Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.
feat(trust): ship privacy and control milestone (#83)
Leo896e298a15cb
diff --git a/.env.example b/.env.exampleindex fc67dcef9..8b13fdc2a 100644--- a/.env.example+++ b/.env.example@@ -1,31 +1,4 @@-# Optional: T3 Connect source builds-# `cp .env.example .env` enables T3 Connect against the production deployment.-# These are the same public identifiers baked into official release builds, not-# secrets. Remove or comment them out to build with cloud features disabled.-# Do not add server-side secrets to this file.--# Production Clerk instance. To use your own, get these from the Clerk Dashboard-# under API keys, JWT templates, and OAuth applications.-T3CODE_CLERK_PUBLISHABLE_KEY=pk_live_Y2xlcmsudDMuY29kZXMk-T3CODE_CLERK_JWT_TEMPLATE=t3-relay-T3CODE_CLERK_CLI_OAUTH_CLIENT_ID=hzxSgY2cH10sDU2r--# Optional: signed macOS passkey builds. The RP domain defaults to the Frontend API-# hostname encoded in T3CODE_CLERK_PUBLISHABLE_KEY. Set the override only when Clerk-# returns a different RP ID or when multiple domains must be entitled.-# T3CODE_APPLE_TEAM_ID=ABC1234567-# T3CODE_MACOS_PROVISIONING_PROFILE=/absolute/path/to/t3code.provisionprofile-# T3CODE_CLERK_PASSKEY_RP_DOMAINS=example.clerk.accounts.dev,clerk.example.com--# Production relay. For a self-hosted relay, `infra/relay` deploys update it-# automatically.-T3CODE_RELAY_URL=https://relay.t3.codes--# Optional: hosted app origin used by the CLI's out-of-band OAuth flow.-# Defaults to https://app.t3.codes; override to test against a staging deployment.-# T3CODE_HOSTED_APP_URL=https://nightly.app.t3.codes-# Public, ingest-only mobile OpenTelemetry configuration.# T3CODE_MOBILE_OTLP_TRACES_URL=https://api.axiom.co/v1/traces-# T3CODE_MOBILE_OTLP_TRACES_DATASET=t3-code-mobile-traces-dev+# T3CODE_MOBILE_OTLP_TRACES_DATASET=akeru-mobile-traces-dev# T3CODE_MOBILE_OTLP_TRACES_TOKEN=xaat-...diff --git a/AGENTS.md b/AGENTS.mdindex 784b37cc4..7cfacff46 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -18,7 +18,7 @@ Lots of apps have gotten bogged down with bad tech decisions and "slop". We have### 3. Remote ready-The architecture of T3 Code's websocket layer (npx t3) enables a lot of awesome remote features. These have become core to the product. Whether users are connecting directly over their local network, using Tailscale, or leaning in fully with T3 Connect (our tunnel solution, also in this repo), we need to make sure new features are properly supported.+The architecture of T3 Code's websocket layer (npx t3) enables a lot of awesome remote features. These have become core to the product. Whether users connect directly over their local network, through SSH, with Tailscale, or through their own tunnel, we need to make sure new features are properly supported.### 4. Multi-surfacediff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex 4e757bc1a..083c1fd13 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -12,8 +12,6 @@"smoke-test": "node scripts/smoke-test.mjs"},"dependencies": {- "@clerk/electron": "catalog:",- "@clerk/electron-passkeys": "catalog:","@effect/platform-node": "catalog:","@t3tools/client-runtime": "workspace:*","@t3tools/contracts": "workspace:*",diff --git a/apps/desktop/src/app/DesktopApp.ts b/apps/desktop/src/app/DesktopApp.tsindex be6886c69..ecb3541e6 100644--- a/apps/desktop/src/app/DesktopApp.ts+++ b/apps/desktop/src/app/DesktopApp.ts@@ -10,9 +10,9 @@ 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 ElectronWindow from "../electron/ElectronWindow.ts";import { installDesktopIpcHandlers } from "../ipc/DesktopIpcHandlers.ts";import * as DesktopAppIdentity from "./DesktopAppIdentity.ts";-import * as DesktopClerk from "./DesktopClerk.ts";import * as DesktopApplicationMenu from "../window/DesktopApplicationMenu.ts";import * as DesktopWindow from "../window/DesktopWindow.ts";import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";@@ -145,9 +145,9 @@ const bootstrap = Effect.gen(function* () {const state = yield* DesktopState.DesktopState;const environment = yield* DesktopEnvironment.DesktopEnvironment;const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;+ const desktopWindow = yield* DesktopWindow.DesktopWindow;const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;const wslBackend = yield* DesktopWslBackend.DesktopWslBackend;- const desktopWindow = yield* DesktopWindow.DesktopWindow;yield* logBootstrapInfo("bootstrap start");if (environment.isDevelopment && Option.isNone(environment.configuredBackendPort)) {@@ -182,7 +182,6 @@ const bootstrap = Effect.gen(function* () {scheme: ElectronProtocol.getDesktopScheme(environment.isDevelopment),targetOrigin: rendererTarget,backendOrigin: backendConfig.httpBaseUrl,- clerkFrontendApiHostname: DesktopClerk.desktopClerkFrontendApiHostname,});yield* logBootstrapInfo("bootstrap resolved backend endpoint", {baseUrl: backendConfig.httpBaseUrl.href,@@ -224,7 +223,7 @@ const startup = Effect.gen(function* () {const electronApp = yield* ElectronApp.ElectronApp;const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;const linuxUrlHandler = yield* DesktopLinuxUrlHandler.DesktopLinuxUrlHandler;- const clerk = yield* DesktopClerk.DesktopClerk;+ const electronWindow = yield* ElectronWindow.ElectronWindow;const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;const preReadyElectronOptions = yield* DesktopPreReadyPlatform.DesktopPreReadyElectronOptions;@@ -255,6 +254,22 @@ const startup = Effect.gen(function* () {}const userDataPath = yield* appIdentity.resolveUserDataPath;yield* electronApp.setPath("userData", userDataPath);+ if (!(yield* electronApp.requestSingleInstanceLock)) {+ yield* electronApp.quit;+ return yield* Effect.interrupt;+ }+ const context = yield* Effect.context<ElectronWindow.ElectronWindow>();+ const runPromise = Effect.runPromiseWith(context);+ yield* electronApp.on("second-instance", () => {+ void runPromise(+ Effect.gen(function* () {+ const mainWindow = yield* electronWindow.currentMainOrFirst;+ if (Option.isSome(mainWindow)) {+ yield* electronWindow.reveal(mainWindow.value);+ }+ }),+ );+ });yield* logStartupInfo("runtime logging configured", { logDir: environment.logDir });yield* desktopSettings.load;@@ -270,7 +285,6 @@ const startup = Effect.gen(function* () {yield* appIdentity.configure;yield* lifecycle.register;- yield* clerk.configure;yield* electronApp.whenReady.pipe(Effect.withSpan("desktop.electron.whenReady"),diff --git a/apps/desktop/src/app/DesktopAppIdentity.test.ts b/apps/desktop/src/app/DesktopAppIdentity.test.tsindex 4d149e689..d7c9b1500 100644--- a/apps/desktop/src/app/DesktopAppIdentity.test.ts+++ b/apps/desktop/src/app/DesktopAppIdentity.test.ts@@ -43,6 +43,7 @@ const makeElectronAppLayer = (calls: ElectronAppCalls) =>systemLocale: Effect.succeed("en-US"),whenReady: Effect.void,quit: Effect.void,+ requestSingleInstanceLock: Effect.succeed(true),exit: () => Effect.void,relaunch: () => Effect.void,setPath: () => Effect.void,diff --git a/apps/desktop/src/app/DesktopClerk.test.ts b/apps/desktop/src/app/DesktopClerk.test.tsdeleted file mode 100644index f1a5d818b..000000000--- a/apps/desktop/src/app/DesktopClerk.test.ts+++ /dev/null@@ -1,237 +0,0 @@-import { assert, describe, it } from "@effect/vitest";-import * as Cause from "effect/Cause";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";-import { beforeEach, vi } from "vite-plus/test";--const { createClerkBridgeMock, storageAdapter, storageMock } = vi.hoisted(() => ({- createClerkBridgeMock: vi.fn(),- storageAdapter: {- getItem: vi.fn(),- setItem: vi.fn(),- removeItem: vi.fn(),- },- storageMock: vi.fn(),-}));--vi.mock("@clerk/electron", () => ({- createClerkBridge: createClerkBridgeMock,-}));--vi.mock("@clerk/electron/storage", () => ({- storage: storageMock,-}));--import * as Exit from "effect/Exit";-import * as FileSystem from "effect/FileSystem";-import * as ElectronApp from "../electron/ElectronApp.ts";-import * as ElectronWindow from "../electron/ElectronWindow.ts";-import * as DesktopClerk from "./DesktopClerk.ts";-import * as DesktopEnvironment from "./DesktopEnvironment.ts";--const makeDesktopClerkLayer = (isDevelopment = true, events: string[] = []) => {- const environment = DesktopEnvironment.DesktopEnvironment.of({- stateDir: "/tmp/t3-state",- isDevelopment,- appDataDirectory: "/tmp/app-data",- userDataDirName: isDevelopment ? "akeru-bot-dev" : "akeru-bot",- legacyUserDataDirName: isDevelopment ? "Akeru Bot (Dev)" : "Akeru Bot (Alpha)",- path: { join: (...parts: ReadonlyArray<string>) => parts.join("/") },- } as unknown as DesktopEnvironment.DesktopEnvironment["Service"]);-- const electronApp = {- setPath: (name: string, value: string) =>- Effect.sync(() => {- events.push(`setPath:${name}:${value}`);- }),- } as unknown as ElectronApp.ElectronApp["Service"];-- return DesktopClerk.layer.pipe(- Layer.provide(- Layer.mergeAll(- Layer.succeed(DesktopEnvironment.DesktopEnvironment, environment),- Layer.succeed(ElectronApp.ElectronApp, electronApp),- FileSystem.layerNoop({ exists: () => Effect.succeed(false) }),- ),- ),- );-};--describe("DesktopClerk", () => {- beforeEach(() => {- createClerkBridgeMock.mockReset();- storageMock.mockReset();- });-- it("derives the Clerk Frontend API hostname used by the desktop CSP", () => {- const publishableKey = `pk_test_${btoa("clerk.t3.codes$")}`;-- assert.equal(- DesktopClerk.resolveDesktopClerkFrontendApiHostname(publishableKey),- "clerk.t3.codes",- );- assert.equal(DesktopClerk.resolveDesktopClerkFrontendApiHostname(""), undefined);- assert.equal(DesktopClerk.resolveDesktopClerkFrontendApiHostname("invalid"), undefined);- });-- it.effect("acquires and releases the SDK bridge with the layer", () => {- const cleanup = vi.fn();- const events: string[] = [];- storageMock.mockReturnValue(storageAdapter);- createClerkBridgeMock.mockImplementation(() => {- events.push("createClerkBridge");- return { cleanup, isPrimaryInstance: true };- });-- return Effect.gen(function* () {- yield* Effect.scoped(Layer.build(makeDesktopClerkLayer(true, events)));-- assert.deepEqual(createClerkBridgeMock.mock.calls, [- [- {- storage: storageAdapter,- passkeys: true,- renderer: { scheme: "t3code-dev", host: "app" },- },- ],- ]);- assert.equal(cleanup.mock.calls.length, 1);- // The bridge acquires Electron's single-instance lock at creation, and- // the lock both lives in and creates the userData directory — so the- // real path must be set before the bridge exists.- assert.deepEqual(events, [- "setPath:userData:/tmp/app-data/akeru-bot-dev",- "createClerkBridge",- ]);- storageMock.mockClear();- createClerkBridgeMock.mockClear();- });- });-- it.effect("preserves bridge initialization failures", () => {- const cause = new Error("bridge initialization failed");- storageMock.mockReturnValue(storageAdapter);- createClerkBridgeMock.mockImplementationOnce(() => {- throw cause;- });-- return Effect.gen(function* () {- const error = yield* Effect.scoped(Layer.build(makeDesktopClerkLayer())).pipe(Effect.flip);-- assert.instanceOf(error, DesktopClerk.DesktopClerkBridgeInitializationError);- assert.equal(error.stateDir, "/tmp/t3-state");- assert.equal(error.isDevelopment, true);- assert.strictEqual(error.cause, cause);- assert.equal(- error.message,- 'Failed to initialize the desktop Clerk bridge for state directory "/tmp/t3-state" (development: true).',- );- });- });-- it.effect("preserves bridge cleanup failures", () => {- const cause = new Error("bridge cleanup failed");- storageMock.mockReturnValue(storageAdapter);- createClerkBridgeMock.mockReturnValue({- cleanup: () => {- throw cause;- },- });-- return Effect.gen(function* () {- const exit = yield* Effect.exit(Effect.scoped(Layer.build(makeDesktopClerkLayer(false))));-- assert.equal(exit._tag, "Failure");- if (exit._tag === "Failure") {- const error = Cause.squash(exit.cause);- assert.instanceOf(error, DesktopClerk.DesktopClerkBridgeCleanupError);- assert.equal(error.stateDir, "/tmp/t3-state");- assert.equal(error.isDevelopment, false);- assert.strictEqual(error.cause, cause);- assert.equal(- error.message,- 'Failed to clean up the desktop Clerk bridge for state directory "/tmp/t3-state" (development: false).',- );- }- });- });-- it.effect("registers the second-instance handler in the primary instance", () => {- storageMock.mockReturnValue(storageAdapter);- createClerkBridgeMock.mockReturnValue({ cleanup: vi.fn(), isPrimaryInstance: true });- const quit = vi.fn();- const registeredEvents: string[] = [];- const electronApp = {- quit: Effect.sync(quit),- on: (eventName: string) =>- Effect.sync(() => {- registeredEvents.push(eventName);- }),- } as unknown as ElectronApp.ElectronApp["Service"];- const electronWindow = {} as ElectronWindow.ElectronWindow["Service"];-- return Effect.gen(function* () {- const clerk = yield* DesktopClerk.DesktopClerk;- const exit = yield* Effect.exit(Effect.scoped(clerk.configure));-- assert.isTrue(Exit.isSuccess(exit));- assert.equal(quit.mock.calls.length, 0);- assert.deepEqual(registeredEvents, ["second-instance"]);- }).pipe(- Effect.provide(makeDesktopClerkLayer()),- Effect.provideService(ElectronApp.ElectronApp, electronApp),- Effect.provideService(ElectronWindow.ElectronWindow, electronWindow),- );- });-- it.effect("quits and interrupts startup in a secondary instance", () => {- storageMock.mockReturnValue(storageAdapter);- createClerkBridgeMock.mockReturnValue({ cleanup: vi.fn(), isPrimaryInstance: false });- const quit = vi.fn();- const registeredEvents: string[] = [];- const electronApp = {- quit: Effect.sync(quit),- on: (eventName: string) =>- Effect.sync(() => {- registeredEvents.push(eventName);- }),- } as unknown as ElectronApp.ElectronApp["Service"];- const electronWindow = {} as ElectronWindow.ElectronWindow["Service"];-- return Effect.gen(function* () {- const clerk = yield* DesktopClerk.DesktopClerk;- const exit = yield* Effect.exit(Effect.scoped(clerk.configure));-- assert.isTrue(Exit.hasInterrupts(exit));- assert.equal(quit.mock.calls.length, 1);- assert.deepEqual(registeredEvents, []);- }).pipe(- Effect.provide(makeDesktopClerkLayer()),- Effect.provideService(ElectronApp.ElectronApp, electronApp),- Effect.provideService(ElectronWindow.ElectronWindow, electronWindow),- );- });-- it.each([- { isDevelopment: true, scheme: "t3code-dev" },- { isDevelopment: false, scheme: "t3code" },- ])("configures the SDK with the $scheme renderer origin", ({ isDevelopment, scheme }) => {- const bridge = { cleanup: vi.fn(), isPrimaryInstance: true };- storageMock.mockReturnValue(storageAdapter);- createClerkBridgeMock.mockReturnValue(bridge);-- assert.equal(DesktopClerk.createDesktopClerkBridge("/tmp/t3-state", isDevelopment), bridge);- assert.deepEqual(storageMock.mock.calls, [[{ path: "/tmp/t3-state" }]]);- assert.deepEqual(createClerkBridgeMock.mock.calls, [- [- {- storage: storageAdapter,- passkeys: true,- renderer: { scheme, host: "app" },- },- ],- ]);- storageMock.mockClear();- createClerkBridgeMock.mockClear();- });-});diff --git a/apps/desktop/src/app/DesktopClerk.ts b/apps/desktop/src/app/DesktopClerk.tsdeleted file mode 100644index 5d04d7391..000000000--- a/apps/desktop/src/app/DesktopClerk.ts+++ /dev/null@@ -1,152 +0,0 @@-import { createClerkBridge } from "@clerk/electron";-import { storage } from "@clerk/electron/storage";-import * as Context from "effect/Context";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";-import * as Option from "effect/Option";-import * as Schema from "effect/Schema";-import * as Scope from "effect/Scope";--import { clerkFrontendApiHostnameFromPublishableKey } from "@t3tools/shared/relayAuth";-import * as ElectronApp from "../electron/ElectronApp.ts";-import * as ElectronProtocol from "../electron/ElectronProtocol.ts";-import * as ElectronWindow from "../electron/ElectronWindow.ts";-import * as DesktopAppIdentity from "./DesktopAppIdentity.ts";-import * as DesktopEnvironment from "./DesktopEnvironment.ts";--declare const __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: string | undefined;--export class DesktopClerkBridgeInitializationError extends Schema.TaggedErrorClass<DesktopClerkBridgeInitializationError>()(- "DesktopClerkBridgeInitializationError",- {- stateDir: Schema.String,- isDevelopment: Schema.Boolean,- cause: Schema.Defect(),- },-) {- override get message(): string {- return `Failed to initialize the desktop Clerk bridge for state directory "${this.stateDir}" (development: ${this.isDevelopment}).`;- }-}--export class DesktopClerkBridgeCleanupError extends Schema.TaggedErrorClass<DesktopClerkBridgeCleanupError>()(- "DesktopClerkBridgeCleanupError",- {- stateDir: Schema.String,- isDevelopment: Schema.Boolean,- cause: Schema.Defect(),- },-) {- override get message(): string {- return `Failed to clean up the desktop Clerk bridge for state directory "${this.stateDir}" (development: ${this.isDevelopment}).`;- }-}--export class DesktopClerk extends Context.Service<- DesktopClerk,- {- readonly configure: Effect.Effect<- void,- never,- ElectronApp.ElectronApp | ElectronWindow.ElectronWindow | Scope.Scope- >;- }->()("@t3tools/desktop/app/DesktopClerk") {}--export function resolveDesktopClerkFrontendApiHostname(- publishableKey: string | undefined,-): string | undefined {- const normalizedKey = publishableKey?.trim();- if (!normalizedKey) return undefined;-- try {- return clerkFrontendApiHostnameFromPublishableKey(normalizedKey);- } catch {- return undefined;- }-}--export const desktopClerkFrontendApiHostname = resolveDesktopClerkFrontendApiHostname(- typeof __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__ === "undefined"- ? undefined- : __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__,-);--export function createDesktopClerkBridge(stateDir: string, isDevelopment: boolean) {- return createClerkBridge({- storage: storage({ path: stateDir }),- passkeys: true,- renderer: {- scheme: ElectronProtocol.getDesktopScheme(isDevelopment),- host: ElectronProtocol.DESKTOP_HOST,- },- });-}--export const make = Effect.gen(function* () {- const environment = yield* DesktopEnvironment.DesktopEnvironment;- const electronApp = yield* ElectronApp.ElectronApp;-- // Electron scopes the single-instance lock to the userData directory and- // creates that directory when the lock is acquired. The SDK bridge takes- // the lock at creation, so userData must already point at the real- // directory here — under the default productName-derived path, acquiring- // the lock would create "Akeru Bot (Alpha)" and make the legacy-install- // detection in resolveUserDataPath match on fresh installs.- const userDataPath = yield* DesktopAppIdentity.resolveUserDataPath;- yield* electronApp.setPath("userData", userDataPath);-- const bridge = yield* Effect.acquireRelease(- Effect.try({- try: () => createDesktopClerkBridge(environment.stateDir, environment.isDevelopment),- catch: (cause) =>- new DesktopClerkBridgeInitializationError({- stateDir: environment.stateDir,- isDevelopment: environment.isDevelopment,- cause,- }),- }),- (bridge) =>- Effect.try({- try: () => bridge.cleanup(),- catch: (cause) =>- new DesktopClerkBridgeCleanupError({- stateDir: environment.stateDir,- isDevelopment: environment.isDevelopment,- cause,- }),- }).pipe(Effect.orDie),- );-- return DesktopClerk.of({- configure: Effect.gen(function* () {- const electronApp = yield* ElectronApp.ElectronApp;- const electronWindow = yield* ElectronWindow.ElectronWindow;- const context = yield* Effect.context<ElectronWindow.ElectronWindow>();- const runPromise = Effect.runPromiseWith(context);-- // The SDK bridge holds Electron's single-instance lock (acquired at- // bridge creation) so OAuth deep-link callbacks on Windows/Linux are- // forwarded to the running app. In a secondary instance the bridge has- // already begun quitting the app; app.quit() is asynchronous, so stop- // bootstrap here before whenReady can fire.- if (!bridge.isPrimaryInstance) {- yield* electronApp.quit;- return yield* Effect.interrupt;- }-- yield* electronApp.on("second-instance", () => {- void runPromise(- Effect.gen(function* () {- const mainWindow = yield* electronWindow.currentMainOrFirst;- if (Option.isSome(mainWindow)) {- yield* electronWindow.reveal(mainWindow.value);- }- }),- );- });- }).pipe(Effect.withSpan("desktop.clerk.configure")),- });-});--export const layer = Layer.effect(DesktopClerk, make);diff --git a/apps/desktop/src/app/DesktopConnectionCatalogStore.test.ts b/apps/desktop/src/app/DesktopConnectionCatalogStore.test.tsindex c58830b30..c758b01ab 100644--- a/apps/desktop/src/app/DesktopConnectionCatalogStore.test.ts+++ b/apps/desktop/src/app/DesktopConnectionCatalogStore.test.ts@@ -120,21 +120,12 @@ describe("DesktopConnectionCatalogStore", () => {),);- it.effect("migrates legacy relay, SSH, bearer profile, and credential data", () =>+ it.effect("migrates legacy SSH, bearer profile, and credential data", () =>withStore(Effect.gen(function* () {const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore;const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;const records: readonly PersistedSavedEnvironmentRecord[] = [- {- environmentId: EnvironmentId.make("relay-environment"),- label: "Relay",- httpBaseUrl: "https://relay.example.com/",- wsBaseUrl: "wss://relay.example.com/",- createdAt: "2026-06-01T00:00:00.000Z",- lastConnectedAt: null,- relayManaged: { relayUrl: "https://relay-control.example.com/" },- },{environmentId: EnvironmentId.make("ssh-environment"),label: "SSH",@@ -174,17 +165,12 @@ describe("DesktopConnectionCatalogStore", () => {const catalog = yield* decodeConnectionCatalog(migrated.value);assert.deepInclude(catalog.targets[0], {- _tag: "RelayConnectionTarget",- environmentId: EnvironmentId.make("relay-environment"),- label: "Relay",- });- assert.deepInclude(catalog.targets[1], {_tag: "SshConnectionTarget",environmentId: EnvironmentId.make("ssh-environment"),label: "SSH",connectionId: "ssh:ssh-environment",});- assert.deepInclude(catalog.targets[2], {+ assert.deepInclude(catalog.targets[1], {_tag: "BearerConnectionTarget",environmentId: EnvironmentId.make("bearer-environment"),label: "Bearer",diff --git a/apps/desktop/src/app/DesktopConnectionCatalogStore.ts b/apps/desktop/src/app/DesktopConnectionCatalogStore.tsindex 5ec2edb59..947c8a0cf 100644--- a/apps/desktop/src/app/DesktopConnectionCatalogStore.ts+++ b/apps/desktop/src/app/DesktopConnectionCatalogStore.ts@@ -2,7 +2,6 @@ import {BearerConnectionCredential,BearerConnectionProfile,BearerConnectionTarget,- RelayConnectionTarget,SshConnectionProfile,SshConnectionTarget,} from "@t3tools/client-runtime/connection";@@ -300,16 +299,6 @@ const migrateSavedEnvironmentRecords = Effect.fn(const credentials: Array<RuntimeConnectionCatalogDocumentType["credentials"][number]> = [];for (const record of records) {- if (record.relayManaged !== undefined) {- targets.push(- new RelayConnectionTarget({- environmentId: record.environmentId,- label: record.label,- }),- );- continue;- }-if (record.desktopSsh !== undefined) {const id = connectionId("ssh", record.environmentId);targets.push(@@ -371,7 +360,6 @@ const migrateSavedEnvironmentRecords = Effect.fn(targets,profiles,credentials,- remoteDpopTokens: [],};});diff --git a/apps/desktop/src/app/DesktopEnvironment.test.ts b/apps/desktop/src/app/DesktopEnvironment.test.tsindex a3a9ef2ec..1f1fe0461 100644--- a/apps/desktop/src/app/DesktopEnvironment.test.ts+++ b/apps/desktop/src/app/DesktopEnvironment.test.ts@@ -147,6 +147,7 @@ describe("DesktopEnvironment", () => {baseName: "Akeru Bot",stageLabel: "Alpha",displayName: "Akeru Bot (Alpha)",+ isPackaged: false,});assert.equal(alpha.userDataDirName, "akeru-bot");assert.equal(development.userDataDirName, "akeru-bot-dev");diff --git a/apps/desktop/src/app/DesktopEnvironment.ts b/apps/desktop/src/app/DesktopEnvironment.tsindex 49dbf1d1d..59e25aed6 100644--- a/apps/desktop/src/app/DesktopEnvironment.ts+++ b/apps/desktop/src/app/DesktopEnvironment.ts@@ -100,6 +100,7 @@ function resolveDesktopAppStageLabel(input: {function resolveDesktopAppBranding(input: {readonly isDevelopment: boolean;+ readonly isPackaged: boolean;readonly appVersion: string;}): DesktopAppBranding {const stageLabel = resolveDesktopAppStageLabel(input);@@ -107,6 +108,7 @@ function resolveDesktopAppBranding(input: {baseName: APP_BASE_NAME,stageLabel,displayName: `${APP_BASE_NAME} (${stageLabel})`,+ isPackaged: input.isPackaged,};}@@ -169,6 +171,7 @@ const make = Effect.fn("desktop.environment.make")(function* (: appRoot;const branding = resolveDesktopAppBranding({isDevelopment,+ isPackaged: input.isPackaged,appVersion: input.appVersion,});const displayName = branding.displayName;diff --git a/apps/desktop/src/app/DesktopLifecycle.test.ts b/apps/desktop/src/app/DesktopLifecycle.test.tsindex f5ff3d5f6..66f0eaa8e 100644--- a/apps/desktop/src/app/DesktopLifecycle.test.ts+++ b/apps/desktop/src/app/DesktopLifecycle.test.ts@@ -36,6 +36,7 @@ function makeElectronAppLayer(systemLocale: Effect.succeed("en-US"),whenReady: Effect.void,quit,+ requestSingleInstanceLock: Effect.succeed(true),exit: () => Effect.void,relaunch: () => Effect.void,setPath: () => Effect.void,diff --git a/apps/desktop/src/electron/ElectronApp.test.ts b/apps/desktop/src/electron/ElectronApp.test.tsindex 4189ea793..050a02e0c 100644--- a/apps/desktop/src/electron/ElectronApp.test.ts+++ b/apps/desktop/src/electron/ElectronApp.test.ts@@ -14,6 +14,7 @@ const {onMock,quitMock,relaunchMock,+ requestSingleInstanceLockMock,removeListenerMock,removeSwitchMock,setAboutPanelOptionsMock,@@ -36,6 +37,7 @@ const {onMock: vi.fn(),quitMock: vi.fn(),relaunchMock: vi.fn(),+ requestSingleInstanceLockMock: vi.fn(() => true),removeListenerMock: vi.fn(),removeSwitchMock: vi.fn(),setAboutPanelOptionsMock: vi.fn(),@@ -70,6 +72,7 @@ vi.mock("electron", () => ({on: onMock,quit: quitMock,relaunch: relaunchMock,+ requestSingleInstanceLock: requestSingleInstanceLockMock,removeListener: removeListenerMock,runningUnderARM64Translation: false,setAboutPanelOptions: setAboutPanelOptionsMock,@@ -94,6 +97,7 @@ describe("ElectronApp", () => {onMock.mockClear();quitMock.mockClear();relaunchMock.mockClear();+ requestSingleInstanceLockMock.mockClear();removeListenerMock.mockClear();removeSwitchMock.mockClear();setPathMock.mockClear();@@ -185,6 +189,15 @@ describe("ElectronApp", () => {}).pipe(Effect.provide(ElectronApp.layer)),);+ it.effect("requests Electron's single-instance lock through the service", () =>+ Effect.gen(function* () {+ const electronApp = yield* ElectronApp.ElectronApp;++ assert.isTrue(yield* electronApp.requestSingleInstanceLock);+ assert.equal(requestSingleInstanceLockMock.mock.calls.length, 1);+ }).pipe(Effect.provide(ElectronApp.layer)),+ );+it.effect("scopes native updater quit listeners", () =>Effect.gen(function* () {const listener = vi.fn();diff --git a/apps/desktop/src/electron/ElectronApp.ts b/apps/desktop/src/electron/ElectronApp.tsindex 5a6f16ae8..c2d37d911 100644--- a/apps/desktop/src/electron/ElectronApp.ts+++ b/apps/desktop/src/electron/ElectronApp.ts@@ -52,6 +52,7 @@ export class ElectronApp extends Context.Service<readonly systemLocale: Effect.Effect<string>;readonly whenReady: Effect.Effect<void, ElectronAppWhenReadyError>;readonly quit: Effect.Effect<void>;+ readonly requestSingleInstanceLock: Effect.Effect<boolean>;readonly exit: (code: number) => Effect.Effect<void>;readonly relaunch: (options: Electron.RelaunchOptions) => Effect.Effect<void>;readonly setPath: (@@ -140,6 +141,7 @@ export const make = ElectronApp.of({quit: Effect.sync(() => {Electron.app.quit();}),+ requestSingleInstanceLock: Effect.sync(() => Electron.app.requestSingleInstanceLock()),exit: (code) =>Effect.sync(() => {Electron.app.exit(code);diff --git a/apps/desktop/src/electron/ElectronProtocol.test.ts b/apps/desktop/src/electron/ElectronProtocol.test.tsindex 2db85dafc..32d9eaf59 100644--- a/apps/desktop/src/electron/ElectronProtocol.test.ts+++ b/apps/desktop/src/electron/ElectronProtocol.test.ts@@ -38,7 +38,6 @@ describe("ElectronProtocol", () => {scheme: "t3code-dev",targetOrigin: new URL("http://127.0.0.1:3773/"),backendOrigin: new URL("http://127.0.0.1:3774/"),- clerkFrontendApiHostname: "clerk.t3.codes",});assert.isDefined(handler);@@ -57,7 +56,7 @@ describe("ElectronProtocol", () => {assert.equal(yield* Effect.promise(() => response.text()), "ok");assert.include(response.headers.get("content-security-policy") ?? "",- "script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval' https://clerk.t3.codes https://challenges.cloudflare.com",+ "script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval'",);assert.include(response.headers.get("content-security-policy") ?? "",@@ -102,7 +101,6 @@ describe("ElectronProtocol", () => {scheme: "t3code",targetOrigin: new URL("http://127.0.0.1:3773/"),backendOrigin: new URL("http://127.0.0.1:3773/"),- clerkFrontendApiHostname: undefined,});return yield* Effect.promise(() => handler!(new Request("t3code://other/")));}),@@ -130,7 +128,6 @@ describe("ElectronProtocol", () => {scheme: "t3code-dev",targetOrigin: new URL("http://127.0.0.1:5733/"),backendOrigin: new URL("http://127.0.0.1:3773/"),- clerkFrontendApiHostname: undefined,});return yield* Effect.promise(() => handler!(new Request("t3code-dev://app/")));}),@@ -154,7 +151,6 @@ describe("ElectronProtocol", () => {scheme: "t3code-dev",targetOrigin: new URL("http://127.0.0.1:3773/"),backendOrigin: new URL("http://127.0.0.1:3774/"),- clerkFrontendApiHostname: undefined,}),).pipe(Effect.flip);@@ -179,7 +175,6 @@ describe("ElectronProtocol", () => {scheme: "t3code",targetOrigin: new URL("http://127.0.0.1:3773/"),backendOrigin: new URL("http://127.0.0.1:3773/"),- clerkFrontendApiHostname: undefined,}),),);@@ -200,7 +195,6 @@ describe("ElectronProtocol", () => {scheme: "t3code",targetOrigin: new URL("http://127.0.0.1:3773/"),backendOrigin: new URL("http://127.0.0.1:3773/"),- clerkFrontendApiHostname: "clerk.t3.codes",});const directives = Object.fromEntries(policy.split("; ").map((directive) => {@@ -209,13 +203,7 @@ describe("ElectronProtocol", () => {}),);- assert.deepEqual(directives["script-src"], [- "'self'",- "'unsafe-inline'",- "'wasm-unsafe-eval'",- "https://clerk.t3.codes",- "https://challenges.cloudflare.com",- ]);+ assert.deepEqual(directives["script-src"], ["'self'", "'unsafe-inline'", "'wasm-unsafe-eval'"]);assert.deepEqual(directives["connect-src"], ["'self'", "http:", "https:", "ws:", "wss:"]);assert.deepEqual(directives["img-src"], ["'self'",diff --git a/apps/desktop/src/electron/ElectronProtocol.ts b/apps/desktop/src/electron/ElectronProtocol.tsindex 11459c9ef..6a71984e0 100644--- a/apps/desktop/src/electron/ElectronProtocol.ts+++ b/apps/desktop/src/electron/ElectronProtocol.ts@@ -52,7 +52,6 @@ export interface DesktopProtocolRegistrationInput {readonly scheme: string;readonly targetOrigin: URL;readonly backendOrigin: URL;- readonly clerkFrontendApiHostname: string | undefined;}export class ElectronProtocol extends Context.Service<@@ -65,19 +64,9 @@ export class ElectronProtocol extends Context.Service<>()("@t3tools/desktop/electron/ElectronProtocol") {}export function makeDesktopContentSecurityPolicy(input: DesktopProtocolRegistrationInput): string {- const clerkOrigin = input.clerkFrontendApiHostname- ? `https://${input.clerkFrontendApiHostname}`- : undefined;- const scriptSources = [- "'self'",- "'unsafe-inline'",- "'wasm-unsafe-eval'",- ...(clerkOrigin ? [clerkOrigin] : []),- "https://challenges.cloudflare.com",- ];-- // The renderer connects directly to user-configured environments in addition to- // the build-configured Clerk, relay, and OTLP endpoints. Those environment+ const scriptSources = ["'self'", "'unsafe-inline'", "'wasm-unsafe-eval'"];++ // The renderer connects directly to user-configured environments. Those environment// origins are not known when this response policy is created, so restrict// connections by the network schemes the client supports instead of by host.const connectSources = ["'self'", "http:", "https:", "ws:", "wss:"];diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.tsindex 14caeed8a..1ef71a126 100644--- a/apps/desktop/src/main.ts+++ b/apps/desktop/src/main.ts@@ -34,7 +34,6 @@ import * as ElectronWindow from "./electron/ElectronWindow.ts";import * as DesktopApp from "./app/DesktopApp.ts";import * as DesktopAppIdentity from "./app/DesktopAppIdentity.ts";import * as DesktopConnectionCatalogStore from "./app/DesktopConnectionCatalogStore.ts";-import * as DesktopClerk from "./app/DesktopClerk.ts";import * as DesktopApplicationMenu from "./window/DesktopApplicationMenu.ts";import * as DesktopAssets from "./app/DesktopAssets.ts";import * as DesktopBackendConfiguration from "./backend/DesktopBackendConfiguration.ts";@@ -194,12 +193,6 @@ const desktopApplicationLayer = Layer.mergeAll(Layer.provideMerge(desktopLocalEnvironmentAuthLayer),);-const desktopClerkLayer = DesktopClerk.layer.pipe(- Layer.provideMerge(desktopEnvironmentLayer),- Layer.provideMerge(NodeServices.layer),- Layer.provideMerge(ElectronApp.layer),-);-const desktopApplicationRuntimeLayer = desktopApplicationLayer.pipe(Layer.provideMerge(NodeServices.layer),Layer.provideMerge(NodeHttpClient.layerUndici),@@ -207,12 +200,7 @@ const desktopApplicationRuntimeLayer = desktopApplicationLayer.pipe(Layer.provideMerge(electronLayer),);-// Acquire strict pre-ready setup before Clerk, whose userData resolution can-// yield and let Electron emit ready.-const desktopRuntimeLayer = desktopClerkLayer.pipe(- Layer.flatMap((clerkContext) =>- desktopApplicationRuntimeLayer.pipe(Layer.provideMerge(Layer.succeedContext(clerkContext))),- ),+const desktopRuntimeLayer = desktopApplicationRuntimeLayer.pipe(Layer.provideMerge(DesktopPreReadyPlatform.layer),);diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.tsindex 407c7c3ef..541568f63 100644--- a/apps/desktop/src/preload.ts+++ b/apps/desktop/src/preload.ts@@ -4,13 +4,10 @@ import type {DesktopPreviewRecordingFrame,DesktopPreviewTabState,} from "@t3tools/contracts";-import { exposeClerkBridge } from "@clerk/electron/preload";import { contextBridge, ipcRenderer } from "electron";import * as IpcChannels from "./ipc/channels.ts";-exposeClerkBridge({ passkeys: true });-function unwrapEnsureSshEnvironmentResult(result: unknown) {if (typeof result === "object" &&diff --git a/apps/desktop/src/settings/DesktopClientSettings.test.ts b/apps/desktop/src/settings/DesktopClientSettings.test.tsindex 314d52365..3304b2a87 100644--- a/apps/desktop/src/settings/DesktopClientSettings.test.ts+++ b/apps/desktop/src/settings/DesktopClientSettings.test.ts@@ -13,6 +13,8 @@ import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";import * as DesktopClientSettings from "./DesktopClientSettings.ts";const clientSettings: ClientSettings = {+ reviewedPrivacyPolicyVersion: "",+ reviewedTermsVersion: "",appearanceContrast: 100,browserDefaultViewport: { _tag: "preset", width: 1024, height: 600, presetId: "nest-hub" },browserDefaultZoomFactor: 1.25,diff --git a/apps/desktop/src/settings/DesktopSavedEnvironments.ts b/apps/desktop/src/settings/DesktopSavedEnvironments.tsindex bdda7f9c7..9dec6d7e8 100644--- a/apps/desktop/src/settings/DesktopSavedEnvironments.ts+++ b/apps/desktop/src/settings/DesktopSavedEnvironments.ts@@ -23,6 +23,7 @@ interface PersistedSavedEnvironmentStorageRecord extends Omit<"desktopSsh"> {readonly desktopSsh?: PersistedSavedEnvironmentDesktopSsh;+ readonly relayManaged?: { readonly relayUrl: string };readonly encryptedBearerToken?: string;}@@ -206,7 +207,6 @@ function toPersistedSavedEnvironmentRecord(return {...nextRecord,...(record.desktopSsh ? { desktopSsh: record.desktopSsh } : {}),- ...(record.relayManaged ? { relayManaged: record.relayManaged } : {}),};}@@ -224,7 +224,6 @@ function toSavedEnvironmentStorageRecord(};const metadata = {...(record.desktopSsh ? { desktopSsh: record.desktopSsh } : {}),- ...(record.relayManaged ? { relayManaged: record.relayManaged } : {}),};return Option.match(encryptedBearerToken, {onNone: () => ({ ...nextRecord, ...metadata }),@@ -237,7 +236,7 @@ function normalizeSavedEnvironmentRegistryDocument(): SavedEnvironmentRegistryDocument {return {version: document.version ?? 1,- records: document.records ?? [],+ records: (document.records ?? []).filter((record) => record.relayManaged === undefined),};}diff --git a/apps/desktop/src/telemetry/DesktopTelemetryPublisher.test.ts b/apps/desktop/src/telemetry/DesktopTelemetryPublisher.test.tsindex 3d912a5d5..07e80b8a0 100644--- a/apps/desktop/src/telemetry/DesktopTelemetryPublisher.test.ts+++ b/apps/desktop/src/telemetry/DesktopTelemetryPublisher.test.ts@@ -29,6 +29,7 @@ function makeElectronAppLayer(systemLocale: Effect.succeed("en-US"),whenReady: Effect.void,quit: Effect.void,+ requestSingleInstanceLock: Effect.succeed(true),exit: () => Effect.void,relaunch: () => Effect.void,setPath: () => Effect.void,diff --git a/apps/desktop/src/window/DesktopApplicationMenu.test.ts b/apps/desktop/src/window/DesktopApplicationMenu.test.tsindex a40a113f3..acef93c01 100644--- a/apps/desktop/src/window/DesktopApplicationMenu.test.ts+++ b/apps/desktop/src/window/DesktopApplicationMenu.test.ts@@ -34,6 +34,7 @@ const electronAppLayer = Layer.succeed(ElectronApp.ElectronApp, {systemLocale: Effect.succeed("en-US"),whenReady: Effect.void,quit: Effect.void,+ requestSingleInstanceLock: Effect.succeed(true),exit: () => Effect.void,relaunch: () => Effect.void,setPath: () => Effect.void,diff --git a/apps/desktop/vite.config.ts b/apps/desktop/vite.config.tsindex d1b87c547..bd82e8e2a 100644--- a/apps/desktop/vite.config.ts+++ b/apps/desktop/vite.config.ts@@ -1,14 +1,6 @@import { defineConfig } from "vite-plus";-import { loadRepoEnv } from "../../scripts/lib/public-config.ts";--const repoEnv = loadRepoEnv();const shouldLaunchElectronAfterPack = process.env.T3CODE_DESKTOP_DEV === "1";-const publicConfigDefine = {- __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: JSON.stringify(- repoEnv.T3CODE_CLERK_PUBLISHABLE_KEY?.trim() ?? "",- ),-};export default defineConfig({run: {@@ -41,7 +33,6 @@ export default defineConfig({outDir: "dist-electron",sourcemap: true,outExtensions: () => ({ js: ".cjs" }),- define: publicConfigDefine,entry: ["src/main.ts"],clean: true,deps: {@@ -54,14 +45,7 @@ export default defineConfig({outDir: "dist-electron",sourcemap: true,outExtensions: () => ({ js: ".cjs" }),- define: publicConfigDefine,entry: ["src/preload.ts"],- deps: {- // Sandboxed Electron preloads cannot reliably resolve package imports- // from inside the packaged ASAR. Bundle Clerk's preload bridge into the- // preload artifact instead of leaving a runtime require() behind.- alwaysBundle: (id) => id === "@clerk/electron" || id.startsWith("@clerk/electron/"),- },},{format: "cjs",diff --git a/apps/marketing/src/components/LegalPage.astro b/apps/marketing/src/components/LegalPage.astroindex eb824039e..41a9579b5 100644--- a/apps/marketing/src/components/LegalPage.astro+++ b/apps/marketing/src/components/LegalPage.astro@@ -6,25 +6,25 @@ interface Props {readonly description: string;readonly heading: string;readonly lede: string;- readonly effectiveDate: string;+ readonly status: string;readonly lastUpdated: string;readonly sections: ReadonlyArray<readonly [id: string, label: string]>;}-const { title, description, heading, lede, effectiveDate, lastUpdated, sections } = Astro.props;+const { title, description, heading, lede, status, lastUpdated, sections } = Astro.props;---<Layout title={title} description={description} pageClass="legal-document-page"><div class="legal-page"><a class="legal-index-link" href="/legal"><span aria-hidden="true">←</span> All legal documents</a><header class="legal-hero">- <p class="eyebrow">T3 Tools, Inc. / Legal</p>+ <p class="eyebrow">Akeru Bot / Legal draft</p><h1>{heading}</h1><p class="legal-lede">{lede}</p><dl class="legal-dates" aria-label="Document dates"><div>- <dt>Effective Date</dt>- <dd>{effectiveDate}</dd>+ <dt>Status</dt>+ <dd>{status}</dd></div><div><dt>Last Updated</dt>diff --git a/apps/marketing/src/layouts/Layout.astro b/apps/marketing/src/layouts/Layout.astroindex e42617f6c..bb2650a36 100644--- a/apps/marketing/src/layouts/Layout.astro+++ b/apps/marketing/src/layouts/Layout.astro@@ -186,7 +186,7 @@ const structuredData = [<div class="footer-bottom"><span>© {year} Akeru. MIT licensed.</span><span class="footer-legal">- <a href="/terms-of-service">Terms</a>+ <a href="/terms-of-service">Terms of Use</a><a href="/privacy-policy">Privacy</a><a href="/security-policy">Security</a></span>diff --git a/apps/marketing/src/pages/legal.astro b/apps/marketing/src/pages/legal.astroindex d75413a8d..2d3973153 100644--- a/apps/marketing/src/pages/legal.astro+++ b/apps/marketing/src/pages/legal.astro@@ -5,13 +5,13 @@ const documents = [{number: "01",title: "Privacy Policy",- description: "How T3 Code handles information, connected services, and your privacy choices.",+ description: "How Akeru Bot stores local data and sends data to services you choose.",href: "/privacy-policy",},{number: "02",- title: "Terms of Service",- description: "The terms that govern your use of T3 Code and T3 Tools-operated services.",+ title: "Terms of Use",+ description: "Draft terms for Akeru Bot software and the Akeru Bot website.",href: "/terms-of-service",},{@@ -24,15 +24,15 @@ const documents = [---<Layout- title="Legal — T3 Code"- description="Privacy, terms, and security documents for T3 Code."+ title="Legal - Akeru Bot"+ description="Privacy, terms, and security documents for Akeru Bot."pageClass="legal-document-page"><div class="legal-index"><header class="legal-index-hero">- <p class="eyebrow">T3 Tools, Inc. / Legal</p>+ <p class="eyebrow">Akeru Bot / Legal drafts</p><h1>Legal</h1>- <p>Policies and terms for T3 Code, collected in one place.</p>+ <p>Policies and terms for Akeru Bot.</p></header><nav class="document-list" aria-label="Legal documents">diff --git a/apps/marketing/src/pages/privacy-policy.astro b/apps/marketing/src/pages/privacy-policy.astroindex 0507a7df5..9677cc208 100644--- a/apps/marketing/src/pages/privacy-policy.astro+++ b/apps/marketing/src/pages/privacy-policy.astro@@ -2,451 +2,89 @@import LegalPage from "../components/LegalPage.astro";const sections = [- ["introduction", "Introduction"],- ["information", "Personal information we collect"],- ["uses", "How we use your personal information"],- ["sharing", "How we share your personal information"],- ["choices", "Your choices regarding your personal information"],- ["security", "Security of your personal information"],- ["international", "International users"],- ["children", "Children"],- ["do-not-track", "Do Not Track"],- ["updates", "Updates to this Privacy Policy"],- ["contact", "Contact us"],+ ["local-data", "Data stored locally"],+ ["outbound-data", "Data sent to other services"],+ ["controls", "Your controls"],+ ["retention", "Retention"],+ ["contact", "Contact"],] as const;---<LegalPage- title="Privacy Policy — T3 Code"- description="How T3 Tools, Inc. handles information when you use T3 Code, app.t3.codes, and t3.codes."- heading="T3 Code Privacy Policy"- lede="This Privacy Policy describes how T3 Tools, Inc. collects, uses, and shares personal information when you use the T3 Code desktop, mobile, and hosted web applications, visit the t3.codes marketing site, or use the optional T3 Connect service."- effectiveDate="2026-07-14"- lastUpdated="2026-07-14"+ title="Privacy Policy - Akeru Bot"+ description="How Akeru Bot stores local data and sends data to services you choose."+ heading="Akeru Bot Privacy Policy"+ lede="Akeru Bot is local-first software. This draft explains what stays on your device and what leaves it when you use an online feature."+ status="Draft - counsel review required"+ lastUpdated="2026-08-31"sections={sections}>- <section id="introduction">- <p class="section-number">01</p>- <h2>Introduction</h2>- <p>- This Privacy Policy (the “Policy”) describes how T3 Tools, Inc. (the “Company,” “T3- Tools,” “we,” or “us”) collects, uses, and shares personal information when you use the T3- Code desktop and mobile applications, the hosted T3 Code web application located at- {" "}<a href="https://app.t3.codes">https://app.t3.codes</a>, or the optional T3 Connect- service (together, the “Services”), or visit the T3 Code marketing website located at- {" "}<a href="https://t3.codes">https://t3.codes</a> (the “Site”). This Policy applies to- personal information we collect through the Site and the Services, as well as personal- information you provide to us directly.- </p>- <p>- By using the Site or the Services, you acknowledge the practices described in this- Policy. If you do not agree with this Policy, please do not use the Site or the Services.- This Policy does not govern third-party coding agents, artificial-intelligence providers,- identity providers, or environments that you choose to connect to T3 Code; those third- parties process information under their own terms and privacy policies.- </p>- </section>-- <section id="information">- <p class="section-number">02</p>- <h2>Personal Information We Collect</h2>-- <p>- We collect personal information about you in different ways depending on how you use- T3 Code and which optional features you enable.- </p>-- <h3>Personal Information From Users of T3 Code</h3>-- <p>- When you use T3 Code, we may collect the following categories of personal information:- </p>- <ul>- <li>- <strong>Account information.</strong> If you create or sign in to a T3 account, we- receive general identifiers and profile information from our authentication provider- and the identity provider you select. This may include your name, email address,- profile image, user ID, sign-in method, and authentication credentials or tokens.- </li>- <li>- <strong>Environment and device information.</strong> If you enable T3 Connect, we- process information needed to connect and secure your environments and devices,- including identifiers, labels you assign, public keys, connection endpoints,- credential hashes, connection status, app and operating-system versions, and- notification preferences.- </li>- <li>- <strong>Agent activity and notifications.</strong> If you enable notifications or Live- Activities, we process push tokens and limited activity information needed to provide- those features, such as project and thread titles, model name, status, and activity- headline.- </li>- <li>- <strong>Information you provide to us.</strong> We collect information that you choose- to provide when you request support, send feedback, or otherwise communicate with us.- </li>- </ul>-- <h3>Personal Information From Users of Our Site Generally</h3>- <p>- When you visit the Site or use online portions of the Services, we and our service- providers may automatically log online identifiers and internet-activity information,- including your Internet Protocol (IP) address, device and operating-system type, browser- or app type and version, pages viewed, access times, request timestamps, connection- events, latency, error details, and diagnostic traces. The amount of information we- collect depends on the Services you use and your device and browser settings.- </p>- <p>- We use operational and diagnostic information to provide, secure, maintain, and- troubleshoot the Services, not for targeted advertising.- </p>-- <h3>Information We Get From Others</h3>- <p>- We may receive personal information from service providers that help us operate the- Services, such as authentication and identity providers, app stores, device-platform- providers, and coding-agent providers you choose to use. We may combine this information- with information we collect through the Site and the Services.- </p>-- <h3>Cookies and Local Storage</h3>- <p>- The Site and online portions of the Services may use cookies or similar technologies to- operate essential features, maintain sessions, remember preferences, and understand- whether the Services are functioning correctly. T3 Code also stores connection settings,- credentials, preferences, drafts, and cached thread, file, branch, and server metadata on- your device. Credentials and session tokens use platform-provided protected storage where- supported. Information stored only on your device is not collected by T3 Tools unless it- is transmitted as part of a feature you use.- </p>-- <h3>Device Permissions</h3>- <ul>- <li>- <strong>Camera.</strong> Used when you choose to scan a pairing QR code. Camera frames- are processed on your device.- </li>- <li>- <strong>Photos and files.</strong> Items you select are accessed only to preview them or- attach them to a request you initiate.- </li>- <li>- <strong>Notifications.</strong> Used only if you enable agent-status notifications or- Live Activities.- </li>- <li>- <strong>Local network.</strong> Used to discover or connect to T3 Code environments- accessible from your machine over the network.- </li>- </ul>- </section>-- <section id="uses">- <p class="section-number">03</p>- <h2>How We Use Your Personal Information</h2>- <p>- Subject to this Policy and applicable terms governing third-party applications and- services, we may use personal information for the following purposes:- </p>- <ul>- <li>To establish and verify your identity and authenticate your account;</li>- <li>To link and protect devices and environments and deliver optional notifications;</li>- <li>To process and fulfill requests you make through the Services;</li>- <li>To provide customer service and respond to support requests and feedback;</li>- <li>To communicate with you about the Services and your relationship with us;</li>- <li>To monitor reliability, prevent abuse, and investigate security incidents;</li>- <li>To comply with applicable law and enforce the terms governing the Services; and</li>- <li>- To analyze and improve T3 Code using aggregated, de-identified, or other anonymous- operational information.- </li>- </ul>-- <h3>Training of AI Models</h3>- <p>- We do not use your personal information, source code, prompts, or agent responses to- train artificial-intelligence models.- </p>-- <h3>Compliance and Protection</h3>- <p>We may use personal information to:</p>- <ul>- <li>Comply with applicable laws, lawful requests, and legal process;</li>- <li>Protect the rights, privacy, safety, and property of T3 Tools, our users, and others;</li>- <li>Audit our internal processes for legal, contractual, and policy compliance;</li>- <li>Enforce the terms and conditions that govern the Site and the Services; and</li>- <li>- Prevent, identify, investigate, and deter fraudulent, harmful, unauthorized,- unethical, or illegal activity, including cyberattacks and identity theft.- </li>- </ul>- <p>- We may also use personal information for other purposes consistent with this Policy or- explained to you when we collect the information.- </p>- </section>-- <section id="sharing">- <p class="section-number">04</p>- <h2>How We Share Your Personal Information</h2>- <p>- We may disclose the categories of personal information described above to the following- categories of third parties:- </p>-- <h3>Providers You Choose</h3>- <p>- At your direction, prompts, files, and related content are sent to coding agents and- artificial-intelligence providers configured in your environment. Because you bring and- configure your own coding-agent harness and provider, the applicable third parties vary.- Those providers process information under their own terms and privacy policies.- </p>-- <h3>Third-Party Service Providers</h3>- <p>- We use third-party service providers to help provide the Services and operate our- business. Depending on the features you use, these providers may include:- </p>- <ul class="provider-list">- <li>- <strong>Clerk</strong> <em>(Clerk, Inc.)</em>.<br />- We use Clerk to provide account authentication.<br />- You can view Clerk's privacy policy here:{" "}<a href="https://clerk.com/legal/privacy"- >https://clerk.com/legal/privacy</a- >.- </li>- <li>- <strong>Cloudflare</strong> <em>(Cloudflare, Inc.)</em>.<br />- We use Cloudflare for networking, T3 Connect infrastructure, and content delivery.<br />- You can view Cloudflare's privacy policy here:{" "}<a- href="https://www.cloudflare.com/policies/privacy/"- >https://www.cloudflare.com/policies/privacy/</a- >.- </li>- <li>- <strong>PlanetScale</strong> <em>(PlanetScale, Inc.)</em>.<br />- We use PlanetScale to host the database that supports T3 Connect.<br />- You can view PlanetScale's privacy policy here:{" "}<a- href="https://planetscale.com/legal/privacy"- >https://planetscale.com/legal/privacy</a- >.- </li>- <li>- <strong>Vercel</strong> <em>(Vercel Inc.)</em>.<br />- We use Vercel to host and deploy the T3 Code Site.<br />- You can view Vercel's privacy notice here:{" "}<a- href="https://vercel.com/legal/privacy-notice"- >https://vercel.com/legal/privacy-notice</a- >.- </li>- <li>- <strong>Axiom</strong> <em>(Axiom, Inc.)</em>.<br />- We use Axiom for operational diagnostics that help us maintain and troubleshoot the- Services.<br />- You can view Axiom's privacy policy here:{" "}<a- href="https://axiom.co/docs/legal/privacy">https://axiom.co/docs/legal/privacy</a- >.- </li>- <li>- <strong>PostHog</strong> <em>(PostHog, Inc.)</em>.<br />- We use PostHog to measure visits to the Site.<br />- You can view PostHog's privacy policy here:{" "}<a- href="https://posthog.com/privacy">https://posthog.com/privacy</a- >.- </li>- <li>- <strong>Expo</strong> <em>(650 Industries, Inc.)</em>.<br />- We use Expo for application updates and related mobile-app services.<br />- You can view Expo's privacy policy here:{" "}<a href="https://expo.dev/privacy"- >https://expo.dev/privacy</a- >.- </li>- <li>- <strong>Apple</strong> <em>(Apple Inc.)</em>.<br />- We use Apple services for app distribution, optional authentication, and platform- notifications.<br />- You can view Apple's privacy policy here:{" "}<a- href="https://www.apple.com/legal/privacy/">https://www.apple.com/legal/privacy/</a- >.- </li>- <li>- <strong>Google</strong> <em>(Google LLC)</em>.<br />- We use Google services for app distribution and optional authentication.<br />- You can view Google's privacy policy here:{" "}<a- href="https://policies.google.com/privacy">https://policies.google.com/privacy</a- >.- </li>- </ul>- <p>- These providers process information for us under their own contractual and privacy- obligations.- </p>-- <h3>Affiliates and Professional Advisors</h3>- <p>- We may share personal information with our affiliates for purposes consistent with this- Policy and with lawyers, accountants, bankers, and other professional advisors in the- course of the services they provide to us.- </p>-- <h3>Corporate Restructuring</h3>- <p>- We may share some or all personal information in connection with or during negotiation of- a merger, financing, acquisition, reorganization, bankruptcy, dissolution, sale of- assets, or similar transaction. If another company acquires T3 Tools or its assets, that- company may possess the personal information collected by us and assume the rights and- obligations described in this Policy.- </p>-- <h3>Legal and Safety Disclosures</h3>- <p>- We may disclose personal information if we believe in good faith that disclosure is- necessary to comply with law or legal process; protect or defend the rights, property, or- safety of T3 Tools, users of the Site or the Services, or others; investigate or prevent- fraud, abuse, or unlawful activity; or enforce this Policy and the terms governing the- Services. We may also share personal information at your direction, with your consent, or- as described to you when the information is collected.- </p>-- <h3>No Sale of Personal Information</h3>- <p>- We do not sell your personal information or share it for cross-context behavioral or- targeted advertising.- </p>-- <h3>Third-Party Websites and Services</h3>- <p>- The Site and the Services may contain links to third-party websites or services. When you- follow a third-party link or connect a third-party service, that third party may collect- personal information from you. We do not control and are not responsible for the privacy- practices or content of third parties.- </p>- </section>-- <section id="choices">- <p class="section-number">05</p>- <h2>Your Choices Regarding Your Personal Information</h2>-- <h3>Account and Connection Choices</h3>- <p>- You may use local or direct connections without signing in to a T3 account. You can- disconnect environments, sign out, disable optional notifications and Live Activities,- and clear local caches from Settings. You can grant or revoke camera, photo, local-network,- and notification permissions in your device settings.- </p>-- <h3>Cookies and Local Data</h3>- <p>- You can use your browser settings to stop accepting or to delete cookies, although some- portions of the Site or the Services may not function correctly as a result. Information- stored only on your device remains there until you clear it, remove the relevant- connection, or uninstall the app. The mobile app provides cache controls under- {" "}<strong>Settings → App → Client Storage</strong>.- </p>-- <h3>Retention and Deletion</h3>- <p>- We retain account, environment-link, device-registration, notification, and security- information while your account or the relevant feature is active and for as long as- reasonably necessary to provide the Services, protect them from abuse, comply with law,- and resolve disputes. Operational diagnostic traces are configured to expire after 30- days. Some records may remain longer in backups or where retention is required for- security, fraud prevention, or legal compliance.- </p>- <p>- To request deletion of your T3 account and associated T3 Connect data, email{" "}<a- href="mailto:[email protected]">[email protected]</a- >{" "}from the email address associated with your account. We may need to verify your- identity. Deleting a T3 account does not delete information held by an environment or- coding-agent provider you control; contact those providers or delete that information- directly.- </p>-- <h3>Your Privacy Rights</h3>- <p>- Depending on where you live, you may have rights to request access to, correction of,- deletion of, or a portable copy of your personal information, or to restrict or object- to certain processing. You may also have the right to appeal our response or complain to- a data-protection authority. We will honor applicable rights after verifying your- request.- </p>- </section>-- <section id="security">- <p class="section-number">06</p>- <h2>Security of Your Personal Information</h2>- <p>- T3 Tools is committed to protecting the security of your personal information. We use- administrative, technical, and organizational safeguards designed to protect personal- information from unauthorized access, use, or disclosure. These safeguards include- encrypted network transport, scoped and proof-bound access tokens for supported- connection flows, protected credential storage, and redaction of authorization headers- from relay diagnostics.- </p>- <p>- No method of transmission over the Internet or method of electronic storage is completely- secure. While we use reasonable efforts to protect personal information, we cannot- guarantee its absolute security. You are responsible for securing the environments,- coding-agent accounts, credentials, and networks that you connect to T3 Code.- </p>- </section>-- <section id="international">- <p class="section-number">07</p>- <h2>International Users</h2>- <p>- The Site and the Services are provided from the United States and are governed by United- States law. If you use the Site or the Services from outside the United States, your- personal information may be transferred to and processed in the United States and other- countries where we or our service providers operate. Where required, we use lawful- safeguards for international transfers of personal information.- </p>- </section>+ <section id="local-data">+ <p class="section-number">01</p>+ <h2>Data stored locally</h2>+ <p>+ Akeru Bot stores projects, threads, settings, secrets, logs, reviewed policy versions, and+ cached data under the Akeru Bot data directory on the environment you control. The project+ does not require a hosted Akeru account. Direct remote connections may carry this data between+ your own devices and environment.+ </p>+ </section>- <section id="children">- <p class="section-number">08</p>- <h2>Children</h2>- <p>- The Site and the Services are not intended for children under 13 years of age, and you- must be at least 13 years old to use them. We do not knowingly collect, use, or disclose- personal information from children under 13. If you believe a child under 13 has provided- us with personal information, please contact us so that we can take appropriate action.- </p>- </section>+ <section id="outbound-data">+ <p class="section-number">02</p>+ <h2>Data sent to other services</h2>+ <ul>+ <li>+ <strong>Agent providers.</strong> Prompts, selected files, tool results, screenshots, and+ conversation context go to the provider CLI or service you choose. That provider controls+ its own processing and retention.+ </li>+ <li>+ <strong>Product feedback.</strong> Feedback you submit goes to feedback.akeru.bot and may be+ kept for up to 90 days.+ </li>+ <li>+ <strong>Voice.</strong> During a voice call, microphone audio and session data go to the+ ChatGPT Realtime service.+ </li>+ <li>+ <strong>Updates.</strong> Provider checks contact provider release sources. Signed desktop+ builds contact the configured release host to check for and download updates.+ </li>+ <li>+ <strong>Optional analytics.</strong> If you opt in and the distributor configures PostHog,+ Akeru Bot sends app version, platform, architecture, client type, and feature events with a+ random installation identifier. It does not use a provider account identifier.+ </li>+ </ul>+ </section>- <section id="do-not-track">- <p class="section-number">09</p>- <h2>Do Not Track</h2>- <p>- We currently do not respond to browser “Do Not Track” signals. T3 Code does not use- personal information for cross-context behavioral or targeted advertising.- </p>- </section>+ <section id="controls">+ <p class="section-number">03</p>+ <h2>Your controls</h2>+ <p>+ Privacy settings let you turn analytics, product feedback, voice calls, and provider update+ checks on or off. Analytics starts off. You can stop provider data transfers by not starting+ a provider run or by disconnecting that provider.+ </p>+ </section>- <section id="updates">- <p class="section-number">10</p>- <h2>Updates to This Privacy Policy</h2>- <p>- We reserve the right to update this Policy from time to time. If we make material changes,- we will post the revised Policy at this URL, update the “Last Updated” and “Effective Date”- above, and provide any additional notice required by law. Except as otherwise indicated,- changes become effective when the revised Policy is posted.- </p>- </section>+ <section id="retention">+ <p class="section-number">04</p>+ <h2>Retention</h2>+ <p>+ Local data remains until you remove it. Akeru Bot does not control the retention rules of your+ selected providers, release hosts, app stores, or ChatGPT. Review those services before you+ send confidential or regulated data.+ </p>+ </section>- <section id="contact">- <p class="section-number">11</p>- <h2>Contact Us</h2>- <p>- If you have questions about this Policy or wish to make a privacy or deletion request,- please contact us at:- </p>- <address>- <strong>T3 Tools, Inc.</strong><br />- 2261 Market Street #5309<br />- San Francisco, CA 94114<br />- United States- </address>- <a class="contact-link" href="mailto:[email protected]">[email protected]</a>+ <section id="contact">+ <p class="section-number">05</p>+ <h2>Contact</h2>+ <p>+ Report privacy questions through the Akeru Bot repository. This draft must receive qualified+ legal counsel review before any public release.+ </p></section></LegalPage>diff --git a/apps/marketing/src/pages/security-policy.astro b/apps/marketing/src/pages/security-policy.astroindex c9b05ec36..2621d9ad6 100644--- a/apps/marketing/src/pages/security-policy.astro+++ b/apps/marketing/src/pages/security-policy.astro@@ -2,186 +2,58 @@import LegalPage from "../components/LegalPage.astro";const sections = [- ["introduction", "Introduction"],+ ["scope", "Scope"],["reporting", "Reporting security issues"],- ["safe-harbor", "Responsible research and safe harbor"],- ["practices", "Our security practices"],- ["responsibilities", "Your responsibilities"],- ["updates", "Updates to this policy"],- ["contact", "Contact us"],+ ["responsibilities", "Shared responsibilities"],+ ["contact", "Contact"],] as const;---<LegalPage- title="Security Policy — T3 Code"- description="How to report security issues in T3 Code and how T3 Tools approaches product security."- heading="T3 Code Security Policy"- lede="Security is a shared responsibility. This policy explains how to report a vulnerability, how we protect T3 Tools-operated services, and how you can secure the environments and providers you connect to T3 Code."- effectiveDate="2026-07-15"- lastUpdated="2026-07-15"+ title="Security Policy - Akeru Bot"+ description="How to report security issues in Akeru Bot."+ heading="Akeru Bot Security Policy"+ lede="This draft covers the Akeru Bot software and website. It does not cover agent providers or infrastructure that you operate."+ status="Draft - counsel review required"+ lastUpdated="2026-08-31"sections={sections}>- <section id="introduction">+ <section id="scope"><p class="section-number">01</p>- <h2>Introduction</h2>+ <h2>Scope</h2><p>- This Security Policy describes the vulnerability-reporting process and security practices for- the T3 Code desktop and mobile applications, the hosted application at{" "}<a- href="https://app.t3.codes">https://app.t3.codes</a- >, the optional T3 Connect service, and the T3 Code website at{" "}<a href="https://t3.codes"- >https://t3.codes</a- >.- </p>- <p>- T3 Code connects software running on your devices and in environments you control with- coding-agent harnesses and providers you choose. We secure the software and infrastructure- operated by T3 Tools, but we do not control the security of your devices, environments,- repositories, networks, credentials, or third-party providers. Please review the shared- responsibilities below when assessing risk.+ This policy covers vulnerabilities in the Akeru Bot source code, packaged applications, and+ Akeru Bot website. It does not authorize testing third-party providers, user devices,+ repositories, networks, or environments.</p></section><section id="reporting"><p class="section-number">02</p>- <h2>Reporting Security Issues</h2>- <p>- If you believe you have found a security vulnerability affecting T3 Code or T3 Tools-operated- infrastructure, email{" "}<a href="mailto:[email protected]">[email protected]</a>. Please do not- disclose the issue publicly until we have had a reasonable opportunity to investigate and- remediate it.- </p>- <p>Please include, when available:</p>- <ul>- <li>A description of the issue and its potential impact;</li>- <li>The affected application, version, URL, endpoint, or component;</li>- <li>Clear reproduction steps or a minimal proof of concept;</li>- <li>Relevant logs, screenshots, or request and response details with secrets removed; and</li>- <li>Your preferred contact information and whether you want public credit.</li>- </ul>- <p>- We aim to acknowledge complete reports within one business day, keep reporters informed of- material progress, and coordinate disclosure after a fix is available. Resolution time varies- with severity, complexity, and dependencies on third parties.- </p>- </section>-- <section id="safe-harbor">- <p class="section-number">03</p>- <h2>Responsible Research and Safe Harbor</h2>- <p>- We support good-faith security research. If you make a genuine effort to comply with this- policy, avoid harm, respect privacy, and report findings promptly, we will treat your research- as authorized and will not initiate legal action against you for accidental, good-faith- violations of this policy. If a third party initiates legal action concerning compliant- research, we will make our authorization known where appropriate.- </p>- <p>To remain within this safe harbor, you must:</p>- <ul>- <li>Test only accounts, data, and systems you own or have explicit permission to test;</li>- <li>Stop and report immediately if you encounter personal, confidential, or production data;</li>- <li>Access only the minimum information needed to demonstrate the issue;</li>- <li>Avoid disrupting availability, degrading performance, or damaging or deleting data;</li>- <li>Not use social engineering, phishing, physical attacks, or denial-of-service testing;</li>- <li>Not test third-party services or infrastructure outside T3 Tools’ control; and</li>- <li>Give us reasonable time to address the issue before public disclosure.</li>- </ul>- <p>- This safe harbor does not authorize violations of law or activity outside the scope of this- policy. Vulnerability rewards are not guaranteed and, if offered, are determined by T3 Tools- in its discretion.- </p>- </section>-- <section id="practices">- <p class="section-number">04</p>- <h2>Our Security Practices</h2>- <p>- We use administrative, technical, and organizational safeguards designed for the nature of T3- Code and the information processed by T3 Tools-operated services. These practices include:- </p>- <ul>- <li>- <strong>Data minimization.</strong> T3 Code is designed so coding-session content can remain- between your clients, your environment, and the harnesses and providers you configure. We- process information through T3 Tools-operated infrastructure only when needed for a feature- you enable.- </li>- <li>- <strong>Encrypted transport.</strong> T3 Tools-operated network services use encrypted- transport. Supported connection flows use scoped credentials and security controls designed- to reduce unauthorized reuse.- </li>- <li>- <strong>Credential protection.</strong> T3 Code uses platform-provided protected storage for- credentials and session tokens where supported. We design operational logging to avoid- collecting secrets that are not needed to operate or troubleshoot the Services.- </li>- <li>- <strong>Access controls.</strong> Access to production systems and operational data is limited- according to job responsibilities and protected using authentication and authorization- controls.- </li>- <li>- <strong>Maintenance and monitoring.</strong> We monitor T3 Tools-operated services for- reliability and security events, review dependencies, and deploy updates and mitigations as- appropriate.- </li>- <li>- <strong>Established providers.</strong> We use specialized providers for services such as- authentication, hosting, and application distribution and evaluate the controls relevant to- their role.- </li>- </ul>+ <h2>Reporting security issues</h2><p>- No system is completely secure. These practices reduce risk but do not guarantee that the Site- or Services will be free from vulnerabilities or unauthorized access.+ Use a private GitHub security advisory in the Akeru Bot repository. Include the affected+ version, impact, reproduction steps, and evidence with secrets removed. Do not publish the+ issue before maintainers have time to investigate it.</p></section><section id="responsibilities">- <p class="section-number">05</p>- <h2>Your Responsibilities</h2>- <p>- Because you control much of the T3 Code execution path, you play an important role in securing- it. You are responsible for:- </p>- <ul>- <li>Keeping T3 Code, your operating systems, and connected tools up to date;</li>- <li>Securing your devices, repositories, environments, networks, and backups;</li>- <li>Protecting account, provider, repository, and environment credentials;</li>- <li>Using multi-factor authentication where your identity and coding-agent providers support it;</li>- <li>Granting providers and integrations only the permissions they need;</li>- <li>Reviewing commands, source changes, and other agent output before applying or executing it;</li>- <li>Removing lost or unused devices and revoking credentials you believe may be compromised; and</li>- <li>Following the security policies of your selected harnesses, providers, and infrastructure.</li>- </ul>- <p>- Do not send passwords, API keys, access tokens, or private keys in a vulnerability report.- Revoke any secret that may have been exposed before sharing sanitized evidence with us.- </p>- </section>-- <section id="updates">- <p class="section-number">06</p>- <h2>Updates to This Policy</h2>+ <p class="section-number">03</p>+ <h2>Shared responsibilities</h2><p>- We may update this Security Policy as T3 Code, our infrastructure, and security practices- evolve. We will post revisions at this URL and update the dates above. Material changes to the- vulnerability-reporting process or safe-harbor terms will apply prospectively.+ Akeru Bot runs coding agents on systems you control. Keep the app and operating system up to+ date. Protect provider and repository credentials. Review commands and source changes before+ you approve them. Revoke any credential that may have leaked.</p></section><section id="contact">- <p class="section-number">07</p>- <h2>Contact Us</h2>- <p>- Report security issues or ask security-related questions at{" "}<a- href="mailto:[email protected]">[email protected]</a- >.- </p>+ <p class="section-number">04</p>+ <h2>Contact</h2><p>- For general legal questions, contact{" "}<a href="mailto:[email protected]">[email protected]</a>.- For privacy requests, contact{" "}<a href="mailto:[email protected]">[email protected]</a>.+ Use the Akeru Bot repository for security questions. This draft must receive qualified legal+ counsel review before any public release.</p></section></LegalPage>diff --git a/apps/marketing/src/pages/terms-of-service.astro b/apps/marketing/src/pages/terms-of-service.astroindex e6de5f2c7..8d976a6d8 100644--- a/apps/marketing/src/pages/terms-of-service.astro+++ b/apps/marketing/src/pages/terms-of-service.astro@@ -2,395 +2,79 @@import LegalPage from "../components/LegalPage.astro";const sections = [- ["introduction", "Introduction"],- ["accounts", "Accounts"],- ["content", "Your content and providers"],- ["rights", "T3 Code and proprietary rights"],+ ["software", "The software"],+ ["providers", "Providers and user content"],["acceptable-use", "Acceptable use"],- ["availability", "Availability and changes"],- ["fees", "Fees"],+ ["warranty", "Warranty and liability"],["privacy", "Privacy"],- ["termination", "Suspension and termination"],- ["beta", "Beta services"],- ["disclaimers", "Disclaimers"],- ["liability", "Limitation of liability"],- ["indemnification", "Indemnification"],- ["copyright", "Copyright complaints"],- ["third-parties", "Third-party services"],- ["feedback", "Feedback"],- ["disputes", "Dispute resolution"],- ["miscellaneous", "Miscellaneous"],- ["changes", "Changes to these Terms"],- ["contact", "Contact us"],+ ["contact", "Contact"],] as const;---<LegalPage- title="Terms of Service — T3 Code"- description="The terms that govern your use of T3 Code, app.t3.codes, T3 Connect, and t3.codes."- heading="T3 Code Terms of Service"- lede="These Terms govern your use of T3 Code, including its desktop, mobile, and hosted applications, the optional T3 Connect service, and the t3.codes website."- effectiveDate="2026-07-15"- lastUpdated="2026-07-15"+ title="Terms of Use - Akeru Bot"+ description="Draft terms for use of the Akeru Bot software and website."+ heading="Akeru Bot Terms of Use"+ lede="These draft terms cover the Akeru Bot software and website. The open-source license continues to govern the source code."+ status="Draft - counsel review required"+ lastUpdated="2026-08-31"sections={sections}>- <section id="introduction">+ <section id="software"><p class="section-number">01</p>- <h2>Introduction</h2>+ <h2>The software</h2><p>- These Terms of Service (the “Terms”) are a binding agreement between you and T3 Tools, Inc.- (“T3 Tools,” “we,” “us,” or “our”). They govern your access to and use of the T3 Code desktop- and mobile applications, the hosted T3 Code application at{" "}<a href="https://app.t3.codes"- >https://app.t3.codes</a- >, and the optional T3 Connect service (together, the “Services”), as well as the T3 Code- marketing website at{" "}<a href="https://t3.codes">https://t3.codes</a> (the “Site”).- </p>- <p>- By accessing or using the Site or Services, you agree to these Terms. If you use the Services- for an organization, you represent that you have authority to bind that organization, and- “you” includes the organization. If you do not agree to these Terms, do not use the Site or- Services.- </p>- <p>- You must be at least 13 years old to use the Site or Services. If the law where you live- requires a greater age to enter into these Terms, you must meet that requirement or have a- parent or legal guardian agree on your behalf.+ Akeru Bot is local-first, open-source software. The MIT License included with the repository+ governs your use, copying, modification, and distribution of the source code. These Terms do+ not create a hosted Akeru account or cloud service.</p></section>- <section id="accounts">+ <section id="providers"><p class="section-number">02</p>- <h2>Accounts</h2>+ <h2>Providers and user content</h2><p>- You can use some T3 Code features without creating a T3 account. An account may be required- for account-backed features, including T3 Connect. You agree to provide accurate account- information, keep your credentials secure, and promptly notify us if you suspect unauthorized- access. You are responsible for activity performed through your account and connected devices,- except to the extent caused by our failure to use reasonable security measures.- </p>- <p>- You may not share credentials in a way that compromises the Services, impersonate another- person, or create accounts through unauthorized automated means. We may require reasonable- verification before restoring access or acting on an account request.+ You choose and configure each agent provider. You keep your rights in prompts, files, tool+ results, and other content. You must have permission to send that content to the selected+ provider. Provider terms, charges, output rules, and retention policies apply to its service.</p></section>- <section id="content">+ <section id="acceptable-use"><p class="section-number">03</p>- <h2>Your Content and Providers</h2>+ <h2>Acceptable use</h2><p>- T3 Code can help you send prompts, source files, images, attachments, review comments, and- instructions to coding-agent harnesses and providers you choose, and display their responses,- command output, file changes, source code, and diffs (collectively, “User Content”). You retain- all rights you have in your User Content.- </p>- <p>- You bring and configure your own coding-agent harness and provider. Your User Content is- ordinarily processed in the environment you control and by the providers you select, not by- T3 Tools. When you enable a T3 Tools-operated feature that must transmit or process User- Content, you grant us a limited, non-exclusive license to host, transmit, reproduce, and- process that content only as reasonably necessary to provide, secure, and troubleshoot that- feature. This license ends when the content is no longer needed for those purposes, subject to- reasonable backup, security, and legal-retention requirements.- </p>- <p>- You represent that you have the rights and permissions needed to use and submit User Content- and to direct its processing by your selected harnesses and providers. You are responsible for- reviewing those providers’ terms, privacy practices, data controls, and output before using- them with confidential, proprietary, regulated, or personal information.+ Do not use Akeru Bot to break the law, violate another person's rights, gain unauthorized+ access, distribute malware, or damage systems. You are responsible for reviewing commands,+ payments, messages, deletions, and production actions before you approve them.</p></section>- <section id="rights">+ <section id="warranty"><p class="section-number">04</p>- <h2>T3 Code and Proprietary Rights</h2>- <p>- T3 Tools and its licensors own the Site, the Services, and their branding, designs, hosted- infrastructure, documentation, and other materials, excluding User Content and third-party- materials. These Terms do not transfer ownership of either party’s intellectual property.- </p>+ <h2>Warranty and liability</h2><p>- Portions of T3 Code are available as open-source software. Your use, copying, modification, and- distribution of that source code are governed by the license included with the applicable- repository or component. These Terms govern your use of the hosted Services and do not limit- rights granted to you by an applicable open-source license.- </p>- <p>- Subject to these Terms, we grant you a limited, non-exclusive, non-transferable, revocable right- to access and use the Services for lawful personal or internal business purposes. You may not- use our trademarks, service marks, or trade dress without written permission.- </p>- </section>-- <section id="acceptable-use">- <p class="section-number">05</p>- <h2>Acceptable Use</h2>- <p>You may not use the Site or Services to:</p>- <ul>- <li>Violate applicable law or another person’s rights;</li>- <li>Upload, transmit, or generate content you do not have the right to use;</li>- <li>Distribute malware, exploit code, or harmful content except in authorized security work;</li>- <li>Probe, attack, disrupt, or gain unauthorized access to the Services or another system;</li>- <li>Bypass rate limits, access controls, security measures, or usage restrictions;</li>- <li>Interfere with other users or place an unreasonable load on shared infrastructure;</li>- <li>Use the Services to facilitate fraud, harassment, abuse, or deceptive conduct; or</li>- <li>Misrepresent that output or activity from a third-party agent was produced or endorsed by us.</li>- </ul>- <p>- Authorized security research must follow our{" "}<a href="/security-policy">Security Policy</a>.- We may investigate suspected violations and take proportionate action to protect users and the- Services.- </p>- </section>-- <section id="availability">- <p class="section-number">06</p>- <h2>Availability and Changes</h2>- <p>- We may add, change, suspend, or discontinue features, integrations, or supported platforms. We- aim to provide reasonable notice when a change materially reduces an account-backed feature,- but urgent security, legal, or reliability changes may take effect immediately. The Services- may be unavailable because of maintenance, provider outages, network conditions, or events- outside our control.- </p>- <p>- T3 Code depends on software, environments, networks, and coding-agent providers that you- configure or that third parties operate. We do not control their availability, compatibility,- pricing, or behavior.- </p>- </section>-- <section id="fees">- <p class="section-number">07</p>- <h2>Fees</h2>- <p>- T3 Code is currently offered without a T3 Tools subscription fee unless we clearly state- otherwise for a feature. You remain responsible for charges from your coding-agent providers,- cloud infrastructure, network operators, app stores, and other third parties. If we introduce- a paid feature, we will present its price and applicable payment terms before you purchase it.+ The software is provided under the warranty and liability terms in the MIT License. Agent+ output can be wrong or unsafe. Keep backups and review actions that can affect money, data,+ accounts, or production systems.</p></section><section id="privacy">- <p class="section-number">08</p>+ <p class="section-number">05</p><h2>Privacy</h2><p>- Our{" "}<a href="/privacy-policy">Privacy Policy</a> explains how T3 Tools collects, uses, and- shares personal information when you use the Site and Services. Third-party environments,- harnesses, identity providers, and coding-agent providers process information under their own- terms and privacy policies.+ The <a href="/privacy-policy">Privacy Policy</a> lists local storage, outbound data, retention,+ and available controls.</p></section>- <section id="termination">- <p class="section-number">09</p>- <h2>Suspension and Termination</h2>- <p>- You may stop using the Services at any time. You may disconnect environments and devices from- within T3 Code and may request deletion of an account as described in our Privacy Policy.- </p>- <p>- We may suspend or terminate access to account-backed or hosted features if we reasonably- believe you materially violated these Terms, created a security or legal risk, failed to pay an- applicable fee, or used the Services in a way that could harm other users or shared- infrastructure. When practicable, we will give notice and an opportunity to cure. We may act- immediately where needed to prevent harm or comply with law.- </p>- <p>- Provisions that by their nature should survive termination—including ownership, disclaimers,- limitations of liability, indemnification, and dispute terms—will survive.- </p>- </section>-- <section id="beta">- <p class="section-number">10</p>- <h2>Beta Services</h2>- <p>- T3 Code is an early-stage product, and some or all features may be identified as alpha, beta,- preview, experimental, or pre-release (“Beta Services”). Beta Services may be incomplete,- change without notice, contain errors, or lose data. Do not rely on Beta Services as the sole- copy of important work, and review proposed commands and file changes before applying them.- </p>- </section>-- <section id="disclaimers">- <p class="section-number">11</p>- <h2>Disclaimers</h2>- <p class="legal-notice">- TO THE MAXIMUM EXTENT PERMITTED BY LAW, THE SITE AND SERVICES ARE PROVIDED “AS IS” AND “AS- AVAILABLE,” WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING WARRANTIES OF- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE, AND NON-INFRINGEMENT.- </p>- <p>- Coding agents and artificial-intelligence systems can produce incorrect, insecure, incomplete,- or harmful output. You are responsible for reviewing output, commands, patches, and other- actions before relying on or executing them. We do not warrant that the Services or third-party- output will be uninterrupted, secure, accurate, error-free, or suitable for your purpose.- </p>- <p>- Some jurisdictions do not allow certain warranty exclusions, so some of the foregoing may not- apply to you.- </p>- </section>-- <section id="liability">- <p class="section-number">12</p>- <h2>Limitation of Liability</h2>- <p class="legal-notice">- TO THE MAXIMUM EXTENT PERMITTED BY LAW, T3 TOOLS AND ITS AFFILIATES, OFFICERS, EMPLOYEES,- AGENTS, AND LICENSORS WILL NOT BE LIABLE FOR INDIRECT, INCIDENTAL, SPECIAL, CONSEQUENTIAL,- EXEMPLARY, OR PUNITIVE DAMAGES, OR FOR LOST PROFITS, REVENUE, DATA, GOODWILL, OR BUSINESS- OPPORTUNITIES, ARISING FROM OR RELATED TO THE SITE, SERVICES, OR THESE TERMS.- </p>- <p>- To the maximum extent permitted by law, our aggregate liability for all claims arising from or- relating to the Site, Services, or these Terms will not exceed the greater of $100 or the amount- you paid directly to T3 Tools for the Services during the 12 months before the event giving rise- to the claim. These limitations apply regardless of the legal theory and even if a remedy fails- of its essential purpose. They do not limit liability that cannot lawfully be limited.- </p>- </section>-- <section id="indemnification">- <p class="section-number">13</p>- <h2>Indemnification</h2>- <p>- To the extent permitted by law, you will defend, indemnify, and hold harmless T3 Tools and its- affiliates, officers, employees, and agents from third-party claims, damages, losses, and- reasonable legal fees arising from your User Content, your use of the Site or Services in- violation of these Terms or law, or your infringement of another person’s rights. We will- promptly notify you of a covered claim and reasonably cooperate in its defense. You may not- settle a claim in a way that admits fault by or imposes obligations on us without our written- consent.- </p>- </section>-- <section id="copyright">- <p class="section-number">14</p>- <h2>Copyright Complaints</h2>- <p>- If you believe material available through a T3 Tools-operated part of the Site or Services- infringes your copyright, send a notice to{" "}<a href="mailto:[email protected]">[email protected]</a- >{" "}identifying the copyrighted work, the allegedly infringing material and its location, your- contact information, a statement of good-faith belief, a statement under penalty of perjury- that the notice is accurate and you are authorized to act, and your physical or electronic- signature.- </p>- <p>- T3 Tools does not control content stored only in a user’s environment or held by a user-selected- provider. Requests concerning that material should be directed to the operator that hosts it.- </p>- </section>-- <section id="third-parties">- <p class="section-number">15</p>- <h2>Third-Party Services</h2>- <p>- The Services may connect to or display content from third-party coding agents, model providers,- identity providers, repositories, app stores, websites, and infrastructure. Your use of those- services is governed by their terms. We do not endorse or control third-party services and are- not responsible for their content, security, availability, output, or data practices.- </p>- <p>- Third-party and open-source software included with T3 Code is governed by its applicable- license notices. Where those licenses conflict with these Terms for that software, the- applicable open-source license controls.- </p>- </section>-- <section id="feedback">- <p class="section-number">16</p>- <h2>Feedback</h2>- <p>- If you send us ideas, suggestions, or other feedback about T3 Code, you grant T3 Tools a- perpetual, irrevocable, worldwide, royalty-free right to use and commercialize that feedback- without restriction or compensation. This does not transfer ownership of your User Content.- </p>- </section>-- <section id="disputes">- <p class="section-number">17</p>- <h2>Dispute Resolution</h2>- <p class="legal-notice">- PLEASE READ THIS SECTION CAREFULLY. IT REQUIRES MOST DISPUTES TO BE RESOLVED BY INDIVIDUAL- BINDING ARBITRATION AND WAIVES JURY TRIALS AND CLASS OR REPRESENTATIVE ACTIONS.- </p>- <h3>Informal Resolution</h3>- <p>- Before starting arbitration or a court proceeding, the party raising a dispute must send a- written notice describing the dispute and requested relief. Notices to us must be sent to{" "}<a- href="mailto:[email protected]">[email protected]</a- >. The parties will try in good faith to resolve the dispute for at least 30 days.- </p>- <h3>Binding Arbitration</h3>- <p>- Except for disputes eligible for small-claims court and requests for injunctive relief to- protect intellectual property or prevent unauthorized access, unresolved disputes will be- resolved by binding individual arbitration administered by JAMS under its applicable consumer- or comprehensive rules. The Federal Arbitration Act governs this agreement. Arbitration may- take place remotely unless the arbitrator determines that an in-person hearing is necessary.- </p>- <h3>No Class Actions</h3>- <p>- Disputes must be brought only on an individual basis. Neither party may participate in a class,- collective, consolidated, or representative action or arbitration to the extent permitted by- law.- </p>- <h3>Opt Out</h3>- <p>- You may opt out of this arbitration agreement by emailing{" "}<a href="mailto:[email protected]"- >[email protected]</a- > within 30 days after you first accept these Terms. Include your name, the email associated- with your account if any, and a clear statement that you opt out of arbitration.- </p>- <p>- If the arbitration agreement does not apply, exclusive jurisdiction and venue will lie in the- state and federal courts located in San Francisco County, California, and each party consents- to those courts.- </p>- </section>-- <section id="miscellaneous">- <p class="section-number">18</p>- <h2>Miscellaneous</h2>- <p>- California law governs these Terms without regard to conflict-of-law principles, except that- the Federal Arbitration Act governs the arbitration provisions. These Terms and documents- incorporated by reference are the entire agreement between you and us regarding the Site and- Services. If a provision is unenforceable, it will be modified to the minimum extent necessary- or severed, and the remaining provisions will continue in effect.- </p>- <p>- Our failure to enforce a provision is not a waiver. You may not assign these Terms without our- written consent. We may assign them in connection with a merger, acquisition, reorganization,- or sale of assets. We are not liable for delays or failures caused by events beyond our- reasonable control. Headings are for convenience only, and “including” means “including without- limitation.”- </p>- </section>-- <section id="changes">- <p class="section-number">19</p>- <h2>Changes to These Terms</h2>+ <section id="contact">+ <p class="section-number">06</p>+ <h2>Contact</h2><p>- We may update these Terms from time to time. We will post updated Terms at this URL and update- the dates above. If a change materially affects your rights, we will provide additional notice- when reasonably practicable or as required by law. Changes apply prospectively from their- effective date. Your continued use of the Site or Services after that date means you accept the- updated Terms.+ Report terms questions through the Akeru Bot repository. This draft must receive qualified+ legal counsel review before any public release.</p></section>-- <section id="contact">- <p class="section-number">20</p>- <h2>Contact Us</h2>- <p>If you have questions about these Terms, contact us at:</p>- <address>- <strong>T3 Tools, Inc.</strong><br />- 2261 Market Street #5309<br />- San Francisco, CA 94114<br />- United States- </address>- <a class="contact-link" href="mailto:[email protected]">[email protected]</a>- </section></LegalPage>diff --git a/apps/mobile/README.md b/apps/mobile/README.mdindex 0eb865cb7..86b163e37 100644--- a/apps/mobile/README.md+++ b/apps/mobile/README.md@@ -1,122 +1,82 @@-# T3 Code Mobile+# Akeru Bot Mobile-> [!WARNING]-> T3 Code Mobile is currently in development and is not distributed yet. If you want to try it out, you can build it from source.+Akeru Bot Mobile is the React Native client for iOS and Android. It connects directly to an Akeru+Bot server through pairing, a saved bearer connection, LAN access, or Tailscale.-## Quickstart+## Requirements-> [!NOTE]-> Uses native modules so using Expo Go is not supported. You need to use the Expo Dev Client.--This app has three variants:--- `development`: Expo dev client, installable side-by-side as `T3 Code Dev`-- `preview`: persistent internal preview build, installable side-by-side as `T3 Code Preview`-- `production`: store/release build as `T3 Code`+The app uses native modules and does not run in Expo Go. Use the Expo development client.Run commands from `apps/mobile`.-T3 Connect is optional and disabled in a fresh clone. Public configuration belongs in the-repository-root `.env` or `.env.local`, not an `apps/mobile/.env` file. See-[`../../.env.example`](../../.env.example).-## Development-Start Metro for the dev client:+Start Metro:```bashvp run dev:client```-Build and run the local iOS dev client:+Build and run the local iOS development app:```bashvp run ios:dev```-If your Xcode account only has a Personal Team, use a bundle identifier you control and opt into the-reduced-capability local build. Personal Team builds omit the widget and share extensions, push-entitlement, and native Sign in with Apple entitlement; builds without this opt-in are unchanged.--```bash-T3CODE_IOS_PERSONAL_TEAM=1 \-T3CODE_IOS_PERSONAL_TEAM_BUNDLE_ID=com.example.t3code.dev \-vp run ios:dev-```--Build and install a self-contained Release app that does not need Metro:+Build a self-contained iOS release app:```bashvp run ios:release```-The Personal Team equivalent also needs a unique bundle identifier:--```bash-T3CODE_IOS_PERSONAL_TEAM=1 \-T3CODE_IOS_PERSONAL_TEAM_BUNDLE_ID=com.example.t3code \-vp run ios:release-```--Build and run the local iOS preview app:+Build the local preview app:```bashvp run ios:preview```-Force the review diff highlighter engine:+A Personal Team build needs a bundle identifier that you control:```bash-EXPO_PUBLIC_REVIEW_HIGHLIGHTER_ENGINE=javascript vp run ios:dev+T3CODE_IOS_PERSONAL_TEAM=1 \+T3CODE_IOS_PERSONAL_TEAM_BUNDLE_ID=com.example.akeru.dev \+vp run ios:dev```-`javascript` is the default and recommended setting for the review diff screen. Set `EXPO_PUBLIC_REVIEW_HIGHLIGHTER_ENGINE=native` only when you explicitly want to test the native Shiki engine.+Personal Team builds omit extensions and entitlements that require a paid Apple Developer account.-Inspect the resolved Expo config for a variant:+## Configuration++Inspect the resolved Expo configuration:```bashvp run config:devvp run config:preview```-Run static checks for mobile native code:+The JavaScript review highlighter is the default. Set+`EXPO_PUBLIC_REVIEW_HIGHLIGHTER_ENGINE=native` only when testing the native engine.++Run native static checks:```bashnode ../../scripts/mobile-native-static-check.ts```-The native lint task runs SwiftLint for Swift plus ktlint and detekt for Kotlin. Missing native tools are reported as warnings and skipped locally. CI installs the default toolset from `apps/mobile/Brewfile` before running the native checks.--## EAS Builds+The task runs SwiftLint, ktlint, and detekt when those tools are installed.-CI uses Expo fingerprinting with the `preview:dev` profile to reuse an existing compatible build when possible, or start a new internal EAS build when native runtime inputs change. Production and default local builds continue to use the `appVersion` runtime policy.+## EAS builds-For preview or production EAS environments, set `T3CODE_CLERK_PUBLISHABLE_KEY`,-`T3CODE_CLERK_JWT_TEMPLATE`, and `T3CODE_RELAY_URL`-as EAS environment variables. Expo config maps the canonical values into the mobile build.--Create a PR preview dev-client build manually:+CI can use Expo fingerprinting to reuse compatible preview builds. Manual commands are:```bashvp run eas:ios:preview:dev-```--Create a cloud dev-client build:--```bashvp run eas:ios:dev-```--Create a persistent preview build:--```bashvp run eas:ios:preview-```--Android equivalents:--```bashvp run eas:android:devvp run eas:android:preview:devvp run eas:android:preview```++No hosted account or hosted transport configuration is required. The app stores saved+environment records on the device and connects to each server directly.diff --git a/apps/mobile/app.config.ts b/apps/mobile/app.config.tsindex 9a5172547..5cbc4ce63 100644--- a/apps/mobile/app.config.ts+++ b/apps/mobile/app.config.ts@@ -65,7 +65,6 @@ const VARIANT_CONFIG = {scheme: "t3code-dev",iosBundleIdentifier: "com.t3tools.t3code.dev",androidPackage: "com.t3tools.t3code.dev",- relyingParty: "clerk.t3.codes",assets: DEVELOPMENT_ASSETS,},preview: {@@ -73,7 +72,6 @@ const VARIANT_CONFIG = {scheme: "t3code-preview",iosBundleIdentifier: "com.t3tools.t3code.preview",androidPackage: "com.t3tools.t3code.preview",- relyingParty: "clerk.t3.codes",assets: PREVIEW_ASSETS,},production: {@@ -81,7 +79,6 @@ const VARIANT_CONFIG = {scheme: "t3code",iosBundleIdentifier: "com.t3tools.t3code",androidPackage: "com.t3tools.t3code",- relyingParty: "clerk.t3.codes",assets: RELEASE_ASSETS,},} as const;@@ -189,10 +186,6 @@ const config: ExpoConfig = {// does not fall back to a personal team (which cannot sign app groups,// Sign in with Apple, or push notification entitlements).appleTeamId: "ARK85ZXQ4Z",- associatedDomains: [- `applinks:${variant.relyingParty}`,- `webcredentials:${variant.relyingParty}`,- ],infoPlist: {NSAppTransportSecurity: {NSAllowsArbitraryLoads: true,@@ -272,9 +265,6 @@ const config: ExpoConfig = {mode: APP_VARIANT === "development" ? "development" : "production",},],- // appleSignIn must be gated here: withoutIosPersonalTeamCapabilities.cjs runs before- // plugins earlier in this array, so it cannot strip the entitlement Clerk would add.- ["@clerk/expo", { theme: "./clerk-theme.json", appleSignIn: !isIosPersonalTeamBuild }],"expo-web-browser",["expo-quick-actions",@@ -344,22 +334,6 @@ const config: ExpoConfig = {extra: {appVariant: APP_VARIANT,iosPersonalTeamBuild: isIosPersonalTeamBuild,- relay: {- url: repoEnv.T3CODE_RELAY_URL ?? null,- },- clerk: {- publishableKey: repoEnv.EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY ?? null,- jwtTemplate: repoEnv.EXPO_PUBLIC_CLERK_JWT_TEMPLATE ?? null,- },- // Native Google sign-in credentials. @clerk/expo reads these from `extra`- // under their exact env-var names (not nested), and its config plugin reads- // the iOS URL scheme at prebuild to register it in Info.plist.- // Unset values must be omitted (not null): the public manifest serializes- // null to {}, which is truthy and would defeat Clerk's fallback checks.- EXPO_PUBLIC_CLERK_GOOGLE_WEB_CLIENT_ID: repoEnv.EXPO_PUBLIC_CLERK_GOOGLE_WEB_CLIENT_ID,- EXPO_PUBLIC_CLERK_GOOGLE_IOS_CLIENT_ID: repoEnv.EXPO_PUBLIC_CLERK_GOOGLE_IOS_CLIENT_ID,- EXPO_PUBLIC_CLERK_GOOGLE_ANDROID_CLIENT_ID: repoEnv.EXPO_PUBLIC_CLERK_GOOGLE_ANDROID_CLIENT_ID,- EXPO_PUBLIC_CLERK_GOOGLE_IOS_URL_SCHEME: repoEnv.EXPO_PUBLIC_CLERK_GOOGLE_IOS_URL_SCHEME,observability: {tracesUrl: repoEnv.EXPO_PUBLIC_OTLP_TRACES_URL ?? "https://api.axiom.co/v1/traces",tracesDataset: repoEnv.EXPO_PUBLIC_OTLP_TRACES_DATASET ?? null,diff --git a/apps/mobile/clerk-theme.json b/apps/mobile/clerk-theme.jsondeleted file mode 100644index 119927a04..000000000--- a/apps/mobile/clerk-theme.json+++ /dev/null@@ -1,39 +0,0 @@-{- "colors": {- "primary": "#262626",- "background": "#F2F2F7",- "input": "#FFFFFF",- "danger": "#DC2626",- "success": "#059669",- "warning": "#D97706",- "foreground": "#262626",- "mutedForeground": "#737373",- "primaryForeground": "#FFFFFF",- "inputForeground": "#262626",- "neutral": "#F5F5F5",- "border": "#E5E5EA",- "ring": "#A3A3A3",- "muted": "#F2F2F7",- "shadow": "#000000"- },- "darkColors": {- "primary": "#F5F5F5",- "background": "#0E0E0E",- "input": "#171717",- "danger": "#FCA5A5",- "success": "#34D399",- "warning": "#FBBF24",- "foreground": "#F5F5F5",- "mutedForeground": "#A3A3A3",- "primaryForeground": "#0A0A0A",- "inputForeground": "#F5F5F5",- "neutral": "#1C1C1C",- "border": "#2A2A2A",- "ring": "#525252",- "muted": "#0E0E0E",- "shadow": "#000000"- },- "design": {- "borderRadius": 18- }-}diff --git a/apps/mobile/package.json b/apps/mobile/package.jsonindex 1097f6a33..cc4797366 100644--- a/apps/mobile/package.json+++ b/apps/mobile/package.json@@ -44,7 +44,6 @@},"dependencies": {"@callstack/liquid-glass": "^0.7.1",- "@clerk/expo": "catalog:","@effect/atom-react": "catalog:","@expo-google-fonts/dm-sans": "^0.4.2","@expo/metro-runtime": "~56.0.15",@@ -124,6 +123,7 @@"devDependencies": {"@effect/vitest": "catalog:","@pierre/trees": "1.0.0-beta.4",+ "@types/node": "catalog:","@types/react": "~19.2.0","babel-preset-expo": "~56.0.0","tailwindcss": "^4.0.0",diff --git a/apps/mobile/src/App.tsx b/apps/mobile/src/App.tsxindex 8b219afcc..a34e2c448 100644--- a/apps/mobile/src/App.tsx+++ b/apps/mobile/src/App.tsx@@ -10,7 +10,7 @@ import { createStaticNavigation } from "@react-navigation/native";import { RegistryContext } from "@effect/atom-react";import { ConfirmDialogHost } from "./components/ConfirmDialogHost";-import { CloudAuthProvider } from "./features/cloud/CloudAuthProvider";+import { MobilePolicyNotice } from "./features/settings/MobilePolicyNotice";import { prepareNativeShowcaseCapture } from "./features/showcase/nativeShowcaseScene";import { IncomingShareProvider } from "./features/sharing/IncomingShareProvider";import {@@ -61,11 +61,9 @@ function SplashScreenCoordinator() {export default function App() {return (<RegistryContext.Provider value={appAtomRegistry}>- <CloudAuthProvider>- <AppearancePreferencesProvider>- <AppContent />- </AppearancePreferencesProvider>- </CloudAuthProvider>+ <AppearancePreferencesProvider>+ <AppContent />+ </AppearancePreferencesProvider></RegistryContext.Provider>);}@@ -97,6 +95,7 @@ function AppContent() {<Navigation linking={appLinking} theme={navigationTheme} /></IncomingShareProvider><ConfirmDialogHost />+ <MobilePolicyNotice /></BlurTargetView>{/* Anchored-menu overlays render here — in-window, so thekeyboard stays up while a dropdown is open. */}diff --git a/apps/mobile/src/Stack.tsx b/apps/mobile/src/Stack.tsxindex efbdfb487..e05dc017f 100644--- a/apps/mobile/src/Stack.tsx+++ b/apps/mobile/src/Stack.tsx@@ -18,8 +18,6 @@ import { AppText as Text } from "./components/AppText";import { getCompactBrandHeaderOptions } from "./components/CompactBrandTitle";import { ArchivedThreadsRouteScreen } from "./features/archive/ArchivedThreadsRouteScreen";import { useAgentNotificationNavigation } from "./features/agent-awareness/notificationNavigation";-import { ConnectOnboardingRouteScreen } from "./features/cloud/ConnectOnboardingRouteScreen";-import { useConnectOnboardingNavigation } from "./features/cloud/connectOnboardingNavigation";import { ThreadFilesTreeScreen, ThreadFileScreen } from "./features/files/ThreadFilesRouteScreen";import { AdaptiveWorkspaceLayout } from "./features/layout/AdaptiveWorkspaceLayout";import { HardwareKeyboardCommandProvider } from "./features/keyboard/HardwareKeyboardCommandProvider";@@ -52,7 +50,6 @@ import { NewTaskFlowProvider } from "./features/threads/new-task-flow-provider";import { NewTaskRouteScreen } from "./features/threads/NewTaskRouteScreen";import { SettingsAppearanceRouteScreen } from "./features/settings/SettingsAppearanceRouteScreen";import { SettingsClientStorageRouteScreen } from "./features/settings/SettingsClientStorageRouteScreen";-import { SettingsAuthRouteScreen } from "./features/settings/SettingsAuthRouteScreen";import { SettingsEnvironmentsRouteScreen } from "./features/settings/SettingsEnvironmentsRouteScreen";import { SettingsLegalRouteScreen } from "./features/settings/SettingsLegalRouteScreen";import { SettingsProjectGroupingRouteScreen } from "./features/settings/SettingsProjectGroupingRouteScreen";@@ -210,8 +207,7 @@ const SettingsContentStack = createNativeStackNavigator({});// The outer stack never owns visible chrome. Settings routes render inside a-// nested stack whose native header remains mounted, while Clerk owns auth chrome.-// Keeping bar visibility invariant avoids iOS 26's headerless-to-headered jump.+// nested stack whose native header remains mounted.const SettingsSheetStack = createNativeStackNavigator({initialRouteName: "SettingsContent",screenOptions: {@@ -222,15 +218,6 @@ const SettingsSheetStack = createNativeStackNavigator({screen: SettingsContentStack,linking: "",}),- SettingsAuth: createNativeStackScreen({- screen: SettingsAuthRouteScreen,- linking: "auth",- }),- SettingsWaitlist: createNativeStackScreen({- // Keep the old deep link working after the Connect GA launch.- screen: SettingsAuthRouteScreen,- linking: "waitlist",- }),},});@@ -329,7 +316,6 @@ const NewTaskSheetStack = createNativeStackNavigator({// influence the adaptive workspace layout: opening Settings over Home should// not flip the sidebar in or change the active thread.const WORKSPACE_OVERLAY_ROUTES = new Set([- "ConnectOnboarding","Connections","ConnectionsNew","GitBranches",@@ -374,8 +360,6 @@ function RootStackLayout(props: {const { pendingShare } = useIncomingShare();const sharePresentationRef = useRef(EMPTY_INCOMING_SHARE_PRESENTATION_STATE);useAgentNotificationNavigation();- // Presents the T3 Connect onboarding sheet after an in-session sign-in.- useConnectOnboardingNavigation();// Launcher app shortcuts: routes shortcut taps and tracks opened threads.useAppShortcuts(props.state);useEffect(() => {@@ -584,20 +568,6 @@ export const RootStack = createNativeStackNavigator({title: "Legal",},}),- ConnectOnboarding: createNativeStackScreen({- screen: ConnectOnboardingRouteScreen,- linking: "connect-onboarding",- options: {- // A root-level Android formSheet does not host the native stack bar;- // the route renders an embedded AndroidSheetHeader instead.- ...(Platform.OS === "android" ? { headerShown: false } : SHEET_SOLID_HEADER_OPTIONS),- title: "Set up T3 Connect",- gestureEnabled: true,- ...FORM_SHEET_PRESENTATION_OPTIONS,- sheetAllowedDetents: [0.6, 0.95],- sheetGrabberVisible: true,- },- }),Connections: createNativeStackScreen({screen: ConnectionsRouteScreen,linking: "connections",diff --git a/apps/mobile/src/connection/migration.test.ts b/apps/mobile/src/connection/migration.test.tsindex 5cb17bd5b..b3ce186d6 100644--- a/apps/mobile/src/connection/migration.test.ts+++ b/apps/mobile/src/connection/migration.test.ts@@ -5,7 +5,7 @@ import * as Effect from "effect/Effect";import { migrateLegacyConnectionCatalog } from "./migration";describe("migrateLegacyConnectionCatalog", () => {- it.effect("migrates bearer and relay-managed connections into the new catalog", () =>+ it.effect("migrates bearer connections and drops hosted relay records", () =>Effect.gen(function* () {const bearerEnvironmentId = EnvironmentId.make("bearer-environment");const relayEnvironmentId = EnvironmentId.make("relay-environment");@@ -37,13 +37,13 @@ describe("migrateLegacyConnectionCatalog", () => {}),);- expect(catalog.targets).toHaveLength(2);+ expect(catalog.targets).toHaveLength(1);expect(catalog.targets.find((target) => target.environmentId === bearerEnvironmentId)?._tag,).toBe("BearerConnectionTarget");- expect(- catalog.targets.find((target) => target.environmentId === relayEnvironmentId)?._tag,- ).toBe("RelayConnectionTarget");+ expect(catalog.targets.some((target) => target.environmentId === relayEnvironmentId)).toBe(+ false,+ );expect(catalog.profiles).toHaveLength(1);expect(catalog.credentials).toHaveLength(1);expect(catalog.credentials[0]?.credential).toMatchObject({diff --git a/apps/mobile/src/connection/migration.ts b/apps/mobile/src/connection/migration.tsindex 6f324c9ff..96f4bea5c 100644--- a/apps/mobile/src/connection/migration.ts+++ b/apps/mobile/src/connection/migration.ts@@ -2,8 +2,6 @@ import {BearerConnectionCredential,BearerConnectionProfile,BearerConnectionRegistration,- RelayConnectionRegistration,- RelayConnectionTarget,BearerConnectionTarget,} from "@t3tools/client-runtime/connection";import {@@ -49,15 +47,7 @@ function migrateConnection(connection: typeof LegacySavedRemoteConnection.Type,): ConnectionCatalogDocument {if (isRelayManaged(connection)) {- return registerConnectionInCatalog(- document,- new RelayConnectionRegistration({- target: new RelayConnectionTarget({- environmentId: connection.environmentId,- label: connection.environmentLabel,- }),- }),- );+ return document;}if (connection.bearerToken === null || connection.bearerToken.trim() === "") {diff --git a/apps/mobile/src/connection/platform.ts b/apps/mobile/src/connection/platform.tsindex 8e699e4c2..052bd71a3 100644--- a/apps/mobile/src/connection/platform.ts+++ b/apps/mobile/src/connection/platform.ts@@ -1,10 +1,8 @@import {ClientPresentation,- CloudSession,EnvironmentOwnedDataCleanup,PlatformConnectionSource,PrimaryEnvironmentAuth,- RelayDeviceIdentity,SshEnvironmentGateway,} from "@t3tools/client-runtime/platform";import {@@ -13,7 +11,6 @@ import {Connectivity,Wakeups,} from "@t3tools/client-runtime/connection";-import { managedRelayAccountChanges, managedRelaySessionAtom } from "@t3tools/client-runtime/relay";import { AuthStandardClientScopes } from "@t3tools/contracts";import * as Context from "effect/Context";import * as Effect from "effect/Effect";@@ -27,8 +24,6 @@ import { AppState } from "react-native";import { authClientMetadata } from "../lib/authClientMetadata";import * as Runtime from "../lib/runtime";-import * as MobileStorage from "../persistence/mobile-storage";-import { appAtomRegistry } from "../state/atom-registry";import { clearThreadOutboxEnvironment } from "../state/thread-outbox";import { clearComposerDraftsEnvironment } from "../state/use-composer-drafts";import { mobileApplicationActiveWakeup } from "./app-state-wakeups";@@ -87,83 +82,32 @@ const connectivityLayer = Connectivity.layer({});const wakeupsLayer = Wakeups.layer({- changes: Stream.merge(- Stream.callback<"application-active-probe" | "application-active-reconnect">((queue) =>- Effect.acquireRelease(- Effect.sync(() => {- let backgroundedAtMs = AppState.currentState === "background" ? Date.now() : null;- return AppState.addEventListener("change", (state) => {- if (state === "background") {- backgroundedAtMs = Date.now();- return;- }- if (state === "active") {- Queue.offerUnsafe(queue, mobileApplicationActiveWakeup(backgroundedAtMs, Date.now()));- backgroundedAtMs = null;- }- });- }),- (subscription) => Effect.sync(() => subscription.remove()),- ).pipe(Effect.asVoid),- ),- managedRelayAccountChanges(appAtomRegistry).pipe(- Stream.map(() => "credentials-changed" as const),- ),+ changes: Stream.callback<"application-active-probe" | "application-active-reconnect">((queue) =>+ Effect.acquireRelease(+ Effect.sync(() => {+ let backgroundedAtMs = AppState.currentState === "background" ? Date.now() : null;+ return AppState.addEventListener("change", (state) => {+ if (state === "background") {+ backgroundedAtMs = Date.now();+ return;+ }+ if (state === "active") {+ Queue.offerUnsafe(queue, mobileApplicationActiveWakeup(backgroundedAtMs, Date.now()));+ backgroundedAtMs = null;+ }+ });+ }),+ (subscription) => Effect.sync(() => subscription.remove()),+ ).pipe(Effect.asVoid),),});const capabilitiesLayer = Layer.effectContext(- Effect.gen(function* () {- const storage = yield* MobileStorage.MobileStorage;- return Context.make(- CloudSession,- CloudSession.of({- clerkToken: Effect.gen(function* () {- const session = appAtomRegistry.get(managedRelaySessionAtom);- if (session === null) {- return yield* new ConnectionBlockedError({- reason: "authentication",- detail: "Sign in to T3 Connect to connect this environment.",- });- }- const token = yield* session.readClerkToken().pipe(- Effect.mapError(- (error) =>- new ConnectionTransientError({- reason: "network",- detail: error.message,- }),- ),- );- if (token === null) {- return yield* new ConnectionBlockedError({- reason: "authentication",- detail: "The T3 Connect session is unavailable.",- });- }- return token;- }),- }),+ Effect.sync(() =>+ Context.make(+ PrimaryEnvironmentAuth,+ PrimaryEnvironmentAuth.of({ bearerToken: Effect.succeed(Option.none()) }),).pipe(- Context.add(- PrimaryEnvironmentAuth,- PrimaryEnvironmentAuth.of({ bearerToken: Effect.succeed(Option.none()) }),- ),- Context.add(- RelayDeviceIdentity,- RelayDeviceIdentity.of({- deviceId: storage.loadOrCreateAgentAwarenessDeviceId.pipe(- Effect.mapError(- (cause) =>- new ConnectionTransientError({- reason: "remote-unavailable",- detail: `Could not load the mobile device identity: ${String(cause)}`,- }),- ),- Effect.map(Option.some),- ),- }),- ),Context.add(ClientPresentation,ClientPresentation.of({@@ -191,8 +135,8 @@ const capabilitiesLayer = Layer.effectContext(disconnect: () => Effect.void,}),),- );- }),+ ),+ ),);const platformConnectionSourceLayer = Layer.succeed(diff --git a/apps/mobile/src/connection/storage.ts b/apps/mobile/src/connection/storage.tsindex e84418167..e8ade4bc3 100644--- a/apps/mobile/src/connection/storage.ts+++ b/apps/mobile/src/connection/storage.ts@@ -7,7 +7,6 @@ import {removeCatalogValue,replaceCatalogValue,} from "@t3tools/client-runtime/platform";-import { TokenStore } from "@t3tools/client-runtime/authorization";import {ConnectionTransientError,CredentialStore,@@ -100,39 +99,10 @@ export const connectionStorageLayer = Layer.effectContext(),})),});- const remoteTokenStore = TokenStore.make({- get: (environmentId) =>- catalog.read.pipe(- Effect.map((document) =>- Option.fromUndefinedOr(- document.remoteDpopTokens.find((token) => token.environmentId === environmentId),- ),- ),- ),- put: (token) =>- catalog.update((document) => ({- ...document,- remoteDpopTokens: replaceCatalogValue(- document.remoteDpopTokens,- (value) => value.environmentId,- token,- ),- })),- remove: (environmentId) =>- catalog.update((document) => ({- ...document,- remoteDpopTokens: removeCatalogValue(- document.remoteDpopTokens,- (value) => value.environmentId,- environmentId,- ),- })),- });return Context.make(ConnectionTargetStore, targetStore).pipe(Context.add(ConnectionRegistrationStore, registrationStore),Context.add(ProfileStore.ConnectionProfileStore, profileStore),Context.add(CredentialStore.ConnectionCredentialStore, credentialStore),- Context.add(TokenStore.RemoteDpopAccessTokenStore, remoteTokenStore),);}),);diff --git a/apps/mobile/src/features/agent-awareness/capabilities.ts b/apps/mobile/src/features/agent-awareness/capabilities.tsdeleted file mode 100644index d627f3657..000000000--- a/apps/mobile/src/features/agent-awareness/capabilities.ts+++ /dev/null@@ -1,5 +0,0 @@-import Constants from "expo-constants";--export function supportsAgentAwarenessPush() {- return Constants.expoConfig?.extra?.iosPersonalTeamBuild !== true;-}diff --git a/apps/mobile/src/features/agent-awareness/liveActivityPreferences.test.ts b/apps/mobile/src/features/agent-awareness/liveActivityPreferences.test.tsdeleted file mode 100644index 0ee3e59b9..000000000--- a/apps/mobile/src/features/agent-awareness/liveActivityPreferences.test.ts+++ /dev/null@@ -1,187 +0,0 @@-import { beforeEach, vi } from "vite-plus/test";-import { describe, expect, it } from "@effect/vitest";-import * as Effect from "effect/Effect";-import type { EnvironmentId } from "@t3tools/contracts";-import { ManagedRelay } from "@t3tools/client-runtime/relay";-import * as Layer from "effect/Layer";-import { HttpClient } from "effect/unstable/http";--import type { SavedRemoteConnection } from "../../lib/connection";-import { MobileStorage } from "../../persistence/mobile-storage";-import {- CloudEnvironmentLinkError,- linkEnvironmentToCloudWithPreference,-} from "../cloud/linkEnvironment";-import { setLiveActivityUpdatesEnabled } from "./liveActivityPreferences";-import { updateAgentAwarenessRegistrationPreferences } from "./remoteRegistration";--vi.mock("expo-secure-store", () => ({- deleteItemAsync: vi.fn(),- getItemAsync: vi.fn(),- setItemAsync: vi.fn(),-}));--vi.mock("react-native", () => ({- Platform: { OS: "ios" },-}));--vi.mock("../cloud/linkEnvironment", () => ({- linkEnvironmentToCloudWithPreference: vi.fn(() => Effect.void),-}));--vi.mock("./remoteRegistration", () => ({- updateAgentAwarenessRegistrationPreferences: vi.fn(() => Effect.void),-}));--const connection: SavedRemoteConnection = {- environmentId: "env-1" as EnvironmentId,- environmentLabel: "Desktop",- pairingUrl: "https://desktop.example.test/",- displayUrl: "https://desktop.example.test/",- httpBaseUrl: "https://desktop.example.test/",- wsBaseUrl: "wss://desktop.example.test/ws",- bearerToken: "local-bearer",-};--const testLayer = Layer.mergeAll(- Layer.succeed(ManagedRelay.ManagedRelayClient, null as never),- Layer.succeed(- HttpClient.HttpClient,- HttpClient.make(() => Effect.die("unexpected HTTP request")),- ),- Layer.succeed(- MobileStorage,- MobileStorage.of({- loadSavedConnections: Effect.succeed([]),- saveConnection: () => Effect.void,- clearSavedConnection: () => Effect.void,- loadOrCreateAgentAwarenessDeviceId: Effect.succeed("device-1"),- loadAgentAwarenessDeviceId: Effect.succeed("device-1"),- loadAgentAwarenessRegistrationRecord: Effect.succeed(null),- saveAgentAwarenessRegistrationRecord: () => Effect.void,- clearAgentAwarenessRegistrationRecord: Effect.void,- loadRecentThreadShortcuts: Effect.succeed([]),- saveRecentThreadShortcuts: () => Effect.void,- }),- ),-);--describe("liveActivityPreferences", () => {- beforeEach(() => {- vi.clearAllMocks();- });-- it.effect("pushes disabled Live Activity preferences to relay registrations", () =>- Effect.gen(function* () {- yield* setLiveActivityUpdatesEnabled({- enabled: false,- previousEnabled: true,- clerkToken: "clerk-token",- connections: [connection],- });-- expect(updateAgentAwarenessRegistrationPreferences).toHaveBeenCalledWith({- liveActivitiesEnabled: false,- });- expect(linkEnvironmentToCloudWithPreference).toHaveBeenCalledWith({- clerkToken: "clerk-token",- connection,- liveActivitiesEnabled: false,- });- }).pipe(Effect.provide(testLayer)),- );-- it.effect("pushes enabled Live Activity preferences to relay registrations", () =>- Effect.gen(function* () {- yield* setLiveActivityUpdatesEnabled({- enabled: true,- previousEnabled: false,- clerkToken: "clerk-token",- connections: [connection],- });-- expect(updateAgentAwarenessRegistrationPreferences).toHaveBeenCalledWith({- liveActivitiesEnabled: true,- });- expect(linkEnvironmentToCloudWithPreference).toHaveBeenCalledWith({- clerkToken: "clerk-token",- connection,- liveActivitiesEnabled: true,- });- }).pipe(Effect.provide(testLayer)),- );-- it.effect("keeps local preferences refreshable when signed out", () =>- Effect.gen(function* () {- yield* setLiveActivityUpdatesEnabled({- enabled: false,- previousEnabled: true,- clerkToken: null,- connections: [connection],- });-- expect(updateAgentAwarenessRegistrationPreferences).toHaveBeenCalledWith({- liveActivitiesEnabled: false,- });- expect(linkEnvironmentToCloudWithPreference).not.toHaveBeenCalled();- }).pipe(Effect.provide(testLayer)),- );-- it.effect("does not try to re-link managed relay connections without bearer credentials", () => {- const managedConnection: SavedRemoteConnection = {- ...connection,- bearerToken: null,- };-- return Effect.gen(function* () {- yield* setLiveActivityUpdatesEnabled({- enabled: true,- previousEnabled: false,- clerkToken: "clerk-token",- connections: [connection, managedConnection],- });-- expect(linkEnvironmentToCloudWithPreference).toHaveBeenCalledTimes(1);- expect(linkEnvironmentToCloudWithPreference).toHaveBeenCalledWith({- clerkToken: "clerk-token",- connection,- liveActivitiesEnabled: true,- });- }).pipe(Effect.provide(testLayer));- });-- it.effect("restores relay preferences when an environment update fails", () => {- vi.mocked(linkEnvironmentToCloudWithPreference).mockImplementationOnce(() =>- Effect.fail(new CloudEnvironmentLinkError({ message: "environment update failed" })),- );-- return Effect.gen(function* () {- const exit = yield* Effect.exit(- setLiveActivityUpdatesEnabled({- enabled: false,- previousEnabled: true,- clerkToken: "clerk-token",- connections: [connection],- }),- );-- expect(exit._tag).toBe("Failure");- expect(updateAgentAwarenessRegistrationPreferences).toHaveBeenNthCalledWith(1, {- liveActivitiesEnabled: false,- });- expect(updateAgentAwarenessRegistrationPreferences).toHaveBeenNthCalledWith(2, {- liveActivitiesEnabled: true,- });- expect(linkEnvironmentToCloudWithPreference).toHaveBeenNthCalledWith(1, {- clerkToken: "clerk-token",- connection,- liveActivitiesEnabled: false,- });- expect(linkEnvironmentToCloudWithPreference).toHaveBeenNthCalledWith(2, {- clerkToken: "clerk-token",- connection,- liveActivitiesEnabled: true,- });- }).pipe(Effect.provide(testLayer));- });-});diff --git a/apps/mobile/src/features/agent-awareness/liveActivityPreferences.ts b/apps/mobile/src/features/agent-awareness/liveActivityPreferences.tsdeleted file mode 100644index 1b30769e7..000000000--- a/apps/mobile/src/features/agent-awareness/liveActivityPreferences.ts+++ /dev/null@@ -1,73 +0,0 @@-import * as Effect from "effect/Effect";--import type { SavedRemoteConnection } from "../../lib/connection";-import { linkEnvironmentToCloudWithPreference } from "../cloud/linkEnvironment";-import { updateAgentAwarenessRegistrationPreferences } from "./remoteRegistration";--export const setLiveActivityUpdatesEnabled = Effect.fn("setLiveActivityUpdatesEnabled")(- function* (input: {- readonly enabled: boolean;- readonly previousEnabled: boolean;- readonly clerkToken: string | null;- readonly connections: ReadonlyArray<SavedRemoteConnection>;- }) {- const linkedConnections = input.connections.filter(- (connection) => connection.bearerToken !== null,- );-- const updateRelayPreference = Effect.fn("updateRelayPreference")(function* (enabled: boolean) {- yield* updateAgentAwarenessRegistrationPreferences({- liveActivitiesEnabled: enabled,- });-- const clerkToken = input.clerkToken;- if (!clerkToken) return;-- yield* Effect.forEach(- linkedConnections,- (connection) =>- linkEnvironmentToCloudWithPreference({- clerkToken,- connection,- liveActivitiesEnabled: enabled,- }),- { concurrency: "unbounded" },- );- });-- const restoreRelayPreference = Effect.fn("restoreRelayPreference")(function* () {- yield* updateAgentAwarenessRegistrationPreferences({- liveActivitiesEnabled: input.previousEnabled,- }).pipe(- Effect.catchCause((cause) =>- Effect.logWarning("Could not restore Live Activity device preference.", cause),- ),- );-- const clerkToken = input.clerkToken;- if (!clerkToken) return;-- yield* Effect.forEach(- linkedConnections,- (connection) =>- linkEnvironmentToCloudWithPreference({- clerkToken,- connection,- liveActivitiesEnabled: input.previousEnabled,- }).pipe(- Effect.catchCause((cause) =>- Effect.logWarning(- `Could not restore Live Activity preference for environment ${connection.environmentId}.`,- cause,- ),- ),- ),- { concurrency: "unbounded" },- );- });-- yield* updateRelayPreference(input.enabled).pipe(- Effect.onError(() => restoreRelayPreference()),- );- },-);diff --git a/apps/mobile/src/features/agent-awareness/registrationPayload.ts b/apps/mobile/src/features/agent-awareness/registrationPayload.tsdeleted file mode 100644index 8279a27fe..000000000--- a/apps/mobile/src/features/agent-awareness/registrationPayload.ts+++ /dev/null@@ -1,46 +0,0 @@-import type { RelayDeviceRegistrationRequest } from "@t3tools/contracts/relay";--import type { Preferences } from "../../persistence/mobile-preferences";-import { supportsAgentAwarenessPush } from "./capabilities";--// Development builds are Xcode-signed and receive sandbox APNs tokens;-// preview and production builds are distribution-signed and use production-// APNs. The relay routes each device's pushes accordingly.-export function resolveApsEnvironment(appVariant: unknown): "sandbox" | "production" {- return appVariant === "development" ? "sandbox" : "production";-}--export function makeRelayDeviceRegistrationRequest(input: {- readonly deviceId: string;- readonly label: string;- readonly iosMajorVersion: number;- readonly appVersion?: string;- readonly bundleId?: string;- readonly apsEnvironment?: "sandbox" | "production";- readonly pushToken?: string;- readonly pushToStartToken?: string;- readonly notificationsEnabled: boolean;- readonly preferences: Preferences;-}): RelayDeviceRegistrationRequest {- const pushAvailable = supportsAgentAwarenessPush();- const liveActivitiesEnabled = pushAvailable && input.preferences.liveActivitiesEnabled !== false;- return {- deviceId: input.deviceId,- label: input.label,- platform: "ios",- iosMajorVersion: input.iosMajorVersion,- appVersion: input.appVersion,- ...(input.bundleId ? { bundleId: input.bundleId } : {}),- ...(input.apsEnvironment ? { apsEnvironment: input.apsEnvironment } : {}),- ...(input.pushToken ? { pushToken: input.pushToken } : {}),- ...(input.pushToStartToken ? { pushToStartToken: input.pushToStartToken } : {}),- preferences: {- liveActivitiesEnabled,- notificationsEnabled: pushAvailable && input.notificationsEnabled,- notifyOnApproval: true,- notifyOnInput: true,- notifyOnCompletion: true,- notifyOnFailure: true,- },- };-}diff --git a/apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts b/apps/mobile/src/features/agent-awareness/remoteRegistration.test.tsdeleted file mode 100644index 582c58fb2..000000000--- a/apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts+++ /dev/null@@ -1,935 +0,0 @@-/// <reference types="node" />--import * as NodeCrypto from "node:crypto";--import { beforeEach, vi } from "vite-plus/test";-import { describe, expect, it } from "@effect/vitest";-import Constants from "expo-constants";-import * as Effect from "effect/Effect";-import * as Exit from "effect/Exit";-import * as Layer from "effect/Layer";-import { FetchHttpClient } from "effect/unstable/http";-import { ManagedRelay } from "@t3tools/client-runtime/relay";--import type { EnvironmentId } from "@t3tools/contracts";-import { verifyDpopProof } from "@t3tools/shared/dpop";-import type { SavedRemoteConnection } from "../../lib/connection";-import { cryptoLayer } from "../cloud/dpop";-import { managedRelayClientLayer } from "../cloud/managedRelayLayer";-import {- clearAgentAwarenessRegistrationRecord,- loadAgentAwarenessRegistrationRecord,- loadOrCreateAgentAwarenessDeviceId,- loadPreferences,- saveAgentAwarenessRegistrationRecord,-} from "../../persistence/imperative";-import type { Preferences } from "../../persistence/mobile-preferences";-import { makeRelayDeviceRegistrationRequest, resolveApsEnvironment } from "./registrationPayload";-import {- AgentAwarenessOperationError,- __resetAgentAwarenessRemoteRegistrationForTest,- armAgentAwarenessLiveActivityForLocalWork,- getAgentAwarenessRegistrationStatus,- mergeAgentAwarenessRegistrationPreferences,- refreshActiveLiveActivityRemoteRegistration,- refreshAgentAwarenessRegistration,- normalizeAgentAwarenessRelayBaseUrl,- registerAgentAwarenessConnection,- registerLiveActivityPushToken,- releaseAgentAwarenessRelayTokenProvider,- setAgentAwarenessRelayTokenProvider,- shouldRegisterAgentAwarenessDeviceForProvider,- unregisterAgentAwarenessConnection,-} from "./remoteRegistration";-import * as Notifications from "expo-notifications";--const secureStore = vi.hoisted(() => new Map<string, string>());-const widgetMocks = vi.hoisted(() => ({- getInstances: vi.fn(() => []),- start: vi.fn(() => ({})),-}));-const environmentConfigsMock = vi.hoisted(() => ({- configs: new Map<- string,- { environment: { capabilities: { agentActivityPublishing?: boolean } } }- >(),-}));-const backgroundRuntime = vi.hoisted(() => ({- pending: [] as Array<{- readonly operation: unknown;- readonly resolve: (exit: Exit.Exit<unknown, unknown>) => void;- }>,-}));-const appStateMock = vi.hoisted(() => ({- listeners: [] as Array<(state: string) => void>,-}));-const registrationRecordStore = vi.hoisted(() => ({- current: null as {- readonly identity: string;- readonly signature: string;- readonly pushToStartToken?: string;- } | null,-}));--vi.mock("expo-constants", () => ({- default: {- expoConfig: {- version: "1.0.0",- extra: {},- },- },-}));--vi.mock("expo-widgets", () => ({- addPushToStartTokenListener: vi.fn(() => ({ remove: vi.fn() })),-}));--vi.mock("../../widgets/AgentActivity", () => ({- default: {- getInstances: widgetMocks.getInstances,- start: widgetMocks.start,- },-}));--// The state modules pull the whole connection stack (and native expo modules)-// into the import graph; the arming gate only needs the configs map.-vi.mock("../../state/atom-registry", () => ({- appAtomRegistry: {- get: () => environmentConfigsMock.configs,- },-}));--vi.mock("../../state/server", () => ({- environmentServerConfigsAtom: Symbol("environmentServerConfigsAtom"),-}));--vi.mock("expo-notifications", () => ({- addPushTokenListener: vi.fn(() => ({ remove: vi.fn() })),- getDevicePushTokenAsync: vi.fn(() => Promise.resolve({ type: "ios", data: "apns-token" })),- getPermissionsAsync: vi.fn(() => Promise.resolve({ granted: true })),-}));--vi.mock("expo-crypto", () => ({- CryptoDigestAlgorithm: {- SHA1: "SHA-1",- SHA256: "SHA-256",- SHA384: "SHA-384",- SHA512: "SHA-512",- },- getRandomBytes: (byteCount: number) => new Uint8Array(NodeCrypto.randomBytes(byteCount)),- getRandomBytesAsync: (byteCount: number) =>- Promise.resolve(new Uint8Array(NodeCrypto.randomBytes(byteCount))),- digest: (algorithm: string, data: unknown) => {- if (!(data instanceof Uint8Array)) {- return Promise.reject(new TypeError("expo-crypto digest data must be a typed array."));- }- return Promise.resolve(- new Uint8Array(NodeCrypto.createHash(algorithm).update(data).digest()).buffer,- );- },-}));--vi.mock("expo-secure-store", () => ({- getItemAsync: (key: string) => Promise.resolve(secureStore.get(key) ?? null),- setItemAsync: (key: string, value: string) => {- secureStore.set(key, value);- return Promise.resolve();- },-}));--vi.mock("react-native", () => ({- Platform: {- OS: "ios",- Version: "18.0",- },- AppState: {- addEventListener: (_event: string, listener: (state: string) => void) => {- appStateMock.listeners.push(listener);- return {- remove: () => {- const index = appStateMock.listeners.indexOf(listener);- if (index >= 0) {- appStateMock.listeners.splice(index, 1);- }- },- };- },- },-}));--vi.mock("../../lib/runtime", () => ({- runtime: {- runPromiseExit: (operation: unknown) =>- new Promise((resolve) => {- backgroundRuntime.pending.push({ operation, resolve });- }),- },-}));--vi.mock("../../persistence/imperative", () => ({- loadAgentAwarenessDeviceId: vi.fn(() => Promise.resolve("device-1")),- loadOrCreateAgentAwarenessDeviceId: vi.fn(() => Promise.resolve("device-1")),- loadPreferences: vi.fn(() => Promise.resolve({ liveActivitiesEnabled: false })),- loadAgentAwarenessRegistrationRecord: vi.fn(() =>- Promise.resolve(registrationRecordStore.current),- ),- saveAgentAwarenessRegistrationRecord: vi.fn((record: { identity: string; signature: string }) => {- registrationRecordStore.current = record;- return Promise.resolve();- }),- clearAgentAwarenessRegistrationRecord: vi.fn(() => {- registrationRecordStore.current = null;- return Promise.resolve();- }),-}));--function proofIat(proof: string): number {- const payload = proof.split(".")[1];- if (!payload) {- throw new Error("Missing DPoP payload.");- }- const decoded = JSON.parse(Buffer.from(payload, "base64url").toString("utf8")) as {- readonly iat: number;- };- return decoded.iat;-}--function savedConnection(): SavedRemoteConnection {- return {- environmentId: "env-1" as EnvironmentId,- environmentLabel: "Desktop",- pairingUrl: "https://desktop.example/pair",- displayUrl: "https://desktop.example",- httpBaseUrl: "https://desktop.example",- wsBaseUrl: "wss://desktop.example/ws",- bearerToken: "bearer-token",- };-}--const relayTestLayer = managedRelayClientLayer("https://relay.example.test").pipe(- Layer.provide(Layer.mergeAll(FetchHttpClient.layer, cryptoLayer)),-);--const runBackgroundOperations = Effect.fn("TestRemoteRegistration.runBackgroundOperations")(- function* () {- let idlePasses = 0;- for (;;) {- yield* Effect.promise(() => Promise.resolve());- const pending = backgroundRuntime.pending.shift();- if (!pending) {- idlePasses++;- if (idlePasses >= 3) {- return;- }- continue;- }- idlePasses = 0;- const exit = yield* Effect.exit(- pending.operation as Effect.Effect<unknown, unknown, ManagedRelay.ManagedRelayClient>,- );- yield* Effect.sync(() => {- pending.resolve(exit);- });- }- },-);--describe("makeRelayDeviceRegistrationRequest", () => {- beforeEach(() => {- vi.unstubAllGlobals();- vi.stubGlobal("__DEV__", false);- secureStore.clear();- backgroundRuntime.pending.length = 0;- Constants.expoConfig!.extra = {};- __resetAgentAwarenessRemoteRegistrationForTest();- appStateMock.listeners.length = 0;- registrationRecordStore.current = null;- vi.mocked(saveAgentAwarenessRegistrationRecord).mockClear();- vi.mocked(loadAgentAwarenessRegistrationRecord).mockClear();- vi.mocked(clearAgentAwarenessRegistrationRecord).mockClear();- vi.mocked(loadOrCreateAgentAwarenessDeviceId).mockResolvedValue("device-1");- widgetMocks.getInstances.mockReset();- widgetMocks.getInstances.mockReturnValue([]);- widgetMocks.start.mockClear();- environmentConfigsMock.configs.clear();- });-- it("preserves disabled Live Activity preferences in relay registrations", () => {- expect(- makeRelayDeviceRegistrationRequest({- deviceId: "device-1",- label: "Julius's iPhone",- iosMajorVersion: 18,- appVersion: "1.0.0",- pushToken: "apns-token",- pushToStartToken: "push-to-start-token",- notificationsEnabled: true,- preferences: {- liveActivitiesEnabled: false,- },- }),- ).toEqual({- deviceId: "device-1",- label: "Julius's iPhone",- platform: "ios",- iosMajorVersion: 18,- appVersion: "1.0.0",- pushToken: "apns-token",- pushToStartToken: "push-to-start-token",- preferences: {- liveActivitiesEnabled: false,- notificationsEnabled: true,- notifyOnApproval: true,- notifyOnInput: true,- notifyOnCompletion: true,- notifyOnFailure: true,- },- });- });-- it("registers the app's APNs routing so the relay targets the right bundle", () => {- expect(- makeRelayDeviceRegistrationRequest({- deviceId: "device-1",- label: "Julius's iPhone",- iosMajorVersion: 18,- appVersion: "1.0.0",- bundleId: "com.t3tools.t3code.preview",- apsEnvironment: resolveApsEnvironment("preview"),- notificationsEnabled: true,- preferences: {},- }),- ).toMatchObject({- bundleId: "com.t3tools.t3code.preview",- apsEnvironment: "production",- });- });-- it("routes development builds to the APNs sandbox", () => {- expect(resolveApsEnvironment("development")).toBe("sandbox");- expect(resolveApsEnvironment("preview")).toBe("production");- expect(resolveApsEnvironment("production")).toBe("production");- expect(resolveApsEnvironment(undefined)).toBe("production");- });-- it("disables push features in Personal Team relay registrations", () => {- Constants.expoConfig!.extra = { iosPersonalTeamBuild: true };-- expect(- makeRelayDeviceRegistrationRequest({- deviceId: "device-1",- label: "Julius's iPhone",- iosMajorVersion: 18,- appVersion: "1.0.0",- pushToken: "apns-token",- pushToStartToken: "push-to-start-token",- notificationsEnabled: true,- preferences: {},- }).preferences,- ).toMatchObject({- liveActivitiesEnabled: false,- notificationsEnabled: false,- });- });-- it("marks notification delivery disabled when APNs permission is unavailable", () => {- expect(- makeRelayDeviceRegistrationRequest({- deviceId: "device-1",- label: "Julius's iPhone",- iosMajorVersion: 18,- appVersion: "1.0.0",- pushToStartToken: "push-to-start-token",- notificationsEnabled: false,- preferences: {- liveActivitiesEnabled: true,- },- }),- ).toEqual({- deviceId: "device-1",- label: "Julius's iPhone",- platform: "ios",- iosMajorVersion: 18,- appVersion: "1.0.0",- pushToStartToken: "push-to-start-token",- preferences: {- liveActivitiesEnabled: true,- notificationsEnabled: false,- notifyOnApproval: true,- notifyOnInput: true,- notifyOnCompletion: true,- notifyOnFailure: true,- },- });- });-- it("normalizes relay base URLs for APNs registration requests", () => {- expect(normalizeAgentAwarenessRelayBaseUrl(" https://relay.example.test/// ")).toBe(- "https://relay.example.test",- );- expect(normalizeAgentAwarenessRelayBaseUrl(" ")).toBeNull();- });-- it("overrides persisted preferences for an in-flight registration", () => {- expect(- mergeAgentAwarenessRegistrationPreferences(- { liveActivitiesEnabled: false, baseFontSize: 18 },- { liveActivitiesEnabled: true },- ),- ).toEqual({ liveActivitiesEnabled: true, baseFontSize: 18 });- });-- it.effect("registers at most one listener while a Live Activity push token is pending", () => {- registerAgentAwarenessConnection(savedConnection());- const addPushTokenListener = vi.fn();- const activity = {- getPushToken: vi.fn(() => Promise.resolve(null)),- addPushTokenListener,- };-- return Effect.gen(function* () {- expect(yield* registerLiveActivityPushToken({ activity: activity as never })).toBe(false);- expect(yield* registerLiveActivityPushToken({ activity: activity as never })).toBe(false);-- expect(activity.getPushToken).toHaveBeenCalledTimes(2);- expect(addPushTokenListener).toHaveBeenCalledTimes(1);- }).pipe(Effect.provide(relayTestLayer));- });-- it.effect("preserves Live Activity push-token lookup failures", () => {- const cause = new Error("native token lookup failed");- const activity = {- getPushToken: vi.fn(() => Promise.reject(cause)),- addPushTokenListener: vi.fn(),- };-- return Effect.gen(function* () {- const error = yield* Effect.flip(- registerLiveActivityPushToken({ activity: activity as never }),- );-- expect(error).toBeInstanceOf(AgentAwarenessOperationError);- expect(error).toMatchObject({- _tag: "AgentAwarenessOperationError",- operation: "read-live-activity-push-token",- cause,- message: "Agent awareness operation read-live-activity-push-token failed.",- });- }).pipe(Effect.provide(relayTestLayer));- });-- it.effect(- "reports Live Activity token registration as skipped when relay auth is unavailable",- () => {- registerAgentAwarenessConnection(savedConnection());- const activity = {- getPushToken: vi.fn(() => Promise.resolve("activity-token")),- addPushTokenListener: vi.fn(),- };-- return Effect.gen(function* () {- expect(yield* registerLiveActivityPushToken({ activity: activity as never })).toBe(false);- }).pipe(Effect.provide(relayTestLayer));- },- );-- it.effect(- "registers APNS-started Live Activities for relay updates without mutating them locally",- () => {- const activity = {- getPushToken: vi.fn(() => Promise.resolve("activity-token")),- addPushTokenListener: vi.fn(),- start: vi.fn(),- update: vi.fn(),- end: vi.fn(),- };- widgetMocks.getInstances.mockReturnValue([activity] as never);- setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));-- return Effect.gen(function* () {- yield* refreshActiveLiveActivityRemoteRegistration();-- expect(activity.getPushToken).toHaveBeenCalled();- expect(activity.start).not.toHaveBeenCalled();- expect(activity.update).not.toHaveBeenCalled();- expect(activity.end).not.toHaveBeenCalled();- }).pipe(Effect.provide(relayTestLayer));- },- );-- it.effect(- "re-registers active Live Activity tokens when the app returns to the foreground",- () => {- const activity = {- getPushToken: vi.fn(() => Promise.resolve("activity-token")),- addPushTokenListener: vi.fn(),- };- widgetMocks.getInstances.mockReturnValue([activity] as never);- setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));-- return Effect.gen(function* () {- yield* runBackgroundOperations();- activity.getPushToken.mockClear();-- expect(appStateMock.listeners).toHaveLength(1);- for (const listener of appStateMock.listeners) {- listener("background");- }- yield* runBackgroundOperations();- expect(activity.getPushToken).not.toHaveBeenCalled();-- for (const listener of appStateMock.listeners) {- listener("active");- }- yield* runBackgroundOperations();- expect(activity.getPushToken).toHaveBeenCalled();- }).pipe(Effect.provide(relayTestLayer));- },- );-- it("ends local Live Activities and stops foreground reconciliation on cloud sign-out", () => {- const end = vi.fn(() => Promise.resolve());- const activity = {- getPushToken: vi.fn(() => Promise.resolve("activity-token")),- addPushTokenListener: vi.fn(),- end,- };- widgetMocks.getInstances.mockReturnValue([activity] as never);- setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));- expect(appStateMock.listeners).toHaveLength(1);-- setAgentAwarenessRelayTokenProvider(null);-- expect(end).toHaveBeenCalledWith("immediate");- expect(appStateMock.listeners).toHaveLength(0);- });-- it.effect("refreshes APNs registration for connected environments after settings changes", () => {- registerAgentAwarenessConnection(savedConnection());- return Effect.gen(function* () {- yield* runBackgroundOperations();- vi.mocked(Notifications.getDevicePushTokenAsync).mockClear();-- yield* refreshAgentAwarenessRegistration();-- expect(Notifications.getDevicePushTokenAsync).toHaveBeenCalledTimes(1);- }).pipe(Effect.provide(relayTestLayer));- });-- it.effect("registers the APNs device when cloud auth becomes available", () => {- const fetchMock = vi.fn((request: RequestInfo | URL) => {- const url = request instanceof Request ? request.url : String(request);- return Promise.resolve(- Response.json(- url.endsWith("/v1/client/dpop-token")- ? {- access_token: "relay-dpop-token",- issued_token_type: "urn:ietf:params:oauth:token-type:access_token",- token_type: "DPoP",- expires_in: 300,- scope: "mobile:registration",- }- : { ok: true },- ),- );- });- vi.stubGlobal("fetch", fetchMock);- Constants.expoConfig!.extra = {- relay: {- url: "https://relay.example.test/",- },- };-- setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));-- return Effect.gen(function* () {- yield* runBackgroundOperations();-- expect(fetchMock).toHaveBeenCalledTimes(2);- const [request, init] = fetchMock.mock.calls[1] as unknown as [- unknown,- RequestInit | undefined,- ];- const url = request instanceof Request ? request.url : String(request);- const method = request instanceof Request ? request.method : init?.method;- const headers = request instanceof Request ? request.headers : new Headers(init?.headers);- const dpop = headers.get("dpop");- expect(url).toBe("https://relay.example.test/v1/mobile/devices");- expect(method).toBe("POST");- expect(headers.get("authorization")).toBe("DPoP relay-dpop-token");- expect(dpop).toEqual(expect.any(String));- if (!dpop) {- throw new Error("Missing DPoP header.");- }- expect(- verifyDpopProof({- proof: dpop,- method: "POST",- url: "https://relay.example.test/v1/mobile/devices",- expectedAccessToken: "relay-dpop-token",- nowEpochSeconds: proofIat(dpop),- }),- ).toMatchObject({ ok: true });- expect(getAgentAwarenessRegistrationStatus()).toBe("registered");- }).pipe(Effect.provide(relayTestLayer));- });-- it.effect("marks registration failed when device registration cannot complete", () => {- Constants.expoConfig!.extra = {- relay: {- url: "https://relay.example.test/",- },- };- vi.mocked(loadOrCreateAgentAwarenessDeviceId).mockRejectedValueOnce(- new Error("registration failed"),- );- setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));-- return Effect.gen(function* () {- // Drive the registration directly so the assertion does not depend on the- // background queue draining; refreshAgentAwarenessRegistration swallows the- // error but must record the failed status so the settings toggles cannot- // read as enabled.- yield* refreshAgentAwarenessRegistration();- expect(getAgentAwarenessRegistrationStatus()).toBe("failed");- }).pipe(Effect.provide(relayTestLayer));- });-- it("clears registration status on cloud sign-out", () => {- setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));- setAgentAwarenessRelayTokenProvider(null);- expect(getAgentAwarenessRegistrationStatus()).toBe("unknown");- expect(clearAgentAwarenessRegistrationRecord).toHaveBeenCalled();- });-- it("releases the provider without ending activities or clearing the registration", () => {- const end = vi.fn(() => Promise.resolve());- const activity = {- getPushToken: vi.fn(() => Promise.resolve("activity-token")),- addPushTokenListener: vi.fn(),- end,- };- widgetMocks.getInstances.mockReturnValue([activity] as never);- registrationRecordStore.current = { identity: "", signature: "sig" };- setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));- expect(appStateMock.listeners).toHaveLength(1);-- releaseAgentAwarenessRelayTokenProvider();-- expect(appStateMock.listeners).toHaveLength(0);- expect(end).not.toHaveBeenCalled();- expect(clearAgentAwarenessRegistrationRecord).not.toHaveBeenCalled();- expect(registrationRecordStore.current).not.toBeNull();- });-- it.effect("resets a pending status to unknown when relay config is missing", () => {- // No relay url configured: registration can neither run nor ever succeed,- // so the status must not stick at "pending".- setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));-- return Effect.gen(function* () {- yield* runBackgroundOperations();- expect(getAgentAwarenessRegistrationStatus()).toBe("unknown");- }).pipe(Effect.provide(relayTestLayer));- });-- it.effect("keeps a registered status when a later refresh fails", () => {- Constants.expoConfig!.extra = {- relay: {- url: "https://relay.example.test/",- },- };- setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));-- return Effect.gen(function* () {- yield* runBackgroundOperations();- expect(getAgentAwarenessRegistrationStatus()).toBe("registered");-- // The relay still holds the accepted registration; a transient refresh- // failure must not flip the settings toggles off.- vi.mocked(loadOrCreateAgentAwarenessDeviceId).mockRejectedValueOnce(- new Error("transient failure"),- );- yield* refreshAgentAwarenessRegistration();- expect(getAgentAwarenessRegistrationStatus()).toBe("registered");- }).pipe(Effect.provide(relayTestLayer));- });-- it.effect("does not re-register the same account when nothing has changed", () => {- Constants.expoConfig!.extra = {- relay: {- url: "https://relay.example.test/",- },- };- setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));-- return Effect.gen(function* () {- yield* refreshAgentAwarenessRegistration();- expect(getAgentAwarenessRegistrationStatus()).toBe("registered");- expect(saveAgentAwarenessRegistrationRecord).toHaveBeenCalledTimes(1);- expect(registrationRecordStore.current).not.toBeNull();-- // Second attempt with an identical payload must skip the relay entirely,- // so no new registration record is written.- vi.mocked(saveAgentAwarenessRegistrationRecord).mockClear();- yield* refreshAgentAwarenessRegistration();- expect(getAgentAwarenessRegistrationStatus()).toBe("registered");- expect(saveAgentAwarenessRegistrationRecord).not.toHaveBeenCalled();- }).pipe(Effect.provide(relayTestLayer));- });-- it.effect("dedupes rapid activity-token re-registrations within the replay window", () => {- // Fetch counts are unreliable here (the module-level relay layer captures- // the first test's fetch), so assert on the flow's own seams: a real- // registration attempt loads the device id, a deduped one short-circuits- // before it.- const fetchMock = vi.fn((request: RequestInfo | URL) => {- const url = request instanceof Request ? request.url : String(request);- return Promise.resolve(- Response.json(- url.endsWith("/v1/client/dpop-token")- ? {- access_token: "relay-dpop-token",- issued_token_type: "urn:ietf:params:oauth:token-type:access_token",- token_type: "DPoP",- expires_in: 300,- scope: "mobile:registration",- }- : { ok: true },- ),- );- });- vi.stubGlobal("fetch", fetchMock);- Constants.expoConfig!.extra = {- relay: {- url: "https://relay.example.test/",- },- };- const activity = {- getPushToken: vi.fn(() => Promise.resolve("activity-token")),- addPushTokenListener: vi.fn(),- };- widgetMocks.getInstances.mockReturnValue([activity] as never);- setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));-- return Effect.gen(function* () {- // Drains the sign-in refresh, which registers the activity token.- yield* runBackgroundOperations();- expect(activity.getPushToken).toHaveBeenCalled();-- // A burst refresh (foreground / connection update seconds later) must- // dedupe: it reads the token but never proceeds to a registration- // attempt (which would load the device id first).- vi.mocked(loadOrCreateAgentAwarenessDeviceId).mockClear();- yield* refreshActiveLiveActivityRemoteRegistration();- expect(loadOrCreateAgentAwarenessDeviceId).not.toHaveBeenCalled();- }).pipe(Effect.provide(relayTestLayer));- });-- it.effect("re-registers when the stored account identity differs", () => {- Constants.expoConfig!.extra = {- relay: {- url: "https://relay.example.test/",- },- };- registrationRecordStore.current = { identity: "someone-else", signature: "stale" };- setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));-- return Effect.gen(function* () {- yield* refreshAgentAwarenessRegistration();- expect(saveAgentAwarenessRegistrationRecord).toHaveBeenCalledTimes(1);- }).pipe(Effect.provide(relayTestLayer));- });-- it.effect("coalesces simultaneous sign-in and environment connection registrations", () => {- const fetchMock = vi.fn((request: RequestInfo | URL) => {- const url = request instanceof Request ? request.url : String(request);- return Promise.resolve(- Response.json(- url.endsWith("/v1/client/dpop-token")- ? {- access_token: "relay-dpop-token",- issued_token_type: "urn:ietf:params:oauth:token-type:access_token",- token_type: "DPoP",- expires_in: 300,- scope: "mobile:registration",- }- : { ok: true },- ),- );- });- vi.stubGlobal("fetch", fetchMock);- Constants.expoConfig!.extra = {- relay: {- url: "https://relay.example.test/",- },- };-- vi.mocked(Notifications.getPermissionsAsync).mockClear();- setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));- registerAgentAwarenessConnection(savedConnection());-- return Effect.gen(function* () {- yield* runBackgroundOperations();- expect(Notifications.getPermissionsAsync).toHaveBeenCalledTimes(1);- }).pipe(Effect.provide(relayTestLayer));- });-- it.effect("continues queued device registration after a failed auth lookup", () => {- Constants.expoConfig!.extra = {- relay: {- url: "https://relay.example.test/",- },- };-- const tokenProvider = vi- .fn<() => Promise<string | null>>()- .mockRejectedValueOnce(new Error("auth unavailable"))- .mockResolvedValue("clerk-token-user-a");- setAgentAwarenessRelayTokenProvider(tokenProvider);- const tokenListener = vi.mocked(Notifications.addPushTokenListener).mock.calls.at(-1)?.[0];- expect(tokenListener).toBeDefined();- tokenListener?.({ type: "ios", data: "rotated-apns-token" } as never);-- return Effect.gen(function* () {- yield* runBackgroundOperations();-- expect(backgroundRuntime.pending).toHaveLength(0);- expect(tokenProvider).toHaveBeenCalledTimes(2);- }).pipe(Effect.provide(relayTestLayer));- });-- it("only registers again when the authenticated identity changes", () => {- expect(shouldRegisterAgentAwarenessDeviceForProvider(null, "user-a")).toBe(true);- expect(shouldRegisterAgentAwarenessDeviceForProvider("user-a", "user-a")).toBe(false);- expect(shouldRegisterAgentAwarenessDeviceForProvider("user-a", "user-b")).toBe(true);- expect(shouldRegisterAgentAwarenessDeviceForProvider("user-a", undefined)).toBe(true);- });-- it.effect("registers rotated APNs tokens without rereading the native token", () => {- const fetchMock = vi.fn((request: RequestInfo | URL) => {- const url = request instanceof Request ? request.url : String(request);- return Promise.resolve(- Response.json(- url.endsWith("/v1/client/dpop-token")- ? {- access_token: "relay-dpop-token",- issued_token_type: "urn:ietf:params:oauth:token-type:access_token",- token_type: "DPoP",- expires_in: 300,- scope: "mobile:registration",- }- : { ok: true },- ),- );- });- vi.stubGlobal("fetch", fetchMock);- Constants.expoConfig!.extra = {- relay: {- url: "https://relay.example.test/",- },- };-- vi.mocked(Notifications.getDevicePushTokenAsync).mockClear();- setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));-- const tokenListener = vi.mocked(Notifications.addPushTokenListener).mock.calls.at(-1)?.[0];- expect(tokenListener).toBeDefined();- tokenListener?.({ type: "ios", data: "rotated-apns-token" } as never);-- return Effect.gen(function* () {- yield* runBackgroundOperations();- expect(Notifications.getDevicePushTokenAsync).toHaveBeenCalledTimes(1);- }).pipe(Effect.provide(relayTestLayer));- });-- it.effect(- "keeps the user-scoped relay APNs device when an environment connection is removed",- () => {- const fetchMock = vi.fn((request: RequestInfo | URL) => {- const url = request instanceof Request ? request.url : String(request);- return Promise.resolve(- Response.json(- url.endsWith("/v1/client/dpop-token")- ? {- access_token: "relay-dpop-token",- issued_token_type: "urn:ietf:params:oauth:token-type:access_token",- token_type: "DPoP",- expires_in: 300,- scope: "mobile:registration",- }- : { ok: true },- ),- );- });- vi.stubGlobal("fetch", fetchMock);- Constants.expoConfig!.extra = {- relay: {- url: "https://relay.example.test/",- },- };-- registerAgentAwarenessConnection(savedConnection());- setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));- return Effect.gen(function* () {- yield* runBackgroundOperations();- fetchMock.mockClear();-- unregisterAgentAwarenessConnection(savedConnection().environmentId);-- expect(fetchMock).not.toHaveBeenCalled();- }).pipe(Effect.provide(relayTestLayer));- },- );-- it("skips the Live Activity seed when the environment reports publishing disabled", async () => {- setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));- vi.mocked(loadPreferences).mockResolvedValueOnce({- liveActivitiesEnabled: true,- } as Preferences);- environmentConfigsMock.configs.set("env-1", {- environment: { capabilities: { agentActivityPublishing: false } },- });-- armAgentAwarenessLiveActivityForLocalWork({- environmentId: "env-1" as EnvironmentId,- threadTitle: "Fix the flaky test",- projectTitle: "t3code",- });- await new Promise((resolve) => setTimeout(resolve, 0));-- expect(widgetMocks.start).not.toHaveBeenCalled();- });-- it("seeds the Live Activity for publishing and pre-capability environments", async () => {- setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));- environmentConfigsMock.configs.set("env-publishing", {- environment: { capabilities: { agentActivityPublishing: true } },- });-- vi.mocked(loadPreferences).mockResolvedValueOnce({- liveActivitiesEnabled: true,- } as Preferences);- armAgentAwarenessLiveActivityForLocalWork({- environmentId: "env-publishing" as EnvironmentId,- threadTitle: "Fix the flaky test",- projectTitle: "t3code",- });- await new Promise((resolve) => setTimeout(resolve, 0));- expect(widgetMocks.start).toHaveBeenCalledTimes(1);-- // An environment without the capability may run an older server that- // still publishes; only an explicit false skips the seed.- widgetMocks.start.mockClear();- vi.mocked(loadPreferences).mockResolvedValueOnce({- liveActivitiesEnabled: true,- } as Preferences);- armAgentAwarenessLiveActivityForLocalWork({- environmentId: "env-pre-capability" as EnvironmentId,- threadTitle: "Fix the flaky test",- projectTitle: "t3code",- });- await new Promise((resolve) => setTimeout(resolve, 0));- expect(widgetMocks.start).toHaveBeenCalledTimes(1);- });-});diff --git a/apps/mobile/src/features/agent-awareness/remoteRegistration.ts b/apps/mobile/src/features/agent-awareness/remoteRegistration.tsdeleted file mode 100644index b0f77d770..000000000--- a/apps/mobile/src/features/agent-awareness/remoteRegistration.ts+++ /dev/null@@ -1,1140 +0,0 @@-import { type LiveActivity } from "expo-widgets";-import Constants from "expo-constants";-import * as Notifications from "expo-notifications";-import * as Effect from "effect/Effect";-import * as Schema from "effect/Schema";-import { AppState, Platform } from "react-native";-import type { EnvironmentId } from "@t3tools/contracts";-import {- type RelayDeviceRegistrationRequest,- type RelayAgentActivitySnapshotResponse,- type RelayLiveActivityRegistrationRequest,-} from "@t3tools/contracts/relay";-import { findErrorTraceId } from "@t3tools/client-runtime/errors";-import { ManagedRelay } from "@t3tools/client-runtime/relay";-import {- isAtomCommandInterrupted,- settleAsyncResult,- squashAtomCommandFailure,-} from "@t3tools/client-runtime/state/runtime";--import type { SavedRemoteConnection } from "../../lib/connection";-import { runtime } from "../../lib/runtime";-import { appAtomRegistry } from "../../state/atom-registry";-import { environmentServerConfigsAtom } from "../../state/server";-import type { Preferences } from "../../persistence/mobile-preferences";-import {- clearAgentAwarenessRegistrationRecord,- loadAgentAwarenessDeviceId,- loadAgentAwarenessRegistrationRecord,- loadOrCreateAgentAwarenessDeviceId,- loadPreferences,- saveAgentAwarenessRegistrationRecord,-} from "../../persistence/imperative";-import AgentActivity, { type AgentActivityProps } from "../../widgets/AgentActivity";-import { resolveCloudPublicConfig } from "../cloud/publicConfig";-import { supportsAgentAwarenessPush } from "./capabilities";-import { makeRelayDeviceRegistrationRequest, resolveApsEnvironment } from "./registrationPayload";--const REMOTE_ACTIVITY_REGISTRATION_RETRY_MS = 15_000;--const AgentAwarenessOperation = Schema.Literals([- "read-notification-permissions",- "read-native-push-token",- "read-device-registration-relay-token",- "read-device-unregistration-relay-token",- "read-live-activity-registration-relay-token",- "load-device-registration-identifier",- "load-device-registration-preferences",- "load-device-unregistration-identifier",- "read-live-activity-push-token",- "load-live-activity-registration-identifier",- "list-active-live-activities",- "load-live-activity-prime-preferences",- "prime-live-activity",-]);--export class AgentAwarenessOperationError extends Schema.TaggedErrorClass<AgentAwarenessOperationError>()(- "AgentAwarenessOperationError",- {- operation: AgentAwarenessOperation,- cause: Schema.Defect(),- },-) {- override get message(): string {- return `Agent awareness operation ${this.operation} failed.`;- }-}--const environmentConnections = new Map<EnvironmentId, SavedRemoteConnection>();-const activityPushTokenListeners = new WeakSet<LiveActivity<AgentActivityProps>>();-// Activity tokens the relay recently accepted, by acceptance time. The refresh-// runs on sign-in, every app foreground, and every environment-connection-// update, which arrive in bursts and spammed identical registrations. But the-// registration is not a pure no-op: the relay replays the current aggregate to-// this device on every accepted registration, and that replay is the-// foreground reconciliation that repairs drifted or orphaned activities. So-// dedupe only within a short window — bursts collapse to one request, while a-// foreground after real time away still triggers a replay. Cleared on-// sign-out/identity change alongside the device registration state.-const ACTIVITY_TOKEN_REREGISTER_INTERVAL_MS = 60_000;-const registeredActivityPushTokens = new Map<string, number>();-let pushTokenSubscription: { remove: () => void } | null = null;-let appStateSubscription: { remove: () => void } | null = null;--// Whether the relay has actually accepted this device's registration. The-// notification/Live Activity settings toggles must reflect this rather than-// only local iOS permission or saved preferences: if the registration request-// never succeeded, the device cannot receive anything, so the switches must-// not read as enabled.-export type AgentAwarenessRegistrationStatus = "unknown" | "pending" | "registered" | "failed";-let registrationStatus: AgentAwarenessRegistrationStatus = "unknown";-const registrationStatusListeners = new Set<() => void>();--function setRegistrationStatus(next: AgentAwarenessRegistrationStatus): void {- if (registrationStatus === next) {- return;- }- registrationStatus = next;- for (const listener of registrationStatusListeners) {- listener();- }-}--export function getAgentAwarenessRegistrationStatus(): AgentAwarenessRegistrationStatus {- return registrationStatus;-}--export function subscribeAgentAwarenessRegistrationStatus(listener: () => void): () => void {- registrationStatusListeners.add(listener);- return () => {- registrationStatusListeners.delete(listener);- };-}-let activeLiveActivityRegistrationRetry: ReturnType<typeof setTimeout> | null = null;-let relayTokenProvider: (() => Promise<string | null>) | null = null;-let relayTokenProviderIdentity: string | null = null;-let deviceRegistrationGeneration = 0;-let activeDeviceRegistration: {- readonly input: DeviceRegistrationInput;- operation: Promise<void>;-} | null = null;-let pendingDeviceRegistration: {- readonly input: DeviceRegistrationInput;- readonly context: string;-} | null = null;--interface DeviceRegistrationInput {- readonly observedPushToken?: string;-}--interface RegisterDeviceInput extends DeviceRegistrationInput {- readonly preferencesOverride?: Partial<Preferences>;-}--export function mergeAgentAwarenessRegistrationPreferences(- stored: Preferences,- override: Partial<Preferences> | undefined,-): Preferences {- return { ...stored, ...override };-}--export function normalizeAgentAwarenessRelayBaseUrl(- value: string | null | undefined,-): string | null {- const trimmed = value?.trim();- if (!trimmed) {- return null;- }- return trimmed.replace(/\/+$/g, "");-}--function readRelayConfig(): { readonly url: string } | null {- const relayUrl = resolveCloudPublicConfig().relay.url;- if (!relayUrl) {- logRegistrationDebug("relay registration skipped; relay config missing");- return null;- }-- return { url: relayUrl };-}--function canRegisterRemoteLiveActivities(): boolean {- return Platform.OS === "ios";-}--export function shouldRegisterAgentAwarenessDeviceForProvider(- previousIdentity: string | null,- identity: string | undefined,-): boolean {- return identity === undefined || identity !== previousIdentity;-}--export function setAgentAwarenessRelayTokenProvider(- provider: (() => Promise<string | null>) | null,- identity?: string,-): void {- const isExistingIdentity =- provider !== null &&- !shouldRegisterAgentAwarenessDeviceForProvider(relayTokenProviderIdentity, identity);- if (!isExistingIdentity) {- deviceRegistrationGeneration++;- activeDeviceRegistration = null;- pendingDeviceRegistration = null;- registeredActivityPushTokens.clear();- }- relayTokenProvider = provider;- relayTokenProviderIdentity = provider ? (identity ?? null) : null;- if (!provider) {- pushTokenSubscription?.remove();- pushTokenSubscription = null;- appStateSubscription?.remove();- appStateSubscription = null;- if (activeLiveActivityRegistrationRetry) {- clearTimeout(activeLiveActivityRegistrationRetry);- activeLiveActivityRegistrationRetry = null;- }- // Without a signed-in user the relay can no longer update or end these- // activities, so they would sit orphaned on the lock screen.- endLocalLiveActivities("live activity cleanup after cloud sign-out failed");- setRegistrationStatus("unknown");- // Sign-out is the only thing that invalidates a stored registration, so the- // next sign-in re-registers.- void clearAgentAwarenessRegistrationRecord().catch((error: unknown) => {- logRegistrationError("clear registration record on sign-out failed", error);- });- return;- }- ensurePushTokenListener();- ensureAppStateListener();- runRegistrationInBackground(- refreshActiveLiveActivityRemoteRegistration(),- "active live activity registration after cloud sign-in failed",- );- if (isExistingIdentity) {- // Same account re-activating (e.g. Clerk token refresh) normally needs no- // re-registration — but if the previous attempt never succeeded, this is- // the only trigger that will retry it before the next cold start.- if (registrationStatus !== "registered") {- enqueueDeviceRegistration({}, "device registration retry after cloud session refresh failed");- }- return;- }- enqueueDeviceRegistration({}, "device registration after cloud sign-in failed");-}--// Detach the provider and native listeners without the destructive sign-out-// cleanup. For provider teardown while the user is still signed in (e.g. the-// auth bridge unmounting/remounting), ending lock-screen activities and wiping-// the persisted registration would be wrong — the relay still holds a valid-// registration and the next mount reuses it.-export function releaseAgentAwarenessRelayTokenProvider(): void {- relayTokenProvider = null;- relayTokenProviderIdentity = null;- pushTokenSubscription?.remove();- pushTokenSubscription = null;- appStateSubscription?.remove();- appStateSubscription = null;- if (activeLiveActivityRegistrationRetry) {- clearTimeout(activeLiveActivityRegistrationRetry);- activeLiveActivityRegistrationRetry = null;- }-}--function iosMajorVersion(): number {- const version = Platform.Version;- if (typeof version === "number") {- return Math.floor(version);- }- const major = Number.parseInt(version.split(".")[0] ?? "", 10);- return Number.isFinite(major) ? major : 18;-}--function nativePushTokenRegistration(observedPushToken?: string) {- return Effect.gen(function* () {- if (!canRegisterRemoteLiveActivities() || !supportsAgentAwarenessPush()) {- return { notificationsEnabled: false, pushToken: null };- }- if (observedPushToken) {- return { notificationsEnabled: true, pushToken: observedPushToken };- }- const permissions = yield* Effect.tryPromise({- try: () => Notifications.getPermissionsAsync(),- catch: (cause) =>- new AgentAwarenessOperationError({- operation: "read-notification-permissions",- cause,- }),- });- if (!permissions.granted) {- return { notificationsEnabled: false, pushToken: null };- }- const token = yield* Effect.tryPromise({- try: () => Notifications.getDevicePushTokenAsync(),- catch: (cause) =>- new AgentAwarenessOperationError({- operation: "read-native-push-token",- cause,- }),- }).pipe(- Effect.tapError((error) =>- Effect.sync(() => {- logRegistrationError("native APNs token lookup failed", error);- }),- ),- Effect.orElseSucceed(() => null),- );- const pushToken =- token?.type === "ios" && typeof token.data === "string" && token.data.trim().length > 0- ? token.data.trim()- : null;- return { notificationsEnabled: pushToken !== null, pushToken };- });-}--const relayToken = (- operation: "read-device-registration-relay-token" | "read-live-activity-registration-relay-token",-) =>- Effect.gen(function* () {- const provider = relayTokenProvider;- if (!provider) {- return null;- }- return yield* Effect.tryPromise({- try: provider,- catch: (cause) => new AgentAwarenessOperationError({ operation, cause }),- });- });--// Stable fingerprint of everything the relay stores for this device. When it-// matches the last accepted registration for the same account, re-registering-// is a no-op, so a launch that changed nothing skips the request entirely.-function registrationSignature(body: RelayDeviceRegistrationRequest): string {- return [- body.deviceId,- body.pushToken ?? "",- body.bundleId ?? "",- body.apsEnvironment ?? "",- body.appVersion ?? "",- body.label,- body.iosMajorVersion,- body.preferences.notificationsEnabled,- body.preferences.liveActivitiesEnabled,- body.preferences.notifyOnApproval,- body.preferences.notifyOnInput,- body.preferences.notifyOnCompletion,- body.preferences.notifyOnFailure,- ].join("|");-}--function registerDeviceWithRelay(- body: RelayDeviceRegistrationRequest,- expectedGeneration: number,-): Effect.Effect<void, unknown, ManagedRelay.ManagedRelayClient> {- return Effect.gen(function* () {- if (expectedGeneration !== deviceRegistrationGeneration) {- logRegistrationDebug("device registration cancelled before relay request", {- expectedGeneration,- currentGeneration: deviceRegistrationGeneration,- });- return;- }- const relayConfig = readRelayConfig();- if (!relayConfig) {- // Nothing is in flight and nothing can succeed until configuration- // appears; "pending" would otherwise stick forever.- setRegistrationStatus("unknown");- return;- }- const token = yield* relayToken("read-device-registration-relay-token");- if (expectedGeneration !== deviceRegistrationGeneration) {- logRegistrationDebug("device registration cancelled after auth lookup", {- expectedGeneration,- currentGeneration: deviceRegistrationGeneration,- });- return;- }- if (!token) {- logRegistrationDebug("relay device registration skipped; user is not signed in");- setRegistrationStatus("unknown");- return;- }-- // Skip the request when this account already registered an identical- // payload; the relay upsert would be a no-op. The record is only cleared on- // sign-out, so a device stays registered across launches without re-hitting- // the relay every time the app opens.- const identity = relayTokenProviderIdentity ?? "";- const persisted = yield* Effect.tryPromise({- try: () => loadAgentAwarenessRegistrationRecord(),- catch: (cause) => cause,- }).pipe(Effect.orElseSucceed(() => null));- if (expectedGeneration !== deviceRegistrationGeneration) {- // Signed out while the record loaded — do not resurrect the cleared- // record or report the previous account's registration as current.- logRegistrationDebug("device registration cancelled after record lookup", {- expectedGeneration,- currentGeneration: deviceRegistrationGeneration,- });- return;- }- const payload = body;- // The relay URL participates so pointing the app at a different relay- // invalidates the record and re-registers there.- const signature = `${relayConfig.url}|${registrationSignature(payload)}`;- if (persisted && persisted.identity === identity && persisted.signature === signature) {- setRegistrationStatus("registered");- logRegistrationDebug("relay device registration skipped; already registered for account", {- expectedGeneration,- });- return;- }-- const client = yield* ManagedRelay.ManagedRelayClient;- logRegistrationDebug("relay device registration request started", {- expectedGeneration,- });- yield* client.registerDevice({- clerkToken: token,- payload,- });- if (expectedGeneration !== deviceRegistrationGeneration) {- // Signed out while the request was in flight: the sign-out path already- // reset the status and cleared the record for the next account, so a- // stale success must not overwrite either.- logRegistrationDebug("device registration completed after sign-out; result discarded", {- expectedGeneration,- currentGeneration: deviceRegistrationGeneration,- });- return;- }- setRegistrationStatus("registered");- yield* Effect.promise(() =>- saveAgentAwarenessRegistrationRecord({- identity,- signature,- }).catch((error: unknown) => {- logRegistrationError("persist registration record failed", error);- }),- );- logRegistrationDebug("relay device registration request completed", {- expectedGeneration,- });- });-}--function unregisterDeviceWithRelay(input: {- readonly deviceId: string;- readonly tokenProvider: () => Promise<string | null>;-}): Effect.Effect<void, unknown, ManagedRelay.ManagedRelayClient> {- return Effect.gen(function* () {- if (!readRelayConfig()) return;- const token = yield* Effect.tryPromise({- try: input.tokenProvider,- catch: (cause) =>- new AgentAwarenessOperationError({- operation: "read-device-unregistration-relay-token",- cause,- }),- });- if (!token) {- logRegistrationDebug("relay device unregistration skipped; user is not signed in");- return;- }-- const client = yield* ManagedRelay.ManagedRelayClient;- yield* client.unregisterDevice({- clerkToken: token,- deviceId: input.deviceId,- });- });-}--// The environment descriptor advertises whether agent-activity publishes-// currently leave that server (`capabilities.agentActivityPublishing`). Only-// an explicit false skips the seed card: older servers omit the capability-// but may still publish.-function environmentPublishesAgentActivity(environmentId: EnvironmentId): boolean {- return (- appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities- .agentActivityPublishing !== false- );-}--// Arms the lock-screen card the moment the user starts agent work from this-// phone, while the app is still foregrounded and the fresh activity's token-// can be registered immediately. The seeded row is a best-effort placeholder;-// the relay's registration replay repaints it with the authoritative-// aggregate within seconds. No-ops when a card is already armed, and skips-// environments that report publishing disabled — the seed would sit on-// "Connecting" forever with no update ever arriving to repaint or end it.-export function armAgentAwarenessLiveActivityForLocalWork(input: {- readonly environmentId: EnvironmentId;- readonly threadTitle: string;- readonly projectTitle: string;-}): void {- if (!canRegisterRemoteLiveActivities() || !relayTokenProvider) {- return;- }- if (!environmentPublishesAgentActivity(input.environmentId)) {- logRegistrationDebug("live activity arming skipped; environment does not publish", {- environmentId: input.environmentId,- });- return;- }- void loadPreferences()- .catch(() => null)- .then((preferences) => {- if (preferences?.liveActivitiesEnabled === false) {- return;- }- armAgentAwarenessLiveActivityForLocalWorkNow(input);- });-}--function armAgentAwarenessLiveActivityForLocalWorkNow(input: {- readonly threadTitle: string;- readonly projectTitle: string;-}): void {- try {- if (AgentActivity.getInstances().length > 0) {- return;- }- const nowIso = new Date(Date.now()).toISOString();- const activity = AgentActivity.start({- title: "T3 Code",- subtitle: "Agent work in progress",- activeCount: 1,- updatedAt: nowIso,- activities: [- {- environmentId: "",- threadId: "",- projectTitle: input.projectTitle,- threadTitle: input.threadTitle,- modelTitle: "",- phase: "starting",- status: "Connecting",- updatedAt: nowIso,- deepLink: "/",- },- ],- });- logRegistrationDebug("live activity card armed for local work", {- threadTitle: input.threadTitle,- });- runRegistrationInBackground(- registerLiveActivityPushToken({ activity }).pipe(Effect.asVoid),- "live activity arming after local task start failed",- );- } catch (error) {- logRegistrationError("live activity arming failed", error);- }-}--function readAgentActivitySnapshot(): Effect.Effect<- RelayAgentActivitySnapshotResponse | null,- never,- ManagedRelay.ManagedRelayClient-> {- return Effect.gen(function* () {- if (!readRelayConfig()) return null;- const token = yield* relayToken("read-live-activity-registration-relay-token");- if (!token) {- return null;- }- const client = yield* ManagedRelay.ManagedRelayClient;- return yield* client.getAgentActivitySnapshot({ clerkToken: token });- }).pipe(- Effect.catch((error) =>- Effect.sync(() => {- logRegistrationError("agent activity snapshot read failed", error);- return null;- }),- ),- );-}--function registerLiveActivityWithRelay(- body: RelayLiveActivityRegistrationRequest,-): Effect.Effect<boolean, unknown, ManagedRelay.ManagedRelayClient> {- return Effect.gen(function* () {- if (!readRelayConfig()) return false;- const token = yield* relayToken("read-live-activity-registration-relay-token");- if (!token) {- logRegistrationDebug("relay live activity registration skipped; user is not signed in");- return false;- }-- const client = yield* ManagedRelay.ManagedRelayClient;- yield* client.registerLiveActivity({- clerkToken: token,- payload: body,- });- return true;- });-}--function logRegistrationError(context: string, error: unknown): void {- if (!__DEV__) {- return;- }- console.warn(`[agent-awareness] ${context}`, {- message: error instanceof Error ? error.message : String(error),- traceId: findErrorTraceId(error),- error,- });-}--function logRegistrationDebug(context: string, details?: unknown): void {- if (!__DEV__) {- return;- }- console.log(`[agent-awareness] ${context}`, details ?? "");-}--function runRegistrationInBackground(- operation: Effect.Effect<unknown, unknown, ManagedRelay.ManagedRelayClient>,- context: string,-): void {- void (async () => {- const result = await settleAsyncResult(() => runtime.runPromiseExit(operation));- if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {- logRegistrationError(context, squashAtomCommandFailure(result));- }- })();-}--function mergeDeviceRegistrationInput(- current: DeviceRegistrationInput,- next: DeviceRegistrationInput,-): DeviceRegistrationInput {- const observedPushToken = next.observedPushToken ?? current.observedPushToken;- return observedPushToken ? { observedPushToken } : {};-}--function registrationAddsInformation(- current: DeviceRegistrationInput,- next: DeviceRegistrationInput,-): boolean {- return (- next.observedPushToken !== undefined && next.observedPushToken !== current.observedPushToken- );-}--function startPendingDeviceRegistration(): void {- if (activeDeviceRegistration || !pendingDeviceRegistration) {- return;- }-- const next = pendingDeviceRegistration;- pendingDeviceRegistration = null;- const generation = deviceRegistrationGeneration;- logRegistrationDebug("device registration started", {- generation,- hasObservedPushToken: next.input.observedPushToken !== undefined,- });- if (registrationStatus !== "registered") {- setRegistrationStatus("pending");- }- const registration = {- input: next.input,- operation: Promise.resolve(),- };- activeDeviceRegistration = registration;- registration.operation = (async () => {- const result = await settleAsyncResult(() =>- runtime.runPromiseExit(registerDevice(next.input, generation)),- );- if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {- // A transient failure on a later refresh (e.g. token rotation) leaves- // the prior accepted registration intact on the relay, so an already- // registered device stays "registered" rather than flipping the- // settings toggles off.- if (registrationStatus !== "registered") {- setRegistrationStatus("failed");- }- logRegistrationError(next.context, squashAtomCommandFailure(result));- }- logRegistrationDebug("device registration finished", { generation });- if (activeDeviceRegistration === registration) {- activeDeviceRegistration = null;- }- startPendingDeviceRegistration();- })();-}--function enqueueDeviceRegistration(input: DeviceRegistrationInput, context: string): void {- if (- activeDeviceRegistration &&- !registrationAddsInformation(activeDeviceRegistration.input, input)- ) {- logRegistrationDebug("device registration coalesced with active request", {- generation: deviceRegistrationGeneration,- });- return;- }-- logRegistrationDebug("device registration enqueued", {- generation: deviceRegistrationGeneration,- hasActiveRegistration: activeDeviceRegistration !== null,- hasPendingRegistration: pendingDeviceRegistration !== null,- });- pendingDeviceRegistration = pendingDeviceRegistration- ? {- input: mergeDeviceRegistrationInput(pendingDeviceRegistration.input, input),- context,- }- : { input, context };- startPendingDeviceRegistration();-}--function registerDevice(- input: RegisterDeviceInput = {},- expectedGeneration = deviceRegistrationGeneration,-): Effect.Effect<void, unknown, ManagedRelay.ManagedRelayClient> {- return Effect.gen(function* () {- if (!canRegisterRemoteLiveActivities()) {- logRegistrationDebug("device registration skipped; platform does not support it");- return;- }-- logRegistrationDebug("device registration loading local state", { expectedGeneration });- const [deviceId, storedPreferences] = yield* Effect.all([- Effect.tryPromise({- try: () => loadOrCreateAgentAwarenessDeviceId(),- catch: (cause) =>- new AgentAwarenessOperationError({- operation: "load-device-registration-identifier",- cause,- }),- }),- Effect.tryPromise({- try: () => loadPreferences(),- catch: (cause) =>- new AgentAwarenessOperationError({- operation: "load-device-registration-preferences",- cause,- }),- }),- ]);- const preferences = mergeAgentAwarenessRegistrationPreferences(- storedPreferences,- input.preferencesOverride,- );- const pushTokenRegistration = yield* nativePushTokenRegistration(input?.observedPushToken);- logRegistrationDebug("device registration local state ready", {- expectedGeneration,- notificationsEnabled: pushTokenRegistration.notificationsEnabled,- });- const bundleId = Constants.expoConfig?.ios?.bundleIdentifier?.trim();- yield* registerDeviceWithRelay(- makeRelayDeviceRegistrationRequest({- deviceId,- label: Constants.deviceName?.trim() || "iOS device",- iosMajorVersion: iosMajorVersion(),- appVersion: Constants.expoConfig?.version,- ...(bundleId ? { bundleId } : {}),- apsEnvironment: resolveApsEnvironment(Constants.expoConfig?.extra?.appVariant),- ...(pushTokenRegistration.pushToken ? { pushToken: pushTokenRegistration.pushToken } : {}),- notificationsEnabled: pushTokenRegistration.notificationsEnabled,- preferences,- }),- expectedGeneration,- );- });-}--function registerDeviceForCurrentUser(): Effect.Effect<- void,- unknown,- ManagedRelay.ManagedRelayClient-> {- return registerDevice(undefined);-}--function ensurePushTokenListener(): void {- if (pushTokenSubscription || !canRegisterRemoteLiveActivities()) {- return;- }-- pushTokenSubscription = Notifications.addPushTokenListener((token) => {- if (token.type === "ios" && typeof token.data === "string" && token.data.trim().length > 0) {- enqueueDeviceRegistration(- { observedPushToken: token.data.trim() },- "native APNs token rotation registration failed",- );- }- });-}--// Re-registering activity tokens on foreground makes the relay replay the-// current aggregate to this device, which updates content that drifted while-// pushes could not be delivered and ends orphaned activities whose end push-// never arrived. (Deduped by ACTIVITY_TOKEN_REREGISTER_INTERVAL_MS: rapid-// foreground/sign-in bursts collapse to one registration, but returning after-// real time away still replays.)-function ensureAppStateListener(): void {- if (appStateSubscription || !canRegisterRemoteLiveActivities()) {- return;- }-- appStateSubscription = AppState.addEventListener("change", (state) => {- if (state !== "active") {- return;- }- runRegistrationInBackground(- refreshActiveLiveActivityRemoteRegistration(),- "active live activity reconciliation after app foreground failed",- );- });-}--function endLocalLiveActivities(context: string): void {- if (!canRegisterRemoteLiveActivities()) {- return;- }- try {- for (const activity of AgentActivity.getInstances()) {- activity.end("immediate").catch((error: unknown) => {- logRegistrationError(context, error);- });- }- } catch (error) {- logRegistrationError(context, error);- }-}--export function registerAgentAwarenessConnection(connection: SavedRemoteConnection): void {- if (!canRegisterRemoteLiveActivities()) {- return;- }-- environmentConnections.set(connection.environmentId, connection);- ensurePushTokenListener();- ensureAppStateListener();- enqueueDeviceRegistration({}, "device registration failed");- runRegistrationInBackground(- refreshActiveLiveActivityRemoteRegistration(),- "active live activity registration after environment connection failed",- );-}--function removeAgentAwarenessConnection(environmentId: EnvironmentId): void {- environmentConnections.delete(environmentId);-}--export function unregisterAgentAwarenessConnection(environmentId: EnvironmentId): void {- removeAgentAwarenessConnection(environmentId);-}--export function unregisterAllAgentAwarenessConnections(): void {- environmentConnections.clear();- pushTokenSubscription?.remove();- pushTokenSubscription = null;- appStateSubscription?.remove();- appStateSubscription = null;- if (activeLiveActivityRegistrationRetry) {- clearTimeout(activeLiveActivityRegistrationRetry);- activeLiveActivityRegistrationRetry = null;- }-}--export function refreshAgentAwarenessRegistration(): Effect.Effect<- void,- never,- ManagedRelay.ManagedRelayClient-> {- return registerDeviceForCurrentUser().pipe(- Effect.catch((error) =>- Effect.sync(() => {- // Same rationale as the queued path: a failed refresh does not undo an- // already accepted registration.- if (registrationStatus !== "registered") {- setRegistrationStatus("failed");- }- logRegistrationError("device registration refresh failed", error);- }),- ),- );-}--export function updateAgentAwarenessRegistrationPreferences(- preferencesOverride: Partial<Preferences>,-): Effect.Effect<void, unknown, ManagedRelay.ManagedRelayClient> {- return registerDevice({ preferencesOverride }).pipe(- Effect.tapError((error) =>- Effect.sync(() => {- if (registrationStatus !== "registered") {- setRegistrationStatus("failed");- }- logRegistrationError("device preference registration refresh failed", error);- }),- ),- );-}--export function __resetAgentAwarenessRemoteRegistrationForTest(): void {- environmentConnections.clear();- pushTokenSubscription?.remove();- pushTokenSubscription = null;- appStateSubscription?.remove();- appStateSubscription = null;- if (activeLiveActivityRegistrationRetry) {- clearTimeout(activeLiveActivityRegistrationRetry);- activeLiveActivityRegistrationRetry = null;- }- relayTokenProvider = null;- relayTokenProviderIdentity = null;- deviceRegistrationGeneration++;- activeDeviceRegistration = null;- pendingDeviceRegistration = null;- registrationStatus = "unknown";- registrationStatusListeners.clear();- registeredActivityPushTokens.clear();-}--export function unregisterAgentAwarenessDeviceForCurrentUser(- tokenProvider: () => Promise<string | null>,-): Effect.Effect<void, never, ManagedRelay.ManagedRelayClient> {- return Effect.gen(function* () {- const deviceId = yield* Effect.tryPromise({- try: () => loadAgentAwarenessDeviceId(),- catch: (cause) =>- new AgentAwarenessOperationError({- operation: "load-device-unregistration-identifier",- cause,- }),- });- if (!deviceId) {- return;- }- yield* unregisterDeviceWithRelay({ deviceId, tokenProvider });- }).pipe(- Effect.catch((error) =>- Effect.sync(() => {- logRegistrationError("device unregistration failed", error);- }),- ),- );-}--export function registerLiveActivityPushToken(input: {- readonly activity: LiveActivity<AgentActivityProps>;-}): Effect.Effect<boolean, unknown, ManagedRelay.ManagedRelayClient> {- return Effect.gen(function* () {- if (!canRegisterRemoteLiveActivities()) {- return false;- }-- const activityPushToken = yield* Effect.tryPromise({- try: () => input.activity.getPushToken(),- catch: (cause) =>- new AgentAwarenessOperationError({- operation: "read-live-activity-push-token",- cause,- }),- });- if (!activityPushToken) {- if (activityPushTokenListeners.has(input.activity)) {- logRegistrationDebug(- "live activity push token not available yet; token listener already registered",- {- connectionCount: environmentConnections.size,- },- );- return false;- }-- logRegistrationDebug(- "live activity push token not available yet; listening for token event",- {- connectionCount: environmentConnections.size,- },- );- activityPushTokenListeners.add(input.activity);- input.activity.addPushTokenListener((event) => {- if (event.pushToken) {- logRegistrationDebug("live activity push token event received", {- tokenSuffix: event.pushToken.slice(-8),- });- runRegistrationInBackground(- registerLiveActivityPushTokenValue({- activityPushToken: event.pushToken,- }),- "live activity token listener registration failed",- );- }- });- return false;- }-- return yield* registerLiveActivityPushTokenValue({- activityPushToken,- });- });-}--function registerLiveActivityPushTokenValue(input: {- readonly activityPushToken: string;-}): Effect.Effect<boolean, unknown, ManagedRelay.ManagedRelayClient> {- return Effect.gen(function* () {- const acceptedAt = registeredActivityPushTokens.get(input.activityPushToken);- if (- acceptedAt !== undefined &&- Date.now() - acceptedAt < ACTIVITY_TOKEN_REREGISTER_INTERVAL_MS- ) {- return true;- }- const deviceId = yield* Effect.tryPromise({- try: () => loadOrCreateAgentAwarenessDeviceId(),- catch: (cause) =>- new AgentAwarenessOperationError({- operation: "load-live-activity-registration-identifier",- cause,- }),- });- const registered = yield* registerLiveActivityWithRelay({- deviceId,- activityPushToken: input.activityPushToken,- });- if (registered) {- registeredActivityPushTokens.set(input.activityPushToken, Date.now());- logRegistrationDebug("live activity push token registered", {- tokenSuffix: input.activityPushToken.slice(-8),- });- }- return registered;- });-}--function scheduleActiveLiveActivityRegistrationRetry(): void {- if (activeLiveActivityRegistrationRetry || !relayTokenProvider) {- return;- }-- activeLiveActivityRegistrationRetry = setTimeout(() => {- activeLiveActivityRegistrationRetry = null;- runRegistrationInBackground(- refreshActiveLiveActivityRemoteRegistration(),- "active live activity token retry failed",- );- }, REMOTE_ACTIVITY_REGISTRATION_RETRY_MS);-}--export function refreshActiveLiveActivityRemoteRegistration(): Effect.Effect<- void,- never,- ManagedRelay.ManagedRelayClient-> {- return Effect.gen(function* () {- if (!canRegisterRemoteLiveActivities() || !relayTokenProvider) {- return;- }-- let activities = yield* Effect.try({- try: () => AgentActivity.getInstances(),- catch: (cause) =>- new AgentAwarenessOperationError({- operation: "list-active-live-activities",- cause,- }),- }).pipe(- Effect.catch((error) =>- Effect.sync(() => {- logRegistrationError("active live activity lookup failed", error);- return [] as ReadonlyArray<LiveActivity<AgentActivityProps>>;- }),- ),- );-- // The relay tracks exactly one card per device; if concurrent arming ever- // produced extras, end them so only one keeps receiving updates.- if (activities.length > 1) {- for (const extra of activities.slice(1)) {- extra.end("immediate").catch((error: unknown) => {- logRegistrationError("duplicate live activity cleanup failed", error);- });- }- activities = activities.slice(0, 1);- }-- // Activities are only ever created here, in the foreground, where the- // update token can be observed and registered immediately — the relay- // never remote-starts one (background push-to-start wakes proved too- // unreliable to hand the token over). Arming is conditional: the relay is- // asked what the card would show first, so an idle open never creates an- // empty lock-screen card, and an armed card is born with the real- // aggregate instead of a placeholder.- if (activities.length === 0) {- const preferences = yield* Effect.tryPromise({- try: () => loadPreferences(),- catch: (cause) =>- new AgentAwarenessOperationError({- operation: "load-live-activity-prime-preferences",- cause,- }),- }).pipe(Effect.orElseSucceed(() => null));- // The toggle defaults to on: an unset preference (fresh install) must- // prime, so only an explicit false blocks it.- if (preferences?.liveActivitiesEnabled !== false) {- const snapshot = yield* readAgentActivitySnapshot();- // The snapshot request yields; an arm-on-send may have created the- // card in the meantime. Re-check so two cards are never started.- const armedMeanwhile = yield* Effect.try({- try: () => AgentActivity.getInstances(),- catch: () => [] as ReadonlyArray<LiveActivity<AgentActivityProps>>,- }).pipe(Effect.orElseSucceed(() => [] as ReadonlyArray<LiveActivity<AgentActivityProps>>));- if (armedMeanwhile.length > 0) {- activities = [...armedMeanwhile];- } else if (snapshot?.aggregate && snapshot.aggregate.activeCount > 0) {- const aggregate = snapshot.aggregate;- const primed = yield* Effect.try({- try: () =>- AgentActivity.start({- title: aggregate.title,- subtitle: aggregate.subtitle,- activeCount: aggregate.activeCount,- updatedAt: aggregate.updatedAt,- activities: aggregate.activities,- }),- catch: (cause) =>- new AgentAwarenessOperationError({- operation: "prime-live-activity",- cause,- }),- }).pipe(- Effect.catch((error) =>- Effect.sync(() => {- logRegistrationError("live activity priming failed", error);- return null;- }),- ),- );- if (primed) {- logRegistrationDebug("live activity card primed", {- activeCount: aggregate.activeCount,- });- activities = [primed];- }- }- }- }-- const registrationResults = yield* Effect.forEach(activities, (activity) =>- registerLiveActivityPushToken({ activity }).pipe(- Effect.map((registered) => !registered),- Effect.catch((error) =>- Effect.sync(() => {- logRegistrationError("active live activity token registration failed", error);- return true;- }),- ),- ),- );-- if (registrationResults.some(Boolean)) {- scheduleActiveLiveActivityRegistrationRetry();- }- });-}diff --git a/apps/mobile/src/features/cloud/CloudAuthProvider.test.ts b/apps/mobile/src/features/cloud/CloudAuthProvider.test.tsdeleted file mode 100644index 2bc62d2a3..000000000--- a/apps/mobile/src/features/cloud/CloudAuthProvider.test.ts+++ /dev/null@@ -1,60 +0,0 @@-import { managedRelaySessionAtom } from "@t3tools/client-runtime/relay";-import { afterEach, describe, expect, it, vi } from "vite-plus/test";--import { appAtomRegistry } from "../../state/atom-registry";-import { activateCloudRelayAccount, deactivateCloudRelayAccount } from "./CloudAuthProvider";-import { setAgentAwarenessRelayTokenProvider } from "../agent-awareness/remoteRegistration";--vi.mock("@clerk/expo", () => ({- ClerkProvider: vi.fn(),- useAuth: vi.fn(),-}));--vi.mock("@clerk/expo/token-cache", () => ({- tokenCache: {},-}));--vi.mock("../../lib/runtime", () => ({- runtime: {- runPromiseExit: vi.fn(),- },-}));--vi.mock("../../connection/catalog", () => ({- environmentCatalog: {- removeRelayEnvironments: {},- },-}));--vi.mock("./publicConfig", () => ({- resolveCloudPublicConfig: vi.fn(() => ({- clerk: { publishableKey: null },- relay: { url: null },- })),- resolveRelayClerkTokenOptions: vi.fn(),-}));--vi.mock("../agent-awareness/remoteRegistration", () => ({- setAgentAwarenessRelayTokenProvider: vi.fn(),- unregisterAgentAwarenessDeviceForCurrentUser: vi.fn(),-}));--afterEach(() => {- deactivateCloudRelayAccount();- vi.clearAllMocks();-});--describe("CloudAuthProvider relay account isolation", () => {- it("clears relay and agent-awareness credentials before cleanup can fail", async () => {- const tokenProvider = async () => "account-1-token";- activateCloudRelayAccount("account-1", tokenProvider);- expect(appAtomRegistry.get(managedRelaySessionAtom)?.accountId).toBe("account-1");-- deactivateCloudRelayAccount();- const cleanup = Promise.reject(new Error("Persistence removal failed.")).catch(() => undefined);-- expect(appAtomRegistry.get(managedRelaySessionAtom)).toBeNull();- expect(vi.mocked(setAgentAwarenessRelayTokenProvider)).toHaveBeenLastCalledWith(null);- await cleanup;- });-});diff --git a/apps/mobile/src/features/cloud/CloudAuthProvider.tsx b/apps/mobile/src/features/cloud/CloudAuthProvider.tsxdeleted file mode 100644index f7ece97cb..000000000--- a/apps/mobile/src/features/cloud/CloudAuthProvider.tsx+++ /dev/null@@ -1,196 +0,0 @@-import { ClerkProvider, useAuth } from "@clerk/expo";-import { tokenCache } from "@clerk/expo/token-cache";-import { ManagedRelay, setManagedRelaySession } from "@t3tools/client-runtime/relay";-import {- reportAtomCommandResult,- settleAsyncResult,- settlePromise,-} from "@t3tools/client-runtime/state/runtime";-import * as Effect from "effect/Effect";-import { type ReactNode, useEffect, useRef } from "react";--import { environmentCatalog } from "../../connection/catalog";-import { runtime } from "../../lib/runtime";-import { appAtomRegistry } from "../../state/atom-registry";-import { useAtomCommand } from "../../state/use-atom-command";-import {- releaseAgentAwarenessRelayTokenProvider,- setAgentAwarenessRelayTokenProvider,- unregisterAgentAwarenessDeviceForCurrentUser,-} from "../agent-awareness/remoteRegistration";-import { clearConnectOnboardingRequest, requestConnectOnboarding } from "./connectOnboarding";-import { resolveCloudPublicConfig, resolveRelayClerkTokenOptions } from "./publicConfig";--function resetManagedRelayTokenCache() {- return settleAsyncResult(() =>- runtime.runPromiseExit(- ManagedRelay.ManagedRelayClient.pipe(Effect.flatMap((client) => client.resetTokenCache)),- ),- );-}--export function deactivateCloudRelayAccount(): void {- setAgentAwarenessRelayTokenProvider(null);- setManagedRelaySession(appAtomRegistry, null);-}--export function activateCloudRelayAccount(- accountId: string,- tokenProvider: () => Promise<string | null>,-): void {- setAgentAwarenessRelayTokenProvider(tokenProvider, accountId);- setManagedRelaySession(appAtomRegistry, {- accountId,- readClerkToken: tokenProvider,- });-}--function CloudAuthBridge(props: { readonly children: ReactNode }) {- const { getToken, isLoaded, isSignedIn, userId } = useAuth({ treatPendingAsSignedOut: false });- const removeRelayEnvironments = useAtomCommand(environmentCatalog.removeRelayEnvironments, {- reportFailure: false,- reportDefect: false,- });- const previousTokenProviderRef = useRef<{- readonly userId: string;- readonly provider: () => Promise<string | null>;- } | null>(null);- const observedAccountRef = useRef<string | null | undefined>(undefined);- const accountTransitionRef = useRef<Promise<void> | null>(null);-- useEffect(() => {- let cancelled = false;- if (!isLoaded) {- return;- }-- const previousObservedAccount = observedAccountRef.current;- const nextAccount = isSignedIn && userId ? userId : null;- observedAccountRef.current = nextAccount;-- // Every sign-in or account switch that completes during this session (a- // cold start observes undefined → account and must not re-prompt) requests- // the T3 Connect onboarding sheet — account transitions clear the- // connected environments, so each new session starts with no devices to- // reach. The request itself is issued after the cleanup transition inside- // activateSession, so the sheet never lists the previous account's- // environments; sign-out drops any not-yet-presented request instead.- const isAccountTransition =- previousObservedAccount !== undefined && previousObservedAccount !== nextAccount;- if (isAccountTransition && nextAccount === null) {- clearConnectOnboardingRequest();- }-- const queueAccountCleanup = (- previous: {- readonly userId: string;- readonly provider: () => Promise<string | null>;- } | null,- ) => {- const previousTransition = accountTransitionRef.current ?? Promise.resolve();- accountTransitionRef.current = previousTransition.then(async () => {- const cleanup = [- resetManagedRelayTokenCache(),- removeRelayEnvironments(),- ...(previous- ? [- settleAsyncResult(() =>- runtime.runPromiseExit(- unregisterAgentAwarenessDeviceForCurrentUser(previous.provider),- ),- ),- ]- : []),- ];- const results = await Promise.all(cleanup);- for (const result of results) {- reportAtomCommandResult(result, { label: "cloud account cleanup" });- }- });- return accountTransitionRef.current;- };-- if (!isSignedIn || !userId) {- const previous = previousTokenProviderRef.current;- previousTokenProviderRef.current = null;- deactivateCloudRelayAccount();- if (previousObservedAccount !== null) {- void queueAccountCleanup(previous);- }- return;- }-- const previous = previousTokenProviderRef.current;- const tokenProvider = () => getToken(resolveRelayClerkTokenOptions());- const activateSession = () => {- if (cancelled) {- return;- }- previousTokenProviderRef.current = { userId, provider: tokenProvider };- activateCloudRelayAccount(userId, tokenProvider);- if (isAccountTransition) {- requestConnectOnboarding(userId);- }- };- const activateAfterTransition = (transition: Promise<void>) => {- void (async () => {- const result = await settlePromise(async () => {- await transition;- activateSession();- });- reportAtomCommandResult(result, { label: "cloud account activation" });- })();- };- if (- previousObservedAccount !== undefined &&- previousObservedAccount !== null &&- previousObservedAccount !== userId- ) {- previousTokenProviderRef.current = null;- deactivateCloudRelayAccount();- activateAfterTransition(queueAccountCleanup(previous));- } else {- activateAfterTransition(accountTransitionRef.current ?? Promise.resolve());- }-- return () => {- cancelled = true;- };- }, [getToken, isLoaded, isSignedIn, removeRelayEnvironments, userId]);-- useEffect(- () => () => {- previousTokenProviderRef.current = null;- // Unmounting is not a sign-out: the user is usually still signed in, so- // detach the provider without ending lock-screen activities or wiping the- // persisted registration (a remount reuses both).- releaseAgentAwarenessRelayTokenProvider();- setManagedRelaySession(appAtomRegistry, null);- },- [],- );-- return props.children;-}--export function CloudAuthProvider(props: { readonly children: ReactNode }) {- const config = resolveCloudPublicConfig();- const publishableKey = config.clerk.publishableKey;- const relayUrl = config.relay.url;-- useEffect(() => {- if (!publishableKey || !relayUrl) {- deactivateCloudRelayAccount();- }- }, [publishableKey, relayUrl]);-- if (!publishableKey || !relayUrl) {- return props.children;- }-- return (- <ClerkProvider publishableKey={publishableKey} tokenCache={tokenCache}>- <CloudAuthBridge>{props.children}</CloudAuthBridge>- </ClerkProvider>- );-}diff --git a/apps/mobile/src/features/cloud/ConnectOnboardingRouteScreen.tsx b/apps/mobile/src/features/cloud/ConnectOnboardingRouteScreen.tsxdeleted file mode 100644index 952d1c388..000000000--- a/apps/mobile/src/features/cloud/ConnectOnboardingRouteScreen.tsx+++ /dev/null@@ -1,137 +0,0 @@-import { NativeHeaderToolbar } from "../../native/StackHeader";-import { useAuth } from "@clerk/expo";-import { StackActions, useNavigation } from "@react-navigation/native";-import { useCallback, useEffect, useState } from "react";-import { Platform, Pressable, RefreshControl, ScrollView, View } from "react-native";-import { useSafeAreaInsets } from "react-native-safe-area-context";--import { reportAtomCommandResult, settlePromise } from "@t3tools/client-runtime/state/runtime";-import { AndroidSheetHeader } from "../../components/AndroidScreenHeader";-import { AppText as Text } from "../../components/AppText";-import { useRemoteConnections } from "../../state/use-remote-environment-registry";-import { CloudEnvironmentRows } from "../connection/CloudEnvironmentRows";-import { splitEnvironmentSections } from "../connection/environmentSections";-import { useConnectionController } from "../connection/useConnectionController";-import { optOutOfConnectOnboarding } from "./connectOnboardingOptOut";-import { hasCloudPublicConfig } from "./publicConfig";--/**- * Post-sign-in onboarding sheet for T3 Connect. Mobile never publishes- * environments itself — it consumes ones published elsewhere — so this simply- * surfaces the account's T3 Connect environments right after sign-in so every- * device can be connected in one go. It shows on every sign-in: sign-out- * clears the connected environments, so each new session starts from zero.- */-export function ConnectOnboardingRouteScreen() {- const navigation = useNavigation();-- // The route is deep-linkable; without cloud config the sheet would present- // empty with no chrome to dismiss it, so bail back out instead.- useEffect(() => {- if (hasCloudPublicConfig()) {- return;- }- if (navigation.canGoBack()) {- navigation.goBack();- } else {- navigation.dispatch(StackActions.replace("Home"));- }- }, [navigation]);-- return hasCloudPublicConfig() ? <ConfiguredConnectOnboardingRouteScreen /> : null;-}--function ConfiguredConnectOnboardingRouteScreen() {- const navigation = useNavigation();- const insets = useSafeAreaInsets();- const { isSignedIn, userId } = useAuth({ treatPendingAsSignedOut: false });- const { connectedEnvironments, onReconnectEnvironment } = useRemoteConnections();- const { refreshRelayEnvironments } = useConnectionController();- const { connectedCloudEnvironments } = splitEnvironmentSections({- connectedEnvironments,- cloudEnvironments: null,- });-- // Pull-to-refresh tracks its own spinner instead of discovery's refreshing- // flag, so background refreshes (e.g. the sign-in one) don't yank the- // content down.- const [isPullRefreshing, setIsPullRefreshing] = useState(false);- const handlePullRefresh = useCallback(() => {- void (async () => {- setIsPullRefreshing(true);- await refreshRelayEnvironments();- setIsPullRefreshing(false);- })();- }, [refreshRelayEnvironments]);-- const handleClose = useCallback(() => {- navigation.goBack();- }, [navigation]);-- // Persist before dismissing so a quick sign-out/sign-in cannot race ahead- // of the preference write; the write is a local secure-store update.- const handleDontShowAgain = useCallback(() => {- void (async () => {- if (userId) {- const result = await settlePromise(() => optOutOfConnectOnboarding(userId));- reportAtomCommandResult(result, { label: "connect onboarding opt-out" });- }- navigation.goBack();- })();- }, [navigation, userId]);-- return (- <View collapsable={false} className="flex-1 bg-sheet">- {Platform.OS === "android" ? (- <AndroidSheetHeader- title="Set up T3 Connect"- actions={[{ accessibilityLabel: "Close", icon: "xmark", onPress: handleClose }]}- />- ) : (- <NativeHeaderToolbar placement="right">- <NativeHeaderToolbar.Button icon="xmark" onPress={handleClose} separateBackground />- </NativeHeaderToolbar>- )}- <ScrollView- alwaysBounceVertical- contentInsetAdjustmentBehavior="automatic"- showsVerticalScrollIndicator={false}- className="flex-1"- contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}- contentContainerStyle={{- gap: 16,- paddingHorizontal: 20,- paddingTop: 16,- }}- refreshControl={- <RefreshControl refreshing={isPullRefreshing} onRefresh={handlePullRefresh} />- }- >- {isSignedIn ? (- <CloudEnvironmentRows- connectedCloudEnvironments={connectedCloudEnvironments}- onReconnectEnvironment={onReconnectEnvironment}- showHeader={false}- />- ) : (- <View collapsable={false} className="rounded-[24px] bg-card p-5">- <Text className="text-sm leading-normal text-foreground-muted">- Sign in to your T3 account to set up T3 Connect.- </Text>- </View>- )}-- {userId ? (- <Pressable- accessibilityRole="button"- hitSlop={8}- onPress={handleDontShowAgain}- className="items-center py-1 active:opacity-70"- >- <Text className="text-xs text-foreground-muted">{"Don't show this again"}</Text>- </Pressable>- ) : null}- </ScrollView>- </View>- );-}diff --git a/apps/mobile/src/features/cloud/cloudDebugLog.ts b/apps/mobile/src/features/cloud/cloudDebugLog.tsdeleted file mode 100644index 840a3db55..000000000--- a/apps/mobile/src/features/cloud/cloudDebugLog.ts+++ /dev/null@@ -1,18 +0,0 @@-export function isCloudDebugEnabled(): boolean {- return (- (typeof __DEV__ !== "undefined" && __DEV__) ||- (typeof globalThis !== "undefined" &&- (globalThis as { __T3_CLOUD_DEBUG__?: boolean }).__T3_CLOUD_DEBUG__ === true)- );-}--export function cloudDebugLog(event: string, data?: Record<string, unknown>): void {- if (!isCloudDebugEnabled()) {- return;- }- if (data) {- console.log(`[t3-cloud] ${event}`, data);- } else {- console.log(`[t3-cloud] ${event}`);- }-}diff --git a/apps/mobile/src/features/cloud/cloudEnvironmentPresentation.test.ts b/apps/mobile/src/features/cloud/cloudEnvironmentPresentation.test.tsdeleted file mode 100644index 05a34cc98..000000000--- a/apps/mobile/src/features/cloud/cloudEnvironmentPresentation.test.ts+++ /dev/null@@ -1,88 +0,0 @@-import { EnvironmentId } from "@t3tools/contracts";-import type { RelayEnvironmentStatusResponse } from "@t3tools/contracts/relay";-import { describe, expect, it } from "vite-plus/test";--import { availableCloudEnvironmentPresentation } from "./cloudEnvironmentPresentation";--function relayStatus(- status: RelayEnvironmentStatusResponse["status"],- error?: string,- traceId?: string,-): RelayEnvironmentStatusResponse {- return {- environmentId: EnvironmentId.make("environment-cloud"),- endpoint: {- httpBaseUrl: "https://cloud.example.test/",- wsBaseUrl: "wss://cloud.example.test/ws",- providerKind: "cloudflare_tunnel",- },- status,- checkedAt: "2026-06-05T16:49:11.000Z",- ...(error ? { error } : {}),- ...(traceId ? { traceId } : {}),- };-}--describe("available cloud environment presentation", () => {- it("presents an online unsaved environment as available, not connected", () => {- expect(- availableCloudEnvironmentPresentation({- isStatusPending: false,- status: relayStatus("online"),- statusError: null,- statusErrorTraceId: null,- }),- ).toEqual({- connectionError: null,- connectionErrorTraceId: null,- connectionState: "available",- statusText: "Available · Relay online",- });- });-- it("keeps relay status checks distinct from connection attempts", () => {- expect(- availableCloudEnvironmentPresentation({- isStatusPending: true,- status: null,- statusError: null,- statusErrorTraceId: null,- }),- ).toEqual({- connectionError: null,- connectionErrorTraceId: null,- connectionState: "available",- statusText: "Available · Checking relay status...",- });- });-- it("surfaces an offline relay as an error", () => {- expect(- availableCloudEnvironmentPresentation({- isStatusPending: false,- status: relayStatus("offline", "Tunnel is unavailable.", "trace-offline"),- statusError: null,- statusErrorTraceId: null,- }),- ).toEqual({- connectionError: "Tunnel is unavailable.",- connectionErrorTraceId: "trace-offline",- connectionState: "error",- statusText: "Tunnel is unavailable.",- });- });-- it("preserves trace metadata for relay request failures", () => {- expect(- availableCloudEnvironmentPresentation({- isStatusPending: false,- status: null,- statusError: "Could not get relay environment status.",- statusErrorTraceId: "trace-status",- }),- ).toMatchObject({- connectionError: "Could not get relay environment status.",- connectionErrorTraceId: "trace-status",- });- });-});diff --git a/apps/mobile/src/features/cloud/cloudEnvironmentPresentation.ts b/apps/mobile/src/features/cloud/cloudEnvironmentPresentation.tsdeleted file mode 100644index 8a734c9b9..000000000--- a/apps/mobile/src/features/cloud/cloudEnvironmentPresentation.ts+++ /dev/null@@ -1,53 +0,0 @@-import type { RelayEnvironmentStatusResponse } from "@t3tools/contracts/relay";-import { type EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";--export interface AvailableCloudEnvironmentPresentation {- readonly connectionError: string | null;- readonly connectionErrorTraceId: string | null;- readonly connectionState: EnvironmentConnectionPhase;- readonly statusText: string;-}--export function availableCloudEnvironmentPresentation(input: {- readonly isStatusPending: boolean;- readonly status: RelayEnvironmentStatusResponse | null;- readonly statusError: string | null;- readonly statusErrorTraceId: string | null;-}): AvailableCloudEnvironmentPresentation {- if (input.status?.status === "online") {- return {- connectionError: null,- connectionErrorTraceId: null,- connectionState: "available",- statusText: "Available · Relay online",- };- }-- if (input.status?.status === "offline") {- const connectionError = input.status.error ?? "Relay is offline.";- return {- connectionError,- connectionErrorTraceId: input.status.traceId ?? null,- connectionState: "error",- statusText: connectionError,- };- }-- if (input.statusError) {- return {- connectionError: input.statusError,- connectionErrorTraceId: input.statusErrorTraceId,- connectionState: "error",- statusText: input.statusError,- };- }-- return {- connectionError: null,- connectionErrorTraceId: null,- connectionState: "available",- statusText: input.isStatusPending- ? "Available · Checking relay status..."- : "Available · Relay status unknown",- };-}diff --git a/apps/mobile/src/features/cloud/connectOnboarding.ts b/apps/mobile/src/features/cloud/connectOnboarding.tsdeleted file mode 100644index 9d3944331..000000000--- a/apps/mobile/src/features/cloud/connectOnboarding.ts+++ /dev/null@@ -1,24 +0,0 @@-import { Atom } from "effect/unstable/reactivity";--import { appAtomRegistry } from "../../state/atom-registry";--// Signals RootStackLayout (inside the navigation tree) that an in-session-// sign-in just completed. Holds the account id so a sign-out between the-// request and the navigation cannot present the sheet for the wrong account.-export const connectOnboardingRequestAtom = Atom.make<string | null>(null).pipe(- Atom.keepAlive,- Atom.withLabel("mobile:connect-onboarding-request"),-);--/**- * Requests the onboarding sheet for the given account. Sign-out clears the- * connected environments, so onboarding runs on every in-session sign-in —- * each new session starts with no connected devices.- */-export function requestConnectOnboarding(accountId: string): void {- appAtomRegistry.set(connectOnboardingRequestAtom, accountId);-}--export function clearConnectOnboardingRequest(): void {- appAtomRegistry.set(connectOnboardingRequestAtom, null);-}diff --git a/apps/mobile/src/features/cloud/connectOnboardingNavigation.ts b/apps/mobile/src/features/cloud/connectOnboardingNavigation.tsdeleted file mode 100644index 5c75df80c..000000000--- a/apps/mobile/src/features/cloud/connectOnboardingNavigation.ts+++ /dev/null@@ -1,49 +0,0 @@-import { useAtomValue } from "@effect/atom-react";-import { useNavigation } from "@react-navigation/native";-import { useEffect } from "react";--import { appAtomRegistry } from "../../state/atom-registry";-import { clearConnectOnboardingRequest, connectOnboardingRequestAtom } from "./connectOnboarding";-import { isConnectOnboardingOptedOut } from "./connectOnboardingOptOut";--// Sign-in happens inside the Settings sheet; give its session-state transition-// a beat to settle before presenting another formSheet on top.-const PRESENT_ONBOARDING_DELAY_MS = 600;--/**- * Consumes the onboarding request inside the navigation tree (RootStackLayout)- * and presents the onboarding formSheet. Lives apart from connectOnboarding.ts- * so non-navigation consumers (CloudAuthProvider) do not pull- * @react-navigation into their module graph.- */-export function useConnectOnboardingNavigation(): void {- const navigation = useNavigation();- const requestedAccountId = useAtomValue(connectOnboardingRequestAtom);-- useEffect(() => {- if (requestedAccountId === null) {- return;- }- let cancelled = false;- const timer = setTimeout(() => {- void (async () => {- // A failed preference read prefers showing the sheet.- const optedOut = await isConnectOnboardingOptedOut(requestedAccountId).catch(() => false);- // The cancelled flag covers effect re-runs, but a sign-out can clear- // the request atom moments before this render commits — re-check the- // atom so a stale request never presents the sheet.- if (cancelled || appAtomRegistry.get(connectOnboardingRequestAtom) !== requestedAccountId) {- return;- }- clearConnectOnboardingRequest();- if (!optedOut) {- navigation.navigate("ConnectOnboarding");- }- })();- }, PRESENT_ONBOARDING_DELAY_MS);- return () => {- cancelled = true;- clearTimeout(timer);- };- }, [navigation, requestedAccountId]);-}diff --git a/apps/mobile/src/features/cloud/connectOnboardingOptOut.ts b/apps/mobile/src/features/cloud/connectOnboardingOptOut.tsdeleted file mode 100644index ff74863b6..000000000--- a/apps/mobile/src/features/cloud/connectOnboardingOptOut.ts+++ /dev/null@@ -1,21 +0,0 @@-import { loadPreferences, updatePreferences } from "../../persistence/imperative";--// Lives apart from connectOnboarding.ts so CloudAuthProvider (which imports-// the request signal) never pulls the persistence adapter into its-// module graph; that breaks CloudAuthProvider.test.ts suite loading.--/** Whether the account chose "Don't show this again". */-export async function isConnectOnboardingOptedOut(accountId: string): Promise<boolean> {- const preferences = await loadPreferences();- return preferences.connectOnboardingOptOutAccounts?.includes(accountId) ?? false;-}--/** Persists "Don't show this again" for the account. */-export async function optOutOfConnectOnboarding(accountId: string): Promise<void> {- await updatePreferences((current) => {- const optedOut = current.connectOnboardingOptOutAccounts ?? [];- return optedOut.includes(accountId)- ? {}- : { connectOnboardingOptOutAccounts: [...optedOut, accountId] };- });-}diff --git a/apps/mobile/src/features/cloud/dpop.test.ts b/apps/mobile/src/features/cloud/dpop.test.tsdeleted file mode 100644index 8945d148e..000000000--- a/apps/mobile/src/features/cloud/dpop.test.ts+++ /dev/null@@ -1,166 +0,0 @@-/// <reference types="node" />--import * as NodeCrypto from "node:crypto";--import { vi } from "vite-plus/test";-import { describe, expect, it } from "@effect/vitest";-import * as Crypto from "effect/Crypto";-import * as Effect from "effect/Effect";-import { verifyDpopProof } from "@t3tools/shared/dpop";--import {- createDpopProof,- generateDpopProofKeyPair,- loadOrCreateDpopProofKeyPair,- cryptoLayer,-} from "./dpop";--vi.mock("expo-crypto", () => ({- CryptoDigestAlgorithm: {- SHA1: "SHA-1",- SHA256: "SHA-256",- SHA384: "SHA-384",- SHA512: "SHA-512",- },- getRandomBytes: (byteCount: number) => new Uint8Array(NodeCrypto.randomBytes(byteCount)),- getRandomBytesAsync: (byteCount: number) =>- Promise.resolve(new Uint8Array(NodeCrypto.randomBytes(byteCount))),- digest: (algorithm: string, data: unknown) => {- if (!(data instanceof Uint8Array)) {- return Promise.reject(new TypeError("expo-crypto digest data must be a typed array."));- }- return Promise.resolve(- new Uint8Array(NodeCrypto.createHash(algorithm).update(data).digest()).buffer,- );- },-}));--const secureStore = new Map<string, string>();-vi.mock("expo-secure-store", () => ({- getItemAsync: (key: string) => Promise.resolve(secureStore.get(key) ?? null),- setItemAsync: (key: string, value: string) => {- secureStore.set(key, value);- return Promise.resolve();- },-}));--function proofIat(proof: string): number {- const payload = proof.split(".")[1];- if (!payload) {- throw new Error("Missing DPoP payload.");- }- const decoded = JSON.parse(Buffer.from(payload, "base64url").toString("utf8")) as {- readonly iat: number;- };- return decoded.iat;-}--function proofHtu(proof: string): string {- const payload = proof.split(".")[1];- if (!payload) {- throw new Error("Missing DPoP payload.");- }- const decoded = JSON.parse(Buffer.from(payload, "base64url").toString("utf8")) as {- readonly htu: string;- };- return decoded.htu;-}--describe("mobile DPoP", () => {- it.effect("passes typed-array digest input through the Expo Crypto adapter", () =>- Effect.gen(function* () {- const crypto = yield* Crypto.Crypto;- const digest = yield* crypto.digest("SHA-256", new TextEncoder().encode("typed-array"));-- expect(Buffer.from(digest).toString("hex")).toBe(- NodeCrypto.createHash("sha256").update("typed-array").digest("hex"),- );- }).pipe(Effect.provide(cryptoLayer)),- );-- it.effect("persists and reuses the installation proof key", () =>- Effect.gen(function* () {- secureStore.clear();- const first = yield* loadOrCreateDpopProofKeyPair();- const second = yield* loadOrCreateDpopProofKeyPair();-- expect(second.thumbprint).toBe(first.thumbprint);- expect(second.privateJwk).toEqual(first.privateJwk);- }).pipe(Effect.provide(cryptoLayer)),- );-- it.effect("rejects malformed persisted proof keys", () =>- Effect.gen(function* () {- secureStore.set("t3code.cloud.dpop-proof-key", `{"kty":"EC","crv":"P-256","d":42}`);-- const error = yield* loadOrCreateDpopProofKeyPair().pipe(Effect.flip);-- expect(error.message).toBe("Stored DPoP proof key is invalid.");- }).pipe(Effect.provide(cryptoLayer)),- );-- it.effect("signs connect and bootstrap proofs with the same ephemeral proof key", () =>- Effect.gen(function* () {- const proofKey = yield* generateDpopProofKeyPair();- const connect = yield* createDpopProof({- method: "POST",- url: "https://relay.example.test/v1/environments/env-1/connect",- accessToken: "clerk-token",- proofKey,- });- const bootstrap = yield* createDpopProof({- method: "POST",- url: "https://desktop.example.test/oauth/token",- proofKey,- });-- expect(connect.thumbprint).toBe(proofKey.thumbprint);- expect(bootstrap.thumbprint).toBe(proofKey.thumbprint);- expect(- verifyDpopProof({- proof: connect.proof,- method: "POST",- url: "https://relay.example.test/v1/environments/env-1/connect",- expectedThumbprint: proofKey.thumbprint,- expectedAccessToken: "clerk-token",- nowEpochSeconds: proofIat(connect.proof),- }),- ).toMatchObject({ ok: true, thumbprint: proofKey.thumbprint });- expect(- verifyDpopProof({- proof: bootstrap.proof,- method: "POST",- url: "https://desktop.example.test/oauth/token",- expectedThumbprint: proofKey.thumbprint,- nowEpochSeconds: proofIat(bootstrap.proof),- }),- ).toMatchObject({ ok: true, thumbprint: proofKey.thumbprint });- }).pipe(Effect.provide(cryptoLayer)),- );-- it.effect("signs DPoP proofs with RFC 9449 htu normalization", () =>- Effect.gen(function* () {- const proofKey = yield* generateDpopProofKeyPair();- const proof = yield* createDpopProof({- method: "POST",- url: "https://relay.example.test/v1/environments/env-1/connect?debug=1#ignored",- accessToken: "clerk-token",- proofKey,- });-- expect(proofHtu(proof.proof)).toBe(- "https://relay.example.test/v1/environments/env-1/connect",- );- expect(- verifyDpopProof({- proof: proof.proof,- method: "POST",- url: "https://relay.example.test/v1/environments/env-1/connect?debug=1#ignored",- expectedThumbprint: proofKey.thumbprint,- expectedAccessToken: "clerk-token",- nowEpochSeconds: proofIat(proof.proof),- }),- ).toMatchObject({ ok: true });- }).pipe(Effect.provide(cryptoLayer)),- );-});diff --git a/apps/mobile/src/features/cloud/dpop.ts b/apps/mobile/src/features/cloud/dpop.tsdeleted file mode 100644index eabf0dd79..000000000--- a/apps/mobile/src/features/cloud/dpop.ts+++ /dev/null@@ -1,302 +0,0 @@-import * as Clock from "effect/Clock";-import * as Crypto from "effect/Crypto";-import * as Data from "effect/Data";-import * as Effect from "effect/Effect";-import * as Encoding from "effect/Encoding";-import * as Result from "effect/Result";-import * as Schema from "effect/Schema";-import * as ExpoCrypto from "expo-crypto";-import * as SecureStore from "expo-secure-store";-import { p256 } from "@noble/curves/nist";-import { DpopPublicJwk, normalizeDpopHtu } from "@t3tools/shared/dpopCommon";-import * as Layer from "effect/Layer";--export class CloudDpopError extends Data.TaggedError("CloudDpopError")<{- readonly message: string;- readonly cause?: unknown;-}> {}--function cloudDpopError(message: string) {- return (cause: unknown) => new CloudDpopError({ message, cause });-}--const DpopPrivateJwkSchema = Schema.Struct({- ...DpopPublicJwk.fields,- d: Schema.String,-});--const DpopPrivateJwkJson = Schema.fromJsonString(DpopPrivateJwkSchema);-const decodeDpopPrivateJwkJson = Schema.decodeUnknownEffect(DpopPrivateJwkJson);-const encodeDpopPrivateJwkJson = Schema.encodeEffect(DpopPrivateJwkJson);--const DpopJwtHeaderJson = Schema.fromJsonString(- Schema.Struct({- typ: Schema.Literal("dpop+jwt"),- alg: Schema.Literal("ES256"),- jwk: DpopPublicJwk,- }),-);--const DpopJwtPayloadJson = Schema.fromJsonString(- Schema.Struct({- htm: Schema.String,- htu: Schema.String,- jti: Schema.String,- iat: Schema.Int,- ath: Schema.optionalKey(Schema.String),- }),-);--const encodeDpopJwtHeaderJson = Schema.encodeEffect(DpopJwtHeaderJson);-const encodeDpopJwtPayloadJson = Schema.encodeEffect(DpopJwtPayloadJson);--function toExpoDigestAlgorithm(- algorithm: Crypto.DigestAlgorithm,-): ExpoCrypto.CryptoDigestAlgorithm {- switch (algorithm) {- case "SHA-1":- return ExpoCrypto.CryptoDigestAlgorithm.SHA1;- case "SHA-256":- return ExpoCrypto.CryptoDigestAlgorithm.SHA256;- case "SHA-384":- return ExpoCrypto.CryptoDigestAlgorithm.SHA384;- case "SHA-512":- return ExpoCrypto.CryptoDigestAlgorithm.SHA512;- }-}--export const cryptoLayer = Layer.succeed(- Crypto.Crypto,- Crypto.make({- randomBytes: ExpoCrypto.getRandomBytes,- digest: (algorithm, data) =>- Effect.promise(async () => {- const input = new Uint8Array(data.length);- input.set(data);- return new Uint8Array(await ExpoCrypto.digest(toExpoDigestAlgorithm(algorithm), input));- }),- }),-);--type DpopPrivateJwk = typeof DpopPrivateJwkSchema.Type;--export interface DpopProofKeyPair {- readonly privateJwk: DpopPrivateJwk;- readonly publicJwk: DpopPublicJwk;- readonly thumbprint: string;-}--const DPOP_PROOF_KEY_STORAGE_KEY = "t3code.cloud.dpop-proof-key";--function base64UrlToBytes(value: string): Uint8Array {- return Result.getOrThrow(Encoding.decodeBase64Url(value));-}--function sha256Digest(- data: Uint8Array,- message: string,-): Effect.Effect<Uint8Array, CloudDpopError, Crypto.Crypto> {- return Crypto.Crypto.pipe(- Effect.flatMap((crypto) => crypto.digest("SHA-256", data)),- Effect.mapError(cloudDpopError(message)),- );-}--function base64UrlSha256(- data: Uint8Array,- message: string,-): Effect.Effect<string, CloudDpopError, Crypto.Crypto> {- return sha256Digest(data, message).pipe(Effect.map(Encoding.encodeBase64Url));-}--function dpopThumbprintInput(jwk: DpopPublicJwk): string {- return JSON.stringify({- crv: jwk.crv,- kty: jwk.kty,- x: jwk.x,- y: jwk.y,- });-}--function computeDpopJwkThumbprintEffect(- jwk: DpopPublicJwk,-): Effect.Effect<string, CloudDpopError, Crypto.Crypto> {- return base64UrlSha256(- new TextEncoder().encode(dpopThumbprintInput(jwk)),- "Could not hash the DPoP public key thumbprint.",- );-}--function computeDpopAccessTokenHashEffect(- accessToken: string,-): Effect.Effect<string, CloudDpopError, Crypto.Crypto> {- return base64UrlSha256(- new TextEncoder().encode(accessToken),- "Could not hash the DPoP access token.",- );-}--function secureRandomBytes(- byteCount: number,- message: string,-): Effect.Effect<Uint8Array, CloudDpopError, Crypto.Crypto> {- return Crypto.Crypto.pipe(- Effect.flatMap((crypto) => crypto.randomBytes(byteCount)),- Effect.mapError(cloudDpopError(message)),- );-}--function publicJwkFromUncompressedPublicKey(publicKey: Uint8Array): DpopPublicJwk {- if (publicKey.length !== 65 || publicKey[0] !== 0x04) {- throw new Error("Generated DPoP public key is not an uncompressed P-256 point.");- }- return {- kty: "EC",- crv: "P-256",- x: Encoding.encodeBase64Url(publicKey.slice(1, 33)),- y: Encoding.encodeBase64Url(publicKey.slice(33, 65)),- };-}--function privateJwkFromPrivateKey(- privateKey: Uint8Array,- publicJwk: DpopPublicJwk,-): DpopPrivateJwk {- return { ...publicJwk, d: Encoding.encodeBase64Url(privateKey) };-}--export function generateDpopProofKeyPair(): Effect.Effect<- DpopProofKeyPair,- CloudDpopError,- Crypto.Crypto-> {- return Effect.gen(function* () {- let privateKey: Uint8Array;- do {- privateKey = yield* secureRandomBytes(- p256.CURVE.nByteLength,- "Could not generate DPoP key pair randomness.",- );- } while (!p256.utils.isValidPrivateKey(privateKey));- const publicJwk = yield* Effect.try({- try: () => publicJwkFromUncompressedPublicKey(p256.getPublicKey(privateKey, false)),- catch: cloudDpopError("Generated DPoP public key is invalid."),- });- const thumbprint = yield* computeDpopJwkThumbprintEffect(publicJwk);- return {- privateJwk: privateJwkFromPrivateKey(privateKey, publicJwk),- publicJwk,- thumbprint,- };- });-}--export function loadOrCreateDpopProofKeyPair(): Effect.Effect<- DpopProofKeyPair,- CloudDpopError,- Crypto.Crypto-> {- return Effect.gen(function* () {- const stored = yield* Effect.tryPromise({- try: () => SecureStore.getItemAsync(DPOP_PROOF_KEY_STORAGE_KEY),- catch: cloudDpopError("Could not read the DPoP proof key."),- });- if (stored) {- const storedPrivateJwk = yield* decodeDpopPrivateJwkJson(stored).pipe(- Effect.mapError(cloudDpopError("Stored DPoP proof key is invalid.")),- );- const restored = yield* Effect.try({- try: () => {- const privateKey = base64UrlToBytes(storedPrivateJwk.d);- const publicJwk = publicJwkFromUncompressedPublicKey(- p256.getPublicKey(privateKey, false),- );- if (publicJwk.x !== storedPrivateJwk.x || publicJwk.y !== storedPrivateJwk.y) {- throw new Error("Stored DPoP key does not match its public key.");- }- return { privateJwk: storedPrivateJwk, publicJwk };- },- catch: cloudDpopError("Stored DPoP proof key is invalid."),- });- const thumbprint = yield* computeDpopJwkThumbprintEffect(restored.publicJwk);- return {- ...restored,- thumbprint,- };- }- const generated = yield* generateDpopProofKeyPair();- const encodedPrivateJwk = yield* encodeDpopPrivateJwkJson(generated.privateJwk).pipe(- Effect.mapError(cloudDpopError("Could not encode the DPoP proof key.")),- );- yield* Effect.tryPromise({- try: () => SecureStore.setItemAsync(DPOP_PROOF_KEY_STORAGE_KEY, encodedPrivateJwk),- catch: cloudDpopError("Could not store the DPoP proof key."),- });- return generated;- });-}--function normalizeHtu(url: string): Effect.Effect<string, CloudDpopError> {- const normalized = normalizeDpopHtu(url);- return normalized- ? Effect.succeed(normalized)- : Effect.fail(new CloudDpopError({ message: "DPoP URL is invalid." }));-}--export function createDpopProof(input: {- readonly method: string;- readonly url: string;- readonly accessToken?: string;- readonly proofKey?: DpopProofKeyPair;-}): Effect.Effect<- { readonly proof: string; readonly thumbprint: string },- CloudDpopError,- Crypto.Crypto-> {- return Effect.gen(function* () {- const keyPair = input.proofKey ?? (yield* generateDpopProofKeyPair());- const privateKey = yield* Effect.try({- try: () => base64UrlToBytes(keyPair.privateJwk.d),- catch: cloudDpopError("Could not import DPoP private key."),- });- const nowMs = yield* Clock.currentTimeMillis;- const jti = yield* Crypto.Crypto.pipe(- Effect.flatMap((crypto) => crypto.randomUUIDv4),- Effect.mapError(cloudDpopError("Could not generate DPoP proof identifier.")),- );- const htu = yield* normalizeHtu(input.url);- const header = yield* encodeDpopJwtHeaderJson({- typ: "dpop+jwt",- alg: "ES256",- jwk: keyPair.publicJwk,- }).pipe(- Effect.map(Encoding.encodeBase64Url),- Effect.mapError(cloudDpopError("Could not encode DPoP proof header.")),- );- const ath = input.accessToken- ? yield* computeDpopAccessTokenHashEffect(input.accessToken)- : null;- const payload = yield* encodeDpopJwtPayloadJson({- htm: input.method.toUpperCase(),- htu,- jti,- iat: Math.floor(nowMs / 1_000),- ...(ath ? { ath } : {}),- }).pipe(- Effect.map(Encoding.encodeBase64Url),- Effect.mapError(cloudDpopError("Could not encode DPoP proof payload.")),- );- const signatureInputHash = yield* sha256Digest(- new TextEncoder().encode(`${header}.${payload}`),- "Could not hash DPoP signing input.",- );- const signature = yield* Effect.try({- try: () => p256.sign(signatureInputHash, privateKey, { prehash: false }).toCompactRawBytes(),- catch: cloudDpopError("Could not sign DPoP proof."),- });- return {- proof: `${header}.${payload}.${Encoding.encodeBase64Url(signature)}`,- thumbprint: keyPair.thumbprint,- };- });-}diff --git a/apps/mobile/src/features/cloud/linkEnvironment.test.ts b/apps/mobile/src/features/cloud/linkEnvironment.test.tsdeleted file mode 100644index 4d7b08641..000000000--- a/apps/mobile/src/features/cloud/linkEnvironment.test.ts+++ /dev/null@@ -1,1188 +0,0 @@-import { beforeEach, vi } from "vite-plus/test";-import { describe, expect, it } from "@effect/vitest";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";-import { EnvironmentId } from "@t3tools/contracts";-import { RelayMobileClientId } from "@t3tools/contracts/relay";-import { ManagedRelay } from "@t3tools/client-runtime/relay";-import { remoteHttpClientLayer } from "@t3tools/client-runtime/rpc";-import { HttpClient } from "effect/unstable/http";-import { MobilePreferencesStore } from "../../persistence/mobile-preferences";-import { MobileStorage } from "../../persistence/mobile-storage";--import {- cloudEnvironmentsPendingStatus,- linkEnvironmentToCloud,- linkEnvironmentToCloudWithPreference,- connectCloudEnvironment,- listCloudEnvironments,- listCloudEnvironmentsWithStatus,- normalizeRelayBaseUrl,- refreshCloudEnvironmentConnection,-} from "./linkEnvironment";--vi.mock("expo-constants", () => ({- default: {- expoConfig: {- extra: {- relay: {- url: "https://relay.example.test",- },- },- },- },-}));--vi.mock("expo-device", () => ({- osVersion: "18.4.1",- modelName: "iPhone 15 Pro",-}));--vi.mock("react-native", () => ({- Platform: {- OS: "ios",- },-}));--vi.mock("expo-secure-store", () => ({- deleteItemAsync: vi.fn(),- getItemAsync: vi.fn(),- setItemAsync: vi.fn(),-}));--const loadPreferences = vi.fn(() => Effect.succeed({}));--const savedConnection = {- environmentId: EnvironmentId.make("env-1"),- environmentLabel: "Desktop",- pairingUrl: "https://desktop.example.test/",- displayUrl: "https://desktop.example.test/",- httpBaseUrl: "https://desktop.example.test/",- wsBaseUrl: "wss://desktop.example.test/ws",- bearerToken: "local-bearer",-};--const stableClerkToken = "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJzdWIiOiJ1c2VyXzEyMyJ9.test";--const createProofMock = vi.fn(- (input: { readonly method: string; readonly url: string; readonly accessToken?: string }) =>- Effect.succeed(`dpop:${input.method}:${input.url}`),-);-const testDpopSignerLayer = Layer.succeed(- ManagedRelay.ManagedRelayDpopSigner,- ManagedRelay.ManagedRelayDpopSigner.of({- thumbprint: Effect.succeed("client-proof-key-thumbprint"),- createProof: (input) => createProofMock(input),- }),-);--function cloudClientLayer() {- const httpClientLayer = remoteHttpClientLayer((input, init) => globalThis.fetch(input, init));- return Layer.mergeAll(- httpClientLayer,- Layer.succeed(- MobilePreferencesStore,- MobilePreferencesStore.of({- load: loadPreferences(),- savePatch: (patch) => Effect.succeed(patch),- update: () => Effect.succeed({}),- }),- ),- Layer.succeed(- MobileStorage,- MobileStorage.of({- loadSavedConnections: Effect.succeed([]),- saveConnection: () => Effect.void,- clearSavedConnection: () => Effect.void,- loadOrCreateAgentAwarenessDeviceId: Effect.succeed("device-1"),- loadAgentAwarenessDeviceId: Effect.succeed("device-1"),- loadAgentAwarenessRegistrationRecord: Effect.succeed(null),- saveAgentAwarenessRegistrationRecord: () => Effect.void,- clearAgentAwarenessRegistrationRecord: Effect.void,- loadRecentThreadShortcuts: Effect.succeed([]),- saveRecentThreadShortcuts: () => Effect.void,- }),- ),- ManagedRelay.layer({- relayUrl: "https://relay.example.test",- clientId: RelayMobileClientId,- }).pipe(Layer.provideMerge(testDpopSignerLayer), Layer.provide(httpClientLayer)),- );-}--const withCloudServices = <A, E>(- effect: Effect.Effect<- A,- E,- | HttpClient.HttpClient- | ManagedRelay.ManagedRelayClient- | ManagedRelay.ManagedRelayDpopSigner- | MobilePreferencesStore- | MobileStorage- >,-) => effect.pipe(Effect.provide(cloudClientLayer()));--function validLinkProof() {- return "signed-environment-link-jwt";-}--function validLinkResponse(environmentId = "env-1") {- return {- ok: true,- environmentId,- endpoint: {- httpBaseUrl: "https://managed.example.test/",- wsBaseUrl: "wss://managed.example.test/ws",- providerKind: "cloudflare_tunnel",- },- endpointRuntime: {- providerKind: "cloudflare_tunnel",- connectorToken: "connector-token",- },- relayIssuer: "https://relay.example.test",- cloudUserId: "user_123",- environmentCredential: "environment-credential",- cloudMintPublicKey: "cloud-mint-public-key",- };-}--function validLinkChallengeResponse() {- return {- challenge: "link-challenge",- expiresAt: "2026-05-25T00:05:00.000Z",- };-}--function requestBodyText(body: BodyInit | null | undefined): string {- return body instanceof Uint8Array ? new TextDecoder().decode(body) : String(body ?? "");-}--function validDpopAccessTokenResponse(scope = "environment:status environment:connect") {- return {- access_token: "relay-dpop-token",- issued_token_type: "urn:ietf:params:oauth:token-type:access_token",- token_type: "DPoP",- expires_in: 300,- scope,- };-}--function listedEnvironment(environmentId: string) {- return {- environmentId: EnvironmentId.make(environmentId),- label: "Desktop",- endpoint: {- httpBaseUrl: `https://${environmentId}.example.test/`,- wsBaseUrl: `wss://${environmentId}.example.test/ws`,- providerKind: "cloudflare_tunnel" as const,- },- linkedAt: "2026-05-25T00:00:00.000Z",- };-}--describe("mobile cloud link environment client", () => {- beforeEach(() => {- vi.restoreAllMocks();- createProofMock.mockClear();- loadPreferences.mockClear();- });-- it("normalizes configured relay base URLs before building DPoP-bound requests", () => {- expect(normalizeRelayBaseUrl(" https://relay.example.test/// ")).toBe(- "https://relay.example.test",- );- expect(normalizeRelayBaseUrl(" ")).toBeNull();- });-- it("makes linked environments visible while their status is still loading", () => {- expect(cloudEnvironmentsPendingStatus([listedEnvironment("env-1")])).toMatchObject([- {- environment: { environmentId: "env-1", label: "Desktop" },- status: null,- statusError: "Checking status...",- },- ]);- });-- it.effect("decodes relay environment list responses before returning records", () =>- Effect.gen(function* () {- vi.stubGlobal(- "fetch",- vi.fn(() =>- Promise.resolve(- Response.json({- environments: [- {- environmentId: "env-1",- label: "Desktop",- endpoint: {- httpBaseUrl: "https://desktop.example.test/",- wsBaseUrl: "wss://desktop.example.test/ws",- providerKind: "cloudflare_tunnel",- },- linkedAt: "2026-05-25T00:00:00.000Z",- },- ],- }),- ),- ),- );-- const records = yield* withCloudServices(- listCloudEnvironments({ clerkToken: "clerk-token" }),- );- expect(records).toEqual([- {- environmentId: "env-1",- label: "Desktop",- endpoint: {- httpBaseUrl: "https://desktop.example.test/",- wsBaseUrl: "wss://desktop.example.test/ws",- providerKind: "cloudflare_tunnel",- },- linkedAt: "2026-05-25T00:00:00.000Z",- },- ]);- }),- );-- it.effect("rejects malformed relay environment list responses", () =>- Effect.gen(function* () {- vi.stubGlobal(- "fetch",- vi.fn(() =>- Promise.resolve(- Response.json({- environments: [- {- environmentId: "env-1",- label: "Desktop",- endpoint: {- httpBaseUrl: "",- wsBaseUrl: "wss://desktop.example.test/ws",- providerKind: "cloudflare_tunnel",- },- linkedAt: "2026-05-25T00:00:00.000Z",- },- ],- }),- ),- ),- );-- const error = yield* withCloudServices(- listCloudEnvironments({ clerkToken: "clerk-token" }),- ).pipe(Effect.flip);- expect(error).toMatchObject({- _tag: "CloudEnvironmentLinkError",- message: "https://relay.example.test/v1/environments failed",- });- }),- );-- it.effect("loads signed status for each advertised cloud environment", () =>- Effect.gen(function* () {- const fetchMock = vi.fn((url: string | URL, _init?: RequestInit) => {- if (String(url) === "https://relay.example.test/v1/environments") {- return Promise.resolve(- Response.json({- environments: [- {- environmentId: "env-1",- label: "Desktop",- endpoint: {- httpBaseUrl: "https://desktop.example.test/",- wsBaseUrl: "wss://desktop.example.test/ws",- providerKind: "cloudflare_tunnel",- },- linkedAt: "2026-05-25T00:00:00.000Z",- },- ],- }),- );- }- if (String(url) === "https://relay.example.test/v1/client/dpop-token") {- return Promise.resolve(Response.json(validDpopAccessTokenResponse()));- }- expect(String(url)).toBe("https://relay.example.test/v1/environments/env-1/status");- return Promise.resolve(- Response.json({- environmentId: "env-1",- endpoint: {- httpBaseUrl: "https://desktop.example.test/",- wsBaseUrl: "wss://desktop.example.test/ws",- providerKind: "cloudflare_tunnel",- },- status: "online",- checkedAt: "2026-05-25T00:01:00.000Z",- descriptor: {- environmentId: "env-1",- label: "Desktop",- platform: { os: "darwin", arch: "arm64" },- serverVersion: "0.0.0-test",- capabilities: { repositoryIdentity: true },- },- }),- );- });- vi.stubGlobal("fetch", fetchMock);-- const records = yield* withCloudServices(- listCloudEnvironmentsWithStatus({ clerkToken: "clerk-token" }),- );- expect(records).toMatchObject([- {- environment: {- environmentId: "env-1",- label: "Desktop",- },- status: {- environmentId: "env-1",- status: "online",- checkedAt: "2026-05-25T00:01:00.000Z",- },- statusError: null,- },- ]);- expect(String(fetchMock.mock.calls[2]?.[0])).toBe(- "https://relay.example.test/v1/environments/env-1/status",- );- expect(fetchMock.mock.calls[2]?.[1]?.method).toBe("POST");- const statusHeaders = new Headers(fetchMock.mock.calls[2]?.[1]?.headers);- expect(statusHeaders.get("authorization")).toBe("DPoP relay-dpop-token");- expect(statusHeaders.get("dpop")).toBe(- "dpop:POST:https://relay.example.test/v1/environments/env-1/status",- );- expect(createProofMock).toHaveBeenCalledWith({- method: "POST",- url: "https://relay.example.test/v1/environments/env-1/status",- accessToken: "relay-dpop-token",- });- }),- );-- it.effect("reuses one valid DPoP access token while probing multiple environment statuses", () =>- Effect.gen(function* () {- const fetchMock = vi.fn((url: string | URL, _init?: RequestInit) => {- if (String(url).endsWith("/v1/environments")) {- return Promise.resolve(- Response.json({- environments: [listedEnvironment("env-1"), listedEnvironment("env-2")],- }),- );- }- if (String(url).endsWith("/v1/client/dpop-token")) {- return Promise.resolve(Response.json(validDpopAccessTokenResponse()));- }- const environmentId = String(url).includes("/env-1/") ? "env-1" : "env-2";- return Promise.resolve(- Response.json({- environmentId,- endpoint: listedEnvironment(environmentId).endpoint,- status: "online",- checkedAt: "2026-05-25T00:01:00.000Z",- descriptor: {- environmentId,- label: "Desktop",- platform: { os: "darwin", arch: "arm64" },- serverVersion: "0.0.0-test",- capabilities: { repositoryIdentity: true },- },- }),- );- });- vi.stubGlobal("fetch", fetchMock);-- yield* withCloudServices(listCloudEnvironmentsWithStatus({ clerkToken: stableClerkToken }));-- expect(- fetchMock.mock.calls.filter(([url]) => String(url).endsWith("/v1/client/dpop-token")),- ).toHaveLength(1);- }),- );-- it.effect("reuses the status-and-connect token when connecting from the cloud list", () =>- Effect.gen(function* () {- const fetchMock = vi.fn((url: string | URL, _init?: RequestInit) => {- if (String(url).endsWith("/v1/environments")) {- return Promise.resolve(- Response.json({- environments: [listedEnvironment("env-1")],- }),- );- }- if (String(url).endsWith("/v1/client/dpop-token")) {- return Promise.resolve(Response.json(validDpopAccessTokenResponse()));- }- if (String(url).endsWith("/status")) {- return Promise.resolve(- Response.json({- environmentId: "env-1",- endpoint: listedEnvironment("env-1").endpoint,- status: "online",- checkedAt: "2026-05-25T00:01:00.000Z",- descriptor: {- environmentId: "env-1",- label: "Desktop",- platform: { os: "darwin", arch: "arm64" },- serverVersion: "0.0.0-test",- capabilities: { repositoryIdentity: true },- },- }),- );- }- if (String(url).endsWith("/connect")) {- return Promise.resolve(- Response.json({- environmentId: "env-1",- endpoint: listedEnvironment("env-1").endpoint,- credential: "one-time-cloud-credential",- expiresAt: "2026-05-25T00:05:00.000Z",- }),- );- }- if (String(url).endsWith("/.well-known/t3/environment")) {- return Promise.resolve(- Response.json({- environmentId: "env-1",- label: "Desktop",- platform: { os: "darwin", arch: "arm64" },- serverVersion: "0.0.0-test",- capabilities: { repositoryIdentity: true },- }),- );- }- return Promise.resolve(- Response.json({- access_token: "environment-dpop-token",- issued_token_type: "urn:ietf:params:oauth:token-type:access_token",- token_type: "DPoP",- expires_in: 3600,- scope: "orchestration:read orchestration:operate terminal:operate review:write",- }),- );- });- vi.stubGlobal("fetch", fetchMock);-- yield* withCloudServices(- Effect.gen(function* () {- const records = yield* listCloudEnvironmentsWithStatus({- clerkToken: stableClerkToken,- });- yield* connectCloudEnvironment({- clerkToken: stableClerkToken,- environment: records[0]!.environment,- });- }),- );-- expect(- fetchMock.mock.calls.filter(([url]) => String(url).endsWith("/v1/client/dpop-token")),- ).toHaveLength(1);- const exchangeRequest = fetchMock.mock.calls.find(([url]) =>- String(url).endsWith("/v1/client/dpop-token"),- )?.[1];- expect(new URLSearchParams(requestBodyText(exchangeRequest?.body)).get("scope")).toBe(- "environment:status environment:connect",- );- const environmentTokenRequest = fetchMock.mock.calls.find(([url]) =>- String(url).endsWith("/oauth/token"),- )?.[1];- const environmentTokenBody = new URLSearchParams(- requestBodyText(environmentTokenRequest?.body),- );- expect(environmentTokenBody.get("client_label")).toBe("T3 Code Mobile");- expect(environmentTokenBody.get("client_device_type")).toBe("mobile");- expect(environmentTokenBody.get("client_os")).toBe("iOS");- }),- );-- it.effect("keeps advertised environments visible when status probing fails", () =>- Effect.gen(function* () {- vi.stubGlobal(- "fetch",- vi.fn((url: string | URL) => {- if (String(url) === "https://relay.example.test/v1/environments") {- return Promise.resolve(- Response.json({- environments: [- {- environmentId: "env-1",- label: "Desktop",- endpoint: {- httpBaseUrl: "https://desktop.example.test/",- wsBaseUrl: "wss://desktop.example.test/ws",- providerKind: "cloudflare_tunnel",- },- linkedAt: "2026-05-25T00:00:00.000Z",- },- ],- }),- );- }- if (String(url) === "https://relay.example.test/v1/client/dpop-token") {- return Promise.resolve(Response.json(validDpopAccessTokenResponse()));- }- return Promise.resolve(Response.json({ error: "offline" }, { status: 503 }));- }),- );-- const records = yield* withCloudServices(- listCloudEnvironmentsWithStatus({ clerkToken: "clerk-token" }),- );- expect(records).toMatchObject([- {- environment: {- environmentId: "env-1",- label: "Desktop",- },- status: null,- statusError: "https://relay.example.test/v1/environments/env-1/status failed",- },- ]);- }),- );-- it.effect("rejects status responses for a different advertised environment", () =>- Effect.gen(function* () {- vi.stubGlobal(- "fetch",- vi.fn((url: string | URL) => {- if (String(url) === "https://relay.example.test/v1/environments") {- return Promise.resolve(- Response.json({- environments: [- {- environmentId: "env-1",- label: "Desktop",- endpoint: {- httpBaseUrl: "https://desktop.example.test/",- wsBaseUrl: "wss://desktop.example.test/ws",- providerKind: "cloudflare_tunnel",- },- linkedAt: "2026-05-25T00:00:00.000Z",- },- ],- }),- );- }- if (String(url) === "https://relay.example.test/v1/client/dpop-token") {- return Promise.resolve(Response.json(validDpopAccessTokenResponse()));- }- return Promise.resolve(- Response.json({- environmentId: "env-other",- endpoint: {- httpBaseUrl: "https://desktop.example.test/",- wsBaseUrl: "wss://desktop.example.test/ws",- providerKind: "cloudflare_tunnel",- },- status: "online",- checkedAt: "2026-05-25T00:01:00.000Z",- descriptor: {- environmentId: "env-other",- label: "Other Desktop",- platform: { os: "darwin", arch: "arm64" },- serverVersion: "0.0.0-test",- capabilities: { repositoryIdentity: true },- },- }),- );- }),- );-- const records = yield* withCloudServices(- listCloudEnvironmentsWithStatus({ clerkToken: "clerk-token" }),- );- expect(records).toMatchObject([- {- environment: {- environmentId: "env-1",- label: "Desktop",- },- status: null,- statusError: "Relay returned status for a different environment.",- },- ]);- }),- );-- it.effect(- "rejects relay link credentials for a different environment before persisting relay config",- () =>- Effect.gen(function* () {- const fetchMock = vi.fn((url: string | URL) => {- if (String(url).endsWith("/v1/client/environment-link-challenges")) {- return Promise.resolve(Response.json(validLinkChallengeResponse()));- }- if (String(url).endsWith("/api/connect/link-proof")) {- return Promise.resolve(Response.json(validLinkProof()));- }- return Promise.resolve(Response.json(validLinkResponse("env-other")));- });- vi.stubGlobal("fetch", fetchMock);-- const error = yield* withCloudServices(- linkEnvironmentToCloud({- clerkToken: "clerk-token",- connection: savedConnection,- }),- ).pipe(Effect.flip);- expect(error).toMatchObject({- _tag: "CloudEnvironmentLinkError",- message: "Relay returned credentials for a different environment.",- });- expect(fetchMock).toHaveBeenCalledTimes(3);- }),- );-- it.effect("preserves typed local environment failures while obtaining a link proof", () =>- Effect.gen(function* () {- const fetchMock = vi.fn((url: string | URL) => {- if (String(url).endsWith("/v1/client/environment-link-challenges")) {- return Promise.resolve(Response.json(validLinkChallengeResponse()));- }- return Promise.resolve(- Response.json(- {- _tag: "EnvironmentHttpUnauthorizedError",- message: "Invalid environment bearer session.",- },- { status: 401 },- ),- );- });- vi.stubGlobal("fetch", fetchMock);-- const error = yield* withCloudServices(- linkEnvironmentToCloud({- clerkToken: "clerk-token",- connection: savedConnection,- }),- ).pipe(Effect.flip);- expect(error._tag).toBe("CloudEnvironmentLinkError");- expect(error.message).toBe(- "Could not obtain environment link proof: Invalid environment bearer session.",- );- expect(fetchMock).toHaveBeenCalledTimes(2);- }),- );-- it.effect("preserves typed relay error bodies while linking environments", () =>- Effect.gen(function* () {- const fetchMock = vi.fn((url: string | URL) => {- if (String(url).endsWith("/v1/client/environment-link-challenges")) {- return Promise.resolve(Response.json(validLinkChallengeResponse()));- }- if (String(url).endsWith("/api/connect/link-proof")) {- return Promise.resolve(Response.json(validLinkProof()));- }- return Promise.resolve(- Response.json(- {- _tag: "RelayEnvironmentLinkProofInvalidError",- code: "environment_link_proof_invalid",- reason: "origin_not_allowed",- traceId: "trace-test",- },- { status: 400 },- ),- );- });- vi.stubGlobal("fetch", fetchMock);-- const error = yield* withCloudServices(- linkEnvironmentToCloud({- clerkToken: "clerk-token",- connection: savedConnection,- }),- ).pipe(Effect.flip);- expect(error).toMatchObject({- _tag: "CloudEnvironmentLinkError",- message:- "https://relay.example.test/v1/client/environment-links failed: Relay rejected the environment link proof (origin_not_allowed).",- traceId: "trace-test",- });- expect(fetchMock).toHaveBeenCalledTimes(3);- }),- );-- it.effect("rejects relay link credentials for a different managed endpoint provider", () =>- Effect.gen(function* () {- const fetchMock = vi.fn((url: string | URL) => {- if (String(url).endsWith("/v1/client/environment-link-challenges")) {- return Promise.resolve(Response.json(validLinkChallengeResponse()));- }- if (String(url).endsWith("/api/connect/link-proof")) {- return Promise.resolve(Response.json(validLinkProof()));- }- return Promise.resolve(- Response.json({- ...validLinkResponse(),- endpoint: {- ...validLinkResponse().endpoint,- providerKind: "manual",- },- }),- );- });- vi.stubGlobal("fetch", fetchMock);-- const error = yield* withCloudServices(- linkEnvironmentToCloud({- clerkToken: "clerk-token",- connection: savedConnection,- }),- ).pipe(Effect.flip);- expect(error).toMatchObject({- _tag: "CloudEnvironmentLinkError",- message: "Relay returned credentials for a different endpoint provider.",- });- expect(fetchMock).toHaveBeenCalledTimes(3);- }),- );-- it.effect("preserves disabled Live Activity preferences when linking an environment", () =>- Effect.gen(function* () {- loadPreferences.mockReturnValueOnce(Effect.succeed({ liveActivitiesEnabled: false }));- const bodies: Array<unknown> = [];- const fetchMock = vi.fn((url: string | URL, init?: RequestInit) => {- if (init?.body) {- // @effect-diagnostics-next-line preferSchemaOverJson:off- bodies.push(JSON.parse(requestBodyText(init.body)));- }- if (String(url).endsWith("/v1/client/environment-link-challenges")) {- return Promise.resolve(Response.json(validLinkChallengeResponse()));- }- if (String(url).endsWith("/api/connect/link-proof")) {- return Promise.resolve(Response.json(validLinkProof()));- }- if (String(url).endsWith("/v1/client/environment-links")) {- return Promise.resolve(Response.json(validLinkResponse()));- }- return Promise.resolve(- Response.json({ ok: true, endpointRuntimeStatus: { status: "configured" } }),- );- });- vi.stubGlobal("fetch", fetchMock);-- yield* withCloudServices(- linkEnvironmentToCloud({- clerkToken: "clerk-token",- connection: savedConnection,- }),- );-- expect(bodies[1]).toMatchObject({- endpoint: {- httpBaseUrl: "https://desktop.example.test/",- wsBaseUrl: "wss://desktop.example.test/ws",- providerKind: "cloudflare_tunnel",- },- origin: {- localHttpHost: "127.0.0.1",- localHttpPort: 443,- },- });- expect(bodies[2]).toMatchObject({- deviceId: "device-1",- notificationsEnabled: true,- liveActivitiesEnabled: false,- managedTunnelsEnabled: true,- });- expect(bodies[3]).toMatchObject({- cloudUserId: "user_123",- environmentCredential: "environment-credential",- });- }),- );-- it.effect("uses an explicit Live Activity preference when persisted state is unavailable", () =>- Effect.gen(function* () {- loadPreferences.mockReturnValueOnce(Effect.die("persisted preferences must not be read"));- const bodies: Array<Record<string, unknown>> = [];- const fetchMock = vi.fn((url: string | URL, init?: RequestInit) => {- if (init?.body) {- // @effect-diagnostics-next-line preferSchemaOverJson:off- bodies.push(JSON.parse(requestBodyText(init.body)) as Record<string, unknown>);- }- if (String(url).endsWith("/v1/client/environment-link-challenges")) {- return Promise.resolve(Response.json(validLinkChallengeResponse()));- }- if (String(url).endsWith("/api/connect/link-proof")) {- return Promise.resolve(Response.json(validLinkProof()));- }- if (String(url).endsWith("/v1/client/environment-links")) {- return Promise.resolve(Response.json(validLinkResponse()));- }- return Promise.resolve(- Response.json({ ok: true, endpointRuntimeStatus: { status: "configured" } }),- );- });- vi.stubGlobal("fetch", fetchMock);-- yield* withCloudServices(- linkEnvironmentToCloudWithPreference({- clerkToken: "clerk-token",- connection: savedConnection,- liveActivitiesEnabled: true,- }),- );-- expect(bodies.filter((body) => "liveActivitiesEnabled" in body)).toEqual([- expect.objectContaining({ liveActivitiesEnabled: true }),- expect.objectContaining({ liveActivitiesEnabled: true }),- ]);- }),- );-- it.effect(- "does not persist cloud connect bootstrap credentials in saved connection records",- () =>- Effect.gen(function* () {- let connectRequestBody = "";- const fetchMock = vi.fn((url: string | URL, init?: RequestInit) => {- if (String(url).endsWith("/v1/client/dpop-token")) {- return Promise.resolve(- Response.json(validDpopAccessTokenResponse("environment:connect")),- );- }- if (String(url).endsWith("/.well-known/t3/environment")) {- return Promise.resolve(- Response.json({- environmentId: "env-1",- label: "Desktop",- platform: { os: "darwin", arch: "arm64" },- serverVersion: "0.0.0-test",- capabilities: { repositoryIdentity: true },- }),- );- }- if (String(url).endsWith("/oauth/token")) {- return Promise.resolve(- Response.json({- access_token: "environment-dpop-token",- issued_token_type: "urn:ietf:params:oauth:token-type:access_token",- token_type: "DPoP",- expires_in: 3600,- scope: "orchestration:read orchestration:operate terminal:operate review:write",- }),- );- }- connectRequestBody = requestBodyText(init?.body);- return Promise.resolve(- Response.json({- environmentId: "env-1",- endpoint: {- httpBaseUrl: "https://desktop.example.test/",- wsBaseUrl: "wss://desktop.example.test/ws",- providerKind: "cloudflare_tunnel",- },- credential: "one-time-cloud-credential",- expiresAt: "2026-05-25T00:05:00.000Z",- }),- );- });- vi.stubGlobal("fetch", fetchMock);-- const connection = yield* withCloudServices(- connectCloudEnvironment({- clerkToken: "clerk-token",- environment: {- environmentId: EnvironmentId.make("env-1"),- label: "Desktop",- endpoint: {- httpBaseUrl: "https://desktop.example.test/",- wsBaseUrl: "wss://desktop.example.test/ws",- providerKind: "cloudflare_tunnel",- },- linkedAt: "2026-05-25T00:00:00.000Z",- },- }),- );-- expect(connection.pairingUrl).toBe("https://desktop.example.test/");- expect(connection.pairingUrl).not.toContain("one-time-cloud-credential");- expect(connection.bearerToken).toBeNull();- expect(connection.authenticationMethod).toBe("dpop");- expect(connection.dpopAccessToken).toBe("environment-dpop-token");- expect(connection.relayManaged).toBe(true);- // @effect-diagnostics-next-line preferSchemaOverJson:off- expect(JSON.parse(connectRequestBody)).toMatchObject({- deviceId: "device-1",- clientKeyThumbprint: "client-proof-key-thumbprint",- });- expect(createProofMock).toHaveBeenCalledWith({- method: "POST",- url: "https://relay.example.test/v1/environments/env-1/connect",- accessToken: "relay-dpop-token",- });- expect(createProofMock).toHaveBeenCalledWith({- method: "POST",- url: "https://desktop.example.test/oauth/token",- });- }),- );-- it.effect("refreshes a saved environment against a rotated managed endpoint", () =>- Effect.gen(function* () {- vi.stubGlobal(- "fetch",- vi.fn((url: string | URL) => {- if (String(url).endsWith("/v1/client/dpop-token")) {- return Promise.resolve(- Response.json(validDpopAccessTokenResponse("environment:connect")),- );- }- if (String(url).endsWith("/.well-known/t3/environment")) {- return Promise.resolve(- Response.json({- environmentId: "env-1",- label: "Rotated Desktop",- platform: { os: "darwin", arch: "arm64" },- serverVersion: "0.0.0-test",- capabilities: { repositoryIdentity: true },- }),- );- }- if (String(url).endsWith("/oauth/token")) {- return Promise.resolve(- Response.json({- access_token: "fresh-environment-dpop-token",- issued_token_type: "urn:ietf:params:oauth:token-type:access_token",- token_type: "DPoP",- expires_in: 3600,- scope: "orchestration:read orchestration:operate terminal:operate review:write",- }),- );- }- return Promise.resolve(- Response.json({- environmentId: "env-1",- endpoint: {- httpBaseUrl: "https://rotated-desktop.example.test/",- wsBaseUrl: "wss://rotated-desktop.example.test/ws",- providerKind: "cloudflare_tunnel",- },- credential: "rotated-one-time-cloud-credential",- expiresAt: "2026-05-25T00:05:00.000Z",- }),- );- }),- );-- const connection = yield* withCloudServices(- refreshCloudEnvironmentConnection({- clerkToken: "clerk-token",- connection: {- environmentId: EnvironmentId.make("env-1"),- environmentLabel: "Desktop",- pairingUrl: "https://desktop.example.test/",- displayUrl: "https://desktop.example.test/",- httpBaseUrl: "https://desktop.example.test/",- wsBaseUrl: "wss://desktop.example.test/ws",- bearerToken: null,- authenticationMethod: "dpop",- relayManaged: true,- },- }),- );-- expect(connection).toMatchObject({- environmentId: "env-1",- environmentLabel: "Rotated Desktop",- displayUrl: "https://rotated-desktop.example.test/",- httpBaseUrl: "https://rotated-desktop.example.test/",- wsBaseUrl: "wss://rotated-desktop.example.test/ws",- dpopAccessToken: "fresh-environment-dpop-token",- });- }),- );-- it.effect("rejects relay connect responses for a different environment", () =>- Effect.gen(function* () {- vi.stubGlobal(- "fetch",- vi.fn((url: string | URL) =>- Promise.resolve(- String(url).endsWith("/v1/client/dpop-token")- ? Response.json(validDpopAccessTokenResponse("environment:connect"))- : Response.json({- environmentId: "env-other",- endpoint: {- httpBaseUrl: "https://desktop.example.test/",- wsBaseUrl: "wss://desktop.example.test/ws",- providerKind: "cloudflare_tunnel",- },- credential: "one-time-cloud-credential",- expiresAt: "2026-05-25T00:05:00.000Z",- }),- ),- ),- );-- const error = yield* withCloudServices(- connectCloudEnvironment({- clerkToken: "clerk-token",- environment: {- environmentId: EnvironmentId.make("env-1"),- label: "Desktop",- endpoint: {- httpBaseUrl: "https://desktop.example.test/",- wsBaseUrl: "wss://desktop.example.test/ws",- providerKind: "cloudflare_tunnel",- },- linkedAt: "2026-05-25T00:00:00.000Z",- },- }),- ).pipe(Effect.flip);- expect(error).toMatchObject({- _tag: "CloudEnvironmentLinkError",- message: "Relay returned credentials for a different environment.",- });- }),- );-- it.effect("preserves relay DPoP auth failures while connecting environments", () =>- Effect.gen(function* () {- vi.stubGlobal(- "fetch",- vi.fn((url: string | URL) =>- Promise.resolve(- String(url).endsWith("/v1/client/dpop-token")- ? Response.json(validDpopAccessTokenResponse("environment:connect"))- : Response.json(- {- _tag: "RelayAuthInvalidError",- code: "auth_invalid",- reason: "invalid_dpop",- traceId: "trace-connect",- },- { status: 401 },- ),- ),- ),- );-- const error = yield* withCloudServices(- connectCloudEnvironment({- clerkToken: "clerk-token",- environment: {- environmentId: EnvironmentId.make("env-1"),- label: "Desktop",- endpoint: {- httpBaseUrl: "https://desktop.example.test/",- wsBaseUrl: "wss://desktop.example.test/ws",- providerKind: "cloudflare_tunnel",- },- linkedAt: "2026-05-25T00:00:00.000Z",- },- }),- ).pipe(Effect.flip);- expect(error).toMatchObject({- _tag: "CloudEnvironmentLinkError",- message:- "https://relay.example.test/v1/environments/env-1/connect failed: Relay rejected the DPoP proof.",- traceId: "trace-connect",- });- }),- );-- it.effect("rejects relay connect responses for a different endpoint", () =>- Effect.gen(function* () {- vi.stubGlobal(- "fetch",- vi.fn((url: string | URL) =>- Promise.resolve(- String(url).endsWith("/v1/client/dpop-token")- ? Response.json(validDpopAccessTokenResponse("environment:connect"))- : Response.json({- environmentId: "env-1",- endpoint: {- httpBaseUrl: "https://other-desktop.example.test/",- wsBaseUrl: "wss://other-desktop.example.test/ws",- providerKind: "cloudflare_tunnel",- },- credential: "one-time-cloud-credential",- expiresAt: "2026-05-25T00:05:00.000Z",- }),- ),- ),- );-- const error = yield* withCloudServices(- connectCloudEnvironment({- clerkToken: "clerk-token",- environment: {- environmentId: EnvironmentId.make("env-1"),- label: "Desktop",- endpoint: {- httpBaseUrl: "https://desktop.example.test/",- wsBaseUrl: "wss://desktop.example.test/ws",- providerKind: "cloudflare_tunnel",- },- linkedAt: "2026-05-25T00:00:00.000Z",- },- }),- ).pipe(Effect.flip);- expect(error).toMatchObject({- _tag: "CloudEnvironmentLinkError",- message: "Relay returned credentials for a different endpoint.",- });- }),- );-- it.effect(- "rejects managed endpoints whose descriptor does not match the selected environment",- () =>- Effect.gen(function* () {- vi.stubGlobal(- "fetch",- vi.fn((url: string | URL) =>- Promise.resolve(- String(url).endsWith("/v1/client/dpop-token")- ? Response.json(validDpopAccessTokenResponse("environment:connect"))- : String(url).endsWith("/.well-known/t3/environment")- ? Response.json({- environmentId: "env-other",- label: "Other Desktop",- platform: { os: "darwin", arch: "arm64" },- serverVersion: "0.0.0-test",- capabilities: { repositoryIdentity: true },- })- : Response.json({- environmentId: "env-1",- endpoint: {- httpBaseUrl: "https://desktop.example.test/",- wsBaseUrl: "wss://desktop.example.test/ws",- providerKind: "cloudflare_tunnel",- },- credential: "one-time-cloud-credential",- expiresAt: "2026-05-25T00:05:00.000Z",- }),- ),- ),- );-- const error = yield* withCloudServices(- connectCloudEnvironment({- clerkToken: "clerk-token",- environment: {- environmentId: EnvironmentId.make("env-1"),- label: "Desktop",- endpoint: {- httpBaseUrl: "https://desktop.example.test/",- wsBaseUrl: "wss://desktop.example.test/ws",- providerKind: "cloudflare_tunnel",- },- linkedAt: "2026-05-25T00:00:00.000Z",- },- }),- ).pipe(Effect.flip);- expect(error).toMatchObject({- _tag: "CloudEnvironmentLinkError",- message: "Connected endpoint descriptor does not match the selected environment.",- });- }),- );-});diff --git a/apps/mobile/src/features/cloud/linkEnvironment.ts b/apps/mobile/src/features/cloud/linkEnvironment.tsdeleted file mode 100644index 958827ee4..000000000--- a/apps/mobile/src/features/cloud/linkEnvironment.ts+++ /dev/null@@ -1,617 +0,0 @@-import * as Data from "effect/Data";-import * as Effect from "effect/Effect";-import * as Schema from "effect/Schema";-import { HttpClient } from "effect/unstable/http";-import {- EnvironmentCloudEndpointUnavailableError,- EnvironmentHttpBadRequestError,- EnvironmentHttpConflictError,- EnvironmentHttpForbiddenError,- EnvironmentHttpInternalServerError,- EnvironmentHttpUnauthorizedError,-} from "@t3tools/contracts";-import { stripPairingTokenFromUrl } from "@t3tools/shared/remote";-import {- type RelayEnvironmentConnectResponse as RelayEnvironmentConnectResponseType,- type RelayEnvironmentLinkResponse as RelayEnvironmentLinkResponseType,- RelayEnvironmentConnectScope,- RelayEnvironmentStatusScope,- type RelayDpopAccessTokenScope,- type RelayProtectedError as RelayProtectedErrorType,- type RelayClientEnvironmentRecord,- type RelayEnvironmentStatusResponse as RelayEnvironmentStatusResponseType,- type RelayManagedEndpointProviderKind,-} from "@t3tools/contracts/relay";-import { exchangeRemoteDpopAccessToken } from "@t3tools/client-runtime/authorization";-import { fetchRemoteEnvironmentDescriptor } from "@t3tools/client-runtime/environment";-import { findErrorTraceId } from "@t3tools/client-runtime/errors";-import { ManagedRelay } from "@t3tools/client-runtime/relay";-import { makeEnvironmentHttpApiClient } from "@t3tools/client-runtime/rpc";--import { authClientMetadata } from "../../lib/authClientMetadata";-import type { SavedRemoteConnection } from "../../lib/connection";-import * as MobilePreferences from "../../persistence/mobile-preferences";-import * as MobileStorage from "../../persistence/mobile-storage";-import { resolveCloudPublicConfig } from "./publicConfig";--const RELAY_STATUS_AND_CONNECT_SCOPES = [- RelayEnvironmentStatusScope,- RelayEnvironmentConnectScope,-] satisfies ReadonlyArray<RelayDpopAccessTokenScope>;--export function normalizeRelayBaseUrl(value: string | null | undefined): string | null {- const trimmed = value?.trim();- if (!trimmed) {- return null;- }- return trimmed.replace(/\/+$/g, "");-}--function readRelayUrl(): string | null {- return resolveCloudPublicConfig().relay.url;-}--export class CloudEnvironmentLinkError extends Data.TaggedError("CloudEnvironmentLinkError")<{- readonly message: string;- readonly cause?: unknown;- readonly traceId?: string;-}> {}--export interface CloudEnvironmentRecordWithStatus {- readonly environment: RelayClientEnvironmentRecord;- readonly status: RelayEnvironmentStatusResponseType | null;- readonly statusError: string | null;-}--const isEnvironmentCloudApiError = Schema.is(- Schema.Union([- EnvironmentHttpBadRequestError,- EnvironmentHttpUnauthorizedError,- EnvironmentHttpForbiddenError,- EnvironmentHttpConflictError,- EnvironmentHttpInternalServerError,- EnvironmentCloudEndpointUnavailableError,- ]),-);--const MANAGED_ENDPOINT_PROVIDER_KIND =- "cloudflare_tunnel" satisfies RelayManagedEndpointProviderKind;--function cloudEnvironmentLinkError(message: string) {- return (cause: unknown) => {- const environmentError = findEnvironmentCloudApiError(cause);- const traceId = findErrorTraceId(cause);- return new CloudEnvironmentLinkError({- message: environmentError- ? `${message.replace(/[.:]$/, "")}: ${environmentError.message}`- : withDevCause(message, cause),- cause,- ...(traceId === null ? {} : { traceId }),- });- };-}--function isDevRuntime(): boolean {- return typeof __DEV__ !== "undefined" && __DEV__;-}--function causeMessage(cause: unknown): string | null {- if (cause instanceof Error && cause.message) {- return cause.message;- }- if (typeof cause === "object" && cause !== null) {- const record = cause as { readonly message?: unknown; readonly cause?: unknown };- if (typeof record.message === "string" && record.message.length > 0) {- const nested = causeMessage(record.cause);- return nested ? `${record.message}: ${nested}` : record.message;- }- }- return null;-}--function withDevCause(message: string, cause: unknown): string {- if (!isDevRuntime()) {- return message;- }- const detail = causeMessage(cause);- return detail ? `${message} (${detail})` : message;-}--function relayProtectedErrorMessage(error: RelayProtectedErrorType): string {- switch (error._tag) {- case "RelayAuthInvalidError":- switch (error.reason) {- case "missing_bearer":- case "invalid_bearer":- return "Relay rejected the cloud session token.";- case "invalid_dpop":- return "Relay rejected the DPoP proof.";- case "not_authorized":- return "Relay rejected the authenticated request.";- }- case "RelayEnvironmentLinkProofExpiredError":- return "Relay rejected an expired environment link proof.";- case "RelayEnvironmentLinkProofInvalidError":- return `Relay rejected the environment link proof (${error.reason}).`;- case "RelayEnvironmentConnectNotAuthorizedError":- // "Not authorized" covers non-auth causes too; surface the reason so a- // missing link doesn't read as a credential problem.- if (error.reason === "environment_link_not_found") {- return "Relay has no active link for this environment. The environment server may not have re-established its link yet.";- }- return error.reason- ? `Relay rejected the environment connection request (${error.reason}).`- : "Relay rejected the environment connection request.";- case "RelayEnvironmentEndpointUnavailableError":- return `Relay could not reach the environment endpoint (${error.reason}).`;- case "RelayEnvironmentEndpointTimedOutError":- return "Relay timed out while contacting the environment endpoint.";- case "RelayEnvironmentLinkFailedError":- return `Relay could not link the environment (${error.reason}).`;- case "RelayEnvironmentLinkUnavailableError":- return `Relay cannot provision the managed endpoint (${error.reason}).`;- case "RelayEnvironmentLinkLimitExceededError":- return `Relay refused the link: this account already has its maximum of ${error.maxTunnels} managed tunnels. Unlink an environment to free one up.`;- case "RelayAgentActivityPublishProofExpiredError":- return "Relay rejected an expired agent activity publish proof.";- case "RelayAgentActivityPublishProofInvalidError":- return `Relay rejected the agent activity publish proof (${error.reason}).`;- case "RelayInternalError":- return `Relay encountered an internal error (${error.reason}).`;- }-}--function decodedRelayClientError(message: string) {- return (cause: ManagedRelay.ManagedRelayClientError) => {- const relayError =- cause._tag === "ManagedRelayRequestFailedError" ? cause.relayError : undefined;- const traceId = cause._tag === "ManagedRelayRequestFailedError" ? cause.traceId : undefined;- const detail = relayError ? relayProtectedErrorMessage(relayError) : null;- return new CloudEnvironmentLinkError({- message: detail ? `${message}: ${detail}` : message,- cause,- ...(traceId ? { traceId } : {}),- });- };-}--function findEnvironmentCloudApiError(cause: unknown): { readonly message: string } | null {- if (isEnvironmentCloudApiError(cause)) {- return cause;- }- if (typeof cause !== "object" || cause === null) {- return null;- }- return "cause" in cause ? findEnvironmentCloudApiError(cause.cause) : null;-}--function requireRelayUrl(): Effect.Effect<string, CloudEnvironmentLinkError> {- const relayUrl = readRelayUrl();- return relayUrl- ? Effect.succeed(relayUrl)- : Effect.fail(new CloudEnvironmentLinkError({ message: "Relay URL is not configured." }));-}--function endpointOrigin(httpBaseUrl: string) {- const url = new URL(httpBaseUrl);- return {- localHttpHost: "127.0.0.1",- localHttpPort: Number(url.port || (url.protocol === "https:" ? 443 : 80)),- };-}--function ensureLinkedEnvironmentMatches(input: {- readonly expectedEnvironmentId: string;- readonly expectedProviderKind: RelayManagedEndpointProviderKind;- readonly link: RelayEnvironmentLinkResponseType;-}): Effect.Effect<void, CloudEnvironmentLinkError> {- if (input.link.environmentId !== input.expectedEnvironmentId) {- return new CloudEnvironmentLinkError({- message: "Relay returned credentials for a different environment.",- });- }- if (input.link.endpoint.providerKind !== input.expectedProviderKind) {- return new CloudEnvironmentLinkError({- message: "Relay returned credentials for a different endpoint provider.",- });- }- return Effect.void;-}--function endpointMatches(- left: RelayClientEnvironmentRecord["endpoint"],- right: RelayClientEnvironmentRecord["endpoint"],-): boolean {- return (- left.httpBaseUrl === right.httpBaseUrl &&- left.wsBaseUrl === right.wsBaseUrl &&- left.providerKind === right.providerKind- );-}--function ensureStatusMatchesEnvironment(input: {- readonly environment: RelayClientEnvironmentRecord;- readonly status: RelayEnvironmentStatusResponseType;-}): Effect.Effect<void, CloudEnvironmentLinkError> {- if (input.status.environmentId !== input.environment.environmentId) {- return new CloudEnvironmentLinkError({- message: "Relay returned status for a different environment.",- });- }- if (!endpointMatches(input.status.endpoint, input.environment.endpoint)) {- return new CloudEnvironmentLinkError({- message: "Relay returned status for a different endpoint.",- });- }- if (- input.status.descriptor &&- input.status.descriptor.environmentId !== input.environment.environmentId- ) {- return new CloudEnvironmentLinkError({- message: "Relay returned status descriptor for a different environment.",- });- }- return Effect.void;-}--function ensureConnectEndpointMatchesEnvironment(input: {- readonly environment: RelayClientEnvironmentRecord;- readonly connect: RelayEnvironmentConnectResponseType;-}): Effect.Effect<void, CloudEnvironmentLinkError> {- if (!endpointMatches(input.connect.endpoint, input.environment.endpoint)) {- return new CloudEnvironmentLinkError({- message: "Relay returned credentials for a different endpoint.",- });- }- return Effect.void;-}--interface LinkEnvironmentToCloudInput {- readonly connection: SavedRemoteConnection;- readonly clerkToken: string;-}--type LinkEnvironmentToCloudRequirements =- | HttpClient.HttpClient- | ManagedRelay.ManagedRelayClient- | MobileStorage.MobileStorage;--export function linkEnvironmentToCloudWithPreference(- input: LinkEnvironmentToCloudInput & { readonly liveActivitiesEnabled: boolean },-): Effect.Effect<void, CloudEnvironmentLinkError, LinkEnvironmentToCloudRequirements> {- return Effect.gen(function* () {- if (!input.connection.bearerToken) {- return yield* new CloudEnvironmentLinkError({- message: "Only a locally paired bearer connection can be linked to the cloud.",- });- }- const localBearerToken = input.connection.bearerToken;- const relayUrl = yield* requireRelayUrl();- const relayClient = yield* ManagedRelay.ManagedRelayClient;- const storage = yield* MobileStorage.MobileStorage;- const deviceId = yield* storage.loadOrCreateAgentAwarenessDeviceId.pipe(- Effect.mapError(cloudEnvironmentLinkError("Could not load the mobile device id.")),- );- const liveActivitiesEnabled = input.liveActivitiesEnabled;- const challenge = yield* relayClient- .createEnvironmentLinkChallenge({- clerkToken: input.clerkToken,- payload: {- notificationsEnabled: true,- liveActivitiesEnabled,- managedTunnelsEnabled: true,- },- })- .pipe(- Effect.mapError(- decodedRelayClientError(`${relayUrl}/v1/client/environment-link-challenges failed`),- ),- );- const environmentClient = yield* makeEnvironmentHttpApiClient(input.connection.httpBaseUrl);- const proof = yield* environmentClient.connect- .linkProof({- headers: { authorization: `Bearer ${localBearerToken}` },- payload: {- challenge: challenge.challenge,- relayIssuer: relayUrl,- endpoint: {- httpBaseUrl: input.connection.httpBaseUrl,- wsBaseUrl: input.connection.wsBaseUrl,- providerKind: MANAGED_ENDPOINT_PROVIDER_KIND,- },- origin: endpointOrigin(input.connection.httpBaseUrl),- },- })- .pipe(Effect.mapError(cloudEnvironmentLinkError("Could not obtain environment link proof.")));- const link = yield* relayClient- .linkEnvironment({- clerkToken: input.clerkToken,- payload: {- deviceId,- proof,- notificationsEnabled: true,- liveActivitiesEnabled,- managedTunnelsEnabled: true,- },- })- .pipe(- Effect.mapError(decodedRelayClientError(`${relayUrl}/v1/client/environment-links failed`)),- );- yield* ensureLinkedEnvironmentMatches({- expectedEnvironmentId: input.connection.environmentId,- expectedProviderKind: MANAGED_ENDPOINT_PROVIDER_KIND,- link,- });-- yield* environmentClient.connect- .relayConfig({- headers: { authorization: `Bearer ${localBearerToken}` },- payload: {- relayUrl,- relayIssuer: link.relayIssuer,- cloudUserId: link.cloudUserId,- environmentCredential: link.environmentCredential,- cloudMintPublicKey: link.cloudMintPublicKey,- endpointRuntime: link.endpointRuntime,- },- })- .pipe(- Effect.mapError(cloudEnvironmentLinkError("Could not configure environment relay access.")),- );- });-}--export function linkEnvironmentToCloud(- input: LinkEnvironmentToCloudInput,-): Effect.Effect<- void,- CloudEnvironmentLinkError,- LinkEnvironmentToCloudRequirements | MobilePreferences.MobilePreferencesStore-> {- return MobilePreferences.MobilePreferencesStore.pipe(- Effect.flatMap((preferencesStore) => preferencesStore.load),- Effect.mapError(cloudEnvironmentLinkError("Could not load mobile notification preferences.")),- Effect.flatMap((preferences) =>- linkEnvironmentToCloudWithPreference({- ...input,- liveActivitiesEnabled: preferences.liveActivitiesEnabled !== false,- }),- ),- );-}--export function listCloudEnvironments(input: {- readonly clerkToken: string;-}): Effect.Effect<- ReadonlyArray<RelayClientEnvironmentRecord>,- CloudEnvironmentLinkError,- ManagedRelay.ManagedRelayClient-> {- return Effect.gen(function* () {- const relayUrl = yield* requireRelayUrl();- const relayClient = yield* ManagedRelay.ManagedRelayClient;-- return yield* relayClient- .listEnvironments({- clerkToken: input.clerkToken,- })- .pipe(Effect.mapError(decodedRelayClientError(`${relayUrl}/v1/environments failed`)));- });-}--export function getCloudEnvironmentStatus(input: {- readonly clerkToken: string;- readonly environment: RelayClientEnvironmentRecord;- readonly relayScopes?: ReadonlyArray<RelayDpopAccessTokenScope>;-}): Effect.Effect<- RelayEnvironmentStatusResponseType,- CloudEnvironmentLinkError,- ManagedRelay.ManagedRelayClient-> {- return Effect.gen(function* () {- const relayUrl = yield* requireRelayUrl();- const relayClient = yield* ManagedRelay.ManagedRelayClient;- const status = yield* relayClient- .getEnvironmentStatus({- clerkToken: input.clerkToken,- scopes: input.relayScopes ?? [RelayEnvironmentStatusScope],- environmentId: input.environment.environmentId,- })- .pipe(- Effect.mapError(- decodedRelayClientError(- `${relayUrl}/v1/environments/${encodeURIComponent(input.environment.environmentId)}/status failed`,- ),- ),- );- yield* ensureStatusMatchesEnvironment({ environment: input.environment, status });- return status;- });-}--export function cloudEnvironmentsPendingStatus(- environments: ReadonlyArray<RelayClientEnvironmentRecord>,-): ReadonlyArray<CloudEnvironmentRecordWithStatus> {- return environments.map((environment) => ({- environment,- status: null,- statusError: "Checking status...",- }));-}--export function loadCloudEnvironmentStatuses(input: {- readonly clerkToken: string;- readonly environments: ReadonlyArray<RelayClientEnvironmentRecord>;-}): Effect.Effect<- ReadonlyArray<CloudEnvironmentRecordWithStatus>,- CloudEnvironmentLinkError,- ManagedRelay.ManagedRelayClient-> {- return Effect.forEach(- input.environments,- (environment) =>- getCloudEnvironmentStatus({- clerkToken: input.clerkToken,- environment,- relayScopes: RELAY_STATUS_AND_CONNECT_SCOPES,- }).pipe(- Effect.match({- onFailure: (error) => ({- environment,- status: null,- statusError: error.message,- }),- onSuccess: (status) => ({- environment,- status,- statusError: null,- }),- }),- ),- { concurrency: "unbounded" },- );-}--export function listCloudEnvironmentsWithStatus(input: {- readonly clerkToken: string;-}): Effect.Effect<- ReadonlyArray<CloudEnvironmentRecordWithStatus>,- CloudEnvironmentLinkError,- ManagedRelay.ManagedRelayClient-> {- return Effect.gen(function* () {- const environments = yield* listCloudEnvironments(input);- return yield* loadCloudEnvironmentStatuses({- clerkToken: input.clerkToken,- environments,- });- });-}--const loadAgentAwarenessDeviceId = Effect.fn("mobile.cloud.loadAgentAwarenessDeviceId")(- function* () {- const storage = yield* MobileStorage.MobileStorage;- return yield* storage.loadOrCreateAgentAwarenessDeviceId.pipe(- Effect.mapError(cloudEnvironmentLinkError("Could not load the mobile device id.")),- );- },-);--const connectRelayManagedEnvironment = Effect.fn("mobile.cloud.connectRelayManagedEnvironment")(- function* (input: {- readonly clerkToken: string;- readonly environmentId: RelayClientEnvironmentRecord["environmentId"];- readonly expectedEnvironment?: RelayClientEnvironmentRecord;- }) {- yield* Effect.annotateCurrentSpan({ "environment.id": input.environmentId });- const relayUrl = yield* requireRelayUrl();- const relayClient = yield* ManagedRelay.ManagedRelayClient;-- const deviceId = yield* loadAgentAwarenessDeviceId();- const connect = yield* relayClient- .connectEnvironment({- clerkToken: input.clerkToken,- scopes: [RelayEnvironmentConnectScope],- environmentId: input.environmentId,- deviceId,- })- .pipe(- Effect.mapError(- decodedRelayClientError(- `${relayUrl}/v1/environments/${encodeURIComponent(input.environmentId)}/connect failed`,- ),- ),- );- if (connect.environmentId !== input.environmentId) {- return yield* new CloudEnvironmentLinkError({- message: "Relay returned credentials for a different environment.",- });- }- if (input.expectedEnvironment) {- yield* ensureConnectEndpointMatchesEnvironment({- environment: input.expectedEnvironment,- connect,- });- }-- const descriptor = yield* fetchRemoteEnvironmentDescriptor({- httpBaseUrl: connect.endpoint.httpBaseUrl,- }).pipe(- Effect.mapError(- cloudEnvironmentLinkError("Could not fetch the connected environment descriptor."),- ),- );- if (descriptor.environmentId !== connect.environmentId) {- return yield* new CloudEnvironmentLinkError({- message: "Connected endpoint descriptor does not match the selected environment.",- });- }- const signer = yield* ManagedRelay.ManagedRelayDpopSigner;- const bootstrapDpop = yield* signer- .createProof({- method: "POST",- url: new URL("/oauth/token", connect.endpoint.httpBaseUrl).toString(),- })- .pipe(Effect.mapError(cloudEnvironmentLinkError("Could not create bootstrap DPoP proof.")));- const bootstrap = yield* exchangeRemoteDpopAccessToken({- httpBaseUrl: connect.endpoint.httpBaseUrl,- credential: connect.credential,- dpopProof: bootstrapDpop,- clientMetadata: authClientMetadata(),- }).pipe(- Effect.mapError(- cloudEnvironmentLinkError("Could not exchange a managed endpoint DPoP access token."),- ),- );- const pairingUrl = new URL(connect.endpoint.httpBaseUrl);- pairingUrl.hash = new URLSearchParams([["token", connect.credential]]).toString();-- return {- environmentId: descriptor.environmentId,- environmentLabel: descriptor.label,- pairingUrl: stripPairingTokenFromUrl(pairingUrl).toString(),- displayUrl: connect.endpoint.httpBaseUrl,- httpBaseUrl: connect.endpoint.httpBaseUrl,- wsBaseUrl: connect.endpoint.wsBaseUrl,- bearerToken: null,- authenticationMethod: "dpop",- dpopAccessToken: bootstrap.access_token,- relayManaged: true,- } satisfies SavedRemoteConnection;- },-);--export function connectCloudEnvironment(input: {- readonly clerkToken: string;- readonly environment: RelayClientEnvironmentRecord;-}): Effect.Effect<- SavedRemoteConnection,- CloudEnvironmentLinkError,- | HttpClient.HttpClient- | ManagedRelay.ManagedRelayClient- | ManagedRelay.ManagedRelayDpopSigner- | MobileStorage.MobileStorage-> {- return connectRelayManagedEnvironment({- clerkToken: input.clerkToken,- environmentId: input.environment.environmentId,- expectedEnvironment: input.environment,- });-}--export function refreshCloudEnvironmentConnection(input: {- readonly clerkToken: string;- readonly connection: SavedRemoteConnection;-}): Effect.Effect<- SavedRemoteConnection,- CloudEnvironmentLinkError,- | HttpClient.HttpClient- | ManagedRelay.ManagedRelayClient- | ManagedRelay.ManagedRelayDpopSigner- | MobileStorage.MobileStorage-> {- return connectRelayManagedEnvironment({- clerkToken: input.clerkToken,- environmentId: input.connection.environmentId,- });-}diff --git a/apps/mobile/src/features/cloud/managedRelayLayer.ts b/apps/mobile/src/features/cloud/managedRelayLayer.tsdeleted file mode 100644index 2da1fa915..000000000--- a/apps/mobile/src/features/cloud/managedRelayLayer.ts+++ /dev/null@@ -1,62 +0,0 @@-import { ManagedRelay } from "@t3tools/client-runtime/relay";-import { RelayMobileClientId } from "@t3tools/contracts/relay";-import * as Crypto from "effect/Crypto";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";--import { createDpopProof, loadOrCreateDpopProofKeyPair } from "./dpop";-import { managedRelayAccessTokenStore } from "./managedRelayTokenStore";--const relayDpopSignerLayer = Layer.effect(- ManagedRelay.ManagedRelayDpopSigner,- Effect.gen(function* () {- const crypto = yield* Crypto.Crypto;- const loadProofKey = yield* Effect.cached(- loadOrCreateDpopProofKeyPair().pipe(Effect.provideService(Crypto.Crypto, crypto)),- );- return ManagedRelay.ManagedRelayDpopSigner.of({- thumbprint: loadProofKey.pipe(- Effect.map((proofKey) => proofKey.thumbprint),- Effect.mapError(- (error) =>- new ManagedRelay.ManagedRelayDpopKeyLoadError({- keyStore: "expo-secure-store",- cause: error,- }),- ),- Effect.withSpan("mobile.managedRelayDpopSigner.loadThumbprint"),- ),- createProof: Effect.fn("mobile.managedRelayDpopSigner.createProof")(function* (input) {- const proofKey = yield* loadProofKey.pipe(- Effect.mapError(- (error) =>- new ManagedRelay.ManagedRelayDpopProofCreationError({- method: input.method,- url: input.url,- cause: error,- }),- ),- );- return yield* createDpopProof({ ...input, proofKey }).pipe(- Effect.provideService(Crypto.Crypto, crypto),- Effect.map((proof) => proof.proof),- Effect.mapError(- (error) =>- new ManagedRelay.ManagedRelayDpopProofCreationError({- method: input.method,- url: input.url,- cause: error,- }),- ),- );- }),- });- }),-);--export const managedRelayClientLayer = (relayUrl: string) =>- ManagedRelay.layer({- relayUrl,- clientId: RelayMobileClientId,- accessTokenStore: managedRelayAccessTokenStore,- }).pipe(Layer.provideMerge(relayDpopSignerLayer));diff --git a/apps/mobile/src/features/cloud/managedRelayState.ts b/apps/mobile/src/features/cloud/managedRelayState.tsdeleted file mode 100644index eec1e3410..000000000--- a/apps/mobile/src/features/cloud/managedRelayState.ts+++ /dev/null@@ -1,100 +0,0 @@-import { useAtomValue } from "@effect/atom-react";-import {- createManagedRelayQueryManager,- managedRelaySessionAtom,- readManagedRelaySnapshotState,-} from "@t3tools/client-runtime/relay";-import type {- RelayClientEnvironmentRecord,- RelayEnvironmentStatusResponse,-} from "@t3tools/contracts/relay";-import { AsyncResult, Atom } from "effect/unstable/reactivity";-import { useCallback, useEffect } from "react";--import { runtimeContextLayer } from "../../lib/runtime";-import { appAtomRegistry } from "../../state/atom-registry";-import { cloudDebugLog } from "./cloudDebugLog";--const managedRelayAtomRuntime = Atom.runtime(runtimeContextLayer);--export const managedRelayQueryManager = createManagedRelayQueryManager(managedRelayAtomRuntime, {- onQueryEvent: (event) =>- cloudDebugLog(`query:${event.operation}:${event.stage}:${event.phase}`, { ...event }),-});--const EMPTY_ENVIRONMENTS_ATOM = Atom.make(- AsyncResult.success<ReadonlyArray<RelayClientEnvironmentRecord>>([]),-).pipe(Atom.keepAlive, Atom.withLabel("managed-relay:mobile:environments:null"));--const EMPTY_ENVIRONMENT_STATUS_ATOM = Atom.make(- AsyncResult.initial<RelayEnvironmentStatusResponse, never>(false),-).pipe(Atom.keepAlive, Atom.withLabel("managed-relay:mobile:environment-status:null"));--export function useManagedRelayEnvironments() {- const session = useAtomValue(managedRelaySessionAtom);- const accountId = session?.accountId ?? null;- const atom = accountId- ? managedRelayQueryManager.environmentsAtom(accountId)- : EMPTY_ENVIRONMENTS_ATOM;- const result = useAtomValue(atom);- const snapshot = readManagedRelaySnapshotState(result);- useEffect(() => {- if (snapshot.error) {- console.error("[t3-cloud] Relay environment listing failed", {- message: snapshot.error,- traceId: snapshot.errorTraceId,- });- }- }, [snapshot.error, snapshot.errorTraceId]);- const refresh = useCallback(() => {- if (accountId) {- managedRelayQueryManager.refreshEnvironments(appAtomRegistry, accountId);- }- }, [accountId]);-- return {- ...snapshot,- accountId,- refresh,- };-}--export function useManagedRelayEnvironmentStatus(environment: RelayClientEnvironmentRecord) {- const session = useAtomValue(managedRelaySessionAtom);- const accountId = session?.accountId ?? null;- const atom = accountId- ? managedRelayQueryManager.environmentStatusAtom({ accountId, environment })- : EMPTY_ENVIRONMENT_STATUS_ATOM;- const result = useAtomValue(atom);- const snapshot = readManagedRelaySnapshotState(result);- useEffect(() => {- if (snapshot.error) {- console.error("[t3-cloud] Relay environment status failed", {- environmentId: environment.environmentId,- message: snapshot.error,- traceId: snapshot.errorTraceId,- });- }- }, [environment.environmentId, snapshot.error, snapshot.errorTraceId]);- const refresh = useCallback(() => {- if (accountId) {- managedRelayQueryManager.refreshEnvironmentStatus(appAtomRegistry, {- accountId,- environment,- });- }- }, [accountId, environment]);-- return {- ...snapshot,- accountId,- refresh,- };-}--export function refreshManagedRelayEnvironments(): void {- const session = appAtomRegistry.get(managedRelaySessionAtom);- if (session) {- managedRelayQueryManager.refreshEnvironments(appAtomRegistry, session.accountId);- }-}diff --git a/apps/mobile/src/features/cloud/managedRelayTokenStore.test.ts b/apps/mobile/src/features/cloud/managedRelayTokenStore.test.tsdeleted file mode 100644index 9642e5f63..000000000--- a/apps/mobile/src/features/cloud/managedRelayTokenStore.test.ts+++ /dev/null@@ -1,85 +0,0 @@-import { expect, it } from "@effect/vitest";-import * as Effect from "effect/Effect";-import * as Logger from "effect/Logger";-import * as SecureStore from "expo-secure-store";-import { vi } from "vite-plus/test";--const secureStore = vi.hoisted(() => new Map<string, string>());--vi.mock("expo-secure-store", () => ({- getItemAsync: vi.fn((key: string) => Promise.resolve(secureStore.get(key) ?? null)),- setItemAsync: vi.fn((key: string, value: string) => {- secureStore.set(key, value);- return Promise.resolve();- }),- deleteItemAsync: vi.fn((key: string) => {- secureStore.delete(key);- return Promise.resolve();- }),-}));--import {- ManagedRelayTokenStoreError,- managedRelayAccessTokenStore,-} from "./managedRelayTokenStore";--it.effect("round-trips and clears persisted managed relay access tokens", () =>- Effect.gen(function* () {- secureStore.clear();- const entries = [- {- accountId: "user-1",- clientId: "t3-mobile",- relayUrl: "https://relay.example.test",- thumbprint: "thumbprint",- scopes: ["environment:connect"],- accessToken: "access-token",- expiresAtMillis: 1_800_000,- },- ] as const;-- yield* managedRelayAccessTokenStore.save(entries);- expect(yield* managedRelayAccessTokenStore.load).toEqual(entries);-- yield* managedRelayAccessTokenStore.clear;- expect(yield* managedRelayAccessTokenStore.load).toEqual([]);- }),-);--it.effect("falls back to an empty cache when persisted data is invalid", () =>- Effect.gen(function* () {- secureStore.clear();- secureStore.set("t3code.cloud.relay-access-tokens", "not-json");-- expect(yield* managedRelayAccessTokenStore.load).toEqual([]);- }),-);--it.effect("logs structured storage failures before falling back to an empty cache", () => {- const messages: Array<unknown> = [];- const logger = Logger.make(({ message }) => {- messages.push(message);- });- const cause = new Error("secure store unavailable");- vi.mocked(SecureStore.getItemAsync).mockRejectedValueOnce(cause);-- return Effect.gen(function* () {- expect(yield* managedRelayAccessTokenStore.load).toEqual([]);-- const message = messages.find(- (candidate) =>- Array.isArray(candidate) && candidate[0] === "Managed relay token store operation failed.",- );- expect(message).toBeDefined();- const context = (message as ReadonlyArray<unknown>)[1] as {- readonly cause: ManagedRelayTokenStoreError;- };- expect(context.cause).toBeInstanceOf(ManagedRelayTokenStoreError);- expect(context.cause).toMatchObject({- operation: "read",- storageKey: "t3code.cloud.relay-access-tokens",- cause,- });- expect(context.cause.message).not.toContain(cause.message);- }).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false })));-});diff --git a/apps/mobile/src/features/cloud/managedRelayTokenStore.ts b/apps/mobile/src/features/cloud/managedRelayTokenStore.tsdeleted file mode 100644index 0730f277f..000000000--- a/apps/mobile/src/features/cloud/managedRelayTokenStore.ts+++ /dev/null@@ -1,133 +0,0 @@-import { ManagedRelay } from "@t3tools/client-runtime/relay";-import * as Effect from "effect/Effect";-import * as Schema from "effect/Schema";-import * as SecureStore from "expo-secure-store";--const MANAGED_RELAY_TOKEN_CACHE_KEY = "t3code.cloud.relay-access-tokens";-const MANAGED_RELAY_TOKEN_CACHE_VERSION = 1;--const ManagedRelayAccessTokenCacheEntrySchema = Schema.Struct({- accountId: Schema.String,- clientId: Schema.Literals(["t3-mobile", "t3-web"]),- relayUrl: Schema.String,- thumbprint: Schema.String,- scopes: Schema.Array(- Schema.Literals(["environment:connect", "environment:status", "mobile:registration"]),- ),- accessToken: Schema.String,- expiresAtMillis: Schema.Number,-});--const ManagedRelayAccessTokenCacheSchema = Schema.fromJsonString(- Schema.Struct({- version: Schema.Literal(MANAGED_RELAY_TOKEN_CACHE_VERSION),- entries: Schema.Array(ManagedRelayAccessTokenCacheEntrySchema),- }),-);--const decodeManagedRelayAccessTokenCache = Schema.decodeUnknownEffect(- ManagedRelayAccessTokenCacheSchema,-);-const encodeManagedRelayAccessTokenCache = Schema.encodeEffect(ManagedRelayAccessTokenCacheSchema);--export class ManagedRelayTokenStoreError extends Schema.TaggedErrorClass<ManagedRelayTokenStoreError>()(- "ManagedRelayTokenStoreError",- {- operation: Schema.Literals(["read", "decode", "encode", "write", "clear"]),- storageKey: Schema.String,- cause: Schema.Defect(),- },-) {- override get message(): string {- return `Managed relay token store operation "${this.operation}" failed for key "${this.storageKey}".`;- }-}--function logStoreFailure(error: ManagedRelayTokenStoreError) {- return Effect.logWarning("Managed relay token store operation failed.", {- errorTag: error._tag,- operation: error.operation,- storageKey: error.storageKey,- cause: error,- });-}--const loadManagedRelayAccessTokens = Effect.tryPromise({- try: () => SecureStore.getItemAsync(MANAGED_RELAY_TOKEN_CACHE_KEY),- catch: (cause) =>- new ManagedRelayTokenStoreError({- operation: "read",- storageKey: MANAGED_RELAY_TOKEN_CACHE_KEY,- cause,- }),-}).pipe(- Effect.flatMap((encoded) =>- encoded === null- ? Effect.succeed<ReadonlyArray<ManagedRelay.ManagedRelayAccessTokenCacheEntry>>([])- : decodeManagedRelayAccessTokenCache(encoded).pipe(- Effect.map((cache) => cache.entries),- Effect.mapError(- (cause) =>- new ManagedRelayTokenStoreError({- operation: "decode",- storageKey: MANAGED_RELAY_TOKEN_CACHE_KEY,- cause,- }),- ),- ),- ),-);--const saveManagedRelayAccessTokens = (- entries: ReadonlyArray<ManagedRelay.ManagedRelayAccessTokenCacheEntry>,-) =>- encodeManagedRelayAccessTokenCache({- version: MANAGED_RELAY_TOKEN_CACHE_VERSION,- entries,- }).pipe(- Effect.mapError(- (cause) =>- new ManagedRelayTokenStoreError({- operation: "encode",- storageKey: MANAGED_RELAY_TOKEN_CACHE_KEY,- cause,- }),- ),- Effect.flatMap((encoded) =>- Effect.tryPromise({- try: () => SecureStore.setItemAsync(MANAGED_RELAY_TOKEN_CACHE_KEY, encoded),- catch: (cause) =>- new ManagedRelayTokenStoreError({- operation: "write",- storageKey: MANAGED_RELAY_TOKEN_CACHE_KEY,- cause,- }),- }),- ),- );--const clearManagedRelayAccessTokens = Effect.tryPromise({- try: () => SecureStore.deleteItemAsync(MANAGED_RELAY_TOKEN_CACHE_KEY),- catch: (cause) =>- new ManagedRelayTokenStoreError({- operation: "clear",- storageKey: MANAGED_RELAY_TOKEN_CACHE_KEY,- cause,- }),-});--export const managedRelayAccessTokenStore: ManagedRelay.ManagedRelayAccessTokenStore = {- load: loadManagedRelayAccessTokens.pipe(- Effect.tapError(logStoreFailure),- Effect.orElseSucceed(() => []),- Effect.withSpan("mobile.managedRelayTokenStore.load"),- ),- save: Effect.fn("mobile.managedRelayTokenStore.save")((entries) =>- saveManagedRelayAccessTokens(entries).pipe(Effect.tapError(logStoreFailure), Effect.ignore),- ),- clear: clearManagedRelayAccessTokens.pipe(- Effect.tapError(logStoreFailure),- Effect.ignore,- Effect.withSpan("mobile.managedRelayTokenStore.clear"),- ),-};diff --git a/apps/mobile/src/features/cloud/publicConfig.test.ts b/apps/mobile/src/features/cloud/publicConfig.test.tsdeleted file mode 100644index 05bf1a8fb..000000000--- a/apps/mobile/src/features/cloud/publicConfig.test.ts+++ /dev/null@@ -1,131 +0,0 @@-import { describe, expect, it, vi } from "vite-plus/test";--import {- CloudPublicConfigMissingError,- hasTracingPublicConfig,- resolveCloudPublicConfig,- resolveRelayClerkTokenOptions,-} from "./publicConfig";--vi.mock("expo-constants", () => ({- default: {- expoConfig: {- extra: {},- },- },-}));--describe("resolveCloudPublicConfig", () => {- it("reports the missing Clerk JWT template as structured configuration", () => {- expect(() => resolveRelayClerkTokenOptions()).toThrowError(- new CloudPublicConfigMissingError({ key: "T3CODE_CLERK_JWT_TEMPLATE" }),- );- });-- it("returns no cloud configuration for an unconfigured build", () => {- expect(resolveCloudPublicConfig({})).toEqual({- clerk: {- publishableKey: null,- jwtTemplate: null,- },- relay: {- url: null,- },- observability: {- tracesUrl: null,- tracesDataset: null,- tracesToken: null,- },- });- });-- it("normalizes statically injected cloud configuration", () => {- expect(- resolveCloudPublicConfig({- clerk: { publishableKey: " pk_test_example ", jwtTemplate: " t3-relay " },- relay: { url: " https://relay.example.test/// " },- observability: {- tracesUrl: " https://api.axiom.co/v1/traces ",- tracesDataset: " mobile-traces ",- tracesToken: " public-ingest-token ",- },- }),- ).toEqual({- clerk: {- publishableKey: "pk_test_example",- jwtTemplate: "t3-relay",- },- relay: {- url: "https://relay.example.test",- },- observability: {- tracesUrl: "https://api.axiom.co/v1/traces",- tracesDataset: "mobile-traces",- tracesToken: "public-ingest-token",- },- });- });-- it("rejects an insecure relay URL", () => {- expect(- resolveCloudPublicConfig({- clerk: { publishableKey: "pk_test_example", jwtTemplate: "t3-relay" },- relay: { url: "http://relay.example.test" },- }),- ).toEqual({- clerk: {- publishableKey: "pk_test_example",- jwtTemplate: "t3-relay",- },- relay: {- url: null,- },- observability: {- tracesUrl: null,- tracesDataset: null,- tracesToken: null,- },- });- });-- it("rejects an insecure traces URL", () => {- expect(- resolveCloudPublicConfig({- observability: {- tracesUrl: "http://api.axiom.co/v1/traces",- tracesDataset: "mobile-traces",- tracesToken: "public-ingest-token",- },- }).observability,- ).toEqual({- tracesUrl: null,- tracesDataset: "mobile-traces",- tracesToken: "public-ingest-token",- });- });-- it("keeps tracing disabled unless every public tracing value is configured", () => {- expect(hasTracingPublicConfig(resolveCloudPublicConfig({}))).toBe(false);- expect(- hasTracingPublicConfig(- resolveCloudPublicConfig({- observability: {- tracesUrl: "https://api.axiom.co/v1/traces",- tracesDataset: "mobile-traces",- },- }),- ),- ).toBe(false);- expect(- hasTracingPublicConfig(- resolveCloudPublicConfig({- observability: {- tracesUrl: "https://api.axiom.co/v1/traces",- tracesDataset: "mobile-traces",- tracesToken: "public-ingest-token",- },- }),- ),- ).toBe(true);- });-});diff --git a/apps/mobile/src/features/cloud/publicConfig.ts b/apps/mobile/src/features/cloud/publicConfig.tsdeleted file mode 100644index 93a78fa4f..000000000--- a/apps/mobile/src/features/cloud/publicConfig.ts+++ /dev/null@@ -1,105 +0,0 @@-import Constants from "expo-constants";-import { relayClerkTokenOptions } from "@t3tools/shared/relayAuth";-import { normalizeSecureRelayUrl } from "@t3tools/shared/relayUrl";-import * as Schema from "effect/Schema";--export class CloudPublicConfigMissingError extends Schema.TaggedErrorClass<CloudPublicConfigMissingError>()(- "CloudPublicConfigMissingError",- {- key: Schema.Literal("T3CODE_CLERK_JWT_TEMPLATE"),- },-) {- override get message(): string {- return `${this.key} is not configured.`;- }-}--export interface CloudPublicConfig {- readonly clerk: {- readonly publishableKey: string | null;- readonly jwtTemplate: string | null;- };- readonly relay: {- readonly url: string | null;- };- readonly observability: {- readonly tracesUrl: string | null;- readonly tracesDataset: string | null;- readonly tracesToken: string | null;- };-}--type UntrustedSection<T> = {- readonly [Key in keyof T]?: unknown;-};--type ExpoExtra =- | {- readonly [Section in keyof CloudPublicConfig]?: UntrustedSection<CloudPublicConfig[Section]>;- }- | undefined;--function trimNonEmpty(value: unknown): string | null {- return typeof value === "string" && value.trim() ? value.trim() : null;-}--function normalizeSecureUrl(value: unknown): string | null {- const raw = trimNonEmpty(value);- if (raw === null) {- return null;- }- try {- const url = new URL(raw);- return url.protocol === "https:" ? url.toString() : null;- } catch {- return null;- }-}--export function resolveCloudPublicConfig(extra: ExpoExtra = Constants.expoConfig?.extra) {- return {- clerk: {- publishableKey: trimNonEmpty(extra?.clerk?.publishableKey),- jwtTemplate: trimNonEmpty(extra?.clerk?.jwtTemplate),- },- relay: {- url: normalizeSecureRelayUrl(trimNonEmpty(extra?.relay?.url) ?? ""),- },- observability: {- tracesUrl: normalizeSecureUrl(extra?.observability?.tracesUrl),- tracesDataset: trimNonEmpty(extra?.observability?.tracesDataset),- tracesToken: trimNonEmpty(extra?.observability?.tracesToken),- },- } satisfies CloudPublicConfig;-}--export function hasCloudPublicConfig(): boolean {- const config = resolveCloudPublicConfig();- return Boolean(config.clerk.publishableKey && config.clerk.jwtTemplate && config.relay.url);-}--type Configured<T> = {- readonly [Key in keyof T]: NonNullable<T[Key]>;-};--type TracingPublicConfig = Omit<CloudPublicConfig, "observability"> & {- readonly observability: Configured<CloudPublicConfig["observability"]>;-};--export function hasTracingPublicConfig(- config: CloudPublicConfig = resolveCloudPublicConfig(),-): config is TracingPublicConfig {- return Boolean(- config.observability.tracesUrl &&- config.observability.tracesDataset &&- config.observability.tracesToken,- );-}--export function resolveRelayClerkTokenOptions() {- const { jwtTemplate } = resolveCloudPublicConfig().clerk;- if (!jwtTemplate) {- throw new CloudPublicConfigMissingError({ key: "T3CODE_CLERK_JWT_TEMPLATE" });- }- return relayClerkTokenOptions(jwtTemplate);-}diff --git a/apps/mobile/src/features/connection/CloudEnvironmentRows.tsx b/apps/mobile/src/features/connection/CloudEnvironmentRows.tsxdeleted file mode 100644index 6da73eaeb..000000000--- a/apps/mobile/src/features/connection/CloudEnvironmentRows.tsx+++ /dev/null@@ -1,414 +0,0 @@-import { useAuth } from "@clerk/expo";-import { SymbolView } from "../../components/AppSymbol";-import {- connectionStatusText,- type EnvironmentConnectionPhase,-} from "@t3tools/client-runtime/connection";-import type { EnvironmentId } from "@t3tools/contracts";-import { useCallback, useState } from "react";-import {- ActivityIndicator,- Pressable,- type NativeSyntheticEvent,- type TextLayoutEventData,- View,-} from "react-native";--import { AppText as Text } from "../../components/AppText";-import { ThemedSwitch } from "../../components/ThemedSwitch";-import { cn } from "../../lib/cn";-import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";-import { useThemeColor } from "../../lib/useThemeColor";-import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";-import { availableCloudEnvironmentPresentation } from "../cloud/cloudEnvironmentPresentation";-import { hasCloudPublicConfig } from "../cloud/publicConfig";-import { ConnectionStatusDot } from "./ConnectionStatusDot";-import { type RelayEnvironmentView, useConnectionController } from "./useConnectionController";--interface CloudEnvironmentRowsProps {- readonly connectedCloudEnvironments: ReadonlyArray<ConnectedEnvironmentSummary>;- readonly onReconnectEnvironment: (environmentId: EnvironmentId) => void;- readonly showcaseAvailableEnvironments?: ReadonlyArray<RelayEnvironmentView>;- readonly showcaseSignedIn?: boolean;- /**- * Hide the "T3 Connect" section title + refresh button for hosts that- * provide their own chrome (the onboarding sheet's native header and- * pull-to-refresh).- */- readonly showHeader?: boolean;-}--/**- * "T3 Connect" section: every environment published to the signed-in account,- * with connect switches, availability status, refresh, and loading/error- * states. Shared between the Settings environments screen and the T3 Connect- * onboarding sheet.- *- * Already-connected relay environments render even without cloud config or a- * signed-in account — they are registered on this device and must stay- * reachable and removable. Only discovery (the available list, refresh, and- * its errors) requires a signed-in session.- */-export function CloudEnvironmentRows(props: CloudEnvironmentRowsProps) {- // Showcase captures run without a Clerk publishable key, so `ClerkProvider`- // is never mounted and any `useAuth` call throws — the fixture states whether- // the rows are signed in instead of asking Clerk.- if (props.showcaseSignedIn !== undefined) {- return props.showcaseSignedIn ? <CloudEnvironmentRowsContent {...props} /> : null;- }- // No cloud config means no `ClerkProvider` either, so `useAuth` would throw.- if (!hasCloudPublicConfig()) {- return <ConnectedOnlyCloudEnvironmentRows {...props} />;- }- return <SignedInCloudEnvironmentRows {...props} />;-}--function SignedInCloudEnvironmentRows(props: CloudEnvironmentRowsProps) {- const { isSignedIn } = useAuth({ treatPendingAsSignedOut: false });- if (!isSignedIn) return <ConnectedOnlyCloudEnvironmentRows {...props} />;- return <CloudEnvironmentRowsContent {...props} />;-}--function ConnectedOnlyCloudEnvironmentRows(props: CloudEnvironmentRowsProps) {- if (props.connectedCloudEnvironments.length === 0) return null;- return <CloudEnvironmentRowsContent {...props} discoveryAvailable={false} />;-}--function CloudEnvironmentRowsContent(- props: CloudEnvironmentRowsProps & { readonly discoveryAvailable?: boolean },-) {- const controller = useConnectionController();- const iconColor = useThemeColor("--color-icon");- const discoveryAvailable = props.discoveryAvailable ?? true;- const availableCloudEnvironments = discoveryAvailable- ? (props.showcaseAvailableEnvironments ?? controller.availableRelayEnvironments)- : [];- const [expandedErrorId, setExpandedErrorId] = useState<string | null>(null);- const hasCloudRows =- props.connectedCloudEnvironments.length > 0 || availableCloudEnvironments.length > 0;-- const handleConnectCloudEnvironment = useCallback(- (entry: RelayEnvironmentView) => controller.connectRelayEnvironment(entry.environment),- [controller],- );-- const handleDisconnectCloudEnvironment = useCallback(- (environmentId: EnvironmentId) => controller.removeEnvironment(environmentId),- [controller],- );-- const handleToggleCloudError = useCallback((environmentId: string) => {- setExpandedErrorId((current) => (current === environmentId ? null : environmentId));- }, []);-- const showHeader = props.showHeader ?? true;-- return (- <View collapsable={false} className={cn("gap-3", showHeader && "mt-5")}>- {showHeader ? (- <View className="flex-row items-center justify-between px-1">- <Text className="text-sm font-t3-bold uppercase text-foreground-muted">T3 Connect</Text>- {discoveryAvailable ? (- <Pressable- accessibilityRole="button"- disabled={controller.relayDiscovery.isRefreshing}- onPress={() => {- void controller.refreshRelayEnvironments();- }}- className="h-9 w-9 items-center justify-center rounded-full bg-subtle active:opacity-70 disabled:opacity-50"- >- {controller.relayDiscovery.isRefreshing ? (- <ActivityIndicator color={iconColor} size="small" />- ) : (- <SymbolView- name="arrow.clockwise"- size={14}- tintColor={iconColor}- type="monochrome"- />- )}- </Pressable>- ) : null}- </View>- ) : null}-- {hasCloudRows ? (- <View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">- {props.connectedCloudEnvironments.map((environment, index) => (- <ConnectedCloudEnvironmentRow- key={environment.environmentId}- environment={environment}- borderTop={index !== 0}- onConnect={() => props.onReconnectEnvironment(environment.environmentId)}- onDisconnect={() => handleDisconnectCloudEnvironment(environment.environmentId)}- errorExpanded={expandedErrorId === environment.environmentId}- onToggleError={() => handleToggleCloudError(environment.environmentId)}- />- ))}- {availableCloudEnvironments.map((environment, index) => (- <CloudEnvironmentRow- key={environment.environment.environmentId}- environment={environment}- borderTop={props.connectedCloudEnvironments.length > 0 || index !== 0}- onConnect={() => handleConnectCloudEnvironment(environment)}- errorExpanded={expandedErrorId === environment.environment.environmentId}- onToggleError={() => handleToggleCloudError(environment.environment.environmentId)}- />- ))}- </View>- ) : controller.relayDiscovery.isRefreshing ? (- <View collapsable={false} className="items-center gap-3 rounded-[24px] bg-card p-6">- <ActivityIndicator color={iconColor} />- <Text className="text-center text-sm leading-normal text-foreground-muted">- Loading linked cloud environments.- </Text>- </View>- ) : controller.relayDiscovery.error ? null : (- <View collapsable={false} className="rounded-[24px] bg-card p-5">- <Text className="text-sm leading-normal text-foreground-muted">- No additional linked cloud environments.- </Text>- </View>- )}-- {/* Rendered alongside any connected rows — a failed discovery must not- hide behind an otherwise-healthy list. */}- {discoveryAvailable &&- controller.relayDiscovery.error &&- !controller.relayDiscovery.isRefreshing ? (- <View collapsable={false} className="gap-3 rounded-[24px] bg-card p-5">- <Text className="text-base font-t3-bold text-foreground">- Could not load T3 Connect environments- </Text>- <Text className="text-sm text-foreground-muted">{controller.relayDiscovery.error}</Text>- {controller.relayDiscovery.errorTraceId ? (- <CopyTraceIdButton traceId={controller.relayDiscovery.errorTraceId} />- ) : null}- <Pressable- accessibilityRole="button"- onPress={() => {- void controller.refreshRelayEnvironments();- }}- className="self-start rounded-full bg-subtle px-3.5 py-2 active:opacity-70"- >- <Text className="text-xs font-t3-bold text-foreground">Try again</Text>- </Pressable>- </View>- ) : null}- </View>- );-}--function ConnectedCloudEnvironmentRow(props: {- readonly environment: ConnectedEnvironmentSummary;- readonly borderTop: boolean;- readonly errorExpanded: boolean;- readonly onConnect: () => void;- readonly onDisconnect: () => void;- readonly onToggleError: () => void;-}) {- return (- <CloudEnvironmentRowShell- borderTop={props.borderTop}- connectionError={props.environment.connectionError}- connectionErrorTraceId={props.environment.connectionErrorTraceId}- connectionState={props.environment.connectionState}- errorExpanded={props.errorExpanded}- label={props.environment.environmentLabel}- onValueChange={(enabled) => {- if (enabled) {- props.onConnect();- return;- }- props.onDisconnect();- }}- onToggleError={props.onToggleError}- value={props.environment.connectionState !== "available"}- />- );-}--function CloudEnvironmentRow(props: {- readonly environment: RelayEnvironmentView;- readonly borderTop: boolean;- readonly errorExpanded: boolean;- readonly onConnect: () => void;- readonly onToggleError: () => void;-}) {- const presentation = availableCloudEnvironmentPresentation({- isStatusPending: props.environment.availability === "checking",- status: props.environment.status,- statusError: props.environment.error,- statusErrorTraceId: props.environment.traceId,- });-- return (- <CloudEnvironmentRowShell- borderTop={props.borderTop}- connectionError={presentation.connectionError}- connectionErrorTraceId={presentation.connectionErrorTraceId}- connectionState={presentation.connectionState}- errorExpanded={props.errorExpanded}- label={props.environment.environment.label}- onValueChange={(enabled) => {- if (enabled) {- props.onConnect();- }- }}- onToggleError={props.onToggleError}- statusText={presentation.statusText}- value={false}- />- );-}--function CloudEnvironmentRowShell(props: {- readonly borderTop: boolean;- readonly connectionError: string | null;- readonly connectionErrorTraceId: string | null;- readonly connectionState: EnvironmentConnectionPhase;- readonly disabled?: boolean;- readonly errorExpanded: boolean;- readonly label: string;- readonly onToggleError: () => void;- readonly onValueChange: (enabled: boolean) => void;- readonly statusText?: string;- readonly value: boolean;-}) {- const chevron = useThemeColor("--color-chevron");- const isRetrying =- props.connectionState === "connecting" || props.connectionState === "reconnecting";- const shouldPulse = isRetrying;- const statusText =- props.statusText ??- connectionStatusText({- phase: props.connectionState,- error: props.connectionError,- traceId: props.connectionErrorTraceId,- });- const statusClassName = props.connectionError- ? "text-rose-500 dark:text-rose-400"- : "text-foreground-muted";- const [errorMeasurement, setErrorMeasurement] = useState<{- readonly text: string;- readonly lineCount: number;- } | null>(null);- const errorTraceId = props.connectionErrorTraceId;- const measuredErrorText = errorTraceId ? `${statusText} Trace ID: ${errorTraceId}` : statusText;- const errorLineCount =- errorMeasurement?.text === measuredErrorText ? errorMeasurement.lineCount : 0;- const errorCanExpand = props.connectionError !== null && errorLineCount > 1;- const isErrorExpanded = errorCanExpand && props.errorExpanded;- const StatusContainer = errorCanExpand ? Pressable : View;- const onMeasuredErrorTextLayout = useCallback(- (event: NativeSyntheticEvent<TextLayoutEventData>) => {- if (!props.connectionError) {- return;- }- const nextLineCount = event.nativeEvent.lines.length;- setErrorMeasurement((currentMeasurement) =>- currentMeasurement?.text === measuredErrorText &&- currentMeasurement.lineCount === nextLineCount- ? currentMeasurement- : { text: measuredErrorText, lineCount: nextLineCount },- );- },- [measuredErrorText, props.connectionError],- );- return (- <View- collapsable={false}- className={cn(- "flex-row items-center gap-3 bg-card px-4 py-3.5",- props.borderTop && "border-t border-border",- )}- >- <View className="min-w-0 flex-1 gap-0.5">- <View className="min-w-0 flex-row items-center gap-2">- <ConnectionStatusDot state={props.connectionState} pulse={shouldPulse} size={7} />- <Text- className="min-w-0 flex-shrink text-base font-t3-bold leading-snug text-foreground"- numberOfLines={1}- >- {props.label}- </Text>- </View>- {props.connectionError ? (- <Text- aria-hidden- onTextLayout={onMeasuredErrorTextLayout}- className={cn("absolute inset-x-0 -z-[1] text-xs opacity-0", statusClassName)}- >- {measuredErrorText}- </Text>- ) : null}- <StatusContainer- {...(errorCanExpand- ? { accessibilityRole: "button" as const, onPress: props.onToggleError }- : {})}- className="min-w-0 flex-row items-start gap-1"- >- <Text- className={cn("min-w-0 flex-1 text-xs", statusClassName)}- numberOfLines={isErrorExpanded ? undefined : 1}- >- {statusText}- {errorTraceId ? (- <>- {" Trace ID: "}- <Text- accessibilityHint="Copies the trace ID"- accessibilityRole="button"- className={cn("text-xs underline decoration-dotted", statusClassName)}- onLongPress={(event) => {- event.stopPropagation();- copyTextWithHaptic(errorTraceId, { target: "connection-trace-id" });- }}- onPress={(event) => {- event.stopPropagation();- }}- >- {errorTraceId}- </Text>- </>- ) : null}- </Text>- {errorCanExpand ? (- <SymbolView- name="chevron.down"- size={10}- tintColor={chevron}- type="monochrome"- style={{- marginTop: 3,- transform: [{ rotate: isErrorExpanded ? "180deg" : "0deg" }],- }}- />- ) : null}- </StatusContainer>- </View>- <ThemedSwitch- disabled={props.disabled}- onValueChange={props.onValueChange}- value={props.value}- />- </View>- );-}--function CopyTraceIdButton(props: { readonly traceId: string }) {- const iconColor = useThemeColor("--color-icon");-- return (- <Pressable- accessibilityRole="button"- onPress={() => {- copyTextWithHaptic(props.traceId, { target: "connection-trace-id" });- }}- className="self-start flex-row items-center gap-1.5 rounded-full bg-subtle px-3 py-2 active:opacity-70"- >- <SymbolView name="doc.on.doc" size={12} tintColor={iconColor} type="monochrome" />- <Text className="text-xs font-t3-bold text-foreground">Copy trace ID</Text>- </Pressable>- );-}diff --git a/apps/mobile/src/features/connection/ConnectionEnvironmentRow.tsx b/apps/mobile/src/features/connection/ConnectionEnvironmentRow.tsxindex 03a0eb502..da3df0325 100644--- a/apps/mobile/src/features/connection/ConnectionEnvironmentRow.tsx+++ b/apps/mobile/src/features/connection/ConnectionEnvironmentRow.tsx@@ -131,55 +131,45 @@ export function ConnectionEnvironmentRow(props: {exiting={FadeOut.duration(150)}className="gap-3 px-4 pb-4">- {props.environment.isRelayManaged ? (- <Text className="text-sm text-foreground-muted">- Managed by T3 Connect. Tunnel details update automatically.+ <View className="gap-1.5">+ <Text className="text-2xs font-t3-bold tracking-[0.8px] uppercase text-foreground-muted">+ Label</Text>- ) : (- <>- <View className="gap-1.5">- <Text className="text-2xs font-t3-bold tracking-[0.8px] uppercase text-foreground-muted">- Label- </Text>- <TextInput- autoCapitalize="words"- autoCorrect={false}- placeholder="My MacBook"- value={label}- onChangeText={setLabel}- className="rounded-[14px] border border-input-border bg-input px-4 py-3 text-base text-foreground"- />- </View>+ <TextInput+ autoCapitalize="words"+ autoCorrect={false}+ placeholder="My MacBook"+ value={label}+ onChangeText={setLabel}+ className="rounded-[14px] border border-input-border bg-input px-4 py-3 text-base text-foreground"+ />+ </View>- <View className="gap-1.5">- <Text className="text-2xs font-t3-bold tracking-[0.8px] uppercase text-foreground-muted">- URL- </Text>- <TextInput- autoCapitalize="none"- autoCorrect={false}- keyboardType="url"- placeholder="192.168.1.100:8080"- value={url}- onChangeText={setUrl}- className="rounded-[14px] border border-input-border bg-input px-4 py-3 text-base text-foreground"- />- </View>- </>- )}+ <View className="gap-1.5">+ <Text className="text-2xs font-t3-bold tracking-[0.8px] uppercase text-foreground-muted">+ URL+ </Text>+ <TextInput+ autoCapitalize="none"+ autoCorrect={false}+ keyboardType="url"+ placeholder="192.168.1.100:8080"+ value={url}+ onChangeText={setUrl}+ className="rounded-[14px] border border-input-border bg-input px-4 py-3 text-base text-foreground"+ />+ </View><View className="flex-row justify-end gap-2">- {props.environment.isRelayManaged ? null : (- <Pressable- className="min-h-[42px] flex-1 flex-row items-center justify-center gap-1.5 rounded-[14px] bg-primary px-3.5 py-2.5 active:opacity-70"- onPress={handleSave}- >- <SymbolView name="checkmark" size={13} tintColor={primaryFg} type="monochrome" />- <Text className="text-xs font-t3-bold tracking-[0.8px] uppercase text-primary-foreground">- Save- </Text>- </Pressable>- )}+ <Pressable+ className="min-h-[42px] flex-1 flex-row items-center justify-center gap-1.5 rounded-[14px] bg-primary px-3.5 py-2.5 active:opacity-70"+ onPress={handleSave}+ >+ <SymbolView name="checkmark" size={13} tintColor={primaryFg} type="monochrome" />+ <Text className="text-xs font-t3-bold tracking-[0.8px] uppercase text-primary-foreground">+ Save+ </Text>+ </Pressable><PressableclassName="h-[42px] w-[42px] items-center justify-center rounded-[14px] border border-input-border bg-input active:opacity-70"diff --git a/apps/mobile/src/features/connection/environmentSections.test.ts b/apps/mobile/src/features/connection/environmentSections.test.tsdeleted file mode 100644index 6d07f40a5..000000000--- a/apps/mobile/src/features/connection/environmentSections.test.ts+++ /dev/null@@ -1,159 +0,0 @@-import { EnvironmentId } from "@t3tools/contracts";-import type { RelayClientEnvironmentRecord } from "@t3tools/contracts/relay";-import { describe, expect, it } from "vite-plus/test";-import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";-import { relayManagedEnvironmentIds, splitEnvironmentSections } from "./environmentSections";--function connectedEnvironment(- input: Omit<Partial<ConnectedEnvironmentSummary>, "environmentId"> & {- readonly environmentId: string;- readonly isRelayManaged: boolean;- },-): ConnectedEnvironmentSummary {- return {- environmentId: EnvironmentId.make(input.environmentId),- environmentLabel: input.environmentLabel ?? input.environmentId,- displayUrl: input.displayUrl ?? `https://${input.environmentId}.example.test/`,- isRelayManaged: input.isRelayManaged,- connectionState: input.connectionState ?? "connected",- connectionError: input.connectionError ?? null,- connectionErrorTraceId: input.connectionErrorTraceId ?? null,- };-}--function cloudEnvironment(environmentId: string): RelayClientEnvironmentRecord {- return {- environmentId: EnvironmentId.make(environmentId),- label: environmentId,- endpoint: {- httpBaseUrl: `https://${environmentId}.cloud.example.test/`,- wsBaseUrl: `wss://${environmentId}.cloud.example.test/ws`,- providerKind: "cloudflare_tunnel",- },- linkedAt: "2026-01-01T00:00:00.000Z",- };-}--describe("relayManagedEnvironmentIds", () => {- it("leaves out a backend that was saved directly", () => {- const ids = relayManagedEnvironmentIds([- connectedEnvironment({ environmentId: "environment-local", isRelayManaged: false }),- connectedEnvironment({ environmentId: "environment-cloud", isRelayManaged: true }),- ]);-- expect([...ids]).toEqual([EnvironmentId.make("environment-cloud")]);- });-});--describe("mobile environment settings sections", () => {- it("keeps saved relay-managed connections under T3 Connect", () => {- const local = connectedEnvironment({- environmentId: "environment-local",- isRelayManaged: false,- });- const cloud = connectedEnvironment({- environmentId: "environment-cloud",- isRelayManaged: true,- });-- const sections = splitEnvironmentSections({- connectedEnvironments: [cloud, local],- cloudEnvironments: [- cloudEnvironment("environment-cloud"),- cloudEnvironment("environment-new"),- ],- });-- expect(sections.localEnvironments).toEqual([local]);- expect(sections.connectedCloudEnvironments).toEqual([cloud]);- expect(- sections.availableCloudEnvironments.map((environment) => environment.environmentId),- ).toEqual([EnvironmentId.make("environment-new")]);- });-- it("keeps saved relay-managed connections visible when cloud listing is unavailable", () => {- const cloud = connectedEnvironment({- environmentId: "environment-cloud",- isRelayManaged: true,- connectionState: "reconnecting",- connectionError: "Environment did not respond before the connection timeout.",- });-- const sections = splitEnvironmentSections({- connectedEnvironments: [cloud],- cloudEnvironments: null,- });-- expect(sections.localEnvironments).toEqual([]);- expect(sections.connectedCloudEnvironments).toEqual([cloud]);- expect(sections.availableCloudEnvironments).toEqual([]);- });-- it("keeps an available saved relay environment as a fallback when listing is unavailable", () => {- const cloud = connectedEnvironment({- environmentId: "environment-cloud",- isRelayManaged: true,- connectionState: "available",- });-- const sections = splitEnvironmentSections({- connectedEnvironments: [cloud],- cloudEnvironments: null,- });-- expect(sections.connectedCloudEnvironments).toEqual([cloud]);- expect(sections.availableCloudEnvironments).toEqual([]);- });-- it("does not duplicate a saved relay environment in the available cloud listing", () => {- const cloud = connectedEnvironment({- environmentId: "environment-cloud",- isRelayManaged: true,- connectionState: "available",- });- const listedCloud = cloudEnvironment("environment-cloud");-- const sections = splitEnvironmentSections({- connectedEnvironments: [cloud],- cloudEnvironments: [listedCloud],- });-- expect(sections.connectedCloudEnvironments).toEqual([cloud]);- expect(sections.availableCloudEnvironments).toEqual([]);- });-- it("still offers a cloud environment saved directly as a local backend", () => {- const local = connectedEnvironment({- environmentId: "environment-cloud",- isRelayManaged: false,- });-- const sections = splitEnvironmentSections({- connectedEnvironments: [local],- cloudEnvironments: [cloudEnvironment("environment-cloud")],- });-- expect(sections.localEnvironments).toEqual([local]);- expect(sections.connectedCloudEnvironments).toEqual([]);- expect(- sections.availableCloudEnvironments.map((environment) => environment.environmentId),- ).toEqual([EnvironmentId.make("environment-cloud")]);- });-- it("keeps failed relay environments in the local connection row", () => {- const cloud = connectedEnvironment({- environmentId: "environment-cloud",- isRelayManaged: true,- connectionState: "error",- connectionError: "Connection failed.",- });-- const sections = splitEnvironmentSections({- connectedEnvironments: [cloud],- cloudEnvironments: [cloudEnvironment("environment-cloud")],- });-- expect(sections.connectedCloudEnvironments).toEqual([cloud]);- expect(sections.availableCloudEnvironments).toEqual([]);- });-});diff --git a/apps/mobile/src/features/connection/environmentSections.ts b/apps/mobile/src/features/connection/environmentSections.tsdeleted file mode 100644index 10ba636dc..000000000--- a/apps/mobile/src/features/connection/environmentSections.ts+++ /dev/null@@ -1,47 +0,0 @@-import type { EnvironmentId } from "@t3tools/contracts";-import type { RelayClientEnvironmentRecord } from "@t3tools/contracts/relay";-import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";--export interface EnvironmentSectionsInput {- readonly connectedEnvironments: ReadonlyArray<ConnectedEnvironmentSummary>;- readonly cloudEnvironments: ReadonlyArray<RelayClientEnvironmentRecord> | null;-}--export interface EnvironmentSections {- readonly localEnvironments: ReadonlyArray<ConnectedEnvironmentSummary>;- readonly connectedCloudEnvironments: ReadonlyArray<ConnectedEnvironmentSummary>;- readonly availableCloudEnvironments: ReadonlyArray<RelayClientEnvironmentRecord>;-}--/**- * Ids of the environments that already occupy a T3 Connect slot. A backend saved directly is- * not one of them, so it must not suppress the cloud environment that happens to share its id.- */-export function relayManagedEnvironmentIds(- environments: ReadonlyArray<{- readonly environmentId: EnvironmentId;- readonly isRelayManaged: boolean;- }>,-): ReadonlySet<EnvironmentId> {- return new Set(- environments- .filter((environment) => environment.isRelayManaged)- .map((environment) => environment.environmentId),- );-}--export function splitEnvironmentSections(input: EnvironmentSectionsInput): EnvironmentSections {- const savedEnvironmentIds = relayManagedEnvironmentIds(input.connectedEnvironments);-- return {- localEnvironments: input.connectedEnvironments.filter(- (environment) => !environment.isRelayManaged,- ),- connectedCloudEnvironments: input.connectedEnvironments.filter(- (environment) => environment.isRelayManaged,- ),- availableCloudEnvironments: (input.cloudEnvironments ?? []).filter(- (environment) => !savedEnvironmentIds.has(environment.environmentId),- ),- };-}diff --git a/apps/mobile/src/features/connection/useConnectionController.ts b/apps/mobile/src/features/connection/useConnectionController.tsindex faa344775..941c4299c 100644--- a/apps/mobile/src/features/connection/useConnectionController.ts+++ b/apps/mobile/src/features/connection/useConnectionController.ts@@ -1,14 +1,4 @@-import { useAtomValue } from "@effect/atom-react";-import {- RelayConnectionRegistration,- RelayConnectionTarget,-} from "@t3tools/client-runtime/connection";import type { EnvironmentId } from "@t3tools/contracts";-import type {- RelayClientEnvironmentRecord,- RelayEnvironmentStatusResponse,-} from "@t3tools/contracts/relay";-import * as Option from "effect/Option";import { useCallback, useMemo } from "react";import { environmentCatalog } from "../../connection/catalog";@@ -17,74 +7,26 @@ import {updateBearerConnection,} from "../../connection/onboarding";import { useEnvironments } from "../../state/environments";-import { relayEnvironmentDiscovery } from "../../state/relay";import { useAtomCommand } from "../../state/use-atom-command";import { projectWorkspaceEnvironment, type WorkspaceEnvironment } from "../../state/workspaceModel";-import { relayManagedEnvironmentIds } from "./environmentSections";--export interface RelayEnvironmentView {- readonly environment: RelayClientEnvironmentRecord;- readonly availability: "checking" | "online" | "offline" | "error";- readonly status: RelayEnvironmentStatusResponse | null;- readonly error: string | null;- readonly traceId: string | null;-}export function useConnectionController() {const { environments } = useEnvironments();- const discovery = useAtomValue(relayEnvironmentDiscovery.stateValueAtom);const connectPairingUrlMutation = useAtomCommand(connectPairingUrlAtom, {reportFailure: false,});const updateBearer = useAtomCommand(updateBearerConnection, { reportFailure: false });- const registerEnvironment = useAtomCommand(environmentCatalog.register, "environment register");const removeEnvironmentMutation = useAtomCommand(environmentCatalog.remove, "environment remove");const retryEnvironmentMutation = useAtomCommand(environmentCatalog.retryNow, "environment retry");- const refreshRelayEnvironments = useAtomCommand(- relayEnvironmentDiscovery.refresh,- "relay environment refresh",- );const connectedEnvironments = useMemo<ReadonlyArray<WorkspaceEnvironment>>(() => environments.map(projectWorkspaceEnvironment),[environments],);- const registeredIds = useMemo(- () => relayManagedEnvironmentIds(connectedEnvironments),- [connectedEnvironments],- );- const relayEnvironments = useMemo<ReadonlyArray<RelayEnvironmentView>>(- () =>- [...discovery.environments.values()].map((entry) => ({- environment: entry.environment,- availability: entry.availability,- status: Option.getOrNull(entry.status),- error: Option.getOrNull(entry.error)?.message ?? null,- traceId: Option.getOrNull(entry.error)?.traceId ?? null,- })),- [discovery.environments],- );- const availableRelayEnvironments = useMemo(- () => relayEnvironments.filter((entry) => !registeredIds.has(entry.environment.environmentId)),- [registeredIds, relayEnvironments],- );-const connectPairingUrl = useCallback((pairingUrl: string) => connectPairingUrlMutation(pairingUrl),[connectPairingUrlMutation],);- const connectRelayEnvironment = useCallback(- (environment: RelayClientEnvironmentRecord) =>- registerEnvironment(- new RelayConnectionRegistration({- target: new RelayConnectionTarget({- environmentId: environment.environmentId,- label: environment.label,- }),- }),- ),- [registerEnvironment],- );const removeEnvironment = useCallback((environmentId: EnvironmentId) => removeEnvironmentMutation(environmentId),[removeEnvironmentMutation],@@ -108,19 +50,9 @@ export function useConnectionController() {return {connectedEnvironments,- relayEnvironments,- availableRelayEnvironments,- relayDiscovery: {- isRefreshing: discovery.refreshing,- isOffline: discovery.offline,- error: Option.getOrNull(discovery.error)?.message ?? null,- errorTraceId: Option.getOrNull(discovery.error)?.traceId ?? null,- },connectPairingUrl,- connectRelayEnvironment,removeEnvironment,retryEnvironment,updateEnvironment,- refreshRelayEnvironments,};}diff --git a/apps/mobile/src/features/home/workspace-connection-status.test.ts b/apps/mobile/src/features/home/workspace-connection-status.test.tsindex 15a990bb1..1fb2cb7ba 100644--- a/apps/mobile/src/features/home/workspace-connection-status.test.ts+++ b/apps/mobile/src/features/home/workspace-connection-status.test.ts@@ -46,7 +46,6 @@ describe("workspace connection status", () => {environmentId: "environment-1" as never,environmentLabel: "Julius’s Mac mini",displayUrl: "",- isRelayManaged: false,connectionState: "reconnecting",connectionError: null,connectionErrorTraceId: null,@@ -99,7 +98,6 @@ describe("workspace connection status", () => {environmentId: "environment-1" as never,environmentLabel: "Julius’s Mac mini",displayUrl: "",- isRelayManaged: false,connectionState: "reconnecting",connectionError: null,connectionErrorTraceId: null,diff --git a/apps/mobile/src/features/observability/tracing.test.ts b/apps/mobile/src/features/observability/tracing.test.tsdeleted file mode 100644index b0deb15be..000000000--- a/apps/mobile/src/features/observability/tracing.test.ts+++ /dev/null@@ -1,97 +0,0 @@-import { expect, it } from "@effect/vitest";-import * as Cause from "effect/Cause";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";-import { vi } from "vite-plus/test";--import { remoteHttpClientLayer } from "@t3tools/client-runtime/rpc";-import { withRelayClientTracing } from "@t3tools/shared/relayTracing";--import { makeTracingLayer } from "./tracing";--vi.mock("expo-constants", () => ({- default: {- expoConfig: {- extra: {},- },- },-}));--it.effect("exports spans through the scoped mobile OTLP layer", () => {- const fetchFn = vi.fn<typeof fetch>(async () => new Response(null, { status: 202 }));- const tracingLayer = makeTracingLayer(- {- tracesUrl: "https://api.axiom.test/v1/traces",- tracesDataset: "mobile-traces",- tracesToken: "public-ingest-token",- },- {- appVariant: "test",- serviceVersion: "1.2.3",- },- ).pipe(Layer.provide(remoteHttpClientLayer(fetchFn)));- const tracedApplication = Layer.effectDiscard(- Effect.void.pipe(Effect.withSpan("mobile.test.span"), withRelayClientTracing),- ).pipe(Layer.provide(tracingLayer));-- return Effect.gen(function* () {- yield* Layer.build(tracedApplication);-- expect(fetchFn).not.toHaveBeenCalled();- }).pipe(- Effect.scoped,- Effect.andThen(- Effect.sync(() => {- expect(fetchFn).toHaveBeenCalledOnce();- const [url, init] = fetchFn.mock.calls[0]!;- expect(String(url)).toBe("https://api.axiom.test/v1/traces");- expect(new Headers(init?.headers).get("authorization")).toBe("Bearer public-ingest-token");- expect(new Headers(init?.headers).get("x-axiom-dataset")).toBe("mobile-traces");- expect(new TextDecoder().decode(init?.body as Uint8Array)).toContain("mobile.test.span");- }),- ),- );-});--it.effect("does not let OTLP serialization failures alter application effects", () => {- const fetchFn = vi.fn<typeof fetch>(async () => new Response(null, { status: 202 }));- const tracingLayer = makeTracingLayer(- {- tracesUrl: "https://api.axiom.test/v1/traces",- tracesDataset: "mobile-traces",- tracesToken: "public-ingest-token",- },- {- appVariant: "test",- serviceVersion: "1.2.3",- },- ).pipe(Layer.provide(remoteHttpClientLayer(fetchFn)));- const failure = { durationNanos: 1n };- const tracedApplication = Layer.effectDiscard(- Effect.fail(failure).pipe(- Effect.withSpan("mobile.test.failed-span"),- withRelayClientTracing,- Effect.exit,- Effect.flatMap((exit) => {- const reason = exit._tag === "Failure" ? exit.cause.reasons[0] : undefined;- return reason && Cause.isFailReason(reason)- ? Effect.sync(() => {- expect(reason.error).toBe(failure);- })- : Effect.die(new Error("Expected the original typed failure."));- }),- ),- ).pipe(Layer.provide(tracingLayer));-- return Layer.build(tracedApplication).pipe(- Effect.scoped,- Effect.andThen(- Effect.sync(() => {- expect(fetchFn).toHaveBeenCalledOnce();- expect(new TextDecoder().decode(fetchFn.mock.calls[0]?.[1]?.body as Uint8Array)).toContain(- "mobile.test.failed-span",- );- }),- ),- );-});diff --git a/apps/mobile/src/features/observability/tracing.ts b/apps/mobile/src/features/observability/tracing.tsdeleted file mode 100644index eb73abba2..000000000--- a/apps/mobile/src/features/observability/tracing.ts+++ /dev/null@@ -1,41 +0,0 @@-import Constants from "expo-constants";-import { makeRelayClientTracingLayer } from "@t3tools/shared/relayTracing";--import { hasTracingPublicConfig, resolveCloudPublicConfig } from "../cloud/publicConfig";--export interface TracingConfig {- readonly tracesUrl: string;- readonly tracesDataset: string;- readonly tracesToken: string;-}--export interface TracingResource {- readonly serviceVersion?: string;- readonly appVariant: string;-}--export function resolveTracingConfig(): TracingConfig | null {- const config = resolveCloudPublicConfig();- if (!hasTracingPublicConfig(config)) {- return null;- }- const { tracesUrl, tracesDataset, tracesToken } = config.observability;- return { tracesUrl, tracesDataset, tracesToken };-}--export function makeTracingLayer(config: TracingConfig | null, resource: TracingResource) {- return makeRelayClientTracingLayer(config, {- serviceName: "t3-mobile-relay-client",- serviceVersion: resource.serviceVersion,- runtime: "react-native",- client: `mobile-${resource.appVariant}`,- });-}--export const tracingLayer = makeTracingLayer(resolveTracingConfig(), {- serviceVersion: Constants.expoConfig?.version,- appVariant:- typeof Constants.expoConfig?.extra?.appVariant === "string"- ? Constants.expoConfig.extra.appVariant- : "unknown",-});diff --git a/apps/mobile/src/features/settings/MobilePolicyNotice.logic.ts b/apps/mobile/src/features/settings/MobilePolicyNotice.logic.tsnew file mode 100644index 000000000..ded5d62ad--- /dev/null+++ b/apps/mobile/src/features/settings/MobilePolicyNotice.logic.ts@@ -0,0 +1,19 @@+import { AKERU_PRIVACY_POLICY_VERSION, AKERU_TERMS_VERSION } from "@t3tools/contracts/settings";++export function needsMobilePolicyAcknowledgement(preferences: {+ readonly reviewedPrivacyPolicyVersion?: string;+ readonly reviewedTermsVersion?: string;+}): boolean {+ return (+ preferences.reviewedPrivacyPolicyVersion !== AKERU_PRIVACY_POLICY_VERSION ||+ preferences.reviewedTermsVersion !== AKERU_TERMS_VERSION+ );+}++export function shouldShowMobilePolicyNotice(input: {+ readonly appVariant: string;+ readonly loaded: boolean;+ readonly needsAcknowledgement: boolean;+}): boolean {+ return input.loaded && input.appVariant !== "development" && input.needsAcknowledgement;+}diff --git a/apps/mobile/src/features/settings/MobilePolicyNotice.test.ts b/apps/mobile/src/features/settings/MobilePolicyNotice.test.tsnew file mode 100644index 000000000..0686d171d--- /dev/null+++ b/apps/mobile/src/features/settings/MobilePolicyNotice.test.ts@@ -0,0 +1,55 @@+import { describe, expect, it } from "@effect/vitest";++import {+ needsMobilePolicyAcknowledgement,+ shouldShowMobilePolicyNotice,+} from "./MobilePolicyNotice.logic";++describe("mobile policy notice", () => {+ it("requires the current local policy versions", () => {+ expect(needsMobilePolicyAcknowledgement({})).toBe(true);+ expect(+ needsMobilePolicyAcknowledgement({+ reviewedPrivacyPolicyVersion: "2026-08-31",+ reviewedTermsVersion: "2026-08-31",+ }),+ ).toBe(false);+ expect(+ needsMobilePolicyAcknowledgement({+ reviewedPrivacyPolicyVersion: "2026-08-31",+ reviewedTermsVersion: "older",+ }),+ ).toBe(true);+ });++ it("shows only after signed-build preferences load", () => {+ expect(+ shouldShowMobilePolicyNotice({+ appVariant: "production",+ loaded: true,+ needsAcknowledgement: true,+ }),+ ).toBe(true);+ expect(+ shouldShowMobilePolicyNotice({+ appVariant: "preview",+ loaded: true,+ needsAcknowledgement: true,+ }),+ ).toBe(true);+ expect(+ shouldShowMobilePolicyNotice({+ appVariant: "development",+ loaded: true,+ needsAcknowledgement: true,+ }),+ ).toBe(false);+ expect(+ shouldShowMobilePolicyNotice({+ appVariant: "production",+ loaded: false,+ needsAcknowledgement: true,+ }),+ ).toBe(false);+ });+});diff --git a/apps/mobile/src/features/settings/MobilePolicyNotice.tsx b/apps/mobile/src/features/settings/MobilePolicyNotice.tsxnew file mode 100644index 000000000..92c4b0a53--- /dev/null+++ b/apps/mobile/src/features/settings/MobilePolicyNotice.tsx@@ -0,0 +1,88 @@+import { useAtomSet, useAtomValue } from "@effect/atom-react";+import { AKERU_PRIVACY_POLICY_VERSION, AKERU_TERMS_VERSION } from "@t3tools/contracts/settings";+import Constants from "expo-constants";+import * as Linking from "expo-linking";+import { AsyncResult } from "effect/unstable/reactivity";+import { type ColorValue, Modal, Pressable, View } from "react-native";++import { AppText } from "../../components/AppText";+import { useThemeColor } from "../../lib/useThemeColor";+import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";+import { PRIVACY_POLICY_URL, TERMS_OF_SERVICE_URL } from "./lib/legal-document-url";+import {+ needsMobilePolicyAcknowledgement,+ shouldShowMobilePolicyNotice,+} from "./MobilePolicyNotice.logic";++export function MobilePolicyNotice() {+ const preferences = useAtomValue(mobilePreferencesAtom);+ const updatePreferences = useAtomSet(updateMobilePreferencesAtom);+ const pressedOverlay = useThemeColor("--color-subtle");+ const loaded = AsyncResult.isSuccess(preferences);+ const appVariant =+ (Constants.expoConfig?.extra?.appVariant as string | undefined) ?? "development";+ const visible = shouldShowMobilePolicyNotice({+ appVariant,+ loaded,+ needsAcknowledgement: loaded && needsMobilePolicyAcknowledgement(preferences.value),+ });++ return (+ <Modal visible={visible} transparent animationType="fade" statusBarTranslucent>+ <View className="flex-1 items-center justify-center bg-backdrop px-8">+ <View className="w-full rounded-[24px] bg-card px-6 pb-4 pt-5">+ <AppText className="text-lg font-t3-medium">Review Akeru Bot policies</AppText>+ <AppText className="mt-2 text-sm text-foreground-secondary">+ Akeru Bot runs locally. Provider prompts and enabled online features still send data to+ their listed services.+ </AppText>+ <View className="mt-5 flex-row flex-wrap justify-end gap-1">+ <PolicyButton+ label="Terms of Use"+ onPress={() => void Linking.openURL(TERMS_OF_SERVICE_URL).catch(() => undefined)}+ pressedOverlay={pressedOverlay}+ />+ <PolicyButton+ label="Privacy Policy"+ onPress={() => void Linking.openURL(PRIVACY_POLICY_URL).catch(() => undefined)}+ pressedOverlay={pressedOverlay}+ />+ <PolicyButton+ label="I reviewed these drafts"+ onPress={() =>+ updatePreferences({+ reviewedPrivacyPolicyVersion: AKERU_PRIVACY_POLICY_VERSION,+ reviewedTermsVersion: AKERU_TERMS_VERSION,+ })+ }+ pressedOverlay={pressedOverlay}+ />+ </View>+ </View>+ </View>+ </Modal>+ );+}++function PolicyButton({+ label,+ onPress,+ pressedOverlay,+}: {+ readonly label: string;+ readonly onPress: () => void;+ readonly pressedOverlay: ColorValue;+}) {+ return (+ <View className="overflow-hidden rounded-full">+ <Pressable+ accessibilityRole="button"+ className="min-h-10 items-center justify-center px-4"+ android_ripple={{ color: pressedOverlay }}+ onPress={onPress}+ >+ <AppText className="text-base font-t3-medium">{label}</AppText>+ </Pressable>+ </View>+ );+}diff --git a/apps/mobile/src/features/settings/SettingsAuthRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsAuthRouteScreen.tsxdeleted file mode 100644index 96d612f8c..000000000--- a/apps/mobile/src/features/settings/SettingsAuthRouteScreen.tsx+++ /dev/null@@ -1,50 +0,0 @@-import { useAuth } from "@clerk/expo";-import { AuthView, UserProfileView } from "@clerk/expo/native";-import { StackActions, useNavigation } from "@react-navigation/native";-import { useCallback, useEffect, useLayoutEffect, useRef } from "react";-import { View } from "react-native";--import { hasCloudPublicConfig } from "../cloud/publicConfig";--export function SettingsAuthRouteScreen() {- const navigation = useNavigation();-- useLayoutEffect(() => {- if (!hasCloudPublicConfig()) {- navigation.dispatch(StackActions.replace("SettingsContent"));- }- }, [navigation]);-- return hasCloudPublicConfig() ? <ConfiguredSettingsAuthRouteScreen /> : null;-}--function ConfiguredSettingsAuthRouteScreen() {- const { isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });- const navigation = useNavigation();- const handleHostBack = useCallback(- () => navigation.dispatch(StackActions.popTo("SettingsContent")),- [navigation],- );- const hasBeenSignedIn = useRef(isSignedIn);- if (isSignedIn) {- hasBeenSignedIn.current = true;- }-- useEffect(() => {- if (hasBeenSignedIn.current && isLoaded && isSignedIn === false) {- navigation.dispatch(StackActions.popTo("SettingsContent"));- }- }, [isLoaded, isSignedIn, navigation]);-- return (- <View collapsable={false} className="flex-1 overflow-hidden bg-sheet">- {isLoaded ? (- hasBeenSignedIn.current ? (- <UserProfileView isDismissible={false} onHostBack={handleHostBack} />- ) : (- <AuthView isDismissible={false} onHostBack={handleHostBack} />- )- ) : null}- </View>- );-}diff --git a/apps/mobile/src/features/settings/SettingsEnvironmentsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsEnvironmentsRouteScreen.tsxindex 6b6d589fa..d5ff4bb45 100644--- a/apps/mobile/src/features/settings/SettingsEnvironmentsRouteScreen.tsx+++ b/apps/mobile/src/features/settings/SettingsEnvironmentsRouteScreen.tsx@@ -8,17 +8,13 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";import { AppText as Text } from "../../components/AppText";import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";-import { CloudEnvironmentRows } from "../connection/CloudEnvironmentRows";import { ConnectionEnvironmentRow } from "../connection/ConnectionEnvironmentRow";-import { splitEnvironmentSections } from "../connection/environmentSections";import { cn } from "../../lib/cn";import { useThemeColor } from "../../lib/useThemeColor";import { useRemoteConnections } from "../../state/use-remote-environment-registry";import {applyShowcaseLocalEnvironmentDisplayUrls,resolveShowcaseEnvironmentUpdateDisplayUrl,- SHOWCASE_AVAILABLE_CLOUD_ENVIRONMENTS,- SHOWCASE_CONNECTED_CLOUD_ENVIRONMENTS,} from "../showcase/showcaseEnvironmentRows";const SHOWCASE_ENABLED = process.env.EXPO_PUBLIC_SHOWCASE === "1";@@ -32,16 +28,9 @@ export function SettingsEnvironmentsRouteScreen() {} = useRemoteConnections();const navigation = useNavigation();const insets = useSafeAreaInsets();- const environmentSections = splitEnvironmentSections({- connectedEnvironments,- cloudEnvironments: null,- });const localEnvironments = SHOWCASE_ENABLED- ? applyShowcaseLocalEnvironmentDisplayUrls(environmentSections.localEnvironments)- : environmentSections.localEnvironments;- const connectedCloudEnvironments = SHOWCASE_ENABLED- ? SHOWCASE_CONNECTED_CLOUD_ENVIRONMENTS- : environmentSections.connectedCloudEnvironments;+ ? applyShowcaseLocalEnvironmentDisplayUrls(connectedEnvironments)+ : connectedEnvironments;const hasLocalEnvironments = localEnvironments.length > 0;const [expandedId, setExpandedId] = useState<EnvironmentId | null>(null);const accentColor = useThemeColor("--color-icon-muted");@@ -56,7 +45,7 @@ export function SettingsEnvironmentsRouteScreen() {updates: { readonly label: string; readonly displayUrl: string },) => {if (!SHOWCASE_ENABLED) return onUpdateEnvironment(environmentId, updates);- const actualEnvironment = environmentSections.localEnvironments.find(+ const actualEnvironment = connectedEnvironments.find((environment) => environment.environmentId === environmentId,);const presentedEnvironment = localEnvironments.find(@@ -74,7 +63,7 @@ export function SettingsEnvironmentsRouteScreen() {: updates.displayUrl,});},- [environmentSections.localEnvironments, localEnvironments, onUpdateEnvironment],+ [connectedEnvironments, localEnvironments, onUpdateEnvironment],);return (@@ -158,20 +147,6 @@ export function SettingsEnvironmentsRouteScreen() {</Text></View>)}-- {/* Always mounted: already-connected relay environments must stay- visible (and removable) even when cloud config is missing or the- user is signed out — the component gates discovery itself. */}- <CloudEnvironmentRows- connectedCloudEnvironments={connectedCloudEnvironments}- onReconnectEnvironment={onReconnectEnvironment}- {...(SHOWCASE_ENABLED- ? {- showcaseAvailableEnvironments: SHOWCASE_AVAILABLE_CLOUD_ENVIRONMENTS,- showcaseSignedIn: true,- }- : {})}- /></ScrollView></View>);diff --git a/apps/mobile/src/features/settings/SettingsRouteScreen.logic.test.ts b/apps/mobile/src/features/settings/SettingsRouteScreen.logic.test.tsindex 259eaf949..80c4c61be 100644--- a/apps/mobile/src/features/settings/SettingsRouteScreen.logic.test.ts+++ b/apps/mobile/src/features/settings/SettingsRouteScreen.logic.test.ts@@ -2,24 +2,20 @@ import { describe, expect, it } from "vite-plus/test";import { EnvironmentId } from "@t3tools/contracts";-import {- resolveAgentAwarenessPlatformPresentation,- resolveSettingsEnvironmentId,-} from "./SettingsRouteScreen.logic";--describe("resolveAgentAwarenessPlatformPresentation", () => {- it("explains that agent awareness settings are unavailable on Android", () => {- expect(resolveAgentAwarenessPlatformPresentation("android")).toEqual({- supported: false,- subtitle: "iOS only",- });- });-- it("leaves supported iOS settings unchanged", () => {- expect(resolveAgentAwarenessPlatformPresentation("ios")).toEqual({- supported: true,- subtitle: undefined,- });+import { privacyControlPatch, resolveSettingsEnvironmentId } from "./SettingsRouteScreen.logic";++describe("privacyControlPatch", () => {+ it.each([+ ["analytics", true, { analyticsEnabled: true }],+ ["analytics", false, { analyticsEnabled: false }],+ ["product-feedback", true, { productFeedbackEnabled: true }],+ ["product-feedback", false, { productFeedbackEnabled: false }],+ ["voice", true, { voice: { enabled: true } }],+ ["voice", false, { voice: { enabled: false } }],+ ["provider-update-checks", true, { enableProviderUpdateChecks: true }],+ ["provider-update-checks", false, { enableProviderUpdateChecks: false }],+ ] as const)("maps %s to its server settings patch", (control, enabled, expected) => {+ expect(privacyControlPatch(control, enabled)).toEqual(expected);});});diff --git a/apps/mobile/src/features/settings/SettingsRouteScreen.logic.ts b/apps/mobile/src/features/settings/SettingsRouteScreen.logic.tsindex 2b27a1b10..437fdb67a 100644--- a/apps/mobile/src/features/settings/SettingsRouteScreen.logic.ts+++ b/apps/mobile/src/features/settings/SettingsRouteScreen.logic.ts@@ -1,12 +1,21 @@-import type { EnvironmentId } from "@t3tools/contracts";+import type { EnvironmentId, ServerSettingsPatch } from "@t3tools/contracts";-export function resolveAgentAwarenessPlatformPresentation(platform: string): {- readonly supported: boolean;- readonly subtitle: string | undefined;-} {- return platform === "ios"- ? { supported: true, subtitle: undefined }- : { supported: false, subtitle: "iOS only" };+export type PrivacyControl = "analytics" | "product-feedback" | "voice" | "provider-update-checks";++export function privacyControlPatch(+ control: PrivacyControl,+ enabled: boolean,+): ServerSettingsPatch {+ switch (control) {+ case "analytics":+ return { analyticsEnabled: enabled };+ case "product-feedback":+ return { productFeedbackEnabled: enabled };+ case "voice":+ return { voice: { enabled } };+ case "provider-update-checks":+ return { enableProviderUpdateChecks: enabled };+ }}export function resolveSettingsEnvironmentId(diff --git a/apps/mobile/src/features/settings/SettingsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsRouteScreen.tsxindex ad2811ffa..9241a9bc6 100644--- a/apps/mobile/src/features/settings/SettingsRouteScreen.tsx+++ b/apps/mobile/src/features/settings/SettingsRouteScreen.tsx@@ -1,39 +1,18 @@-import { useAuth, useUser } from "@clerk/expo";import { useAtomSet, useAtomValue } from "@effect/atom-react";import { EnvironmentId } from "@t3tools/contracts";import Constants from "expo-constants";-import * as Notifications from "expo-notifications";import { useNavigation, type StaticScreenProps } from "@react-navigation/native";import { NativeStackScreenOptions } from "../../native/StackHeader";import { SymbolView } from "../../components/AppSymbol";-import * as Effect from "effect/Effect";import { AsyncResult } from "effect/unstable/reactivity";-import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";-import { Alert, Linking, Platform, Pressable, ScrollView, View } from "react-native";+import { useCallback, useEffect, useRef, useState } from "react";+import { Alert, Platform, Pressable, ScrollView, View } from "react-native";import { useSafeAreaInsets } from "react-native-safe-area-context";-import {- isAtomCommandInterrupted,- reportAtomCommandResult,- settleAsyncResult,- settlePromise,- squashAtomCommandFailure,-} from "@t3tools/client-runtime/state/runtime";import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";import { AppText as Text } from "../../components/AppText";-import { supportsAgentAwarenessPush } from "../agent-awareness/capabilities";-import { setLiveActivityUpdatesEnabled } from "../agent-awareness/liveActivityPreferences";-import { requestAgentNotificationPermission } from "../agent-awareness/notificationPermissions";-import {- getAgentAwarenessRegistrationStatus,- refreshAgentAwarenessRegistration,- subscribeAgentAwarenessRegistrationStatus,-} from "../agent-awareness/remoteRegistration";-import { refreshManagedRelayEnvironments } from "../cloud/managedRelayState";-import { hasCloudPublicConfig, resolveRelayClerkTokenOptions } from "../cloud/publicConfig";import { withNativeGlassHeaderItem } from "../layout/native-glass-header-items";import { WorkspaceSidebarToolbar } from "../layout/workspace-sidebar-toolbar";-import { runtime } from "../../lib/runtime";import { useThemeColor } from "../../lib/useThemeColor";import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";import { useThreadListV2Enabled } from "../threads/use-thread-list-v2-enabled";@@ -50,26 +29,11 @@ import { SettingsRow } from "./components/SettingsRow";import { SettingsSection } from "./components/SettingsSection";import { SettingsSwitchRow } from "./components/SettingsSwitchRow";import {- resolveAgentAwarenessPlatformPresentation,+ privacyControlPatch,+ type PrivacyControl,resolveSettingsEnvironmentId,} from "./SettingsRouteScreen.logic";-type NotificationStatus = "checking" | "enabled" | "disabled" | "unsupported";-type LiveActivityStatus = "checking" | "enabled" | "disabled" | "signed-out" | "linking";--// Reflects whether the relay actually accepted this device's registration.-// The notification and Live Activity switches are gated on this so they can-// never read as enabled when the device cannot receive anything (e.g. the-// registration request timed out).-function useDeviceRegistered(): boolean {- const status = useSyncExternalStore(- subscribeAgentAwarenessRegistrationStatus,- getAgentAwarenessRegistrationStatus,- () => "unknown" as const,- );- return status === "registered";-}-type SettingsRouteParams = {readonly environmentId?: EnvironmentId | ReadonlyArray<string> | null;};@@ -112,11 +76,7 @@ export function SettingsRouteScreen({ route }: StaticScreenProps<SettingsRoutePa}}/>)}- {hasCloudPublicConfig() ? (- <ConfiguredSettingsRouteScreen environmentId={environmentId} />- ) : (- <LocalSettingsRouteScreen environmentId={environmentId} />- )}+ <LocalSettingsRouteScreen environmentId={environmentId} /></>);}@@ -157,403 +117,9 @@ function LocalSettingsRouteScreen({<ErrorsSettingsSection environmentId={connections[0]?.environmentId ?? null} />- <GeneralSettingsSection environmentId={settingsEnvironmentId} />-- <SettingsSection title="Appearance">- <SettingsRow icon="paintbrush" label="Appearance" target="SettingsAppearance" />- </SettingsSection>-- <LegacySettingsSection />-- <ArchivedThreadsSettingsSection />-- <AppSettingsSection />- </ScrollView>- </View>- );-}--function ConfiguredSettingsRouteScreen({- environmentId,-}: {- readonly environmentId: EnvironmentId | null;-}) {- const preferencesResult = useAtomValue(mobilePreferencesAtom);- const savePreferences = useAtomSet(updateMobilePreferencesAtom);- const agentAwarenessPushAvailable = supportsAgentAwarenessPush();- const agentAwarenessPlatform = resolveAgentAwarenessPlatformPresentation(Platform.OS);- const insets = useSafeAreaInsets();- const navigation = useNavigation();- const { getToken, isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });- const { user } = useUser();- const { savedConnectionsById } = useSavedRemoteConnections();- const [notificationStatus, setNotificationStatus] = useState<NotificationStatus>("checking");- const [liveActivityStatus, setLiveActivityStatus] = useState<LiveActivityStatus>("checking");- const deviceRegistered = useDeviceRegistered();- const liveActivitiesPreferenceEnabled = AsyncResult.isSuccess(preferencesResult)- ? preferencesResult.value.liveActivitiesEnabled !== false- : true;-- const connections = useMemo(() => Object.values(savedConnectionsById), [savedConnectionsById]);- const environmentCount = connections.length;- const settingsEnvironmentId = resolveSettingsEnvironmentId(- environmentId,- connections.map((connection) => connection.environmentId),- );- const accountLabel = useMemo(() => {- if (!isLoaded) return "Checking";- if (!isSignedIn) return "Sign in";- return user?.primaryEmailAddress?.emailAddress ?? "Signed in";- }, [isLoaded, isSignedIn, user?.primaryEmailAddress?.emailAddress]);-- const refreshNotifications = useCallback(async () => {- if (process.env.EXPO_OS !== "ios") {- setNotificationStatus("unsupported");- return;- }- const result = await settlePromise(() => Notifications.getPermissionsAsync());- if (result._tag === "Failure") {- reportAtomCommandResult(result, { label: "notification permission refresh" });- setNotificationStatus("disabled");- return;- }- setNotificationStatus(result.value.granted ? "enabled" : "disabled");- }, []);-- useEffect(() => {- void refreshNotifications();- }, [refreshNotifications]);-- useEffect(() => {- if (!isLoaded) {- setLiveActivityStatus("checking");- return;- }- if (!isSignedIn) {- setLiveActivityStatus("signed-out");- return;- }- if (!AsyncResult.isSuccess(preferencesResult)) {- if (AsyncResult.isFailure(preferencesResult)) {- reportAtomCommandResult(preferencesResult, { label: "live activity preference load" });- setLiveActivityStatus("enabled");- } else {- setLiveActivityStatus("checking");- }- return;- }- setLiveActivityStatus(- preferencesResult.value.liveActivitiesEnabled === false ? "disabled" : "enabled",- );- }, [isLoaded, isSignedIn, preferencesResult]);-- const requestNotifications = useCallback(async () => {- const result = await settleAsyncResult(() =>- runtime.runPromiseExit(- requestAgentNotificationPermission.pipe(- Effect.tap((permission) =>- permission.type === "granted" ? refreshAgentAwarenessRegistration() : Effect.void,- ),- ),- ),- );- if (result._tag === "Failure") {- if (!isAtomCommandInterrupted(result)) {- const error = squashAtomCommandFailure(result);- Alert.alert(- "Notifications unavailable",- error instanceof Error ? error.message : "Could not request notification permission.",- );- }- return;- }- if (result.value.type === "granted") {- setNotificationStatus("enabled");- // Permission alone is not enough: the switch stays off until the relay- // registration succeeds, so tell the user the truth about which happened.- if (getAgentAwarenessRegistrationStatus() === "registered") {- Alert.alert(- "Notifications enabled",- "Live Activity notifications are enabled for this device.",- );- } else {- Alert.alert(- "Couldn't finish enabling notifications",- "Notification access was granted, but this device could not be registered with T3 Connect. Notifications will start once registration succeeds.",- );- }- return;- }- if (result.value.type === "unsupported") {- setNotificationStatus("unsupported");- Alert.alert(- "Notifications unavailable",- "Live Activity notifications are only available on iOS.",- );- return;- }- setNotificationStatus("disabled");- if (result.value.canAskAgain) {- Alert.alert("Notifications disabled", "Notifications were not enabled.");- return;- }- Alert.alert(- "Notifications disabled",- "Notifications were denied for this app. Open Settings to enable them.",- [- { text: "Cancel", style: "cancel" },- { text: "Open Settings", onPress: () => void Linking.openSettings() },- ],- );- }, []);-- const promptSignIn = useCallback(() => {- Alert.alert(- "Sign in to T3 Connect",- "Live Activity updates require T3 Connect so relay can deliver updates to this device.",- [- { text: "Cancel", style: "cancel" },- {- text: "Continue",- onPress: () => navigation.navigate("SettingsSheet", { screen: "SettingsAuth" }),- },- ],- );- }, [navigation]);-- const linkEnvironments = useCallback(async () => {- if (!isSignedIn) {- promptSignIn();- return;- }-- setLiveActivityStatus("linking");- const tokenResult = await settlePromise(() => getToken(resolveRelayClerkTokenOptions()));- if (tokenResult._tag === "Failure") {- setLiveActivityStatus("disabled");- const error = squashAtomCommandFailure(tokenResult);- Alert.alert(- "Live Activities unavailable",- error instanceof Error ? error.message : "Could not enable Live Activity updates.",- );- return;- }- if (!tokenResult.value) {- promptSignIn();- setLiveActivityStatus("signed-out");- return;- }-- const updateResult = await settleAsyncResult(() =>- runtime.runPromiseExit(- setLiveActivityUpdatesEnabled({- enabled: true,- previousEnabled: liveActivitiesPreferenceEnabled,- clerkToken: tokenResult.value,- connections,- }),- ),- );- if (updateResult._tag === "Failure") {- setLiveActivityStatus("disabled");- if (!isAtomCommandInterrupted(updateResult)) {- const error = squashAtomCommandFailure(updateResult);- Alert.alert(- "Live Activities unavailable",- error instanceof Error ? error.message : "Could not enable Live Activity updates.",- );- }- return;- }-- savePreferences({ liveActivitiesEnabled: true });- refreshManagedRelayEnvironments();- setLiveActivityStatus("enabled");- // The environment link can succeed while this device's own registration- // (the push-to-start token the relay needs) has not — don't claim Live- // Activities are live until the device is actually registered.- if (getAgentAwarenessRegistrationStatus() === "registered") {- Alert.alert(- "Live Activities enabled",- environmentCount > 0- ? `${environmentCount} environment${environmentCount === 1 ? "" : "s"} linked for Live Activity updates.`- : "Live Activity updates are enabled. Add an environment to start receiving updates.",- );- } else {- Alert.alert(- "Couldn't finish enabling Live Activities",- "This device could not be registered with T3 Connect, so Live Activities won't appear yet. They'll start once registration succeeds.",- );- }- }, [- connections,- environmentCount,- getToken,- isSignedIn,- liveActivitiesPreferenceEnabled,- promptSignIn,- savePreferences,- ]);-- const handleDeviceNotificationsChange = useCallback(- (enabled: boolean) => {- if (enabled) {- void requestNotifications();- return;- }-- Alert.alert(- "Disable notifications",- "Notification permission is controlled by iOS. Open Settings to disable notifications for T3 Code.",- [- { text: "Cancel", style: "cancel" },- { text: "Open Settings", onPress: () => void Linking.openSettings() },- ],- );- },- [requestNotifications],- );-- const handleLiveActivitiesChange = useCallback(- (enabled: boolean) => {- if (!enabled) {- setLiveActivityStatus("disabled");- void (async () => {- let token: string | null = null;- if (isSignedIn) {- const tokenResult = await settlePromise(() =>- getToken(resolveRelayClerkTokenOptions()),- );- if (tokenResult._tag === "Failure") {- reportAtomCommandResult(tokenResult, {- label: "live activity disable token lookup",- });- return;- }- token = tokenResult.value;- }-- const updateResult = await settleAsyncResult(() =>- runtime.runPromiseExit(- setLiveActivityUpdatesEnabled({- enabled: false,- previousEnabled: liveActivitiesPreferenceEnabled,- clerkToken: token,- connections,- }),- ),- );- if (updateResult._tag === "Failure") {- setLiveActivityStatus("enabled");- reportAtomCommandResult(updateResult, {- label: "live activity disable",- });- return;- }- savePreferences({ liveActivitiesEnabled: false });- refreshManagedRelayEnvironments();- })();- return;- }-- if (!isSignedIn) {- promptSignIn();- return;- }-- void linkEnvironments();- },- [- connections,- getToken,- isSignedIn,- linkEnvironments,- liveActivitiesPreferenceEnabled,- promptSignIn,- savePreferences,- ],- );-- const openAccount = useCallback(() => {- if (!isLoaded) return;- navigation.navigate("SettingsSheet", { screen: "SettingsAuth" });- }, [isLoaded, navigation]);-- return (- <View collapsable={false} className="flex-1 bg-sheet">- <ScrollView- contentInsetAdjustmentBehavior="automatic"- showsVerticalScrollIndicator={false}- className="flex-1"- contentContainerClassName="gap-6 px-5 pt-4"- contentContainerStyle={{- paddingBottom: Math.max(insets.bottom, 18) + 18,- }}- >- <View className="gap-3">- <SettingsSection title="Account">- <SettingsRow- icon="person.crop.circle"- label="T3 Account"- value={accountLabel}- onPress={openAccount}- />- </SettingsSection>- <Text className="px-2 text-sm text-foreground-muted">- T3 Code works locally without signing in. Cloud features are optional.- </Text>- </View>-- <SettingsSection title="Configuration">- <SettingsRow- icon="desktopcomputer"- label="Environments"- value={`${environmentCount}`}- target="SettingsEnvironments"- />- <SettingsSwitchRow- icon="bell.badge"- label="Device Notifications"- disabled={- !agentAwarenessPlatform.supported ||- !agentAwarenessPushAvailable ||- notificationStatus === "checking" ||- notificationStatus === "unsupported"- }- subtitle={agentAwarenessPlatform.subtitle}- // Only reads as on when this device is actually registered with the- // relay; otherwise notifications cannot be delivered regardless of- // the local iOS permission.- value={- agentAwarenessPushAvailable && notificationStatus === "enabled" && deviceRegistered- }- onValueChange={handleDeviceNotificationsChange}- />- <SettingsSwitchRow- disabled={- !agentAwarenessPlatform.supported ||- !agentAwarenessPushAvailable ||- !isLoaded ||- liveActivityStatus === "checking" ||- liveActivityStatus === "linking"- }- icon="bolt.circle"- label="Live Activity Updates"- subtitle={agentAwarenessPlatform.subtitle}- // Same gate: a saved preference is meaningless until the device- // registration the relay needs to push updates has succeeded.- value={- agentAwarenessPushAvailable &&- (liveActivityStatus === "enabled" || liveActivityStatus === "linking") &&- deviceRegistered- }- onValueChange={handleLiveActivitiesChange}- />- </SettingsSection>-- <ErrorsSettingsSection environmentId={connections[0]?.environmentId ?? null} />+ <GeneralSettingsSection />- <GeneralSettingsSection environmentId={settingsEnvironmentId} />+ <PrivacySettingsSection environmentId={settingsEnvironmentId} /><SettingsSection title="Appearance"><SettingsRow icon="paintbrush" label="Appearance" target="SettingsAppearance" />@@ -595,34 +161,62 @@ function ErrorsSettingsSection({);}-function AnalyticsSettingsSwitch({ environmentId }: { readonly environmentId: EnvironmentId }) {+function PrivacySettingsSection({+ environmentId,+}: {+ readonly environmentId: EnvironmentId | null;+}) {+ if (environmentId === null) return null;+ return <EnvironmentPrivacySettingsSection environmentId={environmentId} />;+}++function EnvironmentPrivacySettingsSection({+ environmentId,+}: {+ readonly environmentId: EnvironmentId;+}) {const settings = useAtomValue(serverEnvironment.settingsValueAtom(environmentId));- const updateSettings = useAtomCommand(serverEnvironment.updateSettings);- const [saving, setSaving] = useState(false);+ const updateSettings = useAtomCommand(serverEnvironment.updateSettings, { reportFailure: false });+ if (!settings) return null;++ const updateControl = (control: PrivacyControl, enabled: boolean) => {+ void updateSettings({+ environmentId,+ input: { patch: privacyControlPatch(control, enabled) },+ });+ };return (- <SettingsSwitchRow- disabled={settings === null || saving}- icon="chart.bar"- label="Analytics"- value={settings?.analyticsEnabled ?? true}- onValueChange={async (analyticsEnabled) => {- setSaving(true);- try {- await updateSettings({ environmentId, input: { patch: { analyticsEnabled } } });- } finally {- setSaving(false);- }- }}- />+ <SettingsSection title="Privacy">+ <SettingsSwitchRow+ icon="chart.bar.xaxis"+ label="Anonymous analytics"+ value={settings.analyticsEnabled}+ onValueChange={(enabled) => updateControl("analytics", enabled)}+ />+ <SettingsSwitchRow+ icon="text.bubble"+ label="Product feedback"+ value={settings.productFeedbackEnabled}+ onValueChange={(enabled) => updateControl("product-feedback", enabled)}+ />+ <SettingsSwitchRow+ icon="bolt.circle"+ label="Voice calls"+ value={settings.voice.enabled}+ onValueChange={(enabled) => updateControl("voice", enabled)}+ />+ <SettingsSwitchRow+ icon="arrow.clockwise"+ label="Provider update checks"+ value={settings.enableProviderUpdateChecks}+ onValueChange={(enabled) => updateControl("provider-update-checks", enabled)}+ />+ </SettingsSection>);}-function GeneralSettingsSection({- environmentId,-}: {- readonly environmentId: EnvironmentId | null;-}) {+function GeneralSettingsSection() {const preferencesResult = useAtomValue(mobilePreferencesAtom);const savePreferences = useAtomSet(updateMobilePreferencesAtom);const autoSettleOnMerge =@@ -639,17 +233,6 @@ function GeneralSettingsSection({onValueChange={(value) => savePreferences({ autoSettleOnMerge: value })}/><SettingsRow icon="chart.bar.xaxis" label="Usage" target="SettingsUsage" />- {environmentId === null ? (- <SettingsSwitchRow- disabled- icon="chart.bar"- label="Analytics"- value- onValueChange={() => {}}- />- ) : (- <AnalyticsSettingsSwitch environmentId={environmentId} />- )}</SettingsSection>);}diff --git a/apps/mobile/src/features/settings/lib/legal-document-url.test.ts b/apps/mobile/src/features/settings/lib/legal-document-url.test.tsindex 10ce4ca48..c60810686 100644--- a/apps/mobile/src/features/settings/lib/legal-document-url.test.ts+++ b/apps/mobile/src/features/settings/lib/legal-document-url.test.ts@@ -4,17 +4,17 @@ import { isLegalDocumentUrl } from "./legal-document-url";describe("isLegalDocumentUrl", () => {it.each([- "https://t3.codes/legal",- "https://t3.codes/legal/",- "https://t3.codes/privacy-policy?source=app",- "https://t3.codes/terms-of-service#updates",- "https://t3.codes/security-policy",+ "https://akeru.bot/legal",+ "https://akeru.bot/legal/",+ "https://akeru.bot/privacy-policy?source=app",+ "https://akeru.bot/terms-of-service#updates",+ "https://akeru.bot/security-policy",])("allows a configured legal document: %s", (url) => {expect(isLegalDocumentUrl(url)).toBe(true);});it.each([- "https://t3.codes/download",+ "https://akeru.bot/download","https://example.com/legal","javascript:alert(1)","not-a-url",diff --git a/apps/mobile/src/features/settings/lib/legal-document-url.ts b/apps/mobile/src/features/settings/lib/legal-document-url.tsindex 455637561..9acdfe603 100644--- a/apps/mobile/src/features/settings/lib/legal-document-url.ts+++ b/apps/mobile/src/features/settings/lib/legal-document-url.ts@@ -1,4 +1,4 @@-const DEFAULT_MARKETING_SITE_URL = "https://t3.codes";+const DEFAULT_MARKETING_SITE_URL = "https://akeru.bot";function resolveMarketingSiteUrl(override: string | undefined): URL {try {diff --git a/apps/mobile/src/features/showcase/showcaseEnvironmentRows.test.ts b/apps/mobile/src/features/showcase/showcaseEnvironmentRows.test.tsindex a459cbe1d..53f80e874 100644--- a/apps/mobile/src/features/showcase/showcaseEnvironmentRows.test.ts+++ b/apps/mobile/src/features/showcase/showcaseEnvironmentRows.test.ts@@ -16,7 +16,6 @@ function environment(environmentId: EnvironmentId.make(environmentId),environmentLabel,displayUrl,- isRelayManaged: false,connectionState: "connected",connectionError: null,connectionErrorTraceId: null,diff --git a/apps/mobile/src/features/showcase/showcaseEnvironmentRows.ts b/apps/mobile/src/features/showcase/showcaseEnvironmentRows.tsindex 66ec3046c..39bfa9b7c 100644--- a/apps/mobile/src/features/showcase/showcaseEnvironmentRows.ts+++ b/apps/mobile/src/features/showcase/showcaseEnvironmentRows.ts@@ -1,6 +1,3 @@-import { EnvironmentId } from "@t3tools/contracts";--import type { RelayEnvironmentView } from "../connection/useConnectionController";import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";const SHOWCASE_LOCAL_ENVIRONMENT_DISPLAY_URLS: Readonly<Record<string, string>> = {@@ -29,42 +26,3 @@ export function resolveShowcaseEnvironmentUpdateDisplayUrl(input: {? input.actualDisplayUrl: input.submittedDisplayUrl;}--const pocketPiId = EnvironmentId.make("showcase-pocket-pi");-const pocketPiEndpoint = {- httpBaseUrl: "https://pocket-pi.t3.sh",- wsBaseUrl: "wss://pocket-pi.t3.sh",- providerKind: "t3_relay" as const,-};--export const SHOWCASE_CONNECTED_CLOUD_ENVIRONMENTS: ReadonlyArray<ConnectedEnvironmentSummary> = [- {- environmentId: EnvironmentId.make("showcase-aurora-gpu"),- environmentLabel: "Aurora GPU Pod",- displayUrl: "https://aurora-gpu.t3.sh",- isRelayManaged: true,- connectionState: "connected",- connectionError: null,- connectionErrorTraceId: null,- },-];--export const SHOWCASE_AVAILABLE_CLOUD_ENVIRONMENTS: ReadonlyArray<RelayEnvironmentView> = [- {- environment: {- environmentId: pocketPiId,- label: "Pocket Pi",- endpoint: pocketPiEndpoint,- linkedAt: "2026-07-16T08:00:00.000Z",- },- availability: "online",- status: {- environmentId: pocketPiId,- endpoint: pocketPiEndpoint,- status: "online",- checkedAt: "2026-07-16T08:41:00.000Z",- },- error: null,- traceId: null,- },-];diff --git a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsxindex 8f5beb69c..718a42941 100644--- a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx+++ b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx@@ -53,8 +53,6 @@ import {} from "../../state/use-composer-drafts";import { useEnvironmentServerConfig, useProjects } from "../../state/entities";import { resolveSelectableModelSelection } from "../../lib/modelOptions";-import { deriveThreadTitleFromPrompt } from "../../lib/projectThreadStartTurn";-import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration";import { enqueueThreadOutboxMessage, removeThreadOutboxMessage } from "../../state/thread-outbox";import { useRemoteConnectionStatus } from "../../state/use-remote-environment-registry";import { useNewTaskFlow } from "./new-task-flow-provider";@@ -714,15 +712,6 @@ export function NewTaskDraftScreen(props: {}flow.setSubmitting(true);- // Arm the lock-screen card before the async thread creation: backgrounding- // the app right after tapping submit would otherwise reject the foreground- // -only Activity start. If creation fails, the token registration's replay- // finds no work and ends the card within seconds.- armAgentAwarenessLiveActivityForLocalWork({- environmentId: selectedProject.environmentId,- threadTitle: deriveThreadTitleFromPrompt(initialMessageText),- projectTitle: selectedProject.title,- });const creationBranch = resolveProjectThreadCreationBranch({workspaceMode,selectedBranch: selectedBranchName,diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsxindex c771aaebc..305f6fc87 100644--- a/apps/mobile/src/features/threads/ThreadComposer.tsx+++ b/apps/mobile/src/features/threads/ThreadComposer.tsx@@ -7,6 +7,7 @@ import type {RuntimeMode,ServerConfig as T3ServerConfig,} from "@t3tools/contracts";+import { useAtomValue } from "@effect/atom-react";import {detectComposerTrigger,replaceTextRange,@@ -35,7 +36,6 @@ import Animated, {} from "react-native-reanimated";import { useThemeColor } from "../../lib/useThemeColor";import { themeColorWithAlpha } from "../../lib/mobileTheme";-import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration";import { scopedThreadKey } from "../../lib/scopedEntities";import { AppText as Text } from "../../components/AppText";@@ -66,6 +66,8 @@ import {} from "@t3tools/shared/searchRanking";import { resolveProviderOptionDescriptors } from "../../lib/providerOptions";import { useComposerPathSearch } from "../../state/use-composer-path-search";+import { botEnvironment, environmentBotsAtom } from "../../state/bots";+import { useAtomCommand } from "../../state/use-atom-command";import { ComposerCommandPopover, type ComposerCommandItem } from "./ComposerCommandPopover";import { matchesSlashSkillQuery } from "./composerSlashSkillSearch";import {@@ -76,6 +78,7 @@ import {useThreadSettingsSheetPresentation,type NavigationWithFinishTransitioning,} from "./use-thread-settings-sheet-presentation";+import { buildBotUsageCapPatch } from "./botStepUsage";/*** Height of the collapsed composer (pill + vertical padding, excluding safe-area inset).@@ -284,6 +287,9 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposerisEditorFocused: isFocused,});const settingsRoutePresentation = useExistingThreadSettingsRoutePresentation();+ const bots = useAtomValue(environmentBotsAtom(props.environmentId));+ const bot = bots.find((candidate) => candidate.id === props.selectedThread.botId);+ const updateBot = useAtomCommand(botEnvironment.update, { reportFailure: false });const settingsRoutePresentedRef = useRef(false);const wasExpandedBeforePreviewRef = useRef(false);const inFlightThreadIdsRef = useRef(new Set<string>());@@ -556,25 +562,10 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposerif (messageId === null) {return;}- // Sending a prompt starts agent work: arm the lock-screen card while the- // app is foregrounded and the activity token can be registered. Armed- // after the send so its preference read and native Activity start don't- // contend with the queued-message feedback on the tap frame.- armAgentAwarenessLiveActivityForLocalWork({- environmentId: props.environmentId,- threadTitle: props.selectedThread.title,- projectTitle: props.environmentLabel ?? "T3 Code",- });} finally {inFlightThreadIdsRef.current.delete(threadKey);}- }, [- onSendMessage,- props.environmentId,- props.environmentLabel,- props.selectedThread.id,- props.selectedThread.title,- ]);+ }, [onSendMessage, props.environmentId, props.selectedThread.id]);const handleCommandSelect = useCallback((item: ComposerCommandItem) => {if (!composerTrigger) return;@@ -644,6 +635,16 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer}),[currentModelOption?.capabilities, currentModelSelection.options],);+ const updateBotUsageCap = useCallback(+ async (input: string) => {+ if (!bot) return false;+ const patch = buildBotUsageCapPatch(bot.id, input, currentModelOption?.providerDriver);+ if (!patch) return false;+ const result = await updateBot({ environmentId: props.environmentId, input: patch });+ return result._tag === "Success";+ },+ [bot, currentModelOption?.providerDriver, props.environmentId, updateBot],+ );const settingsOwnerId = scopedThreadKey(props.environmentId, props.selectedThread.id);const settingsRouteSession = useMemo<ExistingThreadSettingsRouteSession>(() => ({@@ -656,15 +657,24 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposerprops.onUpdateModelSelection({ ...currentModelSelection, options }),runtimeMode: currentRuntimeMode,onUpdateRuntimeMode: props.onUpdateRuntimeMode,+ ...(bot+ ? {+ botUsageCap: bot.usageCap,+ botUsageCapProviderDriver: currentModelOption?.providerDriver,+ onUpdateBotUsageCap: updateBotUsageCap,+ }+ : {}),}),[currentModelSelection,currentRuntimeMode,+ bot,props.onUpdateModelSelection,props.onUpdateRuntimeMode,providerOptionDescriptors,settingsOwnerId,threadProviderGroups,+ updateBotUsageCap,],);const openSettings = useCallback(() => {diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsxindex 6c7f66b88..9f8f31a81 100644--- a/apps/mobile/src/features/threads/ThreadFeed.tsx+++ b/apps/mobile/src/features/threads/ThreadFeed.tsx@@ -5,6 +5,7 @@ import type { EnvironmentId, MessageId, ThreadId, TurnId } from "@t3tools/contraimport { classifyMarkdownImageSource } from "@t3tools/client-runtime/markdown-images";import { CHAT_LIST_ANCHOR_OFFSET, resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";import { formatElapsed } from "@t3tools/shared/orchestrationTiming";+import { formatTokens, formatUsd } from "@t3tools/shared/usageFormat";import { SymbolView } from "../../components/AppSymbol";import { HeaderHeightContext } from "@react-navigation/elements";import { useNavigation } from "@react-navigation/native";@@ -101,6 +102,7 @@ import {resolveThreadFeedLiveFollow,type ThreadFeedLiveFollowEvent,} from "./thread-feed-live-follow";+import { formatBotStepEngine, type BotStepMeterData } from "./botStepUsage";import {collapsedWorkLogHeight,ThreadWorkGroupToggle,@@ -1141,6 +1143,7 @@ function renderFeedEntry(className={cn(showAssistantMeta ? "mb-5 px-1" : "mb-2 px-1")}{...(enterAnimated ? { entering: FadeIn.duration(220) } : {})}>+ {entry.botStepMeter ? <BotStepMeter meter={entry.botStepMeter} /> : null}{message.text.trim().length > 0 ? (hasNativeSelectableMarkdownText() ? (<SelectableMarkdownText@@ -1202,6 +1205,24 @@ function renderFeedEntry();}+function BotStepMeter(props: { readonly meter: BotStepMeterData }) {+ const label = `${formatBotStepEngine(props.meter.engine)} · ${+ props.meter.tokens === null ? "—" : formatTokens(props.meter.tokens)+ } tokens · ${props.meter.costUsd === null ? "$—" : formatUsd(props.meter.costUsd)}${+ props.meter.hardStopReached ? " · Hard stop" : ""+ }`;++ return (+ <Text+ accessibilityLabel={label}+ className="mb-1 font-mono text-xs tabular-nums text-foreground-muted"+ numberOfLines={1}+ >+ {label}+ </Text>+ );+}+const WorkingTimelineRow = memo(function WorkingTimelineRow(props: { readonly startedAt: string }) {const [nowMs, setNowMs] = useState(() => Date.now());diff --git a/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx b/apps/mobile/src/features/threads/ThreadSettingsSheet.tsxindex b47e41d3e..9f4620c2c 100644--- a/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx+++ b/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx@@ -1,4 +1,5 @@import type {+ BotUsageCap,ModelSelection,ProviderOptionDescriptor,ProviderOptionSelection,@@ -27,7 +28,7 @@ import {useState,type ReactNode,} from "react";-import { Platform, Pressable, ScrollView, TextInput, View } from "react-native";+import { Alert, Platform, Pressable, ScrollView, TextInput, View } from "react-native";import Animated, { FadeIn, FadeOut, LinearTransition } from "react-native-reanimated";import { useSafeAreaInsets } from "react-native-safe-area-context";@@ -59,6 +60,7 @@ import {pendingModelAfterPress,providerSectionIsCollapsed,} from "./thread-settings-sheet-state";+import { resolveBotUsageCapForProvider } from "./botStepUsage";/*** Everyday harnesses start expanded; every other provider (OpenRouter catalogs@@ -288,6 +290,9 @@ type ThreadSettingsSessionProps = {readonly onUpdateOptionSelections: (selections: ReadonlyArray<ProviderOptionSelection>) => void;readonly runtimeMode: RuntimeMode;readonly onUpdateRuntimeMode: (mode: RuntimeMode) => void;+ readonly botUsageCap?: BotUsageCap | null;+ readonly botUsageCapProviderDriver?: string;+ readonly onUpdateBotUsageCap?: (input: string) => Promise<boolean>;};export type ExistingThreadSettingsRouteSession = ThreadSettingsSessionProps & {@@ -335,6 +340,10 @@ type ThreadSettingsSessionValue = {readonly providerGroups: ReadonlyArray<ProviderGroup>;readonly runtimeMode: RuntimeMode;readonly onUpdateRuntimeMode: (mode: RuntimeMode) => void;+ readonly botUsageCapInput: string | undefined;+ readonly botUsageCapAvailable: boolean;+ readonly botUsageCapDirty: boolean;+ readonly botUsageCapValid: boolean;readonly displayedDescriptors: ReadonlyArray<ProviderOptionDescriptor>;readonly providerExpansionOverrides: ReadonlySet<string>;readonly hasLegacyModels: boolean;@@ -344,12 +353,14 @@ type ThreadSettingsSessionValue = {readonly showLegacy: boolean;readonly applyOptionChange: (id: string, value: string | boolean) => void;readonly commitPendingModel: () => void;+ readonly commitBotUsageCap: () => Promise<boolean>;readonly isApplied: (option: ModelOption) => boolean;readonly isDisplayed: (option: ModelOption) => boolean;readonly pressModel: (option: ModelOption) => void;readonly setProviderFilter: (providerKey: string | null) => void;readonly setSearchQuery: (query: string) => void;readonly setShowLegacy: (showLegacy: boolean) => void;+ readonly setBotUsageCapInput: (input: string) => void;readonly toggleProvider: (providerKey: string) => void;};@@ -366,6 +377,17 @@ function ThreadSettingsSessionProvider(() => new Set(),);const [pendingModel, setPendingModel] = useState<ModelOption | null>(null);+ const [botUsageCapInput, setBotUsageCapInput] = useState<string | undefined>(() =>+ props.botUsageCap === undefined ? undefined : (props.botUsageCap?.limit.toString() ?? ""),+ );+ const resolvedBotUsageCap =+ botUsageCapInput === undefined+ ? undefined+ : resolveBotUsageCapForProvider(botUsageCapInput, props.botUsageCapProviderDriver);+ const parsedBotUsageCap = resolvedBotUsageCap?.limit;+ const botUsageCapDirty =+ botUsageCapInput !== undefined && parsedBotUsageCap !== (props.botUsageCap?.limit ?? null);+ const botUsageCapValid = botUsageCapInput === undefined || parsedBotUsageCap !== undefined;const isApplied = useCallback((option: ModelOption) =>@@ -405,6 +427,13 @@ function ThreadSettingsSessionProvider(props.onSelectModel(pendingModel);}}, [pendingModel, props.onSelectModel]);+ const commitBotUsageCap = useCallback(+ () =>+ botUsageCapInput === undefined || !botUsageCapDirty+ ? Promise.resolve(true)+ : (props.onUpdateBotUsageCap?.(botUsageCapInput) ?? Promise.resolve(false)),+ [botUsageCapDirty, botUsageCapInput, props.onUpdateBotUsageCap],+ );const applyOptionChange = useCallback((id: string, value: string | boolean) => {@@ -453,6 +482,10 @@ function ThreadSettingsSessionProvider(providerGroups: props.providerGroups,runtimeMode: props.runtimeMode,onUpdateRuntimeMode: props.onUpdateRuntimeMode,+ botUsageCapInput,+ botUsageCapAvailable: resolvedBotUsageCap?.available ?? true,+ botUsageCapDirty,+ botUsageCapValid,displayedDescriptors,providerExpansionOverrides,hasLegacyModels,@@ -462,16 +495,23 @@ function ThreadSettingsSessionProvider(showLegacy: showLegacyToggle,applyOptionChange,commitPendingModel,+ commitBotUsageCap,isApplied,isDisplayed,pressModel,setProviderFilter,setSearchQuery,setShowLegacy: setShowLegacyToggle,+ setBotUsageCapInput,toggleProvider,}),[applyOptionChange,+ botUsageCapDirty,+ botUsageCapInput,+ botUsageCapValid,+ resolvedBotUsageCap?.available,+ commitBotUsageCap,commitPendingModel,displayedDescriptors,providerExpansionOverrides,@@ -705,7 +745,7 @@ function ThreadSettingsOptionsItem(props: {})}<Animated.View layout={THREAD_SETTINGS_OPTIONS_LAYOUT_TRANSITION}><DisclosureRow- isLast+ isLast={session.botUsageCapInput === undefined}label="Runtime"value={RUNTIME_MODE_CHOICES.find((choice) => choice.mode === session.runtimeMode)?.label@@ -713,6 +753,27 @@ function ThreadSettingsOptionsItem(props: {onPress={() => props.onOpenSubmenu({ kind: "runtime" })}/></Animated.View>+ {session.botUsageCapInput !== undefined && session.botUsageCapAvailable ? (+ <View className="min-h-14 flex-row items-center gap-3 bg-card px-4 py-2">+ <Text className="text-sm font-t3-medium text-foreground">Token hard stop</Text>+ <TextInput+ accessibilityLabel="Token hard stop"+ className="min-w-24 flex-1 text-right text-base tabular-nums text-foreground"+ inputMode="numeric"+ keyboardType="number-pad"+ onChangeText={session.setBotUsageCapInput}+ placeholder="No limit"+ placeholderTextColorClassName="accent-placeholder"+ returnKeyType="done"+ value={session.botUsageCapInput}+ />+ </View>+ ) : session.botUsageCapInput !== undefined ? (+ <View className="min-h-14 flex-row items-center justify-between gap-3 bg-card px-4 py-2">+ <Text className="text-sm font-t3-medium text-foreground">Token hard stop</Text>+ <Text className="text-sm text-foreground-muted">Unavailable for this provider</Text>+ </View>+ ) : null}</Animated.View>{Platform.OS !== "ios" && session.hasLegacyModels ? (@@ -946,10 +1007,20 @@ function ThreadSettingsModelsScreen() {const navigation = useNavigation<NativeStackNavigationProp<ThreadSettingsPickerStackParams>>();const usesNativeMailSearchToolbar = Platform.OS === "ios" && NATIVE_MAIL_SEARCH_TOOLBAR_SUPPORTED;const hasCustomCatalogFilter = session.providerFilter !== null || session.showLegacy;- const commitAndClose = useCallback(() => {+ const [saving, setSaving] = useState(false);+ const hasPendingChanges = session.pendingModel !== null || session.botUsageCapDirty;+ const commitAndClose = useCallback(async () => {+ if (!session.botUsageCapValid || saving) return;+ setSaving(true);+ const saved = await session.commitBotUsageCap();+ setSaving(false);+ if (!saved) {+ Alert.alert("Could not save bot settings");+ return;+ }session.commitPendingModel();presentation.onClose();- }, [presentation, session]);+ }, [presentation, saving, session]);const filterMenu = useMemo(() => ({title: "Model filters",@@ -994,9 +1065,10 @@ function ThreadSettingsModelsScreen() {<AndroidScreenHeaderactions={[{- accessibilityLabel: session.pendingModel ? "Save thread settings" : "Done",+ accessibilityLabel: hasPendingChanges ? "Save thread settings" : "Done",+ disabled: saving || !session.botUsageCapValid,icon: "checkmark",- onPress: commitAndClose,+ onPress: () => void commitAndClose(),},]}onBack={presentation.onClose}@@ -1059,9 +1131,10 @@ function ThreadSettingsModelsScreen() {</NativeHeaderToolbar><NativeHeaderToolbar placement="right"><NativeHeaderToolbar.Button- accessibilityLabel={session.pendingModel ? "Save thread settings" : "Done"}- label={session.pendingModel ? "Save" : "Done"}- onPress={commitAndClose}+ accessibilityLabel={hasPendingChanges ? "Save thread settings" : "Done"}+ disabled={saving || !session.botUsageCapValid}+ label={hasPendingChanges ? "Save" : "Done"}+ onPress={() => void commitAndClose()}/></NativeHeaderToolbar>{Platform.OS === "ios" && !usesNativeMailSearchToolbar ? (diff --git a/apps/mobile/src/features/threads/botStepUsage.test.ts b/apps/mobile/src/features/threads/botStepUsage.test.tsnew file mode 100644index 000000000..01df79e1b--- /dev/null+++ b/apps/mobile/src/features/threads/botStepUsage.test.ts@@ -0,0 +1,80 @@+import { BotId, EventId, TurnId, type OrchestrationThreadActivity } from "@t3tools/contracts";+import { describe, expect, it } from "vite-plus/test";++import {+ buildBotStepMeters,+ buildBotUsageCapPatch,+ formatBotStepEngine,+ resolveBotUsageCapForProvider,+} from "./botStepUsage";++function activity(+ id: string,+ kind: string,+ payload: OrchestrationThreadActivity["payload"],+): OrchestrationThreadActivity {+ return {+ id: EventId.make(id),+ tone: "info",+ kind,+ summary: "Usage",+ payload,+ turnId: TurnId.make("turn-1"),+ createdAt: "2026-08-31T00:00:00.000Z",+ };+}++describe("mobile bot step usage", () => {+ it("derives settled usage and a hard stop", () => {+ const meters = buildBotStepMeters([+ activity("usage", "bot.step-usage.updated", {+ botId: "bot-1",+ engine: { provider: "codex", model: "gpt-5.6-sol" },+ tokens: 1_200,+ estimatedCost: { status: "available", usd: 0.42 },+ }),+ activity("cap", "bot.usage-cap.hit", { limit: 1_000 }),+ ]);++ expect(meters.get("turn-1")).toEqual({+ engine: { provider: "codex", model: "gpt-5.6-sol" },+ tokens: 1_200,+ costUsd: 0.42,+ hardStopReached: true,+ });+ expect(formatBotStepEngine(meters.get("turn-1")!.engine)).toBe("codex/gpt-5.6-sol");+ });++ it("builds set and clear patches without changing other bot fields", () => {+ const botId = BotId.make("bot-1");++ expect(buildBotUsageCapPatch(botId, "50000")).toEqual({+ botId,+ usageCap: { unit: "tokens", limit: 50_000 },+ });+ expect(buildBotUsageCapPatch(botId, " ")).toEqual({ botId, usageCap: null });+ expect(buildBotUsageCapPatch(botId, "1.5")).toBeNull();+ expect(buildBotUsageCapPatch(botId, "0")).toBeNull();+ });++ it("clears hard stops for occupancy-only providers", () => {+ const botId = BotId.make("bot-1");++ expect(resolveBotUsageCapForProvider("50000", "cursor")).toEqual({+ available: false,+ limit: null,+ });+ expect(buildBotUsageCapPatch(botId, "50000", "cursor")).toEqual({+ botId,+ usageCap: null,+ });+ expect(buildBotUsageCapPatch(botId, "50000", "grok")).toEqual({+ botId,+ usageCap: null,+ });+ expect(buildBotUsageCapPatch(botId, "50000", "codex")).toEqual({+ botId,+ usageCap: { unit: "tokens", limit: 50_000 },+ });+ });+});diff --git a/apps/mobile/src/features/threads/botStepUsage.ts b/apps/mobile/src/features/threads/botStepUsage.tsnew file mode 100644index 000000000..668da819d--- /dev/null+++ b/apps/mobile/src/features/threads/botStepUsage.ts@@ -0,0 +1,83 @@+import type { UpdateBotInput } from "@t3tools/client-runtime/state/bots";+import {+ AkeruStepUsageSnapshot,+ type BotEngine,+ type BotId,+ type OrchestrationThreadActivity,+} from "@t3tools/contracts";+import * as Schema from "effect/Schema";++const isAkeruStepUsageSnapshot = Schema.is(AkeruStepUsageSnapshot);++export interface BotStepMeterData {+ readonly engine: BotEngine;+ readonly tokens: number | null;+ readonly costUsd: number | null;+ readonly hardStopReached: boolean;+}++export function buildBotStepMeters(+ activities: ReadonlyArray<OrchestrationThreadActivity>,+): ReadonlyMap<string, BotStepMeterData> {+ const meters = new Map<string, BotStepMeterData>();+ const cappedTurns = new Set<string>();+ for (const activity of activities) {+ if (activity.kind === "bot.usage-cap.hit" && activity.turnId !== null) {+ cappedTurns.add(activity.turnId);+ continue;+ }+ if (+ activity.kind !== "bot.step-usage.updated" ||+ activity.turnId === null ||+ !isAkeruStepUsageSnapshot(activity.payload)+ ) {+ continue;+ }+ meters.set(activity.turnId, {+ engine: activity.payload.engine,+ tokens: activity.payload.tokens,+ costUsd:+ activity.payload.estimatedCost.status === "available"+ ? activity.payload.estimatedCost.usd+ : null,+ hardStopReached: false,+ });+ }+ for (const turnId of cappedTurns) {+ const meter = meters.get(turnId);+ if (meter) meters.set(turnId, { ...meter, hardStopReached: true });+ }+ return meters;+}++export function formatBotStepEngine(engine: BotEngine): string {+ return engine.model.startsWith(`${engine.provider}/`)+ ? engine.model+ : `${engine.provider}/${engine.model}`;+}++export function parseBotUsageCapInput(input: string): number | null | undefined {+ if (input.trim().length === 0) return null;+ const limit = Number(input);+ return Number.isSafeInteger(limit) && limit > 0 ? limit : undefined;+}++export function resolveBotUsageCapForProvider(+ input: string,+ providerDriver?: string,+): { readonly available: boolean; readonly limit: number | null | undefined } {+ if (providerDriver === "cursor" || providerDriver === "grok") {+ return { available: false, limit: null };+ }+ return { available: true, limit: parseBotUsageCapInput(input) };+}++export function buildBotUsageCapPatch(+ botId: BotId,+ input: string,+ providerDriver?: string,+): UpdateBotInput | null {+ const { limit } = resolveBotUsageCapForProvider(input, providerDriver);+ if (limit === undefined) return null;+ return { botId, usageCap: limit === null ? null : { unit: "tokens", limit } };+}diff --git a/apps/mobile/src/lib/connection.test.ts b/apps/mobile/src/lib/connection.test.tsindex f474c7e6e..58a34818a 100644--- a/apps/mobile/src/lib/connection.test.ts+++ b/apps/mobile/src/lib/connection.test.ts@@ -1,11 +1,5 @@import { afterEach, describe, expect, it, vi } from "vite-plus/test";-import { EnvironmentId } from "@t3tools/contracts";--import {- isRelayManagedConnection,- redactPairingCredential,- toStableSavedRemoteConnection,-} from "./connection";+import { redactPairingCredential } from "./connection";import { authClientMetadata } from "./authClientMetadata";const mobilePlatform = vi.hoisted(() => ({ OS: "ios" as "ios" | "android" }));@@ -79,30 +73,4 @@ describe("mobile remote connection records", () => {),).toBe("https://app.t3.codes/pair?host=https%3A%2F%2Fdesktop.example&label=Desktop");});-- it("recognizes explicitly managed relay connections", () => {- expect(isRelayManagedConnection({ relayManaged: true })).toBe(true);- });-- it("keeps existing DPoP tunnel records read-only after upgrading", () => {- expect(isRelayManagedConnection({ authenticationMethod: "dpop" })).toBe(true);- expect(isRelayManagedConnection({ authenticationMethod: "bearer" })).toBe(false);- });-- it("drops short-lived managed environment credentials from stable records", () => {- const connection = {- environmentId: EnvironmentId.make("environment-1"),- environmentLabel: "Desktop",- pairingUrl: "https://desktop.example/",- displayUrl: "https://desktop.example/",- httpBaseUrl: "https://desktop.example/",- wsBaseUrl: "wss://desktop.example/",- bearerToken: null,- authenticationMethod: "dpop",- dpopAccessToken: "short-lived-token",- relayManaged: true,- } as const;-- expect(toStableSavedRemoteConnection(connection)).not.toHaveProperty("dpopAccessToken");- });});diff --git a/apps/mobile/src/lib/connection.ts b/apps/mobile/src/lib/connection.tsindex df26a192c..c280a66f2 100644--- a/apps/mobile/src/lib/connection.ts+++ b/apps/mobile/src/lib/connection.ts@@ -10,9 +10,6 @@ export interface SavedRemoteConnection {readonly httpBaseUrl: string;readonly wsBaseUrl: string;readonly bearerToken: string | null;- readonly authenticationMethod?: "bearer" | "dpop";- readonly dpopAccessToken?: string;- readonly relayManaged?: true;}export type RemoteClientConnectionState = EnvironmentConnectionPhase;@@ -25,20 +22,3 @@ export function redactPairingCredential(pairingUrl: string): string {return trimmed;}}--export function isRelayManagedConnection(- connection: Pick<SavedRemoteConnection, "authenticationMethod" | "relayManaged">,-): boolean {- return connection.relayManaged === true || connection.authenticationMethod === "dpop";-}--export function toStableSavedRemoteConnection(- connection: SavedRemoteConnection,-): SavedRemoteConnection {- if (!isRelayManagedConnection(connection) || !connection.dpopAccessToken) {- return connection;- }-- const { dpopAccessToken: _, ...stableConnection } = connection;- return stableConnection;-}diff --git a/apps/mobile/src/lib/runtime.ts b/apps/mobile/src/lib/runtime.tsindex 98730edfb..b398c11ae 100644--- a/apps/mobile/src/lib/runtime.ts+++ b/apps/mobile/src/lib/runtime.ts@@ -1,37 +1,54 @@+import * as Crypto from "effect/Crypto";+import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";import * as ManagedRuntime from "effect/ManagedRuntime";import * as Socket from "effect/unstable/socket/Socket";+import * as ExpoCrypto from "expo-crypto";import { remoteHttpClientLayer } from "@t3tools/client-runtime/rpc";-import { cryptoLayer } from "../features/cloud/dpop";-import { managedRelayClientLayer } from "../features/cloud/managedRelayLayer";-import { resolveCloudPublicConfig } from "../features/cloud/publicConfig";-import { tracingLayer } from "../features/observability/tracing";import * as Persistence from "../persistence/layer";-function configuredRelayUrl(): string {- return resolveCloudPublicConfig().relay.url ?? "http://relay.invalid";+function toExpoDigestAlgorithm(+ algorithm: Crypto.DigestAlgorithm,+): ExpoCrypto.CryptoDigestAlgorithm {+ switch (algorithm) {+ case "SHA-1":+ return ExpoCrypto.CryptoDigestAlgorithm.SHA1;+ case "SHA-256":+ return ExpoCrypto.CryptoDigestAlgorithm.SHA256;+ case "SHA-384":+ return ExpoCrypto.CryptoDigestAlgorithm.SHA384;+ case "SHA-512":+ return ExpoCrypto.CryptoDigestAlgorithm.SHA512;+ }}const httpClientLayer = remoteHttpClientLayer(fetch);+const cryptoLayer = Layer.succeed(+ Crypto.Crypto,+ Crypto.make({+ randomBytes: ExpoCrypto.getRandomBytes,+ digest: (algorithm, data) =>+ Effect.promise(async () => {+ const input = new Uint8Array(data.length);+ input.set(data);+ return new Uint8Array(await ExpoCrypto.digest(toExpoDigestAlgorithm(algorithm), input));+ }),+ }),+);type RuntimeLayerSource =- | ReturnType<typeof managedRelayClientLayer>| typeof Socket.layerWebSocketConstructorGlobal| typeof cryptoLayer| typeof httpClientLayer- | typeof Persistence.layer- | typeof tracingLayer;+ | typeof Persistence.layer;-const runtimeLayer = Layer.merge(- managedRelayClientLayer(configuredRelayUrl()),+const runtimeLayer = Layer.mergeAll(Socket.layerWebSocketConstructorGlobal,-).pipe(- Layer.provideMerge(cryptoLayer),- Layer.provideMerge(httpClientLayer),- Layer.provideMerge(tracingLayer.pipe(Layer.provide(httpClientLayer))),- Layer.provideMerge(Persistence.layer),+ cryptoLayer,+ httpClientLayer,+ Persistence.layer,);export const runtime: ManagedRuntime.ManagedRuntime<diff --git a/apps/mobile/src/lib/storage.test.ts b/apps/mobile/src/lib/storage.test.tsindex fe022c119..5eb9d5c9a 100644--- a/apps/mobile/src/lib/storage.test.ts+++ b/apps/mobile/src/lib/storage.test.ts@@ -100,20 +100,6 @@ import {saveConnection,savePreferencesPatch,} from "../persistence/imperative";-import { toStableSavedRemoteConnection } from "./connection";--const managedConnection = {- environmentId: EnvironmentId.make("environment-1"),- environmentLabel: "Desktop",- pairingUrl: "https://desktop.example/",- displayUrl: "https://desktop.example/",- httpBaseUrl: "https://desktop.example/",- wsBaseUrl: "wss://desktop.example/",- bearerToken: null,- authenticationMethod: "dpop",- dpopAccessToken: "short-lived-token",- relayManaged: true,-} as const;describe("mobile connection storage", () => {beforeEach(() => {@@ -121,24 +107,6 @@ describe("mobile connection storage", () => {vi.clearAllMocks();});- it("persists relay-managed connections without their ephemeral access token", async () => {- await saveConnection(managedConnection);-- const savedValue = mocks.setItemAsync.mock.calls[0]?.[1];- expect(savedValue).toBeDefined();- expect(JSON.parse(savedValue ?? "")).toEqual({- connections: [toStableSavedRemoteConnection(managedConnection)],- });- });-- it("loads relay-managed connection metadata without a cached access token", async () => {- await saveConnection(managedConnection);-- await expect(loadSavedConnections()).resolves.toEqual([- toStableSavedRemoteConnection(managedConnection),- ]);- });-it("preserves secure-storage read failures with operation and key context", async () => {const cause = new Error("keychain unavailable");mocks.getItemAsync.mockRejectedValueOnce(cause);diff --git a/apps/mobile/src/lib/threadActivity.test.ts b/apps/mobile/src/lib/threadActivity.test.tsindex a1317ac2b..56ea09547 100644--- a/apps/mobile/src/lib/threadActivity.test.ts+++ b/apps/mobile/src/lib/threadActivity.test.ts@@ -252,6 +252,49 @@ function makeThread(}describe("buildThreadFeed", () => {+ it("attaches bot step usage to its assistant message without a duplicate work row", () => {+ const turnId = TurnId.make("turn-bot");+ const thread = makeThread({+ id: ThreadId.make("thread-bot"),+ projectId: ProjectId.make("project-1"),+ title: "Bot thread",+ messages: [+ {+ id: MessageId.make("assistant-bot"),+ role: "assistant",+ text: "Done",+ turnId,+ streaming: false,+ createdAt: "2026-08-31T00:00:02.000Z",+ updatedAt: "2026-08-31T00:00:02.000Z",+ },+ ],+ activities: [+ makeActivity({+ id: EventId.make("usage"),+ kind: "bot.step-usage.updated",+ summary: "Usage",+ turnId,+ createdAt: "2026-08-31T00:00:01.000Z",+ payload: {+ botId: "bot-1",+ engine: { provider: "codex", model: "gpt-5.6-sol" },+ tokens: 1_200,+ estimatedCost: { status: "available", usd: 0.42 },+ },+ }),+ ],+ });++ expect(buildThreadFeed(thread)).toEqual([+ expect.objectContaining({+ type: "message",+ id: "assistant-bot",+ botStepMeter: expect.objectContaining({ tokens: 1_200, costUsd: 0.42 }),+ }),+ ]);+ });+it("keeps older local feedback before newer messages returned by the server", () => {const submission = {id: MessageId.make("feedback-command-ordering"),diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.tsindex a9b357a07..7c232a247 100644--- a/apps/mobile/src/lib/threadActivity.ts+++ b/apps/mobile/src/lib/threadActivity.ts@@ -18,6 +18,8 @@ import * as Arr from "effect/Array";import * as Order from "effect/Order";import * as Schema from "effect/Schema";+import { buildBotStepMeters, type BotStepMeterData } from "../features/threads/botStepUsage";+export interface PendingApproval {readonly requestId: ApprovalRequestId;readonly requestKind: ProviderRequestKind;@@ -102,6 +104,7 @@ type RawThreadFeedEntry =readonly id: string;readonly createdAt: string;readonly message: OrchestrationThread["messages"][number];+ readonly botStepMeter?: BotStepMeterData;}| {readonly type: "activity";@@ -339,6 +342,8 @@ function deriveWorkLogEntries(if (activity.kind === "task.updated" && !isTerminalBypassUpdate(activity)) continue;if (activity.kind === "tool.progress") continue;if (activity.kind === "context-window.updated") continue;+ if (activity.kind === "bot.step-usage.updated") continue;+ if (activity.kind === "bot.usage-cap.hit") continue;if (activity.summary === "Checkpoint captured") continue;if (isPlanBoundaryToolActivity(activity)) continue;if (isAgentInternalActivity(activity)) continue;@@ -1400,10 +1405,10 @@ export function derivePendingApprovals(? payload.options.filter(isProviderApprovalOption): undefined;- if (activity.kind === "approval.requested" && requestId && requestKind) {+ if (activity.kind === "approval.requested" && requestId) {openByRequestId.set(requestId, {requestId,- requestKind,+ requestKind: requestKind ?? "command",createdAt: activity.createdAt,...(detail ? { detail } : {}),...(appName ? { appName } : {}),@@ -1555,6 +1560,7 @@ export function buildThreadFeed(: loadedMessages;const oldestLoadedMessageCreatedAt =options?.loadedMessages !== undefined ? (loadedMessages[0]?.createdAt ?? null) : null;+ const botStepMeters = buildBotStepMeters(thread.activities);const workLogEntries = deriveWorkLogEntries(thread.activities);const entries = Arr.sortWith([@@ -1563,6 +1569,7 @@ export function buildThreadFeed(id: message.id,createdAt: message.createdAt,message,+ ...(message.turnId === null ? {} : { botStepMeter: botStepMeters.get(message.turnId) }),})),...workLogEntries.filter((entry) => {diff --git a/apps/mobile/src/persistence/mobile-preferences.ts b/apps/mobile/src/persistence/mobile-preferences.tsindex 5d0bd8a3c..b12cbaac4 100644--- a/apps/mobile/src/persistence/mobile-preferences.ts+++ b/apps/mobile/src/persistence/mobile-preferences.ts@@ -16,6 +16,8 @@ const PREFERENCES_KEY = "t3code.preferences";const PREFERENCES_FALLBACK_KEY = "t3code.preferences.fallback";export interface Preferences {+ readonly reviewedPrivacyPolicyVersion?: string;+ readonly reviewedTermsVersion?: string;readonly liveActivitiesEnabled?: boolean;readonly themeId?: MobileThemeId;readonly lightThemeId?: MobileThemeId;@@ -26,7 +28,6 @@ export interface Preferences {readonly markdownFontSize?: number;readonly codeFontSize?: number | null;readonly codeWordBreak?: boolean;- readonly connectOnboardingOptOutAccounts?: ReadonlyArray<string>;readonly collapsedProjectGroups?: readonly string[];/** @deprecated Kept temporarily so older OTA bundles retain the selected mode. */readonly projectGroupingEnabled?: boolean;@@ -87,6 +88,8 @@ export class MobilePreferencesStore extends Context.Service<function sanitizePreferences(parsed: Preferences): Preferences {const preferences: {+ reviewedPrivacyPolicyVersion?: string;+ reviewedTermsVersion?: string;liveActivitiesEnabled?: boolean;themeId?: MobileThemeId;lightThemeId?: MobileThemeId;@@ -97,7 +100,6 @@ function sanitizePreferences(parsed: Preferences): Preferences {markdownFontSize?: number;codeFontSize?: number | null;codeWordBreak?: boolean;- connectOnboardingOptOutAccounts?: ReadonlyArray<string>;collapsedProjectGroups?: readonly string[];projectGroupingEnabled?: boolean;projectGroupingMode?: SidebarProjectGroupingMode;@@ -108,6 +110,12 @@ function sanitizePreferences(parsed: Preferences): Preferences {threadListV2SnoozedShelfExpanded?: boolean;} = {};+ if (typeof parsed.reviewedPrivacyPolicyVersion === "string") {+ preferences.reviewedPrivacyPolicyVersion = parsed.reviewedPrivacyPolicyVersion;+ }+ if (typeof parsed.reviewedTermsVersion === "string") {+ preferences.reviewedTermsVersion = parsed.reviewedTermsVersion;+ }if (typeof parsed.liveActivitiesEnabled === "boolean") {preferences.liveActivitiesEnabled = parsed.liveActivitiesEnabled;}@@ -147,11 +155,6 @@ function sanitizePreferences(parsed: Preferences): Preferences {preferences.codeFontSize = parsed.codeFontSize;}if (typeof parsed.codeWordBreak === "boolean") preferences.codeWordBreak = parsed.codeWordBreak;- if (Array.isArray(parsed.connectOnboardingOptOutAccounts)) {- preferences.connectOnboardingOptOutAccounts = parsed.connectOnboardingOptOutAccounts.filter(- (account): account is string => typeof account === "string",- );- }if (Array.isArray(parsed.collapsedProjectGroups)) {preferences.collapsedProjectGroups = parsed.collapsedProjectGroups.filter((key): key is string => typeof key === "string",diff --git a/apps/mobile/src/persistence/mobile-storage.ts b/apps/mobile/src/persistence/mobile-storage.tsindex 266e8c1a9..52b0204d7 100644--- a/apps/mobile/src/persistence/mobile-storage.ts+++ b/apps/mobile/src/persistence/mobile-storage.ts@@ -6,11 +6,7 @@ import { pipe } from "effect/Function";import * as Layer from "effect/Layer";import * as Schema from "effect/Schema";-import {- isRelayManagedConnection,- type SavedRemoteConnection,- toStableSavedRemoteConnection,-} from "../lib/connection";+import { type SavedRemoteConnection } from "../lib/connection";import * as MobileSecureStorage from "./mobile-secure-storage";const CONNECTIONS_KEY = "t3code.connections";@@ -152,11 +148,7 @@ export const make = Effect.fn("MobileStorage.make")(function* () {Effect.map((parsed) =>pipe(parsed?.connections ?? [],- Arr.filter(- (connection) =>- !!connection.environmentId &&- (!!connection.bearerToken?.trim() || isRelayManagedConnection(connection)),- ),+ Arr.filter((connection) => !!connection.environmentId && !!connection.bearerToken?.trim()),),),);@@ -165,15 +157,14 @@ export const make = Effect.fn("MobileStorage.make")(function* () {connection: SavedRemoteConnection,) {const current = yield* loadSavedConnections;- const stableConnection = toStableSavedRemoteConnection(connection);const next = current.some((entry) => entry.environmentId === connection.environmentId)? pipe(current,Arr.map((entry) =>- entry.environmentId === connection.environmentId ? stableConnection : entry,+ entry.environmentId === connection.environmentId ? connection : entry,),)- : pipe(current, Arr.append(stableConnection));+ : pipe(current, Arr.append(connection));yield* writeJson(CONNECTIONS_KEY, { connections: next });});diff --git a/apps/mobile/src/state/bots.ts b/apps/mobile/src/state/bots.tsnew file mode 100644index 000000000..e6629fa6b--- /dev/null+++ b/apps/mobile/src/state/bots.ts@@ -0,0 +1,17 @@+import { createBotEnvironmentAtoms } from "@t3tools/client-runtime/state/bots";+import type { EnvironmentId, OrchestrationBot } from "@t3tools/contracts";+import { Atom } from "effect/unstable/reactivity";++import { connectionAtomRuntime } from "../connection/runtime";+import { environmentSnapshotAtom } from "./shell";++const EMPTY_BOTS: ReadonlyArray<OrchestrationBot> = Object.freeze([]);++export const botEnvironment = createBotEnvironmentAtoms(connectionAtomRuntime);++export const environmentBotsAtom = Atom.family((environmentId: EnvironmentId) =>+ Atom.make(+ (get): ReadonlyArray<OrchestrationBot> =>+ get(environmentSnapshotAtom(environmentId))?.bots ?? EMPTY_BOTS,+ ).pipe(Atom.withLabel(`mobile-bots:${environmentId}`)),+);diff --git a/apps/mobile/src/state/environments.ts b/apps/mobile/src/state/environments.tsindex 88d80631a..87b7c6c94 100644--- a/apps/mobile/src/state/environments.ts+++ b/apps/mobile/src/state/environments.ts@@ -14,7 +14,6 @@ export interface EnvironmentPresentation extends BaseEnvironmentPresentation {readonly environmentId: EnvironmentId;readonly label: string;readonly displayUrl: string | null;- readonly relayManaged: boolean;}export function projectEnvironmentPresentation(@@ -26,7 +25,6 @@ export function projectEnvironmentPresentation(environmentId,label: presentation.entry.target.label,displayUrl: connectionCatalogDisplayUrl(presentation.entry),- relayManaged: presentation.entry.target._tag === "RelayConnectionTarget",};}diff --git a/apps/mobile/src/state/preferences.test.ts b/apps/mobile/src/state/preferences.test.tsindex c53594eb2..a401a7ac8 100644--- a/apps/mobile/src/state/preferences.test.ts+++ b/apps/mobile/src/state/preferences.test.ts@@ -62,6 +62,35 @@ function makePreferencesState(}describe("mobile preferences state", () => {+ it.effect("persists reviewed policy versions locally", () =>+ Effect.gen(function* () {+ const savePatch = vi.fn((patch: Partial<Preferences>) => Effect.succeed(patch));+ const state = makePreferencesState({ load: Effect.succeed({}), savePatch });+ const registry = AtomRegistry.make();+ const unmountPreferences = registry.mount(state.preferencesAtom);+ const unmountUpdate = registry.mount(state.updatePreferencesAtom);++ yield* AtomRegistry.getResult(registry, state.preferencesAtom, { suspendOnWaiting: true });+ registry.set(state.updatePreferencesAtom, {+ reviewedPrivacyPolicyVersion: "2026-08-31",+ reviewedTermsVersion: "2026-08-31",+ });++ yield* Effect.promise(() =>+ vi.waitFor(() => {+ expect(savePatch).toHaveBeenCalledWith({+ reviewedPrivacyPolicyVersion: "2026-08-31",+ reviewedTermsVersion: "2026-08-31",+ });+ }),+ );++ unmountUpdate();+ unmountPreferences();+ registry.dispose();+ }),+ );+it.effect("shares one preference load across consumers", () =>Effect.gen(function* () {const load = vi.fn(() => Promise.resolve<Preferences>({ baseFontSize: 17 }));diff --git a/apps/mobile/src/state/relay.ts b/apps/mobile/src/state/relay.tsdeleted file mode 100644index f07857273..000000000--- a/apps/mobile/src/state/relay.ts+++ /dev/null@@ -1,6 +0,0 @@-import { createRelayEnvironmentDiscoveryAtoms } from "@t3tools/client-runtime/state/relay";--import { connectionAtomRuntime } from "../connection/runtime";--export const relayEnvironmentDiscovery =- createRelayEnvironmentDiscoveryAtoms(connectionAtomRuntime);diff --git a/apps/mobile/src/state/remote-runtime-types.ts b/apps/mobile/src/state/remote-runtime-types.tsindex 89abd3c22..30dc6485b 100644--- a/apps/mobile/src/state/remote-runtime-types.ts+++ b/apps/mobile/src/state/remote-runtime-types.ts@@ -12,7 +12,6 @@ export interface ConnectedEnvironmentSummary {readonly environmentId: EnvironmentId;readonly environmentLabel: string;readonly displayUrl: string;- readonly isRelayManaged: boolean;readonly connectionState: EnvironmentConnectionPhase;readonly connectionError: string | null;readonly connectionErrorTraceId: string | null;diff --git a/apps/mobile/src/state/use-remote-environment-registry.ts b/apps/mobile/src/state/use-remote-environment-registry.tsindex 6fb41fc09..b67ad7695 100644--- a/apps/mobile/src/state/use-remote-environment-registry.ts+++ b/apps/mobile/src/state/use-remote-environment-registry.ts@@ -60,13 +60,6 @@ function toSavedConnection(httpBaseUrl,wsBaseUrl,bearerToken: authorization?._tag === "Bearer" ? authorization.token : null,- ...(environment.relayManaged- ? {- authenticationMethod: "dpop" as const,- relayManaged: true as const,- ...(authorization?._tag === "Dpop" ? { dpopAccessToken: authorization.accessToken } : {}),- }- : { authenticationMethod: "bearer" as const }),};}@@ -136,7 +129,6 @@ export function useRemoteConnectionStatus() {environmentId: environment.environmentId,environmentLabel: environment.environmentLabel,displayUrl: environment.displayUrl,- isRelayManaged: environment.isRelayManaged,connectionState: environment.connectionState,connectionError: environment.connectionError,connectionErrorTraceId: environment.connectionErrorTraceId,diff --git a/apps/mobile/src/state/use-thread-selection.ts b/apps/mobile/src/state/use-thread-selection.tsindex 8e340ef33..96b17b58a 100644--- a/apps/mobile/src/state/use-thread-selection.ts+++ b/apps/mobile/src/state/use-thread-selection.ts@@ -48,6 +48,9 @@ function threadDetailToShell(environmentId,id: thread.id,projectId: thread.projectId,+ botId: thread.botId ?? null,+ groupId: thread.groupId ?? null,+ respondingBotId: thread.respondingBotId ?? null,title: thread.title,modelSelection: thread.modelSelection,runtimeMode: thread.runtimeMode,diff --git a/apps/mobile/src/state/workspaceModel.test.ts b/apps/mobile/src/state/workspaceModel.test.tsindex e51273d57..76b3d5560 100644--- a/apps/mobile/src/state/workspaceModel.test.ts+++ b/apps/mobile/src/state/workspaceModel.test.ts@@ -20,7 +20,6 @@ function environment(environmentId: ENVIRONMENT_ID,label: "Julius's MacBook Pro",displayUrl: "https://environment.example.test",- relayManaged: false,entry: {target: new BearerConnectionTarget({environmentId: ENVIRONMENT_ID,diff --git a/apps/mobile/src/state/workspaceModel.ts b/apps/mobile/src/state/workspaceModel.tsindex 44c43d6c8..bc51dcdbf 100644--- a/apps/mobile/src/state/workspaceModel.ts+++ b/apps/mobile/src/state/workspaceModel.ts@@ -9,7 +9,6 @@ export interface WorkspaceEnvironment {readonly environmentId: EnvironmentId;readonly environmentLabel: string;readonly displayUrl: string;- readonly isRelayManaged: boolean;readonly connectionState: EnvironmentConnectionPhase;readonly connectionError: string | null;readonly connectionErrorTraceId: string | null;@@ -37,7 +36,6 @@ export function projectWorkspaceEnvironment(environmentId: environment.environmentId,environmentLabel: environment.label,displayUrl: environment.displayUrl ?? "",- isRelayManaged: environment.relayManaged,connectionState: environment.connection.phase,connectionError: environment.connection.error,connectionErrorTraceId: environment.connection.traceId,diff --git a/apps/mobile/tsconfig.json b/apps/mobile/tsconfig.jsonindex f3763c565..29b189b6e 100644--- a/apps/mobile/tsconfig.json+++ b/apps/mobile/tsconfig.json@@ -2,6 +2,7 @@"extends": "expo/tsconfig.base","compilerOptions": {"allowImportingTsExtensions": true,- "strict": true+ "strict": true,+ "types": ["node"]}}diff --git a/apps/server/integration/OrchestrationEngineHarness.integration.ts b/apps/server/integration/OrchestrationEngineHarness.integration.tsindex 914afafa2..6b8cb5f55 100644--- a/apps/server/integration/OrchestrationEngineHarness.integration.ts+++ b/apps/server/integration/OrchestrationEngineHarness.integration.ts@@ -87,7 +87,6 @@ import * as VcsDriverRegistry from "../src/vcs/VcsDriverRegistry.ts";import { VcsStatusBroadcaster } from "../src/vcs/VcsStatusBroadcaster.ts";import { GitWorkflowService } from "../src/git/GitWorkflowService.ts";import * as VcsProcess from "../src/vcs/VcsProcess.ts";-import * as AgentAwarenessRelay from "../src/relay/AgentAwarenessRelay.ts";import { BotUsageLedgerLive } from "../src/usage/BotUsageLedger.ts";const decodeCodexSettings = Schema.decodeEffect(CodexSettings);@@ -393,12 +392,6 @@ export const makeOrchestrationIntegrationHarness = (drain: Effect.void,}),),- Layer.provideMerge(- Layer.succeed(AgentAwarenessRelay.AgentAwarenessRelay, {- publishThread: () => Effect.void,- start: () => Effect.void,- }),- ),);const layer = Layer.empty.pipe(Layer.provideMerge(runtimeServicesLayer),diff --git a/apps/server/src/auth/EnvironmentAuth.test.ts b/apps/server/src/auth/EnvironmentAuth.test.tsindex 440efcee5..1e0901c53 100644--- a/apps/server/src/auth/EnvironmentAuth.test.ts+++ b/apps/server/src/auth/EnvironmentAuth.test.ts@@ -103,7 +103,6 @@ it.layer(NodeServices.layer)("EnvironmentAuth.layer", (it) => {"orchestration:operate","terminal:operate","review:write",- "relay:read",]);expect(verified.subject).toBe("one-time-token");}).pipe(Effect.provide(makeEnvironmentAuthLayer())),@@ -182,10 +181,8 @@ it.layer(NodeServices.layer)("EnvironmentAuth.layer", (it) => {"orchestration:operate","terminal:operate","review:write",- "relay:read","access:read","access:write",- "relay:write",]);expect(verified.subject).toBe("administrative-bootstrap");}).pipe(Effect.provide(makeEnvironmentAuthLayer())),diff --git a/apps/server/src/auth/EnvironmentAuth.ts b/apps/server/src/auth/EnvironmentAuth.tsindex b56772f89..e27d7aaac 100644--- a/apps/server/src/auth/EnvironmentAuth.ts+++ b/apps/server/src/auth/EnvironmentAuth.ts@@ -19,7 +19,6 @@ import {} from "@t3tools/contracts";import { encodeOAuthScope } from "@t3tools/shared/oauthScope";import * as Context from "effect/Context";-import * as Crypto from "effect/Crypto";import * as DateTime from "effect/DateTime";import * as Duration from "effect/Duration";import * as Effect from "effect/Effect";@@ -32,7 +31,6 @@ import * as EnvironmentAuthPolicy from "./EnvironmentAuthPolicy.ts";import * as PairingGrantStore from "./PairingGrantStore.ts";import * as ServerSecretStore from "./ServerSecretStore.ts";import * as SessionStore from "./SessionStore.ts";-import { verifyRequestDpopProof } from "./dpop.ts";import { layerConfig as SqlitePersistenceLayer } from "../persistence/Layers/Sqlite.ts";export const DEFAULT_SESSION_SUBJECT = "cli-issued-session";@@ -63,7 +61,6 @@ export interface AuthenticatedSession {readonly subject: string;readonly method: ServerAuthSessionMethod;readonly scopes: ReadonlyArray<AuthEnvironmentScope>;- readonly proofKeyThumbprint?: string;readonly expiresAt?: DateTime.DateTime;}@@ -203,110 +200,6 @@ export class ServerAuthWebSocketTokenIssueError extends Schema.TaggedErrorClass<}}-export class ServerAuthDpopReplayStateRecordError extends Schema.TaggedErrorClass<ServerAuthDpopReplayStateRecordError>()(- "ServerAuthDpopReplayStateRecordError",- {- ...serverAuthInternalErrorContext,- },-) {- override get message(): string {- return "Failed to record DPoP proof replay state.";- }-}--export class ServerAuthDpopReplayKeyCalculationError extends Schema.TaggedErrorClass<ServerAuthDpopReplayKeyCalculationError>()(- "ServerAuthDpopReplayKeyCalculationError",- {- ...serverAuthInternalErrorContext,- },-) {- override get message(): string {- return "Failed to calculate DPoP replay key.";- }-}--export class ServerAuthLinkedCloudAccountVerificationError extends Schema.TaggedErrorClass<ServerAuthLinkedCloudAccountVerificationError>()(- "ServerAuthLinkedCloudAccountVerificationError",- {- ...serverAuthInternalErrorContext,- },-) {- override get message(): string {- return "Could not verify the linked cloud account.";- }-}--export class ServerAuthLinkedCloudAccountReadError extends Schema.TaggedErrorClass<ServerAuthLinkedCloudAccountReadError>()(- "ServerAuthLinkedCloudAccountReadError",- {- ...serverAuthInternalErrorContext,- },-) {- override get message(): string {- return "Could not read the linked cloud account.";- }-}--export class ServerAuthLinkedCloudAccountMissingError extends Schema.TaggedErrorClass<ServerAuthLinkedCloudAccountMissingError>()(- "ServerAuthLinkedCloudAccountMissingError",- {},-) {- override get message(): string {- return "Cloud linked user is not installed for this environment.";- }-}--export class ServerAuthCloudLinkJwtSigningError extends Schema.TaggedErrorClass<ServerAuthCloudLinkJwtSigningError>()(- "ServerAuthCloudLinkJwtSigningError",- {- ...serverAuthInternalErrorContext,- },-) {- override get message(): string {- return "Failed to sign cloud link JWT.";- }-}--export class ServerAuthCloudMintPublicKeyMissingError extends Schema.TaggedErrorClass<ServerAuthCloudMintPublicKeyMissingError>()(- "ServerAuthCloudMintPublicKeyMissingError",- {},-) {- override get message(): string {- return "Cloud mint public key is not installed for this environment.";- }-}--export class ServerAuthCloudRelayIssuerMissingError extends Schema.TaggedErrorClass<ServerAuthCloudRelayIssuerMissingError>()(- "ServerAuthCloudRelayIssuerMissingError",- {},-) {- override get message(): string {- return "Cloud relay issuer is not installed for this environment.";- }-}--export class ServerAuthCloudHealthJwtSigningError extends Schema.TaggedErrorClass<ServerAuthCloudHealthJwtSigningError>()(- "ServerAuthCloudHealthJwtSigningError",- {- ...serverAuthInternalErrorContext,- },-) {- override get message(): string {- return "Failed to sign cloud health JWT.";- }-}--export class ServerAuthCloudMintJwtSigningError extends Schema.TaggedErrorClass<ServerAuthCloudMintJwtSigningError>()(- "ServerAuthCloudMintJwtSigningError",- {- ...serverAuthInternalErrorContext,- },-) {- override get message(): string {- return "Failed to sign cloud mint JWT.";- }-}-export const ServerAuthInternalError = Schema.Union([ServerAuthBootstrapCredentialValidationError,ServerAuthSessionCredentialValidationError,@@ -320,16 +213,6 @@ export const ServerAuthInternalError = Schema.Union([ServerAuthSessionRevocationError,ServerAuthOtherSessionsRevocationError,ServerAuthWebSocketTokenIssueError,- ServerAuthDpopReplayStateRecordError,- ServerAuthDpopReplayKeyCalculationError,- ServerAuthLinkedCloudAccountVerificationError,- ServerAuthLinkedCloudAccountReadError,- ServerAuthLinkedCloudAccountMissingError,- ServerAuthCloudLinkJwtSigningError,- ServerAuthCloudMintPublicKeyMissingError,- ServerAuthCloudRelayIssuerMissingError,- ServerAuthCloudHealthJwtSigningError,- ServerAuthCloudMintJwtSigningError,]);export type ServerAuthInternalError = typeof ServerAuthInternalError.Type;export const isServerAuthInternalError = Schema.is(ServerAuthInternalError);@@ -425,9 +308,6 @@ export class EnvironmentAuth extends Context.Service<credential: string,requestedScopes: ReadonlyArray<AuthEnvironmentScope> | undefined,requestMetadata: AuthClientMetadata,- input?: {- readonly proofKeyThumbprint?: string;- },) => Effect.Effect<AuthAccessTokenResult,ServerAuthInvalidCredentialError | ServerAuthInvalidRequestError | ServerAuthInternalError@@ -437,7 +317,6 @@ export class EnvironmentAuth extends Context.Service<readonly label?: string;readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;readonly subject?: string;- readonly proofKeyThumbprint?: string;readonly purpose?: "startup";}) => Effect.Effect<IssuedPairingLink, ServerAuthInternalError>;readonly issuePairingCredential: (@@ -498,7 +377,6 @@ type BootstrapExchangeResult = {};const AUTHORIZATION_PREFIX = "Bearer ";-const DPOP_AUTHORIZATION_PREFIX = "DPoP ";const WEBSOCKET_TICKET_QUERY_PARAM = "wsTicket";const bySessionPriority = (left: AuthClientSession, right: AuthClientSession) => {@@ -545,21 +423,10 @@ function parseBearerToken(request: HttpServerRequest.HttpServerRequest): stringreturn token.length > 0 ? token : null;}-function parseDpopToken(request: HttpServerRequest.HttpServerRequest): string | null {- const header = request.headers["authorization"];- if (typeof header !== "string" || !header.startsWith(DPOP_AUTHORIZATION_PREFIX)) {- return null;- }- const token = header.slice(DPOP_AUTHORIZATION_PREFIX.length).trim();- return token.length > 0 ? token : null;-}-export const make = Effect.gen(function* () {const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy;const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;const sessions = yield* SessionStore.SessionStore;- const secretStore = yield* ServerSecretStore.ServerSecretStore;- const crypto = yield* Crypto.Crypto;const descriptor = yield* policy.getDescriptor();const authenticateToken = (@@ -583,7 +450,6 @@ export const make = Effect.gen(function* () {subject: session.subject,method: session.method,scopes: session.scopes,- ...(session.proofKeyThumbprint ? { proofKeyThumbprint: session.proofKeyThumbprint } : {}),...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),})),mapSessionVerificationErrors,@@ -594,41 +460,11 @@ export const make = Effect.gen(function* () {): Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError> => {const cookieToken = request.cookies[sessions.cookieName];const bearerToken = parseBearerToken(request);- const dpopToken = parseDpopToken(request);- const credential = cookieToken ?? bearerToken ?? dpopToken;+ const credential = cookieToken ?? bearerToken;if (!credential) {return Effect.fail(new ServerAuthMissingCredentialError({}));}- return authenticateToken(credential).pipe(- Effect.flatMap((session) => {- if (session.proofKeyThumbprint) {- if (!dpopToken || dpopToken !== credential) {- return Effect.fail(- new ServerAuthInvalidCredentialError({- diagnostic: "DPoP-bound access token requires DPoP authorization.",- }),- );- }- return verifyRequestDpopProof({- request,- expectedThumbprint: session.proofKeyThumbprint,- expectedAccessToken: dpopToken,- }).pipe(- Effect.provideService(ServerSecretStore.ServerSecretStore, secretStore),- Effect.provideService(Crypto.Crypto, crypto),- Effect.as(session),- );- }- if (dpopToken) {- return Effect.fail(- new ServerAuthInvalidCredentialError({- diagnostic: "DPoP authorization requires a proof-bound access token.",- }),- );- }- return Effect.succeed(session);- }),- );+ return authenticateToken(credential);};const getSessionState: EnvironmentAuth["Service"]["getSessionState"] = (request) =>@@ -689,8 +525,8 @@ export const make = Effect.gen(function* () {);const exchangeBootstrapCredentialForAccessToken: EnvironmentAuth["Service"]["exchangeBootstrapCredentialForAccessToken"] =- (credential, requestedScopes, requestMetadata, input) =>- bootstrapCredentials.consume(credential, input).pipe(+ (credential, requestedScopes, requestMetadata) =>+ bootstrapCredentials.consume(credential).pipe(Effect.mapError(toBootstrapExchangeError),Effect.flatMap((grant) =>Effect.gen(function* () {@@ -700,15 +536,9 @@ export const make = Effect.gen(function* () {}return yield* sessions.issue({- method: input?.proofKeyThumbprint ? "dpop-access-token" : "bearer-access-token",+ method: "bearer-access-token",subject: grant.subject,scopes: grantedScopes,- ...(input?.proofKeyThumbprint- ? {- proofKeyThumbprint: input.proofKeyThumbprint,- ttl: Duration.hours(1),- }- : {}),client: {...requestMetadata,...(grant.label ? { label: grant.label } : {}),@@ -728,7 +558,7 @@ export const make = Effect.gen(function* () {({access_token: session.token,issued_token_type: AuthAccessTokenType,- token_type: input?.proofKeyThumbprint ? "DPoP" : "Bearer",+ token_type: "Bearer",expires_in: Math.max(0,Math.floor(@@ -776,7 +606,6 @@ export const make = Effect.gen(function* () {subject: input?.subject ?? "one-time-token",...(input?.ttl ? { ttl: input.ttl } : {}),...(input?.label ? { label: input.label } : {}),- ...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}),...(input?.purpose ? { purpose: input.purpose } : {}),});return {diff --git a/apps/server/src/auth/EnvironmentAuthAdmin.test.ts b/apps/server/src/auth/EnvironmentAuthAdmin.test.tsindex 03009270e..9248714fd 100644--- a/apps/server/src/auth/EnvironmentAuthAdmin.test.ts+++ b/apps/server/src/auth/EnvironmentAuthAdmin.test.ts@@ -82,10 +82,8 @@ it.layer(NodeServices.layer)("EnvironmentAuth administrative operations", (it) ="orchestration:operate","terminal:operate","review:write",- "relay:read","access:read","access:write",- "relay:write",]);expect(issued.client.deviceType).toBe("bot");expect(issued.client.label).toBe("deploy-bot");@@ -95,10 +93,8 @@ it.layer(NodeServices.layer)("EnvironmentAuth administrative operations", (it) ="orchestration:operate","terminal:operate","review:write",- "relay:read","access:read","access:write",- "relay:write",]);expect(verified.method).toBe("bearer-access-token");expect(listedBeforeRevoke).toHaveLength(1);diff --git a/apps/server/src/auth/EnvironmentAuthPolicy.ts b/apps/server/src/auth/EnvironmentAuthPolicy.tsindex df39d50a2..49ddee9f3 100644--- a/apps/server/src/auth/EnvironmentAuthPolicy.ts+++ b/apps/server/src/auth/EnvironmentAuthPolicy.ts@@ -36,7 +36,7 @@ export const make = Effect.gen(function* () {const descriptor: ServerAuthDescriptor = {policy,bootstrapMethods,- sessionMethods: ["browser-session-cookie", "bearer-access-token", "dpop-access-token"],+ sessionMethods: ["browser-session-cookie", "bearer-access-token"],sessionCookieName: resolveSessionCookieName({mode: config.mode,port: config.port,diff --git a/apps/server/src/auth/PairingGrantStore.test.ts b/apps/server/src/auth/PairingGrantStore.test.tsindex 5242dd738..3d64e396d 100644--- a/apps/server/src/auth/PairingGrantStore.test.ts+++ b/apps/server/src/auth/PairingGrantStore.test.ts@@ -79,7 +79,6 @@ it.layer(NodeServices.layer)("PairingGrantStore.layer", (it) => {"orchestration:operate","terminal:operate","review:write",- "relay:read",]);expect(first.subject).toBe("one-time-token");expect(first.label).toBe("Julius iPhone");@@ -114,29 +113,6 @@ it.layer(NodeServices.layer)("PairingGrantStore.layer", (it) => {}).pipe(Effect.provide(makePairingGrantStoreLayer())),);- it.effect("requires the bound proof key thumbprint when present", () =>- Effect.gen(function* () {- const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;- const token = yield* bootstrapCredentials.issueOneTimeToken({- proofKeyThumbprint: "client-proof-key-thumbprint",- });-- const missing = yield* Effect.flip(bootstrapCredentials.consume(token.credential));- const wrong = yield* Effect.flip(- bootstrapCredentials.consume(token.credential, {- proofKeyThumbprint: "other-proof-key-thumbprint",- }),- );- const consumed = yield* bootstrapCredentials.consume(token.credential, {- proofKeyThumbprint: "client-proof-key-thumbprint",- });-- expect(missing.message).toContain("proof key mismatch");- expect(wrong.message).toContain("proof key mismatch");- expect(consumed.proofKeyThumbprint).toBe("client-proof-key-thumbprint");- }).pipe(Effect.provide(makePairingGrantStoreLayer())),- );-it.effect("seeds the desktop bootstrap credential as a reusable grant", () =>Effect.gen(function* () {const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;@@ -150,10 +126,8 @@ it.layer(NodeServices.layer)("PairingGrantStore.layer", (it) => {"orchestration:operate","terminal:operate","review:write",- "relay:read","access:read","access:write",- "relay:write",]);expect(first.subject).toBe("desktop-bootstrap");expect(second.method).toBe("desktop-bootstrap");diff --git a/apps/server/src/auth/PairingGrantStore.ts b/apps/server/src/auth/PairingGrantStore.tsindex 53bd9f93b..afbaaf7ff 100644--- a/apps/server/src/auth/PairingGrantStore.ts+++ b/apps/server/src/auth/PairingGrantStore.ts@@ -25,7 +25,6 @@ export interface BootstrapGrant {readonly scopes: ReadonlyArray<AuthEnvironmentScope>;readonly subject: string;readonly label?: string;- readonly proofKeyThumbprint?: string;readonly expiresAt: DateTime.DateTime;}@@ -47,15 +46,6 @@ export class ExpiredBootstrapCredentialError extends Schema.TaggedErrorClass<Exp}}-export class BootstrapCredentialProofKeyMismatchError extends Schema.TaggedErrorClass<BootstrapCredentialProofKeyMismatchError>()(- "BootstrapCredentialProofKeyMismatchError",- {},-) {- override get message(): string {- return "Bootstrap credential proof key mismatch.";- }-}-export class UnavailableBootstrapCredentialError extends Schema.TaggedErrorClass<UnavailableBootstrapCredentialError>()("UnavailableBootstrapCredentialError",{},@@ -68,7 +58,6 @@ export class UnavailableBootstrapCredentialError extends Schema.TaggedErrorClassexport const BootstrapCredentialInvalidError = Schema.Union([UnknownBootstrapCredentialError,ExpiredBootstrapCredentialError,- BootstrapCredentialProofKeyMismatchError,UnavailableBootstrapCredentialError,]);export type BootstrapCredentialInvalidError = typeof BootstrapCredentialInvalidError.Type;@@ -179,7 +168,6 @@ export interface IssuedBootstrapCredential {readonly id: string;readonly credential: string;readonly label?: string;- readonly proofKeyThumbprint?: string;readonly expiresAt: DateTime.Utc;}@@ -201,7 +189,6 @@ export class PairingGrantStore extends Context.Service<readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;readonly subject?: string;readonly label?: string;- readonly proofKeyThumbprint?: string;/*** "startup" marks the credential the server mints for itself at boot,* which gets the long dev TTL when a dev URL is configured.@@ -216,9 +203,6 @@ export class PairingGrantStore extends Context.Service<readonly revoke: (id: string) => Effect.Effect<boolean, BootstrapCredentialInternalError>;readonly consume: (credential: string,- input?: {- readonly proofKeyThumbprint?: string;- },) => Effect.Effect<BootstrapGrant, BootstrapCredentialError>;}>()("akeru-bot/auth/PairingGrantStore") {}@@ -395,7 +379,6 @@ export const make = Effect.gen(function* () {id,credential,...(input?.label ? { label: input.label } : {}),- ...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}),expiresAt,};const subject = input?.subject ?? "one-time-token";@@ -407,7 +390,6 @@ export const make = Effect.gen(function* () {scopes: input?.scopes ?? AuthStandardClientScopes,subject,label: input?.label ?? null,- proofKeyThumbprint: input?.proofKeyThumbprint ?? null,createdAt: now,expiresAt: expiresAt,})@@ -435,7 +417,7 @@ export const make = Effect.gen(function* () {});const consume: PairingGrantStore["Service"]["consume"] = Effect.fn("PairingGrantStore.consume")(- function* (credential, input) {+ function* (credential) {const now = yield* DateTime.now;const seededResult: ConsumeResult = yield* Ref.modify(seededGrantsRef,@@ -465,17 +447,6 @@ export const make = Effect.gen(function* () {];}- if (grant.proofKeyThumbprint && grant.proofKeyThumbprint !== input?.proofKeyThumbprint) {- return [- {- _tag: "error",- reason: "not-found",- error: new BootstrapCredentialProofKeyMismatchError({}),- },- next,- ];- }-const remainingUses = grant.remainingUses;if (typeof remainingUses === "number") {if (remainingUses <= 1) {@@ -496,9 +467,6 @@ export const make = Effect.gen(function* () {scopes: grant.scopes,subject: grant.subject,...(grant.label ? { label: grant.label } : {}),- ...(grant.proofKeyThumbprint- ? { proofKeyThumbprint: grant.proofKeyThumbprint }- : {}),expiresAt: grant.expiresAt,} satisfies BootstrapGrant,},@@ -517,7 +485,6 @@ export const make = Effect.gen(function* () {const consumed = yield* pairingLinks.consumeAvailable({credential,- proofKeyThumbprint: input?.proofKeyThumbprint ?? null,consumedAt: now,now,})@@ -530,9 +497,6 @@ export const make = Effect.gen(function* () {scopes: consumed.value.scopes,subject: consumed.value.subject,...(consumed.value.label ? { label: consumed.value.label } : {}),- ...(consumed.value.proofKeyThumbprint- ? { proofKeyThumbprint: consumed.value.proofKeyThumbprint }- : {}),expiresAt: consumed.value.expiresAt,} satisfies BootstrapGrant;}@@ -556,13 +520,6 @@ export const make = Effect.gen(function* () {return yield* new ExpiredBootstrapCredentialError({});}- if (- matching.value.proofKeyThumbprint !== null &&- matching.value.proofKeyThumbprint !== input?.proofKeyThumbprint- ) {- return yield* new BootstrapCredentialProofKeyMismatchError({});- }-return yield* new UnavailableBootstrapCredentialError({});},);diff --git a/apps/server/src/auth/RpcAuthorization.test.ts b/apps/server/src/auth/RpcAuthorization.test.tsindex 994b2ba68..ef124410e 100644--- a/apps/server/src/auth/RpcAuthorization.test.ts+++ b/apps/server/src/auth/RpcAuthorization.test.ts@@ -1,8 +1,6 @@import {AuthOrchestrationOperateScope,AuthOrchestrationReadScope,- AuthRelayReadScope,- AuthRelayWriteScope,WS_METHODS,WsRpcGroup,} from "@t3tools/contracts";@@ -46,13 +44,6 @@ describe("RPC authorization scopes", () => {expect(requiredScopeForRpcMethod(WS_METHODS.botUsage)).toBe(AuthOrchestrationReadScope);});- it("allows relay status reads without granting relay installation access", () => {- expect(requiredScopeForRpcMethod(WS_METHODS.cloudGetRelayClientStatus)).toBe(- AuthRelayReadScope,- );- expect(requiredScopeForRpcMethod(WS_METHODS.cloudInstallRelayClient)).toBe(AuthRelayWriteScope);- });-it("requires permission to operate on a thread before uploading feedback", () => {expect(requiredScopeForRpcMethod(WS_METHODS.providerUploadFeedback)).toBe(AuthOrchestrationOperateScope,diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.tsindex df669858e..8c2d2f82f 100644--- a/apps/server/src/auth/RpcAuthorization.ts+++ b/apps/server/src/auth/RpcAuthorization.ts@@ -2,8 +2,6 @@ import {AuthAccessReadScope,AuthOrchestrationOperateScope,AuthOrchestrationReadScope,- AuthRelayReadScope,- AuthRelayWriteScope,AuthReviewWriteScope,AuthTerminalOperateScope,ORCHESTRATION_WS_METHODS,@@ -71,8 +69,6 @@ export const RPC_REQUIRED_SCOPES = {[WS_METHODS.portabilityExport]: AuthOrchestrationReadScope,[WS_METHODS.portabilityPreviewImport]: AuthOrchestrationReadScope,[WS_METHODS.portabilityApplyImport]: AuthOrchestrationOperateScope,- [WS_METHODS.cloudGetRelayClientStatus]: AuthRelayReadScope,- [WS_METHODS.cloudInstallRelayClient]: AuthRelayWriteScope,[WS_METHODS.sourceControlLookupRepository]: AuthOrchestrationReadScope,[WS_METHODS.sourceControlCloneRepository]: AuthOrchestrationOperateScope,[WS_METHODS.sourceControlPublishRepository]: AuthOrchestrationOperateScope,diff --git a/apps/server/src/auth/SessionStore.test.ts b/apps/server/src/auth/SessionStore.test.tsindex 1fb01c1f0..08057600a 100644--- a/apps/server/src/auth/SessionStore.test.ts+++ b/apps/server/src/auth/SessionStore.test.ts@@ -147,7 +147,6 @@ it.layer(NodeServices.layer)("SessionStore.layer", (it) => {"orchestration:operate","terminal:operate","review:write",- "relay:read",]);}).pipe(Effect.provide(Layer.merge(makeSessionStoreLayer(), TestClock.layer()))),);diff --git a/apps/server/src/auth/SessionStore.ts b/apps/server/src/auth/SessionStore.tsindex 8be2dcabd..f2049397a 100644--- a/apps/server/src/auth/SessionStore.ts+++ b/apps/server/src/auth/SessionStore.ts@@ -38,7 +38,6 @@ export interface IssuedSession {readonly client: AuthClientMetadata;readonly expiresAt: DateTime.DateTime;readonly scopes: ReadonlyArray<AuthEnvironmentScope>;- readonly proofKeyThumbprint?: string;}export interface VerifiedSession {@@ -49,7 +48,6 @@ export interface VerifiedSession {readonly expiresAt?: DateTime.DateTime;readonly subject: string;readonly scopes: ReadonlyArray<AuthEnvironmentScope>;- readonly proofKeyThumbprint?: string;}export type SessionCredentialChange =@@ -366,7 +364,6 @@ export class SessionStore extends Context.Service<readonly method?: ServerAuthSessionMethod;readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;readonly client?: AuthClientMetadata;- readonly proofKeyThumbprint?: string;}) => Effect.Effect<IssuedSession, SessionCredentialInternalError>;readonly verify: (token: string) => Effect.Effect<VerifiedSession, SessionCredentialError>;readonly issueWebSocketToken: (@@ -417,8 +414,7 @@ const SessionClaims = Schema.Struct({sid: AuthSessionId,sub: Schema.String,scopes: AuthEnvironmentScopes,- method: Schema.Literals(["browser-session-cookie", "bearer-access-token", "dpop-access-token"]),- jkt: Schema.optionalKey(Schema.String),+ method: Schema.Literals(["browser-session-cookie", "bearer-access-token"]),iat: Schema.Number,exp: Schema.Number,});@@ -619,7 +615,6 @@ export const make = Effect.gen(function* () {sub: input?.subject ?? "browser",scopes: input?.scopes ?? AuthStandardClientScopes,method: input?.method ?? "browser-session-cookie",- ...(input?.proofKeyThumbprint ? { jkt: input.proofKeyThumbprint } : {}),iat: issuedAt.epochMilliseconds,exp: expiresAt.epochMilliseconds,};@@ -679,7 +674,6 @@ export const make = Effect.gen(function* () {client,expiresAt: expiresAt,scopes: claims.scopes,- ...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),} satisfies IssuedSession;},);@@ -741,7 +735,6 @@ export const make = Effect.gen(function* () {expiresAt: expiresAt.value,subject: claims.sub,scopes: claims.scopes,- ...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),} satisfies VerifiedSession;},);diff --git a/apps/server/src/auth/dpop.test.ts b/apps/server/src/auth/dpop.test.tsdeleted file mode 100644index fa75c407b..000000000--- a/apps/server/src/auth/dpop.test.ts+++ /dev/null@@ -1,37 +0,0 @@-import { describe, expect, it } from "vite-plus/test";-import * as PlatformError from "effect/PlatformError";--import { SecretStorePersistError } from "./ServerSecretStore.ts";-import { mapDpopReplayStoreError } from "./dpop.ts";--const storeFailure = (tag: "AlreadyExists" | "PermissionDenied") =>- new SecretStorePersistError({- resource: "DPoP proof",- cause: PlatformError.systemError({- _tag: tag,- module: "FileSystem",- method: "open",- pathOrDescriptor: "dpop-proof.bin",- }),- });--describe("mapDpopReplayStoreError", () => {- it("reports replay conflicts as invalid credentials", () => {- const cause = storeFailure("AlreadyExists");- const error = mapDpopReplayStoreError(cause);-- expect(error._tag).toBe("ServerAuthInvalidCredentialError");- if (error._tag === "ServerAuthInvalidCredentialError") {- expect(error.cause).toBe(cause);- }- });-- it("reports replay-store availability failures as internal errors", () => {- const error = mapDpopReplayStoreError(storeFailure("PermissionDenied"));-- expect(error._tag).toBe("ServerAuthDpopReplayStateRecordError");- if (error._tag === "ServerAuthDpopReplayStateRecordError") {- expect(error.message).toBe("Failed to record DPoP proof replay state.");- }- });-});diff --git a/apps/server/src/auth/dpop.ts b/apps/server/src/auth/dpop.tsdeleted file mode 100644index f19984eb3..000000000--- a/apps/server/src/auth/dpop.ts+++ /dev/null@@ -1,87 +0,0 @@-import { verifyDpopProof } from "@t3tools/shared/dpop";-import * as Crypto from "effect/Crypto";-import * as DateTime from "effect/DateTime";-import * as Effect from "effect/Effect";-import * as Encoding from "effect/Encoding";-import * as Option from "effect/Option";-import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";--import {- ServerAuthDpopReplayKeyCalculationError,- ServerAuthDpopReplayStateRecordError,- ServerAuthInvalidCredentialError,- type ServerAuthInternalError,-} from "./EnvironmentAuth.ts";-import * as ServerSecretStore from "./ServerSecretStore.ts";--export const mapDpopReplayStoreError = (- error: ServerSecretStore.SecretStoreError,-): ServerAuthInvalidCredentialError | ServerAuthInternalError =>- ServerSecretStore.isSecretAlreadyExistsError(error)- ? new ServerAuthInvalidCredentialError({- diagnostic: "DPoP proof replayed.",- cause: error,- })- : new ServerAuthDpopReplayStateRecordError({- cause: error,- });--export const verifyRequestDpopProof = (input: {- readonly request: HttpServerRequest.HttpServerRequest;- readonly expectedThumbprint?: string;- readonly expectedAccessToken?: string;-}) =>- Effect.gen(function* () {- const proof = input.request.headers.dpop;- const url = HttpServerRequest.toURL(input.request);- if (Option.isNone(url)) {- return yield* new ServerAuthInvalidCredentialError({- diagnostic: "Invalid DPoP request URL.",- });- }- const now = yield* DateTime.now;- const result = verifyDpopProof({- proof,- method: input.request.method,- url: url.value.href,- nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),- ...(input.expectedThumbprint ? { expectedThumbprint: input.expectedThumbprint } : {}),- ...(input.expectedAccessToken ? { expectedAccessToken: input.expectedAccessToken } : {}),- });- if (!result.ok) {- return yield* new ServerAuthInvalidCredentialError({- diagnostic: result.reason,- });- }- const secretStore = yield* ServerSecretStore.ServerSecretStore;- const replayKey = yield* Crypto.Crypto.pipe(- Effect.flatMap((crypto) =>- crypto.digest("SHA-256", new TextEncoder().encode(`${result.thumbprint}:${result.jti}`)),- ),- Effect.map(Encoding.encodeBase64Url),- Effect.mapError(- (cause) =>- new ServerAuthDpopReplayKeyCalculationError({- cause,- }),- ),- );- yield* secretStore- .create(- `dpop-proof-${replayKey}`,- new TextEncoder().encode(- [- `thumbprint=${result.thumbprint}`,- `jti=${result.jti}`,- `iat=${result.iat}`,- `consumedAt=${DateTime.formatIso(now)}`,- ].join("\n"),- ),- )- .pipe(- Effect.catchIf(ServerSecretStore.isSecretStoreError, (error) =>- Effect.fail(mapDpopReplayStoreError(error)),- ),- );- return result.thumbprint;- });diff --git a/apps/server/src/auth/http.ts b/apps/server/src/auth/http.tsindex 780aaabde..0065dbef2 100644--- a/apps/server/src/auth/http.ts+++ b/apps/server/src/auth/http.ts@@ -4,8 +4,6 @@ import {AuthStandardClientScopes,AuthOrchestrationOperateScope,AuthOrchestrationReadScope,- AuthRelayReadScope,- AuthRelayWriteScope,AuthReviewWriteScope,AuthTerminalOperateScope,EnvironmentAuthInvalidError,@@ -27,7 +25,6 @@ import { parseAllowedOAuthScope } from "@t3tools/shared/oauthScope";import { causeErrorTag } from "@t3tools/shared/observability";import * as DateTime from "effect/DateTime";import * as Effect from "effect/Effect";-import { identity } from "effect/Function";import * as Layer from "effect/Layer";import * as Cookies from "effect/unstable/http/Cookies";import * as HttpEffect from "effect/unstable/http/HttpEffect";@@ -36,9 +33,7 @@ import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";import * as EnvironmentAuth from "./EnvironmentAuth.ts";import * as SessionStore from "./SessionStore.ts";-import { traceAuthenticatedRelayRequest, traceRelayRequest } from "../cloud/traceRelayRequest.ts";import { deriveAuthClientMetadata } from "./utils.ts";-import { verifyRequestDpopProof } from "./dpop.ts";const CREDENTIAL_RESPONSE_HEADERS = {"cache-control": "no-store",@@ -49,22 +44,6 @@ const appendCredentialResponseHeaders = HttpEffect.appendPreResponseHandler((_reEffect.succeed(HttpServerResponse.setHeaders(response, CREDENTIAL_RESPONSE_HEADERS)),);-const appendDpopChallengeHeader = HttpEffect.appendPreResponseHandler((_request, response) =>- Effect.succeed(HttpServerResponse.setHeader(response, "www-authenticate", "DPoP")),-);--const appendDpopChallengeOnUnauthorized = (error: EnvironmentAuthInvalidError) =>- Effect.gen(function* () {- const request = yield* HttpServerRequest.HttpServerRequest;- const usesDpop =- (request.originalUrl.startsWith("/oauth/token") && request.headers.dpop !== undefined) ||- request.headers.authorization?.startsWith("DPoP ") === true;- if (usesDpop) {- yield* appendDpopChallengeHeader;- }- return yield* error;- });-export const currentEnvironmentTraceId = Effect.currentParentSpan.pipe(Effect.map((span) => span.traceId),Effect.orElseSucceed(() => "unavailable"),@@ -191,9 +170,8 @@ export const environmentAuthenticatedAuthLayer = Layer.effect(...session,scopes: new Set(session.scopes),}),- session.subject === "cloud-connect" ? traceAuthenticatedRelayRequest : identity,);- }).pipe(Effect.catchTag("EnvironmentAuthInvalidError", appendDpopChallengeOnUnauthorized));+ });}),);@@ -269,25 +247,11 @@ export const authHttpApiLayer = HttpApiBuilder.group(AuthReviewWriteScope,AuthAccessReadScope,AuthAccessWriteScope,- AuthRelayReadScope,- AuthRelayWriteScope,]),});if (requestedScopes === null) {return yield* failEnvironmentInvalidRequest("invalid_scope");}- const proofKeyThumbprint = args.headers.dpop- ? yield* verifyRequestDpopProof({ request }).pipe(- Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, () =>- appendDpopChallengeHeader.pipe(- Effect.andThen(failEnvironmentAuthInvalid("invalid_credential")),- ),- ),- Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>- failEnvironmentInternal("access_token_issuance_failed", error),- ),- )- : undefined;yield* appendCredentialResponseHeaders;return yield* serverAuth.exchangeBootstrapCredentialForAccessToken(args.payload.subject_token,@@ -302,10 +266,8 @@ export const authHttpApiLayer = HttpApiBuilder.group(...(args.payload.client_os ? { os: args.payload.client_os } : {}),},}),- proofKeyThumbprint ? { proofKeyThumbprint } : undefined,);},- traceRelayRequest,Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>failEnvironmentAuthInvalid(EnvironmentAuth.serverAuthCredentialReason(error)),),diff --git a/apps/server/src/bin.test.ts b/apps/server/src/bin.test.tsindex 937073c23..994c37f56 100644--- a/apps/server/src/bin.test.ts+++ b/apps/server/src/bin.test.ts@@ -45,11 +45,8 @@ import { environmentAuthenticatedAuthLayer } from "./auth/http.ts";const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);class ProjectCliHttpApi extends HttpApi.make("environment").add(EnvironmentOrchestrationHttpApi) {}-const connectCli = makeCli({ cloudEnabled: true });-const noConnectCli = makeCli({ cloudEnabled: false });const runCli = (args: ReadonlyArray<string>, command = cli) =>Command.runWith(command, { version: "0.0.0" })(args);-const runConnectCli = (args: ReadonlyArray<string>) => runCli(args, connectCli);const runCliWithRuntime = (args: ReadonlyArray<string>) =>runCli(args).pipe(Effect.provide(CliRuntimeLayer));@@ -184,30 +181,11 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {}),);- it.effect("rejects connect commands when public configuration is missing", () =>+ it.effect("exposes service lifecycle commands", () =>Effect.gen(function* () {- const error = yield* runCli(["connect", "status"], noConnectCli).pipe(Effect.flip);+ const { output } = yield* captureStdout(runCli(["service", "--help"]));- if (!CliError.isCliError(error)) {- assert.fail(`Expected CliError, got ${String(error)}`);- }- if (error._tag !== "ShowHelp") {- assert.fail(`Expected ShowHelp, got ${error._tag}`);- }- assert.deepEqual(error.commandPath, ["akeru", "connect"]);- assert.include(error.errors[0]?.message ?? "", "missing T3 Connect public configuration");-- const output = (yield* TestConsole.errorLines).join("\n");- assert.include(output, "ERROR");- assert.include(output, "missing T3 Connect public configuration");- }).pipe(Effect.provide(Layer.mergeAll(CliRuntimeLayer, TestConsole.layer))),- );-- it.effect("exposes service lifecycle commands without T3 Connect configuration", () =>- Effect.gen(function* () {- const { output } = yield* captureStdout(runCli(["service", "--help"], noConnectCli));-- assert.include(output, "Manage the T3 Code background service.");+ assert.include(output, "Manage the Akeru Bot background service.");assert.include(output, "install");assert.include(output, "uninstall");assert.include(output, "update");@@ -215,117 +193,6 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {}),);- it.effect("reports fresh headless connect state without requiring local configuration", () =>- Effect.gen(function* () {- const baseDir = NodeFS.mkdtempSync(- NodePath.join(NodeOS.tmpdir(), "t3-cli-cloud-status-test-"),- );- const { output } = yield* captureStdout(- runConnectCli(["connect", "status", "--base-dir", baseDir, "--json"]),- );- // @effect-diagnostics-next-line preferSchemaOverJson:off - CLI JSON output is decoded as a presentation DTO.- const status = JSON.parse(output) as {- readonly desired: boolean;- readonly authenticated: boolean;- readonly linked: boolean;- readonly cloudUserId: string | null;- readonly relayUrl: string | null;- };-- assert.equal(status.desired, false);- assert.equal(status.authenticated, false);- assert.equal(status.linked, false);- assert.equal(status.cloudUserId, null);- assert.equal(status.relayUrl, null);- }),- );-- it.effect("reports actionable human-readable headless connect state", () =>- Effect.gen(function* () {- const baseDir = NodeFS.mkdtempSync(- NodePath.join(NodeOS.tmpdir(), "t3-cli-cloud-status-human-test-"),- );- const { output } = yield* captureStdout(- runConnectCli(["connect", "status", "--base-dir", baseDir]),- );-- assert.include(output, "T3 Connect\n Exposure: disabled");- assert.include(output, " Authorization: missing");- assert.include(output, " Environment link: not provisioned");- assert.include(output, "Next: Run `akeru connect link` to authorize and enable T3 Connect.");- }),- );-- it.effect("accepts the --headless login override without enabling access", () =>- Effect.gen(function* () {- const baseDir = NodeFS.mkdtempSync(- NodePath.join(NodeOS.tmpdir(), "t3-cli-cloud-login-test-"),- );- const { secretsDir } = yield* ServerConfig.deriveServerPaths(baseDir, undefined);- NodeFS.mkdirSync(secretsDir, { recursive: true });- NodeFS.writeFileSync(- NodePath.join(secretsDir, "cloud-cli-oauth-token.bin"),- // @effect-diagnostics-next-line preferSchemaOverJson:off - Test fixture matches the persisted CLI token representation.- JSON.stringify({- accessToken: "access-token",- refreshToken: "refresh-token",- expiresAtEpochMs: Number.MAX_SAFE_INTEGER,- }),- );-- const login = yield* captureStdout(- runConnectCli(["connect", "login", "--base-dir", baseDir, "--headless"]),- );- const status = yield* captureStdout(- runConnectCli(["connect", "status", "--base-dir", baseDir, "--json"]),- );- // @effect-diagnostics-next-line preferSchemaOverJson:off - CLI JSON output is decoded as a presentation DTO.- const decoded = JSON.parse(status.output) as {- readonly desired: boolean;- readonly authenticated: boolean;- };-- assert.equal(login.output, "✓ Signed in");- assert.isFalse(decoded.desired);- assert.isTrue(decoded.authenticated);- }),- );-- it.effect("disables headless connect without a running server", () =>- Effect.gen(function* () {- const baseDir = NodeFS.mkdtempSync(- NodePath.join(NodeOS.tmpdir(), "t3-cli-cloud-unlink-test-"),- );- const { output } = yield* captureStdout(- runConnectCli(["connect", "unlink", "--base-dir", baseDir]),- );-- assert.equal(output, "T3 Connect is disabled locally.");- }),- );-- it.effect("logs out of headless connect and removes the stored CLI authorization", () =>- Effect.gen(function* () {- const baseDir = NodeFS.mkdtempSync(- NodePath.join(NodeOS.tmpdir(), "t3-cli-cloud-logout-test-"),- );- const { secretsDir } = yield* ServerConfig.deriveServerPaths(baseDir, undefined);- const tokenPath = NodePath.join(secretsDir, "cloud-cli-oauth-token.bin");- NodeFS.mkdirSync(secretsDir, { recursive: true });- NodeFS.writeFileSync(tokenPath, "invalid persisted token");-- const { output } = yield* captureStdout(- runConnectCli(["connect", "logout", "--base-dir", baseDir]),- );-- assert.equal(- output,- "Signed out of T3 Connect locally.\nThe background service is managed separately with `akeru service`.",- );- assert.isFalse(NodeFS.existsSync(tokenPath));- }),- );-it.effect("executes auth pairing subcommands and redacts secrets from list output", () =>Effect.gen(function* () {const baseDir = NodeFS.mkdtempSync(@@ -390,10 +257,8 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {"orchestration:operate","terminal:operate","review:write",- "relay:read","access:read","access:write",- "relay:write",]);assert.equal(listed.length, 1);assert.equal(listed[0]?.sessionId, issued.sessionId);@@ -402,10 +267,8 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {"orchestration:operate","terminal:operate","review:write",- "relay:read","access:read","access:write",- "relay:write",]);assert.equal("token" in (listed[0] ?? {}), false);}),diff --git a/apps/server/src/bin.ts b/apps/server/src/bin.tsindex 6d054d621..e0cc210f9 100644--- a/apps/server/src/bin.ts+++ b/apps/server/src/bin.ts@@ -2,15 +2,12 @@ import * as NodeRuntime from "@effect/platform-node/NodeRuntime";import * as NodeServices from "@effect/platform-node/NodeServices";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";-import { Argument, Command } from "effect/unstable/cli";-import * as CliError from "effect/unstable/cli/CliError";+import { Command } from "effect/unstable/cli";import * as NetService from "@t3tools/shared/Net";import packageJson from "../package.json" with { type: "json" };import { authCommand } from "./cli/auth.ts";-import { connectCommand } from "./cli/connect.ts";import { pairCommand } from "./cli/pair.ts";-import { hasCloudPublicConfig } from "./cloud/publicConfig.ts";import { sharedServerCommandFlags } from "./cli/config.ts";import { isEntrypoint } from "./entrypoint.ts";import { projectCommand } from "./cli/project.ts";@@ -21,31 +18,7 @@ import { triageCommand } from "./cli/triage.ts";const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);-const connectPublicConfigMissingMessage =- "T3 Connect commands are unavailable: this build is missing T3 Connect public configuration.";--class ConnectPublicConfigMissingError extends CliError.UserError {- override get message() {- return connectPublicConfigMissingMessage;- }-}--const connectUnavailableCommand = Command.make("connect", {- command: Argument.string("command").pipe(Argument.variadic),-}).pipe(- Command.withDescription("T3 Connect is unavailable in builds without public configuration."),- Command.withHidden,- Command.withHandler(() =>- Effect.fail(- new CliError.ShowHelp({- commandPath: ["akeru", "connect"],- errors: [new ConnectPublicConfigMissingError({ cause: connectPublicConfigMissingMessage })],- }),- ),- ),-);--export const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) =>+export const makeCli = () =>Command.make("akeru", { ...sharedServerCommandFlags }).pipe(Command.withDescription("Run the Akeru Bot server."),Command.withHandler((flags) => runServerCommand(flags)),@@ -58,7 +31,6 @@ export const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) =>serviceCommand,servicePreflightCommand,triageCommand,- cloudEnabled ? connectCommand : connectUnavailableCommand,]),);diff --git a/apps/server/src/cli/connect.test.ts b/apps/server/src/cli/connect.test.tsdeleted file mode 100644index 1e0c88c24..000000000--- a/apps/server/src/cli/connect.test.ts+++ /dev/null@@ -1,218 +0,0 @@-import * as RelayClient from "@t3tools/shared/relayClient";-import { assert, it } from "@effect/vitest";-import * as Cause from "effect/Cause";-import * as ConfigProvider from "effect/ConfigProvider";-import * as Console from "effect/Console";-import * as Effect from "effect/Effect";-import * as Exit from "effect/Exit";-import * as Logger from "effect/Logger";-import * as Option from "effect/Option";-import * as References from "effect/References";-import * as Terminal from "effect/Terminal";--import * as BootService from "../cloud/bootService.ts";-import {- acquireRelayClientForLink,- formatHeadlessAuthorizationPrompt,- formatRelayClientReady,- headlessSessionConfig,- isPublishAgentActivityEnabledValue,- reportCloudDisconnectResults,-} from "./connect.ts";-import { recoverServiceOnboardingOffer } from "./service.ts";--it("explains how to complete headless authorization", () => {- assert.equal(- formatHeadlessAuthorizationPrompt("https://example.test/connect"),- [- "Headless authorization",- "Open this URL on a device with a browser:",- " https://example.test/connect",- "",- "After signing in, return here and enter the code shown in your browser.",- ].join("\n"),- );-});--it("formats relay readiness without printing its installation path", () => {- assert.equal(formatRelayClientReady("2026.5.2"), "✓ Relay client ready · cloudflared 2026.5.2");-});--const readHeadlessSessionConfig = (env: Record<string, string>) =>- headlessSessionConfig.pipe(Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env }))));--const managedExecutable = {- status: "available",- executablePath: "/tmp/cloudflared",- source: "managed",- version: RelayClient.CLOUDFLARED_VERSION,-} as const;--it.effect("detects headless operation from individual SSH config values", () =>- Effect.gen(function* () {- assert.isFalse(yield* readHeadlessSessionConfig({}));- assert.isFalse(yield* readHeadlessSessionConfig({ CI: "true" }));- assert.isTrue(yield* readHeadlessSessionConfig({ SSH_CONNECTION: "client server" }));- assert.isTrue(yield* readHeadlessSessionConfig({ SSH_TTY: "/dev/pts/1" }));- }),-);--it.effect("treats cancelling optional background setup as a successful skip", () =>- Effect.gen(function* () {- const result = yield* recoverServiceOnboardingOffer(Effect.fail(new Terminal.QuitError({})));- assert.isFalse(result);- }),-);--it.effect("keeps a successful connection when a remote service update is pending", () =>- Effect.gen(function* () {- const result = yield* recoverServiceOnboardingOffer(- Effect.fail(new BootService.BootServiceUpdatePendingError()),- );- assert.isFalse(result);- }),-);--it.effect("does not install the relay client when the user declines the managed download", () =>- Effect.gen(function* () {- let installCalls = 0;- const result = yield* acquireRelayClientForLink(- {- resolve: Effect.succeed({- status: "missing",- version: RelayClient.CLOUDFLARED_VERSION,- }),- install: Effect.sync(() => {- installCalls += 1;- return managedExecutable;- }),- installWithProgress: () =>- Effect.sync(() => {- installCalls += 1;- return managedExecutable;- }),- },- () => Effect.succeed(false),- () => Effect.void,- );-- assert.isTrue(Option.isNone(result));- assert.equal(installCalls, 0);- }),-);--it.effect("installs the relay client after the user accepts the managed download", () =>- Effect.gen(function* () {- let installCalls = 0;- const progress: Array<string> = [];- const result = yield* acquireRelayClientForLink(- {- resolve: Effect.succeed({- status: "missing",- version: RelayClient.CLOUDFLARED_VERSION,- }),- install: Effect.sync(() => {- installCalls += 1;- return managedExecutable;- }),- installWithProgress: (report) =>- report({ type: "progress", stage: "downloading" }).pipe(- Effect.andThen(- Effect.sync(() => {- installCalls += 1;- return managedExecutable;- }),- ),- ),- },- () => Effect.succeed(true),- (event) =>- Effect.sync(() => {- if (event.type === "progress") {- progress.push(event.stage);- }- }),- );-- assert.deepEqual(Option.getOrThrow(result), managedExecutable);- assert.equal(installCalls, 1);- assert.deepEqual(progress, ["downloading"]);- }),-);--it.effect("reuses an available relay client executable without prompting", () =>- Effect.gen(function* () {- let promptCalls = 0;- const result = yield* acquireRelayClientForLink(- {- resolve: Effect.succeed(managedExecutable),- install: Effect.die("unexpected install"),- installWithProgress: () => Effect.die("unexpected install"),- },- () =>- Effect.sync(() => {- promptCalls += 1;- return false;- }),- () => Effect.void,- );-- assert.deepEqual(Option.getOrThrow(result), managedExecutable);- assert.equal(promptCalls, 0);- }),-);--it.effect("keeps disconnect causes in structured logs and out of console warnings", () => {- const warnings: ReadonlyArray<unknown>[] = [];- const logs: Readonly<Record<string, unknown>>[] = [];- const testConsole = {- ...globalThis.console,- warn: (...args: ReadonlyArray<unknown>) => {- warnings.push(args);- },- } satisfies Console.Console;- const logger = Logger.make(({ fiber }) => {- logs.push(fiber.getRef(References.CurrentLogAnnotations));- });- const liveFailure = "live unlink private diagnostic";- const relayFailure = "relay revoke private diagnostic";-- return reportCloudDisconnectResults({- clearAuthorization: true,- liveResult: {- status: "failed",- cause: Cause.fail(new Error(liveFailure)),- },- relayResult: Exit.failCause(Cause.die(new Error(relayFailure))),- }).pipe(- Effect.provideService(Console.Console, testConsole),- Effect.provide(Logger.layer([logger], { mergeWithExisting: false })),- Effect.tap(() =>- Effect.sync(() => {- assert.lengthOf(warnings, 2);- const warningText = warnings.flat().map(String).join("\n");- assert.include(warningText, "running server could not stop its tunnel");- assert.include(warningText, "Could not revoke the relay-side environment record");- assert.notInclude(warningText, liveFailure);- assert.notInclude(warningText, relayFailure);- assert.deepEqual(- logs.map(({ operation, clearAuthorization }) => ({ operation, clearAuthorization })),- [- { operation: "live-server-unlink", clearAuthorization: true },- { operation: "relay-environment-unlink", clearAuthorization: true },- ],- );- const loggedCauses = logs.map((log) => String(log.cause)).join("\n");- assert.include(loggedCauses, liveFailure);- assert.include(loggedCauses, relayFailure);- }),- ),- );-});--it("treats only the literal 'true' as publish-enabled", () => {- assert.equal(isPublishAgentActivityEnabledValue("true"), true);- assert.equal(isPublishAgentActivityEnabledValue("false"), false);- assert.equal(isPublishAgentActivityEnabledValue(null), false);- assert.equal(isPublishAgentActivityEnabledValue("TRUE"), false);-});diff --git a/apps/server/src/cli/connect.ts b/apps/server/src/cli/connect.tsdeleted file mode 100644index 5b7c4aaff..000000000--- a/apps/server/src/cli/connect.ts+++ /dev/null@@ -1,722 +0,0 @@-import {- AuthRelayWriteScope,- EnvironmentHttpApi,- type RelayClientInstallProgressEvent,- type RelayClientInstallProgressStage,-} from "@t3tools/contracts";-import { RelayOkResponse } from "@t3tools/contracts/relay";-import { HostProcessPlatform } from "@t3tools/shared/hostProcess";-import * as RelayClient from "@t3tools/shared/relayClient";-import { withRelayClientTracing } from "@t3tools/shared/relayTracing";-import * as Cause from "effect/Cause";-import * as Config from "effect/Config";-import * as Console from "effect/Console";-import * as Crypto from "effect/Crypto";-import * as Duration from "effect/Duration";-import * as Effect from "effect/Effect";-import * as Exit from "effect/Exit";-import * as FileSystem from "effect/FileSystem";-import * as Layer from "effect/Layer";-import * as Option from "effect/Option";-import * as References from "effect/References";-import * as Schema from "effect/Schema";-import * as Terminal from "effect/Terminal";-import { Command, Flag, GlobalFlag, Prompt } from "effect/unstable/cli";-import {- FetchHttpClient,- HttpClient,- HttpClientRequest,- HttpClientResponse,-} from "effect/unstable/http";-import * as HttpApiClient from "effect/unstable/httpapi/HttpApiClient";--import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";-import * as ServerSecretStore from "../auth/ServerSecretStore.ts";-import * as BootService from "../cloud/bootService.ts";-import * as CliState from "../cloud/CliState.ts";-import * as CliTokenManager from "../cloud/CliTokenManager.ts";-import {- CLOUD_LINKED_USER_ID,- isAgentActivityPublishingEnabledValue,- PUBLISH_AGENT_ACTIVITY_SECRET,- RELAY_URL_SECRET,-} from "../cloud/config.ts";-import { relayUrlConfig } from "../cloud/publicConfig.ts";-import { headlessRelayClientTracingLayer } from "../cloud/relayTracing.ts";-import * as ServerConfig from "../config.ts";-import * as ServerEnvironment from "../environment/ServerEnvironment.ts";-import * as ExternalLauncher from "../process/externalLauncher.ts";-import { readPersistedServerRuntimeState } from "../serverRuntimeState.ts";-import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";-import { resolveCliCommand } from "./invocation.ts";-import {- bootServiceLayer,- offerServiceDuringOnboarding,- recoverServiceOnboardingOffer,-} from "./service.ts";--const jsonFlag = Flag.boolean("json").pipe(- Flag.withDescription("Emit JSON instead of human-readable output."),- Flag.withDefault(false),-);--const isCloudCliTokenManagerError = Schema.is(CliTokenManager.CloudCliTokenManagerError);--const headlessFlag = Flag.boolean("headless").pipe(- Flag.withDescription("Authorize without a local browser using out-of-band OAuth."),- Flag.withDefault(false),-);--/**- * Inside an SSH session there is no local browser to complete the loopback- * OAuth callback, so out-of-band OAuth is the only flow that can work.- */-export const headlessSessionConfig = Config.all({- sshConnection: Config.string("SSH_CONNECTION").pipe(Config.option),- sshTty: Config.string("SSH_TTY").pipe(Config.option),-}).pipe(- Config.map(({ sshConnection, sshTty }) => Option.isSome(sshConnection) || Option.isSome(sshTty)),-);--const promptForOutOfBandOAuthCode = Effect.fn("cloud.cli.prompt_for_out_of_band_oauth_code")(- function* ({ authorizeUrl, validate }: CliTokenManager.OutOfBandOAuthPromptInput) {- yield* Console.log(formatHeadlessAuthorizationPrompt(authorizeUrl));- return yield* Prompt.run(Prompt.text({ message: "Authorization code", validate }));- },-);--export function formatHeadlessAuthorizationPrompt(authorizeUrl: string): string {- return [- "Headless authorization",- "Open this URL on a device with a browser:",- ` ${authorizeUrl}`,- "",- "After signing in, return here and enter the code shown in your browser.",- ].join("\n");-}--/** Returns the connected account identity, if the flow could determine one. */-const authorizeCli = Effect.fn("cloud.cli.authorize")(function* (options: {- readonly headless: boolean;-}) {- const tokens = yield* CliTokenManager.CloudCliTokenManager;- const useOutOfBandOAuth = options.headless || (yield* headlessSessionConfig);- if (!useOutOfBandOAuth) {- const authorization = yield* tokens.get;- if (authorization._tag === "Authorized") {- return authorization.token.identity ?? null;- }- yield* Console.log("\nHeadless mode enabled. A new authorization link is ready below.");- }- // A stored credential whose refresh fails (revoked, expired grant) must- // fall through to a fresh out-of-band authorization, not dead-end the command.- const existing = yield* tokens.getExisting.pipe(- Effect.catchTag("CloudCliCredentialRefreshError", () =>- Console.log(- "The stored T3 Connect credential could not be refreshed; signing in again.",- ).pipe(Effect.as(Option.none())),- ),- );- if (Option.isSome(existing)) {- return existing.value.identity ?? null;- }- const { token, identity } = yield* CliTokenManager.outOfBandOAuthLogin(- promptForOutOfBandOAuthCode,- ).pipe(- Effect.mapError((cause) =>- // Ctrl-C / EOF at the prompt is a QuitError; let it propagate so the CLI- // cancels quietly instead of dumping an authorization error.- Terminal.isQuitError(cause) || isCloudCliTokenManagerError(cause)- ? cause- : new CliTokenManager.CloudCliAuthorizationError({ cause }),- ),- );- yield* tokens.store(token);- return identity;-});--function bytesToString(value: Uint8Array): string {- return new TextDecoder().decode(value);-}--function stringToBytes(value: string): Uint8Array {- return new TextEncoder().encode(value);-}--export function isPublishAgentActivityEnabledValue(value: string | null): boolean {- return isAgentActivityPublishingEnabledValue(value);-}--interface CloudCliStatus {- readonly desired: boolean;- readonly authenticated: boolean;- readonly linked: boolean;- readonly cloudUserId: string | null;- readonly relayUrl: string | null;- readonly publishAgentActivity: boolean;- readonly relayClient: RelayClient.RelayClientStatus;-}--function formatRelayClientStatus(executable: RelayClient.RelayClientStatus): ReadonlyArray<string> {- switch (executable.status) {- case "available": {- const source =- executable.source === "path"- ? "PATH"- : executable.source === "managed"- ? "managed install"- : "configured override";- return [- ` Relay client: available via ${source}`,- ` Path: ${executable.executablePath}`,- ` Version: ${executable.version}`,- ];- }- case "missing":- return [" Relay client: not installed"];- case "unsupported":- return [- ` Relay client: unsupported on ${executable.platform}-${executable.arch}`,- ` Managed version: ${executable.version}`,- ];- }-}--function formatCloudStatus(status: CloudCliStatus, options?: { readonly json?: boolean }): string {- if (options?.json) {- return JSON.stringify(status, null, 2);- }-- const provisioned = status.linked- ? "provisioned"- : status.desired && status.authenticated- ? "pending server startup"- : "not provisioned";- const nextStep = !status.authenticated- ? "Run `akeru connect link` to authorize and enable T3 Connect."- : !status.desired- ? "Run `akeru connect link` to enable T3 Connect."- : !status.linked- ? "Start T3 to provision the environment link and launch its managed tunnel."- : undefined;-- return [- "T3 Connect",- ` Exposure: ${status.desired ? "enabled" : "disabled"}`,- ` Authorization: ${status.authenticated ? "stored credential" : "missing"}`,- ` Environment link: ${provisioned}`,- ` Relay: ${status.relayUrl ?? "not provisioned"}`,- ` Publish agent activity: ${status.publishAgentActivity ? "enabled" : "disabled"}`,- ...formatRelayClientStatus(status.relayClient),- ...(nextStep ? ["", `Next: ${nextStep}`] : []),- ].join("\n");-}--const CLOUD_CLI_LIVE_SERVER_TIMEOUT = Duration.seconds(5);--const confirmRelayClientInstall = (version: string) =>- Prompt.run(- Prompt.confirm({- message: `The T3 relay client is required for T3 Connect. Download and install version ${version}?`,- initial: false,- }),- );--function relayClientInstallProgressMessage(stage: RelayClientInstallProgressStage): string {- switch (stage) {- case "checking":- return "Checking existing installation";- case "waiting_for_lock":- return "Waiting for installation lock";- case "downloading":- return "Downloading";- case "verifying":- return "Verifying download";- case "installing":- return "Installing";- case "validating":- return "Validating executable";- case "activating":- return "Activating installation";- }-}--const reportRelayClientInstallProgress = (event: RelayClientInstallProgressEvent) =>- event.type === "progress"- ? Console.log(`Relay client: ${relayClientInstallProgressMessage(event.stage)}...`)- : Effect.void;--export const acquireRelayClientForLink = Effect.fn("cloud.cli.acquire_relay_client_for_link")(- function* <ConfirmError, ConfirmContext>(- relayClient: RelayClient.RelayClient["Service"],- confirmInstall: (version: string) => Effect.Effect<boolean, ConfirmError, ConfirmContext>,- reportProgress: (event: RelayClientInstallProgressEvent) => Effect.Effect<void>,- ) {- const executable = yield* relayClient.resolve;- if (executable.status === "available") {- return Option.some(executable);- }- if (executable.status === "unsupported") {- return Option.some(yield* relayClient.installWithProgress(reportProgress));- }- if (!(yield* confirmInstall(executable.version))) {- return Option.none();- }- return Option.some(yield* relayClient.installWithProgress(reportProgress));- },-);--const withCloudCliSessionToken = <A, E, R>(- environmentAuth: EnvironmentAuth.EnvironmentAuth["Service"],- run: (token: string) => Effect.Effect<A, E, R>,-) =>- Effect.acquireUseRelease(- environmentAuth.issueSession({- scopes: [AuthRelayWriteScope],- subject: "cloud-cli",- label: "akeru connect cli",- }),- (issued) => run(issued.token),- (issued) => environmentAuth.revokeSession(issued.sessionId).pipe(Effect.ignore({ log: true })),- );--type LiveCloudActionResult =- | { readonly status: "not-running" }- | { readonly status: "succeeded" }- | { readonly status: "failed"; readonly cause: Cause.Cause<unknown> };--const runLiveCloudUnlink = Effect.fn("cloud.cli.run_live_unlink")(function* () {- const config = yield* ServerConfig.ServerConfig;- const runtimeState = yield* readPersistedServerRuntimeState(config.serverRuntimeStatePath);- if (Option.isNone(runtimeState)) {- return { status: "not-running" } satisfies LiveCloudActionResult;- }-- const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;- const result = yield* Effect.exit(- withCloudCliSessionToken(environmentAuth, (token) =>- HttpApiClient.make(EnvironmentHttpApi, {- baseUrl: runtimeState.value.origin,- }).pipe(- Effect.flatMap((client) =>- client.connect.unlink({ headers: { authorization: `Bearer ${token}` } }),- ),- Effect.timeout(CLOUD_CLI_LIVE_SERVER_TIMEOUT),- ),- ),- );- return Exit.isSuccess(result)- ? ({ status: "succeeded" } satisfies LiveCloudActionResult)- : ({ status: "failed", cause: result.cause } satisfies LiveCloudActionResult);-});--type RelayUnlinkResult =- | { readonly status: "not-authenticated" }- | { readonly status: "revoked" }- | { readonly status: "not-linked" };--type CloudDisconnectOperation = "live-server-unlink" | "relay-environment-unlink";--const logCloudDisconnectFailure = (- operation: CloudDisconnectOperation,- clearAuthorization: boolean,- cause: Cause.Cause<unknown>,-) =>- Effect.logWarning("T3 Connect disconnect operation failed.").pipe(- Effect.annotateLogs({- operation,- clearAuthorization,- cause: Cause.pretty(cause),- }),- );--const unlinkRelayEnvironment = Effect.fn("cloud.cli.unlink_relay_environment")(function* () {- const tokens = yield* CliTokenManager.CloudCliTokenManager;- const token = yield* tokens.getExisting;- if (Option.isNone(token)) {- return { status: "not-authenticated" } satisfies RelayUnlinkResult;- }-- const environment = yield* ServerEnvironment.ServerEnvironment;- const environmentId = yield* environment.getEnvironmentId;- const relayUrl = yield* relayUrlConfig;- const httpClient = yield* HttpClient.HttpClient;- const response = yield* HttpClientRequest.delete(- `${relayUrl}/v1/client/environment-links/${encodeURIComponent(environmentId)}`,- ).pipe(- HttpClientRequest.bearerToken(token.value.accessToken),- httpClient.execute,- Effect.flatMap(HttpClientResponse.filterStatusOk),- Effect.flatMap(HttpClientResponse.schemaBodyJson(RelayOkResponse)),- withRelayClientTracing,- );- return response.ok- ? ({ status: "revoked" } satisfies RelayUnlinkResult)- : ({ status: "not-linked" } satisfies RelayUnlinkResult);-});--export const reportCloudDisconnectResults = Effect.fn("cloud.cli.report_disconnect_results")(- function* (input: {- readonly clearAuthorization: boolean;- readonly liveResult: LiveCloudActionResult;- readonly relayResult: Exit.Exit<RelayUnlinkResult, unknown>;- }) {- if (input.liveResult.status === "failed") {- yield* logCloudDisconnectFailure(- "live-server-unlink",- input.clearAuthorization,- input.liveResult.cause,- );- yield* Console.warn(- "T3 Connect is disabled, but the running server could not stop its tunnel.\nRestart that server to stop the connector.",- );- } else {- yield* Console.log("T3 Connect is disabled locally.");- }-- if (Exit.isFailure(input.relayResult)) {- yield* logCloudDisconnectFailure(- "relay-environment-unlink",- input.clearAuthorization,- input.relayResult.cause,- );- yield* Console.warn(- input.clearAuthorization- ? "Could not revoke the relay-side environment record before signing out.\nThe stored CLI authorization was still removed locally."- : "Could not revoke the relay-side environment record yet.\nRun `akeru connect unlink` again when the relay is reachable.",- );- } else if (input.relayResult.value.status === "revoked") {- yield* Console.log("Revoked the relay-side environment record.");- }- },-);--const disconnectCloud = Effect.fn("cloud.cli.disconnect")(function* (options: {- readonly clearAuthorization: boolean;-}) {- yield* CliState.setCliDesiredCloudLink(false);- const liveResult = yield* runLiveCloudUnlink();- const relayResult = yield* Effect.exit(unlinkRelayEnvironment());- yield* CliState.clearPersistedCloudLink;-- if (options.clearAuthorization) {- const tokens = yield* CliTokenManager.CloudCliTokenManager;- yield* tokens.clear;- }-- yield* reportCloudDisconnectResults({- clearAuthorization: options.clearAuthorization,- liveResult,- relayResult,- });-- if (options.clearAuthorization) {- yield* Console.log(- "Signed out of T3 Connect locally.\nThe background service is managed separately with `akeru service`.",- );- }-});--const runCloudCommand = Effect.fn("cloud.cli.run_cloud_command")(function* <A, E>(- flags: { readonly baseDir: Option.Option<string> },- run: Effect.Effect<- A,- E,- | ServerSecretStore.ServerSecretStore- | CliTokenManager.CloudCliTokenManager- | RelayClient.RelayClient- | EnvironmentAuth.EnvironmentAuth- | BootService.BootService- | Crypto.Crypto- | FileSystem.FileSystem- | HttpClient.HttpClient- | Prompt.Environment- | ServerConfig.ServerConfig- | ServerEnvironment.ServerEnvironment- >,- options?: {- readonly quietLogs?: boolean;- },-) {- const logLevel = yield* GlobalFlag.LogLevel;- const config = yield* resolveCliAuthConfig(flags, logLevel);- const minimumLogLevel = options?.quietLogs ? "Error" : config.logLevel;- const runtimeLayer = Layer.mergeAll(- ServerSecretStore.layer,- CliTokenManager.layer.pipe(- Layer.provide(ServerSecretStore.layer),- Layer.provide(ExternalLauncher.layer),- ),- RelayClient.layerCloudflared({ baseDir: config.baseDir }),- EnvironmentAuth.runtimeLayer,- ServerEnvironment.layer.pipe(Layer.provide(ServerSecretStore.layer)),- bootServiceLayer(config),- headlessRelayClientTracingLayer,- ).pipe(- Layer.provideMerge(FetchHttpClient.layer),- Layer.provideMerge(ServerConfig.layer(config)),- Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),- );- return yield* run.pipe(Effect.provide(runtimeLayer));-});--const connectedAs = (identity: string | null): string => (identity ? ` as ${identity}` : "");--export function formatRelayClientReady(version: string): string {- return `✓ Relay client ready · cloudflared ${version}`;-}--const linkEnvironmentForConnect = Effect.fn("cloud.cli.link_environment")(function* (options: {- readonly headless: boolean;- readonly publishOnly?: boolean;-}) {- const publishOnly = options.publishOnly ?? false;- if (!publishOnly) {- const relayClient = yield* RelayClient.RelayClient;- const installed = yield* acquireRelayClientForLink(- relayClient,- confirmRelayClientInstall,- reportRelayClientInstallProgress,- );- if (Option.isNone(installed)) {- yield* Console.log("T3 Connect setup cancelled. The relay client was not installed.");- return null;- }- yield* Console.log(formatRelayClientReady(installed.value.version));- }-- const identity = yield* authorizeCli(options);- yield* CliState.setCliDesiredCloudLink(true, publishOnly ? "publish_only" : "managed");- if (publishOnly) {- const secrets = yield* ServerSecretStore.ServerSecretStore;- yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, stringToBytes("true"));- }- return { identity } as const;-});--const connectLoginCommand = Command.make("login", {- ...projectLocationFlags,- headless: headlessFlag,-}).pipe(- Command.withDescription("Authorize the T3 Connect CLI without enabling remote access."),- Command.withHandler((flags) =>- runCloudCommand(- flags,- Effect.gen(function* () {- yield* Console.log("T3 Connect\n");- const identity = yield* authorizeCli(flags);- yield* Console.log(`✓ Signed in${connectedAs(identity)}`);- }),- ),- ),-);--const connectLinkCommand = Command.make("link", {- ...projectLocationFlags,- headless: headlessFlag,- publishOnly: Flag.boolean("publish-only").pipe(- Flag.withDescription(- "Link to publish agent activity only — no managed tunnel. Reach this environment out of band (e.g. Tailscale).",- ),- Flag.withDefault(false),- ),-}).pipe(- Command.withDescription("Authorize this environment for T3 Connect on next start."),- Command.withHandler((flags) =>- runCloudCommand(- flags,- Effect.gen(function* () {- yield* Console.log("T3 Connect\n");- const linked = yield* linkEnvironmentForConnect(flags);- if (linked) {- const serveCommand = yield* resolveCliCommand("serve");- yield* Console.log(- flags.publishOnly- ? `✓ Authorized${connectedAs(linked.identity)}\n\nNext\n Start T3 to publish agent activity (no managed tunnel).`- : `✓ Authorized${connectedAs(linked.identity)}\n\nNext\n Start the server with \`${serveCommand}\` to make this machine reachable.`,- );- }- }),- ),- ),-);--const connectStatusCommand = Command.make("status", {- ...projectLocationFlags,- json: jsonFlag,-}).pipe(- Command.withDescription("Show persisted T3 Connect and relay client state."),- Command.withHandler((flags) =>- runCloudCommand(- flags,- Effect.gen(function* () {- const secrets = yield* ServerSecretStore.ServerSecretStore;- const relayClient = yield* RelayClient.RelayClient;- const tokens = yield* CliTokenManager.CloudCliTokenManager;- const [desired, authenticated, cloudUserId, relayUrl, publishAgentActivity, executable] =- yield* Effect.all(- [- CliState.readCliDesiredCloudLink,- tokens.hasCredential,- secrets.get(CLOUD_LINKED_USER_ID),- secrets.get(RELAY_URL_SECRET),- secrets.get(PUBLISH_AGENT_ACTIVITY_SECRET),- relayClient.resolve,- ],- { concurrency: "unbounded" },- );- const status: CloudCliStatus = {- desired,- authenticated,- linked: Option.isSome(cloudUserId),- cloudUserId: Option.isSome(cloudUserId) ? bytesToString(cloudUserId.value) : null,- relayUrl: Option.isSome(relayUrl) ? bytesToString(relayUrl.value) : null,- publishAgentActivity: isPublishAgentActivityEnabledValue(- Option.isSome(publishAgentActivity) ? bytesToString(publishAgentActivity.value) : null,- ),- relayClient: executable,- };- yield* Console.log(formatCloudStatus(status, { json: flags.json }));- }),- {- quietLogs: flags.json,- },- ),- ),-);--const connectPublishCommand = Command.make("publish", {- ...projectLocationFlags,- disable: Flag.boolean("disable").pipe(- Flag.withDescription("Stop publishing agent activity to your mobile clients."),- Flag.withDefault(false),- ),-}).pipe(- Command.withDescription(- "Toggle publishing agent activity (push notifications and Live Activities) to your mobile clients.",- ),- Command.withHandler((flags) =>- runCloudCommand(- flags,- Effect.gen(function* () {- const secrets = yield* ServerSecretStore.ServerSecretStore;- const tokens = yield* CliTokenManager.CloudCliTokenManager;- const enabled = !flags.disable;- yield* secrets.set(- PUBLISH_AGENT_ACTIVITY_SECRET,- stringToBytes(enabled ? "true" : "false"),- );- if (!enabled) {- // If enabling scheduled a publish-only link that hasn't been- // provisioned yet, disabling must cancel it too — otherwise the next- // start still links an environment whose only purpose was publishing.- // A pending managed link is left alone; it exists for the tunnel.- const linkedNow = Option.isSome(yield* secrets.get(CLOUD_LINKED_USER_ID));- if (!linkedNow && (yield* CliState.readCliDesiredLinkMode) === "publish_only") {- yield* CliState.setCliDesiredCloudLink(false);- yield* Console.log("Cancelled the pending publish-only T3 Connect link.");- }- yield* Console.log("Publishing agent activity disabled.");- return;- }-- yield* Console.log("Publishing agent activity enabled.");- const linked = Option.isSome(yield* secrets.get(CLOUD_LINKED_USER_ID));- if (linked) {- return;- }-- // Publishing needs the relay to know this environment belongs to you.- // Establish a tunnel-free publish-only link automatically so signing in- // is all it takes — the mobile client can still reach the environment- // out of band without T3 Connect.- if (!(yield* tokens.hasCredential)) {- yield* Console.log(- "Run `akeru connect login` first so this environment can be authorized to publish.",- );- return;- }- // A link may already be desired (e.g. `akeru connect link` before the- // server's first start). Never downgrade it: a desired managed link- // also covers publishing, so only request a publish-only link when no- // link is pending at all.- if (yield* CliState.readCliDesiredCloudLink) {- yield* Console.log(- "A T3 Connect link is already pending. Start T3 to finish provisioning it; publishing starts once it links.",- );- return;- }- yield* CliState.setCliDesiredCloudLink(true, "publish_only");- yield* Console.log(- "Restart T3 to finish authorizing this environment to publish (no managed tunnel is created).",- );- }),- ),- ),-);--const connectUnlinkCommand = Command.make("unlink", {- ...projectLocationFlags,-}).pipe(- Command.withDescription("Disable T3 Connect while retaining the stored authorization."),- Command.withHandler((flags) =>- runCloudCommand(flags, disconnectCloud({ clearAuthorization: false })),- ),-);--const connectLogoutCommand = Command.make("logout", {- ...projectLocationFlags,-}).pipe(- Command.withDescription("Disable T3 Connect and clear the stored CLI authorization."),- Command.withHandler((flags) =>- runCloudCommand(flags, disconnectCloud({ clearAuthorization: true })),- ),-);--export const connectCommand = Command.make("connect", {- ...projectLocationFlags,- headless: headlessFlag,-}).pipe(- Command.withDescription("Set up T3 Connect for this machine."),- Command.withHandler((flags) =>- runCloudCommand(- flags,- Effect.gen(function* () {- yield* Console.log("T3 Connect\n");- const linked = yield* linkEnvironmentForConnect(flags);- if (!linked) {- return;- }- // Show which account was linked so an unexpected identity (an- // authorization code for a different account) is visible before the- // machine is brought online.- yield* Console.log(`✓ Connected${connectedAs(linked.identity)}`);-- // Connect itself already succeeded; a boot-service failure must not- // fail the command, just tell the user what happened and move on.- const background = yield* recoverServiceOnboardingOffer(offerServiceDuringOnboarding);- if (background) {- const platform = yield* HostProcessPlatform;- yield* Console.log(- platform === "darwin"- ? "\n✓ Background service ready\n\nT3 Code will stay reachable while you are logged in to this Mac."- : "\n✓ Background service ready\n\nT3 Code will stay reachable after you log out.",- );- return;- }- const serveCommand = yield* resolveCliCommand("serve");- yield* Console.log(- `\nNext\n Start the server with \`${serveCommand}\` to make this machine reachable.`,- );- }),- ),- ),- Command.withSubcommands([- connectLoginCommand,- connectLinkCommand,- connectPublishCommand,- connectStatusCommand,- connectUnlinkCommand,- connectLogoutCommand,- ]),-);diff --git a/apps/server/src/cli/invocation.ts b/apps/server/src/cli/invocation.tsindex ae7f07f98..53b02e293 100644--- a/apps/server/src/cli/invocation.ts+++ b/apps/server/src/cli/invocation.ts@@ -48,7 +48,7 @@ export function suggestedPackageSpec(version: string): string {/*** Render an `akeru <subcommand>` suggestion that matches how this process was- * launched, so copy/pasting it works. An `npx akeru-bot connect` launch suggests+ * launched, so copy/pasting it works. An `npx akeru-bot pair` launch suggests* `npx akeru-bot serve`, a global install suggests `akeru serve`, and a nightly* build keeps the `@nightly` tag.*/diff --git a/apps/server/src/cli/pair.test.ts b/apps/server/src/cli/pair.test.tsindex 4c234a4d6..6909e2838 100644--- a/apps/server/src/cli/pair.test.ts+++ b/apps/server/src/cli/pair.test.ts@@ -194,7 +194,7 @@ describe("akeru pair", () => {).pipe(Effect.provide(NodeServices.layer)),);- it.effect("directs to akeru serve or akeru connect when no server is running", () =>+ it.effect("directs to akeru serve when no server is running", () =>Effect.gen(function* () {const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-none-test-"));@@ -205,9 +205,8 @@ describe("akeru pair", () => {const rendered = String(typeof error === "object" && error !== null && "cause" in error ? error.cause : error,);- assert.include(rendered, "No running T3 Code server found.");+ assert.include(rendered, "No running Akeru Bot server found.");assert.include(rendered, "npx akeru-bot serve");- assert.include(rendered, "npx akeru-bot connect");}).pipe(Effect.provide(NodeServices.layer)),);@@ -236,7 +235,7 @@ describe("akeru pair", () => {const rendered = String(typeof error === "object" && error !== null && "cause" in error ? error.cause : error,);- assert.include(rendered, "No running T3 Code server found.");+ assert.include(rendered, "No running Akeru Bot server found.");}),).pipe(Effect.provide(NodeServices.layer)),);@@ -262,7 +261,7 @@ describe("akeru pair", () => {const rendered = String(typeof error === "object" && error !== null && "cause" in error ? error.cause : error,);- assert.include(rendered, "No running T3 Code server found.");+ assert.include(rendered, "No running Akeru Bot server found.");}).pipe(Effect.provide(NodeServices.layer)),);});diff --git a/apps/server/src/cli/pair.ts b/apps/server/src/cli/pair.tsindex 4b7508726..bcfa54495 100644--- a/apps/server/src/cli/pair.ts+++ b/apps/server/src/cli/pair.ts@@ -76,9 +76,9 @@ export class NoRunningServerError extends Schema.TaggedErrorClass<NoRunningServe) {override get message(): string {return [- "No running T3 Code server found.",+ "No running Akeru Bot server found.",...this.checkedStatePaths.map((statePath) => ` checked ${statePath}`),- "Start one with `npx akeru-bot serve`, or connect this machine with T3 Connect: `npx akeru-bot connect`.",+ "Start one with `npx akeru-bot serve`.",].join("\n");}}diff --git a/apps/server/src/cli/service.test.ts b/apps/server/src/cli/service.test.tsindex 24a82949c..e6aee1fd2 100644--- a/apps/server/src/cli/service.test.ts+++ b/apps/server/src/cli/service.test.ts@@ -14,7 +14,7 @@ it("reports the installed service version and host paths", () => {assert.equal(formatServiceStatus(status, "0.0.29"),[- "T3 Code service",+ "Akeru Bot service"," Status: installed · [email protected]"," Unit: /home/me/.config/systemd/user/t3code.service"," Logs: /home/me/.t3/userdata/logs/boot-service.log",diff --git a/apps/server/src/cli/service.ts b/apps/server/src/cli/service.tsindex 2716bc383..8e7474d92 100644--- a/apps/server/src/cli/service.ts+++ b/apps/server/src/cli/service.ts@@ -49,13 +49,13 @@ export function formatServiceStatus(cliVersion: string,): string {if (!status.supported) {- return "T3 Code service\n Status: unavailable on this machine\n Supported on: Linux with systemd, macOS with launchd";+ return "Akeru Bot service\n Status: unavailable on this machine\n Supported on: Linux with systemd, macOS with launchd";}if (!status.installed) {- return "T3 Code service\n Status: not installed\n Next: Run `akeru service install`.";+ return "Akeru Bot service\n Status: not installed\n Next: Run `akeru service install`.";}return [- "T3 Code service",+ "Akeru Bot service",` Status: ${status.current ? `installed · akeru-bot@${cliVersion}` : "needs an update or repair"}`,` Unit: ${status.unitPath}`,` Logs: ${status.logPath}`,@@ -73,7 +73,7 @@ const runServiceCommand = Effect.fn("cli.service.run")(function* <A, E>(});const serviceInstallCommand = Command.make("install", projectLocationFlags).pipe(- Command.withDescription("Install T3 Code as a background service for this user."),+ Command.withDescription("Install Akeru Bot as a background service for this user."),Command.withHandler((flags) =>runServiceCommand(flags,@@ -81,12 +81,12 @@ const serviceInstallCommand = Command.make("install", projectLocationFlags).pipeconst result = yield* reconcileService();if (!result.changed) {yield* Console.log(- `T3 Code service is already installed with akeru-bot@${packageJson.version}.`,+ `Akeru Bot service is already installed with akeru-bot@${packageJson.version}.`,);return;}yield* Console.log(- `${result.previouslyInstalled ? "Updated" : "Installed"} T3 Code service with akeru-bot@${packageJson.version}.\nLogs: ${result.plan.logPath}`,+ `${result.previouslyInstalled ? "Updated" : "Installed"} Akeru Bot service with akeru-bot@${packageJson.version}.\nLogs: ${result.plan.logPath}`,);}),),@@ -103,11 +103,13 @@ const serviceUpdateCommand = Command.make("update", projectLocationFlags).pipe(Effect.gen(function* () {const result = yield* reconcileService();if (!result.changed) {- yield* Console.log(`T3 Code service is already using akeru-bot@${packageJson.version}.`);+ yield* Console.log(+ `Akeru Bot service is already using akeru-bot@${packageJson.version}.`,+ );return;}yield* Console.log(- `${result.previouslyInstalled ? "Updated" : "Installed"} T3 Code service with akeru-bot@${packageJson.version}.\nLogs: ${result.plan.logPath}`,+ `${result.previouslyInstalled ? "Updated" : "Installed"} Akeru Bot service with akeru-bot@${packageJson.version}.\nLogs: ${result.plan.logPath}`,);}),),@@ -115,7 +117,7 @@ const serviceUpdateCommand = Command.make("update", projectLocationFlags).pipe();const serviceUninstallCommand = Command.make("uninstall", projectLocationFlags).pipe(- Command.withDescription("Stop and remove the T3 Code background service."),+ Command.withDescription("Stop and remove the Akeru Bot background service."),Command.withHandler((flags) =>runServiceCommand(flags,@@ -123,7 +125,7 @@ const serviceUninstallCommand = Command.make("uninstall", projectLocationFlags).const service = yield* BootService.BootService;const removed = yield* service.uninstall;yield* Console.log(- removed ? "Removed the T3 Code service." : "T3 Code service is not installed.",+ removed ? "Removed the Akeru Bot service." : "Akeru Bot service is not installed.",);}),),@@ -131,7 +133,7 @@ const serviceUninstallCommand = Command.make("uninstall", projectLocationFlags).);const serviceStatusCommand = Command.make("status", projectLocationFlags).pipe(- Command.withDescription("Show whether the T3 Code background service is installed."),+ Command.withDescription("Show whether the Akeru Bot background service is installed."),Command.withHandler((flags) =>runServiceCommand(flags,@@ -150,7 +152,7 @@ export const offerServiceDuringOnboarding = Effect.gen(function* () {return false;}if (installed && current) {- yield* Console.log("T3 Code is already set up to run in the background on this machine.");+ yield* Console.log("Akeru Bot is already set up to run in the background on this machine.");return true;}// A LaunchAgent starts at login and dies at logout; there is no@@ -159,12 +161,10 @@ export const offerServiceDuringOnboarding = Effect.gen(function* () {const wanted = yield* Prompt.run(Prompt.confirm({message: installed- ? "The installed T3 Code service needs an update or repair. Update it now?"+ ? "The installed Akeru Bot service needs an update or repair. Update it now?": platform === "darwin"- ? "Run T3 Code in the background whenever you log in to this Mac? " +- "It stays reachable through T3 Connect while you are logged in."- : "Run T3 Code in the background whenever this machine boots? " +- "It stays reachable through T3 Connect even after you log out.",+ ? "Run Akeru Bot in the background whenever you log in to this Mac?"+ : "Run Akeru Bot in the background whenever this machine boots?",initial: true,}),);@@ -198,7 +198,7 @@ export const recoverServiceOnboardingOffer = <R>();export const serviceCommand = Command.make("service").pipe(- Command.withDescription("Manage the T3 Code background service."),+ Command.withDescription("Manage the Akeru Bot background service."),Command.withSubcommands([serviceInstallCommand,serviceUninstallCommand,diff --git a/apps/server/src/cloud/CliState.test.ts b/apps/server/src/cloud/CliState.test.tsdeleted file mode 100644index 39f904b47..000000000--- a/apps/server/src/cloud/CliState.test.ts+++ /dev/null@@ -1,82 +0,0 @@-import * as NodeServices from "@effect/platform-node/NodeServices";-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 ServerSecretStore from "../auth/ServerSecretStore.ts";-import { ServerConfig } from "../config.ts";-import * as CliState from "./CliState.ts";-import {- CLOUD_ENDPOINT_RUNTIME_CONFIG,- CLOUD_LINKED_USER_ID,- CLOUD_MINT_PUBLIC_KEY,- PUBLISH_AGENT_ACTIVITY_SECRET,- RELAY_ENVIRONMENT_CREDENTIAL_SECRET,- RELAY_ISSUER_SECRET,- RELAY_URL_SECRET,-} from "./config.ts";--const persistedCloudLinkSecrets = [- CLOUD_LINKED_USER_ID,- RELAY_URL_SECRET,- RELAY_ISSUER_SECRET,- RELAY_ENVIRONMENT_CREDENTIAL_SECRET,- CLOUD_MINT_PUBLIC_KEY,- CLOUD_ENDPOINT_RUNTIME_CONFIG,- PUBLISH_AGENT_ACTIVITY_SECRET,-] as const;--const makeTestLayer = () =>- ServerSecretStore.layer.pipe(- Layer.provide(- ServerConfig.layerTest(process.cwd(), {- prefix: "t3-cloud-cli-state-test-",- }),- ),- );--it.layer(NodeServices.layer)("CliState", (it) => {- it.effect("persists desired exposure and clears provisioned relay state", () =>- Effect.gen(function* () {- const secrets = yield* ServerSecretStore.ServerSecretStore;-- assert.isFalse(yield* CliState.readCliDesiredCloudLink);- yield* CliState.setCliDesiredCloudLink(true);- assert.isTrue(yield* CliState.readCliDesiredCloudLink);-- for (const name of persistedCloudLinkSecrets) {- yield* secrets.set(name, new TextEncoder().encode(name));- }- yield* CliState.clearPersistedCloudLink;-- assert.isFalse(yield* CliState.readCliDesiredCloudLink);- for (const name of persistedCloudLinkSecrets) {- assert.isTrue(Option.isNone(yield* secrets.get(name)));- }- }).pipe(Effect.provide(makeTestLayer())),- );-- it.effect("round-trips the desired link mode and defaults legacy links to managed", () =>- Effect.gen(function* () {- const secrets = yield* ServerSecretStore.ServerSecretStore;-- assert.equal(yield* CliState.readCliDesiredLinkMode, "managed");-- yield* CliState.setCliDesiredCloudLink(true, "publish_only");- assert.isTrue(yield* CliState.readCliDesiredCloudLink);- assert.equal(yield* CliState.readCliDesiredLinkMode, "publish_only");-- yield* CliState.setCliDesiredCloudLink(true, "managed");- assert.equal(yield* CliState.readCliDesiredLinkMode, "managed");-- // A pre-existing link persisted the literal "true"; treat it as managed.- yield* secrets.set(CliState.CLOUD_CLI_DESIRED_LINK_SECRET, new TextEncoder().encode("true"));- assert.isTrue(yield* CliState.readCliDesiredCloudLink);- assert.equal(yield* CliState.readCliDesiredLinkMode, "managed");-- yield* CliState.setCliDesiredCloudLink(false);- assert.equal(yield* CliState.readCliDesiredLinkMode, "managed");- }).pipe(Effect.provide(makeTestLayer())),- );-});diff --git a/apps/server/src/cloud/CliState.ts b/apps/server/src/cloud/CliState.tsdeleted file mode 100644index 9af9a032f..000000000--- a/apps/server/src/cloud/CliState.ts+++ /dev/null@@ -1,74 +0,0 @@-import * as Effect from "effect/Effect";-import * as Option from "effect/Option";--import * as ServerSecretStore from "../auth/ServerSecretStore.ts";-import {- CLOUD_ENDPOINT_RUNTIME_CONFIG,- CLOUD_LINKED_USER_ID,- CLOUD_MINT_PUBLIC_KEY,- PUBLISH_AGENT_ACTIVITY_SECRET,- RELAY_ENVIRONMENT_CREDENTIAL_SECRET,- RELAY_ISSUER_SECRET,- RELAY_URL_SECRET,-} from "./config.ts";--export const CLOUD_CLI_DESIRED_LINK_SECRET = "cloud-cli-desired-link";--// "managed" provisions a Cloudflare tunnel (default, legacy value "true").-// "publish_only" links the environment to the relay purely to publish agent-// activity — no tunnel, no relay-advertised endpoint — so activity can flow to-// mobile clients even when they reach the environment out of band (Tailscale,-// direct pairing) without T3 Connect.-export type CliDesiredLinkMode = "managed" | "publish_only";--const MANAGED_BYTES = new TextEncoder().encode("managed");-const PUBLISH_ONLY_BYTES = new TextEncoder().encode("publish_only");--export const readCliDesiredCloudLink = Effect.gen(function* () {- const secrets = yield* ServerSecretStore.ServerSecretStore;- return Option.isSome(yield* secrets.get(CLOUD_CLI_DESIRED_LINK_SECRET));-});--export const readCliDesiredLinkMode = Effect.gen(function* () {- const secrets = yield* ServerSecretStore.ServerSecretStore;- const value = yield* secrets.get(CLOUD_CLI_DESIRED_LINK_SECRET);- if (Option.isNone(value)) {- return "managed" as CliDesiredLinkMode;- }- // Legacy links stored the literal "true" and are always managed.- return new TextDecoder().decode(value.value) === "publish_only"- ? ("publish_only" as CliDesiredLinkMode)- : ("managed" as CliDesiredLinkMode);-});--export const setCliDesiredCloudLink = Effect.fn("cloud.cli_state.set_desired")(function* (- desired: boolean,- mode: CliDesiredLinkMode = "managed",-) {- const secrets = yield* ServerSecretStore.ServerSecretStore;- if (desired) {- yield* secrets.set(- CLOUD_CLI_DESIRED_LINK_SECRET,- mode === "publish_only" ? PUBLISH_ONLY_BYTES : MANAGED_BYTES,- );- } else {- yield* secrets.remove(CLOUD_CLI_DESIRED_LINK_SECRET);- }-});--export const clearPersistedCloudLink = Effect.gen(function* () {- const secrets = yield* ServerSecretStore.ServerSecretStore;- yield* Effect.all(- [- secrets.remove(CLOUD_CLI_DESIRED_LINK_SECRET),- secrets.remove(CLOUD_LINKED_USER_ID),- secrets.remove(RELAY_URL_SECRET),- secrets.remove(RELAY_ISSUER_SECRET),- secrets.remove(RELAY_ENVIRONMENT_CREDENTIAL_SECRET),- secrets.remove(CLOUD_MINT_PUBLIC_KEY),- secrets.remove(CLOUD_ENDPOINT_RUNTIME_CONFIG),- secrets.remove(PUBLISH_AGENT_ACTIVITY_SECRET),- ],- { concurrency: "unbounded" },- );-});diff --git a/apps/server/src/cloud/CliTokenManager.test.ts b/apps/server/src/cloud/CliTokenManager.test.tsdeleted file mode 100644index e6eb6b7cd..000000000--- a/apps/server/src/cloud/CliTokenManager.test.ts+++ /dev/null@@ -1,264 +0,0 @@-import { readConnectAuthorizeRequest } from "@t3tools/shared/connectAuth";-import * as NodeServices from "@effect/platform-node/NodeServices";-import { assert, it } from "@effect/vitest";-import * as ConfigProvider from "effect/ConfigProvider";-import * as Crypto from "effect/Crypto";-import * as Deferred from "effect/Deferred";-import * as Effect from "effect/Effect";-import * as Encoding from "effect/Encoding";-import * as Layer from "effect/Layer";-import * as Option from "effect/Option";-import * as Queue from "effect/Queue";-import * as Schema from "effect/Schema";-import * as Terminal from "effect/Terminal";-import * as HttpClient from "effect/unstable/http/HttpClient";-import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";--import * as CliTokenManager from "./CliTokenManager.ts";-import type { OutOfBandOAuthPromptInput } from "./CliTokenManager.ts";--// pk_test_<base64 of "clerk.example.test$">-const TEST_ENV = {- T3CODE_CLERK_PUBLISHABLE_KEY: "pk_test_Y2xlcmsuZXhhbXBsZS50ZXN0JA==",- T3CODE_CLERK_CLI_OAUTH_CLIENT_ID: "oauth_client_test",- T3CODE_HOSTED_APP_URL: "https://hosted.example.test",-};--interface RecordedTokenRequest {- readonly url: string;- readonly params: URLSearchParams;-}--// A JWT whose payload claims { email: "[email protected]" } (signature is not-// verified — the CLI only reads the claim to display the connected account).-const TestIdTokenHeaderJson = Schema.fromJsonString(Schema.Struct({ alg: Schema.Literal("none") }));-const TestIdTokenPayloadJson = Schema.fromJsonString(Schema.Struct({ email: Schema.String }));-const encodeTestIdTokenHeader = Schema.encodeSync(TestIdTokenHeaderJson);-const encodeTestIdTokenPayload = Schema.encodeSync(TestIdTokenPayloadJson);-const idTokenWithEmail = (() => {- const header = Encoding.encodeBase64Url(encodeTestIdTokenHeader({ alg: "none" }));- const payload = Encoding.encodeBase64Url(- encodeTestIdTokenPayload({ email: "[email protected]" }),- );- return `${header}.${payload}.`;-})();--const TestTokenResponseJson = Schema.fromJsonString(- Schema.Struct({- access_token: Schema.String,- refresh_token: Schema.String,- id_token: Schema.String,- expires_in: Schema.Number,- token_type: Schema.String,- }),-);-const encodeTestTokenResponse = Schema.encodeSync(TestTokenResponseJson);--const makeTokenEndpointLayer = (- requests: Array<RecordedTokenRequest>,- options?: { readonly idToken?: string },-) =>- Layer.succeed(- HttpClient.HttpClient,- HttpClient.make((request) =>- Effect.sync(() => {- const body =- request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : "";- requests.push({ url: request.url, params: new URLSearchParams(body) });- return HttpClientResponse.fromWeb(- request,- new Response(- encodeTestTokenResponse({- access_token: "access-token-1",- refresh_token: "refresh-token-1",- id_token: options?.idToken ?? idTokenWithEmail,- expires_in: 3600,- token_type: "bearer",- }),- { status: 200, headers: { "content-type": "application/json" } },- ),- );- }),- ),- );--const provideTestEnv = Effect.provide(- ConfigProvider.layer(ConfigProvider.fromEnv({ env: TEST_ENV })),-);--const isAuthorizationError = Schema.is(CliTokenManager.CloudCliAuthorizationError);--class PromptRejectedError extends Schema.TaggedErrorClass<PromptRejectedError>()(- "PromptRejectedError",- { message: Schema.String },-) {}--it("formats loopback authorization with a headless-host fallback", () => {- assert.equal(- CliTokenManager.formatLoopbackAuthorizationPrompt("https://clerk.example.test/authorize"),- [- "Open this URL to authorize T3 Connect:",- " https://clerk.example.test/authorize",- "",- "Press \u001b[1mEnter\u001b[22m to open it in your browser.",- "No browser on this device? Press \u001b[1mH\u001b[22m to switch to headless mode.",- ].join("\n"),- );-});--const makeTestTerminal = (queue: Queue.Queue<Terminal.UserInput>) =>- Terminal.make({- columns: Effect.succeed(80),- rows: Effect.succeed(24),- readInput: Effect.succeed(Queue.asDequeue(queue)),- readLine: Effect.never,- display: () => Effect.void,- });--const userInput = (name: string): Terminal.UserInput => ({- input: Option.some(name),- key: { name, ctrl: false, meta: false, shift: name !== name.toLowerCase() },-});--it.effect("opens the browser on Enter and switches the active flow on H", () =>- Effect.gen(function* () {- const queue = yield* Queue.make<Terminal.UserInput>();- yield* Queue.offerAll(queue, [userInput("enter"), userInput("H")]);- const opened: Array<string> = [];-- const result = yield* CliTokenManager.waitForLoopbackAuthorization({- authorizationUrl: "https://clerk.example.test/authorize",- callback: Effect.never,- terminal: makeTestTerminal(queue),- launchBrowser: (url) =>- Effect.sync(() => {- opened.push(url);- }),- });-- assert.deepEqual(opened, ["https://clerk.example.test/authorize"]);- assert.deepEqual(result, { _tag: "HeadlessRequested" });- }),-);--it.effect("finishes normally when the browser callback wins", () =>- Effect.gen(function* () {- const queue = yield* Queue.make<Terminal.UserInput>();- const callback = yield* Deferred.make<string>();- yield* Deferred.succeed(callback, "clerk-code-123");-- const result = yield* CliTokenManager.waitForLoopbackAuthorization({- authorizationUrl: "https://clerk.example.test/authorize",- callback: Deferred.await(callback),- terminal: makeTestTerminal(queue),- launchBrowser: () => Effect.die("browser launch should not run"),- });-- assert.deepEqual(result, { _tag: "AuthorizationCode", code: "clerk-code-123" });- }),-);--it.layer(NodeServices.layer)("CliTokenManager.outOfBandOAuthLogin", (it) => {- it.effect("prints a hosted authorize URL and exchanges the out-of-band code with PKCE", () =>- Effect.gen(function* () {- const requests: Array<RecordedTokenRequest> = [];- let seenAuthorizeUrl = "";-- const { token, identity } = yield* CliTokenManager.outOfBandOAuthLogin(- ({ authorizeUrl, validate }: OutOfBandOAuthPromptInput) =>- Effect.gen(function* () {- seenAuthorizeUrl = authorizeUrl;- const request = readConnectAuthorizeRequest(new URL(authorizeUrl));- assert.isNotNull(request);- return yield* validate(`clerk-code-123.${request!.state}`).pipe(- Effect.mapError((message) => new PromptRejectedError({ message })),- );- }),- ).pipe(Effect.provide(makeTokenEndpointLayer(requests)), provideTestEnv);-- const authorizeUrl = new URL(seenAuthorizeUrl);- assert.equal(authorizeUrl.origin, "https://hosted.example.test");- assert.equal(authorizeUrl.pathname, "/connect");- const request = readConnectAuthorizeRequest(authorizeUrl);- assert.isNotNull(request);- assert.match(request!.state, /^[A-Za-z0-9_-]{22}$/);-- assert.equal(token.accessToken, "access-token-1");- assert.equal(token.refreshToken, "refresh-token-1");- assert.equal(token.identity, "[email protected]");- // The id_token's email claim is surfaced so connect can show the account.- assert.equal(identity, "[email protected]");-- assert.lengthOf(requests, 1);- const exchange = requests[0]!;- assert.equal(exchange.url, "https://clerk.example.test/oauth/token");- assert.equal(exchange.params.get("grant_type"), "authorization_code");- assert.equal(exchange.params.get("code"), "clerk-code-123");- assert.equal(- exchange.params.get("redirect_uri"),- "https://hosted.example.test/connect/callback",- );- assert.equal(exchange.params.get("client_id"), "oauth_client_test");- // The verifier must hash to the challenge advertised in the authorize URL.- const verifier = exchange.params.get("code_verifier");- assert.isNotNull(verifier);- const crypto = yield* Crypto.Crypto;- const digest = yield* crypto.digest("SHA-256", new TextEncoder().encode(verifier!));- assert.equal(Encoding.encodeBase64Url(digest), request!.challenge);- }),- );-- it.effect("rejects out-of-band codes whose state does not match the request", () =>- Effect.gen(function* () {- const requests: Array<RecordedTokenRequest> = [];-- const validationErrors: Array<string> = [];- const result = yield* CliTokenManager.outOfBandOAuthLogin(- ({ validate }: OutOfBandOAuthPromptInput) =>- validate("clerk-code-123.wrong-state").pipe(- Effect.tapError((message) => Effect.sync(() => validationErrors.push(message))),- Effect.mapError((message) => new PromptRejectedError({ message })),- ),- ).pipe(Effect.provide(makeTokenEndpointLayer(requests)), provideTestEnv, Effect.flip);-- assert.lengthOf(requests, 0);- assert.lengthOf(validationErrors, 1);- assert.include(validationErrors[0], "different connect request");- assert.instanceOf(result, PromptRejectedError);- }),- );-- it.effect("ignores an id_token whose claims are not valid JSON", () =>- Effect.gen(function* () {- const requests: Array<RecordedTokenRequest> = [];- const malformedIdToken = `header.${Encoding.encodeBase64Url("not-json")}.signature`;-- const { identity } = yield* CliTokenManager.outOfBandOAuthLogin(- ({ authorizeUrl }: OutOfBandOAuthPromptInput) => {- const request = readConnectAuthorizeRequest(new URL(authorizeUrl));- assert.isNotNull(request);- return Effect.succeed(`clerk-code-123.${request!.state}`);- },- ).pipe(- Effect.provide(makeTokenEndpointLayer(requests, { idToken: malformedIdToken })),- provideTestEnv,- );-- assert.isNull(identity);- assert.lengthOf(requests, 1);- }),- );-- it.effect("fails without touching the token endpoint when the prompt returns garbage", () =>- Effect.gen(function* () {- const requests: Array<RecordedTokenRequest> = [];-- const result = yield* CliTokenManager.outOfBandOAuthLogin(() =>- Effect.succeed("not-a-connect-code"),- ).pipe(Effect.provide(makeTokenEndpointLayer(requests)), provideTestEnv, Effect.flip);-- assert.lengthOf(requests, 0);- assert.isTrue(isAuthorizationError(result));- }),- );-});diff --git a/apps/server/src/cloud/CliTokenManager.ts b/apps/server/src/cloud/CliTokenManager.tsdeleted file mode 100644index 1b0fdd454..000000000--- a/apps/server/src/cloud/CliTokenManager.ts+++ /dev/null@@ -1,493 +0,0 @@-// @effect-diagnostics nodeBuiltinImport:off - The CLI loopback OAuth callback is a Node HTTP boundary.-import * as NodeHttp from "node:http";--import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";-import * as Clock from "effect/Clock";-import * as Cause from "effect/Cause";-import * as Console from "effect/Console";-import * as Context from "effect/Context";-import * as Crypto from "effect/Crypto";-import * as Deferred from "effect/Deferred";-import * as Duration from "effect/Duration";-import * as Effect from "effect/Effect";-import * as Encoding from "effect/Encoding";-import * as Layer from "effect/Layer";-import * as Option from "effect/Option";-import * as Queue from "effect/Queue";-import * as Schema from "effect/Schema";-import * as Semaphore from "effect/Semaphore";-import * as Terminal from "effect/Terminal";-import * as HttpClient from "effect/unstable/http/HttpClient";-import * as HttpClientRequest from "effect/unstable/http/HttpClientRequest";-import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";-import * as HttpRouter from "effect/unstable/http/HttpRouter";-import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";-import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";--import {- buildConnectAuthorizeRequestUrl,- checkConnectAuthCode,- connectCallbackUrl,-} from "@t3tools/shared/connectAuth";--import * as ServerSecretStore from "../auth/ServerSecretStore.ts";-import * as ExternalLauncher from "../process/externalLauncher.ts";-import {- cloudCliOAuthConfig,- hostedAppUrlConfig,- type CloudCliOAuthConfig,-} from "./publicConfig.ts";-import { renderLoopbackAuthorizationCompleteHtml } from "./cliAuthHtml.ts";--const CLOUD_CLI_OAUTH_TOKEN_SECRET = "cloud-cli-oauth-token";-const CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT = Duration.minutes(10);-const CLOUD_CLI_OAUTH_REFRESH_EARLY_MS = Duration.toMillis(Duration.minutes(5));-const boldTerminalText = (value: string): string => `\u001b[1m${value}\u001b[22m`;--export function formatLoopbackAuthorizationPrompt(authorizationUrl: string): string {- return [- "Open this URL to authorize T3 Connect:",- ` ${authorizationUrl}`,- "",- `Press ${boldTerminalText("Enter")} to open it in your browser.`,- `No browser on this device? Press ${boldTerminalText("H")} to switch to headless mode.`,- ].join("\n");-}--export type LoopbackAuthorizationResult =- | { readonly _tag: "AuthorizationCode"; readonly code: string }- | { readonly _tag: "HeadlessRequested" };--const readLoopbackAuthorizationAction = Effect.fn(- "cloud.cli_token.read_loopback_authorization_action",-)(function* (input: Queue.Dequeue<Terminal.UserInput, Cause.Done>) {- while (true) {- const event = yield* Queue.take(input).pipe(Effect.mapError(() => new Terminal.QuitError({})));- const keyName = event.key.name.toLowerCase();- if (!event.key.ctrl && !event.key.meta && keyName === "h") {- return "headless" as const;- }- if (keyName === "enter" || keyName === "return") {- return "open-browser" as const;- }- }-});--export const waitForLoopbackAuthorization = Effect.fn(- "cloud.cli_token.wait_for_loopback_authorization",-)(function* <E, R>(input: {- readonly authorizationUrl: string;- readonly callback: Effect.Effect<string, E, R>;- readonly terminal: Terminal.Terminal;- readonly launchBrowser: (- url: string,- ) => Effect.Effect<void, ExternalLauncher.ExternalLauncherError>;-}) {- return yield* Effect.scoped(- Effect.gen(function* () {- const terminalInput = yield* input.terminal.readInput;- while (true) {- const result = yield* Effect.raceFirst(- input.callback.pipe(- Effect.map(- (code): LoopbackAuthorizationResult => ({ _tag: "AuthorizationCode", code }),- ),- ),- readLoopbackAuthorizationAction(terminalInput),- );- if (typeof result !== "string") {- return result;- }- if (result === "headless") {- return { _tag: "HeadlessRequested" } as const;- }- yield* input- .launchBrowser(input.authorizationUrl)- .pipe(- Effect.catch(() =>- Console.warn(- `Could not open a browser on this device. Open the URL above manually, or press ${boldTerminalText("H")} to switch to headless mode.`,- ),- ),- );- }- }),- );-});--const PersistedToken = Schema.Struct({- accessToken: Schema.String,- refreshToken: Schema.String,- expiresAtEpochMs: Schema.Number,- identity: Schema.optional(Schema.String),-});-export type PersistedToken = typeof PersistedToken.Type;--const PersistedTokenJson = Schema.fromJsonString(PersistedToken);-const decodePersistedToken = Schema.decodeUnknownEffect(PersistedTokenJson);-const encodePersistedToken = Schema.encodeEffect(PersistedTokenJson);--const OAuthTokenResponse = Schema.Struct({- access_token: Schema.String,- refresh_token: Schema.optional(Schema.String),- id_token: Schema.optional(Schema.String),- expires_in: Schema.Number,- token_type: Schema.String,-});--const OidcIdentityClaimsJson = Schema.fromJsonString(- Schema.Struct({- email: Schema.optional(Schema.String),- preferred_username: Schema.optional(Schema.String),- sub: Schema.optional(Schema.String),- }),-);-const decodeOidcIdentityClaimsJson = Schema.decodeUnknownOption(OidcIdentityClaimsJson);--/**- * Best-effort read of the `email` (or fallback) claim from an OIDC id_token.- * Only used to show the operator which account they linked, so a malformed- * token degrades to "no identity" rather than an error.- */-function idTokenIdentity(idToken: string | undefined): string | null {- if (!idToken) return null;- const payload = idToken.split(".")[1];- if (!payload) return null;- const decoded = Encoding.decodeBase64UrlString(payload);- if (decoded._tag !== "Success") return null;- const claims = decodeOidcIdentityClaimsJson(decoded.success);- if (Option.isNone(claims)) return null;- for (const value of [claims.value.email, claims.value.preferred_username, claims.value.sub]) {- if (typeof value === "string" && value.length > 0) return value;- }- return null;-}--export class CloudCliCredentialRemovalError extends Schema.TaggedErrorClass<CloudCliCredentialRemovalError>()(- "CloudCliCredentialRemovalError",- { cause: Schema.Defect() },-) {- override get message(): string {- return "Could not remove the stored T3 Connect CLI credential.";- }-}--export class CloudCliCredentialRefreshError extends Schema.TaggedErrorClass<CloudCliCredentialRefreshError>()(- "CloudCliCredentialRefreshError",- { cause: Schema.Defect() },-) {- override get message(): string {- return "Could not refresh the T3 Connect CLI credential.";- }-}--export class CloudCliCredentialReadError extends Schema.TaggedErrorClass<CloudCliCredentialReadError>()(- "CloudCliCredentialReadError",- { cause: Schema.Defect() },-) {- override get message(): string {- return "Could not read the stored T3 Connect CLI credential.";- }-}--export class CloudCliAuthorizationError extends Schema.TaggedErrorClass<CloudCliAuthorizationError>()(- "CloudCliAuthorizationError",- { cause: Schema.Defect() },-) {- override get message(): string {- return "Could not authorize the T3 Connect CLI.";- }-}--export class CloudCliAuthorizationTimeoutError extends Schema.TaggedErrorClass<CloudCliAuthorizationTimeoutError>()(- "CloudCliAuthorizationTimeoutError",- { cause: Schema.Defect() },-) {- override get message(): string {- return "Timed out waiting for T3 Connect authorization.";- }-}--export const CloudCliTokenManagerError = Schema.Union([- CloudCliCredentialRemovalError,- CloudCliCredentialRefreshError,- CloudCliCredentialReadError,- CloudCliAuthorizationError,- CloudCliAuthorizationTimeoutError,-]);-export type CloudCliTokenManagerError = typeof CloudCliTokenManagerError.Type;--export class CloudCliTokenManager extends Context.Service<- CloudCliTokenManager,- {- readonly get: Effect.Effect<- | { readonly _tag: "Authorized"; readonly token: PersistedToken }- | { readonly _tag: "HeadlessRequested" },- CloudCliTokenManagerError | Terminal.QuitError- >;- readonly getExisting: Effect.Effect<Option.Option<PersistedToken>, CloudCliTokenManagerError>;- readonly hasCredential: Effect.Effect<boolean, CloudCliTokenManagerError>;- readonly store: (token: PersistedToken) => Effect.Effect<void, CloudCliTokenManagerError>;- readonly clear: Effect.Effect<void, CloudCliTokenManagerError>;- }->()("akeru-bot/cloud/CliTokenManager/CloudCliTokenManager") {}--function stringToBytes(value: string): Uint8Array {- return new TextEncoder().encode(value);-}--function bytesToString(value: Uint8Array): string {- return new TextDecoder().decode(value);-}--const exchangeToken = Effect.fn("cloud.cli_token.exchange")(function* (- metadata: Pick<CloudCliOAuthConfig, "tokenEndpoint">,- params: Record<string, string>,-) {- const httpClient = (yield* HttpClient.HttpClient).pipe(HttpClient.filterStatusOk);- const response = yield* HttpClientRequest.post(metadata.tokenEndpoint).pipe(- HttpClientRequest.bodyUrlParams(params),- httpClient.execute,- Effect.flatMap(HttpClientResponse.schemaBodyJson(OAuthTokenResponse)),- );- const now = yield* Clock.currentTimeMillis;- const identity = idTokenIdentity(response.id_token);- return {- token: {- accessToken: response.access_token,- refreshToken: response.refresh_token ?? params.refresh_token ?? "",- expiresAtEpochMs: now + response.expires_in * 1_000,- ...(identity === null ? {} : { identity }),- } satisfies PersistedToken,- identity,- };-});--const makePkceRequest = Effect.gen(function* () {- const crypto = yield* Crypto.Crypto;- const verifier = Encoding.encodeBase64Url(yield* crypto.randomBytes(32));- const challenge = Encoding.encodeBase64Url(- yield* crypto.digest("SHA-256", new TextEncoder().encode(verifier)),- );- const state = Encoding.encodeBase64Url(yield* crypto.randomBytes(16));- return { verifier, challenge, state };-});--export interface OutOfBandOAuthPromptInput {- readonly authorizeUrl: string;- readonly validate: (value: string) => Effect.Effect<string, string>;-}--/**- * Out-of-band OAuth for machines without a local browser (SSH). The user- * opens the hosted /connect URL elsewhere, signs in, and enters the displayed- * code in this terminal. The PKCE verifier never leaves this process, so the- * authorization code is useless to an observer, and the state bundled into- * the blob preserves the loopback flow's CSRF check.- */-export const outOfBandOAuthLogin = Effect.fn("cloud.cli_token.out_of_band_oauth_login")(function* <- E,- R,->(promptForCode: (input: OutOfBandOAuthPromptInput) => Effect.Effect<string, E, R>) {- const metadata = yield* cloudCliOAuthConfig;- const hostedAppUrl = yield* hostedAppUrlConfig;- const { verifier, challenge, state } = yield* makePkceRequest;-- const authorizationCode = yield* promptForCode({- authorizeUrl: buildConnectAuthorizeRequestUrl({ hostedAppUrl, state, challenge }),- validate: (value) => {- const checked = checkConnectAuthCode(value, state);- return typeof checked === "string" ? Effect.fail(checked) : Effect.succeed(value);- },- }).pipe(- // Clerk authorization codes expire on this horizon anyway; matching the- // loopback flow's timeout turns an abandoned prompt into a clear error.- Effect.timeout(CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT),- Effect.catchTag("TimeoutError", (cause) =>- Effect.fail(new CloudCliAuthorizationTimeoutError({ cause })),- ),- );- // promptForCode is caller-supplied, so re-check the returned value rather- // than trusting that the prompt ran validate.- const authCode = checkConnectAuthCode(authorizationCode, state);- if (typeof authCode === "string") {- return yield* new CloudCliAuthorizationError({ cause: authCode });- }-- return yield* exchangeToken(metadata, {- grant_type: "authorization_code",- code: authCode.code,- redirect_uri: connectCallbackUrl(hostedAppUrl),- client_id: metadata.clientId,- code_verifier: verifier,- });-});--export const make = Effect.gen(function* () {- // Capture exactly the services the login/refresh flows need at build time- // (matching the behavior before the out-of-band flow captured the instances), not- // the whole ambient context.- const crypto = yield* Crypto.Crypto;- const httpClient = yield* HttpClient.HttpClient;- const services = Context.make(Crypto.Crypto, crypto).pipe(- Context.add(HttpClient.HttpClient, httpClient),- );- const secrets = yield* ServerSecretStore.ServerSecretStore;- const terminal = yield* Terminal.Terminal;- const externalLauncher = yield* ExternalLauncher.ExternalLauncher;- const semaphore = yield* Semaphore.make(1);- const persist = Effect.fn("cloud.cli_token.persist")(function* (token: PersistedToken) {- const encoded = yield* encodePersistedToken(token);- yield* secrets.set(CLOUD_CLI_OAUTH_TOKEN_SECRET, stringToBytes(encoded));- return token;- });-- const clear = secrets- .remove(CLOUD_CLI_OAUTH_TOKEN_SECRET)- .pipe(Effect.mapError((cause) => new CloudCliCredentialRemovalError({ cause })));-- const read = Effect.fn("cloud.cli_token.read")(function* () {- const encoded = yield* secrets.get(CLOUD_CLI_OAUTH_TOKEN_SECRET);- if (Option.isNone(encoded)) return Option.none<PersistedToken>();- return Option.some(yield* decodePersistedToken(bytesToString(encoded.value)));- });-- const refresh = Effect.fn("cloud.cli_token.refresh")(function* (token: PersistedToken) {- const metadata = yield* cloudCliOAuthConfig;- const { token: refreshed } = yield* exchangeToken(metadata, {- grant_type: "refresh_token",- refresh_token: token.refreshToken,- client_id: metadata.clientId,- });- return refreshed.identity === undefined && token.identity !== undefined- ? { ...refreshed, identity: token.identity }- : refreshed;- });-- const login = Effect.fn("cloud.cli_token.login")(function* () {- const metadata = yield* cloudCliOAuthConfig;- const hostedAppUrl = yield* hostedAppUrlConfig;- const { verifier, challenge, state } = yield* makePkceRequest;- const callback = yield* Deferred.make<string>();- const callbackRoute = HttpRouter.add(- "GET",- "/callback",- Effect.gen(function* () {- const request = yield* HttpServerRequest.HttpServerRequest;- const url = new URL(request.originalUrl, metadata.redirectUri);- const code = url.searchParams.get("code");- if (url.searchParams.get("state") !== state || !code) {- return HttpServerResponse.text("Invalid T3 Connect authorization callback.", {- status: 400,- });- }- yield* Deferred.succeed(callback, code);- return HttpServerResponse.html(renderLoopbackAuthorizationCompleteHtml());- }),- );- yield* HttpRouter.serve(callbackRoute, {- disableListenLog: true,- disableLogger: true,- }).pipe(- Layer.provide(- NodeHttpServer.layer(NodeHttp.createServer, {- host: "127.0.0.1",- port: metadata.loopbackPort,- disablePreemptiveShutdown: true,- }),- ),- Layer.build,- );- // The hosted /connect page establishes a Clerk session before forwarding- // the request to /oauth/authorize with the loopback redirect URI. Sending- // a signed-out browser to /oauth/authorize directly loses the authorize- // parameters across Clerk's sign-in redirect (#5051).- const authorizationUrl = buildConnectAuthorizeRequestUrl({- hostedAppUrl,- state,- challenge,- loopbackPort: metadata.loopbackPort,- });- yield* Console.log(formatLoopbackAuthorizationPrompt(authorizationUrl));- const authorization = yield* waitForLoopbackAuthorization({- authorizationUrl,- callback: Deferred.await(callback).pipe(- Effect.timeout(CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT),- Effect.catchTag("TimeoutError", (cause) =>- Effect.fail(new CloudCliAuthorizationTimeoutError({ cause })),- ),- ),- terminal,- launchBrowser: externalLauncher.launchBrowser,- });- if (authorization._tag === "HeadlessRequested") {- return authorization;- }- const { token } = yield* exchangeToken(metadata, {- grant_type: "authorization_code",- code: authorization.code,- redirect_uri: metadata.redirectUri,- client_id: metadata.clientId,- code_verifier: verifier,- });- return { _tag: "Authorized", token } as const;- });-- const getExistingNoLock = Effect.fn("cloud.cli_token.get_existing_no_lock")(function* () {- const token = yield* read();- if (Option.isNone(token)) return token;- const now = yield* Clock.currentTimeMillis;- if (token.value.expiresAtEpochMs - CLOUD_CLI_OAUTH_REFRESH_EARLY_MS > now) {- return token;- }- return Option.some(yield* refresh(token.value).pipe(Effect.flatMap(persist)));- });-- const getExisting = semaphore.withPermits(1)(- getExistingNoLock().pipe(- Effect.mapError((cause) => new CloudCliCredentialRefreshError({ cause })),- Effect.provide(services),- ),- );- const hasCredential = semaphore.withPermits(1)(- read().pipe(- Effect.map(Option.isSome),- Effect.mapError((cause) => new CloudCliCredentialReadError({ cause })),- ),- );- const get = semaphore.withPermits(1)(- Effect.gen(function* () {- // A stored credential that can't be read or refreshed (corrupt, revoked,- // expired grant) must fall through to a fresh login rather than dead-end- // the command — authorizeCli applies the same fallback to out-of-band- // authorization.- const token = yield* getExistingNoLock().pipe(- Effect.orElseSucceed(() => Option.none<PersistedToken>()),- );- if (Option.isSome(token)) {- return { _tag: "Authorized", token: token.value } as const;- }- const authorization = yield* Effect.scoped(login());- return authorization._tag === "Authorized"- ? ({ _tag: "Authorized", token: yield* persist(authorization.token) } as const)- : authorization;- }).pipe(- Effect.mapError((cause) =>- Terminal.isQuitError(cause) ? cause : new CloudCliAuthorizationError({ cause }),- ),- Effect.provide(services),- ),- );- const store = Effect.fn("cloud.cli_token.store")(function* (token: PersistedToken) {- yield* semaphore.withPermits(1)(- persist(token).pipe(- Effect.asVoid,- Effect.mapError((cause) => new CloudCliAuthorizationError({ cause })),- ),- );- });-- return CloudCliTokenManager.of({ get, getExisting, hasCredential, store, clear });-});--export const layer = Layer.effect(CloudCliTokenManager, make);diff --git a/apps/server/src/cloud/ManagedEndpointRuntime.test.ts b/apps/server/src/cloud/ManagedEndpointRuntime.test.tsdeleted file mode 100644index b45b50992..000000000--- a/apps/server/src/cloud/ManagedEndpointRuntime.test.ts+++ /dev/null@@ -1,396 +0,0 @@-import { describe, expect, it } from "@effect/vitest";-import { vi } from "vite-plus/test";-import * as Deferred from "effect/Deferred";-import * as Effect from "effect/Effect";-import * as Fiber from "effect/Fiber";-import * as Layer from "effect/Layer";-import * as Option from "effect/Option";-import * as PlatformError from "effect/PlatformError";-import * as Sink from "effect/Sink";-import * as Stream from "effect/Stream";-import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";-import * as RelayClient from "@t3tools/shared/relayClient";--import * as ServerSecretStore from "../auth/ServerSecretStore.ts";-import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";--const relayClientAvailableLayer = Layer.succeed(- RelayClient.RelayClient,- RelayClient.RelayClient.of({- resolve: Effect.succeed({- status: "available",- executablePath: "cloudflared",- source: "path",- version: RelayClient.CLOUDFLARED_VERSION,- }),- install: Effect.die("unused"),- installWithProgress: () => Effect.die("unused"),- }),-);--const runtimeDependencies = (- spawner: ReturnType<typeof ChildProcessSpawner.make>,- relayClientLayer = relayClientAvailableLayer,-) =>- Layer.mergeAll(- Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),- relayClientLayer,- Layer.mock(ServerSecretStore.ServerSecretStore)({- get: () => Effect.succeed(Option.none()),- }),- );--const buildCloudManagedEndpointRuntime = (- spawner: ReturnType<typeof ChildProcessSpawner.make>,- relayClientLayer = relayClientAvailableLayer,-) =>- Effect.gen(function* () {- const context = yield* Layer.build(- ManagedEndpointRuntime.layer.pipe(- Layer.provide(runtimeDependencies(spawner, relayClientLayer)),- ),- );- return yield* Effect.service(ManagedEndpointRuntime.CloudManagedEndpointRuntime).pipe(- Effect.provide(context),- );- });--function makeHandle(input: {- readonly pid: number;- readonly onKill: () => void;- readonly isRunning?: () => boolean;- readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode>;-}) {- return ChildProcessSpawner.makeHandle({- pid: ChildProcessSpawner.ProcessId(input.pid),- exitCode: input.exitCode ?? Effect.never,- isRunning: Effect.sync(() => input.isRunning?.() ?? true),- kill: () =>- Effect.sync(() => {- input.onKill();- }),- unref: Effect.succeed(Effect.void),- stdin: Sink.drain,- stdout: Stream.empty,- stderr: Stream.empty,- all: Stream.empty,- getInputFd: () => Sink.drain,- getOutputFd: () => Stream.empty,- });-}--describe("CloudManagedEndpointRuntime", () => {- it("classifies Cloudflare connection and warning output", () => {- expect(- ManagedEndpointRuntime.classifyRelayClientOutput(- "2026-06-17T02:00:00Z INF Registered tunnel connection connIndex=0",- ),- ).toBe("connected");- expect(- ManagedEndpointRuntime.classifyRelayClientOutput(- "2026-06-17T02:00:00Z ERR Failed to serve tunnel connection",- ),- ).toBe("warning");- expect(- ManagedEndpointRuntime.classifyRelayClientOutput(- "2026-06-17T02:00:00Z INF Starting metrics server",- ),- ).toBe("debug");- // FTL (fatal) and PNC (panic) are more severe than ERR and must surface.- expect(- ManagedEndpointRuntime.classifyRelayClientOutput(- "2026-06-17T02:00:00Z FTL Cannot determine default origin certificate path",- ),- ).toBe("warning");- expect(- ManagedEndpointRuntime.classifyRelayClientOutput("2026-06-17T02:00:00Z PNC runtime panic"),- ).toBe("warning");- });-- it.effect("starts, deduplicates, rotates, and stops the Cloudflare connector", () =>- Effect.gen(function* () {- const spawned: Array<ChildProcess.StandardCommand> = [];- const killed: Array<number> = [];- let nextPid = 100;- const spawner = ChildProcessSpawner.make((command) =>- Effect.gen(function* () {- if (!ChildProcess.isStandardCommand(command)) {- throw new Error("Expected standard command.");- }- spawned.push(command);- const pid = nextPid;- nextPid += 1;- const handle = makeHandle({- pid,- onKill: () => {- killed.push(pid);- },- });- yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));- return handle;- }),- );- const runtime = yield* buildCloudManagedEndpointRuntime(spawner);-- yield* runtime.applyConfig({- providerKind: "cloudflare_tunnel",- connectorToken: "token-1",- tunnelId: "tunnel-1",- tunnelName: "t3-code-env-1",- });- yield* runtime.applyConfig({- providerKind: "cloudflare_tunnel",- connectorToken: "token-1",- tunnelId: "tunnel-1",- tunnelName: "t3-code-env-1",- });- yield* runtime.applyConfig({- providerKind: "cloudflare_tunnel",- connectorToken: "token-2",- tunnelId: "tunnel-1",- tunnelName: "t3-code-env-1",- });- const stopped = yield* runtime.applyConfig(null);-- expect(spawned.map((command) => command.command)).toEqual(["cloudflared", "cloudflared"]);- expect(spawned.map((command) => command.args)).toEqual([- ["tunnel", "run"],- ["tunnel", "run"],- ]);- expect(spawned.map((command) => command.options.env?.TUNNEL_TOKEN)).toEqual([- "token-1",- "token-2",- ]);- expect(spawned.map((command) => command.options.stdout)).toEqual(["pipe", "pipe"]);- expect(spawned.map((command) => command.options.stderr)).toEqual(["pipe", "pipe"]);- expect(spawned.map((command) => command.options.detached)).toEqual([false, false]);- expect(spawned.map((command) => command.options.shell)).toEqual([false, false]);- expect(killed).toEqual([100, 101]);- expect(stopped).toEqual({ status: "disabled" });- }),- );-- it.effect("stops an active connector when a non-Cloudflare runtime config is applied", () =>- Effect.gen(function* () {- const killed: Array<number> = [];- const spawner = ChildProcessSpawner.make(() =>- Effect.gen(function* () {- const handle = makeHandle({- pid: 200,- onKill: () => {- killed.push(200);- },- });- yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));- return handle;- }),- );- const runtime = yield* buildCloudManagedEndpointRuntime(spawner);-- const started = yield* runtime.applyConfig({- providerKind: "cloudflare_tunnel",- connectorToken: "token",- });- const unsupported = yield* runtime.applyConfig({- providerKind: "manual",- connectorToken: "manual-token",- });-- expect(started.status).toBe("running");- expect(unsupported).toEqual({ status: "unsupported", providerKind: "manual" });- expect(killed).toEqual([200]);- }),- );-- it.effect("restarts the connector when the active process has exited", () =>- Effect.gen(function* () {- const spawned: Array<number> = [];- const killed: Array<number> = [];- let firstRunning = true;- const spawner = ChildProcessSpawner.make(() =>- Effect.gen(function* () {- const pid = spawned.length === 0 ? 300 : 301;- spawned.push(pid);- const handle = makeHandle({- pid,- isRunning: () => (pid === 300 ? firstRunning : true),- onKill: () => {- killed.push(pid);- },- });- yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));- return handle;- }),- );- const runtime = yield* buildCloudManagedEndpointRuntime(spawner);- const config = {- providerKind: "cloudflare_tunnel" as const,- connectorToken: "token",- tunnelId: "tunnel-1",- };-- const first = yield* runtime.applyConfig(config);- firstRunning = false;- const second = yield* runtime.applyConfig(config);-- expect(first).toMatchObject({ status: "running", pid: 300 });- expect(second).toMatchObject({ status: "running", pid: 301 });- expect(spawned).toEqual([300, 301]);- expect(killed).toEqual([300]);- }),- );-- it.effect("supervises the active connector and restarts it after process exit", () =>- Effect.gen(function* () {- const spawned: Array<number> = [];- const killed: Array<number> = [];- const firstExit = yield* Deferred.make<ChildProcessSpawner.ExitCode>();- const secondSpawned = yield* Deferred.make<void>();- const spawner = ChildProcessSpawner.make(() =>- Effect.gen(function* () {- const pid = spawned.length === 0 ? 400 : 401;- spawned.push(pid);- if (pid === 401) {- yield* Deferred.succeed(secondSpawned, undefined);- }- const handle = makeHandle({- pid,- exitCode:- pid === 400- ? Deferred.await(firstExit)- : (Effect.never as Effect.Effect<ChildProcessSpawner.ExitCode>),- onKill: () => {- killed.push(pid);- },- });- yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));- return handle;- }),- );- const runtime = yield* buildCloudManagedEndpointRuntime(spawner);-- const started = yield* runtime.applyConfig({- providerKind: "cloudflare_tunnel",- connectorToken: "token",- tunnelId: "tunnel-1",- });- yield* Deferred.succeed(firstExit, ChildProcessSpawner.ExitCode(1));- yield* Deferred.await(secondSpawned);-- expect(started).toMatchObject({ status: "running", pid: 400 });- expect(spawned).toEqual([400, 401]);- expect(killed).toEqual([400]);- }),- );-- it.effect("serializes concurrent connector config changes", () =>- Effect.gen(function* () {- const spawned: Array<number> = [];- const killed: Array<number> = [];- const firstSpawnEntered = yield* Deferred.make<void>();- const releaseFirstSpawn = yield* Deferred.make<void>();- const spawner = ChildProcessSpawner.make(() =>- Effect.gen(function* () {- const pid = 500 + spawned.length;- spawned.push(pid);- if (pid === 500) {- yield* Deferred.succeed(firstSpawnEntered, undefined);- yield* Deferred.await(releaseFirstSpawn);- }- const handle = makeHandle({- pid,- onKill: () => {- killed.push(pid);- },- });- yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));- return handle;- }),- );- const runtime = yield* buildCloudManagedEndpointRuntime(spawner);-- const first = yield* runtime- .applyConfig({- providerKind: "cloudflare_tunnel",- connectorToken: "token-1",- })- .pipe(Effect.forkChild);- yield* Deferred.await(firstSpawnEntered);- const second = yield* runtime- .applyConfig({- providerKind: "cloudflare_tunnel",- connectorToken: "token-2",- })- .pipe(Effect.forkChild);- yield* Deferred.succeed(releaseFirstSpawn, undefined);-- yield* Fiber.join(first);- const status = yield* Fiber.join(second);-- expect(status).toMatchObject({ status: "running", pid: 501 });- expect(spawned).toEqual([500, 501]);- expect(killed).toEqual([500]);- }),- );-- it.effect("reports connector spawn failures", () =>- Effect.gen(function* () {- const spawner = ChildProcessSpawner.make(() =>- Effect.fail(- PlatformError.systemError({- _tag: "NotFound",- module: "ChildProcess",- method: "spawn",- description: "cloudflared missing",- }),- ),- );- const runtime = yield* buildCloudManagedEndpointRuntime(spawner);-- const status = yield* runtime.applyConfig({- providerKind: "cloudflare_tunnel",- connectorToken: "token",- tunnelId: "tunnel-1",- });-- expect(status).toMatchObject({- status: "failed",- providerKind: "cloudflare_tunnel",- tunnelId: "tunnel-1",- });- }),- );-- it.effect("reports a missing relay client executable without spawning", () =>- Effect.gen(function* () {- const spawn = vi.fn();- const spawner = ChildProcessSpawner.make(spawn);- const runtime = yield* buildCloudManagedEndpointRuntime(- spawner,- Layer.succeed(- RelayClient.RelayClient,- RelayClient.RelayClient.of({- resolve: Effect.succeed({- status: "missing",- version: RelayClient.CLOUDFLARED_VERSION,- }),- install: Effect.die("unused"),- installWithProgress: () => Effect.die("unused"),- }),- ),- );-- const status = yield* runtime.applyConfig({- providerKind: "cloudflare_tunnel",- connectorToken: "token",- });-- expect(status).toEqual({- status: "failed",- providerKind: "cloudflare_tunnel",- reason: "The relay client is not installed.",- });- expect(spawn).not.toHaveBeenCalled();- }),- );-});diff --git a/apps/server/src/cloud/ManagedEndpointRuntime.ts b/apps/server/src/cloud/ManagedEndpointRuntime.tsdeleted file mode 100644index eca417977..000000000--- a/apps/server/src/cloud/ManagedEndpointRuntime.ts+++ /dev/null@@ -1,322 +0,0 @@-import type { RelayManagedEndpointRuntimeConfig } from "@t3tools/contracts/relay";-import * as RelayClient from "@t3tools/shared/relayClient";-import * as Context from "effect/Context";-import * as Effect from "effect/Effect";-import * as Exit from "effect/Exit";-import * as Layer from "effect/Layer";-import * as Option from "effect/Option";-import * as Ref from "effect/Ref";-import * as Result from "effect/Result";-import * as Semaphore from "effect/Semaphore";-import * as Scope from "effect/Scope";-import * as Stream from "effect/Stream";-import * as ChildProcess from "effect/unstable/process/ChildProcess";-import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";--import * as ServerSecretStore from "../auth/ServerSecretStore.ts";-import { CLOUD_ENDPOINT_RUNTIME_CONFIG, decodeRuntimeConfig } from "./config.ts";--function bytesToString(bytes: Uint8Array): string {- return new TextDecoder().decode(bytes);-}--const readRuntimeConfig = Effect.gen(function* () {- const secrets = yield* ServerSecretStore.ServerSecretStore;- const bytes = yield* secrets.get(CLOUD_ENDPOINT_RUNTIME_CONFIG);- if (Option.isNone(bytes)) {- return null;- }- return Option.getOrNull(decodeRuntimeConfig(bytesToString(bytes.value)));-});--export type CloudManagedEndpointRuntimeStatus =- | {- readonly status: "disabled";- }- | {- readonly status: "failed";- readonly providerKind: RelayManagedEndpointRuntimeConfig["providerKind"];- readonly reason: string;- readonly tunnelId?: string;- readonly tunnelName?: string;- }- | {- readonly status: "running";- readonly providerKind: "cloudflare_tunnel";- readonly pid: number;- readonly tunnelId?: string;- readonly tunnelName?: string;- }- | {- readonly status: "unsupported";- readonly providerKind: RelayManagedEndpointRuntimeConfig["providerKind"];- };--export class CloudManagedEndpointRuntime extends Context.Service<- CloudManagedEndpointRuntime,- {- readonly applyConfig: (- config: RelayManagedEndpointRuntimeConfig | null,- ) => Effect.Effect<CloudManagedEndpointRuntimeStatus>;- }->()("akeru-bot/cloud/ManagedEndpointRuntime/CloudManagedEndpointRuntime") {}--interface ActiveConnector {- readonly child: ChildProcessSpawner.ChildProcessHandle;- readonly scope: Scope.Closeable;- readonly configKey: string;- readonly config: RelayManagedEndpointRuntimeConfig;-}--export function classifyRelayClientOutput(line: string): "connected" | "warning" | "debug" {- if (/\bRegistered tunnel connection\b/iu.test(line)) {- return "connected";- }- // cloudflared uses zerolog level tokens. FTL (fatal) and PNC (panic) are more- // severe than ERR, so they must surface at least as loudly — without them a- // fatal connector failure would be logged at debug and hidden.- return /\b(?:ERR|WRN|FTL|PNC)\b/u.test(line) ? "warning" : "debug";-}--function runtimeConfigKey(config: RelayManagedEndpointRuntimeConfig): string {- return JSON.stringify({- providerKind: config.providerKind,- connectorToken: config.connectorToken,- tunnelId: config.tunnelId ?? null,- tunnelName: config.tunnelName ?? null,- });-}--const stopConnector = (connector: ActiveConnector | null) =>- connector- ? Scope.close(connector.scope, Exit.void).pipe(- Effect.tap(() =>- Effect.logInfo("Relay client stopped", {- pid: Number(connector.child.pid),- }),- ),- Effect.ignore,- )- : Effect.void;--export const make = Effect.gen(function* () {- const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;- const relayClient = yield* RelayClient.RelayClient;- const activeRef = yield* Ref.make<ActiveConnector | null>(null);- const desiredConfigRef = yield* Ref.make<RelayManagedEndpointRuntimeConfig | null>(null);- const reconcileSemaphore = yield* Semaphore.make(1);- let reconcileConfig: CloudManagedEndpointRuntime["Service"]["applyConfig"];-- const stopActive = Effect.gen(function* () {- const active = yield* Ref.getAndSet(activeRef, null);- yield* stopConnector(active);- });-- const superviseConnector = (connector: ActiveConnector) =>- Effect.gen(function* () {- const result = yield* Effect.result(connector.child.exitCode);- yield* reconcileSemaphore.withPermits(1)(- Effect.gen(function* () {- const active = yield* Ref.get(activeRef);- if (- active?.child.pid !== connector.child.pid ||- active.configKey !== connector.configKey- ) {- return;- }- yield* Ref.set(activeRef, null);- yield* stopConnector(connector);-- const desiredConfig = yield* Ref.get(desiredConfigRef);- if (- !desiredConfig ||- desiredConfig.providerKind !== "cloudflare_tunnel" ||- runtimeConfigKey(desiredConfig) !== connector.configKey- ) {- return;- }-- yield* Effect.logWarning("Relay client exited; restarting", {- pid: Number(connector.child.pid),- ...(Result.isSuccess(result)- ? { exitCode: Number(result.success) }- : { cause: result.failure }),- tunnelId: connector.config.tunnelId,- tunnelName: connector.config.tunnelName,- });- yield* reconcileConfig(desiredConfig);- }),- );- }).pipe(- Effect.catchCause((cause) => Effect.logWarning("Relay client supervisor failed", { cause })),- );-- const observeConnectorOutput = (connector: ActiveConnector) =>- connector.child.all.pipe(- Stream.decodeText(),- Stream.splitLines,- Stream.map((line) => line.trim()),- Stream.filter((line) => line.length > 0),- Stream.runForEach((line) => {- const output = line.replaceAll(connector.config.connectorToken, "<redacted>");- const attributes = {- pid: Number(connector.child.pid),- tunnelId: connector.config.tunnelId,- tunnelName: connector.config.tunnelName,- output,- };- switch (classifyRelayClientOutput(line)) {- case "connected":- return Effect.logInfo("Relay client tunnel connection registered", attributes);- case "warning":- return Effect.logWarning("Relay client reported a transport warning", attributes);- case "debug":- return Effect.logDebug("Relay client output", attributes);- }- }),- Effect.catchCause((cause) =>- Effect.logWarning("Relay client output observer failed", {- cause,- pid: Number(connector.child.pid),- tunnelId: connector.config.tunnelId,- tunnelName: connector.config.tunnelName,- }),- ),- );-- reconcileConfig = Effect.fn("CloudManagedEndpointRuntime.reconcileConfig")(function* (config) {- if (!config || config.providerKind !== "cloudflare_tunnel") {- yield* stopActive;- return config- ? { status: "unsupported", providerKind: config.providerKind }- : { status: "disabled" };- }-- const nextConfigKey = runtimeConfigKey(config);- const active = yield* Ref.get(activeRef);- if (active?.configKey === nextConfigKey) {- const isRunning = yield* active.child.isRunning.pipe(Effect.orElseSucceed(() => false));- if (isRunning) {- return {- status: "running",- providerKind: "cloudflare_tunnel",- pid: Number(active.child.pid),- ...(active.config.tunnelId ? { tunnelId: active.config.tunnelId } : {}),- ...(active.config.tunnelName ? { tunnelName: active.config.tunnelName } : {}),- } satisfies CloudManagedEndpointRuntimeStatus;- }- }-- yield* stopActive;-- const executable = yield* relayClient.resolve;- if (executable.status !== "available") {- return {- status: "failed",- providerKind: "cloudflare_tunnel",- reason:- executable.status === "unsupported"- ? `Relay client is unsupported on ${executable.platform}-${executable.arch}.`- : "The relay client is not installed.",- ...(config.tunnelId ? { tunnelId: config.tunnelId } : {}),- ...(config.tunnelName ? { tunnelName: config.tunnelName } : {}),- } satisfies CloudManagedEndpointRuntimeStatus;- }-- const connectorScope = yield* Scope.make("sequential");- const child = yield* spawner- .spawn(- ChildProcess.make(executable.executablePath, ["tunnel", "run"], {- detached: false,- env: {- ...process.env,- TUNNEL_TOKEN: config.connectorToken,- },- shell: false,- stderr: "pipe",- stdout: "pipe",- }),- )- .pipe(- Effect.provideService(Scope.Scope, connectorScope),- Effect.tap((child) =>- Effect.logInfo("Relay client process started; waiting for tunnel connection", {- pid: Number(child.pid),- tunnelId: config.tunnelId,- tunnelName: config.tunnelName,- }),- ),- Effect.catch((cause) =>- Effect.logWarning("Failed to start relay client", {- cause,- tunnelId: config.tunnelId,- tunnelName: config.tunnelName,- }).pipe(- Effect.andThen(Scope.close(connectorScope, Exit.void).pipe(Effect.ignore)),- Effect.as({- status: "failed",- providerKind: "cloudflare_tunnel",- reason: String(cause),- ...(config.tunnelId ? { tunnelId: config.tunnelId } : {}),- ...(config.tunnelName ? { tunnelName: config.tunnelName } : {}),- } satisfies CloudManagedEndpointRuntimeStatus),- ),- ),- );-- if ("status" in child && child.status === "failed") {- return child;- }-- if (!("status" in child)) {- const connector = {- child,- scope: connectorScope,- configKey: nextConfigKey,- config,- } satisfies ActiveConnector;- yield* Ref.set(activeRef, connector);- yield* Effect.forkIn(observeConnectorOutput(connector), connectorScope);- yield* Effect.forkIn(superviseConnector(connector), connectorScope);- return {- status: "running",- providerKind: "cloudflare_tunnel",- pid: Number(child.pid),- ...(config.tunnelId ? { tunnelId: config.tunnelId } : {}),- ...(config.tunnelName ? { tunnelName: config.tunnelName } : {}),- } satisfies CloudManagedEndpointRuntimeStatus;- }-- return {- status: "failed",- providerKind: "cloudflare_tunnel",- reason: "Relay client did not start.",- ...(config.tunnelId ? { tunnelId: config.tunnelId } : {}),- ...(config.tunnelName ? { tunnelName: config.tunnelName } : {}),- } satisfies CloudManagedEndpointRuntimeStatus;- });-- const applyConfig = Effect.fn("CloudManagedEndpointRuntime.applyConfig")(- (config: RelayManagedEndpointRuntimeConfig | null) =>- reconcileSemaphore.withPermits(1)(- Ref.set(desiredConfigRef, config).pipe(Effect.andThen(reconcileConfig(config))),- ),- );-- const runtime = CloudManagedEndpointRuntime.of({- applyConfig,- });-- const initialConfig = yield* readRuntimeConfig.pipe(- Effect.catch((cause) =>- Effect.logWarning("Failed to read managed endpoint runtime config", { cause }).pipe(- Effect.as(null),- ),- ),- );- yield* runtime.applyConfig(initialConfig);- yield* Effect.addFinalizer(() => runtime.applyConfig(null));- return runtime;-});--export const layer = Layer.effect(CloudManagedEndpointRuntime, make);diff --git a/apps/server/src/cloud/cliAuthHtml.test.ts b/apps/server/src/cloud/cliAuthHtml.test.tsdeleted file mode 100644index 1104927b9..000000000--- a/apps/server/src/cloud/cliAuthHtml.test.ts+++ /dev/null@@ -1,31 +0,0 @@-import { expect, it } from "@effect/vitest";--import {- renderLoopbackAuthorizationCompleteHtml,- resolveLoopbackAuthorizationStage,-} from "./cliAuthHtml.ts";--it("renders the branded loopback authorization completion page", () => {- const html = renderLoopbackAuthorizationCompleteHtml();-- expect(resolveLoopbackAuthorizationStage()).toBe("dev");- expect(html).toContain("T3 Code (Dev)");- expect(html).toContain('class="stage stage-dev"');- expect(html).not.toContain("Secure terminal handoff");- expect(html).toContain("You're connected");- expect(html).toContain("Return to your terminal");- expect(html).not.toContain('class="next"');- expect(html).toContain('name="viewport"');- expect(html).not.toContain('class="status"');-});--it("renders the matching header treatment for each release channel", () => {- const nightly = renderLoopbackAuthorizationCompleteHtml("nightly");- const latest = renderLoopbackAuthorizationCompleteHtml("latest");-- expect(nightly).toContain("T3 Code (Nightly)");- expect(nightly).toContain('class="stage stage-nightly"');- expect(latest).toContain('<p class="brand">T3 Code</p>');- expect(latest).not.toContain("(Latest)");- expect(latest).toContain('class="stage stage-latest"');-});diff --git a/apps/server/src/cloud/cliAuthHtml.ts b/apps/server/src/cloud/cliAuthHtml.tsdeleted file mode 100644index 5a22a2599..000000000--- a/apps/server/src/cloud/cliAuthHtml.ts+++ /dev/null@@ -1,155 +0,0 @@-export type LoopbackAuthorizationStage = "dev" | "nightly" | "latest";--declare const __T3CODE_BUILD_CHANNEL__: "nightly" | "latest" | undefined;--export function resolveLoopbackAuthorizationStage(): LoopbackAuthorizationStage {- return typeof __T3CODE_BUILD_CHANNEL__ === "undefined" ? "dev" : __T3CODE_BUILD_CHANNEL__;-}--const stageBrands = {- dev: "T3 Code (Dev)",- nightly: "T3 Code (Nightly)",- latest: "T3 Code",-} as const satisfies Record<LoopbackAuthorizationStage, string>;--export function renderLoopbackAuthorizationCompleteHtml(- stage: LoopbackAuthorizationStage = resolveLoopbackAuthorizationStage(),-): string {- const stageBrand = stageBrands[stage];-- return `<!doctype html>-<html lang="en">- <head>- <meta charset="utf-8" />- <meta name="viewport" content="width=device-width, initial-scale=1" />- <meta name="color-scheme" content="light dark" />- <title>T3 Connect authorization complete</title>- <style>- :root {- color-scheme: light dark;- font-family: ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;- background: #f6f7f9;- color: #17191f;- }- * { box-sizing: border-box; }- body {- min-height: 100vh;- margin: 0;- display: grid;- place-items: center;- padding: 32px 16px;- background:- radial-gradient(48rem 22rem at 50% -8rem, rgba(47, 119, 235, 0.15), transparent),- #f6f7f9;- }- main {- width: min(100%, 576px);- overflow: hidden;- border: 1px solid rgba(23, 25, 31, 0.1);- border-radius: 20px;- background: rgba(255, 255, 255, 0.94);- box-shadow: 0 24px 64px rgba(16, 24, 40, 0.16);- }- .stage {- position: relative;- height: 96px;- overflow: hidden;- padding: 22px 24px;- color: white;- }- .stage-latest {- background:- radial-gradient(circle at 76% 18%, rgba(136, 204, 255, 0.52), transparent 38%),- linear-gradient(135deg, #2468df, #172f82);- }- .stage-dev {- background: linear-gradient(145deg, #5ab8fa 0%, #347ff8 46%, #1939bd 100%);- }- .stage-dev::before {- content: "";- position: absolute;- inset: 0;- opacity: 0.42;- background-image:- linear-gradient(rgba(234, 246, 255, 0.25) 1px, transparent 1px),- linear-gradient(90deg, rgba(234, 246, 255, 0.25) 1px, transparent 1px),- linear-gradient(rgba(234, 246, 255, 0.12) 1px, transparent 1px),- linear-gradient(90deg, rgba(234, 246, 255, 0.12) 1px, transparent 1px);- background-size: 32px 32px, 32px 32px, 8px 8px, 8px 8px;- }- .stage-nightly {- background:- radial-gradient(22rem 8rem at 78% 18%, rgba(81, 101, 216, 0.42), transparent 58%),- linear-gradient(145deg, #07152f 0%, #151443 52%, #32155b 100%);- }- .stage-nightly::before {- content: "";- position: absolute;- inset: 0;- opacity: 0.78;- background-image:- radial-gradient(circle at 12px 12px, rgba(228, 234, 255, 0.9) 0 1px, transparent 1.5px),- radial-gradient(circle at 38px 28px, rgba(228, 234, 255, 0.58) 0 0.8px, transparent 1.3px),- radial-gradient(circle at 58px 9px, rgba(200, 215, 255, 0.72) 0 0.9px, transparent 1.4px);- background-size: 72px 48px, 96px 64px, 128px 56px;- }- .stage::after {- content: "";- position: absolute;- inset: 0;- background:- radial-gradient(circle at 78% 20%, rgba(210, 255, 255, 0.36), transparent 34%),- linear-gradient(to bottom, transparent 24%, rgba(8, 28, 89, 0.38));- }- .stage-content {- position: relative;- z-index: 1;- height: 100%;- display: flex;- align-items: center;- justify-content: space-between;- }- .brand {- margin: 0;- font-size: 10px;- font-weight: 700;- letter-spacing: 0.2em;- text-transform: uppercase;- }- .brand { color: rgba(255, 255, 255, 0.82); }- .content { padding: 30px 32px 34px; }- .eyebrow {- margin: 0 0 8px;- color: #2866cc;- font-size: 10px;- font-weight: 700;- letter-spacing: 0.18em;- text-transform: uppercase;- }- h1 { margin: 0; font-size: clamp(26px, 5vw, 34px); line-height: 1.12; letter-spacing: -0.035em; }- .description { margin: 12px 0 0; color: #646975; font-size: 15px; line-height: 1.6; }- @media (prefers-color-scheme: dark) {- :root { background: #101115; color: #f1f3f7; }- body { background: radial-gradient(48rem 22rem at 50% -8rem, rgba(55, 102, 210, 0.2), transparent), #101115; }- main { border-color: rgba(255, 255, 255, 0.1); background: rgba(25, 27, 33, 0.96); }- .eyebrow { color: #77a8ff; }- .description { color: #a8adb8; }- }- </style>- </head>- <body>- <main>- <header class="stage stage-${stage}" data-stage="${stage}">- <div class="stage-content">- <p class="brand">${stageBrand}</p>- </div>- </header>- <section class="content">- <p class="eyebrow">Browser authorization complete</p>- <h1>You're connected</h1>- <p class="description">Return to your terminal to finish setting up T3 Connect. You can close this window.</p>- </section>- </main>- </body>-</html>`;-}diff --git a/apps/server/src/cloud/config.ts b/apps/server/src/cloud/config.tsdeleted file mode 100644index 2eff693f6..000000000--- a/apps/server/src/cloud/config.ts+++ /dev/null@@ -1,58 +0,0 @@-import { RelayManagedEndpointRuntimeConfig } from "@t3tools/contracts/relay";-import * as Effect from "effect/Effect";-import * as Option from "effect/Option";-import * as Schema from "effect/Schema";--import type * as ServerSecretStore from "../auth/ServerSecretStore.ts";--export const CLOUD_MINT_PUBLIC_KEY = "cloud-mint-ed25519-public-key";-export const CLOUD_ENDPOINT_RUNTIME_CONFIG = "cloud-endpoint-runtime-config";-export const CLOUD_LINKED_USER_ID = "cloud-linked-user-id";-export const RELAY_URL_SECRET = "cloud-relay-url";-export const RELAY_ISSUER_SECRET = "cloud-relay-issuer";-export const RELAY_ENVIRONMENT_CREDENTIAL_SECRET = "cloud-relay-environment-credential";-export const PUBLISH_AGENT_ACTIVITY_SECRET = "cloud-publish-agent-activity";--export const encodeEndpointRuntimeConfigJson = Schema.encodeEffect(- Schema.fromJsonString(RelayManagedEndpointRuntimeConfig),-);--export const decodeRuntimeConfig = Schema.decodeUnknownOption(- Schema.fromJsonString(RelayManagedEndpointRuntimeConfig),-);--export function isAgentActivityPublishingEnabledValue(value: string | null): boolean {- return value === "true";-}--/** Whether agent-activity publishes currently leave this environment: the- publish opt-in secret is enabled and the relay link credentials exist.- Mirrors the per-publish gate in AgentAwarenessRelay, so the descriptor- capability never advertises publishing that the publisher would skip. */-export const readAgentActivityPublishingActive = (- secrets: ServerSecretStore.ServerSecretStore["Service"],-): Effect.Effect<boolean> =>- Effect.gen(function* () {- const readSecretString = (name: string) =>- secrets- .get(name)- .pipe(- Effect.map((bytes) =>- Option.isSome(bytes) ? new TextDecoder().decode(bytes.value) : null,- ),- );- const [enabled, url, environmentCredential] = yield* Effect.all([- readSecretString(PUBLISH_AGENT_ACTIVITY_SECRET),- readSecretString(RELAY_URL_SECRET),- readSecretString(RELAY_ENVIRONMENT_CREDENTIAL_SECRET),- ]);- // Empty strings are as unconfigured as missing files: the publisher's- // truthiness gate skips them, so the capability must too.- return (- isAgentActivityPublishingEnabledValue(enabled) &&- url !== null &&- url !== "" &&- environmentCredential !== null &&- environmentCredential !== ""- );- }).pipe(Effect.orElseSucceed(() => false));diff --git a/apps/server/src/cloud/environmentKeys.test.ts b/apps/server/src/cloud/environmentKeys.test.tsdeleted file mode 100644index 48c44ccc4..000000000--- a/apps/server/src/cloud/environmentKeys.test.ts+++ /dev/null@@ -1,90 +0,0 @@-import * as NodeServices from "@effect/platform-node/NodeServices";-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 PlatformError from "effect/PlatformError";--import * as ServerSecretStore from "../auth/ServerSecretStore.ts";-import * as ServerConfig from "../config.ts";-import { getOrCreateEnvironmentKeyPairFromSecretStore } from "./environmentKeys.ts";--const makeServerSecretStoreLayer = () =>- ServerSecretStore.layer.pipe(- Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-environment-keys-test-" })),- );--const unusedSecretStoreOperation = () => Effect.die("unused secret-store operation");--it.layer(NodeServices.layer)("getOrCreateEnvironmentKeyPairFromSecretStore", (it) => {- it.effect("persists one atomic keypair secret and reuses it", () =>- Effect.gen(function* () {- const secretStore = yield* ServerSecretStore.ServerSecretStore;-- const first = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secretStore);- const second = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secretStore);-- assert.deepEqual(second, first);- assert.isTrue(Option.isSome(yield* secretStore.get("cloud-link-ed25519-key-pair")));- assert.isTrue(Option.isNone(yield* secretStore.get("cloud-link-ed25519-private-key")));- assert.isTrue(Option.isNone(yield* secretStore.get("cloud-link-ed25519-public-key")));- }).pipe(Effect.provide(makeServerSecretStoreLayer())),- );-- it.effect("migrates a legacy keypair into the atomic secret", () =>- Effect.gen(function* () {- const secretStore = yield* ServerSecretStore.ServerSecretStore;- yield* secretStore.set("cloud-link-ed25519-private-key", new TextEncoder().encode("private"));- yield* secretStore.set("cloud-link-ed25519-public-key", new TextEncoder().encode("public"));-- assert.deepEqual(yield* getOrCreateEnvironmentKeyPairFromSecretStore(secretStore), {- privateKey: "private",- publicKey: "public",- });- assert.isTrue(Option.isSome(yield* secretStore.get("cloud-link-ed25519-key-pair")));- }).pipe(Effect.provide(makeServerSecretStoreLayer())),- );-- it.effect("uses the persisted keypair when a concurrent creator wins", () =>- Effect.gen(function* () {- const winner = new TextEncoder().encode(- '{"privateKey":"winner-private","publicKey":"winner-public"}',- );- let createAttempted = false;- const secretStore = {- get: (name) =>- Effect.sync(() =>- name === "cloud-link-ed25519-key-pair" && createAttempted- ? Option.some(winner)- : Option.none(),- ),- set: unusedSecretStoreOperation,- create: () =>- Effect.sync(() => {- createAttempted = true;- }).pipe(- Effect.flatMap(() =>- Effect.fail(- new ServerSecretStore.SecretStorePersistError({- resource: "environment signing key pair",- cause: PlatformError.systemError({- _tag: "AlreadyExists",- module: "FileSystem",- method: "open",- pathOrDescriptor: "cloud-link-ed25519-key-pair.bin",- }),- }),- ),- ),- ),- getOrCreateRandom: unusedSecretStoreOperation,- remove: unusedSecretStoreOperation,- } satisfies ServerSecretStore.ServerSecretStore["Service"];-- assert.deepEqual(yield* getOrCreateEnvironmentKeyPairFromSecretStore(secretStore), {- privateKey: "winner-private",- publicKey: "winner-public",- });- }),- );-});diff --git a/apps/server/src/cloud/environmentKeys.ts b/apps/server/src/cloud/environmentKeys.tsdeleted file mode 100644index 1d0cde91b..000000000--- a/apps/server/src/cloud/environmentKeys.ts+++ /dev/null@@ -1,103 +0,0 @@-import * as NodeCrypto from "node:crypto";-import * as Effect from "effect/Effect";-import * as Option from "effect/Option";-import * as Schema from "effect/Schema";--import * as ServerSecretStore from "../auth/ServerSecretStore.ts";--const CLOUD_LINK_KEY_PAIR = "cloud-link-ed25519-key-pair";-const CLOUD_LINK_PRIVATE_KEY = "cloud-link-ed25519-private-key";-const CLOUD_LINK_PUBLIC_KEY = "cloud-link-ed25519-public-key";--const EnvironmentKeyPair = Schema.Struct({- privateKey: Schema.String,- publicKey: Schema.String,-});-type EnvironmentKeyPair = typeof EnvironmentKeyPair.Type;--const EnvironmentKeyPairJson = Schema.fromJsonString(EnvironmentKeyPair);-const decodeEnvironmentKeyPair = Schema.decodeUnknownEffect(EnvironmentKeyPairJson);-const encodeEnvironmentKeyPair = Schema.encodeEffect(EnvironmentKeyPairJson);--function bytesToString(bytes: Uint8Array): string {- return new TextDecoder().decode(bytes);-}--function stringToBytes(value: string): Uint8Array {- return new TextEncoder().encode(value);-}--const KEY_PAIR_RESOURCE = "environment signing key pair";--const keyPairDecodeError = (cause: unknown): ServerSecretStore.SecretStoreDecodeError =>- new ServerSecretStore.SecretStoreDecodeError({ resource: KEY_PAIR_RESOURCE, cause });--const keyPairEncodeError = (cause: unknown): ServerSecretStore.SecretStoreEncodeError =>- new ServerSecretStore.SecretStoreEncodeError({ resource: KEY_PAIR_RESOURCE, cause });--const keyPairConcurrentReadError = (): ServerSecretStore.SecretStoreConcurrentReadError =>- new ServerSecretStore.SecretStoreConcurrentReadError({ resource: KEY_PAIR_RESOURCE });--const readEnvironmentKeyPair = Effect.fn("readEnvironmentKeyPair")(function* (- secrets: ServerSecretStore.ServerSecretStore["Service"],-) {- const encoded = yield* secrets.get(CLOUD_LINK_KEY_PAIR);- if (Option.isNone(encoded)) {- return Option.none<EnvironmentKeyPair>();- }- const decoded = yield* decodeEnvironmentKeyPair(bytesToString(encoded.value)).pipe(- Effect.mapError(keyPairDecodeError),- );- return Option.some(decoded);-});--const persistEnvironmentKeyPair = Effect.fn("persistEnvironmentKeyPair")(function* (- secrets: ServerSecretStore.ServerSecretStore["Service"],- keyPair: EnvironmentKeyPair,-) {- const encoded = yield* encodeEnvironmentKeyPair(keyPair).pipe(- Effect.mapError(keyPairEncodeError),- );- return yield* secrets.create(CLOUD_LINK_KEY_PAIR, stringToBytes(encoded)).pipe(- Effect.as(keyPair),- Effect.catchIf(ServerSecretStore.isSecretStoreError, (error) =>- ServerSecretStore.isSecretAlreadyExistsError(error)- ? readEnvironmentKeyPair(secrets).pipe(- Effect.flatMap(- Option.match({- onSome: Effect.succeed,- onNone: () => Effect.fail(keyPairConcurrentReadError()),- }),- ),- )- : Effect.fail(error),- ),- );-});--export const getOrCreateEnvironmentKeyPairFromSecretStore = Effect.fn(function* (- secrets: ServerSecretStore.ServerSecretStore["Service"],-) {- const existing = yield* readEnvironmentKeyPair(secrets);- if (Option.isSome(existing)) {- return existing.value;- }-- const existingPrivate = yield* secrets.get(CLOUD_LINK_PRIVATE_KEY);- const existingPublic = yield* secrets.get(CLOUD_LINK_PUBLIC_KEY);- if (Option.isSome(existingPrivate) && Option.isSome(existingPublic)) {- return yield* persistEnvironmentKeyPair(secrets, {- privateKey: bytesToString(existingPrivate.value),- publicKey: bytesToString(existingPublic.value),- });- }-- const keyPair = NodeCrypto.generateKeyPairSync("ed25519", {- privateKeyEncoding: { format: "pem", type: "pkcs8" },- publicKeyEncoding: { format: "pem", type: "spki" },- });- return yield* persistEnvironmentKeyPair(secrets, {- privateKey: keyPair.privateKey,- publicKey: keyPair.publicKey,- });-});diff --git a/apps/server/src/cloud/http.test.ts b/apps/server/src/cloud/http.test.tsdeleted file mode 100644index 82da77118..000000000--- a/apps/server/src/cloud/http.test.ts+++ /dev/null@@ -1,611 +0,0 @@-import * as NodeServices from "@effect/platform-node/NodeServices";-import { describe, expect, it } from "@effect/vitest";-import * as Effect from "effect/Effect";-import * as FileSystem from "effect/FileSystem";-import * as Layer from "effect/Layer";-import * as Option from "effect/Option";-import * as Path from "effect/Path";-import * as PlatformError from "effect/PlatformError";-import * as Tracer from "effect/Tracer";-import {- HttpClient,- HttpClientResponse,- HttpServerRequest,- type HttpClientRequest,-} from "effect/unstable/http";--import { EnvironmentId } from "@t3tools/contracts";-import { RelayClientTracer } from "@t3tools/shared/relayTracing";-import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";-import * as ServerSecretStore from "../auth/ServerSecretStore.ts";-import * as ServerConfigModule from "../config.ts";-import { writeServiceState } from "../serviceLauncher.ts";-import {- SERVICE_LAUNCHER_PROTOCOL,- SERVICE_STATE_FILE,- SERVICE_STOP_MARKER_FILE,- type ServiceUpdateRecord,-} from "./serviceProtocol.ts";-import * as ServerEnvironment from "../environment/ServerEnvironment.ts";-import { CLOUD_CLI_DESIRED_LINK_SECRET } from "./CliState.ts";-import * as CliTokenManager from "./CliTokenManager.ts";-import type { RelayLinkProofRequest } from "@t3tools/contracts/relay";-import { CLOUD_ENDPOINT_RUNTIME_CONFIG, RELAY_URL_SECRET } from "./config.ts";-import {- consumeCloudReplayGuards,- isSupportedLinkProviderKind,- linkProofScopes,- pendingServiceUpdateExists,- reconcileDesiredCloudLink,- releaseManagedTunnelOnShutdown,-} from "./http.ts";-import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";-import { traceAuthenticatedRelayRequest, traceRelayRequest } from "./traceRelayRequest.ts";--const storeFailure = (tag: "AlreadyExists" | "PermissionDenied") =>- new ServerSecretStore.SecretStorePersistError({- resource: "cloud replay guard",- cause: PlatformError.systemError({- _tag: tag,- module: "FileSystem",- method: "open",- pathOrDescriptor: "cloud-replay-guard.bin",- }),- });--const unusedSecretStoreOperation = () => Effect.die("unused secret-store operation");--function makeSecretStore(- create: ServerSecretStore.ServerSecretStore["Service"]["create"],-): ServerSecretStore.ServerSecretStore["Service"] {- return {- get: unusedSecretStoreOperation,- set: unusedSecretStoreOperation,- create,- getOrCreateRandom: unusedSecretStoreOperation,- remove: unusedSecretStoreOperation,- };-}--it("preserves messages surfaced by cloud 500 responses", () => {- const cause = new Error("cloud operation failed");-- expect([- new EnvironmentAuth.ServerAuthLinkedCloudAccountVerificationError({ cause }).message,- new EnvironmentAuth.ServerAuthLinkedCloudAccountReadError({ cause }).message,- new EnvironmentAuth.ServerAuthLinkedCloudAccountMissingError({}).message,- new EnvironmentAuth.ServerAuthCloudLinkJwtSigningError({ cause }).message,- new EnvironmentAuth.ServerAuthCloudMintPublicKeyMissingError({}).message,- new EnvironmentAuth.ServerAuthCloudRelayIssuerMissingError({}).message,- new EnvironmentAuth.ServerAuthCloudHealthJwtSigningError({ cause }).message,- new EnvironmentAuth.ServerAuthCloudMintJwtSigningError({ cause }).message,- ]).toEqual([- "Could not verify the linked cloud account.",- "Could not read the linked cloud account.",- "Cloud linked user is not installed for this environment.",- "Failed to sign cloud link JWT.",- "Cloud mint public key is not installed for this environment.",- "Cloud relay issuer is not installed for this environment.",- "Failed to sign cloud health JWT.",- "Failed to sign cloud mint JWT.",- ]);-});--describe("consumeCloudReplayGuards", () => {- it.effect("reports already-created guards as replay conflicts", () =>- Effect.gen(function* () {- const consumed = yield* consumeCloudReplayGuards({- secrets: makeSecretStore(() => Effect.fail(storeFailure("AlreadyExists"))),- names: ["cloud-jti", "cloud-nonce"],- value: new Uint8Array(),- });-- expect(consumed).toBe(false);- }),- );-- it.effect("preserves replay-store availability failures", () =>- Effect.gen(function* () {- const failure = storeFailure("PermissionDenied");- const error = yield* Effect.flip(- consumeCloudReplayGuards({- secrets: makeSecretStore(() => Effect.fail(failure)),- names: ["cloud-jti", "cloud-nonce"],- value: new Uint8Array(),- }),- );-- expect(error).toBe(failure);- }),- );-});--describe("relay request tracing", () => {- it.effect("does not accept an unauthenticated request trace parent", () =>- Effect.gen(function* () {- const spans: Array<Tracer.Span> = [];- const productTracer = Tracer.make({- span: (options) => {- const span = new Tracer.NativeSpan(options);- spans.push(span);- return span;- },- });- const request = HttpServerRequest.fromWeb(- new Request("https://environment.example.test/api/t3-cloud/mint-credential", {- headers: {- traceparent: "00-0123456789abcdef0123456789abcdef-0123456789abcdef-01",- },- }),- );-- yield* traceRelayRequest(Effect.void.pipe(Effect.withSpan("relay.mint.handler"))).pipe(- Effect.provideService(HttpServerRequest.HttpServerRequest, request),- Effect.provideService(RelayClientTracer, Option.some(productTracer)),- );-- expect(spans).toHaveLength(1);- const span = spans[0]!;- expect(span.traceId).not.toBe("0123456789abcdef0123456789abcdef");- expect(Option.isNone(span.parent)).toBe(true);- }),- );-- it.effect("continues an authenticated relay trace with the product tracer", () =>- Effect.gen(function* () {- const spans: Array<Tracer.Span> = [];- const productTracer = Tracer.make({- span: (options) => {- const span = new Tracer.NativeSpan(options);- spans.push(span);- return span;- },- });- const request = HttpServerRequest.fromWeb(- new Request("https://environment.example.test/api/t3-cloud/mint-credential", {- headers: {- traceparent: "00-0123456789abcdef0123456789abcdef-0123456789abcdef-01",- },- }),- );-- yield* traceAuthenticatedRelayRequest(- Effect.void.pipe(Effect.withSpan("relay.mint.handler")),- ).pipe(- Effect.provideService(HttpServerRequest.HttpServerRequest, request),- Effect.provideService(RelayClientTracer, Option.some(productTracer)),- );-- expect(spans).toHaveLength(1);- const span = spans[0]!;- expect(span.traceId).toBe("0123456789abcdef0123456789abcdef");- expect(Option.getOrUndefined(span.parent)?.spanId).toBe("0123456789abcdef");- }),- );-});--describe("reconcileDesiredCloudLink", () => {- it.effect("requires stored CLI authorization without exposing an HTTP endpoint", () =>- Effect.gen(function* () {- const error = yield* Effect.flip(reconcileDesiredCloudLink("http://127.0.0.1:3774"));-- expect(error).toMatchObject({- _tag: "EnvironmentHttpUnauthorizedError",- message: "Run `akeru connect link` to authorize this environment.",- });- }).pipe(- Effect.provideService(- ServerSecretStore.ServerSecretStore,- makeSecretStore(unusedSecretStoreOperation),- ),- Effect.provideService(- ServerEnvironment.ServerEnvironment,- ServerEnvironment.ServerEnvironment.of({- getEnvironmentId: unusedSecretStoreOperation(),- getDescriptor: unusedSecretStoreOperation(),- }),- ),- Effect.provideService(- ManagedEndpointRuntime.CloudManagedEndpointRuntime,- ManagedEndpointRuntime.CloudManagedEndpointRuntime.of({- applyConfig: unusedSecretStoreOperation,- } satisfies ManagedEndpointRuntime.CloudManagedEndpointRuntime["Service"]),- ),- Effect.provideService(- EnvironmentAuth.EnvironmentAuth,- EnvironmentAuth.EnvironmentAuth.of({} as EnvironmentAuth.EnvironmentAuth["Service"]),- ),- Effect.provideService(- CliTokenManager.CloudCliTokenManager,- CliTokenManager.CloudCliTokenManager.of({- get: unusedSecretStoreOperation(),- getExisting: Effect.succeed(Option.none()),- hasCredential: unusedSecretStoreOperation(),- store: () => unusedSecretStoreOperation(),- clear: unusedSecretStoreOperation(),- }),- ),- Effect.provideService(- HttpClient.HttpClient,- HttpClient.make(() => unusedSecretStoreOperation()),- ),- Effect.provide(NodeServices.layer),- ),- );-});--describe("releaseManagedTunnelOnShutdown", () => {- const cliToken: CliTokenManager.PersistedToken = {- accessToken: "cli-access-token",- refreshToken: "cli-refresh-token",- expiresAtEpochMs: Number.MAX_SAFE_INTEGER,- };-- function makeMemorySecretStore(initial: Iterable<readonly [string, string]> = []) {- const values = new Map<string, Uint8Array>(- Array.from(initial, ([name, value]) => [name, new TextEncoder().encode(value)] as const),- );- const store: ServerSecretStore.ServerSecretStore["Service"] = {- get: (name) => Effect.sync(() => Option.fromNullishOr(values.get(name))),- set: (name, value) =>- Effect.sync(() => {- values.set(name, value);- }),- create: unusedSecretStoreOperation,- getOrCreateRandom: unusedSecretStoreOperation,- remove: (name) =>- Effect.sync(() => {- values.delete(name);- }),- };- return { store, values };- }-- interface ReleaseHarness {- readonly store: ServerSecretStore.ServerSecretStore["Service"];- readonly applyConfigCalls: Array<unknown>;- readonly requests: Array<HttpClientRequest.HttpClientRequest>;- readonly respond?: () => Response;- }-- // Writes the launcher's durable state file into this test's baseDir with- // the launcher's own writer; the release reads it to detect an in-flight- // update handoff.- const writeLauncherState = (update: ServiceUpdateRecord) =>- Effect.gen(function* () {- const path = yield* Path.Path;- const config = yield* ServerConfigModule.ServerConfig;- const statePath = path.join(config.baseDir, "runtime", SERVICE_STATE_FILE);- yield* Effect.promise(() =>- writeServiceState(statePath, {- protocol: SERVICE_LAUNCHER_PROTOCOL,- activeVersion: "0.0.30",- update,- }),- );- });-- const provideReleaseHarness =- (harness: ReleaseHarness) =>- <A, E, R>(effect: Effect.Effect<A, E, R>) =>- effect.pipe(- Effect.provideService(ServerSecretStore.ServerSecretStore, harness.store),- Effect.provideService(- ServerEnvironment.ServerEnvironment,- ServerEnvironment.ServerEnvironment.of({- getEnvironmentId: Effect.succeed(EnvironmentId.make("env_123")),- getDescriptor: Effect.die("unused"),- }),- ),- Effect.provideService(- ManagedEndpointRuntime.CloudManagedEndpointRuntime,- ManagedEndpointRuntime.CloudManagedEndpointRuntime.of({- applyConfig: (config) =>- Effect.sync(() => {- harness.applyConfigCalls.push(config);- return {- status: "disabled",- } satisfies ManagedEndpointRuntime.CloudManagedEndpointRuntimeStatus;- }),- }),- ),- Effect.provideService(- EnvironmentAuth.EnvironmentAuth,- EnvironmentAuth.EnvironmentAuth.of({} as EnvironmentAuth.EnvironmentAuth["Service"]),- ),- Effect.provideService(- CliTokenManager.CloudCliTokenManager,- CliTokenManager.CloudCliTokenManager.of({- get: unusedSecretStoreOperation(),- getExisting: Effect.succeed(Option.some(cliToken)),- hasCredential: unusedSecretStoreOperation(),- store: () => unusedSecretStoreOperation(),- clear: unusedSecretStoreOperation(),- }),- ),- Effect.provideService(- HttpClient.HttpClient,- HttpClient.make((request) =>- Effect.sync(() => {- harness.requests.push(request);- return HttpClientResponse.fromWeb(- request,- (harness.respond ?? (() => Response.json({ ok: true })))(),- );- }),- ),- ),- // The release consults the launcher state file under the configured- // baseDir, so every harness run gets a scoped temp baseDir.- Effect.provide(- ServerConfigModule.layerTest("/", { prefix: "t3-http-release-test-" }).pipe(- Layer.provideMerge(NodeServices.layer),- ),- ),- Effect.scoped,- );-- // The persisted state of a CLI-managed link whose tunnel is releasable.- const managedLinkSecrets = [- [CLOUD_ENDPOINT_RUNTIME_CONFIG, "runtime-config"],- [RELAY_URL_SECRET, "https://relay.example.test"],- [CLOUD_CLI_DESIRED_LINK_SECRET, "managed"],- ] as const;-- it.effect("stops the connector, releases the relay tunnel, and drops the dead token", () => {- const { store, values } = makeMemorySecretStore(managedLinkSecrets);- const applyConfigCalls: Array<unknown> = [];- const requests: Array<HttpClientRequest.HttpClientRequest> = [];-- return Effect.gen(function* () {- const released = yield* releaseManagedTunnelOnShutdown();-- expect(released).toBe(true);- expect(applyConfigCalls).toEqual([null]);- expect(requests).toHaveLength(1);- const request = requests[0]!;- expect(request.method).toBe("DELETE");- expect(request.url).toBe(- "https://relay.example.test/v1/client/environment-links/env_123/tunnel",- );- expect(request.headers.authorization).toBe("Bearer cli-access-token");- expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(false);- }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));- });-- it.effect("does nothing for links without a stored managed tunnel runtime config", () => {- const { store } = makeMemorySecretStore();- const applyConfigCalls: Array<unknown> = [];- const requests: Array<HttpClientRequest.HttpClientRequest> = [];-- return Effect.gen(function* () {- const released = yield* releaseManagedTunnelOnShutdown();-- expect(released).toBe(false);- expect(applyConfigCalls).toEqual([]);- expect(requests).toEqual([]);- }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));- });-- it.effect("leaves the tunnel of a web/mobile-installed link untouched", () => {- // A managed runtime config without a CLI-desired link: the environment was- // linked by a web/mobile client, and nothing re-provisions the tunnel on- // the next boot, so shutdown must not release it.- const { store, values } = makeMemorySecretStore([- [CLOUD_ENDPOINT_RUNTIME_CONFIG, "runtime-config"],- [RELAY_URL_SECRET, "https://relay.example.test"],- ]);- const applyConfigCalls: Array<unknown> = [];- const requests: Array<HttpClientRequest.HttpClientRequest> = [];-- return Effect.gen(function* () {- const released = yield* releaseManagedTunnelOnShutdown();-- expect(released).toBe(false);- expect(applyConfigCalls).toEqual([]);- expect(requests).toEqual([]);- expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(true);- }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));- });-- it.effect("leaves the tunnel of a publish-only desired link untouched", () => {- const { store, values } = makeMemorySecretStore([- [CLOUD_ENDPOINT_RUNTIME_CONFIG, "runtime-config"],- [RELAY_URL_SECRET, "https://relay.example.test"],- [CLOUD_CLI_DESIRED_LINK_SECRET, "publish_only"],- ]);- const applyConfigCalls: Array<unknown> = [];- const requests: Array<HttpClientRequest.HttpClientRequest> = [];-- return Effect.gen(function* () {- const released = yield* releaseManagedTunnelOnShutdown();-- expect(released).toBe(false);- expect(applyConfigCalls).toEqual([]);- expect(requests).toEqual([]);- expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(true);- }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));- });-- it.effect("keeps the tunnel when shutdown hands off to a pending update", () => {- const { store, values } = makeMemorySecretStore(managedLinkSecrets);- const applyConfigCalls: Array<unknown> = [];- const requests: Array<HttpClientRequest.HttpClientRequest> = [];-- return Effect.gen(function* () {- yield* writeLauncherState({- id: "update-1",- fromVersion: "0.0.30",- targetVersion: "0.0.31",- dbPath: "/tmp/state.sqlite",- status: "pending",- });-- const released = yield* releaseManagedTunnelOnShutdown();-- // The launcher restarts a server immediately, so the tunnel is not- // orphaned; keeping it avoids the hostname route re-propagation that- // dominates update downtime. The stored config must survive so the- // next boot respawns the connector against the same tunnel.- expect(released).toBe(false);- expect(applyConfigCalls).toEqual([]);- expect(requests).toEqual([]);- expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(true);- }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));- });-- it.effect("still releases a pending update when the launcher is stopping", () => {- // `akeru service uninstall` or `systemctl stop` during the pending window:- // the launcher writes its stop marker before signalling the child, so no- // replacement server is coming and the tunnel must not be kept.- const { store, values } = makeMemorySecretStore(managedLinkSecrets);- const applyConfigCalls: Array<unknown> = [];- const requests: Array<HttpClientRequest.HttpClientRequest> = [];-- return Effect.gen(function* () {- yield* writeLauncherState({- id: "update-1",- fromVersion: "0.0.30",- targetVersion: "0.0.31",- dbPath: "/tmp/state.sqlite",- status: "pending",- });- const fs = yield* FileSystem.FileSystem;- const path = yield* Path.Path;- const config = yield* ServerConfigModule.ServerConfig;- yield* fs.writeFileString(path.join(config.baseDir, "runtime", SERVICE_STOP_MARKER_FILE), "");-- expect(yield* pendingServiceUpdateExists).toBe(true);- const released = yield* releaseManagedTunnelOnShutdown();-- expect(released).toBe(true);- expect(requests).toHaveLength(1);- expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(false);- }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));- });-- it.effect("still releases when the recorded update already settled", () => {- const { store, values } = makeMemorySecretStore(managedLinkSecrets);- const applyConfigCalls: Array<unknown> = [];- const requests: Array<HttpClientRequest.HttpClientRequest> = [];-- return Effect.gen(function* () {- yield* writeLauncherState({- id: "update-1",- fromVersion: "0.0.30",- targetVersion: "0.0.31",- status: "committed",- });-- const released = yield* releaseManagedTunnelOnShutdown();-- expect(released).toBe(true);- expect(requests).toHaveLength(1);- expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(false);- }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));- });-- it.effect("keeps a runtime config that a fast restart replaced mid-release", () => {- const { store, values } = makeMemorySecretStore(managedLinkSecrets);- const applyConfigCalls: Array<unknown> = [];- const requests: Array<HttpClientRequest.HttpClientRequest> = [];- const freshConfig = new TextEncoder().encode("fresh-runtime-config");-- return Effect.gen(function* () {- const released = yield* releaseManagedTunnelOnShutdown();-- expect(released).toBe(true);- // The finalizer only drops the config it released; the one written by- // the restarted process while the DELETE was in flight stays.- expect(values.get(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(freshConfig);- }).pipe(- provideReleaseHarness({- store,- applyConfigCalls,- requests,- respond: () => {- // A restarted process reconciled and stored a fresh connector config- // while this shutdown's release request was in flight.- values.set(CLOUD_ENDPOINT_RUNTIME_CONFIG, freshConfig);- return Response.json({ ok: true });- },- }),- );- });-- it.effect("keeps the stored connector token when the relay skipped the release", () => {- // ok:false means a concurrent provision owns the recorded tunnel, so the- // stored runtime config (possibly freshly written by that provision) must- // survive.- const { store, values } = makeMemorySecretStore(managedLinkSecrets);- const applyConfigCalls: Array<unknown> = [];- const requests: Array<HttpClientRequest.HttpClientRequest> = [];-- return Effect.gen(function* () {- const released = yield* releaseManagedTunnelOnShutdown();-- expect(released).toBe(false);- expect(requests).toHaveLength(1);- expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(true);- }).pipe(- provideReleaseHarness({- store,- applyConfigCalls,- requests,- respond: () => Response.json({ ok: false }),- }),- );- });-- it.effect("keeps the stored connector token when the relay release request fails", () => {- const { store, values } = makeMemorySecretStore(managedLinkSecrets);- const applyConfigCalls: Array<unknown> = [];- const requests: Array<HttpClientRequest.HttpClientRequest> = [];-- return Effect.gen(function* () {- const result = yield* Effect.result(releaseManagedTunnelOnShutdown());-- expect(result._tag).toBe("Failure");- expect(requests).toHaveLength(1);- // The tunnel still exists, so the stored token stays valid across the- // restart and the next boot can bring the connector back immediately.- expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(true);- }).pipe(- provideReleaseHarness({- store,- applyConfigCalls,- requests,- respond: () => Response.json({ ok: false }, { status: 503 }),- }),- );- });-});--describe("link proof provider kinds", () => {- const proofRequest = (- providerKind: RelayLinkProofRequest["endpoint"]["providerKind"],- ): RelayLinkProofRequest => ({- challenge: "challenge",- relayIssuer: "https://relay.example.test",- endpoint: {- httpBaseUrl: "http://127.0.0.1:7331",- wsBaseUrl: "ws://127.0.0.1:7331",- providerKind,- },- origin: { localHttpHost: "127.0.0.1", localHttpPort: 7331 },- });-- it("accepts managed and manual endpoints but not t3_relay", () => {- expect(isSupportedLinkProviderKind(proofRequest("cloudflare_tunnel"))).toBe(true);- expect(isSupportedLinkProviderKind(proofRequest("manual"))).toBe(true);- expect(isSupportedLinkProviderKind(proofRequest("t3_relay"))).toBe(false);- });-- it("only claims the managed-tunnel scope for tunnel links", () => {- expect(linkProofScopes(proofRequest("cloudflare_tunnel"))).toEqual([- "agent_activity_notifications",- "managed_tunnels",- ]);- expect(linkProofScopes(proofRequest("manual"))).toEqual(["agent_activity_notifications"]);- });-});diff --git a/apps/server/src/cloud/http.ts b/apps/server/src/cloud/http.tsdeleted file mode 100644index cc67874a4..000000000--- a/apps/server/src/cloud/http.ts+++ /dev/null@@ -1,1087 +0,0 @@-import * as NodeCrypto from "node:crypto";-import {- AuthRelayReadScope,- AuthRelayWriteScope,- AuthStandardClientScopes,- EnvironmentCloudEndpointUnavailableError,- EnvironmentCloudLinkStateResult,- EnvironmentCloudRelayConfigResult,- EnvironmentHttpApi,- EnvironmentHttpBadRequestError,- EnvironmentHttpConflictError,- EnvironmentHttpInternalServerError,- EnvironmentHttpUnauthorizedError,-} from "@t3tools/contracts";-import {- RelayCloudEnvironmentHealthProofPayload,- RelayCloudEnvironmentHealthRequest,- RelayCloudMintCredentialProofPayload,- RelayCloudMintCredentialRequest,- RelayEnvironmentHealthResponseProofPayload,- type RelayEnvironmentHealthResponse as RelayEnvironmentHealthResponseShape,- RelayEnvironmentConfigRequest,- RelayEnvironmentLinkChallengeResponse,- RelayEnvironmentLinkResponse,- RelayEnvironmentMintResponseProofPayload,- type RelayEnvironmentMintResponse as RelayEnvironmentMintResponseShape,- RelayEnvironmentLinkProof,- RelayEnvironmentLinkProofPayload,- RelayLinkProofRequest,- RelayManagedEndpointOrigin,- RelayOkResponse,-} from "@t3tools/contracts/relay";-import { withRelayClientTracing } from "@t3tools/shared/relayTracing";-import {- normalizeRelayIssuer,- RELAY_HEALTH_REQUEST_TYP,- RELAY_HEALTH_RESPONSE_TYP,- RELAY_LINK_PROOF_TYP,- RELAY_MINT_REQUEST_TYP,- RELAY_MINT_RESPONSE_TYP,- signRelayJwt,- verifyRelayJwt,-} from "@t3tools/shared/relayJwt";-import { isSecureRelayUrl } from "@t3tools/shared/relayUrl";-import * as DateTime from "effect/DateTime";-import * as Crypto from "effect/Crypto";-import * as Duration from "effect/Duration";-import * as Effect from "effect/Effect";-import * as FileSystem from "effect/FileSystem";-import * as Option from "effect/Option";-import * as Path from "effect/Path";-import * as Schema from "effect/Schema";-import * as HttpEffect from "effect/unstable/http/HttpEffect";-import { HttpServerRequest, HttpServerResponse } from "effect/unstable/http";-import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";-import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";--import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";-import * as ServerSecretStore from "../auth/ServerSecretStore.ts";-import { requireEnvironmentScope } from "../auth/http.ts";-import * as ServerConfig from "../config.ts";-import * as ServerEnvironment from "../environment/ServerEnvironment.ts";-import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";-import {- SERVICE_STATE_FILE,- SERVICE_STOP_MARKER_FILE,- serviceStateHasPendingUpdate,-} from "./serviceProtocol.ts";-import {- CLOUD_ENDPOINT_RUNTIME_CONFIG,- CLOUD_LINKED_USER_ID,- CLOUD_MINT_PUBLIC_KEY,- encodeEndpointRuntimeConfigJson,- PUBLISH_AGENT_ACTIVITY_SECRET,- RELAY_ENVIRONMENT_CREDENTIAL_SECRET,- RELAY_ISSUER_SECRET,- RELAY_URL_SECRET,-} from "./config.ts";-import { relayUrlConfig } from "./publicConfig.ts";-import {- readCliDesiredCloudLink,- readCliDesiredLinkMode,- setCliDesiredCloudLink,-} from "./CliState.ts";-import * as CliTokenManager from "./CliTokenManager.ts";-import { getOrCreateEnvironmentKeyPairFromSecretStore } from "./environmentKeys.ts";-import { traceRelayRequest } from "./traceRelayRequest.ts";--const CLOUD_MINT_NONCE_PREFIX = "cloud-mint-nonce-";-const CLOUD_MINT_JTI_PREFIX = "cloud-mint-jti-";-const CLOUD_HEALTH_NONCE_PREFIX = "cloud-health-nonce-";-const CLOUD_HEALTH_JTI_PREFIX = "cloud-health-jti-";-const CLOUD_PROOF_MAX_LIFETIME_SECONDS = 5 * 60;-const CLOUD_PROOF_CLOCK_SKEW_SECONDS = 60;-const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]);-const CLOUD_CREDENTIAL_RESPONSE_HEADERS = {- "cache-control": "no-store",- pragma: "no-cache",-} as const;--const appendCloudCredentialResponseHeaders = HttpEffect.appendPreResponseHandler(- (_request, response) =>- Effect.succeed(HttpServerResponse.setHeaders(response, CLOUD_CREDENTIAL_RESPONSE_HEADERS)),-);--const failEnvironmentCloudInternalError =- (message: string) =>- (cause: unknown): Effect.Effect<never, EnvironmentHttpInternalServerError> =>- Effect.logError(message, { cause }).pipe(- Effect.flatMap(() => Effect.fail(new EnvironmentHttpInternalServerError({ message }))),- );--const failCloudCliTokenManagerError = (error: CliTokenManager.CloudCliTokenManagerError) =>- failEnvironmentCloudInternalError(error.message)(error);--const requireRelayUrl = relayUrlConfig.pipe(- Effect.mapError(- () =>- new EnvironmentHttpInternalServerError({- message: "T3CODE_RELAY_URL must be configured as a secure absolute HTTPS origin.",- }),- ),-);--function bytesToString(bytes: Uint8Array): string {- return new TextDecoder().decode(bytes);-}--function stringToBytes(value: string): Uint8Array {- return new TextEncoder().encode(value);-}--export function consumeCloudReplayGuards(input: {- readonly secrets: ServerSecretStore.ServerSecretStore["Service"];- readonly names: ReadonlyArray<string>;- readonly value: Uint8Array;-}) {- return Effect.all(- input.names.map((name) =>- input.secrets.create(name, input.value).pipe(- Effect.as(true),- Effect.catchIf(ServerSecretStore.isSecretStoreError, (error) =>- ServerSecretStore.isSecretAlreadyExistsError(error)- ? Effect.succeed(false)- : Effect.fail(error),- ),- ),- ),- { concurrency: input.names.length },- ).pipe(Effect.map((created) => created.every(Boolean)));-}--function normalizePemForSignedPayload(value: string): string {- return value.trim();-}--function normalizeHostname(hostname: string): string {- return hostname- .trim()- .toLowerCase()- .replace(/^\[(.*)\]$/, "$1");-}--function validateCloudMintPublicKey(- publicKey: string,-): Effect.Effect<void, EnvironmentHttpBadRequestError> {- return Effect.try({- try: () => NodeCrypto.createPublicKey(publicKey.replace(/\\n/g, "\n")),- catch: () =>- new EnvironmentHttpBadRequestError({- message: "Cloud mint public key must be a valid Ed25519 public key.",- }),- }).pipe(- Effect.flatMap((key) =>- key.asymmetricKeyType === "ed25519"- ? Effect.void- : Effect.fail(- new EnvironmentHttpBadRequestError({- message: "Cloud mint public key must be a valid Ed25519 public key.",- }),- ),- ),- );-}--function validateRelayConfigPayload(- payload: RelayEnvironmentConfigRequest,-): Effect.Effect<void, EnvironmentHttpBadRequestError> {- if (!isSecureRelayUrl(payload.relayUrl)) {- return Effect.fail(- new EnvironmentHttpBadRequestError({- message: "Relay URL must be a secure absolute HTTPS URL.",- }),- );- }- if (payload.relayIssuer !== undefined && !isSecureRelayUrl(payload.relayIssuer)) {- return Effect.fail(- new EnvironmentHttpBadRequestError({- message: "Relay issuer must be a secure absolute HTTPS URL.",- }),- );- }- if (payload.environmentCredential.trim().length === 0) {- return Effect.fail(- new EnvironmentHttpBadRequestError({- message: "Relay environment credential is required.",- }),- );- }- if (payload.cloudUserId.trim().length === 0) {- return Effect.fail(- new EnvironmentHttpBadRequestError({- message: "Cloud user id is required.",- }),- );- }- return Effect.void;-}--function validateLinkedCloudUser(input: {- readonly secrets: ServerSecretStore.ServerSecretStore["Service"];- readonly cloudUserId: string;-}): Effect.Effect<void, EnvironmentAuth.ServerAuthInternalError | EnvironmentHttpConflictError> {- return input.secrets.get(CLOUD_LINKED_USER_ID).pipe(- Effect.mapError(- (cause) =>- new EnvironmentAuth.ServerAuthLinkedCloudAccountVerificationError({- cause,- }),- ),- Effect.flatMap((existing) => {- if (Option.isNone(existing)) {- return Effect.void;- }- const existingCloudUserId = bytesToString(existing.value);- return existingCloudUserId === input.cloudUserId- ? Effect.void- : Effect.fail(- new EnvironmentHttpConflictError({- message:- "This environment is already linked to a different cloud account. Unlink it before switching accounts.",- }),- );- }),- );-}--function readInstalledCloudUserId(- secrets: ServerSecretStore.ServerSecretStore["Service"],-): Effect.Effect<string, EnvironmentAuth.ServerAuthInternalError> {- return secrets.get(CLOUD_LINKED_USER_ID).pipe(- Effect.mapError(- (cause) =>- new EnvironmentAuth.ServerAuthLinkedCloudAccountReadError({- cause,- }),- ),- Effect.flatMap((bytes) =>- Option.isSome(bytes)- ? Effect.succeed(bytesToString(bytes.value))- : Effect.fail(new EnvironmentAuth.ServerAuthLinkedCloudAccountMissingError({})),- ),- );-}--function isLoopbackHostname(hostname: string): boolean {- return LOOPBACK_HOSTNAMES.has(normalizeHostname(hostname));-}--function firstForwardedHeaderValue(value: string | undefined): string | undefined {- const first = value?.split(",")[0]?.trim();- return first && first.length > 0 ? first : undefined;-}--function requestAbsoluteUrl(request: HttpServerRequest.HttpServerRequest): string | null {- try {- return new URL(request.originalUrl).href;- } catch {- const host = firstForwardedHeaderValue(request.headers.host) ?? "127.0.0.1";- try {- return new URL(request.originalUrl, `http://${host}`).href;- } catch {- return null;- }- }-}--function hasForwardedAuthorityHeaders(request: HttpServerRequest.HttpServerRequest): boolean {- return (- firstForwardedHeaderValue(request.headers["x-forwarded-host"]) !== undefined ||- firstForwardedHeaderValue(request.headers["x-forwarded-proto"]) !== undefined- );-}--function endpointRequestPort(url: URL): number {- return Number(url.port || (url.protocol === "https:" ? 443 : 80));-}--function isAllowedEndpointOrigin(input: {- readonly origin: RelayManagedEndpointOrigin;- readonly requestUrl: string;-}): boolean {- if (!isLoopbackHostname(input.origin.localHttpHost)) {- return false;- }-- const url = new URL(input.requestUrl);- if (!isLoopbackHostname(url.hostname)) {- return false;- }-- return input.origin.localHttpPort === endpointRequestPort(url);-}--// A managed (Cloudflare tunnel) endpoint is provisioned by the relay and must-// point at a loopback origin. A manual endpoint is reached out of band (e.g.-// Tailscale) or not advertised at all for publish-only links, so it is not-// tied to the managed-tunnel scope.-export function isSupportedLinkProviderKind(request: RelayLinkProofRequest): boolean {- return (- request.endpoint.providerKind === "cloudflare_tunnel" ||- request.endpoint.providerKind === "manual"- );-}--export function linkProofScopes(- request: RelayLinkProofRequest,-): RelayEnvironmentLinkProofPayload["scopes"] {- return request.endpoint.providerKind === "cloudflare_tunnel"- ? ["agent_activity_notifications", "managed_tunnels"]- : ["agent_activity_notifications"];-}--function hasExactScope(input: {- readonly scopes: ReadonlyArray<string>;- readonly expected: string;-}): boolean {- return input.scopes.length === 1 && input.scopes[0] === input.expected;-}--function hasBoundedCloudProofLifetime(input: {- readonly iat: number;- readonly exp: number;- readonly nowSeconds: number;-}): boolean {- return (- input.exp > input.iat &&- input.exp - input.iat <= CLOUD_PROOF_MAX_LIFETIME_SECONDS &&- input.iat <= input.nowSeconds + CLOUD_PROOF_CLOCK_SKEW_SECONDS- );-}--const decodeCloudHealthProof = Schema.decodeUnknownEffect(RelayCloudEnvironmentHealthProofPayload);-const decodeCloudMintProof = Schema.decodeUnknownEffect(RelayCloudMintCredentialProofPayload);--interface CloudHttpDependencies {- readonly secrets: ServerSecretStore.ServerSecretStore["Service"];- readonly environment: ServerEnvironment.ServerEnvironment["Service"];- readonly endpointRuntime: ManagedEndpointRuntime.CloudManagedEndpointRuntime["Service"];- readonly environmentAuth: EnvironmentAuth.EnvironmentAuth["Service"];- readonly cliTokenManager: CliTokenManager.CloudCliTokenManager["Service"];- readonly httpClient: HttpClient.HttpClient;-}--const cloudHttpDependencies = Effect.gen(function* () {- return {- secrets: yield* ServerSecretStore.ServerSecretStore,- environment: yield* ServerEnvironment.ServerEnvironment,- endpointRuntime: yield* ManagedEndpointRuntime.CloudManagedEndpointRuntime,- environmentAuth: yield* EnvironmentAuth.EnvironmentAuth,- cliTokenManager: yield* CliTokenManager.CloudCliTokenManager,- httpClient: yield* HttpClient.HttpClient,- } satisfies CloudHttpDependencies;-});--const makeCloudLinkProof = Effect.fn("environment.cloud.makeLinkProof")(function* (- dependencies: CloudHttpDependencies,- request: RelayLinkProofRequest,- requestUrl: string,-) {- const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(dependencies.secrets);- if (- !isSupportedLinkProviderKind(request) ||- !isAllowedEndpointOrigin({- origin: request.origin,- requestUrl,- })- ) {- return yield* new EnvironmentHttpBadRequestError({- message: "Invalid managed endpoint origin.",- });- }- const now = yield* DateTime.now;- const expiresAt = DateTime.add(now, { minutes: 5 });- const nowSeconds = Math.floor(now.epochMilliseconds / 1_000);- const descriptor = yield* dependencies.environment.getDescriptor;- const payload = {- iss: `t3-env:${descriptor.environmentId}`,- aud: normalizeRelayIssuer(request.relayIssuer),- sub: descriptor.environmentId,- jti: yield* Crypto.Crypto.pipe(Effect.flatMap((crypto) => crypto.randomUUIDv4)),- iat: nowSeconds,- exp: Math.floor(expiresAt.epochMilliseconds / 1_000),- challenge: request.challenge,- descriptor,- environmentId: descriptor.environmentId,- environmentPublicKey: normalizePemForSignedPayload(keyPair.publicKey),- endpoint: request.endpoint,- origin: request.origin,- scopes: linkProofScopes(request),- } satisfies RelayEnvironmentLinkProofPayload;- return yield* signRelayJwt({- privateKey: keyPair.privateKey,- typ: RELAY_LINK_PROOF_TYP,- payload,- }).pipe(- Effect.mapError(- (cause) =>- new EnvironmentAuth.ServerAuthCloudLinkJwtSigningError({- cause,- }),- ),- );-});--const cloudLinkProofHandler = Effect.fn("environment.cloud.linkProof")(- function* (dependencies: CloudHttpDependencies, request: RelayLinkProofRequest) {- yield* requireEnvironmentScope(AuthRelayWriteScope);- const httpRequest = yield* HttpServerRequest.HttpServerRequest;- const requestUrl = requestAbsoluteUrl(httpRequest);- if (requestUrl === null || hasForwardedAuthorityHeaders(httpRequest)) {- return yield* new EnvironmentHttpBadRequestError({- message: "Invalid managed endpoint origin.",- });- }- const proof = yield* makeCloudLinkProof(dependencies, request, requestUrl);- yield* appendCloudCredentialResponseHeaders;- return proof satisfies RelayEnvironmentLinkProof;- },- Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>- failEnvironmentCloudInternalError(error.message)(error),- ),- Effect.catchIf(- ServerSecretStore.isSecretStoreError,- failEnvironmentCloudInternalError("Could not generate environment link proof."),- ),- Effect.catchTag(- "PlatformError",- failEnvironmentCloudInternalError("Could not generate environment link proof."),- ),-);--const applyCloudRelayConfig = Effect.fn("environment.cloud.applyRelayConfig")(function* (- dependencies: CloudHttpDependencies,- payload: RelayEnvironmentConfigRequest,-) {- yield* validateRelayConfigPayload(payload);- yield* validateLinkedCloudUser({- secrets: dependencies.secrets,- cloudUserId: payload.cloudUserId,- });- yield* validateCloudMintPublicKey(payload.cloudMintPublicKey);- const endpointRuntimeStatus = yield* dependencies.endpointRuntime.applyConfig(- payload.endpointRuntime,- );- const ok =- endpointRuntimeStatus.status === "disabled" || endpointRuntimeStatus.status === "running";- if (!ok) {- return yield* new EnvironmentCloudEndpointUnavailableError({- message: "Managed endpoint runtime could not be started.",- endpointRuntimeStatus,- });- }-- yield* dependencies.secrets.set(RELAY_URL_SECRET, stringToBytes(payload.relayUrl));- yield* dependencies.secrets.set(- RELAY_ISSUER_SECRET,- stringToBytes(payload.relayIssuer ?? payload.relayUrl),- );- yield* dependencies.secrets.set(CLOUD_LINKED_USER_ID, stringToBytes(payload.cloudUserId));- yield* dependencies.secrets.set(- RELAY_ENVIRONMENT_CREDENTIAL_SECRET,- stringToBytes(payload.environmentCredential),- );- yield* dependencies.secrets.set(CLOUD_MINT_PUBLIC_KEY, stringToBytes(payload.cloudMintPublicKey));- if (payload.endpointRuntime) {- const endpointRuntimeJson = yield* encodeEndpointRuntimeConfigJson(payload.endpointRuntime);- yield* dependencies.secrets.set(- CLOUD_ENDPOINT_RUNTIME_CONFIG,- stringToBytes(endpointRuntimeJson),- );- } else {- yield* dependencies.secrets.remove(CLOUD_ENDPOINT_RUNTIME_CONFIG);- }- return { ok, endpointRuntimeStatus } satisfies EnvironmentCloudRelayConfigResult;-});--const cloudRelayConfigHandler = Effect.fn("environment.cloud.relayConfig")(- function* (dependencies: CloudHttpDependencies, payload: RelayEnvironmentConfigRequest) {- yield* requireEnvironmentScope(AuthRelayWriteScope);- return yield* applyCloudRelayConfig(dependencies, payload);- },- Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>- failEnvironmentCloudInternalError(error.message)(error),- ),- Effect.catchIf(- ServerSecretStore.isSecretStoreError,- failEnvironmentCloudInternalError("Could not persist environment relay configuration."),- ),- Effect.catchTag(- "SchemaError",- failEnvironmentCloudInternalError("Could not persist environment relay configuration."),- ),-);--const relayClientRequest = <A>(- dependencies: CloudHttpDependencies,- input: {- readonly url: string;- readonly token: string;- readonly payload: unknown;- readonly schema: Schema.Decoder<A>;- },-) =>- HttpClientRequest.post(input.url).pipe(- HttpClientRequest.bearerToken(input.token),- HttpClientRequest.bodyJson(input.payload),- Effect.flatMap(dependencies.httpClient.execute),- Effect.flatMap(HttpClientResponse.filterStatusOk),- Effect.flatMap(HttpClientResponse.schemaBodyJson(input.schema)),- Effect.mapError(- (cause) =>- new EnvironmentHttpInternalServerError({- message: `T3 Connect relay request failed: ${String(cause)}`,- }),- ),- withRelayClientTracing,- );--const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesiredLinkWith")(- function* (dependencies: CloudHttpDependencies, localOrigin: string) {- const localUrl = yield* Effect.try({- try: () => new URL(localOrigin),- catch: () =>- new EnvironmentHttpBadRequestError({- message: "Could not resolve local environment origin.",- }),- });- if (localUrl.origin !== localOrigin) {- return yield* new EnvironmentHttpBadRequestError({- message: "Could not resolve local environment origin.",- });- }- const localWsOrigin = localOrigin.replace(/^http/u, "ws");- const token = yield* dependencies.cliTokenManager.getExisting.pipe(- Effect.flatMap(- Option.match({- onNone: () =>- Effect.fail(- new EnvironmentHttpUnauthorizedError({- message: "Run `akeru connect link` to authorize this environment.",- }),- ),- onSome: Effect.succeed,- }),- ),- );- const mode = yield* readCliDesiredLinkMode;- const managedTunnelsEnabled = mode !== "publish_only";- const relayUrl = yield* requireRelayUrl;- const challenge = yield* relayClientRequest(dependencies, {- url: `${relayUrl}/v1/client/environment-link-challenges`,- token: token.accessToken,- payload: {- notificationsEnabled: true,- liveActivitiesEnabled: true,- managedTunnelsEnabled,- },- schema: RelayEnvironmentLinkChallengeResponse,- });- const proof = yield* makeCloudLinkProof(- dependencies,- {- challenge: challenge.challenge,- relayIssuer: relayUrl,- endpoint: {- httpBaseUrl: localOrigin,- wsBaseUrl: localWsOrigin,- providerKind: managedTunnelsEnabled ? "cloudflare_tunnel" : "manual",- },- origin: {- localHttpHost: localUrl.hostname,- localHttpPort: endpointRequestPort(localUrl),- },- },- localOrigin,- );- const link = yield* relayClientRequest(dependencies, {- url: `${relayUrl}/v1/client/environment-links`,- token: token.accessToken,- payload: {- proof,- notificationsEnabled: true,- liveActivitiesEnabled: true,- managedTunnelsEnabled,- },- schema: RelayEnvironmentLinkResponse,- });- yield* setCliDesiredCloudLink(true, mode);- return yield* applyCloudRelayConfig(dependencies, {- relayUrl,- relayIssuer: link.relayIssuer,- cloudUserId: link.cloudUserId,- environmentCredential: link.environmentCredential,- cloudMintPublicKey: link.cloudMintPublicKey,- endpointRuntime: link.endpointRuntime,- });- },- Effect.catchIf(- ServerSecretStore.isSecretStoreError,- failEnvironmentCloudInternalError("Could not persist desired T3 Connect link state."),- ),- Effect.catchTags({- CloudCliCredentialRemovalError: failCloudCliTokenManagerError,- CloudCliCredentialRefreshError: failCloudCliTokenManagerError,- CloudCliCredentialReadError: failCloudCliTokenManagerError,- CloudCliAuthorizationError: failCloudCliTokenManagerError,- CloudCliAuthorizationTimeoutError: failCloudCliTokenManagerError,- }),-);--export const reconcileDesiredCloudLink = Effect.fn("environment.cloud.reconcileDesiredLink")(- function* (localOrigin: string) {- return yield* reconcileDesiredCloudLinkWith(yield* cloudHttpDependencies, localOrigin);- },-);--// The launcher owns this durable state, so read it directly both when a trial-// decides whether it owns pre-activation cleanup and while a server tears down.-export const pendingServiceUpdateExists = Effect.gen(function* () {- const config = yield* ServerConfig.ServerConfig;- const fs = yield* FileSystem.FileSystem;- const path = yield* Path.Path;- const runtimeDir = path.join(config.baseDir, "runtime");- const stateText = yield* fs- .readFileString(path.join(runtimeDir, SERVICE_STATE_FILE))- .pipe(Effect.option);- return Option.isSome(stateText) && serviceStateHasPendingUpdate(stateText.value);-});--// A pending update alone is not proof a replacement server is coming: an-// explicit launcher stop (`akeru service uninstall`, `systemctl stop`,-// `launchctl bootout`) during-// the pending window also tears this server down. The launcher marks that case-// just before it signals the child, so pending + no marker is the handoff.-const pendingUpdateHandoffExists = Effect.gen(function* () {- if (!(yield* pendingServiceUpdateExists)) {- return false;- }- const config = yield* ServerConfig.ServerConfig;- const fs = yield* FileSystem.FileSystem;- const path = yield* Path.Path;- const runtimeDir = path.join(config.baseDir, "runtime");- const stopping = yield* fs- .exists(path.join(runtimeDir, SERVICE_STOP_MARKER_FILE))- .pipe(Effect.orElseSucceed(() => false));- return !stopping;-});--// Cloudflare bills per provisioned tunnel, so an environment that goes offline-// must not leave its tunnel behind. Releasing deletes only the tunnel — the-// relay keeps the link and its hostname reservation, and the next startup's-// link reconcile provisions a replacement tunnel under the same URL.-export const releaseManagedTunnelOnShutdown = Effect.fn(- "environment.cloud.releaseManagedTunnelOnShutdown",-)(function* () {- const dependencies = yield* cloudHttpDependencies;- // Only a managed link stores a runtime config; publish-only links have no- // tunnel to release.- const runtimeConfig = yield* dependencies.secrets.get(CLOUD_ENDPOINT_RUNTIME_CONFIG);- if (Option.isNone(runtimeConfig)) {- return false;- }- // Only CLI-desired managed links release on shutdown, because the startup- // reconcile that provisions the replacement tunnel only runs for them. A- // link installed by a web/mobile client comes back after a restart by- // reapplying the stored connector token — it has no boot-time re-provision- // path — so its tunnel must survive the restart. (Unlink still deletes it.)- if (!(yield* readCliDesiredCloudLink) || (yield* readCliDesiredLinkMode) !== "managed") {- return false;- }- // A shutdown that hands off to a pending remote update is not the- // environment going offline: the launcher immediately brings a server back- // (the new version, or the old one after a rollback). Deleting the tunnel- // here forces that server to provision a replacement UUID, and the public- // hostname's route to the new tunnel takes 1-2 minutes to propagate — the- // dominant cost of an update restart. Keep the tunnel instead: the next- // boot respawns the connector from the stored config and is reachable as- // soon as it connects, and the reconcile confirms the still-live tunnel- // without replacing it.- if (yield* pendingUpdateHandoffExists) {- yield* Effect.logInfo("Keeping the managed tunnel across the update restart");- return false;- }- const token = yield* dependencies.cliTokenManager.getExisting;- if (Option.isNone(token)) {- return false;- }- // The link belongs to the relay it was installed against, so target the- // persisted URL: T3CODE_RELAY_URL may have changed since the link was made.- const relayUrl = yield* dependencies.secrets.get(RELAY_URL_SECRET);- if (Option.isNone(relayUrl)) {- return false;- }- const environmentId = yield* dependencies.environment.getEnvironmentId;- // Stop the local connector before the relay deletes the tunnel it serves.- yield* dependencies.endpointRuntime.applyConfig(null);- const response = yield* HttpClientRequest.delete(- `${bytesToString(relayUrl.value)}/v1/client/environment-links/${encodeURIComponent(environmentId)}/tunnel`,- ).pipe(- HttpClientRequest.bearerToken(token.value.accessToken),- dependencies.httpClient.execute,- Effect.flatMap(HttpClientResponse.filterStatusOk),- Effect.flatMap(HttpClientResponse.schemaBodyJson(RelayOkResponse)),- withRelayClientTracing,- );- // ok:false means the relay skipped deletion because a concurrent provision- // owns the recorded tunnel now — leave the stored config alone.- if (!response.ok) {- return false;- }- // The connector token died with the tunnel. Drop the stored config so the- // next start waits for the link reconcile instead of respawning the relay- // client with a dead token. Kept when the release request fails: the tunnel- // still exists, so the stored token keeps working across the restart.- // Only dropped while it is still the config this shutdown released — a fast- // restart may already have reconciled and stored a fresh config for its- // replacement tunnel, and that one must survive this finalizer.- const storedConfig = yield* dependencies.secrets.get(CLOUD_ENDPOINT_RUNTIME_CONFIG);- if (- Option.isSome(storedConfig) &&- bytesToString(storedConfig.value) === bytesToString(runtimeConfig.value)- ) {- yield* dependencies.secrets.remove(CLOUD_ENDPOINT_RUNTIME_CONFIG);- }- return true;-});--const readCloudLinkState = Effect.fn("environment.cloud.readLinkState")(function* (- dependencies: CloudHttpDependencies,-) {- const [cloudUserId, relayUrl, relayIssuer, endpointRuntimeConfig, publishAgentActivity] =- yield* Effect.all(- [- dependencies.secrets.get(CLOUD_LINKED_USER_ID),- dependencies.secrets.get(RELAY_URL_SECRET),- dependencies.secrets.get(RELAY_ISSUER_SECRET),- dependencies.secrets.get(CLOUD_ENDPOINT_RUNTIME_CONFIG),- dependencies.secrets.get(PUBLISH_AGENT_ACTIVITY_SECRET),- ],- { concurrency: 5 },- );- return {- linked: Option.isSome(cloudUserId),- cloudUserId: Option.isSome(cloudUserId) ? bytesToString(cloudUserId.value) : null,- relayUrl: Option.isSome(relayUrl) ? bytesToString(relayUrl.value) : null,- relayIssuer: Option.isSome(relayIssuer) ? bytesToString(relayIssuer.value) : null,- // The managed tunnel runtime config is only stored for managed links; a- // publish-only link leaves it absent.- managedTunnelActive: Option.isSome(endpointRuntimeConfig),- publishAgentActivity: Option.isSome(publishAgentActivity)- ? bytesToString(publishAgentActivity.value) === "true"- : false,- } satisfies EnvironmentCloudLinkStateResult;-});--const cloudLinkStateHandler = Effect.fn("environment.cloud.linkState")(- function* (dependencies: CloudHttpDependencies) {- yield* requireEnvironmentScope(AuthRelayReadScope);- return yield* readCloudLinkState(dependencies);- },- Effect.catchIf(- ServerSecretStore.isSecretStoreError,- failEnvironmentCloudInternalError("Could not read environment relay configuration."),- ),-);--const cloudUnlinkHandler = Effect.fn("environment.cloud.unlink")(- function* (dependencies: CloudHttpDependencies) {- yield* requireEnvironmentScope(AuthRelayWriteScope);- const endpointRuntimeStatus = yield* dependencies.endpointRuntime.applyConfig(null);- yield* Effect.all(- [- dependencies.secrets.remove(CLOUD_LINKED_USER_ID),- dependencies.secrets.remove(RELAY_URL_SECRET),- dependencies.secrets.remove(RELAY_ISSUER_SECRET),- dependencies.secrets.remove(RELAY_ENVIRONMENT_CREDENTIAL_SECRET),- dependencies.secrets.remove(CLOUD_MINT_PUBLIC_KEY),- dependencies.secrets.remove(CLOUD_ENDPOINT_RUNTIME_CONFIG),- dependencies.secrets.remove(PUBLISH_AGENT_ACTIVITY_SECRET),- ],- { concurrency: 7 },- );- yield* setCliDesiredCloudLink(false);- return { ok: true, endpointRuntimeStatus } satisfies EnvironmentCloudRelayConfigResult;- },- Effect.catchIf(- ServerSecretStore.isSecretStoreError,- failEnvironmentCloudInternalError("Could not remove environment relay configuration."),- ),-);--const cloudPreferencesHandler = Effect.fn("environment.cloud.preferences")(- function* (- dependencies: CloudHttpDependencies,- payload: { readonly publishAgentActivity: boolean },- ) {- yield* requireEnvironmentScope(AuthRelayWriteScope);- yield* dependencies.secrets.set(- PUBLISH_AGENT_ACTIVITY_SECRET,- stringToBytes(String(payload.publishAgentActivity)),- );- return yield* readCloudLinkState(dependencies);- },- Effect.catchIf(- ServerSecretStore.isSecretStoreError,- failEnvironmentCloudInternalError("Could not persist environment cloud preferences."),- ),-);--const cloudEnvironmentHealthHandler = Effect.fn("environment.cloud.health")(- function* (dependencies: CloudHttpDependencies, request: RelayCloudEnvironmentHealthRequest) {- const cloudMintPublicKey = yield* dependencies.secrets- .get(CLOUD_MINT_PUBLIC_KEY)- .pipe(- Effect.flatMap((bytes) =>- Option.isSome(bytes)- ? Effect.succeed(bytesToString(bytes.value))- : Effect.fail(new EnvironmentAuth.ServerAuthCloudMintPublicKeyMissingError({})),- ),- );- const relayIssuer = yield* dependencies.secrets- .get(RELAY_ISSUER_SECRET)- .pipe(- Effect.flatMap((bytes) =>- Option.isSome(bytes)- ? Effect.succeed(bytesToString(bytes.value))- : dependencies.secrets- .get(RELAY_URL_SECRET)- .pipe(- Effect.flatMap((fallbackBytes) =>- Option.isSome(fallbackBytes)- ? Effect.succeed(bytesToString(fallbackBytes.value))- : Effect.fail(new EnvironmentAuth.ServerAuthCloudRelayIssuerMissingError({})),- ),- ),- ),- );- const environmentId = yield* dependencies.environment.getEnvironmentId;- const linkedCloudUserId = yield* readInstalledCloudUserId(dependencies.secrets);- const now = yield* DateTime.now;- const nowSeconds = Math.floor(now.epochMilliseconds / 1_000);- const proofOption = yield* verifyRelayJwt({- publicKey: cloudMintPublicKey,- token: request.proof,- typ: RELAY_HEALTH_REQUEST_TYP,- issuer: normalizeRelayIssuer(relayIssuer),- audience: `t3-env:${environmentId}`,- nowEpochSeconds: nowSeconds,- }).pipe(Effect.flatMap(decodeCloudHealthProof), Effect.option);- if (- Option.isNone(proofOption) ||- proofOption.value.environmentId !== environmentId ||- proofOption.value.sub !== linkedCloudUserId ||- !hasBoundedCloudProofLifetime({ ...proofOption.value, nowSeconds }) ||- !hasExactScope({ scopes: proofOption.value.scope, expected: "environment:status" })- ) {- return yield* new EnvironmentHttpUnauthorizedError({- message: "Invalid cloud health request.",- });- }- const proof = proofOption.value;-- const jtiSecretName = `${CLOUD_HEALTH_JTI_PREFIX}${proof.jti}`;- const nonceSecretName = `${CLOUD_HEALTH_NONCE_PREFIX}${proof.nonce}`;- const consumedReplayGuards = yield* consumeCloudReplayGuards({- secrets: dependencies.secrets,- names: [jtiSecretName, nonceSecretName],- value: stringToBytes(DateTime.formatIso(now)),- });- if (!consumedReplayGuards) {- return yield* new EnvironmentHttpConflictError({- message: "Cloud health request was already consumed.",- });- }-- const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(dependencies.secrets);- const descriptor = yield* dependencies.environment.getDescriptor;- const responseExpiresAt = DateTime.add(now, { minutes: 5 });- const responsePayload = {- iss: `t3-env:${environmentId}`,- aud: normalizeRelayIssuer(relayIssuer),- sub: environmentId,- jti: yield* Crypto.Crypto.pipe(Effect.flatMap((crypto) => crypto.randomUUIDv4)),- iat: nowSeconds,- exp: Math.floor(responseExpiresAt.epochMilliseconds / 1_000),- environmentId,- requestNonce: proof.nonce,- status: "online",- descriptor,- checkedAt: DateTime.formatIso(now),- } satisfies RelayEnvironmentHealthResponseProofPayload;- const responseProof = yield* signRelayJwt({- privateKey: keyPair.privateKey,- typ: RELAY_HEALTH_RESPONSE_TYP,- payload: responsePayload,- }).pipe(- Effect.mapError(- (cause) =>- new EnvironmentAuth.ServerAuthCloudHealthJwtSigningError({- cause,- }),- ),- );- const response = {- environmentId,- status: "online",- descriptor,- checkedAt: responsePayload.checkedAt,- proof: responseProof,- } satisfies RelayEnvironmentHealthResponseShape;-- yield* appendCloudCredentialResponseHeaders;- return response;- },- Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>- failEnvironmentCloudInternalError(error.message)(error),- ),- Effect.catchIf(- ServerSecretStore.isSecretStoreError,- failEnvironmentCloudInternalError("Could not answer cloud health request."),- ),- Effect.catchTag(- "PlatformError",- failEnvironmentCloudInternalError("Could not answer cloud health request."),- ),-);--const cloudMintCredentialHandler = Effect.fn("environment.cloud.mintCredential")(- function* (dependencies: CloudHttpDependencies, request: RelayCloudMintCredentialRequest) {- const cloudMintPublicKey = yield* dependencies.secrets- .get(CLOUD_MINT_PUBLIC_KEY)- .pipe(- Effect.flatMap((bytes) =>- Option.isSome(bytes)- ? Effect.succeed(bytesToString(bytes.value))- : Effect.fail(new EnvironmentAuth.ServerAuthCloudMintPublicKeyMissingError({})),- ),- );- const relayIssuer = yield* dependencies.secrets- .get(RELAY_ISSUER_SECRET)- .pipe(- Effect.flatMap((bytes) =>- Option.isSome(bytes)- ? Effect.succeed(bytesToString(bytes.value))- : dependencies.secrets- .get(RELAY_URL_SECRET)- .pipe(- Effect.flatMap((fallbackBytes) =>- Option.isSome(fallbackBytes)- ? Effect.succeed(bytesToString(fallbackBytes.value))- : Effect.fail(new EnvironmentAuth.ServerAuthCloudRelayIssuerMissingError({})),- ),- ),- ),- );- const environmentId = yield* dependencies.environment.getEnvironmentId;- const linkedCloudUserId = yield* readInstalledCloudUserId(dependencies.secrets);- const now = yield* DateTime.now;- const nowSeconds = Math.floor(now.epochMilliseconds / 1_000);- const proofOption = yield* verifyRelayJwt({- publicKey: cloudMintPublicKey,- token: request.proof,- typ: RELAY_MINT_REQUEST_TYP,- issuer: normalizeRelayIssuer(relayIssuer),- audience: `t3-env:${environmentId}`,- nowEpochSeconds: nowSeconds,- }).pipe(Effect.flatMap(decodeCloudMintProof), Effect.option);- if (- Option.isNone(proofOption) ||- proofOption.value.environmentId !== environmentId ||- proofOption.value.sub !== linkedCloudUserId ||- proofOption.value.cnf.jkt !== proofOption.value.clientProofKeyThumbprint ||- !hasBoundedCloudProofLifetime({ ...proofOption.value, nowSeconds }) ||- !hasExactScope({ scopes: proofOption.value.scope, expected: "environment:connect" })- ) {- return yield* new EnvironmentHttpUnauthorizedError({- message: "Invalid cloud mint request.",- });- }- const proof = proofOption.value;-- const jtiSecretName = `${CLOUD_MINT_JTI_PREFIX}${proof.jti}`;- const nonceSecretName = `${CLOUD_MINT_NONCE_PREFIX}${proof.nonce}`;- const consumedReplayGuards = yield* consumeCloudReplayGuards({- secrets: dependencies.secrets,- names: [jtiSecretName, nonceSecretName],- value: stringToBytes(DateTime.formatIso(now)),- });- if (!consumedReplayGuards) {- return yield* new EnvironmentHttpConflictError({- message: "Cloud mint request was already consumed.",- });- }-- const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(dependencies.secrets);- const issued = yield* dependencies.environmentAuth.createPairingLink({- scopes: AuthStandardClientScopes,- subject: "cloud-connect",- ttl: Duration.minutes(2),- label: "T3 Connect connect",- proofKeyThumbprint: proof.clientProofKeyThumbprint,- });- const responsePayload = {- iss: `t3-env:${environmentId}`,- aud: normalizeRelayIssuer(relayIssuer),- sub: environmentId,- jti: yield* Crypto.Crypto.pipe(Effect.flatMap((crypto) => crypto.randomUUIDv4)),- iat: nowSeconds,- exp: Math.floor(issued.expiresAt.epochMilliseconds / 1_000),- environmentId,- clientProofKeyThumbprint: proof.clientProofKeyThumbprint,- requestNonce: proof.nonce,- credential: issued.credential,- } satisfies RelayEnvironmentMintResponseProofPayload;- const responseProof = yield* signRelayJwt({- privateKey: keyPair.privateKey,- typ: RELAY_MINT_RESPONSE_TYP,- payload: responsePayload,- }).pipe(- Effect.mapError(- (cause) =>- new EnvironmentAuth.ServerAuthCloudMintJwtSigningError({- cause,- }),- ),- );- const response = {- credential: issued.credential,- expiresAt: DateTime.formatIso(issued.expiresAt),- proof: responseProof,- } satisfies RelayEnvironmentMintResponseShape;-- yield* appendCloudCredentialResponseHeaders;- return response;- },- Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>- failEnvironmentCloudInternalError(error.message)(error),- ),- Effect.catchIf(- ServerSecretStore.isSecretStoreError,- failEnvironmentCloudInternalError("Could not issue cloud connection credential."),- ),- Effect.catchTag(- "PlatformError",- failEnvironmentCloudInternalError("Could not issue cloud connection credential."),- ),-);--export const connectHttpApiLayer = HttpApiBuilder.group(- EnvironmentHttpApi,- "connect",- Effect.fnUntraced(function* (handlers) {- const dependencies = yield* cloudHttpDependencies;- return handlers- .handle("linkProof", ({ payload }) => cloudLinkProofHandler(dependencies, payload))- .handle("relayConfig", ({ payload }) => cloudRelayConfigHandler(dependencies, payload))- .handle("linkState", () => cloudLinkStateHandler(dependencies))- .handle("unlink", () => cloudUnlinkHandler(dependencies))- .handle("preferences", ({ payload }) => cloudPreferencesHandler(dependencies, payload))- .handle("health", ({ payload }) => cloudEnvironmentHealthHandler(dependencies, payload))- .handle("mintCredential", ({ payload }) => cloudMintCredentialHandler(dependencies, payload))- .handle("t3MintCredential", ({ payload }) =>- traceRelayRequest(cloudMintCredentialHandler(dependencies, payload)),- );- }),-);diff --git a/apps/server/src/cloud/publicConfig.test.ts b/apps/server/src/cloud/publicConfig.test.tsdeleted file mode 100644index f8324f947..000000000--- a/apps/server/src/cloud/publicConfig.test.ts+++ /dev/null@@ -1,181 +0,0 @@-import { assert, it } from "@effect/vitest";-import * as ConfigProvider from "effect/ConfigProvider";-import * as Effect from "effect/Effect";-import * as Result from "effect/Result";--import {- hostedAppUrlConfig,- makeCloudCliOAuthConfig,- makeRelayUrlConfig,- resolveRelayClientTracingConfig,-} from "./publicConfig.ts";--const provideEnv = (env: Readonly<Record<string, string>>) =>- Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env })));--it.effect("uses the statically injected relay URL when no runtime override exists", () =>- Effect.gen(function* () {- const relayUrl = yield* makeRelayUrlConfig("https://embedded.example.test///").pipe(- provideEnv({}),- );-- assert.equal(relayUrl, "https://embedded.example.test");- }),-);--it.effect("prefers a runtime relay URL override over the statically injected value", () =>- Effect.gen(function* () {- const relayUrl = yield* makeRelayUrlConfig("https://embedded.example.test").pipe(- provideEnv({ T3CODE_RELAY_URL: "https://runtime.example.test///" }),- );-- assert.equal(relayUrl, "https://runtime.example.test");- }),-);--it.effect("requires a relay URL when the server bundle has no injected value", () =>- makeRelayUrlConfig("").pipe(provideEnv({}), Effect.flip),-);--it.effect("rejects an insecure runtime relay URL override", () =>- makeRelayUrlConfig("https://embedded.example.test").pipe(- provideEnv({ T3CODE_RELAY_URL: "http://runtime.example.test" }),- Effect.flip,- ),-);--it.effect("rejects an injected relay URL with a non-origin path", () =>- makeRelayUrlConfig("https://embedded.example.test/path").pipe(provideEnv({}), Effect.flip),-);--it.effect("normalizes the hosted app URL to an absolute origin", () =>- Effect.gen(function* () {- assert.equal(- yield* hostedAppUrlConfig.pipe(- provideEnv({ T3CODE_HOSTED_APP_URL: "https://nightly.app.t3.codes" }),- ),- "https://nightly.app.t3.codes",- );- assert.equal(- yield* hostedAppUrlConfig.pipe(- provideEnv({ T3CODE_HOSTED_APP_URL: "http://localhost:5733" }),- ),- "http://localhost:5733",- );- }),-);--it.effect("rejects malformed or insecure hosted app URLs", () =>- Effect.gen(function* () {- for (const value of [- "app.t3.codes",- "http://app.t3.codes",- "https://app.t3.codes/nested",- "https://app.t3.codes?alias=true",- ]) {- const result = yield* hostedAppUrlConfig.pipe(- provideEnv({ T3CODE_HOSTED_APP_URL: value }),- Effect.result,- );- assert.isTrue(Result.isFailure(result), value);- }- }),-);--it.effect("derives direct Clerk OAuth endpoints from statically injected public config", () =>- Effect.gen(function* () {- const config = yield* makeCloudCliOAuthConfig({- clerkPublishableKeyFallback: "pk_test_Y2xlcmsuZXhhbXBsZS50ZXN0JA==",- clerkCliOAuthClientIdFallback: "oauth_client_embedded",- }).pipe(provideEnv({}));-- assert.deepEqual(config, {- tokenEndpoint: "https://clerk.example.test/oauth/token",- clientId: "oauth_client_embedded",- loopbackPort: 34338,- redirectUri: "http://127.0.0.1:34338/callback",- scopes: ["openid", "profile", "email"],- });- }),-);--it.effect("prefers runtime Clerk OAuth config overrides over statically injected values", () =>- Effect.gen(function* () {- const config = yield* makeCloudCliOAuthConfig({- clerkPublishableKeyFallback: "pk_test_ZW1iZWRkZWQuZXhhbXBsZS50ZXN0JA==",- clerkCliOAuthClientIdFallback: "oauth_client_embedded",- }).pipe(- provideEnv({- T3CODE_CLERK_PUBLISHABLE_KEY: "pk_test_cnVudGltZS5leGFtcGxlLnRlc3Qk",- T3CODE_CLERK_CLI_OAUTH_CLIENT_ID: "oauth_client_runtime",- }),- );-- assert.equal(config.tokenEndpoint, "https://runtime.example.test/oauth/token");- assert.equal(config.clientId, "oauth_client_runtime");- }),-);--it.effect("requires Clerk OAuth config when the server bundle has no injected values", () =>- makeCloudCliOAuthConfig({- clerkPublishableKeyFallback: "",- clerkCliOAuthClientIdFallback: "",- }).pipe(provideEnv({}), Effect.flip),-);--it.effect("reports malformed Clerk publishable keys as typed configuration failures", () =>- Effect.gen(function* () {- const result = yield* makeCloudCliOAuthConfig({- clerkPublishableKeyFallback: "pk_test_not-base64!!",- clerkCliOAuthClientIdFallback: "oauth_client_embedded",- }).pipe(provideEnv({}), Effect.result);-- assert.isTrue(Result.isFailure(result));- if (Result.isFailure(result)) {- assert.equal(result.failure.cause._tag, "SourceError");- if (result.failure.cause._tag === "SourceError") {- assert.equal(- result.failure.cause.message,- "Failed to derive Clerk Frontend API URL from the publishable key.",- );- assert.instanceOf(result.failure.cause.cause, Error);- }- }- }),-);--it("resolves relay client tracing from runtime config with build-time fallback", () => {- const fallback = {- tracesUrl: "https://embedded.example.test/v1/traces",- tracesDataset: "embedded-dataset",- tracesToken: "embedded-token",- };-- assert.deepEqual(resolveRelayClientTracingConfig({}, fallback), fallback);- assert.deepEqual(- resolveRelayClientTracingConfig(- {- T3CODE_RELAY_CLIENT_OTLP_TRACES_URL: "https://runtime.example.test/v1/traces",- T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET: "runtime-dataset",- T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN: "runtime-token",- },- fallback,- ),- {- tracesUrl: "https://runtime.example.test/v1/traces",- tracesDataset: "runtime-dataset",- tracesToken: "runtime-token",- },- );- assert.equal(- resolveRelayClientTracingConfig(- {- T3CODE_RELAY_CLIENT_OTLP_TRACES_URL: "http://insecure.example.test/v1/traces",- T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET: "runtime-dataset",- T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN: "runtime-token",- },- fallback,- ),- null,- );-});diff --git a/apps/server/src/cloud/publicConfig.ts b/apps/server/src/cloud/publicConfig.tsdeleted file mode 100644index e977d7cfd..000000000--- a/apps/server/src/cloud/publicConfig.ts+++ /dev/null@@ -1,215 +0,0 @@-import {- connectLoopbackRedirectUri,- CONNECT_OAUTH_SCOPES,- DEFAULT_HOSTED_APP_URL,-} from "@t3tools/shared/connectAuth";-import { clerkFrontendApiUrlFromPublishableKey } from "@t3tools/shared/relayAuth";-import { normalizeSecureRelayUrl } from "@t3tools/shared/relayUrl";-import * as Config from "effect/Config";-import * as ConfigProvider from "effect/ConfigProvider";-import * as Effect from "effect/Effect";-import * as Schema from "effect/Schema";-import * as SchemaIssue from "effect/SchemaIssue";--declare const __T3CODE_BUILD_RELAY_URL__: string | undefined;-declare const __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: string | undefined;-declare const __T3CODE_BUILD_CLERK_CLI_OAUTH_CLIENT_ID__: string | undefined;-declare const __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_URL__: string | undefined;-declare const __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_DATASET__: string | undefined;-declare const __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_TOKEN__: string | undefined;--const CLOUD_CLI_OAUTH_LOOPBACK_PORT = 34338;-const CLOUD_CLI_OAUTH_SCOPES = CONNECT_OAUTH_SCOPES;--function validateRelayUrl(value: string) {- const relayUrl = normalizeSecureRelayUrl(value);- return relayUrl === null- ? Effect.fail(- new Config.ConfigError(- new Schema.SchemaError(- new SchemaIssue.InvalidValue({- message: "Relay URL must be a secure absolute HTTPS origin.",- }),- ),- ),- )- : Effect.succeed(relayUrl);-}--function readBuildTimeValue(value: string | undefined): string {- return typeof value === "undefined" ? "" : value.trim();-}--function normalizeSecureUrl(value: string): string | null {- try {- const url = new URL(value);- return url.protocol === "https:" ? url.toString() : null;- } catch {- return null;- }-}--export const buildTimeRelayUrl =- typeof __T3CODE_BUILD_RELAY_URL__ === "undefined"- ? ""- : (normalizeSecureRelayUrl(__T3CODE_BUILD_RELAY_URL__) ?? "");-export const buildTimeClerkPublishableKey = readBuildTimeValue(- typeof __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__ === "undefined"- ? undefined- : __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__,-);-export const buildTimeClerkCliOAuthClientId = readBuildTimeValue(- typeof __T3CODE_BUILD_CLERK_CLI_OAUTH_CLIENT_ID__ === "undefined"- ? undefined- : __T3CODE_BUILD_CLERK_CLI_OAUTH_CLIENT_ID__,-);-export const buildTimeRelayClientTracing = {- tracesUrl: readBuildTimeValue(- typeof __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_URL__ === "undefined"- ? undefined- : __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_URL__,- ),- tracesDataset: readBuildTimeValue(- typeof __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_DATASET__ === "undefined"- ? undefined- : __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_DATASET__,- ),- tracesToken: readBuildTimeValue(- typeof __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_TOKEN__ === "undefined"- ? undefined- : __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_TOKEN__,- ),-} as const;--export function resolveRelayClientTracingConfig(- env: Readonly<Record<string, string | undefined>> = process.env,- fallback = buildTimeRelayClientTracing,-) {- const tracesUrl = env.T3CODE_RELAY_CLIENT_OTLP_TRACES_URL?.trim() || fallback.tracesUrl;- const tracesDataset =- env.T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET?.trim() || fallback.tracesDataset;- const tracesToken = env.T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN?.trim() || fallback.tracesToken;- const normalizedTracesUrl = normalizeSecureUrl(tracesUrl);- return normalizedTracesUrl && tracesDataset && tracesToken- ? { tracesUrl: normalizedTracesUrl, tracesDataset, tracesToken }- : null;-}--export function makeRelayUrlConfig(fallback = buildTimeRelayUrl) {- const runtimeConfig = Config.nonEmptyString("T3CODE_RELAY_URL");- return (fallback ? runtimeConfig.pipe(Config.withDefault(fallback)) : runtimeConfig).pipe(- Config.mapOrFail(validateRelayUrl),- );-}--export const relayUrlConfig = makeRelayUrlConfig();--/**- * Hosted app origin used for out-of-band OAuth on headless- * machines. Overridable so staging/nightly builds can point their CLIs at a- * matching hosted deployment.- */-export const hostedAppUrlConfig = makePublicValueConfig(- "T3CODE_HOSTED_APP_URL",- DEFAULT_HOSTED_APP_URL,-).pipe(Config.mapOrFail(validateHostedAppUrl));--function validateHostedAppUrl(value: string) {- try {- const url = new URL(value);- const isLoopbackHttp =- url.protocol === "http:" &&- (url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]");- if (- (url.protocol !== "https:" && !isLoopbackHttp) ||- url.pathname !== "/" ||- url.search !== "" ||- url.hash !== ""- ) {- throw new Error("invalid hosted app origin");- }- return Effect.succeed(url.origin);- } catch {- return Effect.fail(- new Config.ConfigError(- new Schema.SchemaError(- new SchemaIssue.InvalidValue({- message: "Hosted app URL must be an absolute HTTPS origin (or HTTP loopback origin).",- }),- ),- ),- );- }-}--function makePublicValueConfig(name: string, fallback: string) {- const runtimeConfig = Config.nonEmptyString(name);- return (fallback ? runtimeConfig.pipe(Config.withDefault(fallback)) : runtimeConfig).pipe(- Config.map((value) => value.trim()),- );-}--/**- * The CLI never calls Clerk's /oauth/authorize itself: the browser leg goes- * through the hosted /connect page, which builds the authorize URL after a- * Clerk session exists (see CliTokenManager.login). Only the token endpoint- * is contacted directly.- */-export interface CloudCliOAuthConfig {- readonly tokenEndpoint: string;- readonly clientId: string;- readonly loopbackPort: number;- readonly redirectUri: string;- readonly scopes: typeof CLOUD_CLI_OAUTH_SCOPES;-}--export function makeCloudCliOAuthConfig({- clerkPublishableKeyFallback = buildTimeClerkPublishableKey,- clerkCliOAuthClientIdFallback = buildTimeClerkCliOAuthClientId,-}: {- readonly clerkPublishableKeyFallback?: string;- readonly clerkCliOAuthClientIdFallback?: string;-} = {}) {- return Config.all({- clerkPublishableKey: makePublicValueConfig(- "T3CODE_CLERK_PUBLISHABLE_KEY",- clerkPublishableKeyFallback,- ),- clientId: makePublicValueConfig(- "T3CODE_CLERK_CLI_OAUTH_CLIENT_ID",- clerkCliOAuthClientIdFallback,- ),- }).pipe(- Config.mapOrFail(({ clerkPublishableKey, clientId }) =>- Effect.try({- try: () => clerkFrontendApiUrlFromPublishableKey(clerkPublishableKey),- catch: (cause) =>- new Config.ConfigError(- new ConfigProvider.SourceError({- message: "Failed to derive Clerk Frontend API URL from the publishable key.",- cause,- }),- ),- }).pipe(- Effect.map(- (clerkFrontendApiUrl) =>- ({- tokenEndpoint: `${clerkFrontendApiUrl}/oauth/token`,- clientId,- loopbackPort: CLOUD_CLI_OAUTH_LOOPBACK_PORT,- redirectUri: connectLoopbackRedirectUri(CLOUD_CLI_OAUTH_LOOPBACK_PORT),- scopes: CLOUD_CLI_OAUTH_SCOPES,- }) satisfies CloudCliOAuthConfig,- ),- ),- ),- );-}--export const cloudCliOAuthConfig = makeCloudCliOAuthConfig();--export const hasCloudPublicConfig = Boolean(- (normalizeSecureRelayUrl(process.env.T3CODE_RELAY_URL ?? "") ?? buildTimeRelayUrl) &&- (process.env.T3CODE_CLERK_PUBLISHABLE_KEY?.trim() || buildTimeClerkPublishableKey) &&- (process.env.T3CODE_CLERK_CLI_OAUTH_CLIENT_ID?.trim() || buildTimeClerkCliOAuthClientId),-);diff --git a/apps/server/src/cloud/relayTracing.ts b/apps/server/src/cloud/relayTracing.tsdeleted file mode 100644index e35c94545..000000000--- a/apps/server/src/cloud/relayTracing.ts+++ /dev/null@@ -1,21 +0,0 @@-import { makeRelayClientTracingLayer } from "@t3tools/shared/relayTracing";--import { resolveRelayClientTracingConfig } from "./publicConfig.ts";--const relayClientTracingConfig = resolveRelayClientTracingConfig();--export const headlessRelayClientTracingLayer = makeRelayClientTracingLayer(- relayClientTracingConfig,- {- serviceName: "t3-headless-relay-client",- runtime: "node",- client: "headless-cli",- },-);--export const serverRelayBrokerTracingLayer = makeRelayClientTracingLayer(relayClientTracingConfig, {- serviceName: "t3-server",- runtime: "node",- client: "environment-server",- component: "relay-broker",-});diff --git a/apps/server/src/cloud/traceRelayRequest.ts b/apps/server/src/cloud/traceRelayRequest.tsdeleted file mode 100644index 1481b8912..000000000--- a/apps/server/src/cloud/traceRelayRequest.ts+++ /dev/null@@ -1,21 +0,0 @@-import { withRelayClientTracing } from "@t3tools/shared/relayTracing";-import * as Effect from "effect/Effect";-import * as Option from "effect/Option";-import { HttpServerRequest, HttpTraceContext } from "effect/unstable/http";--export const traceRelayRequest = <A, E, R>(- effect: Effect.Effect<A, E, R>,-): Effect.Effect<A, E, R> => effect.pipe(withRelayClientTracing);--export const traceAuthenticatedRelayRequest = <A, E, R>(- effect: Effect.Effect<A, E, R>,-): Effect.Effect<A, E, R | HttpServerRequest.HttpServerRequest> =>- HttpServerRequest.HttpServerRequest.pipe(- Effect.flatMap((request) =>- Option.match(HttpTraceContext.fromHeaders(request.headers), {- onNone: () => effect,- onSome: (parent) => effect.pipe(Effect.withParentSpan(parent)),- }),- ),- withRelayClientTracing,- );diff --git a/apps/server/src/environment/ServerEnvironment.test.ts b/apps/server/src/environment/ServerEnvironment.test.tsindex 531d06121..04175683b 100644--- a/apps/server/src/environment/ServerEnvironment.test.ts+++ b/apps/server/src/environment/ServerEnvironment.test.ts@@ -3,16 +3,9 @@ import { expect, it } from "@effect/vitest";import * as Effect from "effect/Effect";import * as FileSystem from "effect/FileSystem";import * as Layer from "effect/Layer";-import * as Option from "effect/Option";import * as PlatformError from "effect/PlatformError";import * as Schema from "effect/Schema";-import * as ServerSecretStore from "../auth/ServerSecretStore.ts";-import {- PUBLISH_AGENT_ACTIVITY_SECRET,- RELAY_ENVIRONMENT_CREDENTIAL_SECRET,- RELAY_URL_SECRET,-} from "../cloud/config.ts";import * as ServerConfig from "../config.ts";import * as ServerEnvironment from "./ServerEnvironment.ts";@@ -21,21 +14,7 @@ const isServerEnvironmentIdPersistenceError = Schema.is();const makeServerEnvironmentLayer = (baseDir: string) =>- ServerEnvironment.layer.pipe(- Layer.provide(ServerSecretStore.layer),- Layer.provide(ServerConfig.layerTest(process.cwd(), baseDir)),- );--const emptySecretStoreLayer = Layer.succeed(- ServerSecretStore.ServerSecretStore,- ServerSecretStore.ServerSecretStore.of({- get: () => Effect.succeed(Option.none()),- set: () => Effect.void,- create: () => Effect.void,- getOrCreateRandom: () => Effect.succeed(new Uint8Array()),- remove: () => Effect.void,- }),-);+ ServerEnvironment.layer.pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), baseDir)));const makeServerConfig = Effect.fn(function* (baseDir: string) {const derivedPaths = yield* ServerConfig.deriveServerPaths(baseDir, undefined);@@ -94,53 +73,6 @@ it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => {expect(second.capabilities.pullRequests).toBe(true);expect(second.capabilities.threadTitleRegeneration).toBe(true);expect(second.capabilities.threadPullRequestLinking).toBe(true);- expect(second.capabilities.agentActivityPublishing).toBe(false);- }),- );-- it.effect("reports agent activity publishing from the current secret state", () =>- Effect.gen(function* () {- const fileSystem = yield* FileSystem.FileSystem;- const baseDir = yield* fileSystem.makeTempDirectoryScoped({- prefix: "t3-server-environment-publish-test-",- });- const testLayer = Layer.mergeAll(- ServerEnvironment.layer.pipe(Layer.provide(ServerSecretStore.layer)),- ServerSecretStore.layer,- ).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), baseDir)));-- yield* Effect.gen(function* () {- const secrets = yield* ServerSecretStore.ServerSecretStore;- const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;- const encode = (value: string) => new TextEncoder().encode(value);-- const unlinked = yield* serverEnvironment.getDescriptor;- expect(unlinked.capabilities.agentActivityPublishing).toBe(false);-- // The opt-in alone is not enough: without relay link credentials no- // publish would leave this environment.- yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, encode("true"));- const withoutLink = yield* serverEnvironment.getDescriptor;- expect(withoutLink.capabilities.agentActivityPublishing).toBe(false);-- // Empty credentials are as unconfigured as missing ones: the- // publisher's truthiness gate skips them, so the capability must not- // advertise publishing.- yield* secrets.set(RELAY_URL_SECRET, encode(""));- yield* secrets.set(RELAY_ENVIRONMENT_CREDENTIAL_SECRET, encode("credential"));- const emptyUrl = yield* serverEnvironment.getDescriptor;- expect(emptyUrl.capabilities.agentActivityPublishing).toBe(false);-- yield* secrets.set(RELAY_URL_SECRET, encode("https://relay.example"));- const linked = yield* serverEnvironment.getDescriptor;- expect(linked.capabilities.agentActivityPublishing).toBe(true);-- // The toggle changes at runtime, so the same service instance must- // reflect a flip without a restart.- yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, encode("false"));- const disabled = yield* serverEnvironment.getDescriptor;- expect(disabled.capabilities.agentActivityPublishing).toBe(false);- }).pipe(Effect.provide(testLayer));}),);@@ -183,7 +115,6 @@ it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => {}).pipe(Effect.provide(ServerEnvironment.layer.pipe(- Layer.provide(emptySecretStoreLayer),Layer.provide(Layer.merge(ServerConfig.layer(serverConfig), failingFileSystemLayer)),),),diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.tsindex b9bea4ee7..8b3c6f016 100644--- a/apps/server/src/environment/ServerEnvironment.ts+++ b/apps/server/src/environment/ServerEnvironment.ts@@ -9,8 +9,6 @@ import * as Path from "effect/Path";import * as Schema from "effect/Schema";import packageJson from "../../package.json" with { type: "json" };-import * as ServerSecretStore from "../auth/ServerSecretStore.ts";-import { readAgentActivityPublishingActive } from "../cloud/config.ts";import { resolveServerSelfUpdateCapability } from "../cloud/selfUpdate.ts";import { resolveServiceLauncherMode } from "../cloud/serviceLauncherClient.ts";import * as ServerConfig from "../config.ts";@@ -68,7 +66,6 @@ export const make = Effect.gen(function* () {const fileSystem = yield* FileSystem.FileSystem;const path = yield* Path.Path;const serverConfig = yield* ServerConfig.ServerConfig;- const secrets = yield* ServerSecretStore.ServerSecretStore;const crypto = yield* Crypto.Crypto;const hostPlatform = yield* HostProcessPlatform;const hostArchitecture = yield* HostProcessArchitecture;@@ -161,22 +158,13 @@ export const make = Effect.gen(function* () {return ServerEnvironment.of({getEnvironmentId: Effect.succeed(environmentId),- // The publish opt-in and relay link change at runtime (`akeru connect- // publish`, the client settings toggle), so the capability is read per- // descriptor request rather than baked in at startup.- getDescriptor: readAgentActivityPublishingActive(secrets).pipe(- Effect.map((agentActivityPublishing) => ({- ...descriptor,- capabilities: { ...descriptor.capabilities, agentActivityPublishing },- })),- ),+ getDescriptor: Effect.succeed(descriptor),});});/*** ServerEnvironment is acquired from persisted filesystem and host-process* state. It intentionally has no fallback Layer.succeed value: callers must- * provide the external platform services, a ServerConfig, and the- * ServerSecretStore backing the descriptor's publishing capability.+ * provide the external platform services and a ServerConfig.*/export const layer = Layer.effect(ServerEnvironment, make).pipe(Layer.provide(ProcessRunner.layer));diff --git a/apps/server/src/http.ts b/apps/server/src/http.tsindex c3104e7bc..84b041717 100644--- a/apps/server/src/http.ts+++ b/apps/server/src/http.ts@@ -35,7 +35,6 @@ import {} from "./assets/AttachmentUpload.ts";import * as BrowserTraceCollector from "./observability/BrowserTraceCollector.ts";import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";-import { traceRelayRequest } from "./cloud/traceRelayRequest.ts";import {annotateEnvironmentRequest,failEnvironmentScopeRequired,@@ -138,7 +137,7 @@ export const serverEnvironmentHttpApiLayer = HttpApiBuilder.group(Effect.fn("environment.metadata.descriptor")(function* (args) {yield* annotateEnvironmentRequest(args.endpoint.name);return yield* serverEnvironment.getDescriptor;- }, traceRelayRequest),+ }),);}),);diff --git a/apps/server/src/httpCors.ts b/apps/server/src/httpCors.tsindex aeb8dbce5..e44486d3c 100644--- a/apps/server/src/httpCors.ts+++ b/apps/server/src/httpCors.ts@@ -4,7 +4,6 @@ export const browserApiCorsAllowedHeaders = ["b3","traceparent","content-type",- "dpop",] as const;export const browserApiCorsHeaders = {diff --git a/apps/server/src/mcp/McpHttpServer.test.ts b/apps/server/src/mcp/McpHttpServer.test.tsindex d97fd2901..24bb49765 100644--- a/apps/server/src/mcp/McpHttpServer.test.ts+++ b/apps/server/src/mcp/McpHttpServer.test.ts@@ -173,6 +173,19 @@ it.effect("registers annotated tools and preserves authenticated request contextyield* Stream.runForEach(events, (event) => {if (event.type === "connected") return Effect.void;routedRequests.push(event.request);+ if (event.request.operation === "navigate") {+ return broker.respond({+ clientId: "mcp-test-client",+ connectionId: event.connectionId,+ requestId: event.request.requestId,+ ok: false,+ error: {+ _tag: "PreviewAutomationExecutionError",+ message: "host cause: provider-secret",+ detail: { token: "provider-secret" },+ },+ });+ }return broker.respond({clientId: "mcp-test-client",connectionId: event.connectionId,@@ -197,16 +210,31 @@ it.effect("registers annotated tools and preserves authenticated request contextheight: 5,},}- : event.request.operation === "press"- ? undefined- : {- available: true,- visible: true,- tabId,- url: "http://example.test/",- title: "Example",- loading: false,- },+ : event.request.operation === "evaluate"+ ? {+ arbitrary: "unrecognizable-secret",+ chatPath: "/Users/leo/.akeru/chat.json",+ screenshot,+ }+ : event.request.operation === "recordingStop"+ ? {+ id: "recording-1",+ tabId,+ path: "/Users/leo/.akeru/browser-artifacts/recording.webm",+ mimeType: "video/webm",+ sizeBytes: 123,+ createdAt: "2026-01-01T00:00:00Z",+ }+ : event.request.operation === "press"+ ? undefined+ : {+ available: true,+ visible: true,+ tabId,+ url: "http://example.test/",+ title: "Example",+ loading: false,+ },});}).pipe(Effect.forkScoped);yield* Effect.yieldNow;@@ -276,6 +304,50 @@ it.effect("registers annotated tools and preserves authenticated request contextalternateTabId,);+ const evaluation = yield* server+ .callTool({ name: "preview_evaluate", arguments: { expression: "document.body" } })+ .pipe(+ Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),+ Effect.provideService(McpSchema.McpServerClient, client),+ );+ expect(evaluation.structuredContent).toEqual({+ redactionStatus: "omitted-unverified-preview-evaluation",+ });+ expect(evaluation.content).toEqual([+ {+ type: "text",+ text: '{"redactionStatus":"omitted-unverified-preview-evaluation"}',+ },+ ]);++ const recording = yield* server+ .callTool({ name: "preview_recording_stop", arguments: {} })+ .pipe(+ Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),+ Effect.provideService(McpSchema.McpServerClient, client),+ );+ expect(recording.structuredContent).toMatchObject({ path: "[REDACTED]" });+ expect(recording.content).toEqual([+ {+ type: "text",+ text: '{"id":"recording-1","tabId":"tab-mcp-test","path":"[REDACTED]","mimeType":"video/webm","sizeBytes":123,"createdAt":"2026-01-01T00:00:00Z"}',+ },+ ]);++ const navigation = yield* server+ .callTool({ name: "preview_navigate", arguments: { url: "https://example.test" } })+ .pipe(+ Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),+ Effect.provideService(McpSchema.McpServerClient, client),+ );+ expect(navigation.isError).toBe(true);+ expect(navigation.content).toEqual([+ {+ type: "text",+ text: "Preview automation navigate failed on client mcp-test-client.",+ },+ ]);+const actionRequests = [{ name: "preview_click", arguments: { x: 10, y: 10 } },{ name: "preview_type", arguments: { text: "Hello" } },diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.tsindex dfcb5ac24..f5eee59e4 100644--- a/apps/server/src/mcp/McpHttpServer.ts+++ b/apps/server/src/mcp/McpHttpServer.ts@@ -10,7 +10,6 @@ import { McpProtocol, McpSchema, McpServer, Tool } from "effect/unstable/ai";import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";import packageJson from "../../package.json" with { type: "json" };-import { redactPreviewSnapshot } from "./PreviewSnapshotRedaction.ts";import * as McpInvocationContext from "./McpInvocationContext.ts";import * as McpSessionRegistry from "./McpSessionRegistry.ts";import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts";@@ -175,14 +174,13 @@ const registerPreviewSnapshot = Effect.fn("McpHttpServer.registerPreviewSnapshotreadonly [key: string]: unknown;};const { screenshot, ...page } = snapshot;- const redacted = redactPreviewSnapshot(page, screenshot);const metadata = {- ...redacted.page,+ ...page,screenshot: {mimeType: screenshot.mimeType,width: screenshot.width,height: screenshot.height,- redacted: redacted.frameRedacted,+ redacted: true,},};return Effect.succeed(@@ -193,7 +191,7 @@ const registerPreviewSnapshot = Effect.fn("McpHttpServer.registerPreviewSnapshot{ type: "text", text: JSON.stringify(metadata) },{type: "image",- data: redacted.screenshot,+ data: new Uint8Array(Buffer.from(screenshot.data, "base64")),mimeType: screenshot.mimeType,},],diff --git a/apps/server/src/mcp/PreviewAutomationBroker.test.ts b/apps/server/src/mcp/PreviewAutomationBroker.test.tsindex 3bc0fd713..7cc894c79 100644--- a/apps/server/src/mcp/PreviewAutomationBroker.test.ts+++ b/apps/server/src/mcp/PreviewAutomationBroker.test.ts@@ -19,6 +19,7 @@ import * as Deferred from "effect/Deferred";import * as Fiber from "effect/Fiber";import * as Result from "effect/Result";import * as Stream from "effect/Stream";+import { PNG } from "pngjs";import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts";@@ -39,6 +40,37 @@ const makeHost = (overrides: Partial<PreviewAutomationHost> = {}): PreviewAutoma...overrides,});+const snapshotResult = (() => {+ const png = new PNG({ width: 1, height: 1 });+ png.data.fill(255);+ return {+ url: "http://localhost:3200",+ title: "Example",+ loading: false,+ visibleText: "Example",+ interactiveElements: [],+ accessibilityTree: {},+ consoleEntries: [],+ networkEntries: [],+ actionTimeline: [],+ screenshot: {+ mimeType: "image/png" as const,+ data: PNG.sync.write(png).toString("base64"),+ width: 1,+ height: 1,+ },+ };+})();++const recordingResult = (tabId: PreviewTabId) => ({+ id: "recording-1",+ tabId,+ path: "/Users/leo/.akeru/browser-artifacts/recording.webm",+ mimeType: "video/webm",+ sizeBytes: 123,+ createdAt: "2026-01-01T00:00:00Z",+});+type RoutedRequest = PreviewAutomationRequest & {readonly connectionId: PreviewAutomationStreamEvent["connectionId"];};@@ -84,6 +116,69 @@ it.effect("atomically registers a connected host and correlates its response", (),);+it.effect("fails closed when a provider-bound frame cannot be masked", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const broker = yield* makeBroker;+ const requests = requestsFrom(yield* broker.connect(makeHost()));+ yield* Stream.runForEach(requests, (request) =>+ broker.respond({+ clientId: "client-1",+ connectionId: request.connectionId,+ requestId: request.requestId,+ ok: true,+ result: {+ ...snapshotResult,+ screenshot: {+ ...snapshotResult.screenshot,+ data: Buffer.from("raw pixels").toString("base64"),+ },+ },+ }),+ ).pipe(Effect.forkScoped);+ yield* Effect.yieldNow;++ const error = yield* broker+ .invoke<void>({ scope, operation: "snapshot", input: {} })+ .pipe(Effect.flip);++ expect(error).toBeInstanceOf(PreviewAutomationMalformedResponseError);+ }),+ ),+);++it.effect("rejects screenshot payloads from non-snapshot operations", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const broker = yield* makeBroker;+ const requests = requestsFrom(yield* broker.connect(makeHost()));+ yield* Stream.runForEach(requests, (request) =>+ broker.respond({+ clientId: "client-1",+ connectionId: request.connectionId,+ requestId: request.requestId,+ ok: true,+ result:+ request.operation === "status"+ ? { data: "raw pixels", mimeType: "image/png" }+ : { screenshot: { data: "raw pixels" } },+ }),+ ).pipe(Effect.forkScoped);+ yield* Effect.yieldNow;++ const statusError = yield* broker+ .invoke<void>({ scope, operation: "status", input: {} })+ .pipe(Effect.flip);+ const navigateError = yield* broker+ .invoke<void>({ scope, operation: "navigate", input: { url: "https://example.test" } })+ .pipe(Effect.flip);++ expect(statusError).toBeInstanceOf(PreviewAutomationMalformedResponseError);+ expect(navigateError).toBeInstanceOf(PreviewAutomationMalformedResponseError);+ }),+ ),+);+it.effect("targets multiple tabs explicitly while retaining a default tab", () =>Effect.scoped(Effect.gen(function* () {@@ -104,7 +199,7 @@ it.effect("targets multiple tabs explicitly while retaining a default tab", () =result:request.operation === "open"? { available: true, tabId: openedTabIds[openIndex++] }- : { url: "http://localhost:3200" },+ : snapshotResult,});}).pipe(Effect.forkScoped);yield* Effect.yieldNow;@@ -147,7 +242,7 @@ it.effect("does not let an older response replace a newer explicit tab target",connectionId: request.connectionId,requestId: request.requestId,ok: true,- result: { url: "http://localhost:3200" },+ result: snapshotResult,});if (request.tabId === newerTabId) {yield* Deferred.succeed(releaseOlderResponse, undefined);@@ -192,8 +287,8 @@ it.effect("tracks the tab returned by a targeted recording stop", () =>request.operation === "open"? { available: true, tabId: browsingTabId }: request.operation === "recordingStop"- ? { id: "recording-1", tabId: recordingTabId }- : { url: "http://localhost:3200" },+ ? recordingResult(recordingTabId)+ : snapshotResult,});}).pipe(Effect.forkScoped);yield* Effect.yieldNow;@@ -234,7 +329,7 @@ it.effect("does not let a no-tab response suppress an earlier tab decision", ()result:request.operation === "open"? { available: true, tabId: marker === "older" ? openedTabId : initialTabId }- : { url: "http://localhost:3200" },+ : snapshotResult,});if (marker === "newer") {yield* Deferred.succeed(releaseOpenResponse, undefined);diff --git a/apps/server/src/mcp/PreviewAutomationBroker.ts b/apps/server/src/mcp/PreviewAutomationBroker.tsindex e0125df7a..5758d9679 100644--- a/apps/server/src/mcp/PreviewAutomationBroker.ts+++ b/apps/server/src/mcp/PreviewAutomationBroker.ts@@ -33,6 +33,7 @@ import * as Stream from "effect/Stream";import * as SynchronizedRef from "effect/SynchronizedRef";import * as McpInvocationContext from "./McpInvocationContext.ts";+import { redactProviderVisiblePreviewResult } from "./PreviewSnapshotRedaction.ts";export interface PreviewAutomationInvokeInput {readonly scope: McpInvocationContext.McpInvocationScope;@@ -412,7 +413,15 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {});if (!pending) return;if (response.ok) {- yield* Deferred.succeed(pending.deferred, response.result);+ yield* Effect.try({+ try: () => redactProviderVisiblePreviewResult(pending.context.operation, response.result),+ catch: () => new PreviewAutomationMalformedResponseError(pending.context),+ }).pipe(+ Effect.matchEffect({+ onFailure: (error) => Deferred.fail(pending.deferred, error),+ onSuccess: (result) => Deferred.succeed(pending.deferred, result),+ }),+ );} else {yield* Deferred.fail(pending.deferred,diff --git a/apps/server/src/mcp/PreviewSnapshotRedaction.test.ts b/apps/server/src/mcp/PreviewSnapshotRedaction.test.tsindex 186b93b78..ea39664cb 100644--- a/apps/server/src/mcp/PreviewSnapshotRedaction.test.ts+++ b/apps/server/src/mcp/PreviewSnapshotRedaction.test.ts@@ -1,8 +1,12 @@import { PNG } from "pngjs";import { describe, expect, it, vi } from "vite-plus/test";+import { redactSensitiveText } from "@t3tools/shared/sensitiveDataRedaction";-import { redactComputerScreenshot, redactPreviewSnapshot } from "./PreviewSnapshotRedaction.ts";-import { redactSensitiveText } from "./SensitiveDataRedaction.ts";+import {+ redactComputerScreenshot,+ redactPreviewSnapshot,+ redactProviderVisiblePreviewResult,+} from "./PreviewSnapshotRedaction.ts";function testScreenshot() {const png = new PNG({ width: 2, height: 2 });@@ -111,4 +115,114 @@ describe("preview snapshot redaction", () => {const result = redactComputerScreenshot({ mediaType: "image/png", data: bytes });expect(Buffer.from(result.data).includes(text)).toBe(false);});++ it("sanitizes snapshots before they reach a provider", () => {+ const result = redactProviderVisiblePreviewResult("snapshot", {+ url: "http://example.test/",+ title: "[email protected]",+ loading: false,+ visibleText: "token=visible-secret",+ interactiveElements: [+ {+ tag: "input",+ role: "textbox",+ name: "[email protected]",+ selector: "#email",+ x: 0,+ y: 0,+ width: 100,+ height: 20,+ },+ ],+ accessibilityTree: {+ nodes: [{ name: { value: "AX name secret" }, value: { value: "AX value secret" } }],+ },+ consoleEntries: [+ { level: "log", text: "token=console-secret", timestamp: "2026-01-01T00:00:00Z" },+ ],+ networkEntries: [],+ actionTimeline: [],+ screenshot: testScreenshot(),+ }) as {+ readonly accessibilityTree: unknown;+ readonly title: string;+ readonly visibleText: string;+ readonly interactiveElements: ReadonlyArray<{ readonly name: string }>;+ readonly consoleEntries: ReadonlyArray<{ readonly text: string }>;+ readonly screenshot: { readonly data: string };+ };++ expect(result.accessibilityTree).toEqual({+ redactionStatus: "omitted-unverified-accessibility-tree",+ });+ expect(result.title).toBe("[REDACTED]");+ expect(result.visibleText).toBe("[REDACTED]");+ expect(result.interactiveElements[0]?.name).toBe("[REDACTED]");+ expect(result.consoleEntries[0]?.text).toBe("[REDACTED]");+ const png = PNG.sync.read(Buffer.from(result.screenshot.data, "base64"));+ expect([...png.data.subarray(0, 4)]).toEqual([0, 0, 0, 255]);+ });++ it("omits arbitrary evaluation output and redacts local artifact paths", () => {+ expect(+ redactProviderVisiblePreviewResult("evaluate", {+ arbitrary: "unrecognizable-secret",+ screenshot: testScreenshot(),+ }),+ ).toEqual({ redactionStatus: "omitted-unverified-preview-evaluation" });++ expect(+ redactProviderVisiblePreviewResult("recordingStop", {+ id: "recording-1",+ tabId: "tab-1",+ path: "/Users/leo/.akeru/browser-artifacts/recording.webm",+ mimeType: "video/webm",+ sizeBytes: 123,+ createdAt: "2026-01-01T00:00:00Z",+ }),+ ).toMatchObject({ path: "[REDACTED]" });++ expect(+ redactProviderVisiblePreviewResult("status", {+ chatPath: "/tmp/chat.json",+ logPath: "/tmp/browser.log",+ uploadPath: "/tmp/upload.png",+ }),+ ).toEqual({+ chatPath: "[REDACTED]",+ logPath: "[REDACTED]",+ uploadPath: "[REDACTED]",+ });+ });++ it("fails closed when a provider screenshot cannot be masked", () => {+ expect(() =>+ redactProviderVisiblePreviewResult("snapshot", {+ url: "http://example.test/",+ title: "Example",+ loading: false,+ visibleText: "safe",+ interactiveElements: [],+ accessibilityTree: {},+ consoleEntries: [],+ networkEntries: [],+ actionTimeline: [],+ screenshot: { ...testScreenshot(), data: Buffer.from("raw pixels").toString("base64") },+ }),+ ).toThrow();+ });++ it("rejects screenshot strings and nested image data", () => {+ expect(() =>+ redactProviderVisiblePreviewResult("status", { screenshot: "raw-base64-data" }),+ ).toThrow("Unredacted screenshot data is not provider-safe.");+ expect(() =>+ redactProviderVisiblePreviewResult("status", { image: { data: "raw-base64-data" } }),+ ).toThrow("Unredacted screenshot data is not provider-safe.");+ expect(() =>+ redactProviderVisiblePreviewResult("status", {+ screenshot: [{ data: "raw-base64-data" }],+ }),+ ).toThrow("Unredacted screenshot data is not provider-safe.");+ });});diff --git a/apps/server/src/mcp/PreviewSnapshotRedaction.ts b/apps/server/src/mcp/PreviewSnapshotRedaction.tsindex 46dc69546..f759888f6 100644--- a/apps/server/src/mcp/PreviewSnapshotRedaction.ts+++ b/apps/server/src/mcp/PreviewSnapshotRedaction.ts@@ -1,12 +1,20 @@+import {+ PreviewAutomationRecordingArtifact,+ PreviewAutomationSnapshot,+ type PreviewAutomationOperation,+} from "@t3tools/contracts";+import { redactSensitiveText } from "@t3tools/shared/sensitiveDataRedaction";+import * as Schema from "effect/Schema";import { PNG } from "pngjs";-import { redactSensitiveText } from "./SensitiveDataRedaction.ts";-const REDACTED = "[REDACTED]";export const MAX_SCREENSHOT_BYTES = 20 * 1_024 * 1_024;const MAX_SCREENSHOT_PIXELS = 16_000_000;+const screenshotField = /^(?:screenshot|image|frame)$/i;const secretField =- /^(?:api[_-]?key|access[_-]?token|refresh[_-]?token|token|secret|password|authorization|cookie|set-cookie|session|sessionId|clientSecret|awsSecretAccessKey)$/i;+ /^(?:api[_-]?key|access[_-]?token|refresh[_-]?token|token|secret|password|authorization|cookie|set-cookie|session|sessionId|clientSecret|awsSecretAccessKey|(?:artifact|chat|file|log|recording|upload)?path)$/i;+const decodeSnapshot = Schema.decodeUnknownSync(PreviewAutomationSnapshot);+const decodeRecordingArtifact = Schema.decodeUnknownSync(PreviewAutomationRecordingArtifact);function redactValue(value: unknown, fieldName?: string): { value: unknown; redacted: boolean } {if (fieldName && secretField.test(fieldName)) return { value: REDACTED, redacted: true };@@ -23,13 +31,32 @@ function redactValue(value: unknown, fieldName?: string): { value: unknown; redaif (typeof value !== "object" || value === null) return { value, redacted: false };let redacted = false;- const object: Record<string, unknown> = {};+ const entries: Array<[string, unknown]> = [];for (const [key, item] of Object.entries(value)) {const result = redactValue(item, key);redacted ||= result.redacted;- object[key] = result.value;+ entries.push([key, result.value]);}- return { value: object, redacted };+ return { value: Object.fromEntries(entries), redacted };+}++function rejectScreenshotPayload(value: unknown, fieldName?: string): void {+ if (typeof value === "string" && fieldName && screenshotField.test(fieldName)) {+ throw new Error("Unredacted screenshot data is not provider-safe.");+ }+ if (Array.isArray(value)) {+ for (const item of value) rejectScreenshotPayload(item, fieldName);+ return;+ }+ if (typeof value !== "object" || value === null) return;+ if (+ Object.hasOwn(value, "data") &&+ ((fieldName !== undefined && screenshotField.test(fieldName)) ||+ Object.hasOwn(value, "mimeType"))+ ) {+ throw new Error("Unredacted screenshot data is not provider-safe.");+ }+ for (const [key, item] of Object.entries(value)) rejectScreenshotPayload(item, key);}function readPngDimensions(bytes: Uint8Array) {@@ -98,7 +125,35 @@ export function redactPreviewSnapshot(}return {page: redactedPage.value as Readonly<Record<string, unknown>>,- screenshot: blankPng(bytes),+ screenshot: redactComputerScreenshot({ mediaType: "image/png", data: bytes }).data,frameRedacted: true,};}++export function redactProviderVisiblePreviewResult(+ operation: PreviewAutomationOperation,+ input: unknown,+): unknown {+ if (operation === "evaluate") {+ return { redactionStatus: "omitted-unverified-preview-evaluation" };+ }+ if (operation === "snapshot") {+ const snapshot = decodeSnapshot(input);+ const { accessibilityTree: _accessibilityTree, screenshot, ...page } = snapshot;+ const redacted = redactPreviewSnapshot(page, screenshot);+ return {+ ...redacted.page,+ accessibilityTree: { redactionStatus: "omitted-unverified-accessibility-tree" },+ screenshot: {+ ...screenshot,+ data: Buffer.from(redacted.screenshot).toString("base64"),+ },+ };+ }++ rejectScreenshotPayload(input);+ if (operation === "recordingStop") {+ return { ...decodeRecordingArtifact(input), path: REDACTED };+ }+ return redactValue(input).value;+}diff --git a/apps/server/src/observability/Layers/Observability.ts b/apps/server/src/observability/Layers/Observability.tsindex 8aac09275..fb8eb6b53 100644--- a/apps/server/src/observability/Layers/Observability.ts+++ b/apps/server/src/observability/Layers/Observability.ts@@ -1,4 +1,3 @@-import { httpHeaderRedactionLayer } from "@t3tools/shared/httpObservability";import { makeLocalFileTracer, makeTraceSink } from "@t3tools/shared/observability";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";@@ -24,7 +23,6 @@ export const ObservabilityLive = Layer.unwrap(const traceReferencesLayer = Layer.mergeAll(Layer.succeed(Tracer.MinimumTraceLevel, config.traceMinLevel),Layer.succeed(References.TracerTimingEnabled, config.traceTimingEnabled),- httpHeaderRedactionLayer,);const tracerLayer = Layer.unwrap(diff --git a/apps/server/src/orchestration/Layers/BotPersistence.test.ts b/apps/server/src/orchestration/Layers/BotPersistence.test.tsindex 24125312b..aeb3bbd8a 100644--- a/apps/server/src/orchestration/Layers/BotPersistence.test.ts+++ b/apps/server/src/orchestration/Layers/BotPersistence.test.ts@@ -549,4 +549,39 @@ it.layer(TestLayer)("bot persistence", (it) => {);}),);++ it.effect("maps historical Akeru Cloud bots to local during projection rebuilds", () =>+ Effect.gen(function* () {+ const engine = yield* OrchestrationEngineService;+ const projectionPipeline = yield* OrchestrationProjectionPipeline;+ const snapshots = yield* ProjectionSnapshotQuery;+ const sql = yield* SqlClient.SqlClient;+ const botId = BotId.make("bot-legacy-akeru-cloud");++ yield* engine.dispatch({+ type: "bot.create",+ commandId: CommandId.make("cmd-bot-legacy-akeru-cloud"),+ botId,+ name: "Legacy",+ title: "Legacy",+ avatar: { kind: "dither", seed: "legacy" },+ engine: null,+ sandbox: "local",+ usageCap: null,+ groupId: null,+ createdAt: "2026-01-01T00:00:00.000Z",+ });+ yield* sql`+ UPDATE orchestration_events+ SET payload_json = json_set(payload_json, '$.sandbox', 'akeru-cloud')+ WHERE event_type = 'bot.created' AND stream_id = ${botId}+ `;+ yield* sql`DELETE FROM projection_bots`;+ yield* sql`DELETE FROM projection_state WHERE projector = 'projection.bots'`;+ yield* projectionPipeline.bootstrap;++ const bot = (yield* snapshots.getShellSnapshot()).bots.find((item) => item.id === botId);+ assert.equal(bot?.sandbox, null);+ }),+ );});diff --git a/apps/server/src/orchestration/Layers/OrchestrationReactor.test.ts b/apps/server/src/orchestration/Layers/OrchestrationReactor.test.tsindex 300d1526b..13524ae85 100644--- a/apps/server/src/orchestration/Layers/OrchestrationReactor.test.ts+++ b/apps/server/src/orchestration/Layers/OrchestrationReactor.test.ts@@ -11,7 +11,6 @@ import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngeimport { ThreadDeletionReactor } from "../Services/ThreadDeletionReactor.ts";import { OrchestrationReactor } from "../Services/OrchestrationReactor.ts";import { makeOrchestrationReactor } from "./OrchestrationReactor.ts";-import * as AgentAwarenessRelay from "../../relay/AgentAwarenessRelay.ts";describe("OrchestrationReactor", () => {let runtime: ManagedRuntime.ManagedRuntime<OrchestrationReactor, never> | null = null;@@ -64,15 +63,6 @@ describe("OrchestrationReactor", () => {drain: Effect.void,}),),- Layer.provideMerge(- Layer.succeed(AgentAwarenessRelay.AgentAwarenessRelay, {- publishThread: () => Effect.void,- start: () => {- started.push("agent-awareness-relay");- return Effect.void;- },- }),- ),),);@@ -85,7 +75,6 @@ describe("OrchestrationReactor", () => {"provider-command-reactor","checkpoint-reactor","thread-deletion-reactor",- "agent-awareness-relay",]);await Effect.runPromise(Scope.close(scope, Exit.void));diff --git a/apps/server/src/orchestration/Layers/OrchestrationReactor.ts b/apps/server/src/orchestration/Layers/OrchestrationReactor.tsindex fb7543e31..5e432d988 100644--- a/apps/server/src/orchestration/Layers/OrchestrationReactor.ts+++ b/apps/server/src/orchestration/Layers/OrchestrationReactor.ts@@ -9,21 +9,18 @@ import { CheckpointReactor } from "../Services/CheckpointReactor.ts";import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";import { ThreadDeletionReactor } from "../Services/ThreadDeletionReactor.ts";-import * as AgentAwarenessRelay from "../../relay/AgentAwarenessRelay.ts";export const makeOrchestrationReactor = Effect.gen(function* () {const providerRuntimeIngestion = yield* ProviderRuntimeIngestionService;const providerCommandReactor = yield* ProviderCommandReactor;const checkpointReactor = yield* CheckpointReactor;const threadDeletionReactor = yield* ThreadDeletionReactor;- const agentAwarenessRelay = yield* AgentAwarenessRelay.AgentAwarenessRelay;const start: OrchestrationReactorShape["start"] = Effect.fn("start")(function* () {yield* providerRuntimeIngestion.start();yield* providerCommandReactor.start();yield* checkpointReactor.start();yield* threadDeletionReactor.start();- yield* agentAwarenessRelay.start();});return {diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.test.tsindex d27caed4a..3711e9750 100644--- a/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts+++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts@@ -2086,13 +2086,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {FROM projection_pending_approvalsWHERE request_id = 'approval-request-stale-1'`;- assert.deepEqual(approvalRows, [- {- requestId: "approval-request-stale-1",- status: "resolved",- resolvedAt: "2026-02-26T12:30:03.000Z",- },- ]);+ assert.deepEqual(approvalRows, []);const threadRows = yield* sql<{readonly pendingApprovalCount: number;diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.tsindex 7b36274be..eec8f6ab2 100644--- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts+++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts@@ -1796,35 +1796,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjectirequestId,});if (event.payload.activity.kind === "approval.resolved") {- const resolvedDecisionRaw =- typeof event.payload.activity.payload === "object" &&- event.payload.activity.payload !== null &&- "decision" in event.payload.activity.payload- ? (event.payload.activity.payload as { decision?: unknown }).decision- : null;- const resolvedDecision =- resolvedDecisionRaw === "accept" ||- resolvedDecisionRaw === "acceptForSession" ||- resolvedDecisionRaw === "acceptAlways" ||- resolvedDecisionRaw === "decline" ||- resolvedDecisionRaw === "cancel"- ? resolvedDecisionRaw- : null;- yield* projectionPendingApprovalRepository.upsert({- requestId,- threadId: Option.isSome(existingRow)- ? existingRow.value.threadId- : event.payload.threadId,- turnId: Option.isSome(existingRow)- ? existingRow.value.turnId- : event.payload.activity.turnId,- status: "resolved",- decision: resolvedDecision,- createdAt: Option.isSome(existingRow)- ? existingRow.value.createdAt- : event.payload.activity.createdAt,- resolvedAt: event.payload.activity.createdAt,- });+ yield* projectionPendingApprovalRepository.deleteByRequestId({ requestId });return;}if (event.payload.activity.kind === "provider.approval.respond.failed") {@@ -1842,15 +1814,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjectiif (existingRow.value.status === "resolved") {return;}- yield* projectionPendingApprovalRepository.upsert({- requestId,- threadId: existingRow.value.threadId,- turnId: existingRow.value.turnId,- status: "resolved",- decision: null,- createdAt: existingRow.value.createdAt,- resolvedAt: event.payload.activity.createdAt,- });+ yield* projectionPendingApprovalRepository.deleteByRequestId({ requestId });return;}return;@@ -1881,22 +1845,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti}case "thread.approval-response-requested": {- const existingRow = yield* projectionPendingApprovalRepository.getByRequestId({- requestId: event.payload.requestId,- });- yield* projectionPendingApprovalRepository.upsert({- requestId: event.payload.requestId,- threadId: Option.isSome(existingRow)- ? existingRow.value.threadId- : event.payload.threadId,- turnId: Option.isSome(existingRow) ? existingRow.value.turnId : null,- status: "resolved",- decision: event.payload.decision,- createdAt: Option.isSome(existingRow)- ? existingRow.value.createdAt- : event.payload.createdAt,- resolvedAt: event.payload.createdAt,- });+ // Keep the request pending until the provider confirms the response.return;}diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.tsindex aad902ce7..cfa5561e9 100644--- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts+++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts@@ -3056,6 +3056,84 @@ describe("ProviderRuntimeIngestion", () => {expect(resolvedPayload?.requestType).toBe("command_execution_approval");});+ it("removes a pending approval after a lifecycle cancellation", async () => {+ const harness = await createHarness();+ const base = {+ provider: ProviderDriverKind.make("codex"),+ threadId: asThreadId("thread-1"),+ turnId: asTurnId("turn-approval-cancel"),+ requestId: RuntimeRequestId.make("request-approval-cancel"),+ };++ harness.emit({+ type: "turn.started",+ eventId: asEventId("evt-approval-cancel-turn"),+ provider: base.provider,+ threadId: base.threadId,+ turnId: base.turnId,+ createdAt: "2026-01-01T00:00:00.000Z",+ });+ await waitForThread(+ harness.readModel,+ (thread) => thread.session?.activeTurnId === base.turnId,+ );++ harness.emit({+ ...base,+ type: "request.opened",+ eventId: asEventId("evt-approval-cancel-opened"),+ createdAt: "2026-01-01T00:00:00.000Z",+ payload: {+ requestType: "dynamic_tool_call",+ actor: "agent",+ target: "gmail_send_message",+ action: "send",+ },+ });+ const openedThread = await waitForThread(harness.readModel, (thread) =>+ thread.activities.some(+ (activity: ProviderRuntimeTestActivity) =>+ activity.id === "evt-approval-cancel-opened" && activity.kind === "approval.requested",+ ),+ );+ expect(+ openedThread.activities.some(+ (activity: ProviderRuntimeTestActivity) => activity.id === "evt-approval-cancel-resolved",+ ),+ ).toBe(false);++ harness.emit({+ ...base,+ type: "request.resolved",+ eventId: asEventId("evt-approval-cancel-resolved"),+ createdAt: "2026-01-01T00:00:01.000Z",+ payload: {+ requestType: "dynamic_tool_call",+ decision: "cancel",+ actor: "system",+ target: "gmail_send_message",+ action: "send",+ outcome: "cancelled",+ },+ });++ const thread = await waitForThread(harness.readModel, (entry) =>+ entry.activities.some(+ (activity: ProviderRuntimeTestActivity) =>+ activity.id === "evt-approval-cancel-resolved" && activity.kind === "approval.resolved",+ ),+ );+ const resolved = thread.activities.find(+ (activity: ProviderRuntimeTestActivity) => activity.id === "evt-approval-cancel-resolved",+ );+ expect(resolved?.payload).toMatchObject({+ actor: "system",+ target: "gmail_send_message",+ action: "send",+ outcome: "cancelled",+ });+ });+it("maps runtime.error into errored session state", async () => {const harness = await createHarness();const now = "2026-01-01T00:00:00.000Z";diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.tsindex 3d2e3a763..206d879f1 100644--- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts+++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts@@ -416,7 +416,10 @@ export function runtimeEventToActivities(requestId: toApprovalRequestId(event.requestId),...(requestKind ? { requestKind } : {}),requestType: event.payload.requestType,+ ...(event.payload.actor ? { actor: event.payload.actor } : {}),+ ...(event.payload.target ? { target: event.payload.target } : {}),...(event.payload.toolName ? { toolName: event.payload.toolName } : {}),+ ...(event.payload.action ? { action: event.payload.action } : {}),...(feedbackArgs !== undefined ? { args: feedbackArgs } : {}),...(event.payload.detail ? { detail: event.payload.detail } : {}),...(event.payload.appName ? { appName: event.payload.appName } : {}),@@ -445,6 +448,10 @@ export function runtimeEventToActivities(...(requestKind ? { requestKind } : {}),requestType: event.payload.requestType,...(event.payload.decision ? { decision: event.payload.decision } : {}),+ ...(event.payload.actor ? { actor: event.payload.actor } : {}),+ ...(event.payload.target ? { target: event.payload.target } : {}),+ ...(event.payload.action ? { action: event.payload.action } : {}),+ ...(event.payload.outcome ? { outcome: event.payload.outcome } : {}),},turnId: toTurnId(event.turnId) ?? null,...maybeSequence,diff --git a/apps/server/src/persistence/AuthPairingLinks.ts b/apps/server/src/persistence/AuthPairingLinks.tsindex e9ab45c05..0bf11d9b7 100644--- a/apps/server/src/persistence/AuthPairingLinks.ts+++ b/apps/server/src/persistence/AuthPairingLinks.ts@@ -22,7 +22,6 @@ export const AuthPairingLinkRecord = Schema.Struct({scopes: Schema.fromJsonString(AuthEnvironmentScopes),subject: Schema.String,label: Schema.NullOr(Schema.String),- proofKeyThumbprint: Schema.NullOr(Schema.String),createdAt: Schema.DateTimeUtcFromString,expiresAt: Schema.DateTimeUtcFromString,consumedAt: Schema.NullOr(Schema.DateTimeUtcFromString),@@ -37,7 +36,6 @@ export const CreateAuthPairingLinkInput = Schema.Struct({scopes: AuthEnvironmentScopes,subject: Schema.String,label: Schema.NullOr(Schema.String),- proofKeyThumbprint: Schema.NullOr(Schema.String),createdAt: Schema.DateTimeUtcFromString,expiresAt: Schema.DateTimeUtcFromString,});@@ -45,7 +43,6 @@ export type CreateAuthPairingLinkInput = typeof CreateAuthPairingLinkInput.Type;export const ConsumeAuthPairingLinkInput = Schema.Struct({credential: Schema.String,- proofKeyThumbprint: Schema.NullOr(Schema.String),consumedAt: Schema.DateTimeUtcFromString,now: Schema.DateTimeUtcFromString,});@@ -74,7 +71,6 @@ const AuthPairingLinkRawDbRow = Schema.Struct({scopes: Schema.Unknown,subject: Schema.Unknown,label: Schema.Unknown,- proofKeyThumbprint: Schema.Unknown,createdAt: Schema.Unknown,expiresAt: Schema.Unknown,consumedAt: Schema.Unknown,@@ -133,7 +129,6 @@ export const make = Effect.gen(function* () {scopes,subject,label,- proof_key_thumbprint,created_at,expires_at,consumed_at,@@ -146,7 +141,6 @@ export const make = Effect.gen(function* () {${JSON.stringify(input.scopes)},${input.subject},${input.label},- ${input.proofKeyThumbprint},${input.createdAt},${input.expiresAt},NULL,@@ -158,7 +152,7 @@ export const make = Effect.gen(function* () {const consumeAvailablePairingLinkRow = SqlSchema.findOneOption({Request: ConsumeAuthPairingLinkInput,Result: AuthPairingLinkRawDbRow,- execute: ({ credential, proofKeyThumbprint, consumedAt, now }) =>+ execute: ({ credential, consumedAt, now }) =>sql`UPDATE auth_pairing_linksSET consumed_at = ${consumedAt}@@ -166,10 +160,7 @@ export const make = Effect.gen(function* () {AND revoked_at IS NULLAND consumed_at IS NULLAND expires_at > ${now}- AND (- proof_key_thumbprint IS NULL- OR proof_key_thumbprint = ${proofKeyThumbprint}- )+ AND proof_key_thumbprint IS NULLRETURNINGid AS "id",credential AS "credential",@@ -177,7 +168,6 @@ export const make = Effect.gen(function* () {scopes AS "scopes",subject AS "subject",label AS "label",- proof_key_thumbprint AS "proofKeyThumbprint",created_at AS "createdAt",expires_at AS "expiresAt",consumed_at AS "consumedAt",@@ -197,7 +187,6 @@ export const make = Effect.gen(function* () {scopes AS "scopes",subject AS "subject",label AS "label",- proof_key_thumbprint AS "proofKeyThumbprint",created_at AS "createdAt",expires_at AS "expiresAt",consumed_at AS "consumedAt",@@ -206,6 +195,7 @@ export const make = Effect.gen(function* () {WHERE revoked_at IS NULLAND consumed_at IS NULLAND expires_at > ${now}+ AND proof_key_thumbprint IS NULLORDER BY created_at DESC, id DESC`,});@@ -236,7 +226,6 @@ export const make = Effect.gen(function* () {scopes AS "scopes",subject AS "subject",label AS "label",- proof_key_thumbprint AS "proofKeyThumbprint",created_at AS "createdAt",expires_at AS "expiresAt",consumed_at AS "consumedAt",diff --git a/apps/server/src/persistence/RepositoryErrorCorrelation.test.ts b/apps/server/src/persistence/RepositoryErrorCorrelation.test.tsindex 379b06e2a..4543c1489 100644--- a/apps/server/src/persistence/RepositoryErrorCorrelation.test.ts+++ b/apps/server/src/persistence/RepositoryErrorCorrelation.test.ts@@ -163,7 +163,6 @@ describe("persistence error correlation", () => {scopes,subject,label: null,- proofKeyThumbprint: null,createdAt: issuedAt,expiresAt,}),diff --git a/apps/server/src/persistence/Services/ProjectionBots.ts b/apps/server/src/persistence/Services/ProjectionBots.tsindex f9caa56c9..10d89fa8a 100644--- a/apps/server/src/persistence/Services/ProjectionBots.ts+++ b/apps/server/src/persistence/Services/ProjectionBots.ts@@ -2,7 +2,7 @@ import {BotAvatar,BotEngine,BotId,- BotSandbox,+ PersistedBotSandbox,BotUsageCap,GroupId,IsoDateTime,@@ -25,7 +25,7 @@ export const ProjectionBot = Schema.Struct({disabledMcpServerIds: Schema.Array(McpServerId),avatar: BotAvatar,engine: Schema.NullOr(BotEngine),- sandbox: Schema.NullOr(BotSandbox),+ sandbox: PersistedBotSandbox,runtimeMode: RuntimeMode,usageCap: Schema.NullOr(BotUsageCap),voiceEnabled: Schema.Boolean,diff --git a/apps/server/src/portability.ts b/apps/server/src/portability.tsindex c590278d4..64487ecc3 100644--- a/apps/server/src/portability.ts+++ b/apps/server/src/portability.ts@@ -45,7 +45,7 @@ const ARCHIVE_RECORD_TYPES = ["thread",] as const;const ARCHIVE_EXCLUSIONS = [- "Access tokens, cookies, passwords, secret values, environment variables, pairing and relay credentials",+ "Access tokens, cookies, passwords, secret values, environment variables, and pairing credentials","Absolute local paths, project scripts, attachments, image avatar files, Git refs, pull request links, and diff blobs","Event identifiers, event sequences, command receipts, provider sessions, and opaque provider configuration","Conversation attachments, raw approval payloads, provider request details, and deleted threads and projects",@@ -487,6 +487,10 @@ export function portableRecords(const requestKind = stringField(activity.payload, "requestKind");const requestType = stringField(activity.payload, "requestType");const decision = stringField(activity.payload, "decision");+ const actor = stringField(activity.payload, "actor");+ const target = stringField(activity.payload, "target");+ const action = stringField(activity.payload, "action");+ const outcome = stringField(activity.payload, "outcome");return [{originalKind: originalKind as@@ -498,6 +502,10 @@ export function portableRecords(...(requestKind ? { requestKind } : {}),...(requestType ? { requestType } : {}),...(decision ? { decision } : {}),+ ...(actor ? { actor } : {}),+ ...(target ? { target } : {}),+ ...(action ? { action } : {}),+ ...(outcome ? { outcome } : {}),provider:stringField(activity.payload, "provider") ?? thread.modelSelection.instanceId,createdAt: activity.createdAt,@@ -665,6 +673,10 @@ function assertSafeImportedRecord(record: PortabilityArchiveRecord): void {approval.requestKind,approval.requestType,approval.decision,+ approval.actor,+ approval.target,+ approval.action,+ approval.outcome,]) {if (value !== undefined)assertSafeImportedText(`Thread '${record.id}' approval field`, value);@@ -1762,6 +1774,10 @@ export function commandsForPortabilityImport(...(approval.requestKind ? { requestKind: approval.requestKind } : {}),...(approval.requestType ? { requestType: approval.requestType } : {}),...(approval.decision ? { decision: approval.decision } : {}),+ ...(approval.actor ? { actor: approval.actor } : {}),+ ...(approval.target ? { target: approval.target } : {}),+ ...(approval.action ? { action: approval.action } : {}),+ ...(approval.outcome ? { outcome: approval.outcome } : {}),provider: approval.provider,},turnId: null,diff --git a/apps/server/src/provider/AkeruMastraHarness.test.ts b/apps/server/src/provider/AkeruMastraHarness.test.tsindex 1be4df77e..6740e4cb4 100644--- a/apps/server/src/provider/AkeruMastraHarness.test.ts+++ b/apps/server/src/provider/AkeruMastraHarness.test.ts@@ -19,6 +19,7 @@ import { assert, describe, expect, it, vi } from "vite-plus/test";import { AKERU_AGENT_INSTRUCTIONS, AKERU_BOT_INSTRUCTIONS } from "./AkeruAgentInstructions.ts";import {AkeruPassiveObservationalMemoryProcessor,+ akeruActionNeedsApproval,createAkeruObserveHooks,createAkeruMastraHarness,createAkeruMastraMemory,@@ -31,6 +32,39 @@ import {import { productFeedbackToolInputSchema } from "./AkeruMastraHarness.ts";import type { AkeruToolRuntime } from "./AkeruToolRuntime.ts";+describe("Akeru action classifier", () => {+ it.each([+ ["rm -rf .cache", "delete"],+ ["git push origin main", "publish"],+ ["psql -c 'DROP TABLE sessions'", "delete"],+ ["wrangler deploy", "production"],+ ["cat ~/.ssh/id_rsa", "secrets"],+ ['curl -X POST --data \'{"text":"hello"}\' https://example.com/messages', "send"],+ ["cd workspace && git push origin main", "publish"],+ ["find . -name '*.tmp' -delete", "delete"],+ ["python -c 'import os; os.remove(\"tmp.txt\")'", "delete"],+ ] as const)("classifies %s as %s", (command, action) => {+ expect(criticalAkeruAction("execute_command", { command })).toBe(action);+ expect(akeruActionNeedsApproval("execute_command", { command })).toBe(true);+ });++ it.each(["bun test", "git status", "rg -n TODO apps", "cat README.md"])(+ "leaves ordinary local command %s unclassified",+ (command) => {+ expect(criticalAkeruAction("execute_command", { command })).toBeNull();+ expect(akeruActionNeedsApproval("execute_command", { command })).toBe(false);+ },+ );++ it("requires approval when nested input exceeds the inspection limit", () => {+ let args: unknown = { action: "send" };+ for (let depth = 0; depth < 101; depth += 1) args = { nested: args };++ expect(criticalAkeruAction("custom_tool", args)).toBeNull();+ expect(akeruActionNeedsApproval("custom_tool", args)).toBe(true);+ });+});+describe("AkeruMastraHarness", () => {it("emits observer and reflector metering callbacks", async () => {const started: unknown[] = [];diff --git a/apps/server/src/provider/AkeruMastraHarness.ts b/apps/server/src/provider/AkeruMastraHarness.tsindex f193e6cd5..9f221dcfb 100644--- a/apps/server/src/provider/AkeruMastraHarness.ts+++ b/apps/server/src/provider/AkeruMastraHarness.ts@@ -433,6 +433,25 @@ const READ_ONLY_INTENT_TOKENS = new Set(["status","view",]);+const CRITICAL_SHELL_ACTIONS: ReadonlyArray<readonly [AkeruCriticalAction, RegExp]> = [+ [+ "delete",+ /(?:^|[;&|]\s*)(?:sudo\s+)?(?:rm|rmdir|unlink)\b|\b(?:drop|truncate)\s+(?:database|schema|table)\b|\bdelete\s+from\b/i,+ ],+ ["publish", /(?:^|[;&|]\s*)git\s+push\b/i],+ [+ "production",+ /(?:^|[;&|]\s*)(?:kubectl\s+(?:apply|delete|replace|rollout)|terraform\s+(?:apply|destroy)|docker\s+push)\b/i,+ ],+ [+ "secrets",+ /(?:^|[;&|]\s*)(?:(?:printenv|env)(?:\s|$)|(?:cat|head|tail|less|more|sed|awk|grep|rg)\b[^\n;&|]*(?:\.env\b|\/\.ssh\/id_[\w-]+|credentials?|secrets?|tokens?)|gh\s+auth\s+token|security\s+find-(?:generic|internet)-password|op\s+(?:read|get)|vault\s+(?:kv\s+)?get|aws\s+secretsmanager\s+get-secret-value|gcloud\s+secrets\s+versions\s+access|kubectl\s+get\s+secrets?)\b/i,+ ],+ [+ "send",+ /(?:^|[;&|]\s*)(?:(?:mail|mailx)\b|curl\b[^\n;&|]*(?:--data(?:-raw|-binary)?|-d\b|--form|-F\b|--request\s+post|-X\s*post))/i,+ ],+];function textTokens(value: string): ReadonlySet<string> {return new Set(@@ -459,6 +478,13 @@ function criticalActionFromText(value: string): AkeruCriticalAction | null {return null;}+function criticalActionFromShellCommand(value: string): AkeruCriticalAction | null {+ for (const [action, pattern] of CRITICAL_SHELL_ACTIONS) {+ if (pattern.test(value)) return action;+ }+ return criticalActionFromText(value);+}+type AkeruActionInspection = {readonly action: AkeruCriticalAction | null;readonly hasUnclassifiedIntent: boolean;@@ -484,11 +510,10 @@ function inspectAkeruAction(toolName: string, args?: unknown): AkeruActionInspecconst keyedAction = criticalActionFromText(key);if (keyedAction) return { action: keyedAction, hasUnclassifiedIntent: false };if (ACTION_TEXT_KEYS.has(normalizedKey) && typeof entry === "string") {- if (normalizedKey === "command") {- const action = classifyAkeruExternalCommand(entry);- if (action) return { action, hasUnclassifiedIntent: false };- }- const action = criticalActionFromText(entry);+ const action =+ normalizedKey === "command"+ ? criticalActionFromShellCommand(entry)+ : criticalActionFromText(entry);if (action) return { action, hasUnclassifiedIntent: false };if (MUTATING_INTENT_KEYS.has(normalizedKey)) {const tokens = textTokens(entry);@@ -507,7 +532,7 @@ function inspectAkeruAction(toolName: string, args?: unknown): AkeruActionInspecif (typeof entry === "object" && entry !== null) pending.push(entry);}}- return { action: null, hasUnclassifiedIntent };+ return { action: null, hasUnclassifiedIntent: hasUnclassifiedIntent || pending.length > 0 };}export function criticalAkeruAction(toolName: string, args?: unknown): AkeruCriticalAction | null {diff --git a/apps/server/src/provider/Layers/AgentController.test.ts b/apps/server/src/provider/Layers/AgentController.test.tsindex 0a8d8a1d6..26dbb534e 100644--- a/apps/server/src/provider/Layers/AgentController.test.ts+++ b/apps/server/src/provider/Layers/AgentController.test.ts@@ -753,8 +753,8 @@ describe("AgentControllerLive", () => {expect(events.find((event) => event.type === "request.opened")).toMatchObject({payload: {options: [- { decision: "accept", label: "Allow" },{ decision: "decline", label: "Decline" },+ { decision: "accept", label: "Approve" },],},});@@ -1466,9 +1466,20 @@ describe("AgentControllerLive", () => {);});- it.effect("cancels pending approvals when the turn or session ends", () => {+ it.effect("fails closed for MCP tools missing from the manager index", () => {const bridge = makeBridge();const mastra = makeMastraHarness();+ const mcpManager = {+ init: vi.fn(async () => undefined),+ disconnect: vi.fn(async () => undefined),+ getTools: vi.fn(() => ({+ indexed_read: { mcp: { annotations: { readOnlyHint: true } } },+ })),+ getServerStatuses: vi.fn(() => []),+ };+ const makeMcpManager: NonNullable<AgentControllerLiveOptions["makeMcpManager"]> = vi.fn(+ () => mcpManager as never,+ );return provideController(Effect.gen(function* () {const controller = yield* AgentController;@@ -1480,73 +1491,131 @@ describe("AgentControllerLive", () => {cwd: process.cwd(),modelSelection: codexSelection,runtimeMode: "full-access",+ mcpServers: [+ {+ id: McpServerId.make("mcp-test"),+ name: "Test MCP",+ transport: "url",+ url: "https://example.com/mcp",+ enabled: true,+ createdAt: "2026-01-01T00:00:00.000Z",+ updatedAt: "2026-01-01T00:00:00.000Z",+ },+ ],});+const events: ProviderRuntimeEvent[] = [];- const expectCancelledOnce = (requestId: string) =>- expect(- events.filter(- (event) => event.type === "request.resolved" && event.requestId === requestId,- ),- ).toEqual([- expect.objectContaining({- payload: { requestType: "dynamic_tool_call", decision: "cancel" },- }),- ]);const eventsFiber = yield* controller.streamEvents.pipe(Stream.runForEach((event) => Effect.sync(() => events.push(event))),Effect.forkChild({ startImmediately: true }),);yield* Effect.yieldNow;-- yield* controller.sendTurn({ threadId: codexThreadId, input: "Run pwd." });- mastra.emit({- type: "tool_approval_required",- toolCallId: "turn-expiry",- toolName: "Shell",- args: { command: "pwd" },- } as AgentControllerEvent);- mastra.emit({ type: "agent_end", reason: "complete" } as AgentControllerEvent);- mastra.finishSend();- yield* Effect.yieldNow;+ yield* controller.sendTurn({ threadId: codexThreadId, input: "Use tools." });+ for (const [toolCallId, toolName, args] of [+ ["builtin-safe", "execute_command", { command: "bun test" }],+ ["indexed-read", "indexed_read", { query: "status" }],+ ["missing-index", "new_mcp_tool", { value: "unknown" }],+ ] as const) {+ mastra.emit({+ type: "tool_approval_required",+ toolCallId,+ toolName,+ args,+ } as AgentControllerEvent);+ }yield* Effect.yieldNow;- expectCancelledOnce("turn-expiry");- yield* controller.respondToRequest({+ expect(mastra.session.respondToToolApproval).toHaveBeenCalledWith({+ toolCallId: "builtin-safe",+ decision: "approve",+ });+ expect(mastra.session.respondToToolApproval).toHaveBeenCalledWith({+ toolCallId: "indexed-read",+ decision: "approve",+ });+ expect(events.filter((event) => event.type === "request.opened")).toEqual([+ expect.objectContaining({+ requestId: "missing-index",+ payload: expect.objectContaining({ target: "new_mcp_tool" }),+ }),+ ]);+ yield* Fiber.interrupt(eventsFiber);+ }),+ bridge.service,+ mastra.factory,+ makeMcpManager,+ );+ });++ it.effect("resolves pending approvals when a turn or session ends", () => {+ const bridge = makeBridge();+ const mastra = makeMastraHarness();+ return provideController(+ Effect.gen(function* () {+ const controller = yield* AgentController;+ yield* resolveCodex(controller);+ yield* controller.startSession(codexThreadId, {threadId: codexThreadId,- requestId: ApprovalRequestId.make("turn-expiry"),- decision: "accept",+ provider: ProviderDriverKind.make("codex"),+ providerInstanceId: codexInstanceId,+ cwd: process.cwd(),+ modelSelection: codexSelection,+ runtimeMode: "full-access",});- expect(mastra.session.respondToToolApproval).not.toHaveBeenCalled();+ const events: ProviderRuntimeEvent[] = [];+ const eventsFiber = yield* controller.streamEvents.pipe(+ Stream.runForEach((event) => Effect.sync(() => events.push(event))),+ Effect.forkChild({ startImmediately: true }),+ );+ yield* Effect.yieldNow;- yield* controller.sendTurn({ threadId: codexThreadId, input: "Run pwd again." });+ yield* controller.sendTurn({ threadId: codexThreadId, input: "Finish." });+ for (const requestId of ["finish-1", "finish-2"]) {+ mastra.emit({+ type: "tool_approval_required",+ toolCallId: requestId,+ toolName: "gmail_send_message",+ args: { to: "[email protected]" },+ } as AgentControllerEvent);+ }+ mastra.emit({ type: "agent_end", reason: "complete" } as AgentControllerEvent);+ mastra.finishSend();+ yield* Effect.yieldNow;++ yield* controller.sendTurn({ threadId: codexThreadId, input: "Interrupt." });mastra.emit({type: "tool_approval_required",- toolCallId: "tool-end-expiry",- toolName: "Shell",- args: { command: "pwd" },- } as AgentControllerEvent);- mastra.emit({- type: "tool_end",- toolCallId: "tool-end-expiry",- result: "cancelled",- isError: false,- denied: true,+ toolCallId: "interrupt-1",+ toolName: "gmail_send_message",+ args: { to: "[email protected]" },} as AgentControllerEvent);+ yield* controller.interruptTurn({ threadId: codexThreadId });yield* Effect.yieldNow;- yield* Effect.yieldNow;- expectCancelledOnce("tool-end-expiry");+ yield* controller.sendTurn({ threadId: codexThreadId, input: "Stop." });mastra.emit({type: "tool_approval_required",- toolCallId: "session-expiry",- toolName: "Shell",- args: { command: "pwd" },+ toolCallId: "stop-1",+ toolName: "gmail_send_message",+ args: { to: "[email protected]" },} as AgentControllerEvent);yield* controller.stopSession({ threadId: codexThreadId });yield* Effect.yieldNow;- yield* Effect.yieldNow;- expectCancelledOnce("session-expiry");+ const resolved = events.filter((event) => event.type === "request.resolved");+ expect(resolved.map((event) => event.requestId)).toEqual([+ "finish-1",+ "finish-2",+ "interrupt-1",+ "stop-1",+ ]);+ for (const event of resolved) {+ expect(event.payload).toMatchObject({+ decision: "cancel",+ actor: "system",+ outcome: "cancelled",+ });+ }yield* Fiber.interrupt(eventsFiber);}),bridge.service,diff --git a/apps/server/src/provider/Layers/AgentController.ts b/apps/server/src/provider/Layers/AgentController.tsindex 27f7f7589..26ee6fb77 100644--- a/apps/server/src/provider/Layers/AgentController.ts+++ b/apps/server/src/provider/Layers/AgentController.ts@@ -4,7 +4,12 @@ import * as NodeFS from "node:fs";import * as NodePath from "node:path";import { AuthStorage } from "@mastra/code-sdk/auth/storage";-import { createMcpManager, type McpServerConfig } from "@mastra/code-sdk/mcp/index";+import {+ createMcpManager,+ type McpManager,+ type McpServerConfig,+} from "@mastra/code-sdk/mcp/index";+import { TOOL_NAME_OVERRIDES } from "@mastra/code-sdk/tool-names";import type {AgentControllerEvent,MastraDBMessage,@@ -67,7 +72,9 @@ import {} from "../../subscription-auth/service.ts";import {akeruActionNeedsApproval,+ akeruToolCategory,createAkeruMastraHarness,+ criticalAkeruAction,mastraModelId,type AkeruMastraHarness,type AkeruMastraHarnessOptions,@@ -111,6 +118,9 @@ import { LegacyProviderBridge } from "../Services/LegacyProviderBridge.ts";const DEFAULT_MODE_ID = "build";const PLAN_MODE_ID = "plan";+const BUILTIN_MASTRA_TOOL_NAMES: ReadonlySet<string> = new Set(+ Object.values(TOOL_NAME_OVERRIDES).map((tool) => tool.name),+);type MastraSession = AkeruMastraSession;interface ResolvedEngine {@@ -157,9 +167,15 @@ interface ActiveSession {readonly connectorSessionApprovals: Set<string>;toolSession: AkeruToolSession;readonly workspaceResourceKey: string;+ readonly pendingApprovals: Map<string, PendingApproval>;readonly unsubscribe: () => void;}+interface PendingApproval {+ readonly toolName: string;+ readonly action: string;+}+export interface AgentControllerLiveOptions {readonly makeMastraHarness?: (options: AkeruMastraHarnessOptions) => Promise<AkeruMastraHarness>;readonly makeMcpManager?: typeof createMcpManager;@@ -298,7 +314,7 @@ export function mcpServerIdForToolName(function permissionPolicy(runtimeMode: RuntimeMode,- category: "read" | "edit" | "execute" | "mcp" | "other",+ category: ReturnType<typeof akeruToolCategory>,): "allow" | "ask" {if (runtimeMode === "full-access" || runtimeMode === "auto") return "allow";if (category === "read") return "allow";@@ -306,6 +322,23 @@ function permissionPolicy(return "ask";}+function mcpToolNeedsApproval(manager: McpManager | undefined, toolName: string): boolean {+ if (BUILTIN_MASTRA_TOOL_NAMES.has(toolName)) return false;+ if (!manager) return true;+ const tools = manager.getTools();+ if (!tools || !Object.hasOwn(tools, toolName)) return true;+ const tool = tools[toolName] as {+ readonly mcp?: { readonly annotations?: { readonly readOnlyHint?: boolean } };+ };+ return tool.mcp?.annotations?.readOnlyHint !== true;+}++function approvalDetail(toolName: string, action: string | null, oneUse: boolean): string {+ if (!oneUse) return `Allow ${toolName}?`;+ const target = action ? `${action} action with ${toolName}` : `action with ${toolName}`;+ return `Approve this ${target}? This approval applies only to the pending action. It cannot undo completed work.`;+}+function usesMastraCode(provider: ProviderDriverKind): boolean {return provider === "codex" || provider === "kimi";}@@ -775,15 +808,32 @@ const make = (options?: AgentControllerLiveOptions) =>}};- const cancelPendingApprovals = (threadId: ThreadId, active: ActiveSession) => {- for (const requestId of active.approvalRequests.keys()) {- publish({- ...baseEvent(threadId, active, active.activeTurn?.turnId),- requestId: RuntimeRequestId.make(requestId),- type: "request.resolved",- payload: { requestType: "dynamic_tool_call", decision: "cancel" },- });+ const cancelPendingApproval = (+ threadId: ThreadId,+ active: ActiveSession,+ requestId: string,+ pending: PendingApproval,+ ) => {+ publish({+ ...baseEvent(threadId, active, active.activeTurn?.turnId),+ requestId: RuntimeRequestId.make(requestId),+ type: "request.resolved",+ payload: {+ requestType: "dynamic_tool_call",+ decision: "cancel",+ actor: "system",+ target: pending.toolName,+ action: pending.action,+ outcome: "cancelled",+ },+ });+ };++ const cancelAllPendingApprovals = (threadId: ThreadId, active: ActiveSession) => {+ for (const [requestId, pending] of active.pendingApprovals) {+ cancelPendingApproval(threadId, active, requestId, pending);}+ active.pendingApprovals.clear();active.approvalRequests.clear();toolRuntime.clearApprovals(String(threadId));};@@ -799,7 +849,7 @@ const make = (options?: AgentControllerLiveOptions) =>queueTurnMemory(threadId, active, turn);turn.finished = true;completeAssistantMessages(threadId, active, turn);- cancelPendingApprovals(threadId, active);+ cancelAllPendingApprovals(threadId, active);publish({...baseEvent(threadId, active, turn.turnId),type: "turn.completed",@@ -936,14 +986,7 @@ const make = (options?: AgentControllerLiveOptions) =>case "tool_end": {if (!turn) return;const toolName = active.toolNames.get(event.toolCallId) ?? "tool";- if (active.approvalRequests.delete(event.toolCallId)) {- publish({- ...baseEvent(threadId, active, turn.turnId),- requestId: RuntimeRequestId.make(event.toolCallId),- type: "request.resolved",- payload: { requestType: "dynamic_tool_call", decision: "cancel" },- });- }+ active.approvalRequests.delete(event.toolCallId);active.toolNames.delete(event.toolCallId);const mcpServerId = mcpServerIdForToolName(active.mcpServerIds, toolName);if (mcpServerId && !event.denied) {@@ -958,6 +1001,11 @@ const make = (options?: AgentControllerLiveOptions) =>toolName,event.isError || event.denied ? "failure" : "success",);+ const pending = active.pendingApprovals.get(event.toolCallId);+ if (pending) {+ cancelPendingApproval(threadId, active, event.toolCallId, pending);+ active.pendingApprovals.delete(event.toolCallId);+ }publish({...baseEvent(threadId, active, turn.turnId),itemId: RuntimeItemId.make(event.toolCallId),@@ -973,14 +1021,33 @@ const make = (options?: AgentControllerLiveOptions) =>});return;}- case "tool_approval_required":+ case "tool_approval_required": {if (!turn) return;completeAssistantMessages(threadId, active, turn);active.toolNames.set(event.toolCallId, event.toolName);+ const action = criticalAkeruAction(event.toolName, event.args);+ const oneUseApproval =+ akeruActionNeedsApproval(event.toolName, event.args) ||+ mcpToolNeedsApproval(sessionResources.getMcpManager(String(threadId)), event.toolName);+ if (+ event.toolName !== AKERU_PRODUCT_FEEDBACK_TOOL_NAME &&+ !oneUseApproval &&+ permissionPolicy(active.runtimeMode, akeruToolCategory(event.toolName)) === "allow"+ ) {+ active.session.respondToToolApproval({+ toolCallId: event.toolCallId,+ decision: "approve",+ });+ return;+ }active.approvalRequests.set(event.toolCallId, {name: event.toolName,input: event.args,});+ active.pendingApprovals.set(event.toolCallId, {+ toolName: event.toolName,+ action: action ?? "unclassified",+ });turn.waiting = true;publishSessionState(threadId, active, "waiting");publish({@@ -989,12 +1056,15 @@ const make = (options?: AgentControllerLiveOptions) =>type: "request.opened",payload: {requestType: "dynamic_tool_call",+ actor: "agent",+ target: event.toolName,detail: isCodexComputerUseTool(event.toolName)? "Allow Computer Use?": event.toolName === AKERU_PRODUCT_FEEDBACK_TOOL_NAME? "Review product feedback"- : `Allow ${event.toolName}?`,+ : approvalDetail(event.toolName, action, oneUseApproval),toolName: isCodexComputerUseTool(event.toolName) ? "Computer Use" : event.toolName,+ ...(action ? { action } : {}),args: isCodexComputerUseTool(event.toolName) ? undefined : event.args,options: isCodexComputerUseTool(event.toolName)? [@@ -1008,10 +1078,13 @@ const make = (options?: AgentControllerLiveOptions) =>]: AKERU_TOOL_CATALOG.some((tool) => tool.id === event.toolName) ||isMemoryToolId(event.toolName) ||- akeruActionNeedsApproval(event.toolName, event.args)+ oneUseApproval? [- { decision: "accept", label: "Allow" },{ decision: "decline", label: "Decline" },+ {+ decision: "accept",+ label: oneUseApproval ? "Approve" : "Allow",+ },]: [{ decision: "accept", label: "Allow" },@@ -1021,6 +1094,7 @@ const make = (options?: AgentControllerLiveOptions) =>},});return;+ }case "tool_suspended":if (!turn) return;completeAssistantMessages(threadId, active, turn);@@ -1489,6 +1563,7 @@ const make = (options?: AgentControllerLiveOptions) =>connectorSessionApprovals: new Set<string>(),toolSession,workspaceResourceKey,+ pendingApprovals: new Map<string, PendingApproval>(),unsubscribe,} satisfies ActiveSession;}).pipe(Effect.onError(() => cleanupCreatedSession));@@ -1645,8 +1720,10 @@ const make = (options?: AgentControllerLiveOptions) =>if (!active.activeTurn) return;const toolCallId = String(input.requestId);const toolRequest = active.approvalRequests.get(toolCallId);- if (!toolRequest) return;+ const pendingApproval = active.pendingApprovals.get(toolCallId);+ if (!toolRequest || !pendingApproval) return;active.approvalRequests.delete(toolCallId);+ active.pendingApprovals.delete(toolCallId);const { name: toolName, input: toolInput } = toolRequest;const akeruTool = AKERU_TOOL_CATALOG.find((tool) => tool.id === toolName);const runtimeToolId = akeruTool?.id ?? (isMemoryToolId(toolName) ? toolName : undefined);@@ -1670,19 +1747,31 @@ const make = (options?: AgentControllerLiveOptions) =>active.session.permissions.setForTool({ toolName, policy: "allow" }),);}+ const target = pendingApproval.toolName;+ const decision =+ input.decision === "acceptForSession" || input.decision === "acceptAlways"+ ? "accept"+ : input.decision;if (active.activeTurn) active.activeTurn.waiting = false;active.session.respondToToolApproval({toolCallId,decision:runtimeToolId && input.decision !== "decline" && input.decision !== "cancel"? "approve"- : approvalDecision(input.decision),+ : approvalDecision(decision),});publish({...baseEvent(input.threadId, active, active.activeTurn?.turnId),requestId: RuntimeRequestId.make(toolCallId),type: "request.resolved",- payload: { requestType: "dynamic_tool_call" as const, decision: input.decision },+ payload: {+ requestType: "dynamic_tool_call" as const,+ decision,+ actor: "user",+ target,+ action: pendingApproval.action,+ outcome: decision === "accept" ? "approved" : "denied",+ },});publishSessionState(input.threadId, active, "running");});@@ -1746,9 +1835,12 @@ const make = (options?: AgentControllerLiveOptions) =>}return yield* legacyProviderBridge.stopSession(input);}- cancelPendingApprovals(input.threadId, active);active.session.abort();- if (active.activeTurn) finishTurn(input.threadId, active, "interrupted");+ if (active.activeTurn) {+ finishTurn(input.threadId, active, "interrupted");+ } else {+ cancelAllPendingApprovals(input.threadId, active);+ }active.unsubscribe();publishSessionState(input.threadId, active, "stopped");yield* runMastra("deleteSession", () =>diff --git a/apps/server/src/provider/Layers/CodexAdapter.test.ts b/apps/server/src/provider/Layers/CodexAdapter.test.tsindex 7ec84f0a2..4f13f0a32 100644--- a/apps/server/src/provider/Layers/CodexAdapter.test.ts+++ b/apps/server/src/provider/Layers/CodexAdapter.test.ts@@ -1390,6 +1390,62 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {}),);+ it.effect("accumulates independent model-call usage within a turn", () =>+ Effect.gen(function* () {+ const { adapter, runtime } = yield* startLifecycleRuntime();+ const eventsFiber = yield* Stream.runCollect(Stream.take(adapter.streamEvents, 3)).pipe(+ Effect.forkChild,+ );++ for (const [index, totalTokens] of [400, 800, 1_200].entries()) {+ yield* runtime.emit({+ id: asEventId(`evt-codex-usage-${index}`),+ kind: "notification",+ provider: ProviderDriverKind.make("codex"),+ threadId: asThreadId("thread-1"),+ turnId: asTurnId("turn-1"),+ createdAt: "2026-01-01T00:00:00.000Z",+ method: "thread/tokenUsage/updated",+ payload: {+ threadId: "thread-1",+ turnId: "turn-1",+ tokenUsage: {+ total: {+ inputTokens: totalTokens - 100,+ cachedInputTokens: 0,+ outputTokens: 100,+ reasoningOutputTokens: 0,+ totalTokens,+ },+ last: {+ inputTokens: 300,+ cachedInputTokens: 0,+ outputTokens: 100,+ reasoningOutputTokens: 0,+ totalTokens: 400,+ },+ modelContextWindow: 258_400,+ },+ },+ } satisfies ProviderEvent);+ }++ const events = Array.from(yield* Fiber.join(eventsFiber));+ NodeAssert.deepEqual(+ events.map((event) =>+ event.type === "thread.token-usage.updated" ? event.payload.usage.lastUsedTokens : null,+ ),+ [400, 800, 1_200],+ );+ NodeAssert.deepEqual(+ events.map((event) =>+ event.type === "thread.token-usage.updated" ? event.payload.usage.lastInputTokens : null,+ ),+ [300, 600, 900],+ );+ }),+ );+// Production calls startSession from a request fiber that finishes as soon as// the session exists. `Effect.forkChild` made the runtime event consumer a// child of that fiber, and Effect interrupts a fiber's children when itdiff --git a/apps/server/src/provider/Layers/CodexAdapter.ts b/apps/server/src/provider/Layers/CodexAdapter.tsindex 7a2d71674..7c2e83255 100644--- a/apps/server/src/provider/Layers/CodexAdapter.ts+++ b/apps/server/src/provider/Layers/CodexAdapter.ts@@ -157,15 +157,40 @@ function isFatalCodexProcessStderrMessage(message: string): boolean {return FATAL_CODEX_STDERR_SNIPPETS.some((snippet) => normalized.includes(snippet));}+interface CodexTurnTokenUsage {+ readonly threadTotalTokens: number;+ readonly totalTokens: number;+ readonly inputTokens: number;+ readonly cachedInputTokens: number;+ readonly outputTokens: number;+ readonly reasoningOutputTokens: number;+}+function normalizeCodexTokenUsage(usage: EffectCodexSchema.V2ThreadTokenUsageUpdatedNotification["tokenUsage"],-): ThreadTokenUsageSnapshot | undefined {+ previous: CodexTurnTokenUsage | undefined,+):+ | { readonly snapshot: ThreadTokenUsageSnapshot; readonly total: CodexTurnTokenUsage }+ | undefined {const totalProcessedTokens = usage.total.totalTokens;const usedTokens = usage.last.totalTokens;if (usedTokens === undefined || usedTokens <= 0) {return undefined;}+ const isNewModelCall =+ previous === undefined || totalProcessedTokens > previous.threadTotalTokens;+ const total = isNewModelCall+ ? {+ threadTotalTokens: totalProcessedTokens,+ totalTokens: (previous?.totalTokens ?? 0) + usedTokens,+ inputTokens: (previous?.inputTokens ?? 0) + usage.last.inputTokens,+ cachedInputTokens: (previous?.cachedInputTokens ?? 0) + usage.last.cachedInputTokens,+ outputTokens: (previous?.outputTokens ?? 0) + usage.last.outputTokens,+ reasoningOutputTokens:+ (previous?.reasoningOutputTokens ?? 0) + usage.last.reasoningOutputTokens,+ }+ : previous;const maxTokens = usage.modelContextWindow ?? undefined;const inputTokens = usage.last.inputTokens;const cachedInputTokens = usage.last.cachedInputTokens;@@ -173,23 +198,24 @@ function normalizeCodexTokenUsage(const reasoningOutputTokens = usage.last.reasoningOutputTokens;return {- usedTokens,- ...(totalProcessedTokens !== undefined && totalProcessedTokens > usedTokens- ? { totalProcessedTokens }- : {}),- ...(maxTokens !== undefined ? { maxTokens } : {}),- ...(inputTokens !== undefined ? { inputTokens } : {}),- ...(cachedInputTokens !== undefined ? { cachedInputTokens } : {}),- ...(outputTokens !== undefined ? { outputTokens } : {}),- ...(reasoningOutputTokens !== undefined ? { reasoningOutputTokens } : {}),- ...(usedTokens !== undefined ? { lastUsedTokens: usedTokens } : {}),- ...(inputTokens !== undefined ? { lastInputTokens: inputTokens } : {}),- ...(cachedInputTokens !== undefined ? { lastCachedInputTokens: cachedInputTokens } : {}),- ...(outputTokens !== undefined ? { lastOutputTokens: outputTokens } : {}),- ...(reasoningOutputTokens !== undefined- ? { lastReasoningOutputTokens: reasoningOutputTokens }- : {}),- compactsAutomatically: true,+ total,+ snapshot: {+ usedTokens,+ ...(totalProcessedTokens !== undefined && totalProcessedTokens > usedTokens+ ? { totalProcessedTokens }+ : {}),+ ...(maxTokens !== undefined ? { maxTokens } : {}),+ ...(inputTokens !== undefined ? { inputTokens } : {}),+ ...(cachedInputTokens !== undefined ? { cachedInputTokens } : {}),+ ...(outputTokens !== undefined ? { outputTokens } : {}),+ ...(reasoningOutputTokens !== undefined ? { reasoningOutputTokens } : {}),+ lastUsedTokens: total.totalTokens,+ lastInputTokens: total.inputTokens,+ lastCachedInputTokens: total.cachedInputTokens,+ lastOutputTokens: total.outputTokens,+ lastReasoningOutputTokens: total.reasoningOutputTokens,+ compactsAutomatically: true,+ },};}@@ -764,6 +790,7 @@ function mapCollabAgentEvent(function mapToRuntimeEvents(event: ProviderEvent,canonicalThreadId: ThreadId,+ tokenUsageByTurnId?: Map<string, CodexTurnTokenUsage>,): ReadonlyArray<ProviderRuntimeEvent> {if (event.kind === "notification" && event.method.startsWith("collabAgent/")) {return mapCollabAgentEvent(event, canonicalThreadId);@@ -1019,16 +1046,21 @@ function mapToRuntimeEvents(EffectCodexSchema.V2ThreadTokenUsageUpdatedNotification,event.payload,);- const normalizedUsage = payload ? normalizeCodexTokenUsage(payload.tokenUsage) : undefined;- if (!normalizedUsage) {+ if (!payload) {return [];}+ const normalizedUsage = normalizeCodexTokenUsage(+ payload.tokenUsage,+ tokenUsageByTurnId?.get(payload.turnId),+ );+ if (!normalizedUsage) return [];+ tokenUsageByTurnId?.set(payload.turnId, normalizedUsage.total);return [{type: "thread.token-usage.updated",...runtimeEventBase(event, canonicalThreadId),payload: {- usage: normalizedUsage,+ usage: normalizedUsage.snapshot,},},];@@ -1039,6 +1071,7 @@ function mapToRuntimeEvents(if (!turnId) {return [];}+ tokenUsageByTurnId?.delete(turnId);return [{...runtimeEventBase(event, canonicalThreadId),@@ -1054,6 +1087,7 @@ function mapToRuntimeEvents(if (!payload) {return [];}+ if (event.turnId) tokenUsageByTurnId?.delete(event.turnId);const errorMessage = trimText(payload.turn.error?.message);return [{@@ -1068,6 +1102,7 @@ function mapToRuntimeEvents(}if (event.method === "turn/aborted") {+ if (event.turnId) tokenUsageByTurnId?.delete(event.turnId);return [{...runtimeEventBase(event, canonicalThreadId),@@ -1733,10 +1768,11 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (// this a child of `startSession`, and Effect interrupts a fiber's// children when it completes, so the consumer died on return and every// runtime event the session emitted afterwards was dropped.+ const tokenUsageByTurnId = new Map<string, CodexTurnTokenUsage>();const eventFiber = yield* Stream.runForEach(runtime.events, (event) =>Effect.gen(function* () {yield* writeNativeEvent(event);- const runtimeEvents = mapToRuntimeEvents(event, event.threadId);+ const runtimeEvents = mapToRuntimeEvents(event, event.threadId, tokenUsageByTurnId);if (runtimeEvents.length === 0) {yield* Effect.logDebug("ignoring unhandled Codex provider event", {method: event.method,diff --git a/apps/server/src/provider/botBrowser.test.ts b/apps/server/src/provider/botBrowser.test.tsindex dddefcb61..072d5487e 100644--- a/apps/server/src/provider/botBrowser.test.ts+++ b/apps/server/src/provider/botBrowser.test.ts@@ -7,6 +7,7 @@ import {import { describe, expect, it, vi } from "vite-plus/test";import {+ browserRpcErrorMessage,createBotBrowser,createBotBrowserTools,lightpandaMcpCommand,@@ -40,6 +41,15 @@ async function executeTool(}describe("sandbox bot browser", () => {+ it("redacts sensitive browser RPC errors", () => {+ expect(+ browserRpcErrorMessage({+ code: -1,+ message: "Browser failed for [email protected] token=secret-value-1234",+ }),+ ).toBe("Browser failed for [REDACTED] [REDACTED]");+ });+it("exposes only the Akeru navigate, snapshot, click, and type tools", () => {expect(Object.keys(createBotBrowserTools(rpc()))).toEqual(["browser_navigate",diff --git a/apps/server/src/provider/botBrowser.ts b/apps/server/src/provider/botBrowser.tsindex b63a3c2ba..2d244b573 100644--- a/apps/server/src/provider/botBrowser.ts+++ b/apps/server/src/provider/botBrowser.ts@@ -6,11 +6,10 @@ import * as NodeTimersPromises from "node:timers/promises";import type { ToolsInput } from "@mastra/core/agent";import { createTool } from "@mastra/core/tools";import type { ProcessHandle, Workspace, WorkspaceSandbox } from "@mastra/core/workspace";+import { redactSensitiveText } from "@t3tools/shared/sensitiveDataRedaction";import { z } from "zod";-import { redactSensitiveText } from "../mcp/SensitiveDataRedaction.ts";import type { AkeruBrowserEndpoint } from "./botWorkspace.ts";-const LIGHTPANDA_VERSION = "0.3.7";const MAX_SNAPSHOT_LENGTH = 50 * 1_024;const MCP_PROTOCOL_VERSION = "2024-11-05";@@ -82,6 +81,10 @@ interface JsonRpcResponse {readonly error?: { readonly code?: number; readonly message?: string };}+export function browserRpcErrorMessage(error: NonNullable<JsonRpcResponse["error"]>): string {+ return redactSensitiveText(error.message ?? `Browser RPC ${error.code ?? "failed"}.`).value;+}+export interface BrowserHttpResponse {readonly status: number;readonly body: string;@@ -455,7 +458,7 @@ class LightpandaRpc implements BotBrowserRpc {}const parsed = JSON.parse(response.body) as JsonRpcResponse;if (parsed.error) {- throw new Error(parsed.error.message ?? `Browser RPC ${parsed.error.code ?? "failed"}.`);+ throw new Error(browserRpcErrorMessage(parsed.error));}return {result: parsed.result,@@ -504,10 +507,9 @@ export function createBotBrowserTools(rpc: BotBrowserRpc): ToolsInput {inputSchema: z.object({}),execute: async () => {const snapshot = await call("tree", {});- const redacted = redactSensitiveText(snapshot).value;return {- snapshot: redacted.slice(0, MAX_SNAPSHOT_LENGTH),- truncated: redacted.length > MAX_SNAPSHOT_LENGTH,+ snapshot: snapshot.slice(0, MAX_SNAPSHOT_LENGTH),+ truncated: snapshot.length > MAX_SNAPSHOT_LENGTH,};},}),diff --git a/apps/server/src/relay/AgentAwarenessRelay.test.ts b/apps/server/src/relay/AgentAwarenessRelay.test.tsdeleted file mode 100644index 80ab7941c..000000000--- a/apps/server/src/relay/AgentAwarenessRelay.test.ts+++ /dev/null@@ -1,739 +0,0 @@-import * as NodeCrypto from "node:crypto";-import * as NodeServices from "@effect/platform-node/NodeServices";--import type {- EnvironmentId,- ExecutionEnvironmentDescriptor,- OrchestrationEvent,- OrchestrationProjectShell,- OrchestrationShellSnapshot,- OrchestrationThreadShell,- ProjectId,- ThreadId,- TurnId,-} from "@t3tools/contracts";-import type {- RelayAgentActivityPublishProofPayload,- RelayAgentActivityState,-} from "@t3tools/contracts/relay";-import { CommandId, ProviderInstanceId } from "@t3tools/contracts";-import { RelayClientTracer } from "@t3tools/shared/relayTracing";-import { RELAY_ACTIVITY_PUBLISH_TYP, verifyRelayJwt } from "@t3tools/shared/relayJwt";-import { describe, expect, it } from "@effect/vitest";-import * as Deferred from "effect/Deferred";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";-import * as Option from "effect/Option";-import * as Queue from "effect/Queue";-import * as Stream from "effect/Stream";-import * as Tracer from "effect/Tracer";--import * as ServerSecretStore from "../auth/ServerSecretStore.ts";-import * as ServerEnvironment from "../environment/ServerEnvironment.ts";-import {- OrchestrationEngineService,- type OrchestrationEngineShape,-} from "../orchestration/Services/OrchestrationEngine.ts";-import {- ProjectionSnapshotQuery,- type ProjectionSnapshotQueryShape,-} from "../orchestration/Services/ProjectionSnapshotQuery.ts";-import {- RELAY_ENVIRONMENT_CREDENTIAL_SECRET,- RELAY_ISSUER_SECRET,- RELAY_URL_SECRET,- PUBLISH_AGENT_ACTIVITY_SECRET,-} from "../cloud/config.ts";-import * as AgentAwarenessRelay from "./AgentAwarenessRelay.ts";--const state: RelayAgentActivityState = {- environmentId: "env" as RelayAgentActivityState["environmentId"],- threadId: "thread" as RelayAgentActivityState["threadId"],- projectTitle: "Project",- threadTitle: "Thread",- modelTitle: "gpt-5.4",- phase: "running",- headline: "Running",- updatedAt: "2026-05-25T00:00:00.000Z",- deepLink: "/threads/env/thread",-};--const encodeSecret = (value: string): Uint8Array => new TextEncoder().encode(value);--function makeMemorySecretStore() {- const values = new Map<string, Uint8Array>();- const store = {- get: ((name) =>- Effect.sync(() => {- const value = values.get(name);- return value === undefined ? Option.none() : Option.some(Uint8Array.from(value));- })) satisfies ServerSecretStore.ServerSecretStore["Service"]["get"],- set: ((name, value) =>- Effect.sync(() => {- values.set(name, Uint8Array.from(value));- })) satisfies ServerSecretStore.ServerSecretStore["Service"]["set"],- create: ((name, value) =>- Effect.sync(() => {- values.set(name, Uint8Array.from(value));- })) satisfies ServerSecretStore.ServerSecretStore["Service"]["create"],- getOrCreateRandom: ((name, bytes) =>- Effect.sync(() => {- const existing = values.get(name);- if (existing) {- return existing;- }- const generated = new Uint8Array(bytes);- values.set(name, generated);- return generated;- })) satisfies ServerSecretStore.ServerSecretStore["Service"]["getOrCreateRandom"],- remove: ((name) =>- Effect.sync(() => {- values.delete(name);- })) satisfies ServerSecretStore.ServerSecretStore["Service"]["remove"],- } satisfies ServerSecretStore.ServerSecretStore["Service"];- return {- store,- setString: (name: string, value: string) => store.set(name, encodeSecret(value)),- };-}--describe.sequential("signRelayAgentActivityPublishProof", () => {- it("distinguishes pending link credentials from disabled publication", () => {- expect(- AgentAwarenessRelay.resolveAgentActivityPublishingStartupState({- relayConfigured: false,- publishEnabled: false,- }),- ).toBe("waiting-for-link");- expect(- AgentAwarenessRelay.resolveAgentActivityPublishingStartupState({- relayConfigured: true,- publishEnabled: false,- }),- ).toBe("disabled");- expect(- AgentAwarenessRelay.resolveAgentActivityPublishingStartupState({- relayConfigured: true,- publishEnabled: true,- }),- ).toBe("enabled");- });-- it("derives the thread id from the aggregate id for thread events without payload thread ids", () => {- const threadId = "thread-aggregate-1" as ThreadId;- const now = "2026-05-25T00:00:00.000Z";- const event = {- type: "thread.activity-appended",- sequence: 1,- eventId: "evt-aggregate-1",- commandId: CommandId.make("cmd-1"),- aggregateKind: "thread",- aggregateId: threadId,- actor: { kind: "server" },- payload: {},- occurredAt: now,- } as unknown as OrchestrationEvent;-- expect(AgentAwarenessRelay.eventThreadId(event)).toBe(threadId);- });-- it("does not publish start intents, streaming content, or non-awareness activity events", () => {- const now = "2026-05-25T00:00:00.000Z";- const base = {- sequence: 1,- eventId: "evt-1",- commandId: CommandId.make("cmd-1"),- aggregateKind: "thread",- aggregateId: "thread-1" as ThreadId,- occurredAt: now,- };-- expect(- AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({- ...base,- type: "thread.message-sent",- payload: {- threadId: "thread-1" as ThreadId,- streaming: true,- },- } as unknown as OrchestrationEvent),- ).toBe(false);- expect(- AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({- ...base,- type: "thread.activity-appended",- payload: {- threadId: "thread-1" as ThreadId,- activity: {- kind: "task.progress",- },- },- } as unknown as OrchestrationEvent),- ).toBe(false);- expect(- AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({- ...base,- type: "thread.activity-appended",- payload: {- threadId: "thread-1" as ThreadId,- activity: {- kind: "approval.requested",- },- },- } as unknown as OrchestrationEvent),- ).toBe(true);- expect(- AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({- ...base,- metadata: { importedHistory: true },- type: "thread.archived",- payload: { threadId: "thread-1" as ThreadId },- } as unknown as OrchestrationEvent),- ).toBe(false);- expect(- AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({- ...base,- type: "thread.message-sent",- payload: {- threadId: "thread-1" as ThreadId,- streaming: false,- },- } as unknown as OrchestrationEvent),- ).toBe(false);- expect(- AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({- ...base,- type: "thread.turn-start-requested",- payload: {- threadId: "thread-1" as ThreadId,- },- } as unknown as OrchestrationEvent),- ).toBe(false);- });-- it("deduplicates awareness state updates whose only change is their event timestamp", () => {- expect(AgentAwarenessRelay.agentAwarenessPublishIdentity(state)).toBe(- AgentAwarenessRelay.agentAwarenessPublishIdentity({- ...state,- updatedAt: "2026-05-25T00:10:00.000Z",- }),- );- expect(AgentAwarenessRelay.agentAwarenessPublishIdentity(state)).not.toBe(- AgentAwarenessRelay.agentAwarenessPublishIdentity({- ...state,- phase: "completed",- headline: "Agent finished",- }),- );- });-- it("requires an explicit opt-in before publishing agent activity", () => {- expect(AgentAwarenessRelay.isAgentActivityPublishingEnabled(null)).toBe(false);- expect(AgentAwarenessRelay.isAgentActivityPublishingEnabled("false")).toBe(false);- expect(AgentAwarenessRelay.isAgentActivityPublishingEnabled("true")).toBe(true);- });-- it("redacts failed activity details and caps other relay detail", () => {- expect(- AgentAwarenessRelay.sanitizeRelayAgentActivityState({- ...state,- phase: "failed",- detail: "Provider process exited with secret token.",- }),- ).toMatchObject({- phase: "failed",- detail: "The agent run failed.",- });- expect(- AgentAwarenessRelay.sanitizeRelayAgentActivityState({- ...state,- detail: "x".repeat(200),- })?.detail,- ).toHaveLength(160);- });-- it("resolves a null publish state when a thread or project snapshot disappeared", () => {- const environmentId = "env-1" as EnvironmentId;- const threadId = "thread-1" as ThreadId;- const thread = {- id: threadId,- projectId: "project-1" as ProjectId,- title: "Deleted thread",- modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },- session: null,- latestTurn: null,- updatedAt: "2026-05-25T00:00:00.000Z",- hasPendingApprovals: false,- hasPendingUserInput: false,- } as OrchestrationThreadShell;-- expect(- AgentAwarenessRelay.resolveAgentAwarenessRelayPublishSnapshot({- environmentId,- threadId,- thread: Option.none(),- project: Option.none(),- }),- ).toEqual({- projectId: null,- state: null,- reason: "thread-not-found",- });-- expect(- AgentAwarenessRelay.resolveAgentAwarenessRelayPublishSnapshot({- environmentId,- threadId,- thread: Option.some(thread),- project: Option.none(),- }),- ).toEqual({- projectId: "project-1",- state: null,- reason: "project-not-found",- });- });-- it("selects only active shell snapshot threads for startup catch-up", () => {- const now = "2026-05-25T00:00:00.000Z";- const environmentId = "env-1" as EnvironmentId;- const projectId = "project-1" as ProjectId;- const activeThreadId = "thread-active" as ThreadId;- const idleThreadId = "thread-idle" as ThreadId;-- const baseThread = {- projectId,- title: "Run remote agent",- modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },- runtimeMode: "full-access",- interactionMode: "default",- branch: null,- worktreePath: null,- latestTurn: null,- createdAt: now,- updatedAt: now,- archivedAt: null,- settledOverride: null,- settledAt: null,- session: null,- latestUserMessageAt: null,- hasPendingApprovals: false,- hasPendingUserInput: false,- hasActionableProposedPlan: false,- } satisfies Omit<OrchestrationThreadShell, "id">;-- expect(- AgentAwarenessRelay.resolveAgentAwarenessRelayActiveThreadIds({- environmentId,- projects: [- {- id: projectId,- title: "T3 Code",- },- ],- threads: [- {- ...baseThread,- id: activeThreadId,- latestTurn: {- turnId: "turn-1" as TurnId,- state: "running",- requestedAt: now,- startedAt: now,- completedAt: null,- assistantMessageId: null,- },- },- {- ...baseThread,- id: idleThreadId,- },- {- ...baseThread,- id: "thread-missing-project" as ThreadId,- projectId: "missing-project" as ProjectId,- latestTurn: {- turnId: "turn-2" as TurnId,- state: "running",- requestedAt: now,- startedAt: now,- completedAt: null,- assistantMessageId: null,- },- },- ],- }),- ).toEqual([activeThreadId]);- });-- it("signs the activity publish JWT and rejects tampering", async () => {- const keyPair = NodeCrypto.generateKeyPairSync("ed25519", {- privateKeyEncoding: { format: "pem", type: "pkcs8" },- publicKeyEncoding: { format: "pem", type: "spki" },- });- const payload = {- iss: "t3-env:env",- aud: "https://relay.example.test",- sub: "env",- jti: "nonce-1",- iat: 100,- exp: 200,- environmentId: state.environmentId,- threadId: state.threadId,- state,- } satisfies RelayAgentActivityPublishProofPayload;- const proof = await Effect.runPromise(- AgentAwarenessRelay.signRelayAgentActivityPublishProof({- privateKey: keyPair.privateKey,- payload,- }),- );-- await expect(- Effect.runPromise(- verifyRelayJwt({- publicKey: keyPair.publicKey,- token: proof,- typ: RELAY_ACTIVITY_PUBLISH_TYP,- issuer: "t3-env:env",- audience: "https://relay.example.test",- nowEpochSeconds: 150,- }),- ),- ).resolves.toMatchObject({ jti: "nonce-1", state });- await expect(- Effect.runPromise(- verifyRelayJwt({- publicKey: keyPair.publicKey,- token: (() => {- const [header, body, signature = ""] = proof.split(".");- const corruptedSignature = `${signature.startsWith("a") ? "b" : "a"}${signature.slice(1)}`;- return `${header}.${body}.${corruptedSignature}`;- })(),- typ: RELAY_ACTIVITY_PUBLISH_TYP,- issuer: "t3-env:env",- audience: "https://relay.example.test",- nowEpochSeconds: 150,- }),- ),- ).rejects.toBeDefined();- });-- it.effect("keeps the orchestration listener armed until relay config is installed", () =>- Effect.scoped(- Effect.gen(function* () {- const events = yield* Queue.unbounded<OrchestrationEvent>();- const threadShellRequested = yield* Deferred.make<void>();- const secrets = makeMemorySecretStore();- const now = "2026-05-25T00:00:00.000Z";- const projectId = "project-1" as ProjectId;- const threadId = "thread-1" as ThreadId;- const environmentId = "env-1" as EnvironmentId;-- const project = {- id: projectId,- title: "T3 Code",- workspaceRoot: "/workspace",- repositoryIdentity: null,- defaultModelSelection: null,- scripts: [],- createdAt: now,- updatedAt: now,- } satisfies OrchestrationProjectShell;-- const thread = {- id: threadId,- projectId,- title: "Run remote agent",- modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },- runtimeMode: "full-access",- interactionMode: "default",- branch: null,- worktreePath: null,- latestTurn: {- turnId: "turn-1" as TurnId,- state: "running",- requestedAt: now,- startedAt: now,- completedAt: null,- assistantMessageId: null,- },- createdAt: now,- updatedAt: now,- archivedAt: null,- settledOverride: null,- settledAt: null,- session: {- threadId,- status: "running",- providerName: "Codex",- runtimeMode: "full-access",- activeTurnId: "turn-1" as TurnId,- lastError: null,- updatedAt: now,- },- latestUserMessageAt: now,- hasPendingApprovals: false,- hasPendingUserInput: false,- hasActionableProposedPlan: false,- } satisfies OrchestrationThreadShell;-- const orchestrationEngine = {- readEvents: () => Stream.empty,- dispatch: () => Effect.succeed({ sequence: 1 }),- streamDomainEvents: Stream.fromQueue(events),- latestSequence: Effect.succeed(0),- } satisfies OrchestrationEngineShape;-- const snapshotQuery = {- getShellSnapshot: () =>- Effect.succeed({- snapshotSequence: 1,- projects: [project],- bots: [],- groups: [],- delegations: [],- threads: [thread],- updatedAt: now,- } satisfies OrchestrationShellSnapshot),- getThreadShellById: () =>- Deferred.succeed(threadShellRequested, undefined).pipe(- Effect.ignore,- Effect.as(Option.some(thread)),- ),- getProjectShellById: () => Effect.succeed(Option.some(project)),- } as unknown as ProjectionSnapshotQueryShape;-- const descriptor = {- environmentId,- label: "Test Desktop",- platform: {- os: "darwin",- arch: "arm64",- },- serverVersion: "0.0.0-test",- capabilities: {- repositoryIdentity: true,- },- } satisfies ExecutionEnvironmentDescriptor;-- const layer = Layer.mergeAll(- Layer.succeed(ServerSecretStore.ServerSecretStore, secrets.store),- Layer.succeed(ServerEnvironment.ServerEnvironment, {- getEnvironmentId: Effect.succeed(environmentId),- getDescriptor: Effect.succeed(descriptor),- }),- Layer.succeed(OrchestrationEngineService, orchestrationEngine),- Layer.succeed(ProjectionSnapshotQuery, snapshotQuery),- );-- yield* Effect.gen(function* () {- const relay = yield* AgentAwarenessRelay.AgentAwarenessRelay;- yield* relay.start();- yield* secrets.setString(RELAY_URL_SECRET, "http://127.0.0.1:1");- yield* secrets.setString(RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "relay-credential");- yield* secrets.setString(PUBLISH_AGENT_ACTIVITY_SECRET, "true");- yield* Queue.offer(events, {- type: "thread.activity-appended",- sequence: 1,- eventId: "evt-1",- commandId: CommandId.make("cmd-1"),- aggregateKind: "thread",- aggregateId: threadId,- actor: { kind: "server" },- payload: {- threadId,- activity: {- kind: "approval.requested",- },- },- occurredAt: now,- } as unknown as OrchestrationEvent);-- yield* Deferred.await(threadShellRequested).pipe(Effect.timeout("2 seconds"));- }).pipe(- Effect.provide(- AgentAwarenessRelay.layer.pipe(- Layer.provide(layer),- Layer.provideMerge(NodeServices.layer),- ),- ),- );- }),- ),- );-- it.effect("publishes agent activity to the relay transport URL, not the relay issuer", () =>- Effect.scoped(- Effect.gen(function* () {- const originalFetch = globalThis.fetch;- const context = yield* Effect.context<never>();- const runFork = Effect.runForkWith(context);- const events = yield* Queue.unbounded<OrchestrationEvent>();- const fetchSeen = yield* Deferred.make<URL>();- const userSpans: Array<string> = [];- const productSpans: Array<string> = [];- const collectingTracer = (spans: Array<string>) =>- Tracer.make({- span: (options) => {- const span = new Tracer.NativeSpan(options);- const end = span.end.bind(span);- span.end = (endTime, exit) => {- end(endTime, exit);- spans.push(span.name);- };- return span;- },- });- const secrets = makeMemorySecretStore();- const now = "2026-05-25T00:00:00.000Z";- const projectId = "project-1" as ProjectId;- const threadId = "thread-1" as ThreadId;- const environmentId = "env-1" as EnvironmentId;-- const project = {- id: projectId,- title: "T3 Code",- workspaceRoot: "/workspace",- repositoryIdentity: null,- defaultModelSelection: null,- scripts: [],- createdAt: now,- updatedAt: now,- } satisfies OrchestrationProjectShell;-- const thread = {- id: threadId,- projectId,- title: "Run remote agent",- modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },- runtimeMode: "full-access",- interactionMode: "default",- branch: null,- worktreePath: null,- latestTurn: {- turnId: "turn-1" as TurnId,- state: "running",- requestedAt: now,- startedAt: now,- completedAt: null,- assistantMessageId: null,- },- createdAt: now,- updatedAt: now,- archivedAt: null,- settledOverride: null,- settledAt: null,- session: {- threadId,- status: "running",- providerName: "Codex",- runtimeMode: "full-access",- activeTurnId: "turn-1" as TurnId,- lastError: null,- updatedAt: now,- },- latestUserMessageAt: now,- hasPendingApprovals: false,- hasPendingUserInput: false,- hasActionableProposedPlan: false,- } satisfies OrchestrationThreadShell;-- const descriptor = {- environmentId,- label: "Test Desktop",- platform: {- os: "darwin",- arch: "arm64",- },- serverVersion: "0.0.0-test",- capabilities: {- repositoryIdentity: true,- },- } satisfies ExecutionEnvironmentDescriptor;-- globalThis.fetch = ((input: Parameters<typeof fetch>[0]) => {- const url = new URL(- typeof input === "string" || input instanceof URL- ? input- : (input as unknown as { readonly url: string }).url,- );- runFork(Deferred.succeed(fetchSeen, url));- return Promise.resolve(Response.json({ ok: true, deliveries: [] }));- }) as unknown as typeof fetch;- yield* Effect.addFinalizer(() =>- Effect.sync(() => {- globalThis.fetch = originalFetch;- }),- );-- const layer = Layer.mergeAll(- Layer.succeed(ServerSecretStore.ServerSecretStore, secrets.store),- Layer.succeed(ServerEnvironment.ServerEnvironment, {- getEnvironmentId: Effect.succeed(environmentId),- getDescriptor: Effect.succeed(descriptor),- }),- Layer.succeed(OrchestrationEngineService, {- readEvents: () => Stream.empty,- dispatch: () => Effect.succeed({ sequence: 1 }),- streamDomainEvents: Stream.fromQueue(events),- latestSequence: Effect.succeed(0),- } satisfies OrchestrationEngineShape),- Layer.succeed(ProjectionSnapshotQuery, {- getShellSnapshot: () =>- Effect.succeed({- snapshotSequence: 1,- projects: [project],- bots: [],- groups: [],- delegations: [],- threads: [thread],- updatedAt: now,- } satisfies OrchestrationShellSnapshot),- getThreadShellById: () => Effect.succeed(Option.some(thread)),- getProjectShellById: () => Effect.succeed(Option.some(project)),- } as unknown as ProjectionSnapshotQueryShape),- );-- yield* Effect.gen(function* () {- const relay = yield* AgentAwarenessRelay.AgentAwarenessRelay;- yield* secrets.setString(RELAY_URL_SECRET, "https://transport.example.test");- yield* secrets.setString(RELAY_ISSUER_SECRET, "https://issuer.example.test");- yield* secrets.setString(RELAY_ENVIRONMENT_CREDENTIAL_SECRET, "relay-credential");- yield* secrets.setString(PUBLISH_AGENT_ACTIVITY_SECRET, "true");- yield* relay.start();- yield* Queue.offer(events, {- type: "thread.activity-appended",- sequence: 1,- eventId: "evt-1",- commandId: CommandId.make("cmd-1"),- aggregateKind: "thread",- aggregateId: threadId,- actor: { kind: "server" },- payload: {- threadId,- activity: {- kind: "approval.requested",- },- },- occurredAt: now,- } as unknown as OrchestrationEvent);-- const url = yield* Deferred.await(fetchSeen).pipe(Effect.timeout("2 seconds"));- expect(url.origin).toBe("https://transport.example.test");- expect(productSpans).toContain("makePublishProof");- expect(userSpans).not.toContain("makePublishProof");- }).pipe(- Effect.provide(- AgentAwarenessRelay.layer.pipe(- Layer.provide(layer),- Layer.provideMerge(NodeServices.layer),- ),- ),- Effect.provideService(RelayClientTracer, Option.some(collectingTracer(productSpans))),- Effect.withTracer(collectingTracer(userSpans)),- );- }),- ),- );-});diff --git a/apps/server/src/relay/AgentAwarenessRelay.ts b/apps/server/src/relay/AgentAwarenessRelay.tsdeleted file mode 100644index 768926401..000000000--- a/apps/server/src/relay/AgentAwarenessRelay.ts+++ /dev/null@@ -1,642 +0,0 @@-import type {- EnvironmentId,- OrchestrationEvent,- OrchestrationProjectShell,- OrchestrationThreadShell,- ThreadId,-} from "@t3tools/contracts";-import {- RelayApi,- type RelayAgentActivityPublishProofPayload,- type RelayAgentActivityState,-} from "@t3tools/contracts/relay";-import { projectThreadAwareness } from "@t3tools/shared/agentAwareness";-import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";-import { withRelayClientTracing } from "@t3tools/shared/relayTracing";-import {- normalizeRelayIssuer,- RELAY_ACTIVITY_PUBLISH_TYP,- signRelayJwt,-} from "@t3tools/shared/relayJwt";-import * as Cause from "effect/Cause";-import * as Context from "effect/Context";-import * as Crypto from "effect/Crypto";-import * as DateTime from "effect/DateTime";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";-import * as Option from "effect/Option";-import * as Ref from "effect/Ref";-import type * as Scope from "effect/Scope";-import * as Stream from "effect/Stream";-import * as FetchHttpClient from "effect/unstable/http/FetchHttpClient";-import * as HttpClient from "effect/unstable/http/HttpClient";-import * as HttpClientRequest from "effect/unstable/http/HttpClientRequest";-import * as HttpApiClient from "effect/unstable/httpapi/HttpApiClient";--import * as ServerSecretStore from "../auth/ServerSecretStore.ts";-import {- isAgentActivityPublishingEnabledValue,- PUBLISH_AGENT_ACTIVITY_SECRET,- RELAY_ENVIRONMENT_CREDENTIAL_SECRET,- RELAY_ISSUER_SECRET,- RELAY_URL_SECRET,-} from "../cloud/config.ts";-import { getOrCreateEnvironmentKeyPairFromSecretStore } from "../cloud/environmentKeys.ts";-import * as ServerEnvironment from "../environment/ServerEnvironment.ts";-import * as OrchestrationEngine from "../orchestration/Services/OrchestrationEngine.ts";-import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";-import { forkParked } from "../serverActivation.ts";--export class AgentAwarenessRelay extends Context.Service<- AgentAwarenessRelay,- {- readonly publishThread: (threadId: ThreadId) => Effect.Effect<void>;- readonly start: () => Effect.Effect<void, never, Scope.Scope>;- }->()("akeru-bot/relay/AgentAwarenessRelay") {}--export function eventThreadId(event: OrchestrationEvent): ThreadId | null {- const payload = event.payload as { readonly threadId?: unknown };- if (typeof payload.threadId === "string") {- return payload.threadId as ThreadId;- }- if (event.aggregateKind === "thread" && typeof event.aggregateId === "string") {- return event.aggregateId as ThreadId;- }- return null;-}--export function shouldPublishAgentAwarenessEvent(event: OrchestrationEvent): boolean {- if (event.metadata?.importedHistory === true) return false;- switch (event.type) {- case "thread.message-sent":- case "thread.turn-start-requested":- // These events express intent to start work, but the shell still contains- // the previous turn's terminal state until the provider acknowledges the- // new turn. Publishing that snapshot can queue a fresh "Done" alert just- // before the real running state arrives. Provider lifecycle events publish- // the authoritative starting/running state instead.- return false;- case "thread.proposed-plan-upserted":- case "thread.runtime-mode-set":- case "thread.interaction-mode-set":- return false;- case "thread.activity-appended":- return (- event.payload.activity.kind === "approval.requested" ||- event.payload.activity.kind === "approval.resolved" ||- event.payload.activity.kind === "provider.approval.respond.failed" ||- event.payload.activity.kind === "user-input.requested" ||- event.payload.activity.kind === "user-input.resolved" ||- event.payload.activity.kind === "runtime.error"- );- default:- return true;- }-}--export function agentAwarenessPublishIdentity(state: RelayAgentActivityState | null): string {- if (state === null) {- return "null";- }- const { updatedAt: _updatedAt, ...meaningfulState } = state;- return JSON.stringify(meaningfulState);-}--export function isAgentActivityPublishingEnabled(value: string | null): boolean {- return isAgentActivityPublishingEnabledValue(value);-}--export function resolveAgentActivityPublishingStartupState(input: {- readonly relayConfigured: boolean;- readonly publishEnabled: boolean;-}): "waiting-for-link" | "disabled" | "enabled" {- if (!input.relayConfigured) {- return "waiting-for-link";- }- return input.publishEnabled ? "enabled" : "disabled";-}--const RELAY_AGENT_ACTIVITY_DETAIL_MAX_LENGTH = 160;-const REDACTED_RELAY_AGENT_FAILURE_DETAIL = "The agent run failed.";--export function sanitizeRelayAgentActivityState(- state: RelayAgentActivityState | null,-): RelayAgentActivityState | null {- if (state === null) {- return null;- }- const { detail: _detail, ...rest } = state;- const detail = (state.phase === "failed" ? REDACTED_RELAY_AGENT_FAILURE_DETAIL : state.detail)- ?.trim()- .slice(0, RELAY_AGENT_ACTIVITY_DETAIL_MAX_LENGTH)- .trim();- return detail ? { ...rest, detail } : rest;-}--function relayEnvironmentClient(token: string) {- return HttpClient.mapRequest(HttpClientRequest.setHeader("authorization", `Bearer ${token}`));-}--function deliveryStats(- deliveries: ReadonlyArray<{- readonly ok: boolean;- readonly queued?: boolean | undefined;- readonly kind: string;- readonly apnsStatus?: number | null;- readonly apnsReason?: string | null;- }>,-) {- let queued = 0;- let successful = 0;- let failed = 0;- const failedReasons: string[] = [];- const kinds = new Set<string>();-- for (const delivery of deliveries) {- kinds.add(delivery.kind);- if (delivery.queued) {- queued += 1;- continue;- }- if (delivery.ok) {- successful += 1;- continue;- }- failed += 1;- failedReasons.push(`${delivery.apnsStatus ?? "transport"}:${delivery.apnsReason ?? "unknown"}`);- }-- return {- total: deliveries.length,- queued,- successful,- failed,- kinds: [...kinds],- failedReasons,- };-}--export function signRelayAgentActivityPublishProof(input: {- readonly privateKey: string;- readonly payload: RelayAgentActivityPublishProofPayload;-}) {- return signRelayJwt({- privateKey: input.privateKey,- typ: RELAY_ACTIVITY_PUBLISH_TYP,- payload: input.payload,- });-}--const makePublishProof = Effect.fn("makePublishProof")(function* (input: {- readonly privateKey: string;- readonly relayIssuer: string;- readonly environmentId: string;- readonly threadId: ThreadId;- readonly state: RelayAgentActivityState | null;- readonly jti: string;-}) {- const now = yield* DateTime.now;- const expiresAt = DateTime.add(now, { minutes: 5 });- const payload = {- iss: `t3-env:${input.environmentId}`,- aud: normalizeRelayIssuer(input.relayIssuer),- sub: input.environmentId,- jti: input.jti,- iat: Math.floor(now.epochMilliseconds / 1_000),- exp: Math.floor(expiresAt.epochMilliseconds / 1_000),- environmentId: input.environmentId as RelayAgentActivityPublishProofPayload["environmentId"],- threadId: input.threadId,- state: input.state,- } satisfies RelayAgentActivityPublishProofPayload;- return yield* signRelayAgentActivityPublishProof({ privateKey: input.privateKey, payload });-});--// Compact, log-safe view of the fields the awareness phase ladder reads.-export function describeThreadShellForAwareness(- thread: Option.Option<OrchestrationThreadShell>,-): Record<string, unknown> {- if (Option.isNone(thread)) {- return { found: false };- }- const shell = thread.value;- return {- found: true,- sessionStatus: shell.session?.status ?? null,- sessionActiveTurnId: shell.session?.activeTurnId ?? null,- latestTurnId: shell.latestTurn?.turnId ?? null,- latestTurnState: shell.latestTurn?.state ?? null,- latestTurnCompletedAt: shell.latestTurn?.completedAt ?? null,- hasPendingApprovals: shell.hasPendingApprovals,- hasPendingUserInput: shell.hasPendingUserInput,- };-}--export function resolveAgentAwarenessRelayPublishSnapshot(input: {- readonly environmentId: EnvironmentId;- readonly threadId: ThreadId;- readonly thread: Option.Option<OrchestrationThreadShell>;- readonly project: Option.Option<OrchestrationProjectShell>;-}): {- readonly projectId: string | null;- readonly state: RelayAgentActivityState | null;- readonly reason: "snapshot" | "thread-not-found" | "project-not-found";-} {- if (Option.isNone(input.thread)) {- return {- projectId: null,- state: null,- reason: "thread-not-found",- };- }- if (Option.isNone(input.project)) {- return {- projectId: input.thread.value.projectId,- state: null,- reason: "project-not-found",- };- }- return {- projectId: input.thread.value.projectId,- state: sanitizeRelayAgentActivityState(- projectThreadAwareness({- environmentId: input.environmentId,- project: input.project.value,- thread: input.thread.value,- }),- ),- reason: "snapshot",- };-}--export function resolveAgentAwarenessRelayActiveThreadIds(input: {- readonly environmentId: EnvironmentId;- readonly projects: ReadonlyArray<Pick<OrchestrationProjectShell, "id" | "title">>;- readonly threads: ReadonlyArray<OrchestrationThreadShell>;-}): ReadonlyArray<ThreadId> {- const projectById = new Map(input.projects.map((project) => [project.id, project]));- return input.threads- .filter((thread) => {- const project = projectById.get(thread.projectId);- if (!project) {- return false;- }- return (- projectThreadAwareness({- environmentId: input.environmentId,- project,- thread,- }) !== null- );- })- .map((thread) => thread.id);-}--export const make = Effect.gen(function* () {- const secrets = yield* ServerSecretStore.ServerSecretStore;- const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;- const snapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;- const orchestrationEngine = yield* OrchestrationEngine.OrchestrationEngineService;- const crypto = yield* Crypto.Crypto;- const cloudLinkKeyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secrets);- const activeSnapshotPublishedRef = yield* Ref.make(false);- const publishedStateByThreadRef = yield* Ref.make(new Map<ThreadId, string>());-- const readSecretString = (name: string) =>- secrets- .get(name)- .pipe(- Effect.map((bytes) =>- Option.isSome(bytes) ? new TextDecoder().decode(bytes.value) : null,- ),- );-- const readRelayConfig = Effect.gen(function* () {- const [url, issuer, environmentCredential] = yield* Effect.all([- readSecretString(RELAY_URL_SECRET),- readSecretString(RELAY_ISSUER_SECRET),- readSecretString(RELAY_ENVIRONMENT_CREDENTIAL_SECRET),- ]);- return url && environmentCredential- ? { url, issuer: issuer ?? url, environmentCredential }- : null;- });-- const readPublishAgentActivityEnabled = readSecretString(PUBLISH_AGENT_ACTIVITY_SECRET).pipe(- Effect.map(isAgentActivityPublishingEnabled),- );-- const makeRelayClient = (relayConfig: {- readonly url: string;- readonly environmentCredential: string;- }) =>- HttpApiClient.make(RelayApi, {- baseUrl: relayConfig.url,- transformClient: relayEnvironmentClient(relayConfig.environmentCredential),- }).pipe(Effect.provide(FetchHttpClient.layer));-- // Deadlines for publishes that need confirmation (tombstones and- // first-state completions). The confirming publish is re-enqueued through- // the same drainable worker as every other publish, so a confirmed- // tombstone can never race an in-flight live update; a recovered state- // clears the deadline. Assigned after the worker exists.- const publishConfirmDeadlines = new Map<ThreadId, number>();- let schedulePublishConfirm: (threadId: ThreadId) => Effect.Effect<void> = () => Effect.void;-- const publishThreadUnsafe = Effect.fn("publishThreadUnsafe")(function* (threadId: ThreadId) {- const publishAgentActivity = yield* readPublishAgentActivityEnabled.pipe(- Effect.orElseSucceed(() => false),- );- if (!publishAgentActivity) {- yield* Effect.logDebug("agent activity publish skipped; publication disabled", {- threadId,- });- return;- }- const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));- if (!relayConfig) {- yield* Effect.logDebug("agent activity publish skipped; relay link credentials unavailable", {- threadId,- });- return;- }- const relayClient = yield* makeRelayClient(relayConfig);- const environmentId = yield* serverEnvironment.getEnvironmentId;-- const publishState = (input: {- readonly projectId: string | null;- readonly state: RelayAgentActivityState | null;- readonly reason: string;- }) =>- Effect.gen(function* () {- const proof = yield* makePublishProof({- privateKey: cloudLinkKeyPair.privateKey,- relayIssuer: relayConfig.issuer,- environmentId,- threadId,- state: input.state,- jti: yield* crypto.randomUUIDv4,- });-- yield* Effect.logInfo("publishing agent activity for thread", {- environmentId,- threadId,- projectId: input.projectId,- statePhase: input.state?.phase ?? null,- hasState: input.state !== null,- reason: input.reason,- });-- const response = yield* relayClient.server.publishAgentActivity({- params: {- environmentId,- threadId,- },- payload: {- state: input.state,- proof,- },- });-- yield* Effect.logInfo("agent activity publish completed", {- environmentId,- threadId,- ok: response.ok,- deliveries: deliveryStats(response.deliveries),- });- });-- const thread = yield* snapshotQuery.getThreadShellById(threadId);- const project = Option.isSome(thread)- ? yield* snapshotQuery.getProjectShellById(thread.value.projectId)- : Option.none<OrchestrationProjectShell>();- const snapshot = resolveAgentAwarenessRelayPublishSnapshot({- environmentId,- threadId,- thread,- project,- });- const publishIdentity = agentAwarenessPublishIdentity(snapshot.state);- const publishedStateByThread = yield* Ref.get(publishedStateByThreadRef);- if (publishedStateByThread.get(threadId) === publishIdentity) {- // The projection is back at (or never left) the last published state, so- // any pending deferred confirmation is moot. Leaving the deadline in- // place would let a much later transient null find it already expired- // and publish a tombstone immediately, skipping the deferral window.- publishConfirmDeadlines.delete(threadId);- yield* Effect.logDebug("agent activity publish skipped; projected state unchanged", {- environmentId,- threadId,- reason: snapshot.reason,- });- return;- }-- // Two projections need confirmation before publishing, because both can- // appear transiently while the projector is mid-write and publishing them- // immediately is destructive or noisy:- // - null (tombstone) while the previous published state was live: deletes- // the thread from every armed card mid-conversation.- // - completed as the thread's FIRST published state: sessions boot at- // "ready" before their first turn, which projects as completed for an- // instant and sends a spurious Done notification at thread birth.- // Defer, schedule a re-publish through the ordinary worker queue, and- // only publish if the projection still holds when it drains.- const requiresConfirmation =- (snapshot.state === null &&- publishedStateByThread.get(threadId) !== agentAwarenessPublishIdentity(null)) ||- (snapshot.state?.phase === "completed" && !publishedStateByThread.has(threadId));- if (requiresConfirmation) {- const nowMs = (yield* DateTime.now).epochMilliseconds;- const deadline = publishConfirmDeadlines.get(threadId);- if (deadline === undefined) {- publishConfirmDeadlines.set(threadId, nowMs + 5_000);- yield* Effect.logInfo("agent activity publish deferred pending confirmation", {- environmentId,- threadId,- reason: snapshot.reason,- statePhase: snapshot.state?.phase ?? null,- shell: describeThreadShellForAwareness(thread),- });- yield* schedulePublishConfirm(threadId);- return;- }- if (nowMs < deadline) {- return;- }- publishConfirmDeadlines.delete(threadId);- yield* Effect.logInfo("agent activity deferred publish confirmed", {- environmentId,- threadId,- reason: snapshot.reason,- statePhase: snapshot.state?.phase ?? null,- shell: describeThreadShellForAwareness(thread),- });- } else {- publishConfirmDeadlines.delete(threadId);- }-- if (snapshot.reason === "thread-not-found") {- yield* Effect.logDebug("publishing agent activity tombstone; thread not found", {- environmentId,- threadId,- });- } else if (snapshot.reason === "project-not-found") {- yield* Effect.logDebug("publishing agent activity tombstone; project not found", {- environmentId,- threadId,- projectId: snapshot.projectId,- });- }-- yield* publishState({- projectId: snapshot.projectId,- state: snapshot.state,- reason: snapshot.reason,- });- yield* Ref.update(publishedStateByThreadRef, (publishedStates) => {- const nextPublishedStates = new Map(publishedStates);- nextPublishedStates.set(threadId, publishIdentity);- return nextPublishedStates;- });- });-- const publishThread: AgentAwarenessRelay["Service"]["publishThread"] = (threadId) =>- publishThreadUnsafe(threadId).pipe(- Effect.catchCause((cause) => {- return Effect.logWarning("agent activity publish failed", {- threadId,- cause: Cause.pretty(cause),- });- }),- Effect.withSpan("AgentAwarenessRelay.publishThread"),- withRelayClientTracing,- );-- const publishActiveThreadsUnsafe = Effect.gen(function* () {- const publishAgentActivity = yield* readPublishAgentActivityEnabled.pipe(- Effect.orElseSucceed(() => false),- );- if (!publishAgentActivity) {- yield* Effect.logDebug("agent activity snapshot skipped; publication disabled");- return false;- }- const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));- if (!relayConfig) {- yield* Effect.logDebug("agent activity snapshot skipped; relay link credentials unavailable");- return false;- }- const environmentId = yield* serverEnvironment.getEnvironmentId;- const snapshot = yield* snapshotQuery.getShellSnapshot();- const activeThreadIds = resolveAgentAwarenessRelayActiveThreadIds({- environmentId,- projects: snapshot.projects,- threads: snapshot.threads,- });- if (activeThreadIds.length === 0) {- yield* Effect.logDebug("agent activity snapshot has no publishable threads");- return true;- }- yield* Effect.logInfo("publishing active agent activity snapshot", {- count: activeThreadIds.length,- });- yield* Effect.forEach(activeThreadIds, publishThread, { concurrency: 4, discard: true });- return true;- });-- const publishActiveThreadsOnceWhenConfigured = (logEnabledWhenReady: boolean) =>- Effect.gen(function* () {- while (!(yield* Ref.get(activeSnapshotPublishedRef))) {- const published = yield* publishActiveThreadsUnsafe.pipe(Effect.orElseSucceed(() => false));- if (published) {- yield* Ref.set(activeSnapshotPublishedRef, true);- if (logEnabledWhenReady) {- const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));- yield* Effect.logInfo("agent activity publishing enabled after link reconciliation", {- relayUrl: relayConfig?.url,- });- }- return;- }- yield* Effect.sleep("5 seconds");- }- });-- const worker = yield* makeDrainableWorker(publishThread);-- schedulePublishConfirm = (threadId) =>- Effect.forkDetach(- Effect.sleep("5 seconds").pipe(- Effect.andThen(worker.enqueue(threadId)),- Effect.catchCause((cause) =>- Effect.logWarning("deferred agent activity confirmation failed", {- threadId,- cause: Cause.pretty(cause),- }),- ),- ),- ).pipe(Effect.asVoid);-- const start: AgentAwarenessRelay["Service"]["start"] = Effect.fn("AgentAwarenessRelay.start")(- function* () {- const [relayConfig, publishEnabled] = yield* Effect.all([- readRelayConfig.pipe(Effect.orElseSucceed(() => null)),- readPublishAgentActivityEnabled.pipe(Effect.orElseSucceed(() => false)),- ]);- const startupState = resolveAgentActivityPublishingStartupState({- relayConfigured: relayConfig !== null,- publishEnabled,- });- switch (startupState) {- case "waiting-for-link":- yield* Effect.logInfo(- "agent activity publishing standby; waiting for T3 Connect link reconciliation",- );- break;- case "disabled":- yield* Effect.logInfo("agent activity publishing disabled by T3 Connect configuration");- break;- case "enabled":- yield* Effect.logInfo("agent activity publishing enabled", {- relayUrl: relayConfig?.url,- });- break;- }- yield* forkParked(- Effect.sleep("1 second").pipe(- Effect.andThen(publishActiveThreadsOnceWhenConfigured(startupState !== "enabled")),- ),- );- yield* forkParked(- Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {- const threadId = eventThreadId(event);- if (threadId === null) {- return Effect.logDebug("agent activity publishing ignored event without thread id", {- eventType: event.type,- });- }- if (!shouldPublishAgentAwarenessEvent(event)) {- return Effect.logDebug(- "agent activity publishing ignored event without activity changes",- {- eventType: event.type,- threadId,- },- );- }- return Effect.logDebug("agent activity publishing queued thread publish", {- eventType: event.type,- threadId,- }).pipe(Effect.andThen(worker.enqueue(threadId)));- }),- );- },- );-- return AgentAwarenessRelay.of({- publishThread,- start,- });-});--export const layer = Layer.effect(AgentAwarenessRelay, make);diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.tsindex 2fec245a2..70e2b5904 100644--- a/apps/server/src/server.test.ts+++ b/apps/server/src/server.test.ts@@ -1,7 +1,6 @@import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";import * as NodeSocket from "@effect/platform-node/NodeSocket";import * as NodeServices from "@effect/platform-node/NodeServices";-import * as NodeCrypto from "node:crypto";import { HostProcessEnvironment, HostProcessPlatform } from "@t3tools/shared/hostProcess";import {@@ -37,13 +36,6 @@ import {WsRpcGroup,EditorId,} from "@t3tools/contracts";-import {- computeDpopAccessTokenHash,- computeDpopJwkThumbprint,- type DpopPublicJwk,-} from "@t3tools/shared/dpop";-import { RELAY_HEALTH_REQUEST_TYP, RELAY_MINT_REQUEST_TYP } from "@t3tools/shared/relayJwt";-import * as RelayClient from "@t3tools/shared/relayClient";import { assert, it } from "@effect/vitest";import { assertFailure, assertInclude, assertTrue } from "@effect/vitest/utils";import * as Clock from "effect/Clock";@@ -153,8 +145,6 @@ import * as ReviewService from "./review/ReviewService.ts";import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts";import * as ServerSecretStore from "./auth/ServerSecretStore.ts";import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";-import * as CloudManagedEndpointRuntime from "./cloud/ManagedEndpointRuntime.ts";-import * as CloudCliTokenManager from "./cloud/CliTokenManager.ts";import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts";import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts";@@ -431,11 +421,6 @@ const buildAppUnderTest = (options?: {repositoryIdentityResolver?: Partial<RepositoryIdentityResolver.RepositoryIdentityResolver["Service"]>;- cloudManagedEndpointRuntime?: Partial<- CloudManagedEndpointRuntime.CloudManagedEndpointRuntime["Service"]- >;- relayClient?: Partial<RelayClient.RelayClient["Service"]>;- cloudCliTokenManager?: Partial<CloudCliTokenManager.CloudCliTokenManager["Service"]>;nativeTelemetryClient?: Partial<NativeTelemetryClient.NativeTelemetryClient["Service"]>;desktopTelemetryReceiver?: Partial<DesktopTelemetryReceiver.DesktopTelemetryReceiver["Service"]@@ -988,38 +973,6 @@ const buildAppUnderTest = (options?: {...options?.layers?.repositoryIdentityResolver,}),),- Layer.provide(- Layer.succeed(- CloudManagedEndpointRuntime.CloudManagedEndpointRuntime,- CloudManagedEndpointRuntime.CloudManagedEndpointRuntime.of({- applyConfig: () => Effect.succeed({ status: "disabled" }),- ...options?.layers?.cloudManagedEndpointRuntime,- }),- ),- ),- Layer.provide(- Layer.succeed(- RelayClient.RelayClient,- RelayClient.RelayClient.of({- resolve: Effect.succeed({- status: "missing",- version: RelayClient.CLOUDFLARED_VERSION,- }),- install: Effect.die("unused relay-client install"),- installWithProgress: () => Effect.die("unused relay-client install"),- ...options?.layers?.relayClient,- }),- ),- ),- Layer.provide(- Layer.mock(CloudCliTokenManager.CloudCliTokenManager)({- get: Effect.die(new Error("Unexpected T3 Connect CLI authorization request.")),- getExisting: Effect.succeed(Option.none()),- hasCredential: Effect.succeed(false),- clear: Effect.void,- ...options?.layers?.cloudCliTokenManager,- }),- ),Layer.provideMerge(makeAuthTestLayer()),Layer.provideMerge(ServerSecretStore.layer),Layer.provide(workspaceAndProjectServicesLayer),@@ -1143,7 +1096,7 @@ const exchangeAccessToken = (requested_token_type: AuthAccessTokenType,scope:options?.scope ??- "orchestration:read orchestration:operate terminal:operate review:write relay:read access:read access:write relay:write",+ "orchestration:read orchestration:operate terminal:operate review:write access:read access:write",...(options?.clientMetadata?.label ? { client_label: options.clientMetadata.label } : {}),...(options?.clientMetadata?.deviceType? { client_device_type: options.clientMetadata.deviceType }@@ -1168,131 +1121,6 @@ const exchangeAccessToken = (};});-const makeDpopProof = (input: {- readonly method: string;- readonly url: string;- readonly iat: number;- readonly accessToken?: string;- readonly jti?: string;- readonly privateKey?: NodeCrypto.KeyObject;- readonly publicJwk?: DpopPublicJwk;-}) => {- const keyPair =- input.privateKey && input.publicJwk- ? { privateKey: input.privateKey, publicJwk: input.publicJwk }- : (() => {- const { privateKey, publicKey } = NodeCrypto.generateKeyPairSync("ec", {- namedCurve: "P-256",- });- return { privateKey, publicJwk: publicKey.export({ format: "jwk" }) as DpopPublicJwk };- })();- const header = Buffer.from(- JSON.stringify({- typ: "dpop+jwt",- alg: "ES256",- jwk: keyPair.publicJwk,- }),- ).toString("base64url");- const payload = Buffer.from(- JSON.stringify({- htm: input.method,- htu: input.url,- jti: input.jti ?? "proof-1",- iat: input.iat,- ...(input.accessToken ? { ath: computeDpopAccessTokenHash(input.accessToken) } : {}),- }),- ).toString("base64url");- const signature = NodeCrypto.sign("sha256", Buffer.from(`${header}.${payload}`), {- key: keyPair.privateKey,- dsaEncoding: "ieee-p1363",- }).toString("base64url");- return {- proof: `${header}.${payload}.${signature}`,- thumbprint: computeDpopJwkThumbprint(keyPair.publicJwk),- privateKey: keyPair.privateKey,- publicJwk: keyPair.publicJwk,- };-};--const makeCloudMintCredentialRequest = (input: {- readonly privateKey: string;- readonly environmentId: EnvironmentId;- readonly clientProofKeyThumbprint: string;- readonly issuer?: string;- readonly audience?: string;- readonly subject?: string;- readonly jti?: string;- readonly nonce: string;- readonly issuedAt: string;- readonly expiresAt: string;- readonly scope?: ReadonlyArray<"environment:connect">;-}) => {- const payload = {- iss: input.issuer ?? "https://relay.example.test",- aud: input.audience ?? `t3-env:${input.environmentId}`,- sub: input.subject ?? "user_123",- jti: input.jti ?? "cloud-mint-jti-1",- environmentId: input.environmentId,- clientProofKeyThumbprint: input.clientProofKeyThumbprint,- cnf: {- jkt: input.clientProofKeyThumbprint,- },- nonce: input.nonce,- iat: Math.floor(DateTime.makeUnsafe(input.issuedAt).epochMilliseconds / 1_000),- exp: Math.floor(DateTime.makeUnsafe(input.expiresAt).epochMilliseconds / 1_000),- scope: input.scope ?? ["environment:connect"],- } as const;- const header = Buffer.from(- JSON.stringify({ alg: "EdDSA", typ: RELAY_MINT_REQUEST_TYP }),- ).toString("base64url");- const encodedPayload = Buffer.from(JSON.stringify(payload)).toString("base64url");- const signingInput = `${header}.${encodedPayload}`;- return {- proof: `${signingInput}.${NodeCrypto.sign(null, Buffer.from(signingInput), input.privateKey).toString("base64url")}`,- };-};--const makeCloudEnvironmentHealthRequest = (input: {- readonly privateKey: string;- readonly environmentId: EnvironmentId;- readonly issuer?: string;- readonly audience?: string;- readonly subject?: string;- readonly jti?: string;- readonly nonce: string;- readonly issuedAt: string;- readonly expiresAt: string;- readonly scope?: ReadonlyArray<"environment:status">;-}) => {- const payload = {- iss: input.issuer ?? "https://relay.example.test",- aud: input.audience ?? `t3-env:${input.environmentId}`,- sub: input.subject ?? "user_123",- jti: input.jti ?? "cloud-health-jti-1",- environmentId: input.environmentId,- nonce: input.nonce,- iat: Math.floor(DateTime.makeUnsafe(input.issuedAt).epochMilliseconds / 1_000),- exp: Math.floor(DateTime.makeUnsafe(input.expiresAt).epochMilliseconds / 1_000),- scope: input.scope ?? ["environment:status"],- } as const;- const header = Buffer.from(- JSON.stringify({ alg: "EdDSA", typ: RELAY_HEALTH_REQUEST_TYP }),- ).toString("base64url");- const encodedPayload = Buffer.from(JSON.stringify(payload)).toString("base64url");- const signingInput = `${header}.${encodedPayload}`;- return {- proof: `${signingInput}.${NodeCrypto.sign(null, Buffer.from(signingInput), input.privateKey).toString("base64url")}`,- };-};--const decodeCompactJwtPayload = <A>(token: string): A => {- const encodedPayload = token.split(".")[1];- if (!encodedPayload) {- throw new Error("JWT does not contain a payload.");- }- return JSON.parse(Buffer.from(encodedPayload, "base64url").toString("utf8")) as A;-};-class AuthenticationGetterError extends Data.TaggedError("AuthenticationGetterError")<{readonly message: string;}> {}@@ -1429,7 +1257,6 @@ const assertBrowserApiCorsPreflightHeaders = ("authorization","b3","content-type",- "dpop","traceparent",]);};@@ -1618,11 +1445,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {assert.equal(body.authenticated, false);assert.equal(body.auth.policy, "desktop-managed-local");assert.deepEqual(body.auth.bootstrapMethods, ["desktop-bootstrap"]);- assert.deepEqual(body.auth.sessionMethods, [- "browser-session-cookie",- "bearer-access-token",- "dpop-access-token",- ]);+ assert.deepEqual(body.auth.sessionMethods, ["browser-session-cookie", "bearer-access-token"]);// Desktop, so port-scoped: instances scan for a free port and share// 127.0.0.1, and cookies are not scoped by port.assert.isTrue(body.auth.sessionCookieName.startsWith("t3_session_"));@@ -1673,7 +1496,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {assert.equal(tokenBody.token_type, "Bearer");assert.equal(tokenBody.scope,- "orchestration:read orchestration:operate terminal:operate review:write relay:read access:read access:write relay:write",+ "orchestration:read orchestration:operate terminal:operate review:write access:read access:write",);assert.equal(typeof tokenBody.access_token, "string");@@ -1697,10 +1520,8 @@ it.layer(NodeServices.layer)("server router seam", (it) => {"orchestration:operate","terminal:operate","review:write",- "relay:read","access:read","access:write",- "relay:write",]);}).pipe(Effect.provide(NodeHttpServer.layerTest)),);@@ -1766,1614 +1587,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {}).pipe(Effect.provide(NodeHttpServer.layerTest)),);- it.effect(- "exchanges a bootstrap credential for a DPoP-bound access token without bearer downgrade",- () =>- Effect.gen(function* () {- yield* buildAppUnderTest();-- const ownerCookie = yield* getAuthenticatedSessionCookieHeader();- const credentialResponse = yield* HttpClient.post("/api/auth/pairing-token", {- headers: { cookie: ownerCookie },- body: yield* HttpBody.json({}),- });- const credential = (yield* credentialResponse.json) as { readonly credential: string };- const tokenUrl = yield* getHttpServerUrl("/oauth/token");- const now = yield* DateTime.now;- const tokenProof = makeDpopProof({- method: "POST",- url: tokenUrl,- iat: Math.floor(now.epochMilliseconds / 1_000),- jti: "token-exchange-proof",- });- const tokenResponse = yield* fetchEffect(tokenUrl, {- method: "POST",- headers: {- "content-type": "application/x-www-form-urlencoded",- dpop: tokenProof.proof,- },- body: new URLSearchParams({- grant_type: "urn:ietf:params:oauth:grant-type:token-exchange",- subject_token: credential.credential,- subject_token_type: "urn:t3:params:oauth:token-type:environment-bootstrap",- requested_token_type: "urn:ietf:params:oauth:token-type:access_token",- scope: "orchestration:read orchestration:operate terminal:operate review:write",- }).toString(),- });- const token = yield* responseJsonEffect<{- readonly access_token: string;- readonly token_type: string;- }>(tokenResponse);-- assert.equal(tokenResponse.status, 200);- assert.equal(tokenResponse.headers["cache-control"], "no-store");- assert.equal(token.token_type, "DPoP");-- const sessionUrl = yield* getHttpServerUrl("/api/auth/session");- const bearerResponse = yield* fetchEffect(sessionUrl, {- headers: { authorization: `Bearer ${token.access_token}` },- });- const bearerState = yield* responseJsonEffect<{ readonly authenticated: boolean }>(- bearerResponse,- );- assert.equal(bearerState.authenticated, false);-- const sessionProof = makeDpopProof({- method: "GET",- url: sessionUrl,- iat: Math.floor(now.epochMilliseconds / 1_000),- jti: "session-proof",- accessToken: token.access_token,- privateKey: tokenProof.privateKey,- publicJwk: tokenProof.publicJwk,- });- const dpopResponse = yield* fetchEffect(sessionUrl, {- headers: {- authorization: `DPoP ${token.access_token}`,- dpop: sessionProof.proof,- },- });- const dpopState = yield* responseJsonEffect<{- readonly authenticated: boolean;- readonly sessionMethod?: string;- }>(dpopResponse);- assert.equal(dpopState.authenticated, true);- assert.equal(dpopState.sessionMethod, "dpop-access-token");- }).pipe(Effect.provide(NodeHttpServer.layerTest)),- );-- it.effect("rejects replayed DPoP proofs across token exchanges", () =>- Effect.gen(function* () {- yield* buildAppUnderTest();-- const ownerCookie = yield* getAuthenticatedSessionCookieHeader();- const firstCredentialResponse = yield* HttpClient.post("/api/auth/pairing-token", {- headers: {- cookie: ownerCookie,- },- body: yield* HttpBody.json({}),- });- const firstCredential = (yield* firstCredentialResponse.json) as {- readonly credential: string;- };- const secondCredentialResponse = yield* HttpClient.post("/api/auth/pairing-token", {- headers: {- cookie: ownerCookie,- },- body: yield* HttpBody.json({}),- });- const secondCredential = (yield* secondCredentialResponse.json) as {- readonly credential: string;- };- const tokenUrl = yield* getHttpServerUrl("/oauth/token");- const now = yield* DateTime.now;- const dpop = makeDpopProof({- method: "POST",- url: tokenUrl,- iat: Math.floor(now.epochMilliseconds / 1_000),- });-- const firstBootstrap = yield* exchangeAccessToken(firstCredential.credential, {- headers: {- dpop: dpop.proof,- },- scope: "orchestration:read orchestration:operate terminal:operate review:write",- });- const replayBootstrap = yield* exchangeAccessToken(secondCredential.credential, {- headers: {- dpop: dpop.proof,- },- scope: "orchestration:read orchestration:operate terminal:operate review:write",- });-- assert.equal(firstBootstrap.response.status, 200);- assert.equal(replayBootstrap.response.status, 401);- assert.equal(replayBootstrap.body._tag, "EnvironmentAuthInvalidError");- assert.equal(replayBootstrap.body.code, "auth_invalid");- assert.equal(replayBootstrap.body.reason, "invalid_credential");- assert.equal(typeof replayBootstrap.body.traceId, "string");- }).pipe(Effect.provide(NodeHttpServer.layerTest)),- );-- it.effect("ignores forwarded host headers when validating token exchange DPoP URLs", () =>- Effect.gen(function* () {- yield* buildAppUnderTest();-- const ownerCookie = yield* getAuthenticatedSessionCookieHeader();- const credentialResponse = yield* HttpClient.post("/api/auth/pairing-token", {- headers: {- cookie: ownerCookie,- },- body: yield* HttpBody.json({}),- });- const credential = (yield* credentialResponse.json) as {- readonly credential: string;- };- const tokenUrl = yield* getHttpServerUrl("/oauth/token");- const now = yield* DateTime.now;- const dpop = makeDpopProof({- method: "POST",- url: tokenUrl,- iat: Math.floor(now.epochMilliseconds / 1_000),- });-- const bootstrap = yield* exchangeAccessToken(credential.credential, {- headers: {- dpop: dpop.proof,- "x-forwarded-host": "environment.example.test",- },- scope: "orchestration:read orchestration:operate terminal:operate review:write",- });-- assert.equal(bootstrap.response.status, 200);- assert.equal(bootstrap.body.token_type, "DPoP");- }).pipe(Effect.provide(NodeHttpServer.layerTest)),- );-- it.effect("rejects token exchange DPoP proofs bound to spoofed forwarded hosts", () =>- Effect.gen(function* () {- yield* buildAppUnderTest();-- const ownerCookie = yield* getAuthenticatedSessionCookieHeader();- const credentialResponse = yield* HttpClient.post("/api/auth/pairing-token", {- headers: {- cookie: ownerCookie,- },- body: yield* HttpBody.json({}),- });- const credential = (yield* credentialResponse.json) as {- readonly credential: string;- };- const tokenUrl = yield* getHttpServerUrl("/oauth/token");- const spoofedUrl = new URL(tokenUrl);- spoofedUrl.hostname = "environment.example.test";- const now = yield* DateTime.now;- const dpop = makeDpopProof({- method: "POST",- url: spoofedUrl.href,- iat: Math.floor(now.epochMilliseconds / 1_000),- });-- const bootstrap = yield* exchangeAccessToken(credential.credential, {- headers: {- dpop: dpop.proof,- "x-forwarded-host": spoofedUrl.host,- },- scope: "orchestration:read orchestration:operate terminal:operate review:write",- });-- assert.equal(bootstrap.response.status, 401);- assert.equal(bootstrap.body._tag, "EnvironmentAuthInvalidError");- assert.equal(bootstrap.body.code, "auth_invalid");- assert.equal(bootstrap.body.reason, "invalid_credential");- assert.equal(typeof bootstrap.body.traceId, "string");- }).pipe(Effect.provide(NodeHttpServer.layerTest)),- );-- it.effect("rejects cloud link proofs for non-loopback managed endpoint origins", () =>- Effect.gen(function* () {- yield* buildAppUnderTest();-- const ownerCookie = yield* getAuthenticatedSessionCookieHeader();- const linkProofUrl = yield* getHttpServerUrl("/api/connect/link-proof");- const linkProofResponse = yield* fetchEffect(linkProofUrl, {- method: "POST",- headers: {- cookie: ownerCookie,- "content-type": "application/json",- },- body: jsonRequestBody({- challenge: "relay-link-challenge",- relayIssuer: "https://relay.example.test",- endpoint: {- httpBaseUrl: "https://environment.example.test/",- wsBaseUrl: "wss://environment.example.test/ws",- providerKind: "manual",- },- origin: {- localHttpHost: "192.168.1.42",- localHttpPort: 3773,- },- }),- });- const body = yield* responseJsonEffect<{- readonly _tag?: string;- readonly message?: string;- }>(linkProofResponse);-- assert.equal(linkProofResponse.status, 400);- assert.equal(body._tag, "EnvironmentHttpBadRequestError");- assert.equal(body.message, "Invalid managed endpoint origin.");- }).pipe(Effect.provide(NodeHttpServer.layerTest)),- );-- it.effect("rejects cloud link proofs for unsupported endpoint providers", () =>- Effect.gen(function* () {- yield* buildAppUnderTest();-- const ownerCookie = yield* getAuthenticatedSessionCookieHeader();- const linkProofUrl = yield* getHttpServerUrl("/api/connect/link-proof");- const serverPort = Number(new URL(linkProofUrl).port);- const linkProofResponse = yield* fetchEffect(linkProofUrl, {- method: "POST",- headers: {- cookie: ownerCookie,- "content-type": "application/json",- },- body: jsonRequestBody({- challenge: "relay-link-challenge",- relayIssuer: "https://relay.example.test",- endpoint: {- httpBaseUrl: linkProofUrl.replace("/api/connect/link-proof", ""),- wsBaseUrl: linkProofUrl- .replace("http://", "ws://")- .replace("/api/connect/link-proof", "/ws"),- // "manual" and "cloudflare_tunnel" are supported; "t3_relay" is not.- providerKind: "t3_relay",- },- origin: {- localHttpHost: "127.0.0.1",- localHttpPort: serverPort,- },- }),- });- const body = yield* responseJsonEffect<{- readonly _tag?: string;- readonly message?: string;- }>(linkProofResponse);-- assert.equal(linkProofResponse.status, 400);- assert.equal(body._tag, "EnvironmentHttpBadRequestError");- assert.equal(body.message, "Invalid managed endpoint origin.");- }).pipe(Effect.provide(NodeHttpServer.layerTest)),- );-- it.effect("rejects cloud link proofs requested through a public managed endpoint", () =>- Effect.gen(function* () {- yield* buildAppUnderTest();-- const linkProofUrl = yield* getHttpServerUrl("/api/connect/link-proof");- const serverPort = Number(new URL(linkProofUrl).port);- const linkProofResponse = yield* HttpClient.post("/api/connect/link-proof", {- headers: {- cookie: yield* getAuthenticatedSessionCookieHeader(),- "content-type": "application/json",- host: "environment.example.test",- "x-forwarded-host": "environment.example.test",- "x-forwarded-proto": "https",- },- body: HttpBody.text(- jsonRequestBody({- challenge: "relay-link-challenge",- relayIssuer: "https://relay.example.test",- endpoint: {- httpBaseUrl: "https://environment.example.test/",- wsBaseUrl: "wss://environment.example.test/ws",- providerKind: "manual",- },- origin: {- localHttpHost: "127.0.0.1",- localHttpPort: serverPort,- },- }),- "application/json",- ),- });- const body = (yield* linkProofResponse.json) as {- readonly _tag?: string;- readonly message?: string;- };-- assert.equal(linkProofResponse.status, 400);- assert.equal(body._tag, "EnvironmentHttpBadRequestError");- assert.equal(body.message, "Invalid managed endpoint origin.");- }).pipe(Effect.provide(NodeHttpServer.layerTest)),- );-- it.effect(- "rejects cloud link proofs when a public request spoofs loopback forwarded headers",- () =>- Effect.gen(function* () {- yield* buildAppUnderTest();-- const linkProofUrl = yield* getHttpServerUrl("/api/connect/link-proof");- const serverPort = Number(new URL(linkProofUrl).port);- const linkProofResponse = yield* HttpClient.post("/api/connect/link-proof", {- headers: {- cookie: yield* getAuthenticatedSessionCookieHeader(),- "content-type": "application/json",- host: "environment.example.test",- "x-forwarded-host": `127.0.0.1:${serverPort}`,- "x-forwarded-proto": "http",- },- body: HttpBody.text(- jsonRequestBody({- challenge: "relay-link-challenge",- relayIssuer: "https://relay.example.test",- endpoint: {- httpBaseUrl: "https://environment.example.test/",- wsBaseUrl: "wss://environment.example.test/ws",- providerKind: "manual",- },- origin: {- localHttpHost: "127.0.0.1",- localHttpPort: serverPort,- },- }),- "application/json",- ),- });- const body = (yield* linkProofResponse.json) as {- readonly _tag?: string;- readonly message?: string;- };-- assert.equal(linkProofResponse.status, 400);- assert.equal(body._tag, "EnvironmentHttpBadRequestError");- assert.equal(body.message, "Invalid managed endpoint origin.");- }).pipe(Effect.provide(NodeHttpServer.layerTest)),- );-- it.effect("rejects cloud link proofs with malformed forwarded request hosts", () =>- Effect.gen(function* () {- yield* buildAppUnderTest();-- const linkProofUrl = yield* getHttpServerUrl("/api/connect/link-proof");- const serverPort = Number(new URL(linkProofUrl).port);- const linkProofResponse = yield* HttpClient.post("/api/connect/link-proof", {- headers: {- cookie: yield* getAuthenticatedSessionCookieHeader(),- "content-type": "application/json",- host: "bad host",- "x-forwarded-host": "bad host",- "x-forwarded-proto": "https",- },- body: HttpBody.text(- jsonRequestBody({- challenge: "relay-link-challenge",- relayIssuer: "https://relay.example.test",- endpoint: {- httpBaseUrl: "https://environment.example.test/",- wsBaseUrl: "wss://environment.example.test/ws",- providerKind: "manual",- },- origin: {- localHttpHost: "127.0.0.1",- localHttpPort: serverPort,- },- }),- "application/json",- ),- });- const body = (yield* linkProofResponse.json) as {- readonly _tag?: string;- readonly message?: string;- };-- assert.equal(linkProofResponse.status, 400);- assert.equal(body._tag, "EnvironmentHttpBadRequestError");- assert.equal(body.message, "Invalid managed endpoint origin.");- }).pipe(Effect.provide(NodeHttpServer.layerTest)),- );-- it.effect("rejects local cloud link proofs for a different loopback port", () =>- Effect.gen(function* () {- yield* buildAppUnderTest();-- const ownerCookie = yield* getAuthenticatedSessionCookieHeader();- const linkProofUrl = yield* getHttpServerUrl("/api/connect/link-proof");- const serverPort = Number(new URL(linkProofUrl).port);- const linkProofResponse = yield* fetchEffect(linkProofUrl, {- method: "POST",- headers: {- cookie: ownerCookie,- "content-type": "application/json",- },- body: jsonRequestBody({- challenge: "relay-link-challenge",- relayIssuer: "https://relay.example.test",- endpoint: {- httpBaseUrl: "https://environment.example.test/",- wsBaseUrl: "wss://environment.example.test/ws",- providerKind: "manual",- },- origin: {- localHttpHost: "127.0.0.1",- localHttpPort: serverPort === 65_535 ? serverPort - 1 : serverPort + 1,- },- }),- });- const body = yield* responseJsonEffect<{- readonly _tag?: string;- readonly message?: string;- }>(linkProofResponse);-- assert.equal(linkProofResponse.status, 400);- assert.equal(body._tag, "EnvironmentHttpBadRequestError");- assert.equal(body.message, "Invalid managed endpoint origin.");- }).pipe(Effect.provide(NodeHttpServer.layerTest)),- );-- it.effect("allows standard clients to read managed relay configuration state", () =>- Effect.gen(function* () {- yield* buildAppUnderTest();-- const ownerCookie = yield* getAuthenticatedSessionCookieHeader();- const credentialResponse = yield* HttpClient.post("/api/auth/pairing-token", {- headers: { cookie: ownerCookie },- body: yield* HttpBody.json({}),- });- const credential = (yield* credentialResponse.json) as { readonly credential: string };- const pairedCookie = yield* getAuthenticatedSessionCookieHeader(credential.credential);- const linkStateUrl = yield* getHttpServerUrl("/api/connect/link-state");- const response = yield* fetchEffect(linkStateUrl, {- headers: { cookie: pairedCookie },- });- const body = yield* responseJsonEffect<{- readonly linked?: boolean;- readonly publishAgentActivity?: boolean;- }>(response);-- assert.equal(response.status, 200);- assert.equal(body.linked, false);- assert.equal(body.publishAgentActivity, false);- }).pipe(Effect.provide(NodeHttpServer.layerTest)),- );-- it.effect(- "reports relay client status and streams installation progress over environment RPC",- () =>- Effect.gen(function* () {- const installedRelayClient = {- status: "available" as const,- executablePath: "/tmp/t3/tools/cloudflared",- source: "managed" as const,- version: RelayClient.CLOUDFLARED_VERSION,- };- yield* buildAppUnderTest({- layers: {- relayClient: {- resolve: Effect.succeed({- status: "missing",- version: RelayClient.CLOUDFLARED_VERSION,- }),- install: Effect.succeed(installedRelayClient),- installWithProgress: (report) =>- report({ type: "progress", stage: "checking" }).pipe(- Effect.andThen(report({ type: "progress", stage: "downloading" })),- Effect.as(installedRelayClient),- ),- },- },- });-- const wsUrl = yield* getWsServerUrl("/ws");- const status = yield* Effect.scoped(- withWsRpcClient(wsUrl, (client) => client[WS_METHODS.cloudGetRelayClientStatus]({})),- );- const installEvents = yield* Effect.scoped(- withWsRpcClient(wsUrl, (client) =>- client[WS_METHODS.cloudInstallRelayClient]({}).pipe(Stream.runCollect),- ),- );-- assert.equal(status.status, "missing");- assert.deepEqual(Array.from(installEvents), [- { type: "progress", stage: "checking" },- { type: "progress", stage: "downloading" },- { type: "complete", status: installedRelayClient },- ]);- }).pipe(Effect.provide(NodeHttpServer.layerTest)),- );-- it.effect("requires relay write scope to update agent activity publication", () =>- Effect.gen(function* () {- yield* buildAppUnderTest();-- const ownerCookie = yield* getAuthenticatedSessionCookieHeader();- const preferencesUrl = yield* getHttpServerUrl("/api/connect/preferences");- const ownerResponse = yield* fetchEffect(preferencesUrl, {- method: "POST",- headers: {- cookie: ownerCookie,- "content-type": "application/json",- },- body: jsonRequestBody({ publishAgentActivity: true }),- });- const ownerBody = yield* responseJsonEffect<{- readonly publishAgentActivity?: boolean;- }>(ownerResponse);- assert.equal(ownerResponse.status, 200);- assert.equal(ownerBody.publishAgentActivity, true);-- const credentialResponse = yield* HttpClient.post("/api/auth/pairing-token", {- headers: { cookie: ownerCookie },- body: yield* HttpBody.json({}),- });- const credential = (yield* credentialResponse.json) as { readonly credential: string };- const pairedCookie = yield* getAuthenticatedSessionCookieHeader(credential.credential);- const pairedResponse = yield* fetchEffect(preferencesUrl, {- method: "POST",- headers: {- cookie: pairedCookie,- "content-type": "application/json",- },- body: jsonRequestBody({ publishAgentActivity: false }),- });- const pairedBody = yield* responseJsonEffect<{- readonly _tag?: string;- readonly requiredScope?: string;- }>(pairedResponse);- assert.equal(pairedResponse.status, 403);- assert.equal(pairedBody._tag, "EnvironmentScopeRequiredError");- assert.equal(pairedBody.requiredScope, "relay:write");- }).pipe(Effect.provide(NodeHttpServer.layerTest)),- );-- it.effect("rejects relay config with an invalid cloud mint public key", () =>- Effect.gen(function* () {- yield* buildAppUnderTest();-- const ownerCookie = yield* getAuthenticatedSessionCookieHeader();- const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config");- const relayConfigResponse = yield* fetchEffect(relayConfigUrl, {- method: "POST",- headers: {- cookie: ownerCookie,- "content-type": "application/json",- },- body: jsonRequestBody({- relayUrl: "https://relay.example.test",- cloudUserId: "user_123",- environmentCredential: "t3env_test_credential",- cloudMintPublicKey: "not-a-public-key",- endpointRuntime: null,- }),- });- const body = yield* responseJsonEffect<{- readonly _tag?: string;- readonly message?: string;- }>(relayConfigResponse);-- assert.equal(relayConfigResponse.status, 400);- assert.equal(body._tag, "EnvironmentHttpBadRequestError");- assert.equal(body.message, "Cloud mint public key must be a valid Ed25519 public key.");- }).pipe(Effect.provide(NodeHttpServer.layerTest)),- );-- it.effect("rejects relay config with insecure relay metadata or empty credentials", () =>- Effect.gen(function* () {- yield* buildAppUnderTest();-- const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", {- privateKeyEncoding: { format: "pem", type: "pkcs8" },- publicKeyEncoding: { format: "pem", type: "spki" },- });- const ownerCookie = yield* getAuthenticatedSessionCookieHeader();- const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config");- const postRelayConfig = (body: {- readonly relayUrl: string;- readonly relayIssuer?: string;- readonly cloudUserId: string;- readonly environmentCredential: string;- }) =>- fetchEffect(relayConfigUrl, {- method: "POST",- headers: {- cookie: ownerCookie,- "content-type": "application/json",- },- body: jsonRequestBody({- ...body,- cloudMintPublicKey: cloudKeyPair.publicKey,- endpointRuntime: null,- }),- });-- const insecureRelayUrl = yield* postRelayConfig({- relayUrl: "http://relay.example.test",- cloudUserId: "user_123",- environmentCredential: "t3env_test_credential",- });- const insecureRelayIssuer = yield* postRelayConfig({- relayUrl: "https://relay.example.test",- cloudUserId: "user_123",- relayIssuer: "http://relay.example.test",- environmentCredential: "t3env_test_credential",- });- const nonOriginRelayUrl = yield* postRelayConfig({- relayUrl: "https://relay.example.test/path",- cloudUserId: "user_123",- environmentCredential: "t3env_test_credential",- });- const emptyCredential = yield* postRelayConfig({- relayUrl: "https://relay.example.test",- cloudUserId: "user_123",- environmentCredential: " ",- });- const insecureRelayUrlBody = yield* responseJsonEffect<{ readonly message?: string }>(- insecureRelayUrl,- );- const insecureRelayIssuerBody = yield* responseJsonEffect<{ readonly message?: string }>(- insecureRelayIssuer,- );- const nonOriginRelayUrlBody = yield* responseJsonEffect<{ readonly message?: string }>(- nonOriginRelayUrl,- );- const emptyCredentialBody = yield* responseJsonEffect<{ readonly message?: string }>(- emptyCredential,- );-- assert.equal(insecureRelayUrl.status, 400);- assert.equal(insecureRelayUrlBody.message, "Relay URL must be a secure absolute HTTPS URL.");- assert.equal(insecureRelayIssuer.status, 400);- assert.equal(- insecureRelayIssuerBody.message,- "Relay issuer must be a secure absolute HTTPS URL.",- );- assert.equal(nonOriginRelayUrl.status, 400);- assert.equal(nonOriginRelayUrlBody.message, "Relay URL must be a secure absolute HTTPS URL.");- assert.equal(emptyCredential.status, 400);- assert.equal(emptyCredentialBody.message, "Relay environment credential is required.");- }).pipe(Effect.provide(NodeHttpServer.layerTest)),- );-- it.effect("rejects relay config replacement from a different cloud account", () =>- Effect.gen(function* () {- yield* buildAppUnderTest();-- const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", {- privateKeyEncoding: { format: "pem", type: "pkcs8" },- publicKeyEncoding: { format: "pem", type: "spki" },- });- const ownerCookie = yield* getAuthenticatedSessionCookieHeader();- const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config");- const postRelayConfig = (cloudUserId: string, environmentCredential: string) =>- fetchEffect(relayConfigUrl, {- method: "POST",- headers: {- cookie: ownerCookie,- "content-type": "application/json",- },- body: jsonRequestBody({- relayUrl: "https://relay.example.test",- cloudUserId,- environmentCredential,- cloudMintPublicKey: cloudKeyPair.publicKey,- endpointRuntime: null,- }),- });-- const firstResponse = yield* postRelayConfig("user_123", "t3env_first_credential");- const replacementResponse = yield* postRelayConfig("user_456", "t3env_second_credential");- const replacementBody = yield* responseJsonEffect<{- readonly _tag?: string;- readonly message?: string;- }>(replacementResponse);-- assert.equal(firstResponse.status, 200);- assert.equal(replacementResponse.status, 409);- assert.equal(replacementBody._tag, "EnvironmentHttpConflictError");- assert.equal(- replacementBody.message,- "This environment is already linked to a different cloud account. Unlink it before switching accounts.",- );- }).pipe(Effect.provide(NodeHttpServer.layerTest)),- );-- it.effect("reports local cloud link state from persisted relay config", () =>- Effect.gen(function* () {- yield* buildAppUnderTest();-- const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", {- privateKeyEncoding: { format: "pem", type: "pkcs8" },- publicKeyEncoding: { format: "pem", type: "spki" },- });- const ownerCookie = yield* getAuthenticatedSessionCookieHeader();- const linkStateUrl = yield* getHttpServerUrl("/api/connect/link-state");- const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config");-- const initialResponse = yield* fetchEffect(linkStateUrl, {- headers: {- cookie: ownerCookie,- },- });- const initialBody = yield* responseJsonEffect<{- readonly linked?: boolean;- readonly cloudUserId?: string | null;- }>(initialResponse);- assert.equal(initialResponse.status, 200);- assert.equal(initialBody.linked, false);- assert.equal(initialBody.cloudUserId, null);-- const relayConfigResponse = yield* fetchEffect(relayConfigUrl, {- method: "POST",- headers: {- cookie: ownerCookie,- "content-type": "application/json",- },- body: jsonRequestBody({- relayUrl: "https://transport.example.test",- relayIssuer: "https://relay.example.test",- cloudUserId: "user_123",- environmentCredential: "t3env_test_credential",- cloudMintPublicKey: cloudKeyPair.publicKey,- endpointRuntime: null,- }),- });- assert.equal(relayConfigResponse.status, 200);-- const linkedResponse = yield* fetchEffect(linkStateUrl, {- headers: {- cookie: ownerCookie,- },- });- const linkedBody = yield* responseJsonEffect<{- readonly linked?: boolean;- readonly cloudUserId?: string | null;- readonly relayUrl?: string | null;- readonly relayIssuer?: string | null;- }>(linkedResponse);-- assert.equal(linkedResponse.status, 200);- assert.equal(linkedBody.linked, true);- assert.equal(linkedBody.cloudUserId, "user_123");- assert.equal(linkedBody.relayUrl, "https://transport.example.test");- assert.equal(linkedBody.relayIssuer, "https://relay.example.test");- }).pipe(Effect.provide(NodeHttpServer.layerTest)),- );-- it.effect("does not expose internal cloud reconciliation over HTTP", () =>- Effect.gen(function* () {- yield* buildAppUnderTest();-- const reconcileUrl = yield* getHttpServerUrl("/api/connect/reconcile");- const response = yield* fetchEffect(reconcileUrl, {- method: "POST",- });-- assert.equal(response.status, 404);- }).pipe(Effect.provide(NodeHttpServer.layerTest)),- );-- it.effect("unlinks local cloud state and disables the managed endpoint runtime", () =>- Effect.gen(function* () {- const appliedRuntimeConfigs: Array<unknown> = [];- yield* buildAppUnderTest({- layers: {- cloudManagedEndpointRuntime: {- applyConfig: (config) => {- appliedRuntimeConfigs.push(config);- if (!config) {- return Effect.succeed({ status: "disabled" });- }- return Effect.succeed({- status: "running",- providerKind: "cloudflare_tunnel",- pid: 123,- ...(config.tunnelId ? { tunnelId: config.tunnelId } : {}),- ...(config.tunnelName ? { tunnelName: config.tunnelName } : {}),- });- },- },- },- });-- const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", {- privateKeyEncoding: { format: "pem", type: "pkcs8" },- publicKeyEncoding: { format: "pem", type: "spki" },- });- const ownerCookie = yield* getAuthenticatedSessionCookieHeader();- const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config");- const unlinkUrl = yield* getHttpServerUrl("/api/connect/unlink");- const linkStateUrl = yield* getHttpServerUrl("/api/connect/link-state");-- const relayConfigResponse = yield* fetchEffect(relayConfigUrl, {- method: "POST",- headers: {- cookie: ownerCookie,- "content-type": "application/json",- },- body: jsonRequestBody({- relayUrl: "https://transport.example.test",- relayIssuer: "https://relay.example.test",- cloudUserId: "user_123",- environmentCredential: "t3env_test_credential",- cloudMintPublicKey: cloudKeyPair.publicKey,- endpointRuntime: {- providerKind: "cloudflare_tunnel",- connectorToken: "connector-token",- tunnelId: "tunnel-id",- tunnelName: "tunnel-name",- },- }),- });- assert.equal(relayConfigResponse.status, 200);-- const unlinkResponse = yield* fetchEffect(unlinkUrl, {- method: "POST",- headers: {- cookie: ownerCookie,- },- });- const unlinkBody = yield* responseJsonEffect<{- readonly ok?: boolean;- readonly endpointRuntimeStatus?: { readonly status?: string };- }>(unlinkResponse);- assert.equal(unlinkResponse.status, 200);- assert.equal(unlinkBody.ok, true);- assert.equal(unlinkBody.endpointRuntimeStatus?.status, "disabled");-- const linkStateResponse = yield* fetchEffect(linkStateUrl, {- headers: {- cookie: ownerCookie,- },- });- const linkStateBody = yield* responseJsonEffect<{- readonly linked?: boolean;- readonly cloudUserId?: string | null;- readonly relayUrl?: string | null;- readonly relayIssuer?: string | null;- }>(linkStateResponse);- assert.equal(linkStateResponse.status, 200);- assert.equal(linkStateBody.linked, false);- assert.equal(linkStateBody.cloudUserId, null);- assert.equal(linkStateBody.relayUrl, null);- assert.equal(linkStateBody.relayIssuer, null);- assert.deepEqual(appliedRuntimeConfigs, [- {- providerKind: "cloudflare_tunnel",- connectorToken: "connector-token",- tunnelId: "tunnel-id",- tunnelName: "tunnel-name",- },- null,- ]);- }).pipe(Effect.provide(NodeHttpServer.layerTest)),- );-- it.effect("rejects replayed cloud mint requests atomically", () =>- Effect.gen(function* () {- yield* buildAppUnderTest();-- const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", {- privateKeyEncoding: { format: "pem", type: "pkcs8" },- publicKeyEncoding: { format: "pem", type: "spki" },- });- const ownerCookie = yield* getAuthenticatedSessionCookieHeader();- const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config");- const relayConfigResponse = yield* fetchEffect(relayConfigUrl, {- method: "POST",- headers: {- cookie: ownerCookie,- "content-type": "application/json",- },- body: jsonRequestBody({- relayUrl: "https://relay.example.test",- cloudUserId: "user_123",- environmentCredential: "t3env_test_credential",- cloudMintPublicKey: cloudKeyPair.publicKey,- endpointRuntime: null,- }),- });- assert.equal(relayConfigResponse.status, 200);-- const now = yield* DateTime.now;- const request = makeCloudMintCredentialRequest({- privateKey: cloudKeyPair.privateKey,- environmentId: testEnvironmentDescriptor.environmentId,- clientProofKeyThumbprint: "client-proof-key-thumbprint",- nonce: "cloud-mint-nonce-1",- issuedAt: DateTime.formatIso(now),- expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })),- });- const mintUrl = yield* getHttpServerUrl("/api/connect/mint-credential");- const postMint = () =>- fetchEffect(mintUrl, {- method: "POST",- headers: {- "content-type": "application/json",- },- body: jsonRequestBody(request),- });-- const firstResponse = yield* postMint();- const replayResponse = yield* postMint();- const replayBody = yield* responseJsonEffect<{- readonly _tag?: string;- readonly message?: string;- }>(replayResponse);-- assert.equal(firstResponse.status, 200);- assert.equal(replayResponse.status, 409);- assert.equal(replayBody._tag, "EnvironmentHttpConflictError");- assert.equal(replayBody.message, "Cloud mint request was already consumed.");- }).pipe(Effect.provide(NodeHttpServer.layerTest)),- );-- it.effect("serves the documented T3 Connect mint credential endpoint", () =>- Effect.gen(function* () {- yield* buildAppUnderTest();-- const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", {- privateKeyEncoding: { format: "pem", type: "pkcs8" },- publicKeyEncoding: { format: "pem", type: "spki" },- });- const ownerCookie = yield* getAuthenticatedSessionCookieHeader();- const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config");- const relayConfigResponse = yield* fetchEffect(relayConfigUrl, {- method: "POST",- headers: {- cookie: ownerCookie,- "content-type": "application/json",- },- body: jsonRequestBody({- relayUrl: "https://relay.example.test",- cloudUserId: "user_123",- environmentCredential: "t3env_test_credential",- cloudMintPublicKey: cloudKeyPair.publicKey,- endpointRuntime: null,- }),- });- assert.equal(relayConfigResponse.status, 200);-- const now = yield* DateTime.now;- const request = makeCloudMintCredentialRequest({- privateKey: cloudKeyPair.privateKey,- environmentId: testEnvironmentDescriptor.environmentId,- clientProofKeyThumbprint: "client-proof-key-thumbprint",- jti: "cloud-mint-jti-documented-endpoint",- nonce: "cloud-mint-nonce-documented-endpoint",- issuedAt: DateTime.formatIso(now),- expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })),- });- const mintUrl = yield* getHttpServerUrl("/api/t3-connect/mint-credential");- const response = yield* fetchEffect(mintUrl, {- method: "POST",- headers: {- "content-type": "application/json",- },- body: jsonRequestBody(request),- });-- assert.equal(response.status, 200);- const body = yield* responseJsonEffect<{- readonly credential?: string;- readonly proof?: string;- }>(response);- assert.equal(typeof body.credential, "string");- assert.equal(typeof body.proof, "string");- assert.equal(- decodeCompactJwtPayload<{ readonly requestNonce?: string }>(body.proof!).requestNonce,- "cloud-mint-nonce-documented-endpoint",- );- }).pipe(Effect.provide(NodeHttpServer.layerTest)),- );-- it.effect("serves signed T3 Connect environment health checks", () =>- Effect.gen(function* () {- yield* buildAppUnderTest();-- const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", {- privateKeyEncoding: { format: "pem", type: "pkcs8" },- publicKeyEncoding: { format: "pem", type: "spki" },- });- const ownerCookie = yield* getAuthenticatedSessionCookieHeader();- const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config");- const relayConfigResponse = yield* fetchEffect(relayConfigUrl, {- method: "POST",- headers: {- cookie: ownerCookie,- "content-type": "application/json",- },- body: jsonRequestBody({- relayUrl: "https://relay.example.test",- cloudUserId: "user_123",- environmentCredential: "t3env_test_credential",- cloudMintPublicKey: cloudKeyPair.publicKey,- endpointRuntime: null,- }),- });- assert.equal(relayConfigResponse.status, 200);-- const now = yield* DateTime.now;- const request = makeCloudEnvironmentHealthRequest({- privateKey: cloudKeyPair.privateKey,- environmentId: testEnvironmentDescriptor.environmentId,- jti: "cloud-health-jti-documented-endpoint",- nonce: "cloud-health-nonce-documented-endpoint",- issuedAt: DateTime.formatIso(now),- expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })),- });- const healthUrl = yield* getHttpServerUrl("/api/t3-connect/health");- const response = yield* fetchEffect(healthUrl, {- method: "POST",- headers: {- "content-type": "application/json",- },- body: jsonRequestBody(request),- });-- assert.equal(response.status, 200);- const body = yield* responseJsonEffect<{- readonly status?: string;- readonly descriptor?: { readonly environmentId?: string };- readonly proof?: string;- }>(response);- assert.equal(body.status, "online");- assert.equal(body.descriptor?.environmentId, testEnvironmentDescriptor.environmentId);- assert.equal(typeof body.proof, "string");- assert.equal(- decodeCompactJwtPayload<{ readonly requestNonce?: string }>(body.proof!).requestNonce,- "cloud-health-nonce-documented-endpoint",- );- }).pipe(Effect.provide(NodeHttpServer.layerTest)),- );-- it.effect("rejects replayed cloud health requests atomically", () =>- Effect.gen(function* () {- yield* buildAppUnderTest();-- const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", {- privateKeyEncoding: { format: "pem", type: "pkcs8" },- publicKeyEncoding: { format: "pem", type: "spki" },- });- const ownerCookie = yield* getAuthenticatedSessionCookieHeader();- const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config");- const relayConfigResponse = yield* fetchEffect(relayConfigUrl, {- method: "POST",- headers: {- cookie: ownerCookie,- "content-type": "application/json",- },- body: jsonRequestBody({- relayUrl: "https://relay.example.test",- cloudUserId: "user_123",- environmentCredential: "t3env_test_credential",- cloudMintPublicKey: cloudKeyPair.publicKey,- endpointRuntime: null,- }),- });- assert.equal(relayConfigResponse.status, 200);-- const now = yield* DateTime.now;- const request = makeCloudEnvironmentHealthRequest({- privateKey: cloudKeyPair.privateKey,- environmentId: testEnvironmentDescriptor.environmentId,- jti: "cloud-health-jti-replay",- nonce: "cloud-health-nonce-replay",- issuedAt: DateTime.formatIso(now),- expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })),- });- const healthUrl = yield* getHttpServerUrl("/api/t3-connect/health");- const postHealth = () =>- fetchEffect(healthUrl, {- method: "POST",- headers: {- "content-type": "application/json",- },- body: jsonRequestBody(request),- });-- const firstResponse = yield* postHealth();- const replayResponse = yield* postHealth();- const replayBody = yield* responseJsonEffect<{- readonly _tag?: string;- readonly message?: string;- }>(replayResponse);-- assert.equal(firstResponse.status, 200);- assert.equal(replayResponse.status, 409);- assert.equal(replayBody._tag, "EnvironmentHttpConflictError");- assert.equal(replayBody.message, "Cloud health request was already consumed.");- }).pipe(Effect.provide(NodeHttpServer.layerTest)),- );-- it.effect(- "validates cloud proofs against the configured relay issuer, not the transport URL",- () =>- Effect.gen(function* () {- yield* buildAppUnderTest();-- const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", {- privateKeyEncoding: { format: "pem", type: "pkcs8" },- publicKeyEncoding: { format: "pem", type: "spki" },- });- const ownerCookie = yield* getAuthenticatedSessionCookieHeader();- const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config");- const relayConfigResponse = yield* fetchEffect(relayConfigUrl, {- method: "POST",- headers: {- cookie: ownerCookie,- "content-type": "application/json",- },- body: jsonRequestBody({- relayUrl: "https://transport.example.test",- cloudUserId: "user_123",- relayIssuer: "https://relay.example.test",- environmentCredential: "t3env_test_credential",- cloudMintPublicKey: cloudKeyPair.publicKey,- endpointRuntime: null,- }),- });- assert.equal(relayConfigResponse.status, 200);-- const now = yield* DateTime.now;- const mintUrl = yield* getHttpServerUrl("/api/t3-connect/mint-credential");- const postMint = (request: ReturnType<typeof makeCloudMintCredentialRequest>) =>- fetchEffect(mintUrl, {- method: "POST",- headers: {- "content-type": "application/json",- },- body: jsonRequestBody(request),- });-- const acceptedResponse = yield* postMint(- makeCloudMintCredentialRequest({- privateKey: cloudKeyPair.privateKey,- environmentId: testEnvironmentDescriptor.environmentId,- clientProofKeyThumbprint: "client-proof-key-thumbprint",- issuer: "https://relay.example.test",- jti: "cloud-mint-jti-explicit-relay-issuer",- nonce: "cloud-mint-nonce-explicit-relay-issuer",- issuedAt: DateTime.formatIso(now),- expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })),- }),- );- const rejectedResponse = yield* postMint(- makeCloudMintCredentialRequest({- privateKey: cloudKeyPair.privateKey,- environmentId: testEnvironmentDescriptor.environmentId,- clientProofKeyThumbprint: "client-proof-key-thumbprint",- issuer: "https://transport.example.test",- jti: "cloud-mint-jti-transport-url",- nonce: "cloud-mint-nonce-transport-url",- issuedAt: DateTime.formatIso(now),- expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })),- }),- );-- assert.equal(acceptedResponse.status, 200);- assert.equal(rejectedResponse.status, 401);- }).pipe(Effect.provide(NodeHttpServer.layerTest)),- );-- it.effect("fails relay config when the managed endpoint connector cannot start", () =>- Effect.gen(function* () {- yield* buildAppUnderTest({- layers: {- cloudManagedEndpointRuntime: {- applyConfig: () =>- Effect.succeed({- status: "failed",- providerKind: "cloudflare_tunnel",- reason: "cloudflared missing",- tunnelId: "tunnel-1",- }),- },- },- });-- const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", {- privateKeyEncoding: { format: "pem", type: "pkcs8" },- publicKeyEncoding: { format: "pem", type: "spki" },- });- const ownerCookie = yield* getAuthenticatedSessionCookieHeader();- const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config");- const relayConfigResponse = yield* fetchEffect(relayConfigUrl, {- method: "POST",- headers: {- cookie: ownerCookie,- "content-type": "application/json",- },- body: jsonRequestBody({- relayUrl: "https://relay.example.test",- cloudUserId: "user_123",- environmentCredential: "t3env_test_credential",- cloudMintPublicKey: cloudKeyPair.publicKey,- endpointRuntime: {- providerKind: "cloudflare_tunnel",- connectorToken: "connector-token",- tunnelId: "tunnel-1",- },- }),- });-- assert.equal(relayConfigResponse.status, 503);- const relayConfigBody = yield* responseJsonEffect<{- _tag?: string;- message?: string;- endpointRuntimeStatus?: { status?: string; reason?: string };- }>(relayConfigResponse);- assert.equal(relayConfigBody._tag, "EnvironmentCloudEndpointUnavailableError");- assert.equal(relayConfigBody.message, "Managed endpoint runtime could not be started.");- assert.equal(relayConfigBody.endpointRuntimeStatus?.status, "failed");- assert.equal(relayConfigBody.endpointRuntimeStatus?.reason, "cloudflared missing");-- const now = yield* DateTime.now;- const healthRequest = makeCloudEnvironmentHealthRequest({- privateKey: cloudKeyPair.privateKey,- environmentId: testEnvironmentDescriptor.environmentId,- nonce: "cloud-health-after-failed-runtime",- issuedAt: DateTime.formatIso(now),- expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })),- });- const healthUrl = yield* getHttpServerUrl("/api/t3-connect/health");- const healthResponse = yield* fetchEffect(healthUrl, {- method: "POST",- headers: {- "content-type": "application/json",- },- body: jsonRequestBody(healthRequest),- });- const healthBody = yield* responseJsonEffect<{- _tag?: string;- message?: string;- }>(healthResponse);- assert.equal(healthResponse.status, 500);- assert.equal(healthBody._tag, "EnvironmentHttpInternalServerError");- assert.equal(- healthBody.message,- "Cloud mint public key is not installed for this environment.",- );- }).pipe(Effect.provide(NodeHttpServer.layerTest)),- );-- it.effect("rejects cloud mint requests with the wrong issuer or audience", () =>- Effect.gen(function* () {- yield* buildAppUnderTest();-- const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", {- privateKeyEncoding: { format: "pem", type: "pkcs8" },- publicKeyEncoding: { format: "pem", type: "spki" },- });- const ownerCookie = yield* getAuthenticatedSessionCookieHeader();- const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config");- const relayConfigResponse = yield* fetchEffect(relayConfigUrl, {- method: "POST",- headers: {- cookie: ownerCookie,- "content-type": "application/json",- },- body: jsonRequestBody({- relayUrl: "https://relay.example.test/",- cloudUserId: "user_123",- environmentCredential: "t3env_test_credential",- cloudMintPublicKey: cloudKeyPair.publicKey,- endpointRuntime: null,- }),- });- assert.equal(relayConfigResponse.status, 200);-- const now = yield* DateTime.now;- const mintUrl = yield* getHttpServerUrl("/api/connect/mint-credential");- const postMint = (request: ReturnType<typeof makeCloudMintCredentialRequest>) =>- fetchEffect(mintUrl, {- method: "POST",- headers: {- "content-type": "application/json",- },- body: jsonRequestBody(request),- });-- const wrongIssuer = yield* postMint(- makeCloudMintCredentialRequest({- privateKey: cloudKeyPair.privateKey,- environmentId: testEnvironmentDescriptor.environmentId,- clientProofKeyThumbprint: "client-proof-key-thumbprint",- issuer: "https://attacker.example.test",- jti: "cloud-mint-jti-wrong-issuer",- nonce: "cloud-mint-nonce-wrong-issuer",- issuedAt: DateTime.formatIso(now),- expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })),- }),- );- const wrongAudience = yield* postMint(- makeCloudMintCredentialRequest({- privateKey: cloudKeyPair.privateKey,- environmentId: testEnvironmentDescriptor.environmentId,- clientProofKeyThumbprint: "client-proof-key-thumbprint",- audience: "t3-env:other-environment",- jti: "cloud-mint-jti-wrong-audience",- nonce: "cloud-mint-nonce-wrong-audience",- issuedAt: DateTime.formatIso(now),- expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })),- }),- );-- assert.equal(wrongIssuer.status, 401);- assert.equal(wrongAudience.status, 401);- }).pipe(Effect.provide(NodeHttpServer.layerTest)),- );-- it.effect("rejects cloud mint requests for a cloud subject other than the linked user", () =>- Effect.gen(function* () {- yield* buildAppUnderTest();-- const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", {- privateKeyEncoding: { format: "pem", type: "pkcs8" },- publicKeyEncoding: { format: "pem", type: "spki" },- });- const ownerCookie = yield* getAuthenticatedSessionCookieHeader();- const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config");- const relayConfigResponse = yield* fetchEffect(relayConfigUrl, {- method: "POST",- headers: {- cookie: ownerCookie,- "content-type": "application/json",- },- body: jsonRequestBody({- relayUrl: "https://relay.example.test/",- cloudUserId: "user_123",- environmentCredential: "t3env_test_credential",- cloudMintPublicKey: cloudKeyPair.publicKey,- endpointRuntime: null,- }),- });- assert.equal(relayConfigResponse.status, 200);-- const now = yield* DateTime.now;- const mintUrl = yield* getHttpServerUrl("/api/t3-connect/mint-credential");- const response = yield* fetchEffect(mintUrl, {- method: "POST",- headers: {- "content-type": "application/json",- },- body: jsonRequestBody(- makeCloudMintCredentialRequest({- privateKey: cloudKeyPair.privateKey,- environmentId: testEnvironmentDescriptor.environmentId,- clientProofKeyThumbprint: "client-proof-key-thumbprint",- subject: "user_other",- jti: "cloud-mint-jti-wrong-subject",- nonce: "cloud-mint-nonce-wrong-subject",- issuedAt: DateTime.formatIso(now),- expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })),- }),- ),- });-- assert.equal(response.status, 401);- }).pipe(Effect.provide(NodeHttpServer.layerTest)),- );-- it.effect("rejects cloud mint requests without the exact connect scope", () =>- Effect.gen(function* () {- yield* buildAppUnderTest();-- const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", {- privateKeyEncoding: { format: "pem", type: "pkcs8" },- publicKeyEncoding: { format: "pem", type: "spki" },- });- const ownerCookie = yield* getAuthenticatedSessionCookieHeader();- const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config");- const relayConfigResponse = yield* fetchEffect(relayConfigUrl, {- method: "POST",- headers: {- cookie: ownerCookie,- "content-type": "application/json",- },- body: jsonRequestBody({- relayUrl: "https://relay.example.test/",- cloudUserId: "user_123",- environmentCredential: "t3env_test_credential",- cloudMintPublicKey: cloudKeyPair.publicKey,- endpointRuntime: null,- }),- });- assert.equal(relayConfigResponse.status, 200);-- const now = yield* DateTime.now;- const mintUrl = yield* getHttpServerUrl("/api/t3-connect/mint-credential");- const response = yield* fetchEffect(mintUrl, {- method: "POST",- headers: {- "content-type": "application/json",- },- body: jsonRequestBody(- makeCloudMintCredentialRequest({- privateKey: cloudKeyPair.privateKey,- environmentId: testEnvironmentDescriptor.environmentId,- clientProofKeyThumbprint: "client-proof-key-thumbprint",- jti: "cloud-mint-jti-duplicate-scope",- nonce: "cloud-mint-nonce-duplicate-scope",- issuedAt: DateTime.formatIso(now),- expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })),- scope: ["environment:connect", "environment:connect"],- }),- ),- });-- assert.equal(response.status, 401);- }).pipe(Effect.provide(NodeHttpServer.layerTest)),- );-- it.effect("rejects cloud health requests with the wrong issuer or audience", () =>- Effect.gen(function* () {- yield* buildAppUnderTest();-- const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", {- privateKeyEncoding: { format: "pem", type: "pkcs8" },- publicKeyEncoding: { format: "pem", type: "spki" },- });- const ownerCookie = yield* getAuthenticatedSessionCookieHeader();- const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config");- const relayConfigResponse = yield* fetchEffect(relayConfigUrl, {- method: "POST",- headers: {- cookie: ownerCookie,- "content-type": "application/json",- },- body: jsonRequestBody({- relayUrl: "https://relay.example.test/",- cloudUserId: "user_123",- environmentCredential: "t3env_test_credential",- cloudMintPublicKey: cloudKeyPair.publicKey,- endpointRuntime: null,- }),- });- assert.equal(relayConfigResponse.status, 200);-- const now = yield* DateTime.now;- const healthUrl = yield* getHttpServerUrl("/api/t3-connect/health");- const postHealth = (request: ReturnType<typeof makeCloudEnvironmentHealthRequest>) =>- fetchEffect(healthUrl, {- method: "POST",- headers: {- "content-type": "application/json",- },- body: jsonRequestBody(request),- });-- const wrongIssuer = yield* postHealth(- makeCloudEnvironmentHealthRequest({- privateKey: cloudKeyPair.privateKey,- environmentId: testEnvironmentDescriptor.environmentId,- issuer: "https://attacker.example.test",- jti: "cloud-health-jti-wrong-issuer",- nonce: "cloud-health-nonce-wrong-issuer",- issuedAt: DateTime.formatIso(now),- expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })),- }),- );- const wrongAudience = yield* postHealth(- makeCloudEnvironmentHealthRequest({- privateKey: cloudKeyPair.privateKey,- environmentId: testEnvironmentDescriptor.environmentId,- audience: "t3-env:other-environment",- jti: "cloud-health-jti-wrong-audience",- nonce: "cloud-health-nonce-wrong-audience",- issuedAt: DateTime.formatIso(now),- expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })),- }),- );-- assert.equal(wrongIssuer.status, 401);- assert.equal(wrongAudience.status, 401);- }).pipe(Effect.provide(NodeHttpServer.layerTest)),- );-- it.effect("rejects cloud health requests for a cloud subject other than the linked user", () =>- Effect.gen(function* () {- yield* buildAppUnderTest();-- const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", {- privateKeyEncoding: { format: "pem", type: "pkcs8" },- publicKeyEncoding: { format: "pem", type: "spki" },- });- const ownerCookie = yield* getAuthenticatedSessionCookieHeader();- const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config");- const relayConfigResponse = yield* fetchEffect(relayConfigUrl, {- method: "POST",- headers: {- cookie: ownerCookie,- "content-type": "application/json",- },- body: jsonRequestBody({- relayUrl: "https://relay.example.test/",- cloudUserId: "user_123",- environmentCredential: "t3env_test_credential",- cloudMintPublicKey: cloudKeyPair.publicKey,- endpointRuntime: null,- }),- });- assert.equal(relayConfigResponse.status, 200);-- const now = yield* DateTime.now;- const healthUrl = yield* getHttpServerUrl("/api/t3-connect/health");- const response = yield* fetchEffect(healthUrl, {- method: "POST",- headers: {- "content-type": "application/json",- },- body: jsonRequestBody(- makeCloudEnvironmentHealthRequest({- privateKey: cloudKeyPair.privateKey,- environmentId: testEnvironmentDescriptor.environmentId,- subject: "user_other",- jti: "cloud-health-jti-wrong-subject",- nonce: "cloud-health-nonce-wrong-subject",- issuedAt: DateTime.formatIso(now),- expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })),- }),- ),- });-- assert.equal(response.status, 401);- }).pipe(Effect.provide(NodeHttpServer.layerTest)),- );-- it.effect("rejects cloud health requests without the exact status scope", () =>- Effect.gen(function* () {- yield* buildAppUnderTest();-- const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", {- privateKeyEncoding: { format: "pem", type: "pkcs8" },- publicKeyEncoding: { format: "pem", type: "spki" },- });- const ownerCookie = yield* getAuthenticatedSessionCookieHeader();- const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config");- const relayConfigResponse = yield* fetchEffect(relayConfigUrl, {- method: "POST",- headers: {- cookie: ownerCookie,- "content-type": "application/json",- },- body: jsonRequestBody({- relayUrl: "https://relay.example.test/",- cloudUserId: "user_123",- environmentCredential: "t3env_test_credential",- cloudMintPublicKey: cloudKeyPair.publicKey,- endpointRuntime: null,- }),- });- assert.equal(relayConfigResponse.status, 200);-- const now = yield* DateTime.now;- const healthUrl = yield* getHttpServerUrl("/api/t3-connect/health");- const response = yield* fetchEffect(healthUrl, {- method: "POST",- headers: {- "content-type": "application/json",- },- body: jsonRequestBody(- makeCloudEnvironmentHealthRequest({- privateKey: cloudKeyPair.privateKey,- environmentId: testEnvironmentDescriptor.environmentId,- jti: "cloud-health-jti-duplicate-scope",- nonce: "cloud-health-nonce-duplicate-scope",- issuedAt: DateTime.formatIso(now),- expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })),- scope: ["environment:status", "environment:status"],- }),- ),- });-- assert.equal(response.status, 401);- }).pipe(Effect.provide(NodeHttpServer.layerTest)),- );-it.effect("negotiates permessage-deflate with clients that offer it", () =>Effect.gen(function* () {yield* buildAppUnderTest();@@ -4405,7 +2618,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {"authorization","b3","content-type",- "dpop","traceparent",]);}).pipe(Effect.provide(NodeHttpServer.layerTest)),diff --git a/apps/server/src/server.ts b/apps/server/src/server.tsindex 8b5ed783f..6c1d234bd 100644--- a/apps/server/src/server.ts+++ b/apps/server/src/server.ts@@ -1,9 +1,7 @@import { EnvironmentHttpApi } from "@t3tools/contracts";-import * as Duration from "effect/Duration";import * as Deferred from "effect/Deferred";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";-import * as Schedule from "effect/Schedule";import { FetchHttpClient, HttpRouter, HttpServer } from "effect/unstable/http";import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";@@ -60,8 +58,6 @@ import { ProviderRuntimeIngestionLive } from "./orchestration/Layers/ProviderRunimport { ProviderCommandReactorLive } from "./orchestration/Layers/ProviderCommandReactor.ts";import { CheckpointReactorLive } from "./orchestration/Layers/CheckpointReactor.ts";import { ThreadDeletionReactorLive } from "./orchestration/Layers/ThreadDeletionReactor.ts";-import * as AgentAwarenessRelay from "./relay/AgentAwarenessRelay.ts";-import { hasCloudPublicConfig } from "./cloud/publicConfig.ts";import { ProviderRegistryLive } from "./provider/Layers/ProviderRegistry.ts";import * as ServerSettings from "./serverSettings.ts";import * as ProjectFaviconResolver from "./project/ProjectFaviconResolver.ts";@@ -87,16 +83,6 @@ import * as RemoteOpenTargets from "./environment/RemoteOpenTargets.ts";import { authHttpApiLayer, environmentAuthenticatedAuthLayer } from "./auth/http.ts";import * as ServerSecretStore from "./auth/ServerSecretStore.ts";import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";-import {- connectHttpApiLayer,- pendingServiceUpdateExists,- reconcileDesiredCloudLink,- releaseManagedTunnelOnShutdown,-} from "./cloud/http.ts";-import { serverRelayBrokerTracingLayer } from "./cloud/relayTracing.ts";-import * as CloudManagedEndpointRuntime from "./cloud/ManagedEndpointRuntime.ts";-import * as CloudCliTokenManager from "./cloud/CliTokenManager.ts";-import * as CloudCliState from "./cloud/CliState.ts";import * as ServerSelfUpdate from "./cloud/selfUpdate.ts";import * as ServiceLauncherClient from "./cloud/serviceLauncherClient.ts";import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";@@ -119,9 +105,8 @@ import {} from "./serverRuntimeState.ts";import { orchestrationHttpApiLayer } from "./orchestration/http.ts";import * as NetService from "@t3tools/shared/Net";-import * as RelayClient from "@t3tools/shared/relayClient";import { disableTailscaleServe, ensureTailscaleServe } from "@t3tools/tailscale";-import { forkParked, ServerActivation } from "./serverActivation.ts";+import { ServerActivation } from "./serverActivation.ts";// Effect's default preemptive shutdown waits 20s before finalizing request scopes.// T3's primary transport is long-lived WebSocket RPC, whose Effect scope finalizer@@ -184,13 +169,6 @@ const ResourceDiagnosticsLayerLive = Layer.mergeAll(ProcessResourceMonitor.layer.pipe(Layer.provide(ResourceTelemetryLayerLive)),);-const RelayClientLive = Layer.unwrap(- Effect.gen(function* () {- const config = yield* ServerConfig.ServerConfig;- return RelayClient.layerCloudflared({ baseDir: config.baseDir });- }),-);-const HttpServerLive = Layer.unwrap(Effect.gen(function* () {const config = yield* ServerConfig.ServerConfig;@@ -256,7 +234,6 @@ const ReactorLayerLive = Layer.empty.pipe(Layer.provideMerge(ProviderCommandReactorLive),Layer.provideMerge(CheckpointReactorLive),Layer.provideMerge(ThreadDeletionReactorLive),- Layer.provideMerge(AgentAwarenessRelay.layer.pipe(Layer.provide(ServerSecretStore.layer))),Layer.provideMerge(RuntimeReceiptBusLive),);@@ -384,14 +361,6 @@ const AuthLayerLive = EnvironmentAuth.layer.pipe(Layer.provide(ServerSecretStore.layer),);-const CloudManagedEndpointRuntimeLive = Layer.mergeAll(- RelayClientLive,- CloudManagedEndpointRuntime.layer.pipe(- Layer.provide(ServerSecretStore.layer),- Layer.provide(RelayClientLive),- ),-);-const ProviderRuntimeLayerLive = ProviderSessionReaperLive.pipe(Layer.provideMerge(ProviderSessionDirectoryLayerLive),Layer.provideMerge(ProviderLayerLive),@@ -437,15 +406,6 @@ const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(Layer.provideMerge(ServerEnvironment.layer),Layer.provideMerge(AuthLayerLive),Layer.provideMerge(ServerSecretStore.layer),- Layer.provideMerge(- Layer.mergeAll(- CloudCliTokenManager.layer.pipe(- Layer.provide(ServerSecretStore.layer),- Layer.provide(ExternalLauncher.layer),- ),- CloudManagedEndpointRuntimeLive,- ),- ),);const RuntimeDependenciesLive = RuntimeCoreDependenciesLive.pipe(@@ -473,7 +433,6 @@ export const makeRoutesLayer = Layer.mergeAll(Layer.mergeAll(HttpApiBuilder.layer(EnvironmentHttpApi).pipe(Layer.provide(authHttpApiLayer),- Layer.provide(connectHttpApiLayer),Layer.provide(orchestrationHttpApiLayer),Layer.provide(serverEnvironmentHttpApiLayer),Layer.provide(environmentAuthenticatedAuthLayer),@@ -501,7 +460,6 @@ export const makeServerLayer = Layer.unwrap(const activationLayer = Layer.succeed(ServerActivation, awaitActivation);const runtimeStateParked = yield* Deferred.make<void>();const tailscaleParked = yield* Deferred.make<void>();- const cloudLinkParked = yield* Deferred.make<void>();const routesReady = yield* Deferred.make<void>();const launcherLayer = ServiceLauncherClient.layer;@@ -599,83 +557,12 @@ export const makeServerLayer = Layer.unwrap(),): Layer.empty;- const cloudDesiredLinkReconcileLayer = Layer.effectDiscard(- Effect.gen(function* () {- if (!hasCloudPublicConfig) {- yield* Deferred.succeed(cloudLinkParked, undefined).pipe(Effect.orDie);- return;- }- const releaseManagedTunnel = releaseManagedTunnelOnShutdown().pipe(- Effect.timeout("10 seconds"),- Effect.tap((released) =>- released ? Effect.logInfo("Released the managed tunnel on shutdown") : Effect.void,- ),- Effect.catchCause((cause) =>- Effect.logWarning(- "Failed to release the managed tunnel on shutdown; the next link reuses it",- { cause },- ),- ),- Effect.asVoid,- );- // A launcher trial can be stopped before activation. The previous- // server is already gone, so the trial owns cleanup immediately; the- // pending-state check keeps the tunnel for normal commit or rollback,- // while the launcher's explicit-stop marker allows it to be released.- // Other runtimes wait for activation so a failed standby cannot tear- // down the active runtime's tunnel.- const cleanupBeforeActivation = yield* pendingServiceUpdateExists;- if (cleanupBeforeActivation) {- yield* Effect.addFinalizer(() => releaseManagedTunnel);- }- yield* forkParked(- Effect.gen(function* () {- if (!cleanupBeforeActivation) {- yield* Effect.addFinalizer(() => releaseManagedTunnel);- }- if (!(yield* CloudCliState.readCliDesiredCloudLink)) return;- const server = yield* HttpServer.HttpServer;- const address = server.address;- if (typeof address === "string" || !("port" in address)) return;- // No settling delay before the first attempt: routes are already- // serving by the time activation opens this gate (the startup- // sequence awaits routesReady), and the retry schedule below- // covers anything this sleep used to hedge against. Every- // millisecond here is dead time on the path to remote- // reachability after a restart.- yield* reconcileDesiredCloudLink(`http://127.0.0.1:${address.port}`).pipe(- Effect.retry({- while: (error) =>- error._tag !== "EnvironmentHttpBadRequestError" &&- error._tag !== "EnvironmentHttpUnauthorizedError" &&- error._tag !== "EnvironmentHttpConflictError",- schedule: Schedule.exponential("1 second").pipe(- Schedule.modifyDelay(({ duration }) =>- Effect.succeed(Duration.min(duration, Duration.seconds(30))),- ),- Schedule.upTo({ duration: "10 minutes" }),- ),- }),- Effect.tap(() => Effect.logInfo("T3 Connect desired link reconciled on startup")),- Effect.catch((cause) =>- Effect.logWarning("Failed to reconcile T3 Connect desired link on startup", {- cause,- }),- ),- );- }),- );- yield* Deferred.succeed(cloudLinkParked, undefined).pipe(Effect.orDie);- }),- );-const runtimeServicesLive = ServerRuntimeStartup.layerWithOptions({activate: Deferred.succeed(activation, undefined).pipe(Effect.asVoid),abort: (error) => Deferred.die(activation, error).pipe(Effect.asVoid),awaitAuxiliaryParked: Effect.all([Deferred.await(runtimeStateParked),- Deferred.await(cloudLinkParked),Deferred.await(routesReady),...(config.tailscaleServeEnabled ? [Deferred.await(tailscaleParked)] : []),],@@ -691,13 +578,11 @@ export const makeServerLayer = Layer.unwrap(httpListeningLayer,runtimeStateLayer,tailscaleServeLayer,- cloudDesiredLinkReconcileLayer,);return serverApplicationLayer.pipe(Layer.provideMerge(runtimeServicesLive),Layer.provide(activationLayer),- Layer.provideMerge(serverRelayBrokerTracingLayer),Layer.provideMerge(HttpServerLive),Layer.provide(ApplicationObservabilityLive),Layer.provideMerge(FetchHttpClient.layer),diff --git a/apps/server/src/telemetry/AnalyticsService.ts b/apps/server/src/telemetry/AnalyticsService.tsindex 37126d291..3edd3b858 100644--- a/apps/server/src/telemetry/AnalyticsService.ts+++ b/apps/server/src/telemetry/AnalyticsService.ts@@ -153,7 +153,7 @@ function normalizeProvider(value: string): UsageAnalyticsProvider {return providerValues.has(value) ? (value as UsageAnalyticsProvider) : "other";}-const sandboxValues = new Set(["none", "local", "vercel", "akeru-cloud", "upstash"]);+const sandboxValues = new Set(["none", "local", "e2b", "daytona", "vercel", "upstash"]);function normalizeSandbox(value: string): UsageSandboxProvider {if (value === "other") return "other";return sandboxValues.has(value) ? (value as UsageSandboxProvider) : "other";diff --git a/apps/server/src/usage/BotUsageLedger.test.ts b/apps/server/src/usage/BotUsageLedger.test.tsindex 9c2b81af1..c252c51e1 100644--- a/apps/server/src/usage/BotUsageLedger.test.ts+++ b/apps/server/src/usage/BotUsageLedger.test.ts@@ -465,7 +465,7 @@ it("reconciles persisted reservations when the ledger restarts", () =>return { afterRestart, afterLateReport: yield* ledger.summarize(botId) };}).pipe(Effect.provide(restartedLayer()));- assert.equal(afterRestart.consumedTokens, 270);+ assert.equal(afterRestart.consumedTokens, 250);assert.equal(afterRestart.reservedTokens, 0);assert.equal(afterRestart.entries.find((entry) => entry.sourceKey.includes("unbound-before-restart"))@@ -481,7 +481,7 @@ it("reconciles persisted reservations when the ledger restarts", () =>?.state,"reported",);- assert.equal(afterLateReport.consumedTokens, 305);+ assert.equal(afterLateReport.consumedTokens, 280);assert.equal(afterLateReport.reservedTokens, 0);NodeFS.rmSync(directory, { recursive: true, force: true });}).pipe(Effect.provide(NodeServices.layer), Effect.orDie));diff --git a/apps/server/src/usage/UsageService.ts b/apps/server/src/usage/UsageService.tsindex 681e7cd32..ee548fba1 100644--- a/apps/server/src/usage/UsageService.ts+++ b/apps/server/src/usage/UsageService.ts@@ -19,6 +19,7 @@ import {type UsageSource,type UsageSummary,type UsageSummaryInput,+ type UsageTokenTotals,UsageReadError,} from "@t3tools/contracts";import * as Cause from "effect/Cause";@@ -39,7 +40,7 @@ import { SubscriptionAuthService } from "../subscription-auth/service.ts";import { resolveClaudeHomePath } from "../provider/Drivers/ClaudeHome.ts";import { resolveCodexHomeLayout } from "../provider/Drivers/CodexHomeLayout.ts";import { UsageAggregator } from "./usageAggregation.ts";-import { parseRateTable, type RateTable } from "./usagePricing.ts";+import { parseRateTable, priceUsage, type PricedUsage, type RateTable } from "./usagePricing.ts";import {listTranscriptFiles,readDirectoryVolumeId,@@ -88,36 +89,48 @@ const ScanCacheJson = Schema.fromJsonString(Schema.Unknown as unknown as Schema.const decodeScanCacheFile = Schema.decodeUnknownEffect(ScanCacheJson);const encodeScanCacheFile = Schema.encodeEffect(ScanCacheJson);+export interface PriceStepUsageInput {+ readonly model: string;+ readonly totals: UsageTokenTotals;+ readonly reportedCostUsd: number | null;+}+export class UsageService extends Context.Service<UsageService,{readonly readSummary: (input: UsageSummaryInput) => Effect.Effect<UsageSummary, UsageReadError>;+ readonly priceStepUsage: (input: PriceStepUsageInput) => Effect.Effect<PricedUsage>;}>()("akeru-bot/usage/UsageService") {}/** Empty summary, for suites that only need the RPC surface to resolve. */-export const layerTest = Layer.succeed(- UsageService,- UsageService.of({- readSummary: (input) =>- Effect.succeed({- contractVersion: USAGE_CONTRACT_VERSION,- readAt: "1970-01-01T00:00:00.000Z",- timeZone: input.timeZone,- sinceDay: input.sinceDay,- untilDay: input.untilDay,- buckets: [],- sources: [],- pricing: {- status: "unavailable",- source: LITELLM_RATES_URL,- fetchedAt: null,- knownModels: 0,- },- scanDurationMs: 0,- }),- }),-);+export const layerTestWithRates = (rateTable: RateTable) =>+ Layer.succeed(+ UsageService,+ UsageService.of({+ readSummary: (input) =>+ Effect.succeed({+ contractVersion: USAGE_CONTRACT_VERSION,+ readAt: "1970-01-01T00:00:00.000Z",+ timeZone: input.timeZone,+ sinceDay: input.sinceDay,+ untilDay: input.untilDay,+ buckets: [],+ sources: [],+ pricing: {+ status: "unavailable",+ source: LITELLM_RATES_URL,+ fetchedAt: null,+ knownModels: rateTable.size,+ },+ scanDurationMs: 0,+ }),+ priceStepUsage: (input) =>+ Effect.succeed(priceUsage(rateTable, input.model, input.totals, input.reportedCostUsd)),+ }),+ );++export const layerTest = layerTestWithRates(new Map());export const make = Effect.gen(function* () {const fileSystem = yield* FileSystem.FileSystem;@@ -297,6 +310,13 @@ export const make = Effect.gen(function* () {return records;});+ const priceStepUsage = Effect.fn("UsageService.priceStepUsage")(function* (+ input: PriceStepUsageInput,+ ) {+ yield* ensureRates();+ return priceUsage(rates, input.model, input.totals, input.reportedCostUsd);+ });+const readSummary = Effect.fn("UsageService.readSummary")(function* (input: UsageSummaryInput) {if (input.sinceDay > input.untilDay) {return yield* new UsageReadError({@@ -454,7 +474,7 @@ export const make = Effect.gen(function* () {} satisfies UsageSummary;});- return { readSummary } as const;+ return { readSummary, priceStepUsage } as const;});export const layer = Layer.effect(UsageService, make);diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.tsindex a1bdbdbd1..56b6370e0 100644--- a/apps/server/src/ws.ts+++ b/apps/server/src/ws.ts@@ -56,8 +56,6 @@ import {ProjectSearchEntriesError,ProjectWriteFileError,ProviderUploadFeedbackError,- RelayClientInstallFailedError,- type RelayClientInstallProgressEvent,type ServerSelfUpdateError,type ServerSelfUpdateProgressEvent,type ServerProvider,@@ -161,7 +159,6 @@ import * as VcsProcess from "./vcs/VcsProcess.ts";import * as PairingGrantStore from "./auth/PairingGrantStore.ts";import * as SessionStore from "./auth/SessionStore.ts";import { failEnvironmentAuthInvalid, failEnvironmentInternal } from "./auth/http.ts";-import * as RelayClient from "@t3tools/shared/relayClient";const isOrchestrationDispatchCommandError = Schema.is(OrchestrationDispatchCommandError);const nowIso = Effect.map(DateTime.now, DateTime.formatIso);@@ -563,7 +560,6 @@ const makeWsRpcLayer = (const processResourceMonitor = yield* ProcessResourceMonitor.ProcessResourceMonitor;const resourceTelemetry = yield* ResourceTelemetry.ResourceTelemetry;const usage = yield* UsageService.UsageService;- const relayClient = yield* RelayClient.RelayClient;const memory =Option.isSome(entityMemoryRepository) && Option.isSome(memoryCandidates)? createMemoryRpcHandlers({@@ -2408,39 +2404,6 @@ const makeWsRpcLayer = (}),{ "rpc.aggregate": "bot" },),- [WS_METHODS.cloudGetRelayClientStatus]: (_input) =>- observeRpcEffect(WS_METHODS.cloudGetRelayClientStatus, relayClient.resolve, {- "rpc.aggregate": "cloud",- }),- [WS_METHODS.cloudInstallRelayClient]: (_input) =>- observeRpcStream(- WS_METHODS.cloudInstallRelayClient,- Stream.callback<RelayClientInstallProgressEvent, RelayClientInstallFailedError>(- (queue) =>- relayClient- .installWithProgress((event) => Queue.offer(queue, event).pipe(Effect.asVoid))- .pipe(- Effect.flatMap((status) =>- Queue.offer(queue, {- type: "complete",- status,- }),- ),- Effect.catchTag("RelayClientInstallError", (error) =>- Queue.fail(- queue,- new RelayClientInstallFailedError({- reason: error.reason,- message: error.message,- }),- ),- ),- Effect.andThen(Queue.end(queue)),- Effect.forkScoped,- ),- ),- { "rpc.aggregate": "cloud" },- ),[WS_METHODS.sourceControlLookupRepository]: (input) =>observeRpcEffect(WS_METHODS.sourceControlLookupRepository,diff --git a/apps/server/vite.config.ts b/apps/server/vite.config.tsindex 647af2a88..d7bc9587b 100644--- a/apps/server/vite.config.ts+++ b/apps/server/vite.config.ts@@ -2,7 +2,6 @@ import "vite-plus/test/config";import { defineConfig, mergeConfig } from "vite-plus";import baseConfig from "../../vite.config.ts";-import { loadRepoEnv } from "../../scripts/lib/public-config.ts";import packageJson from "./package.json" with { type: "json" };// The bundle used to inline only workspace packages, leaving every third-party@@ -20,7 +19,6 @@ import {export { shouldBundleCliDependency };-const repoEnv = loadRepoEnv();const cliBuildChannel = packageJson.version.includes("-nightly.") ? "nightly" : "latest";export default mergeConfig(@@ -56,22 +54,6 @@ export default mergeConfig(},define: {__T3CODE_BUILD_CHANNEL__: JSON.stringify(cliBuildChannel),- __T3CODE_BUILD_RELAY_URL__: JSON.stringify(repoEnv.T3CODE_RELAY_URL?.trim() ?? ""),- __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: JSON.stringify(- repoEnv.T3CODE_CLERK_PUBLISHABLE_KEY?.trim() ?? "",- ),- __T3CODE_BUILD_CLERK_CLI_OAUTH_CLIENT_ID__: JSON.stringify(- repoEnv.T3CODE_CLERK_CLI_OAUTH_CLIENT_ID?.trim() ?? "",- ),- __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_URL__: JSON.stringify(- repoEnv.T3CODE_RELAY_CLIENT_OTLP_TRACES_URL?.trim() ?? "",- ),- __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_DATASET__: JSON.stringify(- repoEnv.T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET?.trim() ?? "",- ),- __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_TOKEN__: JSON.stringify(- repoEnv.T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN?.trim() ?? "",- ),},},test: {diff --git a/apps/web/package.json b/apps/web/package.jsonindex babe0cfba..5a90519f6 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -13,8 +13,6 @@},"dependencies": {"@base-ui/react": "^1.4.1",- "@clerk/electron": "catalog:",- "@clerk/react": "catalog:","@dnd-kit/core": "^6.3.1","@dnd-kit/modifiers": "^9.0.0","@dnd-kit/sortable": "^10.0.0",diff --git a/apps/web/src/branding.test.ts b/apps/web/src/branding.test.tsindex b7262af3b..d71e61a88 100644--- a/apps/web/src/branding.test.ts+++ b/apps/web/src/branding.test.ts@@ -27,6 +27,7 @@ describe("branding", () => {baseName: "Akeru Bot",stageLabel: "Nightly",displayName: "Akeru Bot (Nightly)",+ isPackaged: true,}),},},@@ -37,6 +38,7 @@ describe("branding", () => {expect(branding.APP_BASE_NAME).toBe("Akeru Bot");expect(branding.APP_STAGE_LABEL).toBe("Nightly");expect(branding.APP_DISPLAY_NAME).toBe("Akeru Bot (Nightly)");+ expect(branding.IS_PACKAGED_DESKTOP).toBe(true);});it("normalizes hosted app channel metadata", async () => {diff --git a/apps/web/src/branding.ts b/apps/web/src/branding.tsindex 8185246be..a4e0deaab 100644--- a/apps/web/src/branding.ts+++ b/apps/web/src/branding.ts@@ -24,4 +24,5 @@ export const APP_STAGE_LABEL =export const APP_DISPLAY_NAME =injectedDesktopAppBranding?.displayName ??formatAppDisplayName({ baseName: APP_BASE_NAME, stageLabel: APP_STAGE_LABEL });+export const IS_PACKAGED_DESKTOP = injectedDesktopAppBranding?.isPackaged ?? false;export const APP_VERSION = import.meta.env.APP_VERSION || "0.0.0";diff --git a/apps/web/src/clientPersistenceStorage.test.ts b/apps/web/src/clientPersistenceStorage.test.tsindex 8f849a6e7..18f0cdcee 100644--- a/apps/web/src/clientPersistenceStorage.test.ts+++ b/apps/web/src/clientPersistenceStorage.test.ts@@ -44,6 +44,8 @@ describe("clientPersistenceStorage", () => {await import("./clientPersistenceStorage");const settings = {...DEFAULT_CLIENT_SETTINGS,+ reviewedPrivacyPolicyVersion: "2026-08-31",+ reviewedTermsVersion: "2026-08-31",timestampFormat: "24-hour" as const,};diff --git a/apps/web/src/cloud/connectCliAuth.test.ts b/apps/web/src/cloud/connectCliAuth.test.tsdeleted file mode 100644index 3d41c4166..000000000--- a/apps/web/src/cloud/connectCliAuth.test.ts+++ /dev/null@@ -1,109 +0,0 @@-import { afterEach, describe, expect, it, vi } from "vite-plus/test";--import {- buildConnectCliClerkAuthorizeUrl,- connectCliSignInRedirectUrl,- hasConnectCliAuthConfig,- readConnectCliCallbackResult,-} from "./connectCliAuth";--// Any pk_test_* key decodes to <base64 hostname>.clerk.accounts.dev.-const TEST_PUBLISHABLE_KEY = `pk_test_${btoa("witty-mole-42.clerk.accounts.dev$")}`;--describe("connectCliAuth", () => {- afterEach(() => {- vi.unstubAllEnvs();- });-- it("requires both the publishable key and the CLI OAuth client id", () => {- vi.stubEnv("VITE_CLERK_PUBLISHABLE_KEY", TEST_PUBLISHABLE_KEY);- vi.stubEnv("VITE_CLERK_JWT_TEMPLATE", "t3-relay");- vi.stubEnv("VITE_T3CODE_RELAY_URL", "https://relay.example.com");- expect(hasConnectCliAuthConfig()).toBe(false);-- vi.stubEnv("VITE_CLERK_CLI_OAUTH_CLIENT_ID", "oauthapp_123");- expect(hasConnectCliAuthConfig()).toBe(true);- });-- it("builds the Clerk authorize URL with the configured hosted origin's callback", () => {- vi.stubEnv("VITE_CLERK_PUBLISHABLE_KEY", TEST_PUBLISHABLE_KEY);- vi.stubEnv("VITE_CLERK_CLI_OAUTH_CLIENT_ID", "oauthapp_123");- vi.stubEnv("VITE_HOSTED_APP_URL", "https://nightly.app.t3.codes");-- const authorizeUrl = buildConnectCliClerkAuthorizeUrl({- state: "state-1",- challenge: "challenge-1",- });- expect(authorizeUrl).not.toBeNull();-- const url = new URL(authorizeUrl!);- expect(url.hostname).toBe("witty-mole-42.clerk.accounts.dev");- expect(url.pathname).toBe("/oauth/authorize");- expect(url.searchParams.get("redirect_uri")).toBe(- "https://nightly.app.t3.codes/connect/callback",- );- expect(url.searchParams.get("state")).toBe("state-1");- expect(url.searchParams.get("code_challenge")).toBe("challenge-1");- expect(url.searchParams.get("code_challenge_method")).toBe("S256");- });-- it("redirects straight to the CLI's loopback listener when the request carries a port", () => {- vi.stubEnv("VITE_CLERK_PUBLISHABLE_KEY", TEST_PUBLISHABLE_KEY);- vi.stubEnv("VITE_CLERK_CLI_OAUTH_CLIENT_ID", "oauthapp_123");-- const authorizeUrl = buildConnectCliClerkAuthorizeUrl({- state: "state-1",- challenge: "challenge-1",- loopbackPort: 34338,- });- expect(authorizeUrl).not.toBeNull();-- const url = new URL(authorizeUrl!);- expect(url.searchParams.get("redirect_uri")).toBe("http://127.0.0.1:34338/callback");- expect(url.searchParams.get("state")).toBe("state-1");- });-- it("returns null when the CLI OAuth client id is not configured", () => {- vi.stubEnv("VITE_CLERK_PUBLISHABLE_KEY", TEST_PUBLISHABLE_KEY);- expect(- buildConnectCliClerkAuthorizeUrl({ state: "state-1", challenge: "challenge-1" }),- ).toBeNull();- });-- it("sends the sign-in redirect to the authorize endpoint, not back to /connect", () => {- vi.stubEnv("VITE_CLERK_PUBLISHABLE_KEY", TEST_PUBLISHABLE_KEY);- vi.stubEnv("VITE_CLERK_CLI_OAUTH_CLIENT_ID", "oauthapp_123");-- const connectUrl = "https://app.t3.codes/connect#state=state-1&challenge=challenge-1";- const redirectUrl = connectCliSignInRedirectUrl(- { state: "state-1", challenge: "challenge-1" },- connectUrl,- );-- expect(redirectUrl).not.toBe(connectUrl);- expect(new URL(redirectUrl).pathname).toBe("/oauth/authorize");- });-- it("falls back to the current URL when the authorize URL cannot be built", () => {- vi.stubEnv("VITE_CLERK_PUBLISHABLE_KEY", TEST_PUBLISHABLE_KEY);-- const connectUrl = "https://app.t3.codes/connect#state=state-1&challenge=challenge-1";- expect(- connectCliSignInRedirectUrl({ state: "state-1", challenge: "challenge-1" }, connectUrl),- ).toBe(connectUrl);- });-- it("reads the code and state Clerk echoes back to the callback", () => {- expect(- readConnectCliCallbackResult(- new URL("https://app.t3.codes/connect/callback?code=abc&state=state-1"),- ),- ).toEqual({ code: "abc", state: "state-1" });- expect(- readConnectCliCallbackResult(new URL("https://app.t3.codes/connect/callback?code=abc")),- ).toBeNull();- expect(- readConnectCliCallbackResult(new URL("https://app.t3.codes/connect/callback?state=s")),- ).toBeNull();- });-});diff --git a/apps/web/src/cloud/connectCliAuth.ts b/apps/web/src/cloud/connectCliAuth.tsdeleted file mode 100644index 815715da2..000000000--- a/apps/web/src/cloud/connectCliAuth.ts+++ /dev/null@@ -1,117 +0,0 @@-import {- buildConnectClerkAuthorizeUrl,- connectCallbackUrl,- connectLoopbackRedirectUri,- CONNECT_OAUTH_SCOPES,- type ConnectAuthorizeRequest,-} from "@t3tools/shared/connectAuth";-import { clerkFrontendApiUrlFromPublishableKey } from "@t3tools/shared/relayAuth";--import { configuredHostedAppUrl, isHostedStaticApp } from "../hostedPairing";-import { hasCloudPublicConfig, resolveCloudPublicConfig, trimNonEmpty } from "./publicConfig";--const CONNECT_CLI_AUTH_STATE_STORAGE_KEY = "t3code-connect-cli-auth-state";--export function resolveConnectCliOAuthClientId(): string | null {- return trimNonEmpty(import.meta.env.VITE_CLERK_CLI_OAUTH_CLIENT_ID as string | undefined);-}--export function hasConnectCliAuthConfig(): boolean {- return Boolean(- resolveCloudPublicConfig().clerkPublishableKey && resolveConnectCliOAuthClientId(),- );-}--/**- * Gate for the /connect routes: the CLI handshake only exists on the hosted- * deployment (the same bundle ships inside local instances) and needs the- * Clerk CLI OAuth client configured at build time.- */-export function connectCliAuthRoutesEnabled(): boolean {- return isHostedStaticApp() && hasCloudPublicConfig() && hasConnectCliAuthConfig();-}--/**- * Builds the Clerk authorize URL for a CLI-initiated connect request. The- * state is mirrored into sessionStorage so the callback page can verify the- * response matches a request this browser actually started.- *- * A request carrying a loopback port came from a CLI with a local callback- * listener: the authorization code must return to `127.0.0.1` directly, so- * the hosted callback page never sees it. Clerk enforces its registered- * redirect URI allowlist either way.- */-export function buildConnectCliClerkAuthorizeUrl(request: ConnectAuthorizeRequest): string | null {- const { clerkPublishableKey } = resolveCloudPublicConfig();- const clientId = resolveConnectCliOAuthClientId();- if (!clerkPublishableKey || !clientId) {- return null;- }- return buildConnectClerkAuthorizeUrl({- authorizationEndpoint: `${clerkFrontendApiUrlFromPublishableKey(clerkPublishableKey)}/oauth/authorize`,- clientId,- redirectUri:- request.loopbackPort === undefined- ? connectCallbackUrl(configuredHostedAppUrl())- : connectLoopbackRedirectUri(request.loopbackPort),- scopes: CONNECT_OAUTH_SCOPES,- state: request.state,- challenge: request.challenge,- });-}--/**- * Where Clerk sends the browser once the sign-in modal on /connect completes.- * It has to be the authorize endpoint rather than this page: /connect carries- * the CLI request in its fragment, so navigating back to the same URL is a- * same-document fragment navigation the browser never reloads — and Clerk- * treats any post-sign-in navigation as a page unload and skips the state emit- * that would otherwise re-render the surface, so the session never arrives- * either. Falls back to the current URL when the authorize URL cannot be- * built, which only happens on a deployment without the CLI OAuth config.- */-export function connectCliSignInRedirectUrl(- request: ConnectAuthorizeRequest,- currentHref: string,-): string {- return buildConnectCliClerkAuthorizeUrl(request) ?? currentHref;-}--export function rememberConnectCliAuthState(state: string): void {- try {- window.sessionStorage.setItem(CONNECT_CLI_AUTH_STATE_STORAGE_KEY, state);- } catch {- // Session storage can be unavailable (e.g. blocked). The callback page- // then falls back to trusting the state Clerk echoed back.- }-}--/**- * Read-only on purpose: this runs during render, where a removal would be- * consumed by React's double-invoked/discarded renders (StrictMode) and- * silently disable the state check. The value is not a secret and is- * overwritten by the next /connect visit.- */-export function readConnectCliAuthState(): string | null {- try {- return window.sessionStorage.getItem(CONNECT_CLI_AUTH_STATE_STORAGE_KEY);- } catch {- return null;- }-}--export interface ConnectCliCallbackResult {- readonly code: string;- readonly state: string;-}--export function readConnectCliCallbackResult(- url: URL = new URL(window.location.href),-): ConnectCliCallbackResult | null {- const code = url.searchParams.get("code")?.trim() ?? "";- const state = url.searchParams.get("state")?.trim() ?? "";- if (!code || !state) {- return null;- }- return { code, state };-}diff --git a/apps/web/src/cloud/connectOnboarding.ts b/apps/web/src/cloud/connectOnboarding.tsdeleted file mode 100644index 7d61e11c6..000000000--- a/apps/web/src/cloud/connectOnboarding.ts+++ /dev/null@@ -1,18 +0,0 @@-import * as Schema from "effect/Schema";--/**- * Accounts that opted out of the post-sign-in T3 Connect onboarding wizard- * ("Don't show this again"). The wizard otherwise shows on every sign-in,- * since sign-out clears the connected environments.- */-export const CONNECT_ONBOARDING_OPT_OUT_STORAGE_KEY = "t3code:connect-onboarding-opt-out:v1";--export const ConnectOnboardingOptOutSchema = Schema.Struct({- optOutAccounts: Schema.Array(Schema.String),-});--export type ConnectOnboardingOptOutState = typeof ConnectOnboardingOptOutSchema.Type;--export const EMPTY_CONNECT_ONBOARDING_OPT_OUT_STATE: ConnectOnboardingOptOutState = {- optOutAccounts: [],-};diff --git a/apps/web/src/cloud/dpop.test.ts b/apps/web/src/cloud/dpop.test.tsdeleted file mode 100644index 75951db1b..000000000--- a/apps/web/src/cloud/dpop.test.ts+++ /dev/null@@ -1,35 +0,0 @@-import { verifyDpopProof } from "@t3tools/shared/dpop";-import { describe, expect, it } from "@effect/vitest";-import * as Effect from "effect/Effect";-import { decodeJwt } from "jose";-import { vi } from "vite-plus/test";--import { browserCryptoLayer, createBrowserDpopProof, generateBrowserDpopKey } from "./dpop";--describe("browser DPoP proofs", () => {- it.effect("signs relay resource proofs with an access-token hash", () =>- Effect.gen(function* () {- vi.stubGlobal("indexedDB", undefined);- const proofKey = yield* generateBrowserDpopKey;- const proof = yield* createBrowserDpopProof({- method: "POST",- url: "https://relay.example.test/v1/environments/env-1/connect?ignored=true",- accessToken: "relay-access-token",- proofKey,- }).pipe(Effect.provide(browserCryptoLayer));- const issuedAt = decodeJwt(proof.proof).iat;- expect(issuedAt).toBeTypeOf("number");-- expect(- verifyDpopProof({- proof: proof.proof,- method: "POST",- url: "https://relay.example.test/v1/environments/env-1/connect",- expectedThumbprint: proof.thumbprint,- expectedAccessToken: "relay-access-token",- nowEpochSeconds: issuedAt!,- }),- ).toMatchObject({ ok: true });- }),- );-});diff --git a/apps/web/src/cloud/dpop.ts b/apps/web/src/cloud/dpop.tsdeleted file mode 100644index d0994955d..000000000--- a/apps/web/src/cloud/dpop.ts+++ /dev/null@@ -1,185 +0,0 @@-import {- computeDpopAccessTokenHash,- computeDpopJwkThumbprint,- DpopPublicJwk,-} from "@t3tools/shared/dpop";-import * as Crypto from "effect/Crypto";-import * as Data from "effect/Data";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";-import * as Schema from "effect/Schema";-import { importJWK, SignJWT, type JWK } from "jose";--export interface BrowserDpopKey {- readonly privateKey: CryptoKey;- readonly publicJwk: DpopPublicJwk;- readonly thumbprint: string;-}--export class BrowserDpopError extends Data.TaggedError("BrowserDpopError")<{- readonly message: string;- readonly cause?: unknown;-}> {}--const DPOP_DATABASE_NAME = "t3code:cloud-auth";-const DPOP_DATABASE_VERSION = 1;-const DPOP_KEY_STORE_NAME = "keys";-const DPOP_KEY_ID = "relay-dpop-proof-key";-const decodeDpopPublicJwk = Schema.decodeUnknownEffect(DpopPublicJwk);--export const browserCryptoLayer = 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));- }),- }),-);--function dpopError(message: string, cause?: unknown) {- return new BrowserDpopError({ message, ...(cause === undefined ? {} : { cause }) });-}--function openDpopDatabase(): Effect.Effect<IDBDatabase, BrowserDpopError> {- return Effect.callback<IDBDatabase, BrowserDpopError>((resume) => {- const request = indexedDB.open(DPOP_DATABASE_NAME, DPOP_DATABASE_VERSION);- request.addEventListener("error", () =>- resume(- Effect.fail(dpopError("Could not open DPoP key storage.", request.error ?? undefined)),- ),- );- request.addEventListener("upgradeneeded", () => {- if (!request.result.objectStoreNames.contains(DPOP_KEY_STORE_NAME)) {- request.result.createObjectStore(DPOP_KEY_STORE_NAME);- }- });- request.addEventListener("success", () => resume(Effect.succeed(request.result)));- });-}--export function readStoredBrowserDpopKey(): Effect.Effect<BrowserDpopKey | null, BrowserDpopError> {- if (typeof indexedDB === "undefined") {- return Effect.succeed(null);- }- return Effect.acquireUseRelease(- openDpopDatabase(),- (database) =>- Effect.callback<BrowserDpopKey | null, BrowserDpopError>((resume) => {- const request = database- .transaction(DPOP_KEY_STORE_NAME, "readonly")- .objectStore(DPOP_KEY_STORE_NAME)- .get(DPOP_KEY_ID);- request.addEventListener("error", () =>- resume(Effect.fail(dpopError("Could not read DPoP key.", request.error ?? undefined))),- );- request.addEventListener("success", () =>- resume(Effect.succeed((request.result as BrowserDpopKey | undefined) ?? null)),- );- }),- (database) => Effect.sync(() => database.close()),- );-}--export function writeStoredBrowserDpopKey(- key: BrowserDpopKey,-): Effect.Effect<void, BrowserDpopError> {- if (typeof indexedDB === "undefined") {- return Effect.void;- }- return Effect.acquireUseRelease(- openDpopDatabase(),- (database) =>- Effect.callback<void, BrowserDpopError>((resume) => {- const transaction = database.transaction(DPOP_KEY_STORE_NAME, "readwrite");- transaction.addEventListener("error", () =>- resume(- Effect.fail(dpopError("Could not write DPoP key.", transaction.error ?? undefined)),- ),- );- transaction.addEventListener("complete", () => resume(Effect.void));- transaction.objectStore(DPOP_KEY_STORE_NAME).put(key, DPOP_KEY_ID);- }),- (database) => Effect.sync(() => database.close()),- );-}--export const generateBrowserDpopKey = Effect.gen(function* () {- const generated = yield* Effect.tryPromise({- try: () =>- crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, [- "sign",- "verify",- ]) as Promise<CryptoKeyPair>,- catch: (cause) => dpopError("Could not generate DPoP proof key.", cause),- });- const privateJwk = yield* Effect.tryPromise({- try: () => crypto.subtle.exportKey("jwk", generated.privateKey),- catch: (cause) => dpopError("Could not export DPoP private key.", cause),- });- const publicJwk = yield* Effect.tryPromise({- try: () => crypto.subtle.exportKey("jwk", generated.publicKey),- catch: (cause) => dpopError("Could not export DPoP public key.", cause),- }).pipe(- Effect.flatMap((jwk) => decodeDpopPublicJwk(jwk)),- Effect.mapError((cause) =>- cause instanceof BrowserDpopError- ? cause- : dpopError("Generated DPoP public key is invalid.", cause),- ),- );- const privateKey = yield* Effect.tryPromise({- try: () => importJWK(privateJwk as JWK, "ES256", { extractable: false }) as Promise<CryptoKey>,- catch: (cause) => dpopError("Could not import DPoP private key.", cause),- });- return {- privateKey,- publicJwk,- thumbprint: computeDpopJwkThumbprint(publicJwk),- };-});--export function createBrowserDpopProof(input: {- readonly method: string;- readonly url: string;- readonly accessToken?: string;- readonly proofKey: BrowserDpopKey;-}): Effect.Effect<- { readonly proof: string; readonly thumbprint: string },- BrowserDpopError,- Crypto.Crypto-> {- return Effect.gen(function* () {- const normalizedUrl = yield* Effect.try({- try: () => new URL(input.url),- catch: (cause) => dpopError("Could not normalize DPoP proof URL.", cause),- });- normalizedUrl.search = "";- normalizedUrl.hash = "";- const jti = yield* Crypto.Crypto.pipe(- Effect.flatMap((crypto) => crypto.randomUUIDv4),- Effect.mapError((cause) => dpopError("Could not generate DPoP proof identifier.", cause)),- );- const proof = yield* Effect.tryPromise({- try: () =>- new SignJWT({- htm: input.method.toUpperCase(),- htu: normalizedUrl.toString(),- jti,- ...(input.accessToken ? { ath: computeDpopAccessTokenHash(input.accessToken) } : {}),- })- .setProtectedHeader({- typ: "dpop+jwt",- alg: "ES256",- jwk: input.proofKey.publicJwk,- })- .setIssuedAt()- .sign(input.proofKey.privateKey),- catch: (cause) => dpopError("Could not sign DPoP proof.", cause),- });- return { proof, thumbprint: input.proofKey.thumbprint };- });-}diff --git a/apps/web/src/cloud/linkEnvironment.test.ts b/apps/web/src/cloud/linkEnvironment.test.tsdeleted file mode 100644index 38e205bea..000000000--- a/apps/web/src/cloud/linkEnvironment.test.ts+++ /dev/null@@ -1,439 +0,0 @@-import {- type DesktopBridge,- EnvironmentId,- type RelayClientInstallProgressEvent,- WS_METHODS,-} from "@t3tools/contracts";-import { RelayWebClientId } from "@t3tools/contracts/relay";-import { describe, expect, it } from "@effect/vitest";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";-import * as Option from "effect/Option";-import * as Stream from "effect/Stream";-import * as SubscriptionRef from "effect/SubscriptionRef";-import { HttpClient } from "effect/unstable/http";-import { afterEach, beforeEach, vi } from "vite-plus/test";-import {- AVAILABLE_CONNECTION_STATE,- EnvironmentSupervisor,- type PreparedConnection,- PrimaryConnectionTarget,-} from "@t3tools/client-runtime/connection";-import { type RpcSession } from "@t3tools/client-runtime/rpc";-import { EnvironmentRegistry } from "@t3tools/client-runtime/connection";-import { ManagedRelay } from "@t3tools/client-runtime/relay";-import { remoteHttpClientLayer } from "@t3tools/client-runtime/rpc";-import { __resetDesktopPrimaryAuthForTests } from "../environments/primary/desktopAuth";--import {- collectCloudLinkTargets,- linkPrimaryEnvironmentToCloud,- listManagedCloudEnvironments,- normalizeRelayBaseUrl,- readPrimaryCloudLinkState,- type CloudLinkTarget,- unlinkPrimaryEnvironmentFromCloud,- updatePrimaryCloudPreferences,-} from "./linkEnvironment";--const TARGET: CloudLinkTarget = {- environmentId: "environment-1",- label: "Desktop",- httpBaseUrl: "http://127.0.0.1:3000",- wsBaseUrl: "ws://127.0.0.1:3000",-};--const relayClientInstallDialog = vi.hoisted(() => ({- requestConfirmation: vi.fn(),- reportProgress: vi.fn(),- finish: vi.fn(),-}));--vi.mock("./relayClientInstallDialog", () => ({- requestRelayClientInstallConfirmation: relayClientInstallDialog.requestConfirmation,- reportRelayClientInstallProgress: relayClientInstallDialog.reportProgress,- finishRelayClientInstall: relayClientInstallDialog.finish,-}));--const createProof = vi.fn(() => Effect.succeed("dpop-proof"));-const dpopSignerLayer = Layer.succeed(- ManagedRelay.ManagedRelayDpopSigner,- ManagedRelay.ManagedRelayDpopSigner.of({- thumbprint: Effect.succeed("thumbprint"),- createProof,- }),-);--function relayLayer() {- const http = remoteHttpClientLayer(globalThis.fetch);- return Layer.mergeAll(- http,- ManagedRelay.layer({- relayUrl: "https://relay.example.test",- clientId: RelayWebClientId,- }).pipe(Layer.provideMerge(dpopSignerLayer), Layer.provide(http)),- );-}--function registryLayer(options?: {- readonly status?: { readonly status: "available"; readonly version: string };- readonly installEvents?: ReadonlyArray<RelayClientInstallProgressEvent>;-}) {- return Layer.effect(- EnvironmentRegistry,- Effect.gen(function* () {- const client = {- [WS_METHODS.cloudGetRelayClientStatus]: () =>- Effect.succeed(options?.status ?? { status: "available", version: "2026.6.0" }),- [WS_METHODS.cloudInstallRelayClient]: () =>- Stream.fromIterable(options?.installEvents ?? []),- } as unknown as RpcSession["client"];- const session: RpcSession = {- client,- initialConfig: Effect.never,- ready: Effect.void,- probe: Effect.void,- closed: Effect.never,- };- const target = new PrimaryConnectionTarget({- environmentId: EnvironmentId.make(TARGET.environmentId),- label: TARGET.label,- httpBaseUrl: TARGET.httpBaseUrl,- wsBaseUrl: TARGET.wsBaseUrl,- });- const supervisor = EnvironmentSupervisor.of({- target,- state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),- session: yield* SubscriptionRef.make(Option.some(session)),- prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),- connect: Effect.void,- disconnect: Effect.void,- retryNow: Effect.void,- } satisfies EnvironmentSupervisor["Service"]);- const registry = {- run: <A, E, R>(_environmentId: EnvironmentId, effect: Effect.Effect<A, E, R>) =>- Effect.provideService(effect, EnvironmentSupervisor, supervisor),- runStream: <A, E, R>(_environmentId: EnvironmentId, stream: Stream.Stream<A, E, R>) =>- Stream.provideService(stream, EnvironmentSupervisor, supervisor),- } as unknown as EnvironmentRegistry["Service"];- return EnvironmentRegistry.of(registry);- }),- );-}--function services(options?: Parameters<typeof registryLayer>[0]) {- return Layer.mergeAll(relayLayer(), registryLayer(options));-}--function withServices<A, E>(- effect: Effect.Effect<- A,- E,- HttpClient.HttpClient | ManagedRelay.ManagedRelayClient | EnvironmentRegistry- >,- options?: Parameters<typeof registryLayer>[0],-) {- return effect.pipe(Effect.provide(services(options)));-}--function bodyText(body: BodyInit | null | undefined): string {- return body instanceof Uint8Array ? new TextDecoder().decode(body) : String(body ?? "");-}--beforeEach(() => {- vi.clearAllMocks();- vi.stubEnv("VITE_T3CODE_RELAY_URL", "https://relay.example.test");- relayClientInstallDialog.requestConfirmation.mockResolvedValue(true);-});--afterEach(() => {- __resetDesktopPrimaryAuthForTests();- vi.unstubAllGlobals();- vi.unstubAllEnvs();- vi.restoreAllMocks();-});--describe("web cloud link environment client", () => {- it("normalizes relay URLs and de-duplicates cloud link targets", () => {- expect(normalizeRelayBaseUrl(" https://relay.example.test/// ")).toBe(- "https://relay.example.test",- );- expect(normalizeRelayBaseUrl(" ")).toBeNull();- expect(- collectCloudLinkTargets({- primary: TARGET,- saved: [TARGET, { ...TARGET, environmentId: "environment-2" }],- }).map((target) => target.environmentId),- ).toEqual(["environment-1", "environment-2"]);- });-- it.effect("lists relay-managed environments through the typed relay client", () =>- Effect.gen(function* () {- const fetchMock = vi.fn().mockResolvedValue(- Response.json({- environments: [- {- environmentId: "environment-1",- label: "Desktop",- endpoint: {- httpBaseUrl: "https://desktop.example.test",- wsBaseUrl: "wss://desktop.example.test",- providerKind: "cloudflare_tunnel",- },- linkedAt: "2026-06-06T00:00:00.000Z",- },- ],- }),- );- vi.stubGlobal("fetch", fetchMock);-- const environments = yield* withServices(- listManagedCloudEnvironments({ clerkToken: "clerk-token" }),- );-- expect(environments).toHaveLength(1);- expect(fetchMock.mock.calls[0]?.[1]?.headers.authorization).toBe("Bearer clerk-token");- }),- );-- it.effect("reads primary cloud link state from the explicit target", () =>- Effect.gen(function* () {- const fetchMock = vi.fn().mockResolvedValue(- Response.json({- linked: true,- cloudUserId: "user-1",- relayUrl: "https://relay.example.test",- relayIssuer: "https://relay.example.test",- managedTunnelActive: true,- publishAgentActivity: false,- }),- );- vi.stubGlobal("fetch", fetchMock);-- const state = yield* withServices(readPrimaryCloudLinkState({ target: TARGET }));-- expect(Option.fromNullishOr(state)).toEqual(- Option.some({- linked: true,- cloudUserId: "user-1",- relayUrl: "https://relay.example.test",- relayIssuer: "https://relay.example.test",- managedTunnelActive: true,- publishAgentActivity: false,- }),- );- expect(String(fetchMock.mock.calls[0]?.[0])).toBe(- "http://127.0.0.1:3000/api/connect/link-state",- );- }),- );-- it.effect("uses desktop bearer auth for primary cloud link state", () =>- Effect.gen(function* () {- const fetchMock = vi.fn().mockResolvedValue(- Response.json({- linked: true,- cloudUserId: "user-1",- relayUrl: "https://relay.example.test",- relayIssuer: "https://relay.example.test",- managedTunnelActive: true,- publishAgentActivity: false,- }),- );- vi.stubGlobal("fetch", fetchMock);- vi.stubGlobal("window", {- location: { origin: "t3code://app" },- desktopBridge: {- getLocalEnvironmentBearerToken: vi.fn().mockResolvedValue("desktop-bearer-token"),- } as unknown as DesktopBridge,- });-- yield* withServices(readPrimaryCloudLinkState({ target: TARGET }));-- const request = new Request(fetchMock.mock.calls[0]?.[0], fetchMock.mock.calls[0]?.[1]);- expect(request.credentials).not.toBe("include");- expect(request.headers.get("authorization")).toBe("Bearer desktop-bearer-token");- }),- );-- it.effect("updates agent activity publishing for the explicit primary target", () =>- Effect.gen(function* () {- const fetchMock = vi.fn().mockResolvedValue(- Response.json({- linked: true,- cloudUserId: "user-1",- relayUrl: "https://relay.example.test",- relayIssuer: "https://relay.example.test",- managedTunnelActive: true,- publishAgentActivity: true,- }),- );- vi.stubGlobal("fetch", fetchMock);-- const state = yield* withServices(- updatePrimaryCloudPreferences({- target: TARGET,- publishAgentActivity: true,- }),- );-- expect(state.publishAgentActivity).toBe(true);- expect(String(fetchMock.mock.calls[0]?.[0])).toBe(- "http://127.0.0.1:3000/api/connect/preferences",- );- expect(fetchMock.mock.calls[0]?.[1]?.method).toBe("POST");- // @effect-diagnostics-next-line preferSchemaOverJson:off- expect(JSON.parse(bodyText(fetchMock.mock.calls[0]?.[1]?.body))).toEqual({- publishAgentActivity: true,- });- }),- );-- it.effect("links an available primary environment without invoking installation", () =>- Effect.gen(function* () {- const fetchMock = vi- .fn()- .mockResolvedValueOnce(- Response.json({- challenge: "challenge",- expiresAt: "2026-06-06T00:05:00.000Z",- }),- )- .mockResolvedValueOnce(Response.json("signed-proof"))- .mockResolvedValueOnce(- Response.json({- ok: true,- environmentId: TARGET.environmentId,- endpoint: {- httpBaseUrl: "https://desktop.example.test",- wsBaseUrl: "wss://desktop.example.test",- providerKind: "cloudflare_tunnel",- },- endpointRuntime: null,- relayIssuer: "https://relay.example.test",- cloudUserId: "user-1",- environmentCredential: "environment-credential",- cloudMintPublicKey: "public-key",- }),- )- .mockResolvedValueOnce(- Response.json({ ok: true, endpointRuntimeStatus: { status: "configured" } }),- );- vi.stubGlobal("fetch", fetchMock);-- yield* withServices(- linkPrimaryEnvironmentToCloud({- target: TARGET,- clerkToken: "clerk-token",- }),- );-- expect(relayClientInstallDialog.requestConfirmation).not.toHaveBeenCalled();- expect(String(fetchMock.mock.calls[1]?.[0])).toBe(- "http://127.0.0.1:3000/api/connect/link-proof",- );- // @effect-diagnostics-next-line preferSchemaOverJson:off- expect(JSON.parse(bodyText(fetchMock.mock.calls[1]?.[1]?.body))).toMatchObject({- challenge: "challenge",- endpoint: {- httpBaseUrl: TARGET.httpBaseUrl,- wsBaseUrl: TARGET.wsBaseUrl,- },- });- }),- );-- it.effect("links publish-only without a managed tunnel", () =>- Effect.gen(function* () {- const fetchMock = vi- .fn()- .mockResolvedValueOnce(- Response.json({- challenge: "challenge",- expiresAt: "2026-06-06T00:05:00.000Z",- }),- )- .mockResolvedValueOnce(Response.json("signed-proof"))- .mockResolvedValueOnce(- Response.json({- ok: true,- environmentId: TARGET.environmentId,- endpoint: {- httpBaseUrl: TARGET.httpBaseUrl,- wsBaseUrl: TARGET.wsBaseUrl,- providerKind: "manual",- },- endpointRuntime: null,- relayIssuer: "https://relay.example.test",- cloudUserId: "user-1",- environmentCredential: "environment-credential",- cloudMintPublicKey: "public-key",- }),- )- .mockResolvedValueOnce(- Response.json({ ok: true, endpointRuntimeStatus: { status: "disabled" } }),- );- vi.stubGlobal("fetch", fetchMock);-- yield* withServices(- linkPrimaryEnvironmentToCloud({- target: TARGET,- clerkToken: "clerk-token",- mode: "publish_only",- }),- );-- // @effect-diagnostics-next-line preferSchemaOverJson:off- expect(JSON.parse(bodyText(fetchMock.mock.calls[0]?.[1]?.body))).toMatchObject({- managedTunnelsEnabled: false,- });- // @effect-diagnostics-next-line preferSchemaOverJson:off- expect(JSON.parse(bodyText(fetchMock.mock.calls[1]?.[1]?.body))).toMatchObject({- endpoint: { providerKind: "manual" },- });- }),- );-- it.effect("installs a missing relay client before linking", () =>- Effect.gen(function* () {- vi.stubGlobal("fetch", vi.fn().mockResolvedValue(Response.json({ malformed: true })));-- yield* withServices(- linkPrimaryEnvironmentToCloud({- target: TARGET,- clerkToken: "clerk-token",- }),- {- status: { status: "available", version: "2026.6.0" },- installEvents: [],- },- ).pipe(Effect.flip);-- expect(relayClientInstallDialog.requestConfirmation).not.toHaveBeenCalled();- }),- );-- it.effect("unlinks locally before revoking the relay record", () =>- Effect.gen(function* () {- const fetchMock = vi- .fn()- .mockResolvedValueOnce(- Response.json({ ok: true, endpointRuntimeStatus: { status: "disabled" } }),- )- .mockResolvedValueOnce(Response.json({ ok: true }));- vi.stubGlobal("fetch", fetchMock);-- yield* withServices(- unlinkPrimaryEnvironmentFromCloud({- target: TARGET,- clerkToken: "clerk-token",- }),- );-- expect(String(fetchMock.mock.calls[0]?.[0])).toBe("http://127.0.0.1:3000/api/connect/unlink");- expect(String(fetchMock.mock.calls[1]?.[0])).toContain(- `/v1/client/environment-links/${TARGET.environmentId}`,- );- }),- );-});diff --git a/apps/web/src/cloud/linkEnvironment.ts b/apps/web/src/cloud/linkEnvironment.tsdeleted file mode 100644index e65a72329..000000000--- a/apps/web/src/cloud/linkEnvironment.ts+++ /dev/null@@ -1,494 +0,0 @@-import * as Data from "effect/Data";-import * as Effect from "effect/Effect";-import * as Option from "effect/Option";-import * as Schema from "effect/Schema";-import * as Stream from "effect/Stream";-import { HttpClient } from "effect/unstable/http";-import {- EnvironmentCloudEndpointUnavailableError,- type EnvironmentCloudLinkStateResult,- EnvironmentHttpBadRequestError,- EnvironmentHttpConflictError,- EnvironmentHttpForbiddenError,- EnvironmentHttpInternalServerError,- EnvironmentHttpUnauthorizedError,- EnvironmentId,- WS_METHODS,-} from "@t3tools/contracts";-import {- type RelayClientDeviceRecord,- type RelayClientEnvironmentRecord,- type RelayEnvironmentLinkResponse,- type RelayProtectedError as RelayProtectedErrorType,- type RelayManagedEndpointProviderKind,-} from "@t3tools/contracts/relay";-import { EnvironmentRegistry } from "@t3tools/client-runtime/connection";-import { request, runStream } from "@t3tools/client-runtime/rpc";-import { makeEnvironmentHttpApiClient } from "@t3tools/client-runtime/rpc";-import { ManagedRelay } from "@t3tools/client-runtime/relay";--import {- readPrimaryEnvironmentDescriptor,- readPrimaryEnvironmentTarget,-} from "../environments/primary";-import { primaryEnvironmentHttpLayer } from "../environments/primary/httpLayer";-import { resolveCloudPublicConfig } from "./publicConfig";-import {- finishRelayClientInstall,- reportRelayClientInstallProgress,- requestRelayClientInstallConfirmation,-} from "./relayClientInstallDialog";--export function normalizeRelayBaseUrl(value: string | null | undefined): string | null {- const trimmed = value?.trim();- if (!trimmed) {- return null;- }- return trimmed.replace(/\/+$/g, "");-}--function relayUrl(): string | null {- return resolveCloudPublicConfig().relayUrl;-}--export class CloudEnvironmentLinkError extends Data.TaggedError("CloudEnvironmentLinkError")<{- readonly message: string;- readonly cause?: unknown;- readonly traceId?: string;-}> {}--const relayClientRpcError = (message: string) => (cause: unknown) =>- new CloudEnvironmentLinkError({- message,- cause,- });--function ensureRelayClientAvailable(- environmentId: EnvironmentId,-): Effect.Effect<void, CloudEnvironmentLinkError, EnvironmentRegistry> {- return Effect.gen(function* () {- const registry = yield* EnvironmentRegistry;- const status = yield* registry- .run(environmentId, request(WS_METHODS.cloudGetRelayClientStatus, {}))- .pipe(Effect.mapError(relayClientRpcError("Could not check relay client availability.")));- if (status.status === "available") return;- if (status.status === "unsupported") {- return yield* new CloudEnvironmentLinkError({- message: `Akeru Bot cannot install the relay client automatically on ${status.platform}-${status.arch}.`,- });- }-- const confirmed = yield* Effect.tryPromise({- try: () => requestRelayClientInstallConfirmation(status.version),- catch: relayClientRpcError("Could not confirm relay client installation."),- });- if (!confirmed) {- return yield* new CloudEnvironmentLinkError({- message: "Relay client installation was cancelled.",- });- }-- const installed = yield* registry- .runStream(- environmentId,- runStream(WS_METHODS.cloudInstallRelayClient, {}).pipe(- Stream.tap((event) => Effect.sync(() => reportRelayClientInstallProgress(event))),- ),- )- .pipe(- Stream.runLast,- Effect.mapError(relayClientRpcError("Could not install the relay client.")),- Effect.ensuring(Effect.sync(finishRelayClientInstall)),- );- if (Option.isNone(installed) || installed.value.type !== "complete") {- return yield* new CloudEnvironmentLinkError({- message: "The relay client install completed without a final status.",- });- }- const installedStatus = installed.value.status;- if (installedStatus.status !== "available") {- return yield* new CloudEnvironmentLinkError({- message:- installedStatus.status === "unsupported"- ? `Akeru Bot cannot install the relay client automatically on ${installedStatus.platform}-${installedStatus.arch}.`- : "The relay client is still unavailable after installation.",- });- }- });-}--const isEnvironmentCloudApiError = Schema.is(- Schema.Union([- EnvironmentHttpBadRequestError,- EnvironmentHttpUnauthorizedError,- EnvironmentHttpForbiddenError,- EnvironmentHttpConflictError,- EnvironmentHttpInternalServerError,- EnvironmentCloudEndpointUnavailableError,- ]),-);--function relayProtectedErrorMessage(error: RelayProtectedErrorType): string {- switch (error._tag) {- case "RelayAuthInvalidError":- switch (error.reason) {- case "missing_bearer":- case "invalid_bearer":- return "Relay rejected the cloud session token.";- case "invalid_dpop":- return "Relay rejected the DPoP proof.";- case "not_authorized":- return "Relay rejected the authenticated request.";- }- case "RelayEnvironmentLinkProofExpiredError":- return "Relay rejected an expired environment link proof.";- case "RelayEnvironmentLinkProofInvalidError":- return `Relay rejected the environment link proof (${error.reason}).`;- case "RelayEnvironmentConnectNotAuthorizedError":- // "Not authorized" covers non-auth causes too; surface the reason so a- // missing link doesn't read as a credential problem.- if (error.reason === "environment_link_not_found") {- return "Relay has no active link for this environment. The environment server may not have re-established its link yet.";- }- return error.reason- ? `Relay rejected the environment connection request (${error.reason}).`- : "Relay rejected the environment connection request.";- case "RelayEnvironmentEndpointUnavailableError":- return `Relay could not reach the environment endpoint (${error.reason}).`;- case "RelayEnvironmentEndpointTimedOutError":- return "Relay timed out while contacting the environment endpoint.";- case "RelayEnvironmentLinkFailedError":- return `Relay could not link the environment (${error.reason}).`;- case "RelayEnvironmentLinkUnavailableError":- return `Relay cannot provision the managed endpoint (${error.reason}).`;- case "RelayEnvironmentLinkLimitExceededError":- return `Relay refused the link: this account already has its maximum of ${error.maxTunnels} managed tunnels. Unlink an environment to free one up.`;- case "RelayAgentActivityPublishProofExpiredError":- return "Relay rejected an expired agent activity publish proof.";- case "RelayAgentActivityPublishProofInvalidError":- return `Relay rejected the agent activity publish proof (${error.reason}).`;- case "RelayInternalError":- return `Relay encountered an internal error (${error.reason}).`;- }-}--function decodedRelayClientError(message: string) {- return (cause: ManagedRelay.ManagedRelayClientError) => {- const relayError =- cause._tag === "ManagedRelayRequestFailedError" ? cause.relayError : undefined;- const traceId = cause._tag === "ManagedRelayRequestFailedError" ? cause.traceId : undefined;- const detail = relayError ? relayProtectedErrorMessage(relayError) : null;- return new CloudEnvironmentLinkError({- message: detail ? `${message}: ${detail}` : message,- cause,- ...(traceId ? { traceId } : {}),- });- };-}--function findEnvironmentCloudApiError(cause: unknown): { readonly message: string } | null {- if (isEnvironmentCloudApiError(cause)) {- return cause;- }- if (typeof cause !== "object" || cause === null) {- return null;- }- return "cause" in cause ? findEnvironmentCloudApiError(cause.cause) : null;-}--const environmentApiError = (message: string) => (cause: unknown) => {- const environmentError = findEnvironmentCloudApiError(cause);- return new CloudEnvironmentLinkError({- message: environmentError- ? `${message.replace(/[.:]$/, "")}: ${environmentError.message}`- : message,- cause,- });-};--function endpointOrigin(httpBaseUrl: string) {- const url = new URL(httpBaseUrl);- return {- localHttpHost: "127.0.0.1",- localHttpPort: Number(url.port || (url.protocol === "https:" ? 443 : 80)),- };-}--const MANAGED_ENDPOINT_PROVIDER_KIND =- "cloudflare_tunnel" satisfies RelayManagedEndpointProviderKind;--function ensureLinkedEnvironmentMatches(input: {- readonly expectedEnvironmentId: string;- readonly expectedProviderKind: RelayManagedEndpointProviderKind;- readonly link: RelayEnvironmentLinkResponse;-}): Effect.Effect<void, CloudEnvironmentLinkError> {- if (input.link.environmentId !== input.expectedEnvironmentId) {- return new CloudEnvironmentLinkError({- message: "Relay returned credentials for a different environment.",- });- }- if (input.link.endpoint.providerKind !== input.expectedProviderKind) {- return new CloudEnvironmentLinkError({- message: "Relay returned credentials for a different endpoint provider.",- });- }- return Effect.void;-}--export interface CloudLinkTarget {- readonly environmentId: string;- readonly label: string;- readonly httpBaseUrl: string;- readonly wsBaseUrl: string;-}--export type CloudLinkState = EnvironmentCloudLinkStateResult;--export function collectCloudLinkTargets(input: {- readonly primary: CloudLinkTarget | null;- readonly saved: ReadonlyArray<CloudLinkTarget>;-}): ReadonlyArray<CloudLinkTarget> {- const byId = new Map<string, CloudLinkTarget>();- if (input.primary) {- byId.set(input.primary.environmentId, input.primary);- }- for (const environment of input.saved) {- if (!byId.has(environment.environmentId)) {- byId.set(environment.environmentId, environment);- }- }- return [...byId.values()];-}--export function readPrimaryCloudLinkTarget(): CloudLinkTarget | null {- const descriptor = readPrimaryEnvironmentDescriptor();- const target = readPrimaryEnvironmentTarget();- if (!descriptor || !target) {- return null;- }- return {- environmentId: descriptor.environmentId,- label: descriptor.label,- httpBaseUrl: target.target.httpBaseUrl,- wsBaseUrl: target.target.wsBaseUrl,- };-}--export function listManagedCloudEnvironments(input: {- readonly clerkToken: string;-}): Effect.Effect<- ReadonlyArray<RelayClientEnvironmentRecord>,- CloudEnvironmentLinkError,- ManagedRelay.ManagedRelayClient-> {- return Effect.gen(function* () {- const configuredRelayUrl = relayUrl();- if (!configuredRelayUrl) {- return yield* new CloudEnvironmentLinkError({- message: "T3CODE_RELAY_URL is not configured.",- });- }- const relayClient = yield* ManagedRelay.ManagedRelayClient;- return yield* relayClient- .listEnvironments({- clerkToken: input.clerkToken,- })- .pipe(- Effect.mapError(- (cause) =>- new CloudEnvironmentLinkError({- message: "Could not list relay-managed environments.",- cause,- }),- ),- );- });-}--export function listCloudDevices(input: {- readonly clerkToken: string;-}): Effect.Effect<- ReadonlyArray<RelayClientDeviceRecord>,- CloudEnvironmentLinkError,- ManagedRelay.ManagedRelayClient-> {- return Effect.gen(function* () {- if (!relayUrl()) {- return yield* new CloudEnvironmentLinkError({- message: "T3CODE_RELAY_URL is not configured.",- });- }- const relayClient = yield* ManagedRelay.ManagedRelayClient;- return yield* relayClient.listDevices({ clerkToken: input.clerkToken }).pipe(- Effect.mapError(- (cause) =>- new CloudEnvironmentLinkError({- message: "Could not list cloud devices.",- cause,- }),- ),- );- });-}--export function readPrimaryCloudLinkState(input: {- readonly target: CloudLinkTarget;-}): Effect.Effect<CloudLinkState | null, CloudEnvironmentLinkError, HttpClient.HttpClient> {- return Effect.gen(function* () {- const client = yield* makeEnvironmentHttpApiClient(input.target.httpBaseUrl);- return yield* client.connect- .linkState({ headers: {} })- .pipe(Effect.mapError(environmentApiError("Could not read environment cloud link state.")));- }).pipe(Effect.provide(primaryEnvironmentHttpLayer));-}--export function updatePrimaryCloudPreferences(input: {- readonly target: CloudLinkTarget;- readonly publishAgentActivity: boolean;-}): Effect.Effect<CloudLinkState, CloudEnvironmentLinkError, HttpClient.HttpClient> {- return Effect.gen(function* () {- const client = yield* makeEnvironmentHttpApiClient(input.target.httpBaseUrl);- return yield* client.connect- .preferences({- headers: {},- payload: input,- })- .pipe(- Effect.mapError(environmentApiError("Could not update environment cloud preferences.")),- );- }).pipe(Effect.provide(primaryEnvironmentHttpLayer));-}--export function unlinkPrimaryEnvironmentFromCloud(input: {- readonly target: CloudLinkTarget;- readonly clerkToken: string | null;-}): Effect.Effect<- void,- CloudEnvironmentLinkError,- HttpClient.HttpClient | ManagedRelay.ManagedRelayClient-> {- return Effect.gen(function* () {- const client = yield* makeEnvironmentHttpApiClient(input.target.httpBaseUrl);- yield* client.connect- .unlink({ headers: {} })- .pipe(Effect.mapError(environmentApiError("Could not unlink the environment from cloud.")));-- const configuredRelayUrl = relayUrl();- if (configuredRelayUrl && input.clerkToken) {- const relayClient = yield* ManagedRelay.ManagedRelayClient;- yield* relayClient- .unlinkEnvironment({- clerkToken: input.clerkToken,- environmentId: EnvironmentId.make(input.target.environmentId),- })- .pipe(- Effect.catch((cause) =>- Effect.logWarning("Could not revoke cloud environment link after local unlink.", {- cause,- }),- ),- );- }- }).pipe(Effect.provide(primaryEnvironmentHttpLayer));-}--// "publish_only" links the environment to the relay for agent-activity-// publishing alone: no managed tunnel is provisioned, so it can be toggled-// independently of T3 Connect while clients reach the environment out of band.-export type CloudLinkMode = "managed" | "publish_only";--const PUBLISH_ONLY_PROVIDER_KIND = "manual" satisfies RelayManagedEndpointProviderKind;--export function linkPrimaryEnvironmentToCloud(input: {- readonly target: CloudLinkTarget;- readonly clerkToken: string;- readonly mode?: CloudLinkMode;-}): Effect.Effect<- void,- CloudEnvironmentLinkError,- EnvironmentRegistry | HttpClient.HttpClient | ManagedRelay.ManagedRelayClient-> {- return Effect.gen(function* () {- const configuredRelayUrl = relayUrl();- if (!configuredRelayUrl) {- return yield* new CloudEnvironmentLinkError({- message: "T3CODE_RELAY_URL is not configured.",- });- }- const managedTunnelsEnabled = (input.mode ?? "managed") === "managed";- const providerKind = managedTunnelsEnabled- ? MANAGED_ENDPOINT_PROVIDER_KIND- : PUBLISH_ONLY_PROVIDER_KIND;- const relayClient = yield* ManagedRelay.ManagedRelayClient;- const environmentClient = yield* makeEnvironmentHttpApiClient(input.target.httpBaseUrl);- if (managedTunnelsEnabled) {- yield* ensureRelayClientAvailable(EnvironmentId.make(input.target.environmentId));- }-- const challenge = yield* relayClient- .createEnvironmentLinkChallenge({- clerkToken: input.clerkToken,- payload: {- notificationsEnabled: true,- liveActivitiesEnabled: true,- managedTunnelsEnabled,- },- })- .pipe(- Effect.mapError(- decodedRelayClientError(- `${configuredRelayUrl}/v1/client/environment-link-challenges failed`,- ),- ),- );- const proof = yield* environmentClient.connect- .linkProof({- headers: {},- payload: {- challenge: challenge.challenge,- relayIssuer: configuredRelayUrl,- endpoint: {- httpBaseUrl: input.target.httpBaseUrl,- wsBaseUrl: input.target.wsBaseUrl,- providerKind,- },- origin: endpointOrigin(input.target.httpBaseUrl),- },- })- .pipe(Effect.mapError(environmentApiError("Could not obtain environment link proof.")));- const link = yield* relayClient- .linkEnvironment({- clerkToken: input.clerkToken,- payload: {- proof,- notificationsEnabled: true,- liveActivitiesEnabled: true,- managedTunnelsEnabled,- },- })- .pipe(- Effect.mapError(- decodedRelayClientError(`${configuredRelayUrl}/v1/client/environment-links failed`),- ),- );- yield* ensureLinkedEnvironmentMatches({- expectedEnvironmentId: input.target.environmentId,- expectedProviderKind: providerKind,- link,- });-- yield* environmentClient.connect- .relayConfig({- headers: {},- payload: {- relayUrl: configuredRelayUrl,- relayIssuer: link.relayIssuer,- cloudUserId: link.cloudUserId,- environmentCredential: link.environmentCredential,- cloudMintPublicKey: link.cloudMintPublicKey,- endpointRuntime: link.endpointRuntime,- },- })- .pipe(Effect.mapError(environmentApiError("Could not configure environment relay access.")));- }).pipe(Effect.provide(primaryEnvironmentHttpLayer));-}diff --git a/apps/web/src/cloud/linkEnvironmentAtoms.ts b/apps/web/src/cloud/linkEnvironmentAtoms.tsdeleted file mode 100644index 1094e860e..000000000--- a/apps/web/src/cloud/linkEnvironmentAtoms.ts+++ /dev/null@@ -1,46 +0,0 @@-import {- createAtomCommandScheduler,- createRuntimeCommand,-} from "@t3tools/client-runtime/state/runtime";--import { connectionAtomRuntime } from "../connection/runtime";-import {- linkPrimaryEnvironmentToCloud,- type CloudLinkMode,- type CloudLinkTarget,- unlinkPrimaryEnvironmentFromCloud,- updatePrimaryCloudPreferences,-} from "./linkEnvironment";--const cloudLinkScheduler = createAtomCommandScheduler();-const cloudLinkConcurrency = {- mode: "serial" as const,- key: (input: { readonly target: CloudLinkTarget }) => input.target.environmentId,-};--export const linkPrimaryEnvironment = createRuntimeCommand(connectionAtomRuntime, {- label: "web:cloud:link-primary-environment",- scheduler: cloudLinkScheduler,- concurrency: cloudLinkConcurrency,- execute: (input: {- readonly target: CloudLinkTarget;- readonly clerkToken: string;- readonly mode?: CloudLinkMode;- }) => linkPrimaryEnvironmentToCloud(input),-});--export const unlinkPrimaryEnvironment = createRuntimeCommand(connectionAtomRuntime, {- label: "web:cloud:unlink-primary-environment",- scheduler: cloudLinkScheduler,- concurrency: cloudLinkConcurrency,- execute: (input: { readonly target: CloudLinkTarget; readonly clerkToken: string | null }) =>- unlinkPrimaryEnvironmentFromCloud(input),-});--export const updatePrimaryEnvironmentPreferences = createRuntimeCommand(connectionAtomRuntime, {- label: "web:cloud:update-primary-environment-preferences",- scheduler: cloudLinkScheduler,- concurrency: cloudLinkConcurrency,- execute: (input: { readonly target: CloudLinkTarget; readonly publishAgentActivity: boolean }) =>- updatePrimaryCloudPreferences(input),-});diff --git a/apps/web/src/cloud/managedAuth.test.ts b/apps/web/src/cloud/managedAuth.test.tsdeleted file mode 100644index aa29a5967..000000000--- a/apps/web/src/cloud/managedAuth.test.ts+++ /dev/null@@ -1,55 +0,0 @@-import { managedRelaySessionAtom, setManagedRelaySession } from "@t3tools/client-runtime/relay";-import { afterEach, describe, expect, it, vi } from "vite-plus/test";--import { appAtomRegistry } from "../rpc/atomRegistry";-import {- activateManagedRelayAuthentication,- deactivateManagedRelayAuthentication,- readManagedRelayClerkToken,-} from "./managedAuth";--vi.mock("@clerk/react", () => ({- useAuth: vi.fn(),-}));--vi.mock("../lib/runtime", () => ({- runtime: {- runPromiseExit: vi.fn(),- },-}));--vi.mock("../connection/catalog", () => ({- environmentCatalog: {- removeRelayEnvironments: {},- },-}));--afterEach(() => {- deactivateManagedRelayAuthentication();-});--describe("managed relay authentication", () => {- it("clears all token access synchronously before account cleanup can fail", async () => {- activateManagedRelayAuthentication("account-1", async () => "account-1-token");- expect(appAtomRegistry.get(managedRelaySessionAtom)?.accountId).toBe("account-1");- expect(await readManagedRelayClerkToken()).toBe("account-1-token");-- deactivateManagedRelayAuthentication();- const cleanup = Promise.reject(new Error("Persistence removal failed.")).catch(() => undefined);-- expect(appAtomRegistry.get(managedRelaySessionAtom)).toBeNull();- expect(await readManagedRelayClerkToken()).toBeNull();- await cleanup;- });-- it("replaces an existing account session atomically", () => {- setManagedRelaySession(appAtomRegistry, {- accountId: "account-1",- readClerkToken: async () => "account-1-token",- });-- activateManagedRelayAuthentication("account-2", async () => "account-2-token");-- expect(appAtomRegistry.get(managedRelaySessionAtom)?.accountId).toBe("account-2");- });-});diff --git a/apps/web/src/cloud/managedAuth.tsx b/apps/web/src/cloud/managedAuth.tsxdeleted file mode 100644index 2f6312145..000000000--- a/apps/web/src/cloud/managedAuth.tsx+++ /dev/null@@ -1,116 +0,0 @@-import { useAuth } from "@clerk/react";-import { ManagedRelay, setManagedRelaySession } from "@t3tools/client-runtime/relay";-import {- reportAtomCommandResult,- settleAsyncResult,- settlePromise,-} from "@t3tools/client-runtime/state/runtime";-import * as Effect from "effect/Effect";-import { useEffect, useRef, type ReactNode } from "react";--import { environmentCatalog } from "../connection/catalog";-import { runtime } from "../lib/runtime";-import { appAtomRegistry } from "../rpc/atomRegistry";-import { useAtomCommand } from "../state/use-atom-command";-import { resolveRelayClerkTokenOptions } from "./publicConfig";--let relayTokenProvider: (() => Promise<string | null>) | null = null;--export async function readManagedRelayClerkToken(): Promise<string | null> {- return relayTokenProvider?.() ?? null;-}--export function deactivateManagedRelayAuthentication(): void {- relayTokenProvider = null;- setManagedRelaySession(appAtomRegistry, null);-}--export function activateManagedRelayAuthentication(- accountId: string,- readClerkToken: () => Promise<string | null>,-): void {- relayTokenProvider = readClerkToken;- setManagedRelaySession(appAtomRegistry, {- accountId,- readClerkToken,- });-}--export function ManagedRelayAuthProvider({ children }: { readonly children: ReactNode }) {- const { getToken, isLoaded, isSignedIn, userId } = useAuth({- treatPendingAsSignedOut: false,- });- const removeRelayEnvironments = useAtomCommand(environmentCatalog.removeRelayEnvironments, {- reportFailure: false,- reportDefect: false,- });- const observedAccountRef = useRef<string | null | undefined>(undefined);- const accountTransitionRef = useRef<Promise<void> | null>(null);-- useEffect(() => {- if (!isLoaded) {- return;- }-- let cancelled = false;- const previousAccount = observedAccountRef.current;- const nextAccount = isSignedIn && userId ? userId : null;- observedAccountRef.current = nextAccount;-- const queueAccountCleanup = () => {- const previousTransition = accountTransitionRef.current ?? Promise.resolve();- accountTransitionRef.current = previousTransition.then(async () => {- const results = await Promise.all([- removeRelayEnvironments(),- settleAsyncResult(() =>- runtime.runPromiseExit(- ManagedRelay.ManagedRelayClient.pipe(- Effect.flatMap((client) => client.resetTokenCache),- ),- ),- ),- ]);- for (const result of results) {- reportAtomCommandResult(result, { label: "cloud account cleanup" });- }- });- return accountTransitionRef.current;- };-- if (!isSignedIn || !userId) {- deactivateManagedRelayAuthentication();- if (previousAccount !== null) {- void queueAccountCleanup();- }- } else {- const tokenProvider = () => getToken(resolveRelayClerkTokenOptions());- const activateSession = () => {- if (!cancelled) {- activateManagedRelayAuthentication(userId, tokenProvider);- }- };- const activateAfterTransition = (transition: Promise<void>) => {- void (async () => {- const result = await settlePromise(async () => {- await transition;- activateSession();- });- reportAtomCommandResult(result, { label: "cloud account activation" });- })();- };- if (previousAccount !== undefined && previousAccount !== null && previousAccount !== userId) {- deactivateManagedRelayAuthentication();- activateAfterTransition(queueAccountCleanup());- } else {- activateAfterTransition(accountTransitionRef.current ?? Promise.resolve());- }- }- return () => {- cancelled = true;- };- }, [getToken, isLoaded, isSignedIn, removeRelayEnvironments, userId]);-- useEffect(() => () => deactivateManagedRelayAuthentication(), []);-- return children;-}diff --git a/apps/web/src/cloud/managedRelayLayer.ts b/apps/web/src/cloud/managedRelayLayer.tsdeleted file mode 100644index 52f9b6496..000000000--- a/apps/web/src/cloud/managedRelayLayer.ts+++ /dev/null@@ -1,82 +0,0 @@-import { ManagedRelay } from "@t3tools/client-runtime/relay";-import { RelayWebClientId } from "@t3tools/contracts/relay";-import * as Crypto from "effect/Crypto";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";-import * as Semaphore from "effect/Semaphore";--import {- createBrowserDpopProof,- generateBrowserDpopKey,- readStoredBrowserDpopKey,- writeStoredBrowserDpopKey,- type BrowserDpopKey,-} from "./dpop";--export const relayDpopSignerLayer = Layer.effect(- ManagedRelay.ManagedRelayDpopSigner,- Effect.gen(function* () {- const crypto = yield* Crypto.Crypto;- const keyLoadSemaphore = yield* Semaphore.make(1);- let loadedKey: BrowserDpopKey | null = null;- const loadOrCreateBrowserDpopKey = keyLoadSemaphore.withPermit(- Effect.gen(function* () {- if (loadedKey) {- return loadedKey;- }- const stored = yield* readStoredBrowserDpopKey();- if (stored) {- loadedKey = stored;- return stored;- }- const generated = yield* generateBrowserDpopKey;- yield* writeStoredBrowserDpopKey(generated);- loadedKey = generated;- return generated;- }),- );-- return ManagedRelay.ManagedRelayDpopSigner.of({- thumbprint: loadOrCreateBrowserDpopKey.pipe(- Effect.map((proofKey) => proofKey.thumbprint),- Effect.mapError(- (error) =>- new ManagedRelay.ManagedRelayDpopKeyLoadError({- keyStore: "indexed-db",- cause: error,- }),- ),- Effect.withSpan("web.managedRelayDpopSigner.loadThumbprint"),- ),- createProof: Effect.fn("web.managedRelayDpopSigner.createProof")(function* (input) {- const proofKey = yield* loadOrCreateBrowserDpopKey.pipe(- Effect.mapError(- (error) =>- new ManagedRelay.ManagedRelayDpopProofCreationError({- method: input.method,- url: input.url,- cause: error,- }),- ),- );- return yield* createBrowserDpopProof({ ...input, proofKey }).pipe(- Effect.provideService(Crypto.Crypto, crypto),- Effect.map((proof) => proof.proof),- Effect.mapError(- (error) =>- new ManagedRelay.ManagedRelayDpopProofCreationError({- method: input.method,- url: input.url,- cause: error,- }),- ),- );- }),- });- }),-);--export const managedRelayClientLayer = (relayUrl: string) =>- ManagedRelay.layer({ relayUrl, clientId: RelayWebClientId }).pipe(- Layer.provideMerge(relayDpopSignerLayer),- );diff --git a/apps/web/src/cloud/managedRelayState.ts b/apps/web/src/cloud/managedRelayState.tsdeleted file mode 100644index 9a56bde88..000000000--- a/apps/web/src/cloud/managedRelayState.ts+++ /dev/null@@ -1,123 +0,0 @@-import { useAtomValue } from "@effect/atom-react";-import {- createManagedRelayQueryManager,- deregisterManagedRelayEnvironment,- ManagedRelay,- managedRelaySessionAtom,- readManagedRelaySnapshotState,-} from "@t3tools/client-runtime/relay";-import {- createAtomCommandScheduler,- createRuntimeCommand,-} from "@t3tools/client-runtime/state/runtime";-import type {- RelayClientDeviceRecord,- RelayClientEnvironmentRecord,-} from "@t3tools/contracts/relay";-import type { EnvironmentId } from "@t3tools/contracts";-import * as Context from "effect/Context";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";-import { AsyncResult, Atom } from "effect/unstable/reactivity";-import { useCallback, useEffect } from "react";--import { runtime } from "../lib/runtime";-import { appAtomRegistry } from "../rpc/atomRegistry";--const managedRelayAtomRuntime = Atom.runtime(- Layer.effect(- ManagedRelay.ManagedRelayClient,- runtime.contextEffect.pipe(- Effect.map((context) => Context.get(context, ManagedRelay.ManagedRelayClient)),- ),- ),-);--export const managedRelayQueryManager = createManagedRelayQueryManager(managedRelayAtomRuntime);--const managedRelayMutationScheduler = createAtomCommandScheduler();--export const deregisterManagedRelayEnvironmentCommand = createRuntimeCommand(- managedRelayAtomRuntime,- {- label: "web:managed-relay:deregister-environment",- scheduler: managedRelayMutationScheduler,- concurrency: {- mode: "serial",- key: (input: { readonly accountId: string; readonly environmentId: EnvironmentId }) =>- input.accountId,- },- execute: (input, registry) => deregisterManagedRelayEnvironment(registry, input),- },-);--const EMPTY_ENVIRONMENTS_ATOM = Atom.make(- AsyncResult.success<ReadonlyArray<RelayClientEnvironmentRecord>>([]),-).pipe(Atom.keepAlive, Atom.withLabel("managed-relay:web:environments:null"));--const EMPTY_DEVICES_ATOM = Atom.make(- AsyncResult.success<ReadonlyArray<RelayClientDeviceRecord>>([]),-).pipe(Atom.keepAlive, Atom.withLabel("managed-relay:web:devices:null"));--export function useManagedRelayEnvironments() {- const session = useAtomValue(managedRelaySessionAtom);- const accountId = session?.accountId ?? null;- const atom = accountId- ? managedRelayQueryManager.environmentsAtom(accountId)- : EMPTY_ENVIRONMENTS_ATOM;- const result = useAtomValue(atom);- const snapshot = readManagedRelaySnapshotState(result);- useEffect(() => {- if (snapshot.error) {- console.error("[t3-cloud] Relay environment listing failed", {- message: snapshot.error,- traceId: snapshot.errorTraceId,- });- }- }, [snapshot.error, snapshot.errorTraceId]);- const refresh = useCallback(() => {- if (accountId) {- managedRelayQueryManager.refreshEnvironments(appAtomRegistry, accountId);- }- }, [accountId]);-- return {- ...snapshot,- accountId,- refresh,- };-}--export function useManagedRelayDevices() {- const session = useAtomValue(managedRelaySessionAtom);- const accountId = session?.accountId ?? null;- const atom = accountId ? managedRelayQueryManager.devicesAtom(accountId) : EMPTY_DEVICES_ATOM;- const result = useAtomValue(atom);- const snapshot = readManagedRelaySnapshotState(result);- useEffect(() => {- if (snapshot.error) {- console.error("[t3-cloud] Relay device listing failed", {- message: snapshot.error,- traceId: snapshot.errorTraceId,- });- }- }, [snapshot.error, snapshot.errorTraceId]);- const refresh = useCallback(() => {- if (accountId) {- managedRelayQueryManager.refreshDevices(appAtomRegistry, accountId);- }- }, [accountId]);-- return {- ...snapshot,- accountId,- refresh,- };-}--export function refreshManagedRelayEnvironments(): void {- const session = appAtomRegistry.get(managedRelaySessionAtom);- if (session) {- managedRelayQueryManager.refreshEnvironments(appAtomRegistry, session.accountId);- }-}diff --git a/apps/web/src/cloud/primaryCloudLinkState.ts b/apps/web/src/cloud/primaryCloudLinkState.tsdeleted file mode 100644index 7c090d3b5..000000000--- a/apps/web/src/cloud/primaryCloudLinkState.ts+++ /dev/null@@ -1,85 +0,0 @@-import { useAtomValue } from "@effect/atom-react";-import type { EnvironmentCloudLinkStateResult } from "@t3tools/contracts";-import * as Cause from "effect/Cause";-import * as Context from "effect/Context";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";-import * as Option from "effect/Option";-import { AsyncResult, Atom } from "effect/unstable/reactivity";-import { HttpClient } from "effect/unstable/http";-import { useCallback, useMemo } from "react";--import { usePrimaryEnvironment } from "../state/environments";-import { runtime } from "../lib/runtime";-import { appAtomRegistry } from "../rpc/atomRegistry";-import { readPrimaryCloudLinkState, type CloudLinkTarget } from "./linkEnvironment";--const primaryCloudLinkAtomRuntime = Atom.runtime(- Layer.effect(- HttpClient.HttpClient,- runtime.contextEffect.pipe(- Effect.map((context) => Context.get(context, HttpClient.HttpClient)),- ),- ),-);--const primaryCloudLinkStateAtom = Atom.family((key: string) => {- const target = JSON.parse(key) as CloudLinkTarget;- return primaryCloudLinkAtomRuntime- .atom(readPrimaryCloudLinkState({ target }))- .pipe(- Atom.swr({ staleTime: 5_000, revalidateOnMount: true }),- Atom.setIdleTTL(5 * 60_000),- Atom.withLabel(`primary-cloud-link:${target.environmentId}`),- );-});--const EMPTY_PRIMARY_CLOUD_LINK_STATE_ATOM = Atom.make(- AsyncResult.success<EnvironmentCloudLinkStateResult | null>(null),-).pipe(Atom.keepAlive, Atom.withLabel("primary-cloud-link:null"));--function targetKey(target: CloudLinkTarget): string {- return JSON.stringify(target);-}--export function refreshPrimaryCloudLinkState(target: CloudLinkTarget | null): void {- if (target) {- appAtomRegistry.refresh(primaryCloudLinkStateAtom(targetKey(target)));- }-}--export function usePrimaryCloudLinkState() {- const primary = usePrimaryEnvironment();- const target = useMemo(- () =>- primary?.entry.target._tag === "PrimaryConnectionTarget"- ? {- environmentId: primary.environmentId,- label: primary.label,- httpBaseUrl: primary.entry.target.httpBaseUrl,- wsBaseUrl: primary.entry.target.wsBaseUrl,- }- : null,- [primary],- );- const atom = target- ? primaryCloudLinkStateAtom(targetKey(target))- : EMPTY_PRIMARY_CLOUD_LINK_STATE_ATOM;- const result = useAtomValue(atom);- const refresh = useCallback(() => {- refreshPrimaryCloudLinkState(target);- }, [target]);- let error: string | null = null;- if (result._tag === "Failure") {- const cause = Cause.squash(result.cause);- error = cause instanceof Error ? cause.message : "Could not read the environment link state.";- }-- return {- data: Option.getOrNull(AsyncResult.value(result)),- error,- isPending: result.waiting,- refresh,- target,- };-}diff --git a/apps/web/src/cloud/publicConfig.test.ts b/apps/web/src/cloud/publicConfig.test.tsdeleted file mode 100644index d42aa34ba..000000000--- a/apps/web/src/cloud/publicConfig.test.ts+++ /dev/null@@ -1,45 +0,0 @@-import { afterEach, describe, expect, it, vi } from "vite-plus/test";--import {- CloudPublicConfigMissingError,- hasCloudPublicConfig,- resolveRelayClerkTokenOptions,-} from "./publicConfig.ts";--afterEach(() => {- vi.unstubAllEnvs();-});--describe("hasCloudPublicConfig", () => {- it("requires both public cloud values", () => {- vi.stubEnv("VITE_CLERK_PUBLISHABLE_KEY", "");- vi.stubEnv("VITE_CLERK_JWT_TEMPLATE", "");- vi.stubEnv("VITE_T3CODE_RELAY_URL", "");- expect(hasCloudPublicConfig()).toBe(false);-- vi.stubEnv("VITE_CLERK_PUBLISHABLE_KEY", "pk_test_example");- expect(hasCloudPublicConfig()).toBe(false);-- vi.stubEnv("VITE_CLERK_JWT_TEMPLATE", "t3-relay");- expect(hasCloudPublicConfig()).toBe(false);-- vi.stubEnv("VITE_T3CODE_RELAY_URL", "https://relay.example.test");- expect(hasCloudPublicConfig()).toBe(true);- });-- it("rejects an insecure relay URL", () => {- vi.stubEnv("VITE_CLERK_PUBLISHABLE_KEY", "pk_test_example");- vi.stubEnv("VITE_CLERK_JWT_TEMPLATE", "t3-relay");- vi.stubEnv("VITE_T3CODE_RELAY_URL", "http://relay.example.test");-- expect(hasCloudPublicConfig()).toBe(false);- });-- it("reports the missing Clerk JWT template as structured configuration", () => {- vi.stubEnv("VITE_CLERK_JWT_TEMPLATE", "");-- expect(() => resolveRelayClerkTokenOptions()).toThrowError(- new CloudPublicConfigMissingError({ key: "T3CODE_CLERK_JWT_TEMPLATE" }),- );- });-});diff --git a/apps/web/src/cloud/publicConfig.ts b/apps/web/src/cloud/publicConfig.tsdeleted file mode 100644index 2caf4f52f..000000000--- a/apps/web/src/cloud/publicConfig.ts+++ /dev/null@@ -1,83 +0,0 @@-import { relayClerkTokenOptions } from "@t3tools/shared/relayAuth";-import { normalizeSecureRelayUrl } from "@t3tools/shared/relayUrl";-import * as Schema from "effect/Schema";--export class CloudPublicConfigMissingError extends Schema.TaggedErrorClass<CloudPublicConfigMissingError>()(- "CloudPublicConfigMissingError",- {- key: Schema.Literal("T3CODE_CLERK_JWT_TEMPLATE"),- },-) {- override get message(): string {- return `${this.key} is not configured.`;- }-}--export interface CloudPublicConfig {- readonly clerkPublishableKey: string | null;- readonly clerkJwtTemplate: string | null;- readonly relayUrl: string | null;- readonly relayTracing: {- readonly tracesUrl: string | null;- readonly tracesDataset: string | null;- readonly tracesToken: string | null;- };-}--export function trimNonEmpty(value: string | undefined): string | null {- return value?.trim() || null;-}--function normalizeSecureUrl(value: string): string | null {- try {- const url = new URL(value);- return url.protocol === "https:" ? url.toString() : null;- } catch {- return null;- }-}--export function resolveCloudPublicConfig(): CloudPublicConfig {- return {- clerkPublishableKey: trimNonEmpty(- import.meta.env.VITE_CLERK_PUBLISHABLE_KEY as string | undefined,- ),- clerkJwtTemplate: trimNonEmpty(import.meta.env.VITE_CLERK_JWT_TEMPLATE as string | undefined),- relayUrl: normalizeSecureRelayUrl(- (import.meta.env.VITE_T3CODE_RELAY_URL as string | undefined) ?? "",- ),- relayTracing: {- tracesUrl: normalizeSecureUrl(- (import.meta.env.VITE_RELAY_OTLP_TRACES_URL as string | undefined) ?? "",- ),- tracesDataset: trimNonEmpty(- import.meta.env.VITE_RELAY_OTLP_TRACES_DATASET as string | undefined,- ),- tracesToken: trimNonEmpty(import.meta.env.VITE_RELAY_OTLP_TRACES_TOKEN as string | undefined),- },- };-}--export function resolveRelayTracingConfig() {- const { relayTracing } = resolveCloudPublicConfig();- return relayTracing.tracesUrl && relayTracing.tracesDataset && relayTracing.tracesToken- ? {- tracesUrl: relayTracing.tracesUrl,- tracesDataset: relayTracing.tracesDataset,- tracesToken: relayTracing.tracesToken,- }- : null;-}--export function hasCloudPublicConfig(): boolean {- const config = resolveCloudPublicConfig();- return Boolean(config.clerkPublishableKey && config.clerkJwtTemplate && config.relayUrl);-}--export function resolveRelayClerkTokenOptions() {- const { clerkJwtTemplate } = resolveCloudPublicConfig();- if (!clerkJwtTemplate) {- throw new CloudPublicConfigMissingError({ key: "T3CODE_CLERK_JWT_TEMPLATE" });- }- return relayClerkTokenOptions(clerkJwtTemplate);-}diff --git a/apps/web/src/cloud/relayClientInstallDialog.test.ts b/apps/web/src/cloud/relayClientInstallDialog.test.tsdeleted file mode 100644index 7bd8d4967..000000000--- a/apps/web/src/cloud/relayClientInstallDialog.test.ts+++ /dev/null@@ -1,95 +0,0 @@-import { beforeEach, describe, expect, it } from "vite-plus/test";--import {- completeRelayClientInstallDialogClose,- finishRelayClientInstall,- readRelayClientInstallDialogState,- RelayClientInstallConfirmationConflictError,- reportRelayClientInstallProgress,- requestRelayClientInstallConfirmation,- resetRelayClientInstallDialogForTests,- respondToRelayClientInstallConfirmation,-} from "./relayClientInstallDialog";--describe("relay client install dialog coordinator", () => {- beforeEach(() => {- resetRelayClientInstallDialogForTests();- });-- it("moves a confirmed installation through streamed progress stages", async () => {- const confirmation = requestRelayClientInstallConfirmation("2026.5.2");- expect(readRelayClientInstallDialogState()).toEqual({- status: "confirming",- version: "2026.5.2",- });-- respondToRelayClientInstallConfirmation(true);- await expect(confirmation).resolves.toBe(true);- expect(readRelayClientInstallDialogState()).toEqual({- status: "installing",- version: "2026.5.2",- stage: "checking",- });-- reportRelayClientInstallProgress({ type: "progress", stage: "downloading" });- expect(readRelayClientInstallDialogState()).toEqual({- status: "installing",- version: "2026.5.2",- stage: "downloading",- });-- finishRelayClientInstall();- expect(readRelayClientInstallDialogState()).toEqual({- status: "closing",- view: {- status: "installing",- version: "2026.5.2",- stage: "downloading",- },- });-- completeRelayClientInstallDialogClose();- expect(readRelayClientInstallDialogState()).toEqual({ status: "idle" });- });-- it("returns to idle when installation is declined", async () => {- const confirmation = requestRelayClientInstallConfirmation("2026.5.2");- respondToRelayClientInstallConfirmation(false);-- await expect(confirmation).resolves.toBe(false);- expect(readRelayClientInstallDialogState()).toEqual({- status: "closing",- view: {- status: "confirming",- version: "2026.5.2",- },- });-- completeRelayClientInstallDialogClose();- expect(readRelayClientInstallDialogState()).toEqual({ status: "idle" });- });-- it("rejects concurrent confirmation with the active install state", async () => {- const confirmation = requestRelayClientInstallConfirmation("2026.5.2");- respondToRelayClientInstallConfirmation(true);- await expect(confirmation).resolves.toBe(true);- reportRelayClientInstallProgress({ type: "progress", stage: "downloading" });-- const error = await requestRelayClientInstallConfirmation("2026.6.0").then(- () => undefined,- (cause: unknown) => cause,- );-- expect(error).toBeInstanceOf(RelayClientInstallConfirmationConflictError);- expect(error).toMatchObject({- requestedVersion: "2026.6.0",- activeVersion: "2026.5.2",- activeDialogStatus: "installing",- activeInstallStage: "downloading",- });- expect(error).not.toHaveProperty("cause");- expect((error as Error).message).toBe(- "Cannot confirm relay client installation 2026.6.0; installation 2026.5.2 has dialog status installing.",- );- });-});diff --git a/apps/web/src/cloud/relayClientInstallDialog.ts b/apps/web/src/cloud/relayClientInstallDialog.tsdeleted file mode 100644index b1b0c6607..000000000--- a/apps/web/src/cloud/relayClientInstallDialog.ts+++ /dev/null@@ -1,126 +0,0 @@-import {- RelayClientInstallProgressStageSchema,- type RelayClientInstallProgressEvent,- type RelayClientInstallProgressStage,-} from "@t3tools/contracts";-import * as Schema from "effect/Schema";--export class RelayClientInstallConfirmationConflictError extends Schema.TaggedErrorClass<RelayClientInstallConfirmationConflictError>()(- "RelayClientInstallConfirmationConflictError",- {- requestedVersion: Schema.String,- activeVersion: Schema.String,- activeDialogStatus: Schema.Literals(["confirming", "installing", "closing"]),- activeInstallStage: Schema.optional(RelayClientInstallProgressStageSchema),- },-) {- override get message(): string {- return `Cannot confirm relay client installation ${this.requestedVersion}; installation ${this.activeVersion} has dialog status ${this.activeDialogStatus}.`;- }-}--export type RelayClientInstallDialogState =- | { readonly status: "idle" }- | { readonly status: "confirming"; readonly version: string }- | {- readonly status: "installing";- readonly version: string;- readonly stage: RelayClientInstallProgressStage;- }- | {- readonly status: "closing";- readonly view:- | { readonly status: "confirming"; readonly version: string }- | {- readonly status: "installing";- readonly version: string;- readonly stage: RelayClientInstallProgressStage;- };- };--const idleState: RelayClientInstallDialogState = { status: "idle" };-let state: RelayClientInstallDialogState = idleState;-let resolveConfirmation: ((confirmed: boolean) => void) | null = null;-const listeners = new Set<() => void>();--function publish(next: RelayClientInstallDialogState) {- state = next;- for (const listener of listeners) {- listener();- }-}--export function readRelayClientInstallDialogState(): RelayClientInstallDialogState {- return state;-}--export function subscribeRelayClientInstallDialog(listener: () => void): () => void {- listeners.add(listener);- return () => {- listeners.delete(listener);- };-}--export function requestRelayClientInstallConfirmation(version: string): Promise<boolean> {- if (state.status !== "idle") {- const activeInstall = state.status === "closing" ? state.view : state;- return Promise.reject(- new RelayClientInstallConfirmationConflictError({- requestedVersion: version,- activeVersion: activeInstall.version,- activeDialogStatus: state.status,- ...(activeInstall.status === "installing"- ? { activeInstallStage: activeInstall.stage }- : {}),- }),- );- }-- publish({ status: "confirming", version });- return new Promise<boolean>((resolve) => {- resolveConfirmation = resolve;- });-}--export function respondToRelayClientInstallConfirmation(confirmed: boolean): void {- if (state.status !== "confirming" || !resolveConfirmation) {- return;- }-- const resolve = resolveConfirmation;- resolveConfirmation = null;- publish(- confirmed- ? { status: "installing", version: state.version, stage: "checking" }- : { status: "closing", view: state },- );- resolve(confirmed);-}--export function reportRelayClientInstallProgress(event: RelayClientInstallProgressEvent): void {- if (state.status !== "installing" || event.type !== "progress") {- return;- }- publish({ ...state, stage: event.stage });-}--export function finishRelayClientInstall(): void {- resolveConfirmation?.(false);- resolveConfirmation = null;- if (state.status === "confirming" || state.status === "installing") {- publish({ status: "closing", view: state });- }-}--export function completeRelayClientInstallDialogClose(): void {- if (state.status === "closing") {- publish(idleState);- }-}--export function resetRelayClientInstallDialogForTests(): void {- resolveConfirmation?.(false);- resolveConfirmation = null;- publish(idleState);- listeners.clear();-}diff --git a/apps/web/src/cloud/useCloudLinkController.ts b/apps/web/src/cloud/useCloudLinkController.tsdeleted file mode 100644index 964ef9a76..000000000--- a/apps/web/src/cloud/useCloudLinkController.ts+++ /dev/null@@ -1,163 +0,0 @@-import { useAuth } from "@clerk/react";-import { findErrorTraceId } from "@t3tools/client-runtime/errors";-import {- isAtomCommandInterrupted,- settlePromise,- squashAtomCommandFailure,-} from "@t3tools/client-runtime/state/runtime";-import { useState } from "react";--import { toastManager } from "../components/ui/toast";-import { relayEnvironmentDiscovery } from "../state/relay";-import { useAtomCommand } from "../state/use-atom-command";-import {- linkPrimaryEnvironment as linkPrimaryEnvironmentAtom,- unlinkPrimaryEnvironment as unlinkPrimaryEnvironmentAtom,- updatePrimaryEnvironmentPreferences as updatePrimaryEnvironmentPreferencesAtom,-} from "./linkEnvironmentAtoms";-import { usePrimaryCloudLinkState } from "./primaryCloudLinkState";-import { resolveRelayClerkTokenOptions } from "./publicConfig";--export interface CloudLinkDesiredState {- readonly managedTunnel: boolean;- readonly publish: boolean;-}--/**- * Drives the primary environment's managed relay link. The relay (managed- * tunnel) and agent-activity publishing are independent capabilities backed by- * a single relay link, so consumers express the full desired state and- * `reconcileCloudState` applies it: unlink when neither is wanted, otherwise- * (re)link with the mode the managed-tunnel bit implies and set the publish- * preference. Re-linking only happens when the managed-tunnel mode actually- * changes, so flipping publish alone is cheap.- */-export function useCloudLinkController() {- const { getToken, isSignedIn } = useAuth();- const refreshRelayEnvironments = useAtomCommand(relayEnvironmentDiscovery.refresh, {- reportFailure: false,- });- const linkPrimaryEnvironment = useAtomCommand(linkPrimaryEnvironmentAtom, {- reportFailure: false,- });- const unlinkPrimaryEnvironment = useAtomCommand(unlinkPrimaryEnvironmentAtom, {- reportFailure: false,- });- const updatePrimaryEnvironmentPreferences = useAtomCommand(- updatePrimaryEnvironmentPreferencesAtom,- { reportFailure: false },- );- const primaryCloudLinkState = usePrimaryCloudLinkState();- const [operationError, setOperationError] = useState<string | null>(null);-- const reportUpdateFailure = (cause: unknown) => {- const message = cause instanceof Error ? cause.message : "Could not update remote access.";- const traceId = findErrorTraceId(cause);- console.error("[t3-connect] Could not update remote access", { message, traceId, cause });- setOperationError(traceId ? `${message} Trace ID: ${traceId}` : message);- toastManager.add({- type: "error",- title: "Could not update remote access",- description: message,- data: traceId- ? {- secondaryActionProps: {- children: "Copy trace ID",- onClick: () => void navigator.clipboard?.writeText(traceId),- },- }- : undefined,- });- };-- // Older environment servers predate the managedTunnelActive field; for them a- // link always implies a managed tunnel, so fall back to `linked`.- const managedTunnelActive =- primaryCloudLinkState.data?.managedTunnelActive ?? primaryCloudLinkState.data?.linked ?? false;- const publishAgentActivity = primaryCloudLinkState.data?.publishAgentActivity ?? false;- const linked = primaryCloudLinkState.data?.linked ?? false;-- const reconcileCloudState = async (desired: CloudLinkDesiredState): Promise<boolean> => {- setOperationError(null);- const target = primaryCloudLinkState.target;- if (!target) {- reportUpdateFailure(new Error("Local environment is not ready yet."));- return false;- }- const tokenResult = await settlePromise(() => getToken(resolveRelayClerkTokenOptions()));- const wantsLink = desired.managedTunnel || desired.publish;-- // A failure after this point may follow a partially applied mutation (e.g.- // the link succeeded but the preference update did not), so every exit —- // success or failure — refreshes the rendered state to whatever the server- // actually holds now.- if (!wantsLink) {- // Unlink works without a relay token — a failed token read must not- // leave the user unable to turn remote access off.- const unlinkResult = await unlinkPrimaryEnvironment({- target,- clerkToken: tokenResult._tag === "Success" ? (tokenResult.value ?? null) : null,- });- if (unlinkResult._tag === "Failure") {- if (!isAtomCommandInterrupted(unlinkResult)) {- reportUpdateFailure(squashAtomCommandFailure(unlinkResult));- }- primaryCloudLinkState.refresh();- return false;- }- } else {- if (tokenResult._tag === "Failure") {- reportUpdateFailure(squashAtomCommandFailure(tokenResult));- return false;- }- const clerkToken = tokenResult.value;- if (!clerkToken) {- reportUpdateFailure(new Error("Sign in before enabling this."));- return false;- }- if (!linked || managedTunnelActive !== desired.managedTunnel) {- const linkResult = await linkPrimaryEnvironment({- target,- clerkToken,- mode: desired.managedTunnel ? "managed" : "publish_only",- });- if (linkResult._tag === "Failure") {- if (!isAtomCommandInterrupted(linkResult)) {- reportUpdateFailure(squashAtomCommandFailure(linkResult));- }- primaryCloudLinkState.refresh();- return false;- }- }- const prefResult = await updatePrimaryEnvironmentPreferences({- target,- publishAgentActivity: desired.publish,- });- if (prefResult._tag === "Failure") {- if (!isAtomCommandInterrupted(prefResult)) {- reportUpdateFailure(squashAtomCommandFailure(prefResult));- }- primaryCloudLinkState.refresh();- return false;- }- }-- primaryCloudLinkState.refresh();- const refreshResult = await refreshRelayEnvironments();- if (refreshResult._tag === "Failure" && !isAtomCommandInterrupted(refreshResult)) {- reportUpdateFailure(squashAtomCommandFailure(refreshResult));- return false;- }- return true;- };-- return {- isSignedIn,- linkState: primaryCloudLinkState,- linked,- managedTunnelActive,- publishAgentActivity,- operationError,- reconcileCloudState,- };-}diff --git a/apps/web/src/components/ProviderUpdateLaunchNotification.environments.ts b/apps/web/src/components/ProviderUpdateLaunchNotification.environments.tsindex 2fb9c16b6..5999f9241 100644--- a/apps/web/src/components/ProviderUpdateLaunchNotification.environments.ts+++ b/apps/web/src/components/ProviderUpdateLaunchNotification.environments.ts@@ -16,7 +16,7 @@ import {* A local environment is either the same-origin primary backend or a* desktop-local secondary (the parallel WSL backend), which connects over* loopback with a bearer token and carries a `local:<backendInstanceId>`- * connection id. SSH, relay, and other remote targets are excluded.+ * connection id. SSH and other remote targets are excluded.*/function isLocalConnectionTarget(target: ConnectionCatalogEntry["target"]): boolean {return target._tag === "PrimaryConnectionTarget" || isDesktopLocalConnectionTarget(target);diff --git a/apps/web/src/components/ProviderUpdateLaunchNotification.tsx b/apps/web/src/components/ProviderUpdateLaunchNotification.tsxindex 411a9141a..70e771305 100644--- a/apps/web/src/components/ProviderUpdateLaunchNotification.tsx+++ b/apps/web/src/components/ProviderUpdateLaunchNotification.tsx@@ -19,8 +19,8 @@ import { openSettings } from "~/settingsDialogStore";/*** True when a desktop-local secondary backend (the parallel WSL backend) is* present alongside the primary. Local secondaries connect over loopback with a- * `local:<backendInstanceId>` bearer connection id; everything else (SSH, relay,- * remote) is ignored. Gating on this keeps non-WSL users on the unchanged+ * `local:<backendInstanceId>` bearer connection id; everything else (SSH or+ * another remote target) is ignored. Gating on this keeps non-WSL users on the unchanged* single-prompt flow.*/function useHasLocalSecondaryEnvironment(): boolean {diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsxindex 98a090d7a..4ab3d8127 100644--- a/apps/web/src/components/Sidebar.tsx+++ b/apps/web/src/components/Sidebar.tsx@@ -1896,7 +1896,7 @@ export default function Sidebar() {[sidebarProjectSortOrder, threads, unsortedProjectGroups],);const serverConfigs = useAtomValue(environmentServerConfigsAtom);- // Threads on non-primary environments (T3 Connect, hosted) resolve their+ // Threads on non-primary environments resolve their// provider entry from their own environment's config: default instance ids// are driver slugs, so a flat map would collide across environments.const providerEntriesByEnvironment = useMemo(diff --git a/apps/web/src/components/clerk/ClerkUserProfilePage.tsx b/apps/web/src/components/clerk/ClerkUserProfilePage.tsxdeleted file mode 100644index 00f20e53f..000000000--- a/apps/web/src/components/clerk/ClerkUserProfilePage.tsx+++ /dev/null@@ -1,86 +0,0 @@-import { RefreshCwIcon } from "lucide-react";-import type { ReactNode } from "react";--import { cn } from "../../lib/utils";-import { Button } from "../ui/button";--export function ClerkUserProfilePage({- action,- children,- className,- description,- title,-}: {- readonly action?: ReactNode;- readonly children: ReactNode;- readonly className?: string;- readonly description?: ReactNode;- readonly title: ReactNode;-}) {- return (- <div className={cn("w-full min-w-0 text-foreground", className)}>- <header className="flex flex-col gap-3 pb-4 sm:flex-row sm:items-start sm:justify-between sm:gap-4 sm:pr-8">- <div className="min-w-0">- <h2 className="text-[1.0625rem] leading-6 font-semibold">{title}</h2>- {description ? (- <p className="mt-1 max-w-[34rem] text-[0.8125rem] leading-[1.125rem] text-muted-foreground sm:min-h-9">- {description}- </p>- ) : null}- </div>- {action ? <div className="shrink-0">{action}</div> : null}- </header>-- {children}- </div>- );-}--export function ClerkUserProfileRefreshButton({- className,- disabled = false,- isPending,- onClick,-}: {- readonly className?: string;- readonly disabled?: boolean;- readonly isPending: boolean;- readonly onClick: () => void;-}) {- return (- <Button- size="sm"- variant="outline"- className={cn("text-[0.8125rem]", className)}- disabled={disabled || isPending}- onClick={onClick}- >- <RefreshCwIcon aria-hidden="true" className={cn("size-3.5", isPending && "animate-spin")} />- Refresh- </Button>- );-}--export function ClerkUserProfileRow({- children,- className,- icon,-}: {- readonly children: ReactNode;- readonly className?: string;- readonly icon: ReactNode;-}) {- return (- <li className={cn("border-t py-4 first:border-t-0", className)}>- <div className="flex items-start gap-3">- <div- aria-hidden="true"- className="flex size-8 shrink-0 items-center justify-center rounded-lg border bg-muted/32 text-muted-foreground"- >- {icon}- </div>- <div className="min-w-0 flex-1">{children}</div>- </div>- </li>- );-}diff --git a/apps/web/src/components/clerk/MobileClientsUserProfilePage.logic.test.ts b/apps/web/src/components/clerk/MobileClientsUserProfilePage.logic.test.tsdeleted file mode 100644index 002ff0827..000000000--- a/apps/web/src/components/clerk/MobileClientsUserProfilePage.logic.test.ts+++ /dev/null@@ -1,65 +0,0 @@-import type { RelayClientDeviceRecord } from "@t3tools/contracts/relay";-import { describe, expect, it } from "vite-plus/test";--import {- mobileClientNotificationDetail,- mobileClientPlatformLabel,- mobileClientUpdatedAtLabel,-} from "./MobileClientsUserProfilePage.logic";--function device(overrides: Partial<RelayClientDeviceRecord> = {}): RelayClientDeviceRecord {- return {- deviceId: "device-1",- label: "Julius’s iPhone",- platform: "ios",- iosMajorVersion: 18,- appVersion: "1.2.3",- notifications: {- enabled: true,- notifyOnApproval: true,- notifyOnInput: false,- notifyOnCompletion: true,- notifyOnFailure: false,- },- liveActivities: { enabled: true },- updatedAt: "2026-06-21T12:00:00.000Z",- ...overrides,- };-}--describe("mobile client presentation", () => {- it("describes the client platform and enabled notification events", () => {- const client = device();-- expect(mobileClientPlatformLabel(client)).toBe("iOS 18 · Akeru Bot 1.2.3");- expect(mobileClientNotificationDetail(client)).toBe(- "Alerts enabled for approvals, completions.",- );- });-- it("distinguishes disabled notifications from an empty event selection", () => {- expect(- mobileClientNotificationDetail(- device({ notifications: { ...device().notifications, enabled: false } }),- ),- ).toBe("Push notifications are disabled on this device.");- expect(- mobileClientNotificationDetail(- device({- notifications: {- enabled: true,- notifyOnApproval: false,- notifyOnInput: false,- notifyOnCompletion: false,- notifyOnFailure: false,- },- }),- ),- ).toBe("Push notifications are enabled, but no alert types are selected.");- });-- it("handles missing app versions and invalid update timestamps", () => {- expect(mobileClientPlatformLabel(device({ appVersion: null }))).toBe("iOS 18");- expect(mobileClientUpdatedAtLabel("not-a-date")).toBe("Update time unavailable");- });-});diff --git a/apps/web/src/components/clerk/MobileClientsUserProfilePage.logic.ts b/apps/web/src/components/clerk/MobileClientsUserProfilePage.logic.tsdeleted file mode 100644index 9801ef93f..000000000--- a/apps/web/src/components/clerk/MobileClientsUserProfilePage.logic.ts+++ /dev/null@@ -1,39 +0,0 @@-import type { RelayClientDeviceRecord } from "@t3tools/contracts/relay";--const mobileClientUpdatedAtFormatter = new Intl.DateTimeFormat(undefined, {- dateStyle: "medium",- timeStyle: "short",-});--const NOTIFICATION_PREFERENCES = [- ["notifyOnApproval", "approvals"],- ["notifyOnInput", "input requests"],- ["notifyOnCompletion", "completions"],- ["notifyOnFailure", "failures"],-] as const satisfies ReadonlyArray<- readonly [keyof RelayClientDeviceRecord["notifications"], string]->;--export function mobileClientPlatformLabel(device: RelayClientDeviceRecord): string {- return `iOS ${device.iosMajorVersion}${device.appVersion ? ` · Akeru Bot ${device.appVersion}` : ""}`;-}--export function mobileClientNotificationDetail(device: RelayClientDeviceRecord): string {- if (!device.notifications.enabled) {- return "Push notifications are disabled on this device.";- }-- const enabledPreferences = NOTIFICATION_PREFERENCES.flatMap(([preference, label]) =>- device.notifications[preference] ? [label] : [],- );- return enabledPreferences.length > 0- ? `Alerts enabled for ${enabledPreferences.join(", ")}.`- : "Push notifications are enabled, but no alert types are selected.";-}--export function mobileClientUpdatedAtLabel(updatedAt: string): string {- const date = new Date(updatedAt);- return Number.isNaN(date.getTime())- ? "Update time unavailable"- : `Updated ${mobileClientUpdatedAtFormatter.format(date)}`;-}diff --git a/apps/web/src/components/clerk/MobileClientsUserProfilePage.tsx b/apps/web/src/components/clerk/MobileClientsUserProfilePage.tsxdeleted file mode 100644index 0b2115718..000000000--- a/apps/web/src/components/clerk/MobileClientsUserProfilePage.tsx+++ /dev/null@@ -1,155 +0,0 @@-import type { RelayClientDeviceRecord } from "@t3tools/contracts/relay";-import { SmartphoneIcon } from "lucide-react";--import { useManagedRelayDevices } from "../../cloud/managedRelayState";-import { Badge } from "../ui/badge";-import { Button } from "../ui/button";-import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "../ui/empty";-import { Skeleton } from "../ui/skeleton";-import {- mobileClientNotificationDetail,- mobileClientPlatformLabel,- mobileClientUpdatedAtLabel,-} from "./MobileClientsUserProfilePage.logic";-import {- ClerkUserProfilePage,- ClerkUserProfileRefreshButton,- ClerkUserProfileRow,-} from "./ClerkUserProfilePage";--const MOBILE_CLIENT_SKELETON_ROWS = ["primary", "secondary"] as const;--function MobileClientStatusBadge({- enabled,- label,-}: {- readonly enabled: boolean;- readonly label: string;-}) {- return (- <Badge variant={enabled ? "success" : "outline"}>- {label}: {enabled ? "On" : "Off"}- </Badge>- );-}--function MobileClientRow({ device }: { readonly device: RelayClientDeviceRecord }) {- return (- <ClerkUserProfileRow icon={<SmartphoneIcon className="size-4" />}>- <div className="flex flex-col gap-0.5 sm:flex-row sm:items-start sm:justify-between sm:gap-3">- <div className="min-w-0">- <h3 className="truncate text-[0.8125rem] leading-[1.125rem] font-medium text-foreground">- {device.label}- </h3>- <p className="text-xs leading-[1.125rem] text-muted-foreground">- {mobileClientPlatformLabel(device)}- </p>- </div>- <p className="shrink-0 text-[0.6875rem] leading-4 text-muted-foreground/75">- {mobileClientUpdatedAtLabel(device.updatedAt)}- </p>- </div>- <div className="mt-2 flex flex-wrap gap-1.5">- <MobileClientStatusBadge- enabled={device.notifications.enabled}- label="Push notifications"- />- <MobileClientStatusBadge enabled={device.liveActivities.enabled} label="Live Activities" />- </div>- <p className="mt-1.5 text-xs leading-[1.125rem] text-muted-foreground/80">- {mobileClientNotificationDetail(device)}- </p>- </ClerkUserProfileRow>- );-}--function MobileClientsSkeleton() {- return (- <div aria-label="Loading mobile clients" className="divide-y border-t" role="status">- {MOBILE_CLIENT_SKELETON_ROWS.map((row) => (- <div key={row} className="py-4">- <div className="flex gap-3">- <Skeleton className="size-8 shrink-0 rounded-lg" />- <div className="flex-1 space-y-2">- <Skeleton className="h-3.5 w-36" />- <Skeleton className="h-3 w-28" />- <div className="flex gap-2">- <Skeleton className="h-4.5 w-28" />- <Skeleton className="h-4.5 w-24" />- </div>- </div>- </div>- </div>- ))}- </div>- );-}--function EmptyMobileClients() {- return (- <Empty className="min-h-64 gap-4 border-t px-6 py-10 md:p-10">- <EmptyMedia className="mb-0" variant="icon">- <SmartphoneIcon />- </EmptyMedia>- <EmptyHeader>- <EmptyTitle className="text-[1.0625rem] leading-6">No mobile clients</EmptyTitle>- <EmptyDescription className="text-[0.8125rem] leading-[1.125rem]">- Sign in to Akeru Bot on your iPhone to register it for push notifications and Live- Activities.- </EmptyDescription>- </EmptyHeader>- </Empty>- );-}--export function MobileClientsUserProfilePage() {- const devicesState = useManagedRelayDevices();- const devices = devicesState.data ?? [];- const isInitialLoad =- !devicesState.accountId || (devicesState.data === null && !devicesState.error);- const hasErrorWithoutData = devicesState.error !== null && devicesState.data === null;-- return (- <ClerkUserProfilePage- title="Mobile clients"- description="Devices registered to receive activity from your environments."- action={- <ClerkUserProfileRefreshButton- isPending={devicesState.isPending}- onClick={devicesState.refresh}- />- }- >- <div>- {devicesState.error ? (- <div- className="mb-4 flex flex-col gap-3 border-t border-destructive/35 py-3 text-[0.8125rem] sm:flex-row sm:items-center sm:justify-between"- role="alert"- >- <div>- <p className="font-medium text-destructive-foreground">- Could not load mobile clients- </p>- <p className="mt-0.5 text-xs text-muted-foreground">{devicesState.error}</p>- </div>- <Button size="xs" variant="outline" onClick={devicesState.refresh}>- Try again- </Button>- </div>- ) : null}-- {isInitialLoad ? (- <MobileClientsSkeleton />- ) : hasErrorWithoutData ? null : devices.length > 0 ? (- <ul className="border-t">- {devices.map((device) => (- <MobileClientRow key={device.deviceId} device={device} />- ))}- </ul>- ) : (- <EmptyMobileClients />- )}- </div>- </ClerkUserProfilePage>- );-}diff --git a/apps/web/src/components/clerk/T3ConnectSidebarSignIn.tsx b/apps/web/src/components/clerk/T3ConnectSidebarSignIn.tsxdeleted file mode 100644index cb103fa19..000000000--- a/apps/web/src/components/clerk/T3ConnectSidebarSignIn.tsx+++ /dev/null@@ -1,79 +0,0 @@-import { UserButton, useAuth } from "@clerk/react";-import { Login01Icon, ServerIcon, SmartphoneIcon } from "@hugeicons/core-free-icons";--import { hasCloudPublicConfig } from "../../cloud/publicConfig";-import { AppIcon } from "../ui/app-icon";-import { SidebarMenu, SidebarMenuButton, SidebarMenuItem } from "../ui/sidebar";-import { MobileClientsUserProfilePage } from "./MobileClientsUserProfilePage";-import { T3ConnectUserProfilePage } from "./T3ConnectUserProfilePage";-import { useT3ConnectAuthPrompt } from "./useT3ConnectAuthPrompt";--export function T3ConnectSidebarSignIn() {- if (!hasCloudPublicConfig()) return null;-- return <ConfiguredT3ConnectSidebarSignIn />;-}--export function T3ConnectSidebarAvatar() {- if (!hasCloudPublicConfig()) return null;-- return <ConfiguredT3ConnectSidebarAvatar />;-}--function ConfiguredT3ConnectSidebarAvatar() {- const { isLoaded, isSignedIn } = useAuth();-- if (!isLoaded || !isSignedIn) return null;-- return (- <UserButton- showName- appearance={{- elements: {- rootBox: "w-full",- userButtonBox: "w-full",- avatarBox: "size-8 ring-1 ring-sidebar-border",- userButtonTrigger:- "w-full min-h-11 justify-start gap-2.5 rounded-lg px-2 py-1.5 text-sidebar-foreground hover:bg-sidebar-row-hover focus-visible:ring-2 focus-visible:ring-ring",- userButtonOuterIdentifier: "min-w-0 truncate text-sm font-medium",- },- }}- >- <UserButton.UserProfilePage- label="Mobile clients"- labelIcon={<AppIcon className="size-4" icon={SmartphoneIcon} />}- url="mobile-clients"- >- <MobileClientsUserProfilePage />- </UserButton.UserProfilePage>- <UserButton.UserProfilePage- label="Linked environments"- labelIcon={<AppIcon className="size-4" icon={ServerIcon} />}- url="t3-connect"- >- <T3ConnectUserProfilePage />- </UserButton.UserProfilePage>- </UserButton>- );-}--function ConfiguredT3ConnectSidebarSignIn() {- const { isLoaded, isSignedIn } = useAuth();- const { authPrompt, openAuthPrompt } = useT3ConnectAuthPrompt();-- if (!isLoaded || isSignedIn) return null;-- return (- <>- <SidebarMenu>- <SidebarMenuItem>- <SidebarMenuButton onClick={openAuthPrompt}>- <AppIcon icon={Login01Icon} />- <span>Sign in for remote access</span>- </SidebarMenuButton>- </SidebarMenuItem>- </SidebarMenu>- {authPrompt}- </>- );-}diff --git a/apps/web/src/components/clerk/T3ConnectUserProfilePage.test.tsx b/apps/web/src/components/clerk/T3ConnectUserProfilePage.test.tsxdeleted file mode 100644index 17ea936b7..000000000--- a/apps/web/src/components/clerk/T3ConnectUserProfilePage.test.tsx+++ /dev/null@@ -1,63 +0,0 @@-import type { EnvironmentId } from "@t3tools/contracts";-import type { RelayClientEnvironmentRecord } from "@t3tools/contracts/relay";-import { renderToStaticMarkup } from "react-dom/server";-import { describe, expect, it, vi } from "vite-plus/test";--import { T3ConnectEnvironmentRow } from "./T3ConnectUserProfilePage";--const environment: RelayClientEnvironmentRecord = {- environmentId: "environment-1" as EnvironmentId,- label: "Studio Mac",- endpoint: {- httpBaseUrl: "https://studio.example.com",- wsBaseUrl: "wss://studio.example.com",- providerKind: "cloudflare_tunnel",- },- linkedAt: "2026-08-12T12:00:00.000Z",-};--function renderRow({- confirmationOpen = false,- mutationPending = false,-}: {- readonly confirmationOpen?: boolean;- readonly mutationPending?: boolean;-} = {}) {- return renderToStaticMarkup(- <T3ConnectEnvironmentRow- environment={environment}- confirmationOpen={confirmationOpen}- mutationPending={mutationPending}- onConfirmationChange={vi.fn()}- onDeregister={vi.fn()}- />,- );-}--describe("Linked environment row", () => {- it("keeps deregistration confirmation inline and collapsed by default", () => {- const markup = renderRow();-- expect(markup).toContain("Studio Mac");- expect(markup).toContain("Deregister");- expect(markup).not.toContain("Deregister server");- expect(markup).not.toContain("Confirm deregistration of Studio Mac");- });-- it("expands Clerk-style confirmation content beneath the environment row", () => {- const markup = renderRow({ confirmationOpen: true });-- expect(markup).toContain("Deregister server");- expect(markup).toContain("“Studio Mac” will be removed from this account.");- expect(markup).toContain("Confirm deregistration of Studio Mac");- expect(markup).toContain("Local connections on your devices are not changed.");- expect(markup).toContain("Cancel");- });-- it("locks the confirmation actions while deregistration is pending", () => {- const markup = renderRow({ confirmationOpen: true, mutationPending: true });-- expect(markup).toContain("Deregistering…");- expect(markup.match(/ disabled=""/g)).toHaveLength(3);- });-});diff --git a/apps/web/src/components/clerk/T3ConnectUserProfilePage.tsx b/apps/web/src/components/clerk/T3ConnectUserProfilePage.tsxdeleted file mode 100644index 86298db0b..000000000--- a/apps/web/src/components/clerk/T3ConnectUserProfilePage.tsx+++ /dev/null@@ -1,258 +0,0 @@-import { findErrorTraceId } from "@t3tools/client-runtime/errors";-import {- isAtomCommandInterrupted,- squashAtomCommandFailure,-} from "@t3tools/client-runtime/state/runtime";-import type { EnvironmentId } from "@t3tools/contracts";-import type { RelayClientEnvironmentRecord } from "@t3tools/contracts/relay";-import { ServerIcon } from "lucide-react";-import { useRef, useState } from "react";--import {- deregisterManagedRelayEnvironmentCommand,- useManagedRelayEnvironments,-} from "../../cloud/managedRelayState";-import { useAtomCommand } from "../../state/use-atom-command";-import { Button } from "../ui/button";-import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible";-import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "../ui/empty";-import { toastManager } from "../ui/toast";-import {- ClerkUserProfilePage,- ClerkUserProfileRefreshButton,- ClerkUserProfileRow,-} from "./ClerkUserProfilePage";--const linkedAtFormatter = new Intl.DateTimeFormat(undefined, { dateStyle: "medium" });--function linkedAtLabel(value: string): string {- const linkedAt = new Date(value);- return Number.isNaN(linkedAt.getTime())- ? "Link date unavailable"- : `Linked ${linkedAtFormatter.format(linkedAt)}`;-}--function endpointLabel(environment: RelayClientEnvironmentRecord): string {- return environment.endpoint.providerKind === "cloudflare_tunnel"- ? "Managed tunnel"- : "Activity publishing only";-}--export function T3ConnectEnvironmentRow(props: {- readonly environment: RelayClientEnvironmentRecord;- readonly confirmationOpen: boolean;- readonly mutationPending: boolean;- readonly onConfirmationChange: (open: boolean) => void;- readonly onDeregister: (environment: RelayClientEnvironmentRecord) => void;-}) {- const { environment } = props;- return (- <ClerkUserProfileRow icon={<ServerIcon className="size-4" />}>- <Collapsible open={props.confirmationOpen} onOpenChange={props.onConfirmationChange}>- <div className="flex items-start gap-4">- <div className="min-w-0 flex-1">- <h3 className="truncate text-[0.8125rem] leading-[1.125rem] font-medium text-foreground">- {environment.label}- </h3>- <p className="mt-1 text-xs leading-[1.125rem] text-muted-foreground">- {linkedAtLabel(environment.linkedAt)} · {endpointLabel(environment)}- </p>- </div>- <CollapsibleTrigger- render={- <Button- size="sm"- variant="destructive-outline"- className="text-[0.8125rem]"- disabled={props.mutationPending}- >- Deregister- </Button>- }- />- </div>-- <CollapsiblePanel>- <div className="pt-3">- <div- className="rounded-lg border border-input bg-muted/32 px-5 py-4 shadow-xs/5"- role="group"- aria-label={`Confirm deregistration of ${environment.label}`}- >- <h4 className="text-[0.8125rem] leading-[1.125rem] font-semibold text-foreground">- Deregister server- </h4>- <p className="mt-1 text-[0.8125rem] leading-[1.125rem] text-muted-foreground">- “{environment.label}” will be removed from this account.- </p>- <p className="mt-4 max-w-xl text-[0.8125rem] leading-[1.125rem] text-muted-foreground">- Remote access will be revoked, any managed tunnel will be removed, and a host space- will become available. Local connections on your devices are not changed.- </p>- <div className="mt-4 flex justify-end gap-2">- <Button- size="sm"- variant="ghost"- className="text-[0.8125rem]"- disabled={props.mutationPending}- onClick={() => props.onConfirmationChange(false)}- >- Cancel- </Button>- <Button- size="sm"- variant="destructive"- className="text-[0.8125rem]"- disabled={props.mutationPending}- onClick={() => props.onDeregister(environment)}- >- {props.mutationPending ? "Deregistering…" : "Deregister"}- </Button>- </div>- </div>- </div>- </CollapsiblePanel>- </Collapsible>- </ClerkUserProfileRow>- );-}--export function T3ConnectUserProfilePage() {- const environmentsState = useManagedRelayEnvironments();- const deregisterEnvironment = useAtomCommand(deregisterManagedRelayEnvironmentCommand, {- reportFailure: false,- });- const [deregisteringEnvironmentId, setDeregisteringEnvironmentId] =- useState<EnvironmentId | null>(null);- const [confirmingEnvironmentId, setConfirmingEnvironmentId] = useState<EnvironmentId | null>(- null,- );- const mutationPendingRef = useRef(false);- const [removedEnvironments, setRemovedEnvironments] = useState<{- readonly accountId: string | null;- readonly linkedAtById: ReadonlyMap<EnvironmentId, string>;- }>({ accountId: null, linkedAtById: new Map() });-- const handleDeregister = async (environment: RelayClientEnvironmentRecord) => {- const accountId = environmentsState.accountId;- if (!accountId || mutationPendingRef.current) return;-- mutationPendingRef.current = true;- setDeregisteringEnvironmentId(environment.environmentId);- const result = await deregisterEnvironment({- accountId,- environmentId: environment.environmentId,- });- mutationPendingRef.current = false;- setDeregisteringEnvironmentId(null);-- if (result._tag === "Success") {- setConfirmingEnvironmentId(null);- setRemovedEnvironments((current) => {- const linkedAtById = new Map(current.accountId === accountId ? current.linkedAtById : []);- linkedAtById.set(environment.environmentId, environment.linkedAt);- return { accountId, linkedAtById };- });- environmentsState.refresh();- toastManager.add({- type: "success",- title: "Server deregistered",- description: "Remote access was revoked and a host space is now available.",- });- return;- }- if (isAtomCommandInterrupted(result)) return;-- const cause = squashAtomCommandFailure(result);- const message = cause instanceof Error ? cause.message : "Could not deregister the server.";- const traceId = findErrorTraceId(cause);- console.error("[t3-connect] Could not deregister environment", {- environmentId: environment.environmentId,- message,- traceId,- cause,- });- toastManager.add({- type: "error",- title: "Could not deregister server",- description: message,- data: traceId- ? {- secondaryActionProps: {- children: "Copy trace ID",- onClick: () => void navigator.clipboard?.writeText(traceId),- },- }- : undefined,- });- };-- const removedEnvironmentLinkedAt =- removedEnvironments.accountId === environmentsState.accountId- ? removedEnvironments.linkedAtById- : new Map<EnvironmentId, string>();- const environments = (environmentsState.data ?? []).filter(- (environment) =>- removedEnvironmentLinkedAt.get(environment.environmentId) !== environment.linkedAt,- );- const isInitialLoad =- !environmentsState.accountId || (environmentsState.data === null && !environmentsState.error);-- return (- <ClerkUserProfilePage- title="Linked environments"- description="Environments registered to your account. Connections on this device are managed in Settings."- action={- <ClerkUserProfileRefreshButton- disabled={deregisteringEnvironmentId !== null}- isPending={environmentsState.isPending}- onClick={environmentsState.refresh}- />- }- >- <div>- {environmentsState.error ? (- <div className="mb-4 border-t border-destructive/35 py-3 text-[0.8125rem]" role="alert">- <p className="font-medium text-destructive-foreground">- Could not load linked environments- </p>- <p className="mt-1 text-xs text-muted-foreground">{environmentsState.error}</p>- </div>- ) : null}-- {isInitialLoad ? (- <p className="border-t py-4 text-[0.8125rem] text-muted-foreground" role="status">- Loading environments…- </p>- ) : environments.length > 0 ? (- <ul className="border-t">- {environments.map((environment) => (- <T3ConnectEnvironmentRow- key={environment.environmentId}- environment={environment}- confirmationOpen={confirmingEnvironmentId === environment.environmentId}- mutationPending={deregisteringEnvironmentId !== null}- onConfirmationChange={(open) =>- setConfirmingEnvironmentId(open ? environment.environmentId : null)- }- onDeregister={(selected) => void handleDeregister(selected)}- />- ))}- </ul>- ) : environmentsState.error ? null : (- <Empty className="min-h-64 gap-4 border-t px-6 py-10 md:p-10">- <EmptyMedia className="mb-0" variant="icon">- <ServerIcon />- </EmptyMedia>- <EmptyHeader>- <EmptyTitle className="text-[1.0625rem] leading-6">No linked environments</EmptyTitle>- <EmptyDescription className="text-[0.8125rem] leading-[1.125rem]">- Link an environment from its local Settings to make it available for remote access.- </EmptyDescription>- </EmptyHeader>- </Empty>- )}- </div>- </ClerkUserProfilePage>- );-}diff --git a/apps/web/src/components/clerk/authRedirect.test.ts b/apps/web/src/components/clerk/authRedirect.test.tsdeleted file mode 100644index e948d1d9c..000000000--- a/apps/web/src/components/clerk/authRedirect.test.ts+++ /dev/null@@ -1,32 +0,0 @@-import { describe, expect, it } from "vite-plus/test";--import { resolveClerkSignInProps } from "./authRedirect";--describe("resolveClerkSignInProps", () => {- it("returns to the current browser URL on the web", () => {- const href = "https://app.t3.codes/connect?state=state-1#details";- expect(resolveClerkSignInProps(href, false)).toEqual({- forceRedirectUrl: href,- signUpForceRedirectUrl: href,- });- });-- it("removes a Clerk virtual pathname and callback params while preserving the desktop route", () => {- expect(- resolveClerkSignInProps(- "t3code://app/CLERK-ROUTER/VIRTUAL/sign-up?__clerk_status=complete#/settings/connections",- true,- ),- ).toEqual({- forceRedirectUrl: "t3code://app/#/settings/connections",- signUpForceRedirectUrl: "t3code://app/#/settings/connections",- });- });-- it("preserves a clean development desktop route", () => {- expect(resolveClerkSignInProps("t3code-dev://app/#/settings/general", true)).toEqual({- forceRedirectUrl: "t3code-dev://app/#/settings/general",- signUpForceRedirectUrl: "t3code-dev://app/#/settings/general",- });- });-});diff --git a/apps/web/src/components/clerk/authRedirect.ts b/apps/web/src/components/clerk/authRedirect.tsdeleted file mode 100644index e0b07241c..000000000--- a/apps/web/src/components/clerk/authRedirect.ts+++ /dev/null@@ -1,21 +0,0 @@-export interface ClerkSignInProps {- forceRedirectUrl?: string;- signUpForceRedirectUrl?: string;-}--export function resolveClerkSignInProps(href: string, isElectron: boolean): ClerkSignInProps {- if (isElectron) {- // Electron routes through the hash, so reset any Clerk virtual pathname without losing the T3 page.- const redirectUrl = new URL(href);- redirectUrl.pathname = "/";- redirectUrl.search = "";-- return {- forceRedirectUrl: redirectUrl.toString(),- signUpForceRedirectUrl: redirectUrl.toString(),- };- }- // The sign-in modal can switch to sign-up, which follows its own redirect- // target; without one Clerk falls back to the URL the modal was opened from.- return { forceRedirectUrl: href, signUpForceRedirectUrl: href };-}diff --git a/apps/web/src/components/clerk/clerkAppearance.test.ts b/apps/web/src/components/clerk/clerkAppearance.test.tsdeleted file mode 100644index f7439810b..000000000--- a/apps/web/src/components/clerk/clerkAppearance.test.ts+++ /dev/null@@ -1,78 +0,0 @@-import { BUILT_IN_THEMES } from "@t3tools/shared/themePalettes";-import { describe, expect, it } from "vite-plus/test";--import { themeColorToHex, type ThemeColors } from "../../themePalette";-import { clerkAppearance } from "./clerkAppearance";--function contrastRatio(first: string, second: string): number {- const toRgb = (value: string) => {- const hex = themeColorToHex(value)?.slice(1, 7);- if (!hex) throw new Error(`Expected a theme color, received ${value}`);- return [0, 1, 2].map(- (channel) => Number.parseInt(hex.slice(channel * 2, channel * 2 + 2), 16) / 255,- );- };- const luminance = (value: string) =>- toRgb(value)- .map((channel) => (channel <= 0.03928 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4))- .reduce((sum, channel, index) => sum + channel * [0.2126, 0.7152, 0.0722][index]!, 0);- const lighter = Math.max(luminance(first), luminance(second));- const darker = Math.min(luminance(first), luminance(second));- return (lighter + 0.05) / (darker + 0.05);-}--function mixThemeColors(first: string, second: string, firstWeight: number): string {- const channels = [first, second].map((value) => {- const hex = themeColorToHex(value)?.slice(1, 7);- if (!hex) throw new Error(`Expected a theme color, received ${value}`);- return [0, 1, 2].map((channel) => Number.parseInt(hex.slice(channel * 2, channel * 2 + 2), 16));- });- const mixed = channels[0]!.map((channel, index) =>- Math.round(channel * firstWeight + channels[1]![index]! * (1 - firstWeight)),- );- return `#${mixed.map((channel) => channel.toString(16).padStart(2, "0")).join("")}`;-}--const builtInThemeModes = BUILT_IN_THEMES.flatMap((theme) =>- [theme.colors, theme.variants?.dark].filter((colors): colors is ThemeColors => !!colors),-);--describe("clerkAppearance", () => {- it("maps theme colors without overriding Clerk's component structure", () => {- expect(clerkAppearance).toEqual({- variables: {- colorPrimary: "var(--update-foreground)",- colorPrimaryForeground: "var(--card)",- colorDanger: "var(--error)",- colorSuccess: "var(--success)",- colorWarning: "var(--warning)",- colorNeutral: "var(--contrast-foreground)",- colorForeground: "var(--contrast-foreground)",- colorMuted: "color-mix(in srgb, var(--card) 98%, var(--contrast-foreground))",- colorMutedForeground: "var(--contrast-muted-foreground)",- colorBackground: "var(--card)",- colorInputForeground: "var(--contrast-foreground)",- colorInput: "var(--secondary)",- colorRing: "var(--ring)",- },- elements: {- formFieldErrorText: { color: "var(--error-foreground)" },- formFieldWarningText: { color: "var(--warning-foreground)" },- formFieldSuccessText: { color: "var(--success-foreground)" },- otpCodeFieldErrorText: { color: "var(--error-foreground)" },- otpCodeFieldSuccessText: { color: "var(--success-foreground)" },- },- });- });-- it.each(builtInThemeModes)("keeps Clerk text readable across a built-in palette", (colors) => {- const mutedSurface = mixThemeColors(colors.surface, colors.text, 0.98);-- expect(contrastRatio(colors.text, colors.surface)).toBeGreaterThanOrEqual(4.5);- expect(contrastRatio(colors.mutedForeground, mutedSurface)).toBeGreaterThanOrEqual(4.5);- expect(contrastRatio(colors.text, colors.secondary)).toBeGreaterThanOrEqual(4.5);- expect(contrastRatio(colors.updateForeground, colors.surface)).toBeGreaterThanOrEqual(4.5);- expect(contrastRatio(colors.errorForeground, colors.surface)).toBeGreaterThanOrEqual(4.5);- expect(contrastRatio(colors.warningForeground, colors.surface)).toBeGreaterThanOrEqual(4.5);- });-});diff --git a/apps/web/src/components/clerk/clerkAppearance.ts b/apps/web/src/components/clerk/clerkAppearance.tsdeleted file mode 100644index 5976bd43a..000000000--- a/apps/web/src/components/clerk/clerkAppearance.ts+++ /dev/null@@ -1,34 +0,0 @@-import type { ClerkProviderProps } from "@clerk/react";--/** Keeps Clerk's stock component structure while binding its color system to- * the live T3 Code palette. CSS variables make theme changes propagate to- * portaled sign-in and profile surfaces without remounting Clerk. */-export const clerkAppearance = {- variables: {- // Clerk reuses its primary color for filled buttons and bare links. The- // app's update foreground is the palette's action hue cast for readable- // text, while the card surface provides the inverse filled-control pair.- colorPrimary: "var(--update-foreground)",- colorPrimaryForeground: "var(--card)",- colorDanger: "var(--error)",- colorSuccess: "var(--success)",- colorWarning: "var(--warning)",- colorNeutral: "var(--contrast-foreground)",- colorForeground: "var(--contrast-foreground)",- // The stock dark theme's muted token is translucent. Clerk uses this as- // the footer's background, so derive an opaque muted surface from the card.- colorMuted: "color-mix(in srgb, var(--card) 98%, var(--contrast-foreground))",- colorMutedForeground: "var(--contrast-muted-foreground)",- colorBackground: "var(--card)",- colorInputForeground: "var(--contrast-foreground)",- colorInput: "var(--secondary)",- colorRing: "var(--ring)",- },- elements: {- formFieldErrorText: { color: "var(--error-foreground)" },- formFieldWarningText: { color: "var(--warning-foreground)" },- formFieldSuccessText: { color: "var(--success-foreground)" },- otpCodeFieldErrorText: { color: "var(--error-foreground)" },- otpCodeFieldSuccessText: { color: "var(--success-foreground)" },- },-} satisfies NonNullable<ClerkProviderProps["appearance"]>;diff --git a/apps/web/src/components/clerk/electronPasskeys.test.ts b/apps/web/src/components/clerk/electronPasskeys.test.tsdeleted file mode 100644index 582b801cc..000000000--- a/apps/web/src/components/clerk/electronPasskeys.test.ts+++ /dev/null@@ -1,60 +0,0 @@-import { createPasskeys } from "@clerk/electron/passkeys";-import { afterEach, describe, expect, it, vi } from "vite-plus/test";--const publicKeyOptions = {- allowCredentials: [],- challenge: new Uint8Array([1]),- rpId: "clerk.t3.codes",- timeout: 60_000,- userVerification: "preferred" as const,-};--const stubNativePasskeys = () => {- const get = vi.fn().mockResolvedValue({- ok: false,- error: { code: "cancelled", message: "user cancelled" },- });-- vi.stubGlobal("location", { protocol: "t3code:", hostname: "app" });- vi.stubGlobal("window", {- PublicKeyCredential: vi.fn(),- __clerk_internal_electron_passkeys: {- platform: "darwin",- electronMajor: 41,- get,- },- });-- return get;-};--describe("Electron passkeys", () => {- afterEach(() => {- vi.unstubAllGlobals();- });-- it("does not send an autofill request to the native bridge", async () => {- const get = stubNativePasskeys();- const passkeys = createPasskeys();-- const result = await passkeys.get({- publicKeyOptions,- conditionalUI: true,- });-- expect(get).not.toHaveBeenCalled();- expect(result.error).toMatchObject({ code: "passkey_operation_aborted" });- });-- it("sends an explicit passkey request to the native bridge", async () => {- const get = stubNativePasskeys();- const passkeys = createPasskeys();-- await passkeys.get({- publicKeyOptions,- conditionalUI: false,- });-- expect(get).toHaveBeenCalledOnce();- });-});diff --git a/apps/web/src/components/clerk/useT3ConnectAuthPrompt.tsx b/apps/web/src/components/clerk/useT3ConnectAuthPrompt.tsxdeleted file mode 100644index 859a122ff..000000000--- a/apps/web/src/components/clerk/useT3ConnectAuthPrompt.tsx+++ /dev/null@@ -1,12 +0,0 @@-import { useClerk } from "@clerk/react";--import { isElectron } from "../../env";-import { resolveClerkSignInProps } from "./authRedirect";--export function useT3ConnectAuthPrompt() {- const clerk = useClerk();- const openAuthPrompt = () => {- clerk.openSignIn(resolveClerkSignInProps(window.location.href, isElectron));- };- return { authPrompt: null, openAuthPrompt };-}diff --git a/apps/web/src/components/cloud/CloudEnvironmentConnectList.tsx b/apps/web/src/components/cloud/CloudEnvironmentConnectList.tsxdeleted file mode 100644index aba8ef6b0..000000000--- a/apps/web/src/components/cloud/CloudEnvironmentConnectList.tsx+++ /dev/null@@ -1,258 +0,0 @@-import { findErrorTraceId } from "@t3tools/client-runtime/errors";-import {- type EnvironmentConnectionPresentation,- RelayConnectionRegistration,- RelayConnectionTarget,-} from "@t3tools/client-runtime/connection";-import {- isAtomCommandInterrupted,- squashAtomCommandFailure,-} from "@t3tools/client-runtime/state/runtime";-import type { EnvironmentId } from "@t3tools/contracts";-import type { RelayClientEnvironmentRecord } from "@t3tools/contracts/relay";-import * as Option from "effect/Option";-import { type ReactNode, useCallback, useEffect, useState } from "react";--import { environmentCatalog } from "~/connection/catalog";-import { cn } from "~/lib/utils";-import { relayEnvironmentDiscovery } from "~/state/relay";-import { useRelayEnvironmentDiscovery } from "~/state/environments";-import { useAtomCommand } from "~/state/use-atom-command";-import { ConnectionStatusDot } from "../ConnectionStatusDot";-import { ITEM_ROW_CLASSNAME, ITEM_ROW_INNER_CLASSNAME } from "../settings/itemRows";-import { Button } from "../ui/button";-import { Skeleton } from "../ui/skeleton";-import { toastManager } from "../ui/toast";-import { presentSavedCloudEnvironmentConnection } from "./cloudEnvironmentConnectionPresentation";--export interface SavedCloudEnvironmentConnection {- readonly environmentId: EnvironmentId;- readonly connection: EnvironmentConnectionPresentation;-}--export function RemoteEnvironmentRowsSkeleton() {- return (- <div className={ITEM_ROW_CLASSNAME}>- <div className={ITEM_ROW_INNER_CLASSNAME}>- <div className="min-w-0 flex-1 space-y-2">- <Skeleton className="h-4 w-32 rounded-full" />- <Skeleton className="h-3 w-20 rounded-full" />- </div>- <Skeleton className="h-7 w-16 rounded-md" />- </div>- </div>- );-}--/**- * The user's linked environments from relay discovery, each with a- * Connect button. The primary environment is always excluded; already-saved- * environments are hidden unless `showSavedEnvironments` renders them with- * their live connection state (used by onboarding, where the full device mesh- * should be visible).- */-export function CloudEnvironmentConnectRows({- primaryEnvironmentId,- savedEnvironments,- showSavedEnvironments = false,- empty = null,-}: {- readonly primaryEnvironmentId: EnvironmentId | null;- readonly savedEnvironments: ReadonlyArray<SavedCloudEnvironmentConnection>;- readonly showSavedEnvironments?: boolean;- readonly empty?: ReactNode;-}) {- const environmentsState = useRelayEnvironmentDiscovery();- const registerEnvironment = useAtomCommand(environmentCatalog.register, {- reportFailure: false,- });- const refreshRelayEnvironments = useAtomCommand(relayEnvironmentDiscovery.refresh, {- reportFailure: false,- });- const connectRelayEnvironment = useCallback(- (environment: RelayClientEnvironmentRecord) =>- registerEnvironment(- new RelayConnectionRegistration({- target: new RelayConnectionTarget({- environmentId: environment.environmentId,- label: environment.label,- }),- }),- ),- [registerEnvironment],- );- const [connectingEnvironmentId, setConnectingEnvironmentId] = useState<EnvironmentId | null>(- null,- );- const savedById = new Map(- savedEnvironments.map((environment) => [environment.environmentId, environment]),- );-- useEffect(() => {- void refreshRelayEnvironments();- }, [refreshRelayEnvironments]);-- const connectEnvironment = async (environment: RelayClientEnvironmentRecord) => {- setConnectingEnvironmentId(environment.environmentId);- const result = await connectRelayEnvironment(environment);- setConnectingEnvironmentId(null);- if (result._tag === "Success") {- toastManager.add({- type: "success",- title: "Environment added",- description: `Connecting to ${environment.label} through its managed tunnel.`,- });- return;- }- if (isAtomCommandInterrupted(result)) {- return;- }- const cause = squashAtomCommandFailure(result);- const message =- cause instanceof Error ? cause.message : "Could not connect the linked environment.";- const traceId = findErrorTraceId(cause);- console.error("[t3-connect] Could not connect environment", { message, traceId, cause });- toastManager.add({- type: "error",- title: "Could not connect environment",- description: message,- data: traceId- ? {- secondaryActionProps: {- children: "Copy trace ID",- onClick: () => void navigator.clipboard?.writeText(traceId),- },- }- : undefined,- });- };-- const visibleEnvironments = [...environmentsState.environments.values()].filter(- ({ environment }) =>- environment.environmentId !== primaryEnvironmentId &&- (showSavedEnvironments || !savedById.has(environment.environmentId)),- );-- const standalone = showSavedEnvironments || savedEnvironments.length === 0;-- if (- standalone &&- visibleEnvironments.length === 0 &&- environmentsState.refreshing &&- environmentsState.environments.size === 0- ) {- return <RemoteEnvironmentRowsSkeleton />;- }-- if (standalone && visibleEnvironments.length === 0) {- // A failed or offline discovery is not "no environments" — misreporting it- // as empty would read as the user's devices having disappeared.- const discoveryProblem = environmentsState.offline- ? "You appear to be offline."- : (Option.getOrNull(environmentsState.error)?.message ?? null);- if (discoveryProblem !== null && !environmentsState.refreshing) {- return (- <div className={ITEM_ROW_CLASSNAME}>- <p className="text-sm font-medium text-destructive">Could not load linked environments</p>- <p className="mt-1 text-xs text-muted-foreground">{discoveryProblem}</p>- <Button- size="sm"- variant="outline"- className="mt-3"- onClick={() => void refreshRelayEnvironments()}- >- Try again- </Button>- </div>- );- }- return empty;- }-- return visibleEnvironments.map(({ environment, availability, error }) => {- const savedEnvironment = savedById.get(environment.environmentId);- const savedConnection = savedEnvironment- ? presentSavedCloudEnvironmentConnection(savedEnvironment.connection)- : null;- const dotClassName = savedConnection- ? savedConnection.tone === "connected"- ? "bg-success"- : savedConnection.tone === "connecting"- ? "bg-warning"- : savedConnection.tone === "error"- ? "bg-destructive"- : "bg-muted-foreground/35"- : availability === "online"- ? "bg-success"- : availability === "error"- ? "bg-destructive"- : availability === "checking"- ? "bg-warning"- : "bg-muted-foreground/35";- const statusText = savedConnection- ? savedConnection.statusText- : availability === "online"- ? "Available · Relay online"- : availability === "offline"- ? "Available · Relay offline"- : availability === "checking"- ? "Available · Checking relay status…"- : (Option.getOrNull(error)?.message ?? "Available · Relay status unavailable");- return (- <div key={environment.environmentId} className={ITEM_ROW_CLASSNAME}>- <div className={ITEM_ROW_INNER_CLASSNAME}>- <div className="min-w-0">- <div className="flex items-center gap-2">- <ConnectionStatusDot- dotClassName={dotClassName}- pingClassName={- savedConnection?.tone === "connecting" ||- (savedConnection === null && availability === "checking")- ? "bg-warning/60 duration-2000"- : null- }- tooltipText={- savedConnection- ? savedConnection.statusText- : availability === "online"- ? "Relay online"- : availability === "offline"- ? "Relay offline"- : availability === "checking"- ? "Checking relay status"- : (Option.getOrNull(error)?.message ?? "Relay status unavailable")- }- />- <p className="truncate text-sm font-medium">{environment.label}</p>- </div>- <p- className={cn(- "mt-1 truncate text-xs",- savedConnection?.tone === "error" ||- (savedConnection?.tone === "connecting" && savedEnvironment?.connection.error) ||- (savedConnection === null && availability === "error")- ? "text-destructive"- : "text-muted-foreground",- )}- >- {statusText}- </p>- </div>- {savedConnection ? (- <Button size="sm" variant="outline" disabled>- {savedConnection.buttonLabel}- </Button>- ) : (- <Button- size="sm"- disabled={connectingEnvironmentId !== null}- onClick={() => void connectEnvironment(environment)}- >- {connectingEnvironmentId === environment.environmentId ? "Connecting…" : "Connect"}- </Button>- )}- </div>- </div>- );- });-}diff --git a/apps/web/src/components/cloud/ConnectCliAuthSurface.tsx b/apps/web/src/components/cloud/ConnectCliAuthSurface.tsxdeleted file mode 100644index 5bfbc89e0..000000000--- a/apps/web/src/components/cloud/ConnectCliAuthSurface.tsx+++ /dev/null@@ -1,209 +0,0 @@-import { useAuth, useClerk, useUser } from "@clerk/react";-import { encodeConnectAuthCode, readConnectAuthorizeRequest } from "@t3tools/shared/connectAuth";-import { useCallback, useEffect, useRef, useState } from "react";--import {- buildConnectCliClerkAuthorizeUrl,- connectCliSignInRedirectUrl,- readConnectCliAuthState,- readConnectCliCallbackResult,- rememberConnectCliAuthState,-} from "../../cloud/connectCliAuth";-import { isElectron } from "../../env";-import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";-import { AuthSurfaceShell } from "../auth/AuthSurfaceShell";-import { resolveClerkSignInProps } from "../clerk/authRedirect";-import { Button } from "../ui/button";--function ConnectCliAuthMessage({- eyebrow,- title,- description,-}: {- readonly eyebrow?: string;- readonly title: string;- readonly description: string;-}) {- return (- <>- {eyebrow ? (- <p className="text-[10px] font-semibold tracking-[0.18em] text-blue-600 uppercase dark:text-blue-400">- {eyebrow}- </p>- ) : null}- <h1 className="mt-2 text-2xl font-semibold tracking-tight sm:text-3xl">{title}</h1>- <p className="mt-2 text-sm leading-relaxed text-muted-foreground">{description}</p>- </>- );-}--const invalidLinkMessage = {- eyebrow: "Authorization request",- title: "This connect link is incomplete",- description:- "The link is missing its authorization request. Re-run `t3 connect` in your terminal and open the freshly printed URL.",-} as const;--/**- * /connect: the URL the CLI prints for both flows. Waits for a Clerk session,- * then forwards the CLI's PKCE request to Clerk's authorize endpoint — with a- * loopback redirect URI when the request carries a port, so the code returns- * straight to the waiting CLI, and the hosted callback page otherwise.- */-export function ConnectCliAuthorizeSurface() {- const [request] = useState(() => readConnectAuthorizeRequest(new URL(window.location.href)));- const clerk = useClerk();- const { isLoaded, isSignedIn } = useAuth();- const signInOpened = useRef(false);- const redirecting = useRef(false);-- const openSignIn = useCallback(() => {- if (!request) {- return;- }- // Clerk redirects to the authorize endpoint itself once sign-in completes,- // so the callback's state check has to be armed before handing off.- rememberConnectCliAuthState(request.state);- clerk.openSignIn(- resolveClerkSignInProps(- connectCliSignInRedirectUrl(request, window.location.href),- isElectron,- ),- );- }, [clerk, request]);-- useEffect(() => {- if (!request || !isLoaded || redirecting.current) {- return;- }- if (!isSignedIn) {- if (!signInOpened.current) {- signInOpened.current = true;- openSignIn();- }- return;- }- const authorizeUrl = buildConnectCliClerkAuthorizeUrl(request);- if (!authorizeUrl) {- return;- }- redirecting.current = true;- rememberConnectCliAuthState(request.state);- window.location.assign(authorizeUrl);- }, [isLoaded, isSignedIn, openSignIn, request]);-- if (!request) {- return (- <AuthSurfaceShell>- <ConnectCliAuthMessage {...invalidLinkMessage} />- </AuthSurfaceShell>- );- }-- return (- <AuthSurfaceShell>- <ConnectCliAuthMessage- eyebrow={- request.loopbackPort === undefined- ? "Step 1 of 2 · Browser authorization"- : "Browser authorization"- }- title="Connecting your terminal"- description={- isSignedIn- ? "Redirecting to authorize remote access for your CLI…"- : "Sign in to continue authorizing remote access for your CLI."- }- />- {isLoaded && !isSignedIn ? (- <div className="mt-6">- <Button type="button" onClick={openSignIn}>- Sign in- </Button>- </div>- ) : null}- </AuthSurfaceShell>- );-}--/**- * /connect/callback: Clerk's redirect target. Shows the one-time code the- * user enters in the waiting terminal.- */-export function ConnectCliCallbackSurface() {- const [result] = useState(readConnectCliCallbackResult);- const [expectedState] = useState(readConnectCliAuthState);- const { user } = useUser();- const { copyToClipboard, isCopied } = useCopyToClipboard({ target: "authentication code" });-- if (!result) {- return (- <AuthSurfaceShell>- <ConnectCliAuthMessage- eyebrow="Step 2 of 2 · Terminal handoff"- title="Authorization did not complete"- description="No authorization code was returned. Re-run `t3 connect` in your terminal and try again."- />- </AuthSurfaceShell>- );- }-- // Fail closed: the legitimate callback always lands in the same browser- // that visited /connect (which recorded the state), so a missing or- // mismatched state means this page was reached some other way — the CSRF- // shape the state parameter exists to stop. Refuse to display a code.- if (expectedState === null || expectedState !== result.state) {- return (- <AuthSurfaceShell>- <ConnectCliAuthMessage- eyebrow="Step 2 of 2 · Terminal handoff"- title="This code belongs to a different request"- description="This authorization response does not match a connect request started in this browser. Re-run `t3 connect` in your terminal and open the freshly printed URL in this browser."- />- </AuthSurfaceShell>- );- }-- const accountLabel = user?.primaryEmailAddress?.emailAddress ?? user?.username ?? null;- const authCode = encodeConnectAuthCode(result);-- return (- <AuthSurfaceShell>- <ConnectCliAuthMessage- eyebrow="Step 2 of 2 · Terminal handoff"- title="Almost connected"- description={- accountLabel- ? `Enter this code in your waiting terminal to connect it as ${accountLabel}.`- : "Enter this code in your waiting terminal to finish connecting."- }- />-- <div className="mt-6 overflow-hidden rounded-xl border border-border/80 bg-background/65">- <div className="flex items-center justify-between border-b border-border/70 px-4 py-2.5">- <span className="text-[10px] font-semibold tracking-[0.16em] text-muted-foreground uppercase">- One-time authorization code- </span>- <span className="font-mono text-[10px] text-muted-foreground">expires shortly</span>- </div>- <code- className="block p-4 font-mono text-sm leading-relaxed break-all select-all"- data-testid="connect-auth-code"- >- {authCode}- </code>- </div>-- <div className="mt-4 flex items-center gap-3">- <Button type="button" onClick={() => copyToClipboard(authCode)}>- {isCopied ? "Copied!" : "Copy authorization code"}- </Button>- </div>-- <p className="mt-6 text-xs leading-relaxed text-muted-foreground">- Only enter this code in a terminal session you started yourself. Anyone holding it can link- their machine to your account while it is valid.- </p>- </AuthSurfaceShell>- );-}diff --git a/apps/web/src/components/cloud/ConnectOnboardingDialog.tsx b/apps/web/src/components/cloud/ConnectOnboardingDialog.tsxdeleted file mode 100644index 93fb50e01..000000000--- a/apps/web/src/components/cloud/ConnectOnboardingDialog.tsx+++ /dev/null@@ -1,433 +0,0 @@-import { useAuth } from "@clerk/react";-import { AuthAdministrativeScopes, AuthRelayWriteScope } from "@t3tools/contracts";-import { CheckIcon } from "lucide-react";-import { useEffect, useRef, useState } from "react";--import {- CONNECT_ONBOARDING_OPT_OUT_STORAGE_KEY,- ConnectOnboardingOptOutSchema,- EMPTY_CONNECT_ONBOARDING_OPT_OUT_STATE,-} from "~/cloud/connectOnboarding";-import { hasCloudPublicConfig } from "~/cloud/publicConfig";-import { useCloudLinkController } from "~/cloud/useCloudLinkController";-import { usePrimarySessionState } from "~/environments/primary";-import { useLocalStorage } from "~/hooks/useLocalStorage";-import { cn } from "~/lib/utils";-import { useEnvironments, usePrimaryEnvironment } from "~/state/environments";-import { CloudEnvironmentConnectRows } from "./CloudEnvironmentConnectList";-import { Button } from "../ui/button";-import { Checkbox } from "../ui/checkbox";-import {- Dialog,- DialogDescription,- DialogFooter,- DialogHeader,- DialogPanel,- DialogPopup,- DialogTitle,-} from "../ui/dialog";-import { Switch } from "../ui/switch";-import { toastManager } from "../ui/toast";--/**- * Post-sign-in onboarding wizard for remote access. Opens on every in-session- * sign-in — sign-out removes the connected relay environments, so each new- * session starts with no devices to reach. It first prompts to publish this- * environment (managed tunnel + agent activity, both defaulting on) when the- * current session is authorized to manage the relay link, then lists the- * account's linked environments so every device can be connected right- * away. A cold load with a restored session does not count as a sign-in.- */-export function ConnectOnboardingDialog() {- if (!hasCloudPublicConfig()) return null;-- return <ConfiguredConnectOnboardingDialog />;-}--type OnboardingStep = "publish" | "devices";--function ConfiguredConnectOnboardingDialog() {- // Mirrors ManagedRelayAuthProvider: a pending Clerk session must not read as- // signed-out, or its later activation would look like a fresh sign-in.- const { isLoaded, isSignedIn, userId } = useAuth({ treatPendingAsSignedOut: false });- const [optOutState, setOptOutState] = useLocalStorage(- CONNECT_ONBOARDING_OPT_OUT_STORAGE_KEY,- EMPTY_CONNECT_ONBOARDING_OPT_OUT_STATE,- ConnectOnboardingOptOutSchema,- );-- const desktopBridge = window.desktopBridge;- const primarySessionState = usePrimarySessionState();- const currentSessionScopes = desktopBridge- ? AuthAdministrativeScopes- : primarySessionState.data?.authenticated- ? (primarySessionState.data.scopes ?? null)- : null;- const canManageRelay = currentSessionScopes?.includes(AuthRelayWriteScope) ?? false;- // The publish step is only offered when we know the answer; opening the- // wizard before the session state resolves would let the step set change- // mid-flight. A failed session read still opens the wizard — it just means- // no publish step.- const sessionScopesKnown =- Boolean(desktopBridge) ||- primarySessionState.data !== null ||- primarySessionState.error !== null;-- const controller = useCloudLinkController();- const showPublishStep = canManageRelay && controller.linkState.target !== null;- const steps: ReadonlyArray<OnboardingStep> = showPublishStep- ? ["publish", "devices"]- : ["devices"];-- const [requestedAccount, setRequestedAccount] = useState<string | null>(null);- const [openForAccount, setOpenForAccount] = useState<string | null>(null);- const [step, setStep] = useState<OnboardingStep>("devices");- const [exposeEnvironment, setExposeEnvironment] = useState(true);- const [publishAgentActivity, setPublishAgentActivity] = useState(true);- const [dontShowAgain, setDontShowAgain] = useState(false);- const [isApplying, setIsApplying] = useState(false);- const prefilledFromLinkStateRef = useRef(false);- const observedAccountRef = useRef<string | null | undefined>(undefined);-- const optOutAccounts = optOutState.optOutAccounts;-- // Every sign-in or account switch that completes during this session- // requests the wizard — account transitions clear the connected relay- // environments, so each new session starts with no devices to reach. A cold- // load observes undefined → account and must not re-prompt.- useEffect(() => {- if (!isLoaded) return;- // A loaded-but-incomplete snapshot (signed in, user id not yet populated)- // must not be recorded as signed-out — the next render would then look- // like a fresh sign-in on a cold load.- if (isSignedIn && !userId) return;- const previousAccount = observedAccountRef.current;- const nextAccount = isSignedIn && userId ? userId : null;- observedAccountRef.current = nextAccount;- if (previousAccount !== undefined && previousAccount !== nextAccount && nextAccount !== null) {- setRequestedAccount(nextAccount);- }- }, [isLoaded, isSignedIn, userId]);-- // A manageable session implies a primary environment, so when the scopes- // allow publishing, wait for the connection target too — otherwise the- // wizard could open on the devices step moments before the publish step- // becomes available and freeze there.- const publishStepDecided = !canManageRelay || controller.linkState.target !== null;-- // Open once the session scopes resolve so the step set is stable. Accounts- // that chose "Don't show this again" are skipped.- useEffect(() => {- if (requestedAccount === null || openForAccount !== null) return;- if (optOutAccounts.includes(requestedAccount)) {- setRequestedAccount(null);- return;- }- if (!sessionScopesKnown || !publishStepDecided) return;- setRequestedAccount(null);- prefilledFromLinkStateRef.current = false;- setExposeEnvironment(true);- setPublishAgentActivity(true);- setDontShowAgain(false);- setStep(canManageRelay && controller.linkState.target !== null ? "publish" : "devices");- setOpenForAccount(requestedAccount);- }, [- canManageRelay,- controller.linkState.target,- openForAccount,- optOutAccounts,- publishStepDecided,- requestedAccount,- sessionScopesKnown,- ]);-- // Signing out (or switching accounts) mid-wizard invalidates everything the- // wizard would do — close it and let the sign-in trigger re-evaluate.- useEffect(() => {- if (openForAccount !== null && (!isSignedIn || userId !== openForAccount)) {- setOpenForAccount(null);- }- if (requestedAccount !== null && (!isSignedIn || userId !== requestedAccount)) {- setRequestedAccount(null);- }- }, [isSignedIn, openForAccount, requestedAccount, userId]);-- // Toggles default on, but an environment that is already linked should show- // its actual configuration instead of silently proposing to rewrite it.- // Only when the link belongs to the account being onboarded, though — after- // an account switch the cached link state can still describe the previous- // account's setup.- const linkStateData = controller.linkState.data;- useEffect(() => {- if (openForAccount === null || prefilledFromLinkStateRef.current || linkStateData === null) {- return;- }- prefilledFromLinkStateRef.current = true;- if (linkStateData.linked && linkStateData.cloudUserId === openForAccount) {- setExposeEnvironment(linkStateData.managedTunnelActive ?? linkStateData.linked);- setPublishAgentActivity(linkStateData.publishAgentActivity);- }- }, [linkStateData, openForAccount]);-- const complete = () => {- // Keep the wizard up while a link request is in flight so its outcome- // (and any failure) stays visible.- if (isApplying) return;- const account = openForAccount;- setOpenForAccount(null);- if (account !== null && dontShowAgain) {- setOptOutState((state) =>- state.optOutAccounts.includes(account)- ? state- : { optOutAccounts: [...state.optOutAccounts, account] },- );- }- };-- const applyPublishSelection = async () => {- // The wizard only ever enables — with both toggles off there is nothing to- // apply, and an existing link must not be torn down from onboarding.- if (!exposeEnvironment && !publishAgentActivity) {- setStep("devices");- return;- }- setIsApplying(true);- const ok = await controller.reconcileCloudState({- managedTunnel: exposeEnvironment,- publish: publishAgentActivity,- });- setIsApplying(false);- if (!ok) return;- toastManager.add({- type: "success",- title: "Remote access enabled",- description: exposeEnvironment- ? "This environment is available to your other devices through its managed tunnel."- : "This environment publishes agent activity to your mobile clients.",- });- setStep("devices");- };-- return (- <Dialog- open={openForAccount !== null}- onOpenChange={(open) => {- // Keep the dialog up while a link request is in flight so its outcome- // (and any failure) stays visible.- if (!open && !isApplying) complete();- }}- >- <DialogPopup className="max-w-xl">- <DialogHeader>- <DialogTitle>Set up remote access</DialogTitle>- <DialogDescription>- Mesh your devices together — publish this environment and connect the rest, all in one- place.- </DialogDescription>- {steps.length > 1 ? (- <OnboardingStepper- steps={steps}- currentStep={step}- disabled={isApplying}- onStepSelect={setStep}- />- ) : null}- </DialogHeader>- <DialogPanel>- {step === "publish" ? (- <PublishStep- exposeEnvironment={exposeEnvironment}- publishAgentActivity={publishAgentActivity}- disabled={isApplying}- operationError={controller.operationError}- onExposeEnvironmentChange={setExposeEnvironment}- onPublishAgentActivityChange={setPublishAgentActivity}- />- ) : (- <DevicesStep />- )}- </DialogPanel>- <DialogFooter variant="bare" className="sm:justify-between">- <label className="flex cursor-pointer items-center gap-2 self-start text-xs text-muted-foreground sm:self-center">- <Checkbox- checked={dontShowAgain}- onCheckedChange={(checked) => setDontShowAgain(checked === true)}- />- Don't show this again- </label>- <div className="flex flex-col-reverse gap-2 sm:flex-row">- {step === "publish" ? (- <>- <Button variant="ghost" disabled={isApplying} onClick={() => setStep("devices")}>- Not now- </Button>- <Button- disabled={- isApplying || (controller.linkState.isPending && linkStateData === null)- }- onClick={() => void applyPublishSelection()}- >- {isApplying ? "Enabling…" : "Continue"}- </Button>- </>- ) : (- <Button disabled={isApplying} onClick={complete}>- Done- </Button>- )}- </div>- </DialogFooter>- </DialogPopup>- </Dialog>- );-}--const STEP_LABELS: Record<OnboardingStep, string> = {- publish: "Publish",- devices: "Connect devices",-};--function OnboardingStepper({- steps,- currentStep,- disabled,- onStepSelect,-}: {- readonly steps: ReadonlyArray<OnboardingStep>;- readonly currentStep: OnboardingStep;- readonly disabled: boolean;- readonly onStepSelect: (step: OnboardingStep) => void;-}) {- const currentIndex = steps.indexOf(currentStep);- return (- <div className="grid grid-cols-2 gap-2">- {steps.map((step, index) => (- <button- key={step}- type="button"- disabled={disabled}- className={cn(- "grid min-w-0 grid-cols-[1rem_minmax(0,1fr)] gap-x-2 rounded-lg border px-3 py-2 text-left",- index === currentIndex- ? "border-primary bg-primary/10 ring-1 ring-primary/25"- : index < currentIndex- ? "border-border bg-background"- : "border-border bg-muted/40",- )}- onClick={() => onStepSelect(step)}- >- <span- className={cn(- "row-span-2 mt-0.5 grid size-4 place-items-center rounded-full border",- index < currentIndex- ? "border-primary bg-primary text-primary-foreground"- : index === currentIndex- ? "border-primary bg-background"- : "border-muted-foreground/35 bg-background",- )}- aria-hidden- >- {index < currentIndex ? <CheckIcon className="size-3" /> : null}- </span>- <span className="text-[10px] font-medium uppercase text-muted-foreground">- Step {index + 1}- </span>- <span className="truncate text-xs font-semibold text-foreground">- {STEP_LABELS[step]}- </span>- </button>- ))}- </div>- );-}--function PublishStep({- exposeEnvironment,- publishAgentActivity,- disabled,- operationError,- onExposeEnvironmentChange,- onPublishAgentActivityChange,-}: {- readonly exposeEnvironment: boolean;- readonly publishAgentActivity: boolean;- readonly disabled: boolean;- readonly operationError: string | null;- readonly onExposeEnvironmentChange: (enabled: boolean) => void;- readonly onPublishAgentActivityChange: (enabled: boolean) => void;-}) {- return (- <div className="space-y-3">- <div className="rounded-lg border">- <OnboardingToggleRow- title="Publish this environment"- description="Make this environment available to your other devices through a managed tunnel."- checked={exposeEnvironment}- disabled={disabled}- onCheckedChange={onExposeEnvironmentChange}- />- <OnboardingToggleRow- title="Publish agent activity"- description="Send activity from this environment to your mobile clients for push notifications and Live Activities."- checked={publishAgentActivity}- disabled={disabled}- onCheckedChange={onPublishAgentActivityChange}- />- </div>- {operationError ? <p className="text-xs text-destructive">{operationError}</p> : null}- </div>- );-}--function OnboardingToggleRow({- title,- description,- checked,- disabled,- onCheckedChange,-}: {- readonly title: string;- readonly description: string;- readonly checked: boolean;- readonly disabled: boolean;- readonly onCheckedChange: (enabled: boolean) => void;-}) {- return (- <div className="flex items-start justify-between gap-4 border-t border-border/60 px-4 py-3 first:border-t-0">- <div className="min-w-0">- <p className="text-sm font-medium">{title}</p>- <p className="mt-1 text-xs text-muted-foreground">{description}</p>- </div>- <Switch- aria-label={title}- checked={checked}- disabled={disabled}- onCheckedChange={onCheckedChange}- />- </div>- );-}--function DevicesStep() {- const { environments } = useEnvironments();- const primaryEnvironment = usePrimaryEnvironment();- const savedEnvironments = environments.filter(- (environment) => environment.entry.target._tag !== "PrimaryConnectionTarget",- );-- return (- <div className="overflow-hidden rounded-lg border">- <CloudEnvironmentConnectRows- primaryEnvironmentId={primaryEnvironment?.environmentId ?? null}- savedEnvironments={savedEnvironments}- showSavedEnvironments- empty={- <p className="px-4 py-6 text-center text-sm text-muted-foreground">- No other environments are published to your account yet. Publish one from another device- and it will show up here.- </p>- }- />- </div>- );-}diff --git a/apps/web/src/components/cloud/RelayClientInstallDialog.tsx b/apps/web/src/components/cloud/RelayClientInstallDialog.tsxdeleted file mode 100644index 2198c1c68..000000000--- a/apps/web/src/components/cloud/RelayClientInstallDialog.tsx+++ /dev/null@@ -1,123 +0,0 @@-import { DownloadIcon } from "lucide-react";-import { useSyncExternalStore } from "react";-import type { RelayClientInstallProgressStage } from "@t3tools/contracts";--import {- completeRelayClientInstallDialogClose,- readRelayClientInstallDialogState,- respondToRelayClientInstallConfirmation,- subscribeRelayClientInstallDialog,-} from "../../cloud/relayClientInstallDialog";-import { Button } from "../ui/button";-import {- Dialog,- DialogDescription,- DialogFooter,- DialogHeader,- DialogPanel,- DialogPopup,- DialogTitle,-} from "../ui/dialog";-const installSteps: ReadonlyArray<{- readonly stage: RelayClientInstallProgressStage;- readonly label: string;-}> = [- { stage: "checking", label: "Checking current installation" },- { stage: "waiting_for_lock", label: "Waiting for installer" },- { stage: "downloading", label: "Downloading relay client" },- { stage: "verifying", label: "Verifying download" },- { stage: "installing", label: "Installing relay client" },- { stage: "validating", label: "Validating executable" },- { stage: "activating", label: "Activating installation" },-];--export function RelayClientInstallDialog() {- const state = useSyncExternalStore(- subscribeRelayClientInstallDialog,- readRelayClientInstallDialogState,- readRelayClientInstallDialogState,- );- const view = state.status === "closing" ? state.view : state;- const isConfirming = view.status === "confirming";- const isInstalling = view.status === "installing";- const activeStepIndex = isInstalling- ? installSteps.findIndex(({ stage }) => stage === view.stage)- : -1;- const activeStep = installSteps[activeStepIndex];-- return (- <Dialog- open={state.status === "confirming" || state.status === "installing"}- onOpenChange={(open) => {- if (!open && isConfirming) {- respondToRelayClientInstallConfirmation(false);- }- }}- onOpenChangeComplete={(open) => {- if (!open) {- completeRelayClientInstallDialogClose();- }- }}- >- <DialogPopup className="max-w-md" showCloseButton={isConfirming}>- <DialogHeader>- <div className="flex size-9 items-center justify-center rounded-lg border border-border/70 bg-muted/60">- <DownloadIcon aria-hidden className="size-4.5 text-muted-foreground" />- </div>- <DialogTitle>- {isInstalling ? "Installing relay client" : "Install relay client?"}- </DialogTitle>- <DialogDescription>- {isInstalling- ? "Akeru Bot is preparing this environment for secure remote access."- : "Akeru Bot needs the relay client to make this environment available for remote access."}- </DialogDescription>- </DialogHeader>- <DialogPanel scrollFade={false}>- {isInstalling ? (- <div className="space-y-2.5">- <div className="flex items-center justify-between gap-3 text-sm">- <p aria-live="polite" className="font-medium text-foreground">- {activeStep?.label}- </p>- <p className="shrink-0 tabular-nums text-muted-foreground">- {activeStepIndex + 1} of {installSteps.length}- </p>- </div>- <progress- aria-label="Relay client installation progress"- className="h-2 w-full appearance-none overflow-hidden rounded-full bg-muted [&::-moz-progress-bar]:rounded-full [&::-moz-progress-bar]:bg-primary [&::-webkit-progress-bar]:rounded-full [&::-webkit-progress-bar]:bg-muted [&::-webkit-progress-value]:rounded-full [&::-webkit-progress-value]:bg-primary"- max={installSteps.length}- value={activeStepIndex + 1}- />- <p className="text-xs leading-relaxed text-muted-foreground">- Keep Akeru Bot open while the relay client is installed.- </p>- </div>- ) : (- <div className="rounded-xl border border-border/70 bg-muted/35 p-3">- <p className="text-sm font-medium text-foreground">Managed relay client</p>- <p className="mt-1 text-sm leading-relaxed text-muted-foreground">- Akeru Bot will download and install version{" "}- {view.status === "confirming" ? view.version : ""} locally.- </p>- </div>- )}- </DialogPanel>- {isConfirming ? (- <DialogFooter>- <Button- variant="outline"- onClick={() => respondToRelayClientInstallConfirmation(false)}- >- Cancel- </Button>- <Button onClick={() => respondToRelayClientInstallConfirmation(true)}>- Download and install- </Button>- </DialogFooter>- ) : null}- </DialogPopup>- </Dialog>- );-}diff --git a/apps/web/src/components/cloud/cloudEnvironmentConnectionPresentation.test.ts b/apps/web/src/components/cloud/cloudEnvironmentConnectionPresentation.test.tsdeleted file mode 100644index 654c2462a..000000000--- a/apps/web/src/components/cloud/cloudEnvironmentConnectionPresentation.test.ts+++ /dev/null@@ -1,55 +0,0 @@-import type { EnvironmentConnectionPresentation } from "@t3tools/client-runtime/connection";-import { describe, expect, it } from "vite-plus/test";--import { presentSavedCloudEnvironmentConnection } from "./cloudEnvironmentConnectionPresentation";--function connection(- phase: EnvironmentConnectionPresentation["phase"],- error: string | null = null,-): EnvironmentConnectionPresentation {- return { phase, error, traceId: null };-}--describe("saved cloud environment connection presentation", () => {- it("only labels a live connection as connected", () => {- expect(presentSavedCloudEnvironmentConnection(connection("connected"))).toEqual({- buttonLabel: "Connected",- statusText: "Connected",- tone: "connected",- });-- expect(presentSavedCloudEnvironmentConnection(connection("connecting"))).toEqual({- buttonLabel: "Connecting…",- statusText: "Connecting...",- tone: "connecting",- });- });-- it("surfaces a failed attempt while the supervisor reconnects", () => {- expect(- presentSavedCloudEnvironmentConnection(- connection("reconnecting", "Relay environment endpoint is unavailable."),- ),- ).toEqual({- buttonLabel: "Reconnecting…",- statusText:- "Failed to connect. Reconnecting... Reason: Relay environment endpoint is unavailable.",- tone: "connecting",- });- });-- it.each([- ["error", "Connection failed", "Connection failed. Reason: Access denied.", "error"],- ["offline", "Offline", "Offline", "idle"],- ["available", "Not connected", "Available", "idle"],- ] as const)(- "presents %s without claiming the environment is connected",- (phase, buttonLabel, statusText, tone) => {- expect(- presentSavedCloudEnvironmentConnection(- connection(phase, phase === "error" ? "Access denied." : null),- ),- ).toEqual({ buttonLabel, statusText, tone });- },- );-});diff --git a/apps/web/src/components/cloud/cloudEnvironmentConnectionPresentation.ts b/apps/web/src/components/cloud/cloudEnvironmentConnectionPresentation.tsdeleted file mode 100644index f2f3395f6..000000000--- a/apps/web/src/components/cloud/cloudEnvironmentConnectionPresentation.ts+++ /dev/null@@ -1,58 +0,0 @@-import {- connectionStatusText,- type EnvironmentConnectionPresentation,-} from "@t3tools/client-runtime/connection";--export interface SavedCloudEnvironmentConnectionPresentation {- readonly buttonLabel: string;- readonly statusText: string;- readonly tone: "connected" | "connecting" | "error" | "idle";-}--/**- * Present the live supervisor state for an environment that is already in the- * connection catalog. Catalog membership only means the environment is saved;- * it does not mean the connection attempt succeeded.- */-export function presentSavedCloudEnvironmentConnection(- connection: EnvironmentConnectionPresentation,-): SavedCloudEnvironmentConnectionPresentation {- switch (connection.phase) {- case "connected":- return {- buttonLabel: "Connected",- statusText: connectionStatusText(connection),- tone: "connected",- };- case "connecting":- return {- buttonLabel: "Connecting…",- statusText: connectionStatusText(connection),- tone: "connecting",- };- case "reconnecting":- return {- buttonLabel: "Reconnecting…",- statusText: connectionStatusText(connection),- tone: "connecting",- };- case "error":- return {- buttonLabel: "Connection failed",- statusText: connectionStatusText(connection),- tone: "error",- };- case "offline":- return {- buttonLabel: "Offline",- statusText: connectionStatusText(connection),- tone: "idle",- };- case "available":- return {- buttonLabel: "Not connected",- statusText: connectionStatusText(connection),- tone: "idle",- };- }-}diff --git a/apps/web/src/components/privacy/PolicyNotice.test.ts b/apps/web/src/components/privacy/PolicyNotice.test.tsnew file mode 100644index 000000000..9d7d13673--- /dev/null+++ b/apps/web/src/components/privacy/PolicyNotice.test.ts@@ -0,0 +1,45 @@+import { describe, expect, it } from "vite-plus/test";++import { needsPolicyAcknowledgement, shouldShowPolicyNotice } from "./PolicyNotice";++describe("needsPolicyAcknowledgement", () => {+ it("requires each current local policy version", () => {+ expect(+ needsPolicyAcknowledgement({+ reviewedPrivacyPolicyVersion: "",+ reviewedTermsVersion: "",+ }),+ ).toBe(true);+ expect(+ needsPolicyAcknowledgement({+ reviewedPrivacyPolicyVersion: "2026-08-31",+ reviewedTermsVersion: "2026-08-31",+ }),+ ).toBe(false);+ });+});++describe("shouldShowPolicyNotice", () => {+ it("opens only for a hydrated packaged desktop build with outdated policies", () => {+ expect(+ shouldShowPolicyNotice({+ hydrated: true,+ isDesktop: true,+ isPackaged: true,+ needsAcknowledgement: true,+ }),+ ).toBe(true);++ for (const key of ["hydrated", "isDesktop", "isPackaged", "needsAcknowledgement"] as const) {+ expect(+ shouldShowPolicyNotice({+ hydrated: true,+ isDesktop: true,+ isPackaged: true,+ needsAcknowledgement: true,+ [key]: false,+ }),+ ).toBe(false);+ }+ });+});diff --git a/apps/web/src/components/privacy/PolicyNotice.tsx b/apps/web/src/components/privacy/PolicyNotice.tsxnew file mode 100644index 000000000..9c3a7637b--- /dev/null+++ b/apps/web/src/components/privacy/PolicyNotice.tsx@@ -0,0 +1,103 @@+import {+ AKERU_MARKETING_SITE_URL,+ AKERU_PRIVACY_POLICY_VERSION,+ AKERU_TERMS_VERSION,+ type ClientSettings,+} from "@t3tools/contracts/settings";++import { IS_PACKAGED_DESKTOP } from "~/branding";+import { isElectron } from "~/env";+import {+ useClientSettings,+ useClientSettingsHydrated,+ useUpdateClientSettings,+} from "~/hooks/useSettings";+import { Button } from "../ui/button";+import {+ Dialog,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogPanel,+ DialogPopup,+ DialogTitle,+} from "../ui/dialog";++export function needsPolicyAcknowledgement(+ settings: Pick<ClientSettings, "reviewedPrivacyPolicyVersion" | "reviewedTermsVersion">,+): boolean {+ return (+ settings.reviewedPrivacyPolicyVersion !== AKERU_PRIVACY_POLICY_VERSION ||+ settings.reviewedTermsVersion !== AKERU_TERMS_VERSION+ );+}++export function shouldShowPolicyNotice(input: {+ readonly hydrated: boolean;+ readonly isDesktop: boolean;+ readonly isPackaged: boolean;+ readonly needsAcknowledgement: boolean;+}): boolean {+ return input.hydrated && input.isDesktop && input.isPackaged && input.needsAcknowledgement;+}++export function PolicyNotice() {+ const hydrated = useClientSettingsHydrated();+ const settings = useClientSettings();+ const updateSettings = useUpdateClientSettings();+ const open = shouldShowPolicyNotice({+ hydrated,+ isDesktop: isElectron,+ isPackaged: IS_PACKAGED_DESKTOP,+ needsAcknowledgement: needsPolicyAcknowledgement(settings),+ });++ return (+ <Dialog open={open}>+ <DialogPopup showCloseButton={false}>+ <DialogHeader>+ <DialogTitle>Review Akeru Bot policies</DialogTitle>+ <DialogDescription>+ Akeru Bot runs locally. Provider prompts and enabled online features still send data to+ their listed services.+ </DialogDescription>+ </DialogHeader>+ <DialogPanel className="space-y-3 text-sm text-muted-foreground">+ <p>+ Read the{" "}+ <a+ className="text-foreground underline underline-offset-4"+ href={`${AKERU_MARKETING_SITE_URL}/terms-of-service`}+ target="_blank"+ rel="noreferrer"+ >+ Terms of Use+ </a>{" "}+ and{" "}+ <a+ className="text-foreground underline underline-offset-4"+ href={`${AKERU_MARKETING_SITE_URL}/privacy-policy`}+ target="_blank"+ rel="noreferrer"+ >+ Privacy Policy+ </a>+ .+ </p>+ </DialogPanel>+ <DialogFooter>+ <Button+ onClick={() =>+ updateSettings({+ reviewedPrivacyPolicyVersion: AKERU_PRIVACY_POLICY_VERSION,+ reviewedTermsVersion: AKERU_TERMS_VERSION,+ })+ }+ >+ I reviewed these drafts+ </Button>+ </DialogFooter>+ </DialogPopup>+ </Dialog>+ );+}diff --git a/apps/web/src/components/roster/BotDetailsPanel.test.tsx b/apps/web/src/components/roster/BotDetailsPanel.test.tsxindex aa1fc4f92..44ecd9c06 100644--- a/apps/web/src/components/roster/BotDetailsPanel.test.tsx+++ b/apps/web/src/components/roster/BotDetailsPanel.test.tsx@@ -4,7 +4,12 @@ import * as NodeFS from "node:fs";import { renderToStaticMarkup } from "react-dom/server";import { describe, expect, it } from "vite-plus/test";-import { BotDetailsPanel, reduceBotDetailsPanelState } from "./BotDetailsPanel";+import {+ BotDetailsPanel,+ parseBotUsageCapInput,+ reduceBotDetailsPanelState,+ resolveBotUsageCapForProvider,+} from "./BotDetailsPanel";import type { Bot } from "./types";const bot: Bot = {@@ -36,6 +41,8 @@ describe("BotDetailsPanel", () => {expect(markup).toContain('aria-label="Bot label"');expect(markup).toContain('aria-label="Bot description"');expect(markup).toContain("Connect a provider");+ expect(markup).toContain("Token hard stop");+ expect(markup).toContain('aria-label="Token hard stop"');expect(markup).toContain(">Sandbox</div>");expect(markup).toContain('aria-label="Sandbox provider"');expect(markup).toContain('aria-label="Bot usage"');@@ -56,6 +63,34 @@ describe("BotDetailsPanel", () => {expect(markup).not.toContain("border-t border-border");});+ it("sets, clears, and rejects invalid hard stops", () => {+ expect(parseBotUsageCapInput("50000")).toEqual({+ valid: true,+ value: { unit: "tokens", limit: 50_000 },+ });+ expect(parseBotUsageCapInput(" ")).toEqual({ valid: true, value: null });+ expect(parseBotUsageCapInput("0")).toEqual({ valid: false, value: null });+ expect(parseBotUsageCapInput("1.5")).toEqual({ valid: false, value: null });+ });++ it("clears hard stops for occupancy-only providers", () => {+ expect(resolveBotUsageCapForProvider("50000", "cursor")).toEqual({+ available: false,+ valid: true,+ value: null,+ });+ expect(resolveBotUsageCapForProvider("50000", "grok")).toEqual({+ available: false,+ valid: true,+ value: null,+ });+ expect(resolveBotUsageCapForProvider("50000", "codex")).toEqual({+ available: true,+ valid: true,+ value: { unit: "tokens", limit: 50_000 },+ });+ });+it("uses the configured right-panel shortcut while open or closed", () => {const source = NodeFS.readFileSync(new URL("./BotDetailsPanel.tsx", import.meta.url), "utf8");@@ -108,6 +143,7 @@ describe("BotDetailsPanel", () => {expect(source).toContain("onSaveBot=");expect(source).toContain("threadRef={threadRef}");expect(source).toContain("voiceEnabled,");+ expect(source).toContain("usageCap,");expect(source).toContain("sandbox,");expect(source).toContain("disabledMcpServerIds,");expect(source).not.toContain("RightPanelTabs");diff --git a/apps/web/src/components/roster/BotDetailsPanel.tsx b/apps/web/src/components/roster/BotDetailsPanel.tsxindex 133bf1edd..9bb8209d6 100644--- a/apps/web/src/components/roster/BotDetailsPanel.tsx+++ b/apps/web/src/components/roster/BotDetailsPanel.tsx@@ -80,11 +80,36 @@ export function reduceBotDetailsPanelState(return { ...state, mobileOpen: action.open };}+export function parseBotUsageCapInput(input: string): {+ readonly valid: boolean;+ readonly value: Bot["usageCap"];+} {+ if (input.trim().length === 0) return { valid: true, value: null };+ const limit = Number(input);+ if (!Number.isSafeInteger(limit) || limit <= 0) return { valid: false, value: null };+ return { valid: true, value: { unit: "tokens", limit } };+}++export function resolveBotUsageCapForProvider(+ input: string,+ providerDriver?: string,+): {+ readonly available: boolean;+ readonly valid: boolean;+ readonly value: Bot["usageCap"];+} {+ if (providerDriver === "cursor" || providerDriver === "grok") {+ return { available: false, valid: true, value: null };+ }+ return { available: true, ...parseBotUsageCapInput(input) };+}+export interface BotProfileUpdate {readonly name: string;readonly label: string | null;readonly description: string | null;readonly engine: BotEngine | null;+ readonly usageCap: Bot["usageCap"];readonly sandbox: Bot["sandbox"];readonly voiceEnabled: boolean;readonly disabledMcpServerIds: readonly McpServerId[];@@ -112,6 +137,7 @@ function BotProfileEditor({const [saving, setSaving] = useState(false);const [saved, setSaved] = useState(false);const [engineChanged, setEngineChanged] = useState(false);+ const [usageCap, setUsageCap] = useState(() => bot.usageCap?.limit.toString() ?? "");const [toolsOpen, setToolsOpen] = useState(false);const [memoryOpen, setMemoryOpen] = useState(false);const [sandbox, setSandbox] = useState<BotSandboxChoice>(() => botSandboxChoice(bot.sandbox));@@ -159,6 +185,9 @@ function BotProfileEditor({const normalizedLabel = label.trim() || null;const normalizedDescription = description.trim() || null;const nextEngine: Bot["engine"] = engineChanged && model ? { provider, model } : bot.engine;+ const resolvedUsageCap = resolveBotUsageCapForProvider(usageCap, activeEntry?.driverKind);+ const usageCapDirty =+ !resolvedUsageCap.valid || resolvedUsageCap.value?.limit !== bot.usageCap?.limit;const nextSandbox: Bot["sandbox"] = sandbox;const tools = useMemo(() => buildBotToolItems(mcpServers), [mcpServers]);const enabledToolCount = tools.filter(@@ -173,6 +202,7 @@ function BotProfileEditor({normalizedLabel !== bot.label ||normalizedDescription !== bot.description ||engineChanged ||+ usageCapDirty ||sandboxDirty ||voiceEnabled !== bot.voiceEnabled ||toolOverridesDirty;@@ -301,6 +331,32 @@ function BotProfileEditor({</Select></div>+ {resolvedUsageCap.available ? (+ <label className="block space-y-2 text-sm font-medium">+ <span>+ Token hard stop <span className="font-normal text-muted-foreground">(optional)</span>+ </span>+ <Input+ aria-label="Token hard stop"+ type="number"+ inputMode="numeric"+ min={1}+ step={1}+ value={usageCap}+ placeholder="No limit"+ onChange={(event) => {+ setUsageCap(event.currentTarget.value);+ markChanged();+ }}+ />+ </label>+ ) : (+ <div className="flex min-h-10 items-center justify-between rounded-lg border border-border bg-muted/20 px-3">+ <span className="text-sm font-medium">Token hard stop</span>+ <span className="text-sm text-muted-foreground">Unavailable for this provider</span>+ </div>+ )}+<div className="flex min-h-10 items-center justify-between rounded-lg border border-border bg-muted/20 px-3"><span className="text-sm font-medium">Voice calls</span><Switch@@ -337,7 +393,7 @@ function BotProfileEditor({{saved ? <span className="mr-auto text-xs text-success">Saved</span> : null}<Buttonsize="sm"- disabled={saving || !dirty || !name.trim() || !onSave}+ disabled={saving || !dirty || !name.trim() || !resolvedUsageCap.valid || !onSave}onClick={() => {if (!onSave) return;setSaving(true);@@ -346,6 +402,7 @@ function BotProfileEditor({label: normalizedLabel,description: normalizedDescription,engine: nextEngine,+ usageCap: resolvedUsageCap.value,sandbox: nextSandbox,voiceEnabled,disabledMcpServerIds,diff --git a/apps/web/src/components/roster/BotRosterSidebar.tsx b/apps/web/src/components/roster/BotRosterSidebar.tsxindex 818e3c4f3..2d54d79ca 100644--- a/apps/web/src/components/roster/BotRosterSidebar.tsx+++ b/apps/web/src/components/roster/BotRosterSidebar.tsx@@ -38,11 +38,11 @@ import { SidebarContent, SidebarGroup, SidebarHeader, SidebarTrigger } from "../import { toastManager } from "../ui/toast";import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";import { BotAvatarView } from "./BotAvatarView";+import { DEFAULT_BOT_RUNTIME_MODE } from "./botSandbox";import { visibleBotChatMessages } from "./botConversationPresentation";import { useBotPresence } from "./botPresence";import { findLatestBotThreadTarget } from "./botThreadRuntime.logic";import { NewBotDialog } from "./NewBotDialog";-import { DEFAULT_BOT_RUNTIME_MODE } from "./botSandbox";import {buildGroupedRosterSections,buildRosterStrip,diff --git a/apps/web/src/components/roster/BotStepMeter.tsx b/apps/web/src/components/roster/BotStepMeter.tsxnew file mode 100644index 000000000..a7e8b09f8--- /dev/null+++ b/apps/web/src/components/roster/BotStepMeter.tsx@@ -0,0 +1,20 @@+import { formatTokens, formatUsd } from "@t3tools/shared/usageFormat";++import { formatBotStepEngine, type BotStepMeterData } from "./botStepMeter.logic";++export function BotStepMeter({ meter }: { readonly meter: BotStepMeterData | undefined }) {+ if (!meter) return null;++ return (+ <div+ className="mt-0.5 truncate font-mono text-[0.7rem] tabular-nums text-muted-foreground/70"+ data-testid="bot-step-meter"+ >+ {formatBotStepEngine(meter.engine)} ·{" "}+ {meter.tokens === null ? "—" : formatTokens(meter.tokens)}+ {" tokens · "}+ {meter.costUsd === null ? "$—" : formatUsd(meter.costUsd)}+ {meter.hardStopReached ? " · Hard stop" : null}+ </div>+ );+}diff --git a/apps/web/src/components/roster/BotThreadLanding.markdown.test.ts b/apps/web/src/components/roster/BotThreadLanding.markdown.test.tsindex ebc0718a5..f08044de6 100644--- a/apps/web/src/components/roster/BotThreadLanding.markdown.test.ts+++ b/apps/web/src/components/roster/BotThreadLanding.markdown.test.ts@@ -27,6 +27,14 @@ describe("BotThreadLanding message formatting", () => {}});+ it("renders step meters for bot and group replies", () => {+ for (const file of ["BotThreadLanding.tsx", "GroupThreadLanding.tsx"]) {+ const source = NodeFS.readFileSync(new URL(`./${file}`, import.meta.url), "utf8");+ expect(source).toContain("<BotStepMeter");+ expect(source).toContain("stepMeters.get(message.turnId)");+ }+ });+it("uses the free-scrolling conversation area instead of end-justified overflow", () => {const botSource = NodeFS.readFileSync(new URL("./BotThreadLanding.tsx", import.meta.url),diff --git a/apps/web/src/components/roster/BotThreadLanding.tsx b/apps/web/src/components/roster/BotThreadLanding.tsxindex c977d1a92..564f6f77d 100644--- a/apps/web/src/components/roster/BotThreadLanding.tsx+++ b/apps/web/src/components/roster/BotThreadLanding.tsx@@ -16,6 +16,7 @@ import {} from "../../providerInstances";import { botEnvironment } from "../../state/bots";import { usePrimaryEnvironmentId } from "../../state/environments";+import { useThreadActivities } from "../../state/entities";import { primaryServerProvidersAtom, serverEnvironment } from "../../state/server";import { environmentSnapshotAtom } from "../../state/shell";import { useEnvironmentQuery } from "../../state/query";@@ -34,6 +35,8 @@ import { DelegationCard } from "./DelegationCard";import { visibleBotChatMessages } from "./botConversationPresentation";import { resolveStickyBotEngine } from "./botEngineSelection";import { BotPromptComposer } from "./BotPromptComposer";+import { BotStepMeter } from "./BotStepMeter";+import { buildBotStepMeters } from "./botStepMeter.logic";import { ThreadErrorBanner } from "../chat/ThreadErrorBanner";import { BotVoiceCallButton, useVoiceCall } from "../voice/VoiceCall";import { useBotPresence } from "./botPresence";@@ -88,6 +91,8 @@ export function BotThreadLanding({ botId }: { readonly botId: string }) {const effectiveModelSelection = stickyEngine;const runtime = useBotThreadRuntime(botId, effectiveModelSelection);const approvalState = useRosterPendingApproval(runtime.linkedThreadRef);+ const activities = useThreadActivities(runtime.linkedThreadRef);+ const stepMeters = useMemo(() => buildBotStepMeters(activities), [activities]);const voiceCall = useVoiceCall();const presence = useBotPresence(botId);const inboxQuery = useEnvironmentQuery(@@ -167,6 +172,9 @@ export function BotThreadLanding({ botId }: { readonly botId: string }) {/><div className="min-w-0 flex-1"><div className="text-sm font-medium">{bot.name}</div>+ <BotStepMeter+ meter={message.turnId === null ? undefined : stepMeters.get(message.turnId)}+ /><ChatMarkdownclassName="mt-1"cwd={runtime.defaultProject?.workspaceRoot}diff --git a/apps/web/src/components/roster/GroupThreadLanding.tsx b/apps/web/src/components/roster/GroupThreadLanding.tsxindex 2ef708bdb..082d669a9 100644--- a/apps/web/src/components/roster/GroupThreadLanding.tsx+++ b/apps/web/src/components/roster/GroupThreadLanding.tsx@@ -1,12 +1,13 @@import { useAtomValue } from "@effect/atom-react";import type { EnvironmentId } from "@t3tools/contracts";import { useNavigate } from "@tanstack/react-router";-import { useEffect } from "react";+import { useEffect, useMemo } from "react";import { selectOpenBotInboxItems } from "../../botInbox";import { openSettings } from "../../settingsDialogStore";import { usePrimaryEnvironmentId } from "../../state/environments";import { useEnvironmentQuery } from "../../state/query";+import { useThreadActivities } from "../../state/entities";import { serverEnvironment } from "../../state/server";import { environmentSnapshotAtom } from "../../state/shell";import { SidebarInset } from "../ui/sidebar";@@ -21,6 +22,8 @@ import { BotConversationScrollArea } from "./BotConversationScrollArea";import { DelegationCard } from "./DelegationCard";import { visibleBotChatMessages } from "./botConversationPresentation";import { BotPromptComposer } from "./BotPromptComposer";+import { BotStepMeter } from "./BotStepMeter";+import { buildBotStepMeters } from "./botStepMeter.logic";import { useGroupPresence } from "./botPresence";import { useRosterStore } from "./rosterStore";import { useGroupThreadRuntime } from "./useGroupThreadRuntime";@@ -37,6 +40,8 @@ export function GroupThreadLanding({ groupId }: { readonly groupId: string }) {const bots = useRosterStore((state) => state.bots);const runtime = useGroupThreadRuntime(groupId);const approvalState = useRosterPendingApproval(runtime.linkedThreadRef);+ const activities = useThreadActivities(runtime.linkedThreadRef);+ const stepMeters = useMemo(() => buildBotStepMeters(activities), [activities]);const presence = useGroupPresence(groupId);const inboxQuery = useEnvironmentQuery(environmentId === null@@ -122,6 +127,9 @@ export function GroupThreadLanding({ groupId }: { readonly groupId: string }) {/><div className="min-w-0 flex-1"><div className="text-sm font-medium">{respondingBot.name}</div>+ <BotStepMeter+ meter={message.turnId === null ? undefined : stepMeters.get(message.turnId)}+ /><ChatMarkdownclassName="mt-1"cwd={runtime.defaultProject?.workspaceRoot}diff --git a/apps/web/src/components/roster/botSandbox.test.ts b/apps/web/src/components/roster/botSandbox.test.tsindex a324b93a0..60ac6e42e 100644--- a/apps/web/src/components/roster/botSandbox.test.ts+++ b/apps/web/src/components/roster/botSandbox.test.ts@@ -37,4 +37,12 @@ describe("botSandbox", () => {]);expect(botSandboxLabel("vercel")).toBe("Vercel Sandbox");});++ it("uses the local setting only for local workspaces", () => {+ expect(resolveBotRuntimeMode(null, "approval-required")).toBe("approval-required");+ expect(resolveBotRuntimeMode("local", "full-access")).toBe("full-access");+ for (const { value: sandbox } of BOT_SANDBOX_OPTIONS.slice(1)) {+ expect(resolveBotRuntimeMode(sandbox, "approval-required")).toBe("full-access");+ }+ });});diff --git a/apps/web/src/components/roster/botStepMeter.logic.test.ts b/apps/web/src/components/roster/botStepMeter.logic.test.tsnew file mode 100644index 000000000..3ec692d3c--- /dev/null+++ b/apps/web/src/components/roster/botStepMeter.logic.test.ts@@ -0,0 +1,55 @@+import { EventId, TurnId, type OrchestrationThreadActivity } from "@t3tools/contracts";+import { describe, expect, it } from "vite-plus/test";++import { buildBotStepMeters, formatBotStepEngine } from "./botStepMeter.logic";++function activity(+ id: string,+ kind: string,+ payload: OrchestrationThreadActivity["payload"],+): OrchestrationThreadActivity {+ return {+ id: EventId.make(id),+ tone: "info",+ kind,+ summary: "Usage",+ payload,+ turnId: TurnId.make("turn-1"),+ createdAt: "2026-08-31T00:00:00.000Z",+ };+}++describe("bot step meter", () => {+ it("formats settled step usage and a hard stop", () => {+ const meters = buildBotStepMeters([+ activity("usage", "bot.step-usage.updated", {+ botId: "bot-1",+ engine: { provider: "codex", model: "gpt-5.6-sol" },+ tokens: 1_200,+ estimatedCost: { status: "available", usd: 0.42 },+ }),+ activity("cap", "bot.usage-cap.hit", { limit: 1_000 }),+ ]);++ expect(meters.get("turn-1")).toEqual({+ engine: { provider: "codex", model: "gpt-5.6-sol" },+ tokens: 1_200,+ costUsd: 0.42,+ hardStopReached: true,+ });+ });++ it("keeps unavailable usage explicit", () => {+ const meters = buildBotStepMeters([+ activity("usage", "bot.step-usage.updated", {+ botId: "bot-1",+ engine: { provider: "anthropic", model: "anthropic/claude-opus-5" },+ tokens: null,+ estimatedCost: { status: "unavailable", usd: null },+ }),+ ]);++ expect(meters.get("turn-1")).toMatchObject({ tokens: null, costUsd: null });+ expect(formatBotStepEngine(meters.get("turn-1")!.engine)).toBe("anthropic/claude-opus-5");+ });+});diff --git a/apps/web/src/components/roster/botStepMeter.logic.ts b/apps/web/src/components/roster/botStepMeter.logic.tsnew file mode 100644index 000000000..cc97680c6--- /dev/null+++ b/apps/web/src/components/roster/botStepMeter.logic.ts@@ -0,0 +1,55 @@+import {+ AkeruStepUsageSnapshot,+ type BotEngine,+ type OrchestrationThreadActivity,+} from "@t3tools/contracts";+import * as Schema from "effect/Schema";++const isAkeruStepUsageSnapshot = Schema.is(AkeruStepUsageSnapshot);++export interface BotStepMeterData {+ readonly engine: BotEngine;+ readonly tokens: number | null;+ readonly costUsd: number | null;+ readonly hardStopReached: boolean;+}++export function buildBotStepMeters(+ activities: ReadonlyArray<OrchestrationThreadActivity>,+): ReadonlyMap<string, BotStepMeterData> {+ const meters = new Map<string, BotStepMeterData>();+ const cappedTurns = new Set<string>();+ for (const activity of activities) {+ if (activity.kind === "bot.usage-cap.hit" && activity.turnId !== null) {+ cappedTurns.add(activity.turnId);+ continue;+ }+ if (+ activity.kind !== "bot.step-usage.updated" ||+ activity.turnId === null ||+ !isAkeruStepUsageSnapshot(activity.payload)+ ) {+ continue;+ }+ meters.set(activity.turnId, {+ engine: activity.payload.engine,+ tokens: activity.payload.tokens,+ costUsd:+ activity.payload.estimatedCost.status === "available"+ ? activity.payload.estimatedCost.usd+ : null,+ hardStopReached: false,+ });+ }+ for (const turnId of cappedTurns) {+ const meter = meters.get(turnId);+ if (meter) meters.set(turnId, { ...meter, hardStopReached: true });+ }+ return meters;+}++export function formatBotStepEngine(engine: BotEngine): string {+ return engine.model.startsWith(`${engine.provider}/`)+ ? engine.model+ : `${engine.provider}/${engine.model}`;+}diff --git a/apps/web/src/components/roster/useBotThreadRuntime.ts b/apps/web/src/components/roster/useBotThreadRuntime.tsindex 35464f69f..00c5c8792 100644--- a/apps/web/src/components/roster/useBotThreadRuntime.ts+++ b/apps/web/src/components/roster/useBotThreadRuntime.ts@@ -37,6 +37,7 @@ import {resolveBotThreadTarget,reserveBotTurnSubmissionAfterObservation,} from "./botThreadRuntime.logic";+import { parseChatPath } from "./roster.logic";import { useRosterStore } from "./rosterStore";const NO_ENVIRONMENT = "" as EnvironmentId;diff --git a/apps/web/src/components/settings/ConnectionsSettings.tsx b/apps/web/src/components/settings/ConnectionsSettings.tsxindex 7cf293150..76e747ba7 100644--- a/apps/web/src/components/settings/ConnectionsSettings.tsx+++ b/apps/web/src/components/settings/ConnectionsSettings.tsx@@ -13,8 +13,6 @@ import {AuthAdministrativeScopes,AuthOrchestrationOperateScope,AuthOrchestrationReadScope,- AuthRelayReadScope,- AuthRelayWriteScope,AuthReviewWriteScope,AuthStandardClientScopes,AuthTerminalOperateScope,@@ -39,7 +37,7 @@ import * as Option from "effect/Option";import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";import { cn } from "../../lib/utils";import { formatElapsedDurationLabel, formatExpiresInLabel } from "../../timestampFormat";-import { resolveDesktopPairingUrl, resolveHostedPairingUrl } from "./pairingUrls";+import { resolveDesktopPairingUrl } from "./pairingUrls";import {applyWslEnableSelection,isQrShareableEndpoint,@@ -104,8 +102,6 @@ import {resolveServerConfigVersionMismatch,resolveServerSelfUpdateCapability,} from "~/versionSkew";-import { hasCloudPublicConfig } from "~/cloud/publicConfig";-import { useCloudLinkController } from "~/cloud/useCloudLinkController";import { authEnvironment } from "~/state/auth";import { environmentCatalog } from "~/connection/catalog";import {@@ -128,7 +124,6 @@ import { useAtomCommand } from "../../state/use-atom-command";import { serverEnvironment } from "~/state/server";import { ConnectionStatusDot } from "../ConnectionStatusDot";import { ServerUpdateAction, ServerUpdateProgress } from "../ServerUpdateAction";-import { CloudEnvironmentConnectRows } from "../cloud/CloudEnvironmentConnectList";import { ITEM_ROW_CLASSNAME, ITEM_ROW_INNER_CLASSNAME } from "./itemRows";const DEFAULT_TAILSCALE_SERVE_PORT = 443;@@ -189,16 +184,6 @@ const PAIRING_SCOPE_OPTIONS: ReadonlyArray<{title: "Manage access",description: "Issue and revoke credentials for other clients.",},- {- scope: AuthRelayReadScope,- title: "View relay",- description: "Inspect managed relay connectivity.",- },- {- scope: AuthRelayWriteScope,- title: "Manage relay",- description: "Change managed tunnel connectivity.",- },];function AccessScopeSummary({@@ -475,12 +460,6 @@ function resolveAdvertisedEndpointPairingUrl(endpoint: AdvertisedEndpoint,credential: string,): string {- if (endpoint.compatibility.hostedHttpsApp === "compatible") {- return (- resolveHostedPairingUrl(endpoint.httpBaseUrl, credential) ??- resolveDesktopPairingUrl(endpoint.httpBaseUrl, credential)- );- }return resolveDesktopPairingUrl(endpoint.httpBaseUrl, credential);}@@ -489,19 +468,7 @@ function resolveCurrentOriginPairingUrl(credential: string): string {return setPairingTokenOnUrl(url, credential).toString();}-function isHostedAppPairingUrl(value: string): boolean {- try {- const url = new URL(value);- return url.pathname === "/pair" && url.searchParams.has("host");- } catch {- return false;- }-}--function endpointShareHint(endpoint: AdvertisedEndpoint, url: string): string {- if (isHostedAppPairingUrl(url)) {- return "Opens the hosted app, no install needed";- }+function endpointShareHint(endpoint: AdvertisedEndpoint): string {switch (endpoint.reachability) {case "lan":return "Devices on the same network";@@ -549,13 +516,6 @@ const PairingLinkListRow = memo(function PairingLinkListRow({() => resolveCurrentOriginPairingUrl(pairingLink.credential),[pairingLink.credential],);- const hostedPairingUrl = useMemo(- () =>- endpointUrl != null && endpointUrl !== ""- ? resolveHostedPairingUrl(endpointUrl, pairingLink.credential)- : null,- [endpointUrl, pairingLink.credential],- );const endpointPairingUrl = useMemo(() => {const endpoint = selectPairingEndpoint(endpoints, defaultEndpointKey);return endpoint ? resolveAdvertisedEndpointPairingUrl(endpoint, pairingLink.credential) : null;@@ -579,7 +539,7 @@ const PairingLinkListRow = memo(function PairingLinkListRow({preferenceKey: endpointDefaultPreferenceKey(endpoint),label: endpoint.label,url,- detail: endpointShareHint(endpoint, url),+ detail: endpointShareHint(endpoint),qrShareable: isQrShareableEndpoint(endpoint),});}@@ -588,7 +548,7 @@ const PairingLinkListRow = memo(function PairingLinkListRow({const shareablePairingUrl =endpointPairingUrl ??(endpointUrl != null && endpointUrl !== ""- ? (hostedPairingUrl ?? resolveDesktopPairingUrl(endpointUrl, pairingLink.credential))+ ? resolveDesktopPairingUrl(endpointUrl, pairingLink.credential): isLoopbackHostname(window.location.hostname)? null: currentOriginPairingUrl);@@ -597,7 +557,6 @@ const PairingLinkListRow = memo(function PairingLinkListRow({const [failedCopyValue, setFailedCopyValue] = useState<string | null>(null);const revealValue = failedCopyValue ?? shareablePairingUrl ?? pairingLink.credential;const isRevealValueUrl = revealValue !== pairingLink.credential;- const isRevealValueHostedAppPairingUrl = isRevealValueUrl && isHostedAppPairingUrl(revealValue);// Never render a QR for a loopback URL, even in the manual-copy fallback.const isRevealValueQrShareable =endpointCopyOptions.find((option) => option.url === revealValue)?.qrShareable ?? true;@@ -608,23 +567,16 @@ const PairingLinkListRow = memo(function PairingLinkListRow({const { copyToClipboard } = useCopyToClipboard<{value: string;- kind: "code" | "hosted-link" | "link";+ kind: "code" | "link";}>({onCopy: ({ kind }) => {toastManager.add({type: "success",- title:- kind === "hosted-link"- ? "Hosted app link copied"- : kind === "link"- ? "Pairing URL copied"- : "Pairing code copied",+ title: kind === "link" ? "Pairing URL copied" : "Pairing code copied",description:- kind === "hosted-link"- ? "Open it in the browser on the device you want to connect."- : kind === "link"- ? "Open it in the client you want to pair to this environment."- : "Paste it into another client to finish pairing.",+ kind === "link"+ ? "Open it in the client you want to pair to this environment."+ : "Paste it into another client to finish pairing.",});},onError: (error, { value, kind }) => {@@ -636,11 +588,9 @@ const PairingLinkListRow = memo(function PairingLinkListRow({stackedThreadToast({type: "error",title: canCopyToClipboard- ? kind === "hosted-link"- ? "Could not copy hosted app link"- : kind === "link"- ? "Could not copy pairing URL"- : "Could not copy pairing code"+ ? kind === "link"+ ? "Could not copy pairing URL"+ : "Could not copy pairing code": "Clipboard copy unavailable",description: canCopyToClipboard ? error.message : "Showing the full value instead.",}),@@ -649,17 +599,12 @@ const PairingLinkListRow = memo(function PairingLinkListRow({});const copyPairingValue = useCallback(- (value: string, kind: "code" | "hosted-link" | "link") => {+ (value: string, kind: "code" | "link") => {copyToClipboard(value, { value, kind });},[copyToClipboard],);- const copyKindForUrl = useCallback(- (url: string): "hosted-link" | "link" => (isHostedAppPairingUrl(url) ? "hosted-link" : "link"),- [],- );-const handleCopyCode = useCallback(() => {copyPairingValue(pairingLink.credential, "code");}, [copyPairingValue, pairingLink.credential]);@@ -741,18 +686,10 @@ const PairingLinkListRow = memo(function PairingLinkListRow({)}<DialogPopup className="max-w-md"><DialogHeader>- <DialogTitle>- {isRevealValueUrl- ? isRevealValueHostedAppPairingUrl- ? "Hosted app pairing link"- : "Pairing link"- : "Pairing code"}- </DialogTitle>+ <DialogTitle>{isRevealValueUrl ? "Pairing link" : "Pairing code"}</DialogTitle><DialogDescription>{isRevealValueUrl- ? isRevealValueHostedAppPairingUrl- ? "Clipboard copy is unavailable here. Open or manually copy this hosted app link on the device you want to connect."- : "Clipboard copy is unavailable here. Open or manually copy this full pairing URL on the device you want to connect."+ ? "Clipboard copy is unavailable here. Open or manually copy this full pairing URL on the device you want to connect.": "Clipboard copy is unavailable here. Manually copy this code into another client."}</DialogDescription></DialogHeader>@@ -861,7 +798,7 @@ const PairingLinkListRow = memo(function PairingLinkListRow({size="xs"variant="ghost"className="shrink-0"- onClick={() => copyPairingValue(qrPairingUrl, copyKindForUrl(qrPairingUrl))}+ onClick={() => copyPairingValue(qrPairingUrl, "link")}>Copy link</Button>@@ -1410,10 +1347,9 @@ function SavedBackendListRow({environment.entry.profile.value._tag === "SshConnectionProfile"? environment.entry.profile.value.target: null;- const metadataBits = [- sshTarget ? `SSH ${formatDesktopSshTarget(sshTarget)}` : null,- environment.relayManaged ? "Managed tunnel" : null,- ].filter((value): value is string => value !== null);+ const metadataBits = [sshTarget ? `SSH ${formatDesktopSshTarget(sshTarget)}` : null].filter(+ (value): value is string => value !== null,+ );// The WSL backend is a desktop-managed local backend (it surfaces as a bearer// environment whose connection id is prefixed "local:"), not a remote@@ -1577,137 +1513,7 @@ const DesktopSshHostRow = memo(function DesktopSshHostRow({);});-function CloudLinkSwitch({- checked,- disabled,- disabledReason,- onCheckedChange,- ariaLabel = "Enable remote access",-}: {- readonly checked: boolean;- readonly disabled: boolean;- readonly disabledReason: string | null;- readonly onCheckedChange?: (enabled: boolean) => void;- readonly ariaLabel?: string;-}) {- const control = (- <Switch- aria-label={ariaLabel}- checked={checked}- disabled={disabled}- {...(onCheckedChange ? { onCheckedChange } : {})}- />- );- return disabledReason ? (- <Tooltip>- <TooltipTrigger render={<span className="inline-flex">{control}</span>} />- <TooltipPopup side="top">{disabledReason}</TooltipPopup>- </Tooltip>- ) : (- control- );-}--function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: boolean }) {- const {- isSignedIn,- linkState: primaryCloudLinkState,- managedTunnelActive,- publishAgentActivity,- operationError,- reconcileCloudState,- } = useCloudLinkController();- const [isUpdating, setIsUpdating] = useState(false);- const [isUpdatingPreference, setIsUpdatingPreference] = useState(false);-- const disabledReason = !isSignedIn- ? "Sign in to manage this environment."- : !canManageRelay- ? "Your session does not have permission to manage remote access."- : null;- const isBusy = isUpdating || isUpdatingPreference;-- const updateManagedTunnel = async (enabled: boolean) => {- setIsUpdating(true);- const ok = await reconcileCloudState({ managedTunnel: enabled, publish: publishAgentActivity });- if (ok) {- // Turning the tunnel off while publishing stays on downgrades the link- // rather than removing it — say so instead of claiming an unlink.- toastManager.add({- type: "success",- title: enabled- ? "Environment linked"- : publishAgentActivity- ? "Managed tunnel disabled"- : "Environment unlinked",- description: enabled- ? "This environment is available through its managed tunnel."- : publishAgentActivity- ? "The managed tunnel was removed. Agent activity publishing stays on."- : "This environment is no longer available through its managed tunnel.",- });- }- setIsUpdating(false);- };-- const updatePublishAgentActivity = async (enabled: boolean) => {- setIsUpdatingPreference(true);- const ok = await reconcileCloudState({ managedTunnel: managedTunnelActive, publish: enabled });- if (ok) {- toastManager.add({- type: "success",- title: enabled ? "Agent activity enabled" : "Agent activity disabled",- description: enabled- ? "This environment publishes agent activity to your mobile clients."- : "This environment will stop publishing agent activity.",- });- }- setIsUpdatingPreference(false);- };-- return (- <>- {window.desktopBridge ? (- <SettingsRow- title="Remote access"- description={- managedTunnelActive- ? "This environment is available to your other devices through its managed tunnel."- : "Make this environment available to your other devices through a managed tunnel."- }- status={operationError ?? primaryCloudLinkState.error}- control={- <CloudLinkSwitch- checked={managedTunnelActive}- disabled={!canManageRelay || !isSignedIn || primaryCloudLinkState.isPending || isBusy}- disabledReason={disabledReason}- onCheckedChange={(enabled) => void updateManagedTunnel(enabled)}- />- }- />- ) : null}- <SettingsRow- title="Publish agent activity"- description="Send activity from this environment to your mobile clients for push notifications and Live Activities. Works without a managed tunnel."- control={- <CloudLinkSwitch- ariaLabel="Publish agent activity to mobile clients"- checked={publishAgentActivity}- disabled={!canManageRelay || !isSignedIn || primaryCloudLinkState.isPending || isBusy}- disabledReason={disabledReason}- onCheckedChange={(enabled) => void updatePublishAgentActivity(enabled)}- />- }- />- </>- );-}--function CloudLinkRow({ canManageRelay }: { readonly canManageRelay: boolean }) {- return hasCloudPublicConfig() ? <ConfiguredCloudLinkRow canManageRelay={canManageRelay} /> : null;-}--function EmptyRemoteEnvironments({ cloudEnabled = true }: { readonly cloudEnabled?: boolean }) {+function EmptyRemoteEnvironments() {return (<Empty className="min-h-52"><EmptyMedia variant="icon">@@ -1715,34 +1521,12 @@ function EmptyRemoteEnvironments({ cloudEnabled = true }: { readonly cloudEnable</EmptyMedia><EmptyHeader><EmptyTitle>No saved remote environments</EmptyTitle>- <EmptyDescription>- {cloudEnabled- ? "Click “Add environment” to pair another environment, or connect one of your linked environments."- : "Click “Add environment” to pair another environment."}- </EmptyDescription>+ <EmptyDescription>Click “Add environment” to pair another environment.</EmptyDescription></EmptyHeader></Empty>);}-function CloudRemoteEnvironmentRows({- primaryEnvironmentId,- savedEnvironments,-}: {- readonly primaryEnvironmentId: EnvironmentId | null;- readonly savedEnvironments: ReadonlyArray<EnvironmentPresentation>;-}) {- return hasCloudPublicConfig() ? (- <CloudEnvironmentConnectRows- primaryEnvironmentId={primaryEnvironmentId}- savedEnvironments={savedEnvironments}- empty={<EmptyRemoteEnvironments />}- />- ) : savedEnvironments.length === 0 ? (- <EmptyRemoteEnvironments cloudEnabled={false} />- ) : null;-}-export function ConnectionsSettings() {const desktopBridge = window.desktopBridge;const { environments } = useEnvironments();@@ -1879,7 +1663,6 @@ export function ConnectionsSettings() {(state) => state.setDefaultAdvertisedEndpointKey,);const canManageLocalBackend = currentSessionScopes?.includes(AuthAccessWriteScope) ?? false;- const canManageRelay = currentSessionScopes?.includes(AuthRelayWriteScope) ?? false;const authAccessChanges = useEnvironmentQuery(canManageLocalBackend && primaryEnvironmentId !== null? authEnvironment.accessChanges({@@ -3066,13 +2849,9 @@ export function ConnectionsSettings() {{renderEndpointRows("endpoint-rail")}{renderTailscaleRow()}{renderWslRow()}- <CloudLinkRow canManageRelay={canManageRelay} /></>) : (- <>- {renderDisabledNetworkAccessRow()}- <CloudLinkRow canManageRelay={canManageRelay} />- </>+ <>{renderDisabledNetworkAccessRow()}</>)}</SettingsSection>@@ -3376,7 +3155,6 @@ export function ConnectionsSettings() {title="Administrative access"description="Pairing links and client-session management require the access:write scope for this backend."/>- <CloudLinkRow canManageRelay={canManageRelay} /></SettingsSection>)}@@ -3453,10 +3231,7 @@ export function ConnectionsSettings() {onRemove={handleRemoveSavedBackend}/>))}- <CloudRemoteEnvironmentRows- primaryEnvironmentId={primaryEnvironmentId}- savedEnvironments={savedEnvironments}- />+ {savedEnvironments.length === 0 ? <EmptyRemoteEnvironments /> : null}</SettingsSection></SettingsPageContainer>);diff --git a/apps/web/src/components/settings/PortabilitySettings.logic.test.ts b/apps/web/src/components/settings/PortabilitySettings.logic.test.tsindex 078b03cee..b94d4e661 100644--- a/apps/web/src/components/settings/PortabilitySettings.logic.test.ts+++ b/apps/web/src/components/settings/PortabilitySettings.logic.test.ts@@ -1,7 +1,6 @@import {BearerConnectionTarget,PrimaryConnectionTarget,- RelayConnectionTarget,} from "@t3tools/client-runtime/connection";import { EnvironmentId, ProjectId, type PortabilityImportPreview } from "@t3tools/contracts";import { describe, expect, it } from "vite-plus/test";@@ -38,11 +37,6 @@ describe("portabilityProjectPickerTarget", () => {}),),).toBe("wsl:Ubuntu");- expect(- portabilityProjectPickerTarget(- new RelayConnectionTarget({ environmentId: ENVIRONMENT_ID, label: "Remote" }),- ),- ).toBeUndefined();});});diff --git a/apps/web/src/components/settings/PrivacySettings.tsx b/apps/web/src/components/settings/PrivacySettings.tsxnew file mode 100644index 000000000..25535e1b4--- /dev/null+++ b/apps/web/src/components/settings/PrivacySettings.tsx@@ -0,0 +1,123 @@+import { AKERU_MARKETING_SITE_URL, DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts/settings";++import { usePrimarySettings, useUpdatePrimarySettings } from "~/hooks/useSettings";+import { Switch } from "../ui/switch";+import {+ SettingResetButton,+ SettingsPageContainer,+ SettingsRow,+ SettingsSection,+} from "./settingsLayout";+import { searchableSetting } from "./settingsSearch";++const privacyPolicyUrl = `${AKERU_MARKETING_SITE_URL}/privacy-policy`;+const termsUrl = `${AKERU_MARKETING_SITE_URL}/terms-of-service`;++export function PrivacySettingsPanel() {+ const settings = usePrimarySettings();+ const updateSettings = useUpdatePrimarySettings();++ return (+ <SettingsPageContainer>+ <SettingsSection title="Privacy controls">+ <SettingsRow+ {...searchableSetting("anonymous-analytics")}+ description="Send app version, platform, architecture, client type, and feature events to PostHog. Akeru Bot does not use provider account IDs."+ resetAction={+ settings.analyticsEnabled !== DEFAULT_SERVER_SETTINGS.analyticsEnabled ? (+ <SettingResetButton+ label="anonymous analytics"+ onClick={() =>+ updateSettings({ analyticsEnabled: DEFAULT_SERVER_SETTINGS.analyticsEnabled })+ }+ />+ ) : null+ }+ control={+ <Switch+ checked={settings.analyticsEnabled}+ onCheckedChange={(checked) => updateSettings({ analyticsEnabled: Boolean(checked) })}+ aria-label="Send anonymous analytics"+ />+ }+ />+ <SettingsRow+ {...searchableSetting("privacy-product-feedback")}+ description="Send feedback you submit to feedback.akeru.bot. The service keeps submissions for up to 90 days."+ control={+ <Switch+ checked={settings.productFeedbackEnabled}+ onCheckedChange={(checked) =>+ updateSettings({ productFeedbackEnabled: Boolean(checked) })+ }+ aria-label="Enable product feedback"+ />+ }+ />+ <SettingsRow+ {...searchableSetting("privacy-voice-calls")}+ description="Send live microphone audio and session data to the ChatGPT Realtime service during a call."+ control={+ <Switch+ checked={settings.voice.enabled}+ onCheckedChange={(checked) =>+ updateSettings({ voice: { enabled: Boolean(checked) } })+ }+ aria-label="Enable voice calls"+ />+ }+ />+ <SettingsRow+ {...searchableSetting("privacy-provider-update-checks")}+ description="Contact provider release sources to check for newer CLI versions."+ control={+ <Switch+ checked={settings.enableProviderUpdateChecks}+ onCheckedChange={(checked) =>+ updateSettings({ enableProviderUpdateChecks: Boolean(checked) })+ }+ aria-label="Enable provider update checks"+ />+ }+ />+ </SettingsSection>++ <SettingsSection title="Outbound data">+ <SettingsRow+ title="Provider CLIs"+ description="Prompts, selected files, tool results, screenshots, and conversation context go to the provider you choose. Provider terms and retention rules apply."+ />+ <SettingsRow+ title="Desktop updates"+ description="Signed desktop builds contact the configured release host to check for and download updates."+ />+ </SettingsSection>++ <SettingsSection title="Legal">+ <SettingsRow+ title="Policies"+ description={+ <span className="flex gap-3">+ <a+ className="underline underline-offset-4"+ href={termsUrl}+ target="_blank"+ rel="noreferrer"+ >+ Terms of Use+ </a>+ <a+ className="underline underline-offset-4"+ href={privacyPolicyUrl}+ target="_blank"+ rel="noreferrer"+ >+ Privacy Policy+ </a>+ </span>+ }+ />+ </SettingsSection>+ </SettingsPageContainer>+ );+}diff --git a/apps/web/src/components/settings/ProviderSettingsPanel.tsx b/apps/web/src/components/settings/ProviderSettingsPanel.tsxindex af56a3f0a..799a0840b 100644--- a/apps/web/src/components/settings/ProviderSettingsPanel.tsx+++ b/apps/web/src/components/settings/ProviderSettingsPanel.tsx@@ -148,7 +148,6 @@ function ProviderLastChecked({ lastCheckedAt }: { lastCheckedAt: string | null }function providerEnvironmentIcon(environment: EnvironmentPresentation) {if (environment.entry.target._tag === "PrimaryConnectionTarget") return MonitorIcon;- if (environment.entry.target._tag === "RelayConnectionTarget") return CloudIcon;if (environment.entry.target._tag === "SshConnectionTarget") return TerminalIcon;if (isDesktopLocalConnectionTarget(environment.entry.target)) return LaptopIcon;return CloudIcon;@@ -156,7 +155,6 @@ function providerEnvironmentIcon(environment: EnvironmentPresentation) {function providerEnvironmentDetail(environment: EnvironmentPresentation): string {if (environment.entry.target._tag === "PrimaryConnectionTarget") return "Primary device";- if (environment.relayManaged) return "Managed tunnel";if (environment.entry.target._tag === "SshConnectionTarget") return "SSH";if (isDesktopLocalConnectionTarget(environment.entry.target)) return "Local device";return environment.displayUrl ?? "Remote device";diff --git a/apps/web/src/components/settings/SettingsDialog.tsx b/apps/web/src/components/settings/SettingsDialog.tsxindex 81c8c20ad..3cc9be711 100644--- a/apps/web/src/components/settings/SettingsDialog.tsx+++ b/apps/web/src/components/settings/SettingsDialog.tsx@@ -5,6 +5,7 @@ import {KeyboardIcon,Link02Icon,PaintBrush01Icon,+ SecurityCheckIcon,Settings02Icon,} from "@hugeicons/core-free-icons";import type { IconSvgElement } from "@hugeicons/react";@@ -31,6 +32,9 @@ const ProvidersPanel = lazy(async () => ({const VoiceSettingsPanel = lazy(async () => ({default: (await import("./VoiceSettings")).VoiceSettingsPanel,}));+const PrivacySettingsPanel = lazy(async () => ({+ default: (await import("./PrivacySettings")).PrivacySettingsPanel,+}));const ConnectionsSettings = lazy(async () => ({default: (await import("./ConnectionsSettings")).ConnectionsSettings,}));@@ -50,6 +54,7 @@ const SECTION_PANELS: Readonly<Record<SettingsSection, ComponentType>> = {appearance: AppearanceSettingsPanel,providers: ProvidersPanel,voice: VoiceSettingsPanel,+ privacy: PrivacySettingsPanel,connections: ConnectionsSettings,keybindings: KeybindingsSettingsPanel,"source-control": SourceControlSettingsPanel,@@ -66,6 +71,7 @@ const NAV_ITEMS: ReadonlyArray<{{ section: "appearance", label: "Appearance", icon: PaintBrush01Icon },{ section: "providers", label: "Providers", icon: BotIcon },{ section: "voice", label: "Voice", icon: CallIcon },+ { section: "privacy", label: "Privacy", icon: SecurityCheckIcon },{ section: "inbox", label: "Errors", icon: AlertCircleIcon },{ section: "connections", label: "Connections", icon: Link02Icon },{ section: "keybindings", label: "Keybindings", icon: KeyboardIcon },diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsxindex fde93346f..386558def 100644--- a/apps/web/src/components/settings/SettingsPanels.tsx+++ b/apps/web/src/components/settings/SettingsPanels.tsx@@ -2250,7 +2250,7 @@ export function GeneralSettingsPanel() {/><SettingsRow- {...searchableSetting("provider-update-checks")}+ title="Provider update checks"description="Check installed provider CLIs for newer available versions."resetAction={settings.enableProviderUpdateChecks !==@@ -2665,29 +2665,6 @@ export function GeneralSettingsPanel() {description="Current version of the application."/>)}- <SettingsRow- {...searchableSetting("analytics")}- description="Share anonymous usage data to help improve Akeru Bot."- control={- <Switch- aria-label="Analytics"- checked={settings.analyticsEnabled}- onCheckedChange={(analyticsEnabled) => updateSettings({ analyticsEnabled })}- />- }- />- <SettingsRow- title="Product feedback"- control={- <Switch- aria-label="Product feedback"- checked={settings.productFeedbackEnabled}- onCheckedChange={(productFeedbackEnabled) =>- updateSettings({ productFeedbackEnabled })- }- />- }- /><SettingsRowtitle="Feedback endpoint"control={diff --git a/apps/web/src/components/settings/pairingUrls.test.ts b/apps/web/src/components/settings/pairingUrls.test.tsindex c5c45bcf1..a3172ee51 100644--- a/apps/web/src/components/settings/pairingUrls.test.ts+++ b/apps/web/src/components/settings/pairingUrls.test.ts@@ -1,24 +1,14 @@-import { afterEach, describe, expect, it, vi } from "vite-plus/test";+import { describe, expect, it } from "vite-plus/test";-import { resolveDesktopPairingUrl, resolveHostedPairingUrl } from "./pairingUrls";+import { resolveDesktopPairingUrl } from "./pairingUrls";describe("settings pairing URL helpers", () => {- afterEach(() => {- vi.unstubAllEnvs();- });-- it("uses direct backend pairing URLs for HTTP endpoints", () => {- expect(resolveHostedPairingUrl("http://192.168.1.44:3773", "PAIRCODE")).toBeNull();+ it("uses direct backend pairing URLs for HTTP and HTTPS endpoints", () => {expect(resolveDesktopPairingUrl("http://192.168.1.44:3773", "PAIRCODE")).toBe("http://192.168.1.44:3773/pair#token=PAIRCODE",);- });-- it("uses hosted pairing URLs for HTTPS endpoints", () => {- vi.stubEnv("VITE_HOSTED_APP_URL", "https://preview.t3.codes");-- expect(resolveHostedPairingUrl("https://host.tailnet.example.ts.net:3773", "PAIRCODE")).toBe(- "https://preview.t3.codes/pair?host=https%3A%2F%2Fhost.tailnet.example.ts.net%3A3773#token=PAIRCODE",+ expect(resolveDesktopPairingUrl("https://host.tailnet.example.ts.net:3773", "PAIRCODE")).toBe(+ "https://host.tailnet.example.ts.net:3773/pair#token=PAIRCODE",);});});diff --git a/apps/web/src/components/settings/pairingUrls.ts b/apps/web/src/components/settings/pairingUrls.tsindex 891fe04ad..437c5d342 100644--- a/apps/web/src/components/settings/pairingUrls.ts+++ b/apps/web/src/components/settings/pairingUrls.ts@@ -1,4 +1,3 @@-import { buildHostedPairingUrl } from "../../hostedPairing";import { setPairingTokenOnUrl } from "../../pairingUrl";export function resolveDesktopPairingUrl(endpointUrl: string, credential: string): string {@@ -6,15 +5,3 @@ export function resolveDesktopPairingUrl(endpointUrl: string, credential: stringurl.pathname = "/pair";return setPairingTokenOnUrl(url, credential).toString();}--export function resolveHostedPairingUrl(endpointUrl: string, credential: string): string | null {- const url = new URL(endpointUrl);- if (url.protocol !== "https:") {- return null;- }-- return buildHostedPairingUrl({- host: endpointUrl,- token: credential,- });-}diff --git a/apps/web/src/components/settings/settingsSearch.test.ts b/apps/web/src/components/settings/settingsSearch.test.tsindex e7e866e7c..5b0f083ea 100644--- a/apps/web/src/components/settings/settingsSearch.test.ts+++ b/apps/web/src/components/settings/settingsSearch.test.ts@@ -86,10 +86,10 @@ describe("searchSettings", () => {});});- it("routes analytics to General settings", () => {+ it("routes analytics to Privacy settings", () => {expect(searchSettings("analytics")[0]).toMatchObject({- id: "analytics",- to: "/settings/general",+ id: "anonymous-analytics",+ to: "/settings/privacy",});});@@ -108,4 +108,15 @@ describe("searchSettings", () => {targetId: "appearance",});});++ it("routes privacy controls to Privacy settings", () => {+ expect(searchSettings("anonymous analytics")[0]).toMatchObject({+ id: "anonymous-analytics",+ to: "/settings/privacy",+ });+ expect(searchSettings("voice calls")[0]).toMatchObject({+ id: "privacy-voice-calls",+ to: "/settings/privacy",+ });+ });});diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.tsindex b68738de1..751db10e1 100644--- a/apps/web/src/components/settings/settingsSearch.ts+++ b/apps/web/src/components/settings/settingsSearch.ts@@ -6,6 +6,7 @@ export type SettingsPath =| "/settings/keybindings"| "/settings/providers"| "/settings/voice"+ | "/settings/privacy"| "/settings/integrations"| "/settings/source-control"| "/settings/connections"@@ -31,6 +32,7 @@ export const SETTINGS_SECTION_LABELS: Readonly<Record<SettingsPath, string>> = {"/settings/keybindings": "Keybindings","/settings/providers": "Providers","/settings/voice": "Voice",+ "/settings/privacy": "Privacy","/settings/integrations": "Integrations","/settings/source-control": "Source Control","/settings/connections": "Connections",@@ -149,9 +151,29 @@ export const SETTINGS_SEARCH_ITEMS = [to: "/settings/general",},{- id: "provider-update-checks",+ id: "privacy",+ title: "Privacy",+ to: "/settings/privacy",+ },+ {+ id: "anonymous-analytics",+ title: "Anonymous analytics",+ to: "/settings/privacy",+ },+ {+ id: "privacy-product-feedback",+ title: "Product feedback",+ to: "/settings/privacy",+ },+ {+ id: "privacy-voice-calls",+ title: "Voice calls",+ to: "/settings/privacy",+ },+ {+ id: "privacy-provider-update-checks",title: "Provider update checks",- to: "/settings/general",+ to: "/settings/privacy",},{id: "local-execution",diff --git a/apps/web/src/components/sidebar/SidebarChrome.test.ts b/apps/web/src/components/sidebar/SidebarChrome.test.tsindex dbdcad7ef..f6c23783c 100644--- a/apps/web/src/components/sidebar/SidebarChrome.test.ts+++ b/apps/web/src/components/sidebar/SidebarChrome.test.ts@@ -139,16 +139,6 @@ describe("sidebar footer", () => {expect(source).not.toContain('openSettings("inbox")');});- it("shows the verified remote-access account identity when Clerk is configured", () => {- const source = NodeFS.readFileSync(- new URL("../clerk/T3ConnectSidebarSignIn.tsx", import.meta.url),- "utf8",- );-- expect(source).toContain("showName");- expect(source).toContain("Sign in for remote access");- });-it("creates manual and first-run bots with approval required", () => {const rosterSource = NodeFS.readFileSync(new URL("../roster/BotRosterSidebar.tsx", import.meta.url),diff --git a/apps/web/src/components/sidebar/SidebarChrome.tsx b/apps/web/src/components/sidebar/SidebarChrome.tsxindex bc3b404dd..9d55ebce4 100644--- a/apps/web/src/components/sidebar/SidebarChrome.tsx+++ b/apps/web/src/components/sidebar/SidebarChrome.tsx@@ -32,7 +32,6 @@ import { environmentSnapshotAtom } from "../../state/shell";import { threadEnvironment } from "../../state/threads";import { useAtomCommand } from "../../state/use-atom-command";import { AkeruMark } from "../AkeruMark";-import { T3ConnectSidebarAvatar, T3ConnectSidebarSignIn } from "../clerk/T3ConnectSidebarSignIn";import { PluginLogoImage } from "../plugins/PluginsCatalog";import { isBuiltinMcpServer } from "../plugins/pluginRegistry";import { cn } from "../../lib/utils";@@ -403,10 +402,6 @@ export const SidebarChromeFooter = memo(function SidebarChromeFooter() {<SidebarMenu><SidebarPluginSummary onClick={handlePluginsClick} /></SidebarMenu>- <div className="min-w-0 group-data-[collapsible=icon]:hidden">- <T3ConnectSidebarSignIn />- <T3ConnectSidebarAvatar />- </div><SidebarMenu className="flex-row items-center gap-1 group-data-[collapsible=icon]:flex-col"><SidebarUtilityItemicon={<AppIcon className="size-4" icon={Settings02Icon} />}diff --git a/apps/web/src/connection/desktopLocal.ts b/apps/web/src/connection/desktopLocal.tsindex c9d8b9387..0c0775d4b 100644--- a/apps/web/src/connection/desktopLocal.ts+++ b/apps/web/src/connection/desktopLocal.ts@@ -9,7 +9,7 @@ import {* Desktop-local secondary backends (e.g. a parallel WSL backend) are registered* by the connection platform source as bearer connections whose id carries this* prefix. It is the renderer's single signal that an environment is a- * host-managed local backend rather than a user-saved remote, SSH, or relay+ * host-managed local backend rather than a user-saved remote or SSH* environment.** Keep this the one source of truth: the producer (`connection/platform.ts`)diff --git a/apps/web/src/connection/platform.ts b/apps/web/src/connection/platform.tsindex 1332bf7ff..c97ce8239 100644--- a/apps/web/src/connection/platform.ts+++ b/apps/web/src/connection/platform.ts@@ -1,10 +1,8 @@import {ClientPresentation,- CloudSession,EnvironmentOwnedDataCleanup,PlatformConnectionSource,PrimaryEnvironmentAuth,- RelayDeviceIdentity,SshEnvironmentGateway,} from "@t3tools/client-runtime/platform";import {@@ -23,7 +21,6 @@ import {} from "@t3tools/client-runtime/connection";import { bootstrapRemoteBearerSession } from "@t3tools/client-runtime/authorization";import { fetchRemoteEnvironmentDescriptor } from "@t3tools/client-runtime/environment";-import { managedRelayAccountChanges, managedRelaySessionAtom } from "@t3tools/client-runtime/relay";import { EnvironmentRpcRequestObserver } from "@t3tools/client-runtime/rpc";import {AuthStandardClientScopes,@@ -51,7 +48,6 @@ import {} from "../environments/primary/target";import { clearComposerDraftsEnvironment } from "../composerDraftStore";import { isHostedStaticApp } from "../hostedPairing";-import { appAtomRegistry } from "../rpc/atomRegistry";import { acknowledgeRpcRequest, trackRpcRequestSent } from "../rpc/requestLatencyState";import {desktopLocalConnectionId,@@ -90,27 +86,22 @@ const connectivityLayer = Connectivity.layer({});const wakeupsLayer = Wakeups.layer({- changes: Stream.merge(- Stream.callback<"application-active">((queue) =>- Effect.acquireRelease(+ changes: Stream.callback<"application-active">((queue) =>+ Effect.acquireRelease(+ Effect.sync(() => {+ const listener = () => {+ if (document.visibilityState === "visible") {+ Queue.offerUnsafe(queue, "application-active");+ }+ };+ document.addEventListener("visibilitychange", listener);+ return listener;+ }),+ (listener) =>Effect.sync(() => {- const listener = () => {- if (document.visibilityState === "visible") {- Queue.offerUnsafe(queue, "application-active");- }- };- document.addEventListener("visibilitychange", listener);- return listener;+ document.removeEventListener("visibilitychange", listener);}),- (listener) =>- Effect.sync(() => {- document.removeEventListener("visibilitychange", listener);- }),- ).pipe(Effect.asVoid),- ),- managedRelayAccountChanges(appAtomRegistry).pipe(- Stream.map(() => "credentials-changed" as const),- ),+ ).pipe(Effect.asVoid),),});@@ -179,36 +170,6 @@ const capabilitiesLayer = Layer.effectContext(metadata: clientMetadata(),scopes: AuthStandardClientScopes,});- const cloudSession = CloudSession.of({- clerkToken: Effect.gen(function* () {- const session = appAtomRegistry.get(managedRelaySessionAtom);- if (session === null) {- return yield* new ConnectionBlockedError({- reason: "authentication",- detail: "Sign in to connect this environment.",- });- }- const token = yield* session.readClerkToken().pipe(- Effect.mapError(- (error) =>- new ConnectionTransientError({- reason: "network",- detail: error.message,- }),- ),- );- if (token === null) {- return yield* new ConnectionBlockedError({- reason: "authentication",- detail: "The remote access session is unavailable.",- });- }- return token;- }),- });- const identity = RelayDeviceIdentity.of({- deviceId: Effect.succeed(Option.none()),- });const primaryAuth = PrimaryEnvironmentAuth.of({bearerToken: Effect.tryPromise({try: readDesktopPrimaryBearerToken,@@ -277,9 +238,7 @@ const capabilitiesLayer = Layer.effectContext(}),});- return Context.make(CloudSession, cloudSession).pipe(- Context.add(PrimaryEnvironmentAuth, primaryAuth),- Context.add(RelayDeviceIdentity, identity),+ return Context.make(PrimaryEnvironmentAuth, primaryAuth).pipe(Context.add(ClientPresentation, presentation),Context.add(SshEnvironmentGateway, ssh),);diff --git a/apps/web/src/connection/storage.test.ts b/apps/web/src/connection/storage.test.tsindex 6d503387b..62887cb56 100644--- a/apps/web/src/connection/storage.test.ts+++ b/apps/web/src/connection/storage.test.ts@@ -12,7 +12,6 @@ const emptyCatalog = {targets: [],profiles: [],credentials: [],- remoteDpopTokens: [],} as const;const decodeCatalog = Schema.decodeUnknownSync(Schema.fromJsonString(ConnectionCatalogDocument));diff --git a/apps/web/src/connection/storage.ts b/apps/web/src/connection/storage.tsindex 4ae476c1d..bf0e9f08b 100644--- a/apps/web/src/connection/storage.ts+++ b/apps/web/src/connection/storage.ts@@ -11,7 +11,6 @@ import {removeConnectionFromCatalog,replaceCatalogValue,} from "@t3tools/client-runtime/platform";-import { TokenStore } from "@t3tools/client-runtime/authorization";import {ConnectionTransientError,CredentialStore,@@ -437,34 +436,6 @@ export const connectionStorageLayer = Layer.effectContext(),})),});- const remoteTokenStore = TokenStore.make({- get: (environmentId) =>- catalog.read.pipe(- Effect.map((document) =>- Option.fromUndefinedOr(- document.remoteDpopTokens.find((token) => token.environmentId === environmentId),- ),- ),- ),- put: (token) =>- catalog.update((document) => ({- ...document,- remoteDpopTokens: replaceCatalogValue(- document.remoteDpopTokens,- (value) => value.environmentId,- token,- ),- })),- remove: (environmentId) =>- catalog.update((document) => ({- ...document,- remoteDpopTokens: removeCatalogValue(- document.remoteDpopTokens,- (value) => value.environmentId,- environmentId,- ),- })),- });const cacheStore = EnvironmentCacheStore.of({loadShell: (environmentId) =>readDatabaseValue(database, SHELL_STORE_NAME, environmentId).pipe(@@ -666,7 +637,6 @@ export const connectionStorageLayer = Layer.effectContext(Context.add(ConnectionRegistrationStore, registrationStore),Context.add(ProfileStore.ConnectionProfileStore, profileStore),Context.add(CredentialStore.ConnectionCredentialStore, credentialStore),- Context.add(TokenStore.RemoteDpopAccessTokenStore, remoteTokenStore),Context.add(EnvironmentCacheStore, cacheStore),);}),diff --git a/apps/web/src/hostedPairing.test.ts b/apps/web/src/hostedPairing.test.tsindex 5bfeadf21..a9e1dd80b 100644--- a/apps/web/src/hostedPairing.test.ts+++ b/apps/web/src/hostedPairing.test.ts@@ -2,7 +2,6 @@ import { afterEach, describe, expect, it, vi } from "vite-plus/test";import {buildHostedChannelSelectionUrl,- buildHostedPairingUrl,hasHostedPairingRequest,isHostedStaticApp,readHostedPairingRequest,@@ -24,25 +23,6 @@ describe("hostedPairing", () => {expect(hasHostedPairingRequest(url)).toBe(true);});- it("prefers hash tokens so generated hosted links do not put credentials in search params", () => {- vi.stubEnv("VITE_HOSTED_APP_URL", "https://preview.t3.codes");-- const url = new URL(- buildHostedPairingUrl({- host: "https://backend.example.com:3773",- token: "pairing-token",- label: "Workstation",- }),- );-- expect(url.origin).toBe("https://preview.t3.codes");- expect(url.pathname).toBe("/pair");- expect(url.searchParams.get("host")).toBe("https://backend.example.com:3773");- expect(url.searchParams.get("label")).toBe("Workstation");- expect(url.searchParams.has("token")).toBe(false);- expect(url.hash).toBe("#token=pairing-token");- });-it("builds hosted channel selection URLs through the configured router origin", () => {vi.stubEnv("VITE_HOSTED_APP_URL", "https://app.t3.codes");diff --git a/apps/web/src/hostedPairing.ts b/apps/web/src/hostedPairing.tsindex 6a9815b4b..94c6a7837 100644--- a/apps/web/src/hostedPairing.ts+++ b/apps/web/src/hostedPairing.ts@@ -1,6 +1,6 @@-import { DEFAULT_HOSTED_APP_URL } from "@t3tools/shared/connectAuth";+import { getPairingTokenFromUrl } from "./pairingUrl";-import { getPairingTokenFromUrl, setPairingTokenOnUrl } from "./pairingUrl";+const DEFAULT_HOSTED_APP_URL = "https://app.t3.codes";export interface HostedPairingRequest {readonly host: string;@@ -64,22 +64,6 @@ export function hasHostedPairingRequest(url: URL = new URL(window.location.href)return readHostedPairingRequest(url) !== null;}-export function buildHostedPairingUrl(input: {- readonly host: string;- readonly token: string;- readonly label?: string | null;-}): string {- const url = new URL("/pair", configuredHostedAppUrl());- url.searchParams.set("host", input.host);-- const label = input.label?.trim();- if (label) {- url.searchParams.set("label", label);- }-- return setPairingTokenOnUrl(url, input.token).toString();-}-export function buildHostedChannelSelectionUrl(input: {readonly channel: HostedAppChannel;}): string {diff --git a/apps/web/src/lib/previewAnnotation.test.ts b/apps/web/src/lib/previewAnnotation.test.tsindex 05f4b8d62..fa3fc20db 100644--- a/apps/web/src/lib/previewAnnotation.test.ts+++ b/apps/web/src/lib/previewAnnotation.test.ts@@ -5,6 +5,7 @@ import {appendPreviewAnnotationPrompt,buildPreviewAnnotationPrompt,extractTrailingPreviewAnnotation,+ previewAnnotationScreenshotFile,} from "./previewAnnotation";const annotation: PreviewAnnotationPayload = {@@ -45,13 +46,13 @@ const annotation: PreviewAnnotationPayload = {};describe("preview annotations", () => {- it("describes regions, drawings, styles, and screenshot context", () => {+ it("describes regions, drawings, styles, and an omitted screenshot", () => {const result = buildPreviewAnnotationPrompt(annotation);expect(result).toContain("Make these cards feel related.");expect(result).toContain("1 marked region");expect(result).toContain("1 drawing");expect(result).toContain("border-radius: 4px → 16px");- expect(result).toContain("attached screenshot");+ expect(result).toContain("Screenshot omitted because local pixel redaction is unavailable.");});it("appends to an existing composer prompt", () => {@@ -70,10 +71,45 @@ describe("preview annotations", () => {expect(result.annotation).toMatchObject({title: "Example",targetSummary: "1 marked region, 1 drawing.",- hasScreenshot: true,+ hasScreenshot: false,});});+ it("does not turn raw preview pixels into a provider attachment", async () => {+ expect(await previewAnnotationScreenshotFile(annotation)).toBeNull();+ });++ it("redacts annotation text and element context before provider egress", () => {+ const result = buildPreviewAnnotationPrompt({+ ...annotation,+ pageTitle: "[email protected]",+ comment: "token=annotation-secret",+ elements: [+ {+ id: "element_1",+ rect: { x: 0, y: 0, width: 10, height: 10 },+ element: {+ pageUrl: "file:///Users/leo/private-preview.html",+ pageTitle: "Private",+ tagName: "input",+ selector: "#secret",+ htmlPreview: '<input value="token=element-secret">',+ componentName: "SecretInput",+ source: null,+ stack: [],+ styles: "color: red",+ pickedAt: "2026-06-11T00:00:00.000Z",+ },+ },+ ],+ });++ expect(result).not.toContain("[email protected]");+ expect(result).not.toContain("annotation-secret");+ expect(result).not.toContain("Users/leo");+ expect(result).not.toContain("element-secret");+ });+it("extracts multiple trailing annotations one at a time", () => {const first = appendPreviewAnnotationPrompt("Fix this", annotation);const secondAnnotation = { ...annotation, id: "annotation_2", pageTitle: "Details" };diff --git a/apps/web/src/lib/previewAnnotation.ts b/apps/web/src/lib/previewAnnotation.tsindex f1723dd93..d187cb615 100644--- a/apps/web/src/lib/previewAnnotation.ts+++ b/apps/web/src/lib/previewAnnotation.ts@@ -1,4 +1,5 @@import type { PreviewAnnotationPayload } from "@t3tools/contracts";+import { redactSensitiveText } from "@t3tools/shared/sensitiveDataRedaction";import { buildElementContextBlock, normalizeElementContextSelection } from "./elementContext";const TRAILING_PREVIEW_ANNOTATION_BLOCK_PATTERN =@@ -48,14 +49,15 @@ export function buildPreviewAnnotationPrompt(annotation: PreviewAnnotationPayloa}}if (annotation.screenshot) {- lines.push("The attached screenshot is the annotated preview crop.");+ lines.push("Screenshot omitted because local pixel redaction is unavailable.");}const elementContexts = annotation.elements.map((target) => normalizeElementContextSelection(target.element)).filter((context) => context !== null);const elementBlock = buildElementContextBlock(elementContexts);if (elementBlock) lines.push(elementBlock);- return ["<preview_annotation>", ...lines, "</preview_annotation>"].join("\n");+ return redactSensitiveText(["<preview_annotation>", ...lines, "</preview_annotation>"].join("\n"))+ .value;}export function appendPreviewAnnotationPrompt(@@ -100,12 +102,7 @@ export function extractTrailingPreviewAnnotation(prompt: string): ExtractedPrevi}export async function previewAnnotationScreenshotFile(- annotation: PreviewAnnotationPayload,+ _annotation: PreviewAnnotationPayload,): Promise<File | null> {- if (!annotation.screenshot) return null;- const response = await fetch(annotation.screenshot.dataUrl);- const blob = await response.blob();- return new File([blob], `preview-annotation-${annotation.id}.png`, {- type: blob.type || "image/png",- });+ return null;}diff --git a/apps/web/src/lib/runtime.ts b/apps/web/src/lib/runtime.tsindex 3836d2a39..6960eec1b 100644--- a/apps/web/src/lib/runtime.ts+++ b/apps/web/src/lib/runtime.ts@@ -1,35 +1,30 @@import * as ManagedRuntime from "effect/ManagedRuntime";-import type * as Effect from "effect/Effect";+import * as Crypto from "effect/Crypto";+import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";import * as Socket from "effect/unstable/socket/Socket";import { remoteHttpClientLayer } from "@t3tools/client-runtime/rpc";-import { makeRelayClientTracingLayer } from "@t3tools/shared/relayTracing";import * as PrimaryEnvironmentHttpClient from "../environments/primary/httpClient";import { primaryEnvironmentHttpLayer } from "../environments/primary/httpLayer";-import { browserCryptoLayer } from "../cloud/dpop";-import { managedRelayClientLayer } from "../cloud/managedRelayLayer";-import { resolveCloudPublicConfig, resolveRelayTracingConfig } from "../cloud/publicConfig";--function configuredRelayUrl(): string {- return resolveCloudPublicConfig().relayUrl ?? "http://relay.invalid";-}-const httpClientLayer = remoteHttpClientLayer((input, init) => globalThis.fetch(input, init));-const relayTracingLayer = makeRelayClientTracingLayer(resolveRelayTracingConfig(), {- serviceName: "t3-web-relay-client",- serviceVersion: import.meta.env.APP_VERSION,- runtime: "browser",- client: typeof window !== "undefined" && window.desktopBridge ? "desktop" : "web",-}).pipe(Layer.provide(httpClientLayer));-+const browserCryptoLayer = 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));+ }),+ }),+);type RuntimeLayerSource =| typeof httpClientLayer| typeof browserCryptoLayer- | typeof Socket.layerWebSocketConstructorGlobal- | typeof relayTracingLayer- | ReturnType<typeof managedRelayClientLayer>;+ | typeof Socket.layerWebSocketConstructorGlobal;export const remoteHttpRuntime = ManagedRuntime.make(httpClientLayer);@@ -58,10 +53,6 @@ const runtimeLayer = Layer.mergeAll(httpClientLayer,browserCryptoLayer,Socket.layerWebSocketConstructorGlobal,- relayTracingLayer,- managedRelayClientLayer(configuredRelayUrl()).pipe(- Layer.provide(Layer.mergeAll(httpClientLayer, browserCryptoLayer)),- ),);export const runtime: ManagedRuntime.ManagedRuntime<diff --git a/apps/web/src/main.tsx b/apps/web/src/main.tsxindex c5468585d..93d6d61b6 100644--- a/apps/web/src/main.tsx+++ b/apps/web/src/main.tsx@@ -1,22 +1,16 @@import React from "react";import ReactDOM from "react-dom/client";-import { ClerkProvider } from "@clerk/react";-import { passkeys } from "@clerk/electron/passkeys";-import { ClerkProvider as ElectronClerkProvider } from "@clerk/electron/react";import { createHashHistory, createBrowserHistory } from "@tanstack/react-router";import "./index.css";import { isElectron } from "./env";-import { ManagedRelayAuthProvider } from "./cloud/managedAuth";-import { hasCloudPublicConfig } from "./cloud/publicConfig";import { getRouter } from "./router";import {syncDocumentElectronPlatformClasses,syncDocumentWindowControlsOverlayClass,} from "./lib/windowControlsOverlay";import { AppRoot } from "./AppRoot";-import { clerkAppearance } from "./components/clerk/clerkAppearance";// Electron loads the app from a file-backed shell, so hash history avoids path resolution issues.const history = isElectron ? createHashHistory() : createBrowserHistory();@@ -28,29 +22,9 @@ if (isElectron) {syncDocumentWindowControlsOverlayClass();}-const clerkPublishableKey = import.meta.env.VITE_CLERK_PUBLISHABLE_KEY as string | undefined;--const app = <AppRoot router={router} />;-ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(<React.StrictMode>- {clerkPublishableKey && hasCloudPublicConfig() ? (- isElectron ? (- <ElectronClerkProvider- appearance={clerkAppearance}- publishableKey={clerkPublishableKey}- passkeys={passkeys}- >- <ManagedRelayAuthProvider>{app}</ManagedRelayAuthProvider>- </ElectronClerkProvider>- ) : (- <ClerkProvider appearance={clerkAppearance} publishableKey={clerkPublishableKey}>- <ManagedRelayAuthProvider>{app}</ManagedRelayAuthProvider>- </ClerkProvider>- )- ) : (- app- )}+ <AppRoot router={router} /></React.StrictMode>,);diff --git a/apps/web/src/remoteOpen.test.ts b/apps/web/src/remoteOpen.test.tsindex ff78967aa..eb18aece4 100644--- a/apps/web/src/remoteOpen.test.ts+++ b/apps/web/src/remoteOpen.test.ts@@ -1,7 +1,6 @@import {BearerConnectionTarget,PrimaryConnectionTarget,- RelayConnectionTarget,SshConnectionTarget,} from "@t3tools/client-runtime/connection";import { buildRemoteOpenUrl, EnvironmentId } from "@t3tools/contracts";@@ -97,7 +96,11 @@ describe("resolveRemoteOpenState", () => {for (const remoteOpenTargets of [[], undefined] as const) {expect(resolveRemoteOpenState({- target: new RelayConnectionTarget({ environmentId, label: "sol" }),+ target: new BearerConnectionTarget({+ environmentId,+ label: "sol",+ connectionId: "remote-1",+ }),sshAlias: null,isDesktopRenderer: false,remoteOpenTargets,diff --git a/apps/web/src/routeTree.gen.ts b/apps/web/src/routeTree.gen.tsindex 638b173ed..4727bdeb8 100644--- a/apps/web/src/routeTree.gen.ts+++ b/apps/web/src/routeTree.gen.ts@@ -12,12 +12,10 @@ import { Route as rootRouteImport } from './routes/__root'import { Route as UsageRouteImport } from './routes/usage'import { Route as SettingsRouteImport } from './routes/settings'import { Route as PairRouteImport } from './routes/pair'-import { Route as ConnectRouteImport } from './routes/connect'import { Route as ChatRouteImport } from './routes/_chat'import { Route as ChatIndexRouteImport } from './routes/_chat.index'import { Route as SettingsSplatRouteImport } from './routes/settings.$'import { Route as ProjectsProjectKeyRouteImport } from './routes/projects.$projectKey'-import { Route as ConnectCallbackRouteImport } from './routes/connect_.callback'import { Route as ChatGroupsGroupIdRouteImport } from './routes/_chat.groups.$groupId'import { Route as ChatDraftDraftIdRouteImport } from './routes/_chat.draft.$draftId'import { Route as ChatBotsBotIdRouteImport } from './routes/_chat.bots.$botId'@@ -38,11 +36,6 @@ const PairRoute = PairRouteImport.update({path: '/pair',getParentRoute: () => rootRouteImport,} as any)-const ConnectRoute = ConnectRouteImport.update({- id: '/connect',- path: '/connect',- getParentRoute: () => rootRouteImport,-} as any)const ChatRoute = ChatRouteImport.update({id: '/_chat',getParentRoute: () => rootRouteImport,@@ -62,11 +55,6 @@ const ProjectsProjectKeyRoute = ProjectsProjectKeyRouteImport.update({path: '/projects/$projectKey',getParentRoute: () => rootRouteImport,} as any)-const ConnectCallbackRoute = ConnectCallbackRouteImport.update({- id: '/connect_/callback',- path: '/connect/callback',- getParentRoute: () => rootRouteImport,-} as any)const ChatGroupsGroupIdRoute = ChatGroupsGroupIdRouteImport.update({id: '/groups/$groupId',path: '/groups/$groupId',@@ -91,11 +79,9 @@ const ChatEnvironmentIdThreadIdRoute =export interface FileRoutesByFullPath {'/': typeof ChatIndexRoute- '/connect': typeof ConnectRoute'/pair': typeof PairRoute'/settings': typeof SettingsRouteWithChildren'/usage': typeof UsageRoute- '/connect/callback': typeof ConnectCallbackRoute'/projects/$projectKey': typeof ProjectsProjectKeyRoute'/settings/$': typeof SettingsSplatRoute'/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute@@ -104,11 +90,9 @@ export interface FileRoutesByFullPath {'/groups/$groupId': typeof ChatGroupsGroupIdRoute}export interface FileRoutesByTo {- '/connect': typeof ConnectRoute'/pair': typeof PairRoute'/settings': typeof SettingsRouteWithChildren'/usage': typeof UsageRoute- '/connect/callback': typeof ConnectCallbackRoute'/projects/$projectKey': typeof ProjectsProjectKeyRoute'/settings/$': typeof SettingsSplatRoute'/': typeof ChatIndexRoute@@ -120,11 +104,9 @@ export interface FileRoutesByTo {export interface FileRoutesById {__root__: typeof rootRouteImport'/_chat': typeof ChatRouteWithChildren- '/connect': typeof ConnectRoute'/pair': typeof PairRoute'/settings': typeof SettingsRouteWithChildren'/usage': typeof UsageRoute- '/connect_/callback': typeof ConnectCallbackRoute'/projects/$projectKey': typeof ProjectsProjectKeyRoute'/settings/$': typeof SettingsSplatRoute'/_chat/': typeof ChatIndexRoute@@ -137,11 +119,9 @@ export interface FileRouteTypes {fileRoutesByFullPath: FileRoutesByFullPathfullPaths:| '/'- | '/connect'| '/pair'| '/settings'| '/usage'- | '/connect/callback'| '/projects/$projectKey'| '/settings/$'| '/$environmentId/$threadId'@@ -150,11 +130,9 @@ export interface FileRouteTypes {| '/groups/$groupId'fileRoutesByTo: FileRoutesByToto:- | '/connect'| '/pair'| '/settings'| '/usage'- | '/connect/callback'| '/projects/$projectKey'| '/settings/$'| '/'@@ -165,11 +143,9 @@ export interface FileRouteTypes {id:| '__root__'| '/_chat'- | '/connect'| '/pair'| '/settings'| '/usage'- | '/connect_/callback'| '/projects/$projectKey'| '/settings/$'| '/_chat/'@@ -181,11 +157,9 @@ export interface FileRouteTypes {}export interface RootRouteChildren {ChatRoute: typeof ChatRouteWithChildren- ConnectRoute: typeof ConnectRoutePairRoute: typeof PairRouteSettingsRoute: typeof SettingsRouteWithChildrenUsageRoute: typeof UsageRoute- ConnectCallbackRoute: typeof ConnectCallbackRouteProjectsProjectKeyRoute: typeof ProjectsProjectKeyRoute}@@ -212,13 +186,6 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof PairRouteImportparentRoute: typeof rootRouteImport}- '/connect': {- id: '/connect'- path: '/connect'- fullPath: '/connect'- preLoaderRoute: typeof ConnectRouteImport- parentRoute: typeof rootRouteImport- }'/_chat': {id: '/_chat'path: ''@@ -247,13 +214,6 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof ProjectsProjectKeyRouteImportparentRoute: typeof rootRouteImport}- '/connect_/callback': {- id: '/connect_/callback'- path: '/connect/callback'- fullPath: '/connect/callback'- preLoaderRoute: typeof ConnectCallbackRouteImport- parentRoute: typeof rootRouteImport- }'/_chat/groups/$groupId': {id: '/_chat/groups/$groupId'path: '/groups/$groupId'@@ -317,11 +277,9 @@ const SettingsRouteWithChildren = SettingsRoute._addFileChildren(const rootRouteChildren: RootRouteChildren = {ChatRoute: ChatRouteWithChildren,- ConnectRoute: ConnectRoute,PairRoute: PairRoute,SettingsRoute: SettingsRouteWithChildren,UsageRoute: UsageRoute,- ConnectCallbackRoute: ConnectCallbackRoute,ProjectsProjectKeyRoute: ProjectsProjectKeyRoute,}export const routeTree = rootRouteImportdiff --git a/apps/web/src/routes/__root.tsx b/apps/web/src/routes/__root.tsxindex e9b016e0c..22a343090 100644--- a/apps/web/src/routes/__root.tsx+++ b/apps/web/src/routes/__root.tsx@@ -9,8 +9,6 @@ import { resolveServerBackedAppDisplayName } from "../branding.logic";import { AppSidebarLayout } from "../components/AppSidebarLayout";import { CommandPalette } from "../components/CommandPalette";import { ConfirmDialogHost } from "../components/ConfirmDialogHost";-import { ConnectOnboardingDialog } from "../components/cloud/ConnectOnboardingDialog";-import { RelayClientInstallDialog } from "../components/cloud/RelayClientInstallDialog";import { SshPasswordPromptDialog } from "../components/desktop/SshPasswordPromptDialog";import { ProviderUpdateLaunchNotification } from "../components/ProviderUpdateLaunchNotification";import { VoiceCallProvider } from "../components/voice/VoiceCall";@@ -20,6 +18,7 @@ import { SettingsDialog } from "../components/settings/SettingsDialog";import { PluginsDialog } from "../components/plugins/PluginsDialog";import { UsageDialog } from "../components/usage/UsageDialog";import { ProductFeedbackDialog } from "../components/productFeedback/ProductFeedbackDialog";+import { PolicyNotice } from "../components/privacy/PolicyNotice";import { RootRouteErrorView } from "./RootRouteErrorView";import {AnchoredToastProvider,@@ -101,7 +100,7 @@ function RootRouteView() {};}, [pathname]);- if (pathname === "/pair" || pathname === "/connect" || pathname.startsWith("/connect/")) {+ if (pathname === "/pair") {return (<><DocumentTitleSync />@@ -135,8 +134,6 @@ function RootRouteView() {<GlassAppearanceSync /><FontAppearanceSync />{primaryEnvironmentAuthenticated ? <AuthenticatedTracingBootstrap /> : null}- <RelayClientInstallDialog />- <ConnectOnboardingDialog /><SshPasswordPromptDialog /><ConfirmDialogHost /><SlowRpcRequestToastCoordinator />@@ -149,6 +146,7 @@ function RootRouteView() {<PluginsDialog /><UsageDialog /><ProductFeedbackDialog />+ <PolicyNotice />{/* Above the router: a theme draft is judged by walking the app, so theeditor has to survive navigation away from settings. */}<ThemeEditorHost />diff --git a/apps/web/src/routes/_chat.bots.$botId.tsx b/apps/web/src/routes/_chat.bots.$botId.tsxindex 699698a74..3ab5ae5b9 100644--- a/apps/web/src/routes/_chat.bots.$botId.tsx+++ b/apps/web/src/routes/_chat.bots.$botId.tsx@@ -32,6 +32,7 @@ function BotThreadRouteView() {label,description,engine,+ usageCap,sandbox,voiceEnabled,disabledMcpServerIds,@@ -45,6 +46,7 @@ function BotThreadRouteView() {label,description,engine,+ usageCap,sandbox,voiceEnabled,disabledMcpServerIds,diff --git a/apps/web/src/routes/_chat.index.tsx b/apps/web/src/routes/_chat.index.tsxindex 557f3fe4c..c3a67468c 100644--- a/apps/web/src/routes/_chat.index.tsx+++ b/apps/web/src/routes/_chat.index.tsx@@ -3,7 +3,6 @@ import { LinkIcon, PlusIcon } from "lucide-react";import { useEffect } from "react";import { APP_DISPLAY_NAME } from "~/branding";-import { hasCloudPublicConfig } from "~/cloud/publicConfig";import { resolveRosterBotId } from "../components/roster/roster.logic";import { useRosterStore } from "../components/roster/rosterStore";import { Button } from "../components/ui/button";@@ -51,8 +50,6 @@ export const Route = createFileRoute("/_chat/")({});function HostedStaticOnboardingState() {- const cloudEnabled = hasCloudPublicConfig();-return (<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground"><div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-x-hidden bg-background">@@ -74,14 +71,12 @@ function HostedStaticOnboardingState() {Connect an environment to get started</EmptyTitle><EmptyDescription className="mt-2 text-sm leading-relaxed text-muted-foreground/78">- {cloudEnabled- ? "Sign in to connect a linked environment through its managed tunnel, or add a reachable backend manually."- : "Add a reachable backend manually to start working from this browser."}+ Add a reachable backend manually to start working from this browser.</EmptyDescription><div className="mt-6 flex justify-center"><Button size="sm" onClick={() => openSettings("connections")}><PlusIcon className="size-4" />- {cloudEnabled ? "Open Connections" : "Add environment"}+ Add environment</Button></div></EmptyHeader>diff --git a/apps/web/src/routes/connect.tsx b/apps/web/src/routes/connect.tsxdeleted file mode 100644index 30750a977..000000000--- a/apps/web/src/routes/connect.tsx+++ /dev/null@@ -1,13 +0,0 @@-import { createFileRoute, redirect } from "@tanstack/react-router";--import { connectCliAuthRoutesEnabled } from "../cloud/connectCliAuth";-import { ConnectCliAuthorizeSurface } from "../components/cloud/ConnectCliAuthSurface";--export const Route = createFileRoute("/connect")({- beforeLoad: () => {- if (!connectCliAuthRoutesEnabled()) {- throw redirect({ to: "/", replace: true });- }- },- component: ConnectCliAuthorizeSurface,-});diff --git a/apps/web/src/routes/connect_.callback.tsx b/apps/web/src/routes/connect_.callback.tsxdeleted file mode 100644index a5beee0b9..000000000--- a/apps/web/src/routes/connect_.callback.tsx+++ /dev/null@@ -1,13 +0,0 @@-import { createFileRoute, redirect } from "@tanstack/react-router";--import { connectCliAuthRoutesEnabled } from "../cloud/connectCliAuth";-import { ConnectCliCallbackSurface } from "../components/cloud/ConnectCliAuthSurface";--export const Route = createFileRoute("/connect_/callback")({- beforeLoad: () => {- if (!connectCliAuthRoutesEnabled()) {- throw redirect({ to: "/", replace: true });- }- },- component: ConnectCliCallbackSurface,-});diff --git a/apps/web/src/session-logic.ts b/apps/web/src/session-logic.tsindex ed84f3b39..53753f509 100644--- a/apps/web/src/session-logic.ts+++ b/apps/web/src/session-logic.ts@@ -447,10 +447,10 @@ export function derivePendingApprovals(? payload.options.filter(isProviderApprovalOption): undefined;- if (activity.kind === "approval.requested" && requestId && requestKind) {+ if (activity.kind === "approval.requested" && requestId) {openByRequestId.set(requestId, {requestId,- requestKind,+ requestKind: requestKind ?? "command",createdAt: activity.createdAt,...(detail ? { detail } : {}),...(appName ? { appName } : {}),diff --git a/apps/web/src/settingsDialogStore.ts b/apps/web/src/settingsDialogStore.tsindex 3efa8cdef..1c75672b7 100644--- a/apps/web/src/settingsDialogStore.ts+++ b/apps/web/src/settingsDialogStore.ts@@ -18,6 +18,7 @@ export const SETTINGS_SECTIONS = ["appearance","providers","voice",+ "privacy","connections","keybindings","source-control",diff --git a/apps/web/src/state/environments.ts b/apps/web/src/state/environments.tsindex 7d9221a69..f936fee74 100644--- a/apps/web/src/state/environments.ts+++ b/apps/web/src/state/environments.ts@@ -3,7 +3,6 @@ import {connectionCatalogDisplayUrl,type EnvironmentPresentation as BaseEnvironmentPresentation,} from "@t3tools/client-runtime/connection";-import { Discovery } from "@t3tools/client-runtime/relay";import type { EnvironmentId } from "@t3tools/contracts";import * as Option from "effect/Option";import { useMemo } from "react";@@ -12,14 +11,12 @@ import { environmentCatalog } from "../connection/catalog";import { environmentPresentations, useEnvironmentPresentation } from "./presentation";import { primaryEnvironmentIdAtom } from "./primaryEnvironment";import { useEnvironmentQuery } from "./query";-import { relayEnvironmentDiscovery } from "./relay";import { usePreparedConnection } from "./session";export interface EnvironmentPresentation extends BaseEnvironmentPresentation {readonly environmentId: EnvironmentId;readonly label: string;readonly displayUrl: string | null;- readonly relayManaged: boolean;}function projectEnvironmentPresentation(@@ -31,7 +28,6 @@ function projectEnvironmentPresentation(environmentId,label: presentation.entry.target.label,displayUrl: connectionCatalogDisplayUrl(presentation.entry),- relayManaged: presentation.entry.target._tag === "RelayConnectionTarget",};}@@ -82,10 +78,6 @@ export function useEnvironmentHttpBaseUrl(environmentId: EnvironmentId | null):return Option.isSome(prepared) ? prepared.value.httpBaseUrl : null;}-export function useRelayEnvironmentDiscovery(): Discovery.RelayEnvironmentDiscoveryState {- return useAtomValue(relayEnvironmentDiscovery.stateValueAtom);-}-export function useEnvironmentConnectionState(environmentId: EnvironmentId | null) {return useEnvironmentQuery(environmentId ? environmentCatalog.stateAtom(environmentId) : null);}diff --git a/apps/web/src/state/relay.ts b/apps/web/src/state/relay.tsdeleted file mode 100644index 3cbac7a18..000000000--- a/apps/web/src/state/relay.ts+++ /dev/null@@ -1,6 +0,0 @@-import { createRelayEnvironmentDiscoveryAtoms } from "@t3tools/client-runtime/state/relay";--import { connectionAtomRuntime } from "../connection/runtime";--export const relayEnvironmentDiscovery: ReturnType<typeof createRelayEnvironmentDiscoveryAtoms> =- createRelayEnvironmentDiscoveryAtoms(connectionAtomRuntime);diff --git a/apps/web/src/vite-env.d.ts b/apps/web/src/vite-env.d.tsindex 31260c8ae..01f2bd81b 100644--- a/apps/web/src/vite-env.d.ts+++ b/apps/web/src/vite-env.d.ts@@ -7,12 +7,6 @@ interface ImportMetaEnv {readonly VITE_WS_URL: string;readonly VITE_HOSTED_APP_URL: string;readonly VITE_HOSTED_APP_CHANNEL: string;- readonly VITE_CLERK_PUBLISHABLE_KEY: string;- readonly VITE_CLERK_JWT_TEMPLATE: string;- readonly VITE_CLERK_CLI_OAUTH_CLIENT_ID: string;- readonly VITE_RELAY_OTLP_TRACES_URL: string;- readonly VITE_RELAY_OTLP_TRACES_DATASET: string;- readonly VITE_RELAY_OTLP_TRACES_TOKEN: string;readonly APP_VERSION: string;}diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.tsindex f3a9b8ab1..ecf74989a 100644--- a/apps/web/vite.config.ts+++ b/apps/web/vite.config.ts@@ -34,13 +34,6 @@ const explicitHost = process.env.HOST?.trim();const host = explicitHost || "localhost";const configuredWsUrl = isSingleOriginDev ? undefined : process.env.VITE_WS_URL?.trim();const configuredHttpUrl = isSingleOriginDev ? undefined : process.env.VITE_HTTP_URL?.trim();-const configuredRelayUrl = repoEnv.VITE_T3CODE_RELAY_URL?.trim() || "";-const configuredClerkPublishableKey = repoEnv.VITE_CLERK_PUBLISHABLE_KEY?.trim() || "";-const configuredClerkJwtTemplate = repoEnv.VITE_CLERK_JWT_TEMPLATE?.trim() || "";-const configuredClerkCliOAuthClientId = repoEnv.VITE_CLERK_CLI_OAUTH_CLIENT_ID?.trim() || "";-const configuredRelayTracingUrl = repoEnv.VITE_RELAY_OTLP_TRACES_URL?.trim() || "";-const configuredRelayTracingDataset = repoEnv.VITE_RELAY_OTLP_TRACES_DATASET?.trim() || "";-const configuredRelayTracingToken = repoEnv.VITE_RELAY_OTLP_TRACES_TOKEN?.trim() || "";const configuredHostedAppChannel = process.env.VITE_HOSTED_APP_CHANNEL?.trim() || "";const configuredAppVersion = process.env.APP_VERSION?.trim() || pkg.version;const configuredHostedAppUrl = (() => {@@ -173,7 +166,6 @@ export default defineConfig(() => {],optimizeDeps: {include: [- "@clerk/react/internal","@pierre/diffs","@pierre/diffs/editor","@pierre/diffs/react",@@ -191,17 +183,6 @@ export default defineConfig(() => {// under single-origin dev this must stay empty even when a `.env`// supplies it, so the client falls back to window.location.origin."import.meta.env.VITE_HTTP_URL": JSON.stringify(configuredHttpUrl ?? ""),- "import.meta.env.VITE_T3CODE_RELAY_URL": JSON.stringify(configuredRelayUrl),- "import.meta.env.VITE_CLERK_PUBLISHABLE_KEY": JSON.stringify(configuredClerkPublishableKey),- "import.meta.env.VITE_CLERK_JWT_TEMPLATE": JSON.stringify(configuredClerkJwtTemplate),- "import.meta.env.VITE_CLERK_CLI_OAUTH_CLIENT_ID": JSON.stringify(- configuredClerkCliOAuthClientId,- ),- "import.meta.env.VITE_RELAY_OTLP_TRACES_URL": JSON.stringify(configuredRelayTracingUrl),- "import.meta.env.VITE_RELAY_OTLP_TRACES_DATASET": JSON.stringify(- configuredRelayTracingDataset,- ),- "import.meta.env.VITE_RELAY_OTLP_TRACES_TOKEN": JSON.stringify(configuredRelayTracingToken),"import.meta.env.VITE_HOSTED_APP_URL": JSON.stringify(configuredHostedAppUrl ?? ""),"import.meta.env.VITE_HOSTED_APP_CHANNEL": JSON.stringify(configuredHostedAppChannel),"import.meta.env.APP_VERSION": JSON.stringify(configuredAppVersion),diff --git a/docs/README.md b/docs/README.mdindex 64cccc723..92742d5f3 100644--- a/docs/README.md+++ b/docs/README.md@@ -1,6 +1,6 @@-# T3 Code docs+# Akeru Bot docs-## Using T3 Code+## Using Akeru Bot- [Install and first run](./user/install.md)- [Permission modes](./user/permission-modes.md)@@ -8,6 +8,7 @@- [Organizing threads](./user/thread-sidebar.md)- [Sending product feedback](./user/product-feedback.md)- [Plugins](./user/plugins.md)+- [Privacy and outbound data](./user/privacy.md)- [Review usage](./user/usage.md)- [Anonymous usage analytics](./user/analytics.md)- [Customize a project icon](./user/project-settings.md)@@ -22,7 +23,7 @@ Mobile app: [apps/mobile/README.md](../apps/mobile/README.md)----## Working on T3 Code+## Working on Akeru BotEverything below is for maintainers. Setup lives in the [root README](../README.md);policy in [CONTRIBUTING.md](../CONTRIBUTING.md); agent rules in [AGENTS.md](../AGENTS.md).@@ -39,7 +40,6 @@ policy in [CONTRIBUTING.md](../CONTRIBUTING.md); agent rules in [AGENTS.md](../A- [Resource telemetry](./internals/resource-telemetry.md)- [Usage analytics](./internals/usage-analytics.md)- [Environment auth](./internals/environment-auth.md)-- [T3 Connect](./internals/t3-connect.md)- [CI gates](./internals/ci.md)- [Engineering work artifacts](./internals/work-artifacts.md)@@ -47,5 +47,4 @@ policy in [CONTRIBUTING.md](../CONTRIBUTING.md); agent rules in [AGENTS.md](../A- [Release](./operations/release.md)- [Observability](./operations/observability.md)-- [Relay observability](./operations/relay-observability.md)- [Mobile app store screenshots](./operations/mobile-app-store-screenshots.md)diff --git a/docs/internals/connection-runtime.md b/docs/internals/connection-runtime.mdindex 46fe0c827..51e88768c 100644--- a/docs/internals/connection-runtime.md+++ b/docs/internals/connection-runtime.md@@ -1,6 +1,6 @@# Connection Runtime-> For maintainers. Using T3 Code? See [docs/user](../user/).+> For maintainers. Using Akeru Bot? See [docs/user](../user/).The connection runtime is shared by web and mobile. It owns connectivity,authentication, retries, transport lifetime, cached environment data, and@@ -16,7 +16,7 @@ supply. There is no legacy connection owner or supported mixed mode.[`connection/layer.ts`][layer] assembles the runtime:- `ConnectionResolver` ([resolver.ts][resolver]) resolves a catalog entry into a- prepared, authenticated endpoint for primary, bearer, relay, or SSH targets.+ prepared, authenticated endpoint for primary, bearer, or SSH targets.- `ConnectionDriver` ([driver.ts][driver]) prepares through the resolver, opensone RPC session, and reports `preparing`, `opening`, and `synchronizing`.- `RpcSessionFactory` ([rpc/session.ts][session]) performs one transport@@ -68,8 +68,6 @@ Wakeup handling differs by phase, in [supervisor.ts][supervisor]:background suspension; it interrupts establishment and resets the retryladder, because the OS may have silently killed the socket underneath theattempt.-- Credential changes interrupt establishment only for relay targets, where a new- credential changes what is being established.- Explicit disconnect, explicit retry, and going offline interrupt establishmentin every case.- While waiting out backoff, application activation resets the retry ladder so a@@ -127,8 +125,6 @@ Web and mobile provide:- network status and network-change streams;- application lifecycle wakeups;-- cloud session credentials;-- device identity;- platform registrations;- persistent catalog, credential, shell, and thread stores;- HTTP, crypto, and telemetry layers.@@ -168,8 +164,6 @@ Required coverage includes:- authentication wakeups;- involuntary close and reconnect;- explicit removal clearing all owned state;-- relay token reuse and refresh;-- progressive relay discovery;- shell and thread cache hydration;- durable subscriptions switching sessions;- command metadata and idempotent queued-command metadata.diff --git a/docs/internals/environment-auth.md b/docs/internals/environment-auth.mdindex 5f4f5b6e9..fc7dbdf83 100644--- a/docs/internals/environment-auth.md+++ b/docs/internals/environment-auth.md@@ -1,62 +1,43 @@-# Environment Authentication Profile+# Environment authentication-> For maintainers. Using T3 Code? See [docs/user](../user/).+> For maintainers. Using Akeru Bot? See [remote access](../user/remote-access.md).-The environment server and the relay use separate credentials, issuers, and trust-boundaries. They intentionally use a similar OAuth-shaped model so that permission-checks and token exchange behavior can be audited against established concepts.+Each Akeru Bot server authenticates its own clients. There is no hosted account or third-party trust+boundary.-## Authorization Model+## Scopes-Environment authorization is capability-based. A session carries zero or more-OAuth-style scope strings:+| Scope | Permission |+| ----------------------- | ------------------------------------------------------- |+| `orchestration:read` | Read projects, threads, configuration, and diagnostics. |+| `orchestration:operate` | Change server and orchestration state. |+| `terminal:operate` | Open and control terminals. |+| `review:write` | Submit review operations. |+| `access:read` | List pairing links and client sessions. |+| `access:write` | Create and revoke pairing links and sessions. |-| Scope | Permission |-| ----------------------- | ------------------------------------------------------------------------ |-| `orchestration:read` | Read snapshots, status, events, configuration, and filesystem/VCS state. |-| `orchestration:operate` | Dispatch user operations and mutate environment-side workspace state. |-| `terminal:operate` | Create, attach, input, resize, clear, restart, and terminate terminals. |-| `review:write` | Read review diff previews used to compose review feedback. |-| `access:read` | Inspect pairing links and client sessions. |-| `access:write` | Create or revoke pairing links and client sessions. |-| `relay:read` | Inspect managed relay connectivity. |-| `relay:write` | Link, configure, or unlink managed relay connectivity. |+Ordinary pairing credentials grant the four orchestration, terminal, and review scopes.+Administrative credentials also grant both access scopes.-Ordinary pairing links grant the four client-operation scopes and read access to-managed relay connectivity:-`orchestration:read orchestration:operate terminal:operate review:write relay:read`.-The desktop bootstrap credential and command-line administrative bootstrap-credentials additionally grant `access:read access:write relay:write`.+## Bootstrap methods-## Authentication Flows+The server accepts these short-lived bootstrap methods:-### Browser Session+- `desktop-bootstrap` for the trusted local desktop handoff.+- `one-time-token` for manual pairing.-`POST /api/auth/browser-session` consumes a one-time bootstrap credential and creates a-browser session cookie. The cookie is an HTTP transport adapter for the same-scoped session model; the response never exposes the session secret to browser-JavaScript.+A bootstrap credential is not a steady-state session. The client exchanges it for either a browser+cookie or a bearer access token.-### Bearer Access Token+## Session methods-Non-browser clients use `POST /oauth/token` with an-`application/x-www-form-urlencoded` body:+The server advertises two session methods:-```text-grant_type=urn:ietf:params:oauth:grant-type:token-exchange-subject_token=<bootstrap credential>-subject_token_type=urn:t3:params:oauth:token-type:environment-bootstrap-requested_token_type=urn:ietf:params:oauth:token-type:access_token-scope=orchestration:read orchestration:operate terminal:operate review:write relay:read-```--Clients may additionally submit `client_label`, `client_device_type`, and-`client_os` extension parameters so the authorized-clients UI can identify the-device that established the session. These are presentation hints only; the-environment derives transport metadata such as IP address and user agent from-the request and does not use these fields for authorization.+- `browser-session-cookie` for a browser served by that server.+- `bearer-access-token` for saved remote, mobile, desktop, and SSH connections.-The response has the token-exchange shape:+`POST /oauth/token` uses the OAuth token-exchange request shape. Requested scopes must be a subset+of the bootstrap grant. A successful response has this form:```json{@@ -64,78 +45,31 @@ The response has the token-exchange shape:"issued_token_type": "urn:ietf:params:oauth:token-type:access_token","token_type": "Bearer","expires_in": 2592000,- "scope": "orchestration:read orchestration:operate terminal:operate review:write relay:read"+ "scope": "orchestration:read orchestration:operate terminal:operate review:write"}```-Sessions issued from a plain bearer exchange use the store's-`DEFAULT_SESSION_TTL` of 30 days. The shorter one-hour `expires_in: 3600` applies-only to DPoP-bound exchanges, where the token is additionally constrained by a-proof key. See `SessionStore.ts` and `EnvironmentAuth.ts`.--Requested scopes must be a subset of the one-time bootstrap credential grant.-An ordinary paired client therefore cannot exchange its grant for-`access:read`, `access:write`, or `relay:write`.--### DPoP-Bound Access Token--The same `/oauth/token` exchange supports proof-of-possession tokens. A client-that sends a `DPoP` header has its proof verified by `verifyRequestDpopProof`;-the resulting JWK thumbprint is stored on the session, which is then issued with-method `dpop-access-token` and a one-hour TTL instead of the bearer default. An-invalid proof gets a DPoP challenge header and a credential error rather than a-bearer token.--`dpop-access-token` is advertised alongside `browser-session-cookie` and-`bearer-access-token` in the descriptor's `sessionMethods`-(`EnvironmentAuthPolicy.ts`), so clients can discover support rather than-assume it. Relay-brokered clients use this mode so that a leaked token cannot be-replayed without the corresponding key.--### WebSocket Ticket--`POST /api/auth/websocket-ticket` accepts any authenticated session and returns-a short-lived, single-purpose WebSocket ticket, issued through-`EnvironmentAuth.issueWebSocketTicket` with a five-minute default TTL. The-client presents its bearer or DPoP credential in headers to get the ticket, then-appends only that ticket to the socket URL as `wsTicket`. This keeps long-lived-tokens and browser cookies out of WebSocket URLs while letting the handshake-authenticate.--The ticket carries its session's scopes; each RPC method then enforces-`orchestration:read`, `orchestration:operate`, `terminal:operate`,-`review:write`, `relay:write`, or `access:read` as appropriate, through-`RPC_REQUIRED_SCOPES` in `apps/server/src/auth/RpcAuthorization.ts`. Review feedback submission currently dispatches-an orchestration operation, so clients performing it also need-`orchestration:operate`. Creating a ticket is not authorization to call every-RPC method.--## Standards Alignment--- Bearer access tokens are used through the `Authorization: Bearer` scheme from- RFC 6750.-- The token endpoint profiles the request and response vocabulary from OAuth 2.0- Token Exchange (RFC 8693), including `subject_token`, `requested_token_type`,- `access_token`, `issued_token_type`, and `token_type`.-- Scope values follow the OAuth 2.0 scope model from RFC 6749: space-delimited,- unordered capabilities with subset checking during exchange.--This is intentionally not a general-purpose OAuth authorization server. The-environment bootstrap token type is private, the bootstrap cookie and WebSocket-connection-token routes are product-specific adapters, and the API returns its-typed `HttpApi` errors rather than implementing every OAuth error response-surface.--## Upgrade Behavior--Migration `031_AuthAuthorizationScopes` is a hard cutover from role-bearing auth-records to scoped records. It deletes existing pairing links and sessions while-leaving non-authentication environment state unchanged. Upgraded clients must-pair again; old `owner` or `client` credentials are never silently mapped to new-capabilities.--## Relay Boundary--Relay-managed tunnels use their own tokens and keys. The relay can reuse scope-parsing and token-exchange conventions, but an environment access token is not a-relay token and cannot be presented to the relay.+The server stores client presentation metadata for the authorized-clients list. IP address and user+agent come from the request. Presentation fields do not grant access.++## WebSocket tickets++`POST /api/auth/websocket-ticket` accepts an authenticated session and returns a short-lived+WebSocket ticket. The client sends its bearer token in the HTTP authorization header, then places+only the ticket in the WebSocket URL.++Each RPC method maps to one required scope in+`apps/server/src/auth/RpcAuthorization.ts`. Creating a ticket does not authorize every RPC.++## Pairing records++Manual pairing links are single-use and expire. Desktop bootstrap credentials remain reusable for+the desktop process lifetime so a renderer reload can recover.++The database can contain legacy proof-bound pairing rows from an older release. The bearer-only+runtime does not consume or list those rows. It does not downgrade them to bearer credentials.++## Upgrade behavior++The scoped-auth migration invalidates older role-based links and sessions. Clients must pair again.+The server does not map old owner or client roles to new scopes.diff --git a/docs/internals/remote.md b/docs/internals/remote.mdindex 6b7c67ad9..8161449bf 100644--- a/docs/internals/remote.md+++ b/docs/internals/remote.md@@ -1,235 +1,70 @@-# Remote Architecture--> For maintainers. Using T3 Code? See [docs/user](../user/).--Remote environments are shipped, not planned. Direct, bearer-paired, relay-tunneled, Tailscale, and-desktop-managed SSH access all exist today. This document describes the model they share and where-each piece lives. For the user-facing setup guide see-[remote access](../user/remote-access.md).--## The model--T3 has one runtime boundary: a client talks to a T3 server over HTTP and WebSocket, and the server-owns orchestration, providers, terminals, git, and filesystem operations. Remoteness is expressed at-the connection layer, never by splitting the runtime.--```text-┌──────────────────────────────────────────────┐-│ Client (desktop / mobile / web) │-│ known environments, connection supervisor │-└───────────────┬──────────────────────────────┘- │ resolves one access endpoint-┌───────────────▼──────────────────────────────┐-│ Access method │-│ direct ws/wss, relay tunnel, │-│ Tailscale serve, desktop-managed ssh │-└───────────────┬──────────────────────────────┘- │ connects to one T3 server-┌───────────────▼──────────────────────────────┐-│ Execution environment = one T3 server │-│ identity, providers, projects/threads, │-│ terminals, git, filesystem │-└──────────────────────────────────────────────┘-```--### ExecutionEnvironment--One running T3 server instance. It owns provider availability and auth, model availability, projects-and threads, terminal processes, filesystem access, git operations, and server settings.+# Remote architecture-It is identified by a stable `environmentId`, persisted by the server at `<stateDir>/environment-id`-and generated on first start (`apps/server/src/environment/ServerEnvironment.ts`). Desktop, mobile,-and web all reason about the same concept.+> For maintainers. Using Akeru Bot? See [remote access](../user/remote-access.md).-### Known environments and connection targets+A client connects to one Akeru Bot server over HTTP and WebSocket. The server owns providers,+projects, threads, terminals, git, and filesystem access. Remote access changes how the client+reaches the server. It does not split that runtime.-A saved client-side entry for an environment the client knows how to reach. It is not-server-authored; it is local to a device or client profile. In the hosted web app these entries are-browser-local. A hosted pairing URL can create one, but it does not give the hosted app a server-side-control plane or a copy of session state.--[`connection/model.ts`][model] defines four target tags, which are the real access taxonomy:--| Target | Used for |-| ------------------------- | ------------------------------------------------------------------------ |-| `PrimaryConnectionTarget` | The platform-managed local server (desktop backend, CLI-served web app). |-| `BearerConnectionTarget` | Any manually paired endpoint reached over direct HTTP/WebSocket. |-| `RelayConnectionTarget` | Managed T3 Connect relay tunnels. |-| `SshConnectionTarget` | Desktop-managed SSH environments. |+## Connection targets-Bearer, relay, and SSH are persisted; primary is platform-managed. Note that Tailscale is not a-separate target kind. A Tailscale URL is paired through the ordinary bearer path in-[`onboarding.ts`][onboarding] (`preparePairingRegistration`), which accepts either a pairing URL or a-host plus pairing code. Tailscale is an endpoint provider and transport, not a distinct runtime-concept.--### AdvertisedEndpoint--A server- or desktop-authored candidate endpoint for an environment: a concrete HTTP and WebSocket-base URL pair, a default/available/unavailable marker, reachability hints (loopback, LAN, private,-public, tunnel), and compatibility hints such as whether the hosted HTTPS app can use it.--Clients treat advertised endpoints as hints, not proof that a route works from the current device.-The connection attempt decides.--The UI shows one default endpoint in the network-access summary and keeps the rest behind an advanced-list. `selectPairingEndpoint` in-[`ConnectionsSettings.tsx`](../../apps/web/src/components/settings/ConnectionsSettings.tsx) excludes-unavailable endpoints and then picks, in order:+The shared client runtime defines three target types:-1. the saved `defaultEndpointKey` override;-2. the first endpoint marked `isDefault`;-3. the first endpoint whose reachability is not `loopback`;-4. the first endpoint compatible with the hosted HTTPS app;-5. otherwise nothing.--There is no unconditional loopback fallback. A loopback endpoint only wins through an explicit saved-override or `isDefault`. Persist the override by stable endpoint kind rather than raw URL where-possible, since LAN addresses change with networks; Tailscale endpoints use provider-specific stable-keys (`tailscale-ip:`, `tailscale-magicdns:`).--### Endpoint providers--Endpoint providers contribute advertised endpoints without becoming part of the core environment-model: core owns environments, pairing, and connection lifecycle, and providers return normalized-`AdvertisedEndpoint` records.--Tailscale is the first provider, and T3 manages more than discovery. When `tailscaleServeEnabled` is-set, the server acquires a Tailscale serve mapping for its actual listening port at startup with-`ensureTailscaleServe` and releases it with `disableTailscaleServe` on scope close-(`apps/server/src/server.ts`, using [`@t3tools/tailscale`](../../packages/tailscale/src/tailscale.ts)).-Endpoint identifiers are synthesized in `apps/desktop/src/backend/tailscaleEndpointProvider.ts` with-`private-network` reachability.--### Hosted pairing request--A hosted pairing request is a bootstrap URL for the static web app, not a transport:--```text-https://app.t3.codes/pair?host=https://backend.example.com:3773#token=PAIRCODE-```--The hosted app reads `host`, takes the token from the URL hash, exchanges it directly with that-backend, strips the token from browser history, and saves the environment record locally. Helpers-live in [`shared/remote.ts`](../../packages/shared/src/remote.ts) (`setPairingTokenOnUrl`,-`getPairingTokenFromUrl`, `stripPairingTokenFromUrl`) and `apps/web/src/hostedPairing.ts`.--Constraints:--- the hosted app does not proxy HTTP or WebSocket traffic;-- the backend must be directly reachable from the browser;-- HTTPS pages can only reach HTTPS/WSS backends;-- HTTP LAN endpoints keep using direct desktop or CLI pairing URLs;-- the token belongs in the hash so it is never sent to the hosted app origin.--### RepositoryIdentity and Project+| Target | Use |+| ------------------------- | ----------------------------------------------------------- |+| `PrimaryConnectionTarget` | The platform-managed local server. |+| `BearerConnectionTarget` | A saved server reached through direct HTTP and WebSocket. |+| `SshConnectionTarget` | A server started and forwarded by the desktop SSH launcher. |-`RepositoryIdentity` is a best-effort logical repo grouping across environments, used for UI grouping-and correlation only, never for routing. `Project` remains environment-local: a local clone and a-remote clone are different projects that may share a `RepositoryIdentity`, and threads bind to one-project in one environment.+Tailscale uses the bearer target. It supplies a reachable address but does not add another+connection type.-## Access methods+A saved target is local to one client. The server remains the source of projects, threads, settings,+and provider state.-Access answers one question: how does the client speak WebSocket to a T3 server? It does not answer-how the server got started or who manages the process.+## Pairing-### Direct WebSocket access+The server issues a short-lived pairing credential. A client exchanges it for a scoped bearer+session and saves the connection locally. The pairing credential is single-use for ordinary links.-`wss://t3.example.com` or `ws://10.0.0.15:3773`, paired as a bearer target. This is the base model.-It works for desktop, mobile, and web with no client-side process management. Browser security rules-are part of it: a hosted HTTPS client cannot connect to plain `ws://` or `http://` LAN backends.+A pairing URL contains the server address and keeps the credential in the URL fragment. The client+removes the credential from browser history after the exchange. The client then connects directly to+that server. No Akeru service proxies the session.-### Relay-tunneled access--Managed T3 Connect relay tunnels use `RelayConnectionTarget` and are the answer when the host is-behind NAT, inbound ports are unavailable, or mobile must reach a desktop-hosted environment. From-the client's perspective this is still an ordinary WebSocket connection; the route is mediated. The-relay Worker only brokers credentials and a managed endpoint; application traffic then flows over-the provisioned Cloudflare tunnel hostname for the life of the connection, not through the relay-Worker itself. See [t3-connect.md](./t3-connect.md).--### Tailscale access--A T3-managed `tailscale serve` mapping exposes the server on the tailnet over HTTPS, and the-resulting private-network endpoints are advertised for pairing. Connection then follows the ordinary-bearer path.+The server may advertise loopback, LAN, Tailscale, or custom HTTPS endpoints. Clients treat those+addresses as hints. A connection attempt is the final reachability check.-### Desktop-managed SSH access+## Direct and Tailscale access-SSH is an access and launch helper, not a separate environment type. `DesktopSshEnvironment`-([apps/desktop/src/ssh/DesktopSshEnvironment.ts][sshenv]) exposes `discoverHosts`,-`ensureEnvironment`, and `disconnectEnvironment`. It discovers targets from SSH config and known-hosts, owns password/askpass prompts, and delegates lifecycle to `SshEnvironmentManager` in-[packages/ssh/src/tunnel.ts][sshtunnel], which resolves the target, launches or reuses the remote T3-server, opens a local tunnel, checks HTTP readiness, optionally issues a remote pairing token, and-returns local HTTP/WS endpoints. Disconnect closes the tunnel and stops the remote server if the-launcher started it; a server that was already running (marked `external`) is left running.--The desktop main process owns this because it can spawn SSH, manage prompts, write launch scripts,-and clean up forwards. The renderer connects through the forwarded URL like any other environment and-needs no SSH-specific RPC path.--Failure handling is explicit: SSH auth failure surfaces before an environment is saved, remote launch-failure includes launcher output where available, forwarded-port failure leaves the environment-disconnected rather than falling back to an unrelated endpoint, and reconnect restores the SSH bridge-before reconnecting the WebSocket client.+Direct LAN and custom HTTPS addresses use the same bearer flow. HTTPS pages can connect only to+HTTPS and WSS servers because browsers block mixed content.-## Launch methods+Tailscale Serve can publish the local server through an HTTPS MagicDNS address. The server manages+that mapping when the user enables it. The resulting address still uses ordinary pairing and bearer+authorization.-Launch answers a different question: how does a T3 server come to exist on the target machine? Keep-it separate from access.+## Desktop SSH access-- **Pre-existing server.** The operator already runs T3 and the client connects directly or through a- tunnel.-- **Desktop-managed remote launch over SSH.** Desktop probes the machine, launches or reuses a remote- server, forwards a port, and the renderer connects normally. The saved environment records that it- came from SSH launch for reconnect and lifecycle UX only; that metadata never changes the protocol- or the identity model.-- **Client-managed local publish.** A local server is published through the relay with- `akeru connect link`, exposing a desktop-hosted environment to mobile without router or firewall- changes.+The desktop app can start or reuse Akeru Bot on an SSH host and open a local port forward. The+remote host owns all server state. The desktop stores an `SshConnectionTarget` and reconnects+through the forwarded endpoint.-The same `ExecutionEnvironment` can be reached several of these ways. Only the launch and access-paths differ.+SSH is a desktop capability because it requires local process and SSH access. Web and mobile can use+a directly reachable server after normal pairing.-## Security model+## Environment identity-Some environments are reachable over untrusted networks, so remote-capable environments require-explicit authentication, tunnel exposure never relies on obscurity, and saved endpoints carry enough-auth metadata to reconnect safely.+Each server stores a stable `environmentId` in its state directory. Clients use that identifier to+reject endpoints that point at a different server than the saved target.-WebSocket authentication is a dedicated short-lived ticket, not a token in a query string. The client-presents its long-lived bearer or DPoP credential in HTTP headers to-`POST /api/auth/websocket-ticket` ([authorization/remote.ts][authremote]), and appends only the-returned ticket as `wsTicket` on the socket URL. The server issues it through-`EnvironmentAuth.issueWebSocketTicket`; tickets are tagged `kind: "websocket"` and default to a-five-minute TTL (`DEFAULT_WEBSOCKET_TOKEN_TTL` in `apps/server/src/auth/SessionStore.ts`). The-handshake verifies the ticket, and each RPC method still enforces its own scope. See-[environment-auth.md](./environment-auth.md).+Repository identity may group related clones in the interface. It never changes routing. A project+always belongs to one environment.-Hosted pairing is a client-side convenience only. The hosted app must not receive pairing tokens-through query parameters, must not store pairing state server-side, and must not imply that an HTTP-backend is reachable from an HTTPS browser context.+## Connection ownership-## Version coordination+`packages/client-runtime` owns target resolution, retries, transport lifetime, cached projections,+and environment-scoped commands. Web and mobile provide platform storage and lifecycle signals.+React components do not create sockets or retry loops.-Remote environments stay online while clients move to newer releases. The environment descriptor-carries the running server version and may advertise a safe replacement path, so the UI can show the-right action without making the transport responsible for process management. The connection-supervisor owns the resulting disconnect and reconnect like any other involuntary close. See-[server-updates.md](./server-updates.md).--## Future work--These remain unbuilt and are listed to keep the model honest:--- third-party tunnel products as additional endpoint providers;-- a relay-hosted OAuth callback broker (see [t3-connect.md](./t3-connect.md));-- richer multi-environment UI beyond the current connections list.--[model]: ../../packages/client-runtime/src/connection/model.ts-[onboarding]: ../../packages/client-runtime/src/connection/onboarding.ts-[authremote]: ../../packages/client-runtime/src/authorization/remote.ts-[sshenv]: ../../apps/desktop/src/ssh/DesktopSshEnvironment.ts-[sshtunnel]: ../../packages/ssh/src/tunnel.ts+See [connection runtime](./connection-runtime.md) and+[environment authentication](./environment-auth.md) for the detailed contracts.diff --git a/docs/internals/t3-code-connect-auth-flow.html b/docs/internals/t3-code-connect-auth-flow.htmldeleted file mode 100644index 038132ee5..000000000--- a/docs/internals/t3-code-connect-auth-flow.html+++ /dev/null@@ -1,1160 +0,0 @@-<!doctype html>-<html lang="en">- <head>- <meta charset="utf-8" />- <meta name="viewport" content="width=device-width, initial-scale=1" />- <title>T3 Connect Architecture</title>- <style>- :root {- color-scheme: light;- --ink: #171717;- --muted: #62646b;- --hairline: #d8d8dd;- --panel: #ffffff;- --paper: #f5f5f2;- --blue: #1457d9;- --green: #1d7d4d;- --amber: #a65f00;- --red: #b8242c;- --violet: #6150b8;- --shadow: 0 18px 55px rgba(25, 25, 28, 0.08);- }-- * {- box-sizing: border-box;- }-- body {- margin: 0;- background:- linear-gradient(90deg, rgba(0, 0, 0, 0.035) 1px, transparent 1px),- linear-gradient(rgba(0, 0, 0, 0.035) 1px, transparent 1px), var(--paper);- background-size: 34px 34px;- color: var(--ink);- font-family:- ui-sans-serif,- -apple-system,- BlinkMacSystemFont,- "Segoe UI",- sans-serif;- line-height: 1.48;- }-- .shell {- width: min(1540px, calc(100vw - 40px));- margin: 0 auto;- padding: 38px 0 72px;- }-- header {- border-bottom: 2px solid var(--ink);- padding-bottom: 24px;- margin-bottom: 28px;- }-- .eyebrow {- color: var(--blue);- font-size: 12px;- font-weight: 800;- letter-spacing: 0.08em;- text-transform: uppercase;- }-- h1 {- max-width: 980px;- margin: 8px 0 12px;- font-size: clamp(34px, 5vw, 66px);- line-height: 0.98;- }-- h2 {- margin: 0 0 14px;- font-size: 26px;- line-height: 1.08;- }-- h3 {- margin: 22px 0 8px;- font-size: 17px;- }-- p {- margin: 0 0 12px;- }-- code,- .mono {- font-family:- ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace;- }-- code {- border-radius: 4px;- background: #f0f0ed;- padding: 1px 4px;- font-size: 0.92em;- }-- .lede {- max-width: 1000px;- margin: 0;- color: var(--muted);- font-size: 18px;- }-- .grid {- display: grid;- grid-template-columns: repeat(12, 1fr);- gap: 18px;- }-- .panel {- grid-column: span 12;- border: 1px solid var(--hairline);- border-radius: 10px;- background: var(--panel);- box-shadow: var(--shadow);- padding: 22px;- }-- .half {- grid-column: span 6;- }-- .callout {- border-left: 5px solid var(--blue);- background: #eef4ff;- padding: 14px 16px;- margin-top: 14px;- }-- .callout.warning {- border-left-color: var(--amber);- background: #fff6e6;- }-- .badge-row {- display: flex;- flex-wrap: wrap;- gap: 8px;- margin-top: 14px;- }-- .badge {- border: 1px solid var(--hairline);- border-radius: 999px;- background: #fff;- padding: 5px 9px;- font-size: 12px;- font-weight: 700;- }-- .badge.user {- border-color: rgba(20, 87, 217, 0.3);- color: var(--blue);- }-- .badge.env {- border-color: rgba(29, 125, 77, 0.3);- color: var(--green);- }-- .badge.local {- border-color: rgba(166, 95, 0, 0.35);- color: var(--amber);- }-- .diagram {- overflow-x: auto;- margin: 12px 0 0;- border: 1px solid var(--hairline);- border-radius: 8px;- background: #fbfbf8;- color: var(--ink);- padding: 18px;- }-- .diagram svg {- display: block;- width: auto !important;- min-width: 100%;- max-width: none !important;- height: auto;- margin: 0 auto;- }-- table {- width: 100%;- border-collapse: collapse;- font-size: 14px;- }-- th,- td {- border-bottom: 1px solid var(--hairline);- padding: 11px 9px;- text-align: left;- vertical-align: top;- }-- th {- color: var(--muted);- font-size: 12px;- letter-spacing: 0.05em;- text-transform: uppercase;- }-- ul {- margin: 8px 0 0;- padding-left: 20px;- }-- li + li {- margin-top: 6px;- }-- .flow {- display: grid;- gap: 10px;- margin-top: 12px;- }-- .step {- border: 1px solid var(--hairline);- border-left: 5px solid var(--green);- border-radius: 8px;- background: #fff;- padding: 12px 14px;- }-- .step strong {- display: block;- margin-bottom: 3px;- }-- .source-list a {- color: var(--blue);- font-weight: 700;- }-- @media (max-width: 860px) {- .half {- grid-column: span 12;- }-- .shell {- width: min(100vw - 24px, 1540px);- padding-top: 24px;- }- }- </style>- </head>- <body>- <main class="shell">- <header>- <div class="eyebrow">Implemented architecture</div>- <h1>T3 Connect Control Plane and Managed Endpoint Flow</h1>- <p class="lede">- T3 Connect links a locally authorized T3 environment to a signed-in cloud user, provisions- a managed HTTPS/WSS endpoint for that environment, and brokers proof-bound remote- connections. The local environment remains the authority that issues environment access- credentials. The hosted relay stores links, reconciles managed endpoint resources,- validates signed proofs, and delivers agent-activity notifications.- </p>- <div class="badge-row">- <span class="badge user">Client -> Relay: Clerk bearer or relay DPoP</span>- <span class="badge env">Relay -> Environment: relay-signed health and mint proofs</span>- <span class="badge env"- >Environment -> Relay: environment bearer plus signed activity proof</span- >- <span class="badge local">Client -> Environment: environment access token plus DPoP</span>- </div>- </header>-- <section class="grid" aria-label="Architecture summary">- <article class="panel half">- <h2>Security Invariant</h2>- <p>- A cloud identity is not an environment login. Remote access requires all of the- following:- </p>- <ul>- <li>a Clerk-authenticated T3 Connect user;</li>- <li>an active relay link for that user and environment;</li>- <li>a DPoP proof key held by the remote client;</li>- <li>a relay-signed mint request accepted by the linked local environment; and</li>- <li>an environment-issued credential bound to the remote client's DPoP thumbprint.</li>- </ul>- <div class="callout">- The relay cannot mint an environment access token by itself. It can only ask the local- environment to mint a short-lived bootstrap credential for an authorized cloud user.- </div>- <p>During an honest connection flow, the relay cannot act as the remote client:</p>- <ul>- <li>- Normal environment API traffic goes directly from the remote client through the- managed endpoint. The relay does not receive the resulting environment access token.- </li>- <li>- The one-time bootstrap credential and resulting environment access token are bound to- the remote client's DPoP public-key thumbprint. Redeeming or using them requires- request proofs signed by the corresponding private key, which stays on the client.- </li>- <li>- Relay-signed health and mint proofs are short-lived, audience-bound, scoped, and- replay-guarded. They are accepted only by the narrow cloud endpoints, not as normal- environment API credentials.- </li>- <li>- Environment health and mint responses are signed by the linked environment and bound- to the request nonce, so a different process behind the tunnel cannot impersonate the- linked environment.- </li>- </ul>- <div class="callout warning">- The hosted relay remains a trusted mint broker: it holds the cloud-mint signing key.- DPoP prevents credential reuse by the relay or tunnel transport during an honest flow,- but it does not make compromise of the relay signing authority harmless.- </div>- </article>-- <article class="panel half">- <h2>Product Boundaries</h2>- <p>- The generic local connector is called the <strong>relay client</strong>. The current- implementation layer uses <code>cloudflared</code>, but that is an internal transport- detail rather than the product contract.- </p>- <ul>- <li>- The relay Worker owns cloud links, managed endpoint allocations, and notifications.- </li>- <li>- The environment server owns local sessions, environment keys, and access tokens.- </li>- <li>The relay client exposes only the environment's loopback HTTP server.</li>- <li>- Web and mobile clients connect directly to the managed environment endpoint after- bootstrap.- </li>- </ul>- </article>- </section>-- <section class="panel" aria-label="Topology">- <h2>Current Topology</h2>- <pre class="diagram mermaid">-flowchart LR- subgraph Clients["User-facing clients"]- Web["Desktop / hosted web UI"]- Mobile["Mobile app"]- CLI["Headless CLI"]- end-- Clerk["Clerk<br/>user identity and OAuth"]-- subgraph Relay["T3 Code Relay on Cloudflare"]- Worker["Relay Worker<br/>HTTP API"]- Queue["APNs delivery queue<br/>with dead-letter queue"]- Hyperdrive["Hyperdrive"]- CF["Cloudflare tunnel + DNS APIs"]- end-- DB["PlanetScale Postgres<br/>prod database + stage branches"]- APNs["Apple Push Notification service"]- Traces["Axiom OTLP traces"]-- subgraph Local["Linked T3 environment"]- Env["Environment server<br/>local auth authority"]- RelayClient["Relay client<br/>cloudflared implementation"]- Secrets["Server secret store<br/>keys + relay config"]- end-- Endpoint["Managed HTTPS/WSS endpoint"]-- Web -->|"Clerk bearer / relay DPoP"| Worker- Mobile -->|"Clerk bearer / relay DPoP"| Worker- CLI -->|"Clerk OAuth bearer"| Worker- Web --> Clerk- Mobile --> Clerk- CLI -->|"PKCE authorization code flow"| Clerk- Worker --> Hyperdrive --> DB- Worker --> Traces- Worker --> CF- Worker --> Queue --> APNs- Worker --> Endpoint- Endpoint --> RelayClient -->|"http://127.0.0.1:port"| Env- Env --> Secrets- Web -->|"environment token + DPoP<br/>HTTPS / WSS"| Endpoint- Mobile -->|"environment token + DPoP<br/>HTTPS / WSS"| Endpoint- Env -->|"environment bearer + signed activity proof"| Worker- </pre>- </section>-- <section class="panel" aria-label="Authentication matrix">- <h2>Authentication and Transport Matrix</h2>- <table>- <thead>- <tr>- <th>Boundary</th>- <th>Transport</th>- <th>Authentication</th>- <th>Purpose</th>- </tr>- </thead>- <tbody>- <tr>- <td>Web or mobile -> relay link management</td>- <td>HTTPS</td>- <td>Clerk session-template bearer token</td>- <td>Create a link challenge, submit an environment proof, list links, or unlink.</td>- </tr>- <tr>- <td>CLI -> relay link management</td>- <td>HTTPS</td>- <td>Clerk OAuth access token obtained with PKCE</td>- <td>Reconcile the desired headless cloud link when the server starts.</td>- </tr>- <tr>- <td>Web or mobile -> relay protected client endpoints</td>- <td>HTTPS</td>- <td>Relay-issued DPoP token plus per-request DPoP proof</td>- <td>- Check environment status, request a remote connection, and register mobile devices.- </td>- </tr>- <tr>- <td>Relay -> managed environment endpoint</td>- <td>HTTPS over the managed tunnel</td>- <td>Short-lived relay-signed JWT request proof</td>- <td>- Request a signed health response or ask the local environment to mint a credential.- </td>- </tr>- <tr>- <td>Environment -> relay activity publication</td>- <td>HTTPS</td>- <td>Relay-issued environment bearer credential plus environment-signed JWT proof</td>- <td>- Publish redacted agent-activity state for push notifications and Live Activities.- </td>- </tr>- <tr>- <td>Remote client -> environment</td>- <td>HTTPS and WSS over the managed tunnel</td>- <td>Environment-issued access token bound to the client DPoP key</td>- <td>Use the normal environment HTTP APIs and request a one-time WebSocket ticket.</td>- </tr>- </tbody>- </table>- </section>-- <section class="panel" aria-label="Credential ownership">- <h2>Credential Ownership</h2>- <table>- <thead>- <tr>- <th>Credential</th>- <th>Created by</th>- <th>Stored by</th>- <th>Use</th>- </tr>- </thead>- <tbody>- <tr>- <td>Clerk session-template JWT</td>- <td>Clerk</td>- <td>Web or mobile client</td>- <td>- Authenticate cloud-user relay requests and bootstrap relay DPoP token exchange.- </td>- </tr>- <tr>- <td>CLI OAuth access and refresh token</td>- <td>Clerk OAuth</td>- <td>Local server secret store</td>- <td>Authorize headless CLI link reconciliation.</td>- </tr>- <tr>- <td>Environment Ed25519 key pair</td>- <td>Local environment server</td>- <td>Local server secret store</td>- <td>- Sign link proofs, health responses, mint responses, and activity publication proofs.- </td>- </tr>- <tr>- <td>Relay cloud-mint key pair</td>- <td>Relay deployment</td>- <td>Private key in relay Worker config; public key installed into the environment</td>- <td>Sign relay-to-environment health and mint requests.</td>- </tr>- <tr>- <td>Relay environment bearer credential</td>- <td>Relay</td>- <td>Hashed in relay Postgres; plaintext in local server secret store</td>- <td>Authenticate environment-to-relay agent-activity publication.</td>- </tr>- <tr>- <td>Relay DPoP access token</td>- <td>Relay</td>- <td>Remote client memory cache</td>- <td>- Authorize status, connect, and mobile registration endpoints with proof of- possession.- </td>- </tr>- <tr>- <td>Environment bootstrap credential</td>- <td>Local environment server</td>- <td>Passed relay -> remote client</td>- <td>One-time exchange at the environment <code>/oauth/token</code> endpoint.</td>- </tr>- <tr>- <td>Environment access token</td>- <td>Local environment server</td>- <td>Remote client</td>- <td>Authorize environment HTTP operations and WebSocket ticket issuance.</td>- </tr>- <tr>- <td>WebSocket ticket</td>- <td>Local environment server</td>- <td>Remote client until consumed</td>- <td>Short-lived one-time credential for the WSS upgrade.</td>- </tr>- <tr>- <td>Relay client connector token</td>- <td>Cloudflare tunnel API</td>- <td>Local server secret store</td>- <td>- Start the local relay client. It is passed through <code>TUNNEL_TOKEN</code>, not a- shell argument.- </td>- </tr>- </tbody>- </table>- </section>-- <section class="grid" aria-label="Core flows">- <article class="panel">- <h2>Flow 1: Link From the Desktop Web UI</h2>- <pre class="diagram mermaid">-sequenceDiagram- participant U as Signed-in user- participant C as Desktop web UI- participant E as Local environment- participant R as Relay Worker- participant CF as Cloudflare APIs- participant RC as Local relay client-- U->>C: Enable T3 Connect for a locally paired environment- C->>E: Check relay client availability- alt relay client is missing- C->>U: Prompt before download and install- U->>C: Confirm- C->>E: Stream relay-client install RPC- E-->>C: Progress stages- end- C->>R: POST /v1/client/environment-link-challenges (Clerk bearer)- R-->>C: Short-lived challenge- C->>E: POST /api/connect/link-proof (local relay:write bearer)- E->>E: Authenticate, reject forwarded authority, get or create key pair, validate loopback origin- E-->>C: Environment-signed link proof- C->>R: POST /v1/client/environment-links (Clerk bearer + proof)- R->>R: Verify challenge, proof, capabilities, nonce, and loopback origin- R->>CF: Reconcile tunnel, ingress, and CNAME- R->>R: Upsert user/environment link and issue environment bearer- R-->>C: Managed endpoint, relay config, and connector token- C->>E: POST /api/connect/relay-config (local relay:write bearer)- E->>RC: Start relay client with TUNNEL_TOKEN- </pre>- <div class="callout">- The local link-proof endpoint requires <code>relay:write</code>, rejects forwarded- authority headers, and accepts only an exact loopback origin. Environment keypair- persistence is atomic across concurrent link attempts.- </div>- <p>- A locally paired mobile client uses the same relay challenge, local proof, relay link,- and local relay-config endpoints. The desktop web UI is the surface that checks relay- client availability and offers the managed install dialog.- </p>- </article>-- <article class="panel">- <h2>Flow 2: Headless CLI Link</h2>- <pre class="diagram mermaid">-sequenceDiagram- participant U as Operator- participant CLI as t3 connect CLI- participant Clerk as Clerk OAuth- participant S as Environment server on next start- participant R as Relay Worker- participant RC as Local relay client-- U->>CLI: t3 connect link- CLI->>CLI: Resolve relay client- alt relay client is missing- CLI->>U: Confirm managed relay-client install- U->>CLI: Confirm- CLI->>CLI: Install with terminal progress updates- end- CLI->>Clerk: Browser PKCE authorization-code flow- Clerk-->>CLI: OAuth access and refresh tokens- CLI->>CLI: Persist desired cloud-link state- U->>S: Start T3 environment server- S->>R: Create challenge and submit local signed proof- R-->>S: Managed endpoint config and connector token- S->>RC: Start relay client- </pre>- <p>- <code>t3 connect login</code> stores authorization without enabling exposure.- <code>t3 connect unlink</code> disables exposure while retaining authorization.- <code>t3 connect logout</code> also removes the stored CLI authorization.- </p>- </article>-- <article class="panel">- <h2>Flow 3: Remote Connect Bootstrap</h2>- <pre class="diagram mermaid">-sequenceDiagram- participant C as Web or mobile client- participant Clerk as Clerk- participant R as Relay Worker- participant E as Managed environment endpoint-- C->>Clerk: Get Clerk session-template JWT- C->>R: POST /v1/client/dpop-token (Clerk JWT + DPoP proof)- R-->>C: Relay DPoP access token- C->>R: POST /v1/environments/:id/connect (relay DPoP)- R->>E: POST /api/t3-connect/mint-credential (relay-signed proof)- E->>E: Verify relay signer, linked user, scope, lifetime, cnf, and replay guards- E-->>R: Bootstrap credential + environment-signed proof- R->>R: Verify environment signature, nonce, endpoint, and DPoP binding- R-->>C: Managed endpoint + bootstrap credential- C->>E: POST /oauth/token (bootstrap credential + DPoP proof)- E-->>C: Environment DPoP-bound access token- C->>E: POST /api/auth/websocket-ticket- E-->>C: One-time WebSocket ticket- C->>E: WSS /ws with ticket- </pre>- <div class="callout">- Relay-to-environment control requests disable redirects, use only a reconciled managed- endpoint allocation, and require a signed environment response before the relay returns- data to the client.- </div>- </article>-- <article class="panel">- <h2>Flow 4: Agent Activity Notifications</h2>- <pre class="diagram mermaid">-sequenceDiagram- participant E as Local environment- participant R as Relay Worker- participant DB as Relay Postgres- participant Q as APNs queue- participant APNs as Apple Push Notification service- participant M as Mobile app-- E->>E: Project publishable thread state and redact failure detail- E->>R: POST /v1/environments/:environmentId/threads/:threadId/agent-activity- Note over E,R: Environment bearer credential + environment-signed per-state proof- R->>R: Verify credential, signature, scope, expiry, and nonce- R->>DB: Store current activity row- R->>Q: Enqueue push or Live Activity delivery jobs- Q->>APNs: Deliver signed APNs request- APNs-->>M: Push notification or Live Activity update- </pre>- <p>- The local server publishes a deliberately narrow projection. Failed runs use a fixed- redacted summary, and detail strings are capped before publication.- </p>- </article>- </section>-- <section class="grid" aria-label="Managed endpoint lifecycle">- <article class="panel half">- <h2>Managed Endpoint Reconciliation</h2>- <p>- Managed endpoint resources are keyed by <code>(userId, environmentId)</code>. The relay- reserves a stable hostname and tunnel name before provisioning, then checkpoints the- tunnel ID, DNS record ID, and ready state in Postgres.- </p>- <div class="flow">- <div class="step">- <strong>1. Reserve deterministic allocation</strong>- Hostname and tunnel name derive from relay stage, cloud user, and environment ID.- </div>- <div class="step">- <strong>2. Reuse or create tunnel</strong>- Existing named tunnels are reused. Tunnel ingress is rewritten to the validated- loopback origin.- </div>- <div class="step">- <strong>3. Reconcile DNS</strong>- Existing CNAMEs are updated and duplicate records are removed. Create conflicts are- recovered by listing and reconciling the winning record.- </div>- <div class="step">- <strong>4. Mark ready</strong>- Connect and status requests use only ready allocations whose hostname still matches- the relay-managed namespace.- </div>- </div>- </article>-- <article class="panel half">- <h2>Unlink Cleanup</h2>- <p>- Relay unlink removes the user's managed endpoint allocation before revoking the- user/environment link:- </p>- <ul>- <li>delete the managed DNS record if present;</li>- <li>delete the Cloudflare tunnel if present;</li>- <li>remove the allocation row;</li>- <li>revoke the user's environment link; and</li>- <li>- revoke the environment publication credential only after the final active link for- that environment key disappears.- </li>- </ul>- <p>- Local unlink stops the relay client and removes the locally persisted relay URL, issuer,- linked user, environment publication credential, cloud-mint public key, connector- config, and agent-activity preference.- </p>- </article>- </section>-- <section class="panel" aria-label="Cloudflare tunnel operational profile">- <h2>Cloudflare Tunnel Operational Profile</h2>- <p>- Managed tunnels are private application backends, not general-purpose public hosting. The- relay provisions one named Cloudflare tunnel and one DNS record per active- <code>(userId, environmentId)</code> allocation.- </p>- <ul>- <li>- <strong>Lifecycle:</strong> the tunnel is created when an environment is linked, reused- across retry-safe reconciliation, kept for the lifetime of that link, and deleted on- unlink. If teardown fails, the allocation checkpoint remains so cleanup can be retried.- </li>- <li>- <strong>Origin:</strong> tunnel ingress is restricted to the linked environment server's- validated loopback HTTP origin. Arbitrary upstream hosts and raw TCP origins are- rejected.- </li>- <li>- <strong>Protocols:</strong> managed endpoints carry HTTPS request/response traffic and- WSS connections only. Remote clients use the normal environment HTTP APIs and- authenticated WebSocket RPC transport through the tunnel.- </li>- <li>- <strong>Relay-generated traffic:</strong> the hosted relay sends sparse HTTPS health- checks and credential-mint requests during status checks and remote connection- bootstrap. It does not proxy steady-state remote sessions.- </li>- <li>- <strong>Traffic shape:</strong> expected load is interactive and user-driven. Active- remote sessions may keep WebSockets open and exchange terminal, agent, and UI updates;- inactive linked environments should carry little or no tunnel traffic.- </li>- <li>- <strong>Capacity planning:</strong> the project is pre-launch, so there is not yet a- production bandwidth baseline. Tunnel count grows with active linked user/environment- allocations, while bandwidth and concurrent WebSockets grow with active remote use.- </li>- </ul>- </section>-- <section class="panel" aria-label="SSRF and tunnel hardening">- <h2>SSRF and Tunnel Hardening</h2>- <table>- <thead>- <tr>- <th>Risk</th>- <th>Implemented control</th>- </tr>- </thead>- <tbody>- <tr>- <td>A client asks the relay to tunnel an arbitrary host.</td>- <td>- The environment and relay both accept managed tunnel origins only for loopback hosts- and valid ports.- </td>- </tr>- <tr>- <td>A forwarded request tricks local origin validation.</td>- <td>- The local link-proof handler requires an exact loopback request URL and rejects- forwarded host or protocol headers.- </td>- </tr>- <tr>- <td>A stored endpoint is replaced with an arbitrary external URL.</td>- <td>- Connect and status resolve a ready allocation from Postgres and require a hostname- under the configured managed endpoint zone.- </td>- </tr>- <tr>- <td>A managed endpoint redirects relay egress elsewhere.</td>- <td>- Relay-to-environment status and mint requests set redirect handling to- <code>manual</code>.- </td>- </tr>- <tr>- <td>A process behind the tunnel returns attacker-controlled data.</td>- <td>- The relay verifies environment-signed health and mint responses against the linked- environment public key, expected nonce, and request binding.- </td>- </tr>- <tr>- <td>A stolen remote access token is replayed.</td>- <td>- Relay and environment access tokens are DPoP-bound; per-request proofs and replay- guards are required.- </td>- </tr>- <tr>- <td>The relay client token leaks through process listings or shell parsing.</td>- <td>- The relay client is spawned without a shell and receives its connector token in- <code>TUNNEL_TOKEN</code>.- </td>- </tr>- </tbody>- </table>- <div class="callout warning">- Managed tunnel hostnames live under the configured tunnel DNS zone. Serving them from a- dedicated registrable domain with a Public Suffix List entry remains an operational- isolation requirement before broad untrusted use.- </div>- </section>-- <section class="panel" aria-label="Relay HTTP API">- <h2>Relay HTTP API</h2>- <p>- The relay publishes an OpenAPI document at <code>/openapi.json</code>, interactive API- docs at <code>/docs</code>, and redirects <code>/</code> to the docs.- </p>- <table>- <thead>- <tr>- <th>Endpoint</th>- <th>Authentication</th>- <th>Purpose</th>- </tr>- </thead>- <tbody>- <tr>- <td><code>GET /health</code></td>- <td>None</td>- <td>Relay health check.</td>- </tr>- <tr>- <td><code>GET /.well-known/oauth-authorization-server</code></td>- <td>None</td>- <td>Relay OAuth token-exchange discovery metadata.</td>- </tr>- <tr>- <td><code>GET /.well-known/oauth-protected-resource</code></td>- <td>None</td>- <td>Relay DPoP protected-resource discovery metadata.</td>- </tr>- <tr>- <td><code>GET /v1/environments</code></td>- <td>Clerk bearer</td>- <td>List environments linked to the signed-in user.</td>- </tr>- <tr>- <td><code>POST /v1/client/environment-link-challenges</code></td>- <td>Clerk bearer</td>- <td>Create a short-lived user-bound environment link challenge.</td>- </tr>- <tr>- <td><code>POST /v1/client/environment-links</code></td>- <td>Clerk bearer</td>- <td>- Verify a local environment proof, reconcile a managed endpoint, and upsert the user- link.- </td>- </tr>- <tr>- <td><code>DELETE /v1/client/environment-links/:environmentId</code></td>- <td>Clerk bearer</td>- <td>Remove managed endpoint resources and revoke the user's link.</td>- </tr>- <tr>- <td><code>POST /v1/client/dpop-token</code></td>- <td>Clerk token in token-exchange payload plus DPoP proof</td>- <td>Issue a relay DPoP access token for the requested supported scopes.</td>- </tr>- <tr>- <td><code>POST /v1/environments/:environmentId/status</code></td>- <td>Relay DPoP</td>- <td>Request and validate a signed environment health response.</td>- </tr>- <tr>- <td><code>POST /v1/environments/:environmentId/connect</code></td>- <td>Relay DPoP</td>- <td>Request and validate an environment bootstrap credential.</td>- </tr>- <tr>- <td><code>POST /v1/mobile/devices</code></td>- <td>Relay DPoP</td>- <td>Register or update a mobile device for notifications.</td>- </tr>- <tr>- <td><code>POST /v1/mobile/live-activities</code></td>- <td>Relay DPoP</td>- <td>Register a Live Activity push token.</td>- </tr>- <tr>- <td><code>DELETE /v1/mobile/devices/:deviceId</code></td>- <td>Relay DPoP</td>- <td>Unregister a mobile device.</td>- </tr>- <tr>- <td>- <code>POST /v1/environments/:environmentId/threads/:threadId/agent-activity</code>- </td>- <td>Environment bearer plus signed publish proof</td>- <td>Publish redacted current agent activity for notification delivery.</td>- </tr>- </tbody>- </table>- </section>-- <section class="panel" aria-label="Environment HTTP API">- <h2>Environment Cloud HTTP API</h2>- <table>- <thead>- <tr>- <th>Endpoint</th>- <th>Authentication</th>- <th>Purpose</th>- </tr>- </thead>- <tbody>- <tr>- <td><code>POST /api/connect/link-proof</code></td>- <td>Local environment token with <code>relay:write</code></td>- <td>Validate local origin and sign an environment link proof.</td>- </tr>- <tr>- <td><code>POST /api/connect/relay-config</code></td>- <td>Local environment token with <code>relay:write</code></td>- <td>Persist linked relay configuration and start the relay client.</td>- </tr>- <tr>- <td><code>GET /api/connect/link-state</code></td>- <td>Local environment token with <code>relay:read</code></td>- <td>Read the environment's current T3 Connect link state.</td>- </tr>- <tr>- <td><code>POST /api/connect/preferences</code></td>- <td>Local environment token with <code>relay:write</code></td>- <td>Enable or disable agent-activity publication.</td>- </tr>- <tr>- <td><code>POST /api/connect/unlink</code></td>- <td>Local environment token with <code>relay:write</code></td>- <td>Stop the relay client and clear local T3 Connect configuration.</td>- </tr>- <tr>- <td><code>POST /api/t3-connect/health</code></td>- <td>Relay-signed proof</td>- <td>Return a signed environment health response.</td>- </tr>- <tr>- <td><code>POST /api/t3-connect/mint-credential</code></td>- <td>Relay-signed proof</td>- <td>Mint a DPoP-bound one-time bootstrap credential for a remote client.</td>- </tr>- <tr>- <td><code>POST /oauth/token</code></td>- <td>Bootstrap credential plus DPoP proof</td>- <td>Exchange a bootstrap credential for an environment access token.</td>- </tr>- <tr>- <td><code>POST /api/auth/websocket-ticket</code></td>- <td>Environment access token</td>- <td>Issue a one-time ticket for the WSS upgrade.</td>- </tr>- </tbody>- </table>- </section>-- <section class="grid" aria-label="Runtime and infrastructure">- <article class="panel half">- <h2>Relay Client Installation</h2>- <p>- Desktop web UI availability checks and installs are local WebSocket RPC methods:- <code>cloud.getRelayClientStatus</code> and streaming- <code>cloud.installRelayClient</code>. The install stream emits the current stage:- checking, waiting for lock, downloading, verifying, installing, validating, and- activating.- </p>- <p>- The web UI asks for confirmation before installation and displays a custom progress- dialog. The CLI invokes the same local relay-client service directly and reports the- same progress stages in the terminal.- </p>- </article>-- <article class="panel half">- <h2>Relay Infrastructure</h2>- <ul>- <li>Cloudflare Worker for the hosted relay HTTP API.</li>- <li>PlanetScale Postgres database named <code>t3coderelay</code>.</li>- <li>- Production uses the shared database; non-production stages use database branches.- </li>- <li>- Cloudflare Hyperdrive with caching disabled and a constrained origin connection limit.- </li>- <li>Cloudflare tunnel and DNS bindings for managed endpoint reconciliation.</li>- <li>Cloudflare APNs delivery queue plus dead-letter queue.</li>- <li>A five-minute cron job that prunes expired DPoP replay rows.</li>- <li>Axiom OTLP trace dataset, scoped ingest token, and recent-spans view per stage.</li>- </ul>- </article>- </section>-- <section class="panel" aria-label="Deployment configuration">- <h2>Deployment Configuration</h2>- <table>- <thead>- <tr>- <th>Boundary</th>- <th>Configuration</th>- </tr>- </thead>- <tbody>- <tr>- <td>Relay infrastructure</td>- <td>- <code>RELAY_API_ZONE_NAME</code>, <code>RELAY_TUNNEL_ZONE_NAME</code>, optional- <code>RELAY_DOMAIN</code>, <code>CLERK_PUBLISHABLE_KEY</code>,- <code>CLERK_SECRET_KEY</code>, <code>CLERK_JWT_AUDIENCE</code>, and APNs- credentials.- </td>- </tr>- <tr>- <td>Source-built desktop/server cloud features</td>- <td>- Optional <code>T3CODE_RELAY_URL</code>, <code>T3CODE_CLERK_PUBLISHABLE_KEY</code>,- and <code>T3CODE_CLERK_CLI_OAUTH_CLIENT_ID</code>. Release builds inject public- values at build time.- </td>- </tr>- <tr>- <td>Web and mobile cloud clients</td>- <td>- Public Clerk publishable key, Clerk JWT template name, and relay URL. Relay URLs- must normalize to an absolute HTTPS origin without credentials, query, fragment, or- non-root path.- </td>- </tr>- </tbody>- </table>- </section>-- <section class="panel" aria-label="Implementation checklist">- <h2>Implementation Checklist</h2>- <ul>- <li>- Keep the relay cloud-mint private key hosted-only; install only its public key into- environments.- </li>- <li>- Keep environment signing private keys local and persist keypair creation atomically.- </li>- <li>- Require a local <code>relay:write</code> session before linking or changing relay- config.- </li>- <li>Validate relay URLs as secure absolute HTTPS origins before sending credentials.</li>- <li>Require loopback-only tunnel origins on both sides of the link-proof boundary.</li>- <li>- Resolve managed endpoint egress from ready allocation rows, not client-supplied URLs.- </li>- <li>Disable redirects on relay-to-environment requests.</li>- <li>Validate environment-signed response proofs before consuming tunneled responses.</li>- <li>Keep tunnel and DNS provisioning retry-safe and deprovision them on unlink.</li>- <li>- Revoke shared environment publication credentials only after the final active link- disappears.- </li>- <li>Redact and cap local agent failure details before publishing them externally.</li>- </ul>- </section>-- <section class="panel" aria-label="Standards references">- <h2>Standards References</h2>- <ul class="source-list">- <li>- <a href="https://www.rfc-editor.org/rfc/rfc8252">RFC 8252</a>: browser-based OAuth for- native apps, used by the CLI PKCE authorization flow.- </li>- <li>- <a href="https://www.rfc-editor.org/rfc/rfc8693">RFC 8693</a>: OAuth token exchange,- used for Clerk-token to relay-DPoP-token exchange.- </li>- <li>- <a href="https://www.rfc-editor.org/rfc/rfc9449">RFC 9449</a>: DPoP proof of possession,- used for relay and environment access tokens.- </li>- </ul>- </section>- </main>- <script type="module">- import mermaid from "https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs";-- mermaid.initialize({- startOnLoad: false,- securityLevel: "strict",- theme: "base",- themeVariables: {- fontFamily: 'ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',- primaryColor: "#eef4ff",- primaryBorderColor: "#1457d9",- primaryTextColor: "#171717",- lineColor: "#62646b",- signalColor: "#171717",- signalTextColor: "#171717",- noteBkgColor: "#fff6e6",- noteTextColor: "#171717",- actorBkg: "#fbfbf8",- actorBorder: "#62646b",- actorTextColor: "#171717",- },- flowchart: {- htmlLabels: true,- curve: "basis",- padding: 18,- },- sequence: {- showSequenceNumbers: true,- mirrorActors: false,- rightAngles: false,- },- });-- await mermaid.run({ querySelector: ".diagram.mermaid" });-- for (const svg of document.querySelectorAll(".diagram.mermaid svg")) {- const viewBox = svg.getAttribute("viewBox");- const width = viewBox?.split(/\s+/).map(Number)[2];- if (Number.isFinite(width) && width > 0) {- svg.style.setProperty("width", `${Math.ceil(width)}px`, "important");- svg.style.setProperty("max-width", "none", "important");- }- }- </script>- </body>-</html>diff --git a/docs/internals/t3-connect.md b/docs/internals/t3-connect.mddeleted file mode 100644index 9c60a3e24..000000000--- a/docs/internals/t3-connect.md+++ /dev/null@@ -1,273 +0,0 @@-# T3 Connect--> For maintainers. Using T3 Code? See [docs/user](../user/).--T3 Connect uses one Clerk application for web, desktop, and mobile authentication. The relay verifies-two kinds of bearer credential: template JWTs generated from the `t3-relay` template with the shared-`t3-code-relay` audience, and Clerk OAuth tokens issued to the CLI. `verifyRelayClientBearerToken` in-`infra/relay/src/http/Api.ts` tries the template/session path first and falls back to OAuth-verification (`acceptsToken: "oauth_token"`), so the CLI's OAuth credential works without a JWT-template.--For the wider system diagram, see-[t3-code-connect-auth-flow.html](./t3-code-connect-auth-flow.html).--## Application Keys--T3 Connect is disabled in a fresh clone. To enable it for source builds against the production-deployment, copy the repository-root example file:--```sh-cp .env.example .env-```--`.env.example` carries the production public identifiers (the same values baked into official-release builds). To target a different Clerk application or relay, set the values yourself in a-repository-root `.env` or `.env.local` file:--```dotenv-T3CODE_CLERK_PUBLISHABLE_KEY=<publishable key>-T3CODE_CLERK_JWT_TEMPLATE=<JWT template name>-T3CODE_CLERK_CLI_OAUTH_CLIENT_ID=<public OAuth application client ID>-T3CODE_RELAY_URL=https://relay.example.com-```--The shared client loader projects these canonical values into framework-specific `VITE_*` and-`EXPO_PUBLIC_*` aliases. Existing aliases remain accepted as overrides for compatibility, but new-client configuration should use the canonical names.--Configuration precedence is:--1. Process or CI environment variables.-2. Repository-root `.env.local`.-3. Repository-root `.env`.--The Clerk publishable key, JWT template name, CLI OAuth client ID, and relay URL are public-identifiers, not secrets.-Web, desktop, mobile, and bundled server builds statically inject the values they consume during-their build step. A built artifact does not need an environment file at runtime. CI release builds-should set `T3CODE_CLERK_PUBLISHABLE_KEY`, `T3CODE_CLERK_JWT_TEMPLATE`,-`T3CODE_CLERK_CLI_OAUTH_CLIENT_ID`, and `T3CODE_RELAY_URL` before building. EAS preview and-production builds only need the Clerk publishable key, JWT template name, and relay URL in their EAS-environment.--When any client-facing public value is absent, cloud UI is omitted. The `akeru connect` command group is-always registered: when the CLI public values are absent, `makeCli` in `apps/server/src/bin.ts`-registers a hidden fallback `connect` command that reports the missing configuration instead of-silently vanishing from help. The bundled server still accepts runtime overrides for self-hosted or-operator-managed deployments.--For a hosted relay deployment, copy `infra/relay/.env.example` to `infra/relay/.env`. The relay-deployment reads `RELAY_DOMAIN`, `RELAY_API_ZONE_NAME`, `RELAY_TUNNEL_ZONE_NAME`,-`CLERK_PUBLISHABLE_KEY`, and `CLERK_JWT_AUDIENCE` through Effect `Config`. There are no checked-in-deployment defaults.-`vp run --filter t3code-relay deploy` invokes Alchemy from the relay directory, so Alchemy loads-`infra/relay/.env`. After a successful deployment, the wrapper updates the repository-root `.env`-with the deployed HTTPS relay URL. The relay still requires-`CLERK_SECRET_KEY` as an Alchemy secret. Never put `CLERK_SECRET_KEY` in a client application-environment or commit it to the repository.--The `prod` Alchemy stage owns the retained PlanetScale database. Non-production stages reference-that database and provision isolated PlanetScale branches, so deploy `prod` before creating a-personal developer stage.--## Headless CLI OAuth Application--The `akeru connect` commands authorize a headless environment with a separate Clerk OAuth application.-This uses an OAuth public client with PKCE, so the CLI stores no client secret.--In **Clerk Dashboard > OAuth applications**:--1. Create an OAuth application for the T3 CLI.-2. Enable the **Public** option so authorization-code exchange uses PKCE.-3. Add **both** allowed redirect URIs:- - `http://127.0.0.1:34338/callback` for the loopback listener;- - `https://app.t3.codes/connect/callback` for the hosted out-of-band flow. This is- `connectCallbackUrl(DEFAULT_HOSTED_APP_URL)` from `packages/shared/src/connectAuth.ts`, so a- custom `T3CODE_HOSTED_APP_URL` means `$T3CODE_HOSTED_APP_URL/connect/callback` instead.- Omitting it breaks headless and SSH authorization.-4. Enable the `openid`, `profile`, and `email` scopes.-5. Set `T3CODE_CLERK_CLI_OAUTH_CLIENT_ID` in the repository-root `.env` file and release build- environment to the generated public client ID.--Both CLI flows start at the hosted `/connect` page (`buildConnectAuthorizeRequestUrl` in-`packages/shared/src/connectAuth.ts`), which waits for a Clerk session and then forwards the request-to Clerk's `/oauth/authorize`. The CLI never opens `/oauth/authorize` directly: a signed-out browser-sent there goes through Clerk's sign-in redirect, which drops the authorize query parameters and-fails the flow with `unsupported_response_type` or an empty `state` (#5051). The loopback flow marks-the request with a `port` fragment parameter so the hosted page asks Clerk to redirect the-authorization code straight to `http://127.0.0.1:<port>/callback`; the out-of-band flow omits it and-uses the hosted `/connect/callback` page instead. The CLI derives Clerk's frontend API URL from the-publishable key and calls only the `/oauth/token` endpoint directly. The relay is not involved in-the OAuth handshake; it only validates the issued Clerk bearer token when the CLI manages an-environment link.--The connect command group is:--```sh-t3 connect # default: onboarding-t3 connect login-t3 connect link # --publish-only-t3 connect status # --json-t3 connect publish # --disable-t3 connect unlink-t3 connect logout-```--`akeru serve` is a separate top-level command, not a connect subcommand.--`akeru connect login` opens the Clerk authorization flow and stores the CLI credential without enabling-cloud exposure. `akeru connect link` installs the pinned managed `cloudflared` binary when needed,-authorizes when needed, and records durable intent to expose the environment. It works without a-running T3 server. The next `akeru serve` or `akeru start` reconciles the relay link and launches the-managed tunnel. `akeru connect unlink` records disabled intent immediately, stops a reachable running-connector, and attempts to revoke the relay-side environment record. It retains the stored CLI-authorization so `akeru connect link` can re-enable exposure without another browser flow. `akeru connect-logout` performs the same cleanup and removes the stored CLI authorization.--The background service has an independent lifecycle. Connect setup may offer to install it, but-logout leaves it running; manage it with `akeru service status`, `install`, `update`, and `uninstall`.--### Headless and SSH authorization--The loopback OAuth callback listener binds to port `34338`. That path only works when a browser on-the same machine can reach it, so `authorizeCli` in `apps/server/src/cli/connect.ts` automatically-selects the out-of-band flow when `--headless` is passed or when it detects SSH through-`SSH_CONNECTION` or `SSH_TTY`. The out-of-band flow prints the hosted `/connect` authorization URL-and accepts a pasted authorization code, so no port is involved.--Port forwarding is therefore optional, not required. Forward the port only if you specifically want-the loopback flow over SSH:--```sh-ssh -L 34338:127.0.0.1:34338 <host>-```--## JWT Template--In **Clerk Dashboard > JWT templates**, create a template with:--| Setting | Value |-| ------- | ---------------------------- |-| Name | `t3-relay` |-| Claims | `{ "aud": "t3-code-relay" }` |--Set `T3CODE_CLERK_JWT_TEMPLATE=t3-relay` in the repository-root `.env`, and set-`CLERK_JWT_AUDIENCE=t3-code-relay` in `infra/relay/.env`. Define `CLERK_JWT_TEMPLATE` and-`CLERK_JWT_AUDIENCE` in the production relay deployment environment as well. The stable `aud` value-is shared by production and non-production relay stages. The client-facing `T3CODE_RELAY_URL` still-selects the concrete relay deployment, but changing that URL does not require a JWT template change.--## Desktop OAuth Redirect Allowlist--The desktop app opens OAuth in the system browser and returns to the app with a custom URL scheme.-In **Clerk Dashboard > Native applications**, enable the Native API and add these entries under the-mobile SSO redirect allowlist:--```text-t3code-dev://app/-t3code://app/-```--Local desktop development uses `t3code-dev://app`, while packaged builds use `t3code://app`. Add the-matching origin to each Clerk instance's Backend API `allowed_origins` array as well. The development-Clerk instance should only need `t3code-dev://app`; the production Clerk instance should only need-`t3code://app`. `@clerk/electron` owns the native request adapter, encrypted Clerk token persistence,-external-browser OAuth transport, and callback delivery for initial sign-in and linked-account flows.--There is currently no Dashboard UI for `allowed_origins`. Preserve any existing entries and update-the instance through the Backend API:--```sh-curl -X PATCH https://api.clerk.com/v1/instance \- -H "Content-Type: application/json" \- -H "Authorization: Bearer $CLERK_SECRET_KEY" \- -d '{"allowed_origins":["t3code://app"]}'-```--Never put `CLERK_SECRET_KEY` in the desktop app, a client-facing environment file, or a build-artifact.--## Desktop Passkeys--The production macOS bundle ID is `com.t3tools.t3code`. To enable native passkeys:--1. Create an explicit macOS App ID for `com.t3tools.t3code` in the Apple Developer portal and enable- **Associated Domains**.-2. Create a compatible macOS provisioning profile for that App ID and the certificate used to sign- the distributed app.-3. In Clerk's Native API settings, add an iOS app with the same Apple Team ID and bundle ID. This is- also the configuration point for Electron/macOS passkeys.-4. Confirm Clerk serves `https://<frontend-api>/.well-known/apple-app-site-association` and that- `webcredentials.apps` contains `<TEAM_ID>.com.t3tools.t3code`.-5. Set the local or CI signing configuration described below.--For a local signed build, add these values to `.env.local` or export them before invoking the-desktop artifact command:--```dotenv-T3CODE_APPLE_TEAM_ID=ABC1234567-T3CODE_MACOS_PROVISIONING_PROFILE=/absolute/path/to/t3code.provisionprofile-# Optional: comma-separated override when Clerk's RP ID differs from the Frontend API hostname.-T3CODE_CLERK_PASSKEY_RP_DOMAINS=example.clerk.accounts.dev,clerk.example.com-```--When `T3CODE_CLERK_PASSKEY_RP_DOMAINS` is absent, the build derives the RP domain from-`T3CODE_CLERK_PUBLISHABLE_KEY`. Signed macOS builds fail early if the Team ID, provisioning profile,-or RP-domain configuration is missing. The generated main-app entitlements include every configured-`webcredentials:<domain>` entry; helper apps keep Electron's minimal default entitlements.--The normal `dev:desktop` launcher is unsigned and cannot complete macOS passkey ceremonies. For-renderer HMR, build and install a signed app first, run the renderer dev server, then launch the-installed app executable with `VITE_DEV_SERVER_URL` and `T3CODE_PORT` set. Rebuild the signed app-after native dependency, main-process, preload, entitlement, provisioning, or signing changes;-renderer-only changes can reuse the installed app.--For the default development ports, run `pnpm dev:web` in one terminal and launch the installed-binary from another:--```sh-VITE_DEV_SERVER_URL=http://127.0.0.1:5733 \-T3CODE_PORT=13773 \- "/Applications/T3 Code (Alpha).app/Contents/MacOS/T3 Code (Alpha)"-```--After changing Associated Domains, bump the build version before rebuilding; macOS may otherwise-reuse stale Shared Web Credentials metadata for the same app/version pair.--Verify the installed bundle before testing:--```sh-codesign --verify --deep --strict "/Applications/T3 Code (Alpha).app"-codesign -d --entitlements :- "/Applications/T3 Code (Alpha).app"-```--The current mobile UI uses Clerk's native authentication view. If a future mobile browser OAuth-flow uses a custom redirect URI, add that exact URI to the same allowlist.--## Sign-in Surfaces--Signed-in users manage T3 Connect under **Connections**. The settings sidebar also has dedicated-controls, rendered by `SettingsSidebarNav.tsx`: `T3ConnectSidebarSignIn` in the footer shows a-**Sign in to T3 Connect** button while signed out, and `T3ConnectSidebarAvatar` shows a Clerk-`UserButton` account control while signed in. Both are gated on cloud public configuration.-Desktop renders the same web bundle, so it has them too. The waitlist enrollment flow from the-private beta was removed when Connect went GA; sign-up is open unless a Clerk restriction below is-enabled.--## Restricting Sign-ups: Known-User Allowlist--For a closed deployment where all permitted users are known in advance, restrict sign-up to-permitted email addresses or domains:--1. In **Clerk Dashboard > Restrictions > Allowlist**, add each permitted email address or email- domain.-2. Enable the allowlist and save.-3. Alternatively, enable **Restricted mode** when all new users must be explicitly invited or- manually created.--Do not enable an empty allowlist: it blocks all new sign-ups.--Clerk allowlists control who can sign up. They do not revoke an existing user's active cloud-access. To remove an already-created user's access, ban that user in Clerk so their active-sessions are ended and future sign-ins are rejected.diff --git a/docs/internals/workspace-layout.md b/docs/internals/workspace-layout.mdindex e933e4528..3b7cba223 100644--- a/docs/internals/workspace-layout.md+++ b/docs/internals/workspace-layout.md@@ -1,6 +1,6 @@# Workspace layout-> For maintainers. Using T3 Code? See [docs/user](../user/).+> For maintainers. Using Akeru Bot? See [docs/user](../user/).A pnpm workspace driven by [vite-plus](https://vite.plus) (`vp`). See [scripts.md](./scripts.md) forthe task commands.@@ -23,8 +23,7 @@ the task commands.- `packages/contracts` (`@t3tools/contracts`): shared Effect Schema definitions. RPC group,orchestration commands/events/read model, auth scopes, environment descriptors, settings.- `packages/shared` (`@t3tools/shared`): framework-agnostic utilities used by server and clients- (`DrainableWorker`, git and source-control helpers, relay auth and signing, DPoP, semver, logging,- observability, and more).+ (`DrainableWorker`, git and source-control helpers, semver, logging, observability, and more).- `packages/client-runtime` (`@t3tools/client-runtime`): connection lifecycle, authorization, RPCsession, environment registry, and Atom-based domain state shared by web and mobile. See its[README](../../packages/client-runtime/README.md).@@ -37,13 +36,6 @@ the task commands.- `packages/effect-codex-app-server` (`effect-codex-app-server`): Effect client for the`codex app-server` JSON-RPC protocol.-## infra--- `infra/relay` (`t3code-relay`): the hosted T3 Connect relay, deployed with Alchemy. Handles- environment discovery, cloud-side records, and mobile notifications. It is not in the hot path;- after connect, client traffic goes directly to the environment. See- [t3-connect.md](./t3-connect.md).-## Other top-level directories- `scripts/`: workspace tooling run through `vp run`. Dev runner, desktop artifact builds, release@@ -59,5 +51,4 @@ the task commands.`@t3tools/shared` and `@t3tools/client-runtime` use explicit subpath exports with no barrel index andno root export. Import the narrow path (`@t3tools/shared/DrainableWorker`,`@t3tools/client-runtime/state/threads`) rather than the package root. Files that are not exported-are implementation details. `@t3tools/contracts` does export a root alongside `./settings` and-`./relay`.+are implementation details. `@t3tools/contracts` exports a root alongside `./settings`.diff --git a/docs/operations/mobile-app-store-screenshots.md b/docs/operations/mobile-app-store-screenshots.mdindex 820addbbe..56ad34958 100644--- a/docs/operations/mobile-app-store-screenshots.md+++ b/docs/operations/mobile-app-store-screenshots.md@@ -1,6 +1,6 @@# Mobile app-store screenshot harness-> For maintainers. Using T3 Code? See [docs/user](../user/).+> For maintainers. Using Akeru Bot? See [docs/user](../user/).The screenshot harness runs the real mobile application against three disposable local T3environments. It creates an isolated base directory and server for each environment, real Git@@ -9,9 +9,8 @@ history. The app pairs with every server through its normal connection flow andopens the production Home, Thread, ThreadTerminal, ThreadReview, and SettingsEnvironments routes.No screenshot-specific screen recreates application UI. `EXPO_PUBLIC_SHOWCASE=1` only enables the-non-rendering pairing/readiness coordinator, disables terminal autofocus so captures do not contain-the software keyboard, and supplies deterministic T3 Connect discovery rows to the real-Environments screen. The local environment cards always come from real paired servers.+non-rendering pairing and readiness coordinator and disables terminal autofocus so captures do not+contain the software keyboard. The local environment cards always come from real paired servers.## Capture the default matrixdiff --git a/docs/operations/relay-observability.md b/docs/operations/relay-observability.mddeleted file mode 100644index 2bc697b2e..000000000--- a/docs/operations/relay-observability.md+++ /dev/null@@ -1,53 +0,0 @@-# Relay observability--> For maintainers. Using T3 Code? See [docs/user](../user/).--The relay Alchemy stack owns a shared Axiom trace setup:--- `t3-code-relay-traces-prod`, the OpenTelemetry trace dataset shared by the Worker, mobile app, and- first-party relay clients-- `t3-code-relay-otel-ingest-prod`, the dataset-scoped Worker ingest token-- `t3-code-mobile-otel-ingest-prod`, the dataset-scoped mobile ingest token-- `t3-code-relay-client-otel-ingest-prod`, the dataset-scoped first-party relay-client ingest token-- `t3-code-relay-recent-spans-prod`, a view of recent request and endpoint spans--Alchemy stages append their sanitized stage name to isolate resources, for example-`t3-code-relay-traces-dev-julius` for a personal stage.--Deploy from `infra/relay` with the normal Alchemy workflow:--```sh-vp run deploy-```--Alchemy resolves account-level Axiom deployment credentials through its provider. At runtime, the-Worker receives only its scoped ingest token. Mobile and relay clients use their own separately-provisioned scoped ingest tokens.--The Worker emits Effect's built-in HTTP server spans plus endpoint and database child spans.-Effect's OpenTelemetry exporter stores semantic HTTP attributes below the `attributes.` prefix.-For example:--```apl-['t3-code-relay-traces-prod']-| where name startswith 'http.server'-| extend endpoint = column_ifexists('attributes.http.route', ''),- customAttributes = column_ifexists('attributes.custom', dynamic({}))-| project _time, name, trace_id, duration,- ['attributes.http.request.method'],- ['attributes.url.path'],- ['attributes.http.response.status_code'],- endpoint,- relayOperation = customAttributes['relay']['operation']-| order by _time desc-| limit 200-```--The provisioned view also reads the endpoint from `attributes.http.route`. Relay-specific span-annotations are stored under `attributes.custom`; `relay.operation` is one of the emitted custom-attributes.--Agents should prefer the provisioned view or APL queries for completed incidents instead of-tailing the Cloudflare Worker. The stack does not provision a separate query token. Responders who-need scripted query access use the authorized account-level `AXIOM_TOKEN` together with-`AXIOM_ORG_ID`; scoped ingest tokens remain write-only credentials for their producers.diff --git a/docs/operations/release.md b/docs/operations/release.mdindex 8898da181..3f4fcd61b 100644--- a/docs/operations/release.md+++ b/docs/operations/release.md@@ -1,5 +1,8 @@# Release smoke runbook+> Do not publish a signed Akeru Bot build until qualified legal counsel approves the current Terms+> of Use and Privacy Policy versions in `packages/contracts/src/settings.ts`.+> For Akeru Bot maintainers.`.depot/workflows/release.yml` validates release inputs without publishing or releasing anything.@@ -13,8 +16,7 @@ Dispatch it from Depot with a version such as `0.0.0-smoke.0`.- macOS builds one arm64 DMG with the `dev.leodoes.akeru` bundle identifier.- The macOS app uses a Developer ID Application certificate. Electron-builder submits and staplesthe app before it packages the DMG. The workflow submits and staples the DMG separately.-- Signed apps always include the Electron hardened-runtime and microphone entitlements. Associated- Domains entitlements are added only when a Clerk passkey configuration is present.+- Signed apps always include the Electron hardened-runtime and microphone entitlements.- The workflow staples and validates the notarization tickets, then runs `codesign` and `spctl`.- Windows builds one unsigned x64 NSIS installer.- Linux builds one unsigned x64 AppImage.@@ -22,8 +24,8 @@ Dispatch it from Depot with a version such as `0.0.0-smoke.0`.- The marketing site passes its type check and production build.Each desktop job uploads its artifact to the workflow run for seven days. The workflow does not-create tags, create GitHub releases, publish npm packages, deploy the relay, deploy a site, update-AUR, or send release announcements.+create tags, create GitHub releases, publish npm packages, deploy a site, update AUR, or send+release announcements.## Depot setupdiff --git a/docs/user/background-service.md b/docs/user/background-service.mdindex 22190c616..09d690ba7 100644--- a/docs/user/background-service.md+++ b/docs/user/background-service.md@@ -1,11 +1,11 @@-# Running T3 Code in the Background+# Running Akeru Bot in the background-On Linux and macOS, T3 Code can run as a background service for your user, so it is ready without+On Linux and macOS, Akeru Bot can run as a background service for your user, so it is ready withoutkeeping a terminal open.-## Manage the Service+## Manage the service-Install it with the latest T3 Code release:+Install it with the latest Akeru Bot release:```shnpx akeru-bot@latest service install@@ -29,16 +29,16 @@ Stop it and remove it from startup:npx akeru-bot@latest service uninstall```-Updating restarts T3 Code briefly. Let active agent work and terminal commands finish first.+Updating restarts Akeru Bot briefly. Let active agent work and terminal commands finish first.If a remote update is already in progress, wait for it to finish before retrying a local update.-The service runs a small stable launcher. Exact T3 Code versions are installed separately, so a+The service runs a small stable launcher. Exact Akeru Bot versions are installed separately, so afailed remote candidate can return to the previous version without rewriting the servicedefinition. The launcher snapshots the database before a remote candidate starts, so databaseupdates roll back with the server version. An older launcher may require one local`service update` before this is available.-## Platform Support+## Platform support**Linux** uses a systemd user unit at `~/.config/systemd/user/t3code.service`. The service startswhen the machine boots and keeps running after you log out (lingering is enabled during install).@@ -63,11 +63,3 @@ A few more macOS notes:on.**Windows** is not supported yet.--## Using It with T3 Connect--T3 Connect may offer to install the service during setup so the host stays reachable in the-background. This is only an onboarding shortcut: the service and T3 Connect are managed separately.--Signing out of T3 Connect does not remove the service. Use `akeru service uninstall` when you no longer-want T3 Code to start in the background.diff --git a/docs/user/bots.md b/docs/user/bots.mdindex 8bacaa3cc..493d84d81 100644--- a/docs/user/bots.md+++ b/docs/user/bots.md@@ -6,12 +6,15 @@ Open a bot to edit its profile in the panel beside the conversation.- Set the bot name.- Add an optional label and description.- Choose the model that the bot uses.+- Set an optional **Token hard stop**. Akeru Bot interrupts the current step at the limit.- Turn on **Voice calls** to show the phone button in that bot's chat header.- Open **Tools** to choose which installed plugins and MCP servers the bot can use. New tools are enabled for every bot by default.- Select **Save** to apply profile, model, voice, and tool changes.Akeru Bot stores the profile in the connected environment. Other clients connected to the same environment see the same bot configuration. Workspace-disabled tools stay unavailable to all bots.+Each settled bot reply shows its engine, step tokens, and estimated USD cost when the provider reports enough usage data.+Settings controls whether bots share their workspace and browser. **Separate** is the default and gives each bot its own workspace identity and browser profile. **Shared** lets bots share files and cookies. Bots can use Local, E2B, Daytona, Vercel Sandbox, or Upstash Box workspaces. Remote workspaces use the provider credentials available to the environment and fail if those credentials are missing.Local bots ask before file changes and shell commands by default. Select **Settings > General > Local execution > Full access** to skip those local prompts. Actions that send, pay, delete, change production, or use secrets still ask. Bots that run in a cloud sandbox do not show the local computer prompt.diff --git a/docs/user/privacy.md b/docs/user/privacy.mdnew file mode 100644index 000000000..dd7066991--- /dev/null+++ b/docs/user/privacy.md@@ -0,0 +1,26 @@+# Privacy and outbound data++Akeru Bot stores threads, settings, secrets, and logs on your device under `~/.akeru`. It does not+require a hosted Akeru account.++Some features send data to services outside your device:++- Provider runs send prompts, selected files, tool results, screenshots, computer frames, and+ conversation context to the provider CLI or service you choose. The provider controls its own+ processing and retention.+- Product feedback goes to `feedback.akeru.bot`. The service may keep submissions for up to 90+ days.+- Voice calls send microphone audio and session data to the ChatGPT Realtime service while a call+ is active.+- Provider update checks contact the release sources for your configured providers. Signed desktop+ builds contact the configured release host for Akeru Bot updates.+- Anonymous analytics use PostHog only when you turn analytics on and the distributor configures a+ PostHog key. Events include the app version, platform, architecture, client type, feature use,+ and a random installation identifier. They do not use a provider account identifier.++Open Settings, then Privacy, to control analytics, product feedback, voice calls, and provider+update checks. Analytics starts off. Mobile shows the same controls in the Privacy section for the+connected environment.++The published Terms of Use and Privacy Policy pages are drafts. Akeru Bot must not ship a signed+release until qualified legal counsel approves them.diff --git a/docs/user/product-feedback.md b/docs/user/product-feedback.mdindex db335136c..32d4c5a09 100644--- a/docs/user/product-feedback.md+++ b/docs/user/product-feedback.md@@ -11,6 +11,6 @@ A submission contains:It does not contain screenshots, raw DOM, input values, credentials, tool results, a thread, or a full conversation. No account is required. A failed send keeps the draft. A confirmed send clears it.-Akeru Bot keeps accepted feedback for 90 days. Turn off **Product feedback** in **Settings → About** to disable sending. Self-hosted environments can set an HTTPS endpoint there. Loopback HTTP endpoints are allowed for local testing.+Akeru Bot keeps accepted feedback for 90 days. Turn off **Product feedback** in **Settings → Privacy** to disable sending. Self-hosted environments can set an HTTPS endpoint in **Settings → About**. Loopback HTTP endpoints are allowed for local testing.Codex-backed Akeru bots can propose feedback text. A proposal can only add bounded text to the same editable draft after one-time approval. The bot cannot send it. You must select **Send** for each submission. Review agent proposals on web or desktop. Mobile can cancel them but cannot open the draft in this version.diff --git a/docs/user/remote-access.md b/docs/user/remote-access.mdindex ee3ef2804..b9b091fc7 100644--- a/docs/user/remote-access.md+++ b/docs/user/remote-access.md@@ -1,238 +1,112 @@-# Remote Access+# Remote access-Use this when you want to connect to a T3 Code server from another device such as a phone, tablet, or separate desktop app.+Use remote access to connect a phone, tablet, browser, or desktop app to an Akeru Bot server that you+control.-## Quick Pairing for a Running Server+## Pair with a running server-If a server is already running on this machine, mint a fresh pairing token and QR code without restarting anything:+Run this on the server machine:```bashnpx akeru-bot pair```-`akeru pair` finds the running server (the shared `~/.t3` install, or the current worktree's dev server when run inside one), issues a one-time pairing token, and prints the pairing URL as a QR code you can scan from your phone.+The command finds the running server, creates a one-time pairing credential, and prints a URL and QR+code. The other device must be able to reach the address in that URL.-If the server is only bound to loopback, the printed URL is not reachable from another device. Pair over your tailnet instead:+For Tailscale HTTPS, run:```bashnpx akeru-bot pair --tailscale```-This publishes the server over Tailscale Serve HTTPS (configuring the mapping if needed — it persists until you run `tailscale serve --https=443 off`) and pairs through the `https://machine.tailnet.ts.net/` URL. Use `--tailscale-serve-port` for a different HTTPS port, `--ttl` to change the token lifetime, and `--base-dir` to target a specific data directory.+This configures Tailscale Serve when needed and prints a pairing URL for the machine's HTTPS+MagicDNS address.-If no server is running, `akeru pair` says so and points you at `npx akeru-bot serve` or `npx akeru-bot connect`.+Treat a pairing URL like a password. The credential expires and ordinary pairing links work once.-## Recommended Setup+## Desktop network access-Use a trusted private network that meshes your devices together, such as a tailnet.+1. Open **Settings** and select **Connections**.+2. Enable **Network access** under **This environment**.+3. Select a reachable LAN, Tailscale, or custom HTTPS endpoint.+4. Select **Create Link**.+5. Open the link on the other device.-That gives you:+A loopback address works only on the same machine. A LAN address requires both devices to reach the+same network. A browser loaded over HTTPS can connect only to an HTTPS and WSS server.-- a stable address to connect to-- transport security at the network layer-- less exposure than opening the server to the public internet+The client connects directly to the address in the link. Akeru Bot does not proxy the connection+through a hosted service.-## Enabling Network Access+## Headless server-There are three ways to reach your server from another device: expose the desktop app's backend,-run a headless server from the CLI, or have the desktop app launch T3 Code over SSH.--### Option 1: Desktop App--If you are already running the desktop app and want to make it reachable from other devices:--1. Open **Settings** → **Connections**.-2. Under **This environment**, toggle **Network access** on. This will restart the app and run the backend on all network interfaces.-3. The settings panel will show the default reachable endpoint, with a `+N` control when more endpoints are available. Expand it to inspect alternatives such as loopback, LAN, private-network, or HTTPS endpoints.-4. Use **Create Link** to generate a pairing link you can share with another device.--The default endpoint controls the QR code and primary copy action for pairing links. You can change it from the expanded endpoint list. The preference is stored by endpoint type, so choosing the local LAN endpoint survives normal IP address changes when you move between networks.--When no user default is saved, the app uses the built-in LAN endpoint for pairing links when-available. You can set another endpoint as the default from the expanded endpoint list.--- HTTPS/WSS-compatible endpoints work from `https://app.t3.codes`, but are not made the default- automatically.-- Non-loopback HTTP endpoints are useful for direct LAN pairing.-- Loopback-only endpoints are not useful for another device unless that device is the same machine.--If the copied link points directly at `http://192.168.x.y:3773`, open it from a client that can reach that LAN address. If it points at `https://app.t3.codes/pair?...`, the hosted web app will save the environment and connect directly to the backend URL in the link.--In the mobile app's **Add Environment** form, a numeric IP address without a scheme uses HTTP. Include `https://` explicitly when the backend is served over HTTPS.--### Tailscale Endpoints--When the desktop app can detect Tailscale, it adds Tailnet endpoints to the reachable endpoint list.--Depending on your Tailscale setup, this may include:--- the machine's `100.x.y.z` Tailnet IP-- a MagicDNS name-- an HTTPS MagicDNS endpoint when Tailscale Serve is configured for this backend--The Tailscale HTTPS endpoint uses the clean MagicDNS URL, such as-`https://machine.tailnet.ts.net/`, and is off until you opt in. Turn on **Enable Tailscale HTTPS**-on the **Tailscale HTTPS** row in **Settings** → **Connections**. The desktop app restarts the-backend with the same server-side behavior as `akeru serve --tailscale-serve`, then the server asks-Tailscale Serve to proxy HTTPS traffic to the local backend. Turn the same switch off to stop it.--The Tailscale support is an endpoint provider add-on. The core remote model still works without Tailscale: LAN HTTP endpoints, custom HTTPS endpoints, future tunnels, and SSH-launched environments all use the same saved environment and pairing flow.--For `https://app.t3.codes`, prefer an HTTPS Tailnet or other HTTPS endpoint. A plain `http://100.x.y.z:3773` endpoint can still work from a desktop client or another browser page served over HTTP, but it will not work from the hosted HTTPS app because of browser mixed-content rules.--### Option 2: Headless Server (CLI)--Use this when you want to run the server without a GUI, for example on a remote machine over SSH.--Run the server with `akeru serve`.+Run a server without the desktop app:```bashnpx akeru-bot serve --host "$(tailscale ip -4)"```-`akeru serve` starts the server without opening a browser and prints:--- a connection string-- a pairing token-- a pairing URL-- a QR code for the pairing URL--From there, connect from another device in either of these ways:--- scan the QR code on your phone-- in the desktop app, enter the full pairing URL-- in the desktop app, enter the host and token separately-- in the hosted web app, open a hosted pairing URL when the backend is reachable over HTTPS+The command prints the server address, pairing credential, URL, and QR code.-Use `akeru serve --help` for the full flag reference. It supports the same general startup options as the normal server command, including an optional `cwd` argument.--For hosted web pairing over Tailscale HTTPS, opt in to Tailscale Serve:+To let Akeru Bot configure Tailscale Serve, run:```bashnpx akeru-bot serve --tailscale-serve```-By default this configures Tailscale Serve on HTTPS port 443 and advertises-`https://machine.tailnet.ts.net/`. Advanced users can choose a different HTTPS port:--```bash-npx akeru-bot serve --tailscale-serve --tailscale-serve-port 8443-```--Once paired, add projects normally: open the Command Palette and choose **Add Project**, then pick-the environment the project lives on. Every saved environment is offered, not only the local one.--### Option 3: Desktop-Managed SSH Launch+Use `--tailscale-serve-port` to choose another HTTPS port. Use `akeru serve --help` for the full+flag list.-Use this when you want the desktop app to start or reuse T3 Code on another machine over SSH.+## Desktop-managed SSH-1. Open **Settings** → **Connections**.-2. Under **Remote Environments**, choose **Add environment**.-3. Select the SSH launch flow.-4. Enter the SSH target, such as `[email protected]`.-5. Confirm the launch. The desktop app probes the host, starts or reuses a remote T3 server, opens a local port forward, and saves the environment.+The desktop app can start or reuse a server on an SSH host.-After setup, the renderer connects to a local forwarded HTTP/WebSocket endpoint. The remote host still owns the actual T3 server, projects, files, git state, terminals, and provider sessions.+1. Open **Settings** and select **Connections**.+2. Select **Add environment**.+3. Select the SSH flow.+4. Enter a target such as `[email protected]`.+5. Confirm the launch.-SSH launch is a desktop feature because it needs local process and SSH access. Once the environment is paired and saved, it uses the same environment list and connection model as direct LAN, Tailscale, HTTPS, or future tunnel-backed environments.+The desktop app starts the remote server and opens a local port forward. The remote machine owns its+projects, threads, files, terminals, git state, and provider sessions.-#### SSH Launch Troubleshooting--The desktop SSH launcher connects with a non-interactive `sh` session, writes a small launcher script under `~/.t3/ssh-launch/<host-key>/`, starts or reuses a remote T3 server, and forwards the remote loopback port back to your desktop.--The remote host must have a compatible Node.js runtime. T3 Code uses the server package's `engines.node` requirement:+The SSH launcher requires a compatible Node.js version on the remote host:```text^22.16 || ^23.11 || >=24.10```-During SSH launch, T3 Code first checks whether `node` is on `PATH`. If it is missing, the launcher-looks in the usual install directories and tries to activate a version manager if it finds one-(Volta, asdf, mise, fnm, nodenv, nvm). That covers most setups, but a version manager that only-initializes from an interactive shell profile will not be picked up.--If launch fails with `node: command not found`, a port-scan failure, or a message that the remote Node version does not satisfy the required range, SSH into the host and check the same non-interactive shell path T3 Code uses:+Check the non-interactive shell if launch fails:```bashssh [email protected] 'sh -lc "command -v node && node --version"'```-If that does not print a compatible Node version, configure your version manager for non-interactive shells or install a compatible Node binary in one of the searched locations. For example, with nvm you may need a default alias:--```bash-nvm alias default 24-```--With mise, asdf, fnm, or nodenv, make sure the tool's shim directory is installed and resolves to a Node version satisfying the range above without an interactive shell.--If reconnecting after an app update fails, retry the SSH launch once. The launcher now compares its generated runner script, stops stale launcher-managed remote servers, clears the SSH launch PID/port state, and starts a fresh remote server. You should not normally need to delete `~/.t3/ssh-launch` or kill `t3` processes manually.--## Updating a Remote Server--When the T3 Code web or desktop app and a remote server use different versions, a warning appears in-the conversation and in **Settings** → **Connections**. Follow the action shown there: T3 Code may-be able to update and reconnect the server for you, or it may ask you to update the desktop app or-run a copied command on the server machine.--Finish active work before updating because the server restarts briefly. For step-by-step guidance,-see [Keeping T3 Code in Sync](./updating.md).--On a Linux host, you can keep the server running after logout and manage it independently of the-connection method. See [Running T3 Code in the Background](./background-service.md).--## How Pairing Works--The remote device does not need a long-lived secret up front.+Configure the remote version manager so that command prints a compatible Node.js version.-Instead:+## Saved environments-1. `akeru serve` issues a one-time owner pairing token.-2. The remote device exchanges that token with the server.-3. The server creates an authenticated session for that device.+After pairing, the client stores a bearer credential for that environment. It reconnects without+reusing the original pairing URL.-After pairing, future access is session-based. You do not need to keep reusing the original token unless you are pairing a new device.+Use `akeru auth` to inspect sessions, create another pairing link, or revoke access:-## Hosted Web App Pairing--The hosted web app at `https://app.t3.codes` can save a remote backend in browser local storage from a URL like:--```text-https://app.t3.codes/pair?host=https://backend.example.com:3773#token=PAIRCODE+```bash+npx akeru-bot auth --help```-Use hosted pairing when the backend is reachable from the browser over HTTPS/WSS. This includes a backend behind a trusted HTTPS tunnel or another HTTPS endpoint you operate.--Do not use hosted pairing for plain HTTP LAN URLs such as `http://192.168.x.y:3773`. Browsers block an HTTPS page from connecting to an insecure HTTP or WS backend. For those endpoints, use the direct pairing URL shown by the desktop app or CLI from a client that can open that HTTP URL directly.--Hosted pairing does not proxy traffic through T3 Code. The browser still connects directly to the backend URL in the pairing link.--## Managing Access Later--Use `akeru auth` to manage access after the initial pairing flow.--Typical uses:--- issue additional pairing credentials-- inspect active sessions-- revoke old pairing links or sessions--Use `akeru auth --help` and the nested subcommand help pages for the full reference.--### Deregister a T3 Connect Environment--Open your account menu and choose **T3 Connect** to see every environment registered to your-account. On mobile, open **Settings** → **T3 Connect**. Choose **Deregister** to revoke an-environment's T3 Connect access, remove any managed tunnel, and free its host space.+Remove a saved environment from **Connections** on web or desktop, or **Environments** on mobile.+This removes the local saved connection. Revoke the server session when the device should no longer+have access.-Deregistration is an account action and does not need a connection to the environment, so it also-works for a server that was wiped or is no longer reachable. Device-local connect and disconnect-controls remain in **Settings** → **Connections** on web and desktop or **Settings** →-**Environments** on mobile.+## Security notes-## Security Notes+- Prefer a private network such as Tailscale.+- Do not expose an HTTP server directly to the public internet.+- Use HTTPS and WSS across untrusted networks.+- Revoke links or sessions that you no longer trust.+- Finish active work before updating a remote server because the server restarts.-- Treat pairing URLs and pairing tokens like passwords.-- Prefer binding `--host` to a trusted private address, such as a Tailnet IP, instead of exposing the server broadly.-- Anyone with a valid pairing credential can create a session until that credential expires or is revoked.-- Hosted pairing links keep the credential in the URL hash so it is not sent to the hosted app server, but it can still be exposed through browser history, screenshots, logs, or copy/paste.-- Use `akeru auth` to revoke credentials or sessions you no longer trust.+See [background service](./background-service.md) for a Linux server that must remain available+after logout.diff --git a/infra/relay/.env.example b/infra/relay/.env.exampledeleted file mode 100644index 7ab2a5d6e..000000000--- a/infra/relay/.env.example+++ /dev/null@@ -1,26 +0,0 @@-# Required: Relay API and managed tunnel domains-# Production adopts retained DNS zones in your Cloudflare account. The API-# zone serves relay.<zone> in production and relay-<stage>.<zone> for personal-# stages. Managed environment endpoints are provisioned below the tunnel zone.-RELAY_API_ZONE_NAME=example.com-RELAY_TUNNEL_ZONE_NAME=tunnels.example.com--# Optional: Relay domain override-# Set this only when the derived relay hostname should not be used.-# RELAY_DOMAIN=relay.example.com--# Required: Clerk-# Get the keys from the Clerk Dashboard under API keys. Set the JWT audience to-# the `aud` claim configured on the `t3-relay` JWT template.-CLERK_PUBLISHABLE_KEY=pk_test_...-CLERK_SECRET_KEY=sk_test_...-CLERK_JWT_AUDIENCE=t3-code-relay--# Required: Apple Push Notification service-# Get these values from your Apple Developer account. Use `sandbox` for-# development APNs credentials and `production` for production credentials.-APNS_ENVIRONMENT=sandbox-APNS_TEAM_ID=...-APNS_KEY_ID=...-APNS_BUNDLE_ID=...-APNS_PRIVATE_KEY=...diff --git a/infra/relay/README.md b/infra/relay/README.mddeleted file mode 100644index 0085c9c5b..000000000--- a/infra/relay/README.md+++ /dev/null@@ -1,166 +0,0 @@-# T3 Connect Relay--> [!NOTE]-> Sign in to T3 Connect from the app under Settings > Connections.--The relay is the hosted control plane for T3 Connect. It helps clients discover and connect to-remote environments, manages the cloud-side records needed for those connections, and delivers-optional mobile notifications and Live Activities.--The relay is intentionally not in the hot path for normal T3 Code traffic. After a client connects,-regular API and WebSocket traffic goes directly between that client and the selected environment.-See the [T3 Connect architecture overview](../../docs/internals/t3-code-connect-auth-flow.html) for the larger system-design.--## Responsibilities--The relay currently owns:--- Linking T3 Code environments to a cloud account.-- Provisioning and tracking managed environment endpoints.-- Issuing short-lived credentials used to connect clients to linked environments.-- Listing linked environments and registered mobile devices for an account.-- Registering mobile notification preferences and APNs tokens.-- Receiving published agent activity and delivering notifications or Live Activity updates.-- Persisting relay state and exposing relay-specific traces for diagnostics.--The environment server and relay have separate credentials and trust boundaries. Read-[Environment Authentication Profile](../../docs/internals/environment-auth.md) before changing token,-credential, or authorization behavior.--## Code Map--- [`alchemy.run.ts`](./alchemy.run.ts) defines the deployed Alchemy stack.-- [`src/worker.ts`](./src/worker.ts) wires Cloudflare bindings, runtime layers, queues, and HTTP APIs.-- [`src/http/Api.ts`](./src/http/Api.ts) contains the relay HTTP handlers and authentication- boundaries.-- [`src/environments`](./src/environments) contains environment linking, credentials, endpoint- provisioning, and connection flows.-- [`src/agentActivity`](./src/agentActivity) contains mobile device registration, activity state,- APNs delivery, and queue processing.-- [`src/auth`](./src/auth) contains relay token and DPoP proof handling.-- [`src/persistence/schema.ts`](./src/persistence/schema.ts) defines persisted relay state. Keep- schema and migration changes together.--Shared request and response schemas live in-[`packages/contracts/src/relay.ts`](../../packages/contracts/src/relay.ts). Shared client-side relay-calls live in-[`packages/client-runtime/src/relay/managedRelay.ts`](../../packages/client-runtime/src/relay/managedRelay.ts).--## Working Locally--Install dependencies from the repository root, then run relay-focused checks from this directory:--```sh-vp install-cd infra/relay-vp test run-vp run typecheck-```--To run a smaller test set while iterating:--```sh-vp test run src/environments/EnvironmentLinker.test.ts-```--Before considering a change complete, run the repository-wide checks from the root:--```sh-vp check-vp run typecheck-```--Backend changes should include tests. Prefer testing the real business logic with external-dependencies represented at their boundary rather than mocking internal behavior.--## Deployment--The relay deploys through Alchemy:--```sh-vp run --filter t3code-relay deploy-```--The stack provisions the Cloudflare Worker and queues, managed endpoint resources, database-connectivity, and relay tracing resources. Copy [`infra/relay/.env.example`](./.env.example) to-`infra/relay/.env` and fill in the deployment-specific values before deploying. Alchemy loads that-file from the relay directory. Runtime secrets include Clerk and APNs credentials. Production adopts-the configured API and tunnel DNS zones as retained Cloudflare resources. Personal stages reference-the production-owned zones.--The `prod` Alchemy stage owns the retained PlanetScale database and is the shared hosted relay for-stable and nightly clients. Every other stage references that database and provisions an isolated-PlanetScale branch and runtime role for local development, so deploy `prod` before creating-developer stages:--```sh-vp run --filter t3code-relay deploy -- --stage prod-vp run --filter t3code-relay deploy -- --env-file .env.local-```--Alchemy defaults personal deployments to the `dev_$USER` stage. Relay custom domains apply the same-DNS-safe sanitization as Alchemy physical resource names, so `prod` uses-`relay.<RELAY_API_ZONE_NAME>` and `dev_julius` uses-`relay-dev-julius.<RELAY_API_ZONE_NAME>`. Managed environment endpoints are provisioned below-`RELAY_TUNNEL_ZONE_NAME`, which may be a different Cloudflare zone. Production tunnel hostnames use-`prod-<digest>.<RELAY_TUNNEL_ZONE_NAME>`; personal stages use-`<stage>-<digest>.<RELAY_TUNNEL_ZONE_NAME>`. `RELAY_DOMAIN` remains available as an explicit API-domain override.--After a successful deploy, the wrapper updates the repository-root `.env` file with the derived relay-URL. That makes subsequent source builds point at the relay that was just deployed without copying-the URL manually.--### Deployment CI--The relay is versioned separately from client releases. `.github/workflows/deploy-relay.yml` deploys-the shared Alchemy `prod` stage on every push to `main`. Stable and nightly release builds both-resolve their static public config from the same-`production` GitHub environment. Pull requests do not deploy relay stages. Developers can-deploy personal non-production stages locally with any stage name other than `prod`.--The repository must define these Actions variables shared by relay deployments:--- `CLOUDFLARE_ACCOUNT_ID`-- `PLANETSCALE_ORGANIZATION`-- `AXIOM_ORG_ID`--The repository must define these Actions secrets shared by relay deployments:--- `CLOUDFLARE_API_TOKEN`-- `PLANETSCALE_API_TOKEN_ID`-- `PLANETSCALE_API_TOKEN`-- `AXIOM_TOKEN`--The `production` GitHub environment must define these Actions variables:--- `RELAY_API_ZONE_NAME`-- `RELAY_TUNNEL_ZONE_NAME`-- `RELAY_DOMAIN` if overriding the derived production relay domain-- `CLERK_PUBLISHABLE_KEY`-- `CLERK_JWT_AUDIENCE`-- `CLERK_JWT_TEMPLATE`-- `APNS_ENVIRONMENT`-- `APNS_TEAM_ID`-- `APNS_KEY_ID`-- `APNS_BUNDLE_ID`--The `production` GitHub environment must define these Actions secrets:--- `CLERK_SECRET_KEY`-- `APNS_PRIVATE_KEY`--The account-scoped repository credentials are consumed by Alchemy while provisioning relay stages; they-are not bound into the relay Worker. The production deployment uses an Axiom personal access token,-so `AXIOM_ORG_ID` must accompany `AXIOM_TOKEN`. The release workflow reads the production relay's-derived public URL and Clerk publishable key from the same environment for downstream desktop, CLI,-and hosted web builds.--See:--- [T3 Connect Clerk Setup](../../docs/internals/t3-connect.md) for Clerk keys, JWT templates, and sign-up restrictions- setup.-- [Relay Observability](../../docs/operations/relay-observability.md) for deployment tracing and diagnostics.-- [T3 Connect Architecture Overview](../../docs/internals/t3-code-connect-auth-flow.html) for the full link,- connect, endpoint, and notification flows.diff --git a/infra/relay/alchemy.run.ts b/infra/relay/alchemy.run.tsdeleted file mode 100644index 60f73bc3a..000000000--- a/infra/relay/alchemy.run.ts+++ /dev/null@@ -1,50 +0,0 @@-// @effect-diagnostics anyUnknownInErrorContext:off layerMergeAllWithDependencies:off - Alchemy provider helpers expose framework-owned any requirements.-import * as Alchemy from "alchemy";-import * as Axiom from "alchemy/Axiom";-import * as Cloudflare from "alchemy/Cloudflare";-import * as Drizzle from "alchemy/Drizzle";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";-import * as Planetscale from "alchemy/Planetscale";--import * as RelayDb from "./src/db.ts";-import { RelayObservability } from "./src/observability.ts";-import { ManagedEndpointZone, RelayApiZone } from "./src/zone.ts";-import ApiLive, { Api } from "./src/worker.ts";--export default Alchemy.Stack(- "T3CodeRelay",- {- providers: Layer.mergeAll(- Axiom.providers(),- Cloudflare.providers(),- Drizzle.providers(),- Planetscale.providers(),- ),- state: Cloudflare.state(),- },- Effect.gen(function* () {- const db = yield* RelayDb.PlanetscaleDatabase;- const hyperdrive = yield* RelayDb.RelayHyperdrive;- const managedEndpointZone = yield* ManagedEndpointZone.pipe(Effect.orDie);- const relayApiZone = yield* RelayApiZone.pipe(Effect.orDie);- const observability = yield* RelayObservability;- const api = yield* Api;-- return {- databaseName: db.database.name,- databaseBranchName: db.branch?.name ?? "main",- hyperdriveName: hyperdrive.name,- workerName: api.workerName,- url: api.url,- relayApiZoneId: relayApiZone.zoneId,- managedEndpointZoneId: managedEndpointZone.zoneId,- mobileTracingUrl: observability.traces.otelTracesEndpoint,- mobileTracingDataset: observability.traces.name,- mobileTracingToken: observability.mobileIngestToken.token,- clientTracingUrl: observability.traces.otelTracesEndpoint,- clientTracingDataset: observability.traces.name,- clientTracingToken: observability.clientIngestToken.token,- };- }).pipe(Effect.provide(ApiLive)),-);diff --git a/infra/relay/migrations/postgres/20260527044716_baseline/migration.sql b/infra/relay/migrations/postgres/20260527044716_baseline/migration.sqldeleted file mode 100644index 694885f38..000000000--- a/infra/relay/migrations/postgres/20260527044716_baseline/migration.sql+++ /dev/null@@ -1,104 +0,0 @@-CREATE TABLE "relay_agent_activity_rows" (- "environment_id" varchar(191),- "environment_public_key" text,- "thread_id" varchar(191),- "state_json" jsonb NOT NULL,- "updated_at" varchar(64) NOT NULL,- "created_at" varchar(64) NOT NULL,- CONSTRAINT "relay_agent_activity_rows_pkey" PRIMARY KEY("environment_id","environment_public_key","thread_id")-);---> statement-breakpoint-CREATE TABLE "relay_delivery_attempts" (- "id" varchar(36) PRIMARY KEY,- "created_at" varchar(64) NOT NULL,- "user_id" varchar(255),- "environment_id" varchar(191),- "thread_id" varchar(191),- "device_id" varchar(255),- "kind" varchar(64) NOT NULL,- "source_job_id" varchar(64),- "token_suffix" varchar(16),- "apns_status" integer,- "apns_reason" text,- "apns_id" varchar(128),- "transport_error" text-);---> statement-breakpoint-CREATE TABLE "relay_dpop_proofs" (- "thumbprint" varchar(128),- "jti" varchar(255),- "iat" integer NOT NULL,- "expires_at" varchar(64) NOT NULL,- "created_at" varchar(64) NOT NULL,- CONSTRAINT "relay_dpop_proofs_pkey" PRIMARY KEY("thumbprint","jti")-);---> statement-breakpoint-CREATE TABLE "relay_environment_credentials" (- "credential_id" varchar(64) PRIMARY KEY,- "environment_id" varchar(191) NOT NULL,- "environment_public_key" text NOT NULL,- "credential_hash" varchar(191) NOT NULL,- "revoked_at" varchar(64),- "created_at" varchar(64) NOT NULL,- "updated_at" varchar(64) NOT NULL-);---> statement-breakpoint-CREATE TABLE "relay_environment_links" (- "user_id" varchar(191),- "environment_id" varchar(191),- "environment_label" text DEFAULT 'T3 Environment' NOT NULL,- "environment_public_key" text NOT NULL,- "endpoint_http_base_url" text NOT NULL,- "endpoint_ws_base_url" text NOT NULL,- "endpoint_provider_kind" varchar(32) NOT NULL,- "notifications_enabled" boolean DEFAULT true NOT NULL,- "live_activities_enabled" boolean DEFAULT true NOT NULL,- "managed_tunnels_enabled" boolean DEFAULT false NOT NULL,- "created_by_device_id" varchar(191),- "revoked_at" varchar(64),- "created_at" varchar(64) NOT NULL,- "updated_at" varchar(64) NOT NULL,- CONSTRAINT "relay_environment_links_pkey" PRIMARY KEY("user_id","environment_id")-);---> statement-breakpoint-CREATE TABLE "relay_live_activities" (- "user_id" varchar(255),- "device_id" varchar(255),- "activity_push_token" text,- "remote_start_queued_at" varchar(64),- "remote_started_at" varchar(64),- "ended_at" varchar(64),- "last_aggregate_json" jsonb,- "last_live_activity_delivery_at" varchar(64),- "created_at" varchar(64) NOT NULL,- "updated_at" varchar(64) NOT NULL,- CONSTRAINT "relay_live_activities_pkey" PRIMARY KEY("user_id","device_id")-);---> statement-breakpoint-CREATE TABLE "relay_mobile_devices" (- "user_id" varchar(255),- "device_id" varchar(255),- "platform" varchar(16) NOT NULL,- "ios_major_version" integer NOT NULL,- "app_version" varchar(64),- "push_token" text,- "push_to_start_token" text,- "preferences_json" jsonb NOT NULL,- "created_at" varchar(64) NOT NULL,- "updated_at" varchar(64) NOT NULL,- CONSTRAINT "relay_mobile_devices_pkey" PRIMARY KEY("user_id","device_id")-);---> statement-breakpoint-CREATE INDEX "idx_relay_agent_activity_rows_updated" ON "relay_agent_activity_rows" ("updated_at");--> statement-breakpoint-CREATE INDEX "idx_relay_delivery_attempts_environment" ON "relay_delivery_attempts" ("environment_id","thread_id","created_at");--> statement-breakpoint-CREATE UNIQUE INDEX "idx_relay_delivery_attempts_source_job" ON "relay_delivery_attempts" ("source_job_id");--> statement-breakpoint-CREATE INDEX "idx_relay_dpop_proofs_expires_at" ON "relay_dpop_proofs" ("expires_at");--> statement-breakpoint-CREATE UNIQUE INDEX "idx_relay_environment_credentials_hash" ON "relay_environment_credentials" ("credential_hash");--> statement-breakpoint-CREATE INDEX "idx_relay_environment_credentials_environment" ON "relay_environment_credentials" ("environment_id","revoked_at");--> statement-breakpoint-CREATE INDEX "idx_relay_environment_credentials_environment_key" ON "relay_environment_credentials" ("environment_id","environment_public_key","revoked_at");--> statement-breakpoint-CREATE INDEX "idx_relay_environment_links_environment" ON "relay_environment_links" ("environment_id","revoked_at");--> statement-breakpoint-CREATE INDEX "idx_relay_live_activities_user" ON "relay_live_activities" ("user_id");--> statement-breakpoint-CREATE UNIQUE INDEX "idx_relay_live_activities_activity_push_token" ON "relay_live_activities" ("activity_push_token");--> statement-breakpoint-CREATE INDEX "idx_relay_mobile_devices_user" ON "relay_mobile_devices" ("user_id");--> statement-breakpoint-CREATE UNIQUE INDEX "idx_relay_mobile_devices_push_token" ON "relay_mobile_devices" ("push_token");--> statement-breakpoint-CREATE UNIQUE INDEX "idx_relay_mobile_devices_push_to_start_token" ON "relay_mobile_devices" ("push_to_start_token");\ No newline at end of filediff --git a/infra/relay/migrations/postgres/20260527044716_baseline/snapshot.json b/infra/relay/migrations/postgres/20260527044716_baseline/snapshot.jsondeleted file mode 100644index aa35a4f8e..000000000--- a/infra/relay/migrations/postgres/20260527044716_baseline/snapshot.json+++ /dev/null@@ -1,1267 +0,0 @@-{- "version": "8",- "dialect": "postgres",- "id": "ad620f05-3fd1-43b8-a3ca-d4c02543d892",- "prevIds": ["00000000-0000-0000-0000-000000000000"],- "ddl": [- {- "isRlsEnabled": false,- "name": "relay_agent_activity_rows",- "entityType": "tables",- "schema": "public"- },- {- "isRlsEnabled": false,- "name": "relay_delivery_attempts",- "entityType": "tables",- "schema": "public"- },- {- "isRlsEnabled": false,- "name": "relay_dpop_proofs",- "entityType": "tables",- "schema": "public"- },- {- "isRlsEnabled": false,- "name": "relay_environment_credentials",- "entityType": "tables",- "schema": "public"- },- {- "isRlsEnabled": false,- "name": "relay_environment_links",- "entityType": "tables",- "schema": "public"- },- {- "isRlsEnabled": false,- "name": "relay_live_activities",- "entityType": "tables",- "schema": "public"- },- {- "isRlsEnabled": false,- "name": "relay_mobile_devices",- "entityType": "tables",- "schema": "public"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "environment_id",- "entityType": "columns",- "schema": "public",- "table": "relay_agent_activity_rows"- },- {- "type": "text",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "environment_public_key",- "entityType": "columns",- "schema": "public",- "table": "relay_agent_activity_rows"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "thread_id",- "entityType": "columns",- "schema": "public",- "table": "relay_agent_activity_rows"- },- {- "type": "jsonb",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "state_json",- "entityType": "columns",- "schema": "public",- "table": "relay_agent_activity_rows"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "updated_at",- "entityType": "columns",- "schema": "public",- "table": "relay_agent_activity_rows"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_at",- "entityType": "columns",- "schema": "public",- "table": "relay_agent_activity_rows"- },- {- "type": "varchar(36)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "id",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_at",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(255)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "user_id",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "environment_id",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "thread_id",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(255)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "device_id",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "kind",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "source_job_id",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(16)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "token_suffix",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "integer",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "apns_status",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "text",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "apns_reason",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(128)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "apns_id",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "text",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "transport_error",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(128)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "thumbprint",- "entityType": "columns",- "schema": "public",- "table": "relay_dpop_proofs"- },- {- "type": "varchar(255)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "jti",- "entityType": "columns",- "schema": "public",- "table": "relay_dpop_proofs"- },- {- "type": "integer",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "iat",- "entityType": "columns",- "schema": "public",- "table": "relay_dpop_proofs"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "expires_at",- "entityType": "columns",- "schema": "public",- "table": "relay_dpop_proofs"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_at",- "entityType": "columns",- "schema": "public",- "table": "relay_dpop_proofs"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "credential_id",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "environment_id",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "type": "text",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "environment_public_key",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "credential_hash",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "revoked_at",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_at",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "updated_at",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "user_id",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "environment_id",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "text",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": "'T3 Environment'",- "generated": null,- "identity": null,- "name": "environment_label",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "text",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "environment_public_key",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "text",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "endpoint_http_base_url",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "text",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "endpoint_ws_base_url",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "varchar(32)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "endpoint_provider_kind",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "boolean",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": "true",- "generated": null,- "identity": null,- "name": "notifications_enabled",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "boolean",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": "true",- "generated": null,- "identity": null,- "name": "live_activities_enabled",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "boolean",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": "false",- "generated": null,- "identity": null,- "name": "managed_tunnels_enabled",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_by_device_id",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "revoked_at",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_at",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "updated_at",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "varchar(255)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "user_id",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "varchar(255)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "device_id",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "text",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "activity_push_token",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "remote_start_queued_at",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "remote_started_at",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "ended_at",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "jsonb",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "last_aggregate_json",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "last_live_activity_delivery_at",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_at",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "updated_at",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "varchar(255)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "user_id",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "varchar(255)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "device_id",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "varchar(16)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "platform",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "integer",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "ios_major_version",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "app_version",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "text",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "push_token",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "text",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "push_to_start_token",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "jsonb",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "preferences_json",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_at",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "updated_at",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "nameExplicit": true,- "columns": [- {- "value": "updated_at",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": false,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_agent_activity_rows_updated",- "entityType": "indexes",- "schema": "public",- "table": "relay_agent_activity_rows"- },- {- "nameExplicit": true,- "columns": [- {- "value": "environment_id",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- },- {- "value": "thread_id",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- },- {- "value": "created_at",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": false,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_delivery_attempts_environment",- "entityType": "indexes",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "nameExplicit": true,- "columns": [- {- "value": "source_job_id",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": true,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_delivery_attempts_source_job",- "entityType": "indexes",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "nameExplicit": true,- "columns": [- {- "value": "expires_at",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": false,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_dpop_proofs_expires_at",- "entityType": "indexes",- "schema": "public",- "table": "relay_dpop_proofs"- },- {- "nameExplicit": true,- "columns": [- {- "value": "credential_hash",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": true,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_environment_credentials_hash",- "entityType": "indexes",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "nameExplicit": true,- "columns": [- {- "value": "environment_id",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- },- {- "value": "revoked_at",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": false,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_environment_credentials_environment",- "entityType": "indexes",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "nameExplicit": true,- "columns": [- {- "value": "environment_id",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- },- {- "value": "environment_public_key",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- },- {- "value": "revoked_at",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": false,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_environment_credentials_environment_key",- "entityType": "indexes",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "nameExplicit": true,- "columns": [- {- "value": "environment_id",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- },- {- "value": "revoked_at",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": false,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_environment_links_environment",- "entityType": "indexes",- "schema": "public",- "table": "relay_environment_links"- },- {- "nameExplicit": true,- "columns": [- {- "value": "user_id",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": false,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_live_activities_user",- "entityType": "indexes",- "schema": "public",- "table": "relay_live_activities"- },- {- "nameExplicit": true,- "columns": [- {- "value": "activity_push_token",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": true,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_live_activities_activity_push_token",- "entityType": "indexes",- "schema": "public",- "table": "relay_live_activities"- },- {- "nameExplicit": true,- "columns": [- {- "value": "user_id",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": false,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_mobile_devices_user",- "entityType": "indexes",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "nameExplicit": true,- "columns": [- {- "value": "push_token",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": true,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_mobile_devices_push_token",- "entityType": "indexes",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "nameExplicit": true,- "columns": [- {- "value": "push_to_start_token",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": true,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_mobile_devices_push_to_start_token",- "entityType": "indexes",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "columns": ["environment_id", "environment_public_key", "thread_id"],- "nameExplicit": false,- "name": "relay_agent_activity_rows_pkey",- "entityType": "pks",- "schema": "public",- "table": "relay_agent_activity_rows"- },- {- "columns": ["thumbprint", "jti"],- "nameExplicit": false,- "name": "relay_dpop_proofs_pkey",- "entityType": "pks",- "schema": "public",- "table": "relay_dpop_proofs"- },- {- "columns": ["user_id", "environment_id"],- "nameExplicit": false,- "name": "relay_environment_links_pkey",- "entityType": "pks",- "schema": "public",- "table": "relay_environment_links"- },- {- "columns": ["user_id", "device_id"],- "nameExplicit": false,- "name": "relay_live_activities_pkey",- "entityType": "pks",- "schema": "public",- "table": "relay_live_activities"- },- {- "columns": ["user_id", "device_id"],- "nameExplicit": false,- "name": "relay_mobile_devices_pkey",- "entityType": "pks",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "columns": ["id"],- "nameExplicit": false,- "name": "relay_delivery_attempts_pkey",- "schema": "public",- "table": "relay_delivery_attempts",- "entityType": "pks"- },- {- "columns": ["credential_id"],- "nameExplicit": false,- "name": "relay_environment_credentials_pkey",- "schema": "public",- "table": "relay_environment_credentials",- "entityType": "pks"- }- ],- "renames": []-}diff --git a/infra/relay/migrations/postgres/20260601225421_add_mobile_device_label/migration.sql b/infra/relay/migrations/postgres/20260601225421_add_mobile_device_label/migration.sqldeleted file mode 100644index 291096637..000000000--- a/infra/relay/migrations/postgres/20260601225421_add_mobile_device_label/migration.sql+++ /dev/null@@ -1 +0,0 @@-ALTER TABLE "relay_mobile_devices" ADD COLUMN "label" text DEFAULT 'iOS device' NOT NULL;diff --git a/infra/relay/migrations/postgres/20260601225421_add_mobile_device_label/snapshot.json b/infra/relay/migrations/postgres/20260601225421_add_mobile_device_label/snapshot.jsondeleted file mode 100644index d79130adb..000000000--- a/infra/relay/migrations/postgres/20260601225421_add_mobile_device_label/snapshot.json+++ /dev/null@@ -1,1280 +0,0 @@-{- "dialect": "postgres",- "id": "e189638b-4700-4656-b86e-d8baa63f5fe4",- "prevIds": ["ad620f05-3fd1-43b8-a3ca-d4c02543d892"],- "version": "8",- "ddl": [- {- "isRlsEnabled": false,- "name": "relay_agent_activity_rows",- "entityType": "tables",- "schema": "public"- },- {- "isRlsEnabled": false,- "name": "relay_delivery_attempts",- "entityType": "tables",- "schema": "public"- },- {- "isRlsEnabled": false,- "name": "relay_dpop_proofs",- "entityType": "tables",- "schema": "public"- },- {- "isRlsEnabled": false,- "name": "relay_environment_credentials",- "entityType": "tables",- "schema": "public"- },- {- "isRlsEnabled": false,- "name": "relay_environment_links",- "entityType": "tables",- "schema": "public"- },- {- "isRlsEnabled": false,- "name": "relay_live_activities",- "entityType": "tables",- "schema": "public"- },- {- "isRlsEnabled": false,- "name": "relay_mobile_devices",- "entityType": "tables",- "schema": "public"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "environment_id",- "entityType": "columns",- "schema": "public",- "table": "relay_agent_activity_rows"- },- {- "type": "text",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "environment_public_key",- "entityType": "columns",- "schema": "public",- "table": "relay_agent_activity_rows"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "thread_id",- "entityType": "columns",- "schema": "public",- "table": "relay_agent_activity_rows"- },- {- "type": "jsonb",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "state_json",- "entityType": "columns",- "schema": "public",- "table": "relay_agent_activity_rows"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "updated_at",- "entityType": "columns",- "schema": "public",- "table": "relay_agent_activity_rows"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_at",- "entityType": "columns",- "schema": "public",- "table": "relay_agent_activity_rows"- },- {- "type": "varchar(36)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "id",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_at",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(255)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "user_id",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "environment_id",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "thread_id",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(255)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "device_id",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "kind",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "source_job_id",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(16)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "token_suffix",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "integer",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "apns_status",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "text",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "apns_reason",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(128)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "apns_id",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "text",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "transport_error",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(128)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "thumbprint",- "entityType": "columns",- "schema": "public",- "table": "relay_dpop_proofs"- },- {- "type": "varchar(255)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "jti",- "entityType": "columns",- "schema": "public",- "table": "relay_dpop_proofs"- },- {- "type": "integer",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "iat",- "entityType": "columns",- "schema": "public",- "table": "relay_dpop_proofs"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "expires_at",- "entityType": "columns",- "schema": "public",- "table": "relay_dpop_proofs"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_at",- "entityType": "columns",- "schema": "public",- "table": "relay_dpop_proofs"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "credential_id",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "environment_id",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "type": "text",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "environment_public_key",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "credential_hash",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "revoked_at",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_at",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "updated_at",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "user_id",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "environment_id",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "text",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": "'T3 Environment'",- "generated": null,- "identity": null,- "name": "environment_label",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "text",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "environment_public_key",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "text",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "endpoint_http_base_url",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "text",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "endpoint_ws_base_url",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "varchar(32)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "endpoint_provider_kind",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "boolean",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": "true",- "generated": null,- "identity": null,- "name": "notifications_enabled",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "boolean",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": "true",- "generated": null,- "identity": null,- "name": "live_activities_enabled",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "boolean",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": "false",- "generated": null,- "identity": null,- "name": "managed_tunnels_enabled",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_by_device_id",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "revoked_at",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_at",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "updated_at",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "varchar(255)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "user_id",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "varchar(255)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "device_id",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "text",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "activity_push_token",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "remote_start_queued_at",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "remote_started_at",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "ended_at",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "jsonb",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "last_aggregate_json",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "last_live_activity_delivery_at",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_at",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "updated_at",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "varchar(255)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "user_id",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "varchar(255)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "device_id",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "text",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": "'iOS device'",- "generated": null,- "identity": null,- "name": "label",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "varchar(16)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "platform",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "integer",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "ios_major_version",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "app_version",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "text",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "push_token",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "text",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "push_to_start_token",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "jsonb",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "preferences_json",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_at",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "updated_at",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "nameExplicit": true,- "columns": [- {- "value": "updated_at",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": false,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_agent_activity_rows_updated",- "entityType": "indexes",- "schema": "public",- "table": "relay_agent_activity_rows"- },- {- "nameExplicit": true,- "columns": [- {- "value": "environment_id",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- },- {- "value": "thread_id",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- },- {- "value": "created_at",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": false,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_delivery_attempts_environment",- "entityType": "indexes",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "nameExplicit": true,- "columns": [- {- "value": "source_job_id",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": true,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_delivery_attempts_source_job",- "entityType": "indexes",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "nameExplicit": true,- "columns": [- {- "value": "expires_at",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": false,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_dpop_proofs_expires_at",- "entityType": "indexes",- "schema": "public",- "table": "relay_dpop_proofs"- },- {- "nameExplicit": true,- "columns": [- {- "value": "credential_hash",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": true,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_environment_credentials_hash",- "entityType": "indexes",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "nameExplicit": true,- "columns": [- {- "value": "environment_id",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- },- {- "value": "revoked_at",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": false,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_environment_credentials_environment",- "entityType": "indexes",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "nameExplicit": true,- "columns": [- {- "value": "environment_id",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- },- {- "value": "environment_public_key",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- },- {- "value": "revoked_at",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": false,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_environment_credentials_environment_key",- "entityType": "indexes",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "nameExplicit": true,- "columns": [- {- "value": "environment_id",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- },- {- "value": "revoked_at",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": false,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_environment_links_environment",- "entityType": "indexes",- "schema": "public",- "table": "relay_environment_links"- },- {- "nameExplicit": true,- "columns": [- {- "value": "user_id",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": false,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_live_activities_user",- "entityType": "indexes",- "schema": "public",- "table": "relay_live_activities"- },- {- "nameExplicit": true,- "columns": [- {- "value": "activity_push_token",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": true,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_live_activities_activity_push_token",- "entityType": "indexes",- "schema": "public",- "table": "relay_live_activities"- },- {- "nameExplicit": true,- "columns": [- {- "value": "user_id",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": false,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_mobile_devices_user",- "entityType": "indexes",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "nameExplicit": true,- "columns": [- {- "value": "push_token",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": true,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_mobile_devices_push_token",- "entityType": "indexes",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "nameExplicit": true,- "columns": [- {- "value": "push_to_start_token",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": true,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_mobile_devices_push_to_start_token",- "entityType": "indexes",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "columns": ["environment_id", "environment_public_key", "thread_id"],- "nameExplicit": false,- "name": "relay_agent_activity_rows_pkey",- "entityType": "pks",- "schema": "public",- "table": "relay_agent_activity_rows"- },- {- "columns": ["thumbprint", "jti"],- "nameExplicit": false,- "name": "relay_dpop_proofs_pkey",- "entityType": "pks",- "schema": "public",- "table": "relay_dpop_proofs"- },- {- "columns": ["user_id", "environment_id"],- "nameExplicit": false,- "name": "relay_environment_links_pkey",- "entityType": "pks",- "schema": "public",- "table": "relay_environment_links"- },- {- "columns": ["user_id", "device_id"],- "nameExplicit": false,- "name": "relay_live_activities_pkey",- "entityType": "pks",- "schema": "public",- "table": "relay_live_activities"- },- {- "columns": ["user_id", "device_id"],- "nameExplicit": false,- "name": "relay_mobile_devices_pkey",- "entityType": "pks",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "columns": ["id"],- "nameExplicit": false,- "name": "relay_delivery_attempts_pkey",- "schema": "public",- "table": "relay_delivery_attempts",- "entityType": "pks"- },- {- "columns": ["credential_id"],- "nameExplicit": false,- "name": "relay_environment_credentials_pkey",- "schema": "public",- "table": "relay_environment_credentials",- "entityType": "pks"- }- ],- "renames": []-}diff --git a/infra/relay/migrations/postgres/20260603035812_managed_endpoint_allocations/migration.sql b/infra/relay/migrations/postgres/20260603035812_managed_endpoint_allocations/migration.sqldeleted file mode 100644index 7b8f00416..000000000--- a/infra/relay/migrations/postgres/20260603035812_managed_endpoint_allocations/migration.sql+++ /dev/null@@ -1,15 +0,0 @@-CREATE TABLE "relay_managed_endpoint_allocations" (- "user_id" varchar(191),- "environment_id" varchar(191),- "hostname" text NOT NULL,- "tunnel_id" varchar(191),- "tunnel_name" text NOT NULL,- "dns_record_id" varchar(191),- "ready_at" varchar(64),- "created_at" varchar(64) NOT NULL,- "updated_at" varchar(64) NOT NULL,- CONSTRAINT "relay_managed_endpoint_allocations_pkey" PRIMARY KEY("user_id","environment_id")-);---> statement-breakpoint-CREATE UNIQUE INDEX "idx_relay_managed_endpoint_allocations_hostname" ON "relay_managed_endpoint_allocations" ("hostname");--> statement-breakpoint-CREATE UNIQUE INDEX "idx_relay_managed_endpoint_allocations_tunnel_name" ON "relay_managed_endpoint_allocations" ("tunnel_name");\ No newline at end of filediff --git a/infra/relay/migrations/postgres/20260603035812_managed_endpoint_allocations/snapshot.json b/infra/relay/migrations/postgres/20260603035812_managed_endpoint_allocations/snapshot.jsondeleted file mode 100644index ead6f6096..000000000--- a/infra/relay/migrations/postgres/20260603035812_managed_endpoint_allocations/snapshot.json+++ /dev/null@@ -1,1453 +0,0 @@-{- "version": "8",- "dialect": "postgres",- "id": "385d476b-d4f6-48a3-99e6-0a95af4ee4e4",- "prevIds": ["e189638b-4700-4656-b86e-d8baa63f5fe4"],- "ddl": [- {- "isRlsEnabled": false,- "name": "relay_agent_activity_rows",- "entityType": "tables",- "schema": "public"- },- {- "isRlsEnabled": false,- "name": "relay_delivery_attempts",- "entityType": "tables",- "schema": "public"- },- {- "isRlsEnabled": false,- "name": "relay_dpop_proofs",- "entityType": "tables",- "schema": "public"- },- {- "isRlsEnabled": false,- "name": "relay_environment_credentials",- "entityType": "tables",- "schema": "public"- },- {- "isRlsEnabled": false,- "name": "relay_environment_links",- "entityType": "tables",- "schema": "public"- },- {- "isRlsEnabled": false,- "name": "relay_live_activities",- "entityType": "tables",- "schema": "public"- },- {- "isRlsEnabled": false,- "name": "relay_managed_endpoint_allocations",- "entityType": "tables",- "schema": "public"- },- {- "isRlsEnabled": false,- "name": "relay_mobile_devices",- "entityType": "tables",- "schema": "public"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "environment_id",- "entityType": "columns",- "schema": "public",- "table": "relay_agent_activity_rows"- },- {- "type": "text",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "environment_public_key",- "entityType": "columns",- "schema": "public",- "table": "relay_agent_activity_rows"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "thread_id",- "entityType": "columns",- "schema": "public",- "table": "relay_agent_activity_rows"- },- {- "type": "jsonb",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "state_json",- "entityType": "columns",- "schema": "public",- "table": "relay_agent_activity_rows"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "updated_at",- "entityType": "columns",- "schema": "public",- "table": "relay_agent_activity_rows"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_at",- "entityType": "columns",- "schema": "public",- "table": "relay_agent_activity_rows"- },- {- "type": "varchar(36)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "id",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_at",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(255)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "user_id",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "environment_id",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "thread_id",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(255)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "device_id",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "kind",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "source_job_id",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(16)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "token_suffix",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "integer",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "apns_status",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "text",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "apns_reason",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(128)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "apns_id",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "text",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "transport_error",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(128)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "thumbprint",- "entityType": "columns",- "schema": "public",- "table": "relay_dpop_proofs"- },- {- "type": "varchar(255)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "jti",- "entityType": "columns",- "schema": "public",- "table": "relay_dpop_proofs"- },- {- "type": "integer",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "iat",- "entityType": "columns",- "schema": "public",- "table": "relay_dpop_proofs"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "expires_at",- "entityType": "columns",- "schema": "public",- "table": "relay_dpop_proofs"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_at",- "entityType": "columns",- "schema": "public",- "table": "relay_dpop_proofs"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "credential_id",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "environment_id",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "type": "text",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "environment_public_key",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "credential_hash",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "revoked_at",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_at",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "updated_at",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "user_id",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "environment_id",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "text",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": "'T3 Environment'",- "generated": null,- "identity": null,- "name": "environment_label",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "text",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "environment_public_key",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "text",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "endpoint_http_base_url",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "text",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "endpoint_ws_base_url",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "varchar(32)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "endpoint_provider_kind",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "boolean",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": "true",- "generated": null,- "identity": null,- "name": "notifications_enabled",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "boolean",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": "true",- "generated": null,- "identity": null,- "name": "live_activities_enabled",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "boolean",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": "false",- "generated": null,- "identity": null,- "name": "managed_tunnels_enabled",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_by_device_id",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "revoked_at",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_at",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "updated_at",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "varchar(255)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "user_id",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "varchar(255)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "device_id",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "text",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "activity_push_token",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "remote_start_queued_at",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "remote_started_at",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "ended_at",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "jsonb",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "last_aggregate_json",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "last_live_activity_delivery_at",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_at",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "updated_at",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "user_id",- "entityType": "columns",- "schema": "public",- "table": "relay_managed_endpoint_allocations"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "environment_id",- "entityType": "columns",- "schema": "public",- "table": "relay_managed_endpoint_allocations"- },- {- "type": "text",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "hostname",- "entityType": "columns",- "schema": "public",- "table": "relay_managed_endpoint_allocations"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "tunnel_id",- "entityType": "columns",- "schema": "public",- "table": "relay_managed_endpoint_allocations"- },- {- "type": "text",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "tunnel_name",- "entityType": "columns",- "schema": "public",- "table": "relay_managed_endpoint_allocations"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "dns_record_id",- "entityType": "columns",- "schema": "public",- "table": "relay_managed_endpoint_allocations"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "ready_at",- "entityType": "columns",- "schema": "public",- "table": "relay_managed_endpoint_allocations"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_at",- "entityType": "columns",- "schema": "public",- "table": "relay_managed_endpoint_allocations"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "updated_at",- "entityType": "columns",- "schema": "public",- "table": "relay_managed_endpoint_allocations"- },- {- "type": "varchar(255)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "user_id",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "varchar(255)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "device_id",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "text",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": "'iOS device'",- "generated": null,- "identity": null,- "name": "label",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "varchar(16)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "platform",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "integer",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "ios_major_version",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "app_version",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "text",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "push_token",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "text",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "push_to_start_token",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "jsonb",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "preferences_json",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_at",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "updated_at",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "nameExplicit": true,- "columns": [- {- "value": "updated_at",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": false,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_agent_activity_rows_updated",- "entityType": "indexes",- "schema": "public",- "table": "relay_agent_activity_rows"- },- {- "nameExplicit": true,- "columns": [- {- "value": "environment_id",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- },- {- "value": "thread_id",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- },- {- "value": "created_at",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": false,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_delivery_attempts_environment",- "entityType": "indexes",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "nameExplicit": true,- "columns": [- {- "value": "source_job_id",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": true,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_delivery_attempts_source_job",- "entityType": "indexes",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "nameExplicit": true,- "columns": [- {- "value": "expires_at",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": false,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_dpop_proofs_expires_at",- "entityType": "indexes",- "schema": "public",- "table": "relay_dpop_proofs"- },- {- "nameExplicit": true,- "columns": [- {- "value": "credential_hash",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": true,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_environment_credentials_hash",- "entityType": "indexes",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "nameExplicit": true,- "columns": [- {- "value": "environment_id",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- },- {- "value": "revoked_at",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": false,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_environment_credentials_environment",- "entityType": "indexes",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "nameExplicit": true,- "columns": [- {- "value": "environment_id",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- },- {- "value": "environment_public_key",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- },- {- "value": "revoked_at",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": false,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_environment_credentials_environment_key",- "entityType": "indexes",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "nameExplicit": true,- "columns": [- {- "value": "environment_id",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- },- {- "value": "revoked_at",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": false,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_environment_links_environment",- "entityType": "indexes",- "schema": "public",- "table": "relay_environment_links"- },- {- "nameExplicit": true,- "columns": [- {- "value": "user_id",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": false,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_live_activities_user",- "entityType": "indexes",- "schema": "public",- "table": "relay_live_activities"- },- {- "nameExplicit": true,- "columns": [- {- "value": "activity_push_token",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": true,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_live_activities_activity_push_token",- "entityType": "indexes",- "schema": "public",- "table": "relay_live_activities"- },- {- "nameExplicit": true,- "columns": [- {- "value": "hostname",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": true,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_managed_endpoint_allocations_hostname",- "entityType": "indexes",- "schema": "public",- "table": "relay_managed_endpoint_allocations"- },- {- "nameExplicit": true,- "columns": [- {- "value": "tunnel_name",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": true,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_managed_endpoint_allocations_tunnel_name",- "entityType": "indexes",- "schema": "public",- "table": "relay_managed_endpoint_allocations"- },- {- "nameExplicit": true,- "columns": [- {- "value": "user_id",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": false,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_mobile_devices_user",- "entityType": "indexes",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "nameExplicit": true,- "columns": [- {- "value": "push_token",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": true,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_mobile_devices_push_token",- "entityType": "indexes",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "nameExplicit": true,- "columns": [- {- "value": "push_to_start_token",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": true,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_mobile_devices_push_to_start_token",- "entityType": "indexes",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "columns": ["environment_id", "environment_public_key", "thread_id"],- "nameExplicit": false,- "name": "relay_agent_activity_rows_pkey",- "entityType": "pks",- "schema": "public",- "table": "relay_agent_activity_rows"- },- {- "columns": ["thumbprint", "jti"],- "nameExplicit": false,- "name": "relay_dpop_proofs_pkey",- "entityType": "pks",- "schema": "public",- "table": "relay_dpop_proofs"- },- {- "columns": ["user_id", "environment_id"],- "nameExplicit": false,- "name": "relay_environment_links_pkey",- "entityType": "pks",- "schema": "public",- "table": "relay_environment_links"- },- {- "columns": ["user_id", "device_id"],- "nameExplicit": false,- "name": "relay_live_activities_pkey",- "entityType": "pks",- "schema": "public",- "table": "relay_live_activities"- },- {- "columns": ["user_id", "environment_id"],- "nameExplicit": false,- "name": "relay_managed_endpoint_allocations_pkey",- "entityType": "pks",- "schema": "public",- "table": "relay_managed_endpoint_allocations"- },- {- "columns": ["user_id", "device_id"],- "nameExplicit": false,- "name": "relay_mobile_devices_pkey",- "entityType": "pks",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "columns": ["id"],- "nameExplicit": false,- "name": "relay_delivery_attempts_pkey",- "schema": "public",- "table": "relay_delivery_attempts",- "entityType": "pks"- },- {- "columns": ["credential_id"],- "nameExplicit": false,- "name": "relay_environment_credentials_pkey",- "schema": "public",- "table": "relay_environment_credentials",- "entityType": "pks"- }- ],- "renames": []-}diff --git a/infra/relay/migrations/postgres/20260706061126_migration/migration.sql b/infra/relay/migrations/postgres/20260706061126_migration/migration.sqldeleted file mode 100644index cba591f37..000000000--- a/infra/relay/migrations/postgres/20260706061126_migration/migration.sql+++ /dev/null@@ -1,3 +0,0 @@-ALTER TABLE "relay_mobile_devices" ADD COLUMN "bundle_id" varchar(255);---> statement-breakpoint-ALTER TABLE "relay_mobile_devices" ADD COLUMN "aps_environment" varchar(16);diff --git a/infra/relay/migrations/postgres/20260706061126_migration/snapshot.json b/infra/relay/migrations/postgres/20260706061126_migration/snapshot.jsondeleted file mode 100644index 0d75da1e4..000000000--- a/infra/relay/migrations/postgres/20260706061126_migration/snapshot.json+++ /dev/null@@ -1,1479 +0,0 @@-{- "dialect": "postgres",- "id": "f4151a65-091a-4601-bde8-029b155255b0",- "prevIds": ["385d476b-d4f6-48a3-99e6-0a95af4ee4e4"],- "version": "8",- "ddl": [- {- "isRlsEnabled": false,- "name": "relay_agent_activity_rows",- "entityType": "tables",- "schema": "public"- },- {- "isRlsEnabled": false,- "name": "relay_delivery_attempts",- "entityType": "tables",- "schema": "public"- },- {- "isRlsEnabled": false,- "name": "relay_dpop_proofs",- "entityType": "tables",- "schema": "public"- },- {- "isRlsEnabled": false,- "name": "relay_environment_credentials",- "entityType": "tables",- "schema": "public"- },- {- "isRlsEnabled": false,- "name": "relay_environment_links",- "entityType": "tables",- "schema": "public"- },- {- "isRlsEnabled": false,- "name": "relay_live_activities",- "entityType": "tables",- "schema": "public"- },- {- "isRlsEnabled": false,- "name": "relay_managed_endpoint_allocations",- "entityType": "tables",- "schema": "public"- },- {- "isRlsEnabled": false,- "name": "relay_mobile_devices",- "entityType": "tables",- "schema": "public"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "environment_id",- "entityType": "columns",- "schema": "public",- "table": "relay_agent_activity_rows"- },- {- "type": "text",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "environment_public_key",- "entityType": "columns",- "schema": "public",- "table": "relay_agent_activity_rows"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "thread_id",- "entityType": "columns",- "schema": "public",- "table": "relay_agent_activity_rows"- },- {- "type": "jsonb",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "state_json",- "entityType": "columns",- "schema": "public",- "table": "relay_agent_activity_rows"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "updated_at",- "entityType": "columns",- "schema": "public",- "table": "relay_agent_activity_rows"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_at",- "entityType": "columns",- "schema": "public",- "table": "relay_agent_activity_rows"- },- {- "type": "varchar(36)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "id",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_at",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(255)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "user_id",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "environment_id",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "thread_id",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(255)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "device_id",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "kind",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "source_job_id",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(16)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "token_suffix",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "integer",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "apns_status",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "text",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "apns_reason",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(128)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "apns_id",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "text",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "transport_error",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(128)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "thumbprint",- "entityType": "columns",- "schema": "public",- "table": "relay_dpop_proofs"- },- {- "type": "varchar(255)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "jti",- "entityType": "columns",- "schema": "public",- "table": "relay_dpop_proofs"- },- {- "type": "integer",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "iat",- "entityType": "columns",- "schema": "public",- "table": "relay_dpop_proofs"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "expires_at",- "entityType": "columns",- "schema": "public",- "table": "relay_dpop_proofs"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_at",- "entityType": "columns",- "schema": "public",- "table": "relay_dpop_proofs"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "credential_id",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "environment_id",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "type": "text",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "environment_public_key",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "credential_hash",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "revoked_at",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_at",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "updated_at",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "user_id",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "environment_id",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "text",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": "'T3 Environment'",- "generated": null,- "identity": null,- "name": "environment_label",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "text",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "environment_public_key",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "text",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "endpoint_http_base_url",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "text",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "endpoint_ws_base_url",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "varchar(32)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "endpoint_provider_kind",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "boolean",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": "true",- "generated": null,- "identity": null,- "name": "notifications_enabled",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "boolean",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": "true",- "generated": null,- "identity": null,- "name": "live_activities_enabled",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "boolean",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": "false",- "generated": null,- "identity": null,- "name": "managed_tunnels_enabled",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_by_device_id",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "revoked_at",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_at",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "updated_at",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "varchar(255)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "user_id",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "varchar(255)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "device_id",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "text",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "activity_push_token",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "remote_start_queued_at",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "remote_started_at",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "ended_at",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "jsonb",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "last_aggregate_json",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "last_live_activity_delivery_at",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_at",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "updated_at",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "user_id",- "entityType": "columns",- "schema": "public",- "table": "relay_managed_endpoint_allocations"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "environment_id",- "entityType": "columns",- "schema": "public",- "table": "relay_managed_endpoint_allocations"- },- {- "type": "text",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "hostname",- "entityType": "columns",- "schema": "public",- "table": "relay_managed_endpoint_allocations"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "tunnel_id",- "entityType": "columns",- "schema": "public",- "table": "relay_managed_endpoint_allocations"- },- {- "type": "text",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "tunnel_name",- "entityType": "columns",- "schema": "public",- "table": "relay_managed_endpoint_allocations"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "dns_record_id",- "entityType": "columns",- "schema": "public",- "table": "relay_managed_endpoint_allocations"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "ready_at",- "entityType": "columns",- "schema": "public",- "table": "relay_managed_endpoint_allocations"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_at",- "entityType": "columns",- "schema": "public",- "table": "relay_managed_endpoint_allocations"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "updated_at",- "entityType": "columns",- "schema": "public",- "table": "relay_managed_endpoint_allocations"- },- {- "type": "varchar(255)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "user_id",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "varchar(255)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "device_id",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "text",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": "'iOS device'",- "generated": null,- "identity": null,- "name": "label",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "varchar(16)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "platform",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "integer",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "ios_major_version",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "app_version",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "varchar(255)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "bundle_id",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "varchar(16)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "aps_environment",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "text",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "push_token",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "text",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "push_to_start_token",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "jsonb",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "preferences_json",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_at",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "updated_at",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "nameExplicit": true,- "columns": [- {- "value": "updated_at",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": false,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_agent_activity_rows_updated",- "entityType": "indexes",- "schema": "public",- "table": "relay_agent_activity_rows"- },- {- "nameExplicit": true,- "columns": [- {- "value": "environment_id",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- },- {- "value": "thread_id",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- },- {- "value": "created_at",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": false,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_delivery_attempts_environment",- "entityType": "indexes",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "nameExplicit": true,- "columns": [- {- "value": "source_job_id",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": true,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_delivery_attempts_source_job",- "entityType": "indexes",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "nameExplicit": true,- "columns": [- {- "value": "expires_at",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": false,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_dpop_proofs_expires_at",- "entityType": "indexes",- "schema": "public",- "table": "relay_dpop_proofs"- },- {- "nameExplicit": true,- "columns": [- {- "value": "credential_hash",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": true,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_environment_credentials_hash",- "entityType": "indexes",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "nameExplicit": true,- "columns": [- {- "value": "environment_id",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- },- {- "value": "revoked_at",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": false,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_environment_credentials_environment",- "entityType": "indexes",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "nameExplicit": true,- "columns": [- {- "value": "environment_id",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- },- {- "value": "environment_public_key",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- },- {- "value": "revoked_at",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": false,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_environment_credentials_environment_key",- "entityType": "indexes",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "nameExplicit": true,- "columns": [- {- "value": "environment_id",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- },- {- "value": "revoked_at",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": false,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_environment_links_environment",- "entityType": "indexes",- "schema": "public",- "table": "relay_environment_links"- },- {- "nameExplicit": true,- "columns": [- {- "value": "user_id",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": false,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_live_activities_user",- "entityType": "indexes",- "schema": "public",- "table": "relay_live_activities"- },- {- "nameExplicit": true,- "columns": [- {- "value": "activity_push_token",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": true,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_live_activities_activity_push_token",- "entityType": "indexes",- "schema": "public",- "table": "relay_live_activities"- },- {- "nameExplicit": true,- "columns": [- {- "value": "hostname",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": true,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_managed_endpoint_allocations_hostname",- "entityType": "indexes",- "schema": "public",- "table": "relay_managed_endpoint_allocations"- },- {- "nameExplicit": true,- "columns": [- {- "value": "tunnel_name",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": true,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_managed_endpoint_allocations_tunnel_name",- "entityType": "indexes",- "schema": "public",- "table": "relay_managed_endpoint_allocations"- },- {- "nameExplicit": true,- "columns": [- {- "value": "user_id",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": false,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_mobile_devices_user",- "entityType": "indexes",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "nameExplicit": true,- "columns": [- {- "value": "push_token",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": true,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_mobile_devices_push_token",- "entityType": "indexes",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "nameExplicit": true,- "columns": [- {- "value": "push_to_start_token",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": true,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_mobile_devices_push_to_start_token",- "entityType": "indexes",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "columns": ["environment_id", "environment_public_key", "thread_id"],- "nameExplicit": false,- "name": "relay_agent_activity_rows_pkey",- "entityType": "pks",- "schema": "public",- "table": "relay_agent_activity_rows"- },- {- "columns": ["thumbprint", "jti"],- "nameExplicit": false,- "name": "relay_dpop_proofs_pkey",- "entityType": "pks",- "schema": "public",- "table": "relay_dpop_proofs"- },- {- "columns": ["user_id", "environment_id"],- "nameExplicit": false,- "name": "relay_environment_links_pkey",- "entityType": "pks",- "schema": "public",- "table": "relay_environment_links"- },- {- "columns": ["user_id", "device_id"],- "nameExplicit": false,- "name": "relay_live_activities_pkey",- "entityType": "pks",- "schema": "public",- "table": "relay_live_activities"- },- {- "columns": ["user_id", "environment_id"],- "nameExplicit": false,- "name": "relay_managed_endpoint_allocations_pkey",- "entityType": "pks",- "schema": "public",- "table": "relay_managed_endpoint_allocations"- },- {- "columns": ["user_id", "device_id"],- "nameExplicit": false,- "name": "relay_mobile_devices_pkey",- "entityType": "pks",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "columns": ["id"],- "nameExplicit": false,- "name": "relay_delivery_attempts_pkey",- "schema": "public",- "table": "relay_delivery_attempts",- "entityType": "pks"- },- {- "columns": ["credential_id"],- "nameExplicit": false,- "name": "relay_environment_credentials_pkey",- "schema": "public",- "table": "relay_environment_credentials",- "entityType": "pks"- }- ],- "renames": []-}diff --git a/infra/relay/migrations/postgres/20260727115225_migration/migration.sql b/infra/relay/migrations/postgres/20260727115225_migration/migration.sqldeleted file mode 100644index 7050872f8..000000000--- a/infra/relay/migrations/postgres/20260727115225_migration/migration.sql+++ /dev/null@@ -1,7 +0,0 @@-CREATE TABLE "relay_managed_tunnel_limits" (- "user_id" varchar(191) PRIMARY KEY,- "max_tunnels" integer NOT NULL,- "created_at" varchar(64) NOT NULL,- "updated_at" varchar(64) NOT NULL-);-diff --git a/infra/relay/migrations/postgres/20260727115225_migration/snapshot.json b/infra/relay/migrations/postgres/20260727115225_migration/snapshot.jsondeleted file mode 100644index 4dca2f924..000000000--- a/infra/relay/migrations/postgres/20260727115225_migration/snapshot.json+++ /dev/null@@ -1,1545 +0,0 @@-{- "dialect": "postgres",- "id": "33575636-77b2-4756-8658-687165e6c9ff",- "prevIds": ["f4151a65-091a-4601-bde8-029b155255b0"],- "version": "8",- "ddl": [- {- "isRlsEnabled": false,- "name": "relay_agent_activity_rows",- "entityType": "tables",- "schema": "public"- },- {- "isRlsEnabled": false,- "name": "relay_delivery_attempts",- "entityType": "tables",- "schema": "public"- },- {- "isRlsEnabled": false,- "name": "relay_dpop_proofs",- "entityType": "tables",- "schema": "public"- },- {- "isRlsEnabled": false,- "name": "relay_environment_credentials",- "entityType": "tables",- "schema": "public"- },- {- "isRlsEnabled": false,- "name": "relay_environment_links",- "entityType": "tables",- "schema": "public"- },- {- "isRlsEnabled": false,- "name": "relay_live_activities",- "entityType": "tables",- "schema": "public"- },- {- "isRlsEnabled": false,- "name": "relay_managed_endpoint_allocations",- "entityType": "tables",- "schema": "public"- },- {- "isRlsEnabled": false,- "name": "relay_managed_tunnel_limits",- "entityType": "tables",- "schema": "public"- },- {- "isRlsEnabled": false,- "name": "relay_mobile_devices",- "entityType": "tables",- "schema": "public"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "environment_id",- "entityType": "columns",- "schema": "public",- "table": "relay_agent_activity_rows"- },- {- "type": "text",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "environment_public_key",- "entityType": "columns",- "schema": "public",- "table": "relay_agent_activity_rows"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "thread_id",- "entityType": "columns",- "schema": "public",- "table": "relay_agent_activity_rows"- },- {- "type": "jsonb",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "state_json",- "entityType": "columns",- "schema": "public",- "table": "relay_agent_activity_rows"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "updated_at",- "entityType": "columns",- "schema": "public",- "table": "relay_agent_activity_rows"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_at",- "entityType": "columns",- "schema": "public",- "table": "relay_agent_activity_rows"- },- {- "type": "varchar(36)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "id",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_at",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(255)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "user_id",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "environment_id",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "thread_id",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(255)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "device_id",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "kind",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "source_job_id",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(16)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "token_suffix",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "integer",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "apns_status",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "text",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "apns_reason",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(128)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "apns_id",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "text",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "transport_error",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(128)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "thumbprint",- "entityType": "columns",- "schema": "public",- "table": "relay_dpop_proofs"- },- {- "type": "varchar(255)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "jti",- "entityType": "columns",- "schema": "public",- "table": "relay_dpop_proofs"- },- {- "type": "integer",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "iat",- "entityType": "columns",- "schema": "public",- "table": "relay_dpop_proofs"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "expires_at",- "entityType": "columns",- "schema": "public",- "table": "relay_dpop_proofs"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_at",- "entityType": "columns",- "schema": "public",- "table": "relay_dpop_proofs"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "credential_id",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "environment_id",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "type": "text",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "environment_public_key",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "credential_hash",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "revoked_at",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_at",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "updated_at",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "user_id",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "environment_id",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "text",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": "'T3 Environment'",- "generated": null,- "identity": null,- "name": "environment_label",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "text",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "environment_public_key",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "text",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "endpoint_http_base_url",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "text",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "endpoint_ws_base_url",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "varchar(32)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "endpoint_provider_kind",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "boolean",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": "true",- "generated": null,- "identity": null,- "name": "notifications_enabled",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "boolean",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": "true",- "generated": null,- "identity": null,- "name": "live_activities_enabled",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "boolean",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": "false",- "generated": null,- "identity": null,- "name": "managed_tunnels_enabled",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_by_device_id",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "revoked_at",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_at",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "updated_at",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "varchar(255)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "user_id",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "varchar(255)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "device_id",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "text",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "activity_push_token",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "remote_start_queued_at",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "remote_started_at",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "ended_at",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "jsonb",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "last_aggregate_json",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "last_live_activity_delivery_at",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_at",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "updated_at",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "user_id",- "entityType": "columns",- "schema": "public",- "table": "relay_managed_endpoint_allocations"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "environment_id",- "entityType": "columns",- "schema": "public",- "table": "relay_managed_endpoint_allocations"- },- {- "type": "text",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "hostname",- "entityType": "columns",- "schema": "public",- "table": "relay_managed_endpoint_allocations"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "tunnel_id",- "entityType": "columns",- "schema": "public",- "table": "relay_managed_endpoint_allocations"- },- {- "type": "text",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "tunnel_name",- "entityType": "columns",- "schema": "public",- "table": "relay_managed_endpoint_allocations"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "dns_record_id",- "entityType": "columns",- "schema": "public",- "table": "relay_managed_endpoint_allocations"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "ready_at",- "entityType": "columns",- "schema": "public",- "table": "relay_managed_endpoint_allocations"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_at",- "entityType": "columns",- "schema": "public",- "table": "relay_managed_endpoint_allocations"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "updated_at",- "entityType": "columns",- "schema": "public",- "table": "relay_managed_endpoint_allocations"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "user_id",- "entityType": "columns",- "schema": "public",- "table": "relay_managed_tunnel_limits"- },- {- "type": "integer",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "max_tunnels",- "entityType": "columns",- "schema": "public",- "table": "relay_managed_tunnel_limits"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_at",- "entityType": "columns",- "schema": "public",- "table": "relay_managed_tunnel_limits"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "updated_at",- "entityType": "columns",- "schema": "public",- "table": "relay_managed_tunnel_limits"- },- {- "type": "varchar(255)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "user_id",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "varchar(255)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "device_id",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "text",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": "'iOS device'",- "generated": null,- "identity": null,- "name": "label",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "varchar(16)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "platform",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "integer",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "ios_major_version",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "app_version",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "varchar(255)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "bundle_id",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "varchar(16)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "aps_environment",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "text",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "push_token",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "text",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "push_to_start_token",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "jsonb",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "preferences_json",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_at",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "updated_at",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "nameExplicit": true,- "columns": [- {- "value": "updated_at",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": false,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_agent_activity_rows_updated",- "entityType": "indexes",- "schema": "public",- "table": "relay_agent_activity_rows"- },- {- "nameExplicit": true,- "columns": [- {- "value": "environment_id",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- },- {- "value": "thread_id",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- },- {- "value": "created_at",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": false,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_delivery_attempts_environment",- "entityType": "indexes",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "nameExplicit": true,- "columns": [- {- "value": "source_job_id",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": true,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_delivery_attempts_source_job",- "entityType": "indexes",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "nameExplicit": true,- "columns": [- {- "value": "expires_at",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": false,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_dpop_proofs_expires_at",- "entityType": "indexes",- "schema": "public",- "table": "relay_dpop_proofs"- },- {- "nameExplicit": true,- "columns": [- {- "value": "credential_hash",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": true,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_environment_credentials_hash",- "entityType": "indexes",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "nameExplicit": true,- "columns": [- {- "value": "environment_id",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- },- {- "value": "revoked_at",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": false,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_environment_credentials_environment",- "entityType": "indexes",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "nameExplicit": true,- "columns": [- {- "value": "environment_id",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- },- {- "value": "environment_public_key",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- },- {- "value": "revoked_at",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": false,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_environment_credentials_environment_key",- "entityType": "indexes",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "nameExplicit": true,- "columns": [- {- "value": "environment_id",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- },- {- "value": "revoked_at",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": false,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_environment_links_environment",- "entityType": "indexes",- "schema": "public",- "table": "relay_environment_links"- },- {- "nameExplicit": true,- "columns": [- {- "value": "user_id",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": false,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_live_activities_user",- "entityType": "indexes",- "schema": "public",- "table": "relay_live_activities"- },- {- "nameExplicit": true,- "columns": [- {- "value": "activity_push_token",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": true,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_live_activities_activity_push_token",- "entityType": "indexes",- "schema": "public",- "table": "relay_live_activities"- },- {- "nameExplicit": true,- "columns": [- {- "value": "hostname",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": true,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_managed_endpoint_allocations_hostname",- "entityType": "indexes",- "schema": "public",- "table": "relay_managed_endpoint_allocations"- },- {- "nameExplicit": true,- "columns": [- {- "value": "tunnel_name",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": true,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_managed_endpoint_allocations_tunnel_name",- "entityType": "indexes",- "schema": "public",- "table": "relay_managed_endpoint_allocations"- },- {- "nameExplicit": true,- "columns": [- {- "value": "user_id",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": false,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_mobile_devices_user",- "entityType": "indexes",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "nameExplicit": true,- "columns": [- {- "value": "push_token",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": true,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_mobile_devices_push_token",- "entityType": "indexes",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "nameExplicit": true,- "columns": [- {- "value": "push_to_start_token",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": true,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_mobile_devices_push_to_start_token",- "entityType": "indexes",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "columns": ["environment_id", "environment_public_key", "thread_id"],- "nameExplicit": false,- "name": "relay_agent_activity_rows_pkey",- "entityType": "pks",- "schema": "public",- "table": "relay_agent_activity_rows"- },- {- "columns": ["thumbprint", "jti"],- "nameExplicit": false,- "name": "relay_dpop_proofs_pkey",- "entityType": "pks",- "schema": "public",- "table": "relay_dpop_proofs"- },- {- "columns": ["user_id", "environment_id"],- "nameExplicit": false,- "name": "relay_environment_links_pkey",- "entityType": "pks",- "schema": "public",- "table": "relay_environment_links"- },- {- "columns": ["user_id", "device_id"],- "nameExplicit": false,- "name": "relay_live_activities_pkey",- "entityType": "pks",- "schema": "public",- "table": "relay_live_activities"- },- {- "columns": ["user_id", "environment_id"],- "nameExplicit": false,- "name": "relay_managed_endpoint_allocations_pkey",- "entityType": "pks",- "schema": "public",- "table": "relay_managed_endpoint_allocations"- },- {- "columns": ["user_id", "device_id"],- "nameExplicit": false,- "name": "relay_mobile_devices_pkey",- "entityType": "pks",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "columns": ["id"],- "nameExplicit": false,- "name": "relay_delivery_attempts_pkey",- "schema": "public",- "table": "relay_delivery_attempts",- "entityType": "pks"- },- {- "columns": ["credential_id"],- "nameExplicit": false,- "name": "relay_environment_credentials_pkey",- "schema": "public",- "table": "relay_environment_credentials",- "entityType": "pks"- },- {- "columns": ["user_id"],- "nameExplicit": false,- "name": "relay_managed_tunnel_limits_pkey",- "schema": "public",- "table": "relay_managed_tunnel_limits",- "entityType": "pks"- }- ],- "renames": []-}diff --git a/infra/relay/migrations/postgres/20260727144838_migration/migration.sql b/infra/relay/migrations/postgres/20260727144838_migration/migration.sqldeleted file mode 100644index 02c54cb59..000000000--- a/infra/relay/migrations/postgres/20260727144838_migration/migration.sql+++ /dev/null@@ -1,3 +0,0 @@-DROP INDEX "idx_relay_live_activities_user";---> statement-breakpoint-DROP INDEX "idx_relay_mobile_devices_user";diff --git a/infra/relay/migrations/postgres/20260727144838_migration/snapshot.json b/infra/relay/migrations/postgres/20260727144838_migration/snapshot.jsondeleted file mode 100644index d5be365ee..000000000--- a/infra/relay/migrations/postgres/20260727144838_migration/snapshot.json+++ /dev/null@@ -1,1503 +0,0 @@-{- "dialect": "postgres",- "id": "2374caff-40bf-423c-9255-55e76dddbc2a",- "prevIds": ["33575636-77b2-4756-8658-687165e6c9ff"],- "version": "8",- "ddl": [- {- "isRlsEnabled": false,- "name": "relay_agent_activity_rows",- "entityType": "tables",- "schema": "public"- },- {- "isRlsEnabled": false,- "name": "relay_delivery_attempts",- "entityType": "tables",- "schema": "public"- },- {- "isRlsEnabled": false,- "name": "relay_dpop_proofs",- "entityType": "tables",- "schema": "public"- },- {- "isRlsEnabled": false,- "name": "relay_environment_credentials",- "entityType": "tables",- "schema": "public"- },- {- "isRlsEnabled": false,- "name": "relay_environment_links",- "entityType": "tables",- "schema": "public"- },- {- "isRlsEnabled": false,- "name": "relay_live_activities",- "entityType": "tables",- "schema": "public"- },- {- "isRlsEnabled": false,- "name": "relay_managed_endpoint_allocations",- "entityType": "tables",- "schema": "public"- },- {- "isRlsEnabled": false,- "name": "relay_managed_tunnel_limits",- "entityType": "tables",- "schema": "public"- },- {- "isRlsEnabled": false,- "name": "relay_mobile_devices",- "entityType": "tables",- "schema": "public"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "environment_id",- "entityType": "columns",- "schema": "public",- "table": "relay_agent_activity_rows"- },- {- "type": "text",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "environment_public_key",- "entityType": "columns",- "schema": "public",- "table": "relay_agent_activity_rows"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "thread_id",- "entityType": "columns",- "schema": "public",- "table": "relay_agent_activity_rows"- },- {- "type": "jsonb",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "state_json",- "entityType": "columns",- "schema": "public",- "table": "relay_agent_activity_rows"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "updated_at",- "entityType": "columns",- "schema": "public",- "table": "relay_agent_activity_rows"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_at",- "entityType": "columns",- "schema": "public",- "table": "relay_agent_activity_rows"- },- {- "type": "varchar(36)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "id",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_at",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(255)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "user_id",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "environment_id",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "thread_id",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(255)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "device_id",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "kind",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "source_job_id",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(16)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "token_suffix",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "integer",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "apns_status",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "text",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "apns_reason",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(128)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "apns_id",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "text",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "transport_error",- "entityType": "columns",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "type": "varchar(128)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "thumbprint",- "entityType": "columns",- "schema": "public",- "table": "relay_dpop_proofs"- },- {- "type": "varchar(255)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "jti",- "entityType": "columns",- "schema": "public",- "table": "relay_dpop_proofs"- },- {- "type": "integer",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "iat",- "entityType": "columns",- "schema": "public",- "table": "relay_dpop_proofs"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "expires_at",- "entityType": "columns",- "schema": "public",- "table": "relay_dpop_proofs"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_at",- "entityType": "columns",- "schema": "public",- "table": "relay_dpop_proofs"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "credential_id",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "environment_id",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "type": "text",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "environment_public_key",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "credential_hash",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "revoked_at",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_at",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "updated_at",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "user_id",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "environment_id",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "text",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": "'T3 Environment'",- "generated": null,- "identity": null,- "name": "environment_label",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "text",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "environment_public_key",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "text",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "endpoint_http_base_url",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "text",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "endpoint_ws_base_url",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "varchar(32)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "endpoint_provider_kind",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "boolean",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": "true",- "generated": null,- "identity": null,- "name": "notifications_enabled",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "boolean",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": "true",- "generated": null,- "identity": null,- "name": "live_activities_enabled",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "boolean",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": "false",- "generated": null,- "identity": null,- "name": "managed_tunnels_enabled",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_by_device_id",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "revoked_at",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_at",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "updated_at",- "entityType": "columns",- "schema": "public",- "table": "relay_environment_links"- },- {- "type": "varchar(255)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "user_id",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "varchar(255)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "device_id",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "text",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "activity_push_token",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "remote_start_queued_at",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "remote_started_at",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "ended_at",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "jsonb",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "last_aggregate_json",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "last_live_activity_delivery_at",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_at",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "updated_at",- "entityType": "columns",- "schema": "public",- "table": "relay_live_activities"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "user_id",- "entityType": "columns",- "schema": "public",- "table": "relay_managed_endpoint_allocations"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "environment_id",- "entityType": "columns",- "schema": "public",- "table": "relay_managed_endpoint_allocations"- },- {- "type": "text",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "hostname",- "entityType": "columns",- "schema": "public",- "table": "relay_managed_endpoint_allocations"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "tunnel_id",- "entityType": "columns",- "schema": "public",- "table": "relay_managed_endpoint_allocations"- },- {- "type": "text",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "tunnel_name",- "entityType": "columns",- "schema": "public",- "table": "relay_managed_endpoint_allocations"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "dns_record_id",- "entityType": "columns",- "schema": "public",- "table": "relay_managed_endpoint_allocations"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "ready_at",- "entityType": "columns",- "schema": "public",- "table": "relay_managed_endpoint_allocations"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_at",- "entityType": "columns",- "schema": "public",- "table": "relay_managed_endpoint_allocations"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "updated_at",- "entityType": "columns",- "schema": "public",- "table": "relay_managed_endpoint_allocations"- },- {- "type": "varchar(191)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "user_id",- "entityType": "columns",- "schema": "public",- "table": "relay_managed_tunnel_limits"- },- {- "type": "integer",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "max_tunnels",- "entityType": "columns",- "schema": "public",- "table": "relay_managed_tunnel_limits"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_at",- "entityType": "columns",- "schema": "public",- "table": "relay_managed_tunnel_limits"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "updated_at",- "entityType": "columns",- "schema": "public",- "table": "relay_managed_tunnel_limits"- },- {- "type": "varchar(255)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "user_id",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "varchar(255)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "device_id",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "text",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": "'iOS device'",- "generated": null,- "identity": null,- "name": "label",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "varchar(16)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "platform",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "integer",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "ios_major_version",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "app_version",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "varchar(255)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "bundle_id",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "varchar(16)",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "aps_environment",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "text",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "push_token",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "text",- "typeSchema": null,- "notNull": false,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "push_to_start_token",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "jsonb",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "preferences_json",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "created_at",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "type": "varchar(64)",- "typeSchema": null,- "notNull": true,- "dimensions": 0,- "default": null,- "generated": null,- "identity": null,- "name": "updated_at",- "entityType": "columns",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "nameExplicit": true,- "columns": [- {- "value": "updated_at",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": false,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_agent_activity_rows_updated",- "entityType": "indexes",- "schema": "public",- "table": "relay_agent_activity_rows"- },- {- "nameExplicit": true,- "columns": [- {- "value": "environment_id",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- },- {- "value": "thread_id",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- },- {- "value": "created_at",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": false,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_delivery_attempts_environment",- "entityType": "indexes",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "nameExplicit": true,- "columns": [- {- "value": "source_job_id",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": true,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_delivery_attempts_source_job",- "entityType": "indexes",- "schema": "public",- "table": "relay_delivery_attempts"- },- {- "nameExplicit": true,- "columns": [- {- "value": "expires_at",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": false,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_dpop_proofs_expires_at",- "entityType": "indexes",- "schema": "public",- "table": "relay_dpop_proofs"- },- {- "nameExplicit": true,- "columns": [- {- "value": "credential_hash",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": true,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_environment_credentials_hash",- "entityType": "indexes",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "nameExplicit": true,- "columns": [- {- "value": "environment_id",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- },- {- "value": "revoked_at",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": false,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_environment_credentials_environment",- "entityType": "indexes",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "nameExplicit": true,- "columns": [- {- "value": "environment_id",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- },- {- "value": "environment_public_key",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- },- {- "value": "revoked_at",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": false,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_environment_credentials_environment_key",- "entityType": "indexes",- "schema": "public",- "table": "relay_environment_credentials"- },- {- "nameExplicit": true,- "columns": [- {- "value": "environment_id",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- },- {- "value": "revoked_at",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": false,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_environment_links_environment",- "entityType": "indexes",- "schema": "public",- "table": "relay_environment_links"- },- {- "nameExplicit": true,- "columns": [- {- "value": "activity_push_token",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": true,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_live_activities_activity_push_token",- "entityType": "indexes",- "schema": "public",- "table": "relay_live_activities"- },- {- "nameExplicit": true,- "columns": [- {- "value": "hostname",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": true,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_managed_endpoint_allocations_hostname",- "entityType": "indexes",- "schema": "public",- "table": "relay_managed_endpoint_allocations"- },- {- "nameExplicit": true,- "columns": [- {- "value": "tunnel_name",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": true,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_managed_endpoint_allocations_tunnel_name",- "entityType": "indexes",- "schema": "public",- "table": "relay_managed_endpoint_allocations"- },- {- "nameExplicit": true,- "columns": [- {- "value": "push_token",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": true,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_mobile_devices_push_token",- "entityType": "indexes",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "nameExplicit": true,- "columns": [- {- "value": "push_to_start_token",- "isExpression": false,- "asc": true,- "nullsFirst": false,- "opclass": null- }- ],- "isUnique": true,- "where": null,- "with": "",- "method": "btree",- "concurrently": false,- "name": "idx_relay_mobile_devices_push_to_start_token",- "entityType": "indexes",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "columns": ["environment_id", "environment_public_key", "thread_id"],- "nameExplicit": false,- "name": "relay_agent_activity_rows_pkey",- "entityType": "pks",- "schema": "public",- "table": "relay_agent_activity_rows"- },- {- "columns": ["thumbprint", "jti"],- "nameExplicit": false,- "name": "relay_dpop_proofs_pkey",- "entityType": "pks",- "schema": "public",- "table": "relay_dpop_proofs"- },- {- "columns": ["user_id", "environment_id"],- "nameExplicit": false,- "name": "relay_environment_links_pkey",- "entityType": "pks",- "schema": "public",- "table": "relay_environment_links"- },- {- "columns": ["user_id", "device_id"],- "nameExplicit": false,- "name": "relay_live_activities_pkey",- "entityType": "pks",- "schema": "public",- "table": "relay_live_activities"- },- {- "columns": ["user_id", "environment_id"],- "nameExplicit": false,- "name": "relay_managed_endpoint_allocations_pkey",- "entityType": "pks",- "schema": "public",- "table": "relay_managed_endpoint_allocations"- },- {- "columns": ["user_id", "device_id"],- "nameExplicit": false,- "name": "relay_mobile_devices_pkey",- "entityType": "pks",- "schema": "public",- "table": "relay_mobile_devices"- },- {- "columns": ["id"],- "nameExplicit": false,- "name": "relay_delivery_attempts_pkey",- "schema": "public",- "table": "relay_delivery_attempts",- "entityType": "pks"- },- {- "columns": ["credential_id"],- "nameExplicit": false,- "name": "relay_environment_credentials_pkey",- "schema": "public",- "table": "relay_environment_credentials",- "entityType": "pks"- },- {- "columns": ["user_id"],- "nameExplicit": false,- "name": "relay_managed_tunnel_limits_pkey",- "schema": "public",- "table": "relay_managed_tunnel_limits",- "entityType": "pks"- }- ],- "renames": []-}diff --git a/infra/relay/package.json b/infra/relay/package.jsondeleted file mode 100644index 4e9519671..000000000--- a/infra/relay/package.json+++ /dev/null@@ -1,32 +0,0 @@-{- "name": "t3code-relay",- "private": true,- "type": "module",- "scripts": {- "deploy": "node -- scripts/deploy.ts",- "destroy": "alchemy destroy",- "test": "vp test run",- "typecheck": "tsgo --noEmit"- },- "dependencies": {- "@clerk/backend": "catalog:",- "@effect/sql-pg": "catalog:",- "@noble/curves": "catalog:",- "@noble/hashes": "catalog:",- "@t3tools/client-runtime": "workspace:*",- "@t3tools/contracts": "workspace:*",- "@t3tools/shared": "workspace:*",- "alchemy": "2.0.0-beta.65",- "drizzle-orm": "1.0.0-rc.4",- "effect": "catalog:"- },- "devDependencies": {- "@cloudflare/workers-types": "^4.20260601.1",- "@effect/platform-node": "catalog:",- "@effect/vitest": "catalog:",- "@types/node": "catalog:",- "drizzle-kit": "1.0.0-rc.4",- "vite": "catalog:",- "vite-plus": "catalog:"- }-}diff --git a/infra/relay/scripts/deploy.test.ts b/infra/relay/scripts/deploy.test.tsdeleted file mode 100644index 4447c3493..000000000--- a/infra/relay/scripts/deploy.test.ts+++ /dev/null@@ -1,227 +0,0 @@-import * as NodeServices from "@effect/platform-node/NodeServices";-import { describe, expect, it } from "@effect/vitest";-import * as Effect from "effect/Effect";-import * as FileSystem from "effect/FileSystem";-import * as Path from "effect/Path";--import {- hasDeployChanges,- missingRelayPublicConfigFields,- publicConfigFromOutput,- reconcileRootEnvPublicConfig,- RelayDeployError,- RelayDeployPublicConfigUnavailableError,- serializeGithubOutput,- serializeRelayClientTracingEnvironment,-} from "./deploy.ts";--describe("RelayDeployError", () => {- it("reports the incomplete state source, stage, and missing fields", () => {- const missingFields = missingRelayPublicConfigFields({- url: "https://relay.example.test",- mobileTracingUrl: "https://api.axiom.co/v1/traces",- });- const error = new RelayDeployError({- source: "alchemy_state",- stage: "production",- missingFields,- });-- expect(error).toMatchObject({- source: "alchemy_state",- stage: "production",- missingFields: [- "mobileTracingDataset",- "mobileTracingToken",- "clientTracingUrl",- "clientTracingDataset",- "clientTracingToken",- ],- });- expect(error.message).toBe(- "Relay deploy output from 'alchemy_state' for stage 'production' is missing required public config fields: mobileTracingDataset, mobileTracingToken, clientTracingUrl, clientTracingDataset, clientTracingToken",- );- });-- it("distinguishes deploy results that do not produce public config", () => {- const error = new RelayDeployPublicConfigUnavailableError({- result: "dry-run",- stage: "production",- outputPath: "/tmp/relay-client.env",- });-- expect(error.message).toBe(- "Relay deploy result 'dry-run' for stage 'production' did not produce public config required by GitHub environment output '/tmp/relay-client.env'.",- );- });-});--describe("hasDeployChanges", () => {- it("detects resource, binding, and deletion changes", () => {- expect(hasDeployChanges({ resources: {}, deletions: {} } as never)).toBe(false);- expect(- hasDeployChanges({- resources: {- api: { action: "create", bindings: [] },- },- deletions: {},- } as never),- ).toBe(true);- expect(- hasDeployChanges({- resources: {- api: { action: "noop", bindings: [{ action: "update" }] },- },- deletions: {},- } as never),- ).toBe(true);- expect(- hasDeployChanges({- resources: {},- deletions: {- api: { action: "delete", bindings: [] },- },- } as never),- ).toBe(true);- });-});--describe("reconcileRootEnvPublicConfig", () => {- const config = {- relayUrl: "https://relay.example.test",- mobileTracingUrl: "https://api.axiom.co/v1/traces",- mobileTracingDataset: "t3-code-mobile-traces-dev",- mobileTracingToken: "xaat-public-ingest",- clientTracingUrl: "https://api.axiom.co/v1/traces",- clientTracingDataset: "t3-code-relay-client-traces-dev",- clientTracingToken: "xaat-relay-client-ingest",- } as const;-- it("adds the complete local client config", () => {- expect(reconcileRootEnvPublicConfig("", config)).toBe(- [- "T3CODE_RELAY_URL=https://relay.example.test",- "T3CODE_MOBILE_OTLP_TRACES_URL=https://api.axiom.co/v1/traces",- "T3CODE_MOBILE_OTLP_TRACES_DATASET=t3-code-mobile-traces-dev",- "T3CODE_MOBILE_OTLP_TRACES_TOKEN=xaat-public-ingest",- "T3CODE_RELAY_CLIENT_OTLP_TRACES_URL=https://api.axiom.co/v1/traces",- "T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET=t3-code-relay-client-traces-dev",- "T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=xaat-relay-client-ingest",- "",- ].join("\n"),- );- });-- it("replaces stale values while preserving unrelated entries", () => {- expect(- reconcileRootEnvPublicConfig(- [- "T3CODE_CLERK_PUBLISHABLE_KEY=pk_test_example",- "T3CODE_RELAY_URL=https://old.example.test",- "T3CODE_MOBILE_OTLP_TRACES_URL=https://old.example.test/v1/traces",- "T3CODE_MOBILE_OTLP_TRACES_DATASET=old-dataset",- "T3CODE_MOBILE_OTLP_TRACES_TOKEN=old-token",- "T3CODE_RELAY_CLIENT_OTLP_TRACES_URL=https://old.example.test/v1/traces",- "T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET=old-client-dataset",- "T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=old-client-token",- "",- ].join("\n"),- config,- ),- ).toBe(- [- "T3CODE_CLERK_PUBLISHABLE_KEY=pk_test_example",- "T3CODE_RELAY_URL=https://relay.example.test",- "T3CODE_MOBILE_OTLP_TRACES_URL=https://api.axiom.co/v1/traces",- "T3CODE_MOBILE_OTLP_TRACES_DATASET=t3-code-mobile-traces-dev",- "T3CODE_MOBILE_OTLP_TRACES_TOKEN=xaat-public-ingest",- "T3CODE_RELAY_CLIENT_OTLP_TRACES_URL=https://api.axiom.co/v1/traces",- "T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET=t3-code-relay-client-traces-dev",- "T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=xaat-relay-client-ingest",- "",- ].join("\n"),- );- });-});--describe("serializeGithubOutput", () => {- it("serializes relay deploy metadata for GitHub Actions outputs", () => {- expect(- serializeGithubOutput({- changed: false,- result: "noop",- relay_url: "https://relay.example.test",- }),- ).toBe("changed=false\nresult=noop\nrelay_url=https://relay.example.test\n");- });-});--describe("serializeRelayClientTracingEnvironment", () => {- it("serializes tracing config for downstream GITHUB_ENV loading", () => {- expect(- serializeRelayClientTracingEnvironment({- relayUrl: "https://relay.example.test",- mobileTracingUrl: "https://api.axiom.co/v1/traces",- mobileTracingDataset: "mobile",- mobileTracingToken: "mobile-token",- clientTracingUrl: "https://api.axiom.co/v1/traces",- clientTracingDataset: "relay",- clientTracingToken: "client-token",- }),- ).toBe(- [- "T3CODE_RELAY_CLIENT_OTLP_TRACES_URL=https://api.axiom.co/v1/traces",- "T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET=relay",- "T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN=client-token",- "",- ].join("\n"),- );- });-});--describe("release workflow tracing config propagation", () => {- it.effect("uses an artifact instead of a masked cross-job token output", () =>- Effect.gen(function* () {- const fileSystem = yield* FileSystem.FileSystem;- const path = yield* Path.Path;- const workflowPath = yield* path.fromFileUrl(- new URL("../../../.github/workflows/release.yml", import.meta.url),- );- const workflow = yield* fileSystem.readFileString(workflowPath);-- expect(workflow).not.toContain("client_tracing_token:");- expect(workflow).not.toContain("needs.relay_public_config.outputs.client_tracing_token");- expect(workflow).toContain('--github-env-file "$RUNNER_TEMP/relay-client-tracing.env"');- expect(workflow).toContain("name: relay-client-tracing-config");- expect(workflow).toContain('cat "$config_path" >> "$GITHUB_ENV"');- }).pipe(Effect.provide(NodeServices.layer)),- );-});--describe("publicConfigFromOutput", () => {- it("reads the complete public tracing config from persisted Alchemy output", () => {- expect(- publicConfigFromOutput({- url: "https://relay.example.test",- mobileTracingUrl: "https://api.axiom.co/v1/traces",- mobileTracingDataset: "mobile",- mobileTracingToken: "mobile-token",- clientTracingUrl: "https://api.axiom.co/v1/traces",- clientTracingDataset: "relay",- clientTracingToken: "client-token",- }),- ).toEqual({- relayUrl: "https://relay.example.test",- mobileTracingUrl: "https://api.axiom.co/v1/traces",- mobileTracingDataset: "mobile",- mobileTracingToken: "mobile-token",- clientTracingUrl: "https://api.axiom.co/v1/traces",- clientTracingDataset: "relay",- clientTracingToken: "client-token",- });- });-- it("rejects incomplete stack output", () => {- expect(publicConfigFromOutput({ url: "https://relay.example.test" })).toBeNull();- });-});diff --git a/infra/relay/scripts/deploy.ts b/infra/relay/scripts/deploy.tsdeleted file mode 100644index 1942b8735..000000000--- a/infra/relay/scripts/deploy.ts+++ /dev/null@@ -1,501 +0,0 @@-#!/usr/bin/env node--import * as NodeRuntime from "@effect/platform-node/NodeRuntime";-import { AdoptPolicy } from "alchemy/AdoptPolicy";-import { AlchemyContext, AlchemyContextLive } from "alchemy/AlchemyContext";-import * as Apply from "alchemy/Apply";-import { ArtifactStore, createArtifactStore, provideFreshArtifactStore } from "alchemy/Artifacts";-import { AuthProviders } from "alchemy/Auth/AuthProvider";-import { CredentialsStoreLive } from "alchemy/Auth/Credentials";-import { ProfileLive } from "alchemy/Auth/Profile";-import * as Cloudflare from "alchemy/Cloudflare";-import { Cli } from "alchemy/Cli/Cli";-import { LoggingCli } from "alchemy/Cli/LoggingCli";-import * as Plan from "alchemy/Plan";-import * as Stage from "alchemy/Stage";-import * as State from "alchemy/State/State";-import { TelemetryLive } from "alchemy/Telemetry/Layer";-import { PlatformServices } from "alchemy/Util/PlatformServices";-import * as Config from "effect/Config";-import * as ConfigProvider from "effect/ConfigProvider";-import * as Console from "effect/Console";-import * as Effect from "effect/Effect";-import * as FileSystem from "effect/FileSystem";-import * as Layer from "effect/Layer";-import * as Option from "effect/Option";-import * as Path from "effect/Path";-import * as Redacted from "effect/Redacted";-import * as Schema from "effect/Schema";-import { Command, Flag, Prompt } from "effect/unstable/cli";-import * as FetchHttpClient from "effect/unstable/http/FetchHttpClient";--import RelayStack from "../alchemy.run.ts";--const relayDeployOutputFields = [- "url",- "mobileTracingUrl",- "mobileTracingDataset",- "mobileTracingToken",- "clientTracingUrl",- "clientTracingDataset",- "clientTracingToken",-] as const;--export const RelayDeployOutputField = Schema.Literals(relayDeployOutputFields);-export type RelayDeployOutputField = typeof RelayDeployOutputField.Type;--export const RelayDeployResult = Schema.Literals([- "applied",- "noop",- "dry-run",- "cancelled",- "state",-]);-export type RelayDeployResult = typeof RelayDeployResult.Type;--export class RelayDeployError extends Schema.TaggedErrorClass<RelayDeployError>()(- "RelayDeployError",- {- source: Schema.Literals(["alchemy_state", "alchemy_apply"]),- stage: Schema.String,- missingFields: Schema.Array(RelayDeployOutputField),- },-) {- override get message(): string {- return `Relay deploy output from '${this.source}' for stage '${this.stage}' is missing required public config fields: ${this.missingFields.join(", ")}`;- }-}--export class RelayDeployPublicConfigUnavailableError extends Schema.TaggedErrorClass<RelayDeployPublicConfigUnavailableError>()(- "RelayDeployPublicConfigUnavailableError",- {- result: RelayDeployResult,- stage: Schema.String,- outputPath: Schema.String,- },-) {- override get message(): string {- return `Relay deploy result '${this.result}' for stage '${this.stage}' did not produce public config required by GitHub environment output '${this.outputPath}'.`;- }-}--export interface RelayDeployOptions {- readonly dryRun: boolean;- readonly force: boolean;- readonly envFile: Option.Option<string>;- readonly stage: Option.Option<string>;- readonly yes: boolean;- readonly adopt: boolean;- readonly githubOutput: boolean;- readonly githubEnvFile: Option.Option<string>;- readonly readState: boolean;-}--export interface RelayPublicConfig {- readonly relayUrl: string;- readonly mobileTracingUrl: string;- readonly mobileTracingDataset: string;- readonly mobileTracingToken: string;- readonly clientTracingUrl: string;- readonly clientTracingDataset: string;- readonly clientTracingToken: string;-}--const publicConfigEnvEntries = (config: RelayPublicConfig) =>- ({- T3CODE_RELAY_URL: config.relayUrl,- T3CODE_MOBILE_OTLP_TRACES_URL: config.mobileTracingUrl,- T3CODE_MOBILE_OTLP_TRACES_DATASET: config.mobileTracingDataset,- T3CODE_MOBILE_OTLP_TRACES_TOKEN: config.mobileTracingToken,- T3CODE_RELAY_CLIENT_OTLP_TRACES_URL: config.clientTracingUrl,- T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET: config.clientTracingDataset,- T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN: config.clientTracingToken,- }) as const;--export function reconcileRootEnvPublicConfig(contents: string, config: RelayPublicConfig): string {- let next = contents;- for (const [name, value] of Object.entries(publicConfigEnvEntries(config))) {- const entry = `${name}=${value}`;- const pattern = new RegExp(`^${name}=.*$`, "mu");- if (pattern.test(next)) {- next = next.replace(pattern, entry);- continue;- }- if (!next) {- next = `${entry}\n`;- continue;- }- next = `${next}${next.endsWith("\n") ? "" : "\n"}${entry}\n`;- }- return next;-}--export function reconcileRootEnvRelayUrl(contents: string, relayUrl: string): string {- return reconcileRootEnvPublicConfig(contents, {- relayUrl,- mobileTracingUrl: "",- mobileTracingDataset: "",- mobileTracingToken: "",- clientTracingUrl: "",- clientTracingDataset: "",- clientTracingToken: "",- })- .split("\n")- .filter((line) => !line.startsWith("T3CODE_MOBILE_OTLP_TRACES_"))- .filter((line) => !line.startsWith("T3CODE_RELAY_CLIENT_OTLP_TRACES_"))- .join("\n");-}--export function hasDeployChanges(plan: Plan.Plan): boolean {- return (- Object.keys(plan.deletions).length > 0 ||- Object.values(plan.resources).some(- (node) =>- node.action !== "noop" || node.bindings.some((binding) => binding.action !== "noop"),- )- );-}--export interface RelayDeployOutcome {- readonly result: RelayDeployResult;- readonly changed: boolean;- readonly publicConfig: Option.Option<RelayPublicConfig>;-}--export function serializeGithubOutput(entries: Readonly<Record<string, string | boolean>>): string {- return Object.entries(entries)- .map(([key, value]) => `${key}=${value}\n`)- .join("");-}--export function serializeRelayClientTracingEnvironment(config: RelayPublicConfig): string {- return serializeGithubOutput({- T3CODE_RELAY_CLIENT_OTLP_TRACES_URL: config.clientTracingUrl,- T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET: config.clientTracingDataset,- T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN: config.clientTracingToken,- });-}--const relayRoot = Effect.service(Path.Path).pipe(- Effect.flatMap((path) => path.fromFileUrl(new URL("..", import.meta.url))),-);-const repoRoot = Effect.service(Path.Path).pipe(- Effect.flatMap((path) => path.fromFileUrl(new URL("../../..", import.meta.url))),-);--const loadDeployConfigProvider = Effect.fn("relay.deploy.loadConfigProvider")(function* (- envFileOverride: Option.Option<string>,-) {- const path = yield* Path.Path;- const root = yield* relayRoot;-- if (Option.isSome(envFileOverride)) {- return yield* ConfigProvider.fromDotEnv({ path: path.resolve(root, envFileOverride.value) });- }-- return yield* ConfigProvider.fromDotEnv({ path: path.join(root, ".env") }).pipe(- Effect.orElseSucceed(() => ConfigProvider.fromEnv()),- );-});--const relayDeployStage = Config.nonEmptyString("stage").pipe(- Config.option,- Config.map(- Option.getOrElse(() => `dev_${process.env.USER ?? process.env.USERNAME ?? "unknown"}`),- ),-);--const reconcileRootEnv = Effect.fn("relay.deploy.reconcileRootEnv")(function* (- config: RelayPublicConfig,-) {- const fs = yield* FileSystem.FileSystem;- const path = yield* Path.Path;- const root = yield* repoRoot;- const rootEnvPath = path.join(root, ".env");- const contents = (yield* fs.exists(rootEnvPath)) ? yield* fs.readFileString(rootEnvPath) : "";-- yield* fs.writeFileString(rootEnvPath, reconcileRootEnvPublicConfig(contents, config));- yield* Console.log(`Updated ${rootEnvPath} with relay public client configuration`);-});--const writeGithubOutput = Effect.fn("relay.deploy.writeGithubOutput")(function* (- outcome: RelayDeployOutcome,-) {- const fs = yield* FileSystem.FileSystem;- const githubOutputPath = yield* Config.nonEmptyString("GITHUB_OUTPUT");- yield* fs.writeFileString(- githubOutputPath,- serializeGithubOutput({- changed: outcome.changed,- result: outcome.result,- ...(Option.isSome(outcome.publicConfig)- ? {- relay_url: outcome.publicConfig.value.relayUrl,- }- : {}),- }),- { flag: "a" },- );-});--const writeGithubEnvFile = Effect.fn("relay.deploy.writeGithubEnvFile")(function* (- outcome: RelayDeployOutcome,- outputPath: string,- stage: string,-) {- if (Option.isNone(outcome.publicConfig)) {- return yield* new RelayDeployPublicConfigUnavailableError({- result: outcome.result,- stage,- outputPath,- });- }- const fs = yield* FileSystem.FileSystem;- yield* Console.log(`::add-mask::${outcome.publicConfig.value.clientTracingToken}`);- yield* fs.writeFileString(- outputPath,- serializeRelayClientTracingEnvironment(outcome.publicConfig.value),- );-});--const deployBaseServices = Layer.mergeAll(- Layer.succeed(AuthProviders, {}),- Layer.succeed(ArtifactStore, createArtifactStore()),- Layer.provideMerge(AlchemyContextLive, PlatformServices),- Layer.provide(ProfileLive, PlatformServices),- Layer.provide(CredentialsStoreLive, PlatformServices),- FetchHttpClient.layer,- TelemetryLive,- LoggingCli,-);-const deployServices = deployBaseServices;--function relayPublicConfigValues(- output: unknown,-): Readonly<Record<RelayDeployOutputField, string | undefined>> {- if (typeof output !== "object" || output === null) {- return {- url: undefined,- mobileTracingUrl: undefined,- mobileTracingDataset: undefined,- mobileTracingToken: undefined,- clientTracingUrl: undefined,- clientTracingDataset: undefined,- clientTracingToken: undefined,- };- }- const value = output as Record<string, unknown>;- const text = (name: string) => {- const candidate = value[name];- return typeof candidate === "string" && candidate.length > 0 ? candidate : undefined;- };- const secret = (name: string): string | undefined => {- const candidate = value[name];- if (!Redacted.isRedacted(candidate)) {- return text(name);- }- const redacted = Redacted.value(candidate);- return typeof redacted === "string" && redacted.length > 0 ? redacted : undefined;- };- return {- url: text("url"),- mobileTracingUrl: text("mobileTracingUrl"),- mobileTracingDataset: text("mobileTracingDataset"),- mobileTracingToken: secret("mobileTracingToken"),- clientTracingUrl: text("clientTracingUrl"),- clientTracingDataset: text("clientTracingDataset"),- clientTracingToken: secret("clientTracingToken"),- };-}--export function missingRelayPublicConfigFields(- output: unknown,-): ReadonlyArray<RelayDeployOutputField> {- const values = relayPublicConfigValues(output);- return relayDeployOutputFields.filter((field) => values[field] === undefined);-}--function hasCompleteRelayPublicConfigValues(- values: Readonly<Record<RelayDeployOutputField, string | undefined>>,-): values is Readonly<Record<RelayDeployOutputField, string>> {- return relayDeployOutputFields.every((field) => values[field] !== undefined);-}--export function publicConfigFromOutput(output: unknown): RelayPublicConfig | null {- const values = relayPublicConfigValues(output);- if (!hasCompleteRelayPublicConfigValues(values)) {- return null;- }- return {- relayUrl: values.url,- mobileTracingUrl: values.mobileTracingUrl,- mobileTracingDataset: values.mobileTracingDataset,- mobileTracingToken: values.mobileTracingToken,- clientTracingUrl: values.clientTracingUrl,- clientTracingDataset: values.clientTracingDataset,- clientTracingToken: values.clientTracingToken,- };-}--const readRelayPublicConfig = Effect.fn("relay.deploy.readState")(function* (stage: string) {- const state = yield* State.State;- const service = yield* state;- const output = yield* service.getOutput({ stack: "T3CodeRelay", stage });- const publicConfig = publicConfigFromOutput(output);- if (publicConfig === null) {- return yield* new RelayDeployError({- source: "alchemy_state",- stage,- missingFields: missingRelayPublicConfigFields(output),- });- }- return {- result: "state",- changed: false,- publicConfig: Option.some(publicConfig),- } satisfies RelayDeployOutcome;-});--const runRelayDeploy = Effect.fn("relay.deploy.run")(- function* (- options: RelayDeployOptions,- _configProvider: ConfigProvider.ConfigProvider,- stage: string,- ) {- const stack = yield* RelayStack;- const cli = yield* Cli;- const plan = yield* Plan.make(stack, { force: options.force }).pipe(- Effect.provide(stack.services),- );- const changed = hasDeployChanges(plan);- if (options.dryRun) {- yield* cli.displayPlan(plan);- return {- result: "dry-run",- changed,- publicConfig: Option.none<RelayPublicConfig>(),- } satisfies RelayDeployOutcome;- }- if (!options.yes && changed) {- yield* cli.displayPlan(plan);- const approved = yield* Prompt.run(- Prompt.confirm({- message: "Apply this relay deployment?",- }),- );- if (!approved) {- yield* Console.log("Deployment cancelled.");- return {- result: "cancelled",- changed,- publicConfig: Option.none<RelayPublicConfig>(),- } satisfies RelayDeployOutcome;- }- }- const output = yield* Apply.apply(plan).pipe(Effect.provide(stack.services));- const publicConfig = publicConfigFromOutput(output);- if (publicConfig === null) {- return yield* new RelayDeployError({- source: "alchemy_apply",- stage,- missingFields: missingRelayPublicConfigFields(output),- });- }- return {- result: changed ? "applied" : "noop",- changed,- publicConfig: Option.some(publicConfig),- } satisfies RelayDeployOutcome;- },- (effect, options, configProvider, stage) =>- effect.pipe(- Effect.provide(- Layer.mergeAll(- Layer.effect(- AlchemyContext,- AlchemyContext.pipe(Effect.map((context) => ({ ...context, adopt: options.adopt }))),- ),- Layer.succeed(AdoptPolicy, options.adopt),- Layer.succeed(AuthProviders, {}),- ConfigProvider.layer(configProvider),- Layer.succeed(Stage.Stage, stage),- ),- ),- provideFreshArtifactStore,- ),-);--export const deploy = Effect.fn("relay.deploy")(function* (options: RelayDeployOptions) {- const configProvider = yield* loadDeployConfigProvider(options.envFile);- const configuredStage = yield* relayDeployStage.pipe(- Effect.provide(ConfigProvider.layer(configProvider)),- );- const stage = Option.getOrElse(options.stage, () => configuredStage);- const outcome = options.readState- ? yield* readRelayPublicConfig(stage).pipe(Effect.provide(Cloudflare.state()))- : yield* runRelayDeploy(options, configProvider, stage);- if (Option.isSome(outcome.publicConfig)) {- yield* reconcileRootEnv(outcome.publicConfig.value);- }- if (options.githubOutput) {- yield* writeGithubOutput(outcome);- }- if (Option.isSome(options.githubEnvFile)) {- yield* writeGithubEnvFile(outcome, options.githubEnvFile.value, stage);- }-});--export const relayDeployCommand = Command.make(- "relay-deploy",- {- dryRun: Flag.boolean("dry-run").pipe(- Flag.withDescription("Dry run the deployment without applying changes."),- Flag.withDefault(false),- ),- force: Flag.boolean("force").pipe(- Flag.withDescription("Force updates for resources that would otherwise no-op."),- Flag.withDefault(false),- ),- envFile: Flag.string("env-file").pipe(- Flag.withDescription(- "Environment file to load. Defaults to infra/relay/.env with process env fallback.",- ),- Flag.optional,- ),- stage: Flag.string("stage").pipe(- Flag.withDescription("Stage to deploy. Defaults to dev_${USER}."),- Flag.optional,- ),- yes: Flag.boolean("yes").pipe(- Flag.withDescription("Skip the deployment confirmation prompt."),- Flag.withDefault(false),- ),- adopt: Flag.boolean("adopt").pipe(- Flag.withDescription("Adopt pre-existing cloud resources that conflict with this stack."),- Flag.withDefault(false),- ),- githubOutput: Flag.boolean("github-output").pipe(- Flag.withDescription("Append relay deployment metadata to GITHUB_OUTPUT."),- Flag.withDefault(false),- ),- githubEnvFile: Flag.string("github-env-file").pipe(- Flag.withDescription(- "Write relay client tracing variables to a file suitable for GITHUB_ENV.",- ),- Flag.optional,- ),- readState: Flag.boolean("read-state").pipe(- Flag.withDescription("Read the deployed stack output without planning or applying changes."),- Flag.withDefault(false),- ),- },- deploy,-).pipe(Command.withDescription("Deploy the T3 Code relay through Alchemy."));--if (import.meta.main) {- Command.run(relayDeployCommand, { version: "0.0.0" }).pipe(- Effect.provide(deployServices),- Effect.scoped,- NodeRuntime.runMain,- );-}diff --git a/infra/relay/src/Config.ts b/infra/relay/src/Config.tsdeleted file mode 100644index e7c7d42f2..000000000--- a/infra/relay/src/Config.ts+++ /dev/null@@ -1,37 +0,0 @@-import * as Context from "effect/Context";-import * as Layer from "effect/Layer";-import * as Redacted from "effect/Redacted";-import * as Schema from "effect/Schema";--export const ApnsEnvironment = Schema.Literals(["sandbox", "production"]);-export type ApnsEnvironment = typeof ApnsEnvironment.Type;--export interface ApnsCredentials {- readonly teamId: string;- readonly keyId: string;- readonly privateKey: Redacted.Redacted<string>;- readonly bundleId: string;- readonly environment: ApnsEnvironment;-}--export class RelayConfiguration extends Context.Service<- RelayConfiguration,- {- readonly relayIssuer: string;- readonly apns: ApnsCredentials;- readonly clerkSecretKey: Redacted.Redacted<string>;- readonly clerkPublishableKey: string;- readonly clerkJwtAudience: string;- readonly apnsDeliveryJobSigningSecret: Redacted.Redacted<string>;- readonly cloudMintPrivateKey: Redacted.Redacted<string>;- readonly cloudMintPublicKey: string;- readonly managedEndpointBaseDomain: string | undefined;- readonly managedEndpointNamespace: string | undefined;- }->()("t3code-relay/Config/RelayConfiguration") {}--export const make = (configuration: RelayConfiguration["Service"]) =>- RelayConfiguration.of(configuration);--export const layer = (configuration: RelayConfiguration["Service"]) =>- Layer.succeed(RelayConfiguration, make(configuration));diff --git a/infra/relay/src/agentActivity/AgentActivityPublisher.test.ts b/infra/relay/src/agentActivity/AgentActivityPublisher.test.tsdeleted file mode 100644index 4215f8346..000000000--- a/infra/relay/src/agentActivity/AgentActivityPublisher.test.ts+++ /dev/null@@ -1,814 +0,0 @@-import type { RelayAgentActivityState, RelayDeliveryResult } from "@t3tools/contracts/relay";-import { describe, expect, it } from "@effect/vitest";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";--import * as AgentActivityRows from "./AgentActivityRows.ts";-import * as EnvironmentLinks from "../environments/EnvironmentLinks.ts";-import * as LiveActivities from "./LiveActivities.ts";-import * as AgentActivityPublisher from "./AgentActivityPublisher.ts";-import * as ApnsDeliveries from "./ApnsDeliveries.ts";--const state: RelayAgentActivityState = {- environmentId: "env" as RelayAgentActivityState["environmentId"],- threadId: "thread" as RelayAgentActivityState["threadId"],- projectTitle: "Project",- threadTitle: "Thread",- modelTitle: "gpt-5.4",- phase: "running",- headline: "Running",- updatedAt: "1970-01-01T00:00:00.000Z",- deepLink: "/threads/env/thread",-};--function target(deviceId: string): LiveActivities.TargetRow {- return {- user_id: "dev:julius",- device_id: deviceId,- platform: "ios",- ios_major_version: 18,- app_version: "1.0.0",- bundle_id: null,- aps_environment: null,- push_token: null,- push_to_start_token: "start-token",- preferences_json: "{}",- activity_push_token: null,- remote_start_queued_at: null,- remote_started_at: null,- ended_at: null,- last_aggregate_json: null,- last_live_activity_delivery_at: null,- };-}--function makeLiveActivities(- overrides: Partial<LiveActivities.LiveActivities["Service"]> = {},-): LiveActivities.LiveActivities["Service"] {- return {- register: () => Effect.void,- listTargets: () => Effect.succeed([]),- markDelivery: () => Effect.void,- markStartQueued: () => Effect.void,- clearStartQueued: () => Effect.void,- invalidateDeliveryToken: () => Effect.void,- ...overrides,- };-}--function makeAgentActivityRows(- overrides: Partial<AgentActivityRows.AgentActivityRows["Service"]> = {},-): AgentActivityRows.AgentActivityRows["Service"] {- return {- upsert: () => Effect.void,- remove: () => Effect.void,- pruneTerminal: () => Effect.void,- listForUser: () => Effect.succeed([state]),- getForUserThread: () => Effect.succeed(state),- ...overrides,- };-}--function makeEnvironmentLinks(- overrides: Partial<EnvironmentLinks.EnvironmentLinks["Service"]> = {},-): EnvironmentLinks.EnvironmentLinks["Service"] {- return {- upsert: () => Effect.void,- listUsersForEnvironment: () => Effect.succeed(["dev:julius"]),- listDeliveryUsersForEnvironment: () =>- Effect.succeed([- {- userId: "dev:julius",- notificationsEnabled: true,- liveActivitiesEnabled: true,- },- ]),- listPublicKeysForEnvironment: () => Effect.succeed([]),- listForUser: () => Effect.succeed([]),- getForUser: () => Effect.succeed(null),- revokeForUser: () => Effect.succeed(false),- ...overrides,- };-}--function makeApnsDeliveries(- overrides: Partial<ApnsDeliveries.ApnsDeliveries["Service"]> = {},-): ApnsDeliveries.ApnsDeliveries["Service"] {- return {- sendForTarget: () => Effect.succeed(null),- sendPushNotificationForTarget: () => Effect.succeed(null),- sendLiveActivity: () =>- Effect.succeed({- deviceId: "device",- kind: "live_activity_start",- ok: true,- apnsStatus: 200,- apnsReason: null,- apnsId: "apns-id",- }),- sendPushNotification: () =>- Effect.succeed({- deviceId: "device",- kind: "push_notification",- ok: true,- apnsStatus: 200,- apnsReason: null,- apnsId: "apns-id",- }),- processSignedJob: () =>- Effect.succeed({- deviceId: "device",- kind: "live_activity_start",- ok: true,- apnsStatus: 200,- apnsReason: null,- apnsId: "apns-id",- }),- ...overrides,- };-}--describe("AgentActivityPublisher", () => {- it.effect("replays the latest aggregate when a Live Activity token registers", () => {- const registeredTarget: LiveActivities.TargetRow = {- ...target("device-1"),- push_to_start_token: null,- activity_push_token: "activity-token",- remote_start_queued_at: null,- remote_started_at: "1970-01-01T00:00:01.000Z",- };- const sent: Array<Parameters<ApnsDeliveries.ApnsDeliveries["Service"]["sendForTarget"]>[0]> =- [];- const deliveryResult: RelayDeliveryResult = {- deviceId: "device-1",- kind: "live_activity_update",- ok: true,- apnsStatus: null,- apnsReason: null,- apnsId: "queued",- };-- return Effect.gen(function* () {- const result = yield* Effect.gen(function* () {- const publisher = yield* AgentActivityPublisher.AgentActivityPublisher;- return yield* publisher.replayForLiveActivityRegistration({- userId: "dev:julius",- deviceId: "device-1",- });- }).pipe(- Effect.provide(- AgentActivityPublisher.layer.pipe(- Layer.provide(- Layer.mergeAll(- Layer.succeed(AgentActivityRows.AgentActivityRows, makeAgentActivityRows()),- Layer.succeed(EnvironmentLinks.EnvironmentLinks, makeEnvironmentLinks()),- Layer.succeed(- LiveActivities.LiveActivities,- makeLiveActivities({- listTargets: () => Effect.succeed([registeredTarget, target("device-2")]),- }),- ),- Layer.succeed(- ApnsDeliveries.ApnsDeliveries,- makeApnsDeliveries({- sendForTarget: (input) =>- Effect.sync(() => {- sent.push(input);- return deliveryResult;- }),- }),- ),- ),- ),- ),- ),- );-- expect(result).toEqual(deliveryResult);- expect(sent).toHaveLength(1);- expect(sent[0]?.target.device_id).toBe("device-1");- expect(sent[0]?.aggregate).toMatchObject({- activeCount: 1,- activities: [- {- environmentId: state.environmentId,- threadId: state.threadId,- status: "Working",- },- ],- });- });- });-- it.effect("publishes listed targets through the APNs delivery service", () => {- const firstTarget = target("device-1");- const secondTarget = target("device-2");- const deliveryResult: RelayDeliveryResult = {- deviceId: "device-1",- kind: "live_activity_start",- ok: true,- apnsStatus: 200,- apnsReason: null,- apnsId: "apns-id",- };- const sentTargets: Array<string> = [];- const deliveryLookups: Array<{- readonly environmentId: string;- readonly environmentPublicKey: string;- }> = [];- const upserts: Array<Parameters<AgentActivityRows.AgentActivityRows["Service"]["upsert"]>[0]> =- [];-- return Effect.gen(function* () {- const result = yield* Effect.gen(function* () {- const publisher = yield* AgentActivityPublisher.AgentActivityPublisher;- return yield* publisher.publish({- environmentId: "env",- environmentPublicKey: "environment-public-key",- threadId: "thread",- state,- });- }).pipe(- Effect.provide(- AgentActivityPublisher.layer.pipe(- Layer.provide(- Layer.mergeAll(- Layer.succeed(- AgentActivityRows.AgentActivityRows,- makeAgentActivityRows({- upsert: (input) =>- Effect.sync(() => {- upserts.push(input);- }),- }),- ),- Layer.succeed(- EnvironmentLinks.EnvironmentLinks,- makeEnvironmentLinks({- listDeliveryUsersForEnvironment: (input) =>- Effect.sync(() => {- deliveryLookups.push(input);- return [- {- userId: "dev:julius",- notificationsEnabled: true,- liveActivitiesEnabled: true,- },- ];- }),- }),- ),- Layer.succeed(- LiveActivities.LiveActivities,- makeLiveActivities({- listTargets: () => Effect.succeed([firstTarget, secondTarget]),- }),- ),- Layer.succeed(- ApnsDeliveries.ApnsDeliveries,- makeApnsDeliveries({- sendForTarget: (input) =>- Effect.sync(() => {- sentTargets.push(input.target.device_id);- return input.target.device_id === "device-1" ? deliveryResult : null;- }),- }),- ),- ),- ),- ),- ),- );-- expect(sentTargets).toEqual(["device-1", "device-2"]);- expect(deliveryLookups).toEqual([- {- environmentId: "env",- environmentPublicKey: "environment-public-key",- },- ]);- expect(upserts).toMatchObject([- {- environmentPublicKey: "environment-public-key",- state: {- environmentId: "env",- threadId: "thread",- },- },- ]);- expect(result).toEqual({ ok: true, deliveries: [deliveryResult] });- });- });-- it.effect("ends the last remote Live Activity with a terminal content state", () => {- const completedState: RelayAgentActivityState = {- ...state,- phase: "completed",- headline: "Done",- updatedAt: "1970-01-01T00:00:10.000Z",- };- const sentAggregates: Array<- Parameters<ApnsDeliveries.ApnsDeliveries["Service"]["sendForTarget"]>[0]- > = [];- const upserts: Array<Parameters<AgentActivityRows.AgentActivityRows["Service"]["upsert"]>[0]> =- [];-- return Effect.gen(function* () {- const result = yield* Effect.gen(function* () {- const publisher = yield* AgentActivityPublisher.AgentActivityPublisher;- return yield* publisher.publish({- environmentId: "env",- environmentPublicKey: "environment-public-key",- threadId: "thread",- state: completedState,- });- }).pipe(- Effect.provide(- AgentActivityPublisher.layer.pipe(- Layer.provide(- Layer.mergeAll(- Layer.succeed(- AgentActivityRows.AgentActivityRows,- makeAgentActivityRows({- upsert: (input) =>- Effect.sync(() => {- upserts.push(input);- }),- listForUser: () => Effect.succeed([]),- }),- ),- Layer.succeed(EnvironmentLinks.EnvironmentLinks, makeEnvironmentLinks()),- Layer.succeed(- LiveActivities.LiveActivities,- makeLiveActivities({- listTargets: () =>- Effect.succeed([- {- ...target("device-1"),- push_to_start_token: null,- activity_push_token: "activity-token",- remote_started_at: "1970-01-01T00:00:00.000Z",- },- ]),- }),- ),- Layer.succeed(- ApnsDeliveries.ApnsDeliveries,- makeApnsDeliveries({- sendForTarget: (input) =>- Effect.sync(() => {- sentAggregates.push(input);- return {- deviceId: input.target.device_id,- kind: "live_activity_end",- ok: true,- apnsStatus: null,- apnsReason: null,- apnsId: "queued",- };- }),- }),- ),- ),- ),- ),- ),- );-- expect(result.deliveries).toMatchObject([- {- deviceId: "device-1",- kind: "live_activity_end",- ok: true,- },- ]);- // Terminal states are persisted (and later pruned by the cron) so the- // finished thread can keep a Done row in later aggregates.- expect(upserts).toEqual([- {- environmentPublicKey: "environment-public-key",- state: completedState,- },- ]);- expect(sentAggregates).toHaveLength(1);- expect(sentAggregates[0]?.aggregate).toMatchObject({- activeCount: 0,- subtitle: "Agent work completed",- activities: [- {- environmentId: completedState.environmentId,- threadId: completedState.threadId,- phase: "completed",- status: "Done",- },- ],- });- });- });-- it.effect("queues push notifications for notification-only environment links", () => {- const notificationState: RelayAgentActivityState = {- ...state,- phase: "waiting_for_input",- headline: "Needs input",- };- const liveAggregates: Array<- Parameters<ApnsDeliveries.ApnsDeliveries["Service"]["sendForTarget"]>[0]- > = [];- const pushAggregates: Array<- Parameters<ApnsDeliveries.ApnsDeliveries["Service"]["sendPushNotificationForTarget"]>[0]- > = [];-- return Effect.gen(function* () {- const result = yield* Effect.gen(function* () {- const publisher = yield* AgentActivityPublisher.AgentActivityPublisher;- return yield* publisher.publish({- environmentId: "env",- environmentPublicKey: "environment-public-key",- threadId: "thread",- state: notificationState,- });- }).pipe(- Effect.provide(- AgentActivityPublisher.layer.pipe(- Layer.provide(- Layer.mergeAll(- Layer.succeed(- AgentActivityRows.AgentActivityRows,- makeAgentActivityRows({- listForUser: () => Effect.succeed([]),- }),- ),- Layer.succeed(- EnvironmentLinks.EnvironmentLinks,- makeEnvironmentLinks({- listDeliveryUsersForEnvironment: () =>- Effect.succeed([- {- userId: "dev:julius",- notificationsEnabled: true,- liveActivitiesEnabled: false,- },- ]),- }),- ),- Layer.succeed(- LiveActivities.LiveActivities,- makeLiveActivities({- listTargets: () =>- Effect.succeed([- {- ...target("device-1"),- push_token: "apns-device-token",- push_to_start_token: null,- },- ]),- }),- ),- Layer.succeed(- ApnsDeliveries.ApnsDeliveries,- makeApnsDeliveries({- sendForTarget: (input) =>- Effect.sync(() => {- liveAggregates.push(input);- return null;- }),- sendPushNotificationForTarget: (input) =>- Effect.sync(() => {- pushAggregates.push(input);- return {- deviceId: input.target.device_id,- kind: "push_notification",- ok: true,- queued: true,- apnsStatus: null,- apnsReason: null,- apnsId: null,- };- }),- }),- ),- ),- ),- ),- ),- );-- expect(liveAggregates).toMatchObject([{ aggregate: null }]);- expect(pushAggregates).toHaveLength(1);- expect(pushAggregates[0]?.aggregate).toMatchObject({- activeCount: 1,- activities: [- {- phase: "waiting_for_input",- status: "Input",- threadId: notificationState.threadId,- },- ],- });- expect(result.deliveries).toMatchObject([- {- deviceId: "device-1",- kind: "push_notification",- queued: true,- },- ]);- });- });-- it.effect(- "does not build Live Activity aggregates for links with Live Activities disabled",- () => {- const notificationState: RelayAgentActivityState = {- ...state,- phase: "waiting_for_approval",- headline: "Needs approval",- };- const liveAggregates: Array<- Parameters<ApnsDeliveries.ApnsDeliveries["Service"]["sendForTarget"]>[0]- > = [];- const pushAggregates: Array<- Parameters<ApnsDeliveries.ApnsDeliveries["Service"]["sendPushNotificationForTarget"]>[0]- > = [];-- return Effect.gen(function* () {- const result = yield* Effect.gen(function* () {- const publisher = yield* AgentActivityPublisher.AgentActivityPublisher;- return yield* publisher.publish({- environmentId: "env",- environmentPublicKey: "environment-public-key",- threadId: "thread",- state: notificationState,- });- }).pipe(- Effect.provide(- AgentActivityPublisher.layer.pipe(- Layer.provide(- Layer.mergeAll(- Layer.succeed(- AgentActivityRows.AgentActivityRows,- makeAgentActivityRows({- listForUser: () =>- Effect.succeed([- {- ...state,- environmentId: "other-env" as RelayAgentActivityState["environmentId"],- threadId: "other-thread" as RelayAgentActivityState["threadId"],- },- ]),- }),- ),- Layer.succeed(- EnvironmentLinks.EnvironmentLinks,- makeEnvironmentLinks({- listDeliveryUsersForEnvironment: () =>- Effect.succeed([- {- userId: "dev:julius",- notificationsEnabled: true,- liveActivitiesEnabled: false,- },- ]),- }),- ),- Layer.succeed(- LiveActivities.LiveActivities,- makeLiveActivities({- listTargets: () =>- Effect.succeed([- {- ...target("device-1"),- push_token: "apns-device-token",- push_to_start_token: "push-to-start-token",- },- ]),- }),- ),- Layer.succeed(- ApnsDeliveries.ApnsDeliveries,- makeApnsDeliveries({- sendForTarget: (input) =>- Effect.sync(() => {- liveAggregates.push(input);- return null;- }),- sendPushNotificationForTarget: (input) =>- Effect.sync(() => {- pushAggregates.push(input);- return {- deviceId: input.target.device_id,- kind: "push_notification",- ok: true,- queued: true,- apnsStatus: null,- apnsReason: null,- apnsId: null,- };- }),- }),- ),- ),- ),- ),- ),- );-- expect(liveAggregates).toMatchObject([{ aggregate: null }]);- expect(pushAggregates).toHaveLength(1);- expect(pushAggregates[0]?.aggregate?.activities).toMatchObject([- {- environmentId: notificationState.environmentId,- threadId: notificationState.threadId,- phase: "waiting_for_approval",- },- ]);- expect(result.deliveries).toMatchObject([- {- deviceId: "device-1",- kind: "push_notification",- queued: true,- },- ]);- });- },- );-});--describe("isExpiredAgentActivityState", () => {- const hourMs = 60 * 60 * 1_000;-- it("expires running rows after two hours without an update", () => {- expect(AgentActivityPublisher.isExpiredAgentActivityState(state, 2 * hourMs - 1)).toBe(false);- expect(AgentActivityPublisher.isExpiredAgentActivityState(state, 2 * hourMs + 1)).toBe(true);- });-- it("keeps waiting rows for a day", () => {- const waiting: RelayAgentActivityState = { ...state, phase: "waiting_for_approval" };- expect(AgentActivityPublisher.isExpiredAgentActivityState(waiting, 23 * hourMs)).toBe(false);- expect(AgentActivityPublisher.isExpiredAgentActivityState(waiting, 25 * hourMs)).toBe(true);- });-- it("treats rows with unparseable timestamps as expired", () => {- expect(- AgentActivityPublisher.isExpiredAgentActivityState({ ...state, updatedAt: "not-a-date" }, 0),- ).toBe(true);- });-});--describe("makeAggregateState", () => {- const hourMs = 60 * 60 * 1_000;-- it("drops expired rows from the aggregate", () => {- const fresh: RelayAgentActivityState = {- ...state,- threadId: "thread-fresh" as RelayAgentActivityState["threadId"],- updatedAt: "1970-01-01T03:00:00.000Z",- };- const aggregate = AgentActivityPublisher.makeAggregateState({- activeStates: [state, fresh],- terminalState: null,- nowMs: 3 * hourMs,- });-- expect(aggregate?.activeCount).toBe(1);- expect(aggregate?.activities).toMatchObject([{ threadId: "thread-fresh" }]);- });-- it("returns null when every row has expired and nothing terminal remains", () => {- expect(- AgentActivityPublisher.makeAggregateState({- activeStates: [state],- terminalState: null,- nowMs: 3 * hourMs,- }),- ).toBeNull();- });-- it("still reports the terminal state when active rows have expired", () => {- const terminalState: RelayAgentActivityState = {- ...state,- phase: "completed",- updatedAt: "1970-01-01T03:00:00.000Z",- };- const aggregate = AgentActivityPublisher.makeAggregateState({- activeStates: [state],- terminalState,- nowMs: 3 * hourMs,- });-- expect(aggregate?.activeCount).toBe(0);- expect(aggregate?.activities).toMatchObject([{ phase: "completed" }]);- });-- it("keeps a recently finished thread visible as Done beside active agents", () => {- const active: RelayAgentActivityState = {- ...state,- threadId: "thread-active" as RelayAgentActivityState["threadId"],- updatedAt: "1970-01-01T00:58:00.000Z",- };- const justCompleted: RelayAgentActivityState = {- ...state,- threadId: "thread-done" as RelayAgentActivityState["threadId"],- phase: "completed",- updatedAt: "1970-01-01T00:59:00.000Z",- };- const aggregate = AgentActivityPublisher.makeAggregateState({- activeStates: [active, justCompleted],- terminalState: null,- nowMs: hourMs,- });-- expect(aggregate?.activeCount).toBe(1);- expect(aggregate?.subtitle).toBe("Agent work in progress");- expect(aggregate?.activities).toMatchObject([- { threadId: "thread-active", phase: "running" },- { threadId: "thread-done", phase: "completed", status: "Done" },- ]);- expect(aggregate?.updatedAt).toBe("1970-01-01T00:59:00.000Z");- });-- it("drops finished threads from the aggregate after the display window", () => {- const active: RelayAgentActivityState = {- ...state,- threadId: "thread-active" as RelayAgentActivityState["threadId"],- updatedAt: "1970-01-01T00:58:00.000Z",- };- const staleCompleted: RelayAgentActivityState = {- ...state,- threadId: "thread-done" as RelayAgentActivityState["threadId"],- phase: "completed",- updatedAt: "1970-01-01T00:44:00.000Z",- };- const aggregate = AgentActivityPublisher.makeAggregateState({- activeStates: [active, staleCompleted],- terminalState: null,- nowMs: hourMs,- });-- expect(aggregate?.activities).toMatchObject([{ threadId: "thread-active" }]);- });-- it("keeps showing recently finished work when nothing is active", () => {- const lingeringCompleted: RelayAgentActivityState = {- ...state,- phase: "completed",- updatedAt: "1970-01-01T00:59:00.000Z",- };- const aggregate = AgentActivityPublisher.makeAggregateState({- activeStates: [lingeringCompleted],- terminalState: null,- nowMs: hourMs,- });-- // An armed card never renders an empty state: recently finished threads- // keep Done content on it, and once they age out the aggregate becomes- // null and the delivery layer ends the card.- expect(aggregate).toMatchObject({- activeCount: 0,- subtitle: "Agent work completed",- activities: [{ phase: "completed", status: "Done" }],- });- expect(- AgentActivityPublisher.makeAggregateState({- activeStates: [{ ...lingeringCompleted, updatedAt: "1970-01-01T00:44:00.000Z" }],- terminalState: null,- nowMs: hourMs,- }),- ).toBeNull();- });-- it("gives active agents the display slots before finished ones", () => {- const mkActive = (id: string): RelayAgentActivityState => ({- ...state,- threadId: id as RelayAgentActivityState["threadId"],- updatedAt: "1970-01-01T00:58:00.000Z",- });- const justCompleted: RelayAgentActivityState = {- ...state,- threadId: "thread-done" as RelayAgentActivityState["threadId"],- phase: "completed",- updatedAt: "1970-01-01T00:59:00.000Z",- };- const aggregate = AgentActivityPublisher.makeAggregateState({- activeStates: [- mkActive("a-1"),- mkActive("a-2"),- mkActive("a-3"),- mkActive("a-4"),- mkActive("a-5"),- justCompleted,- ],- terminalState: null,- nowMs: hourMs,- });-- expect(aggregate?.activeCount).toBe(5);- expect(aggregate?.activities).toMatchObject([- { threadId: "a-1" },- { threadId: "a-2" },- { threadId: "a-3" },- { threadId: "a-4" },- { threadId: "a-5" },- ]);- });-});diff --git a/infra/relay/src/agentActivity/AgentActivityPublisher.ts b/infra/relay/src/agentActivity/AgentActivityPublisher.tsdeleted file mode 100644index 9b3bcf229..000000000--- a/infra/relay/src/agentActivity/AgentActivityPublisher.ts+++ /dev/null@@ -1,302 +0,0 @@-import type {- RelayAgentActivityAggregateState,- RelayAgentActivityState,- RelayDeliveryResult,- RelayPublishResponse,-} from "@t3tools/contracts/relay";-import * as Context from "effect/Context";-import * as DateTime from "effect/DateTime";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";-import * as Option from "effect/Option";--import {- isExpiredAgentActivityState,- isTerminalPhase,- MAX_ACTIVITY_ROWS,- sanitizeAgentActivityAggregateState,-} from "./agentActivityPayloads.ts";--export { isExpiredAgentActivityState } from "./agentActivityPayloads.ts";-import * as AgentActivityRows from "./AgentActivityRows.ts";-import * as EnvironmentLinks from "../environments/EnvironmentLinks.ts";-import * as LiveActivities from "./LiveActivities.ts";-import * as ApnsDeliveries from "./ApnsDeliveries.ts";--export type AgentActivityPublishError =- | AgentActivityRows.AgentActivityRowUpsertPersistenceError- | AgentActivityRows.AgentActivityRowDeletePersistenceError- | AgentActivityRows.AgentActivityRowListPersistenceError- | EnvironmentLinks.EnvironmentLinkUserListPersistenceError- | LiveActivities.LiveActivityTargetListPersistenceError- | ApnsDeliveries.ApnsDeliveryError;--export class AgentActivityPublisher extends Context.Service<- AgentActivityPublisher,- {- readonly publish: (input: {- readonly environmentId: string;- readonly environmentPublicKey: string;- readonly threadId: string;- readonly state: RelayAgentActivityState | null;- }) => Effect.Effect<RelayPublishResponse, AgentActivityPublishError>;- readonly replayForLiveActivityRegistration: (input: {- readonly userId: string;- readonly deviceId: string;- }) => Effect.Effect<RelayDeliveryResult | null, AgentActivityPublishError>;- }->()("t3code-relay/agentActivity/AgentActivityPublisher") {}--export const make = Effect.gen(function* () {- const rows = yield* AgentActivityRows.AgentActivityRows;- const links = yield* EnvironmentLinks.EnvironmentLinks;- const liveActivities = yield* LiveActivities.LiveActivities;- const apnsDeliveries = yield* ApnsDeliveries.ApnsDeliveries;-- const publishForDeliveryUser = Effect.fnUntraced(function* (input: {- readonly deliveryUser: EnvironmentLinks.AgentAwarenessDeliveryUserRecord;- readonly state: RelayAgentActivityState | null;- readonly nowMs: number;- }) {- const activeStates = yield* rows.listForUser({ userId: input.deliveryUser.userId });- const liveActivityAggregate = input.deliveryUser.liveActivitiesEnabled- ? makeAggregateState({- activeStates,- terminalState: input.state && isTerminalPhase(input.state) ? input.state : null,- nowMs: input.nowMs,- })- : null;- const notificationOnlyAggregate =- input.deliveryUser.notificationsEnabled &&- !input.deliveryUser.liveActivitiesEnabled &&- input.state !== null- ? makeAggregateState({- activeStates: isTerminalPhase(input.state) ? [] : [input.state],- terminalState: isTerminalPhase(input.state) ? input.state : null,- nowMs: input.nowMs,- })- : null;- const targets = yield* liveActivities.listTargets({ userId: input.deliveryUser.userId });- const deliveriesByTarget = yield* Effect.forEach(- targets,- (target) =>- Effect.all(- [- apnsDeliveries.sendForTarget({- target,- aggregate: liveActivityAggregate,- nowMs: input.nowMs,- }),- notificationOnlyAggregate === null- ? Effect.succeed(null)- : apnsDeliveries.sendPushNotificationForTarget({- target,- aggregate: notificationOnlyAggregate,- }),- ],- { concurrency: 2 },- ),- { concurrency: 4 },- );- return deliveriesByTarget.flat();- });-- return AgentActivityPublisher.of({- replayForLiveActivityRegistration: Effect.fn(- "relay.agent_activity_publisher.replay_for_live_activity_registration",- )(function* (input) {- yield* Effect.annotateCurrentSpan({- "relay.mobile.device_id": input.deviceId,- "relay.operation": "replayForLiveActivityRegistration",- });- const { activeStates, targets } = yield* Effect.all(- {- activeStates: rows.listForUser({ userId: input.userId }),- targets: liveActivities.listTargets({ userId: input.userId }),- },- { concurrency: 2 },- );- const target = targets.find((row) => row.device_id === input.deviceId) ?? null;- if (target === null) {- return null;- }- const now = yield* DateTime.now;- const aggregate = makeAggregateState({- activeStates,- terminalState: null,- nowMs: now.epochMilliseconds,- });- return yield* apnsDeliveries.sendForTarget({- target,- aggregate,- nowMs: now.epochMilliseconds,- });- }),- publish: Effect.fn("relay.agent_activity_publisher.publish")(function* (input) {- yield* Effect.annotateCurrentSpan({- "relay.environment_id": input.environmentId,- "relay.thread_id": input.threadId,- "relay.agent_activity.phase": input.state?.phase ?? "deleted",- });- if (input.state) {- // Terminal states are persisted too (pruned by the cron after they- // age out) so a thread that finishes while other agents are active- // stays visible as Done/Failed in subsequent aggregates instead of- // silently vanishing from the Live Activity.- yield* rows.upsert({- environmentPublicKey: input.environmentPublicKey,- state: input.state,- });- } else {- yield* rows.remove({- environmentId: input.environmentId,- environmentPublicKey: input.environmentPublicKey,- threadId: input.threadId,- });- }-- const deliveryUsers = yield* links.listDeliveryUsersForEnvironment({- environmentId: input.environmentId,- environmentPublicKey: input.environmentPublicKey,- });- const now = yield* DateTime.now;- const deliveriesByUser = yield* Effect.forEach(- deliveryUsers,- (deliveryUser) =>- publishForDeliveryUser({- deliveryUser,- state: input.state,- nowMs: now.epochMilliseconds,- }),- { concurrency: 4 },- );- const deliveries = deliveriesByUser.flat();- return {- ok: true,- deliveries: deliveries.filter(- (delivery): delivery is RelayDeliveryResult => delivery !== null,- ),- };- }),- });-});--function statusForPhase(phase: RelayAgentActivityState["phase"]): string {- switch (phase) {- case "waiting_for_approval":- return "Approval";- case "waiting_for_input":- return "Input";- case "completed":- return "Done";- case "failed":- return "Failed";- case "starting":- // Matches the web sidebar's pill wording (Sidebar.logic.ts) so the same- // thread reads the same across surfaces.- return "Connecting";- case "running":- return "Working";- case "stale":- return "Waiting";- }-}--function aggregateRowForState(state: RelayAgentActivityState) {- return {- environmentId: state.environmentId,- threadId: state.threadId,- projectTitle: state.projectTitle,- threadTitle: state.threadTitle,- modelTitle: state.modelTitle,- phase: state.phase,- status: statusForPhase(state.phase),- updatedAt: state.updatedAt,- deepLink: state.deepLink,- };-}--function terminalAggregateState(state: RelayAgentActivityState): RelayAgentActivityAggregateState {- return sanitizeAgentActivityAggregateState({- title: "T3 Code",- subtitle: state.phase === "failed" ? "Agent work failed" : "Agent work completed",- activeCount: 0,- updatedAt: state.updatedAt,- activities: [aggregateRowForState(state)],- });-}--// How long a finished thread keeps its Done/Failed row in the aggregate while-// other agents are still active. Long enough to be seen on the lock screen,-// short enough that the activity list stays about live work.-export const TERMINAL_AGENT_ACTIVITY_DISPLAY_TTL_MS = 15 * 60 * 1_000;--function isRecentTerminalState(state: RelayAgentActivityState, nowMs: number): boolean {- if (!isTerminalPhase(state)) {- return false;- }- const updatedAtMs = Option.match(DateTime.make(state.updatedAt), {- onNone: () => Number.NaN,- onSome: (dt) => dt.epochMilliseconds,- });- if (Number.isNaN(updatedAtMs)) {- return false;- }- return nowMs - updatedAtMs <= TERMINAL_AGENT_ACTIVITY_DISPLAY_TTL_MS;-}--export function makeAggregateState(input: {- readonly activeStates: ReadonlyArray<RelayAgentActivityState>;- readonly terminalState: RelayAgentActivityState | null;- readonly nowMs: number;-}): RelayAgentActivityAggregateState | null {- const activeStates = input.activeStates.filter(- (state) => !isTerminalPhase(state) && !isExpiredAgentActivityState(state, input.nowMs),- );- if (activeStates.length === 0) {- if (input.terminalState !== null) {- return terminalAggregateState(input.terminalState);- }- // With no live work, recently finished threads keep the card showing- // Done/Failed content (an armed card never renders an empty state). The- // newly-terminal alert rules key off the previously delivered aggregate,- // so replays repaint this without buzzing. Once the terminal rows age- // out, the aggregate is null and the delivery layer ends the card.- const recentTerminal = input.activeStates- .filter((state) => isRecentTerminalState(state, input.nowMs))- .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));- const newest = recentTerminal[0];- if (!newest) {- return null;- }- return sanitizeAgentActivityAggregateState({- title: "T3 Code",- subtitle: newest.phase === "failed" ? "Agent work failed" : "Agent work completed",- activeCount: 0,- updatedAt: newest.updatedAt,- activities: recentTerminal.slice(0, MAX_ACTIVITY_ROWS).map(aggregateRowForState),- });- }- // Recently finished threads ride along after the active ones (display slots- // permitting) so a completion is visible as Done/Failed instead of the row- // silently vanishing while other agents keep the activity alive.- const recentTerminalStates = input.activeStates- .filter((state) => isRecentTerminalState(state, input.nowMs))- .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));- const displayedStates = [- ...activeStates.slice(0, MAX_ACTIVITY_ROWS),- ...recentTerminalStates,- ].slice(0, MAX_ACTIVITY_ROWS);- const updatedAt = [...activeStates, ...recentTerminalStates].reduce((latest, state) =>- state.updatedAt.localeCompare(latest.updatedAt) > 0 ? state : latest,- ).updatedAt;- return sanitizeAgentActivityAggregateState({- title: "T3 Code",- subtitle: "Agent work in progress",- activeCount: activeStates.length,- updatedAt,- activities: displayedStates.map(aggregateRowForState),- });-}--export const layer = Layer.effect(AgentActivityPublisher, make);diff --git a/infra/relay/src/agentActivity/AgentActivityRows.test.ts b/infra/relay/src/agentActivity/AgentActivityRows.test.tsdeleted file mode 100644index 65b0c2a0a..000000000--- a/infra/relay/src/agentActivity/AgentActivityRows.test.ts+++ /dev/null@@ -1,93 +0,0 @@-import type { RelayAgentActivityState } from "@t3tools/contracts/relay";-import { describe, expect, it } from "@effect/vitest";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";--import * as RelayDb from "../db.ts";-import * as AgentActivityRows from "./AgentActivityRows.ts";--const state: RelayAgentActivityState = {- environmentId: "env-1" as RelayAgentActivityState["environmentId"],- threadId: "thread-1" as RelayAgentActivityState["threadId"],- projectTitle: "Project",- threadTitle: "Thread",- modelTitle: "gpt-5.4",- phase: "running",- headline: "Running",- updatedAt: "2026-06-20T00:00:00.000Z",- deepLink: "/threads/env-1/thread-1",-};--describe("AgentActivityRows", () => {- it.effect("preserves activity context on persistence failures", () => {- const cause = new Error("database unavailable");- const failingDb = {- insert: () => ({- values: () => ({- onConflictDoUpdate: () => Effect.fail(cause),- }),- }),- delete: () => ({- where: () => Effect.fail(cause),- }),- select: () => ({- from: () => ({- innerJoin: () => ({- where: () => ({- orderBy: () => Effect.fail(cause),- }),- }),- }),- }),- } as unknown as RelayDb.RelayDb["Service"];-- return Effect.gen(function* () {- const rows = yield* AgentActivityRows.AgentActivityRows;-- const upsertError = yield* rows- .upsert({ environmentPublicKey: "public-key", state })- .pipe(Effect.flip);- expect(upsertError).toMatchObject({- environmentId: "env-1",- threadId: "thread-1",- cause,- });- expect(upsertError.message).toBe(- "Failed to persist agent activity state for environment env-1, thread thread-1.",- );-- const deleteError = yield* rows- .remove({- environmentId: "env-1",- environmentPublicKey: "public-key",- threadId: "thread-1",- })- .pipe(Effect.flip);- expect(deleteError).toMatchObject({- environmentId: "env-1",- threadId: "thread-1",- cause,- });- expect(deleteError.message).toBe(- "Failed to delete agent activity state for environment env-1, thread thread-1.",- );-- const listError = yield* rows.listForUser({ userId: "user-2" }).pipe(Effect.flip);- expect(listError).toMatchObject({ userId: "user-2", cause });- expect(listError.message).toBe("Failed to list agent activity state for user user-2.");-- const getError = yield* rows- .getForUserThread({- userId: "user-2",- environmentId: "env-1",- threadId: "thread-1",- })- .pipe(Effect.flip);- expect(getError).toMatchObject({ userId: "user-2", cause });- }).pipe(- Effect.provide(- AgentActivityRows.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, failingDb))),- ),- );- });-});diff --git a/infra/relay/src/agentActivity/AgentActivityRows.ts b/infra/relay/src/agentActivity/AgentActivityRows.tsdeleted file mode 100644index 54ba1df50..000000000--- a/infra/relay/src/agentActivity/AgentActivityRows.ts+++ /dev/null@@ -1,300 +0,0 @@-import type { RelayAgentActivityState } from "@t3tools/contracts/relay";-import { RelayAgentActivityState as RelayAgentActivityStateSchema } from "@t3tools/contracts/relay";-import * as Context from "effect/Context";-import * as DateTime from "effect/DateTime";-import * as Effect from "effect/Effect";-import * as Function from "effect/Function";-import * as Layer from "effect/Layer";-import * as Option from "effect/Option";-import * as Schema from "effect/Schema";-import { and, desc, eq, isNull, lt, sql } from "drizzle-orm";--import * as RelayDb from "../db.ts";-import { relayAgentActivityRows, relayEnvironmentLinks } from "../persistence/schema.ts";--export class AgentActivityRowUpsertPersistenceError extends Schema.TaggedErrorClass<AgentActivityRowUpsertPersistenceError>()(- "AgentActivityRowUpsertPersistenceError",- {- environmentId: Schema.String,- threadId: Schema.String,- cause: Schema.Defect(),- },-) {- override get message(): string {- return `Failed to persist agent activity state for environment ${this.environmentId}, thread ${this.threadId}.`;- }-}--export class AgentActivityRowDeletePersistenceError extends Schema.TaggedErrorClass<AgentActivityRowDeletePersistenceError>()(- "AgentActivityRowDeletePersistenceError",- {- environmentId: Schema.String,- threadId: Schema.String,- cause: Schema.Defect(),- },-) {- override get message(): string {- return `Failed to delete agent activity state for environment ${this.environmentId}, thread ${this.threadId}.`;- }-}--export class AgentActivityRowPruneTerminalPersistenceError extends Schema.TaggedErrorClass<AgentActivityRowPruneTerminalPersistenceError>()(- "AgentActivityRowPruneTerminalPersistenceError",- {- updatedBefore: Schema.String,- cause: Schema.Defect(),- },-) {- override get message(): string {- return `Failed to prune terminal agent activity rows updated before ${this.updatedBefore}.`;- }-}--export class AgentActivityRowListPersistenceError extends Schema.TaggedErrorClass<AgentActivityRowListPersistenceError>()(- "AgentActivityRowListPersistenceError",- {- userId: Schema.String,- cause: Schema.Defect(),- },-) {- override get message(): string {- return `Failed to list agent activity state for user ${this.userId}.`;- }-}--export class AgentActivityRows extends Context.Service<- AgentActivityRows,- {- readonly upsert: (input: {- readonly environmentPublicKey: string;- readonly state: RelayAgentActivityState;- }) => Effect.Effect<void, AgentActivityRowUpsertPersistenceError>;- readonly pruneTerminal: (input: {- readonly updatedBefore: string;- }) => Effect.Effect<void, AgentActivityRowPruneTerminalPersistenceError>;- readonly remove: (input: {- readonly environmentId: string;- readonly environmentPublicKey: string;- readonly threadId: string;- }) => Effect.Effect<void, AgentActivityRowDeletePersistenceError>;- readonly listForUser: (input: {- readonly userId: string;- }) => Effect.Effect<- ReadonlyArray<RelayAgentActivityState>,- AgentActivityRowListPersistenceError- >;- readonly getForUserThread: (input: {- readonly userId: string;- readonly environmentId: string;- readonly threadId: string;- }) => Effect.Effect<RelayAgentActivityState | null, AgentActivityRowListPersistenceError>;- }->()("t3code-relay/agentActivity/AgentActivityRows") {}--const decodeJsonString = Schema.decodeEffect(Schema.fromJsonString(Schema.Unknown));-const encodeJsonValue = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));--const encodeRelayAgentActivityStateJson = Schema.encodeEffect(- Schema.fromJsonString(RelayAgentActivityStateSchema),-);--const decodeRelayAgentActivityStateJson = Schema.decodeUnknownOption(- Schema.fromJsonString(RelayAgentActivityStateSchema),-);--export const make = Effect.gen(function* () {- const db = yield* RelayDb.RelayDb;-- return AgentActivityRows.of({- upsert: Effect.fn("relay.agent_activity_rows.upsert")(function* (input) {- yield* Effect.annotateCurrentSpan({- "relay.environment_id": input.state.environmentId,- "relay.thread_id": input.state.threadId,- });- const now = yield* DateTime.now;- const stateJson = yield* encodeRelayAgentActivityStateJson(input.state).pipe(- Effect.flatMap(decodeJsonString),- Effect.map(Function.cast<unknown, RelayAgentActivityState>),- Effect.mapError(- (cause) =>- new AgentActivityRowUpsertPersistenceError({- environmentId: input.state.environmentId,- threadId: input.state.threadId,- cause,- }),- ),- );- yield* db- .insert(relayAgentActivityRows)- .values({- environmentId: input.state.environmentId,- environmentPublicKey: input.environmentPublicKey,- threadId: input.state.threadId,- stateJson,- updatedAt: input.state.updatedAt,- createdAt: DateTime.formatIso(now),- })- .onConflictDoUpdate({- target: [- relayAgentActivityRows.environmentId,- relayAgentActivityRows.environmentPublicKey,- relayAgentActivityRows.threadId,- ],- set: {- stateJson,- updatedAt: input.state.updatedAt,- },- })- .pipe(- Effect.mapError(- (cause) =>- new AgentActivityRowUpsertPersistenceError({- environmentId: input.state.environmentId,- threadId: input.state.threadId,- cause,- }),- ),- );- }),-- remove: Effect.fn("relay.agent_activity_rows.remove")(function* (input) {- yield* Effect.annotateCurrentSpan({- "relay.environment_id": input.environmentId,- "relay.thread_id": input.threadId,- });- yield* db- .delete(relayAgentActivityRows)- .where(- and(- eq(relayAgentActivityRows.environmentId, input.environmentId),- eq(relayAgentActivityRows.environmentPublicKey, input.environmentPublicKey),- eq(relayAgentActivityRows.threadId, input.threadId),- ),- )- .pipe(- Effect.mapError(- (cause) =>- new AgentActivityRowDeletePersistenceError({- environmentId: input.environmentId,- threadId: input.threadId,- cause,- }),- ),- );- }),-- pruneTerminal: Effect.fn("relay.agent_activity_rows.prune_terminal")(function* (input) {- yield* Effect.annotateCurrentSpan({- "relay.agent_activity_prune.before": input.updatedBefore,- });- yield* db- .delete(relayAgentActivityRows)- .where(- and(- sql`${relayAgentActivityRows.stateJson} ->> 'phase' IN ('completed', 'failed')`,- lt(relayAgentActivityRows.updatedAt, input.updatedBefore),- ),- )- .pipe(- Effect.mapError(- (cause) =>- new AgentActivityRowPruneTerminalPersistenceError({- updatedBefore: input.updatedBefore,- cause,- }),- ),- );- }),-- listForUser: Effect.fn("relay.agent_activity_rows.list_for_user")(function* (input) {- return yield* db- .select({ stateJson: relayAgentActivityRows.stateJson })- .from(relayAgentActivityRows)- .innerJoin(- relayEnvironmentLinks,- and(- eq(relayEnvironmentLinks.environmentId, relayAgentActivityRows.environmentId),- eq(- relayEnvironmentLinks.environmentPublicKey,- relayAgentActivityRows.environmentPublicKey,- ),- ),- )- .where(- and(- eq(relayEnvironmentLinks.userId, input.userId),- isNull(relayEnvironmentLinks.revokedAt),- eq(relayEnvironmentLinks.liveActivitiesEnabled, true),- ),- )- .orderBy(desc(relayAgentActivityRows.updatedAt))- .pipe(- Effect.flatMap((rows) =>- Effect.forEach(rows, (row) => encodeJsonValue(row.stateJson), {- concurrency: "unbounded",- }),- ),- Effect.map((rows) =>- rows.flatMap((row) => Option.toArray(decodeRelayAgentActivityStateJson(row))),- ),- Effect.mapError(- (cause) =>- new AgentActivityRowListPersistenceError({- userId: input.userId,- cause,- }),- ),- );- }),-- getForUserThread: Effect.fn("relay.agent_activity_rows.get_for_user_thread")(function* (input) {- return yield* db- .select({ stateJson: relayAgentActivityRows.stateJson })- .from(relayAgentActivityRows)- .innerJoin(- relayEnvironmentLinks,- and(- eq(relayEnvironmentLinks.environmentId, relayAgentActivityRows.environmentId),- eq(- relayEnvironmentLinks.environmentPublicKey,- relayAgentActivityRows.environmentPublicKey,- ),- ),- )- .where(- and(- eq(relayEnvironmentLinks.userId, input.userId),- isNull(relayEnvironmentLinks.revokedAt),- eq(relayAgentActivityRows.environmentId, input.environmentId),- eq(relayAgentActivityRows.threadId, input.threadId),- ),- )- .orderBy(desc(relayAgentActivityRows.updatedAt))- .pipe(- Effect.flatMap((rows) =>- Effect.forEach(rows, (row) => encodeJsonValue(row.stateJson), {- concurrency: "unbounded",- }),- ),- Effect.map((rows) => {- for (const row of rows) {- const decoded = decodeRelayAgentActivityStateJson(row);- if (Option.isSome(decoded)) {- return decoded.value;- }- }- return null;- }),- Effect.mapError(- (cause) =>- new AgentActivityRowListPersistenceError({- userId: input.userId,- cause,- }),- ),- );- }),- });-});--export const layer = Layer.effect(AgentActivityRows, make);diff --git a/infra/relay/src/agentActivity/ApnsClient.test.ts b/infra/relay/src/agentActivity/ApnsClient.test.tsdeleted file mode 100644index 9f9877533..000000000--- a/infra/relay/src/agentActivity/ApnsClient.test.ts+++ /dev/null@@ -1,364 +0,0 @@-import * as NodeCrypto from "node:crypto";--import { EnvironmentId, ThreadId } from "@t3tools/contracts";-import type { RelayAgentActivityAggregateState } from "@t3tools/contracts/relay";-import { describe, expect, it } from "@effect/vitest";-import * as DateTime from "effect/DateTime";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";-import * as Redacted from "effect/Redacted";-import * as Schema from "effect/Schema";-import * as HttpClient from "effect/unstable/http/HttpClient";-import * as HttpClientError from "effect/unstable/http/HttpClientError";-import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";--import type { ApnsCredentials } from "../Config.ts";-import * as ApnsClient from "./ApnsClient.ts";-import * as ApnsProviderTokens from "./ApnsProviderTokens.ts";--const isApnsJwtSigningError = Schema.is(ApnsClient.ApnsJwtSigningError);-const isApnsHttpRequestError = Schema.is(ApnsClient.ApnsHttpRequestError);--const TestLayer = ApnsClient.layer.pipe(- Layer.provide(ApnsProviderTokens.layer),- Layer.provide(- Layer.succeed(- HttpClient.HttpClient,- HttpClient.make(() => Effect.die("unexpected APNs HTTP request")),- ),- ),-);--describe("ApnsClient", () => {- const now = DateTime.makeUnsafe(0);- const state: RelayAgentActivityAggregateState = {- title: "T3 Code",- subtitle: "Agent work in progress",- activeCount: 1,- updatedAt: DateTime.formatIso(now),- activities: [- {- environmentId: EnvironmentId.make("env"),- threadId: ThreadId.make("thread"),- projectTitle: "Project",- threadTitle: "Thread",- modelTitle: "gpt-5.4",- phase: "running" as const,- status: "Working",- updatedAt: DateTime.formatIso(now),- deepLink: "/",- },- ],- };-- it.effect("requests an update push token when remotely starting a Live Activity", () =>- Effect.gen(function* () {- const apns = yield* ApnsClient.ApnsClient;- const request = apns.makeLiveActivityRequest({- event: "start",- token: "token",- state,- nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),- nowIso: DateTime.formatIso(now),- });-- expect(request.priority).toBe("10");- expect(request.payload).toMatchObject({- aps: {- event: "start",- "attributes-type": "LiveActivityAttributes",- "input-push-token": 1,- "content-state": {- name: "AgentActivity",- },- },- });- }).pipe(Effect.provide(TestLayer)),- );-- it.effect("builds a low-priority update payload", () =>- Effect.gen(function* () {- const apns = yield* ApnsClient.ApnsClient;- const request = apns.makeLiveActivityRequest({- event: "update",- token: "token",- state,- nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),- nowIso: DateTime.formatIso(now),- });-- expect(request.priority).toBe("5");- expect(request.payload).toMatchObject({- aps: {- event: "update",- "content-state": {- name: "AgentActivity",- },- },- });- }).pipe(Effect.provide(TestLayer)),- );-- it.effect("builds a high-priority alerting update payload when an alert is attached", () =>- Effect.gen(function* () {- const apns = yield* ApnsClient.ApnsClient;- const request = apns.makeLiveActivityRequest({- event: "update",- token: "token",- state,- alert: { title: "Thread", body: "Approval: Project" },- nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),- nowIso: DateTime.formatIso(now),- });-- expect(request.priority).toBe("10");- expect(request.payload).toMatchObject({- aps: {- event: "update",- alert: {- title: "Thread",- body: "Approval: Project",- sound: "default",- },- },- });- }).pipe(Effect.provide(TestLayer)),- );-- it.effect("builds an end payload with a dismissal date", () =>- Effect.gen(function* () {- const apns = yield* ApnsClient.ApnsClient;- const request = apns.makeLiveActivityRequest({- event: "end",- token: "token",- state,- nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),- nowIso: DateTime.formatIso(now),- });-- expect(request.priority).toBe("10");- expect(request.payload).toMatchObject({- aps: {- event: "end",- "dismissal-date": 300,- },- });-- // Without final content the card would freeze on its previous state;- // contentless ends dismiss quickly instead.- const contentless = apns.makeLiveActivityRequest({- event: "end",- token: "token",- state: null,- nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),- nowIso: DateTime.formatIso(now),- });- expect(contentless.payload).toMatchObject({- aps: {- event: "end",- "dismissal-date": 15,- },- });- }).pipe(Effect.provide(TestLayer)),- );-- it.effect("builds a standard APNs alert payload with routing metadata", () =>- Effect.gen(function* () {- const apns = yield* ApnsClient.ApnsClient;- const request = apns.makePushNotificationRequest({- token: "push-token",- notification: {- title: "Thread",- body: "Input: Project",- environmentId: "env",- threadId: "thread",- deepLink: "/threads/env/thread",- },- });-- expect(request.priority).toBe("10");- expect(request.payload).toMatchObject({- aps: {- alert: {- title: "Thread",- body: "Input: Project",- },- sound: "default",- },- environmentId: "env",- threadId: "thread",- deepLink: "/threads/env/thread",- });- }).pipe(Effect.provide(TestLayer)),- );-- it.effect("preserves JWT signing context and the crypto cause", () =>- Effect.gen(function* () {- const apns = yield* ApnsClient.ApnsClient;- const request = apns.makePushNotificationRequest({- token: "push-token",- notification: {- title: "Thread",- body: "Input: Project",- environmentId: "env",- threadId: "thread",- deepLink: "/threads/env/thread",- },- });- const error = yield* Effect.flip(- apns.sendPushNotificationRequest({- credentials: {- teamId: "team-1",- keyId: "key-1",- privateKey: Redacted.make("not-a-private-key"),- bundleId: "com.t3tools.test",- environment: "sandbox",- },- request,- issuedAtUnixSeconds: 123,- }),- );-- expect(isApnsJwtSigningError(error)).toBe(true);- if (!isApnsJwtSigningError(error)) {- return yield* Effect.die("expected APNs JWT signing error");- }- expect(error).toMatchObject({- teamId: "team-1",- keyId: "key-1",- // The provider-token service quantizes iat to the reuse window, so- // the signing context carries the window start rather than the raw- // request time.- issuedAtUnixSeconds: 0,- cause: expect.any(Error),- message: "Failed to sign APNs JWT for key key-1.",- });- }).pipe(Effect.provide(TestLayer)),- );-- it.effect("preserves APNs request context and the HTTP cause", () => {- const httpCause = new Error("network unavailable");- const { privateKey } = NodeCrypto.generateKeyPairSync("ec", {- namedCurve: "prime256v1",- privateKeyEncoding: { type: "pkcs8", format: "pem" },- publicKeyEncoding: { type: "spki", format: "pem" },- });- const credentials = {- teamId: "team-1",- keyId: "key-1",- privateKey: Redacted.make(privateKey),- bundleId: "com.t3tools.test",- environment: "sandbox",- } satisfies ApnsCredentials;- const failingHttpClient = HttpClient.make((request) =>- Effect.fail(- new HttpClientError.HttpClientError({- reason: new HttpClientError.TransportError({ request, cause: httpCause }),- }),- ),- );- const layer = ApnsClient.layer.pipe(- Layer.provide(ApnsProviderTokens.layer),- Layer.provide(Layer.succeed(HttpClient.HttpClient, failingHttpClient)),- );-- return Effect.gen(function* () {- const apns = yield* ApnsClient.ApnsClient;- const request = apns.makePushNotificationRequest({- token: "long-push-token",- notification: {- title: "Thread",- body: "Input: Project",- environmentId: "env",- threadId: "thread",- deepLink: "/threads/env/thread",- },- });- const error = yield* Effect.flip(- apns.sendPushNotificationRequest({- credentials,- request,- issuedAtUnixSeconds: 123,- }),- );-- expect(isApnsHttpRequestError(error)).toBe(true);- if (!isApnsHttpRequestError(error)) {- return yield* Effect.die("expected APNs HTTP request error");- }- expect(error).toMatchObject({- requestKind: "push-notification",- event: null,- environment: "sandbox",- bundleId: "com.t3tools.test",- tokenSuffix: "sh-token",- stage: "send",- status: null,- message: "APNs push-notification request failed during send in sandbox.",- });- expect(error.cause).toBeInstanceOf(HttpClientError.HttpClientError);- expect((error.cause as HttpClientError.HttpClientError).reason).toMatchObject({- _tag: "TransportError",- cause: httpCause,- });- }).pipe(Effect.provide(layer));- });-- it.effect("reuses the signed provider JWT across pushes within the reuse window", () => {- ApnsProviderTokens.__resetApnsProviderTokenCacheForTest();- const { privateKey } = NodeCrypto.generateKeyPairSync("ec", {- namedCurve: "prime256v1",- privateKeyEncoding: { type: "pkcs8", format: "pem" },- publicKeyEncoding: { type: "spki", format: "pem" },- });- const credentials = {- teamId: "team-jwt-cache",- keyId: "key-jwt-cache",- privateKey: Redacted.make(privateKey),- bundleId: "com.t3tools.test",- environment: "sandbox",- } satisfies ApnsCredentials;- const authorizations: Array<string> = [];- const capturingHttpClient = HttpClient.make((request) => {- authorizations.push(request.headers.authorization ?? "");- return Effect.succeed(- HttpClientResponse.fromWeb(- request,- new Response("", { status: 200, headers: { "apns-id": "apns-id-1" } }),- ),- );- });- const layer = ApnsClient.layer.pipe(- Layer.provide(ApnsProviderTokens.layer),- Layer.provide(Layer.succeed(HttpClient.HttpClient, capturingHttpClient)),- );-- return Effect.gen(function* () {- const apns = yield* ApnsClient.ApnsClient;- const request = apns.makePushNotificationRequest({- token: "push-token",- notification: {- title: "Thread",- body: "Input: Project",- environmentId: "env",- threadId: "thread",- deepLink: "/threads/env/thread",- },- });- const send = (issuedAtUnixSeconds: number) =>- apns.sendPushNotificationRequest({ credentials, request, issuedAtUnixSeconds });-- const window = ApnsProviderTokens.APNS_JWT_REUSE_SECONDS;- yield* send(window + 10);- yield* send(window * 2 - 1);- yield* send(window * 2);-- expect(authorizations).toHaveLength(3);- // Within the 45-minute window APNs must see the byte-identical token;- // refreshing it per push trips TooManyProviderTokenUpdates.- expect(authorizations[1]).toBe(authorizations[0]);- expect(authorizations[2]).not.toBe(authorizations[0]);- ApnsProviderTokens.__resetApnsProviderTokenCacheForTest();- }).pipe(Effect.provide(layer));- });-});diff --git a/infra/relay/src/agentActivity/ApnsClient.ts b/infra/relay/src/agentActivity/ApnsClient.tsdeleted file mode 100644index c401eb6c2..000000000--- a/infra/relay/src/agentActivity/ApnsClient.ts+++ /dev/null@@ -1,355 +0,0 @@-import type { RelayAgentActivityAggregateState } from "@t3tools/contracts/relay";-import * as Context from "effect/Context";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";-import * as Option from "effect/Option";-import * as Schema from "effect/Schema";-import * as Headers from "effect/unstable/http/Headers";-import * as HttpClient from "effect/unstable/http/HttpClient";-import * as HttpClientRequest from "effect/unstable/http/HttpClientRequest";-import { ApnsEnvironment as ApnsEnvironmentSchema, type ApnsCredentials } from "../Config.ts";-import type { ApnsLiveActivityAlert, ApnsNotificationPayload } from "./apnsDeliveryJobs.ts";-import { ApnsJwtEncodingError, ApnsJwtSigningError } from "./apnsJwt.ts";-import * as ApnsProviderTokens from "./ApnsProviderTokens.ts";--export { ApnsJwtEncodingError, ApnsJwtSigningError } from "./apnsJwt.ts";--const LIVE_ACTIVITY_NAME = "AgentActivity";-// Updates only flow on domain events, so a healthy agent can be silent for-// minutes (long tool calls, pending approvals). Two minutes made iOS dim-// perfectly healthy activities; ten minutes still bounds how long a dead-// environment can look alive.-const STALE_AFTER_SECONDS = 10 * 60;-const DISMISS_AFTER_SECONDS = 5 * 60;-// An end without a final content-state leaves whatever the card last showed-// frozen on the lock screen until dismissal — get it off quickly instead of-// parading stale state for the full window.-const CONTENTLESS_DISMISS_AFTER_SECONDS = 15;--const ApnsLiveActivityEventSchema = Schema.Literals(["start", "update", "end"]);-export type ApnsLiveActivityEvent = typeof ApnsLiveActivityEventSchema.Type;--const ApnsRequestKindSchema = Schema.Literals(["live-activity", "push-notification"]);--interface ApnsLiveActivityRequest {- readonly token: string;- readonly event: ApnsLiveActivityEvent;- readonly priority: "5" | "10";- readonly payload: unknown;-}--interface ApnsPushNotificationRequest {- readonly token: string;- readonly priority: "10";- readonly payload: unknown;-}--export interface ApnsDeliveryResult {- readonly ok: boolean;- readonly status: number;- readonly reason?: string;- readonly apnsId: string | null;-}--export class ApnsHttpRequestError extends Schema.TaggedErrorClass<ApnsHttpRequestError>()(- "ApnsHttpRequestError",- {- requestKind: ApnsRequestKindSchema,- event: Schema.NullOr(ApnsLiveActivityEventSchema),- environment: ApnsEnvironmentSchema,- bundleId: Schema.String,- tokenSuffix: Schema.String,- stage: Schema.Literals(["send", "read-response"]),- status: Schema.NullOr(Schema.Number),- cause: Schema.Defect(),- },-) {- override get message(): string {- return `APNs ${this.requestKind} request failed during ${this.stage} in ${this.environment}.`;- }-}--export const ApnsError = Schema.Union([- ApnsJwtEncodingError,- ApnsJwtSigningError,- ApnsHttpRequestError,-]);-export type ApnsError = typeof ApnsError.Type;--const decodeApnsErrorResponseJson = Schema.decodeUnknownOption(- Schema.fromJsonString(- Schema.Struct({- reason: Schema.optional(Schema.String),- }),- ),-);-function contentState(state: RelayAgentActivityAggregateState) {- return {- name: LIVE_ACTIVITY_NAME,- props: JSON.stringify(state),- };-}--interface LiveActivityRequestBase {- readonly token: string;- readonly nowEpochSeconds: number;- readonly nowIso: string;-}--type MakeLiveActivityRequestInput =- | (LiveActivityRequestBase & {- readonly event: "end";- readonly state: RelayAgentActivityAggregateState | null;- readonly alert?: ApnsLiveActivityAlert | null;- })- | (LiveActivityRequestBase & {- readonly event: "start" | "update";- readonly state: RelayAgentActivityAggregateState;- readonly alert?: ApnsLiveActivityAlert | null;- });--// An alert dict on an update/end makes it an "alerting" update: iOS wakes the-// screen and plays the haptic (the Apple Sports score-change behavior) instead-// of silently redrawing the activity.-function liveActivityAlertPayload(alert: ApnsLiveActivityAlert) {- return {- alert: {- title: alert.title,- body: alert.body,- sound: "default",- },- };-}--function makeLiveActivityRequest(input: MakeLiveActivityRequestInput): ApnsLiveActivityRequest {- const timestamp = input.nowEpochSeconds;- if (input.event === "end") {- return {- token: input.token,- event: input.event,- priority: "10",- payload: {- aps: {- timestamp,- event: "end",- ...(input.state ? { "content-state": contentState(input.state) } : {}),- ...(input.alert ? liveActivityAlertPayload(input.alert) : {}),- "dismissal-date":- timestamp + (input.state ? DISMISS_AFTER_SECONDS : CONTENTLESS_DISMISS_AFTER_SECONDS),- },- },- };- }-- const state = input.state;- return {- token: input.token,- event: input.event,- // Alerting updates must land immediately; routine redraws stay at the- // budget-friendly low priority.- priority: input.event === "update" && !input.alert ? "5" : "10",- payload: {- aps: {- timestamp,- event: input.event,- ...(input.event === "start"- ? {- "attributes-type": "LiveActivityAttributes",- attributes: {},- "input-push-token": 1,- alert: {- title: state.title,- body: state.subtitle,- },- }- : {}),- ...(input.event === "update" && input.alert ? liveActivityAlertPayload(input.alert) : {}),- "content-state": contentState(state),- "stale-date": timestamp + STALE_AFTER_SECONDS,- },- },- };-}--function makePushNotificationRequest(input: {- readonly token: string;- readonly notification: ApnsNotificationPayload;-}): ApnsPushNotificationRequest {- return {- token: input.token,- priority: "10",- payload: {- aps: {- alert: {- title: input.notification.title,- body: input.notification.body,- },- sound: "default",- },- environmentId: input.notification.environmentId,- threadId: input.notification.threadId,- deepLink: input.notification.deepLink,- },- };-}--function apnsReasonFromBody(body: string): string | undefined {- if (body.trim().length === 0) {- return undefined;- }- return Option.match(decodeApnsErrorResponseJson(body), {- onNone: () => body,- onSome: (parsed) => parsed.reason ?? body,- });-}--export class ApnsClient extends Context.Service<- ApnsClient,- {- readonly makeLiveActivityRequest: typeof makeLiveActivityRequest;- readonly makePushNotificationRequest: typeof makePushNotificationRequest;- readonly sendLiveActivityRequest: (input: {- readonly credentials: ApnsCredentials;- readonly request: ApnsLiveActivityRequest;- readonly issuedAtUnixSeconds: number;- }) => Effect.Effect<ApnsDeliveryResult, ApnsError>;- readonly sendPushNotificationRequest: (input: {- readonly credentials: ApnsCredentials;- readonly request: ApnsPushNotificationRequest;- readonly issuedAtUnixSeconds: number;- }) => Effect.Effect<ApnsDeliveryResult, ApnsError>;- }->()("t3code-relay/agentActivity/ApnsClient") {}--export const make = Effect.gen(function* () {- const httpClient = yield* HttpClient.HttpClient;- const providerTokens = yield* ApnsProviderTokens.ApnsProviderTokens;-- const sendLiveActivityRequest: ApnsClient["Service"]["sendLiveActivityRequest"] = Effect.fn(- "relay.apns.send_live_activity_request",- )(function* (input) {- yield* Effect.annotateCurrentSpan({ "relay.apns.event": input.request.event });- const jwt = yield* providerTokens.getJwt({- ...input.credentials,- issuedAtUnixSeconds: input.issuedAtUnixSeconds,- });- const host =- input.credentials.environment === "production"- ? "https://api.push.apple.com"- : "https://api.sandbox.push.apple.com";- const response = yield* HttpClientRequest.post(`${host}/3/device/${input.request.token}`).pipe(- HttpClientRequest.setHeaders({- authorization: `bearer ${jwt}`,- "apns-priority": input.request.priority,- "apns-push-type": "liveactivity",- "apns-topic": `${input.credentials.bundleId}.push-type.liveactivity`,- }),- HttpClientRequest.bodyJson(input.request.payload),- Effect.flatMap(httpClient.execute),- Effect.mapError(- (cause) =>- new ApnsHttpRequestError({- requestKind: "live-activity",- event: input.request.event,- environment: input.credentials.environment,- bundleId: input.credentials.bundleId,- tokenSuffix: input.request.token.slice(-8),- stage: "send",- status: null,- cause,- }),- ),- );- const responseText = yield* response.text.pipe(- Effect.mapError(- (cause) =>- new ApnsHttpRequestError({- requestKind: "live-activity",- event: input.request.event,- environment: input.credentials.environment,- bundleId: input.credentials.bundleId,- tokenSuffix: input.request.token.slice(-8),- stage: "read-response",- status: response.status,- cause,- }),- ),- );- const reason = apnsReasonFromBody(responseText);- return {- ok: response.status >= 200 && response.status < 300,- status: response.status,- ...(reason === undefined ? {} : { reason }),- apnsId: Option.getOrNull(Headers.get(response.headers, "apns-id")),- };- });-- const sendPushNotificationRequest: ApnsClient["Service"]["sendPushNotificationRequest"] =- Effect.fn("relay.apns.send_push_notification_request")(function* (input) {- yield* Effect.annotateCurrentSpan({ "relay.apns.event": "push_notification" });- const jwt = yield* providerTokens.getJwt({- ...input.credentials,- issuedAtUnixSeconds: input.issuedAtUnixSeconds,- });- const host =- input.credentials.environment === "production"- ? "https://api.push.apple.com"- : "https://api.sandbox.push.apple.com";- const response = yield* HttpClientRequest.post(- `${host}/3/device/${input.request.token}`,- ).pipe(- HttpClientRequest.setHeaders({- authorization: `bearer ${jwt}`,- "apns-priority": input.request.priority,- "apns-push-type": "alert",- "apns-topic": input.credentials.bundleId,- }),- HttpClientRequest.bodyJson(input.request.payload),- Effect.flatMap(httpClient.execute),- Effect.mapError(- (cause) =>- new ApnsHttpRequestError({- requestKind: "push-notification",- event: null,- environment: input.credentials.environment,- bundleId: input.credentials.bundleId,- tokenSuffix: input.request.token.slice(-8),- stage: "send",- status: null,- cause,- }),- ),- );- const responseText = yield* response.text.pipe(- Effect.mapError(- (cause) =>- new ApnsHttpRequestError({- requestKind: "push-notification",- event: null,- environment: input.credentials.environment,- bundleId: input.credentials.bundleId,- tokenSuffix: input.request.token.slice(-8),- stage: "read-response",- status: response.status,- cause,- }),- ),- );- const reason = apnsReasonFromBody(responseText);- return {- ok: response.status >= 200 && response.status < 300,- status: response.status,- ...(reason === undefined ? {} : { reason }),- apnsId: Option.getOrNull(Headers.get(response.headers, "apns-id")),- };- });-- return ApnsClient.of({- makeLiveActivityRequest,- makePushNotificationRequest,- sendLiveActivityRequest,- sendPushNotificationRequest,- });-});--export const layer = Layer.effect(ApnsClient, make);diff --git a/infra/relay/src/agentActivity/ApnsDeliveries.test.ts b/infra/relay/src/agentActivity/ApnsDeliveries.test.tsdeleted file mode 100644index 1c89b56da..000000000--- a/infra/relay/src/agentActivity/ApnsDeliveries.test.ts+++ /dev/null@@ -1,1787 +0,0 @@-import type {- RelayAgentActivityAggregateState,- RelayAgentActivityState,-} from "@t3tools/contracts/relay";-import * as NodeCryptoLayer from "@effect/platform-node/NodeCrypto";-import { describe, expect, it } from "@effect/vitest";-import * as NodeCrypto from "node:crypto";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";-import * as Logger from "effect/Logger";-import * as Redacted from "effect/Redacted";-import * as References from "effect/References";-import {- FetchHttpClient,- HttpClient,- HttpClientRequest,- HttpClientResponse,-} from "effect/unstable/http";--import {- makeApnsDeliveryJobPayload,- signApnsDeliveryJob,- type SignedApnsDeliveryJob,-} from "./apnsDeliveryJobs.ts";-import * as DeliveryAttempts from "./DeliveryAttempts.ts";-import * as LiveActivities from "./LiveActivities.ts";-import * as RelayConfiguration from "../Config.ts";-import * as ApnsDeliveryQueue from "./ApnsDeliveryQueue.ts";-import * as AgentActivityRows from "./AgentActivityRows.ts";-import * as ApnsDeliveries from "./ApnsDeliveries.ts";-import * as ApnsClient from "./ApnsClient.ts";-import * as ApnsProviderTokens from "./ApnsProviderTokens.ts";--const config = RelayConfiguration.RelayConfiguration.of({- relayIssuer: "https://relay.example.test",- apns: {- environment: "sandbox",- teamId: "team-id",- keyId: "key-id",- privateKey: Redacted.make("not-a-private-key"),- bundleId: "com.t3tools.t3code.dev",- },- apnsDeliveryJobSigningSecret: Redacted.make("job-signing-secret"),- clerkSecretKey: Redacted.make("clerk-secret"),- clerkPublishableKey: "pk_test_test",- clerkJwtAudience: "t3-code-relay",- cloudMintPrivateKey: Redacted.make("cloud-private-key"),- cloudMintPublicKey: "cloud-public-key",- managedEndpointBaseDomain: undefined,- managedEndpointNamespace: undefined,-});--const apnsSigningKeyPair = NodeCrypto.generateKeyPairSync("ec", {- namedCurve: "P-256",- privateKeyEncoding: { format: "pem", type: "pkcs8" },- publicKeyEncoding: { format: "pem", type: "spki" },-});--const signingConfig = RelayConfiguration.RelayConfiguration.of({- ...config,- apns: {- ...config.apns,- privateKey: Redacted.make(apnsSigningKeyPair.privateKey),- },-});--const state: RelayAgentActivityState = {- environmentId: "env" as RelayAgentActivityState["environmentId"],- threadId: "thread" as RelayAgentActivityState["threadId"],- projectTitle: "Project",- threadTitle: "Thread",- modelTitle: "gpt-5.4",- phase: "running",- headline: "Running",- updatedAt: "1970-01-01T00:00:00.000Z",- deepLink: "/",-};--const aggregate: RelayAgentActivityAggregateState = {- title: "T3 Code",- subtitle: "Agent work in progress",- activeCount: 1,- updatedAt: state.updatedAt,- activities: [- {- environmentId: state.environmentId,- threadId: state.threadId,- projectTitle: state.projectTitle,- threadTitle: state.threadTitle,- modelTitle: state.modelTitle,- phase: state.phase,- status: "Working",- updatedAt: state.updatedAt,- deepLink: state.deepLink,- },- ],-};--const enabledPreferences = JSON.stringify({- liveActivitiesEnabled: true,- notificationsEnabled: true,- notifyOnApproval: true,- notifyOnInput: true,- notifyOnCompletion: true,- notifyOnFailure: true,-});--const disabledPreferences = JSON.stringify({- liveActivitiesEnabled: false,- notificationsEnabled: true,- notifyOnApproval: true,- notifyOnInput: true,- notifyOnCompletion: true,- notifyOnFailure: true,-});--const notificationsDisabledPreferences = JSON.stringify({- liveActivitiesEnabled: false,- notificationsEnabled: false,- notifyOnApproval: true,- notifyOnInput: true,- notifyOnCompletion: true,- notifyOnFailure: true,-});--const target: LiveActivities.TargetRow = {- user_id: "dev:julius",- device_id: "device-1",- platform: "ios",- ios_major_version: 18,- app_version: "1.0.0",- bundle_id: null,- aps_environment: null,- push_token: null,- push_to_start_token: "start-token",- preferences_json: enabledPreferences,- activity_push_token: "activity-token",- remote_start_queued_at: null,- remote_started_at: "1970-01-01T00:00:00.000Z",- ended_at: null,- last_aggregate_json: null,- last_live_activity_delivery_at: null,-};--function makeLayer(input: {- readonly attempts: Array<DeliveryAttempts.DeliveryAttemptInput>;- readonly sourceJobClaims?: ReadonlyMap<string, DeliveryAttempts.DeliverySourceJobClaimResult>;- readonly queuedJobs?: Array<SignedApnsDeliveryJob>;- readonly queuedStarts?: Array<- Parameters<LiveActivities.LiveActivities["Service"]["markStartQueued"]>[0]- >;- readonly clearedStarts?: Array<- Parameters<LiveActivities.LiveActivities["Service"]["clearStartQueued"]>[0]- >;- readonly markedDeliveries?: Array<- Parameters<LiveActivities.LiveActivities["Service"]["markDelivery"]>[0]- >;- readonly invalidatedTokens?: Array<- Parameters<LiveActivities.LiveActivities["Service"]["invalidateDeliveryToken"]>[0]- >;- readonly currentTargets?: ReadonlyArray<LiveActivities.TargetRow>;- readonly config?: RelayConfiguration.RelayConfiguration["Service"];- // Live agent-activity rows returned by delivery-time state rechecks.- // Defaults to the fixture row so queued updates match unless a test is- // explicitly exercising stale-state behavior.- readonly activityStates?: ReadonlyArray<RelayAgentActivityState>;- // Current per-thread rows used to reject queued updates/notifications that- // have been superseded before APNs delivery.- readonly currentActivityStates?: ReadonlyArray<RelayAgentActivityState>;- readonly execute?: (- request: HttpClientRequest.HttpClientRequest,- ) => Effect.Effect<HttpClientResponse.HttpClientResponse>;-}) {- return ApnsDeliveries.layer.pipe(- Layer.provide(ApnsClient.layer),- Layer.provide(ApnsProviderTokens.layer),- Layer.provide(ApnsDeliveryQueue.layer.pipe(Layer.provide(NodeCryptoLayer.layer))),- Layer.provide(- Layer.mergeAll(- Layer.succeed(AgentActivityRows.AgentActivityRows, {- upsert: () => Effect.void,- remove: () => Effect.void,- pruneTerminal: () => Effect.void,- listForUser: () =>- input.activityStates !== undefined- ? Effect.succeed([...input.activityStates])- : Effect.succeed([state]),- getForUserThread: ({ environmentId, threadId }) =>- Effect.succeed(- (input.currentActivityStates ?? input.activityStates ?? [state]).find(- (current) =>- current.environmentId === environmentId && current.threadId === threadId,- ) ?? null,- ),- } satisfies AgentActivityRows.AgentActivityRows["Service"]),- Layer.succeed(ApnsDeliveryQueue.ApnsDeliveryQueueSender, {- send: (body) =>- Effect.sync(() => {- input.queuedJobs?.push(body);- }),- }),- Layer.succeed(DeliveryAttempts.DeliveryAttempts, {- record: (attempt) =>- Effect.sync(() => {- input.attempts.push(attempt);- }),- claimSourceJob: (attempt) =>- Effect.sync(() => {- const claim = input.sourceJobClaims?.get(attempt.sourceJobId);- if (claim) {- return claim;- }- input.attempts.push(attempt);- return "claimed";- }),- completeSourceJob: (completion) =>- Effect.sync(() => {- const attempt = input.attempts.find(- (row) => row.sourceJobId === completion.sourceJobId,- );- if (attempt) {- Object.assign(attempt, completion);- }- }),- }),- Layer.succeed(LiveActivities.LiveActivities, {- register: () => Effect.void,- listTargets: () => Effect.succeed(input.currentTargets ?? [target]),- markStartQueued: (queued) =>- Effect.sync(() => {- input.queuedStarts?.push(queued);- }),- clearStartQueued: (cleared) =>- Effect.sync(() => {- input.clearedStarts?.push(cleared);- }),- markDelivery: (delivery) =>- Effect.sync(() => {- input.markedDeliveries?.push(delivery);- }),- invalidateDeliveryToken: (invalidated) =>- Effect.sync(() => {- input.invalidatedTokens?.push(invalidated);- }),- }),- RelayConfiguration.layer(input.config ?? config),- input.execute- ? Layer.succeed(HttpClient.HttpClient, HttpClient.make(input.execute))- : FetchHttpClient.layer,- ),- ),- );-}--describe("ApnsDeliveries", () => {- it.effect("never starts an activity remotely when no update token is registered", () => {- const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];- const queuedJobs: Array<SignedApnsDeliveryJob> = [];- const queuedStarts: Array<- Parameters<LiveActivities.LiveActivities["Service"]["markStartQueued"]>[0]- > = [];-- return Effect.gen(function* () {- const deliveries = yield* ApnsDeliveries.ApnsDeliveries;- const result = yield* deliveries.sendForTarget({- target: {- ...target,- activity_push_token: null,- remote_started_at: null,- ended_at: "1970-01-01T00:00:05.000Z",- },- aggregate,- nowMs: 10_000,- });-- // Activities are armed by the app in the foreground; the relay never- // uses the push-to-start token, so the only fallback is the push- // notification channel (none here: the aggregate is not an attention- // phase).- expect(result).toBeNull();- expect(queuedJobs).toEqual([]);- expect(queuedStarts).toEqual([]);- expect(attempts).toEqual([]);- }).pipe(Effect.provide(makeLayer({ attempts, queuedJobs, queuedStarts })));- });-- it.effect("ends the armed card when nothing remains to show", () => {- const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];- const queuedJobs: Array<SignedApnsDeliveryJob> = [];-- return Effect.gen(function* () {- const deliveries = yield* ApnsDeliveries.ApnsDeliveries;- // Within the freshly-armed grace window an empty aggregate delivers- // nothing: the environment's first publish may still be in flight.- const graced = yield* deliveries.sendForTarget({- target,- aggregate: null,- nowMs: 5_000,- });- expect(graced).toBeNull();-- const result = yield* deliveries.sendForTarget({- target,- aggregate: null,- nowMs: 5_000 + 3 * 60 * 1_000,- });-- // An armed card always shows content (live or recently finished work);- // once the aggregate is empty the card ends rather than rendering an- // empty state. The app re-arms on the next open with content.- expect(result?.kind).toBe("live_activity_end");- expect(result?.ok).toBe(true);- expect(queuedJobs).toMatchObject([- {- payload: {- kind: "live_activity_end",- target: {- token: "activity-token",- },- },- },- ]);- expect(attempts).toEqual([]);- }).pipe(Effect.provide(makeLayer({ attempts, queuedJobs })));- });-- it.effect("does not queue a remote start when Live Activities are disabled", () => {- const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];- const queuedJobs: Array<SignedApnsDeliveryJob> = [];-- return Effect.gen(function* () {- const deliveries = yield* ApnsDeliveries.ApnsDeliveries;- const result = yield* deliveries.sendForTarget({- target: {- ...target,- activity_push_token: null,- remote_started_at: null,- ended_at: null,- preferences_json: disabledPreferences,- },- aggregate,- nowMs: 5_000,- });-- expect(result).toBeNull();- expect(queuedJobs).toEqual([]);- expect(attempts).toEqual([]);- }).pipe(Effect.provide(makeLayer({ attempts, queuedJobs })));- });-- it.effect("does not queue a duplicate remote start while a start is already queued", () => {- const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];- const queuedJobs: Array<SignedApnsDeliveryJob> = [];-- return Effect.gen(function* () {- const deliveries = yield* ApnsDeliveries.ApnsDeliveries;- const result = yield* deliveries.sendForTarget({- target: {- ...target,- activity_push_token: null,- remote_start_queued_at: "1970-01-01T00:00:03.000Z",- remote_started_at: null,- ended_at: null,- },- aggregate,- nowMs: 5_000,- });-- expect(result).toBeNull();- expect(queuedJobs).toEqual([]);- expect(attempts).toEqual([]);- }).pipe(Effect.provide(makeLayer({ attempts, queuedJobs })));- });-- it.effect("queues bounded Live Activity aggregate payloads", () => {- const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];- const queuedJobs: Array<SignedApnsDeliveryJob> = [];- const longTitle = "x".repeat(300);- const inputAggregate: RelayAgentActivityAggregateState = {- ...aggregate,- title: longTitle,- subtitle: longTitle,- activities: [0, 1, 2, 3, 4, 5].map((index) =>- Object.assign({}, aggregate.activities[0]!, {- projectTitle: longTitle,- threadTitle: longTitle,- modelTitle: longTitle,- status: longTitle,- threadId: `thread-${index}` as RelayAgentActivityState["threadId"],- deepLink: "https://example.test/not-an-app-link",- }),- ),- };-- return Effect.gen(function* () {- const deliveries = yield* ApnsDeliveries.ApnsDeliveries;- yield* deliveries.sendForTarget({- target,- aggregate: inputAggregate,- nowMs: 10_000,- });-- const payloadAggregate = queuedJobs[0]?.payload.aggregate;- expect(payloadAggregate?.title.length).toBeLessThanOrEqual(120);- expect(payloadAggregate?.subtitle.length).toBeLessThanOrEqual(120);- expect(payloadAggregate?.activities).toHaveLength(5);- expect(payloadAggregate?.activities[0]?.projectTitle.length).toBeLessThanOrEqual(120);- expect(payloadAggregate?.activities[0]?.status.length).toBeLessThanOrEqual(40);- expect(payloadAggregate?.activities[0]?.deepLink).toBe("/");- expect(attempts).toEqual([]);- }).pipe(Effect.provide(makeLayer({ attempts, queuedJobs })));- });-- it.effect("queues Live Activity jobs with the device's APNs routing", () => {- const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];- const queuedJobs: Array<SignedApnsDeliveryJob> = [];-- return Effect.gen(function* () {- const deliveries = yield* ApnsDeliveries.ApnsDeliveries;- yield* deliveries.sendForTarget({- target: {- ...target,- bundle_id: "com.t3tools.t3code.preview",- aps_environment: "production",- ended_at: "1970-01-01T00:00:05.000Z",- },- aggregate,- nowMs: 10_000,- });-- expect(queuedJobs).toMatchObject([- {- payload: {- kind: "live_activity_update",- target: {- token: "activity-token",- bundleId: "com.t3tools.t3code.preview",- apsEnvironment: "production",- },- },- },- ]);- }).pipe(Effect.provide(makeLayer({ attempts, queuedJobs })));- });-- it.effect("sends signed jobs to the device's APNs environment and bundle topic", () => {- const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];- const requests: Array<HttpClientRequest.HttpClientRequest> = [];- const payload = makeApnsDeliveryJobPayload({- kind: "live_activity_update",- userId: target.user_id,- deviceId: target.device_id,- token: "activity-token",- bundleId: "com.t3tools.t3code.preview",- apsEnvironment: "sandbox",- aggregate,- createdAt: "1970-01-01T00:00:00.000Z",- expiresAt: "1970-01-01T00:10:00.000Z",- jobId: "job-routing-1",- });- const signed = signApnsDeliveryJob({- secret: config.apnsDeliveryJobSigningSecret,- payload,- });- const execute = (request: HttpClientRequest.HttpClientRequest) =>- Effect.sync(() => {- requests.push(request);- return HttpClientResponse.fromWeb(request, new Response("", { status: 200 }));- });-- return Effect.gen(function* () {- const deliveries = yield* ApnsDeliveries.ApnsDeliveries;- const result = yield* deliveries.processSignedJob(signed);-- expect(result.ok).toBe(true);- expect(requests).toHaveLength(1);- expect(requests[0]?.url).toBe("https://api.sandbox.push.apple.com/3/device/activity-token");- expect(requests[0]?.headers["apns-topic"]).toBe(- "com.t3tools.t3code.preview.push-type.liveactivity",- );- }).pipe(- Effect.provide(- makeLayer({- attempts,- config: signingConfig,- execute,- }),- ),- );- });-- it.effect(- "suppresses all deliveries when the aggregate is unchanged while a row awaits input",- () => {- const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];- const queuedJobs: Array<SignedApnsDeliveryJob> = [];- const waitingAggregate: RelayAgentActivityAggregateState = {- ...aggregate,- activities: [- {- ...aggregate.activities[0]!,- phase: "waiting_for_input",- status: "Input",- },- ],- };- const waitingAggregateJson = JSON.stringify(waitingAggregate);-- return Effect.gen(function* () {- const deliveries = yield* ApnsDeliveries.ApnsDeliveries;- const result = yield* deliveries.sendForTarget({- target: {- ...target,- // A registered alert token must not turn the suppressed Live- // Activity update into an alert push on every republish.- push_token: "apns-device-token",- last_aggregate_json: waitingAggregateJson,- last_live_activity_delivery_at: "1970-01-01T00:00:04.000Z",- },- aggregate: waitingAggregate,- nowMs: 5_000,- });-- expect(result).toBeNull();- expect(queuedJobs).toEqual([]);- expect(attempts).toEqual([]);- }).pipe(Effect.provide(makeLayer({ attempts, queuedJobs })));- },- );-- it.effect(- "queues an update inside the throttle window when a changed aggregate awaits input",- () => {- const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];- const queuedJobs: Array<SignedApnsDeliveryJob> = [];- const waitingAggregate: RelayAgentActivityAggregateState = {- ...aggregate,- activities: [- {- ...aggregate.activities[0]!,- phase: "waiting_for_input",- status: "Input",- },- ],- };- const previousAggregateJson = JSON.stringify(aggregate);-- return Effect.gen(function* () {- const deliveries = yield* ApnsDeliveries.ApnsDeliveries;- const result = yield* deliveries.sendForTarget({- target: {- ...target,- last_aggregate_json: previousAggregateJson,- last_live_activity_delivery_at: "1970-01-01T00:00:04.000Z",- },- aggregate: waitingAggregate,- nowMs: 5_000,- });-- expect(result?.kind).toBe("live_activity_update");- expect(queuedJobs).toMatchObject([- {- payload: {- kind: "live_activity_update",- target: {- token: "activity-token",- },- },- },- ]);- }).pipe(Effect.provide(makeLayer({ attempts, queuedJobs })));- },- );-- it.effect(- "throttles updates for changed aggregates with stable counts and no pending attention",- () => {- const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];- const queuedJobs: Array<SignedApnsDeliveryJob> = [];- const changedAggregate: RelayAgentActivityAggregateState = {- ...aggregate,- updatedAt: "1970-01-01T00:00:04.000Z",- };- const previousAggregateJson = JSON.stringify(aggregate);-- return Effect.gen(function* () {- const deliveries = yield* ApnsDeliveries.ApnsDeliveries;- const result = yield* deliveries.sendForTarget({- target: {- ...target,- last_aggregate_json: previousAggregateJson,- last_live_activity_delivery_at: "1970-01-01T00:00:04.000Z",- },- aggregate: changedAggregate,- nowMs: 5_000,- });-- expect(result).toBeNull();- expect(queuedJobs).toEqual([]);- }).pipe(Effect.provide(makeLayer({ attempts, queuedJobs })));- },- );-- it.effect("queues an end for an active Live Activity when Live Activities are disabled", () => {- const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];- const queuedJobs: Array<SignedApnsDeliveryJob> = [];-- return Effect.gen(function* () {- const deliveries = yield* ApnsDeliveries.ApnsDeliveries;- const result = yield* deliveries.sendForTarget({- target: {- ...target,- preferences_json: disabledPreferences,- },- aggregate,- nowMs: 5_000,- });-- expect(result?.kind).toBe("live_activity_end");- expect(queuedJobs).toMatchObject([- {- payload: {- kind: "live_activity_end",- target: {- token: "activity-token",- },- },- },- ]);- expect(attempts).toEqual([]);- }).pipe(Effect.provide(makeLayer({ attempts, queuedJobs })));- });-- it.effect(- "queues an alert while ending an active Live Activity when only Live Activities are disabled",- () => {- const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];- const queuedJobs: Array<SignedApnsDeliveryJob> = [];- const inputAggregate: RelayAgentActivityAggregateState = {- ...aggregate,- activities: [- {- ...aggregate.activities[0]!,- phase: "waiting_for_input",- status: "Input",- },- ],- };-- return Effect.gen(function* () {- const deliveries = yield* ApnsDeliveries.ApnsDeliveries;- const result = yield* deliveries.sendForTarget({- target: {- ...target,- push_token: "apns-device-token",- preferences_json: disabledPreferences,- },- aggregate: inputAggregate,- nowMs: 5_000,- });-- expect(result?.kind).toBe("live_activity_end");- expect(queuedJobs).toMatchObject([- {- payload: {- kind: "live_activity_end",- target: {- token: "activity-token",- },- },- },- {- payload: {- kind: "push_notification",- target: {- token: "apns-device-token",- },- notification: {- title: "Thread",- body: "Input: Project",- environmentId: "env",- threadId: "thread",- deepLink: "/",- phase: "waiting_for_input",- updatedAt: state.updatedAt,- },- },- },- ]);- expect(attempts).toEqual([]);- }).pipe(Effect.provide(makeLayer({ attempts, queuedJobs })));- },- );-- it.effect("does not queue alert pushes when notification permission is disabled", () => {- const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];- const queuedJobs: Array<SignedApnsDeliveryJob> = [];- const inputAggregate: RelayAgentActivityAggregateState = {- ...aggregate,- activities: [- {- ...aggregate.activities[0]!,- phase: "waiting_for_input",- status: "Input",- },- ],- };-- return Effect.gen(function* () {- const deliveries = yield* ApnsDeliveries.ApnsDeliveries;- const result = yield* deliveries.sendForTarget({- target: {- ...target,- push_token: "apns-device-token",- preferences_json: notificationsDisabledPreferences,- },- aggregate: inputAggregate,- nowMs: 5_000,- });-- expect(result?.kind).toBe("live_activity_end");- expect(queuedJobs).toMatchObject([- {- payload: {- kind: "live_activity_end",- target: {- token: "activity-token",- },- },- },- ]);- expect(attempts).toEqual([]);- }).pipe(Effect.provide(makeLayer({ attempts, queuedJobs })));- });-- it.effect(- "queues a push notification for approval and input states when no Live Activity delivery is available",- () => {- const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];- const queuedJobs: Array<SignedApnsDeliveryJob> = [];- const inputAggregate: RelayAgentActivityAggregateState = {- ...aggregate,- activities: [- {- ...aggregate.activities[0]!,- phase: "waiting_for_input",- status: "Input",- },- ],- };-- return Effect.gen(function* () {- const deliveries = yield* ApnsDeliveries.ApnsDeliveries;- const result = yield* deliveries.sendForTarget({- target: {- ...target,- push_token: "apns-device-token",- push_to_start_token: null,- activity_push_token: null,- remote_started_at: null,- },- aggregate: inputAggregate,- nowMs: 5_000,- });-- expect(result?.kind).toBe("push_notification");- expect(result?.ok).toBe(true);- expect(queuedJobs).toMatchObject([- {- payload: {- kind: "push_notification",- target: {- token: "apns-device-token",- },- notification: {- title: "Thread",- body: "Input: Project",- environmentId: "env",- threadId: "thread",- deepLink: "/",- },- },- },- ]);- expect(attempts).toEqual([]);- }).pipe(Effect.provide(makeLayer({ attempts, queuedJobs })));- },- );-- it.effect("does not queue a push notification when a thread starts working", () => {- const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];- const queuedJobs: Array<SignedApnsDeliveryJob> = [];-- return Effect.gen(function* () {- const deliveries = yield* ApnsDeliveries.ApnsDeliveries;- const result = yield* deliveries.sendForTarget({- target: {- ...target,- push_token: "apns-device-token",- push_to_start_token: null,- activity_push_token: null,- remote_started_at: null,- },- aggregate,- nowMs: 5_000,- });-- expect(result).toBeNull();- expect(queuedJobs).toEqual([]);- expect(attempts).toEqual([]);- }).pipe(Effect.provide(makeLayer({ attempts, queuedJobs })));- });-- it.effect("queues bounded alert notification payloads", () => {- const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];- const queuedJobs: Array<SignedApnsDeliveryJob> = [];- const longTitle = "x".repeat(300);- const inputAggregate: RelayAgentActivityAggregateState = {- ...aggregate,- activities: [- {- ...aggregate.activities[0]!,- projectTitle: longTitle,- threadTitle: longTitle,- phase: "waiting_for_input",- status: "Input",- deepLink: "https://example.test/not-an-app-link",- },- ],- };-- return Effect.gen(function* () {- const deliveries = yield* ApnsDeliveries.ApnsDeliveries;- yield* deliveries.sendForTarget({- target: {- ...target,- push_token: "apns-device-token",- push_to_start_token: null,- activity_push_token: null,- remote_started_at: null,- },- aggregate: inputAggregate,- nowMs: 5_000,- });-- const notification = queuedJobs[0]?.payload.notification;- expect(notification?.title.length).toBeLessThanOrEqual(120);- expect(notification?.body.length).toBeLessThanOrEqual(120);- expect(notification?.deepLink).toBe("/");- expect(attempts).toEqual([]);- }).pipe(Effect.provide(makeLayer({ attempts, queuedJobs })));- });-- it.effect("preserves the schema cause for invalid queue payloads", () => {- const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];-- return Effect.gen(function* () {- const deliveries = yield* ApnsDeliveries.ApnsDeliveries;- const error = yield* Effect.flip(deliveries.processSignedJob({ invalid: true }));-- expect(error).toMatchObject({- _tag: "ApnsDeliveryJobQueuePayloadInvalid",- receivedType: "object",- message: "Invalid APNs delivery queue job with object payload.",- });- expect(error.cause).toMatchObject({ _tag: "SchemaError" });- }).pipe(Effect.provide(makeLayer({ attempts })));- });-- it.effect("skips a queued start when the user no longer has live work", () => {- const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];- const clearedStarts: Array<- Parameters<LiveActivities.LiveActivities["Service"]["clearStartQueued"]>[0]- > = [];- const payload = makeApnsDeliveryJobPayload({- kind: "live_activity_start",- userId: target.user_id,- deviceId: target.device_id,- token: target.push_to_start_token ?? "start-token",- aggregate,- createdAt: "1970-01-01T00:00:00.000Z",- expiresAt: "1970-01-01T00:10:00.000Z",- jobId: "job-start-1",- });- const signed = signApnsDeliveryJob({- secret: config.apnsDeliveryJobSigningSecret,- payload,- });-- return Effect.gen(function* () {- const deliveries = yield* ApnsDeliveries.ApnsDeliveries;- const result = yield* deliveries.processSignedJob(signed);-- // The start was decided from an aggregate that a newer terminal publish- // has since invalidated; delivering it would birth an orphan activity.- expect(result).toMatchObject({- kind: "live_activity_start",- ok: true,- apnsStatus: null,- });- expect(attempts).toMatchObject([- {- kind: "live_activity_start",- sourceJobId: "job-start-1",- apnsReason: "Stale APNs start job skipped.",- },- ]);- expect(clearedStarts).toMatchObject([{ userId: target.user_id, deviceId: target.device_id }]);- }).pipe(Effect.provide(makeLayer({ attempts, clearedStarts, activityStates: [] })));- });-- it.effect("processes signed jobs through APNs and records attempts", () => {- const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];- const transportErrors: Array<ApnsDeliveries.ApnsDeliveryTransportError> = [];- const logger = Logger.make(({ fiber }) => {- const annotation = fiber.getRef(References.CurrentLogAnnotations).error;- if (!Redacted.isRedacted(annotation)) {- return;- }- const error = Redacted.value(annotation);- if (ApnsDeliveries.isApnsDeliveryTransportError(error)) {- transportErrors.push(error);- }- });- const payload = makeApnsDeliveryJobPayload({- kind: "live_activity_update",- userId: target.user_id,- deviceId: target.device_id,- token: target.activity_push_token ?? "activity-token",- aggregate,- createdAt: "1970-01-01T00:00:00.000Z",- expiresAt: "1970-01-01T00:10:00.000Z",- jobId: "job-1",- });- const signed = signApnsDeliveryJob({- secret: config.apnsDeliveryJobSigningSecret,- payload,- });-- return Effect.gen(function* () {- const deliveries = yield* ApnsDeliveries.ApnsDeliveries;- const result = yield* deliveries.processSignedJob(signed);-- expect(result.kind).toBe("live_activity_update");- expect(result.ok).toBe(false);- expect(attempts).toMatchObject([- {- kind: "live_activity_update",- sourceJobId: "job-1",- token: "activity-token",- },- ]);- expect(transportErrors).toHaveLength(1);- const error = transportErrors[0]!;- expect(error).toMatchObject({- deviceId: target.device_id,- kind: "live_activity_update",- sourceJobId: "job-1",- apnsErrorTag: "ApnsJwtSigningError",- requestStage: null,- });- expect(error.cause).toBeInstanceOf(ApnsClient.ApnsJwtSigningError);- expect(error.cause).toMatchObject({- teamId: "team-id",- keyId: "key-id",- });- expect((error.cause as ApnsClient.ApnsJwtSigningError).cause).toBeDefined();- }).pipe(- Effect.provide(- Layer.mergeAll(- makeLayer({ attempts }),- Logger.layer([logger], { mergeWithExisting: false }),- ),- ),- );- });-- it.effect("processes signed push notification jobs through APNs and records attempts", () => {- const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];- const payload = makeApnsDeliveryJobPayload({- kind: "push_notification",- userId: target.user_id,- deviceId: target.device_id,- token: "apns-device-token",- aggregate: null,- notification: {- title: "Thread",- body: "Input: Project",- environmentId: "env",- threadId: "thread",- deepLink: "/",- },- createdAt: "1970-01-01T00:00:00.000Z",- expiresAt: "1970-01-01T00:10:00.000Z",- jobId: "job-push-1",- });- const signed = signApnsDeliveryJob({- secret: config.apnsDeliveryJobSigningSecret,- payload,- });- const execute = (request: HttpClientRequest.HttpClientRequest) =>- Effect.succeed(HttpClientResponse.fromWeb(request, new Response("", { status: 200 })));-- return Effect.gen(function* () {- const deliveries = yield* ApnsDeliveries.ApnsDeliveries;- const result = yield* deliveries.processSignedJob(signed);-- expect(result.kind).toBe("push_notification");- expect(result.ok).toBe(true);- expect(result.apnsStatus).toBe(200);- expect(attempts).toMatchObject([- {- kind: "push_notification",- sourceJobId: "job-push-1",- token: "apns-device-token",- environmentId: "env",- threadId: "thread",- deviceId: target.device_id,- apnsStatus: 200,- },- ]);- }).pipe(- Effect.provide(- makeLayer({- attempts,- currentTargets: [- {- ...target,- push_token: "apns-device-token",- },- ],- config: signingConfig,- execute,- }),- ),- );- });-- it.effect("skips duplicate signed queue jobs before calling APNs", () => {- const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];- let executeCount = 0;- const payload = makeApnsDeliveryJobPayload({- kind: "push_notification",- userId: target.user_id,- deviceId: target.device_id,- token: "apns-device-token",- aggregate: null,- notification: {- title: "Thread",- body: "Input: Project",- environmentId: "env",- threadId: "thread",- deepLink: "/",- },- createdAt: "1970-01-01T00:00:00.000Z",- expiresAt: "1970-01-01T00:10:00.000Z",- jobId: "job-push-duplicate",- });- const signed = signApnsDeliveryJob({- secret: config.apnsDeliveryJobSigningSecret,- payload,- });- const execute = (request: HttpClientRequest.HttpClientRequest) =>- Effect.sync(() => {- executeCount += 1;- return HttpClientResponse.fromWeb(request, new Response("", { status: 200 }));- });-- return Effect.gen(function* () {- const deliveries = yield* ApnsDeliveries.ApnsDeliveries;- const result = yield* deliveries.processSignedJob(signed);-- expect(result).toMatchObject({- kind: "push_notification",- ok: true,- apnsStatus: null,- apnsReason: "Duplicate APNs delivery job skipped.",- });- expect(executeCount).toBe(0);- expect(attempts).toEqual([]);- }).pipe(- Effect.provide(- makeLayer({- attempts,- sourceJobClaims: new Map([["job-push-duplicate", "completed"]]),- config: signingConfig,- execute,- }),- ),- );- });-- it.effect("skips stale signed Live Activity jobs when the registered token changed", () => {- const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];- let executeCount = 0;- const payload = makeApnsDeliveryJobPayload({- kind: "live_activity_update",- userId: target.user_id,- deviceId: target.device_id,- token: "stale-activity-token",- aggregate,- createdAt: "1970-01-01T00:00:00.000Z",- expiresAt: "1970-01-01T00:10:00.000Z",- jobId: "job-update-stale-token",- });- const signed = signApnsDeliveryJob({- secret: config.apnsDeliveryJobSigningSecret,- payload,- });- const execute = (request: HttpClientRequest.HttpClientRequest) =>- Effect.sync(() => {- executeCount += 1;- return HttpClientResponse.fromWeb(request, new Response("", { status: 200 }));- });-- return Effect.gen(function* () {- const deliveries = yield* ApnsDeliveries.ApnsDeliveries;- const result = yield* deliveries.processSignedJob(signed);-- expect(result).toMatchObject({- kind: "live_activity_update",- ok: true,- apnsStatus: null,- apnsReason: "Stale APNs delivery job skipped.",- });- expect(executeCount).toBe(0);- expect(attempts).toMatchObject([- {- kind: "live_activity_update",- sourceJobId: "job-update-stale-token",- token: "stale-activity-token",- apnsReason: "Stale APNs delivery job skipped.",- },- ]);- }).pipe(- Effect.provide(- makeLayer({- attempts,- config: signingConfig,- execute,- }),- ),- );- });-- it.effect("skips stale signed push notification jobs when the device token changed", () => {- const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];- let executeCount = 0;- const payload = makeApnsDeliveryJobPayload({- kind: "push_notification",- userId: target.user_id,- deviceId: target.device_id,- token: "stale-device-token",- aggregate: null,- notification: {- title: "Thread",- body: "Input: Project",- environmentId: "env",- threadId: "thread",- deepLink: "/",- },- createdAt: "1970-01-01T00:00:00.000Z",- expiresAt: "1970-01-01T00:10:00.000Z",- jobId: "job-push-stale-token",- });- const signed = signApnsDeliveryJob({- secret: config.apnsDeliveryJobSigningSecret,- payload,- });- const execute = (request: HttpClientRequest.HttpClientRequest) =>- Effect.sync(() => {- executeCount += 1;- return HttpClientResponse.fromWeb(request, new Response("", { status: 200 }));- });-- return Effect.gen(function* () {- const deliveries = yield* ApnsDeliveries.ApnsDeliveries;- const result = yield* deliveries.processSignedJob(signed);-- expect(result).toMatchObject({- kind: "push_notification",- ok: true,- apnsStatus: null,- apnsReason: "Stale APNs delivery job skipped.",- });- expect(executeCount).toBe(0);- expect(attempts).toMatchObject([- {- kind: "push_notification",- sourceJobId: "job-push-stale-token",- token: "stale-device-token",- apnsReason: "Stale APNs delivery job skipped.",- },- ]);- }).pipe(- Effect.provide(- makeLayer({- attempts,- currentTargets: [- {- ...target,- push_token: "current-device-token",- },- ],- config: signingConfig,- execute,- }),- ),- );- });-- it.effect("skips a queued Done Live Activity update after the thread resumes working", () => {- const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];- let executeCount = 0;- const completedAt = "1970-01-01T00:00:01.000Z";- const completedAggregate: RelayAgentActivityAggregateState = {- ...aggregate,- activeCount: 0,- updatedAt: completedAt,- activities: [- {- ...aggregate.activities[0]!,- phase: "completed",- status: "Done",- updatedAt: completedAt,- },- ],- };- const payload = makeApnsDeliveryJobPayload({- kind: "live_activity_update",- userId: target.user_id,- deviceId: target.device_id,- token: target.activity_push_token ?? "activity-token",- aggregate: completedAggregate,- alert: { title: "Thread", body: "Done: Project" },- createdAt: completedAt,- expiresAt: "1970-01-01T00:10:00.000Z",- jobId: "job-update-superseded-by-running",- });- const signed = signApnsDeliveryJob({- secret: config.apnsDeliveryJobSigningSecret,- payload,- });- const execute = (request: HttpClientRequest.HttpClientRequest) =>- Effect.sync(() => {- executeCount += 1;- return HttpClientResponse.fromWeb(request, new Response("", { status: 200 }));- });-- return Effect.gen(function* () {- const deliveries = yield* ApnsDeliveries.ApnsDeliveries;- const result = yield* deliveries.processSignedJob(signed);-- expect(result).toMatchObject({- kind: "live_activity_update",- ok: true,- apnsStatus: null,- apnsReason: "Stale APNs delivery job skipped.",- });- expect(executeCount).toBe(0);- expect(attempts).toMatchObject([- {- sourceJobId: "job-update-superseded-by-running",- apnsReason: "Stale agent activity state skipped.",- },- ]);- }).pipe(- Effect.provide(- makeLayer({- attempts,- activityStates: [- {- ...state,- phase: "running",- headline: "Running",- updatedAt: "1970-01-01T00:00:02.000Z",- },- ],- config: signingConfig,- execute,- }),- ),- );- });-- it.effect("skips a queued Done notification after the thread resumes working", () => {- const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];- let executeCount = 0;- const completedAt = "1970-01-01T00:00:01.000Z";- const payload = makeApnsDeliveryJobPayload({- kind: "push_notification",- userId: target.user_id,- deviceId: target.device_id,- token: "apns-device-token",- aggregate: null,- notification: {- title: "Thread",- body: "Done: Project",- environmentId: "env",- threadId: "thread",- deepLink: "/",- phase: "completed",- updatedAt: completedAt,- },- createdAt: completedAt,- expiresAt: "1970-01-01T00:10:00.000Z",- jobId: "job-push-superseded-by-running",- });- const signed = signApnsDeliveryJob({- secret: config.apnsDeliveryJobSigningSecret,- payload,- });- const execute = (request: HttpClientRequest.HttpClientRequest) =>- Effect.sync(() => {- executeCount += 1;- return HttpClientResponse.fromWeb(request, new Response("", { status: 200 }));- });-- return Effect.gen(function* () {- const deliveries = yield* ApnsDeliveries.ApnsDeliveries;- const result = yield* deliveries.processSignedJob(signed);-- expect(result).toMatchObject({- kind: "push_notification",- ok: true,- apnsStatus: null,- apnsReason: "Stale APNs delivery job skipped.",- });- expect(executeCount).toBe(0);- expect(attempts).toMatchObject([- {- sourceJobId: "job-push-superseded-by-running",- apnsReason: "Stale agent activity state skipped.",- },- ]);- }).pipe(- Effect.provide(- makeLayer({- attempts,- currentTargets: [{ ...target, push_token: "apns-device-token" }],- currentActivityStates: [- {- ...state,- phase: "running",- headline: "Running",- updatedAt: "1970-01-01T00:00:02.000Z",- },- ],- config: signingConfig,- execute,- }),- ),- );- });-- it.effect("retries signed queue jobs that are already claimed but not completed", () => {- const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];- let executeCount = 0;- const payload = makeApnsDeliveryJobPayload({- kind: "push_notification",- userId: target.user_id,- deviceId: target.device_id,- token: "apns-device-token",- aggregate: null,- notification: {- title: "Thread",- body: "Input: Project",- environmentId: "env",- threadId: "thread",- deepLink: "/",- },- createdAt: "1970-01-01T00:00:00.000Z",- expiresAt: "1970-01-01T00:10:00.000Z",- jobId: "job-push-in-flight",- });- const signed = signApnsDeliveryJob({- secret: config.apnsDeliveryJobSigningSecret,- payload,- });- const execute = (request: HttpClientRequest.HttpClientRequest) =>- Effect.sync(() => {- executeCount += 1;- return HttpClientResponse.fromWeb(request, new Response("", { status: 200 }));- });-- return Effect.gen(function* () {- const deliveries = yield* ApnsDeliveries.ApnsDeliveries;- const result = yield* Effect.exit(deliveries.processSignedJob(signed));-- expect(result._tag).toBe("Failure");- if (result._tag === "Failure") {- expect(result.cause.toString()).toContain("ApnsDeliveryJobClaimInFlight");- }- expect(executeCount).toBe(0);- expect(attempts).toEqual([]);- }).pipe(- Effect.provide(- makeLayer({- attempts,- sourceJobClaims: new Map([["job-push-in-flight", "in_flight"]]),- config: signingConfig,- execute,- }),- ),- );- });-- it.effect("invalidates dead device push tokens after permanent APNs alert failures", () => {- const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];- const invalidatedTokens: Array<- Parameters<LiveActivities.LiveActivities["Service"]["invalidateDeliveryToken"]>[0]- > = [];- const payload = makeApnsDeliveryJobPayload({- kind: "push_notification",- userId: target.user_id,- deviceId: target.device_id,- token: "apns-device-token",- aggregate: null,- notification: {- title: "Thread",- body: "Failed: Project",- environmentId: "env",- threadId: "thread",- deepLink: "/",- },- createdAt: "1970-01-01T00:00:00.000Z",- expiresAt: "1970-01-01T00:10:00.000Z",- jobId: "job-push-bad-token",- });- const signed = signApnsDeliveryJob({- secret: config.apnsDeliveryJobSigningSecret,- payload,- });- const execute = (request: HttpClientRequest.HttpClientRequest) =>- Effect.succeed(- HttpClientResponse.fromWeb(- request,- Response.json({ reason: "BadDeviceToken" }, { status: 400 }),- ),- );-- return Effect.gen(function* () {- const deliveries = yield* ApnsDeliveries.ApnsDeliveries;- const result = yield* deliveries.processSignedJob(signed);-- expect(result.kind).toBe("push_notification");- expect(result.ok).toBe(false);- expect(result.apnsStatus).toBe(400);- expect(result.apnsReason).toBe("BadDeviceToken");- expect(invalidatedTokens).toMatchObject([- {- userId: target.user_id,- deviceId: target.device_id,- kind: "push_notification",- },- ]);- }).pipe(- Effect.provide(- makeLayer({- attempts,- invalidatedTokens,- currentTargets: [- {- ...target,- push_token: "apns-device-token",- },- ],- config: signingConfig,- execute,- }),- ),- );- });-- it.effect("clears queued start state when a start job fails in APNs", () => {- const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];- const clearedStarts: Array<- Parameters<LiveActivities.LiveActivities["Service"]["clearStartQueued"]>[0]- > = [];- const payload = makeApnsDeliveryJobPayload({- kind: "live_activity_start",- userId: target.user_id,- deviceId: target.device_id,- token: target.push_to_start_token ?? "start-token",- aggregate,- createdAt: "1970-01-01T00:00:00.000Z",- expiresAt: "1970-01-01T00:10:00.000Z",- jobId: "job-start-1",- });- const signed = signApnsDeliveryJob({- secret: config.apnsDeliveryJobSigningSecret,- payload,- });-- return Effect.gen(function* () {- const deliveries = yield* ApnsDeliveries.ApnsDeliveries;- const result = yield* deliveries.processSignedJob(signed);-- expect(result.kind).toBe("live_activity_start");- expect(result.ok).toBe(false);- expect(clearedStarts).toEqual([- {- userId: target.user_id,- deviceId: target.device_id,- },- ]);- }).pipe(- Effect.provide(- makeLayer({- attempts,- clearedStarts,- activityStates: [{ ...state, updatedAt: "9999-01-01T00:00:00.000Z" }],- }),- ),- );- });-- it.effect("invalidates dead push-to-start tokens after permanent APNs start failures", () => {- const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];- const invalidatedTokens: Array<- Parameters<LiveActivities.LiveActivities["Service"]["invalidateDeliveryToken"]>[0]- > = [];- const payload = makeApnsDeliveryJobPayload({- kind: "live_activity_start",- userId: target.user_id,- deviceId: target.device_id,- token: target.push_to_start_token ?? "start-token",- aggregate,- createdAt: "1970-01-01T00:00:00.000Z",- expiresAt: "1970-01-01T00:10:00.000Z",- jobId: "job-start-bad-token",- });- const signed = signApnsDeliveryJob({- secret: config.apnsDeliveryJobSigningSecret,- payload,- });- const execute = (request: HttpClientRequest.HttpClientRequest) =>- Effect.succeed(- HttpClientResponse.fromWeb(- request,- Response.json({ reason: "BadDeviceToken" }, { status: 400 }),- ),- );-- return Effect.gen(function* () {- const deliveries = yield* ApnsDeliveries.ApnsDeliveries;- const result = yield* deliveries.processSignedJob(signed);-- expect(result.kind).toBe("live_activity_start");- expect(result.ok).toBe(false);- expect(result.apnsStatus).toBe(400);- expect(result.apnsReason).toBe("BadDeviceToken");- expect(invalidatedTokens).toMatchObject([- {- userId: target.user_id,- deviceId: target.device_id,- kind: "live_activity_start",- },- ]);- }).pipe(- Effect.provide(- makeLayer({- attempts,- invalidatedTokens,- activityStates: [{ ...state, updatedAt: "9999-01-01T00:00:00.000Z" }],- config: signingConfig,- execute,- }),- ),- );- });-- it.effect("invalidates dead Live Activity tokens after APNs unregisters them", () => {- const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];- const invalidatedTokens: Array<- Parameters<LiveActivities.LiveActivities["Service"]["invalidateDeliveryToken"]>[0]- > = [];- const payload = makeApnsDeliveryJobPayload({- kind: "live_activity_update",- userId: target.user_id,- deviceId: target.device_id,- token: target.activity_push_token ?? "activity-token",- aggregate,- createdAt: "1970-01-01T00:00:00.000Z",- expiresAt: "1970-01-01T00:10:00.000Z",- jobId: "job-update-unregistered",- });- const signed = signApnsDeliveryJob({- secret: config.apnsDeliveryJobSigningSecret,- payload,- });- const execute = (request: HttpClientRequest.HttpClientRequest) =>- Effect.succeed(- HttpClientResponse.fromWeb(- request,- Response.json({ reason: "Unregistered" }, { status: 410 }),- ),- );-- return Effect.gen(function* () {- const deliveries = yield* ApnsDeliveries.ApnsDeliveries;- const result = yield* deliveries.processSignedJob(signed);-- expect(result.kind).toBe("live_activity_update");- expect(result.ok).toBe(false);- expect(result.apnsStatus).toBe(410);- expect(result.apnsReason).toBe("Unregistered");- expect(invalidatedTokens).toMatchObject([- {- userId: target.user_id,- deviceId: target.device_id,- kind: "live_activity_update",- },- ]);- }).pipe(- Effect.provide(makeLayer({ attempts, invalidatedTokens, config: signingConfig, execute })),- );- });-});--describe("live activity alert decisions", () => {- const preferences = {- liveActivitiesEnabled: true,- notificationsEnabled: true,- notifyOnApproval: true,- notifyOnInput: true,- notifyOnCompletion: true,- notifyOnFailure: true,- };-- const attentionRow = {- ...aggregate.activities[0]!,- threadId: "thread-2" as RelayAgentActivityState["threadId"],- threadTitle: "Blocked thread",- phase: "waiting_for_approval" as const,- status: "Approval",- };-- it("alerts when a thread newly enters an attention phase", () => {- const alert = ApnsDeliveries.alertForAttentionTransition({- previousAggregate: aggregate,- nextAggregate: {- ...aggregate,- activeCount: 2,- activities: [...aggregate.activities, attentionRow],- },- preferences,- });- expect(alert).toEqual({ title: "Blocked thread", body: "Approval: Project" });- });-- it("stays silent when the attention phase was already delivered", () => {- const withAttention = {- ...aggregate,- activeCount: 2,- activities: [...aggregate.activities, attentionRow],- };- expect(- ApnsDeliveries.alertForAttentionTransition({- previousAggregate: withAttention,- nextAggregate: withAttention,- preferences,- }),- ).toBeNull();- });-- it("stays silent without a delivered baseline so replays cannot buzz", () => {- expect(- ApnsDeliveries.alertForAttentionTransition({- previousAggregate: null,- nextAggregate: { ...aggregate, activities: [attentionRow] },- preferences,- }),- ).toBeNull();- });-- it("honors the per-event notification switch for attention alerts", () => {- expect(- ApnsDeliveries.alertForAttentionTransition({- previousAggregate: aggregate,- nextAggregate: {- ...aggregate,- activeCount: 2,- activities: [...aggregate.activities, attentionRow],- },- preferences: { ...preferences, notifyOnApproval: false },- }),- ).toBeNull();- });-- it("summarizes multiple newly blocked threads in one alert", () => {- const secondAttentionRow = {- ...attentionRow,- threadId: "thread-3" as RelayAgentActivityState["threadId"],- threadTitle: "Other blocked thread",- phase: "waiting_for_input" as const,- status: "Input",- };- const alert = ApnsDeliveries.alertForAttentionTransition({- previousAggregate: aggregate,- nextAggregate: {- ...aggregate,- activeCount: 3,- activities: [...aggregate.activities, attentionRow, secondAttentionRow],- },- preferences,- });- expect(alert).toEqual({- title: "2 agents need attention",- body: "Blocked thread, Other blocked thread",- });- });-- it("alerts for a terminal aggregate and honors the completion switch", () => {- const terminalAggregate = {- ...aggregate,- activeCount: 0,- activities: [{ ...aggregate.activities[0]!, phase: "completed" as const, status: "Done" }],- };- expect(- ApnsDeliveries.alertForTerminalAggregate({ aggregate: terminalAggregate, preferences }),- ).toEqual({ title: "Thread", body: "Done: Project" });- expect(- ApnsDeliveries.alertForTerminalAggregate({- aggregate: terminalAggregate,- preferences: { ...preferences, notifyOnCompletion: false },- }),- ).toBeNull();- expect(ApnsDeliveries.alertForTerminalAggregate({ aggregate: null, preferences })).toBeNull();- });-- it("alerts when a previously active thread finishes mid-flight", () => {- const doneRow = {- ...aggregate.activities[0]!,- phase: "completed" as const,- status: "Done",- };- const next = {- ...aggregate,- activeCount: 0,- activities: [attentionRow, doneRow],- };- expect(- ApnsDeliveries.alertForNewlyTerminal({- previousAggregate: aggregate,- nextAggregate: next,- preferences,- nowMs: 0,- }),- ).toEqual({ title: "Thread", body: "Done: Project" });- // The completion switch mutes it.- expect(- ApnsDeliveries.alertForNewlyTerminal({- previousAggregate: aggregate,- nextAggregate: next,- preferences: { ...preferences, notifyOnCompletion: false },- nowMs: 0,- }),- ).toBeNull();- // No baseline means no transition to ring on.- expect(- ApnsDeliveries.alertForNewlyTerminal({- previousAggregate: null,- nextAggregate: next,- preferences,- nowMs: 0,- }),- ).toBeNull();- // A Done row that was already terminal (or absent) before stays silent.- expect(- ApnsDeliveries.alertForNewlyTerminal({- previousAggregate: next,- nextAggregate: next,- preferences,- nowMs: 0,- }),- ).toBeNull();- expect(- ApnsDeliveries.alertForNewlyTerminal({- previousAggregate: { ...aggregate, activities: [attentionRow] },- nextAggregate: next,- preferences,- nowMs: 0,- }),- ).toBeNull();- });-});diff --git a/infra/relay/src/agentActivity/ApnsDeliveries.ts b/infra/relay/src/agentActivity/ApnsDeliveries.tsdeleted file mode 100644index 9db9be3f1..000000000--- a/infra/relay/src/agentActivity/ApnsDeliveries.ts+++ /dev/null@@ -1,1279 +0,0 @@-import type {- RelayAgentActivityAggregateState,- RelayAgentAwarenessPreferences,- RelayDeliveryKind,- RelayDeliveryResult,-} from "@t3tools/contracts/relay";-import {- RelayAgentActivityAggregateState as RelayAgentActivityAggregateStateSchema,- RelayAgentAwarenessPreferences as RelayAgentAwarenessPreferencesSchema,- RelayDeliveryKind as RelayDeliveryKindSchema,-} from "@t3tools/contracts/relay";-import * as Context from "effect/Context";-import * as DateTime from "effect/DateTime";-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 {- isExpiredAgentActivityState,- isTerminalPhase,- sanitizeAgentActivityAggregateState,- sanitizeApnsNotificationPayload,-} from "./agentActivityPayloads.ts";-import * as Apns from "./ApnsClient.ts";-import {- ApnsDeliveryJobLiveActivityAggregateMissing,- ApnsDeliveryJobPushNotificationMissing,- ApnsDeliveryJobQueuePayloadInvalid,- type ApnsLiveActivityAlert,- type ApnsNotificationPayload,- SignedApnsDeliveryJob,- isApnsDeliveryJobVerificationError,- verifySignedApnsDeliveryJob,- type ApnsDeliveryJobVerificationError,-} from "./apnsDeliveryJobs.ts";-import * as AgentActivityRows from "./AgentActivityRows.ts";-import * as DeliveryAttempts from "./DeliveryAttempts.ts";-import * as LiveActivities from "./LiveActivities.ts";-import * as RelayConfiguration from "../Config.ts";-import * as ApnsDeliveryQueue from "./ApnsDeliveryQueue.ts";-import { withSpanAttributes } from "../observability.ts";--const MIN_LIVE_ACTIVITY_UPDATE_INTERVAL_MS = 15_000;-// How long a just-armed card may sit with an empty aggregate before an end is-// warranted; covers the gap between arming on send and the environment's-// first publish reaching the relay.-const FRESHLY_ARMED_GRACE_MS = 2 * 60 * 1_000;-const PERMANENT_APNS_TOKEN_REASONS = new Set([- "BadDeviceToken",- "DeviceTokenNotForTopic",- "Unregistered",-]);--type LiveActivityDeliveryKind = Extract<- RelayDeliveryKind,- "live_activity_start" | "live_activity_update" | "live_activity_end"->;--type ChosenLiveActivityDelivery =- | {- readonly kind: "live_activity_start" | "live_activity_update";- readonly token: string;- readonly aggregate: RelayAgentActivityAggregateState;- readonly alert: ApnsLiveActivityAlert | null;- }- | {- readonly kind: "live_activity_end";- readonly token: string;- readonly aggregate: RelayAgentActivityAggregateState | null;- readonly alert: ApnsLiveActivityAlert | null;- };--type ChosenPushNotificationDelivery = {- readonly kind: "push_notification";- readonly token: string;- readonly notification: ApnsNotificationPayload;-};--type ChosenDelivery = ChosenLiveActivityDelivery | ChosenPushNotificationDelivery;--export type ApnsDeliveryError =- | ApnsDeliveryQueue.ApnsDeliveryQueueError- | ApnsDeliveryJobVerificationError- | ApnsDeliveryJobClaimInFlight- | DeliveryAttempts.DeliveryAttemptRecordPersistenceError- | LiveActivities.LiveActivityTargetListPersistenceError- | LiveActivities.LiveActivityDeliveryMarkPersistenceError;--export class ApnsDeliveryJobClaimInFlight extends Schema.TaggedErrorClass<ApnsDeliveryJobClaimInFlight>()(- "ApnsDeliveryJobClaimInFlight",- {- sourceJobId: Schema.String,- },-) {- override get message(): string {- return `APNs delivery job '${this.sourceJobId}' is already in flight`;- }-}--export class ApnsDeliveryTransportError extends Schema.TaggedErrorClass<ApnsDeliveryTransportError>()(- "ApnsDeliveryTransportError",- {- deviceId: Schema.String,- kind: RelayDeliveryKindSchema,- sourceJobId: Schema.NullOr(Schema.String),- apnsErrorTag: Schema.Literals([- "ApnsJwtEncodingError",- "ApnsJwtSigningError",- "ApnsHttpRequestError",- ]),- requestStage: Schema.NullOr(Schema.Literals(["send", "read-response"])),- cause: Schema.Defect(),- },-) {- override get message(): string {- return `APNs ${this.kind} delivery failed for device ${this.deviceId}.`;- }-}--export const isApnsDeliveryTransportError = Schema.is(ApnsDeliveryTransportError);--const decodeRelayAgentActivityAggregateStateJson = Schema.decodeUnknownOption(- Schema.fromJsonString(RelayAgentActivityAggregateStateSchema),-);-const decodeRelayAgentAwarenessPreferencesJson = Schema.decodeUnknownOption(- Schema.fromJsonString(RelayAgentAwarenessPreferencesSchema),-);-const decodeSignedApnsDeliveryJob = Schema.decodeUnknownEffect(SignedApnsDeliveryJob);--function parseAggregate(value: string | null): RelayAgentActivityAggregateState | null {- if (!value) {- return null;- }- return Option.getOrNull(decodeRelayAgentActivityAggregateStateJson(value));-}--function parsePreferences(value: string): RelayAgentAwarenessPreferences | null {- return Option.getOrNull(decodeRelayAgentAwarenessPreferencesJson(value));-}--function aggregateNeedsAttention(aggregate: RelayAgentActivityAggregateState): boolean {- return aggregate.activities.some(- (row) => row.phase === "waiting_for_approval" || row.phase === "waiting_for_input",- );-}--function isAttentionPhase(phase: string): boolean {- return phase === "waiting_for_approval" || phase === "waiting_for_input";-}--// Honors the same per-event notification switches the push channel uses; a-// missing/corrupt preferences blob only disables nothing (matching how the-// liveActivitiesEnabled check treats it), since every registration writes one.-function alertAllowedForPhase(- preferences: RelayAgentAwarenessPreferences | null,- phase: string,-): boolean {- if (preferences === null) {- return true;- }- switch (phase) {- case "waiting_for_approval":- return preferences.notifyOnApproval;- case "waiting_for_input":- return preferences.notifyOnInput;- case "completed":- return preferences.notifyOnCompletion;- case "failed":- return preferences.notifyOnFailure;- default:- return false;- }-}--// Alert copy for an update whose aggregate contains threads that were NOT in an-// attention phase in the previously delivered aggregate. A null previous-// aggregate means there is no known baseline (fresh registration, replay after-// data loss) — alerting there would buzz on reconnect, not on a transition.-export function alertForAttentionTransition(input: {- readonly previousAggregate: RelayAgentActivityAggregateState | null;- readonly nextAggregate: RelayAgentActivityAggregateState;- readonly preferences: RelayAgentAwarenessPreferences | null;-}): ApnsLiveActivityAlert | null {- if (input.previousAggregate === null) {- return null;- }- const previouslyAttention = new Set(- input.previousAggregate.activities- .filter((row) => isAttentionPhase(row.phase))- .map((row) => row.threadId),- );- const newlyAttention = input.nextAggregate.activities.filter(- (row) =>- isAttentionPhase(row.phase) &&- !previouslyAttention.has(row.threadId) &&- alertAllowedForPhase(input.preferences, row.phase),- );- const first = newlyAttention[0];- if (!first) {- return null;- }- if (newlyAttention.length === 1) {- return { title: first.threadTitle, body: `${first.status}: ${first.projectTitle}` };- }- return {- title: `${newlyAttention.length} agents need attention`,- body: newlyAttention.map((row) => row.threadTitle).join(", "),- };-}--// Alert copy for an update whose aggregate contains threads that finished-// (Done/Failed) since the previously delivered aggregate — the mid-flight-// completion buzz while other agents keep the activity alive. Requires the-// thread to have been present and non-terminal before, so a baseline-less-// replay or a row that merely fell off the display cap never rings.-function newlyTerminalRows(- previousAggregate: RelayAgentActivityAggregateState | null,- nextAggregate: RelayAgentActivityAggregateState,-): ReadonlyArray<RelayAgentActivityAggregateState["activities"][number]> {- if (previousAggregate === null) {- return [];- }- const previousPhases = new Map(- previousAggregate.activities.map((row) => [row.threadId, row.phase]),- );- return nextAggregate.activities.filter((row) => {- if (row.phase !== "completed" && row.phase !== "failed") {- return false;- }- const previousPhase = previousPhases.get(row.threadId);- return (- previousPhase !== undefined && previousPhase !== "completed" && previousPhase !== "failed"- );- });-}--function isFreshTerminalRow(- row: RelayAgentActivityAggregateState["activities"][number],- nowMs: number,-): boolean {- const updatedAtMs = Option.match(DateTime.make(row.updatedAt), {- onNone: () => null,- onSome: (dt) => dt.epochMilliseconds,- });- return updatedAtMs !== null && nowMs - updatedAtMs <= TERMINAL_NOTIFICATION_FRESHNESS_MS;-}--export function alertForNewlyTerminal(input: {- readonly previousAggregate: RelayAgentActivityAggregateState | null;- readonly nextAggregate: RelayAgentActivityAggregateState;- readonly preferences: RelayAgentAwarenessPreferences | null;- readonly nowMs: number;-}): ApnsLiveActivityAlert | null {- const newlyTerminal = newlyTerminalRows(input.previousAggregate, input.nextAggregate).filter(- (row) =>- alertAllowedForPhase(input.preferences, row.phase) &&- // Replays of old aggregates (server restarts, redeliveries) repaint- // state without ringing; only fresh completions buzz.- isFreshTerminalRow(row, input.nowMs),- );- const first = newlyTerminal[0];- if (!first) {- return null;- }- if (newlyTerminal.length === 1) {- return { title: first.threadTitle, body: `${first.status}: ${first.projectTitle}` };- }- return {- title: `${newlyTerminal.length} agents finished`,- body: newlyTerminal.map((row) => row.threadTitle).join(", "),- };-}--// Alert copy for an end event carrying a terminal (Done/Failed) aggregate.-export function alertForTerminalAggregate(input: {- readonly aggregate: RelayAgentActivityAggregateState | null;- readonly preferences: RelayAgentAwarenessPreferences | null;-}): ApnsLiveActivityAlert | null {- const row = input.aggregate?.activities[0];- if (!row || (row.phase !== "completed" && row.phase !== "failed")) {- return null;- }- if (!alertAllowedForPhase(input.preferences, row.phase)) {- return null;- }- return { title: row.threadTitle, body: `${row.status}: ${row.projectTitle}` };-}--function shouldUpdateLiveActivity(input: {- readonly previousAggregate: RelayAgentActivityAggregateState | null;- readonly nextAggregate: RelayAgentActivityAggregateState;- readonly lastDeliveryAt: string | null;- readonly nowMs: number;-}): boolean {- if (!input.previousAggregate) {- return true;- }- if (JSON.stringify(input.previousAggregate) === JSON.stringify(input.nextAggregate)) {- return false;- }- if (input.previousAggregate.activeCount !== input.nextAggregate.activeCount) {- return true;- }- if (aggregateNeedsAttention(input.nextAggregate)) {- return true;- }- // A thread finishing must never be throttled away: when a completion and a- // new start land in the same window, activeCount is unchanged and the Done- // transition (and its alert) would otherwise be suppressed.- if (newlyTerminalRows(input.previousAggregate, input.nextAggregate).length > 0) {- return true;- }- const lastDeliveryAtMs =- input.lastDeliveryAt === null- ? null- : Option.match(DateTime.make(input.lastDeliveryAt), {- onNone: () => Number.NaN,- onSome: (dt) => dt.epochMilliseconds,- });- return (- lastDeliveryAtMs === null ||- Number.isNaN(lastDeliveryAtMs) ||- input.nowMs - lastDeliveryAtMs >= MIN_LIVE_ACTIVITY_UPDATE_INTERVAL_MS- );-}--// Completions replayed long after the fact (server restarts republish every-// recently-finished thread) must not ring the device again.-const TERMINAL_NOTIFICATION_FRESHNESS_MS = 2 * 60 * 1_000;--function notificationForAggregate(input: {- readonly target: LiveActivities.TargetRow;- readonly aggregate: RelayAgentActivityAggregateState | null;- readonly nowMs: number;-}): ApnsNotificationPayload | null {- if (!input.target.push_token || input.aggregate === null) {- return null;- }- const preferences = parsePreferences(input.target.preferences_json);- if (!preferences?.notificationsEnabled) {- return null;- }- const activity = input.aggregate.activities[0];- if (!activity) {- return null;- }- if (activity.phase === "completed" || activity.phase === "failed") {- const updatedAtMs = Option.match(DateTime.make(activity.updatedAt), {- onNone: () => null,- onSome: (dt) => dt.epochMilliseconds,- });- if (updatedAtMs === null || input.nowMs - updatedAtMs > TERMINAL_NOTIFICATION_FRESHNESS_MS) {- return null;- }- }- const enabled =- (activity.phase === "waiting_for_approval" && preferences.notifyOnApproval) ||- (activity.phase === "waiting_for_input" && preferences.notifyOnInput) ||- (activity.phase === "completed" && preferences.notifyOnCompletion) ||- (activity.phase === "failed" && preferences.notifyOnFailure);- if (!enabled) {- return null;- }- return {- title: activity.threadTitle,- body: `${activity.status}: ${activity.projectTitle}`,- environmentId: activity.environmentId,- threadId: activity.threadId,- deepLink: activity.deepLink,- phase: activity.phase,- updatedAt: activity.updatedAt,- };-}--// "suppressed" means a Live Activity owns this state but no update is due-// (unchanged or throttled); callers must not fall back to an alert push, or-// every republish of a waiting aggregate would ring the device.-function chooseLiveActivityDelivery(input: {- readonly target: LiveActivities.TargetRow;- readonly aggregate: RelayAgentActivityAggregateState | null;- readonly nowMs: number;-}): ChosenLiveActivityDelivery | "suppressed" | null {- const preferences = parsePreferences(input.target.preferences_json);- if (preferences?.liveActivitiesEnabled === false) {- return input.target.activity_push_token- ? {- kind: "live_activity_end",- token: input.target.activity_push_token,- aggregate: null,- alert: null,- }- : null;- }- // Activities are started by the app in the foreground, never remotely.- // Without a registered token there is nothing addressable; attention- // transitions fall back to the push notification channel until the user- // next arms the card from the app.- if (!input.target.activity_push_token) {- return null;- }- // An armed card always shows content: live agents, or recently finished- // ones (the publisher keeps Done/Failed rows in the aggregate for a- // while). A null aggregate means there is truly nothing left to show, so- // the card ends — arming is cheap now that the app re-arms on any open- // with content.- if (input.aggregate === null) {- // Except right after arming: the app arms the card the moment the user- // starts work, and the token registration's replay can land before the- // environment's first publish for the brand-new thread. Ending here- // would retire the token and orphan the card at its seed content, so a- // freshly armed card keeps its seed until real state arrives.- const armedAtMs = Option.match(- input.target.remote_started_at === null- ? Option.none()- : DateTime.make(input.target.remote_started_at),- { onNone: () => null, onSome: (dt) => dt.epochMilliseconds },- );- if (armedAtMs !== null && input.nowMs - armedAtMs < FRESHLY_ARMED_GRACE_MS) {- return null;- }- return {- kind: "live_activity_end",- token: input.target.activity_push_token,- aggregate: null,- alert: null,- };- }- const nextAggregate = input.aggregate;- const previousAggregate = parseAggregate(input.target.last_aggregate_json);- return shouldUpdateLiveActivity({- previousAggregate,- nextAggregate,- lastDeliveryAt: input.target.last_live_activity_delivery_at,- nowMs: input.nowMs,- })- ? {- kind: "live_activity_update",- token: input.target.activity_push_token,- aggregate: nextAggregate,- alert:- alertForAttentionTransition({- previousAggregate,- nextAggregate,- preferences,- }) ??- alertForNewlyTerminal({- previousAggregate,- nextAggregate,- preferences,- nowMs: input.nowMs,- }),- }- : "suppressed";-}--function chooseDelivery(input: {- readonly target: LiveActivities.TargetRow;- readonly aggregate: RelayAgentActivityAggregateState | null;- readonly nowMs: number;-}): ChosenDelivery | null {- const liveActivityDelivery = chooseLiveActivityDelivery(input);- if (liveActivityDelivery === "suppressed") {- return null;- }- if (liveActivityDelivery) {- return liveActivityDelivery;- }- const notification = notificationForAggregate(input);- return notification && input.target.push_token- ? {- kind: "push_notification",- token: input.target.push_token,- notification,- }- : null;-}--function deliveryEvent(kind: LiveActivityDeliveryKind): Apns.ApnsLiveActivityEvent {- switch (kind) {- case "live_activity_start":- return "start";- case "live_activity_update":- return "update";- case "live_activity_end":- return "end";- }-}--function isPermanentApnsTokenFailure(result: Apns.ApnsDeliveryResult): boolean {- return (- !result.ok &&- (result.status === 410 ||- (result.status === 400 &&- result.reason !== undefined &&- PERMANENT_APNS_TOKEN_REASONS.has(result.reason)))- );-}--function duplicateJobResult(input: {- readonly deviceId: string;- readonly kind: RelayDeliveryKind;-}): RelayDeliveryResult {- return {- deviceId: input.deviceId,- kind: input.kind,- ok: true,- apnsStatus: null,- apnsReason: "Duplicate APNs delivery job skipped.",- apnsId: null,- };-}--function staleJobResult(input: {- readonly deviceId: string;- readonly kind: RelayDeliveryKind;-}): RelayDeliveryResult {- return {- deviceId: input.deviceId,- kind: input.kind,- ok: true,- apnsStatus: null,- apnsReason: "Stale APNs delivery job skipped.",- apnsId: null,- };-}--function deliveryAttemptOutcome(result: Apns.ApnsDeliveryResult) {- return {- ...(result.status === 0 ? {} : { apnsStatus: result.status }),- ...(result.reason === undefined ? {} : { apnsReason: result.reason }),- apnsId: result.apnsId,- ...(result.status === 0 ? { transportError: result.reason ?? "APNs request failed." } : {}),- };-}--const recoverApnsDeliveryTransportError = (- input: {- readonly deviceId: string;- readonly kind: RelayDeliveryKind;- readonly sourceJobId: string | null;- },- cause: Apns.ApnsError,-): Effect.Effect<Apns.ApnsDeliveryResult> => {- const error = new ApnsDeliveryTransportError({- deviceId: input.deviceId,- kind: input.kind,- sourceJobId: input.sourceJobId,- apnsErrorTag: cause._tag,- requestStage: cause._tag === "ApnsHttpRequestError" ? cause.stage : null,- cause,- });- return Effect.logError(error.message).pipe(- Effect.annotateLogs({- error: Redacted.make(error, { label: error._tag }),- "error.type": error._tag,- "error.apns_error_tag": error.apnsErrorTag,- ...(error.requestStage === null ? {} : { "error.request_stage": error.requestStage }),- ...(error.stack === undefined ? {} : { "error.stack": error.stack }),- "relay.mobile.device_id": error.deviceId,- "relay.delivery.kind": error.kind,- ...(error.sourceJobId === null ? {} : { "relay.delivery.job_id": error.sourceJobId }),- }),- Effect.as({- ok: false,- status: 0,- reason: cause.message,- apnsId: null,- }),- );-};--interface LiveActivityDeliveryTarget {- readonly user_id: string;- readonly device_id: string;- readonly bundle_id?: string | null;- readonly aps_environment?: "sandbox" | "production" | null;-}--// Devices register the bundle id and APS environment of the build they run-// (dev/preview/prod variants have distinct bundle ids; development-signed-// builds get sandbox tokens). Sending with mismatched routing yields-// DeviceTokenNotForTopic/BadDeviceToken, so per-device values override the-// relay-wide defaults when present.-function credentialsForTarget(- credentials: RelayConfiguration.RelayConfiguration["Service"]["apns"],- target: LiveActivityDeliveryTarget,-): RelayConfiguration.RelayConfiguration["Service"]["apns"] {- return {- ...credentials,- ...(target.bundle_id ? { bundleId: target.bundle_id } : {}),- ...(target.aps_environment ? { environment: target.aps_environment } : {}),- };-}--function expectedCurrentToken(input: {- readonly target: LiveActivities.TargetRow;- readonly kind: RelayDeliveryKind;-}): string | null {- switch (input.kind) {- case "live_activity_start":- return input.target.push_to_start_token;- case "live_activity_update":- case "live_activity_end":- return input.target.activity_push_token;- case "push_notification":- return input.target.push_token;- }-}--interface SendLiveActivityDeliveryInputBase {- readonly target: LiveActivityDeliveryTarget;- readonly token: string;- readonly sourceJobId?: string | null;-}--export type SendLiveActivityDeliveryInput =- | (SendLiveActivityDeliveryInputBase & {- readonly kind: "live_activity_start" | "live_activity_update";- readonly aggregate: RelayAgentActivityAggregateState;- readonly alert?: ApnsLiveActivityAlert | null;- })- | (SendLiveActivityDeliveryInputBase & {- readonly kind: "live_activity_end";- readonly aggregate: RelayAgentActivityAggregateState | null;- readonly alert?: ApnsLiveActivityAlert | null;- });--function makeLiveActivityDeliveryRequest(- apns: Apns.ApnsClient["Service"],- input: SendLiveActivityDeliveryInput,- now: DateTime.DateTime,-) {- const epochSeconds = Math.floor(now.epochMilliseconds / 1_000);- const base = {- token: input.token,- nowEpochSeconds: epochSeconds,- nowIso: DateTime.formatIso(now),- };- switch (input.kind) {- case "live_activity_start":- case "live_activity_update":- return {- epochSeconds,- iso: base.nowIso,- request: apns.makeLiveActivityRequest({- ...base,- event: deliveryEvent(input.kind),- state: input.aggregate,- alert: input.alert ?? null,- }),- };- case "live_activity_end":- return {- epochSeconds,- iso: base.nowIso,- request: apns.makeLiveActivityRequest({- ...base,- event: "end",- state: input.aggregate,- alert: input.alert ?? null,- }),- };- }-}--export class ApnsDeliveries extends Context.Service<- ApnsDeliveries,- {- readonly sendForTarget: (input: {- readonly target: LiveActivities.TargetRow;- readonly aggregate: RelayAgentActivityAggregateState | null;- readonly nowMs: number;- }) => Effect.Effect<RelayDeliveryResult | null, ApnsDeliveryError>;- readonly sendPushNotificationForTarget: (input: {- readonly target: LiveActivities.TargetRow;- readonly aggregate: RelayAgentActivityAggregateState | null;- }) => Effect.Effect<RelayDeliveryResult | null, ApnsDeliveryError>;- readonly sendLiveActivity: (- input: SendLiveActivityDeliveryInput,- ) => Effect.Effect<RelayDeliveryResult, ApnsDeliveryError>;- readonly processSignedJob: (- body: unknown,- ) => Effect.Effect<RelayDeliveryResult, ApnsDeliveryError>;- readonly sendPushNotification: (input: {- readonly target: LiveActivityDeliveryTarget;- readonly token: string;- readonly sourceJobId?: string | null;- readonly notification: ApnsNotificationPayload;- }) => Effect.Effect<RelayDeliveryResult, ApnsDeliveryError>;- }->()("t3code-relay/agentActivity/ApnsDeliveries") {}--export const make = Effect.gen(function* () {- const attempts = yield* DeliveryAttempts.DeliveryAttempts;- const liveActivities = yield* LiveActivities.LiveActivities;- const deliveryQueue = yield* ApnsDeliveryQueue.ApnsDeliveryQueue;- const config = yield* RelayConfiguration.RelayConfiguration;- const apns = yield* Apns.ApnsClient;- const activityRows = yield* AgentActivityRows.AgentActivityRows;-- // Start jobs are decided at publish time, but consecutive publishes land in- // the same queue batch: a start chosen from a running aggregate can be- // delivered moments after a newer terminal publish already ended the user's- // work, birthing an orphan activity that shows stale content forever (no- // token is ever registered for it, so nothing can update or end it).- // Re-validate at delivery time that the user still has live work; fail open- // on persistence errors so a database hiccup never drops a legitimate start.- const userStillHasLiveWork = Effect.fnUntraced(function* (userId: string) {- const now = yield* DateTime.now;- return yield* activityRows.listForUser({ userId }).pipe(- Effect.map((states) =>- states.some(- (state) =>- !isTerminalPhase(state) && !isExpiredAgentActivityState(state, now.epochMilliseconds),- ),- ),- Effect.catchCause((cause) =>- Effect.logWarning("live-work recheck failed; allowing queued start", { cause }).pipe(- Effect.as(true),- ),- ),- );- });-- const stateIdentityIsCurrent = Effect.fnUntraced(function* (input: {- readonly userId: string;- readonly environmentId: string;- readonly threadId: string;- readonly phase: RelayAgentActivityAggregateState["activities"][number]["phase"];- readonly updatedAt: string;- }) {- return yield* activityRows- .getForUserThread({- userId: input.userId,- environmentId: input.environmentId,- threadId: input.threadId,- })- .pipe(- Effect.map(- (current) =>- current !== null &&- current.phase === input.phase &&- current.updatedAt === input.updatedAt,- ),- // A transient persistence failure must not permanently discard a- // legitimate alert. Fail open and let the signed job's retry/dedupe- // protections handle transport failures as usual.- Effect.catchCause((cause) =>- Effect.logWarning("agent-activity state recheck failed; allowing queued delivery", {- cause,- environmentId: input.environmentId,- threadId: input.threadId,- }).pipe(Effect.as(true)),- ),- );- });-- const aggregateRowsAreCurrent = Effect.fnUntraced(function* (input: {- readonly userId: string;- readonly aggregate: RelayAgentActivityAggregateState;- }) {- return yield* activityRows.listForUser({ userId: input.userId }).pipe(- Effect.map((currentStates) => {- const currentByThread = new Map(- currentStates.map((current) => [- `${current.environmentId}\u0000${current.threadId}`,- current,- ]),- );- return input.aggregate.activities.every((row) => {- const current = currentByThread.get(`${row.environmentId}\u0000${row.threadId}`);- return (- current !== undefined &&- current.phase === row.phase &&- current.updatedAt === row.updatedAt- );- });- }),- Effect.catchCause((cause) =>- Effect.logWarning("agent-activity aggregate recheck failed; allowing queued delivery", {- cause,- userId: input.userId,- }).pipe(Effect.as(true)),- ),- );- });-- const notificationStateIsCurrent = Effect.fnUntraced(function* (input: {- readonly userId: string;- readonly notification: ApnsNotificationPayload;- }) {- // Jobs from older relay versions do not carry a state identity. Preserve- // backwards compatibility and only revalidate newly queued jobs.- if (input.notification.phase === undefined || input.notification.updatedAt === undefined) {- return true;- }- return yield* stateIdentityIsCurrent({- userId: input.userId,- environmentId: input.notification.environmentId,- threadId: input.notification.threadId,- phase: input.notification.phase,- updatedAt: input.notification.updatedAt,- });- });-- const isCurrentSignedJobToken = Effect.fnUntraced(function* (input: {- readonly target: LiveActivityDeliveryTarget;- readonly kind: RelayDeliveryKind;- readonly token: string;- }) {- return yield* liveActivities.listTargets({ userId: input.target.user_id }).pipe(- Effect.map((targets) => {- const currentTarget = targets.find((row) => row.device_id === input.target.device_id);- return (- currentTarget !== undefined &&- expectedCurrentToken({ target: currentTarget, kind: input.kind }) === input.token- );- }),- );- });-- const sendLiveActivity: ApnsDeliveries["Service"]["sendLiveActivity"] = Effect.fn(- "relay.apns_deliveries.send_live_activity",- )(function* (input) {- yield* Effect.annotateCurrentSpan({- "relay.mobile.device_id": input.target.device_id,- "relay.delivery.kind": input.kind,- ...(input.sourceJobId ? { "relay.delivery.job_id": input.sourceJobId } : {}),- });- const now = yield* DateTime.now;- const aggregate =- input.aggregate === null ? null : sanitizeAgentActivityAggregateState(input.aggregate);- const { epochSeconds, iso, request } = makeLiveActivityDeliveryRequest(- apns,- { ...input, aggregate } as SendLiveActivityDeliveryInput,- now,- );- const recoverTransportError = (cause: Apns.ApnsError) =>- recoverApnsDeliveryTransportError(- {- deviceId: input.target.device_id,- kind: input.kind,- sourceJobId: input.sourceJobId ?? null,- },- cause,- );- if (input.sourceJobId) {- const claim = yield* attempts.claimSourceJob({- userId: input.target.user_id,- environmentId: null,- threadId: null,- deviceId: input.target.device_id,- kind: input.kind,- sourceJobId: input.sourceJobId,- token: input.token,- });- if (claim === "completed") {- return duplicateJobResult({ deviceId: input.target.device_id, kind: input.kind });- }- if (claim === "in_flight") {- return yield* new ApnsDeliveryJobClaimInFlight({ sourceJobId: input.sourceJobId });- }- const tokenIsCurrent = yield* isCurrentSignedJobToken({- target: input.target,- kind: input.kind,- token: input.token,- });- if (!tokenIsCurrent) {- yield* attempts.completeSourceJob({- sourceJobId: input.sourceJobId,- apnsReason: "Stale APNs delivery job skipped.",- });- return staleJobResult({ deviceId: input.target.device_id, kind: input.kind });- }- if (- input.kind !== "live_activity_start" &&- aggregate !== null &&- !(yield* aggregateRowsAreCurrent({- userId: input.target.user_id,- aggregate,- }))- ) {- yield* attempts.completeSourceJob({- sourceJobId: input.sourceJobId,- apnsReason: "Stale agent activity state skipped.",- });- return staleJobResult({ deviceId: input.target.device_id, kind: input.kind });- }- }- if (- input.kind === "live_activity_start" &&- !(yield* userStillHasLiveWork(input.target.user_id))- ) {- yield* liveActivities.clearStartQueued({- userId: input.target.user_id,- deviceId: input.target.device_id,- });- if (input.sourceJobId) {- yield* attempts.completeSourceJob({- sourceJobId: input.sourceJobId,- apnsReason: "Stale APNs start job skipped.",- });- }- return staleJobResult({ deviceId: input.target.device_id, kind: input.kind });- }- const result = yield* apns- .sendLiveActivityRequest({- credentials: credentialsForTarget(config.apns, input.target),- request,- issuedAtUnixSeconds: epochSeconds,- })- .pipe(- Effect.catchTags({- ApnsJwtEncodingError: recoverTransportError,- ApnsJwtSigningError: recoverTransportError,- ApnsHttpRequestError: recoverTransportError,- }),- );- if (result.ok) {- yield* liveActivities.markDelivery({- userId: input.target.user_id,- deviceId: input.target.device_id,- kind: input.kind,- aggregate,- deliveredAt: iso,- });- } else if (isPermanentApnsTokenFailure(result)) {- yield* liveActivities.invalidateDeliveryToken({- userId: input.target.user_id,- deviceId: input.target.device_id,- kind: input.kind,- invalidatedAt: iso,- });- } else if (input.kind === "live_activity_start") {- yield* liveActivities.clearStartQueued({- userId: input.target.user_id,- deviceId: input.target.device_id,- });- }- if (input.sourceJobId) {- yield* attempts.completeSourceJob({- sourceJobId: input.sourceJobId,- ...deliveryAttemptOutcome(result),- });- } else {- yield* attempts.record({- userId: input.target.user_id,- environmentId: null,- threadId: null,- deviceId: input.target.device_id,- kind: input.kind,- token: input.token,- ...deliveryAttemptOutcome(result),- });- }- return {- deviceId: input.target.device_id,- kind: input.kind,- ok: result.ok,- apnsStatus: result.status === 0 ? null : result.status,- apnsReason: result.reason ?? null,- apnsId: result.apnsId,- };- });-- const sendPushNotification: ApnsDeliveries["Service"]["sendPushNotification"] = Effect.fn(- "relay.apns_deliveries.send_push_notification",- )(function* (input) {- yield* Effect.annotateCurrentSpan({- "relay.mobile.device_id": input.target.device_id,- "relay.delivery.kind": "push_notification",- ...(input.sourceJobId ? { "relay.delivery.job_id": input.sourceJobId } : {}),- });- const now = yield* DateTime.now;- const epochSeconds = Math.floor(now.epochMilliseconds / 1_000);- const notification = sanitizeApnsNotificationPayload(input.notification);- yield* Effect.annotateCurrentSpan({- "relay.environment_id": notification.environmentId,- "relay.thread_id": notification.threadId,- });- const request = apns.makePushNotificationRequest({- token: input.token,- notification,- });- const recoverTransportError = (cause: Apns.ApnsError) =>- recoverApnsDeliveryTransportError(- {- deviceId: input.target.device_id,- kind: "push_notification",- sourceJobId: input.sourceJobId ?? null,- },- cause,- );- if (input.sourceJobId) {- const claim = yield* attempts.claimSourceJob({- userId: input.target.user_id,- environmentId: notification.environmentId,- threadId: notification.threadId,- deviceId: input.target.device_id,- kind: "push_notification",- sourceJobId: input.sourceJobId,- token: input.token,- });- if (claim === "completed") {- return duplicateJobResult({- deviceId: input.target.device_id,- kind: "push_notification",- });- }- if (claim === "in_flight") {- return yield* new ApnsDeliveryJobClaimInFlight({ sourceJobId: input.sourceJobId });- }- const tokenIsCurrent = yield* isCurrentSignedJobToken({- target: input.target,- kind: "push_notification",- token: input.token,- });- if (!tokenIsCurrent) {- yield* attempts.completeSourceJob({- sourceJobId: input.sourceJobId,- apnsReason: "Stale APNs delivery job skipped.",- });- return staleJobResult({- deviceId: input.target.device_id,- kind: "push_notification",- });- }- if (- !(yield* notificationStateIsCurrent({- userId: input.target.user_id,- notification,- }))- ) {- yield* attempts.completeSourceJob({- sourceJobId: input.sourceJobId,- apnsReason: "Stale agent activity state skipped.",- });- return staleJobResult({- deviceId: input.target.device_id,- kind: "push_notification",- });- }- }- const result = yield* apns- .sendPushNotificationRequest({- credentials: credentialsForTarget(config.apns, input.target),- request,- issuedAtUnixSeconds: epochSeconds,- })- .pipe(- Effect.catchTags({- ApnsJwtEncodingError: recoverTransportError,- ApnsJwtSigningError: recoverTransportError,- ApnsHttpRequestError: recoverTransportError,- }),- );- if (isPermanentApnsTokenFailure(result)) {- yield* liveActivities.invalidateDeliveryToken({- userId: input.target.user_id,- deviceId: input.target.device_id,- kind: "push_notification",- invalidatedAt: DateTime.formatIso(now),- });- }- if (input.sourceJobId) {- yield* attempts.completeSourceJob({- sourceJobId: input.sourceJobId,- ...deliveryAttemptOutcome(result),- });- } else {- yield* attempts.record({- userId: input.target.user_id,- environmentId: notification.environmentId,- threadId: notification.threadId,- deviceId: input.target.device_id,- kind: "push_notification",- token: input.token,- ...deliveryAttemptOutcome(result),- });- }- return {- deviceId: input.target.device_id,- kind: "push_notification" as const,- ok: result.ok,- apnsStatus: result.status === 0 ? null : result.status,- apnsReason: result.reason ?? null,- apnsId: result.apnsId,- };- });-- const processSignedJob: ApnsDeliveries["Service"]["processSignedJob"] = Effect.fn(- "relay.apns_deliveries.process_signed_job",- )(function* (body) {- const signedJob = yield* decodeSignedApnsDeliveryJob(body).pipe(- Effect.mapError(- (cause) =>- new ApnsDeliveryJobQueuePayloadInvalid({- receivedType: Array.isArray(body) ? "array" : body === null ? "null" : typeof body,- cause,- }),- ),- );- const now = yield* DateTime.now;- const payload = verifySignedApnsDeliveryJob({- secret: config.apnsDeliveryJobSigningSecret,- job: signedJob,- nowMs: now.epochMilliseconds,- });- if (isApnsDeliveryJobVerificationError(payload)) {- return yield* payload;- }- yield* Effect.annotateCurrentSpan({- "relay.mobile.device_id": payload.target.deviceId,- "relay.delivery.kind": payload.kind,- "relay.delivery.job_id": payload.jobId,- });- return yield* Effect.suspend(() => {- switch (payload.kind) {- case "live_activity_start":- case "live_activity_update":- if (payload.aggregate === null) {- return Effect.fail(- new ApnsDeliveryJobLiveActivityAggregateMissing({- jobId: payload.jobId,- kind: payload.kind,- userId: payload.target.userId,- deviceId: payload.target.deviceId,- }),- );- }- return sendLiveActivity({- target: {- user_id: payload.target.userId,- device_id: payload.target.deviceId,- bundle_id: payload.target.bundleId ?? null,- aps_environment: payload.target.apsEnvironment ?? null,- },- token: payload.target.token,- sourceJobId: payload.jobId,- kind: payload.kind,- aggregate: payload.aggregate,- alert: payload.alert ?? null,- });- case "live_activity_end":- return sendLiveActivity({- target: {- user_id: payload.target.userId,- device_id: payload.target.deviceId,- bundle_id: payload.target.bundleId ?? null,- aps_environment: payload.target.apsEnvironment ?? null,- },- token: payload.target.token,- sourceJobId: payload.jobId,- kind: payload.kind,- aggregate: payload.aggregate,- alert: payload.alert ?? null,- });- case "push_notification":- if (payload.notification === null) {- return Effect.fail(- new ApnsDeliveryJobPushNotificationMissing({- jobId: payload.jobId,- userId: payload.target.userId,- deviceId: payload.target.deviceId,- }),- );- }- return sendPushNotification({- target: {- user_id: payload.target.userId,- device_id: payload.target.deviceId,- bundle_id: payload.target.bundleId ?? null,- aps_environment: payload.target.apsEnvironment ?? null,- },- token: payload.target.token,- sourceJobId: payload.jobId,- notification: payload.notification,- });- }- }).pipe(withSpanAttributes({ "user.id": payload.target.userId }));- });-- return ApnsDeliveries.of({- sendLiveActivity,- sendPushNotification,- processSignedJob,- sendPushNotificationForTarget: Effect.fnUntraced(function* (input) {- const now = yield* DateTime.now;- const notification = notificationForAggregate({- target: input.target,- aggregate: input.aggregate,- nowMs: now.epochMilliseconds,- });- const token = input.target.push_token;- return yield* notification && token- ? deliveryQueue.enqueuePushNotification({- userId: input.target.user_id,- deviceId: input.target.device_id,- token,- bundleId: input.target.bundle_id,- apsEnvironment: input.target.aps_environment,- notification,- })- : Effect.succeed(null);- }),- sendForTarget: Effect.fnUntraced(function* (input) {- const delivery = chooseDelivery({- target: input.target,- aggregate: input.aggregate,- nowMs: input.nowMs,- });- if (!delivery) {- return null;- }- if (delivery.kind === "push_notification") {- const result = yield* deliveryQueue.enqueuePushNotification({- userId: input.target.user_id,- deviceId: input.target.device_id,- token: delivery.token,- bundleId: input.target.bundle_id,- apsEnvironment: input.target.aps_environment,- notification: delivery.notification,- });- return result;- }- const notification = notificationForAggregate({- target: input.target,- aggregate: input.aggregate,- nowMs: input.nowMs,- });- // The end event doubles as the "task finished" moment. When a companion- // push notification is about to ring the device (below), the activity end- // stays silent; otherwise the end itself carries the alert so LA-only- // users still get the buzz.- const alert =- delivery.kind === "live_activity_end"- ? notification && input.target.push_token- ? null- : alertForTerminalAggregate({- aggregate: delivery.aggregate,- preferences: parsePreferences(input.target.preferences_json),- })- : delivery.alert;- const result = yield* deliveryQueue.enqueueLiveActivity({- userId: input.target.user_id,- deviceId: input.target.device_id,- kind: delivery.kind,- token: delivery.token,- bundleId: input.target.bundle_id,- apsEnvironment: input.target.aps_environment,- aggregate: delivery.aggregate,- alert,- });- if (delivery.kind === "live_activity_end" && notification && input.target.push_token) {- yield* deliveryQueue.enqueuePushNotification({- userId: input.target.user_id,- deviceId: input.target.device_id,- token: input.target.push_token,- bundleId: input.target.bundle_id,- apsEnvironment: input.target.aps_environment,- notification,- });- }- if (delivery.kind === "live_activity_start") {- const now = yield* DateTime.now;- yield* liveActivities.markStartQueued({- userId: input.target.user_id,- deviceId: input.target.device_id,- queuedAt: DateTime.formatIso(now),- });- }- return result;- }),- });-});--export const layer = Layer.effect(ApnsDeliveries, make);diff --git a/infra/relay/src/agentActivity/ApnsDeliveryQueue.test.ts b/infra/relay/src/agentActivity/ApnsDeliveryQueue.test.tsdeleted file mode 100644index 171a81f50..000000000--- a/infra/relay/src/agentActivity/ApnsDeliveryQueue.test.ts+++ /dev/null@@ -1,115 +0,0 @@-import * as NodeCryptoLayer from "@effect/platform-node/NodeCrypto";-import { describe, expect, it } from "@effect/vitest";-import * as Alchemy from "alchemy";-import * as Cloudflare from "alchemy/Cloudflare";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";-import * as Redacted from "effect/Redacted";--import * as RelayConfiguration from "../Config.ts";-import * as ApnsDeliveryQueue from "./ApnsDeliveryQueue.ts";--const config: RelayConfiguration.RelayConfiguration["Service"] = {- relayIssuer: "https://relay.example.com",- apns: {- teamId: "team-1",- keyId: "key-1",- privateKey: Redacted.make("apns-private-key"),- bundleId: "com.t3tools.test",- environment: "sandbox",- },- clerkSecretKey: Redacted.make("clerk-secret"),- clerkPublishableKey: "pk_test_test",- clerkJwtAudience: "t3-code-relay",- apnsDeliveryJobSigningSecret: Redacted.make("apns-job-secret"),- cloudMintPrivateKey: Redacted.make("cloud-private-key"),- cloudMintPublicKey: "cloud-public-key",- managedEndpointBaseDomain: undefined,- managedEndpointNamespace: undefined,-};--describe("ApnsDeliveryQueue", () => {- it.effect("does not require the deployment RuntimeContext when building the Worker layer", () => {- const sent: unknown[] = [];- const sender: Cloudflare.Queues.WriteQueueClient = {- raw: Effect.die("raw queue binding is not used"),- send: (body) =>- Effect.sync(() => {- sent.push(body);- }),- sendBatch: () => Effect.die("batch queue binding is not used"),- };- const runtimeContext = {} as Alchemy.BaseRuntimeContext;- const layer = ApnsDeliveryQueue.layerCloudflareQueues(sender, runtimeContext).pipe(- Layer.provide(NodeCryptoLayer.layer),- Layer.provide(RelayConfiguration.layer(config)),- );-- return Effect.gen(function* () {- const queue = yield* ApnsDeliveryQueue.ApnsDeliveryQueue;- yield* queue.enqueuePushNotification({- userId: "user-1",- deviceId: "device-1",- token: "push-token",- notification: {- title: "Thread",- body: "Input: Project",- environmentId: "env-1",- threadId: "thread-1",- deepLink: "/threads/env-1/thread-1",- },- });-- expect(sent).toHaveLength(1);- }).pipe(Effect.provide(layer));- });-- it.effect("preserves job identity and the queue sender cause", () => {- const cause = new Error("queue unavailable");- const senderCause = new Cloudflare.Queues.SendError({- message: cause.message,- cause,- });- const layer = ApnsDeliveryQueue.layer.pipe(- Layer.provide(NodeCryptoLayer.layer),- Layer.provide(RelayConfiguration.layer(config)),- Layer.provide(- Layer.succeed(ApnsDeliveryQueue.ApnsDeliveryQueueSender, {- send: () => Effect.fail(senderCause),- }),- ),- );-- return Effect.gen(function* () {- const queue = yield* ApnsDeliveryQueue.ApnsDeliveryQueue;- const error = yield* Effect.flip(- queue.enqueuePushNotification({- userId: "user-1",- deviceId: "device-1",- token: "push-token",- notification: {- title: "Thread",- body: "Input: Project",- environmentId: "env-1",- threadId: "thread-1",- deepLink: "/threads/env-1/thread-1",- },- }),- );-- expect(error).toMatchObject({- _tag: "ApnsDeliveryQueueSendError",- operation: "send",- jobId: expect.any(String),- kind: "push_notification",- userId: "user-1",- deviceId: "device-1",- cause: senderCause,- });- expect(senderCause.cause).toBe(cause);- expect(error.message).toBe(- "Failed to enqueue APNs push notification delivery during send for device device-1.",- );- }).pipe(Effect.provide(layer));- });-});diff --git a/infra/relay/src/agentActivity/ApnsDeliveryQueue.ts b/infra/relay/src/agentActivity/ApnsDeliveryQueue.tsdeleted file mode 100644index 2a1d6abba..000000000--- a/infra/relay/src/agentActivity/ApnsDeliveryQueue.ts+++ /dev/null@@ -1,227 +0,0 @@-import * as Alchemy from "alchemy";-import * as Cloudflare from "alchemy/Cloudflare";-import * as Crypto from "effect/Crypto";-import * as Context from "effect/Context";-import * as DateTime from "effect/DateTime";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";-import * as Schema from "effect/Schema";--import {- RelayDeliveryKind as RelayDeliveryKindSchema,- type RelayDeliveryResult,-} from "@t3tools/contracts/relay";--import {- sanitizeAgentActivityAggregateState,- sanitizeApnsNotificationPayload,-} from "./agentActivityPayloads.ts";-import {- expiresAtForJob,- makeApnsDeliveryJobPayload,- signApnsDeliveryJob,- type ApnsDeliveryJobPayload,- type SignedApnsDeliveryJob,-} from "./apnsDeliveryJobs.ts";-import * as RelayConfiguration from "../Config.ts";--export class ApnsDeliveryQueueSendError extends Schema.TaggedErrorClass<ApnsDeliveryQueueSendError>()(- "ApnsDeliveryQueueSendError",- {- operation: Schema.Literals(["generate-job-id", "send"]),- jobId: Schema.NullOr(Schema.String),- kind: RelayDeliveryKindSchema,- userId: Schema.String,- deviceId: Schema.String,- cause: Schema.Defect(),- },-) {- override get message(): string {- return `Failed to enqueue APNs ${this.kind.replaceAll("_", " ")} delivery during ${this.operation} for device ${this.deviceId}.`;- }-}--export type ApnsDeliveryQueueError = ApnsDeliveryQueueSendError;--export class ApnsDeliveryQueueSender extends Context.Service<- ApnsDeliveryQueueSender,- {- readonly send: (- body: SignedApnsDeliveryJob,- ) => Effect.Effect<void, Cloudflare.Queues.SendError>;- }->()("t3code-relay/agentActivity/ApnsDeliveryQueue/ApnsDeliveryQueueSender") {}--export class ApnsDeliveryQueue extends Context.Service<- ApnsDeliveryQueue,- {- readonly enqueueLiveActivity: (input: {- readonly kind: ApnsDeliveryJobPayload["kind"];- readonly userId: string;- readonly deviceId: string;- readonly token: string;- readonly bundleId?: string | null;- readonly apsEnvironment?: "sandbox" | "production" | null;- readonly aggregate: ApnsDeliveryJobPayload["aggregate"];- readonly alert?: ApnsDeliveryJobPayload["alert"];- }) => Effect.Effect<RelayDeliveryResult, ApnsDeliveryQueueError>;- readonly enqueuePushNotification: (input: {- readonly userId: string;- readonly deviceId: string;- readonly token: string;- readonly bundleId?: string | null;- readonly apsEnvironment?: "sandbox" | "production" | null;- readonly notification: NonNullable<ApnsDeliveryJobPayload["notification"]>;- }) => Effect.Effect<RelayDeliveryResult, ApnsDeliveryQueueError>;- }->()("t3code-relay/agentActivity/ApnsDeliveryQueue") {}--export const make = Effect.gen(function* () {- const sender = yield* ApnsDeliveryQueueSender;- const crypto = yield* Crypto.Crypto;- const config = yield* RelayConfiguration.RelayConfiguration;-- return ApnsDeliveryQueue.of({- enqueueLiveActivity: Effect.fn("relay.apns_delivery_queue.enqueue_live_activity")(- function* (input) {- yield* Effect.annotateCurrentSpan({- "relay.mobile.device_id": input.deviceId,- "relay.delivery.kind": input.kind,- });- const now = yield* DateTime.now;- const jobId = yield* crypto.randomUUIDv4.pipe(- Effect.mapError(- (cause) =>- new ApnsDeliveryQueueSendError({- operation: "generate-job-id",- jobId: null,- kind: input.kind,- userId: input.userId,- deviceId: input.deviceId,- cause,- }),- ),- );- yield* Effect.annotateCurrentSpan({ "relay.delivery.job_id": jobId });- const payload = makeApnsDeliveryJobPayload({- ...input,- aggregate:- input.aggregate === null ? null : sanitizeAgentActivityAggregateState(input.aggregate),- jobId,- createdAt: DateTime.formatIso(now),- expiresAt: expiresAtForJob(now.epochMilliseconds),- });- const signed = signApnsDeliveryJob({- secret: config.apnsDeliveryJobSigningSecret,- payload,- });- yield* sender.send(signed).pipe(- Effect.mapError(- (cause) =>- new ApnsDeliveryQueueSendError({- operation: "send",- jobId,- kind: input.kind,- userId: input.userId,- deviceId: input.deviceId,- cause,- }),- ),- );- return {- deviceId: input.deviceId,- kind: input.kind,- ok: true,- queued: true,- apnsStatus: null,- apnsReason: null,- apnsId: null,- };- },- ),- enqueuePushNotification: Effect.fn("relay.apns_delivery_queue.enqueue_push_notification")(- function* (input) {- yield* Effect.annotateCurrentSpan({- "relay.mobile.device_id": input.deviceId,- "relay.delivery.kind": "push_notification",- "relay.environment_id": input.notification.environmentId,- "relay.thread_id": input.notification.threadId,- });- const now = yield* DateTime.now;- const jobId = yield* crypto.randomUUIDv4.pipe(- Effect.mapError(- (cause) =>- new ApnsDeliveryQueueSendError({- operation: "generate-job-id",- jobId: null,- kind: "push_notification",- userId: input.userId,- deviceId: input.deviceId,- cause,- }),- ),- );- yield* Effect.annotateCurrentSpan({ "relay.delivery.job_id": jobId });- const payload = makeApnsDeliveryJobPayload({- kind: "push_notification",- userId: input.userId,- deviceId: input.deviceId,- token: input.token,- bundleId: input.bundleId,- apsEnvironment: input.apsEnvironment,- aggregate: null,- notification: sanitizeApnsNotificationPayload(input.notification),- jobId,- createdAt: DateTime.formatIso(now),- expiresAt: expiresAtForJob(now.epochMilliseconds),- });- const signed = signApnsDeliveryJob({- secret: config.apnsDeliveryJobSigningSecret,- payload,- });- yield* sender.send(signed).pipe(- Effect.mapError(- (cause) =>- new ApnsDeliveryQueueSendError({- operation: "send",- jobId,- kind: "push_notification",- userId: input.userId,- deviceId: input.deviceId,- cause,- }),- ),- );- return {- deviceId: input.deviceId,- kind: "push_notification" as const,- ok: true,- queued: true,- apnsStatus: null,- apnsReason: null,- apnsId: null,- };- },- ),- });-});--export const layer = Layer.effect(ApnsDeliveryQueue, make);--export const layerCloudflareQueues = (- sender: Cloudflare.Queues.WriteQueueClient,- alchemyRuntimeContext: Alchemy.BaseRuntimeContext,-) =>- layer.pipe(- Layer.provide(- Layer.succeed(- ApnsDeliveryQueueSender,- ApnsDeliveryQueueSender.of({- send: (body) =>- sender- .send(body)- .pipe(Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext)),- }),- ),- ),- );diff --git a/infra/relay/src/agentActivity/ApnsProviderTokens.test.ts b/infra/relay/src/agentActivity/ApnsProviderTokens.test.tsdeleted file mode 100644index d98b9f920..000000000--- a/infra/relay/src/agentActivity/ApnsProviderTokens.test.ts+++ /dev/null@@ -1,75 +0,0 @@-import * as NodeCrypto from "node:crypto";--import { describe, expect, it } from "@effect/vitest";-import * as Effect from "effect/Effect";-import * as Redacted from "effect/Redacted";-import * as Schema from "effect/Schema";--import * as ApnsProviderTokens from "./ApnsProviderTokens.ts";--const { privateKey } = NodeCrypto.generateKeyPairSync("ec", {- namedCurve: "prime256v1",- privateKeyEncoding: { type: "pkcs8", format: "pem" },- publicKeyEncoding: { type: "spki", format: "pem" },-});--const signingInput = {- teamId: "team-1",- keyId: "key-1",- privateKey: Redacted.make(privateKey),-};--const WINDOW = ApnsProviderTokens.APNS_JWT_REUSE_SECONDS;--const decodeJwtPayload = Schema.decodeEffect(- Schema.fromJsonString(Schema.Struct({ iat: Schema.Number })),-);--describe("ApnsProviderTokens", () => {- it.effect("derives the byte-identical token across isolates within a window", () => {- ApnsProviderTokens.__resetApnsProviderTokenCacheForTest();- return Effect.gen(function* () {- const tokens = yield* ApnsProviderTokens.ApnsProviderTokens;- const first = yield* tokens.getJwt({ ...signingInput, issuedAtUnixSeconds: WINDOW + 10 });-- // A fresh isolate has no cache; deterministic signing plus quantized- // iat must still reproduce the exact same JWT for the same window.- ApnsProviderTokens.__resetApnsProviderTokenCacheForTest();- const second = yield* tokens.getJwt({- ...signingInput,- issuedAtUnixSeconds: WINDOW * 2 - 1,- });- expect(second).toBe(first);-- const payload = yield* decodeJwtPayload(- Buffer.from(first.split(".")[1]!, "base64url").toString("utf8"),- );- expect(payload.iat).toBe(WINDOW);- ApnsProviderTokens.__resetApnsProviderTokenCacheForTest();- }).pipe(Effect.provide(ApnsProviderTokens.layer));- });-- it.effect("rolls to a new token at the window boundary", () => {- ApnsProviderTokens.__resetApnsProviderTokenCacheForTest();- return Effect.gen(function* () {- const tokens = yield* ApnsProviderTokens.ApnsProviderTokens;- const first = yield* tokens.getJwt({ ...signingInput, issuedAtUnixSeconds: WINDOW + 10 });- const next = yield* tokens.getJwt({ ...signingInput, issuedAtUnixSeconds: WINDOW * 2 });- expect(next).not.toBe(first);- ApnsProviderTokens.__resetApnsProviderTokenCacheForTest();- }).pipe(Effect.provide(ApnsProviderTokens.layer));- });-- it.effect("serves repeat pushes from the isolate cache without re-signing", () => {- ApnsProviderTokens.__resetApnsProviderTokenCacheForTest();- return Effect.gen(function* () {- const tokens = yield* ApnsProviderTokens.ApnsProviderTokens;- const first = yield* tokens.getJwt({ ...signingInput, issuedAtUnixSeconds: WINDOW + 10 });- const again = yield* tokens.getJwt({ ...signingInput, issuedAtUnixSeconds: WINDOW + 500 });- // Deterministic signing makes equality hold either way; toBe on the- // exact string documents the cache contract.- expect(again).toBe(first);- ApnsProviderTokens.__resetApnsProviderTokenCacheForTest();- }).pipe(Effect.provide(ApnsProviderTokens.layer));- });-});diff --git a/infra/relay/src/agentActivity/ApnsProviderTokens.ts b/infra/relay/src/agentActivity/ApnsProviderTokens.tsdeleted file mode 100644index 329f07283..000000000--- a/infra/relay/src/agentActivity/ApnsProviderTokens.ts+++ /dev/null@@ -1,63 +0,0 @@-import * as Context from "effect/Context";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";--import {- apnsProviderTokenCacheKey,- makeApnsJwt,- type ApnsJwtError,- type ApnsJwtSigningInput,-} from "./apnsJwt.ts";--// APNs requires REUSING the provider token: refreshing it more than roughly-// once per 20 minutes returns 429 TooManyProviderTokenUpdates and drops the-// push (observed live: bursty Live Activity updates got 429'd, leaving stale-// lock-screen state). Reuse each signed JWT for most of its 60-minute-// validity.-export const APNS_JWT_REUSE_SECONDS = 45 * 60;--export class ApnsProviderTokens extends Context.Service<- ApnsProviderTokens,- {- readonly getJwt: (input: ApnsJwtSigningInput) => Effect.Effect<string, ApnsJwtError>;- }->()("t3code-relay/agentActivity/ApnsProviderTokens") {}--interface CachedProviderToken {- readonly jwt: string;- readonly issuedAtUnixSeconds: number;-}--// Signing is deterministic (RFC 6979) and iat is quantized below, so every-// isolate independently derives the byte-identical token for a window; this-// map only avoids re-signing on every push. No shared storage is needed, and-// no provider token is ever written anywhere.-const isolateTokenCache = new Map<string, CachedProviderToken>();--export function __resetApnsProviderTokenCacheForTest(): void {- isolateTokenCache.clear();-}--// Quantize iat to the reuse window so all isolates agree on it. The token's-// age stays under APNs' 60-minute limit, and the whole fleet rolls to the-// next token at the same instant — one provider-token update per window.-export function quantizedApnsJwtIssuedAt(nowUnixSeconds: number): number {- return Math.floor(nowUnixSeconds / APNS_JWT_REUSE_SECONDS) * APNS_JWT_REUSE_SECONDS;-}--export const make = () =>- ApnsProviderTokens.of({- getJwt: Effect.fnUntraced(function* (input) {- const issuedAtUnixSeconds = quantizedApnsJwtIssuedAt(input.issuedAtUnixSeconds);- const cacheKey = apnsProviderTokenCacheKey(input);- const cached = isolateTokenCache.get(cacheKey);- if (cached && cached.issuedAtUnixSeconds === issuedAtUnixSeconds) {- return cached.jwt;- }- const jwt = yield* makeApnsJwt({ ...input, issuedAtUnixSeconds });- isolateTokenCache.set(cacheKey, { jwt, issuedAtUnixSeconds });- return jwt;- }),- });--export const layer = Layer.succeed(ApnsProviderTokens, make());diff --git a/infra/relay/src/agentActivity/DeliveryAttempts.test.ts b/infra/relay/src/agentActivity/DeliveryAttempts.test.tsdeleted file mode 100644index 2f3d94898..000000000--- a/infra/relay/src/agentActivity/DeliveryAttempts.test.ts+++ /dev/null@@ -1,414 +0,0 @@-import * as NodeCryptoLayer from "@effect/platform-node/NodeCrypto";-import { describe, expect, it } from "@effect/vitest";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";--import * as RelayDb from "../db.ts";-import { relayDeliveryAttempts } from "../persistence/schema.ts";-import * as DeliveryAttempts from "./DeliveryAttempts.ts";--describe("DeliveryAttempts", () => {- it.effect("records the signed queue source job id for APNs delivery auditability", () => {- const insertedValues: Array<Record<string, unknown>> = [];- const fakeDb = {- insert: (table: unknown) => {- expect(table).toBe(relayDeliveryAttempts);- return {- values: (values: Record<string, unknown>) => {- insertedValues.push(values);- return Effect.void;- },- };- },- } as unknown as RelayDb.RelayDb["Service"];-- return Effect.gen(function* () {- const attempts = yield* DeliveryAttempts.DeliveryAttempts;- yield* attempts.record({- userId: "user-1",- environmentId: "env-1",- threadId: "thread-1",- deviceId: "device-1",- kind: "live_activity_update",- sourceJobId: "job-1",- token: "apns-token",- apnsStatus: 200,- apnsId: "apns-id",- });-- expect(insertedValues).toHaveLength(1);- expect(insertedValues[0]).toMatchObject({- userId: "user-1",- environmentId: "env-1",- threadId: "thread-1",- deviceId: "device-1",- kind: "live_activity_update",- sourceJobId: "job-1",- tokenSuffix: "ns-token",- apnsStatus: 200,- apnsId: "apns-id",- });- }).pipe(- Effect.provide(- DeliveryAttempts.layer.pipe(- Layer.provide(NodeCryptoLayer.layer),- Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb)),- ),- ),- );- });-- it.effect("claims signed queue source jobs before APNs delivery", () => {- const insertedValues: Array<Record<string, unknown>> = [];- const conflictTargets: Array<unknown> = [];- const fakeDb = {- insert: (table: unknown) => {- expect(table).toBe(relayDeliveryAttempts);- return {- values: (values: Record<string, unknown>) => {- insertedValues.push(values);- return {- onConflictDoNothing: (config: { readonly target: unknown }) => {- conflictTargets.push(config.target);- return {- returning: () => Effect.succeed([{ id: values.id }]),- };- },- };- },- };- },- } as unknown as RelayDb.RelayDb["Service"];-- return Effect.gen(function* () {- const attempts = yield* DeliveryAttempts.DeliveryAttempts;- const claimed = yield* attempts.claimSourceJob({- userId: "user-1",- environmentId: "env-1",- threadId: "thread-1",- deviceId: "device-1",- kind: "push_notification",- sourceJobId: "job-1",- token: "apns-token",- });-- expect(claimed).toBe("claimed");- expect(conflictTargets).toEqual([relayDeliveryAttempts.sourceJobId]);- expect(insertedValues[0]).toMatchObject({- kind: "push_notification",- sourceJobId: "job-1",- tokenSuffix: "ns-token",- apnsStatus: null,- });- }).pipe(- Effect.provide(- DeliveryAttempts.layer.pipe(- Layer.provide(NodeCryptoLayer.layer),- Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb)),- ),- ),- );- });-- it.effect("reports completed source jobs when the durable claim already exists", () => {- const fakeDb = {- insert: () => ({- values: () => ({- onConflictDoNothing: () => ({- returning: () => Effect.succeed([]),- }),- }),- }),- select: () => ({- from: () => ({- where: () => ({- limit: () =>- Effect.succeed([- {- createdAt: "2026-05-26T00:00:00.000Z",- apnsStatus: 200,- apnsReason: null,- apnsId: null,- transportError: null,- },- ]),- }),- }),- }),- } as unknown as RelayDb.RelayDb["Service"];-- return Effect.gen(function* () {- const attempts = yield* DeliveryAttempts.DeliveryAttempts;- const claimed = yield* attempts.claimSourceJob({- userId: "user-1",- environmentId: null,- threadId: null,- deviceId: "device-1",- kind: "live_activity_update",- sourceJobId: "job-1",- token: "apns-token",- });-- expect(claimed).toBe("completed");- }).pipe(- Effect.provide(- DeliveryAttempts.layer.pipe(- Layer.provide(NodeCryptoLayer.layer),- Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb)),- ),- ),- );- });-- it.effect("reports in-flight source jobs while an active claim lease exists", () => {- const fakeDb = {- insert: () => ({- values: () => ({- onConflictDoNothing: () => ({- returning: () => Effect.succeed([]),- }),- }),- }),- select: () => ({- from: () => ({- where: () => ({- limit: () =>- Effect.succeed([- {- createdAt: "2999-01-01T00:00:00.000Z",- apnsStatus: null,- apnsReason: null,- apnsId: null,- transportError: null,- },- ]),- }),- }),- }),- } as unknown as RelayDb.RelayDb["Service"];-- return Effect.gen(function* () {- const attempts = yield* DeliveryAttempts.DeliveryAttempts;- const claimed = yield* attempts.claimSourceJob({- userId: "user-1",- environmentId: null,- threadId: null,- deviceId: "device-1",- kind: "live_activity_update",- sourceJobId: "job-1",- token: "apns-token",- });-- expect(claimed).toBe("in_flight");- }).pipe(- Effect.provide(- DeliveryAttempts.layer.pipe(- Layer.provide(NodeCryptoLayer.layer),- Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb)),- ),- ),- );- });-- it.effect("reclaims source jobs after the claim lease expires", () => {- const updatedValues: Array<Record<string, unknown>> = [];- const fakeDb = {- insert: () => ({- values: () => ({- onConflictDoNothing: () => ({- returning: () => Effect.succeed([]),- }),- }),- }),- select: () => ({- from: () => ({- where: () => ({- limit: () =>- Effect.succeed([- {- createdAt: "1969-12-31T23:00:00.000Z",- apnsStatus: null,- apnsReason: null,- apnsId: null,- transportError: null,- },- ]),- }),- }),- }),- update: () => ({- set: (values: Record<string, unknown>) => {- updatedValues.push(values);- return {- where: () => ({- returning: () => Effect.succeed([{ id: "attempt-1" }]),- }),- };- },- }),- } as unknown as RelayDb.RelayDb["Service"];-- return Effect.gen(function* () {- const attempts = yield* DeliveryAttempts.DeliveryAttempts;- const claimed = yield* attempts.claimSourceJob({- userId: "user-1",- environmentId: null,- threadId: null,- deviceId: "device-1",- kind: "live_activity_update",- sourceJobId: "job-1",- token: "apns-token",- });-- expect(claimed).toBe("claimed");- expect(updatedValues[0]?.createdAt).toEqual(expect.any(String));- }).pipe(- Effect.provide(- DeliveryAttempts.layer.pipe(- Layer.provide(NodeCryptoLayer.layer),- Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb)),- ),- ),- );- });-- it.effect("completes a claimed source job with the APNs outcome", () => {- const updatedValues: Array<Record<string, unknown>> = [];- const whereClauses: Array<unknown> = [];- const fakeDb = {- update: (table: unknown) => {- expect(table).toBe(relayDeliveryAttempts);- return {- set: (values: Record<string, unknown>) => {- updatedValues.push(values);- return {- where: (clause: unknown) => {- whereClauses.push(clause);- return Effect.void;- },- };- },- };- },- } as unknown as RelayDb.RelayDb["Service"];-- return Effect.gen(function* () {- const attempts = yield* DeliveryAttempts.DeliveryAttempts;- yield* attempts.completeSourceJob({- sourceJobId: "job-1",- apnsStatus: 410,- apnsReason: "Unregistered",- apnsId: "apns-id",- });-- expect(whereClauses).toHaveLength(1);- expect(updatedValues).toEqual([- {- createdAt: expect.any(String),- apnsStatus: 410,- apnsReason: "Unregistered",- apnsId: "apns-id",- transportError: null,- },- ]);- }).pipe(- Effect.provide(- DeliveryAttempts.layer.pipe(- Layer.provide(NodeCryptoLayer.layer),- Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb)),- ),- ),- );- });-- it.effect("preserves operation context and causes for persistence failures", () => {- const cause = new Error("database unavailable");- const fakeDb = {- insert: () => ({- values: (values: Record<string, unknown>) =>- values.kind === "record"- ? Effect.fail(cause)- : {- onConflictDoNothing: () => ({- returning: () => Effect.fail(cause),- }),- },- }),- update: () => ({- set: () => ({- where: () => Effect.fail(cause),- }),- }),- } as unknown as RelayDb.RelayDb["Service"];-- return Effect.gen(function* () {- const attempts = yield* DeliveryAttempts.DeliveryAttempts;- const recordError = yield* Effect.flip(- attempts.record({- userId: "user-1",- environmentId: "env-1",- threadId: "thread-1",- deviceId: "device-1",- kind: "record",- sourceJobId: "job-1",- token: "apns-token",- }),- );- const claimError = yield* Effect.flip(- attempts.claimSourceJob({- userId: "user-2",- environmentId: "env-2",- threadId: "thread-2",- deviceId: "device-2",- kind: "claim",- sourceJobId: "job-2",- token: "apns-token",- }),- );- const completionError = yield* Effect.flip(- attempts.completeSourceJob({ sourceJobId: "job-3", apnsStatus: 500 }),- );-- expect(recordError).toMatchObject({- operation: "record",- sourceJobId: "job-1",- userId: "user-1",- environmentId: "env-1",- threadId: "thread-1",- deviceId: "device-1",- kind: "record",- cause,- message: "Failed to persist APNs delivery attempt during record.",- });- expect(claimError).toMatchObject({- operation: "claim-source-job",- sourceJobId: "job-2",- userId: "user-2",- environmentId: "env-2",- threadId: "thread-2",- deviceId: "device-2",- kind: "claim",- cause,- message: "Failed to persist APNs delivery attempt during claim-source-job.",- });- expect(completionError).toMatchObject({- operation: "complete-source-job",- sourceJobId: "job-3",- userId: null,- environmentId: null,- threadId: null,- deviceId: null,- kind: null,- cause,- message: "Failed to persist APNs delivery attempt during complete-source-job.",- });- }).pipe(- Effect.provide(- DeliveryAttempts.layer.pipe(- Layer.provide(NodeCryptoLayer.layer),- Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb)),- ),- ),- );- });-});diff --git a/infra/relay/src/agentActivity/DeliveryAttempts.ts b/infra/relay/src/agentActivity/DeliveryAttempts.tsdeleted file mode 100644index 843415abf..000000000--- a/infra/relay/src/agentActivity/DeliveryAttempts.ts+++ /dev/null@@ -1,252 +0,0 @@-import * as Context from "effect/Context";-import * as DateTime from "effect/DateTime";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";-import * as Option from "effect/Option";-import { and, eq, isNull } from "drizzle-orm";-import * as Crypto from "effect/Crypto";-import * as Schema from "effect/Schema";--import * as RelayDb from "../db.ts";-import { relayDeliveryAttempts } from "../persistence/schema.ts";--export class DeliveryAttemptRecordPersistenceError extends Schema.TaggedErrorClass<DeliveryAttemptRecordPersistenceError>()(- "DeliveryAttemptRecordPersistenceError",- {- operation: Schema.Literals(["record", "claim-source-job", "complete-source-job"]),- sourceJobId: Schema.NullOr(Schema.String),- userId: Schema.NullOr(Schema.String),- environmentId: Schema.NullOr(Schema.String),- threadId: Schema.NullOr(Schema.String),- deviceId: Schema.NullOr(Schema.String),- kind: Schema.NullOr(Schema.String),- cause: Schema.Defect(),- },-) {- override get message(): string {- return `Failed to persist APNs delivery attempt during ${this.operation}.`;- }-}--export interface DeliveryAttemptInput {- readonly userId: string | null;- readonly environmentId: string | null;- readonly threadId: string | null;- readonly deviceId: string | null;- readonly kind: string;- readonly sourceJobId?: string | null;- readonly token: string | null;- readonly apnsStatus?: number;- readonly apnsReason?: string;- readonly apnsId?: string | null;- readonly transportError?: string;-}--export interface DeliveryAttemptCompletionInput {- readonly sourceJobId: string;- readonly apnsStatus?: number;- readonly apnsReason?: string;- readonly apnsId?: string | null;- readonly transportError?: string;-}--export type DeliverySourceJobClaimResult = "claimed" | "completed" | "in_flight";--export class DeliveryAttempts extends Context.Service<- DeliveryAttempts,- {- readonly record: (- input: DeliveryAttemptInput,- ) => Effect.Effect<void, DeliveryAttemptRecordPersistenceError>;- readonly claimSourceJob: (- input: DeliveryAttemptInput & { readonly sourceJobId: string },- ) => Effect.Effect<DeliverySourceJobClaimResult, DeliveryAttemptRecordPersistenceError>;- readonly completeSourceJob: (- input: DeliveryAttemptCompletionInput,- ) => Effect.Effect<void, DeliveryAttemptRecordPersistenceError>;- }->()("t3code-relay/agentActivity/DeliveryAttempts") {}--const SOURCE_JOB_CLAIM_LEASE_MINUTES = 10;--function insertValues(- input: DeliveryAttemptInput,- id: string,- createdAt: string,-): typeof relayDeliveryAttempts.$inferInsert {- return {- id,- createdAt,- userId: input.userId,- environmentId: input.environmentId,- threadId: input.threadId,- deviceId: input.deviceId,- kind: input.kind,- sourceJobId: input.sourceJobId ?? null,- tokenSuffix: input.token?.slice(-8) ?? null,- apnsStatus: input.apnsStatus ?? null,- apnsReason: input.apnsReason ?? null,- apnsId: input.apnsId ?? null,- transportError: input.transportError ?? null,- };-}--export const make = Effect.gen(function* () {- const db = yield* RelayDb.RelayDb;- const crypto = yield* Crypto.Crypto;-- const isExpiredClaim = (claimedAt: string | null, now: DateTime.DateTime) => {- if (claimedAt === null) {- return true;- }- return Option.match(DateTime.make(claimedAt), {- onNone: () => true,- onSome: (dateTime) =>- now.epochMilliseconds - dateTime.epochMilliseconds >=- SOURCE_JOB_CLAIM_LEASE_MINUTES * 60 * 1_000,- });- };-- return DeliveryAttempts.of({- record: Effect.fn("relay.delivery_attempts.record")(function* (input) {- yield* Effect.annotateCurrentSpan({- "relay.delivery.kind": input.kind,- ...(input.sourceJobId ? { "relay.delivery.job_id": input.sourceJobId } : {}),- ...(input.deviceId ? { "relay.mobile.device_id": input.deviceId } : {}),- ...(input.environmentId ? { "relay.environment_id": input.environmentId } : {}),- ...(input.threadId ? { "relay.thread_id": input.threadId } : {}),- });- yield* Effect.gen(function* () {- const id = yield* crypto.randomUUIDv4;- const createdAt = DateTime.formatIso(yield* DateTime.now);- yield* db.insert(relayDeliveryAttempts).values(insertValues(input, id, createdAt));- }).pipe(- Effect.mapError(- (cause) =>- new DeliveryAttemptRecordPersistenceError({- operation: "record",- sourceJobId: input.sourceJobId ?? null,- userId: input.userId,- environmentId: input.environmentId,- threadId: input.threadId,- deviceId: input.deviceId,- kind: input.kind,- cause,- }),- ),- );- }),- claimSourceJob: Effect.fn("relay.delivery_attempts.claim_source_job")(function* (input) {- yield* Effect.annotateCurrentSpan({- "relay.delivery.kind": input.kind,- "relay.delivery.job_id": input.sourceJobId,- ...(input.deviceId ? { "relay.mobile.device_id": input.deviceId } : {}),- ...(input.environmentId ? { "relay.environment_id": input.environmentId } : {}),- ...(input.threadId ? { "relay.thread_id": input.threadId } : {}),- });- return yield* Effect.gen(function* () {- const id = yield* crypto.randomUUIDv4;- const now = yield* DateTime.now;- const createdAt = DateTime.formatIso(now);- const inserted = yield* db- .insert(relayDeliveryAttempts)- .values(insertValues(input, id, createdAt))- .onConflictDoNothing({ target: relayDeliveryAttempts.sourceJobId })- .returning({ id: relayDeliveryAttempts.id });- if (inserted.length > 0) {- return "claimed";- }-- const existing = yield* db- .select({- createdAt: relayDeliveryAttempts.createdAt,- apnsStatus: relayDeliveryAttempts.apnsStatus,- apnsReason: relayDeliveryAttempts.apnsReason,- apnsId: relayDeliveryAttempts.apnsId,- transportError: relayDeliveryAttempts.transportError,- })- .from(relayDeliveryAttempts)- .where(eq(relayDeliveryAttempts.sourceJobId, input.sourceJobId))- .limit(1);- const row = existing[0];- if (!row) {- return "in_flight";- }- if (- row.apnsStatus !== null ||- row.apnsReason !== null ||- row.apnsId !== null ||- row.transportError !== null- ) {- return "completed";- }- if (!isExpiredClaim(row.createdAt, now)) {- return "in_flight";- }-- const reclaimed = yield* db- .update(relayDeliveryAttempts)- .set({- createdAt,- })- .where(- and(- eq(relayDeliveryAttempts.sourceJobId, input.sourceJobId),- eq(relayDeliveryAttempts.createdAt, row.createdAt),- isNull(relayDeliveryAttempts.apnsStatus),- isNull(relayDeliveryAttempts.apnsReason),- isNull(relayDeliveryAttempts.apnsId),- isNull(relayDeliveryAttempts.transportError),- ),- )- .returning({ id: relayDeliveryAttempts.id });- return reclaimed.length > 0 ? "claimed" : "in_flight";- }).pipe(- Effect.mapError(- (cause) =>- new DeliveryAttemptRecordPersistenceError({- operation: "claim-source-job",- sourceJobId: input.sourceJobId,- userId: input.userId,- environmentId: input.environmentId,- threadId: input.threadId,- deviceId: input.deviceId,- kind: input.kind,- cause,- }),- ),- );- }),- completeSourceJob: Effect.fn("relay.delivery_attempts.complete_source_job")(function* (input) {- yield* Effect.annotateCurrentSpan({ "relay.delivery.job_id": input.sourceJobId });- const completedAt = DateTime.formatIso(yield* DateTime.now);- yield* db- .update(relayDeliveryAttempts)- .set({- createdAt: completedAt,- apnsStatus: input.apnsStatus ?? null,- apnsReason: input.apnsReason ?? null,- apnsId: input.apnsId ?? null,- transportError: input.transportError ?? null,- })- .where(eq(relayDeliveryAttempts.sourceJobId, input.sourceJobId))- .pipe(- Effect.mapError(- (cause) =>- new DeliveryAttemptRecordPersistenceError({- operation: "complete-source-job",- sourceJobId: input.sourceJobId,- userId: null,- environmentId: null,- threadId: null,- deviceId: null,- kind: null,- cause,- }),- ),- );- }),- });-});--export const layer = Layer.effect(DeliveryAttempts, make);diff --git a/infra/relay/src/agentActivity/Devices.test.ts b/infra/relay/src/agentActivity/Devices.test.tsdeleted file mode 100644index 5a37b1f20..000000000--- a/infra/relay/src/agentActivity/Devices.test.ts+++ /dev/null@@ -1,308 +0,0 @@-import type { RelayDeviceRegistrationRequest } from "@t3tools/contracts/relay";-import { describe, expect, it } from "@effect/vitest";-import type { SQL } from "drizzle-orm";-import { PgDialect } from "drizzle-orm/pg-core";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";--import * as RelayDb from "../db.ts";-import { relayLiveActivities, relayMobileDevices } from "../persistence/schema.ts";-import * as Devices from "./Devices.ts";--const registration: RelayDeviceRegistrationRequest = {- deviceId: "device-1" as RelayDeviceRegistrationRequest["deviceId"],- label: "Julius's iPhone",- platform: "ios",- iosMajorVersion: 18,- appVersion: "1.0.0" as RelayDeviceRegistrationRequest["appVersion"],- bundleId: "com.t3tools.t3code.preview" as RelayDeviceRegistrationRequest["bundleId"],- apsEnvironment: "production",- pushToken: "apns-device-token" as RelayDeviceRegistrationRequest["pushToken"],- pushToStartToken: "push-to-start-token" as RelayDeviceRegistrationRequest["pushToStartToken"],- preferences: {- notificationsEnabled: true,- liveActivitiesEnabled: true,- notifyOnApproval: true,- notifyOnInput: true,- notifyOnCompletion: true,- notifyOnFailure: true,- },-};--describe("Devices", () => {- it.effect("claims APNs tokens globally before upserting the current user device", () => {- const calls: Array<string> = [];- const updateSets: Array<Record<string, unknown>> = [];- const updateConditions: Array<SQL> = [];- const insertedValues: Array<Record<string, unknown>> = [];- const dialect = new PgDialect();-- const fakeDb = {- update: (table: unknown) => {- expect(table).toBe(relayMobileDevices);- calls.push("update");- return {- set: (values: Record<string, unknown>) => {- updateSets.push(values);- calls.push("update.set");- return {- where: (condition: SQL) => {- expect(condition).toBeDefined();- updateConditions.push(condition);- calls.push("update.where");- return Effect.void;- },- };- },- };- },- insert: (table: unknown) => {- expect(table).toBe(relayMobileDevices);- calls.push("insert");- return {- values: (values: Record<string, unknown>) => {- insertedValues.push(values);- calls.push("insert.values");- return {- onConflictDoUpdate: (config: unknown) => {- expect(config).toBeDefined();- calls.push("insert.onConflictDoUpdate");- return Effect.void;- },- };- },- };- },- } as unknown as RelayDb.RelayDb["Service"];-- return Effect.gen(function* () {- const devices = yield* Devices.Devices;- yield* devices.register({ userId: "user-2", registration });-- expect(calls).toEqual([- "update",- "update.set",- "update.where",- "update",- "update.set",- "update.where",- "insert",- "insert.values",- "insert.onConflictDoUpdate",- ]);- expect(updateSets).toEqual([- expect.objectContaining({ pushToken: null }),- expect.objectContaining({ pushToStartToken: null }),- ]);- expect(updateConditions.map((condition) => dialect.sqlToQuery(condition))).toEqual([- {- sql: '"relay_mobile_devices"."push_token" = $1',- params: ["apns-device-token"],- },- {- sql: '"relay_mobile_devices"."push_to_start_token" = $1',- params: ["push-to-start-token"],- },- ]);- expect(insertedValues).toEqual([- expect.objectContaining({- userId: "user-2",- deviceId: "device-1",- bundleId: "com.t3tools.t3code.preview",- apsEnvironment: "production",- pushToken: "apns-device-token",- pushToStartToken: "push-to-start-token",- }),- ]);- }).pipe(- Effect.provide(Devices.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb)))),- );- });-- it.effect("unregisters APNs state only for the current user device", () => {- const calls: Array<string> = [];- const deleteConditions: Array<SQL> = [];- const dialect = new PgDialect();-- const fakeDb = {- delete: (table: unknown) => {- calls.push(table === relayLiveActivities ? "delete.liveActivities" : "delete.devices");- return {- where: (condition: SQL) => {- expect(condition).toBeDefined();- deleteConditions.push(condition);- calls.push("delete.where");- return Effect.void;- },- };- },- } as unknown as RelayDb.RelayDb["Service"];-- return Effect.gen(function* () {- const devices = yield* Devices.Devices;- yield* devices.unregister({ userId: "user-2", deviceId: "device-1" });-- expect(calls).toEqual([- "delete.liveActivities",- "delete.where",- "delete.devices",- "delete.where",- ]);- expect(deleteConditions.map((condition) => dialect.sqlToQuery(condition))).toEqual([- {- sql:- '(("relay_live_activities"."user_id" = $1) and ' +- '("relay_live_activities"."device_id" = $2))',- params: ["user-2", "device-1"],- },- {- sql:- '(("relay_mobile_devices"."user_id" = $1) and ' +- '("relay_mobile_devices"."device_id" = $2))',- params: ["user-2", "device-1"],- },- ]);- }).pipe(- Effect.provide(Devices.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb)))),- );- });-- it.effect("lists safe notification state without exposing APNs tokens", () => {- const dialect = new PgDialect();- let condition: SQL | null = null;- const fakeDb = {- select: () => ({- from: (table: unknown) => {- expect(table).toBe(relayMobileDevices);- return {- where: (nextCondition: SQL) => {- condition = nextCondition;- return Effect.succeed([- {- deviceId: "device-1",- label: "Julius's iPhone",- platform: "ios" as const,- iosMajorVersion: 18,- appVersion: "1.0.0",- preferences: registration.preferences,- updatedAt: "2026-06-01T00:00:00.000Z",- },- ]);- },- };- },- }),- } as unknown as RelayDb.RelayDb["Service"];-- return Effect.gen(function* () {- const devices = yield* Devices.Devices;- const listed = yield* devices.listForUser({ userId: "user-2" });-- expect(condition).not.toBeNull();- expect(dialect.sqlToQuery(condition!)).toEqual({- sql: '"relay_mobile_devices"."user_id" = $1',- params: ["user-2"],- });- expect(listed).toEqual([- {- deviceId: "device-1",- label: "Julius's iPhone",- platform: "ios",- iosMajorVersion: 18,- appVersion: "1.0.0",- notifications: {- enabled: true,- notifyOnApproval: true,- notifyOnInput: true,- notifyOnCompletion: true,- notifyOnFailure: true,- },- liveActivities: {- enabled: true,- },- updatedAt: "2026-06-01T00:00:00.000Z",- },- ]);- }).pipe(- Effect.provide(Devices.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb)))),- );- });-- it.effect("identifies the failed device registration stage", () => {- const cause = new Error("push-token claim failed");- const fakeDb = {- update: () => ({- set: (values: Record<string, unknown>) => ({- where: () => ("pushToken" in values ? Effect.fail(cause) : Effect.void),- }),- }),- } as unknown as RelayDb.RelayDb["Service"];-- return Effect.gen(function* () {- const devices = yield* Devices.Devices;- const error = yield* devices.register({ userId: "user-2", registration }).pipe(Effect.flip);-- expect(error).toMatchObject({- userId: "user-2",- deviceId: "device-1",- stage: "claim-push-token",- });- expect(error.cause).toBe(cause);- expect(error.message).toBe(- "Failed to persist mobile device registration for user-2/device-1 during claim-push-token.",- );- }).pipe(- Effect.provide(Devices.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb)))),- );- });-- it.effect("identifies the failed device unregistration stage", () => {- const cause = new Error("live activity delete failed");- const fakeDb = {- delete: (table: unknown) => ({- where: () => (table === relayLiveActivities ? Effect.fail(cause) : Effect.void),- }),- } as unknown as RelayDb.RelayDb["Service"];-- return Effect.gen(function* () {- const devices = yield* Devices.Devices;- const error = yield* devices- .unregister({ userId: "user-2", deviceId: "device-1" })- .pipe(Effect.flip);-- expect(error).toMatchObject({- userId: "user-2",- deviceId: "device-1",- stage: "delete-live-activity",- });- expect(error.cause).toBe(cause);- expect(error.message).toBe(- "Failed to unregister mobile device user-2/device-1 during delete-live-activity.",- );- }).pipe(- Effect.provide(Devices.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb)))),- );- });-- it.effect("attaches the user to device list failures", () => {- const cause = new Error("device list failed");- const fakeDb = {- select: () => ({- from: () => ({- where: () => Effect.fail(cause),- }),- }),- } as unknown as RelayDb.RelayDb["Service"];-- return Effect.gen(function* () {- const devices = yield* Devices.Devices;- const error = yield* devices.listForUser({ userId: "user-2" }).pipe(Effect.flip);-- expect(error).toMatchObject({ userId: "user-2" });- expect(error.cause).toBe(cause);- expect(error.message).toBe("Failed to list mobile devices for user-2.");- }).pipe(- Effect.provide(Devices.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb)))),- );- });-});diff --git a/infra/relay/src/agentActivity/Devices.ts b/infra/relay/src/agentActivity/Devices.tsdeleted file mode 100644index 42087128c..000000000--- a/infra/relay/src/agentActivity/Devices.ts+++ /dev/null@@ -1,261 +0,0 @@-import type {- RelayClientDeviceRecord,- RelayDeviceRegistrationRequest,-} from "@t3tools/contracts/relay";-import * as Context from "effect/Context";-import * as DateTime from "effect/DateTime";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";-import * as Schema from "effect/Schema";-import { and, eq } from "drizzle-orm";-import { sql } from "drizzle-orm";--import * as RelayDb from "../db.ts";-import { relayLiveActivities, relayMobileDevices } from "../persistence/schema.ts";--export class DeviceRegistrationPersistenceError extends Schema.TaggedErrorClass<DeviceRegistrationPersistenceError>()(- "DeviceRegistrationPersistenceError",- {- userId: Schema.String,- deviceId: Schema.String,- stage: Schema.Literals(["claim-push-token", "claim-push-to-start-token", "upsert-device"]),- cause: Schema.Defect(),- },-) {- override get message(): string {- return `Failed to persist mobile device registration for ${this.userId}/${this.deviceId} during ${this.stage}.`;- }-}--export class DeviceUnregistrationPersistenceError extends Schema.TaggedErrorClass<DeviceUnregistrationPersistenceError>()(- "DeviceUnregistrationPersistenceError",- {- userId: Schema.String,- deviceId: Schema.String,- stage: Schema.Literals(["delete-live-activity", "delete-device"]),- cause: Schema.Defect(),- },-) {- override get message(): string {- return `Failed to unregister mobile device ${this.userId}/${this.deviceId} during ${this.stage}.`;- }-}--export class DeviceListPersistenceError extends Schema.TaggedErrorClass<DeviceListPersistenceError>()(- "DeviceListPersistenceError",- {- userId: Schema.String,- cause: Schema.Defect(),- },-) {- override get message(): string {- return `Failed to list mobile devices for ${this.userId}.`;- }-}--export class Devices extends Context.Service<- Devices,- {- readonly register: (input: {- readonly userId: string;- readonly registration: RelayDeviceRegistrationRequest;- }) => Effect.Effect<void, DeviceRegistrationPersistenceError>;- readonly unregister: (input: {- readonly userId: string;- readonly deviceId: string;- }) => Effect.Effect<void, DeviceUnregistrationPersistenceError>;- readonly listForUser: (input: {- readonly userId: string;- }) => Effect.Effect<ReadonlyArray<RelayClientDeviceRecord>, DeviceListPersistenceError>;- }->()("t3code-relay/agentActivity/Devices") {}--export const make = Effect.gen(function* () {- const db = yield* RelayDb.RelayDb;-- return Devices.of({- register: Effect.fn("relay.devices.register")(function* (input) {- yield* Effect.annotateCurrentSpan({- "relay.mobile.device_id": input.registration.deviceId,- });- const updatedAt = DateTime.formatIso(yield* DateTime.now);- const registration = input.registration;-- // The drizzle handle is alchemy's lazy proxy chain: it only becomes a- // real Effect when consumed via `yield*`. Handing it to Effect.all sends- // the raw Proxy into the fiber runtime, which spins the isolate at 100%- // CPU (registrations then hang until the client aborts) — keep every db- // chain directly yielded.- if (registration.pushToken) {- yield* db- .update(relayMobileDevices)- .set({ pushToken: null, updatedAt })- .where(eq(relayMobileDevices.pushToken, registration.pushToken))- .pipe(- Effect.mapError(- (cause) =>- new DeviceRegistrationPersistenceError({- userId: input.userId,- deviceId: registration.deviceId,- stage: "claim-push-token",- cause,- }),- ),- );- }- if (registration.pushToStartToken) {- yield* db- .update(relayMobileDevices)- .set({ pushToStartToken: null, updatedAt })- .where(eq(relayMobileDevices.pushToStartToken, registration.pushToStartToken))- .pipe(- Effect.mapError(- (cause) =>- new DeviceRegistrationPersistenceError({- userId: input.userId,- deviceId: registration.deviceId,- stage: "claim-push-to-start-token",- cause,- }),- ),- );- }-- yield* db- .insert(relayMobileDevices)- .values({- userId: input.userId,- deviceId: registration.deviceId,- label: registration.label,- platform: registration.platform,- iosMajorVersion: registration.iosMajorVersion,- appVersion: registration.appVersion ?? null,- bundleId: registration.bundleId ?? null,- apsEnvironment: registration.apsEnvironment ?? null,- pushToken: registration.pushToken ?? null,- pushToStartToken: registration.pushToStartToken ?? null,- preferencesJson: registration.preferences,- createdAt: updatedAt,- updatedAt,- })- .onConflictDoUpdate({- target: [relayMobileDevices.userId, relayMobileDevices.deviceId],- set: {- platform: registration.platform,- label: registration.label,- iosMajorVersion: registration.iosMajorVersion,- appVersion: registration.appVersion ?? null,- // Preserve routing from newer app builds when an older build- // re-registers without these fields.- bundleId: sql`coalesce(excluded.bundle_id, ${relayMobileDevices.bundleId})`,- apsEnvironment: sql`coalesce(- excluded.aps_environment,- ${relayMobileDevices.apsEnvironment}- )`,- pushToken: sql`coalesce(excluded.push_token, ${relayMobileDevices.pushToken})`,- pushToStartToken: sql`coalesce(- excluded.push_to_start_token,- ${relayMobileDevices.pushToStartToken}- )`,- preferencesJson: registration.preferences,- updatedAt,- },- })- .pipe(- Effect.mapError(- (cause) =>- new DeviceRegistrationPersistenceError({- userId: input.userId,- deviceId: registration.deviceId,- stage: "upsert-device",- cause,- }),- ),- );- }),- unregister: Effect.fn("relay.devices.unregister")(function* (input) {- yield* Effect.annotateCurrentSpan({- "relay.mobile.device_id": input.deviceId,- });- // Same proxy-chain constraint as register above: db chains must be- // consumed via `yield*`, never passed to Effect.all.- yield* db- .delete(relayLiveActivities)- .where(- and(- eq(relayLiveActivities.userId, input.userId),- eq(relayLiveActivities.deviceId, input.deviceId),- ),- )- .pipe(- Effect.mapError(- (cause) =>- new DeviceUnregistrationPersistenceError({- userId: input.userId,- deviceId: input.deviceId,- stage: "delete-live-activity",- cause,- }),- ),- );- yield* db- .delete(relayMobileDevices)- .where(- and(- eq(relayMobileDevices.userId, input.userId),- eq(relayMobileDevices.deviceId, input.deviceId),- ),- )- .pipe(- Effect.mapError(- (cause) =>- new DeviceUnregistrationPersistenceError({- userId: input.userId,- deviceId: input.deviceId,- stage: "delete-device",- cause,- }),- ),- );- }),- listForUser: Effect.fn("relay.devices.listForUser")(function* (input) {- const rows = yield* db- .select({- deviceId: relayMobileDevices.deviceId,- label: relayMobileDevices.label,- platform: relayMobileDevices.platform,- iosMajorVersion: relayMobileDevices.iosMajorVersion,- appVersion: relayMobileDevices.appVersion,- preferences: relayMobileDevices.preferencesJson,- updatedAt: relayMobileDevices.updatedAt,- })- .from(relayMobileDevices)- .where(eq(relayMobileDevices.userId, input.userId))- .pipe(- Effect.mapError(- (cause) => new DeviceListPersistenceError({ userId: input.userId, cause }),- ),- );- return rows.map((row) => ({- deviceId: row.deviceId,- label: row.label,- platform: row.platform,- iosMajorVersion: row.iosMajorVersion,- appVersion: row.appVersion,- notifications: {- enabled: row.preferences.notificationsEnabled,- notifyOnApproval: row.preferences.notifyOnApproval,- notifyOnInput: row.preferences.notifyOnInput,- notifyOnCompletion: row.preferences.notifyOnCompletion,- notifyOnFailure: row.preferences.notifyOnFailure,- },- liveActivities: {- enabled: row.preferences.liveActivitiesEnabled,- },- updatedAt: row.updatedAt,- }));- }),- });-});--export const layer = Layer.effect(Devices, make);diff --git a/infra/relay/src/agentActivity/LiveActivities.test.ts b/infra/relay/src/agentActivity/LiveActivities.test.tsdeleted file mode 100644index 7f2bce874..000000000--- a/infra/relay/src/agentActivity/LiveActivities.test.ts+++ /dev/null@@ -1,339 +0,0 @@-import type {- RelayAgentActivityAggregateState,- RelayLiveActivityRegistrationRequest,-} from "@t3tools/contracts/relay";-import { describe, expect, it } from "@effect/vitest";-import type { SQL } from "drizzle-orm";-import { PgDialect } from "drizzle-orm/pg-core";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";--import * as RelayDb from "../db.ts";-import { relayLiveActivities } from "../persistence/schema.ts";-import * as LiveActivities from "./LiveActivities.ts";--const aggregate: RelayAgentActivityAggregateState = {- title: "T3 Code",- subtitle: "Agent work in progress",- activeCount: 1,- updatedAt: "2026-05-25T00:00:00.000Z",- activities: [- {- environmentId:- "env" as RelayAgentActivityAggregateState["activities"][number]["environmentId"],- threadId: "thread" as RelayAgentActivityAggregateState["activities"][number]["threadId"],- projectTitle: "Project",- threadTitle: "Thread",- modelTitle: "gpt-5.4",- phase: "running",- status: "Working",- updatedAt: "2026-05-25T00:00:00.000Z",- deepLink: "/threads/env/thread",- },- ],-};--describe("LiveActivities", () => {- it.effect(- "claims Live Activity push tokens globally before upserting the current user device",- () => {- const registration: RelayLiveActivityRegistrationRequest = {- deviceId: "device-1" as RelayLiveActivityRegistrationRequest["deviceId"],- activityPushToken:- "activity-push-token" as RelayLiveActivityRegistrationRequest["activityPushToken"],- };- const calls: Array<string> = [];- const updateSets: Array<Record<string, unknown>> = [];- const updateConditions: Array<SQL> = [];- const insertedValues: Array<Record<string, unknown>> = [];- const conflictConfigs: Array<{- readonly set?: Record<string, unknown>;- }> = [];- const dialect = new PgDialect();-- const fakeDb = {- update: (table: unknown) => {- expect(table).toBe(relayLiveActivities);- calls.push("update");- return {- set: (values: Record<string, unknown>) => {- updateSets.push(values);- calls.push("update.set");- return {- where: (condition: SQL) => {- expect(condition).toBeDefined();- updateConditions.push(condition);- calls.push("update.where");- return Effect.void;- },- };- },- };- },- insert: (table: unknown) => {- expect(table).toBe(relayLiveActivities);- calls.push("insert");- return {- values: (values: Record<string, unknown>) => {- insertedValues.push(values);- calls.push("insert.values");- return {- onConflictDoUpdate: (config: { readonly set?: Record<string, unknown> }) => {- expect(config).toBeDefined();- conflictConfigs.push(config);- calls.push("insert.onConflictDoUpdate");- return Effect.void;- },- };- },- };- },- } as unknown as RelayDb.RelayDb["Service"];-- return Effect.gen(function* () {- const liveActivities = yield* LiveActivities.LiveActivities;- yield* liveActivities.register({ userId: "user-2", registration });-- expect(calls).toEqual([- "update",- "update.set",- "update.where",- "insert",- "insert.values",- "insert.onConflictDoUpdate",- ]);- expect(updateSets).toEqual([- expect.objectContaining({- activityPushToken: null,- remoteStartQueuedAt: null,- remoteStartedAt: null,- }),- ]);- expect(updateConditions.map((condition) => dialect.sqlToQuery(condition))).toEqual([- {- sql: '"relay_live_activities"."activity_push_token" = $1',- params: ["activity-push-token"],- },- ]);- expect(insertedValues).toEqual([- expect.objectContaining({- userId: "user-2",- deviceId: "device-1",- activityPushToken: "activity-push-token",- remoteStartQueuedAt: null,- remoteStartedAt: expect.any(String),- endedAt: null,- lastAggregateJson: null,- lastLiveActivityDeliveryAt: null,- }),- ]);- expect(conflictConfigs[0]?.set).toEqual(- expect.objectContaining({- activityPushToken: "activity-push-token",- remoteStartQueuedAt: null,- remoteStartedAt: expect.any(String),- endedAt: null,- lastAggregateJson: null,- lastLiveActivityDeliveryAt: null,- }),- );- }).pipe(- Effect.provide(- LiveActivities.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb))),- ),- );- },- );-- it.effect("preserves ended state when a delayed update delivery is marked", () => {- const insertedValues: Array<Record<string, unknown>> = [];- const conflictConfigs: Array<{- readonly set?: Record<string, unknown>;- }> = [];-- const fakeDb = {- insert: (table: unknown) => {- expect(table).toBe(relayLiveActivities);- return {- values: (values: Record<string, unknown>) => {- insertedValues.push(values);- return {- onConflictDoUpdate: (config: { readonly set?: Record<string, unknown> }) => {- conflictConfigs.push(config);- return Effect.void;- },- };- },- };- },- } as unknown as RelayDb.RelayDb["Service"];-- return Effect.gen(function* () {- const liveActivities = yield* LiveActivities.LiveActivities;- yield* liveActivities.markDelivery({- userId: "user-2",- deviceId: "device-1",- kind: "live_activity_update",- aggregate,- deliveredAt: "2026-05-25T00:00:10.000Z",- });-- expect(insertedValues).toEqual([- expect.objectContaining({- userId: "user-2",- deviceId: "device-1",- endedAt: null,- }),- ]);- expect(conflictConfigs[0]?.set).toEqual(- expect.objectContaining({- endedAt: relayLiveActivities.endedAt,- lastLiveActivityDeliveryAt: "2026-05-25T00:00:10.000Z",- }),- );- }).pipe(- Effect.provide(- LiveActivities.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb))),- ),- );- });-- it.effect("retires the previous activity token when a start or end is delivered", () => {- const conflictConfigs: Array<{ readonly set?: Record<string, unknown> }> = [];- const fakeDb = {- insert: () => ({- values: () => ({- onConflictDoUpdate: (config: { readonly set?: Record<string, unknown> }) => {- conflictConfigs.push(config);- return Effect.void;- },- }),- }),- } as unknown as RelayDb.RelayDb["Service"];-- return Effect.gen(function* () {- const liveActivities = yield* LiveActivities.LiveActivities;- const mark = (kind: "live_activity_start" | "live_activity_update" | "live_activity_end") =>- liveActivities.markDelivery({- userId: "user-2",- deviceId: "device-1",- kind,- aggregate,- deliveredAt: "2026-05-25T00:00:10.000Z",- });- yield* mark("live_activity_start");- yield* mark("live_activity_update");- yield* mark("live_activity_end");-- // A start begins a new activity generation and an end retires the- // current one; both must drop the stored update token so later- // deliveries can't route to the dead activity. Plain updates keep it.- expect(conflictConfigs[0]?.set).toEqual(- expect.objectContaining({- activityPushToken: null,- remoteStartedAt: "2026-05-25T00:00:10.000Z",- endedAt: null,- }),- );- expect(conflictConfigs[1]?.set?.activityPushToken).not.toBeNull();- expect(conflictConfigs[2]?.set).toEqual(- expect.objectContaining({- activityPushToken: null,- endedAt: "2026-05-25T00:00:10.000Z",- }),- );- }).pipe(- Effect.provide(- LiveActivities.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb))),- ),- );- });-- it.effect("preserves correlation context and causes for persistence failures", () => {- const cause = new Error("database unavailable");- const registration: RelayLiveActivityRegistrationRequest = {- deviceId: "device-1" as RelayLiveActivityRegistrationRequest["deviceId"],- activityPushToken:- "activity-push-token" as RelayLiveActivityRegistrationRequest["activityPushToken"],- };- const fakeDb = {- update: () => ({- set: () => ({ where: () => Effect.fail(cause) }),- }),- insert: () => ({- values: () => ({ onConflictDoUpdate: () => Effect.fail(cause) }),- }),- select: () => ({- from: () => ({- leftJoin: () => ({ where: () => Effect.fail(cause) }),- }),- }),- } as unknown as RelayDb.RelayDb["Service"];-- return Effect.gen(function* () {- const liveActivities = yield* LiveActivities.LiveActivities;- const registrationError = yield* Effect.flip(- liveActivities.register({ userId: "user-1", registration }),- );- const targetListError = yield* Effect.flip(liveActivities.listTargets({ userId: "user-1" }));- const deliveryErrors = yield* Effect.all(- [- liveActivities.markDelivery({- userId: "user-1",- deviceId: "device-1",- kind: "live_activity_update",- aggregate: null,- deliveredAt: "2026-05-25T00:00:10.000Z",- }),- liveActivities.markStartQueued({- userId: "user-1",- deviceId: "device-1",- queuedAt: "2026-05-25T00:00:10.000Z",- }),- liveActivities.clearStartQueued({ userId: "user-1", deviceId: "device-1" }),- liveActivities.invalidateDeliveryToken({- userId: "user-1",- deviceId: "device-1",- kind: "push_notification",- invalidatedAt: "2026-05-25T00:00:10.000Z",- }),- ].map(Effect.flip),- { concurrency: 1 },- );-- expect(registrationError).toMatchObject({- userId: "user-1",- deviceId: "device-1",- cause,- message:- "Failed to persist Live Activity registration for user user-1 and device device-1.",- });- expect(targetListError).toMatchObject({- userId: "user-1",- cause,- message: "Failed to list Live Activity delivery targets for user user-1.",- });-- const expectedDeliveryContext = [- ["mark-delivery", "live_activity_update"],- ["mark-start-queued", null],- ["clear-start-queued", null],- ["invalidate-delivery-token", "push_notification"],- ] as const;- for (const [index, [operation, kind]] of expectedDeliveryContext.entries()) {- expect(deliveryErrors[index]).toMatchObject({- operation,- userId: "user-1",- deviceId: "device-1",- kind,- cause,- message: `Failed to persist Live Activity state during ${operation} for user user-1 and device device-1.`,- });- }- }).pipe(- Effect.provide(- LiveActivities.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb))),- ),- );- });-});diff --git a/infra/relay/src/agentActivity/LiveActivities.ts b/infra/relay/src/agentActivity/LiveActivities.tsdeleted file mode 100644index a2179e1e7..000000000--- a/infra/relay/src/agentActivity/LiveActivities.ts+++ /dev/null@@ -1,479 +0,0 @@-import type {- RelayAgentActivityAggregateState,- RelayDeliveryKind,- RelayLiveActivityRegistrationRequest,-} from "@t3tools/contracts/relay";-import {- RelayAgentActivityAggregateState as RelayAgentActivityAggregateStateSchema,- RelayDeliveryKind as RelayDeliveryKindSchema,-} from "@t3tools/contracts/relay";-import * as Context from "effect/Context";-import * as DateTime from "effect/DateTime";-import * as Effect from "effect/Effect";-import * as Function from "effect/Function";-import * as Layer from "effect/Layer";-import * as Schema from "effect/Schema";-import { and, eq, sql } from "drizzle-orm";--import * as RelayDb from "../db.ts";-import { relayLiveActivities, relayMobileDevices } from "../persistence/schema.ts";--export class LiveActivityRegistrationPersistenceError extends Schema.TaggedErrorClass<LiveActivityRegistrationPersistenceError>()(- "LiveActivityRegistrationPersistenceError",- {- userId: Schema.String,- deviceId: Schema.String,- cause: Schema.Defect(),- },-) {- override get message(): string {- return `Failed to persist Live Activity registration for user ${this.userId} and device ${this.deviceId}.`;- }-}--export class LiveActivityTargetListPersistenceError extends Schema.TaggedErrorClass<LiveActivityTargetListPersistenceError>()(- "LiveActivityTargetListPersistenceError",- {- userId: Schema.String,- cause: Schema.Defect(),- },-) {- override get message(): string {- return `Failed to list Live Activity delivery targets for user ${this.userId}.`;- }-}--export class LiveActivityDeliveryMarkPersistenceError extends Schema.TaggedErrorClass<LiveActivityDeliveryMarkPersistenceError>()(- "LiveActivityDeliveryMarkPersistenceError",- {- operation: Schema.Literals([- "mark-delivery",- "mark-start-queued",- "clear-start-queued",- "invalidate-delivery-token",- ]),- userId: Schema.String,- deviceId: Schema.String,- kind: Schema.NullOr(RelayDeliveryKindSchema),- cause: Schema.Defect(),- },-) {- override get message(): string {- return `Failed to persist Live Activity state during ${this.operation} for user ${this.userId} and device ${this.deviceId}.`;- }-}--export interface DeviceRow {- readonly user_id: string;- readonly device_id: string;- readonly platform: "ios";- readonly ios_major_version: number;- readonly app_version: string | null;- readonly bundle_id: string | null;- readonly aps_environment: "sandbox" | "production" | null;- readonly push_token: string | null;- readonly push_to_start_token: string | null;- readonly preferences_json: string;-}--export interface LiveActivityRow {- readonly activity_push_token: string | null;- readonly remote_start_queued_at: string | null;- readonly remote_started_at: string | null;- readonly ended_at: string | null;- readonly last_aggregate_json: string | null;- readonly last_live_activity_delivery_at: string | null;-}--export type TargetRow = DeviceRow & LiveActivityRow;--export class LiveActivities extends Context.Service<- LiveActivities,- {- readonly register: (input: {- readonly userId: string;- readonly registration: RelayLiveActivityRegistrationRequest;- }) => Effect.Effect<void, LiveActivityRegistrationPersistenceError>;- readonly listTargets: (input: {- readonly userId: string;- }) => Effect.Effect<ReadonlyArray<TargetRow>, LiveActivityTargetListPersistenceError>;- readonly markDelivery: (input: {- readonly userId: string;- readonly deviceId: string;- readonly kind: RelayDeliveryKind;- readonly aggregate: RelayAgentActivityAggregateState | null;- readonly deliveredAt: string;- }) => Effect.Effect<void, LiveActivityDeliveryMarkPersistenceError>;- readonly markStartQueued: (input: {- readonly userId: string;- readonly deviceId: string;- readonly queuedAt: string;- }) => Effect.Effect<void, LiveActivityDeliveryMarkPersistenceError>;- readonly clearStartQueued: (input: {- readonly userId: string;- readonly deviceId: string;- }) => Effect.Effect<void, LiveActivityDeliveryMarkPersistenceError>;- readonly invalidateDeliveryToken: (input: {- readonly userId: string;- readonly deviceId: string;- readonly kind: RelayDeliveryKind;- readonly invalidatedAt: string;- }) => Effect.Effect<void, LiveActivityDeliveryMarkPersistenceError>;- }->()("t3code-relay/agentActivity/LiveActivities") {}--const decodeJsonString = Schema.decodeEffect(Schema.fromJsonString(Schema.Unknown));-const encodeJsonValue = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));--const encodeRelayAgentActivityAggregateStateJson = Schema.encodeEffect(- Schema.fromJsonString(RelayAgentActivityAggregateStateSchema),-);--export const make = Effect.gen(function* () {- const db = yield* RelayDb.RelayDb;-- return LiveActivities.of({- register: Effect.fn("relay.live_activities.register")(function* (input) {- yield* Effect.annotateCurrentSpan({- "relay.mobile.device_id": input.registration.deviceId,- });- yield* Effect.gen(function* () {- const updatedAt = DateTime.formatIso(yield* DateTime.now);- const registration = input.registration;-- yield* db- .update(relayLiveActivities)- .set({- activityPushToken: null,- remoteStartQueuedAt: null,- remoteStartedAt: null,- endedAt: updatedAt,- updatedAt,- })- .where(eq(relayLiveActivities.activityPushToken, registration.activityPushToken));-- yield* db- .insert(relayLiveActivities)- .values({- userId: input.userId,- deviceId: registration.deviceId,- activityPushToken: registration.activityPushToken,- remoteStartQueuedAt: null,- remoteStartedAt: updatedAt,- endedAt: null,- lastAggregateJson: null,- lastLiveActivityDeliveryAt: null,- createdAt: updatedAt,- updatedAt,- })- .onConflictDoUpdate({- target: [relayLiveActivities.userId, relayLiveActivities.deviceId],- set: {- activityPushToken: registration.activityPushToken,- remoteStartQueuedAt: null,- remoteStartedAt: updatedAt,- endedAt: null,- lastAggregateJson: null,- lastLiveActivityDeliveryAt: null,- updatedAt,- },- });- }).pipe(- Effect.mapError(- (cause) =>- new LiveActivityRegistrationPersistenceError({- userId: input.userId,- deviceId: input.registration.deviceId,- cause,- }),- ),- );- }),-- listTargets: Effect.fn("relay.live_activities.list_targets")(function* (input) {- return yield* db- .select({- device_id: relayMobileDevices.deviceId,- user_id: relayMobileDevices.userId,- platform: relayMobileDevices.platform,- ios_major_version: relayMobileDevices.iosMajorVersion,- app_version: relayMobileDevices.appVersion,- bundle_id: relayMobileDevices.bundleId,- aps_environment: relayMobileDevices.apsEnvironment,- push_token: relayMobileDevices.pushToken,- push_to_start_token: relayMobileDevices.pushToStartToken,- preferences_json: relayMobileDevices.preferencesJson,- activity_push_token: relayLiveActivities.activityPushToken,- remote_start_queued_at: relayLiveActivities.remoteStartQueuedAt,- remote_started_at: relayLiveActivities.remoteStartedAt,- ended_at: relayLiveActivities.endedAt,- last_aggregate_json: relayLiveActivities.lastAggregateJson,- last_live_activity_delivery_at: relayLiveActivities.lastLiveActivityDeliveryAt,- })- .from(relayMobileDevices)- .leftJoin(- relayLiveActivities,- and(- eq(relayLiveActivities.userId, relayMobileDevices.userId),- eq(relayLiveActivities.deviceId, relayMobileDevices.deviceId),- ),- )- .where(eq(relayMobileDevices.userId, input.userId))- .pipe(- Effect.flatMap((rows) =>- Effect.forEach(- rows,- (row) =>- Effect.all({- preferences_json: encodeJsonValue(row.preferences_json),- last_aggregate_json:- row.last_aggregate_json === null- ? Effect.succeed(null)- : encodeJsonValue(row.last_aggregate_json),- }).pipe(- Effect.map((json) => ({- ...row,- ...json,- })),- ),- { concurrency: "unbounded" },- ),- ),- Effect.map((rows): ReadonlyArray<TargetRow> => rows),- Effect.mapError(- (cause) =>- new LiveActivityTargetListPersistenceError({- userId: input.userId,- cause,- }),- ),- );- }),-- markDelivery: Effect.fn("relay.live_activities.mark_delivery")(function* (input) {- yield* Effect.annotateCurrentSpan({- "relay.mobile.device_id": input.deviceId,- "relay.delivery.kind": input.kind,- });- yield* Effect.gen(function* () {- const aggregateJson =- input.aggregate === null- ? null- : yield* encodeRelayAgentActivityAggregateStateJson(input.aggregate).pipe(- Effect.flatMap(decodeJsonString),- Effect.map(Function.cast<unknown, RelayAgentActivityAggregateState>),- );-- yield* db- .insert(relayLiveActivities)- .values({- userId: input.userId,- deviceId: input.deviceId,- remoteStartedAt: input.kind === "live_activity_start" ? input.deliveredAt : null,- remoteStartQueuedAt: null,- endedAt: input.kind === "live_activity_end" ? input.deliveredAt : null,- lastAggregateJson: aggregateJson,- lastLiveActivityDeliveryAt: input.deliveredAt,- createdAt: input.deliveredAt,- updatedAt: input.deliveredAt,- })- .onConflictDoUpdate({- target: [relayLiveActivities.userId, relayLiveActivities.deviceId],- set: {- // A delivered start begins a NEW activity generation: the stored- // update token belongs to the previous activity (dead once a new- // one starts, and certainly dead after an end), so keep it only- // for plain updates. Deliveries pause until the app registers- // the fresh activity's token; registerLiveActivity + replay then- // reconcile content (or end the activity if work already- // finished). Without this, updates and ends route to the dead- // token and the new lock-screen card is stranded at its start- // content forever.- activityPushToken:- input.kind === "live_activity_update"- ? sql`${relayLiveActivities.activityPushToken}`- : null,- remoteStartedAt:- input.kind === "live_activity_start"- ? input.deliveredAt- : sql`coalesce(- ${relayLiveActivities.remoteStartedAt},- excluded.remote_started_at- )`,- remoteStartQueuedAt: null,- endedAt:- input.kind === "live_activity_start"- ? null- : input.kind === "live_activity_end"- ? input.deliveredAt- : relayLiveActivities.endedAt,- lastAggregateJson: aggregateJson,- lastLiveActivityDeliveryAt: input.deliveredAt,- updatedAt: input.deliveredAt,- },- });- }).pipe(- Effect.mapError(- (cause) =>- new LiveActivityDeliveryMarkPersistenceError({- operation: "mark-delivery",- userId: input.userId,- deviceId: input.deviceId,- kind: input.kind,- cause,- }),- ),- );- }),-- markStartQueued: Effect.fn("relay.live_activities.mark_start_queued")(function* (input) {- yield* Effect.annotateCurrentSpan({- "relay.mobile.device_id": input.deviceId,- });- yield* db- .insert(relayLiveActivities)- .values({- userId: input.userId,- deviceId: input.deviceId,- remoteStartQueuedAt: input.queuedAt,- remoteStartedAt: null,- endedAt: null,- createdAt: input.queuedAt,- updatedAt: input.queuedAt,- })- .onConflictDoUpdate({- target: [relayLiveActivities.userId, relayLiveActivities.deviceId],- set: {- remoteStartQueuedAt: sql`coalesce(- ${relayLiveActivities.remoteStartQueuedAt},- excluded.remote_start_queued_at- )`,- endedAt: null,- updatedAt: input.queuedAt,- },- })- .pipe(- Effect.mapError(- (cause) =>- new LiveActivityDeliveryMarkPersistenceError({- operation: "mark-start-queued",- userId: input.userId,- deviceId: input.deviceId,- kind: null,- cause,- }),- ),- );- }),-- clearStartQueued: Effect.fn("relay.live_activities.clear_start_queued")(function* (input) {- yield* Effect.annotateCurrentSpan({- "relay.mobile.device_id": input.deviceId,- });- yield* db- .update(relayLiveActivities)- .set({ remoteStartQueuedAt: null })- .where(- and(- eq(relayLiveActivities.userId, input.userId),- eq(relayLiveActivities.deviceId, input.deviceId),- ),- )- .pipe(- Effect.mapError(- (cause) =>- new LiveActivityDeliveryMarkPersistenceError({- operation: "clear-start-queued",- userId: input.userId,- deviceId: input.deviceId,- kind: null,- cause,- }),- ),- );- }),-- invalidateDeliveryToken: Effect.fn("relay.live_activities.invalidate_delivery_token")(- function* (input) {- yield* Effect.annotateCurrentSpan({- "relay.mobile.device_id": input.deviceId,- "relay.delivery.kind": input.kind,- });- yield* Effect.gen(function* () {- if (input.kind === "push_notification") {- yield* db- .update(relayMobileDevices)- .set({- pushToken: null,- updatedAt: input.invalidatedAt,- })- .where(- and(- eq(relayMobileDevices.userId, input.userId),- eq(relayMobileDevices.deviceId, input.deviceId),- ),- );- return;- }-- if (input.kind === "live_activity_start") {- yield* db- .update(relayMobileDevices)- .set({- pushToStartToken: null,- updatedAt: input.invalidatedAt,- })- .where(- and(- eq(relayMobileDevices.userId, input.userId),- eq(relayMobileDevices.deviceId, input.deviceId),- ),- );- yield* db- .update(relayLiveActivities)- .set({- remoteStartQueuedAt: null,- updatedAt: input.invalidatedAt,- })- .where(- and(- eq(relayLiveActivities.userId, input.userId),- eq(relayLiveActivities.deviceId, input.deviceId),- ),- );- return;- }-- yield* db- .update(relayLiveActivities)- .set({- activityPushToken: null,- remoteStartQueuedAt: null,- remoteStartedAt: null,- endedAt: input.invalidatedAt,- updatedAt: input.invalidatedAt,- })- .where(- and(- eq(relayLiveActivities.userId, input.userId),- eq(relayLiveActivities.deviceId, input.deviceId),- ),- );- }).pipe(- Effect.mapError(- (cause) =>- new LiveActivityDeliveryMarkPersistenceError({- operation: "invalidate-delivery-token",- userId: input.userId,- deviceId: input.deviceId,- kind: input.kind,- cause,- }),- ),- );- },- ),- });-});--export const layer = Layer.effect(LiveActivities, make);diff --git a/infra/relay/src/agentActivity/MobileRegistrations.test.ts b/infra/relay/src/agentActivity/MobileRegistrations.test.tsdeleted file mode 100644index ca3948437..000000000--- a/infra/relay/src/agentActivity/MobileRegistrations.test.ts+++ /dev/null@@ -1,486 +0,0 @@-import type {- RelayAgentActivityState,- RelayDeviceRegistrationRequest,-} from "@t3tools/contracts/relay";-import type { SignedApnsDeliveryJob } from "./apnsDeliveryJobs.ts";-import * as NodeCryptoLayer from "@effect/platform-node/NodeCrypto";-import { describe, expect, it } from "@effect/vitest";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";-import * as Logger from "effect/Logger";-import * as Redacted from "effect/Redacted";-import { FetchHttpClient } from "effect/unstable/http";--import * as Devices from "./Devices.ts";-import * as AgentActivityRows from "./AgentActivityRows.ts";-import * as DeliveryAttempts from "./DeliveryAttempts.ts";-import * as EnvironmentLinks from "../environments/EnvironmentLinks.ts";-import * as LiveActivities from "./LiveActivities.ts";-import * as RelayConfiguration from "../Config.ts";-import * as AgentActivityPublisher from "./AgentActivityPublisher.ts";-import * as ApnsDeliveries from "./ApnsDeliveries.ts";-import * as ApnsClient from "./ApnsClient.ts";-import * as ApnsProviderTokens from "./ApnsProviderTokens.ts";-import * as ApnsDeliveryQueue from "./ApnsDeliveryQueue.ts";-import * as MobileRegistrations from "./MobileRegistrations.ts";--const device: RelayDeviceRegistrationRequest = {- deviceId: "device-1" as RelayDeviceRegistrationRequest["deviceId"],- label: "Julius's iPhone",- platform: "ios",- iosMajorVersion: 18,- appVersion: "1.0.0" as RelayDeviceRegistrationRequest["appVersion"],- preferences: {- liveActivitiesEnabled: true,- notificationsEnabled: true,- notifyOnApproval: true,- notifyOnInput: true,- notifyOnCompletion: true,- notifyOnFailure: true,- },-};--function makeDevices(- overrides: Partial<Devices.Devices["Service"]> = {},-): Devices.Devices["Service"] {- return {- register: () => Effect.void,- unregister: () => Effect.void,- listForUser: () => Effect.succeed([]),- ...overrides,- };-}--function makeLiveActivities(- overrides: Partial<LiveActivities.LiveActivities["Service"]> = {},-): LiveActivities.LiveActivities["Service"] {- return {- register: () => Effect.void,- listTargets: () => Effect.succeed([]),- markDelivery: () => Effect.void,- markStartQueued: () => Effect.void,- clearStartQueued: () => Effect.void,- invalidateDeliveryToken: () => Effect.void,- ...overrides,- };-}--function makeAgentActivityRows(- overrides: Partial<AgentActivityRows.AgentActivityRows["Service"]> = {},-): AgentActivityRows.AgentActivityRows["Service"] {- return {- upsert: () => Effect.void,- remove: () => Effect.void,- pruneTerminal: () => Effect.void,- listForUser: () => {- const activeState: RelayAgentActivityState = {- environmentId: "env-1" as RelayAgentActivityState["environmentId"],- threadId: "thread-1" as RelayAgentActivityState["threadId"],- projectTitle: "Project",- threadTitle: "Implement APNs",- modelTitle: "gpt-5.4",- phase: "running",- headline: "Working",- updatedAt: "1970-01-01T00:00:10.000Z",- deepLink: "/env-1/thread-1",- };- return Effect.succeed([activeState]);- },- getForUserThread: () => Effect.succeed(null),- ...overrides,- };-}--function makeEnvironmentLinks(- overrides: Partial<EnvironmentLinks.EnvironmentLinks["Service"]> = {},-): EnvironmentLinks.EnvironmentLinks["Service"] {- return {- upsert: () => Effect.void,- listUsersForEnvironment: () => Effect.succeed(["dev:julius"]),- listDeliveryUsersForEnvironment: () =>- Effect.succeed([- {- userId: "dev:julius",- notificationsEnabled: true,- liveActivitiesEnabled: true,- },- ]),- listPublicKeysForEnvironment: () => Effect.succeed([]),- listForUser: () => Effect.succeed([]),- getForUser: () => Effect.succeed(null),- revokeForUser: () => Effect.succeed(false),- ...overrides,- };-}--function makeDeliveryAttempts(- overrides: Partial<DeliveryAttempts.DeliveryAttempts["Service"]> = {},-): DeliveryAttempts.DeliveryAttempts["Service"] {- return {- record: () => Effect.void,- claimSourceJob: () => Effect.succeed("claimed"),- completeSourceJob: () => Effect.void,- ...overrides,- };-}--const config = RelayConfiguration.RelayConfiguration.of({- relayIssuer: "https://relay.example.test",- apns: {- environment: "sandbox",- teamId: "team-id",- keyId: "key-id",- bundleId: "codes.t3.mobile",- privateKey: Redacted.make("apns-private-key"),- },- clerkSecretKey: Redacted.make("clerk-secret"),- clerkPublishableKey: "pk_test_test",- clerkJwtAudience: "t3-code-relay",- apnsDeliveryJobSigningSecret: Redacted.make("apns-job-secret"),- cloudMintPrivateKey: Redacted.make("cloud-private-key"),- cloudMintPublicKey: "cloud-public-key",- managedEndpointBaseDomain: undefined,- managedEndpointNamespace: undefined,-});--function makeRegistrationReplayLayer(input: {- readonly devices: Devices.Devices["Service"];- readonly liveActivities: LiveActivities.LiveActivities["Service"];- readonly queuedJobs: Array<SignedApnsDeliveryJob>;-}) {- return MobileRegistrations.layer.pipe(- Layer.provide(AgentActivityPublisher.layer),- Layer.provide(- ApnsDeliveries.layer.pipe(- Layer.provide(ApnsClient.layer.pipe(Layer.provide(ApnsProviderTokens.layer))),- ),- ),- Layer.provide(ApnsDeliveryQueue.layer.pipe(Layer.provide(NodeCryptoLayer.layer))),- Layer.provide(- Layer.mergeAll(- Layer.succeed(Devices.Devices, input.devices),- Layer.succeed(AgentActivityRows.AgentActivityRows, makeAgentActivityRows()),- Layer.succeed(EnvironmentLinks.EnvironmentLinks, makeEnvironmentLinks()),- Layer.succeed(LiveActivities.LiveActivities, input.liveActivities),- Layer.succeed(DeliveryAttempts.DeliveryAttempts, makeDeliveryAttempts()),- RelayConfiguration.layer(config),- Layer.succeed(ApnsDeliveryQueue.ApnsDeliveryQueueSender, {- send: (body) =>- Effect.sync(() => {- input.queuedJobs.push(body);- }),- }),- ),- ),- Layer.provide(FetchHttpClient.layer),- );-}--function makeAgentActivityPublisher(- overrides: Partial<AgentActivityPublisher.AgentActivityPublisher["Service"]> = {},-): AgentActivityPublisher.AgentActivityPublisher["Service"] {- return {- publish: () => Effect.succeed({ ok: true, deliveries: [] }),- replayForLiveActivityRegistration: () => Effect.succeed(null),- ...overrides,- };-}--describe("MobileRegistrations", () => {- it.effect("registers devices through the device persistence service", () => {- let registered: Parameters<Devices.Devices["Service"]["register"]>[0] | null = null;- let replayed:- | Parameters<- AgentActivityPublisher.AgentActivityPublisher["Service"]["replayForLiveActivityRegistration"]- >[0]- | null = null;-- return Effect.gen(function* () {- const result = yield* Effect.gen(function* () {- const registrations = yield* MobileRegistrations.MobileRegistrations;- return yield* registrations.registerDevice({ userId: "dev:julius", payload: device });- }).pipe(- Effect.provide(- MobileRegistrations.layer.pipe(- Layer.provide(- Layer.mergeAll(- Layer.succeed(- Devices.Devices,- makeDevices({- register: (input) =>- Effect.sync(() => {- registered = input;- }),- }),- ),- Layer.succeed(LiveActivities.LiveActivities, makeLiveActivities()),- Layer.succeed(AgentActivityRows.AgentActivityRows, makeAgentActivityRows()),- Layer.succeed(- AgentActivityPublisher.AgentActivityPublisher,- makeAgentActivityPublisher({- replayForLiveActivityRegistration: (input) =>- Effect.sync(() => {- replayed = input;- return null;- }),- }),- ),- ),- ),- ),- ),- );-- expect(result).toEqual({ ok: true });- expect(registered).toEqual({ userId: "dev:julius", registration: device });- expect(replayed).toEqual({- userId: "dev:julius",- deviceId: "device-1",- });- });- });-- it.effect("keeps device registration successful when activity replay fails", () => {- const messages: unknown[] = [];- const logger = Logger.make(({ message }) => {- messages.push(message);- });-- return Effect.gen(function* () {- const result = yield* Effect.gen(function* () {- const registrations = yield* MobileRegistrations.MobileRegistrations;- return yield* registrations.registerDevice({ userId: "dev:julius", payload: device });- }).pipe(- Effect.provide(- MobileRegistrations.layer.pipe(- Layer.provide(- Layer.mergeAll(- Layer.succeed(Devices.Devices, makeDevices()),- Layer.succeed(LiveActivities.LiveActivities, makeLiveActivities()),- Layer.succeed(AgentActivityRows.AgentActivityRows, makeAgentActivityRows()),- Layer.succeed(- AgentActivityPublisher.AgentActivityPublisher,- makeAgentActivityPublisher({- replayForLiveActivityRegistration: () =>- Effect.fail(- new AgentActivityRows.AgentActivityRowListPersistenceError({- userId: "dev:julius",- cause: "sensitive device replay detail",- }),- ),- }),- ),- ),- ),- ),- ),- );-- expect(result).toEqual({ ok: true });- expect(messages).toContainEqual([- "device registration activity replay failed",- { errorTag: "AgentActivityRowListPersistenceError" },- ]);- }).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false })));- });-- it.effect("unregisters the current user's device", () => {- let unregistered: Parameters<Devices.Devices["Service"]["unregister"]>[0] | null = null;-- return Effect.gen(function* () {- const result = yield* Effect.gen(function* () {- const registrations = yield* MobileRegistrations.MobileRegistrations;- return yield* registrations.unregisterDevice({- userId: "dev:julius",- deviceId: "device-1",- });- }).pipe(- Effect.provide(- MobileRegistrations.layer.pipe(- Layer.provide(- Layer.mergeAll(- Layer.succeed(- Devices.Devices,- makeDevices({- unregister: (input) =>- Effect.sync(() => {- unregistered = input;- }),- }),- ),- Layer.succeed(LiveActivities.LiveActivities, makeLiveActivities()),- Layer.succeed(AgentActivityRows.AgentActivityRows, makeAgentActivityRows()),- Layer.succeed(- AgentActivityPublisher.AgentActivityPublisher,- makeAgentActivityPublisher(),- ),- ),- ),- ),- ),- );-- expect(result).toEqual({ ok: true });- expect(unregistered).toEqual({- userId: "dev:julius",- deviceId: "device-1",- });- });- });-- it.effect("replays the latest activity state after registering a Live Activity token", () => {- const liveActivity = {- deviceId: "device-1" as const,- activityPushToken: "activity-token" as const,- };- let registered: Parameters<LiveActivities.LiveActivities["Service"]["register"]>[0] | null =- null;- let replayed:- | Parameters<- AgentActivityPublisher.AgentActivityPublisher["Service"]["replayForLiveActivityRegistration"]- >[0]- | null = null;-- return Effect.gen(function* () {- const result = yield* Effect.gen(function* () {- const registrations = yield* MobileRegistrations.MobileRegistrations;- return yield* registrations.registerLiveActivity({- userId: "dev:julius",- payload: liveActivity,- });- }).pipe(- Effect.provide(- MobileRegistrations.layer.pipe(- Layer.provide(- Layer.mergeAll(- Layer.succeed(Devices.Devices, makeDevices()),- Layer.succeed(AgentActivityRows.AgentActivityRows, makeAgentActivityRows()),- Layer.succeed(- LiveActivities.LiveActivities,- makeLiveActivities({- register: (input) =>- Effect.sync(() => {- registered = input;- }),- }),- ),- Layer.succeed(- AgentActivityPublisher.AgentActivityPublisher,- makeAgentActivityPublisher({- replayForLiveActivityRegistration: (input) =>- Effect.sync(() => {- replayed = input;- return null;- }),- }),- ),- ),- ),- ),- ),- );-- expect(result).toEqual({ ok: true });- expect(registered).toEqual({- userId: "dev:julius",- registration: liveActivity,- });- expect(replayed).toEqual({- userId: "dev:julius",- deviceId: "device-1",- });- });- });-- it.effect("returns the current aggregate for the app's arming decision", () => {- return Effect.gen(function* () {- const registrations = yield* MobileRegistrations.MobileRegistrations;- const snapshot = yield* registrations.getAgentActivitySnapshot({ userId: "dev:julius" });-- expect(snapshot.aggregate).toMatchObject({- activeCount: 1,- activities: [{ threadId: "thread-1", phase: "running" }],- });- }).pipe(- Effect.provide(- MobileRegistrations.layer.pipe(- Layer.provide(- Layer.mergeAll(- Layer.succeed(Devices.Devices, makeDevices()),- Layer.succeed(AgentActivityRows.AgentActivityRows, makeAgentActivityRows()),- Layer.succeed(LiveActivities.LiveActivities, makeLiveActivities()),- Layer.succeed(- AgentActivityPublisher.AgentActivityPublisher,- makeAgentActivityPublisher(),- ),- ),- ),- ),- ),- );- });-- it.effect(- "does not remotely start a Live Activity when a device registers after work is already active",- () => {- const queuedJobs: Array<SignedApnsDeliveryJob> = [];- const queuedStarts: Array<- Parameters<LiveActivities.LiveActivities["Service"]["markStartQueued"]>[0]- > = [];- const registeredDevices: Array<Parameters<Devices.Devices["Service"]["register"]>[0]> = [];- const devices = makeDevices({- register: (input) =>- Effect.sync(() => {- registeredDevices.push(input);- }),- });- const liveActivities = makeLiveActivities({- listTargets: () =>- Effect.succeed([- {- user_id: "dev:julius",- device_id: "device-1",- platform: "ios",- ios_major_version: 18,- app_version: "1.0.0",- bundle_id: null,- aps_environment: null,- push_token: "apns-device-token",- push_to_start_token: "push-to-start-token",- preferences_json: JSON.stringify(device.preferences),- activity_push_token: null,- remote_start_queued_at: null,- remote_started_at: null,- ended_at: null,- last_aggregate_json: null,- last_live_activity_delivery_at: null,- },- ]),- markStartQueued: (input) =>- Effect.sync(() => {- queuedStarts.push(input);- }),- });-- return Effect.gen(function* () {- const registrations = yield* MobileRegistrations.MobileRegistrations;- const result = yield* registrations.registerDevice({- userId: "dev:julius",- payload: {- ...device,- pushToken: "apns-device-token",- pushToStartToken: "push-to-start-token",- },- });-- // Activities are armed by the app in the foreground; a device- // registration alone never remote-starts one, even when work is- // already active and a push-to-start token is on file.- expect(result).toEqual({ ok: true });- expect(registeredDevices).toHaveLength(1);- expect(queuedStarts).toEqual([]);- expect(queuedJobs).toEqual([]);- }).pipe(Effect.provide(makeRegistrationReplayLayer({ devices, liveActivities, queuedJobs })));- },- );-});diff --git a/infra/relay/src/agentActivity/MobileRegistrations.ts b/infra/relay/src/agentActivity/MobileRegistrations.tsdeleted file mode 100644index aee83e4b0..000000000--- a/infra/relay/src/agentActivity/MobileRegistrations.ts+++ /dev/null@@ -1,116 +0,0 @@-import type {- RelayAgentActivitySnapshotResponse,- RelayDeviceRegistrationRequest,- RelayLiveActivityRegistrationRequest,-} from "@t3tools/contracts/relay";-import * as DateTime from "effect/DateTime";-import * as Context from "effect/Context";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";--import * as AgentActivityRows from "./AgentActivityRows.ts";-import * as Devices from "./Devices.ts";-import * as LiveActivities from "./LiveActivities.ts";-import * as AgentActivityPublisher from "./AgentActivityPublisher.ts";--export type MobileRegistrationError =- | Devices.DeviceRegistrationPersistenceError- | Devices.DeviceUnregistrationPersistenceError- | LiveActivities.LiveActivityRegistrationPersistenceError- | AgentActivityRows.AgentActivityRowListPersistenceError;--export class MobileRegistrations extends Context.Service<- MobileRegistrations,- {- readonly registerDevice: (input: {- readonly userId: string;- readonly payload: RelayDeviceRegistrationRequest;- }) => Effect.Effect<{ readonly ok: true }, MobileRegistrationError>;- readonly registerLiveActivity: (input: {- readonly userId: string;- readonly payload: RelayLiveActivityRegistrationRequest;- }) => Effect.Effect<{ readonly ok: true }, MobileRegistrationError>;- readonly unregisterDevice: (input: {- readonly userId: string;- readonly deviceId: string;- }) => Effect.Effect<{ readonly ok: true }, MobileRegistrationError>;- readonly getAgentActivitySnapshot: (input: {- readonly userId: string;- }) => Effect.Effect<RelayAgentActivitySnapshotResponse, MobileRegistrationError>;- }->()("t3code-relay/agentActivity/MobileRegistrations") {}--export const make = Effect.gen(function* () {- const rows = yield* AgentActivityRows.AgentActivityRows;- const devices = yield* Devices.Devices;- const liveActivities = yield* LiveActivities.LiveActivities;- const publisher = yield* AgentActivityPublisher.AgentActivityPublisher;-- return MobileRegistrations.of({- registerDevice: Effect.fn("relay.mobile_registrations.register_device")(function* (input) {- yield* Effect.annotateCurrentSpan({- "relay.mobile.device_id": input.payload.deviceId,- "relay.mobile.platform": input.payload.platform,- });- yield* devices.register({ userId: input.userId, registration: input.payload });- yield* publisher- .replayForLiveActivityRegistration({- userId: input.userId,- deviceId: input.payload.deviceId,- })- .pipe(- Effect.tapError((error) =>- Effect.logWarning("device registration activity replay failed", {- errorTag: error._tag,- }),- ),- Effect.ignore,- );- return { ok: true as const };- }),- registerLiveActivity: Effect.fn("relay.mobile_registrations.register_live_activity")(- function* (input) {- yield* Effect.annotateCurrentSpan({- "relay.mobile.device_id": input.payload.deviceId,- });- yield* liveActivities.register({ userId: input.userId, registration: input.payload });- yield* publisher- .replayForLiveActivityRegistration({- userId: input.userId,- deviceId: input.payload.deviceId,- })- .pipe(- Effect.tapError((error) =>- Effect.logWarning("live activity registration replay failed", {- errorTag: error._tag,- }),- ),- Effect.ignore,- );- return { ok: true as const };- },- ),- getAgentActivitySnapshot: Effect.fn("relay.mobile_registrations.get_agent_activity_snapshot")(- function* (input) {- const activeStates = yield* rows.listForUser({ userId: input.userId });- const now = yield* DateTime.now;- return {- aggregate: AgentActivityPublisher.makeAggregateState({- activeStates,- terminalState: null,- nowMs: now.epochMilliseconds,- }),- };- },- ),- unregisterDevice: Effect.fn("relay.mobile_registrations.unregister_device")(function* (input) {- yield* Effect.annotateCurrentSpan({- "relay.mobile.device_id": input.deviceId,- });- yield* devices.unregister(input);- return { ok: true as const };- }),- });-});--export const layer = Layer.effect(MobileRegistrations, make);diff --git a/infra/relay/src/agentActivity/agentActivityPayloads.ts b/infra/relay/src/agentActivity/agentActivityPayloads.tsdeleted file mode 100644index a5e12a4be..000000000--- a/infra/relay/src/agentActivity/agentActivityPayloads.ts+++ /dev/null@@ -1,101 +0,0 @@-import type {- RelayAgentActivityAggregateRow,- RelayAgentActivityAggregateState,- RelayAgentActivityState,-} from "@t3tools/contracts/relay";-import * as DateTime from "effect/DateTime";-import * as Option from "effect/Option";--import type { ApnsNotificationPayload } from "./apnsDeliveryJobs.ts";--export function isTerminalPhase(state: RelayAgentActivityState): boolean {- return state.phase === "completed" || state.phase === "failed";-}--// Rows are only removed when their environment publishes a terminal state. An-// environment that dies mid-run (machine off, process killed) never does, so-// without an age cutoff its threads inflate activeCount forever. Actively-// running phases expire quickly; waiting phases can legitimately sit for hours-// while a user ignores an approval prompt, so they get a longer window. The-// underlying database row is left in place: a late publish for the thread-// refreshes updatedAt and the row becomes visible again.-const RUNNING_AGENT_ACTIVITY_ROW_TTL_MS = 2 * 60 * 60 * 1_000;-const WAITING_AGENT_ACTIVITY_ROW_TTL_MS = 24 * 60 * 60 * 1_000;--export function isExpiredAgentActivityState(- state: RelayAgentActivityState,- nowMs: number,-): boolean {- const updatedAtMs = Option.match(DateTime.make(state.updatedAt), {- onNone: () => Number.NaN,- onSome: (dt) => dt.epochMilliseconds,- });- if (Number.isNaN(updatedAtMs)) {- return true;- }- const ttlMs =- state.phase === "running" || state.phase === "starting"- ? RUNNING_AGENT_ACTIVITY_ROW_TTL_MS- : WAITING_AGENT_ACTIVITY_ROW_TTL_MS;- return nowMs - updatedAtMs > ttlMs;-}--const MAX_SUMMARY_TEXT_LENGTH = 120;-const MAX_STATUS_TEXT_LENGTH = 40;-const MAX_DEEP_LINK_LENGTH = 512;-// The Live Activity banner (lock screen / Notification Center) renders up to-// five rows; the expanded Dynamic Island shows the top three of these.-export const MAX_ACTIVITY_ROWS = 5;--function truncateText(value: string, maxLength: number): string {- const trimmed = value.trim();- if (trimmed.length <= maxLength) {- return trimmed;- }- return trimmed.slice(0, maxLength - 3).trimEnd() + "...";-}--function sanitizeDeepLink(value: string): string {- const trimmed = value.trim();- if (!trimmed.startsWith("/") || trimmed.startsWith("//")) {- return "/";- }- return truncateText(trimmed, MAX_DEEP_LINK_LENGTH);-}--export function sanitizeAgentActivityAggregateRow(- row: RelayAgentActivityAggregateRow,-): RelayAgentActivityAggregateRow {- return {- ...row,- projectTitle: truncateText(row.projectTitle, MAX_SUMMARY_TEXT_LENGTH),- threadTitle: truncateText(row.threadTitle, MAX_SUMMARY_TEXT_LENGTH),- modelTitle: truncateText(row.modelTitle, MAX_SUMMARY_TEXT_LENGTH),- status: truncateText(row.status, MAX_STATUS_TEXT_LENGTH),- deepLink: sanitizeDeepLink(row.deepLink),- };-}--export function sanitizeAgentActivityAggregateState(- aggregate: RelayAgentActivityAggregateState,-): RelayAgentActivityAggregateState {- return {- ...aggregate,- title: truncateText(aggregate.title, MAX_SUMMARY_TEXT_LENGTH),- subtitle: truncateText(aggregate.subtitle, MAX_SUMMARY_TEXT_LENGTH),- activities: aggregate.activities- .slice(0, MAX_ACTIVITY_ROWS)- .map(sanitizeAgentActivityAggregateRow),- };-}--export function sanitizeApnsNotificationPayload(- notification: ApnsNotificationPayload,-): ApnsNotificationPayload {- return {- ...notification,- title: truncateText(notification.title, MAX_SUMMARY_TEXT_LENGTH),- body: truncateText(notification.body, MAX_SUMMARY_TEXT_LENGTH),- deepLink: sanitizeDeepLink(notification.deepLink),- };-}diff --git a/infra/relay/src/agentActivity/apnsDeliveryJobs.test.ts b/infra/relay/src/agentActivity/apnsDeliveryJobs.test.tsdeleted file mode 100644index a0a45b9ed..000000000--- a/infra/relay/src/agentActivity/apnsDeliveryJobs.test.ts+++ /dev/null@@ -1,252 +0,0 @@-import { describe, expect, it } from "@effect/vitest";-import { EnvironmentId, ThreadId } from "@t3tools/contracts";-import type { RelayAgentActivityAggregateState } from "@t3tools/contracts/relay";-import * as Redacted from "effect/Redacted";--import {- makeApnsDeliveryJobPayload,- signApnsDeliveryJob,- verifySignedApnsDeliveryJob,-} from "./apnsDeliveryJobs.ts";--const secret = Redacted.make("queue-signing-secret");-const aggregate: RelayAgentActivityAggregateState = {- title: "T3 Code",- subtitle: "Agent work in progress",- activeCount: 1,- updatedAt: "2026-05-25T00:00:00.000Z",- activities: [- {- environmentId: EnvironmentId.make("env"),- threadId: ThreadId.make("thread"),- projectTitle: "Project",- threadTitle: "Thread",- modelTitle: "gpt-5.4",- phase: "running",- status: "Working",- updatedAt: "2026-05-25T00:00:00.000Z",- deepLink: "/threads/env/thread",- },- ],-};--const notification = {- title: "Thread",- body: "Input: Project",- environmentId: "env",- threadId: "thread",- deepLink: "/threads/env/thread",-};--describe("apnsDeliveryJobs", () => {- it("rejects tampered signed queue jobs", () => {- const payload = makeApnsDeliveryJobPayload({- kind: "live_activity_end",- userId: "user-1",- deviceId: "device-1",- token: "token-1",- aggregate: null,- createdAt: "2026-05-25T00:00:00.000Z",- expiresAt: "2026-05-25T00:05:00.000Z",- jobId: "job-1",- });- const signed = signApnsDeliveryJob({ secret, payload });- const tampered = {- ...signed,- payload: {- ...signed.payload,- target: {- ...signed.payload.target,- token: "attacker-token",- },- },- };-- const result = verifySignedApnsDeliveryJob({- secret,- job: tampered,- nowMs: 0,- });-- expect(result).toMatchObject({- _tag: "ApnsDeliveryJobSignatureInvalid",- jobId: "job-1",- kind: "live_activity_end",- userId: "user-1",- deviceId: "device-1",- message: "Invalid signature for APNs delivery job job-1.",- });- });-- it("rejects Live Activity start jobs without aggregate state", () => {- const payload = makeApnsDeliveryJobPayload({- kind: "live_activity_start",- userId: "user-1",- deviceId: "device-1",- token: "token-1",- aggregate: null,- createdAt: "2026-05-25T00:00:00.000Z",- expiresAt: "2026-05-25T00:05:00.000Z",- jobId: "job-start-invalid",- });- const signed = signApnsDeliveryJob({ secret, payload });-- const result = verifySignedApnsDeliveryJob({- secret,- job: signed,- nowMs: 0,- });-- expect(result).toMatchObject({- _tag: "ApnsDeliveryJobLiveActivityAggregateMissing",- jobId: "job-start-invalid",- kind: "live_activity_start",- userId: "user-1",- deviceId: "device-1",- message: "APNs live activity start job job-start-invalid requires an aggregate.",- });- });-- it("rejects push notification jobs carrying aggregate state", () => {- const payload = makeApnsDeliveryJobPayload({- kind: "push_notification",- userId: "user-1",- deviceId: "device-1",- token: "token-1",- aggregate,- notification,- createdAt: "2026-05-25T00:00:00.000Z",- expiresAt: "2026-05-25T00:05:00.000Z",- jobId: "job-push-invalid",- });- const signed = signApnsDeliveryJob({ secret, payload });-- const result = verifySignedApnsDeliveryJob({- secret,- job: signed,- nowMs: 0,- });-- expect(result).toMatchObject({- _tag: "ApnsDeliveryJobPushNotificationAggregateUnexpected",- jobId: "job-push-invalid",- userId: "user-1",- deviceId: "device-1",- message: "APNs push notification job job-push-invalid must not carry aggregate state.",- });- });-- it("accepts minimal kind-specific signed queue jobs", () => {- const pushPayload = makeApnsDeliveryJobPayload({- kind: "push_notification",- userId: "user-1",- deviceId: "device-1",- token: "token-1",- aggregate: null,- notification,- createdAt: "2026-05-25T00:00:00.000Z",- expiresAt: "2026-05-25T00:05:00.000Z",- jobId: "job-push-valid",- });- const liveActivityPayload = makeApnsDeliveryJobPayload({- kind: "live_activity_update",- userId: "user-1",- deviceId: "device-1",- token: "token-1",- aggregate,- createdAt: "2026-05-25T00:00:00.000Z",- expiresAt: "2026-05-25T00:05:00.000Z",- jobId: "job-live-valid",- });-- expect(- verifySignedApnsDeliveryJob({- secret,- job: signApnsDeliveryJob({ secret, payload: pushPayload }),- nowMs: 0,- }),- ).toEqual(pushPayload);- expect(- verifySignedApnsDeliveryJob({- secret,- job: signApnsDeliveryJob({ secret, payload: liveActivityPayload }),- nowMs: 0,- }),- ).toEqual(liveActivityPayload);- });-- it("rejects jobs with invalid or overlong time windows", () => {- const basePayload = makeApnsDeliveryJobPayload({- kind: "live_activity_end",- userId: "user-1",- deviceId: "device-1",- token: "token-1",- aggregate: null,- createdAt: "2026-05-25T00:00:00.000Z",- expiresAt: "2026-05-25T00:10:00.000Z",- jobId: "job-window",- });- const invalidCreatedAt = {- ...basePayload,- createdAt: "not-a-date",- };- const invertedWindow = {- ...basePayload,- expiresAt: "2026-05-24T23:59:59.000Z",- };- const overlongWindow = {- ...basePayload,- expiresAt: "2026-05-25T00:10:01.000Z",- };-- expect(- verifySignedApnsDeliveryJob({- secret,- job: signApnsDeliveryJob({ secret, payload: invalidCreatedAt }),- nowMs: 0,- }),- ).toMatchObject({- _tag: "ApnsDeliveryJobCreatedAtInvalid",- jobId: "job-window",- kind: "live_activity_end",- userId: "user-1",- deviceId: "device-1",- createdAt: "not-a-date",- message: "APNs delivery job job-window has invalid creation time not-a-date.",- });- expect(- verifySignedApnsDeliveryJob({- secret,- job: signApnsDeliveryJob({ secret, payload: invertedWindow }),- nowMs: 0,- }),- ).toMatchObject({- _tag: "ApnsDeliveryJobTimeWindowInvalid",- jobId: "job-window",- kind: "live_activity_end",- userId: "user-1",- deviceId: "device-1",- createdAt: "2026-05-25T00:00:00.000Z",- expiresAt: "2026-05-24T23:59:59.000Z",- message:- "APNs delivery job job-window has invalid time window 2026-05-25T00:00:00.000Z to 2026-05-24T23:59:59.000Z.",- });- expect(- verifySignedApnsDeliveryJob({- secret,- job: signApnsDeliveryJob({ secret, payload: overlongWindow }),- nowMs: 0,- }),- ).toMatchObject({- _tag: "ApnsDeliveryJobTimeWindowTooLong",- jobId: "job-window",- kind: "live_activity_end",- userId: "user-1",- deviceId: "device-1",- createdAt: "2026-05-25T00:00:00.000Z",- expiresAt: "2026-05-25T00:10:01.000Z",- message:- "APNs delivery job job-window time window 2026-05-25T00:00:00.000Z to 2026-05-25T00:10:01.000Z is too long.",- });- });-});diff --git a/infra/relay/src/agentActivity/apnsDeliveryJobs.ts b/infra/relay/src/agentActivity/apnsDeliveryJobs.tsdeleted file mode 100644index 256ca3edb..000000000--- a/infra/relay/src/agentActivity/apnsDeliveryJobs.ts+++ /dev/null@@ -1,438 +0,0 @@-import * as NodeCrypto from "node:crypto";--import {- RelayAgentActivityAggregateState,- RelayAgentAwarenessPhase,- type RelayDeliveryKind,-} from "@t3tools/contracts/relay";-import { stableStringify } from "@t3tools/shared/relaySigning";-import * as DateTime from "effect/DateTime";-import * as Option from "effect/Option";-import * as Redacted from "effect/Redacted";-import * as Schema from "effect/Schema";--const MAX_JOB_AGE_MS = 10 * 60 * 1_000;-export const APNS_DELIVERY_JOB_SIGNING_ALGORITHM = "hmac-sha256";--const ApnsDeliveryKindSchema = Schema.Literals([- "live_activity_start",- "live_activity_update",- "live_activity_end",- "push_notification",-]);-const LiveActivityStartOrUpdateKindSchema = Schema.Literals([- "live_activity_start",- "live_activity_update",-]);-const LiveActivityKindSchema = Schema.Literals([- "live_activity_start",- "live_activity_update",- "live_activity_end",-]);--const ApnsDeliveryJobContext = {- jobId: Schema.String,- userId: Schema.String,- deviceId: Schema.String,-};--export const ApnsNotificationPayload = Schema.Struct({- title: Schema.String,- body: Schema.String,- environmentId: Schema.String,- threadId: Schema.String,- deepLink: Schema.String,- // Optional so delivery jobs queued by older relay builds still decode.- // New jobs use these fields to avoid delivering a stale Done/attention- // notification after the thread has moved to another phase.- phase: Schema.optional(RelayAgentAwarenessPhase),- updatedAt: Schema.optional(Schema.String),-});-export type ApnsNotificationPayload = typeof ApnsNotificationPayload.Type;--// Alert copy attached to a Live Activity update/end push. Its presence makes-// the update "alerting": iOS wakes the screen, plays the haptic, and briefly-// expands the Dynamic Island instead of silently redrawing.-export const ApnsLiveActivityAlert = Schema.Struct({- title: Schema.String,- body: Schema.String,-});-export type ApnsLiveActivityAlert = typeof ApnsLiveActivityAlert.Type;--export const ApnsDeliveryJobPayload = Schema.Struct({- version: Schema.Literal(1),- jobId: Schema.String,- kind: ApnsDeliveryKindSchema,- target: Schema.Struct({- userId: Schema.String,- deviceId: Schema.String,- token: Schema.String,- // Per-device APNs routing; absent on jobs queued by older relay builds,- // which fall back to the configured defaults.- bundleId: Schema.optional(Schema.NullOr(Schema.String)),- apsEnvironment: Schema.optional(Schema.NullOr(Schema.Literals(["sandbox", "production"]))),- }),- aggregate: Schema.NullOr(RelayAgentActivityAggregateState),- notification: Schema.NullOr(ApnsNotificationPayload),- // Optional so jobs queued by older relay builds still decode.- alert: Schema.optional(Schema.NullOr(ApnsLiveActivityAlert)),- createdAt: Schema.String,- expiresAt: Schema.String,-});-export type ApnsDeliveryJobPayload = typeof ApnsDeliveryJobPayload.Type;--export const SignedApnsDeliveryJob = Schema.Struct({- algorithm: Schema.Literal(APNS_DELIVERY_JOB_SIGNING_ALGORITHM),- payload: ApnsDeliveryJobPayload,- signature: Schema.String,-});-export type SignedApnsDeliveryJob = typeof SignedApnsDeliveryJob.Type;--export class ApnsDeliveryJobQueuePayloadInvalid extends Schema.TaggedErrorClass<ApnsDeliveryJobQueuePayloadInvalid>()(- "ApnsDeliveryJobQueuePayloadInvalid",- {- receivedType: Schema.String,- cause: Schema.Defect(),- },-) {- override get message(): string {- return `Invalid APNs delivery queue job with ${this.receivedType} payload.`;- }-}--export class ApnsDeliveryJobLiveActivityAggregateMissing extends Schema.TaggedErrorClass<ApnsDeliveryJobLiveActivityAggregateMissing>()(- "ApnsDeliveryJobLiveActivityAggregateMissing",- {- ...ApnsDeliveryJobContext,- kind: LiveActivityStartOrUpdateKindSchema,- },-) {- override get message(): string {- return `APNs ${this.kind.replaceAll("_", " ")} job ${this.jobId} requires an aggregate.`;- }-}--export class ApnsDeliveryJobLiveActivityNotificationUnexpected extends Schema.TaggedErrorClass<ApnsDeliveryJobLiveActivityNotificationUnexpected>()(- "ApnsDeliveryJobLiveActivityNotificationUnexpected",- {- ...ApnsDeliveryJobContext,- kind: LiveActivityKindSchema,- },-) {- override get message(): string {- return `APNs ${this.kind.replaceAll("_", " ")} job ${this.jobId} must not carry a push notification payload.`;- }-}--export class ApnsDeliveryJobPushNotificationMissing extends Schema.TaggedErrorClass<ApnsDeliveryJobPushNotificationMissing>()(- "ApnsDeliveryJobPushNotificationMissing",- ApnsDeliveryJobContext,-) {- override get message(): string {- return `APNs push notification job ${this.jobId} requires a notification payload.`;- }-}--export class ApnsDeliveryJobPushNotificationAggregateUnexpected extends Schema.TaggedErrorClass<ApnsDeliveryJobPushNotificationAggregateUnexpected>()(- "ApnsDeliveryJobPushNotificationAggregateUnexpected",- ApnsDeliveryJobContext,-) {- override get message(): string {- return `APNs push notification job ${this.jobId} must not carry aggregate state.`;- }-}--export class ApnsDeliveryJobCreatedAtInvalid extends Schema.TaggedErrorClass<ApnsDeliveryJobCreatedAtInvalid>()(- "ApnsDeliveryJobCreatedAtInvalid",- {- ...ApnsDeliveryJobContext,- kind: ApnsDeliveryKindSchema,- createdAt: Schema.String,- },-) {- override get message(): string {- return `APNs delivery job ${this.jobId} has invalid creation time ${this.createdAt}.`;- }-}--export class ApnsDeliveryJobExpiresAtInvalid extends Schema.TaggedErrorClass<ApnsDeliveryJobExpiresAtInvalid>()(- "ApnsDeliveryJobExpiresAtInvalid",- {- ...ApnsDeliveryJobContext,- kind: ApnsDeliveryKindSchema,- expiresAt: Schema.String,- },-) {- override get message(): string {- return `APNs delivery job ${this.jobId} has invalid expiry ${this.expiresAt}.`;- }-}--export class ApnsDeliveryJobTimeWindowInvalid extends Schema.TaggedErrorClass<ApnsDeliveryJobTimeWindowInvalid>()(- "ApnsDeliveryJobTimeWindowInvalid",- {- ...ApnsDeliveryJobContext,- kind: ApnsDeliveryKindSchema,- createdAt: Schema.String,- expiresAt: Schema.String,- },-) {- override get message(): string {- return `APNs delivery job ${this.jobId} has invalid time window ${this.createdAt} to ${this.expiresAt}.`;- }-}--export class ApnsDeliveryJobTimeWindowTooLong extends Schema.TaggedErrorClass<ApnsDeliveryJobTimeWindowTooLong>()(- "ApnsDeliveryJobTimeWindowTooLong",- {- ...ApnsDeliveryJobContext,- kind: ApnsDeliveryKindSchema,- createdAt: Schema.String,- expiresAt: Schema.String,- },-) {- override get message(): string {- return `APNs delivery job ${this.jobId} time window ${this.createdAt} to ${this.expiresAt} is too long.`;- }-}--export class ApnsDeliveryJobSignatureInvalid extends Schema.TaggedErrorClass<ApnsDeliveryJobSignatureInvalid>()(- "ApnsDeliveryJobSignatureInvalid",- {- ...ApnsDeliveryJobContext,- kind: ApnsDeliveryKindSchema,- },-) {- override get message(): string {- return `Invalid signature for APNs delivery job ${this.jobId}.`;- }-}--export const ApnsDeliveryJobInvalid = Schema.Union([- ApnsDeliveryJobQueuePayloadInvalid,- ApnsDeliveryJobLiveActivityAggregateMissing,- ApnsDeliveryJobLiveActivityNotificationUnexpected,- ApnsDeliveryJobPushNotificationMissing,- ApnsDeliveryJobPushNotificationAggregateUnexpected,- ApnsDeliveryJobCreatedAtInvalid,- ApnsDeliveryJobExpiresAtInvalid,- ApnsDeliveryJobTimeWindowInvalid,- ApnsDeliveryJobTimeWindowTooLong,- ApnsDeliveryJobSignatureInvalid,-]);-export type ApnsDeliveryJobInvalid = typeof ApnsDeliveryJobInvalid.Type;--export class ApnsDeliveryJobExpired extends Schema.TaggedErrorClass<ApnsDeliveryJobExpired>()(- "ApnsDeliveryJobExpired",- {- ...ApnsDeliveryJobContext,- kind: ApnsDeliveryKindSchema,- expiresAt: Schema.String,- },-) {- override get message(): string {- return `APNs delivery job ${this.jobId} expired at ${this.expiresAt}.`;- }-}--export const ApnsDeliveryJobVerificationError = Schema.Union([- ApnsDeliveryJobInvalid,- ApnsDeliveryJobExpired,-]);-export type ApnsDeliveryJobVerificationError = typeof ApnsDeliveryJobVerificationError.Type;--export const isApnsDeliveryJobVerificationError = Schema.is(ApnsDeliveryJobVerificationError);--export function makeApnsDeliveryJobPayload(input: {- readonly kind: RelayDeliveryKind;- readonly userId: string;- readonly deviceId: string;- readonly token: string;- readonly bundleId?: string | null | undefined;- readonly apsEnvironment?: "sandbox" | "production" | null | undefined;- readonly aggregate: ApnsDeliveryJobPayload["aggregate"];- readonly notification?: ApnsNotificationPayload | null;- readonly alert?: ApnsLiveActivityAlert | null | undefined;- readonly createdAt: string;- readonly expiresAt: string;- readonly jobId: string;-}): ApnsDeliveryJobPayload {- return {- version: 1,- jobId: input.jobId,- kind: input.kind,- target: {- userId: input.userId,- deviceId: input.deviceId,- token: input.token,- ...(input.bundleId ? { bundleId: input.bundleId } : {}),- ...(input.apsEnvironment ? { apsEnvironment: input.apsEnvironment } : {}),- },- aggregate: input.aggregate,- notification: input.notification ?? null,- // Omitted (not null) when absent so signatures stay identical to jobs from- // relay builds that predate the field.- ...(input.alert ? { alert: input.alert } : {}),- createdAt: input.createdAt,- expiresAt: input.expiresAt,- };-}--export function expiresAtForJob(createdAtMs: number): string {- return DateTime.formatIso(Option.getOrThrow(DateTime.make(createdAtMs + MAX_JOB_AGE_MS)));-}--function validatePayloadShape(payload: ApnsDeliveryJobPayload): ApnsDeliveryJobInvalid | null {- switch (payload.kind) {- case "live_activity_start":- case "live_activity_update":- if (payload.aggregate === null) {- return new ApnsDeliveryJobLiveActivityAggregateMissing({- jobId: payload.jobId,- kind: payload.kind,- userId: payload.target.userId,- deviceId: payload.target.deviceId,- });- }- if (payload.notification !== null) {- return new ApnsDeliveryJobLiveActivityNotificationUnexpected({- jobId: payload.jobId,- kind: payload.kind,- userId: payload.target.userId,- deviceId: payload.target.deviceId,- });- }- return null;- case "live_activity_end":- if (payload.notification !== null) {- return new ApnsDeliveryJobLiveActivityNotificationUnexpected({- jobId: payload.jobId,- kind: payload.kind,- userId: payload.target.userId,- deviceId: payload.target.deviceId,- });- }- return null;- case "push_notification":- if (payload.notification === null) {- return new ApnsDeliveryJobPushNotificationMissing({- jobId: payload.jobId,- userId: payload.target.userId,- deviceId: payload.target.deviceId,- });- }- if (payload.aggregate !== null) {- return new ApnsDeliveryJobPushNotificationAggregateUnexpected({- jobId: payload.jobId,- userId: payload.target.userId,- deviceId: payload.target.deviceId,- });- }- return null;- }-}--function signatureForPayload(input: {- readonly secret: Redacted.Redacted<string>;- readonly payload: ApnsDeliveryJobPayload;-}): string {- return NodeCrypto.createHmac("sha256", Redacted.value(input.secret))- .update(stableStringify(input.payload))- .digest("base64url");-}--function timingSafeEqualBase64Url(left: string, right: string): boolean {- const leftBuffer = Buffer.from(left, "base64url");- const rightBuffer = Buffer.from(right, "base64url");- if (leftBuffer.length !== rightBuffer.length) {- return false;- }- return NodeCrypto.timingSafeEqual(leftBuffer, rightBuffer);-}--export function signApnsDeliveryJob(input: {- readonly secret: Redacted.Redacted<string>;- readonly payload: ApnsDeliveryJobPayload;-}): SignedApnsDeliveryJob {- return {- algorithm: APNS_DELIVERY_JOB_SIGNING_ALGORITHM,- payload: input.payload,- signature: signatureForPayload(input),- };-}--export function verifySignedApnsDeliveryJob(input: {- readonly secret: Redacted.Redacted<string>;- readonly job: SignedApnsDeliveryJob;- readonly nowMs: number;-}): ApnsDeliveryJobPayload | ApnsDeliveryJobVerificationError {- const payload = input.job.payload;- const invalidPayload = validatePayloadShape(payload);- if (invalidPayload !== null) {- return invalidPayload;- }- const createdAt = DateTime.make(payload.createdAt);- if (Option.isNone(createdAt)) {- return new ApnsDeliveryJobCreatedAtInvalid({- jobId: payload.jobId,- kind: payload.kind,- userId: payload.target.userId,- deviceId: payload.target.deviceId,- createdAt: payload.createdAt,- });- }- const expiresAt = DateTime.make(payload.expiresAt);- if (Option.isNone(expiresAt)) {- return new ApnsDeliveryJobExpiresAtInvalid({- jobId: payload.jobId,- kind: payload.kind,- userId: payload.target.userId,- deviceId: payload.target.deviceId,- expiresAt: payload.expiresAt,- });- }- const createdAtMs = createdAt.value.epochMilliseconds;- const expiresAtMs = expiresAt.value.epochMilliseconds;- if (expiresAtMs <= createdAtMs) {- return new ApnsDeliveryJobTimeWindowInvalid({- jobId: payload.jobId,- kind: payload.kind,- userId: payload.target.userId,- deviceId: payload.target.deviceId,- createdAt: payload.createdAt,- expiresAt: payload.expiresAt,- });- }- if (expiresAtMs - createdAtMs > MAX_JOB_AGE_MS) {- return new ApnsDeliveryJobTimeWindowTooLong({- jobId: payload.jobId,- kind: payload.kind,- userId: payload.target.userId,- deviceId: payload.target.deviceId,- createdAt: payload.createdAt,- expiresAt: payload.expiresAt,- });- }- if (expiresAtMs <= input.nowMs) {- return new ApnsDeliveryJobExpired({- jobId: payload.jobId,- kind: payload.kind,- userId: payload.target.userId,- deviceId: payload.target.deviceId,- expiresAt: payload.expiresAt,- });- }- const expected = signatureForPayload({- secret: input.secret,- payload,- });- if (!timingSafeEqualBase64Url(input.job.signature, expected)) {- return new ApnsDeliveryJobSignatureInvalid({- jobId: payload.jobId,- kind: payload.kind,- userId: payload.target.userId,- deviceId: payload.target.deviceId,- });- }- return payload;-}diff --git a/infra/relay/src/agentActivity/apnsJwt.ts b/infra/relay/src/agentActivity/apnsJwt.tsdeleted file mode 100644index 74c3d15ce..000000000--- a/infra/relay/src/agentActivity/apnsJwt.ts+++ /dev/null@@ -1,160 +0,0 @@-import * as NodeCrypto from "node:crypto";--import { p256 } from "@noble/curves/nist";-import { sha256 } from "@noble/hashes/sha2";-import * as Effect from "effect/Effect";-import * as Encoding from "effect/Encoding";-import * as Redacted from "effect/Redacted";-import * as Result from "effect/Result";-import * as Schema from "effect/Schema";--import type { ApnsCredentials } from "../Config.ts";--export class ApnsJwtEncodingError extends Schema.TaggedErrorClass<ApnsJwtEncodingError>()(- "ApnsJwtEncodingError",- {- component: Schema.Literals(["header", "payload"]),- teamId: Schema.String,- keyId: Schema.String,- issuedAtUnixSeconds: Schema.Number,- cause: Schema.Defect(),- },-) {- override get message(): string {- return `Failed to encode APNs JWT ${this.component} for key ${this.keyId}.`;- }-}--export class ApnsJwtSigningError extends Schema.TaggedErrorClass<ApnsJwtSigningError>()(- "ApnsJwtSigningError",- {- teamId: Schema.String,- keyId: Schema.String,- issuedAtUnixSeconds: Schema.Number,- cause: Schema.Defect(),- },-) {- override get message(): string {- return `Failed to sign APNs JWT for key ${this.keyId}.`;- }-}--export type ApnsJwtError = ApnsJwtEncodingError | ApnsJwtSigningError;--const encodeApnsJwtHeaderJson = Schema.encodeEffect(- Schema.fromJsonString(- Schema.Struct({- alg: Schema.Literal("ES256"),- kid: Schema.String,- }),- ),-);-const encodeApnsJwtPayloadJson = Schema.encodeEffect(- Schema.fromJsonString(- Schema.Struct({- iss: Schema.String,- iat: Schema.Number,- }),- ),-);--export interface ApnsJwtSigningInput {- readonly teamId: ApnsCredentials["teamId"];- readonly keyId: ApnsCredentials["keyId"];- readonly privateKey: ApnsCredentials["privateKey"];- readonly issuedAtUnixSeconds: number;-}--export const makeApnsJwt = Effect.fn("relay.apns.make_jwt")(function* (input: ApnsJwtSigningInput) {- const headerJson = yield* encodeApnsJwtHeaderJson({ alg: "ES256", kid: input.keyId }).pipe(- Effect.mapError(- (cause) =>- new ApnsJwtEncodingError({- component: "header",- teamId: input.teamId,- keyId: input.keyId,- issuedAtUnixSeconds: input.issuedAtUnixSeconds,- cause,- }),- ),- );- const payloadJson = yield* encodeApnsJwtPayloadJson({- iss: input.teamId,- iat: input.issuedAtUnixSeconds,- }).pipe(- Effect.mapError(- (cause) =>- new ApnsJwtEncodingError({- component: "payload",- teamId: input.teamId,- keyId: input.keyId,- issuedAtUnixSeconds: input.issuedAtUnixSeconds,- cause,- }),- ),- );-- const privateKey = Redacted.value(input.privateKey);- const header = Encoding.encodeBase64Url(headerJson);- const payload = Encoding.encodeBase64Url(payloadJson);- const signingInput = `${header}.${payload}`;-- return yield* Effect.try({- try: () => {- // Deterministic ES256 (RFC 6979 via noble) instead of node's randomized- // signer: identical (key, iat) yields the byte-identical JWT on every- // worker isolate, so the fleet presents one stable provider token to- // APNs without any shared storage. Node crypto only converts the PEM to- // the raw scalar noble signs with.- const scalar = apnsSigningScalar(privateKey);- const signature = p256- .sign(sha256(new TextEncoder().encode(signingInput)), scalar, { prehash: false })- .toCompactRawBytes();- return `${signingInput}.${Encoding.encodeBase64Url(signature)}`;- },- catch: (cause) =>- new ApnsJwtSigningError({- teamId: input.teamId,- keyId: input.keyId,- issuedAtUnixSeconds: input.issuedAtUnixSeconds,- cause,- }),- });-});--// PEM parsing is pure and the key set is static per deployment; memoize the-// extracted P-256 scalar so signing never re-parses the PKCS8 document.-const signingScalarCache = new Map<string, Uint8Array>();--function apnsSigningScalar(privateKeyPem: string): Uint8Array {- const cached = signingScalarCache.get(privateKeyPem);- if (cached) {- return cached;- }- const jwk = NodeCrypto.createPrivateKey(privateKeyPem.replace(/\\n/g, "\n")).export({- format: "jwk",- });- if (jwk.crv !== "P-256" || typeof jwk.d !== "string") {- throw new Error("APNs signing key is not a P-256 private key.");- }- const scalar = Result.getOrThrowWith(- Encoding.decodeBase64Url(jwk.d),- () => new Error("APNs signing key scalar is not valid base64url."),- );- signingScalarCache.set(privateKeyPem, scalar);- return scalar;-}--// Fingerprint the key material so rotated credentials never reuse a JWT-// signed by the previous key.-export function apnsProviderTokenCacheKey(input: {- readonly teamId: string;- readonly keyId: string;- readonly privateKey: ApnsCredentials["privateKey"];-}): string {- const keyFingerprint = NodeCrypto.createHash("sha256")- .update(Redacted.value(input.privateKey))- .digest("hex")- .slice(0, 16);- return `${input.teamId}:${input.keyId}:${keyFingerprint}`;-}diff --git a/infra/relay/src/auth/DpopProofs.test.ts b/infra/relay/src/auth/DpopProofs.test.tsdeleted file mode 100644index fba64586e..000000000--- a/infra/relay/src/auth/DpopProofs.test.ts+++ /dev/null@@ -1,125 +0,0 @@-import { describe, expect, it } from "@effect/vitest";-import * as DateTime from "effect/DateTime";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";-import * as Option from "effect/Option";--import * as RelayDb from "../db.ts";-import { relayDpopProofs } from "../persistence/schema.ts";-import * as DpopProofs from "./DpopProofs.ts";--describe("DpopProofReplay", () => {- it.effect("consumes proof ids without pruning expired rows on the request path", () => {- const calls: Array<string> = [];- const insertedValues: Array<{- readonly thumbprint: string;- readonly jti: string;- readonly iat: number;- readonly expiresAt: string;- readonly createdAt: string;- }> = [];- const fakeDb = {- insert: (table: unknown) => {- expect(table).toBe(relayDpopProofs);- calls.push("insert");- return {- values: (values: (typeof insertedValues)[number]) => {- insertedValues.push(values);- calls.push("insert.values");- return {- onConflictDoNothing: () => {- calls.push("insert.onConflictDoNothing");- return {- returning: (selection: unknown) => {- expect(selection).toBeDefined();- calls.push("insert.returning");- return Effect.succeed([{ jti: values.jti }]);- },- };- },- };- },- };- },- } as unknown as RelayDb.RelayDb["Service"];-- return Effect.gen(function* () {- const replay = yield* DpopProofs.DpopProofReplay;- const consumed = yield* replay.consume({- thumbprint: "thumbprint",- jti: "jti",- iat: 1_771_000_000,- expiresAt: Option.getOrThrow(DateTime.make("2026-05-25T12:00:00.000Z")),- });-- expect(consumed).toBe(true);- expect(calls).toEqual([- "insert",- "insert.values",- "insert.onConflictDoNothing",- "insert.returning",- ]);- expect(insertedValues).toMatchObject([- {- thumbprint: "thumbprint",- jti: "jti",- iat: 1_771_000_000,- expiresAt: "2026-05-25T12:00:00.000Z",- },- ]);- }).pipe(- Effect.provide(DpopProofs.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb)))),- );- });-- it.effect("prunes expired proof rows from the maintenance path", () => {- const calls: Array<string> = [];- const fakeDb = {- delete: (table: unknown) => {- expect(table).toBe(relayDpopProofs);- calls.push("delete");- return {- where: (condition: unknown) => {- expect(condition).toBeDefined();- calls.push("delete.where");- return Effect.void;- },- };- },- } as unknown as RelayDb.RelayDb["Service"];-- return Effect.gen(function* () {- const replay = yield* DpopProofs.DpopProofReplay;- yield* replay.pruneExpired;- expect(calls).toEqual(["delete", "delete.where"]);- }).pipe(- Effect.provide(DpopProofs.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb)))),- );- });-- it.effect("retains the prune cutoff and database failure", () => {- const cause = new Error("database unavailable");- const fakeDb = {- delete: (table: unknown) => {- expect(table).toBe(relayDpopProofs);- return {- where: () => Effect.fail(cause),- };- },- } as unknown as RelayDb.RelayDb["Service"];-- return Effect.gen(function* () {- const replay = yield* DpopProofs.DpopProofReplay;- const error = yield* Effect.flip(replay.pruneExpired);-- expect(error).toMatchObject({- _tag: "DpopProofReplayPersistenceError",- operation: "prune-expired",- });- expect(Date.parse(error.expiresBefore ?? "")).not.toBeNaN();- expect(error.cause).toBe(cause);- }).pipe(- Effect.provide(DpopProofs.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb)))),- );- });-});diff --git a/infra/relay/src/auth/DpopProofs.ts b/infra/relay/src/auth/DpopProofs.tsdeleted file mode 100644index fa784eb63..000000000--- a/infra/relay/src/auth/DpopProofs.ts+++ /dev/null@@ -1,155 +0,0 @@-import * as Context from "effect/Context";-import * as DateTime from "effect/DateTime";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";-import * as Schema from "effect/Schema";-import * as HttpApiError from "effect/unstable/httpapi/HttpApiError";-import { lt } from "drizzle-orm";--import { verifyDpopProof } from "@t3tools/shared/dpop";-import * as RelayDb from "../db.ts";-import { relayDpopProofs } from "../persistence/schema.ts";--export class DpopProofReplayPersistenceError extends Schema.TaggedErrorClass<DpopProofReplayPersistenceError>()(- "DpopProofReplayPersistenceError",- {- operation: Schema.Literals(["consume", "prune-expired"]),- thumbprint: Schema.optionalKey(Schema.String),- jti: Schema.optionalKey(Schema.String),- iat: Schema.optionalKey(Schema.Number),- expiresBefore: Schema.optionalKey(Schema.String),- cause: Schema.Defect(),- },-) {- override get message(): string {- return `Failed to persist DPoP proof replay state during '${this.operation}'`;- }-}--export class DpopProofReplay extends Context.Service<- DpopProofReplay,- {- readonly verifyAndConsume: (input: {- readonly proof: string | undefined;- readonly method: string;- readonly url: string;- readonly expectedThumbprint?: string;- readonly expectedAccessToken?: string;- readonly now: DateTime.DateTime;- }) => Effect.Effect<string, HttpApiError.Unauthorized | DpopProofReplayPersistenceError>;- readonly consume: (input: {- readonly thumbprint: string;- readonly jti: string;- readonly iat: number;- readonly expiresAt: DateTime.DateTime;- }) => Effect.Effect<boolean, DpopProofReplayPersistenceError>;- readonly pruneExpired: Effect.Effect<void, DpopProofReplayPersistenceError>;- }->()("t3code-relay/auth/DpopProofs/DpopProofReplay") {}--const make = Effect.gen(function* () {- const db = yield* RelayDb.RelayDb;-- const consume: DpopProofReplay["Service"]["consume"] = Effect.fn("relay.dpop_proofs.consume")(- function* (input) {- const createdAt = DateTime.formatIso(yield* DateTime.now);- const inserted = yield* db- .insert(relayDpopProofs)- .values({- thumbprint: input.thumbprint,- jti: input.jti,- iat: input.iat,- expiresAt: DateTime.formatIso(input.expiresAt),- createdAt,- })- .onConflictDoNothing()- .returning({ jti: relayDpopProofs.jti })- .pipe(- Effect.mapError(- (cause) =>- new DpopProofReplayPersistenceError({- operation: "consume",- thumbprint: input.thumbprint,- jti: input.jti,- iat: input.iat,- cause,- }),- ),- );- return inserted.length > 0;- },- );-- const verifyAndConsume: DpopProofReplay["Service"]["verifyAndConsume"] = Effect.fn(- "relay.dpop_proofs.verify_and_consume",- )(function* (input) {- yield* Effect.annotateCurrentSpan({- "relay.dpop.method": input.method,- "relay.dpop.expected_thumbprint_present": input.expectedThumbprint !== undefined,- "relay.dpop.expected_access_token_present": input.expectedAccessToken !== undefined,- });- const result = verifyDpopProof({- proof: input.proof,- method: input.method,- url: input.url,- nowEpochSeconds: Math.floor(input.now.epochMilliseconds / 1_000),- ...(input.expectedThumbprint ? { expectedThumbprint: input.expectedThumbprint } : {}),- ...(input.expectedAccessToken ? { expectedAccessToken: input.expectedAccessToken } : {}),- });- if (!result.ok) {- yield* Effect.logWarning("relay dpop proof rejected", {- reason: result.reason,- method: input.method,- url: input.url,- expectedThumbprintPresent: input.expectedThumbprint !== undefined,- expectedAccessTokenPresent: input.expectedAccessToken !== undefined,- });- return yield* new HttpApiError.Unauthorized({});- }- const consumed = yield* consume({- thumbprint: result.thumbprint,- jti: result.jti,- iat: result.iat,- expiresAt: DateTime.add(input.now, { minutes: 5 }),- });- if (!consumed) {- yield* Effect.logWarning("relay dpop proof replay rejected", {- thumbprint: result.thumbprint,- jti: result.jti,- iat: result.iat,- });- return yield* new HttpApiError.Unauthorized({});- }- yield* Effect.annotateCurrentSpan({- "relay.dpop.thumbprint": result.thumbprint,- "relay.dpop.iat": result.iat,- });- return result.thumbprint;- });-- const pruneExpired: DpopProofReplay["Service"]["pruneExpired"] = Effect.gen(function* () {- const now = DateTime.formatIso(yield* DateTime.now);- yield* Effect.annotateCurrentSpan({ "relay.dpop_prune.before": now });- yield* db- .delete(relayDpopProofs)- .where(lt(relayDpopProofs.expiresAt, now))- .pipe(- Effect.mapError(- (cause) =>- new DpopProofReplayPersistenceError({- operation: "prune-expired",- expiresBefore: now,- cause,- }),- ),- );- }).pipe(Effect.withSpan("relay.dpop_proofs.prune_expired"));-- return DpopProofReplay.of({- verifyAndConsume,- consume,- pruneExpired,- });-});--export const layer = Layer.effect(DpopProofReplay, make);diff --git a/infra/relay/src/auth/DpopProofs.verifyAndConsume.test.ts b/infra/relay/src/auth/DpopProofs.verifyAndConsume.test.tsdeleted file mode 100644index 7663e8748..000000000--- a/infra/relay/src/auth/DpopProofs.verifyAndConsume.test.ts+++ /dev/null@@ -1,225 +0,0 @@-import * as NodeCrypto from "node:crypto";--import { describe, expect, it } from "@effect/vitest";-import {- computeDpopAccessTokenHash,- computeDpopJwkThumbprint,- type DpopPublicJwk,-} from "@t3tools/shared/dpop";-import * as DateTime from "effect/DateTime";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";--import * as RelayDb from "../db.ts";-import { relayDpopProofs } from "../persistence/schema.ts";-import * as DpopProofs from "./DpopProofs.ts";--interface DpopProofInsertValues {- readonly thumbprint: string;- readonly jti: string;- readonly iat: number;- readonly expiresAt: string;- readonly createdAt: string;-}--function makeDpopProof(input: {- readonly method: string;- readonly url: string;- readonly iat: number;- readonly jti: string;- readonly accessToken?: string;-}) {- const { privateKey, publicKey } = NodeCrypto.generateKeyPairSync("ec", {- namedCurve: "P-256",- });- const publicJwk = publicKey.export({ format: "jwk" }) as DpopPublicJwk;- const header = Buffer.from(- JSON.stringify({- typ: "dpop+jwt",- alg: "ES256",- jwk: publicJwk,- }),- ).toString("base64url");- const payload = Buffer.from(- JSON.stringify({- htm: input.method,- htu: input.url,- jti: input.jti,- iat: input.iat,- ...(input.accessToken ? { ath: computeDpopAccessTokenHash(input.accessToken) } : {}),- }),- ).toString("base64url");- const signature = NodeCrypto.sign("sha256", Buffer.from(`${header}.${payload}`), {- key: privateKey,- dsaEncoding: "ieee-p1363",- }).toString("base64url");- return {- proof: `${header}.${payload}.${signature}`,- thumbprint: computeDpopJwkThumbprint(publicJwk),- };-}--function layer(- insert: (- values: DpopProofInsertValues,- ) => Effect.Effect<ReadonlyArray<{ readonly jti: string }>, { _tag: string }>,-) {- const fakeDb = {- insert: (table: unknown) => {- expect(table).toBe(relayDpopProofs);- return {- values: (values: DpopProofInsertValues) => ({- onConflictDoNothing: () => ({- returning: (selection: unknown) => {- expect(selection).toBeDefined();- return insert(values);- },- }),- }),- };- },- } as unknown as RelayDb.RelayDb["Service"];- return DpopProofs.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb)));-}--function consumeEachProofOnce() {- const consumed = new Set<string>();- return (values: DpopProofInsertValues) =>- Effect.sync(() => {- const key = `${values.thumbprint}:${values.jti}`;- if (consumed.has(key)) {- return [];- }- consumed.add(key);- return [{ jti: values.jti }];- });-}--describe("DpopProofReplay.verifyAndConsume", () => {- it.effect("rejects replayed proofs after persistence consumes the jti once", () => {- const now = DateTime.makeUnsafe("2026-05-25T12:00:00.000Z");- const proof = makeDpopProof({- method: "POST",- url: "https://relay.example.com/v1/environments/env/connect",- iat: Math.floor(now.epochMilliseconds / 1_000),- jti: "proof-1",- });-- return Effect.gen(function* () {- const replay = yield* DpopProofs.DpopProofReplay;- const first = yield* replay.verifyAndConsume({- proof: proof.proof,- method: "POST",- url: "https://relay.example.com/v1/environments/env/connect",- expectedThumbprint: proof.thumbprint,- now,- });- const second = yield* Effect.exit(- replay.verifyAndConsume({- proof: proof.proof,- method: "POST",- url: "https://relay.example.com/v1/environments/env/connect",- expectedThumbprint: proof.thumbprint,- now,- }),- );-- expect(first).toBe(proof.thumbprint);- expect(second._tag).toBe("Failure");- }).pipe(Effect.provide(layer(consumeEachProofOnce())));- });-- it.effect("rejects proofs missing the expected access token hash", () => {- const now = DateTime.makeUnsafe("2026-05-25T12:00:00.000Z");- const proof = makeDpopProof({- method: "POST",- url: "https://relay.example.com/v1/environments/env/connect",- iat: Math.floor(now.epochMilliseconds / 1_000),- jti: "proof-1",- });-- return Effect.gen(function* () {- const replay = yield* DpopProofs.DpopProofReplay;- const result = yield* Effect.exit(- replay.verifyAndConsume({- proof: proof.proof,- method: "POST",- url: "https://relay.example.com/v1/environments/env/connect",- expectedThumbprint: proof.thumbprint,- expectedAccessToken: "clerk-access-token",- now,- }),- );-- expect(result._tag).toBe("Failure");- }).pipe(Effect.provide(layer(() => Effect.die("unexpected DPoP replay persistence"))));- });-- it.effect("preserves replay persistence failures", () => {- const now = DateTime.makeUnsafe("2026-05-25T12:00:00.000Z");- const proof = makeDpopProof({- method: "POST",- url: "https://relay.example.com/v1/environments/env/connect",- iat: Math.floor(now.epochMilliseconds / 1_000),- jti: "proof-persistence-failure",- });- const cause = { _tag: "DatabaseUnavailable" } as const;-- return Effect.gen(function* () {- const replay = yield* DpopProofs.DpopProofReplay;- const error = yield* Effect.flip(- replay.verifyAndConsume({- proof: proof.proof,- method: "POST",- url: "https://relay.example.com/v1/environments/env/connect",- expectedThumbprint: proof.thumbprint,- now,- }),- );-- expect(error).toMatchObject({- _tag: "DpopProofReplayPersistenceError",- operation: "consume",- thumbprint: proof.thumbprint,- jti: "proof-persistence-failure",- iat: Math.floor(now.epochMilliseconds / 1_000),- });- expect(error.cause).toBe(cause);- expect(error).not.toHaveProperty("proof");- }).pipe(Effect.provide(layer(() => Effect.fail(cause))));- });-- it.effect("accepts proofs bound to the access token hash", () => {- const now = DateTime.makeUnsafe("2026-05-25T12:00:00.000Z");- const proof = makeDpopProof({- method: "POST",- url: "https://relay.example.com/v1/environments/env/status",- iat: Math.floor(now.epochMilliseconds / 1_000),- jti: "proof-status-1",- accessToken: "clerk-access-token",- });-- return Effect.gen(function* () {- const replay = yield* DpopProofs.DpopProofReplay;- const thumbprint = yield* replay.verifyAndConsume({- proof: proof.proof,- method: "POST",- url: "https://relay.example.com/v1/environments/env/status",- expectedAccessToken: "clerk-access-token",- now,- });- const second = yield* Effect.exit(- replay.verifyAndConsume({- proof: proof.proof,- method: "POST",- url: "https://relay.example.com/v1/environments/env/status",- expectedAccessToken: "clerk-access-token",- now,- }),- );-- expect(thumbprint).toBe(proof.thumbprint);- expect(second._tag).toBe("Failure");- }).pipe(Effect.provide(layer(consumeEachProofOnce())));- });-});diff --git a/infra/relay/src/auth/RelayTokens.test.ts b/infra/relay/src/auth/RelayTokens.test.tsdeleted file mode 100644index c4a65771e..000000000--- a/infra/relay/src/auth/RelayTokens.test.ts+++ /dev/null@@ -1,188 +0,0 @@-import * as NodeCrypto from "node:crypto";--import { describe, expect, it } from "@effect/vitest";-import { signRelayJwt } from "@t3tools/shared/relayJwt";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";-import * as Redacted from "effect/Redacted";--import * as RelayConfiguration from "../Config.ts";-import * as RelayTokens from "./RelayTokens.ts";--const keyPair = NodeCrypto.generateKeyPairSync("ed25519", {- privateKeyEncoding: { format: "pem", type: "pkcs8" },- publicKeyEncoding: { format: "pem", type: "spki" },-});--const config = RelayConfiguration.RelayConfiguration.of({- relayIssuer: "https://relay.example.test/",- apns: {- environment: "sandbox",- teamId: "team-id",- keyId: "key-id",- privateKey: Redacted.make("private-key"),- bundleId: "com.t3tools.t3code.dev",- },- apnsDeliveryJobSigningSecret: Redacted.make("job-secret"),- clerkSecretKey: Redacted.make("clerk-secret"),- clerkPublishableKey: "pk_test_test",- clerkJwtAudience: "t3-code-relay",- cloudMintPrivateKey: Redacted.make(keyPair.privateKey),- cloudMintPublicKey: keyPair.publicKey,- managedEndpointBaseDomain: undefined,- managedEndpointNamespace: undefined,-});--const layer = RelayTokens.layer.pipe(Layer.provide(RelayConfiguration.layer(config)));--describe("RelayTokens", () => {- it.effect("issues a user-bound environment link challenge", () =>- Effect.gen(function* () {- const relayTokens = yield* RelayTokens.RelayTokens;- const token = yield* relayTokens.issueLinkChallenge({- userId: "user_123",- request: {- notificationsEnabled: true,- liveActivitiesEnabled: true,- managedTunnelsEnabled: true,- },- jti: "challenge-1",- issuedAtEpochSeconds: 100,- expiresAtEpochSeconds: 200,- });-- expect(- yield* relayTokens.verifyLinkChallenge({- token,- userId: "user_123",- request: {- notificationsEnabled: true,- liveActivitiesEnabled: true,- managedTunnelsEnabled: true,- },- nowEpochSeconds: 150,- }),- ).toMatchObject({ sub: "user_123", jti: "challenge-1" });- expect(- yield* relayTokens.verifyLinkChallenge({- token,- userId: "attacker",- request: {- notificationsEnabled: true,- liveActivitiesEnabled: true,- managedTunnelsEnabled: true,- },- nowEpochSeconds: 150,- }),- ).toBeNull();- }).pipe(Effect.provide(layer)),- );-- it.effect("issues and verifies DPoP access tokens bound to one proof-key thumbprint", () =>- Effect.gen(function* () {- const relayTokens = yield* RelayTokens.RelayTokens;- const token = yield* relayTokens.issueDpopAccessToken({- userId: "user_123",- proofKeyThumbprint: "proof-key-thumbprint",- jti: "access-token-1",- issuedAtEpochSeconds: 100,- expiresAtEpochSeconds: 1_900,- clientId: "t3-mobile",- scopes: ["environment:connect", "environment:status", "mobile:registration"],- });-- expect(- yield* relayTokens.verifyDpopAccessToken({ token, nowEpochSeconds: 700 }),- ).toMatchObject({- sub: "user_123",- cnf: { jkt: "proof-key-thumbprint" },- client_id: "t3-mobile",- scope: ["environment:connect", "environment:status", "mobile:registration"],- });- expect(- yield* relayTokens.verifyDpopAccessToken({ token, nowEpochSeconds: 1_961 }),- ).toBeNull();- }).pipe(Effect.provide(layer)),- );-- it.effect("issues tunnel-only DPoP access tokens to web public clients", () =>- Effect.gen(function* () {- const relayTokens = yield* RelayTokens.RelayTokens;- const token = yield* relayTokens.issueDpopAccessToken({- userId: "user_123",- proofKeyThumbprint: "web-proof-key-thumbprint",- jti: "web-access-token-1",- issuedAtEpochSeconds: 100,- expiresAtEpochSeconds: 200,- clientId: "t3-web",- scopes: ["environment:connect", "environment:status"],- });-- expect(- yield* relayTokens.verifyDpopAccessToken({ token, nowEpochSeconds: 150 }),- ).toMatchObject({- client_id: "t3-web",- scope: ["environment:connect", "environment:status"],- cnf: { jkt: "web-proof-key-thumbprint" },- });- }).pipe(Effect.provide(layer)),- );-- it.effect("treats requested scope as an order-independent set", () =>- Effect.gen(function* () {- const relayTokens = yield* RelayTokens.RelayTokens;- expect(- relayTokens.resolveDpopAccessTokenScopes({- clientId: "t3-mobile",- scope: "environment:status environment:connect environment:status",- }),- ).toEqual(["environment:status", "environment:connect"]);- }).pipe(Effect.provide(layer)),- );-- it.effect("rejects signed DPoP tokens whose scope is outside the relay policy", () =>- Effect.gen(function* () {- const relayTokens = yield* RelayTokens.RelayTokens;- const token = yield* signRelayJwt({- privateKey: keyPair.privateKey,- typ: "t3-relay-dpop-access+jwt",- payload: {- iss: "https://relay.example.test",- aud: "https://relay.example.test",- sub: "user_123",- jti: "access-token-invalid-scope",- iat: 100,- exp: 200,- client_id: "t3-mobile",- scope: "environment:admin",- cnf: { jkt: "proof-key-thumbprint" },- },- });-- expect(yield* relayTokens.verifyDpopAccessToken({ token, nowEpochSeconds: 150 })).toBeNull();- }).pipe(Effect.provide(layer)),- );-- it.effect("rejects mobile registration scope on a web public client token", () =>- Effect.gen(function* () {- const relayTokens = yield* RelayTokens.RelayTokens;- const token = yield* signRelayJwt({- privateKey: keyPair.privateKey,- typ: "t3-relay-dpop-access+jwt",- payload: {- iss: "https://relay.example.test",- aud: "https://relay.example.test",- sub: "user_123",- jti: "web-token-invalid-mobile-scope",- iat: 100,- exp: 200,- client_id: "t3-web",- scope: "environment:connect mobile:registration",- cnf: { jkt: "proof-key-thumbprint" },- },- });-- expect(yield* relayTokens.verifyDpopAccessToken({ token, nowEpochSeconds: 150 })).toBeNull();- }).pipe(Effect.provide(layer)),- );-});diff --git a/infra/relay/src/auth/RelayTokens.ts b/infra/relay/src/auth/RelayTokens.tsdeleted file mode 100644index bf4898090..000000000--- a/infra/relay/src/auth/RelayTokens.ts+++ /dev/null@@ -1,227 +0,0 @@-import {- RelayDpopAccessTokenScope,- RelayEnvironmentConnectScope,- RelayEnvironmentStatusScope,- RelayMobileClientId,- RelayMobileRegistrationScope,- RelayWebClientId,- type RelayPublicClientId,- type RelayEnvironmentLinkChallengeRequest,-} from "@t3tools/contracts/relay";-import { encodeOAuthScope, parseAllowedOAuthScope } from "@t3tools/shared/oauthScope";-import {- normalizeRelayIssuer,- RelayJwtError,- signRelayJwt,- verifyRelayJwt,-} from "@t3tools/shared/relayJwt";-import * as Context from "effect/Context";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";-import * as Redacted from "effect/Redacted";-import * as Schema from "effect/Schema";--import * as RelayConfiguration from "../Config.ts";--const LINK_CHALLENGE_TYP = "t3-link-challenge+jwt";-const ACCESS_TOKEN_TYP = "t3-relay-dpop-access+jwt";-const LINK_CHALLENGE_KIND = "environment_link_challenge";-export const RELAY_DPOP_ACCESS_TOKEN_TTL = "30 minutes";--const LinkChallengeClaims = Schema.Struct({- kind: Schema.Literal(LINK_CHALLENGE_KIND),- iss: Schema.String,- aud: Schema.String,- sub: Schema.String,- jti: Schema.String,- iat: Schema.Int,- exp: Schema.Int,- notificationsEnabled: Schema.Boolean,- liveActivitiesEnabled: Schema.Boolean,- managedTunnelsEnabled: Schema.Boolean,-});-export type LinkChallengeClaims = typeof LinkChallengeClaims.Type;--const RelayDpopAccessTokenClaims = Schema.Struct({- iss: Schema.String,- aud: Schema.String,- sub: Schema.String,- jti: Schema.String,- iat: Schema.Int,- exp: Schema.Int,- client_id: Schema.Literals([RelayMobileClientId, RelayWebClientId]),- scope: Schema.String,- cnf: Schema.Struct({ jkt: Schema.String }),-});-export type RelayDpopAccessTokenClaims = Omit<typeof RelayDpopAccessTokenClaims.Type, "scope"> & {- readonly scope: ReadonlyArray<RelayDpopAccessTokenScope>;-};--const decodeLinkChallengeClaims = Schema.decodeUnknownEffect(LinkChallengeClaims);-const decodeDpopAccessTokenClaims = Schema.decodeUnknownEffect(RelayDpopAccessTokenClaims);--const allowedScopesByClientId: Record<- RelayPublicClientId,- ReadonlySet<RelayDpopAccessTokenScope>-> = {- [RelayMobileClientId]: new Set([- RelayEnvironmentConnectScope,- RelayEnvironmentStatusScope,- RelayMobileRegistrationScope,- ]),- [RelayWebClientId]: new Set([RelayEnvironmentConnectScope, RelayEnvironmentStatusScope]),-};--function resolveDpopAccessTokenScopes(input: {- readonly clientId: RelayPublicClientId;- readonly scope: string;-}): ReadonlyArray<RelayDpopAccessTokenScope> | null {- return parseAllowedOAuthScope({- value: input.scope,- allowedScopes: allowedScopesByClientId[input.clientId],- });-}--export class RelayTokens extends Context.Service<- RelayTokens,- {- readonly resolveDpopAccessTokenScopes: typeof resolveDpopAccessTokenScopes;- readonly issueLinkChallenge: (input: {- readonly userId: string;- readonly request: RelayEnvironmentLinkChallengeRequest;- readonly jti: string;- readonly issuedAtEpochSeconds: number;- readonly expiresAtEpochSeconds: number;- }) => Effect.Effect<string, RelayJwtError>;- readonly verifyLinkChallenge: (input: {- readonly token: string;- readonly userId: string;- readonly request: RelayEnvironmentLinkChallengeRequest;- readonly nowEpochSeconds: number;- }) => Effect.Effect<LinkChallengeClaims | null>;- readonly issueDpopAccessToken: (input: {- readonly userId: string;- readonly proofKeyThumbprint: string;- readonly jti: string;- readonly issuedAtEpochSeconds: number;- readonly expiresAtEpochSeconds: number;- readonly clientId: RelayPublicClientId;- readonly scopes: ReadonlyArray<RelayDpopAccessTokenScope>;- }) => Effect.Effect<string, RelayJwtError>;- readonly verifyDpopAccessToken: (input: {- readonly token: string;- readonly nowEpochSeconds: number;- }) => Effect.Effect<RelayDpopAccessTokenClaims | null>;- }->()("t3code-relay/auth/RelayTokens") {}--const make = Effect.gen(function* () {- const config = yield* RelayConfiguration.RelayConfiguration;- const issuer = normalizeRelayIssuer(config.relayIssuer);-- const issueLinkChallenge: RelayTokens["Service"]["issueLinkChallenge"] = Effect.fn(- "relay.tokens.issue_link_challenge",- )(function* (input) {- return yield* signRelayJwt({- privateKey: Redacted.value(config.cloudMintPrivateKey),- typ: LINK_CHALLENGE_TYP,- payload: {- kind: LINK_CHALLENGE_KIND,- iss: issuer,- aud: issuer,- sub: input.userId,- jti: input.jti,- iat: input.issuedAtEpochSeconds,- exp: input.expiresAtEpochSeconds,- ...input.request,- },- });- });-- const verifyLinkChallenge: RelayTokens["Service"]["verifyLinkChallenge"] = Effect.fn(- "relay.tokens.verify_link_challenge",- )((input) =>- verifyRelayJwt({- publicKey: config.cloudMintPublicKey,- token: input.token,- typ: LINK_CHALLENGE_TYP,- issuer,- audience: issuer,- nowEpochSeconds: input.nowEpochSeconds,- }).pipe(- Effect.flatMap(decodeLinkChallengeClaims),- Effect.map((claims) => {- if (- claims.sub !== input.userId ||- (input.request.notificationsEnabled && claims.notificationsEnabled !== true) ||- (input.request.liveActivitiesEnabled && claims.liveActivitiesEnabled !== true) ||- (input.request.managedTunnelsEnabled && claims.managedTunnelsEnabled !== true)- ) {- return null;- }- return claims;- }),- Effect.orElseSucceed(() => null),- ),- );-- const issueDpopAccessToken: RelayTokens["Service"]["issueDpopAccessToken"] = Effect.fn(- "relay.tokens.issue_dpop_access_token",- )(function* (input) {- return yield* signRelayJwt({- privateKey: Redacted.value(config.cloudMintPrivateKey),- typ: ACCESS_TOKEN_TYP,- payload: {- iss: issuer,- aud: issuer,- sub: input.userId,- jti: input.jti,- iat: input.issuedAtEpochSeconds,- exp: input.expiresAtEpochSeconds,- client_id: input.clientId,- scope: encodeOAuthScope(input.scopes),- cnf: { jkt: input.proofKeyThumbprint },- },- });- });-- const verifyDpopAccessToken: RelayTokens["Service"]["verifyDpopAccessToken"] = Effect.fn(- "relay.tokens.verify_dpop_access_token",- )((input) =>- verifyRelayJwt({- publicKey: config.cloudMintPublicKey,- token: input.token,- typ: ACCESS_TOKEN_TYP,- issuer,- audience: issuer,- nowEpochSeconds: input.nowEpochSeconds,- maxTokenAge: RELAY_DPOP_ACCESS_TOKEN_TTL,- }).pipe(- Effect.tapError((error) =>- Effect.annotateCurrentSpan(- "relay.tokens.verification_failure",- RelayJwtError.diagnosticCode(error),- ),- ),- Effect.flatMap(decodeDpopAccessTokenClaims),- Effect.map((claims): RelayDpopAccessTokenClaims | null => {- const scopes = resolveDpopAccessTokenScopes({- clientId: claims.client_id,- scope: claims.scope,- });- return scopes === null ? null : { ...claims, scope: scopes };- }),- Effect.orElseSucceed(() => null),- ),- );-- return RelayTokens.of({- resolveDpopAccessTokenScopes,- issueLinkChallenge,- verifyLinkChallenge,- issueDpopAccessToken,- verifyDpopAccessToken,- });-});--export const layer = Layer.effect(RelayTokens, make);diff --git a/infra/relay/src/db.ts b/infra/relay/src/db.tsdeleted file mode 100644index efb0df567..000000000--- a/infra/relay/src/db.ts+++ /dev/null@@ -1,87 +0,0 @@-import type { PgClient } from "@effect/sql-pg/PgClient";-import * as Cloudflare from "alchemy/Cloudflare";-import * as Drizzle from "alchemy/Drizzle";-import * as Planetscale from "alchemy/Planetscale";-import * as Alchemy from "alchemy";-import * as RemovalPolicy from "alchemy/RemovalPolicy";-import type { EffectPgDatabase } from "drizzle-orm/effect-postgres";-import * as Context from "effect/Context";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";--import { relayDatabaseMode } from "./dbConfig.ts";--export class RelayDb extends Context.Service<- RelayDb,- EffectPgDatabase & {- readonly $client: PgClient;- }->()("t3code-relay/db/RelayDb") {}--export class RelayTransactions extends Context.Service<- RelayTransactions,- {- readonly withTransaction: RelayDb["Service"]["$client"]["withTransaction"];- }->()("t3code-relay/db/RelayTransactions") {- static readonly layer = Layer.effect(- RelayTransactions,- Effect.gen(function* () {- const db = yield* RelayDb;- return RelayTransactions.of({- withTransaction: db.$client.withTransaction,- });- }),- );-}--export const PlanetscaleDatabase = Effect.gen(function* () {- const { stage } = yield* Alchemy.Stack;- const schema = yield* Drizzle.Schema("RelaySchema", {- schema: "./src/persistence/schema.ts",- out: "./migrations/postgres",- dialect: "postgres",- });-- const mode = relayDatabaseMode(stage);- const database =- mode === "shared-database"- ? yield* Planetscale.PostgresDatabase("RelayPostgresDatabase", {- name: "t3coderelay",- region: { slug: "us-west" },- clusterSize: "PS_20",- migrationsDir: schema.out,- migrationsTable: "relay_migrations",- replicas: 2,- }).pipe(RemovalPolicy.retain())- : yield* Planetscale.PostgresDatabase.ref("RelayPostgresDatabase", {- stage: "prod",- });- const branch =- mode === "stage-branch"- ? yield* Planetscale.PostgresBranch("RelayPostgresBranch", {- database,- migrationsDir: schema.out,- migrationsTable: "relay_migrations",- })- : undefined;-- const runtimeRole = yield* Planetscale.PostgresRole("RelayPostgresRuntimeRole", {- database,- ...(branch ? { branch } : {}),- inheritedRoles: ["pg_read_all_data", "pg_write_all_data"],- });-- return { branch, database, runtimeRole };-});--export const RelayHyperdrive = Effect.gen(function* () {- const { runtimeRole } = yield* PlanetscaleDatabase;- return yield* Cloudflare.Hyperdrive.Connection("RelayHyperdrive", {- origin: runtimeRole.origin,- caching: {- disabled: true,- },- originConnectionLimit: 20,- });-});diff --git a/infra/relay/src/dbConfig.test.ts b/infra/relay/src/dbConfig.test.tsdeleted file mode 100644index e97b29a74..000000000--- a/infra/relay/src/dbConfig.test.ts+++ /dev/null@@ -1,11 +0,0 @@-import { describe, expect, it } from "vite-plus/test";--import { relayDatabaseMode } from "./dbConfig.ts";--describe("relayDatabaseMode", () => {- it("uses the shared database only for production", () => {- expect(relayDatabaseMode("prod")).toBe("shared-database");- expect(relayDatabaseMode("dev_julius")).toBe("stage-branch");- expect(relayDatabaseMode("preview")).toBe("stage-branch");- });-});diff --git a/infra/relay/src/dbConfig.ts b/infra/relay/src/dbConfig.tsdeleted file mode 100644index 9f6416aed..000000000--- a/infra/relay/src/dbConfig.ts+++ /dev/null@@ -1,5 +0,0 @@-export type RelayDatabaseMode = "shared-database" | "stage-branch";--export function relayDatabaseMode(stage: string): RelayDatabaseMode {- return stage === "prod" ? "shared-database" : "stage-branch";-}diff --git a/infra/relay/src/deploymentConfig.test.ts b/infra/relay/src/deploymentConfig.test.tsdeleted file mode 100644index 44c7627a4..000000000--- a/infra/relay/src/deploymentConfig.test.ts+++ /dev/null@@ -1,123 +0,0 @@-import { describe, expect, it } from "vite-plus/test";-import * as Schema from "effect/Schema";--import {- managedEndpointDigestInput,- managedEndpointForHostname,- managedEndpointHostname,- isManagedEndpointHostname,- managedEndpointTunnelName,- relayOwnsManagedEndpointZone,- RelayPublicDomainLabelTooLongError,- relayPublicDomainForStage,- relayResourceNameForStage,- relayStageSlug,-} from "./deploymentConfig.ts";--const isRelayPublicDomainLabelTooLongError = Schema.is(RelayPublicDomainLabelTooLongError);--describe("relayStageSlug", () => {- it("matches Alchemy physical-name sanitization for default developer stages", () => {- expect(relayStageSlug("dev_julius")).toBe("dev-julius");- });-});--describe("relayPublicDomainForStage", () => {- it("uses the canonical relay hostname for production", () => {- expect(relayPublicDomainForStage("prod", ".example.com.")).toBe("relay.example.com");- });-- it("isolates personal stages below the imported zone", () => {- expect(relayPublicDomainForStage("dev_julius", "example.com")).toBe(- "relay-dev-julius.example.com",- );- });-- it("reports the stage and derived DNS label when the label is too long", () => {- const stage = `dev_${"x".repeat(60)}`;- let error: unknown;-- try {- relayPublicDomainForStage(stage, "example.com");- } catch (cause) {- error = cause;- }-- if (!isRelayPublicDomainLabelTooLongError(error)) {- throw error;- }- expect(error).toMatchObject({- stage,- label: `relay-dev-${"x".repeat(60)}`,- maxLength: 63,- });- expect(error.message).toBe(- `Relay stage '${stage}' produces custom domain label 'relay-dev-${"x".repeat(60)}' (70 characters), exceeding the DNS label limit of 63.`,- );- });-});--describe("relayOwnsManagedEndpointZone", () => {- it("keeps the shared Cloudflare zone owned by production", () => {- expect(relayOwnsManagedEndpointZone("prod")).toBe(true);- expect(relayOwnsManagedEndpointZone("dev_julius")).toBe(false);- });-});--describe("relayResourceNameForStage", () => {- it("isolates production and personal stages", () => {- expect(relayResourceNameForStage("t3-code-relay-traces", "prod")).toBe(- "t3-code-relay-traces-prod",- );- expect(relayResourceNameForStage("t3-code-relay-traces", "dev_julius")).toBe(- "t3-code-relay-traces-dev-julius",- );- });-});--describe("managed endpoint names", () => {- it("uses the stage slug and a stable stage-scoped digest suffix", () => {- const hash = "ABCDEF0123456789ABCDEF0123456789";-- expect(managedEndpointDigestInput("dev_julius", "user_123", "env_123")).toBe(- "dev_julius:user_123:env_123",- );- expect(managedEndpointHostname("dev_julius", ".example.com.", hash)).toBe(- "dev-julius-abcdef0123456789.example.com",- );- expect(managedEndpointHostname("prod", "t3coderelay.com", hash)).toBe(- "prod-abcdef0123456789.t3coderelay.com",- );- expect(managedEndpointTunnelName("dev_julius", hash)).toBe(- "t3coderelay-managedendpoint-dev-julius-abcdef0123456789",- );- });-- it("keeps the DNS label within the provider limit for long stage names", () => {- const hostname = managedEndpointHostname(- "dev_" + "x".repeat(100),- "example.com",- "a".repeat(64),- );-- expect(hostname.split(".")[0]?.length).toBeLessThanOrEqual(63);- expect(hostname).toMatch(/-a{16}\.example\.com$/);- });-- it("accepts allocated hostnames within the relay zone", () => {- expect(- isManagedEndpointHostname("dev-julius-abcdef0123456789.example.com", "example.com"),- ).toBe(true);- expect(managedEndpointForHostname("dev-julius-abcdef0123456789.example.com")).toEqual({- httpBaseUrl: "https://dev-julius-abcdef0123456789.example.com/",- wsBaseUrl: "wss://dev-julius-abcdef0123456789.example.com/ws",- providerKind: "cloudflare_tunnel",- });- });-- it("rejects hostnames outside the relay zone", () => {- expect(isManagedEndpointHostname("internal.example.net", "example.com")).toBe(false);- expect(isManagedEndpointHostname("example.com.attacker.test", "example.com")).toBe(false);- expect(isManagedEndpointHostname("dev-julius.example.com.", "example.com")).toBe(false);- });-});diff --git a/infra/relay/src/deploymentConfig.ts b/infra/relay/src/deploymentConfig.tsdeleted file mode 100644index fe9d37b29..000000000--- a/infra/relay/src/deploymentConfig.ts+++ /dev/null@@ -1,122 +0,0 @@-import type { RelayManagedEndpoint } from "@t3tools/contracts/relay";-import * as Schema from "effect/Schema";--const DNS_LABEL_MAX_LENGTH = 63;-const MANAGED_ENDPOINT_HASH_LENGTH = 16;-const MANAGED_ENDPOINT_TUNNEL_PREFIX = "t3coderelay-managedendpoint";-export const MANAGED_ENDPOINT_ZONE_OWNER_STAGE = "prod";--export class RelayPublicDomainLabelTooLongError extends Schema.TaggedErrorClass<RelayPublicDomainLabelTooLongError>()(- "RelayPublicDomainLabelTooLongError",- {- stage: Schema.String,- label: Schema.String,- maxLength: Schema.Number,- },-) {- override get message(): string {- return `Relay stage '${this.stage}' produces custom domain label '${this.label}' (${this.label.length} characters), exceeding the DNS label limit of ${this.maxLength}.`;- }-}--function normalizeZoneName(zoneName: string): string {- return zoneName- .trim()- .toLowerCase()- .replace(/^\.+|\.+$/g, "");-}--function isDnsName(name: string): boolean {- return (- name.length > 0 &&- name.length <= 253 &&- name- .split(".")- .every(- (label) =>- label.length > 0 &&- label.length <= DNS_LABEL_MAX_LENGTH &&- /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/u.test(label),- )- );-}--function stableSuffix(hash: string): string {- return hash.toLowerCase().slice(0, MANAGED_ENDPOINT_HASH_LENGTH);-}--function appendDnsSafeSuffix(prefix: string, suffix: string): string {- const truncatedPrefix = prefix- .slice(0, DNS_LABEL_MAX_LENGTH - suffix.length - 1)- .replace(/-+$/g, "");- return `${truncatedPrefix}-${suffix}`;-}--/**- * Alchemy's physical-name helper sanitizes resource names after adding the- * stage. Keep custom domains and runtime-created resources aligned with it.- */-export function relayStageSlug(stage: string): string {- return stage- .toLowerCase()- .replaceAll(/[^a-z0-9-]/g, "-")- .replaceAll(/-+/g, "-")- .replace(/^-+|-+$/g, "");-}--export function relayResourceNameForStage(name: string, stage: string): string {- return `${name}-${relayStageSlug(stage)}`;-}--export function relayOwnsManagedEndpointZone(stage: string): boolean {- return stage === MANAGED_ENDPOINT_ZONE_OWNER_STAGE;-}--export function relayPublicDomainForStage(stage: string, zoneName: string): string {- const stageSlug = relayStageSlug(stage);- const relayLabel = stage === "prod" ? "relay" : `relay-${stageSlug}`;- if (relayLabel.length > DNS_LABEL_MAX_LENGTH) {- throw new RelayPublicDomainLabelTooLongError({- stage,- label: relayLabel,- maxLength: DNS_LABEL_MAX_LENGTH,- });- }- return `${relayLabel}.${normalizeZoneName(zoneName)}`;-}--export function managedEndpointDigestInput(- stage: string,- userId: string,- environmentId: string,-): string {- return `${stage}:${userId}:${environmentId}`;-}--export function managedEndpointHostname(stage: string, baseDomain: string, hash: string): string {- const label = appendDnsSafeSuffix(relayStageSlug(stage), stableSuffix(hash));- return `${label}.${normalizeZoneName(baseDomain)}`;-}--export function isManagedEndpointHostname(hostname: string, baseDomain: string): boolean {- const normalizedHostname = normalizeZoneName(hostname);- const normalizedBaseDomain = normalizeZoneName(baseDomain);- return (- hostname === normalizedHostname &&- isDnsName(normalizedHostname) &&- isDnsName(normalizedBaseDomain) &&- normalizedHostname.endsWith(`.${normalizedBaseDomain}`)- );-}--export function managedEndpointForHostname(hostname: string): RelayManagedEndpoint {- return {- httpBaseUrl: `https://${hostname}/`,- wsBaseUrl: `wss://${hostname}/ws`,- providerKind: "cloudflare_tunnel",- };-}--export function managedEndpointTunnelName(stage: string, hash: string): string {- return `${MANAGED_ENDPOINT_TUNNEL_PREFIX}-${relayStageSlug(stage)}-${stableSuffix(hash)}`;-}diff --git a/infra/relay/src/environments/EnvironmentConnector.test.ts b/infra/relay/src/environments/EnvironmentConnector.test.tsdeleted file mode 100644index 7f536bafb..000000000--- a/infra/relay/src/environments/EnvironmentConnector.test.ts+++ /dev/null@@ -1,824 +0,0 @@-import * as NodeCrypto from "node:crypto";-import * as NodeCryptoLayer from "@effect/platform-node/NodeCrypto";--import {- RelayCloudEnvironmentHealthRequest,- RelayCloudMintCredentialRequest,- RelayCloudEnvironmentHealthProofPayload,- RelayCloudMintCredentialProofPayload,- RelayEnvironmentHealthResponse,- RelayEnvironmentHealthResponseProofPayload,- RelayEnvironmentMintResponse,- RelayEnvironmentMintResponseProofPayload,-} from "@t3tools/contracts/relay";-import { describe, expect, it } from "@effect/vitest";-import * as DateTime from "effect/DateTime";-import { RELAY_HEALTH_RESPONSE_TYP, RELAY_MINT_RESPONSE_TYP } from "@t3tools/shared/relayJwt";-import * as Deferred from "effect/Deferred";-import * as Duration from "effect/Duration";-import * as Effect from "effect/Effect";-import * as Fiber from "effect/Fiber";-import * as Layer from "effect/Layer";-import * as Redacted from "effect/Redacted";-import * as Ref from "effect/Ref";-import * as Result from "effect/Result";-import * as Schema from "effect/Schema";-import * as TestClock from "effect/testing/TestClock";-import * as Tracer from "effect/Tracer";-import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";--import * as EnvironmentLinks from "./EnvironmentLinks.ts";-import * as RelayConfiguration from "../Config.ts";-import * as EnvironmentConnector from "./EnvironmentConnector.ts";-import * as ManagedEndpointAllocations from "./ManagedEndpointAllocations.ts";--const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", {- privateKeyEncoding: { format: "pem", type: "pkcs8" },- publicKeyEncoding: { format: "pem", type: "spki" },-});--const environmentKeyPair = NodeCrypto.generateKeyPairSync("ed25519", {- privateKeyEncoding: { format: "pem", type: "pkcs8" },- publicKeyEncoding: { format: "pem", type: "spki" },-});--const otherEnvironmentKeyPair = NodeCrypto.generateKeyPairSync("ed25519", {- privateKeyEncoding: { format: "pem", type: "pkcs8" },- publicKeyEncoding: { format: "pem", type: "spki" },-});--const decodeHealthRequestBody = Schema.decodeUnknownSync(- Schema.fromJsonString(RelayCloudEnvironmentHealthRequest),-);-const decodeMintRequestBody = Schema.decodeUnknownSync(- Schema.fromJsonString(RelayCloudMintCredentialRequest),-);-const isEnvironmentConnectNotAuthorized = Schema.is(- EnvironmentConnector.EnvironmentConnectNotAuthorized,-);--function requestBodyText(request: HttpClientRequest.HttpClientRequest): string {- return request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : "{}";-}--const settings = RelayConfiguration.RelayConfiguration.of({- relayIssuer: "https://relay.example.test",- apns: {- environment: "sandbox",- teamId: "team-id",- keyId: "key-id",- privateKey: Redacted.make("private-key"),- bundleId: "com.t3tools.t3code.dev",- },- apnsDeliveryJobSigningSecret: Redacted.make("job-secret"),- clerkSecretKey: Redacted.make("clerk-secret"),- clerkPublishableKey: "pk_test_test",- clerkJwtAudience: "t3-code-relay",- cloudMintPrivateKey: Redacted.make(cloudKeyPair.privateKey),- cloudMintPublicKey: cloudKeyPair.publicKey,- managedEndpointBaseDomain: "example.test",- managedEndpointNamespace: undefined,-});--function signTestJwt(payload: object, typ: string, privateKey: string): string {- const header = Buffer.from(JSON.stringify({ alg: "EdDSA", typ })).toString("base64url");- const encodedPayload = Buffer.from(JSON.stringify(payload)).toString("base64url");- const input = `${header}.${encodedPayload}`;- return `${input}.${NodeCrypto.sign(null, Buffer.from(input), privateKey).toString("base64url")}`;-}--function decodeRequestProof<T>(proof: string): T {- const payload = proof.split(".")[1];- if (!payload) throw new Error("Missing JWT payload.");- return JSON.parse(Buffer.from(payload, "base64url").toString("utf8")) as T;-}--function signMintResponse(- request: RelayCloudMintCredentialRequest,- overrides: Partial<RelayEnvironmentMintResponseProofPayload> = {},- privateKey = environmentKeyPair.privateKey,-): RelayEnvironmentMintResponse {- const requestProof = decodeRequestProof<RelayCloudMintCredentialProofPayload>(request.proof);- const payload = {- iss: `t3-env:${requestProof.environmentId}`,- aud: "https://relay.example.test",- sub: requestProof.environmentId,- jti: "mint-response-jti",- iat: requestProof.iat,- exp: requestProof.exp,- environmentId: requestProof.environmentId,- clientProofKeyThumbprint: requestProof.clientProofKeyThumbprint,- requestNonce: requestProof.nonce,- credential: "pairing_credential",- ...overrides,- } satisfies RelayEnvironmentMintResponseProofPayload;- return {- credential: payload.credential,- expiresAt: DateTime.formatIso(DateTime.makeUnsafe(payload.exp * 1_000)),- proof: signTestJwt(payload, RELAY_MINT_RESPONSE_TYP, privateKey),- };-}--function signHealthResponse(- request: RelayCloudEnvironmentHealthRequest,- privateKey = environmentKeyPair.privateKey,- overrides: Partial<RelayEnvironmentHealthResponse> = {},- payloadOverrides: Partial<RelayEnvironmentHealthResponseProofPayload> = {},-): RelayEnvironmentHealthResponse {- const requestProof = decodeRequestProof<RelayCloudEnvironmentHealthProofPayload>(request.proof);- const payload = {- iss: `t3-env:${requestProof.environmentId}`,- aud: "https://relay.example.test",- sub: requestProof.environmentId,- jti: "health-response-jti",- iat: requestProof.iat,- exp: requestProof.exp,- environmentId: requestProof.environmentId,- requestNonce: requestProof.nonce,- status: "online",- descriptor: {- environmentId: requestProof.environmentId,- label: "Connector Test Environment",- platform: { os: "darwin", arch: "arm64" },- serverVersion: "0.0.0-test",- capabilities: { repositoryIdentity: true },- },- checkedAt: DateTime.formatIso(DateTime.makeUnsafe(requestProof.iat * 1_000)),- ...payloadOverrides,- } satisfies RelayEnvironmentHealthResponseProofPayload;- return {- environmentId: payload.environmentId,- status: "online",- descriptor: payload.descriptor,- checkedAt: payload.checkedAt,- proof: signTestJwt(payload, RELAY_HEALTH_RESPONSE_TYP, privateKey),- ...overrides,- };-}--function connectorTestLayer(- execute: (- request: HttpClientRequest.HttpClientRequest,- ) => Effect.Effect<HttpClientResponse.HttpClientResponse>,- options?: {- readonly links?: EnvironmentLinks.EnvironmentLinks["Service"];- readonly allocations?: ManagedEndpointAllocations.ManagedEndpointAllocations["Service"];- },-) {- return EnvironmentConnector.layer.pipe(- Layer.provide(NodeCryptoLayer.layer),- Layer.provide(Layer.succeed(EnvironmentLinks.EnvironmentLinks, options?.links ?? makeLinks())),- Layer.provide(- Layer.succeed(- ManagedEndpointAllocations.ManagedEndpointAllocations,- options?.allocations ?? makeAllocations(),- ),- ),- Layer.provide(RelayConfiguration.layer(settings)),- Layer.provide(Layer.succeed(HttpClient.HttpClient, HttpClient.make(execute))),- );-}--function makeAllocations(- allocation: ManagedEndpointAllocations.ManagedEndpointAllocation | null = {- userId: "user_123",- environmentId: "env-connector-test",- hostname: "env.example.test",- tunnelId: "tunnel-id",- tunnelName: "tunnel-name",- dnsRecordId: "dns-record-id",- readyAt: "2026-05-25T00:00:00.000Z",- updatedAt: "2026-05-25T00:00:00.000Z",- },-): ManagedEndpointAllocations.ManagedEndpointAllocations["Service"] {- return {- get: () => Effect.succeed(allocation),- reserve: () => Effect.die("unused"),- recordTunnel: () => Effect.die("unused"),- recordDns: () => Effect.die("unused"),- markReady: () => Effect.die("unused"),- claimRelease: () => Effect.die("unused"),- claimDeprovision: () => Effect.die("unused"),- remove: () => Effect.die("unused"),- removeClaimed: () => Effect.die("unused"),- };-}--function makeLinks(- overrides: Partial<EnvironmentLinks.RelayLinkedEnvironmentRecord> = {},-): EnvironmentLinks.EnvironmentLinks["Service"] {- return {- upsert: () => Effect.void,- listUsersForEnvironment: () => Effect.succeed([]),- listDeliveryUsersForEnvironment: () => Effect.succeed([]),- listPublicKeysForEnvironment: () => Effect.succeed([environmentKeyPair.publicKey]),- listForUser: () => Effect.succeed([]),- getForUser: () =>- Effect.succeed({- environmentId: "env-connector-test" as never,- label: "Connector Test Environment",- endpoint: {- httpBaseUrl: "https://env.example.test/",- wsBaseUrl: "wss://env.example.test/ws",- providerKind: "cloudflare_tunnel",- },- linkedAt: "2026-05-25T00:00:00.000Z",- environmentPublicKey: environmentKeyPair.publicKey,- ...overrides,- }),- revokeForUser: () => Effect.succeed(false),- };-}--describe("EnvironmentConnector", () => {- it.effect("loads the environment link and managed allocation concurrently", () =>- Effect.gen(function* () {- const started = yield* Ref.make(0);- const bothStarted = yield* Deferred.make<void>();- const release = yield* Deferred.make<void>();- const waitForPeer = Effect.gen(function* () {- const count = yield* Ref.updateAndGet(started, (value) => value + 1);- if (count === 2) {- yield* Deferred.succeed(bothStarted, undefined);- }- yield* Deferred.await(release);- });- const links = makeLinks();- const allocations = makeAllocations();- const execute = (request: HttpClientRequest.HttpClientRequest) =>- Effect.sync(() => {- const healthRequest = decodeHealthRequestBody(requestBodyText(request));- return HttpClientResponse.fromWeb(- request,- Response.json(signHealthResponse(healthRequest), { status: 200 }),- );- });- const status = Effect.gen(function* () {- const connector = yield* EnvironmentConnector.EnvironmentConnector;- return yield* connector.status({- userId: "user_123",- environmentId: "env-connector-test" as never,- });- }).pipe(- Effect.provide(- connectorTestLayer(execute, {- links: {- ...links,- getForUser: (input) => waitForPeer.pipe(Effect.andThen(links.getForUser(input))),- },- allocations: {- ...allocations,- get: (input) => waitForPeer.pipe(Effect.andThen(allocations.get(input))),- },- }),- ),- );-- const fiber = yield* Effect.forkChild(status);- yield* Deferred.await(bothStarted);- yield* Deferred.succeed(release, undefined);- yield* Fiber.join(fiber);-- expect(yield* Ref.get(started)).toBe(2);- }),- );-- it.effect("checks linked environment health through the managed endpoint", () => {- const seenUrls: Array<string> = [];- const seenProofs: Array<RelayCloudEnvironmentHealthProofPayload> = [];- const execute = (request: HttpClientRequest.HttpClientRequest) =>- Effect.sync(() => {- const healthRequest = decodeHealthRequestBody(requestBodyText(request));- seenUrls.push(request.url);- seenProofs.push(decodeRequestProof(healthRequest.proof));- return HttpClientResponse.fromWeb(- request,- Response.json(signHealthResponse(healthRequest), { status: 200 }),- );- });-- return Effect.gen(function* () {- const connector = yield* EnvironmentConnector.EnvironmentConnector;- const result = yield* connector.status({- userId: "user_123",- environmentId: "env-connector-test",- });-- expect(seenUrls).toEqual(["https://env.example.test/api/t3-connect/health"]);- expect(seenProofs[0]).toMatchObject({- iss: "https://relay.example.test",- aud: "t3-env:env-connector-test",- sub: "user_123",- environmentId: "env-connector-test",- scope: ["environment:status"],- });- expect(result).toMatchObject({- environmentId: "env-connector-test",- status: "online",- descriptor: {- environmentId: "env-connector-test",- label: "Connector Test Environment",- },- });- }).pipe(Effect.provide(connectorTestLayer(execute)));- });-- it.effect("rejects manual endpoints before sending a health request", () => {- let requestCount = 0;- const execute = () =>- Effect.sync(() => {- requestCount += 1;- throw new Error("unexpected request");- });-- return Effect.gen(function* () {- const connector = yield* EnvironmentConnector.EnvironmentConnector;- const result = yield* Effect.result(- connector.status({- userId: "user_123",- environmentId: "env-connector-test",- }),- );-- expect(Result.isFailure(result)).toBe(true);- if (Result.isFailure(result)) {- expect(isEnvironmentConnectNotAuthorized(result.failure)).toBe(true);- if (isEnvironmentConnectNotAuthorized(result.failure)) {- expect(result.failure).toMatchObject({- operation: "status",- reason: "endpoint_provider_not_managed",- });- }- }- expect(requestCount).toBe(0);- }).pipe(- Effect.provide(- connectorTestLayer(execute, {- links: makeLinks({- endpoint: {- httpBaseUrl: "https://127.0.0.1/",- wsBaseUrl: "wss://127.0.0.1/ws",- providerKind: "manual",- },- }),- }),- ),- );- });-- it.effect("rejects stale managed endpoints before sending a mint request", () => {- let requestCount = 0;- const spans: Array<Tracer.NativeSpan> = [];- const tracer = Tracer.make({- span: (options) => {- const span = new Tracer.NativeSpan(options);- spans.push(span);- return span;- },- });- const execute = () =>- Effect.sync(() => {- requestCount += 1;- throw new Error("unexpected request");- });-- return Effect.gen(function* () {- const connector = yield* EnvironmentConnector.EnvironmentConnector;- const result = yield* Effect.result(- connector.connect({- userId: "user_123",- environmentId: "env-connector-test",- clientProofKeyThumbprint: "client-proof-key-thumbprint",- }),- );-- expect(Result.isFailure(result)).toBe(true);- if (Result.isFailure(result)) {- expect(isEnvironmentConnectNotAuthorized(result.failure)).toBe(true);- if (isEnvironmentConnectNotAuthorized(result.failure)) {- expect(result.failure).toMatchObject({- operation: "connect",- reason: "managed_endpoint_mismatch",- });- }- }- const resolutionSpan = spans.find(- (span) => span.name === "relay.environment_connector.resolve_managed_endpoint",- );- expect(Object.fromEntries(resolutionSpan?.attributes ?? [])).toMatchObject({- "relay.authorization.allocation_hostname": "env.example.test",- "relay.authorization.allocation_has_ready_at": true,- "relay.authorization.allocation_has_tunnel_id": true,- "relay.authorization.allocation_has_dns_record_id": true,- "relay.authorization.linked_http_base_url": "https://attacker.example.test/",- "relay.authorization.linked_ws_base_url": "wss://attacker.example.test/ws",- "relay.authorization.resolved_http_base_url": "https://env.example.test/",- "relay.authorization.resolved_ws_base_url": "wss://env.example.test/ws",- });- expect(requestCount).toBe(0);- }).pipe(- Effect.provide(- connectorTestLayer(execute, {- links: makeLinks({- endpoint: {- httpBaseUrl: "https://attacker.example.test/",- wsBaseUrl: "wss://attacker.example.test/ws",- providerKind: "cloudflare_tunnel",- },- }),- }),- ),- Effect.provideService(Tracer.Tracer, tracer),- );- });-- it.effect("rejects unready managed endpoint allocations before sending a request", () => {- let requestCount = 0;- const execute = () =>- Effect.sync(() => {- requestCount += 1;- throw new Error("unexpected request");- });-- return Effect.gen(function* () {- const connector = yield* EnvironmentConnector.EnvironmentConnector;- const result = yield* Effect.result(- connector.status({- userId: "user_123",- environmentId: "env-connector-test",- }),- );-- expect(Result.isFailure(result)).toBe(true);- if (Result.isFailure(result)) {- expect(isEnvironmentConnectNotAuthorized(result.failure)).toBe(true);- if (isEnvironmentConnectNotAuthorized(result.failure)) {- expect(result.failure).toMatchObject({- operation: "status",- reason: "managed_endpoint_allocation_not_ready",- });- }- }- expect(requestCount).toBe(0);- }).pipe(- Effect.provide(- connectorTestLayer(execute, {- allocations: makeAllocations({- userId: "user_123",- environmentId: "env-connector-test",- hostname: "env.example.test",- tunnelId: "tunnel-id",- tunnelName: "tunnel-name",- dnsRecordId: "dns-record-id",- readyAt: null,- updatedAt: "2026-05-25T00:00:00.000Z",- }),- }),- ),- );- });-- it.effect("rejects signed health responses with stale checkedAt timestamps", () => {- const execute = (request: HttpClientRequest.HttpClientRequest) =>- Effect.sync(() => {- const healthRequest = decodeHealthRequestBody(requestBodyText(request));- return HttpClientResponse.fromWeb(- request,- Response.json(- signHealthResponse(- healthRequest,- environmentKeyPair.privateKey,- {},- {- checkedAt: "2026-05-24T00:00:00.000Z",- },- ),- { status: 200 },- ),- );- });-- return Effect.gen(function* () {- const connector = yield* EnvironmentConnector.EnvironmentConnector;- const result = yield* Effect.exit(- connector.status({- userId: "user_123",- environmentId: "env-connector-test",- }),- );-- expect(result._tag).toBe("Failure");- if (result._tag === "Failure") {- expect(result.cause.toString()).toContain("EnvironmentMintResponseInvalid");- }- }).pipe(Effect.provide(connectorTestLayer(execute)));- });-- it.effect("reports offline status when the managed endpoint health request fails", () => {- const execute = (request: HttpClientRequest.HttpClientRequest) =>- Effect.succeed(- HttpClientResponse.fromWeb(- request,- Response.json(- {- _tag: "EnvironmentHttpInternalServerError",- message: "Environment is unavailable.",- },- { status: 500 },- ),- ),- );-- return Effect.gen(function* () {- const connector = yield* EnvironmentConnector.EnvironmentConnector;- const result = yield* connector.status({- userId: "user_123",- environmentId: "env-connector-test",- });-- expect(result).toMatchObject({- environmentId: "env-connector-test",- status: "offline",- error: "Managed endpoint health request failed: Environment is unavailable.",- traceId: expect.any(String),- });- }).pipe(Effect.provide(connectorTestLayer(execute)));- });-- it.effect("rejects health responses with a mismatched top-level environment id", () => {- const execute = (request: HttpClientRequest.HttpClientRequest) =>- Effect.sync(() => {- const healthRequest = decodeHealthRequestBody(requestBodyText(request));- return HttpClientResponse.fromWeb(- request,- Response.json(- signHealthResponse(healthRequest, environmentKeyPair.privateKey, {- environmentId: "other-env" as RelayEnvironmentHealthResponse["environmentId"],- }),- { status: 200 },- ),- );- });-- return Effect.gen(function* () {- const connector = yield* EnvironmentConnector.EnvironmentConnector;- const result = yield* Effect.exit(- connector.status({- userId: "user_123",- environmentId: "env-connector-test",- }),- );-- expect(result._tag).toBe("Failure");- if (result._tag === "Failure") {- expect(result.cause.toString()).toContain("EnvironmentMintResponseInvalid");- }- }).pipe(Effect.provide(connectorTestLayer(execute)));- });-- it.effect("rejects health responses with an unsigned top-level descriptor mutation", () => {- const execute = (request: HttpClientRequest.HttpClientRequest) =>- Effect.sync(() => {- const healthRequest = decodeHealthRequestBody(requestBodyText(request));- const response = signHealthResponse(healthRequest);- return HttpClientResponse.fromWeb(- request,- Response.json(- {- ...response,- descriptor: {- ...response.descriptor,- label: "Tampered Environment Label",- },- } satisfies RelayEnvironmentHealthResponse,- { status: 200 },- ),- );- });-- return Effect.gen(function* () {- const connector = yield* EnvironmentConnector.EnvironmentConnector;- const result = yield* Effect.exit(- connector.status({- userId: "user_123",- environmentId: "env-connector-test",- }),- );-- expect(result._tag).toBe("Failure");- if (result._tag === "Failure") {- expect(result.cause.toString()).toContain("EnvironmentMintResponseInvalid");- }- }).pipe(Effect.provide(connectorTestLayer(execute)));- });-- it.effect("rejects health responses when the linked environment public key is malformed", () => {- const execute = (request: HttpClientRequest.HttpClientRequest) =>- Effect.sync(() => {- const healthRequest = decodeHealthRequestBody(requestBodyText(request));- return HttpClientResponse.fromWeb(- request,- Response.json(signHealthResponse(healthRequest), { status: 200 }),- );- });-- return Effect.gen(function* () {- const connector = yield* EnvironmentConnector.EnvironmentConnector;- const result = yield* Effect.exit(- connector.status({- userId: "user_123",- environmentId: "env-connector-test",- }),- );-- expect(result._tag).toBe("Failure");- if (result._tag === "Failure") {- expect(result.cause.toString()).toContain("EnvironmentMintResponseInvalid");- }- }).pipe(- Effect.provide(- connectorTestLayer(execute, {- links: makeLinks({- environmentPublicKey: "not a pem public key",- }),- }),- ),- );- });-- it.effect("mints a one-time environment credential through the linked endpoint", () => {- const seenUrls: Array<string> = [];- const seenProofs: Array<RelayCloudMintCredentialProofPayload> = [];- const execute = (request: HttpClientRequest.HttpClientRequest) =>- Effect.sync(() => {- const mintRequest = decodeMintRequestBody(requestBodyText(request));- seenUrls.push(request.url);- seenProofs.push(decodeRequestProof(mintRequest.proof));- return HttpClientResponse.fromWeb(- request,- Response.json(signMintResponse(mintRequest), { status: 200 }),- );- });-- return Effect.gen(function* () {- const connector = yield* EnvironmentConnector.EnvironmentConnector;- const result = yield* connector.connect({- userId: "user_123",- environmentId: "env-connector-test",- clientProofKeyThumbprint: "client-proof-key-thumbprint",- deviceId: "device-123",- });-- expect(seenUrls).toEqual(["https://env.example.test/api/t3-connect/mint-credential"]);- expect(seenProofs[0]).toMatchObject({- iss: "https://relay.example.test",- aud: "t3-env:env-connector-test",- sub: "user_123",- environmentId: "env-connector-test",- clientProofKeyThumbprint: "client-proof-key-thumbprint",- cnf: { jkt: "client-proof-key-thumbprint" },- deviceId: "device-123",- scope: ["environment:connect"],- });- expect(result).toMatchObject({- environmentId: "env-connector-test",- credential: "pairing_credential",- endpoint: {- httpBaseUrl: "https://env.example.test/",- wsBaseUrl: "wss://env.example.test/ws",- },- });- }).pipe(Effect.provide(connectorTestLayer(execute)));- });-- it.effect("only accepts mint responses signed by the user's linked environment key", () => {- const execute = (request: HttpClientRequest.HttpClientRequest) =>- Effect.sync(() => {- const mintRequest = decodeMintRequestBody(requestBodyText(request));- return HttpClientResponse.fromWeb(- request,- Response.json(signMintResponse(mintRequest, {}, otherEnvironmentKeyPair.privateKey), {- status: 200,- }),- );- });-- return Effect.gen(function* () {- const connector = yield* EnvironmentConnector.EnvironmentConnector;- const result = yield* Effect.exit(- connector.connect({- userId: "user_123",- environmentId: "env-connector-test",- clientProofKeyThumbprint: "client-proof-key-thumbprint",- }),- );-- expect(result._tag).toBe("Failure");- if (result._tag === "Failure") {- expect(result.cause.toString()).toContain("EnvironmentMintResponseInvalid");- }- }).pipe(Effect.provide(connectorTestLayer(execute)));- });-- it.effect("rejects mint responses when the linked environment public key is malformed", () => {- const execute = (request: HttpClientRequest.HttpClientRequest) =>- Effect.sync(() => {- const mintRequest = decodeMintRequestBody(requestBodyText(request));- return HttpClientResponse.fromWeb(- request,- Response.json(signMintResponse(mintRequest), { status: 200 }),- );- });-- return Effect.gen(function* () {- const connector = yield* EnvironmentConnector.EnvironmentConnector;- const result = yield* Effect.exit(- connector.connect({- userId: "user_123",- environmentId: "env-connector-test",- clientProofKeyThumbprint: "client-proof-key-thumbprint",- }),- );-- expect(result._tag).toBe("Failure");- if (result._tag === "Failure") {- expect(result.cause.toString()).toContain("EnvironmentMintResponseInvalid");- }- }).pipe(- Effect.provide(- connectorTestLayer(execute, {- links: makeLinks({- environmentPublicKey: "not a pem public key",- }),- }),- ),- );- });-- it.effect("rejects environment mint responses with an overlong credential window", () => {- const execute = (request: HttpClientRequest.HttpClientRequest) =>- Effect.sync(() => {- const mintRequest = decodeMintRequestBody(requestBodyText(request));- return HttpClientResponse.fromWeb(- request,- Response.json(- { ...signMintResponse(mintRequest), expiresAt: "2999-01-01T00:00:00.000Z" },- { status: 200 },- ),- );- });-- return Effect.gen(function* () {- const connector = yield* EnvironmentConnector.EnvironmentConnector;- const result = yield* Effect.exit(- connector.connect({- userId: "user_123",- environmentId: "env-connector-test",- clientProofKeyThumbprint: "client-proof-key-thumbprint",- }),- );-- expect(result._tag).toBe("Failure");- if (result._tag === "Failure") {- expect(result.cause.toString()).toContain("EnvironmentMintResponseInvalid");- }- }).pipe(Effect.provide(connectorTestLayer(execute)));- });-- it.effect("times out hung managed endpoint mint requests", () => {- let resolveRequestStarted: (() => void) | undefined;- const requestStarted = new Promise<void>((resolve) => {- resolveRequestStarted = () => resolve();- });- const execute = () =>- Effect.sync(() => {- resolveRequestStarted?.();- }).pipe(Effect.andThen(Effect.never as Effect.Effect<HttpClientResponse.HttpClientResponse>));-- return Effect.gen(function* () {- const connector = yield* EnvironmentConnector.EnvironmentConnector;- const resultFiber = yield* connector- .connect({- userId: "user_123",- environmentId: "env-connector-test",- clientProofKeyThumbprint: "client-proof-key-thumbprint",- })- .pipe(Effect.result, Effect.forkScoped);-- yield* Effect.promise(() => requestStarted);- yield* TestClock.adjust(- Duration.millis(EnvironmentConnector.ENVIRONMENT_MINT_REQUEST_TIMEOUT_MS),- );- const result = yield* Fiber.join(resultFiber);-- expect(Result.isFailure(result)).toBe(true);- if (Result.isFailure(result)) {- expect(result.failure._tag).toBe("EnvironmentMintRequestTimedOut");- expect(result.failure).toMatchObject({- environmentId: "env-connector-test",- timeoutMs: EnvironmentConnector.ENVIRONMENT_MINT_REQUEST_TIMEOUT_MS,- });- }- }).pipe(Effect.provide(Layer.merge(TestClock.layer(), connectorTestLayer(execute))));- });-});diff --git a/infra/relay/src/environments/EnvironmentConnector.ts b/infra/relay/src/environments/EnvironmentConnector.tsdeleted file mode 100644index d840f809e..000000000--- a/infra/relay/src/environments/EnvironmentConnector.ts+++ /dev/null@@ -1,675 +0,0 @@-import {- EnvironmentHttpBadRequestError,- EnvironmentHttpConflictError,- EnvironmentHttpForbiddenError,- EnvironmentHttpInternalServerError,- EnvironmentHttpUnauthorizedError,-} from "@t3tools/contracts";-import { makeEnvironmentHttpApiClient } from "@t3tools/client-runtime/rpc";-import {- RelayCloudEnvironmentHealthProofPayload,- RelayEnvironmentHealthResponse,- RelayEnvironmentHealthResponseProofPayload,- RelayEnvironmentMintResponse,- RelayEnvironmentMintResponseProofPayload,- RelayCloudMintCredentialProofPayload,- RelayEnvironmentConnectNotAuthorizedReason,- type RelayEnvironmentConnectResponse,- type RelayEnvironmentStatusResponse,-} from "@t3tools/contracts/relay";-import {- normalizeRelayIssuer,- RELAY_HEALTH_REQUEST_TYP,- RELAY_HEALTH_RESPONSE_TYP,- RELAY_MINT_REQUEST_TYP,- RELAY_MINT_RESPONSE_TYP,- signRelayJwt,- verifyRelayJwt,-} from "@t3tools/shared/relayJwt";-import { stableStringify } from "@t3tools/shared/relaySigning";-import * as Context from "effect/Context";-import * as Crypto from "effect/Crypto";-import * as DateTime from "effect/DateTime";-import * as Duration from "effect/Duration";-import * as Effect from "effect/Effect";-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 FetchHttpClient from "effect/unstable/http/FetchHttpClient";-import * as HttpClient from "effect/unstable/http/HttpClient";-import * as HttpClientError from "effect/unstable/http/HttpClientError";--import * as EnvironmentLinks from "./EnvironmentLinks.ts";-import * as ManagedEndpointAllocations from "./ManagedEndpointAllocations.ts";-import * as RelayConfiguration from "../Config.ts";-import { isManagedEndpointHostname } from "../deploymentConfig.ts";--function environmentConnectNotAuthorizedReasonMessage(- reason: RelayEnvironmentConnectNotAuthorizedReason,-): string {- switch (reason) {- case "client_proof_key_thumbprint_missing":- return "the client proof key thumbprint is missing";- case "environment_link_not_found":- return "no active environment link was found";- case "endpoint_provider_not_managed":- return "the linked endpoint is not relay-managed";- case "managed_endpoint_allocation_not_found":- return "no managed endpoint allocation was found";- case "managed_endpoint_base_domain_not_configured":- return "the managed endpoint base domain is not configured";- case "managed_endpoint_allocation_not_ready":- return "the managed endpoint allocation is incomplete";- case "managed_endpoint_hostname_invalid":- return "the managed endpoint hostname is invalid";- case "managed_endpoint_mismatch":- return "the linked endpoint does not match its managed allocation";- }-}--export class EnvironmentConnectNotAuthorized extends Schema.TaggedErrorClass<EnvironmentConnectNotAuthorized>()(- "EnvironmentConnectNotAuthorized",- {- environmentId: Schema.String,- operation: Schema.Literals(["connect", "status"]),- reason: RelayEnvironmentConnectNotAuthorizedReason,- },-) {- override get message(): string {- return `Environment '${this.environmentId}' is not authorized for ${this.operation}: ${environmentConnectNotAuthorizedReasonMessage(this.reason)}`;- }-}--export class EnvironmentMintRequestFailed extends Schema.TaggedErrorClass<EnvironmentMintRequestFailed>()(- "EnvironmentMintRequestFailed",- {- environmentId: Schema.String,- operation: Schema.Literals(["connect", "status"]),- cause: Schema.Defect(),- },-) {- override get message(): string {- return `Environment '${this.environmentId}' ${this.operation} request failed`;- }-}--export class EnvironmentMintRequestTimedOut extends Schema.TaggedErrorClass<EnvironmentMintRequestTimedOut>()(- "EnvironmentMintRequestTimedOut",- {- environmentId: Schema.String,- timeoutMs: Schema.Number,- },-) {- override get message(): string {- return `Environment '${this.environmentId}' mint request timed out after ${this.timeoutMs}ms`;- }-}--export class EnvironmentMintResponseInvalid extends Schema.TaggedErrorClass<EnvironmentMintResponseInvalid>()(- "EnvironmentMintResponseInvalid",- {- environmentId: Schema.String,- operation: Schema.Literals(["connect", "status"]),- },-) {- override get message(): string {- return `Environment '${this.environmentId}' returned an invalid ${this.operation} response`;- }-}--export type EnvironmentConnectorError =- | EnvironmentConnectNotAuthorized- | EnvironmentMintRequestFailed- | EnvironmentMintRequestTimedOut- | EnvironmentMintResponseInvalid- | EnvironmentLinks.EnvironmentLinkLookupPersistenceError- | ManagedEndpointAllocations.ManagedEndpointAllocationPersistenceError;--export const ENVIRONMENT_MINT_REQUEST_TIMEOUT_MS = 10_000;-const ENVIRONMENT_HEALTH_CLOCK_SKEW_MILLIS = 60 * 1_000;--export class EnvironmentConnector extends Context.Service<- EnvironmentConnector,- {- readonly connect: (input: {- readonly userId: string;- readonly environmentId: string;- readonly clientProofKeyThumbprint: string;- readonly deviceId?: string;- }) => Effect.Effect<RelayEnvironmentConnectResponse, EnvironmentConnectorError>;- readonly status: (input: {- readonly userId: string;- readonly environmentId: string;- }) => Effect.Effect<RelayEnvironmentStatusResponse, EnvironmentConnectorError>;- }->()("t3code-relay/environments/EnvironmentConnector") {}--const decodeMintResponseProof = Schema.decodeUnknownEffect(- RelayEnvironmentMintResponseProofPayload,-);-const decodeHealthResponseProof = Schema.decodeUnknownEffect(- RelayEnvironmentHealthResponseProofPayload,-);-const isEnvironmentHealthError = Schema.is(- Schema.Union([- EnvironmentHttpBadRequestError,- EnvironmentHttpUnauthorizedError,- EnvironmentHttpForbiddenError,- EnvironmentHttpConflictError,- EnvironmentHttpInternalServerError,- ]),-);--function environmentHealthRequestFailureMessage(cause: unknown): string {- return isEnvironmentHealthError(cause)- ? `Managed endpoint health request failed: ${cause.message}`- : "Managed endpoint health request failed.";-}--function environmentHealthRequestFailureReason(cause: unknown): string {- if (isEnvironmentHealthError(cause)) {- return cause._tag;- }- if (HttpClientError.isHttpClientError(cause)) {- return cause.reason._tag;- }- if (Schema.isSchemaError(cause)) {- return "SchemaError";- }- return cause instanceof Error && cause.name ? cause.name : "Unknown";-}--const currentTraceId = Effect.currentSpan.pipe(- Effect.map((span) => span.traceId),- Effect.orElseSucceed(() => "unavailable"),-);--const withoutRedirects = <A, E, R>(effect: Effect.Effect<A, E, R>) =>- effect.pipe(Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" }));--const verifyWithEnvironmentKeys = Effect.fnUntraced(function* <A, E>(input: {- readonly token: string;- readonly typ: string;- readonly issuer: string;- readonly audience: string;- readonly nowEpochSeconds: number;- readonly environmentPublicKeys: ReadonlyArray<string>;- readonly decodePayload: (input: unknown) => Effect.Effect<A, E>;-}) {- const { decodePayload, ...rest } = input;- for (const publicKey of input.environmentPublicKeys) {- const proof = yield* verifyRelayJwt({ ...rest, publicKey }).pipe(- Effect.flatMap(decodePayload),- Effect.option,- );- if (Option.isSome(proof)) {- return proof.value;- }- // A linked environment can have rotated keys; try the remaining active keys.- }- return null;-});--function verifyEnvironmentResponse(input: {- readonly response: RelayEnvironmentMintResponse;- readonly environmentId: string;- readonly requestNonce: string;- readonly clientProofKeyThumbprint: string;- readonly environmentPublicKeys: ReadonlyArray<string>;- readonly relayIssuer: string;- readonly nowEpochSeconds: number;-}) {- return verifyWithEnvironmentKeys({- token: input.response.proof,- typ: RELAY_MINT_RESPONSE_TYP,- issuer: `t3-env:${input.environmentId}`,- audience: normalizeRelayIssuer(input.relayIssuer),- nowEpochSeconds: input.nowEpochSeconds,- environmentPublicKeys: input.environmentPublicKeys,- decodePayload: decodeMintResponseProof,- }).pipe(- Effect.map(- (proof) =>- proof !== null &&- proof.environmentId === input.environmentId &&- proof.requestNonce === input.requestNonce &&- proof.clientProofKeyThumbprint === input.clientProofKeyThumbprint &&- proof.credential === input.response.credential &&- Option.match(DateTime.make(input.response.expiresAt), {- onNone: () => false,- onSome: (expiresAt) => Math.floor(expiresAt.epochMilliseconds / 1_000) === proof.exp,- }),- ),- );-}--function verifyEnvironmentHealthResponse(input: {- readonly response: RelayEnvironmentHealthResponse;- readonly environmentId: string;- readonly requestNonce: string;- readonly requestIssuedAt: DateTime.DateTime;- readonly environmentPublicKeys: ReadonlyArray<string>;- readonly relayIssuer: string;- readonly now: DateTime.DateTime;-}) {- return verifyWithEnvironmentKeys({- token: input.response.proof,- typ: RELAY_HEALTH_RESPONSE_TYP,- issuer: `t3-env:${input.environmentId}`,- audience: normalizeRelayIssuer(input.relayIssuer),- nowEpochSeconds: Math.floor(input.now.epochMilliseconds / 1_000),- environmentPublicKeys: input.environmentPublicKeys,- decodePayload: decodeHealthResponseProof,- }).pipe(- Effect.map((proof) => {- if (- proof === null ||- input.response.environmentId !== input.environmentId ||- proof.environmentId !== input.environmentId ||- proof.requestNonce !== input.requestNonce ||- proof.status !== input.response.status ||- proof.checkedAt !== input.response.checkedAt ||- stableStringify(proof.descriptor) !== stableStringify(input.response.descriptor)- ) {- return false;- }- const checkedAt = DateTime.make(input.response.checkedAt);- if (Option.isNone(checkedAt)) {- return false;- }- return (- checkedAt.value.epochMilliseconds >=- input.requestIssuedAt.epochMilliseconds - ENVIRONMENT_HEALTH_CLOCK_SKEW_MILLIS &&- checkedAt.value.epochMilliseconds <=- input.now.epochMilliseconds + ENVIRONMENT_HEALTH_CLOCK_SKEW_MILLIS- );- }),- );-}--const make = Effect.gen(function* () {- const links = yield* EnvironmentLinks.EnvironmentLinks;- const allocations = yield* ManagedEndpointAllocations.ManagedEndpointAllocations;- const settings = yield* RelayConfiguration.RelayConfiguration;- const httpClient = yield* HttpClient.HttpClient;- const crypto = yield* Crypto.Crypto;- const relayIssuer = normalizeRelayIssuer(settings.relayIssuer);- const makeEnvironmentClient = (httpBaseUrl: string) =>- makeEnvironmentHttpApiClient(httpBaseUrl).pipe(- Effect.provideService(HttpClient.HttpClient, httpClient),- );- const resolveManagedEndpoint = Effect.fn("relay.environment_connector.resolve_managed_endpoint")(- function* (input: {- readonly operation: "connect" | "status";- readonly link: EnvironmentLinks.RelayLinkedEnvironmentRecord;- readonly allocation: ManagedEndpointAllocations.ManagedEndpointAllocation | null;- }) {- if (input.link.endpoint.providerKind !== "cloudflare_tunnel") {- yield* Effect.annotateCurrentSpan({- "relay.authorization.endpoint_provider_kind": input.link.endpoint.providerKind,- });- return yield* new EnvironmentConnectNotAuthorized({- environmentId: input.link.environmentId,- operation: input.operation,- reason: "endpoint_provider_not_managed",- });- }- if (!input.allocation) {- return yield* new EnvironmentConnectNotAuthorized({- environmentId: input.link.environmentId,- operation: input.operation,- reason: "managed_endpoint_allocation_not_found",- });- }- const allocationAttributes = {- "relay.authorization.allocation_hostname": input.allocation.hostname,- "relay.authorization.allocation_has_ready_at": input.allocation.readyAt !== null,- "relay.authorization.allocation_has_tunnel_id": input.allocation.tunnelId !== null,- "relay.authorization.allocation_has_dns_record_id": input.allocation.dnsRecordId !== null,- } as const;- if (!settings.managedEndpointBaseDomain) {- yield* Effect.annotateCurrentSpan(allocationAttributes);- return yield* new EnvironmentConnectNotAuthorized({- environmentId: input.link.environmentId,- operation: input.operation,- reason: "managed_endpoint_base_domain_not_configured",- });- }- if (- input.allocation.readyAt === null ||- input.allocation.tunnelId === null ||- input.allocation.dnsRecordId === null- ) {- yield* Effect.annotateCurrentSpan(allocationAttributes);- return yield* new EnvironmentConnectNotAuthorized({- environmentId: input.link.environmentId,- operation: input.operation,- reason: "managed_endpoint_allocation_not_ready",- });- }- if (- !isManagedEndpointHostname(input.allocation.hostname, settings.managedEndpointBaseDomain)- ) {- yield* Effect.annotateCurrentSpan({- ...allocationAttributes,- "relay.authorization.managed_endpoint_base_domain": settings.managedEndpointBaseDomain,- });- return yield* new EnvironmentConnectNotAuthorized({- environmentId: input.link.environmentId,- operation: input.operation,- reason: "managed_endpoint_hostname_invalid",- });- }- const endpoint = ManagedEndpointAllocations.resolveReadyManagedEndpoint({- allocation: input.allocation,- baseDomain: settings.managedEndpointBaseDomain,- });- if (- endpoint === null ||- endpoint.httpBaseUrl !== input.link.endpoint.httpBaseUrl ||- endpoint.wsBaseUrl !== input.link.endpoint.wsBaseUrl- ) {- yield* Effect.annotateCurrentSpan({- ...allocationAttributes,- "relay.authorization.linked_http_base_url": input.link.endpoint.httpBaseUrl,- "relay.authorization.linked_ws_base_url": input.link.endpoint.wsBaseUrl,- ...(endpoint- ? {- "relay.authorization.resolved_http_base_url": endpoint.httpBaseUrl,- "relay.authorization.resolved_ws_base_url": endpoint.wsBaseUrl,- }- : {}),- });- return yield* new EnvironmentConnectNotAuthorized({- environmentId: input.link.environmentId,- operation: input.operation,- reason: "managed_endpoint_mismatch",- });- }- return endpoint;- },- );-- return EnvironmentConnector.of({- status: Effect.fn("relay.environment_connector.status")(function* (input) {- yield* Effect.annotateCurrentSpan({- "relay.environment_id": input.environmentId,- "relay.operation": "status",- });- const { link, allocation } = yield* Effect.all(- {- link: links.getForUser(input),- allocation: allocations.get(input),- },- { concurrency: 2 },- );- if (!link) {- return yield* new EnvironmentConnectNotAuthorized({- environmentId: input.environmentId,- operation: "status",- reason: "environment_link_not_found",- });- }- const endpoint = yield* resolveManagedEndpoint({- operation: "status",- link,- allocation,- });- const now = yield* DateTime.now;- const expiresAt = DateTime.add(now, { minutes: 2 });- const nonce = yield* crypto.randomUUIDv4.pipe(- Effect.mapError(- (cause) =>- new EnvironmentMintRequestFailed({- environmentId: input.environmentId,- operation: "status",- cause,- }),- ),- );- const payload = {- iss: relayIssuer,- aud: `t3-env:${link.environmentId}`,- sub: input.userId,- jti: yield* crypto.randomUUIDv4.pipe(- Effect.mapError(- (cause) =>- new EnvironmentMintRequestFailed({- environmentId: input.environmentId,- operation: "status",- cause,- }),- ),- ),- iat: Math.floor(now.epochMilliseconds / 1_000),- exp: Math.floor(expiresAt.epochMilliseconds / 1_000),- environmentId: link.environmentId,- nonce,- scope: ["environment:status"],- } satisfies RelayCloudEnvironmentHealthProofPayload;- const proof = yield* signRelayJwt({- privateKey: Redacted.value(settings.cloudMintPrivateKey),- typ: RELAY_HEALTH_REQUEST_TYP,- payload,- }).pipe(- Effect.mapError(- (cause) =>- new EnvironmentMintRequestFailed({- environmentId: input.environmentId,- operation: "status",- cause,- }),- ),- );- const checkedAt = DateTime.formatIso(now);- const traceId = yield* currentTraceId;- const environmentClient = yield* makeEnvironmentClient(endpoint.httpBaseUrl);- const responseOption = yield* environmentClient.connect.health({ payload: { proof } }).pipe(- withoutRedirects,- Effect.match({- onFailure: (cause) => ({ _tag: "Failure" as const, cause }),- onSuccess: (response) => ({ _tag: "Success" as const, response }),- }),- Effect.timeoutOption(Duration.millis(ENVIRONMENT_MINT_REQUEST_TIMEOUT_MS)),- );- if (Option.isNone(responseOption)) {- yield* Effect.annotateCurrentSpan({- "relay.environment_health.outcome": "timeout",- "relay.environment_health.trace_id": traceId,- });- yield* Effect.logWarning("Managed endpoint health request timed out", {- environmentId: link.environmentId,- endpoint: endpoint.httpBaseUrl,- traceId,- });- return {- environmentId: link.environmentId,- endpoint,- status: "offline" as const,- checkedAt,- error: "Managed endpoint health request timed out.",- traceId,- };- }- if (responseOption.value._tag === "Failure") {- const failureReason = environmentHealthRequestFailureReason(responseOption.value.cause);- yield* Effect.annotateCurrentSpan({- "relay.environment_health.outcome": "failure",- "relay.environment_health.failure_reason": failureReason,- "relay.environment_health.trace_id": traceId,- });- yield* Effect.logWarning("Managed endpoint health request failed", {- environmentId: link.environmentId,- endpoint: endpoint.httpBaseUrl,- failureReason,- traceId,- });- return {- environmentId: link.environmentId,- endpoint,- status: "offline" as const,- checkedAt,- error: environmentHealthRequestFailureMessage(responseOption.value.cause),- traceId,- };- }- const decoded = responseOption.value.response;- const verified = yield* verifyEnvironmentHealthResponse({- response: decoded,- environmentId: input.environmentId,- requestNonce: nonce,- requestIssuedAt: now,- environmentPublicKeys: [link.environmentPublicKey],- relayIssuer,- now: yield* DateTime.now,- });- if (!verified) {- return yield* new EnvironmentMintResponseInvalid({- environmentId: input.environmentId,- operation: "status",- });- }- return {- environmentId: link.environmentId,- endpoint,- status: "online" as const,- checkedAt: decoded.checkedAt,- descriptor: decoded.descriptor,- };- }),- connect: Effect.fn("relay.environment_connector.connect")(function* (input) {- yield* Effect.annotateCurrentSpan({- "relay.environment_id": input.environmentId,- "relay.operation": "connect",- "relay.connect.has_device_id": input.deviceId !== undefined,- ...(input.deviceId ? { "relay.mobile.device_id": input.deviceId } : {}),- });- if (input.clientProofKeyThumbprint.trim().length === 0) {- return yield* new EnvironmentConnectNotAuthorized({- environmentId: input.environmentId,- operation: "connect",- reason: "client_proof_key_thumbprint_missing",- });- }- const { link, allocation } = yield* Effect.all(- {- link: links.getForUser(input),- allocation: allocations.get(input),- },- { concurrency: 2 },- );- if (!link) {- return yield* new EnvironmentConnectNotAuthorized({- environmentId: input.environmentId,- operation: "connect",- reason: "environment_link_not_found",- });- }- const endpoint = yield* resolveManagedEndpoint({- operation: "connect",- link,- allocation,- });- const now = yield* DateTime.now;- const expiresAt = DateTime.add(now, { minutes: 2 });- const nonce = yield* crypto.randomUUIDv4.pipe(- Effect.mapError(- (cause) =>- new EnvironmentMintRequestFailed({- environmentId: input.environmentId,- operation: "connect",- cause,- }),- ),- );- const payload = {- iss: relayIssuer,- aud: `t3-env:${link.environmentId}`,- sub: input.userId,- jti: yield* crypto.randomUUIDv4.pipe(- Effect.mapError(- (cause) =>- new EnvironmentMintRequestFailed({- environmentId: input.environmentId,- operation: "connect",- cause,- }),- ),- ),- iat: Math.floor(now.epochMilliseconds / 1_000),- exp: Math.floor(expiresAt.epochMilliseconds / 1_000),- environmentId: link.environmentId,- clientProofKeyThumbprint: input.clientProofKeyThumbprint,- cnf: { jkt: input.clientProofKeyThumbprint },- ...(input.deviceId ? { deviceId: input.deviceId } : {}),- nonce,- scope: ["environment:connect"],- } satisfies RelayCloudMintCredentialProofPayload;- const proof = yield* signRelayJwt({- privateKey: Redacted.value(settings.cloudMintPrivateKey),- typ: RELAY_MINT_REQUEST_TYP,- payload,- }).pipe(- Effect.mapError(- (cause) =>- new EnvironmentMintRequestFailed({- environmentId: input.environmentId,- operation: "connect",- cause,- }),- ),- );- const environmentClient = yield* makeEnvironmentClient(endpoint.httpBaseUrl);- const decoded = yield* environmentClient.connect- .t3MintCredential({ payload: { proof } })- .pipe(- withoutRedirects,- Effect.mapError(- (cause) =>- new EnvironmentMintRequestFailed({- environmentId: input.environmentId,- operation: "connect",- cause,- }),- ),- Effect.timeoutOption(Duration.millis(ENVIRONMENT_MINT_REQUEST_TIMEOUT_MS)),- Effect.flatMap(- Option.match({- onNone: () =>- Effect.fail(- new EnvironmentMintRequestTimedOut({- environmentId: input.environmentId,- timeoutMs: ENVIRONMENT_MINT_REQUEST_TIMEOUT_MS,- }),- ),- onSome: Effect.succeed,- }),- ),- );- const verified = yield* verifyEnvironmentResponse({- response: decoded,- environmentId: input.environmentId,- requestNonce: nonce,- clientProofKeyThumbprint: input.clientProofKeyThumbprint,- environmentPublicKeys: [link.environmentPublicKey],- relayIssuer,- nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),- });- if (!verified) {- return yield* new EnvironmentMintResponseInvalid({- environmentId: input.environmentId,- operation: "connect",- });- }- return {- environmentId: link.environmentId,- endpoint,- credential: decoded.credential,- expiresAt: decoded.expiresAt,- };- }),- });-});--export const layer = Layer.effect(EnvironmentConnector, make);diff --git a/infra/relay/src/environments/EnvironmentCredentials.test.ts b/infra/relay/src/environments/EnvironmentCredentials.test.tsdeleted file mode 100644index 4a2e07c6b..000000000--- a/infra/relay/src/environments/EnvironmentCredentials.test.ts+++ /dev/null@@ -1,250 +0,0 @@-import * as NodeCryptoLayer from "@effect/platform-node/NodeCrypto";-import { describe, expect, it } from "@effect/vitest";-import { PgDialect } from "drizzle-orm/pg-core";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";--import * as RelayDb from "../db.ts";-import { relayEnvironmentCredentials } from "../persistence/schema.ts";-import * as EnvironmentCredentials from "./EnvironmentCredentials.ts";--describe("EnvironmentCredentials", () => {- it.effect("reports the credential creation persistence stage and preserves its cause", () => {- const cause = new Error("database unavailable");- const fakeDb = {- insert: (table: unknown) => {- expect(table).toBe(relayEnvironmentCredentials);- return {- values: () => Effect.void,- };- },- update: (table: unknown) => {- expect(table).toBe(relayEnvironmentCredentials);- return {- set: () => ({- where: () => Effect.fail(cause),- }),- };- },- } as unknown as RelayDb.RelayDb["Service"];-- return Effect.gen(function* () {- const credentials = yield* EnvironmentCredentials.EnvironmentCredentials;- const error = yield* Effect.flip(- credentials.create({- environmentId: "env_test",- environmentPublicKey: "sensitive-public-key-material",- }),- );-- expect(error).toMatchObject({- _tag: "EnvironmentCredentialCreatePersistenceError",- stage: "revoke-previous-credentials",- environmentId: "env_test",- });- expect(error.credentialId).toMatch(/^[0-9a-f]{64}$/);- expect(error.cause).toBe(cause);- expect(error).not.toHaveProperty("environmentPublicKey");- }).pipe(- Effect.provide(- EnvironmentCredentials.layer.pipe(- Layer.provide(NodeCryptoLayer.layer),- Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb)),- ),- ),- );- });-- it.effect("does not retain credential tokens when lookup persistence fails", () => {- const cause = new Error("database unavailable");- const token = "t3env_sensitive-credential-token";- const whereConditions: Array<unknown> = [];- const fakeDb = {- select: () => ({- from: (table: unknown) => {- expect(table).toBe(relayEnvironmentCredentials);- return {- where: (condition: unknown) => ({- limit: () => {- whereConditions.push(condition);- return Effect.fail(cause);- },- }),- };- },- }),- } as unknown as RelayDb.RelayDb["Service"];-- return Effect.gen(function* () {- const credentials = yield* EnvironmentCredentials.EnvironmentCredentials;- const error = yield* Effect.flip(credentials.authenticate(token));-- expect(error).toMatchObject({- _tag: "EnvironmentCredentialAuthenticatePersistenceError",- stage: "lookup-credential",- });- expect(error.cause).toBe(cause);- expect(error).not.toHaveProperty("token");- expect(whereConditions).toHaveLength(1);-- const query = new PgDialect().sqlToQuery(whereConditions[0] as never);- expect(query.sql).toContain("exists");- expect(query.sql).toContain('"relay_environment_links"."environment_id"');- expect(query.sql).toContain('"relay_environment_links"."environment_public_key"');- expect(query.sql).toContain('"relay_environment_links"."revoked_at" is null');- }).pipe(- Effect.provide(- EnvironmentCredentials.layer.pipe(- Layer.provide(NodeCryptoLayer.layer),- Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb)),- ),- ),- );- });-- it.effect(- "creates opaque credentials and revokes only older credentials for the same key",- () => {- const insertedValues: Array<{- readonly credentialId: string;- readonly environmentId: string;- readonly environmentPublicKey: string;- readonly credentialHash: string;- readonly revokedAt: null;- readonly createdAt: string;- readonly updatedAt: string;- }> = [];- const staleCredentialRevocations: Array<{- readonly values: Record<string, unknown>;- readonly condition: unknown;- }> = [];-- const fakeDb = {- insert: (table: unknown) => {- expect(table).toBe(relayEnvironmentCredentials);- return {- values: (values: (typeof insertedValues)[number]) => {- insertedValues.push(values);- return Effect.void;- },- };- },- update: (table: unknown) => {- expect(table).toBe(relayEnvironmentCredentials);- return {- set: (values: Record<string, unknown>) => ({- where: (condition: unknown) => {- staleCredentialRevocations.push({ values, condition });- return Effect.void;- },- }),- };- },- } as unknown as RelayDb.RelayDb["Service"];-- return Effect.gen(function* () {- const credentials = yield* EnvironmentCredentials.EnvironmentCredentials;- const token = yield* credentials.create({- environmentId: "env_test",- environmentPublicKey: "environment-public-key",- });- const [, credentialId, secret] = token.split("_");-- expect(token).toMatch(/^t3env_[0-9a-f]{64}_[0-9a-f]{96}$/);- expect(credentialId).toHaveLength(64);- expect(secret).toHaveLength(96);- expect(insertedValues).toHaveLength(1);- expect(insertedValues[0]).toMatchObject({- credentialId,- environmentId: "env_test",- environmentPublicKey: "environment-public-key",- revokedAt: null,- });- expect(insertedValues[0]?.credentialHash).toMatch(/^[A-Za-z0-9_-]{43}$/);- expect(insertedValues[0]?.credentialHash).not.toContain(token);- expect(insertedValues[0]?.createdAt).toBe(insertedValues[0]?.updatedAt);- expect(staleCredentialRevocations).toHaveLength(1);- expect(staleCredentialRevocations[0]?.values.revokedAt).toEqual(- staleCredentialRevocations[0]?.values.updatedAt,- );-- const query = new PgDialect().sqlToQuery(staleCredentialRevocations[0]?.condition as never);- expect(query.sql).toContain('"relay_environment_credentials"."environment_id" = $1');- expect(query.sql).toContain(- '"relay_environment_credentials"."environment_public_key" = $2',- );- expect(query.sql).toContain('"relay_environment_credentials"."credential_id" <> $3');- expect(query.sql).toContain('"relay_environment_credentials"."revoked_at" is null');- expect(query.params).toEqual(["env_test", "environment-public-key", credentialId]);- }).pipe(- Effect.provide(- EnvironmentCredentials.layer.pipe(- Layer.provide(NodeCryptoLayer.layer),- Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb)),- ),- ),- );- },- );-- it.effect("revokes active credentials for an environment public key", () => {- const updateValues: Array<Record<string, unknown>> = [];- const whereConditions: Array<unknown> = [];- const fakeDb = {- update: (table: unknown) => {- expect(table).toBe(relayEnvironmentCredentials);- return {- set: (values: Record<string, unknown>) => {- updateValues.push(values);- return {- where: (condition: unknown) => {- whereConditions.push(condition);- return {- returning: (selection: unknown) => {- expect(selection).toBeDefined();- return Effect.succeed([{ credentialId: "credential-1" }]);- },- };- },- };- },- };- },- } as unknown as RelayDb.RelayDb["Service"];-- return Effect.gen(function* () {- const credentials = yield* EnvironmentCredentials.EnvironmentCredentials;- const revoked = yield* credentials.revokeForEnvironmentPublicKey({- environmentId: "env_test",- environmentPublicKey: "environment-public-key",- });-- expect(revoked).toBe(true);- expect(updateValues).toHaveLength(1);- expect(updateValues[0]?.revokedAt).toEqual(updateValues[0]?.updatedAt);- expect(whereConditions).toHaveLength(1);-- const query = new PgDialect().sqlToQuery(whereConditions[0] as never);- expect(query.sql).toContain('"relay_environment_credentials"."environment_id" = $1');- expect(query.sql).toContain('"relay_environment_credentials"."environment_public_key" = $2');- expect(query.sql).toContain('"relay_environment_credentials"."revoked_at" is null');- expect(query.sql).toContain("not exists");- expect(query.sql).toContain('"relay_environment_links"."environment_id" = $3');- expect(query.sql).toContain('"relay_environment_links"."environment_public_key" = $4');- expect(query.sql).toContain('"relay_environment_links"."revoked_at" is null');- expect(query.params).toEqual([- "env_test",- "environment-public-key",- "env_test",- "environment-public-key",- ]);- }).pipe(- Effect.provide(- EnvironmentCredentials.layer.pipe(- Layer.provide(NodeCryptoLayer.layer),- Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb)),- ),- ),- );- });-});diff --git a/infra/relay/src/environments/EnvironmentCredentials.ts b/infra/relay/src/environments/EnvironmentCredentials.tsdeleted file mode 100644index 373f894ee..000000000--- a/infra/relay/src/environments/EnvironmentCredentials.ts+++ /dev/null@@ -1,290 +0,0 @@-import * as Context from "effect/Context";-import * as Crypto from "effect/Crypto";-import * as DateTime from "effect/DateTime";-import * as Effect from "effect/Effect";-import * as Encoding from "effect/Encoding";-import * as Layer from "effect/Layer";-import * as Option from "effect/Option";-import * as Schema from "effect/Schema";-import { and, eq, exists, isNull, ne, notExists } from "drizzle-orm";-import { QueryBuilder } from "drizzle-orm/pg-core";--import * as RelayDb from "../db.ts";-import { relayEnvironmentCredentials, relayEnvironmentLinks } from "../persistence/schema.ts";--export class EnvironmentCredentialCreatePersistenceError extends Schema.TaggedErrorClass<EnvironmentCredentialCreatePersistenceError>()(- "EnvironmentCredentialCreatePersistenceError",- {- stage: Schema.Literals([- "generate-credential",- "hash-token",- "insert-credential",- "revoke-previous-credentials",- ]),- environmentId: Schema.String,- credentialId: Schema.optionalKey(Schema.String),- cause: Schema.Defect(),- },-) {- override get message(): string {- return `Environment credential creation failed during '${this.stage}' for environment '${this.environmentId}'${this.credentialId === undefined ? "" : `, credential '${this.credentialId}'`}`;- }-}--export class EnvironmentCredentialAuthenticatePersistenceError extends Schema.TaggedErrorClass<EnvironmentCredentialAuthenticatePersistenceError>()(- "EnvironmentCredentialAuthenticatePersistenceError",- {- stage: Schema.Literals(["hash-token", "lookup-credential"]),- cause: Schema.Defect(),- },-) {- override get message(): string {- return `Environment credential authentication failed during '${this.stage}'`;- }-}--export class EnvironmentCredentialRevokePersistenceError extends Schema.TaggedErrorClass<EnvironmentCredentialRevokePersistenceError>()(- "EnvironmentCredentialRevokePersistenceError",- {- environmentId: Schema.String,- cause: Schema.Defect(),- },-) {- override get message(): string {- return `Failed to revoke credentials for environment '${this.environmentId}'`;- }-}--export interface EnvironmentCredentialPrincipal {- readonly credentialId: string;- readonly environmentId: string;- readonly environmentPublicKey: string;-}--export class EnvironmentCredentials extends Context.Service<- EnvironmentCredentials,- {- readonly create: (input: {- readonly environmentId: string;- readonly environmentPublicKey: string;- }) => Effect.Effect<string, EnvironmentCredentialCreatePersistenceError>;- readonly authenticate: (- token: string,- ) => Effect.Effect<- Option.Option<EnvironmentCredentialPrincipal>,- EnvironmentCredentialAuthenticatePersistenceError- >;- readonly revokeForEnvironmentPublicKey: (input: {- readonly environmentId: string;- readonly environmentPublicKey: string;- }) => Effect.Effect<boolean, EnvironmentCredentialRevokePersistenceError>;- }->()("t3code-relay/environments/EnvironmentCredentials") {}--const make = Effect.gen(function* () {- const db = yield* RelayDb.RelayDb;- const crypto = yield* Crypto.Crypto;- const hashToken = (token: string) =>- crypto- .digest("SHA-256", new TextEncoder().encode(token))- .pipe(Effect.map(Encoding.encodeBase64Url));- const randomTokenPart = (segments: number) =>- Effect.map(Effect.all(Array.from({ length: segments }, () => crypto.randomUUIDv4)), (values) =>- values.join("").replaceAll("-", ""),- );- const makeCredential = Effect.fnUntraced(function* () {- const credentialId = yield* randomTokenPart(2);- const secret = yield* randomTokenPart(3);- return {- credentialId,- token: `t3env_${credentialId}_${secret}`,- };- });-- return EnvironmentCredentials.of({- create: Effect.fn("relay.environment_credentials.create")(function* (input) {- yield* Effect.annotateCurrentSpan({ "relay.environment_id": input.environmentId });- const credential = yield* makeCredential().pipe(- Effect.mapError(- (cause) =>- new EnvironmentCredentialCreatePersistenceError({- stage: "generate-credential",- environmentId: input.environmentId,- cause,- }),- ),- );- const credentialHash = yield* hashToken(credential.token).pipe(- Effect.mapError(- (cause) =>- new EnvironmentCredentialCreatePersistenceError({- stage: "hash-token",- environmentId: input.environmentId,- credentialId: credential.credentialId,- cause,- }),- ),- );- const now = DateTime.formatIso(yield* DateTime.now);- yield* db- .insert(relayEnvironmentCredentials)- .values({- credentialId: credential.credentialId,- environmentId: input.environmentId,- environmentPublicKey: input.environmentPublicKey,- credentialHash,- revokedAt: null,- createdAt: now,- updatedAt: now,- })- .pipe(- Effect.mapError(- (cause) =>- new EnvironmentCredentialCreatePersistenceError({- stage: "insert-credential",- environmentId: input.environmentId,- credentialId: credential.credentialId,- cause,- }),- ),- );- yield* db- .update(relayEnvironmentCredentials)- .set({- revokedAt: now,- updatedAt: now,- })- .where(- and(- eq(relayEnvironmentCredentials.environmentId, input.environmentId),- eq(relayEnvironmentCredentials.environmentPublicKey, input.environmentPublicKey),- ne(relayEnvironmentCredentials.credentialId, credential.credentialId),- isNull(relayEnvironmentCredentials.revokedAt),- ),- )- .pipe(- Effect.mapError(- (cause) =>- new EnvironmentCredentialCreatePersistenceError({- stage: "revoke-previous-credentials",- environmentId: input.environmentId,- credentialId: credential.credentialId,- cause,- }),- ),- );- return credential.token;- }),-- authenticate: Effect.fn("relay.environment_credentials.authenticate")(function* (token) {- const credentialHash = yield* hashToken(token).pipe(- Effect.mapError(- (cause) =>- new EnvironmentCredentialAuthenticatePersistenceError({- stage: "hash-token",- cause,- }),- ),- );- const rows = yield* db- .select({- credentialId: relayEnvironmentCredentials.credentialId,- environmentId: relayEnvironmentCredentials.environmentId,- environmentPublicKey: relayEnvironmentCredentials.environmentPublicKey,- })- .from(relayEnvironmentCredentials)- .where(- and(- eq(relayEnvironmentCredentials.credentialHash, credentialHash),- isNull(relayEnvironmentCredentials.revokedAt),- exists(- new QueryBuilder()- .select({ userId: relayEnvironmentLinks.userId })- .from(relayEnvironmentLinks)- .where(- and(- eq(- relayEnvironmentLinks.environmentId,- relayEnvironmentCredentials.environmentId,- ),- eq(- relayEnvironmentLinks.environmentPublicKey,- relayEnvironmentCredentials.environmentPublicKey,- ),- isNull(relayEnvironmentLinks.revokedAt),- ),- ),- ),- ),- )- .limit(1)- .pipe(- Effect.mapError(- (cause) =>- new EnvironmentCredentialAuthenticatePersistenceError({- stage: "lookup-credential",- cause,- }),- ),- );- const row = rows[0];- if (row) {- yield* Effect.annotateCurrentSpan({ "relay.environment_id": row.environmentId });- }- return row- ? Option.some({- credentialId: row.credentialId,- environmentId: row.environmentId,- environmentPublicKey: row.environmentPublicKey,- })- : Option.none();- }),-- revokeForEnvironmentPublicKey: Effect.fn(- "relay.environment_credentials.revoke_for_environment_public_key",- )(function* (input) {- yield* Effect.annotateCurrentSpan({ "relay.environment_id": input.environmentId });- const revokedAt = DateTime.formatIso(yield* DateTime.now);- const rows = yield* db- .update(relayEnvironmentCredentials)- .set({- revokedAt,- updatedAt: revokedAt,- })- .where(- and(- eq(relayEnvironmentCredentials.environmentId, input.environmentId),- eq(relayEnvironmentCredentials.environmentPublicKey, input.environmentPublicKey),- isNull(relayEnvironmentCredentials.revokedAt),- notExists(- new QueryBuilder()- .select({ userId: relayEnvironmentLinks.userId })- .from(relayEnvironmentLinks)- .where(- and(- eq(relayEnvironmentLinks.environmentId, input.environmentId),- eq(relayEnvironmentLinks.environmentPublicKey, input.environmentPublicKey),- isNull(relayEnvironmentLinks.revokedAt),- ),- ),- ),- ),- )- .returning({- credentialId: relayEnvironmentCredentials.credentialId,- })- .pipe(- Effect.mapError(- (cause) =>- new EnvironmentCredentialRevokePersistenceError({- environmentId: input.environmentId,- cause,- }),- ),- );- return rows.length > 0;- }),- });-});--export const layer = Layer.effect(EnvironmentCredentials, make);diff --git a/infra/relay/src/environments/EnvironmentLinker.test.ts b/infra/relay/src/environments/EnvironmentLinker.test.tsdeleted file mode 100644index c0811e82d..000000000--- a/infra/relay/src/environments/EnvironmentLinker.test.ts+++ /dev/null@@ -1,307 +0,0 @@-import * as NodeCrypto from "node:crypto";-import type {- RelayEnvironmentLinkProofPayload,- RelayEnvironmentLinkRequest,-} from "@t3tools/contracts/relay";-import { RELAY_LINK_PROOF_TYP } from "@t3tools/shared/relayJwt";-import { describe, expect, it } from "@effect/vitest";-import * as DateTime from "effect/DateTime";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";-import * as Redacted from "effect/Redacted";-import * as Result from "effect/Result";-import * as Schema from "effect/Schema";--import * as DpopProofs from "../auth/DpopProofs.ts";-import * as RelayTokens from "../auth/RelayTokens.ts";-import * as EnvironmentCredentials from "./EnvironmentCredentials.ts";-import * as EnvironmentLinks from "./EnvironmentLinks.ts";-import * as RelayConfiguration from "../Config.ts";-import * as EnvironmentLinker from "./EnvironmentLinker.ts";-import * as ManagedEndpointProvider from "./ManagedEndpointProvider.ts";--const relayKeyPair = NodeCrypto.generateKeyPairSync("ed25519", {- privateKeyEncoding: { format: "pem", type: "pkcs8" },- publicKeyEncoding: { format: "pem", type: "spki" },-});-const environmentKeyPair = NodeCrypto.generateKeyPairSync("ed25519", {- privateKeyEncoding: { format: "pem", type: "pkcs8" },- publicKeyEncoding: { format: "pem", type: "spki" },-});-const config = RelayConfiguration.RelayConfiguration.of({- relayIssuer: "https://relay.example.test",- apns: {- environment: "sandbox",- teamId: "team-id",- keyId: "key-id",- privateKey: Redacted.make("private-key"),- bundleId: "com.t3tools.t3code.dev",- },- apnsDeliveryJobSigningSecret: Redacted.make("job-secret"),- clerkSecretKey: Redacted.make("clerk-secret"),- clerkPublishableKey: "pk_test_test",- clerkJwtAudience: "t3-code-relay",- cloudMintPrivateKey: Redacted.make(relayKeyPair.privateKey),- cloudMintPublicKey: relayKeyPair.publicKey,- managedEndpointBaseDomain: undefined,- managedEndpointNamespace: undefined,-});-const isEnvironmentLinkProofInvalid = Schema.is(EnvironmentLinker.EnvironmentLinkProofInvalid);--function signTestJwt(payload: object, typ: string, privateKey: string): string {- const header = Buffer.from(JSON.stringify({ alg: "EdDSA", typ })).toString("base64url");- const encodedPayload = Buffer.from(JSON.stringify(payload)).toString("base64url");- const signingInput = `${header}.${encodedPayload}`;- return `${signingInput}.${NodeCrypto.sign(null, Buffer.from(signingInput), privateKey).toString("base64url")}`;-}--const makeRequest = Effect.gen(function* () {- const now = yield* DateTime.now;- const expiresAt = DateTime.add(now, { minutes: 5 });- const relayTokens = yield* RelayTokens.RelayTokens;- const challenge = yield* relayTokens.issueLinkChallenge({- userId: "user_123",- request: {- notificationsEnabled: true,- liveActivitiesEnabled: true,- managedTunnelsEnabled: true,- },- jti: "challenge-jti",- issuedAtEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),- expiresAtEpochSeconds: Math.floor(expiresAt.epochMilliseconds / 1_000),- });- const payload = {- iss: "t3-env:env-link-test",- aud: "https://relay.example.test",- sub: "env-link-test",- jti: "link-proof-jti",- iat: Math.floor(now.epochMilliseconds / 1_000),- exp: Math.floor(expiresAt.epochMilliseconds / 1_000),- challenge,- environmentId: "env-link-test" as RelayEnvironmentLinkProofPayload["environmentId"],- descriptor: {- environmentId: "env-link-test" as RelayEnvironmentLinkProofPayload["environmentId"],- label: "Link Test Environment",- platform: { os: "darwin", arch: "arm64" },- serverVersion: "0.0.0-test",- capabilities: { repositoryIdentity: true },- },- environmentPublicKey: environmentKeyPair.publicKey.trim(),- endpoint: {- httpBaseUrl: "https://env.example.test/",- wsBaseUrl: "wss://env.example.test/",- providerKind: "manual",- },- origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },- scopes: ["agent_activity_notifications", "managed_tunnels"],- } satisfies RelayEnvironmentLinkProofPayload;- return {- request: {- proof: signTestJwt(payload, RELAY_LINK_PROOF_TYP, environmentKeyPair.privateKey),- notificationsEnabled: true,- liveActivitiesEnabled: true,- managedTunnelsEnabled: false,- } satisfies RelayEnvironmentLinkRequest,- payload,- };-});--function testLayer(input?: {- readonly upsert?: EnvironmentLinks.EnvironmentLinks["Service"]["upsert"];- readonly consume?: DpopProofs.DpopProofReplay["Service"]["consume"];- readonly deprovision?: ManagedEndpointProvider.ManagedEndpointProvider["Service"]["deprovision"];-}) {- return EnvironmentLinker.layer.pipe(- Layer.provideMerge(RelayTokens.layer),- Layer.provide(- Layer.mergeAll(- RelayConfiguration.layer(config),- Layer.succeed(DpopProofs.DpopProofReplay, {- verifyAndConsume: () => Effect.die("unexpected DPoP proof verification"),- consume: input?.consume ?? (() => Effect.succeed(true)),- pruneExpired: Effect.void,- }),- Layer.succeed(EnvironmentLinks.EnvironmentLinks, {- upsert: input?.upsert ?? (() => Effect.void),- listUsersForEnvironment: () => Effect.succeed([]),- listDeliveryUsersForEnvironment: () => Effect.succeed([]),- listPublicKeysForEnvironment: () => Effect.succeed([]),- listForUser: () => Effect.succeed([]),- getForUser: () => Effect.succeed(null),- revokeForUser: () => Effect.succeed(false),- }),- Layer.succeed(EnvironmentCredentials.EnvironmentCredentials, {- create: () => Effect.succeed("t3env_credential_secret"),- authenticate: () => Effect.succeedNone,- revokeForEnvironmentPublicKey: () => Effect.succeed(false),- }),- Layer.succeed(ManagedEndpointProvider.ManagedEndpointProvider, {- prepareDeprovision: () => Effect.succeed(null),- deprovision: input?.deprovision ?? (() => Effect.void),- release: () => Effect.succeed(true),- provision: () =>- Effect.succeed({- endpoint: {- httpBaseUrl: "https://managed.example.test/",- wsBaseUrl: "wss://managed.example.test/ws",- providerKind: "cloudflare_tunnel",- },- runtime: { providerKind: "cloudflare_tunnel", connectorToken: "connector-token" },- }),- }),- ),- ),- );-}--describe("EnvironmentLinker", () => {- it.effect("uses verified JWT claims when linking an environment", () => {- let persistedEnvironmentId: string | null = null;- return Effect.gen(function* () {- const { request, payload } = yield* makeRequest;- const linker = yield* EnvironmentLinker.EnvironmentLinker;- const result = yield* linker.link({ userId: "user_123", request });- expect(result.environmentId).toBe(payload.environmentId);- expect(result.environmentCredential).toBe("t3env_credential_secret");- expect(persistedEnvironmentId).toBe(payload.environmentId);- }).pipe(- Effect.provide(- testLayer({- upsert: (input) =>- Effect.sync(() => {- persistedEnvironmentId = input.proof.environmentId;- }),- }),- ),- );- });-- it.effect("links a publish-only environment with a non-secure nominal endpoint", () => {- let persistedEndpoint: string | null = null;- let deprovisionedEnvironmentId: string | null = null;- return Effect.gen(function* () {- const now = yield* DateTime.now;- const expiresAt = DateTime.add(now, { minutes: 5 });- const relayTokens = yield* RelayTokens.RelayTokens;- const challenge = yield* relayTokens.issueLinkChallenge({- userId: "user_123",- request: {- notificationsEnabled: true,- liveActivitiesEnabled: true,- managedTunnelsEnabled: false,- },- jti: "publish-only-challenge-jti",- issuedAtEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),- expiresAtEpochSeconds: Math.floor(expiresAt.epochMilliseconds / 1_000),- });- const payload = {- iss: "t3-env:env-link-test",- aud: "https://relay.example.test",- sub: "env-link-test",- jti: "publish-only-proof-jti",- iat: Math.floor(now.epochMilliseconds / 1_000),- exp: Math.floor(expiresAt.epochMilliseconds / 1_000),- challenge,- environmentId: "env-link-test" as RelayEnvironmentLinkProofPayload["environmentId"],- descriptor: {- environmentId: "env-link-test" as RelayEnvironmentLinkProofPayload["environmentId"],- label: "Link Test Environment",- platform: { os: "darwin", arch: "arm64" },- serverVersion: "0.0.0-test",- capabilities: { repositoryIdentity: true },- },- environmentPublicKey: environmentKeyPair.publicKey.trim(),- endpoint: {- httpBaseUrl: "http://127.0.0.1:3773/",- wsBaseUrl: "ws://127.0.0.1:3773/",- providerKind: "manual",- },- origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },- scopes: ["agent_activity_notifications"],- } satisfies RelayEnvironmentLinkProofPayload;- const request = {- proof: signTestJwt(payload, RELAY_LINK_PROOF_TYP, environmentKeyPair.privateKey),- notificationsEnabled: true,- liveActivitiesEnabled: true,- managedTunnelsEnabled: false,- } satisfies RelayEnvironmentLinkRequest;- const linker = yield* EnvironmentLinker.EnvironmentLinker;- const result = yield* linker.link({ userId: "user_123", request });- expect(result.environmentCredential).toBe("t3env_credential_secret");- expect(result.endpointRuntime).toBeNull();- expect(persistedEndpoint).toBe("http://127.0.0.1:3773/");- // Downgrading from a managed link must release the previously provisioned- // tunnel; nothing else cleans it up before a full unlink.- expect(deprovisionedEnvironmentId).toBe("env-link-test");- }).pipe(- Effect.provide(- testLayer({- upsert: (input) =>- Effect.sync(() => {- persistedEndpoint = input.endpoint.httpBaseUrl;- }),- deprovision: (input) =>- Effect.sync(() => {- deprovisionedEnvironmentId = input.environmentId;- }),- }),- ),- );- });-- it.effect("rejects a tampered compact proof before persistence", () => {- let persisted = false;- return Effect.gen(function* () {- const { request } = yield* makeRequest;- const segments = request.proof.split(".");- const signature = segments[2]!;- segments[2] = `${signature.startsWith("A") ? "B" : "A"}${signature.slice(1)}`;- const tampered = { ...request, proof: segments.join(".") };- const linker = yield* EnvironmentLinker.EnvironmentLinker;- const result = yield* Effect.result(linker.link({ userId: "user_123", request: tampered }));- expect(Result.isFailure(result)).toBe(true);- if (Result.isFailure(result)) {- expect(isEnvironmentLinkProofInvalid(result.failure)).toBe(true);- if (isEnvironmentLinkProofInvalid(result.failure)) {- expect(result.failure).toMatchObject({- userId: "user_123",- environmentId: "env-link-test",- reason: "invalid_signature_or_scope",- stage: "verify_proof",- cause: { _tag: "RelayJwtError" },- });- }- }- expect(persisted).toBe(false);- }).pipe(- Effect.provide(- testLayer({- upsert: () =>- Effect.sync(() => {- persisted = true;- }),- }),- ),- );- });-- it.effect("rejects replayed JWT ids", () =>- Effect.gen(function* () {- const { request } = yield* makeRequest;- const linker = yield* EnvironmentLinker.EnvironmentLinker;- const result = yield* Effect.result(linker.link({ userId: "user_123", request }));- expect(Result.isFailure(result)).toBe(true);- if (Result.isFailure(result)) {- expect(isEnvironmentLinkProofInvalid(result.failure)).toBe(true);- if (isEnvironmentLinkProofInvalid(result.failure)) {- expect(result.failure).toMatchObject({- userId: "user_123",- environmentId: "env-link-test",- reason: "replayed_nonce",- stage: "consume_proof_nonce",- });- }- }- }).pipe(Effect.provide(testLayer({ consume: () => Effect.succeed(false) }))),- );-});diff --git a/infra/relay/src/environments/EnvironmentLinker.ts b/infra/relay/src/environments/EnvironmentLinker.tsdeleted file mode 100644index fbfdc6428..000000000--- a/infra/relay/src/environments/EnvironmentLinker.ts+++ /dev/null@@ -1,346 +0,0 @@-import {- RelayEnvironmentLinkProofPayload,- RelayEnvironmentLinkProofInvalidReason,- type RelayEnvironmentLinkRequest,-} from "@t3tools/contracts/relay";-import {- decodeRelayJwt,- normalizeRelayIssuer,- RELAY_LINK_PROOF_TYP,- verifyRelayJwt,-} from "@t3tools/shared/relayJwt";-import * as Context from "effect/Context";-import * as DateTime from "effect/DateTime";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";-import * as Schema from "effect/Schema";--import * as DpopProofs from "../auth/DpopProofs.ts";-import * as RelayTokens from "../auth/RelayTokens.ts";-import * as EnvironmentCredentials from "./EnvironmentCredentials.ts";-import * as EnvironmentLinks from "./EnvironmentLinks.ts";-import * as ManagedEndpointProvider from "./ManagedEndpointProvider.ts";-import * as RelayConfiguration from "../Config.ts";--export class EnvironmentLinkProofExpired extends Schema.TaggedErrorClass<EnvironmentLinkProofExpired>()(- "EnvironmentLinkProofExpired",- {- userId: Schema.String,- environmentId: Schema.String,- expiresAt: Schema.String,- },-) {- override get message(): string {- return `Environment '${this.environmentId}' link proof expired at ${this.expiresAt}`;- }-}--export class EnvironmentLinkProofInvalid extends Schema.TaggedErrorClass<EnvironmentLinkProofInvalid>()(- "EnvironmentLinkProofInvalid",- {- userId: Schema.String,- environmentId: Schema.String,- reason: RelayEnvironmentLinkProofInvalidReason,- stage: Schema.Literals([- "decode_token",- "decode_payload",- "verify_proof",- "authorize_capabilities",- "validate_descriptor",- "verify_challenge",- "validate_expiration",- "consume_proof_nonce",- "consume_challenge_nonce",- "validate_origin",- "validate_endpoint",- ]),- cause: Schema.optional(Schema.Defect()),- },-) {- override get message(): string {- return `Environment '${this.environmentId}' link proof is invalid during ${this.stage}: ${this.reason}`;- }-}--export type EnvironmentLinkError =- | EnvironmentLinkProofExpired- | EnvironmentLinkProofInvalid- | DpopProofs.DpopProofReplayPersistenceError- | EnvironmentLinks.EnvironmentLinkUpsertPersistenceError- | EnvironmentCredentials.EnvironmentCredentialCreatePersistenceError- | ManagedEndpointProvider.ManagedEndpointProviderError;--export class EnvironmentLinker extends Context.Service<- EnvironmentLinker,- {- readonly link: (input: {- readonly userId: string;- readonly request: RelayEnvironmentLinkRequest;- }) => Effect.Effect<- {- readonly environmentId: RelayEnvironmentLinkProofPayload["environmentId"];- readonly endpoint: RelayEnvironmentLinkProofPayload["endpoint"];- readonly endpointRuntime:- | ManagedEndpointProvider.ManagedEndpointProvisioningResult["runtime"]- | null;- readonly environmentCredential: string;- },- EnvironmentLinkError- >;- }->()("t3code-relay/environments/EnvironmentLinker") {}--const decodeProof = Schema.decodeUnknownEffect(RelayEnvironmentLinkProofPayload);--function proofAuthorizesRequestedCapabilities(- proof: RelayEnvironmentLinkProofPayload,- request: RelayEnvironmentLinkRequest,-): boolean {- const scopes = new Set(proof.scopes);- if (request.managedTunnelsEnabled && !scopes.has("managed_tunnels")) {- return false;- }- return !(- (request.notificationsEnabled || request.liveActivitiesEnabled) &&- !scopes.has("agent_activity_notifications")- );-}--function isSecureManagedEndpoint(endpoint: RelayEnvironmentLinkProofPayload["endpoint"]): boolean {- try {- const httpUrl = new URL(endpoint.httpBaseUrl);- const wsUrl = new URL(endpoint.wsBaseUrl);- return httpUrl.protocol === "https:" && wsUrl.protocol === "wss:";- } catch {- return false;- }-}--function normalizeHostname(hostname: string): string {- return hostname- .trim()- .toLowerCase()- .replace(/^\[(.*)\]$/u, "$1");-}--function isLoopbackManagedTunnelOrigin(- origin: RelayEnvironmentLinkProofPayload["origin"],-): boolean {- const hostname = normalizeHostname(origin.localHttpHost);- return (- (hostname === "127.0.0.1" || hostname === "::1" || hostname === "localhost") &&- Number.isInteger(origin.localHttpPort) &&- origin.localHttpPort > 0 &&- origin.localHttpPort <= 65_535- );-}--const make = Effect.gen(function* () {- const links = yield* EnvironmentLinks.EnvironmentLinks;- const credentials = yield* EnvironmentCredentials.EnvironmentCredentials;- const managedEndpointProvider = yield* ManagedEndpointProvider.ManagedEndpointProvider;- const proofReplay = yield* DpopProofs.DpopProofReplay;- const relayTokens = yield* RelayTokens.RelayTokens;- const config = yield* RelayConfiguration.RelayConfiguration;-- return EnvironmentLinker.of({- link: Effect.fn("relay.environment_linker.link")(function* (input) {- const now = yield* DateTime.now;- const nowSeconds = Math.floor(now.epochMilliseconds / 1_000);- const unverified = yield* Effect.try({- try: () => decodeRelayJwt(input.request.proof),- catch: (cause) =>- new EnvironmentLinkProofInvalid({- userId: input.userId,- environmentId: "unknown",- reason: "invalid_signature_or_scope",- stage: "decode_token",- cause,- }),- });- const candidate = yield* decodeProof(unverified).pipe(- Effect.mapError(- (cause) =>- new EnvironmentLinkProofInvalid({- userId: input.userId,- environmentId: "unknown",- reason: "invalid_signature_or_scope",- stage: "decode_payload",- cause,- }),- ),- );- yield* Effect.annotateCurrentSpan({- "relay.environment_id": candidate.environmentId,- "relay.link.notifications_enabled": input.request.notificationsEnabled,- "relay.link.live_activities_enabled": input.request.liveActivitiesEnabled,- "relay.link.managed_tunnels_enabled": input.request.managedTunnelsEnabled,- });- if (candidate.exp <= nowSeconds) {- return yield* new EnvironmentLinkProofExpired({- userId: input.userId,- environmentId: candidate.environmentId,- expiresAt: DateTime.formatIso(DateTime.makeUnsafe(candidate.exp * 1_000)),- });- }- const issuer = `t3-env:${candidate.environmentId}`;- const relayIssuer = normalizeRelayIssuer(config.relayIssuer);- const verified = yield* verifyRelayJwt({- publicKey: candidate.environmentPublicKey,- token: input.request.proof,- typ: RELAY_LINK_PROOF_TYP,- issuer,- audience: relayIssuer,- nowEpochSeconds: nowSeconds,- }).pipe(- Effect.flatMap(decodeProof),- Effect.mapError(- (cause) =>- new EnvironmentLinkProofInvalid({- userId: input.userId,- environmentId: candidate.environmentId,- reason: "invalid_signature_or_scope",- stage: "verify_proof",- cause,- }),- ),- );- if (- verified.sub !== verified.environmentId ||- !proofAuthorizesRequestedCapabilities(verified, input.request)- ) {- return yield* new EnvironmentLinkProofInvalid({- userId: input.userId,- environmentId: candidate.environmentId,- reason: "invalid_signature_or_scope",- stage: "authorize_capabilities",- });- }- if (verified.descriptor.environmentId !== verified.environmentId) {- return yield* new EnvironmentLinkProofInvalid({- userId: input.userId,- environmentId: verified.environmentId,- reason: "descriptor_mismatch",- stage: "validate_descriptor",- });- }- const challenge = yield* relayTokens.verifyLinkChallenge({- token: verified.challenge,- userId: input.userId,- request: {- notificationsEnabled: input.request.notificationsEnabled,- liveActivitiesEnabled: input.request.liveActivitiesEnabled,- managedTunnelsEnabled: input.request.managedTunnelsEnabled,- },- nowEpochSeconds: nowSeconds,- });- if (challenge === null) {- return yield* new EnvironmentLinkProofInvalid({- userId: input.userId,- environmentId: verified.environmentId,- reason: "challenge_invalid",- stage: "verify_challenge",- });- }- const expiresAt = DateTime.make(verified.exp * 1_000);- if (expiresAt._tag === "None") {- return yield* new EnvironmentLinkProofInvalid({- userId: input.userId,- environmentId: verified.environmentId,- reason: "invalid_signature_or_scope",- stage: "validate_expiration",- });- }- const consumedNonce = yield* proofReplay.consume({- thumbprint: verified.environmentPublicKey,- jti: verified.jti,- iat: verified.iat,- expiresAt: expiresAt.value,- });- if (!consumedNonce) {- return yield* new EnvironmentLinkProofInvalid({- userId: input.userId,- environmentId: verified.environmentId,- reason: "replayed_nonce",- stage: "consume_proof_nonce",- });- }- const consumedChallenge = yield* proofReplay.consume({- thumbprint: "relay-environment-link-challenge",- jti: challenge.jti,- iat: challenge.iat,- expiresAt: expiresAt.value,- });- if (!consumedChallenge) {- return yield* new EnvironmentLinkProofInvalid({- userId: input.userId,- environmentId: verified.environmentId,- reason: "challenge_invalid",- stage: "consume_challenge_nonce",- });- }- if (input.request.managedTunnelsEnabled && !isLoopbackManagedTunnelOrigin(verified.origin)) {- return yield* new EnvironmentLinkProofInvalid({- userId: input.userId,- environmentId: verified.environmentId,- reason: "origin_not_allowed",- stage: "validate_origin",- });- }- // Downgrading a managed link to publish-only must release the tunnel and- // DNS that were provisioned for it — nothing else cleans them up until a- // full unlink. Best effort: a cleanup failure must not block the link- // itself, and the provider treats an absent allocation as already- // deprovisioned, so retrying on every non-tunnel link is cheap.- if (!input.request.managedTunnelsEnabled) {- yield* managedEndpointProvider- .deprovision({- userId: input.userId,- environmentId: verified.environmentId,- })- .pipe(- Effect.tapError((error) =>- Effect.logWarning("managed endpoint deprovision on publish-only link failed", {- environmentId: verified.environmentId,- errorTag: error._tag,- }),- ),- Effect.ignore,- );- }- const provisioned = input.request.managedTunnelsEnabled- ? yield* managedEndpointProvider.provision({- userId: input.userId,- environmentId: verified.environmentId,- origin: verified.origin,- })- : null;- const endpoint = provisioned?.endpoint ?? verified.endpoint;- // The secure-endpoint requirement only matters when the relay advertises- // this endpoint for other devices to reach (managed tunnel). Publish-only- // links are reached out of band (e.g. Tailscale) and their stored endpoint- // is never used for routing, so a nominal endpoint is acceptable.- if (input.request.managedTunnelsEnabled && !isSecureManagedEndpoint(endpoint)) {- return yield* new EnvironmentLinkProofInvalid({- userId: input.userId,- environmentId: verified.environmentId,- reason: "endpoint_not_secure",- stage: "validate_endpoint",- });- }- yield* links.upsert({ ...input, proof: verified, endpoint });- const environmentCredential = yield* credentials.create({- environmentId: verified.environmentId,- environmentPublicKey: verified.environmentPublicKey,- });- return {- environmentId: verified.environmentId,- endpoint,- endpointRuntime: provisioned?.runtime ?? null,- environmentCredential,- };- }),- });-});--export const layer = Layer.effect(EnvironmentLinker, make);diff --git a/infra/relay/src/environments/EnvironmentLinks.test.ts b/infra/relay/src/environments/EnvironmentLinks.test.tsdeleted file mode 100644index dccb9e39f..000000000--- a/infra/relay/src/environments/EnvironmentLinks.test.ts+++ /dev/null@@ -1,169 +0,0 @@-import { describe, expect, it } from "@effect/vitest";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";-import { PgDialect } from "drizzle-orm/pg-core";--import * as RelayDb from "../db.ts";-import { relayEnvironmentLinks } from "../persistence/schema.ts";-import * as EnvironmentLinks from "./EnvironmentLinks.ts";--describe("EnvironmentLinks", () => {- it.effect("retains link lookup failures with user and environment identity", () => {- const cause = new Error("database unavailable");- const fakeDb = {- select: () => ({- from: (table: unknown) => {- expect(table).toBe(relayEnvironmentLinks);- return {- where: () => ({- limit: () => Effect.fail(cause),- }),- };- },- }),- } as unknown as RelayDb.RelayDb["Service"];-- return Effect.gen(function* () {- const links = yield* EnvironmentLinks.EnvironmentLinks;- const error = yield* Effect.flip(- links.getForUser({ userId: "user-1", environmentId: "env-1" }),- );-- expect(error).toMatchObject({- _tag: "EnvironmentLinkLookupPersistenceError",- userId: "user-1",- environmentId: "env-1",- });- expect(error.cause).toBe(cause);- }).pipe(- Effect.provide(- EnvironmentLinks.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb))),- ),- );- });-- it.effect("identifies delivery-user list failures without retaining key material", () => {- const cause = new Error("database unavailable");- const fakeDb = {- select: () => ({- from: (table: unknown) => {- expect(table).toBe(relayEnvironmentLinks);- return {- where: () => Effect.fail(cause),- };- },- }),- } as unknown as RelayDb.RelayDb["Service"];-- return Effect.gen(function* () {- const links = yield* EnvironmentLinks.EnvironmentLinks;- const error = yield* Effect.flip(- links.listDeliveryUsersForEnvironment({- environmentId: "env-1",- environmentPublicKey: "sensitive-public-key-material",- }),- );-- expect(error).toMatchObject({- _tag: "EnvironmentLinkUserListPersistenceError",- operation: "list-delivery-users",- environmentId: "env-1",- });- expect(error.cause).toBe(cause);- expect(error).not.toHaveProperty("environmentPublicKey");- }).pipe(- Effect.provide(- EnvironmentLinks.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb))),- ),- );- });-- it.effect("selects users when either notifications or Live Activities are enabled", () => {- const whereConditions: Array<unknown> = [];- const fakeDb = {- select: (selection: unknown) => {- expect(selection).toBeDefined();- return {- from: (table: unknown) => {- expect(table).toBe(relayEnvironmentLinks);- return {- where: (condition: unknown) => {- whereConditions.push(condition);- return Effect.succeed([]);- },- };- },- };- },- } as unknown as RelayDb.RelayDb["Service"];-- return Effect.gen(function* () {- const links = yield* EnvironmentLinks.EnvironmentLinks;- expect(yield* links.listUsersForEnvironment({ environmentId: "env-1" })).toEqual([]);- expect(whereConditions).toHaveLength(1);-- const query = new PgDialect().sqlToQuery(whereConditions[0] as never);- expect(query.sql).toContain('"relay_environment_links"."environment_id" = $1');- expect(query.sql).toContain('"relay_environment_links"."revoked_at" is null');- expect(query.sql).toContain('"relay_environment_links"."notifications_enabled" = $2');- expect(query.sql).toContain('"relay_environment_links"."live_activities_enabled" = $3');- expect(query.sql).toContain(" or ");- expect(query.params).toEqual(["env-1", true, true]);- }).pipe(- Effect.provide(- EnvironmentLinks.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb))),- ),- );- });-- it.effect("revokes only the active link owned by the requesting user", () => {- const updateValues: Array<Record<string, unknown>> = [];- const whereConditions: Array<unknown> = [];- const fakeDb = {- update: (table: unknown) => {- expect(table).toBe(relayEnvironmentLinks);- return {- set: (values: Record<string, unknown>) => {- updateValues.push(values);- return {- where: (condition: unknown) => {- whereConditions.push(condition);- return {- returning: (selection: unknown) => {- expect(selection).toBeDefined();- return Effect.succeed([{ environmentId: "env-1" }]);- },- };- },- };- },- };- },- } as unknown as RelayDb.RelayDb["Service"];-- return Effect.gen(function* () {- const links = yield* EnvironmentLinks.EnvironmentLinks;- const revoked = yield* links.revokeForUser({- userId: "user-1",- environmentId: "env-1",- });-- expect(revoked).toBe(true);- expect(updateValues).toHaveLength(1);- expect(updateValues[0]?.revokedAt).toEqual(updateValues[0]?.updatedAt);- expect(typeof updateValues[0]?.revokedAt).toBe("string");- expect(whereConditions).toHaveLength(1);-- const dialect = new PgDialect();- const query = dialect.sqlToQuery(whereConditions[0] as never);- expect(query.sql).toContain('"relay_environment_links"."user_id" = $1');- expect(query.sql).toContain('"relay_environment_links"."environment_id" = $2');- expect(query.sql).toContain('"relay_environment_links"."revoked_at" is null');- expect(query.params).toEqual(["user-1", "env-1"]);- }).pipe(- Effect.provide(- EnvironmentLinks.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb))),- ),- );- });-});diff --git a/infra/relay/src/environments/EnvironmentLinks.ts b/infra/relay/src/environments/EnvironmentLinks.tsdeleted file mode 100644index 6630af0a1..000000000--- a/infra/relay/src/environments/EnvironmentLinks.ts+++ /dev/null@@ -1,433 +0,0 @@-import type {- RelayClientEnvironmentRecord,- RelayEnvironmentLinkProofPayload,- RelayEnvironmentLinkRequest,- RelayManagedEndpoint,-} from "@t3tools/contracts/relay";-import * as Context from "effect/Context";-import * as DateTime from "effect/DateTime";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";-import * as Schema from "effect/Schema";-import { and, eq, isNull, or } from "drizzle-orm";--import * as RelayDb from "../db.ts";-import { relayEnvironmentLinks } from "../persistence/schema.ts";--export interface RelayLinkedEnvironmentRecord extends RelayClientEnvironmentRecord {- readonly environmentPublicKey: string;-}--export interface AgentAwarenessDeliveryUserRecord {- readonly userId: string;- readonly notificationsEnabled: boolean;- readonly liveActivitiesEnabled: boolean;-}--export class EnvironmentLinkUpsertPersistenceError extends Schema.TaggedErrorClass<EnvironmentLinkUpsertPersistenceError>()(- "EnvironmentLinkUpsertPersistenceError",- {- userId: Schema.String,- environmentId: Schema.String,- deviceId: Schema.optionalKey(Schema.String),- cause: Schema.Defect(),- },-) {- override get message(): string {- return `Failed to persist environment link for user '${this.userId}', environment '${this.environmentId}'`;- }-}--export class EnvironmentLinkUserListPersistenceError extends Schema.TaggedErrorClass<EnvironmentLinkUserListPersistenceError>()(- "EnvironmentLinkUserListPersistenceError",- {- operation: Schema.Literals(["list-users", "list-delivery-users"]),- environmentId: Schema.String,- cause: Schema.Defect(),- },-) {- override get message(): string {- return `Environment link user query '${this.operation}' failed for environment '${this.environmentId}'`;- }-}--export class EnvironmentPublicKeyListPersistenceError extends Schema.TaggedErrorClass<EnvironmentPublicKeyListPersistenceError>()(- "EnvironmentPublicKeyListPersistenceError",- {- environmentId: Schema.String,- cause: Schema.Defect(),- },-) {- override get message(): string {- return `Failed to list public keys for environment '${this.environmentId}'`;- }-}--export class EnvironmentLinkListPersistenceError extends Schema.TaggedErrorClass<EnvironmentLinkListPersistenceError>()(- "EnvironmentLinkListPersistenceError",- {- userId: Schema.String,- cause: Schema.Defect(),- },-) {- override get message(): string {- return `Failed to list environment links for user '${this.userId}'`;- }-}--export class EnvironmentLinkLookupPersistenceError extends Schema.TaggedErrorClass<EnvironmentLinkLookupPersistenceError>()(- "EnvironmentLinkLookupPersistenceError",- {- userId: Schema.String,- environmentId: Schema.String,- cause: Schema.Defect(),- },-) {- override get message(): string {- return `Failed to look up environment link for user '${this.userId}', environment '${this.environmentId}'`;- }-}--export class EnvironmentLinkRevokePersistenceError extends Schema.TaggedErrorClass<EnvironmentLinkRevokePersistenceError>()(- "EnvironmentLinkRevokePersistenceError",- {- userId: Schema.String,- environmentId: Schema.String,- cause: Schema.Defect(),- },-) {- override get message(): string {- return `Failed to revoke environment link for user '${this.userId}', environment '${this.environmentId}'`;- }-}--export class EnvironmentLinks extends Context.Service<- EnvironmentLinks,- {- readonly upsert: (input: {- readonly userId: string;- readonly request: RelayEnvironmentLinkRequest;- readonly proof: RelayEnvironmentLinkProofPayload;- readonly endpoint: RelayManagedEndpoint;- }) => Effect.Effect<void, EnvironmentLinkUpsertPersistenceError>;- readonly listUsersForEnvironment: (input: {- readonly environmentId: string;- }) => Effect.Effect<ReadonlyArray<string>, EnvironmentLinkUserListPersistenceError>;- readonly listDeliveryUsersForEnvironment: (input: {- readonly environmentId: string;- readonly environmentPublicKey: string;- }) => Effect.Effect<- ReadonlyArray<AgentAwarenessDeliveryUserRecord>,- EnvironmentLinkUserListPersistenceError- >;- readonly listPublicKeysForEnvironment: (input: {- readonly environmentId: string;- }) => Effect.Effect<ReadonlyArray<string>, EnvironmentPublicKeyListPersistenceError>;- readonly listForUser: (input: {- readonly userId: string;- }) => Effect.Effect<- ReadonlyArray<RelayClientEnvironmentRecord>,- EnvironmentLinkListPersistenceError- >;- readonly getForUser: (input: {- readonly userId: string;- readonly environmentId: string;- }) => Effect.Effect<RelayLinkedEnvironmentRecord | null, EnvironmentLinkLookupPersistenceError>;- readonly revokeForUser: (input: {- readonly userId: string;- readonly environmentId: string;- }) => Effect.Effect<boolean, EnvironmentLinkRevokePersistenceError>;- }->()("t3code-relay/environments/EnvironmentLinks") {}--function agentAwarenessDeliveryUserCondition(environmentId: string) {- return and(- eq(relayEnvironmentLinks.environmentId, environmentId),- isNull(relayEnvironmentLinks.revokedAt),- or(- eq(relayEnvironmentLinks.notificationsEnabled, true),- eq(relayEnvironmentLinks.liveActivitiesEnabled, true),- ),- );-}--function agentAwarenessDeliveryUserKeyCondition(input: {- readonly environmentId: string;- readonly environmentPublicKey: string;-}) {- return and(- agentAwarenessDeliveryUserCondition(input.environmentId),- eq(relayEnvironmentLinks.environmentPublicKey, input.environmentPublicKey),- );-}--const make = Effect.gen(function* () {- const db = yield* RelayDb.RelayDb;-- return EnvironmentLinks.of({- upsert: Effect.fn("relay.environment_links.upsert")(function* (input) {- yield* Effect.annotateCurrentSpan({- "relay.environment_id": input.proof.environmentId,- });- const now = DateTime.formatIso(yield* DateTime.now);- const { request, proof } = input;- const environmentId = proof.environmentId;- const { endpoint } = input;- yield* db- .insert(relayEnvironmentLinks)- .values({- userId: input.userId,- environmentId,- environmentLabel: proof.descriptor.label,- environmentPublicKey: proof.environmentPublicKey,- endpointHttpBaseUrl: endpoint.httpBaseUrl,- endpointWsBaseUrl: endpoint.wsBaseUrl,- endpointProviderKind: endpoint.providerKind,- notificationsEnabled: request.notificationsEnabled,- liveActivitiesEnabled: request.liveActivitiesEnabled,- managedTunnelsEnabled: request.managedTunnelsEnabled,- createdByDeviceId: request.deviceId ?? null,- revokedAt: null,- createdAt: now,- updatedAt: now,- })- .onConflictDoUpdate({- target: [relayEnvironmentLinks.userId, relayEnvironmentLinks.environmentId],- set: {- environmentPublicKey: proof.environmentPublicKey,- environmentLabel: proof.descriptor.label,- endpointHttpBaseUrl: endpoint.httpBaseUrl,- endpointWsBaseUrl: endpoint.wsBaseUrl,- endpointProviderKind: endpoint.providerKind,- notificationsEnabled: request.notificationsEnabled,- liveActivitiesEnabled: request.liveActivitiesEnabled,- managedTunnelsEnabled: request.managedTunnelsEnabled,- createdByDeviceId: request.deviceId ?? null,- revokedAt: null,- updatedAt: now,- },- })- .pipe(- Effect.mapError(- (cause) =>- new EnvironmentLinkUpsertPersistenceError({- userId: input.userId,- environmentId,- ...(request.deviceId === undefined ? {} : { deviceId: request.deviceId }),- cause,- }),- ),- );- }),-- listUsersForEnvironment: Effect.fn("relay.environment_links.list_users_for_environment")(- function* (input) {- yield* Effect.annotateCurrentSpan({ "relay.environment_id": input.environmentId });- return yield* db- .select({ userId: relayEnvironmentLinks.userId })- .from(relayEnvironmentLinks)- .where(agentAwarenessDeliveryUserCondition(input.environmentId))- .pipe(- Effect.map((rows) => rows.map((row) => row.userId)),- Effect.mapError(- (cause) =>- new EnvironmentLinkUserListPersistenceError({- operation: "list-users",- environmentId: input.environmentId,- cause,- }),- ),- );- },- ),-- listDeliveryUsersForEnvironment: Effect.fn(- "relay.environment_links.list_delivery_users_for_environment",- )(function* (input) {- yield* Effect.annotateCurrentSpan({ "relay.environment_id": input.environmentId });- return yield* db- .select({- userId: relayEnvironmentLinks.userId,- notificationsEnabled: relayEnvironmentLinks.notificationsEnabled,- liveActivitiesEnabled: relayEnvironmentLinks.liveActivitiesEnabled,- })- .from(relayEnvironmentLinks)- .where(agentAwarenessDeliveryUserKeyCondition(input))- .pipe(- Effect.map((rows) =>- rows.map((row) => ({- userId: row.userId,- notificationsEnabled: row.notificationsEnabled,- liveActivitiesEnabled: row.liveActivitiesEnabled,- })),- ),- Effect.mapError(- (cause) =>- new EnvironmentLinkUserListPersistenceError({- operation: "list-delivery-users",- environmentId: input.environmentId,- cause,- }),- ),- );- }),-- listPublicKeysForEnvironment: Effect.fn(- "relay.environment_links.list_public_keys_for_environment",- )(function* (input) {- yield* Effect.annotateCurrentSpan({ "relay.environment_id": input.environmentId });- return yield* db- .select({ environmentPublicKey: relayEnvironmentLinks.environmentPublicKey })- .from(relayEnvironmentLinks)- .where(- and(- eq(relayEnvironmentLinks.environmentId, input.environmentId),- isNull(relayEnvironmentLinks.revokedAt),- ),- )- .pipe(- Effect.map((rows) => [- ...new Set(rows.map((row) => row.environmentPublicKey).filter((key) => key.length > 0)),- ]),- Effect.mapError(- (cause) =>- new EnvironmentPublicKeyListPersistenceError({- environmentId: input.environmentId,- cause,- }),- ),- );- }),-- listForUser: Effect.fn("relay.environment_links.list_for_user")(function* (input) {- return yield* db- .select({- environmentId: relayEnvironmentLinks.environmentId,- environmentLabel: relayEnvironmentLinks.environmentLabel,- endpointHttpBaseUrl: relayEnvironmentLinks.endpointHttpBaseUrl,- endpointWsBaseUrl: relayEnvironmentLinks.endpointWsBaseUrl,- endpointProviderKind: relayEnvironmentLinks.endpointProviderKind,- createdAt: relayEnvironmentLinks.createdAt,- })- .from(relayEnvironmentLinks)- .where(- and(- eq(relayEnvironmentLinks.userId, input.userId),- isNull(relayEnvironmentLinks.revokedAt),- ),- )- .pipe(- Effect.map((rows) =>- rows.map((row) => ({- environmentId: row.environmentId as RelayClientEnvironmentRecord["environmentId"],- label:- row.environmentLabel.trim().length > 0 ? row.environmentLabel : row.environmentId,- endpoint: {- httpBaseUrl: row.endpointHttpBaseUrl,- wsBaseUrl: row.endpointWsBaseUrl,- providerKind:- row.endpointProviderKind as RelayClientEnvironmentRecord["endpoint"]["providerKind"],- },- linkedAt: row.createdAt,- })),- ),- Effect.mapError(- (cause) =>- new EnvironmentLinkListPersistenceError({- userId: input.userId,- cause,- }),- ),- );- }),-- getForUser: Effect.fn("relay.environment_links.get_for_user")(function* (input) {- yield* Effect.annotateCurrentSpan({- "relay.environment_id": input.environmentId,- });- return yield* db- .select({- environmentId: relayEnvironmentLinks.environmentId,- environmentLabel: relayEnvironmentLinks.environmentLabel,- environmentPublicKey: relayEnvironmentLinks.environmentPublicKey,- endpointHttpBaseUrl: relayEnvironmentLinks.endpointHttpBaseUrl,- endpointWsBaseUrl: relayEnvironmentLinks.endpointWsBaseUrl,- endpointProviderKind: relayEnvironmentLinks.endpointProviderKind,- createdAt: relayEnvironmentLinks.createdAt,- })- .from(relayEnvironmentLinks)- .where(- and(- eq(relayEnvironmentLinks.userId, input.userId),- eq(relayEnvironmentLinks.environmentId, input.environmentId),- isNull(relayEnvironmentLinks.revokedAt),- ),- )- .limit(1)- .pipe(- Effect.map((rows) => {- const row = rows[0];- return row- ? {- environmentId: row.environmentId as RelayClientEnvironmentRecord["environmentId"],- label:- row.environmentLabel.trim().length > 0- ? row.environmentLabel- : row.environmentId,- endpoint: {- httpBaseUrl: row.endpointHttpBaseUrl,- wsBaseUrl: row.endpointWsBaseUrl,- providerKind:- row.endpointProviderKind as RelayClientEnvironmentRecord["endpoint"]["providerKind"],- },- environmentPublicKey: row.environmentPublicKey,- linkedAt: row.createdAt,- }- : null;- }),- Effect.mapError(- (cause) =>- new EnvironmentLinkLookupPersistenceError({- userId: input.userId,- environmentId: input.environmentId,- cause,- }),- ),- );- }),-- revokeForUser: Effect.fn("relay.environment_links.revoke_for_user")(function* (input) {- yield* Effect.annotateCurrentSpan({- "relay.environment_id": input.environmentId,- });- const revokedAt = DateTime.formatIso(yield* DateTime.now);- const rows = yield* db- .update(relayEnvironmentLinks)- .set({- revokedAt,- updatedAt: revokedAt,- })- .where(- and(- eq(relayEnvironmentLinks.userId, input.userId),- eq(relayEnvironmentLinks.environmentId, input.environmentId),- isNull(relayEnvironmentLinks.revokedAt),- ),- )- .returning({ environmentId: relayEnvironmentLinks.environmentId })- .pipe(- Effect.mapError(- (cause) =>- new EnvironmentLinkRevokePersistenceError({- userId: input.userId,- environmentId: input.environmentId,- cause,- }),- ),- );- return rows.length > 0;- }),- });-});--export const layer = Layer.effect(EnvironmentLinks, make);diff --git a/infra/relay/src/environments/EnvironmentPublishSignatures.test.ts b/infra/relay/src/environments/EnvironmentPublishSignatures.test.tsdeleted file mode 100644index f61c5a27d..000000000--- a/infra/relay/src/environments/EnvironmentPublishSignatures.test.ts+++ /dev/null@@ -1,224 +0,0 @@-import * as NodeCrypto from "node:crypto";-import * as NodeServices from "@effect/platform-node/NodeServices";-import type {- RelayAgentActivityPublishProofPayload,- RelayAgentActivityPublishRequest,- RelayAgentActivityState,-} from "@t3tools/contracts/relay";-import { RELAY_ACTIVITY_PUBLISH_TYP } from "@t3tools/shared/relayJwt";-import { stableStringify } from "@t3tools/shared/relaySigning";-import { describe, expect, it } from "@effect/vitest";-import * as DateTime from "effect/DateTime";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";-import * as Redacted from "effect/Redacted";-import * as Result from "effect/Result";-import * as Schema from "effect/Schema";--import * as DpopProofs from "../auth/DpopProofs.ts";-import * as RelayConfiguration from "../Config.ts";-import * as EnvironmentPublishSignatures from "./EnvironmentPublishSignatures.ts";--const keyPair = NodeCrypto.generateKeyPairSync("ed25519", {- privateKeyEncoding: { format: "pem", type: "pkcs8" },- publicKeyEncoding: { format: "pem", type: "spki" },-});-const config = RelayConfiguration.RelayConfiguration.of({- relayIssuer: "https://relay.example.test",- apns: {- environment: "sandbox",- teamId: "team-id",- keyId: "key-id",- privateKey: Redacted.make("private-key"),- bundleId: "com.t3tools.t3code.dev",- },- apnsDeliveryJobSigningSecret: Redacted.make("job-secret"),- clerkSecretKey: Redacted.make("clerk-secret"),- clerkPublishableKey: "pk_test_test",- clerkJwtAudience: "t3-code-relay",- cloudMintPrivateKey: Redacted.make(keyPair.privateKey),- cloudMintPublicKey: keyPair.publicKey,- managedEndpointBaseDomain: undefined,- managedEndpointNamespace: undefined,-});-const state: RelayAgentActivityState = {- environmentId: "env" as RelayAgentActivityState["environmentId"],- threadId: "thread" as RelayAgentActivityState["threadId"],- projectTitle: "Project",- threadTitle: "Thread",- modelTitle: "gpt-5.4",- phase: "running",- headline: "Running",- updatedAt: "2026-05-25T00:00:00.000Z",- deepLink: "/threads/env/thread",-};-const isEnvironmentPublishSignatureInvalid = Schema.is(- EnvironmentPublishSignatures.EnvironmentPublishSignatureInvalid,-);--function signTestJwt(payload: object, privateKey: string): string {- const header = Buffer.from(- JSON.stringify({ alg: "EdDSA", typ: RELAY_ACTIVITY_PUBLISH_TYP }),- ).toString("base64url");- const encodedPayload = Buffer.from(JSON.stringify(payload)).toString("base64url");- const signingInput = `${header}.${encodedPayload}`;- return `${signingInput}.${NodeCrypto.sign(null, Buffer.from(signingInput), privateKey).toString("base64url")}`;-}--const freshRequest = Effect.gen(function* () {- const now = yield* DateTime.now;- const payload = {- iss: "t3-env:env",- aud: "https://relay.example.test",- sub: "env",- jti: "publish-jti",- iat: Math.floor(now.epochMilliseconds / 1_000),- exp: Math.floor(DateTime.add(now, { minutes: 5 }).epochMilliseconds / 1_000),- environmentId: state.environmentId,- threadId: state.threadId,- state,- } satisfies RelayAgentActivityPublishProofPayload;- return {- state,- proof: signTestJwt(payload, keyPair.privateKey),- } satisfies RelayAgentActivityPublishRequest;-});--function layer(replay?: Partial<DpopProofs.DpopProofReplay["Service"]>) {- return EnvironmentPublishSignatures.layer.pipe(- Layer.provide(- Layer.merge(- RelayConfiguration.layer(config),- Layer.succeed(DpopProofs.DpopProofReplay, {- verifyAndConsume:- replay?.verifyAndConsume ?? (() => Effect.die("unexpected DPoP proof verification")),- consume: replay?.consume ?? (() => Effect.succeed(true)),- pruneExpired: replay?.pruneExpired ?? Effect.void,- }),- ),- ),- Layer.provideMerge(NodeServices.layer),- );-}--describe("EnvironmentPublishSignatures", () => {- it.effect("verifies activity JWTs and scopes replay storage to the environment key", () => {- let replayThumbprint: string | null = null;- return Effect.gen(function* () {- const request = yield* freshRequest;- const signatures = yield* EnvironmentPublishSignatures.EnvironmentPublishSignatures;- yield* signatures.verify({- environmentId: state.environmentId,- environmentPublicKey: keyPair.publicKey,- threadId: state.threadId,- request,- });- expect(replayThumbprint).toBe(- `env-publish:${NodeCrypto.createHash("sha256")- .update(- stableStringify({- environmentId: state.environmentId,- environmentPublicKey: keyPair.publicKey,- }),- )- .digest("base64url")}`,- );- }).pipe(- Effect.provide(- layer({- consume: (input) =>- Effect.sync(() => {- replayThumbprint = input.thumbprint;- return true;- }),- }),- ),- );- });-- it.effect("rejects top-level state tampering", () =>- Effect.gen(function* () {- const request = yield* freshRequest;- const signatures = yield* EnvironmentPublishSignatures.EnvironmentPublishSignatures;- const result = yield* Effect.result(- signatures.verify({- environmentId: state.environmentId,- environmentPublicKey: keyPair.publicKey,- threadId: state.threadId,- request: { ...request, state: { ...state, headline: "Tampered" } },- }),- );- expect(Result.isFailure(result)).toBe(true);- if (Result.isFailure(result)) {- expect(isEnvironmentPublishSignatureInvalid(result.failure)).toBe(true);- if (isEnvironmentPublishSignatureInvalid(result.failure)) {- expect(result.failure).toMatchObject({- environmentId: state.environmentId,- threadId: state.threadId,- reason: "invalid_signature_or_payload",- stage: "validate_claims",- });- }- }- }).pipe(Effect.provide(layer())),- );-- it.effect("preserves the JWT verification failure", () =>- Effect.gen(function* () {- const request = yield* freshRequest;- const segments = request.proof.split(".");- const signature = segments[2]!;- segments[2] = `${signature.startsWith("A") ? "B" : "A"}${signature.slice(1)}`;- const signatures = yield* EnvironmentPublishSignatures.EnvironmentPublishSignatures;- const result = yield* Effect.result(- signatures.verify({- environmentId: state.environmentId,- environmentPublicKey: keyPair.publicKey,- threadId: state.threadId,- request: { ...request, proof: segments.join(".") },- }),- );-- expect(Result.isFailure(result)).toBe(true);- if (Result.isFailure(result)) {- expect(isEnvironmentPublishSignatureInvalid(result.failure)).toBe(true);- if (isEnvironmentPublishSignatureInvalid(result.failure)) {- expect(result.failure).toMatchObject({- environmentId: state.environmentId,- threadId: state.threadId,- reason: "invalid_signature_or_payload",- stage: "verify_proof",- cause: { _tag: "RelayJwtError" },- });- }- }- }).pipe(Effect.provide(layer())),- );-- it.effect("rejects replayed activity JWT ids", () =>- Effect.gen(function* () {- const request = yield* freshRequest;- const signatures = yield* EnvironmentPublishSignatures.EnvironmentPublishSignatures;- const result = yield* Effect.result(- signatures.verify({- environmentId: state.environmentId,- environmentPublicKey: keyPair.publicKey,- threadId: state.threadId,- request,- }),- );- expect(Result.isFailure(result)).toBe(true);- if (Result.isFailure(result)) {- expect(isEnvironmentPublishSignatureInvalid(result.failure)).toBe(true);- if (isEnvironmentPublishSignatureInvalid(result.failure)) {- expect(result.failure).toMatchObject({- environmentId: state.environmentId,- threadId: state.threadId,- reason: "replayed_nonce",- stage: "consume_nonce",- });- }- }- }).pipe(Effect.provide(layer({ consume: () => Effect.succeed(false) }))),- );-});diff --git a/infra/relay/src/environments/EnvironmentPublishSignatures.ts b/infra/relay/src/environments/EnvironmentPublishSignatures.tsdeleted file mode 100644index eb9c15a75..000000000--- a/infra/relay/src/environments/EnvironmentPublishSignatures.ts+++ /dev/null@@ -1,222 +0,0 @@-import {- RelayAgentActivityPublishProofPayload,- RelayAgentActivityPublishProofInvalidReason,- type RelayAgentActivityPublishRequest,-} from "@t3tools/contracts/relay";-import {- decodeRelayJwt,- normalizeRelayIssuer,- RELAY_ACTIVITY_PUBLISH_TYP,- verifyRelayJwt,-} from "@t3tools/shared/relayJwt";-import { stableStringify } from "@t3tools/shared/relaySigning";-import * as Context from "effect/Context";-import * as Crypto from "effect/Crypto";-import * as DateTime from "effect/DateTime";-import * as Effect from "effect/Effect";-import * as Encoding from "effect/Encoding";-import * as Layer from "effect/Layer";-import * as Schema from "effect/Schema";--import * as DpopProofs from "../auth/DpopProofs.ts";-import * as RelayConfiguration from "../Config.ts";--export class EnvironmentPublishSignatureExpired extends Schema.TaggedErrorClass<EnvironmentPublishSignatureExpired>()(- "EnvironmentPublishSignatureExpired",- {- environmentId: Schema.String,- threadId: Schema.String,- expiresAt: Schema.String,- },-) {- override get message(): string {- return `Environment '${this.environmentId}' publish signature for thread '${this.threadId}' expired at ${this.expiresAt}`;- }-}--export class EnvironmentPublishSignatureInvalid extends Schema.TaggedErrorClass<EnvironmentPublishSignatureInvalid>()(- "EnvironmentPublishSignatureInvalid",- {- environmentId: Schema.String,- threadId: Schema.String,- reason: RelayAgentActivityPublishProofInvalidReason,- stage: Schema.Literals([- "decode_token",- "verify_proof",- "validate_claims",- "validate_expiration",- "generate_replay_thumbprint",- "consume_nonce",- ]),- cause: Schema.optional(Schema.Defect()),- },-) {- override get message(): string {- return `Environment '${this.environmentId}' publish signature for thread '${this.threadId}' is invalid during ${this.stage}: ${this.reason}`;- }-}--export class EnvironmentPublishPublicKeyMissing extends Schema.TaggedErrorClass<EnvironmentPublishPublicKeyMissing>()(- "EnvironmentPublishPublicKeyMissing",- {- environmentId: Schema.String,- },-) {- override get message(): string {- return `Environment '${this.environmentId}' has no publish public key`;- }-}--export type EnvironmentPublishSignatureError =- | EnvironmentPublishSignatureExpired- | EnvironmentPublishSignatureInvalid- | EnvironmentPublishPublicKeyMissing- | DpopProofs.DpopProofReplayPersistenceError;--export class EnvironmentPublishSignatures extends Context.Service<- EnvironmentPublishSignatures,- {- readonly verify: (input: {- readonly environmentId: string;- readonly environmentPublicKey: string;- readonly threadId: string;- readonly request: RelayAgentActivityPublishRequest;- }) => Effect.Effect<void, EnvironmentPublishSignatureError>;- }->()("t3code-relay/environments/EnvironmentPublishSignatures") {}--const decodeProof = Schema.decodeUnknownEffect(RelayAgentActivityPublishProofPayload);--function environmentPublishReplayThumbprintData(input: {- readonly environmentId: string;- readonly environmentPublicKey: string;-}) {- return new TextEncoder().encode(- stableStringify({- environmentId: input.environmentId,- environmentPublicKey: input.environmentPublicKey,- }),- );-}--const formatEnvironmentPublishReplayThumbprint = (digest: Uint8Array) =>- `env-publish:${Encoding.encodeBase64Url(digest)}`;--const make = Effect.gen(function* () {- const proofReplay = yield* DpopProofs.DpopProofReplay;- const config = yield* RelayConfiguration.RelayConfiguration;- const crypto = yield* Crypto.Crypto;-- return EnvironmentPublishSignatures.of({- verify: Effect.fn("relay.environment_publish_signatures.verify")(function* (input) {- yield* Effect.annotateCurrentSpan({- "relay.environment_id": input.environmentId,- "relay.thread_id": input.threadId,- });- const now = yield* DateTime.now;- const decoded = yield* Effect.try({- try: () => decodeRelayJwt(input.request.proof),- catch: (cause) =>- new EnvironmentPublishSignatureInvalid({- environmentId: input.environmentId,- threadId: input.threadId,- reason: "invalid_signature_or_payload",- stage: "decode_token",- cause,- }),- });- if (- typeof decoded.exp === "number" &&- decoded.exp <= Math.floor(now.epochMilliseconds / 1_000)- ) {- return yield* new EnvironmentPublishSignatureExpired({- environmentId: input.environmentId,- threadId: input.threadId,- expiresAt: DateTime.formatIso(DateTime.makeUnsafe(decoded.exp * 1_000)),- });- }- const proof = yield* verifyRelayJwt({- publicKey: input.environmentPublicKey,- token: input.request.proof,- typ: RELAY_ACTIVITY_PUBLISH_TYP,- issuer: `t3-env:${input.environmentId}`,- audience: normalizeRelayIssuer(config.relayIssuer),- nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),- }).pipe(- Effect.flatMap(decodeProof),- Effect.mapError(- (cause) =>- new EnvironmentPublishSignatureInvalid({- environmentId: input.environmentId,- threadId: input.threadId,- reason: "invalid_signature_or_payload",- stage: "verify_proof",- cause,- }),- ),- );- if (- proof.environmentId !== input.environmentId ||- proof.threadId !== input.threadId ||- proof.sub !== input.environmentId ||- stableStringify(proof.state) !== stableStringify(input.request.state) ||- (input.request.state !== null &&- (input.request.state.environmentId !== input.environmentId ||- input.request.state.threadId !== input.threadId))- ) {- return yield* new EnvironmentPublishSignatureInvalid({- environmentId: input.environmentId,- threadId: input.threadId,- reason: "invalid_signature_or_payload",- stage: "validate_claims",- });- }- const expiresAt = DateTime.make(proof.exp * 1_000);- if (expiresAt._tag === "None") {- return yield* new EnvironmentPublishSignatureInvalid({- environmentId: input.environmentId,- threadId: input.threadId,- reason: "invalid_signature_or_payload",- stage: "validate_expiration",- });- }- const thumbprint = yield* crypto- .digest(- "SHA-256",- environmentPublishReplayThumbprintData({- environmentId: input.environmentId,- environmentPublicKey: input.environmentPublicKey,- }),- )- .pipe(- Effect.map(formatEnvironmentPublishReplayThumbprint),- Effect.mapError(- (cause) =>- new EnvironmentPublishSignatureInvalid({- environmentId: input.environmentId,- threadId: input.threadId,- reason: "invalid_signature_or_payload",- stage: "generate_replay_thumbprint",- cause,- }),- ),- );- const consumedNonce = yield* proofReplay.consume({- thumbprint,- jti: proof.jti,- iat: proof.iat,- expiresAt: expiresAt.value,- });- if (!consumedNonce) {- return yield* new EnvironmentPublishSignatureInvalid({- environmentId: input.environmentId,- threadId: input.threadId,- reason: "replayed_nonce",- stage: "consume_nonce",- });- }- }),- });-});--export const layer = Layer.effect(EnvironmentPublishSignatures, make);diff --git a/infra/relay/src/environments/ManagedEndpointAllocations.test.ts b/infra/relay/src/environments/ManagedEndpointAllocations.test.tsdeleted file mode 100644index ebf51de10..000000000--- a/infra/relay/src/environments/ManagedEndpointAllocations.test.ts+++ /dev/null@@ -1,148 +0,0 @@-import { describe, expect, it } from "@effect/vitest";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";--import * as RelayDb from "../db.ts";-import { relayManagedEndpointAllocations } from "../persistence/schema.ts";-import * as ManagedEndpointAllocations from "./ManagedEndpointAllocations.ts";--const layerWithDb = (db: RelayDb.RelayDb["Service"]) =>- ManagedEndpointAllocations.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, db)));--describe("ManagedEndpointAllocations", () => {- it.effect("returns a claim generation only when deprovision wins the allocation CAS", () => {- let claimedAt: string | undefined;- const fakeDb = {- update: (table: unknown) => {- expect(table).toBe(relayManagedEndpointAllocations);- return {- set: (values: { readonly updatedAt: string }) => {- claimedAt = values.updatedAt;- return {- where: () => ({- returning: () => Effect.succeed([{ userId: "user-1" }]),- }),- };- },- };- },- } as unknown as RelayDb.RelayDb["Service"];-- return Effect.gen(function* () {- const allocations = yield* ManagedEndpointAllocations.ManagedEndpointAllocations;- const generation = yield* allocations.claimDeprovision({- userId: "user-1",- environmentId: "environment-1",- updatedAt: "captured-generation",- });-- expect(generation).toBe(claimedAt);- expect(generation).not.toBeNull();- }).pipe(Effect.provide(layerWithDb(fakeDb)));- });-- it.effect("does not remove an allocation superseded after a deprovision claim", () => {- const fakeDb = {- delete: (table: unknown) => {- expect(table).toBe(relayManagedEndpointAllocations);- return {- where: () => ({- returning: () => Effect.succeed([]),- }),- };- },- } as unknown as RelayDb.RelayDb["Service"];-- return Effect.gen(function* () {- const allocations = yield* ManagedEndpointAllocations.ManagedEndpointAllocations;- expect(- yield* allocations.removeClaimed({- userId: "user-1",- environmentId: "environment-1",- updatedAt: "outdated-claim-generation",- }),- ).toBe(false);- }).pipe(Effect.provide(layerWithDb(fakeDb)));- });-- it.effect("retains database failures with allocation operation and identity", () => {- const cause = new Error("database unavailable");- const fakeDb = {- select: () => ({- from: (table: unknown) => {- expect(table).toBe(relayManagedEndpointAllocations);- return {- where: () => ({- limit: () => Effect.fail(cause),- }),- };- },- }),- } as unknown as RelayDb.RelayDb["Service"];-- return Effect.gen(function* () {- const allocations = yield* ManagedEndpointAllocations.ManagedEndpointAllocations;- const error = yield* Effect.flip(- allocations.get({ userId: "user-1", environmentId: "environment-1" }),- );-- expect(error).toMatchObject({- _tag: "ManagedEndpointAllocationPersistenceError",- operation: "get",- stage: "database-request",- userId: "user-1",- environmentId: "environment-1",- });- expect(error.cause).toBe(cause);- }).pipe(Effect.provide(layerWithDb(fakeDb)));- });-- it.effect("reports an unresolved reservation without manufacturing a cause", () => {- const fakeDb = {- insert: (table: unknown) => {- expect(table).toBe(relayManagedEndpointAllocations);- return {- values: () => ({- onConflictDoNothing: () => ({- returning: () => Effect.succeed([]),- }),- }),- };- },- select: () => ({- from: (table: unknown) => {- expect(table).toBe(relayManagedEndpointAllocations);- return {- where: () => ({- limit: () => Effect.succeed([]),- }),- };- },- }),- } as unknown as RelayDb.RelayDb["Service"];-- return Effect.gen(function* () {- const allocations = yield* ManagedEndpointAllocations.ManagedEndpointAllocations;- const error = yield* Effect.flip(- allocations.reserve({- userId: "user-1",- environmentId: "environment-1",- hostname: "environment-1.example.test",- tunnelName: "environment-1-tunnel",- }),- );-- expect(error).toMatchObject({- _tag: "ManagedEndpointAllocationPersistenceError",- operation: "reserve",- stage: "resolve-reservation",- userId: "user-1",- environmentId: "environment-1",- hostname: "environment-1.example.test",- tunnelName: "environment-1-tunnel",- });- expect(error.cause).toBeUndefined();- expect(error.message).toContain("'resolve-reservation'");- }).pipe(Effect.provide(layerWithDb(fakeDb)));- });-});diff --git a/infra/relay/src/environments/ManagedEndpointAllocations.ts b/infra/relay/src/environments/ManagedEndpointAllocations.tsdeleted file mode 100644index 4320eeea3..000000000--- a/infra/relay/src/environments/ManagedEndpointAllocations.ts+++ /dev/null@@ -1,423 +0,0 @@-import type { RelayManagedEndpoint } from "@t3tools/contracts/relay";-import { and, eq } from "drizzle-orm";-import * as Context from "effect/Context";-import * as DateTime from "effect/DateTime";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";-import * as Schema from "effect/Schema";--import * as RelayDb from "../db.ts";-import { isManagedEndpointHostname, managedEndpointForHostname } from "../deploymentConfig.ts";-import { relayManagedEndpointAllocations } from "../persistence/schema.ts";--export interface ManagedEndpointAllocation {- readonly userId: string;- readonly environmentId: string;- readonly hostname: string;- readonly tunnelId: string | null;- readonly tunnelName: string;- readonly dnsRecordId: string | null;- readonly readyAt: string | null;- /**- * Doubles as the allocation's generation marker: every mutation rewrites it,- * so `claimRelease` can detect a provision that raced a release.- */- readonly updatedAt: string;-}--export function resolveReadyManagedEndpoint(input: {- readonly allocation: ManagedEndpointAllocation;- readonly baseDomain: string | undefined;-}): RelayManagedEndpoint | null {- if (- !input.baseDomain ||- input.allocation.readyAt === null ||- input.allocation.tunnelId === null ||- input.allocation.dnsRecordId === null ||- !isManagedEndpointHostname(input.allocation.hostname, input.baseDomain)- ) {- return null;- }- return managedEndpointForHostname(input.allocation.hostname);-}--export class ManagedEndpointAllocationPersistenceError extends Schema.TaggedErrorClass<ManagedEndpointAllocationPersistenceError>()(- "ManagedEndpointAllocationPersistenceError",- {- operation: Schema.Literals([- "get",- "reserve",- "record-tunnel",- "record-dns",- "mark-ready",- "claim-release",- "claim-deprovision",- "remove",- "remove-claimed",- ]),- stage: Schema.Literals(["database-request", "resolve-reservation"]),- userId: Schema.String,- environmentId: Schema.String,- hostname: Schema.optionalKey(Schema.String),- tunnelName: Schema.optionalKey(Schema.String),- tunnelId: Schema.optionalKey(Schema.String),- dnsRecordId: Schema.optionalKey(Schema.String),- cause: Schema.optional(Schema.Defect()),- },-) {- override get message(): string {- return `Managed endpoint allocation '${this.operation}' failed during '${this.stage}' for user '${this.userId}', environment '${this.environmentId}'`;- }-}--interface ManagedEndpointAllocationKey {- readonly userId: string;- readonly environmentId: string;-}--interface ReserveManagedEndpointAllocationInput extends ManagedEndpointAllocationKey {- readonly hostname: string;- readonly tunnelName: string;-}--interface RecordManagedEndpointTunnelInput extends ManagedEndpointAllocationKey {- readonly tunnelId: string;-}--interface RecordManagedEndpointDnsInput extends ManagedEndpointAllocationKey {- readonly dnsRecordId: string;-}--interface ClaimManagedEndpointReleaseInput extends ManagedEndpointAllocationKey {- readonly tunnelId: string;- readonly updatedAt: string;-}--interface ClaimManagedEndpointDeprovisionInput extends ManagedEndpointAllocationKey {- readonly updatedAt: string;-}--interface RemoveClaimedManagedEndpointAllocationInput extends ManagedEndpointAllocationKey {- readonly updatedAt: string;-}--export class ManagedEndpointAllocations extends Context.Service<- ManagedEndpointAllocations,- {- readonly get: (- input: ManagedEndpointAllocationKey,- ) => Effect.Effect<ManagedEndpointAllocation | null, ManagedEndpointAllocationPersistenceError>;- readonly reserve: (- input: ReserveManagedEndpointAllocationInput,- ) => Effect.Effect<ManagedEndpointAllocation, ManagedEndpointAllocationPersistenceError>;- readonly recordTunnel: (- input: RecordManagedEndpointTunnelInput,- ) => Effect.Effect<void, ManagedEndpointAllocationPersistenceError>;- readonly recordDns: (- input: RecordManagedEndpointDnsInput,- ) => Effect.Effect<void, ManagedEndpointAllocationPersistenceError>;- readonly markReady: (- input: ManagedEndpointAllocationKey,- ) => Effect.Effect<void, ManagedEndpointAllocationPersistenceError>;- /**- * Atomically claims the right to delete the allocation's tunnel: succeeds- * only while the recorded tunnel and generation still match what the- * caller loaded. A concurrent provision rewrites `updatedAt` when it- * records its tunnel, which makes a stale claim fail and keeps the freshly- * issued tunnel alive.- */- readonly claimRelease: (- input: ClaimManagedEndpointReleaseInput,- ) => Effect.Effect<boolean, ManagedEndpointAllocationPersistenceError>;- /**- * Claims the complete allocation for teardown only if its generation still- * matches the snapshot captured by the unlink operation.- *- * Returns the claim generation used by `removeClaimed`, or null when a- * concurrent provision has already superseded the snapshot.- */- readonly claimDeprovision: (- input: ClaimManagedEndpointDeprovisionInput,- ) => Effect.Effect<string | null, ManagedEndpointAllocationPersistenceError>;- readonly remove: (- input: ManagedEndpointAllocationKey,- ) => Effect.Effect<void, ManagedEndpointAllocationPersistenceError>;- readonly removeClaimed: (- input: RemoveClaimedManagedEndpointAllocationInput,- ) => Effect.Effect<boolean, ManagedEndpointAllocationPersistenceError>;- }->()("t3code-relay/environments/ManagedEndpointAllocations") {}--const allocationSelection = {- userId: relayManagedEndpointAllocations.userId,- environmentId: relayManagedEndpointAllocations.environmentId,- hostname: relayManagedEndpointAllocations.hostname,- tunnelId: relayManagedEndpointAllocations.tunnelId,- tunnelName: relayManagedEndpointAllocations.tunnelName,- dnsRecordId: relayManagedEndpointAllocations.dnsRecordId,- readyAt: relayManagedEndpointAllocations.readyAt,- updatedAt: relayManagedEndpointAllocations.updatedAt,-};--const whereAllocation = (input: ManagedEndpointAllocationKey) =>- and(- eq(relayManagedEndpointAllocations.userId, input.userId),- eq(relayManagedEndpointAllocations.environmentId, input.environmentId),- );--export const make = Effect.gen(function* () {- const db = yield* RelayDb.RelayDb;-- return ManagedEndpointAllocations.of({- get: Effect.fn("relay.managed_endpoint_allocations.get")(function* (- input: ManagedEndpointAllocationKey,- ) {- return yield* db- .select(allocationSelection)- .from(relayManagedEndpointAllocations)- .where(whereAllocation(input))- .limit(1)- .pipe(- Effect.map((rows) => rows[0] ?? null),- Effect.mapError(- (cause) =>- new ManagedEndpointAllocationPersistenceError({- operation: "get",- stage: "database-request",- ...input,- cause,- }),- ),- );- }),- reserve: Effect.fn("relay.managed_endpoint_allocations.reserve")(function* (- input: ReserveManagedEndpointAllocationInput,- ) {- const now = DateTime.formatIso(yield* DateTime.now);- const inserted = yield* db- .insert(relayManagedEndpointAllocations)- .values({- ...input,- createdAt: now,- updatedAt: now,- })- .onConflictDoNothing()- .returning(allocationSelection)- .pipe(- Effect.mapError(- (cause) =>- new ManagedEndpointAllocationPersistenceError({- operation: "reserve",- stage: "database-request",- ...input,- cause,- }),- ),- );-- const allocation =- inserted[0] ??- (yield* db- .select(allocationSelection)- .from(relayManagedEndpointAllocations)- .where(whereAllocation(input))- .limit(1)- .pipe(- Effect.map((rows) => rows[0]),- Effect.mapError(- (cause) =>- new ManagedEndpointAllocationPersistenceError({- operation: "reserve",- stage: "database-request",- ...input,- cause,- }),- ),- ));-- if (allocation === undefined) {- return yield* new ManagedEndpointAllocationPersistenceError({- operation: "reserve",- stage: "resolve-reservation",- ...input,- });- }-- return allocation;- }),- recordTunnel: Effect.fn("relay.managed_endpoint_allocations.record_tunnel")(function* (- input: RecordManagedEndpointTunnelInput,- ) {- yield* db- .update(relayManagedEndpointAllocations)- .set({- tunnelId: input.tunnelId,- updatedAt: DateTime.formatIso(yield* DateTime.now),- })- .where(whereAllocation(input))- .pipe(- Effect.mapError(- (cause) =>- new ManagedEndpointAllocationPersistenceError({- operation: "record-tunnel",- stage: "database-request",- ...input,- cause,- }),- ),- );- }),- recordDns: Effect.fn("relay.managed_endpoint_allocations.record_dns")(function* (- input: RecordManagedEndpointDnsInput,- ) {- yield* db- .update(relayManagedEndpointAllocations)- .set({- dnsRecordId: input.dnsRecordId,- updatedAt: DateTime.formatIso(yield* DateTime.now),- })- .where(whereAllocation(input))- .pipe(- Effect.mapError(- (cause) =>- new ManagedEndpointAllocationPersistenceError({- operation: "record-dns",- stage: "database-request",- ...input,- cause,- }),- ),- );- }),- markReady: Effect.fn("relay.managed_endpoint_allocations.mark_ready")(function* (- input: ManagedEndpointAllocationKey,- ) {- const now = DateTime.formatIso(yield* DateTime.now);- yield* db- .update(relayManagedEndpointAllocations)- .set({- readyAt: now,- updatedAt: now,- })- .where(whereAllocation(input))- .pipe(- Effect.mapError(- (cause) =>- new ManagedEndpointAllocationPersistenceError({- operation: "mark-ready",- stage: "database-request",- ...input,- cause,- }),- ),- );- }),- claimRelease: Effect.fn("relay.managed_endpoint_allocations.claim_release")(function* (- input: ClaimManagedEndpointReleaseInput,- ) {- const claimed = yield* db- .update(relayManagedEndpointAllocations)- .set({- updatedAt: DateTime.formatIso(yield* DateTime.now),- })- .where(- and(- whereAllocation(input),- eq(relayManagedEndpointAllocations.tunnelId, input.tunnelId),- eq(relayManagedEndpointAllocations.updatedAt, input.updatedAt),- ),- )- .returning({ userId: relayManagedEndpointAllocations.userId })- .pipe(- Effect.map((rows) => rows.length > 0),- Effect.mapError(- (cause) =>- new ManagedEndpointAllocationPersistenceError({- operation: "claim-release",- stage: "database-request",- userId: input.userId,- environmentId: input.environmentId,- tunnelId: input.tunnelId,- cause,- }),- ),- );- return claimed;- }),- claimDeprovision: Effect.fn("relay.managed_endpoint_allocations.claim_deprovision")(function* (- input: ClaimManagedEndpointDeprovisionInput,- ) {- const claimedAt = DateTime.formatIso(yield* DateTime.now);- const claimed = yield* db- .update(relayManagedEndpointAllocations)- .set({ updatedAt: claimedAt })- .where(- and(- whereAllocation(input),- eq(relayManagedEndpointAllocations.updatedAt, input.updatedAt),- ),- )- .returning({ userId: relayManagedEndpointAllocations.userId })- .pipe(- Effect.map((rows) => rows.length > 0),- Effect.mapError(- (cause) =>- new ManagedEndpointAllocationPersistenceError({- operation: "claim-deprovision",- stage: "database-request",- userId: input.userId,- environmentId: input.environmentId,- cause,- }),- ),- );- return claimed ? claimedAt : null;- }),- remove: Effect.fn("relay.managed_endpoint_allocations.remove")(function* (- input: ManagedEndpointAllocationKey,- ) {- yield* db- .delete(relayManagedEndpointAllocations)- .where(whereAllocation(input))- .pipe(- Effect.mapError(- (cause) =>- new ManagedEndpointAllocationPersistenceError({- operation: "remove",- stage: "database-request",- ...input,- cause,- }),- ),- );- }),- removeClaimed: Effect.fn("relay.managed_endpoint_allocations.remove_claimed")(function* (- input: RemoveClaimedManagedEndpointAllocationInput,- ) {- return yield* db- .delete(relayManagedEndpointAllocations)- .where(- and(- whereAllocation(input),- eq(relayManagedEndpointAllocations.updatedAt, input.updatedAt),- ),- )- .returning({ userId: relayManagedEndpointAllocations.userId })- .pipe(- Effect.map((rows) => rows.length > 0),- Effect.mapError(- (cause) =>- new ManagedEndpointAllocationPersistenceError({- operation: "remove-claimed",- stage: "database-request",- userId: input.userId,- environmentId: input.environmentId,- cause,- }),- ),- );- }),- });-});--export const layer = Layer.effect(ManagedEndpointAllocations, make);diff --git a/infra/relay/src/environments/ManagedEndpointProvider.test.ts b/infra/relay/src/environments/ManagedEndpointProvider.test.tsdeleted file mode 100644index 4d136658c..000000000--- a/infra/relay/src/environments/ManagedEndpointProvider.test.ts+++ /dev/null@@ -1,1262 +0,0 @@-import * as NodeCrypto from "node:crypto";-import * as NodeServices from "@effect/platform-node/NodeServices";--import { describe, expect, it } from "@effect/vitest";-import * as Alchemy from "alchemy";-import * as Cloudflare from "alchemy/Cloudflare";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";-import * as Redacted from "effect/Redacted";--import * as RelayConfiguration from "../Config.ts";-import * as ManagedEndpointAllocations from "./ManagedEndpointAllocations.ts";-import * as ManagedEndpointProvider from "./ManagedEndpointProvider.ts";-import * as ManagedTunnelLimits from "./ManagedTunnelLimits.ts";--const config = RelayConfiguration.RelayConfiguration.of({- relayIssuer: "https://relay.example.test",- apns: {- environment: "sandbox",- teamId: "team-id",- keyId: "key-id",- privateKey: Redacted.make("private-key"),- bundleId: "com.t3tools.t3code.dev",- },- apnsDeliveryJobSigningSecret: Redacted.make("job-secret"),- clerkSecretKey: Redacted.make("clerk-secret"),- clerkPublishableKey: "pk_test_test",- clerkJwtAudience: "t3-code-relay",- cloudMintPrivateKey: Redacted.make("cloud-private-key"),- cloudMintPublicKey: "cloud-public-key",- managedEndpointBaseDomain: "t3code.test",- managedEndpointNamespace: "dev_julius",-});--interface TunnelCall {- readonly operation: "list" | "create" | "putConfiguration" | "getToken" | "delete";- readonly input: unknown;-}--interface DnsCall {- readonly operation: "listRecords" | "createRecord" | "updateRecord" | "deleteRecord";- readonly input: unknown;-}--interface AllocationCall {- readonly operation:- | "get"- | "reserve"- | "recordTunnel"- | "recordDns"- | "markReady"- | "claimRelease"- | "claimDeprovision"- | "remove"- | "removeClaimed";- readonly input: unknown;-}--function allocationKey(input: { readonly userId: string; readonly environmentId: string }) {- return `${input.userId}:${input.environmentId}`;-}--function makeTunnelClient(calls: TunnelCall[] = []) {- return ManagedEndpointProvider.ManagedEndpointTunnelClient.of({- list: (request) =>- Effect.sync(() => {- calls.push({ operation: "list", input: request });- return { result: [] };- }),- create: (request) =>- Effect.sync(() => {- calls.push({ operation: "create", input: request });- return { id: "tunnel-id", name: request.name };- }),- putConfiguration: (tunnelId, tunnelConfig) =>- Effect.sync(() => {- calls.push({ operation: "putConfiguration", input: { tunnelId, tunnelConfig } });- }),- getToken: (tunnelId) =>- Effect.sync(() => {- calls.push({ operation: "getToken", input: tunnelId });- return "connector-token";- }),- delete: (tunnelId) =>- Effect.sync(() => {- calls.push({ operation: "delete", input: tunnelId });- }),- });-}--function makePersistentTunnelClient(calls: TunnelCall[] = []) {- let tunnel: { readonly id: string; readonly name: string } | null = null;- return ManagedEndpointProvider.ManagedEndpointTunnelClient.of({- list: (request) =>- Effect.sync(() => {- calls.push({ operation: "list", input: request });- return { result: tunnel === null ? [] : [tunnel] };- }),- create: (request) =>- Effect.sync(() => {- calls.push({ operation: "create", input: request });- tunnel = { id: "tunnel-id", name: request.name };- return tunnel;- }),- putConfiguration: (tunnelId, tunnelConfig) =>- Effect.sync(() => {- calls.push({ operation: "putConfiguration", input: { tunnelId, tunnelConfig } });- }),- getToken: (tunnelId) =>- Effect.sync(() => {- calls.push({ operation: "getToken", input: tunnelId });- return "connector-token";- }),- delete: (tunnelId) =>- Effect.sync(() => {- calls.push({ operation: "delete", input: tunnelId });- tunnel = null;- }),- });-}--function makeDnsClient(- calls: DnsCall[] = [],- records: ReadonlyArray<{ readonly id: string }> = [],-) {- let currentRecords = [...records];- return ManagedEndpointProvider.ManagedEndpointDnsClient.of({- listRecords: (hostname) =>- Effect.sync(() => {- calls.push({ operation: "listRecords", input: hostname });- return currentRecords;- }),- createRecord: (request) =>- Effect.sync(() => {- calls.push({ operation: "createRecord", input: request });- const record = { id: "created-record-id" };- currentRecords = [record];- return record;- }),- updateRecord: (dnsRecordId, request) =>- Effect.gen(function* () {- calls.push({ operation: "updateRecord", input: { dnsRecordId, request } });- if (!currentRecords.some((record) => record.id === dnsRecordId)) {- return yield* new ManagedEndpointProvider.ManagedEndpointDnsClientError({- operation: "update-record",- hostname: request.name,- dnsRecordId,- cause: { _tag: "NotFound", dnsRecordId },- });- }- }),- deleteRecord: (dnsRecordId) =>- Effect.sync(() => {- calls.push({ operation: "deleteRecord", input: dnsRecordId });- currentRecords = currentRecords.filter((record) => record.id !== dnsRecordId);- }),- });-}--function makeAllocations(calls: AllocationCall[] = []) {- const allocations = new Map<string, ManagedEndpointAllocations.ManagedEndpointAllocation>();- let generation = 0;- const mutate = (- key: string,- change: (- allocation: ManagedEndpointAllocations.ManagedEndpointAllocation,- ) => ManagedEndpointAllocations.ManagedEndpointAllocation,- ) => {- const allocation = allocations.get(key);- if (allocation !== undefined) {- allocations.set(key, { ...change(allocation), updatedAt: `generation-${++generation}` });- }- };- return ManagedEndpointAllocations.ManagedEndpointAllocations.of({- get: (input) =>- Effect.sync(() => {- calls.push({ operation: "get", input });- return allocations.get(allocationKey(input)) ?? null;- }),- reserve: (input) =>- Effect.sync(() => {- calls.push({ operation: "reserve", input });- const allocation = allocations.get(allocationKey(input)) ?? {- ...input,- tunnelId: null,- dnsRecordId: null,- readyAt: null,- updatedAt: `generation-${++generation}`,- };- allocations.set(allocationKey(input), allocation);- return allocation;- }),- recordTunnel: (input) =>- Effect.sync(() => {- calls.push({ operation: "recordTunnel", input });- mutate(allocationKey(input), (allocation) => ({- ...allocation,- tunnelId: input.tunnelId,- }));- }),- recordDns: (input) =>- Effect.sync(() => {- calls.push({ operation: "recordDns", input });- mutate(allocationKey(input), (allocation) => ({- ...allocation,- dnsRecordId: input.dnsRecordId,- }));- }),- markReady: (input) =>- Effect.sync(() => {- calls.push({ operation: "markReady", input });- mutate(allocationKey(input), (allocation) => ({- ...allocation,- readyAt: "2026-06-02T00:00:00.000Z",- }));- }),- claimRelease: (input) =>- Effect.sync(() => {- calls.push({ operation: "claimRelease", input });- const allocation = allocations.get(allocationKey(input));- if (- allocation === undefined ||- allocation.tunnelId !== input.tunnelId ||- allocation.updatedAt !== input.updatedAt- ) {- return false;- }- mutate(allocationKey(input), (current) => current);- return true;- }),- claimDeprovision: (input) =>- Effect.sync(() => {- calls.push({ operation: "claimDeprovision", input });- const allocation = allocations.get(allocationKey(input));- if (allocation === undefined || allocation.updatedAt !== input.updatedAt) {- return null;- }- mutate(allocationKey(input), (current) => current);- return allocations.get(allocationKey(input))?.updatedAt ?? null;- }),- remove: (input) =>- Effect.sync(() => {- calls.push({ operation: "remove", input });- allocations.delete(allocationKey(input));- }),- removeClaimed: (input) =>- Effect.sync(() => {- calls.push({ operation: "removeClaimed", input });- const allocation = allocations.get(allocationKey(input));- if (allocation === undefined || allocation.updatedAt !== input.updatedAt) {- return false;- }- allocations.delete(allocationKey(input));- return true;- }),- });-}--function makeTunnelLimits(- calls: Array<{ readonly userId: string; readonly environmentId: string }> = [],- result: ManagedTunnelLimits.ManagedTunnelLimitExceeded | null = null,-) {- return ManagedTunnelLimits.ManagedTunnelLimits.of({- ensureCapacity: (input) =>- Effect.suspend(() => {- calls.push(input);- return result === null ? Effect.void : Effect.fail(result);- }),- });-}--function providerLayer(- tunnelClient = makeTunnelClient(),- dnsClient = makeDnsClient(),- allocations = makeAllocations(),- tunnelLimits = makeTunnelLimits(),-) {- return ManagedEndpointProvider.layer.pipe(- Layer.provideMerge(NodeServices.layer),- Layer.provide(RelayConfiguration.layer(config)),- Layer.provide(ManagedEndpointProvider.layerTunnelClient(tunnelClient)),- Layer.provide(ManagedEndpointProvider.layerDnsClient(dnsClient)),- Layer.provide(- Layer.succeed(ManagedEndpointAllocations.ManagedEndpointAllocations, allocations),- ),- Layer.provide(Layer.succeed(ManagedTunnelLimits.ManagedTunnelLimits, tunnelLimits)),- );-}--function expectedManagedHostname(environmentId: string, userId = "user_ABC"): string {- const hash = NodeCrypto.createHash("sha256")- .update(`dev_julius:${userId}:${environmentId}`)- .digest("hex")- .slice(0, 16);- return `dev-julius-${hash}.t3code.test`;-}--function expectedManagedTunnelName(environmentId: string, userId = "user_ABC"): string {- const hash = NodeCrypto.createHash("sha256")- .update(`dev_julius:${userId}:${environmentId}`)- .digest("hex")- .slice(0, 16);- return `t3coderelay-managedendpoint-dev-julius-${hash}`;-}--describe("ManagedEndpointProvider", () => {- it.effect("does not require the deployment RuntimeContext when building the Worker layer", () => {- const tunnelClient = {- list: () => Effect.succeed({ result: [] }),- create: (request: { readonly name: string }) =>- Effect.succeed({ id: "tunnel-id", name: request.name }),- putConfiguration: () => Effect.void,- getToken: () => Effect.succeed("connector-token"),- delete: () => Effect.void,- } as unknown as Cloudflare.Tunnel.ReadWriteTunnelClient;- const dnsClient = {- listDnsRecords: () => Effect.succeed({ result: [] }),- createDnsRecord: () => Effect.succeed({ id: "dns-record-id" }),- updateDnsRecord: () => Effect.void,- deleteDnsRecord: () => Effect.void,- } as unknown as Cloudflare.DNS.ReadWriteDnsClient;- const runtimeContext = {} as Alchemy.BaseRuntimeContext;- const layer = ManagedEndpointProvider.layerCloudflareBindings(- tunnelClient,- dnsClient,- runtimeContext,- ).pipe(- Layer.provideMerge(NodeServices.layer),- Layer.provide(RelayConfiguration.layer(config)),- Layer.provide(- Layer.succeed(ManagedEndpointAllocations.ManagedEndpointAllocations, makeAllocations()),- ),- Layer.provide(Layer.succeed(ManagedTunnelLimits.ManagedTunnelLimits, makeTunnelLimits())),- );-- return Effect.gen(function* () {- const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;- const result = yield* provider.provision({- userId: "user_ABC",- environmentId: "env_ABC",- origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },- });-- expect(result.runtime.connectorToken).toBe("connector-token");- }).pipe(Effect.provide(layer));- });-- it.effect("provisions a Cloudflare tunnel endpoint and connector token", () => {- const tunnelCalls: TunnelCall[] = [];- const dnsCalls: DnsCall[] = [];- const allocationCalls: AllocationCall[] = [];-- return Effect.gen(function* () {- const hostname = expectedManagedHostname("env_ABC");- const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;- const result = yield* provider.provision({- userId: "user_ABC",- environmentId: "env_ABC",- origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },- });-- expect(result).toEqual({- endpoint: {- httpBaseUrl: `https://${hostname}/`,- wsBaseUrl: `wss://${hostname}/ws`,- providerKind: "cloudflare_tunnel",- },- runtime: {- providerKind: "cloudflare_tunnel",- connectorToken: "connector-token",- tunnelId: "tunnel-id",- tunnelName: expectedManagedTunnelName("env_ABC"),- },- });- expect(dnsCalls).toEqual([- { operation: "listRecords", input: hostname },- {- operation: "createRecord",- input: {- type: "CNAME",- name: hostname,- content: "tunnel-id.cfargotunnel.com",- ttl: 1,- proxied: true,- },- },- ]);- expect(tunnelCalls.map((call) => call.operation)).toEqual([- "list",- "create",- "putConfiguration",- "getToken",- ]);- expect(tunnelCalls[2]?.input).toMatchObject({- tunnelConfig: {- ingress: [- {- hostname,- service: "http://127.0.0.1:3773",- },- { service: "http_status:404" },- ],- },- });- expect(tunnelCalls[0]?.input).toEqual({- name: expectedManagedTunnelName("env_ABC"),- isDeleted: false,- });- expect(allocationCalls.map((call) => call.operation)).toEqual([- "reserve",- "recordTunnel",- "recordDns",- "markReady",- ]);- }).pipe(- Effect.provide(- providerLayer(- makeTunnelClient(tunnelCalls),- makeDnsClient(dnsCalls),- makeAllocations(allocationCalls),- ),- ),- );- });-- it.effect("checks the managed tunnel limit before reserving an allocation", () => {- const limitCalls: Array<{ readonly userId: string; readonly environmentId: string }> = [];-- return Effect.gen(function* () {- const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;- yield* provider.provision({- userId: "user_ABC",- environmentId: "env_ABC",- origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },- });-- expect(limitCalls).toEqual([{ userId: "user_ABC", environmentId: "env_ABC" }]);- }).pipe(- Effect.provide(- providerLayer(- makeTunnelClient(),- makeDnsClient(),- makeAllocations(),- makeTunnelLimits(limitCalls),- ),- ),- );- });-- it.effect("refuses to provision past the managed tunnel limit without side effects", () => {- const tunnelCalls: TunnelCall[] = [];- const dnsCalls: DnsCall[] = [];- const allocationCalls: AllocationCall[] = [];- const exceeded = new ManagedTunnelLimits.ManagedTunnelLimitExceeded({- userId: "user_ABC",- environmentId: "env_ABC",- maxTunnels: 10,- activeTunnels: 10,- });-- return Effect.gen(function* () {- const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;- const error = yield* Effect.flip(- provider.provision({- userId: "user_ABC",- environmentId: "env_ABC",- origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },- }),- );-- expect(error).toBe(exceeded);- expect(tunnelCalls).toEqual([]);- expect(dnsCalls).toEqual([]);- expect(allocationCalls).toEqual([]);- }).pipe(- Effect.provide(- providerLayer(- makeTunnelClient(tunnelCalls),- makeDnsClient(dnsCalls),- makeAllocations(allocationCalls),- makeTunnelLimits([], exceeded),- ),- ),- );- });-- it.effect("uses stage-scoped stable names without leaking unusual environment ids", () => {- const tunnelCalls: TunnelCall[] = [];-- return Effect.gen(function* () {- const environmentId = "ENV With Spaces/../Symbols!" + "x".repeat(80);- const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;- yield* provider.provision({- userId: "user_ABC",- environmentId,- origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },- });-- const requestedName = (- tunnelCalls.find((call) => call.operation === "list")?.input as- | { readonly name?: string }- | undefined- )?.name;- expect(requestedName).toMatch(/^t3coderelay-managedendpoint-dev-julius-[a-f0-9]{16}$/);- const configBody = (- tunnelCalls.find((call) => call.operation === "putConfiguration")?.input as- | { readonly tunnelConfig?: unknown }- | undefined- )?.tunnelConfig;- expect(configBody).toMatchObject({- ingress: [- {- hostname: expect.stringMatching(/^dev-julius-[a-f0-9]{16}\.t3code\.test$/),- },- { service: "http_status:404" },- ],- });- const hostname = (- configBody as- | {- readonly ingress?: readonly [{ readonly hostname?: unknown }, unknown];- }- | undefined- )?.ingress?.[0]?.hostname;- expect(typeof hostname === "string" ? hostname.split(".")[0]?.length : 0).toBeLessThanOrEqual(- 63,- );- expect(tunnelCalls.find((call) => call.operation === "create")?.input).toMatchObject({- name: requestedName,- configSrc: "cloudflare",- });- }).pipe(Effect.provide(providerLayer(makeTunnelClient(tunnelCalls))));- });-- it.effect("formats IPv6 loopback origins as valid Cloudflare ingress service URLs", () => {- const tunnelCalls: TunnelCall[] = [];-- return Effect.gen(function* () {- const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;- yield* provider.provision({- userId: "user_ABC",- environmentId: "env-ipv6",- origin: { localHttpHost: "::1", localHttpPort: 3773 },- });-- expect(- tunnelCalls.find((call) => call.operation === "putConfiguration")?.input,- ).toMatchObject({- tunnelConfig: {- ingress: [- {- service: "http://[::1]:3773",- },- { service: "http_status:404" },- ],- },- });- }).pipe(Effect.provide(providerLayer(makeTunnelClient(tunnelCalls))));- });-- it.effect("rejects non-loopback managed endpoint origins before calling Cloudflare", () => {- const dnsCalls: DnsCall[] = [];-- return Effect.gen(function* () {- const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;- const result = yield* Effect.result(- provider.provision({- userId: "user_ABC",- environmentId: "env_ABC",- origin: { localHttpHost: "192.168.1.10", localHttpPort: 3773 },- }),- );-- expect(dnsCalls).toHaveLength(0);- expect(result._tag).toBe("Failure");- if (result._tag === "Failure") {- expect(result.failure).toMatchObject({- _tag: "ManagedEndpointOriginNotAllowed",- userId: "user_ABC",- environmentId: "env_ABC",- host: "192.168.1.10",- port: 3773,- });- }- }).pipe(Effect.provide(providerLayer(makeTunnelClient(), makeDnsClient(dnsCalls))));- });-- it.effect("rejects invalid managed endpoint origin ports before calling Cloudflare", () => {- const dnsCalls: DnsCall[] = [];-- return Effect.gen(function* () {- const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;- const result = yield* Effect.result(- provider.provision({- userId: "user_ABC",- environmentId: "env_ABC",- origin: { localHttpHost: "127.0.0.1", localHttpPort: 65_536 },- }),- );-- expect(dnsCalls).toHaveLength(0);- expect(result._tag).toBe("Failure");- if (result._tag === "Failure") {- expect(result.failure._tag).toBe("ManagedEndpointOriginNotAllowed");- }- }).pipe(Effect.provide(providerLayer(makeTunnelClient(), makeDnsClient(dnsCalls))));- });-- it.effect("reconciles an existing same-host DNS record through the DNS client", () => {- const dnsCalls: DnsCall[] = [];- return Effect.gen(function* () {- const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;- yield* provider.provision({- userId: "user_ABC",- environmentId: "env_ABC",- origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },- });-- expect(dnsCalls.map((call) => call.operation)).toEqual(["listRecords", "updateRecord"]);- expect(dnsCalls[1]?.input).toMatchObject({ dnsRecordId: "existing-record-id" });- }).pipe(- Effect.provide(- providerLayer(makeTunnelClient(), makeDnsClient(dnsCalls, [{ id: "existing-record-id" }])),- ),- );- });-- it.effect("reuses checkpointed resources when provisioning is retried", () => {- const tunnelCalls: TunnelCall[] = [];- const dnsCalls: DnsCall[] = [];- const allocationCalls: AllocationCall[] = [];- const layer = providerLayer(- makePersistentTunnelClient(tunnelCalls),- makeDnsClient(dnsCalls),- makeAllocations(allocationCalls),- );-- return Effect.gen(function* () {- const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;- const request = {- userId: "user_ABC",- environmentId: "env_ABC",- origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },- } as const;- yield* provider.provision(request);- yield* provider.provision(request);-- expect(tunnelCalls.map((call) => call.operation)).toEqual([- "list",- "create",- "putConfiguration",- "getToken",- "list",- "putConfiguration",- "getToken",- ]);- expect(dnsCalls.map((call) => call.operation)).toEqual([- "listRecords",- "createRecord",- "updateRecord",- ]);- expect(allocationCalls.map((call) => call.operation)).toEqual([- "reserve",- "recordTunnel",- "recordDns",- "markReady",- "reserve",- "recordTunnel",- "recordDns",- "markReady",- ]);- }).pipe(Effect.provide(layer));- });-- it.effect("recreates a checkpointed DNS record when it was removed externally", () => {- const dnsCalls: DnsCall[] = [];- const allocationCalls: AllocationCall[] = [];- const dnsClient = makeDnsClient(dnsCalls);- const layer = providerLayer(- makePersistentTunnelClient(),- dnsClient,- makeAllocations(allocationCalls),- );-- return Effect.gen(function* () {- const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;- const request = {- userId: "user_ABC",- environmentId: "env_ABC",- origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },- } as const;- yield* provider.provision(request);- yield* dnsClient.deleteRecord("created-record-id");- yield* provider.provision(request);-- expect(dnsCalls.map((call) => call.operation)).toEqual([- "listRecords",- "createRecord",- "deleteRecord",- "updateRecord",- "listRecords",- "createRecord",- ]);- }).pipe(Effect.provide(layer));- });-- it.effect("does not hide non-not-found checkpoint update failures", () => {- const dnsCalls: DnsCall[] = [];- const failure = new ManagedEndpointProvider.ManagedEndpointDnsClientError({- operation: "update-record",- dnsRecordId: "created-record-id",- cause: new Error("Cloudflare DNS unavailable"),- });- let records: ReadonlyArray<{ readonly id: string }> = [];- const dnsClient = ManagedEndpointProvider.ManagedEndpointDnsClient.of({- listRecords: (hostname) =>- Effect.sync(() => {- dnsCalls.push({ operation: "listRecords", input: hostname });- return records;- }),- createRecord: (request) =>- Effect.sync(() => {- dnsCalls.push({ operation: "createRecord", input: request });- const record = { id: "created-record-id" };- records = [record];- return record;- }),- updateRecord: (dnsRecordId, request) =>- Effect.sync(() => {- dnsCalls.push({ operation: "updateRecord", input: { dnsRecordId, request } });- }).pipe(Effect.andThen(Effect.fail(failure))),- deleteRecord: () => Effect.void,- });- const layer = providerLayer(makePersistentTunnelClient(), dnsClient, makeAllocations());-- return Effect.gen(function* () {- const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;- const request = {- userId: "user_ABC",- environmentId: "env_ABC",- origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },- } as const;- yield* provider.provision(request);- const error = yield* Effect.flip(provider.provision(request));-- expect(error).toMatchObject({- _tag: "ManagedEndpointProvisioningFailed",- stage: "ensure-dns-record",- userId: "user_ABC",- environmentId: "env_ABC",- });- expect(dnsCalls.map((call) => call.operation)).toEqual([- "listRecords",- "createRecord",- "updateRecord",- ]);- }).pipe(Effect.provide(layer));- });-- it.effect(- "deprovisions checkpointed DNS and tunnel resources before removing the allocation",- () => {- const tunnelCalls: TunnelCall[] = [];- const dnsCalls: DnsCall[] = [];- const allocationCalls: AllocationCall[] = [];- const layer = providerLayer(- makePersistentTunnelClient(tunnelCalls),- makeDnsClient(dnsCalls),- makeAllocations(allocationCalls),- );-- return Effect.gen(function* () {- const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;- const key = { userId: "user_ABC", environmentId: "env_ABC" } as const;- yield* provider.provision({- ...key,- origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },- });- yield* provider.deprovision(key);-- expect(dnsCalls.map((call) => call.operation)).toEqual([- "listRecords",- "createRecord",- "deleteRecord",- ]);- expect(tunnelCalls.map((call) => call.operation)).toEqual([- "list",- "create",- "putConfiguration",- "getToken",- "delete",- ]);- expect(allocationCalls.map((call) => call.operation)).toEqual([- "reserve",- "recordTunnel",- "recordDns",- "markReady",- "get",- "claimDeprovision",- "removeClaimed",- ]);- }).pipe(Effect.provide(layer));- },- );-- it.effect("does not deprovision an allocation superseded by a concurrent relink", () => {- const tunnelCalls: TunnelCall[] = [];- const dnsCalls: DnsCall[] = [];- const allocationCalls: AllocationCall[] = [];- const layer = providerLayer(- makePersistentTunnelClient(tunnelCalls),- makeDnsClient(dnsCalls),- makeAllocations(allocationCalls),- );-- return Effect.gen(function* () {- const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;- const key = { userId: "user_ABC", environmentId: "env_ABC" } as const;- const request = {- ...key,- origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },- } as const;- yield* provider.provision(request);- const unlinkTarget = yield* provider.prepareDeprovision(key);- expect(unlinkTarget).not.toBeNull();- if (unlinkTarget === null) {- return;- }-- // A relink refreshes the allocation generation after unlink captured its- // target but before unlink begins external teardown.- yield* provider.provision(request);- const tunnelCallCount = tunnelCalls.length;- const dnsCallCount = dnsCalls.length;- const allocationCallCount = allocationCalls.length;-- yield* provider.deprovision({ ...key, target: unlinkTarget });-- expect(tunnelCalls).toHaveLength(tunnelCallCount);- expect(dnsCalls).toHaveLength(dnsCallCount);- expect(allocationCalls.slice(allocationCallCount).map((call) => call.operation)).toEqual([- "claimDeprovision",- ]);- }).pipe(Effect.provide(layer));- });-- it.effect("releases the tunnel while keeping the allocation, DNS record, and hostname", () => {- const tunnelCalls: TunnelCall[] = [];- const dnsCalls: DnsCall[] = [];- const allocationCalls: AllocationCall[] = [];- const layer = providerLayer(- makePersistentTunnelClient(tunnelCalls),- makeDnsClient(dnsCalls),- makeAllocations(allocationCalls),- );-- return Effect.gen(function* () {- const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;- const key = { userId: "user_ABC", environmentId: "env_ABC" } as const;- const origin = { localHttpHost: "127.0.0.1", localHttpPort: 3773 } as const;- const first = yield* provider.provision({ ...key, origin });- const released = yield* provider.release(key);- const second = yield* provider.provision({ ...key, origin });-- expect(released).toBe(true);- expect(second.endpoint).toEqual(first.endpoint);- expect(tunnelCalls.map((call) => call.operation)).toEqual([- // first provision- "list",- "create",- "putConfiguration",- "getToken",- // release deletes only the tunnel...- "delete",- // ...and the next provision recreates it under the same name- "list",- "create",- "putConfiguration",- "getToken",- ]);- // The DNS record survives the release and is repointed, never deleted.- expect(dnsCalls.map((call) => call.operation)).toEqual([- "listRecords",- "createRecord",- "updateRecord",- ]);- expect(allocationCalls.map((call) => call.operation)).not.toContain("remove");- }).pipe(Effect.provide(layer));- });-- it.effect("treats an environment without a recorded tunnel as already released", () => {- const tunnelCalls: TunnelCall[] = [];- const dnsCalls: DnsCall[] = [];- const layer = providerLayer(- makePersistentTunnelClient(tunnelCalls),- makeDnsClient(dnsCalls),- makeAllocations(),- );-- return Effect.gen(function* () {- const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;- const released = yield* provider.release({ userId: "user_ABC", environmentId: "env_ABC" });-- expect(released).toBe(true);- expect(tunnelCalls).toEqual([]);- expect(dnsCalls).toEqual([]);- }).pipe(Effect.provide(layer));- });-- it.effect("keeps the tunnel alive when a concurrent provision outdates the release claim", () => {- const tunnelCalls: TunnelCall[] = [];- const allocations = makeAllocations();- // Simulates a provision racing the release: the allocation generation no- // longer matches what the release loaded, so the claim fails.- const outdated = ManagedEndpointAllocations.ManagedEndpointAllocations.of({- ...allocations,- claimRelease: () => Effect.succeed(false),- });- const layer = providerLayer(makePersistentTunnelClient(tunnelCalls), makeDnsClient(), outdated);-- return Effect.gen(function* () {- const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;- const key = { userId: "user_ABC", environmentId: "env_ABC" } as const;- yield* provider.provision({- ...key,- origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },- });- const released = yield* provider.release(key);-- // false tells the caller its connector token is still live, so it must- // keep its runtime config.- expect(released).toBe(false);- expect(tunnelCalls.map((call) => call.operation)).toEqual([- "list",- "create",- "putConfiguration",- "getToken",- ]);- }).pipe(Effect.provide(layer));- });-- it.effect("treats an already deleted tunnel as successfully released", () => {- const notFound = { _tag: "NotFound" } as const;- const tunnelClient = ManagedEndpointProvider.ManagedEndpointTunnelClient.of({- ...makeTunnelClient(),- delete: (tunnelId) =>- Effect.fail(- new ManagedEndpointProvider.ManagedEndpointTunnelClientError({- operation: "delete",- tunnelId,- cause: notFound,- }),- ),- });- const layer = providerLayer(tunnelClient, makeDnsClient(), makeAllocations());-- return Effect.gen(function* () {- const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;- const key = { userId: "user_ABC", environmentId: "env_ABC" } as const;- yield* provider.provision({- ...key,- origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },- });- yield* provider.release(key);- }).pipe(Effect.provide(layer));- });-- it.effect("surfaces non-not-found tunnel deletion failures when releasing", () => {- const failure = new ManagedEndpointProvider.ManagedEndpointTunnelClientError({- operation: "delete",- tunnelId: "tunnel-id",- cause: "Cloudflare tunnel deletion failed",- });- const tunnelClient = ManagedEndpointProvider.ManagedEndpointTunnelClient.of({- ...makeTunnelClient(),- delete: () => Effect.fail(failure),- });- const layer = providerLayer(tunnelClient, makeDnsClient(), makeAllocations());-- return Effect.gen(function* () {- const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;- const key = { userId: "user_ABC", environmentId: "env_ABC" } as const;- yield* provider.provision({- ...key,- origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },- });- const error = yield* Effect.flip(provider.release(key));-- expect(error).toMatchObject({- _tag: "ManagedEndpointDeprovisioningFailed",- stage: "delete-tunnel",- userId: key.userId,- environmentId: key.environmentId,- tunnelId: "tunnel-id",- });- expect(error.cause).toBe(failure);- }).pipe(Effect.provide(layer));- });-- it.effect("treats an absent allocation as already deprovisioned", () => {- const tunnelCalls: TunnelCall[] = [];- const dnsCalls: DnsCall[] = [];- const allocationCalls: AllocationCall[] = [];- const layer = providerLayer(- makePersistentTunnelClient(tunnelCalls),- makeDnsClient(dnsCalls),- makeAllocations(allocationCalls),- );-- return Effect.gen(function* () {- const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;- const key = { userId: "user_ABC", environmentId: "env_ABC" } as const;- yield* provider.deprovision(key);-- expect(tunnelCalls).toEqual([]);- expect(dnsCalls).toEqual([]);- expect(allocationCalls).toEqual([{ operation: "get", input: key }]);- }).pipe(Effect.provide(layer));- });-- it.effect("keeps the allocation when tunnel cleanup fails so unlink can retry", () => {- const allocationCalls: AllocationCall[] = [];- const tunnelCalls: TunnelCall[] = [];- let deleteAttempts = 0;- const failure = new ManagedEndpointProvider.ManagedEndpointTunnelClientError({- operation: "delete",- tunnelId: "tunnel-id",- cause: "Cloudflare tunnel deletion failed",- });- const tunnels = makePersistentTunnelClient(tunnelCalls);- const tunnelClient = ManagedEndpointProvider.ManagedEndpointTunnelClient.of({- ...tunnels,- delete: (tunnelId) =>- Effect.gen(function* () {- tunnelCalls.push({ operation: "delete", input: tunnelId });- deleteAttempts++;- if (deleteAttempts === 1) {- return yield* failure;- }- }),- });- const layer = providerLayer(tunnelClient, makeDnsClient(), makeAllocations(allocationCalls));-- return Effect.gen(function* () {- const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;- const key = { userId: "user_ABC", environmentId: "env_ABC" } as const;- yield* provider.provision({- ...key,- origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },- });- const first = yield* Effect.result(provider.deprovision(key));- expect(first._tag).toBe("Failure");- if (first._tag === "Failure") {- expect(first.failure).toMatchObject({- _tag: "ManagedEndpointDeprovisioningFailed",- stage: "delete-tunnel",- userId: key.userId,- environmentId: key.environmentId,- tunnelId: "tunnel-id",- });- expect(first.failure.cause).toBe(failure);- }- yield* provider.deprovision(key);-- expect(allocationCalls.map((call) => call.operation)).toEqual([- "reserve",- "recordTunnel",- "recordDns",- "markReady",- "get",- "claimDeprovision",- "get",- "claimDeprovision",- "removeClaimed",- ]);- }).pipe(Effect.provide(layer));- });-- it.effect("treats already deleted remote resources as successfully deprovisioned", () => {- const allocationCalls: AllocationCall[] = [];- const notFound = { _tag: "NotFound" } as const;- const tunnelClient = ManagedEndpointProvider.ManagedEndpointTunnelClient.of({- ...makeTunnelClient(),- delete: () =>- Effect.fail(- new ManagedEndpointProvider.ManagedEndpointTunnelClientError({- operation: "delete",- tunnelId: "tunnel-id",- cause: notFound,- }),- ),- });- const dnsClient = ManagedEndpointProvider.ManagedEndpointDnsClient.of({- ...makeDnsClient(),- deleteRecord: () =>- Effect.fail(- new ManagedEndpointProvider.ManagedEndpointDnsClientError({- operation: "delete-record",- dnsRecordId: "created-record-id",- cause: notFound,- }),- ),- });- const layer = providerLayer(tunnelClient, dnsClient, makeAllocations(allocationCalls));-- return Effect.gen(function* () {- const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;- const key = { userId: "user_ABC", environmentId: "env_ABC" } as const;- yield* provider.provision({- ...key,- origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },- });- yield* provider.deprovision(key);-- expect(allocationCalls.map((call) => call.operation)).toContain("removeClaimed");- }).pipe(Effect.provide(layer));- });-- it.effect("scopes managed endpoint resources by user", () => {- const tunnelCalls: TunnelCall[] = [];-- return Effect.gen(function* () {- const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;- yield* provider.provision({- userId: "user_ABC",- environmentId: "env_shared",- origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },- });- yield* provider.provision({- userId: "user_DEF",- environmentId: "env_shared",- origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },- });-- expect(- tunnelCalls.filter((call) => call.operation === "list").map((call) => call.input),- ).toEqual([- { name: expectedManagedTunnelName("env_shared", "user_ABC"), isDeleted: false },- { name: expectedManagedTunnelName("env_shared", "user_DEF"), isDeleted: false },- ]);- }).pipe(Effect.provide(providerLayer(makeTunnelClient(tunnelCalls))));- });-- it.effect("recovers when DNS creation reports failure after the record became visible", () => {- const dnsCalls: DnsCall[] = [];- const failure = new ManagedEndpointProvider.ManagedEndpointDnsClientError({- operation: "create-record",- hostname: expectedManagedHostname("env_ABC"),- cause: "ambiguous Cloudflare DNS response",- });- let records: ReadonlyArray<{ readonly id: string }> = [];- const dnsClient = ManagedEndpointProvider.ManagedEndpointDnsClient.of({- listRecords: (hostname) =>- Effect.sync(() => {- dnsCalls.push({ operation: "listRecords", input: hostname });- return records;- }),- createRecord: (request) =>- Effect.gen(function* () {- dnsCalls.push({ operation: "createRecord", input: request });- records = [{ id: "created-record-id" }];- return yield* failure;- }),- updateRecord: (dnsRecordId, request) =>- Effect.sync(() => {- dnsCalls.push({ operation: "updateRecord", input: { dnsRecordId, request } });- }),- deleteRecord: (dnsRecordId) =>- Effect.sync(() => {- dnsCalls.push({ operation: "deleteRecord", input: dnsRecordId });- }),- });-- return Effect.gen(function* () {- const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;- yield* provider.provision({- userId: "user_ABC",- environmentId: "env_ABC",- origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },- });-- expect(dnsCalls.map((call) => call.operation)).toEqual([- "listRecords",- "createRecord",- "listRecords",- "updateRecord",- ]);- }).pipe(Effect.provide(providerLayer(makeTunnelClient(), dnsClient)));- });-- it.effect("reports mismatched tunnel responses without manufacturing a cause", () => {- const dnsCalls: DnsCall[] = [];- const tunnelClient = ManagedEndpointProvider.ManagedEndpointTunnelClient.of({- ...makeTunnelClient(),- create: () => Effect.succeed({ id: "returned-tunnel-id", name: "unexpected-tunnel" }),- });-- return Effect.gen(function* () {- const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;- const error = yield* Effect.flip(- provider.provision({- userId: "user_ABC",- environmentId: "env_ABC",- origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },- }),- );-- expect(error).toMatchObject({- _tag: "ManagedEndpointProvisioningFailed",- stage: "validate-tunnel-response",- userId: "user_ABC",- environmentId: "env_ABC",- hostname: expectedManagedHostname("env_ABC"),- tunnelName: expectedManagedTunnelName("env_ABC"),- returnedTunnelId: "returned-tunnel-id",- returnedTunnelName: "unexpected-tunnel",- });- if (error._tag === "ManagedEndpointProvisioningFailed") {- expect(error.cause).toBeUndefined();- }- expect(dnsCalls).toHaveLength(0);- }).pipe(Effect.provide(providerLayer(tunnelClient, makeDnsClient(dnsCalls))));- });-- it.effect("fails provisioning when the DNS client fails", () => {- const failure = new ManagedEndpointProvider.ManagedEndpointDnsClientError({- operation: "list-records",- hostname: expectedManagedHostname("env_ABC"),- cause: "Cloudflare DNS failure",- });- const dnsClient = ManagedEndpointProvider.ManagedEndpointDnsClient.of({- listRecords: () => Effect.fail(failure),- createRecord: () => Effect.die("unused"),- updateRecord: () => Effect.die("unused"),- deleteRecord: () => Effect.die("unused"),- });-- return Effect.gen(function* () {- const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider;- const error = yield* Effect.flip(- provider.provision({- userId: "user_ABC",- environmentId: "env_ABC",- origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },- }),- );-- expect(error).toMatchObject({- _tag: "ManagedEndpointProvisioningFailed",- stage: "ensure-dns-record",- userId: "user_ABC",- environmentId: "env_ABC",- hostname: expectedManagedHostname("env_ABC"),- tunnelName: expectedManagedTunnelName("env_ABC"),- tunnelId: "tunnel-id",- });- if (error._tag === "ManagedEndpointProvisioningFailed") {- expect(error.cause).toBe(failure);- }- }).pipe(Effect.provide(providerLayer(makeTunnelClient(), dnsClient)));- });-});diff --git a/infra/relay/src/environments/ManagedEndpointProvider.ts b/infra/relay/src/environments/ManagedEndpointProvider.tsdeleted file mode 100644index 9a5788748..000000000--- a/infra/relay/src/environments/ManagedEndpointProvider.ts+++ /dev/null@@ -1,993 +0,0 @@-import * as Alchemy from "alchemy";-import * as Cloudflare from "alchemy/Cloudflare";-import * as Arr from "effect/Array";-import * as Context from "effect/Context";-import * as Crypto from "effect/Crypto";-import * as Effect from "effect/Effect";-import * as Encoding from "effect/Encoding";-import * as Layer from "effect/Layer";-import * as Option from "effect/Option";-import * as Schema from "effect/Schema";--import type {- RelayManagedEndpoint,- RelayManagedEndpointOrigin,- RelayManagedEndpointRuntimeConfig,-} from "@t3tools/contracts/relay";--import * as RelayConfiguration from "../Config.ts";-import {- managedEndpointDigestInput,- managedEndpointForHostname,- managedEndpointHostname,- managedEndpointTunnelName,-} from "../deploymentConfig.ts";-import * as ManagedEndpointAllocations from "./ManagedEndpointAllocations.ts";-import * as ManagedTunnelLimits from "./ManagedTunnelLimits.ts";--export class ManagedEndpointProvisioningNotConfigured extends Schema.TaggedErrorClass<ManagedEndpointProvisioningNotConfigured>()(- "ManagedEndpointProvisioningNotConfigured",- {- userId: Schema.String,- environmentId: Schema.String,- missingSettings: Schema.Array(- Schema.Literals(["managedEndpointBaseDomain", "managedEndpointNamespace"]),- ),- },-) {- override get message(): string {- return `Managed endpoint provisioning is not configured for user '${this.userId}', environment '${this.environmentId}': missing ${this.missingSettings.join(", ")}`;- }-}--const ManagedEndpointProvisioningStage = Schema.Literals([- "derive-environment-hash",- "check-tunnel-limit",- "reserve-allocation",- "ensure-tunnel",- "validate-tunnel-response",- "record-tunnel",- "configure-tunnel",- "ensure-dns-record",- "record-dns",- "get-tunnel-token",- "mark-allocation-ready",-]);--export class ManagedEndpointProvisioningFailed extends Schema.TaggedErrorClass<ManagedEndpointProvisioningFailed>()(- "ManagedEndpointProvisioningFailed",- {- stage: ManagedEndpointProvisioningStage,- userId: Schema.String,- environmentId: Schema.String,- hostname: Schema.optionalKey(Schema.String),- tunnelName: Schema.optionalKey(Schema.String),- tunnelId: Schema.optionalKey(Schema.String),- dnsRecordId: Schema.optionalKey(Schema.String),- returnedTunnelName: Schema.optionalKey(Schema.String),- returnedTunnelId: Schema.optionalKey(Schema.String),- cause: Schema.optional(Schema.Defect()),- },-) {- override get message(): string {- return `Managed endpoint provisioning failed during '${this.stage}' for user '${this.userId}', environment '${this.environmentId}'`;- }-}--const ManagedEndpointDeprovisioningStage = Schema.Literals([- "load-allocation",- "claim-release",- "claim-deprovision",- "delete-dns-record",- "delete-tunnel",- "remove-allocation",-]);--export class ManagedEndpointDeprovisioningFailed extends Schema.TaggedErrorClass<ManagedEndpointDeprovisioningFailed>()(- "ManagedEndpointDeprovisioningFailed",- {- stage: ManagedEndpointDeprovisioningStage,- userId: Schema.String,- environmentId: Schema.String,- tunnelId: Schema.optionalKey(Schema.String),- dnsRecordId: Schema.optionalKey(Schema.String),- cause: Schema.Defect(),- },-) {- override get message(): string {- return `Managed endpoint deprovisioning failed during '${this.stage}' for user '${this.userId}', environment '${this.environmentId}'`;- }-}--export class ManagedEndpointOriginNotAllowed extends Schema.TaggedErrorClass<ManagedEndpointOriginNotAllowed>()(- "ManagedEndpointOriginNotAllowed",- {- userId: Schema.String,- environmentId: Schema.String,- host: Schema.String,- port: Schema.Number,- },-) {- override get message(): string {- return `Managed endpoint origin '${this.host}:${this.port}' is not allowed for user '${this.userId}', environment '${this.environmentId}'`;- }-}--export type ManagedEndpointProviderError =- | ManagedEndpointProvisioningNotConfigured- | ManagedEndpointProvisioningFailed- | ManagedEndpointOriginNotAllowed- | ManagedTunnelLimits.ManagedTunnelLimitExceeded;--export interface ManagedEndpointProvisioningResult {- readonly endpoint: RelayManagedEndpoint;- readonly runtime: RelayManagedEndpointRuntimeConfig;-}--export type ManagedEndpointDeprovisionTarget = ManagedEndpointAllocations.ManagedEndpointAllocation;--export class ManagedEndpointProvider extends Context.Service<- ManagedEndpointProvider,- {- readonly provision: (input: {- readonly userId: string;- readonly environmentId: string;- readonly origin: RelayManagedEndpointOrigin;- }) => Effect.Effect<ManagedEndpointProvisioningResult, ManagedEndpointProviderError>;- /**- * Captures the allocation generation owned by an unlink before its link- * revocation commits. Passing this target to `deprovision` prevents a- * concurrent relink from having its newer allocation torn down.- */- readonly prepareDeprovision: (input: {- readonly userId: string;- readonly environmentId: string;- }) => Effect.Effect<- ManagedEndpointDeprovisionTarget | null,- ManagedEndpointDeprovisioningFailed- >;- readonly deprovision: (input: {- readonly userId: string;- readonly environmentId: string;- readonly target?: ManagedEndpointDeprovisionTarget | null;- }) => Effect.Effect<void, ManagedEndpointDeprovisioningFailed>;- /**- * Deletes the provisioned Cloudflare tunnel while keeping the allocation- * (hostname + tunnel name reservation) and DNS record. Cloudflare bills per- * provisioned tunnel, so environments release the tunnel when they shut- * down; the next `provision` recreates it under the same name and repoints- * the CNAME, preserving the endpoint URL.- *- * Resolves to whether the caller's connector token is now dead: true when- * the tunnel was deleted (or none was recorded to begin with), false when- * a concurrent provision outbid the release claim and the recorded tunnel- * — and any token issued for it — stays live.- */- readonly release: (input: {- readonly userId: string;- readonly environmentId: string;- }) => Effect.Effect<boolean, ManagedEndpointDeprovisioningFailed>;- }->()("t3code-relay/environments/ManagedEndpointProvider") {}--interface ManagedEndpointTunnel {- readonly id?: string | null;- readonly name?: string | null;-}--const ManagedEndpointTunnelClientOperation = Schema.Literals([- "list",- "create",- "put-configuration",- "get-token",- "delete",-]);--export class ManagedEndpointTunnelClientError extends Schema.TaggedErrorClass<ManagedEndpointTunnelClientError>()(- "ManagedEndpointTunnelClientError",- {- operation: ManagedEndpointTunnelClientOperation,- tunnelName: Schema.optionalKey(Schema.String),- tunnelId: Schema.optionalKey(Schema.String),- cause: Schema.Defect(),- },-) {- override get message(): string {- const target = this.tunnelId ?? this.tunnelName;- return `Managed endpoint tunnel provider '${this.operation}' request failed${target === undefined ? "" : ` for '${target}'`}`;- }-}--export class ManagedEndpointTunnelClient extends Context.Service<- ManagedEndpointTunnelClient,- {- readonly list: (request: {- readonly name: string;- readonly isDeleted: false;- }) => Effect.Effect<- { readonly result: ReadonlyArray<ManagedEndpointTunnel> },- ManagedEndpointTunnelClientError- >;- readonly create: (request: {- readonly name: string;- readonly configSrc: "cloudflare";- }) => Effect.Effect<ManagedEndpointTunnel, ManagedEndpointTunnelClientError>;- readonly putConfiguration: (- tunnelId: string,- config: {- readonly ingress: Array<{- readonly hostname?: string;- readonly service: string;- }>;- },- ) => Effect.Effect<unknown, ManagedEndpointTunnelClientError>;- readonly getToken: (- tunnelId: string,- ) => Effect.Effect<string, ManagedEndpointTunnelClientError>;- readonly delete: (tunnelId: string) => Effect.Effect<unknown, ManagedEndpointTunnelClientError>;- }->()("t3code-relay/environments/ManagedEndpointProvider/ManagedEndpointTunnelClient") {}--export const layerTunnelClient = (client: ManagedEndpointTunnelClient["Service"]) =>- Layer.succeed(ManagedEndpointTunnelClient, client);--interface ManagedEndpointCnameRecordInput {- readonly type: "CNAME";- readonly name: string;- readonly content: string;- readonly ttl: 1;- readonly proxied: true;-}--const ManagedEndpointDnsClientOperation = Schema.Literals([- "list-records",- "create-record",- "update-record",- "delete-record",-]);--export class ManagedEndpointDnsClientError extends Schema.TaggedErrorClass<ManagedEndpointDnsClientError>()(- "ManagedEndpointDnsClientError",- {- operation: ManagedEndpointDnsClientOperation,- hostname: Schema.optionalKey(Schema.String),- dnsRecordId: Schema.optionalKey(Schema.String),- cause: Schema.Defect(),- },-) {- override get message(): string {- const target = this.dnsRecordId ?? this.hostname;- return `Managed endpoint DNS provider '${this.operation}' request failed${target === undefined ? "" : ` for '${target}'`}`;- }-}--export class ManagedEndpointDnsClient extends Context.Service<- ManagedEndpointDnsClient,- {- readonly listRecords: (- hostname: string,- ) => Effect.Effect<ReadonlyArray<{ readonly id: string }>, ManagedEndpointDnsClientError>;- readonly createRecord: (- request: ManagedEndpointCnameRecordInput,- ) => Effect.Effect<{ readonly id: string }, ManagedEndpointDnsClientError>;- readonly updateRecord: (- dnsRecordId: string,- request: ManagedEndpointCnameRecordInput,- ) => Effect.Effect<unknown, ManagedEndpointDnsClientError>;- readonly deleteRecord: (- dnsRecordId: string,- ) => Effect.Effect<unknown, ManagedEndpointDnsClientError>;- }->()("t3code-relay/environments/ManagedEndpointProvider/ManagedEndpointDnsClient") {}--export const layerDnsClient = (client: ManagedEndpointDnsClient["Service"]) =>- Layer.succeed(ManagedEndpointDnsClient, client);--const requireCloudflareSettings = Effect.fnUntraced(function* (- settings: RelayConfiguration.RelayConfiguration["Service"],- input: { readonly userId: string; readonly environmentId: string },-) {- const baseDomain = settings.managedEndpointBaseDomain;- const namespace = settings.managedEndpointNamespace;- const missingSettings: Array<"managedEndpointBaseDomain" | "managedEndpointNamespace"> = [];- if (!baseDomain) {- missingSettings.push("managedEndpointBaseDomain");- }- if (!namespace) {- missingSettings.push("managedEndpointNamespace");- }- if (!baseDomain || !namespace) {- return yield* new ManagedEndpointProvisioningNotConfigured({- ...input,- missingSettings,- });- }- return {- baseDomain,- namespace,- };-});--function formatOriginService(origin: RelayManagedEndpointOrigin): string {- const host = origin.localHttpHost.includes(":")- ? `[${origin.localHttpHost.replace(/^\[(.*)\]$/u, "$1")}]`- : origin.localHttpHost;- return `http://${host}:${origin.localHttpPort}`;-}--function normalizeHostname(hostname: string): string {- return hostname- .trim()- .toLowerCase()- .replace(/\.$/u, "")- .replace(/^\[(.*)\]$/u, "$1");-}--function isLoopbackOrigin(origin: RelayManagedEndpointOrigin): boolean {- const hostname = normalizeHostname(origin.localHttpHost);- return (- (hostname === "127.0.0.1" || hostname === "::1" || hostname === "localhost") &&- Number.isInteger(origin.localHttpPort) &&- origin.localHttpPort > 0 &&- origin.localHttpPort <= 65_535- );-}--function isNotFoundCause(cause: unknown): boolean {- if (typeof cause !== "object" || cause === null) {- return false;- }- if ("_tag" in cause && cause._tag === "NotFound") {- return true;- }- if ("status" in cause && cause.status === 404) {- return true;- }- return "cause" in cause && isNotFoundCause(cause.cause);-}--type ManagedEndpointClientError = ManagedEndpointTunnelClientError | ManagedEndpointDnsClientError;--const ignoreNotFound = <A>(- effect: Effect.Effect<A, ManagedEndpointClientError>,-): Effect.Effect<void, ManagedEndpointClientError> =>- effect.pipe(- Effect.asVoid,- Effect.catchTags({- ManagedEndpointTunnelClientError: (error) =>- isNotFoundCause(error.cause) ? Effect.void : Effect.fail(error),- ManagedEndpointDnsClientError: (error) =>- isNotFoundCause(error.cause) ? Effect.void : Effect.fail(error),- }),- );--export const make = Effect.gen(function* () {- const config = yield* RelayConfiguration.RelayConfiguration;- const crypto = yield* Crypto.Crypto;- const tunnels = yield* ManagedEndpointTunnelClient;- const dns = yield* ManagedEndpointDnsClient;- const allocations = yield* ManagedEndpointAllocations.ManagedEndpointAllocations;- const tunnelLimits = yield* ManagedTunnelLimits.ManagedTunnelLimits;-- const updateExistingDnsRecords = Effect.fnUntraced(function* (- records: ReadonlyArray<{ readonly id: string }>,- preferredDnsRecordId: string | null,- dnsRecord: ManagedEndpointCnameRecordInput,- ) {- const keptRecord = records.find((record) => record.id === preferredDnsRecordId) ?? records[0];- if (keptRecord === undefined) {- return null;- }- yield* Effect.forEach(- records,- (record) => (record.id === keptRecord.id ? Effect.void : dns.deleteRecord(record.id)),- { discard: true },- );- yield* dns.updateRecord(keptRecord.id, dnsRecord);- return keptRecord.id;- });-- const ensureDnsRecord = Effect.fnUntraced(function* (- hostname: string,- preferredDnsRecordId: string | null,- dnsRecord: ManagedEndpointCnameRecordInput,- ) {- if (preferredDnsRecordId !== null) {- const checkpointedRecordUpdated = yield* dns- .updateRecord(preferredDnsRecordId, dnsRecord)- .pipe(- Effect.as(true),- Effect.catchTags({- ManagedEndpointDnsClientError: (error) =>- isNotFoundCause(error.cause) ? Effect.succeed(false) : Effect.fail(error),- }),- );- if (checkpointedRecordUpdated) {- return preferredDnsRecordId;- }- }- const existingDnsRecords = yield* dns.listRecords(hostname);- const existingDnsRecordId = yield* updateExistingDnsRecords(- existingDnsRecords,- preferredDnsRecordId,- dnsRecord,- );- if (existingDnsRecordId !== null) {- return existingDnsRecordId;- }- return yield* dns.createRecord(dnsRecord).pipe(- Effect.map((record) => record.id),- Effect.catchTags({- ManagedEndpointDnsClientError: (createError) =>- Effect.gen(function* () {- let records = yield* dns.listRecords(hostname);- for (let attempt = 0; records.length === 0 && attempt < 4; attempt++) {- yield* Effect.sleep("200 millis");- records = yield* dns.listRecords(hostname);- }- return records;- }).pipe(- Effect.flatMap((records) =>- records.length > 0- ? updateExistingDnsRecords(records, preferredDnsRecordId, dnsRecord)- : Effect.fail(createError),- ),- Effect.flatMap((dnsRecordId) =>- dnsRecordId === null ? Effect.fail(createError) : Effect.succeed(dnsRecordId),- ),- ),- }),- );- });-- const prepareDeprovision = Effect.fn("relay.managed_endpoint_provider.prepare_deprovision")(- function* (input: { readonly userId: string; readonly environmentId: string }) {- return yield* allocations.get(input).pipe(- Effect.mapError(- (cause) =>- new ManagedEndpointDeprovisioningFailed({- ...input,- stage: "load-allocation",- cause,- }),- ),- );- },- );-- return ManagedEndpointProvider.of({- prepareDeprovision,- deprovision: Effect.fn("relay.managed_endpoint_provider.deprovision")(function* (input) {- yield* Effect.annotateCurrentSpan({- "relay.user_id": input.userId,- "relay.environment_id": input.environmentId,- });- const allocation =- input.target === undefined ? yield* prepareDeprovision(input) : input.target;- if (allocation === null) {- return;- }- const claimedAt = yield* allocations- .claimDeprovision({- userId: input.userId,- environmentId: input.environmentId,- updatedAt: allocation.updatedAt,- })- .pipe(- Effect.mapError(- (cause) =>- new ManagedEndpointDeprovisioningFailed({- ...input,- stage: "claim-deprovision",- ...(allocation.tunnelId === null ? {} : { tunnelId: allocation.tunnelId }),- ...(allocation.dnsRecordId === null ? {} : { dnsRecordId: allocation.dnsRecordId }),- cause,- }),- ),- );- if (claimedAt === null) {- return;- }- const dnsRecordId = allocation.dnsRecordId;- if (dnsRecordId !== null) {- yield* ignoreNotFound(dns.deleteRecord(dnsRecordId)).pipe(- Effect.mapError(- (cause) =>- new ManagedEndpointDeprovisioningFailed({- ...input,- stage: "delete-dns-record",- dnsRecordId,- cause,- }),- ),- );- }- const tunnelId = allocation.tunnelId;- if (tunnelId !== null) {- yield* ignoreNotFound(tunnels.delete(tunnelId)).pipe(- Effect.mapError(- (cause) =>- new ManagedEndpointDeprovisioningFailed({- ...input,- stage: "delete-tunnel",- tunnelId,- cause,- }),- ),- );- }- yield* allocations- .removeClaimed({- userId: input.userId,- environmentId: input.environmentId,- updatedAt: claimedAt,- })- .pipe(- Effect.mapError(- (cause) =>- new ManagedEndpointDeprovisioningFailed({- ...input,- stage: "remove-allocation",- ...(allocation.tunnelId === null ? {} : { tunnelId: allocation.tunnelId }),- ...(allocation.dnsRecordId === null ? {} : { dnsRecordId: allocation.dnsRecordId }),- cause,- }),- ),- );- }),- release: Effect.fn("relay.managed_endpoint_provider.release")(function* (input) {- yield* Effect.annotateCurrentSpan({- "relay.user_id": input.userId,- "relay.environment_id": input.environmentId,- });- const allocation = yield* allocations.get(input).pipe(- Effect.mapError(- (cause) =>- new ManagedEndpointDeprovisioningFailed({- ...input,- stage: "load-allocation",- cause,- }),- ),- );- const tunnelId = allocation?.tunnelId ?? null;- if (allocation === null || tunnelId === null) {- return true;- }- // Claim the release against the allocation's current generation before- // touching Cloudflare. A provision racing this release (fast environment- // restart) rewrites updatedAt when it records its tunnel, so a stale- // claim means the recorded tunnel may already back a fresh connector and- // must be left alive. A provision that starts after the claim instead- // fails loudly on the deleted tunnel and the client-side retry- // provisions a replacement.- const claimed = yield* allocations- .claimRelease({- userId: input.userId,- environmentId: input.environmentId,- tunnelId,- updatedAt: allocation.updatedAt,- })- .pipe(- Effect.mapError(- (cause) =>- new ManagedEndpointDeprovisioningFailed({- ...input,- stage: "claim-release",- tunnelId,- cause,- }),- ),- );- if (!claimed) {- return false;- }- yield* ignoreNotFound(tunnels.delete(tunnelId)).pipe(- Effect.mapError(- (cause) =>- new ManagedEndpointDeprovisioningFailed({- ...input,- stage: "delete-tunnel",- tunnelId,- cause,- }),- ),- );- // The recorded tunnelId is now stale, but the allocation row is left- // untouched deliberately: connect/status authorization requires a fully- // recorded allocation, and an offline environment must keep reporting- // "offline" (health probe fails) rather than "not authorized". The next- // provision lists tunnels by name, finds none, creates a replacement and- // re-records the fresh id.- return true;- }),- provision: Effect.fn("relay.managed_endpoint_provider.provision")(function* (input) {- yield* Effect.annotateCurrentSpan({- "relay.user_id": input.userId,- "relay.environment_id": input.environmentId,- "relay.managed_endpoint.origin_host": input.origin.localHttpHost,- "relay.managed_endpoint.origin_port": input.origin.localHttpPort,- });- if (!isLoopbackOrigin(input.origin)) {- return yield* new ManagedEndpointOriginNotAllowed({- userId: input.userId,- environmentId: input.environmentId,- host: input.origin.localHttpHost,- port: input.origin.localHttpPort,- });- }- const cf = yield* requireCloudflareSettings(config, input);- const environmentHash = yield* crypto- .digest(- "SHA-256",- new TextEncoder().encode(- managedEndpointDigestInput(cf.namespace, input.userId, input.environmentId),- ),- )- .pipe(- Effect.map(Encoding.encodeHex),- Effect.mapError(- (cause) =>- new ManagedEndpointProvisioningFailed({- userId: input.userId,- environmentId: input.environmentId,- stage: "derive-environment-hash",- cause,- }),- ),- );- const requestedHostname = managedEndpointHostname(- cf.namespace,- cf.baseDomain,- environmentHash,- );- const requestedTunnelName = managedEndpointTunnelName(cf.namespace, environmentHash);- yield* tunnelLimits- .ensureCapacity({- userId: input.userId,- environmentId: input.environmentId,- })- .pipe(- Effect.catchTags({- ManagedTunnelLimitPersistenceError: (cause) =>- Effect.fail(- new ManagedEndpointProvisioningFailed({- userId: input.userId,- environmentId: input.environmentId,- stage: "check-tunnel-limit",- hostname: requestedHostname,- tunnelName: requestedTunnelName,- cause,- }),- ),- }),- );- const allocation = yield* allocations- .reserve({- userId: input.userId,- environmentId: input.environmentId,- hostname: requestedHostname,- tunnelName: requestedTunnelName,- })- .pipe(- Effect.mapError(- (cause) =>- new ManagedEndpointProvisioningFailed({- userId: input.userId,- environmentId: input.environmentId,- stage: "reserve-allocation",- hostname: requestedHostname,- tunnelName: requestedTunnelName,- cause,- }),- ),- );- const { hostname, tunnelName } = allocation;-- const tunnelResponse = yield* tunnels.list({ name: tunnelName, isDeleted: false }).pipe(- Effect.map((tunnels) => tunnels.result),- Effect.map(Arr.findFirst((tunnel) => tunnel.name === tunnelName)),- Effect.flatMap(- Option.match({- onSome: (tunnel) => Effect.succeed(tunnel),- onNone: () => tunnels.create({ name: tunnelName, configSrc: "cloudflare" }),- }),- ),- Effect.mapError(- (cause) =>- new ManagedEndpointProvisioningFailed({- userId: input.userId,- environmentId: input.environmentId,- stage: "ensure-tunnel",- hostname,- tunnelName,- cause,- }),- ),- );- if (!tunnelResponse.id || tunnelResponse.name !== tunnelName) {- return yield* new ManagedEndpointProvisioningFailed({- userId: input.userId,- environmentId: input.environmentId,- stage: "validate-tunnel-response",- hostname,- tunnelName,- ...(tunnelResponse.id ? { returnedTunnelId: tunnelResponse.id } : {}),- ...(tunnelResponse.name ? { returnedTunnelName: tunnelResponse.name } : {}),- });- }- const tunnel = { id: tunnelResponse.id, name: tunnelResponse.name };- yield* allocations- .recordTunnel({- userId: input.userId,- environmentId: input.environmentId,- tunnelId: tunnel.id,- })- .pipe(- Effect.mapError(- (cause) =>- new ManagedEndpointProvisioningFailed({- userId: input.userId,- environmentId: input.environmentId,- stage: "record-tunnel",- hostname,- tunnelName,- tunnelId: tunnel.id,- cause,- }),- ),- );-- yield* tunnels- .putConfiguration(tunnel.id, {- ingress: [- {- hostname,- service: formatOriginService(input.origin),- },- { service: "http_status:404" },- ],- })- .pipe(- Effect.mapError(- (cause) =>- new ManagedEndpointProvisioningFailed({- userId: input.userId,- environmentId: input.environmentId,- stage: "configure-tunnel",- hostname,- tunnelName,- tunnelId: tunnel.id,- cause,- }),- ),- );-- const dnsRecord = {- type: "CNAME",- name: hostname,- content: `${tunnel.id}.cfargotunnel.com`,- ttl: 1,- proxied: true,- } as const;-- const dnsRecordId = yield* ensureDnsRecord(hostname, allocation.dnsRecordId, dnsRecord).pipe(- Effect.mapError(- (cause) =>- new ManagedEndpointProvisioningFailed({- userId: input.userId,- environmentId: input.environmentId,- stage: "ensure-dns-record",- hostname,- tunnelName,- tunnelId: tunnel.id,- ...(allocation.dnsRecordId === null ? {} : { dnsRecordId: allocation.dnsRecordId }),- cause,- }),- ),- );- yield* allocations- .recordDns({- userId: input.userId,- environmentId: input.environmentId,- dnsRecordId,- })- .pipe(- Effect.mapError(- (cause) =>- new ManagedEndpointProvisioningFailed({- userId: input.userId,- environmentId: input.environmentId,- stage: "record-dns",- hostname,- tunnelName,- tunnelId: tunnel.id,- dnsRecordId,- cause,- }),- ),- );-- const connectorToken = yield* tunnels.getToken(tunnel.id).pipe(- Effect.mapError(- (cause) =>- new ManagedEndpointProvisioningFailed({- userId: input.userId,- environmentId: input.environmentId,- stage: "get-tunnel-token",- hostname,- tunnelName,- tunnelId: tunnel.id,- dnsRecordId,- cause,- }),- ),- );- yield* allocations- .markReady({- userId: input.userId,- environmentId: input.environmentId,- })- .pipe(- Effect.mapError(- (cause) =>- new ManagedEndpointProvisioningFailed({- userId: input.userId,- environmentId: input.environmentId,- stage: "mark-allocation-ready",- hostname,- tunnelName,- tunnelId: tunnel.id,- dnsRecordId,- cause,- }),- ),- );-- return {- endpoint: managedEndpointForHostname(hostname),- runtime: {- providerKind: "cloudflare_tunnel",- connectorToken,- tunnelId: tunnel.id,- tunnelName: tunnel.name,- },- } satisfies ManagedEndpointProvisioningResult;- }),- });-});--export const layer = Layer.effect(ManagedEndpointProvider, make);--export const layerCloudflareBindings = (- tunnelClient: Cloudflare.Tunnel.ReadWriteTunnelClient,- dnsClient: Cloudflare.DNS.ReadWriteDnsClient,- alchemyRuntimeContext: Alchemy.BaseRuntimeContext,-) =>- layer.pipe(- Layer.provide(- Layer.mergeAll(- layerTunnelClient({- list: (request) =>- tunnelClient.list(request).pipe(- Effect.mapError(- (cause) =>- new ManagedEndpointTunnelClientError({- operation: "list",- tunnelName: request.name,- cause,- }),- ),- Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),- ),- create: (request) =>- tunnelClient.create(request).pipe(- Effect.mapError(- (cause) =>- new ManagedEndpointTunnelClientError({- operation: "create",- tunnelName: request.name,- cause,- }),- ),- Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),- ),- putConfiguration: (tunnelId, config) =>- tunnelClient.putConfiguration(tunnelId, config).pipe(- Effect.mapError(- (cause) =>- new ManagedEndpointTunnelClientError({- operation: "put-configuration",- tunnelId,- cause,- }),- ),- Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),- ),- getToken: (tunnelId) =>- tunnelClient.getToken(tunnelId).pipe(- Effect.mapError(- (cause) =>- new ManagedEndpointTunnelClientError({- operation: "get-token",- tunnelId,- cause,- }),- ),- Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),- ),- delete: (tunnelId) =>- tunnelClient.delete(tunnelId).pipe(- Effect.mapError(- (cause) =>- new ManagedEndpointTunnelClientError({- operation: "delete",- tunnelId,- cause,- }),- ),- Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),- ),- }),- layerDnsClient({- listRecords: (hostname) =>- dnsClient.listDnsRecords({ search: hostname }).pipe(- Effect.map((response) =>- response.result.filter(- (record): record is typeof record & { readonly id: string } =>- typeof record.id === "string" &&- normalizeHostname(record.name) === normalizeHostname(hostname),- ),- ),- Effect.mapError(- (cause) =>- new ManagedEndpointDnsClientError({- operation: "list-records",- hostname,- cause,- }),- ),- Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),- ),- createRecord: (request) =>- dnsClient.createDnsRecord(request).pipe(- Effect.map((response) => ({ id: response.id })),- Effect.mapError(- (cause) =>- new ManagedEndpointDnsClientError({- operation: "create-record",- hostname: request.name,- cause,- }),- ),- Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),- ),- updateRecord: (dnsRecordId, request) =>- dnsClient.updateDnsRecord(dnsRecordId, request).pipe(- Effect.mapError(- (cause) =>- new ManagedEndpointDnsClientError({- operation: "update-record",- hostname: request.name,- dnsRecordId,- cause,- }),- ),- Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),- ),- deleteRecord: (dnsRecordId) =>- dnsClient.deleteDnsRecord(dnsRecordId).pipe(- Effect.mapError(- (cause) =>- new ManagedEndpointDnsClientError({- operation: "delete-record",- dnsRecordId,- cause,- }),- ),- Effect.provideService(Alchemy.RuntimeContext, alchemyRuntimeContext),- ),- }),- ),- ),- );diff --git a/infra/relay/src/environments/ManagedTunnelLimits.test.ts b/infra/relay/src/environments/ManagedTunnelLimits.test.tsdeleted file mode 100644index b53a487ee..000000000--- a/infra/relay/src/environments/ManagedTunnelLimits.test.ts+++ /dev/null@@ -1,155 +0,0 @@-import { describe, expect, it } from "@effect/vitest";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";--import * as RelayDb from "../db.ts";-import {- relayEnvironmentLinks,- relayManagedEndpointAllocations,- relayManagedTunnelLimits,-} from "../persistence/schema.ts";-import * as ManagedTunnelLimits from "./ManagedTunnelLimits.ts";--const layerWithDb = (db: RelayDb.RelayDb["Service"]) =>- ManagedTunnelLimits.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, db)));--function makeFakeDb(input: {- readonly overrideRows?: Effect.Effect<ReadonlyArray<{ readonly maxTunnels: number }>, Error>;- readonly countRows?: Effect.Effect<ReadonlyArray<{ readonly activeTunnels: number }>, Error>;-}) {- return {- select: () => ({- from: (table: unknown) => {- if (table === relayManagedTunnelLimits) {- return {- where: () => ({- limit: () => input.overrideRows ?? Effect.succeed([]),- }),- };- }- expect(table).toBe(relayManagedEndpointAllocations);- return {- innerJoin: (table: unknown, condition: unknown) => {- expect(table).toBe(relayEnvironmentLinks);- expect(condition).toBeDefined();- return {- where: (where: unknown) => {- expect(where).toBeDefined();- return input.countRows ?? Effect.succeed([{ activeTunnels: 0 }]);- },- };- },- };- },- }),- } as unknown as RelayDb.RelayDb["Service"];-}--describe("ManagedTunnelLimits", () => {- it.effect("allows provisioning below the default limit", () => {- const fakeDb = makeFakeDb({- countRows: Effect.succeed([- { activeTunnels: ManagedTunnelLimits.DEFAULT_MANAGED_TUNNEL_LIMIT - 1 },- ]),- });-- return Effect.gen(function* () {- const limits = yield* ManagedTunnelLimits.ManagedTunnelLimits;- yield* limits.ensureCapacity({ userId: "user-1", environmentId: "environment-1" });- }).pipe(Effect.provide(layerWithDb(fakeDb)));- });-- it.effect("rejects provisioning at the default limit of 3", () => {- const fakeDb = makeFakeDb({- countRows: Effect.succeed([{ activeTunnels: 3 }]),- });-- return Effect.gen(function* () {- const limits = yield* ManagedTunnelLimits.ManagedTunnelLimits;- const error = yield* Effect.flip(- limits.ensureCapacity({ userId: "user-1", environmentId: "environment-1" }),- );-- expect(error).toMatchObject({- _tag: "ManagedTunnelLimitExceeded",- userId: "user-1",- environmentId: "environment-1",- maxTunnels: 3,- activeTunnels: 3,- });- }).pipe(Effect.provide(layerWithDb(fakeDb)));- });-- it.effect("honors a per-user override above the default", () => {- const fakeDb = makeFakeDb({- overrideRows: Effect.succeed([{ maxTunnels: 25 }]),- countRows: Effect.succeed([{ activeTunnels: 10 }]),- });-- return Effect.gen(function* () {- const limits = yield* ManagedTunnelLimits.ManagedTunnelLimits;- yield* limits.ensureCapacity({ userId: "user-1", environmentId: "environment-1" });- }).pipe(Effect.provide(layerWithDb(fakeDb)));- });-- it.effect("honors a per-user override below the default", () => {- const fakeDb = makeFakeDb({- overrideRows: Effect.succeed([{ maxTunnels: 1 }]),- countRows: Effect.succeed([{ activeTunnels: 1 }]),- });-- return Effect.gen(function* () {- const limits = yield* ManagedTunnelLimits.ManagedTunnelLimits;- const error = yield* Effect.flip(- limits.ensureCapacity({ userId: "user-1", environmentId: "environment-1" }),- );-- expect(error).toMatchObject({- _tag: "ManagedTunnelLimitExceeded",- maxTunnels: 1,- activeTunnels: 1,- });- }).pipe(Effect.provide(layerWithDb(fakeDb)));- });-- it.effect("retains database failures with operation and user identity", () => {- const cause = new Error("database unavailable");- const fakeDb = makeFakeDb({- overrideRows: Effect.fail(cause),- });-- return Effect.gen(function* () {- const limits = yield* ManagedTunnelLimits.ManagedTunnelLimits;- const error = yield* Effect.flip(- limits.ensureCapacity({ userId: "user-1", environmentId: "environment-1" }),- );-- expect(error).toMatchObject({- _tag: "ManagedTunnelLimitPersistenceError",- operation: "load-limit",- userId: "user-1",- });- expect(error).toHaveProperty("cause", cause);- }).pipe(Effect.provide(layerWithDb(fakeDb)));- });-- it.effect("retains count failures with operation and user identity", () => {- const cause = new Error("database unavailable");- const fakeDb = makeFakeDb({- countRows: Effect.fail(cause),- });-- return Effect.gen(function* () {- const limits = yield* ManagedTunnelLimits.ManagedTunnelLimits;- const error = yield* Effect.flip(- limits.ensureCapacity({ userId: "user-1", environmentId: "environment-1" }),- );-- expect(error).toMatchObject({- _tag: "ManagedTunnelLimitPersistenceError",- operation: "count-tunnels",- userId: "user-1",- });- }).pipe(Effect.provide(layerWithDb(fakeDb)));- });-});diff --git a/infra/relay/src/environments/ManagedTunnelLimits.ts b/infra/relay/src/environments/ManagedTunnelLimits.tsdeleted file mode 100644index 9d8b9c796..000000000--- a/infra/relay/src/environments/ManagedTunnelLimits.ts+++ /dev/null@@ -1,124 +0,0 @@-import { and, count, eq, isNull, ne } from "drizzle-orm";-import * as Context from "effect/Context";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";-import * as Schema from "effect/Schema";--import * as RelayDb from "../db.ts";-import {- relayEnvironmentLinks,- relayManagedEndpointAllocations,- relayManagedTunnelLimits,-} from "../persistence/schema.ts";--/**- * Managed tunnels a user may hold at once unless a row in- * `relay_managed_tunnel_limits` overrides it for that user.- */-export const DEFAULT_MANAGED_TUNNEL_LIMIT = 3;--export class ManagedTunnelLimitPersistenceError extends Schema.TaggedErrorClass<ManagedTunnelLimitPersistenceError>()(- "ManagedTunnelLimitPersistenceError",- {- operation: Schema.Literals(["load-limit", "count-tunnels"]),- userId: Schema.String,- cause: Schema.Defect(),- },-) {- override get message(): string {- return `Managed tunnel limit '${this.operation}' failed for user '${this.userId}'`;- }-}--export class ManagedTunnelLimitExceeded extends Schema.TaggedErrorClass<ManagedTunnelLimitExceeded>()(- "ManagedTunnelLimitExceeded",- {- userId: Schema.String,- environmentId: Schema.String,- maxTunnels: Schema.Number,- activeTunnels: Schema.Number,- },-) {- override get message(): string {- return `Managed tunnel limit reached for user '${this.userId}': ${this.activeTunnels} of ${this.maxTunnels} tunnels in use`;- }-}--export class ManagedTunnelLimits extends Context.Service<- ManagedTunnelLimits,- {- readonly ensureCapacity: (input: {- readonly userId: string;- readonly environmentId: string;- }) => Effect.Effect<void, ManagedTunnelLimitExceeded | ManagedTunnelLimitPersistenceError>;- }->()("t3code-relay/environments/ManagedTunnelLimits") {}--export const make = Effect.gen(function* () {- const db = yield* RelayDb.RelayDb;-- return ManagedTunnelLimits.of({- ensureCapacity: Effect.fn("relay.managed_tunnel_limits.ensure_capacity")(function* (input) {- const overrides = yield* db- .select({ maxTunnels: relayManagedTunnelLimits.maxTunnels })- .from(relayManagedTunnelLimits)- .where(eq(relayManagedTunnelLimits.userId, input.userId))- .limit(1)- .pipe(- Effect.mapError(- (cause) =>- new ManagedTunnelLimitPersistenceError({- operation: "load-limit",- userId: input.userId,- cause,- }),- ),- );- const maxTunnels = overrides[0]?.maxTunnels ?? DEFAULT_MANAGED_TUNNEL_LIMIT;-- // Allocations already held for this environment are excluded so that- // re-linking an environment the user already has a tunnel for stays- // idempotent even when the account is at its limit.- const counted = yield* db- .select({ activeTunnels: count() })- .from(relayManagedEndpointAllocations)- .innerJoin(- relayEnvironmentLinks,- and(- eq(relayEnvironmentLinks.userId, relayManagedEndpointAllocations.userId),- eq(relayEnvironmentLinks.environmentId, relayManagedEndpointAllocations.environmentId),- ),- )- .where(- and(- eq(relayManagedEndpointAllocations.userId, input.userId),- ne(relayManagedEndpointAllocations.environmentId, input.environmentId),- isNull(relayEnvironmentLinks.revokedAt),- eq(relayEnvironmentLinks.managedTunnelsEnabled, true),- ),- )- .pipe(- Effect.mapError(- (cause) =>- new ManagedTunnelLimitPersistenceError({- operation: "count-tunnels",- userId: input.userId,- cause,- }),- ),- );- const activeTunnels = counted[0]?.activeTunnels ?? 0;-- if (activeTunnels >= maxTunnels) {- return yield* new ManagedTunnelLimitExceeded({- userId: input.userId,- environmentId: input.environmentId,- maxTunnels,- activeTunnels,- });- }- }),- });-});--export const layer = Layer.effect(ManagedTunnelLimits, make);diff --git a/infra/relay/src/http/Api.test.ts b/infra/relay/src/http/Api.test.tsdeleted file mode 100644index daf756a2b..000000000--- a/infra/relay/src/http/Api.test.ts+++ /dev/null@@ -1,510 +0,0 @@-import { createClerkClient, verifyToken } from "@clerk/backend";-import { describe, expect, it } from "@effect/vitest";-import { vi } from "vite-plus/test";-import * as Context from "effect/Context";-import * as Duration from "effect/Duration";-import * as Effect from "effect/Effect";-import * as Fiber from "effect/Fiber";-import * as Layer from "effect/Layer";-import * as Option from "effect/Option";-import * as Predicate from "effect/Predicate";-import * as Redacted from "effect/Redacted";-import * as TestClock from "effect/testing/TestClock";-import * as Tracer from "effect/Tracer";-import * as HttpRouter from "effect/unstable/http/HttpRouter";-import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";-import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";-import { EnvironmentId } from "@t3tools/contracts";-import { RelayEnvironmentAuth } from "@t3tools/contracts/relay";--import {- RELAY_REQUEST_DEADLINE_MS,- relayCors,- relayDocsRedirectRoute,- relayEnvironmentAuthLayer,- relayNotFoundRoute,- revokeEnvironmentLinkRecord,- traceRelayHttpRequestWith,- unlinkEnvironmentRecord,- verifyRelayClientBearerToken,- withoutCapturedParentSpan,-} from "./Api.ts";-import * as RelayConfiguration from "../Config.ts";-import * as RelayDb from "../db.ts";-import * as EnvironmentCredentials from "../environments/EnvironmentCredentials.ts";-import * as EnvironmentLinks from "../environments/EnvironmentLinks.ts";-import * as ManagedEndpointProvider from "../environments/ManagedEndpointProvider.ts";--vi.mock("@clerk/backend", () => ({- createClerkClient: vi.fn(),- verifyToken: vi.fn(),-}));--const relaySettings: RelayConfiguration.RelayConfiguration["Service"] = {- relayIssuer: "https://relay.example.test",- apns: {- teamId: "apns-team",- keyId: "apns-key",- privateKey: Redacted.make("apns-private-key"),- bundleId: "com.example.t3",- environment: "sandbox",- },- clerkSecretKey: Redacted.make("clerk-secret-key"),- clerkPublishableKey: "pk_test_test",- clerkJwtAudience: "t3-code-relay",- apnsDeliveryJobSigningSecret: Redacted.make("apns-delivery-secret"),- cloudMintPrivateKey: Redacted.make("cloud-mint-private-key"),- cloudMintPublicKey: "cloud-mint-public-key",- managedEndpointBaseDomain: undefined,- managedEndpointNamespace: undefined,-};--describe("relay client authentication", () => {- it.effect("preserves the existing Clerk session JWT path", () =>- Effect.gen(function* () {- vi.mocked(verifyToken).mockResolvedValue({- sub: "user_session",- aud: relaySettings.clerkJwtAudience,- } as never);-- expect(yield* verifyRelayClientBearerToken(relaySettings, "session-token")).toEqual({- sub: "user_session",- mode: "clerk_session_bearer",- });- expect(verifyToken).toHaveBeenCalledWith("session-token", {- secretKey: "clerk-secret-key",- audience: relaySettings.clerkJwtAudience,- });- expect(createClerkClient).not.toHaveBeenCalled();- }).pipe(- Effect.ensuring(- Effect.sync(() => {- vi.mocked(verifyToken).mockReset();- vi.mocked(createClerkClient).mockReset();- }),- ),- ),- );-- it.effect("falls back to Clerk OAuth token verification for the headless CLI", () =>- Effect.gen(function* () {- vi.mocked(verifyToken).mockRejectedValue(new Error("not a session JWT"));- vi.mocked(createClerkClient).mockReturnValue({- authenticateRequest: vi.fn().mockResolvedValue({- isAuthenticated: true,- toAuth: () => ({ userId: "user_oauth" }),- }),- } as never);-- expect(yield* verifyRelayClientBearerToken(relaySettings, "oauth-token")).toEqual({- sub: "user_oauth",- mode: "clerk_oauth_bearer",- });- expect(createClerkClient).toHaveBeenCalledWith({- secretKey: "clerk-secret-key",- publishableKey: "pk_test_test",- });- }).pipe(- Effect.ensuring(- Effect.sync(() => {- vi.mocked(verifyToken).mockReset();- vi.mocked(createClerkClient).mockReset();- }),- ),- ),- );-});--describe("relay environment authentication", () => {- it.effect("preserves credential lookup persistence failures as internal errors", () => {- const failure = new EnvironmentCredentials.EnvironmentCredentialAuthenticatePersistenceError({- stage: "lookup-credential",- cause: "database unavailable",- });- const credentials: EnvironmentCredentials.EnvironmentCredentials["Service"] = {- create: () => Effect.die("unused create"),- authenticate: () => Effect.fail(failure),- revokeForEnvironmentPublicKey: () => Effect.die("unused revoke"),- };-- return Effect.gen(function* () {- const auth = yield* RelayEnvironmentAuth;- const error = yield* Effect.flip(- auth.environmentBearer(Effect.succeed(HttpServerResponse.empty()), {- credential: Redacted.make("environment-credential"),- endpoint: {} as never,- group: {} as never,- }),- );-- expect(Predicate.isTagged(error, "RelayInternalError")).toBe(true);- if (Predicate.isTagged(error, "RelayInternalError")) {- expect(error.reason).toBe("persistence_failed");- }- }).pipe(- Effect.provideService(- HttpServerRequest.HttpServerRequest,- HttpServerRequest.fromWeb(new Request("https://relay.test/v1/server/link")),- ),- Effect.provideService(HttpServerRequest.ParsedSearchParams, {}),- Effect.provideService(HttpRouter.RouteContext, {- params: {},- route: {} as never,- }),- Effect.provide(- relayEnvironmentAuthLayer.pipe(- Layer.provide(Layer.succeed(EnvironmentCredentials.EnvironmentCredentials, credentials)),- ),- ),- Effect.scoped,- );- });-});--function relayUnlinkTestLayer(input?: {- readonly withTransaction?: RelayDb.RelayTransactions["Service"]["withTransaction"];- readonly getForUser?: EnvironmentLinks.EnvironmentLinks["Service"]["getForUser"];- readonly revokeForUser?: EnvironmentLinks.EnvironmentLinks["Service"]["revokeForUser"];- readonly revokeCredential?: EnvironmentCredentials.EnvironmentCredentials["Service"]["revokeForEnvironmentPublicKey"];- readonly prepareDeprovision?: ManagedEndpointProvider.ManagedEndpointProvider["Service"]["prepareDeprovision"];- readonly deprovision?: ManagedEndpointProvider.ManagedEndpointProvider["Service"]["deprovision"];-}) {- return Layer.mergeAll(- Layer.succeed(- RelayDb.RelayTransactions,- RelayDb.RelayTransactions.of({- withTransaction: input?.withTransaction ?? ((effect) => effect),- }),- ),- Layer.succeed(- EnvironmentLinks.EnvironmentLinks,- EnvironmentLinks.EnvironmentLinks.of({- upsert: () => Effect.die("unused upsert"),- listUsersForEnvironment: () => Effect.die("unused listUsersForEnvironment"),- listDeliveryUsersForEnvironment: () => Effect.die("unused listDeliveryUsersForEnvironment"),- listPublicKeysForEnvironment: () => Effect.die("unused listPublicKeysForEnvironment"),- listForUser: () => Effect.die("unused listForUser"),- getForUser: input?.getForUser ?? (() => Effect.succeed(null)),- revokeForUser: input?.revokeForUser ?? (() => Effect.succeed(false)),- }),- ),- Layer.succeed(- EnvironmentCredentials.EnvironmentCredentials,- EnvironmentCredentials.EnvironmentCredentials.of({- create: () => Effect.die("unused create"),- authenticate: () => Effect.die("unused authenticate"),- revokeForEnvironmentPublicKey: input?.revokeCredential ?? (() => Effect.succeed(false)),- }),- ),- Layer.succeed(- ManagedEndpointProvider.ManagedEndpointProvider,- ManagedEndpointProvider.ManagedEndpointProvider.of({- provision: () => Effect.die("unused provision"),- prepareDeprovision: input?.prepareDeprovision ?? (() => Effect.succeed(null)),- deprovision: input?.deprovision ?? (() => Effect.void),- release: () => Effect.die("unused release"),- }),- ),- );-}--const linkedEnvironmentRecord = {- environmentId: EnvironmentId.make("environment-1"),- label: "Environment 1",- endpoint: {- httpBaseUrl: "https://environment-1.example.test/",- wsBaseUrl: "wss://environment-1.example.test/ws",- providerKind: "cloudflare_tunnel",- },- environmentPublicKey: "public-key",- linkedAt: "2026-07-28T00:00:00.000Z",-} as const;--describe("relay environment unlink", () => {- it.effect("revokes the link and its credentials in one database transaction", () => {- const calls: Array<string> = [];- return Effect.gen(function* () {- expect(- yield* revokeEnvironmentLinkRecord({- userId: "user-1",- environmentId: "environment-1",- environmentPublicKey: "public-key",- }),- ).toBe(true);- expect(calls).toEqual(["transaction", "link", "credential"]);- }).pipe(- Effect.provide(- relayUnlinkTestLayer({- withTransaction: (effect) => {- calls.push("transaction");- return effect;- },- revokeForUser: () =>- Effect.sync(() => {- calls.push("link");- return true;- }),- revokeCredential: () =>- Effect.sync(() => {- calls.push("credential");- return true;- }),- }),- ),- );- });-- it.effect("commits database revocation before deprovisioning the managed endpoint", () => {- const calls: Array<string> = [];- const deprovisionTarget = {- userId: "user-1",- environmentId: "environment-1",- hostname: "environment-1.example.test",- tunnelId: "tunnel-1",- tunnelName: "environment-1-tunnel",- dnsRecordId: "dns-1",- readyAt: "2026-07-28T00:00:00.000Z",- updatedAt: "generation-before-unlink",- } satisfies ManagedEndpointProvider.ManagedEndpointDeprovisionTarget;-- return Effect.gen(function* () {- expect(- yield* unlinkEnvironmentRecord({- userId: "user-1",- environmentId: "environment-1",- }),- ).toBe(true);- expect(calls).toEqual([- "prepare",- "lookup",- "transaction",- "link",- "credential",- "deprovision",- ]);- }).pipe(- Effect.provide(- relayUnlinkTestLayer({- withTransaction: (effect) => {- calls.push("transaction");- return effect;- },- getForUser: () =>- Effect.sync(() => {- calls.push("lookup");- return linkedEnvironmentRecord;- }),- revokeForUser: () =>- Effect.sync(() => {- calls.push("link");- return true;- }),- revokeCredential: () =>- Effect.sync(() => {- calls.push("credential");- return true;- }),- prepareDeprovision: () =>- Effect.sync(() => {- calls.push("prepare");- return deprovisionTarget;- }),- deprovision: (request) =>- Effect.sync(() => {- expect(request.target).toBe(deprovisionTarget);- calls.push("deprovision");- }),- }),- ),- );- });-- it.effect("does not deprovision when database revocation fails", () => {- const calls: Array<string> = [];- const failure = new EnvironmentCredentials.EnvironmentCredentialRevokePersistenceError({- environmentId: "environment-1",- cause: "database unavailable",- });-- return Effect.gen(function* () {- expect(- yield* Effect.flip(- unlinkEnvironmentRecord({- userId: "user-1",- environmentId: "environment-1",- }),- ),- ).toBe(failure);- expect(calls).toEqual(["prepare", "transaction", "link", "credential"]);- }).pipe(- Effect.provide(- relayUnlinkTestLayer({- withTransaction: (effect) => {- calls.push("transaction");- return effect;- },- getForUser: () => Effect.succeed(linkedEnvironmentRecord),- revokeForUser: () =>- Effect.sync(() => {- calls.push("link");- return true;- }),- revokeCredential: () =>- Effect.sync(() => {- calls.push("credential");- }).pipe(Effect.andThen(Effect.fail(failure))),- prepareDeprovision: () =>- Effect.sync(() => {- calls.push("prepare");- return null;- }),- deprovision: () =>- Effect.sync(() => {- calls.push("deprovision");- }),- }),- ),- );- });-- it.effect("retries deprovisioning after the link is already revoked", () => {- const calls: Array<string> = [];- return Effect.gen(function* () {- expect(- yield* unlinkEnvironmentRecord({- userId: "user-1",- environmentId: "environment-1",- }),- ).toBe(false);- expect(calls).toEqual(["prepare", "deprovision"]);- }).pipe(- Effect.provide(- relayUnlinkTestLayer({- prepareDeprovision: () =>- Effect.sync(() => {- calls.push("prepare");- return null;- }),- deprovision: () =>- Effect.sync(() => {- calls.push("deprovision");- }),- }),- ),- );- });-});--describe("relay request tracing", () => {- it.effect(- "does not parent endpoint spans to an ambient parent captured while building handlers",- () =>- Effect.gen(function* () {- const spans: Array<Tracer.NativeSpan> = [];- const tracer = Tracer.make({- span: (options) => {- const span = new Tracer.NativeSpan(options);- spans.push(span);- return span;- },- });- const ambientParent = Tracer.externalSpan({- traceId: "00000000000000000000000000000001",- spanId: "0000000000000001",- sampled: true,- });- const endpoint = yield* withoutCapturedParentSpan(- Effect.context<never>().pipe(- Effect.map((capturedContext: Context.Context<never>) =>- Effect.succeed(HttpServerResponse.empty({ status: 204 })).pipe(- Effect.withSpan("relay.test.endpoint"),- Effect.provideContext(capturedContext),- ),- ),- ),- ).pipe(Effect.provideService(Tracer.ParentSpan, ambientParent));- const request = HttpServerRequest.fromWeb(- new Request("https://relay.test/v1/mobile/devices?client=mobile", {- method: "POST",- headers: {- authorization: "Bearer secret",- dpop: "signed-proof",- },- }),- );-- yield* traceRelayHttpRequestWith(endpoint, Layer.succeed(Tracer.Tracer, tracer)).pipe(- Effect.provideService(HttpServerRequest.HttpServerRequest, request),- );-- expect(spans.map((span) => span.name)).toEqual(["http.server POST", "relay.test.endpoint"]);- expect(spans[0]?.kind).toBe("server");- expect(spans[0]?.attributes.get("url.path")).toBe("/v1/mobile/devices");- expect(spans[0]?.attributes.get("http.response.status_code")).toBe(204);- expect(spans[0]?.attributes.get("http.request.header.authorization")).toBe("<redacted>");- expect(spans[0]?.attributes.get("http.request.header.dpop")).toBe("<redacted>");- expect(Option.isNone(spans[0]!.parent)).toBe(true);- expect(Option.getOrUndefined(spans[1]!.parent)?.spanId).toBe(spans[0]?.spanId);- }),- );-- it.effect("fails hung requests with a 504 before the client's 10s abort", () =>- Effect.gen(function* () {- const spans: Array<Tracer.NativeSpan> = [];- const tracer = Tracer.make({- span: (options) => {- const span = new Tracer.NativeSpan(options);- spans.push(span);- return span;- },- });- const request = HttpServerRequest.fromWeb(- new Request("https://relay.test/v1/mobile/devices", { method: "POST" }),- );-- const fiber = yield* traceRelayHttpRequestWith(- Effect.never,- Layer.succeed(Tracer.Tracer, tracer),- ).pipe(Effect.provideService(HttpServerRequest.HttpServerRequest, request), Effect.forkChild);- yield* TestClock.adjust(Duration.millis(RELAY_REQUEST_DEADLINE_MS));- const response = yield* Fiber.join(fiber);-- expect(response.status).toBe(504);- expect(spans[0]?.attributes.get("relay.request.deadline_exceeded")).toBe(true);- expect(spans[0]?.attributes.get("http.response.status_code")).toBe(504);- }),- );-});--describe("relay routing fallback", () => {- it.effect("redirects the relay root to the API docs", () =>- Effect.gen(function* () {- const request = HttpServerRequest.fromWeb(new Request("https://relay.test/"));- const httpEffect = yield* HttpRouter.toHttpEffect(- Layer.mergeAll(relayDocsRedirectRoute, relayNotFoundRoute, relayCors),- );- const response = yield* httpEffect.pipe(- Effect.provideService(HttpServerRequest.HttpServerRequest, request),- );-- expect(response.status).toBe(302);- expect(response.headers.location).toBe("/docs");- expect(response.headers["access-control-allow-origin"]).toBe("*");- }).pipe(Effect.scoped),- );-- it.effect("returns a CORS-compatible 404 response for unmatched paths", () =>- Effect.gen(function* () {- const request = HttpServerRequest.fromWeb(- new Request("https://relay.test/v1/environmentsd", { method: "GET" }),- );- const httpEffect = yield* HttpRouter.toHttpEffect(Layer.merge(relayNotFoundRoute, relayCors));- const response = yield* httpEffect.pipe(- Effect.provideService(HttpServerRequest.HttpServerRequest, request),- );-- expect(response.status).toBe(404);- expect(response.headers["access-control-allow-origin"]).toBe("*");- }).pipe(Effect.scoped),- );-});diff --git a/infra/relay/src/http/Api.ts b/infra/relay/src/http/Api.tsdeleted file mode 100644index 50bcff665..000000000--- a/infra/relay/src/http/Api.ts+++ /dev/null@@ -1,1290 +0,0 @@-import { createClerkClient, verifyToken } from "@clerk/backend";-import { sql as drizzleSql } from "drizzle-orm";-import * as Crypto from "effect/Crypto";-import * as Context from "effect/Context";-import * as DateTime from "effect/DateTime";-import * as Duration from "effect/Duration";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";-import * as Option from "effect/Option";-import * as Record from "effect/Record";-import * as Redacted from "effect/Redacted";-import * as Schema from "effect/Schema";-import * as Tracer from "effect/Tracer";-import * as HttpEffect from "effect/unstable/http/HttpEffect";-import * as HttpMiddleware from "effect/unstable/http/HttpMiddleware";-import * as HttpRouter from "effect/unstable/http/HttpRouter";-import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";-import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";-import * as HttpTraceContext from "effect/unstable/http/HttpTraceContext";-import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";-import * as HttpApiError from "effect/unstable/httpapi/HttpApiError";-import { encodeOAuthScope } from "@t3tools/shared/oauthScope";-import { httpHeaderRedactionLayer } from "@t3tools/shared/httpObservability";--import {- RelayApi,- RelayAgentActivityPublishProofExpiredError,- RelayAgentActivityPublishProofInvalidError,- RelayClientAuth,- RelayClientPrincipal,- RelayAccessTokenType,- RelayDpopClientAuth,- RelayEnvironmentConnectScope,- RelayEnvironmentStatusScope,- RelayMobileRegistrationScope,- RelayAuthInvalidError,- type RelayAuthInvalidReason,- RelayEnvironmentAuth,- RelayEnvironmentConnectNotAuthorizedError,- RelayEnvironmentEndpointTimedOutError,- RelayEnvironmentEndpointUnavailableError,- RelayEnvironmentLinkFailedError,- RelayEnvironmentLinkProofExpiredError,- RelayEnvironmentLinkProofInvalidError,- RelayEnvironmentLinkUnavailableError,- RelayEnvironmentLinkLimitExceededError,- RelayEnvironmentPrincipal,- type RelayEnvironmentConnectRequest,- type RelayDpopAccessTokenScope,- RelayInternalError,-} from "@t3tools/contracts/relay";-import { normalizeRelayIssuer } from "@t3tools/shared/relayJwt";--import * as DeliveryAttempts from "../agentActivity/DeliveryAttempts.ts";-import * as AgentActivityRows from "../agentActivity/AgentActivityRows.ts";-import * as Devices from "../agentActivity/Devices.ts";-import * as DpopProofs from "../auth/DpopProofs.ts";-import * as RelayTokens from "../auth/RelayTokens.ts";-import * as EnvironmentCredentials from "../environments/EnvironmentCredentials.ts";-import * as EnvironmentLinks from "../environments/EnvironmentLinks.ts";-import * as LiveActivities from "../agentActivity/LiveActivities.ts";-import * as RelayConfiguration from "../Config.ts";-import * as AgentActivityPublisher from "../agentActivity/AgentActivityPublisher.ts";-import * as EnvironmentConnector from "../environments/EnvironmentConnector.ts";-import * as EnvironmentLinker from "../environments/EnvironmentLinker.ts";-import * as ManagedEndpointProvider from "../environments/ManagedEndpointProvider.ts";-import * as ManagedEndpointAllocations from "../environments/ManagedEndpointAllocations.ts";-import * as EnvironmentPublishSignatures from "../environments/EnvironmentPublishSignatures.ts";-import * as MobileRegistrations from "../agentActivity/MobileRegistrations.ts";-import { withSpanAttributes } from "../observability.ts";-import * as RelayDb from "../db.ts";--const relayCorsAllowedMethods = ["GET", "POST", "DELETE", "OPTIONS"] as const;-const relayCorsAllowedHeaders = [- "authorization",- "b3",- "traceparent",- "content-type",- "dpop",-] as const;-const relayCorsExposedHeaders = ["traceparent", "www-authenticate"] as const;--const relayCorsHeaders = {- "access-control-allow-origin": "*",- "access-control-expose-headers": relayCorsExposedHeaders.join(","),-} as const;--const relayCorsPreflightHeaders = {- ...relayCorsHeaders,- "access-control-allow-methods": relayCorsAllowedMethods.join(","),- "access-control-allow-headers": relayCorsAllowedHeaders.join(","),- "access-control-max-age": "86400",-} as const;--const appendRelayCredentialResponseHeaders = HttpEffect.appendPreResponseHandler(- (_request, response) =>- Effect.succeed(- HttpServerResponse.setHeaders(response, {- "cache-control": "no-store",- pragma: "no-cache",- }),- ),-);--const appendRelayDpopChallengeHeader = HttpEffect.appendPreResponseHandler((_request, response) =>- Effect.succeed(- response.status === 401- ? HttpServerResponse.setHeader(response, "www-authenticate", "DPoP")- : response,- ),-);--const appendRelayTraceContextResponseHeader = Effect.gen(function* () {- const span = yield* Effect.currentParentSpan;- if (span._tag !== "Span") {- return;- }- const traceparent = HttpTraceContext.toHeaders(span).traceparent;- if (traceparent === undefined) {- return;- }- yield* HttpEffect.appendPreResponseHandler((_request, response) =>- Effect.succeed(HttpServerResponse.setHeader(response, "traceparent", traceparent)),- );-}).pipe(Effect.ignore);--export const relayCors = HttpRouter.middleware(- Effect.fnUntraced(function* <E, R>(- httpEffect: Effect.Effect<- HttpServerResponse.HttpServerResponse,- E,- HttpServerRequest.HttpServerRequest | R- >,- ) {- const request = yield* HttpServerRequest.HttpServerRequest;- if (request.method === "OPTIONS") {- return HttpServerResponse.empty({- status: 204,- headers: relayCorsPreflightHeaders,- });- }- const response = yield* httpEffect;- return HttpServerResponse.setHeaders(response, relayCorsHeaders);- }),- { global: true },-);--export const relayNotFoundRoute = HttpRouter.add(- "*",- "/*",- HttpServerResponse.empty({ status: 404 }),-);--export const relayDocsRedirectRoute = HttpRouter.add(- "GET",- "/",- HttpServerResponse.redirect("/docs"),-);--// Shorter than the mobile client's 10s request timeout on purpose: when a-// request hangs (e.g. a stuck upstream query), the client would otherwise-// abort first, the invocation would die with the request span still open, and-// the batched spans would never export — leaving no server-side trace at all.-// Failing server-side first turns the hang into a completed 504 whose trace-// contains the exact child span that stalled, and the response still carries-// the traceparent back to the client.-export const RELAY_REQUEST_DEADLINE_MS = 9_000;--const relayRequestDeadline = <E, R>(- httpEffect: Effect.Effect<- HttpServerResponse.HttpServerResponse,- E,- HttpServerRequest.HttpServerRequest | R- >,-) =>- httpEffect.pipe(- Effect.timeoutOption(Duration.millis(RELAY_REQUEST_DEADLINE_MS)),- Effect.flatMap(- Option.match({- onNone: () =>- Effect.gen(function* () {- const request = yield* HttpServerRequest.HttpServerRequest;- yield* Effect.logError("relay request exceeded deadline", {- "http.method": request.method,- "http.url": request.url,- "relay.request.deadline_ms": RELAY_REQUEST_DEADLINE_MS,- });- yield* Effect.annotateCurrentSpan({- "relay.request.deadline_exceeded": true,- });- return HttpServerResponse.jsonUnsafe(- { error: "relay_request_deadline_exceeded" },- { status: 504 },- );- }),- onSome: Effect.succeed,- }),- ),- );--export const traceRelayHttpRequest = <E, R>(- httpEffect: Effect.Effect<- HttpServerResponse.HttpServerResponse,- E,- HttpServerRequest.HttpServerRequest | R- >,-) =>- // HttpMiddleware finalizes its span on the dispatcher; do not close a request-scoped exporter first.- HttpMiddleware.tracer(- appendRelayTraceContextResponseHeader.pipe(Effect.andThen(relayRequestDeadline(httpEffect))),- ).pipe(Effect.ensuring(Effect.yieldNow));--export const traceRelayHttpRequestWith = <E, R, LayerError, LayerRequirements>(- httpEffect: Effect.Effect<- HttpServerResponse.HttpServerResponse,- E,- HttpServerRequest.HttpServerRequest | R- >,- tracerLayer: Layer.Layer<never, LayerError, LayerRequirements>,-) =>- traceRelayHttpRequest(httpEffect).pipe(- Effect.provide(Layer.merge(tracerLayer, httpHeaderRedactionLayer)),- );--export const withoutCapturedParentSpan = <A, E, R>(- effect: Effect.Effect<A, E, R>,-): Effect.Effect<A, E, R> =>- Effect.withFiber((fiber) => {- const context = fiber.context;- // HttpApiBuilder captures its build context for route handlers; an event parent would outlive export.- fiber.setContext(Context.omit(Tracer.ParentSpan)(context));- return effect.pipe(Effect.ensuring(Effect.sync(() => fiber.setContext(context))));- });--export const relayClientAuthLayer = Layer.effect(- RelayClientAuth,- Effect.gen(function* () {- const config = yield* RelayConfiguration.RelayConfiguration;- return {- clientBearer: Effect.fn("relay.auth.client.bearer")(function* (httpEffect, { credential }) {- const token = readHttpAuthorizationCredential(credential);- const verified = yield* verifyRelayClientBearerToken(config, token).pipe(- Effect.tapError((error) =>- Effect.annotateCurrentSpan(- "relay.auth.clerk_verification_failure",- clerkVerificationFailureReason(error.cause),- ),- ),- Effect.catch(() => relayAuthInvalidError("invalid_bearer")),- );- if (!verified.sub) {- yield* Effect.annotateCurrentSpan({- "relay.auth.clerk_verification_failure": "missing_subject",- });- return yield* relayAuthInvalidError("invalid_bearer");- }- yield* Effect.annotateCurrentSpan({- "relay.auth.mode": verified.mode,- "relay.auth.subject": verified.sub,- });-- return yield* httpEffect.pipe(- withSpanAttributes({ "user.id": verified.sub }),- Effect.provideService(RelayClientPrincipal, {- userId: verified.sub,- token,- }),- );- }),- };- }),-);--export const relayEnvironmentAuthLayer = Layer.effect(- RelayEnvironmentAuth,- Effect.gen(function* () {- const credentials = yield* EnvironmentCredentials.EnvironmentCredentials;- return {- environmentBearer: Effect.fn("relay.auth.environment.bearer")(function* (- httpEffect,- { credential },- ) {- const token = readHttpAuthorizationCredential(credential);- const principal = yield* credentials.authenticate(token).pipe(- Effect.catchTags({- EnvironmentCredentialAuthenticatePersistenceError: () =>- relayInternalErrorResponse("persistence_failed"),- }),- );- if (principal._tag === "None") {- return yield* relayAuthInvalidError("not_authorized");- }- yield* Effect.annotateCurrentSpan({- "relay.auth.mode": "environment_credential",- });- return yield* httpEffect.pipe(- withSpanAttributes({- "relay.environment_id": principal.value.environmentId,- }),- Effect.provideService(RelayEnvironmentPrincipal, principal.value),- );- }),- };- }),-);--export const relayDpopClientAuthLayer = Layer.effect(- RelayDpopClientAuth,- Effect.gen(function* () {- const relayTokens = yield* RelayTokens.RelayTokens;- return {- relayDpop: Effect.fn("relay.auth.dpop_client")(function* (httpEffect, { credential }) {- yield* appendRelayDpopChallengeHeader;- const request = yield* HttpServerRequest.HttpServerRequest;- if (!isDpopAuthorizationHeader(request.headers.authorization)) {- return yield* relayAuthInvalidError("invalid_bearer");- }- const token = readHttpAuthorizationCredential(credential);- const now = yield* DateTime.now;- const verified = yield* relayTokens.verifyDpopAccessToken({- token,- nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),- });- if (!verified) {- return yield* relayAuthInvalidError("invalid_bearer");- }- yield* Effect.annotateCurrentSpan({- "relay.auth.mode": "dpop",- "relay.auth.subject": verified.sub,- });- return yield* httpEffect.pipe(- withSpanAttributes({ "user.id": verified.sub }),- Effect.provideService(RelayClientPrincipal, {- userId: verified.sub,- token,- proofKeyThumbprint: verified.cnf.jkt,- dpopScopes: verified.scope,- }),- );- }),- };- }),-);--function isDpopAuthorizationHeader(value: string | undefined): boolean {- return /^DPoP +/iu.test(value ?? "");-}--function readHttpAuthorizationCredential(credential: Redacted.Redacted<string>): string {- // Effect beta.73 leaves the scheme separator in decoded HTTP credentials.- return Redacted.value(credential).trimStart();-}--export const metadataApi = HttpApiBuilder.group(- RelayApi,- "metadata",- Effect.fnUntraced(function* (handlers) {- const settings = yield* RelayConfiguration.RelayConfiguration;- const issuer = normalizeRelayIssuer(settings.relayIssuer);- const scopes = [- RelayEnvironmentConnectScope,- RelayEnvironmentStatusScope,- RelayMobileRegistrationScope,- ] as const;- return handlers- .handle("authorizationServer", () =>- Effect.succeed({- issuer,- token_endpoint: `${issuer}/v1/client/dpop-token`,- grant_types_supported: ["urn:ietf:params:oauth:grant-type:token-exchange"],- token_endpoint_auth_methods_supported: ["none"],- dpop_signing_alg_values_supported: ["ES256"],- scopes_supported: scopes,- }),- )- .handle("protectedResource", () =>- Effect.succeed({- resource: issuer,- authorization_servers: [issuer],- scopes_supported: scopes,- dpop_bound_access_tokens_required: true,- dpop_signing_alg_values_supported: ["ES256"],- }),- );- }),-);--export const healthApi = HttpApiBuilder.group(- RelayApi,- "health",- Effect.fnUntraced(function* (handlers) {- const db = yield* RelayDb.RelayDb;- return handlers.handle(- "health",- Effect.fn("relay.api.health")(- function* () {- yield* db.execute(drizzleSql`SELECT 1`);- return { ok: true, service: "relay" as const };- },- Effect.catch(() => relayInternalErrorResponse("database_unavailable")),- ),- );- }),-);--export const revokeEnvironmentLinkRecord = Effect.fn(- "relay.api.client.revokeEnvironmentLinkRecord",-)(function* (input: {- readonly userId: string;- readonly environmentId: string;- readonly environmentPublicKey: string;-}) {- const transactions = yield* RelayDb.RelayTransactions;- const links = yield* EnvironmentLinks.EnvironmentLinks;- const credentials = yield* EnvironmentCredentials.EnvironmentCredentials;- return yield* transactions.withTransaction(- Effect.gen(function* () {- const revoked = yield* links.revokeForUser({- userId: input.userId,- environmentId: input.environmentId,- });- if (revoked) {- yield* credentials.revokeForEnvironmentPublicKey({- environmentId: input.environmentId,- environmentPublicKey: input.environmentPublicKey,- });- }- return revoked;- }),- );-});--export const unlinkEnvironmentRecord = Effect.fn("relay.api.client.unlinkEnvironmentRecord")(- function* (input: { readonly userId: string; readonly environmentId: string }) {- const links = yield* EnvironmentLinks.EnvironmentLinks;- const managedEndpointProvider = yield* ManagedEndpointProvider.ManagedEndpointProvider;- const deprovisionTarget = yield* managedEndpointProvider.prepareDeprovision({- userId: input.userId,- environmentId: input.environmentId,- });- const link = yield* links.getForUser({- userId: input.userId,- environmentId: input.environmentId,- });- const unlinked =- link === null- ? false- : yield* revokeEnvironmentLinkRecord({- userId: input.userId,- environmentId: link.environmentId,- environmentPublicKey: link.environmentPublicKey,- });-- // External teardown cannot share the SQL transaction. Run it only after- // revocation commits so a database failure leaves a fully usable active- // link. Still run teardown when the link is already revoked, allowing a- // retry to finish cleanup after an earlier Cloudflare failure.- yield* managedEndpointProvider.deprovision({- userId: input.userId,- environmentId: input.environmentId,- target: deprovisionTarget,- });- return unlinked;- },-);--export const mobileApi = HttpApiBuilder.group(- RelayApi,- "mobile",- Effect.fnUntraced(function* (handlers) {- const registrations = yield* MobileRegistrations.MobileRegistrations;- const dpopProofs = yield* DpopProofs.DpopProofReplay;- return handlers- .handle(- "registerDevice",- Effect.fn("relay.api.mobile.registerDevice")(function* (args) {- const { payload } = args;- const { userId, token } = yield* RelayClientPrincipal;- const proofKeyThumbprint = yield* requireDpopPrincipalScope("mobile:registration");- yield* requireDpopThumbprint(proofKeyThumbprint, {- expectedAccessToken: token,- }).pipe(Effect.provideService(DpopProofs.DpopProofReplay, dpopProofs));- return yield* registrations.registerDevice({ userId, payload });- }, mapRelayCommonApiErrors("invalid_dpop")),- )- .handle(- "registerLiveActivity",- Effect.fn("relay.api.mobile.registerLiveActivity")(function* (args) {- const { payload } = args;- const { userId, token } = yield* RelayClientPrincipal;- const proofKeyThumbprint = yield* requireDpopPrincipalScope("mobile:registration");- yield* requireDpopThumbprint(proofKeyThumbprint, {- expectedAccessToken: token,- }).pipe(Effect.provideService(DpopProofs.DpopProofReplay, dpopProofs));- return yield* registrations.registerLiveActivity({ userId, payload });- }, mapRelayCommonApiErrors("invalid_dpop")),- )- .handle(- "getAgentActivitySnapshot",- Effect.fn("relay.api.mobile.getAgentActivitySnapshot")(function* () {- const { userId, token } = yield* RelayClientPrincipal;- const proofKeyThumbprint = yield* requireDpopPrincipalScope("mobile:registration");- yield* requireDpopThumbprint(proofKeyThumbprint, {- expectedAccessToken: token,- }).pipe(Effect.provideService(DpopProofs.DpopProofReplay, dpopProofs));- return yield* registrations.getAgentActivitySnapshot({ userId });- }, mapRelayCommonApiErrors("invalid_dpop")),- )- .handle(- "unregisterDevice",- Effect.fn("relay.api.mobile.unregisterDevice")(function* (args) {- const { params } = args;- const { userId, token } = yield* RelayClientPrincipal;- const proofKeyThumbprint = yield* requireDpopPrincipalScope("mobile:registration");- yield* requireDpopThumbprint(proofKeyThumbprint, {- expectedAccessToken: token,- }).pipe(Effect.provideService(DpopProofs.DpopProofReplay, dpopProofs));- return yield* registrations.unregisterDevice({ userId, deviceId: params.deviceId });- }, mapRelayCommonApiErrors("invalid_dpop")),- );- }),-);--export const clientApi = HttpApiBuilder.group(- RelayApi,- "client",- Effect.fnUntraced(function* (handlers) {- const config = yield* RelayConfiguration.RelayConfiguration;- const crypto = yield* Crypto.Crypto;- const relayTokens = yield* RelayTokens.RelayTokens;- const linker = yield* EnvironmentLinker.EnvironmentLinker;- const links = yield* EnvironmentLinks.EnvironmentLinks;- const managedEndpointProvider = yield* ManagedEndpointProvider.ManagedEndpointProvider;- const devices = yield* Devices.Devices;- return handlers- .handle(- "listEnvironments",- Effect.fn("relay.api.client.listEnvironments")(function* () {- const { userId } = yield* RelayClientPrincipal;- const environments = yield* links.listForUser({ userId });- return { environments };- }, mapRelayCommonApiErrors("not_authorized")),- )- .handle(- "listDevices",- Effect.fn("relay.api.client.listDevices")(function* () {- const { userId } = yield* RelayClientPrincipal;- return { devices: yield* devices.listForUser({ userId }) };- }, mapRelayCommonApiErrors("not_authorized")),- )- .handle(- "linkEnvironment",- Effect.fn("relay.api.client.linkEnvironment")(- function* (args) {- const { payload } = args;- yield* appendRelayCredentialResponseHeaders;- const { userId } = yield* RelayClientPrincipal;- const result = yield* linker.link({ userId, request: payload });- return {- ok: true,- cloudUserId: userId,- environmentId: result.environmentId,- endpoint: result.endpoint,- endpointRuntime: result.endpointRuntime,- relayIssuer: config.relayIssuer,- environmentCredential: result.environmentCredential,- cloudMintPublicKey: config.cloudMintPublicKey,- };- },- mapErrorTags({- EnvironmentLinkProofExpired: (_error, traceId) =>- new RelayEnvironmentLinkProofExpiredError({- code: "environment_link_proof_expired",- traceId,- }),- EnvironmentLinkProofInvalid: (linkError, traceId) =>- new RelayEnvironmentLinkProofInvalidError({- code: "environment_link_proof_invalid",- reason: linkError.reason,- traceId,- }),- ManagedEndpointProvisioningNotConfigured: (_error, traceId) =>- new RelayEnvironmentLinkUnavailableError({- code: "environment_link_unavailable",- reason: "managed_endpoint_not_configured",- traceId,- }),- ManagedEndpointProvisioningFailed: (_error, traceId) =>- new RelayEnvironmentLinkUnavailableError({- code: "environment_link_unavailable",- reason: "managed_endpoint_provisioning_failed",- traceId,- }),- ManagedEndpointOriginNotAllowed: (_error, traceId) =>- new RelayEnvironmentLinkProofInvalidError({- code: "environment_link_proof_invalid",- reason: "origin_not_allowed",- traceId,- }),- ManagedTunnelLimitExceeded: (limitError, traceId) =>- new RelayEnvironmentLinkLimitExceededError({- code: "environment_link_limit_exceeded",- maxTunnels: limitError.maxTunnels,- traceId,- }),- EnvironmentLinkUpsertPersistenceError: (_error, traceId) =>- new RelayEnvironmentLinkFailedError({- code: "environment_link_failed",- reason: "link_persistence_failed",- traceId,- }),- EnvironmentCredentialCreatePersistenceError: (_error, traceId) =>- new RelayEnvironmentLinkFailedError({- code: "environment_link_failed",- reason: "credential_persistence_failed",- traceId,- }),- DpopProofReplayPersistenceError: (_error, traceId) =>- new RelayEnvironmentLinkFailedError({- code: "environment_link_failed",- reason: "replay_persistence_failed",- traceId,- }),- }),- mapRelayCommonApiErrors("not_authorized"),- ),- )- .handle(- "createEnvironmentLinkChallenge",- Effect.fn("relay.api.client.createEnvironmentLinkChallenge")(function* (args) {- yield* appendRelayCredentialResponseHeaders;- 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 challenge = yield* relayTokens- .issueLinkChallenge({- userId,- request: args.payload,- jti,- issuedAtEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),- expiresAtEpochSeconds: Math.floor(expiresAt.epochMilliseconds / 1_000),- })- .pipe(Effect.catch(() => relayInternalErrorResponse("internal_error")));- return { challenge, expiresAt: DateTime.formatIso(expiresAt) };- }, mapRelayCommonApiErrors("not_authorized")),- )- .handle(- "unlinkEnvironment",- Effect.fn("relay.api.client.unlinkEnvironment")(function* (args) {- const { params } = args;- const { userId } = yield* RelayClientPrincipal;- const unlinked = yield* unlinkEnvironmentRecord({- userId,- environmentId: params.environmentId,- }).pipe(- Effect.catchTags({- SqlError: () => relayInternalErrorResponse("internal_error"),- ManagedEndpointDeprovisioningFailed: () =>- relayInternalErrorResponse("upstream_unavailable"),- }),- );- return { ok: unlinked };- }, mapRelayCommonApiErrors("not_authorized")),- )- .handle(- "releaseEnvironmentTunnel",- Effect.fn("relay.api.client.releaseEnvironmentTunnel")(function* (args) {- const { params } = args;- const { userId } = yield* RelayClientPrincipal;- // ok mirrors whether the connector token is now dead: false means a- // concurrent provision kept the recorded tunnel alive, so the caller- // must not discard its runtime config.- const released = yield* managedEndpointProvider- .release({- userId,- environmentId: params.environmentId,- })- .pipe(Effect.catch(() => relayInternalErrorResponse("upstream_unavailable")));- return { ok: released };- }, mapRelayCommonApiErrors("not_authorized")),- );- }),-);--export const tokenApi = HttpApiBuilder.group(- RelayApi,- "token",- Effect.fnUntraced(function* (handlers) {- const config = yield* RelayConfiguration.RelayConfiguration;- const crypto = yield* Crypto.Crypto;- const dpopProofs = yield* DpopProofs.DpopProofReplay;- const relayTokens = yield* RelayTokens.RelayTokens;- return handlers.handle(- "exchangeDpopAccessToken",- Effect.fn("relay.api.token.exchangeDpopAccessToken")(function* (args) {- yield* appendRelayCredentialResponseHeaders;- const issuer = normalizeRelayIssuer(config.relayIssuer);- const requestedScopes = relayTokens.resolveDpopAccessTokenScopes({- clientId: args.payload.client_id,- scope: args.payload.scope,- });- yield* Effect.annotateCurrentSpan({- "relay.auth.mode": "clerk_bearer_token_exchange",- "relay.oauth.client_id": args.payload.client_id,- "relay.oauth.scopes": args.payload.scope,- });- if (args.payload.resource !== issuer || requestedScopes === null) {- return yield* new HttpApiError.Unauthorized({});- }-- const verified = yield* verifyClerkBearerToken(config, args.payload.subject_token).pipe(- Effect.catch(() => relayAuthInvalidError("invalid_bearer")),- );- if (!verified.sub || !hasExpectedClerkAudience(verified.aud, config.clerkJwtAudience)) {- return yield* relayAuthInvalidError("invalid_bearer");- }- const proofKeyThumbprint = yield* requireDpopProof().pipe(- Effect.provideService(DpopProofs.DpopProofReplay, dpopProofs),- );- 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")),- );- return {- access_token: yield* relayTokens- .issueDpopAccessToken({- userId: verified.sub,- proofKeyThumbprint,- jti,- issuedAtEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),- expiresAtEpochSeconds: Math.floor(expiresAt.epochMilliseconds / 1_000),- clientId: args.payload.client_id,- scopes: requestedScopes,- })- .pipe(Effect.catch(() => relayInternalErrorResponse("internal_error"))),- issued_token_type: RelayAccessTokenType,- token_type: "DPoP" as const,- expires_in: Duration.toSeconds(RelayTokens.RELAY_DPOP_ACCESS_TOKEN_TTL),- scope: encodeOAuthScope(requestedScopes),- };- }, mapRelayCommonApiErrors("invalid_dpop")),- );- }),-);--export const dpopClientApi = HttpApiBuilder.group(- RelayApi,- "dpopClient",- Effect.fnUntraced(function* (handlers) {- const connector = yield* EnvironmentConnector.EnvironmentConnector;- const dpopProofs = yield* DpopProofs.DpopProofReplay;- return handlers- .handle(- "connectEnvironment",- Effect.fn("relay.api.dpopClient.connectEnvironment")(- function* (args) {- const { params, payload } = args;- yield* appendRelayCredentialResponseHeaders;- const { userId, token } = yield* RelayClientPrincipal;- const proofKeyThumbprint = yield* requireDpopPrincipalScope("environment:connect");- const requestedThumbprint = resolveConnectClientKeyThumbprint(payload);- if (!requestedThumbprint || requestedThumbprint !== proofKeyThumbprint) {- return yield* new HttpApiError.Unauthorized({});- }- const clientProofKeyThumbprint = yield* requireDpopThumbprint(proofKeyThumbprint, {- expectedAccessToken: token,- }).pipe(Effect.provideService(DpopProofs.DpopProofReplay, dpopProofs));- return yield* connector.connect({- userId,- environmentId: params.environmentId,- clientProofKeyThumbprint,- ...(payload.deviceId ? { deviceId: payload.deviceId } : {}),- });- },- mapRelayCommonApiErrors("invalid_dpop"),- mapErrorTags({- EnvironmentConnectNotAuthorized: (error, traceId) =>- new RelayEnvironmentConnectNotAuthorizedError({- code: "environment_connect_not_authorized",- reason: error.reason,- traceId,- }),- EnvironmentMintRequestFailed: (_error, traceId) =>- new RelayEnvironmentEndpointUnavailableError({- code: "environment_endpoint_unavailable",- reason: "endpoint_request_failed",- traceId,- }),- EnvironmentMintRequestTimedOut: (_error, traceId) =>- new RelayEnvironmentEndpointTimedOutError({- code: "environment_endpoint_timed_out",- traceId,- }),- EnvironmentMintResponseInvalid: (_error, traceId) =>- new RelayEnvironmentEndpointUnavailableError({- code: "environment_endpoint_unavailable",- reason: "endpoint_response_invalid",- traceId,- }),- }),- ),- )- .handle(- "getEnvironmentStatus",- Effect.fn("relay.api.dpopClient.getEnvironmentStatus")(- function* (args) {- const { params } = args;- const { userId, token } = yield* RelayClientPrincipal;- const proofKeyThumbprint = yield* requireDpopPrincipalScope("environment:status");- yield* requireDpopThumbprint(proofKeyThumbprint, {- expectedAccessToken: token,- }).pipe(Effect.provideService(DpopProofs.DpopProofReplay, dpopProofs));- return yield* connector.status({- userId,- environmentId: params.environmentId,- });- },- mapRelayCommonApiErrors("invalid_dpop"),- mapErrorTags({- EnvironmentConnectNotAuthorized: (error, traceId) =>- new RelayEnvironmentConnectNotAuthorizedError({- code: "environment_connect_not_authorized",- reason: error.reason,- traceId,- }),- EnvironmentMintRequestFailed: (_error, traceId) =>- new RelayEnvironmentEndpointUnavailableError({- code: "environment_endpoint_unavailable",- reason: "endpoint_request_failed",- traceId,- }),- EnvironmentMintRequestTimedOut: (_error, traceId) =>- new RelayEnvironmentEndpointTimedOutError({- code: "environment_endpoint_timed_out",- traceId,- }),- EnvironmentMintResponseInvalid: (_error, traceId) =>- new RelayEnvironmentEndpointUnavailableError({- code: "environment_endpoint_unavailable",- reason: "endpoint_response_invalid",- traceId,- }),- }),- ),- );- }),-);--export const serverApi = HttpApiBuilder.group(- RelayApi,- "server",- Effect.fnUntraced(function* (handlers) {- const publisher = yield* AgentActivityPublisher.AgentActivityPublisher;- const publishSignatures = yield* EnvironmentPublishSignatures.EnvironmentPublishSignatures;- return handlers.handle(- "publishAgentActivity",- Effect.fn("relay.api.server.publishAgentActivity")(- function* (args) {- const { params, payload } = args;- const principal = yield* RelayEnvironmentPrincipal;- if (principal.environmentId !== params.environmentId) {- return yield* new HttpApiError.Unauthorized({});- }- yield* publishSignatures.verify({- environmentId: params.environmentId,- environmentPublicKey: principal.environmentPublicKey,- threadId: params.threadId,- request: payload,- });- return yield* publisher.publish({- environmentId: params.environmentId,- environmentPublicKey: principal.environmentPublicKey,- threadId: params.threadId,- state: payload.state,- });- },- mapErrorTags({- EnvironmentPublishPublicKeyMissing: (_error, traceId) =>- new RelayAuthInvalidError({- code: "auth_invalid",- reason: "not_authorized",- traceId,- }),- EnvironmentPublishSignatureExpired: (_error, traceId) =>- new RelayAgentActivityPublishProofExpiredError({- code: "agent_activity_publish_proof_expired",- traceId,- }),- EnvironmentPublishSignatureInvalid: (_error, traceId) =>- new RelayAgentActivityPublishProofInvalidError({- code: "agent_activity_publish_proof_invalid",- reason: "invalid_signature_or_payload",- traceId,- }),- DpopProofReplayPersistenceError: (_error, traceId) =>- new RelayInternalError({- code: "internal_error",- reason: "persistence_failed",- traceId,- }),- ApnsDeliveryJobQueuePayloadInvalid: (_error, traceId) =>- new RelayInternalError({- code: "internal_error",- reason: "internal_error",- traceId,- }),- ApnsDeliveryJobLiveActivityAggregateMissing: (_error, traceId) =>- new RelayInternalError({- code: "internal_error",- reason: "internal_error",- traceId,- }),- ApnsDeliveryJobLiveActivityNotificationUnexpected: (_error, traceId) =>- new RelayInternalError({- code: "internal_error",- reason: "internal_error",- traceId,- }),- ApnsDeliveryJobPushNotificationMissing: (_error, traceId) =>- new RelayInternalError({- code: "internal_error",- reason: "internal_error",- traceId,- }),- ApnsDeliveryJobPushNotificationAggregateUnexpected: (_error, traceId) =>- new RelayInternalError({- code: "internal_error",- reason: "internal_error",- traceId,- }),- ApnsDeliveryJobCreatedAtInvalid: (_error, traceId) =>- new RelayInternalError({- code: "internal_error",- reason: "internal_error",- traceId,- }),- ApnsDeliveryJobExpiresAtInvalid: (_error, traceId) =>- new RelayInternalError({- code: "internal_error",- reason: "internal_error",- traceId,- }),- ApnsDeliveryJobTimeWindowInvalid: (_error, traceId) =>- new RelayInternalError({- code: "internal_error",- reason: "internal_error",- traceId,- }),- ApnsDeliveryJobTimeWindowTooLong: (_error, traceId) =>- new RelayInternalError({- code: "internal_error",- reason: "internal_error",- traceId,- }),- ApnsDeliveryJobSignatureInvalid: (_error, traceId) =>- new RelayInternalError({- code: "internal_error",- reason: "internal_error",- traceId,- }),- ApnsDeliveryJobExpired: (_error, traceId) =>- new RelayInternalError({- code: "internal_error",- reason: "internal_error",- traceId,- }),- ApnsDeliveryJobClaimInFlight: (_error, traceId) =>- new RelayInternalError({- code: "internal_error",- reason: "internal_error",- traceId,- }),- ApnsDeliveryQueueSendError: (_error, traceId) =>- new RelayInternalError({- code: "internal_error",- reason: "upstream_unavailable",- traceId,- }),- }),- mapRelayCommonApiErrors("not_authorized"),- ),- );- }),-);--class ClerkTokenVerificationFailed extends Schema.TaggedErrorClass<ClerkTokenVerificationFailed>()(- "ClerkTokenVerificationFailed",- {- cause: Schema.Defect(),- },-) {- override get message(): string {- return "Clerk token verification failed";- }-}--const isHttpUnauthorized = Schema.is(HttpApiError.Unauthorized);--const currentTraceId = Effect.currentParentSpan.pipe(- Effect.map((span) => span.traceId),- Effect.orElseSucceed(() => "unavailable"),-);--const RelayCommonPersistenceError = Schema.Union([- Devices.DeviceRegistrationPersistenceError,- Devices.DeviceUnregistrationPersistenceError,- Devices.DeviceListPersistenceError,- LiveActivities.LiveActivityRegistrationPersistenceError,- EnvironmentLinks.EnvironmentLinkUserListPersistenceError,- EnvironmentLinks.EnvironmentPublicKeyListPersistenceError,- EnvironmentLinks.EnvironmentLinkListPersistenceError,- EnvironmentLinks.EnvironmentLinkLookupPersistenceError,- EnvironmentLinks.EnvironmentLinkRevokePersistenceError,- ManagedEndpointAllocations.ManagedEndpointAllocationPersistenceError,- EnvironmentCredentials.EnvironmentCredentialAuthenticatePersistenceError,- EnvironmentCredentials.EnvironmentCredentialRevokePersistenceError,- DpopProofs.DpopProofReplayPersistenceError,- LiveActivities.LiveActivityTargetListPersistenceError,- AgentActivityRows.AgentActivityRowUpsertPersistenceError,- AgentActivityRows.AgentActivityRowDeletePersistenceError,- AgentActivityRows.AgentActivityRowListPersistenceError,- LiveActivities.LiveActivityDeliveryMarkPersistenceError,- DeliveryAttempts.DeliveryAttemptRecordPersistenceError,-]);-type RelayCommonPersistenceError = typeof RelayCommonPersistenceError.Type;-const isRelayCommonPersistenceError = Schema.is(RelayCommonPersistenceError);--type MapRelayCommonApiError<E> =- | Exclude<E, HttpApiError.Unauthorized | RelayCommonPersistenceError>- | (Extract<E, HttpApiError.Unauthorized> extends never ? never : RelayAuthInvalidError)- | (Extract<E, RelayCommonPersistenceError> extends never ? never : RelayInternalError);--function relayInternalErrorResponse(reason: RelayInternalError["reason"]) {- return currentTraceId.pipe(- Effect.flatMap((traceId) =>- Effect.fail(new RelayInternalError({ code: "internal_error", reason, traceId })),- ),- );-}--function mapRelayCommonApiErrors(authReason: RelayAuthInvalidReason) {- const mapError = Effect.fnUntraced(function* <E>(error: E) {- const traceId = yield* currentTraceId;- if (isHttpUnauthorized(error)) {- return yield* Effect.fail(- new RelayAuthInvalidError({- code: "auth_invalid",- reason: authReason,- traceId,- }) as MapRelayCommonApiError<E>,- );- }- if (isRelayCommonPersistenceError(error)) {- return yield* Effect.fail(- new RelayInternalError({- code: "internal_error",- reason: "persistence_failed",- traceId,- }) as MapRelayCommonApiError<E>,- );- }-- return yield* Effect.fail(error as MapRelayCommonApiError<E>);- });-- return <A, E, R>(- effect: Effect.Effect<A, E, R>,- ): Effect.Effect<A, MapRelayCommonApiError<E>, R> => effect.pipe(Effect.catch(mapError));-}--type TaggedErrorTag<E> = Extract<E, { readonly _tag: string }>["_tag"];--type MapErrorTagCases<E> = {- readonly [K in TaggedErrorTag<E>]+?: (- error: Extract<E, { readonly _tag: K }>,- traceId: string,- ) => unknown;-};--type MappedTagError<Cases> = Cases[keyof Cases] extends (- ...args: ReadonlyArray<never>-) => infer Error- ? Error- : never;--type CatchTagCases<E, Cases> = {- readonly [K in TaggedErrorTag<E>]+?: (- error: Extract<E, { readonly _tag: K }>,- ) => Effect.Effect<never, MappedTagError<Cases>>;-} & (unknown extends E ? {} : { readonly [K in Exclude<keyof Cases, TaggedErrorTag<E>>]: never });--function mapErrorTags<- E,- Cases extends MapErrorTagCases<E> &- (unknown extends E ? {} : { readonly [K in Exclude<keyof Cases, TaggedErrorTag<E>>]: never }),->(cases: Cases) {- const catchCases = Record.map(- cases as Record.ReadonlyRecord<- string,- (error: never, traceId: string) => MappedTagError<Cases>- >,- (makeError) => (error: never) =>- currentTraceId.pipe(Effect.flatMap((traceId) => Effect.fail(makeError(error, traceId)))),- ) as CatchTagCases<E, Cases>;-- return <A, R>(- self: Effect.Effect<A, E, R>,- ): Effect.Effect<A, Exclude<E, { readonly _tag: keyof Cases }> | MappedTagError<Cases>, R> =>- // @effect-diagnostics-next-line unsafeEffectTypeAssertion:off- Effect.catchTags(self, catchCases) as Effect.Effect<- A,- Exclude<E, { readonly _tag: keyof Cases }> | MappedTagError<Cases>,- R- >;-}--function resolveConnectClientKeyThumbprint(payload: RelayEnvironmentConnectRequest): string | null {- const requestedThumbprint = payload.clientKeyThumbprint ?? payload.clientProofKeyThumbprint;- if (!requestedThumbprint) {- return null;- }- if (- payload.clientKeyThumbprint &&- payload.clientProofKeyThumbprint &&- payload.clientKeyThumbprint !== payload.clientProofKeyThumbprint- ) {- return null;- }- return requestedThumbprint;-}--function safeAuthFailureReason(value: string): string {- return /^[a-z0-9._-]+$/i.test(value) ? value : "unknown";-}--function clerkVerificationFailureReason(cause: unknown): string {- if (- cause instanceof Error &&- (cause.message.startsWith("Invalid JWT audience claim ") ||- cause.message.startsWith("Invalid JWT audience claim array "))- ) {- return "audience_mismatch";- }- if (typeof cause === "object" && cause !== null && "reason" in cause) {- const reason = (cause as { readonly reason?: unknown }).reason;- if (typeof reason === "string" && reason.length > 0) {- return safeAuthFailureReason(reason);- }- }- if (cause instanceof Error && cause.name) {- return safeAuthFailureReason(cause.name);- }- return "unknown";-}--function hasExpectedClerkAudience(audience: unknown, expectedAudience: string): boolean {- return typeof audience === "string"- ? audience === expectedAudience- : Array.isArray(audience) &&- audience.some((entry) => typeof entry === "string" && entry === expectedAudience);-}--function verifyClerkBearerToken(- config: RelayConfiguration.RelayConfiguration["Service"],- token: string,-) {- return Effect.tryPromise({- try: () =>- verifyToken(token, {- secretKey: Redacted.value(config.clerkSecretKey),- audience: config.clerkJwtAudience,- }),- catch: (cause) => new ClerkTokenVerificationFailed({ cause }),- }).pipe(- Effect.withSpan("verify_clerk_bearer_token", {- attributes: { "relay.auth.token_length": token.length },- }),- );-}--function verifyClerkOAuthBearerToken(- config: RelayConfiguration.RelayConfiguration["Service"],- token: string,-) {- return Effect.tryPromise({- try: async () => {- const client = createClerkClient({- secretKey: Redacted.value(config.clerkSecretKey),- publishableKey: config.clerkPublishableKey,- });- const state = await client.authenticateRequest(- new Request(config.relayIssuer, {- headers: { authorization: `Bearer ${token}` },- }),- { acceptsToken: "oauth_token" },- );- const auth = state.toAuth();- if (!state.isAuthenticated || !auth.userId) {- throw new Error("Clerk OAuth token is not authenticated.");- }- return { sub: auth.userId };- },- catch: (cause) => new ClerkTokenVerificationFailed({ cause }),- });-}--export function verifyRelayClientBearerToken(- config: RelayConfiguration.RelayConfiguration["Service"],- token: string,-) {- return verifyClerkBearerToken(config, token).pipe(- Effect.flatMap((verified) =>- verified.sub && hasExpectedClerkAudience(verified.aud, config.clerkJwtAudience)- ? Effect.succeed({ sub: verified.sub, mode: "clerk_session_bearer" as const })- : Effect.fail(new ClerkTokenVerificationFailed({ cause: "missing_relay_audience" })),- ),- Effect.catch(() =>- verifyClerkOAuthBearerToken(config, token).pipe(- Effect.map((verified) => ({ ...verified, mode: "clerk_oauth_bearer" as const })),- ),- ),- );-}--const requireDpopPrincipalScope = Effect.fn("relay.api.require_dpop_principal_scope")(function* (- scope: RelayDpopAccessTokenScope,-) {- yield* Effect.annotateCurrentSpan({ "relay.dpop.required_scope": scope });- const principal = yield* RelayClientPrincipal;- if (!principal.proofKeyThumbprint || !principal.dpopScopes?.includes(scope)) {- return yield* new HttpApiError.Unauthorized({});- }- return principal.proofKeyThumbprint;-});--const requireDpopThumbprint = Effect.fn("relay.api.require_dpop_thumbprint")(function* (- expectedThumbprint: string,- options?: {- readonly expectedAccessToken?: string;- },-) {- const request = yield* HttpServerRequest.HttpServerRequest;- const now = yield* DateTime.now;- const url = HttpServerRequest.toURL(request);- if (url._tag === "None") {- return yield* new HttpApiError.Unauthorized({});- }- const dpopProofs = yield* DpopProofs.DpopProofReplay;- return yield* dpopProofs.verifyAndConsume({- proof: request.headers.dpop,- method: request.method,- url: url.value.href,- now,- expectedThumbprint,- ...(options?.expectedAccessToken ? { expectedAccessToken: options.expectedAccessToken } : {}),- });-});--const requireDpopProof = Effect.fn("relay.api.require_dpop_proof")(function* (options?: {- readonly expectedAccessToken?: string;-}) {- const request = yield* HttpServerRequest.HttpServerRequest;- const now = yield* DateTime.now;- const url = HttpServerRequest.toURL(request);- if (url._tag === "None") {- return yield* new HttpApiError.Unauthorized({});- }- const dpopProofs = yield* DpopProofs.DpopProofReplay;- return yield* dpopProofs.verifyAndConsume({- proof: request.headers.dpop,- method: request.method,- url: url.value.href,- now,- ...(options?.expectedAccessToken ? { expectedAccessToken: options.expectedAccessToken } : {}),- });-});--const relayAuthInvalidError = Effect.fnUntraced(function* (reason: RelayAuthInvalidReason) {- const traceId = yield* currentTraceId;- yield* Effect.annotateCurrentSpan({- "relay.trace_id": traceId,- "relay.error.outbound_tag": "RelayAuthInvalidError",- "relay.error.outbound_reason": reason,- });- return yield* new RelayAuthInvalidError({ code: "auth_invalid", reason, traceId });-});diff --git a/infra/relay/src/observability.test.ts b/infra/relay/src/observability.test.tsdeleted file mode 100644index 3958b28b9..000000000--- a/infra/relay/src/observability.test.ts+++ /dev/null@@ -1,85 +0,0 @@-import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";-import { expect, it } from "@effect/vitest";-import * as Deferred from "effect/Deferred";-import * as Effect from "effect/Effect";-import * as Redacted from "effect/Redacted";-import * as Schema from "effect/Schema";-import * as HttpServer from "effect/unstable/http/HttpServer";-import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";-import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";-import type { OtlpTracer } from "effect/unstable/observability";--import * as EnvironmentConnector from "./environments/EnvironmentConnector.ts";-import { makeRelayTraceLayer } from "./observability.ts";--interface ExportedRequest {- readonly authorization: string | undefined;- readonly body: string;- readonly dataset: string | undefined;-}--const otlpAttributeValue = (value: {- readonly stringValue?: string | null;- readonly boolValue?: boolean | null;- readonly intValue?: string | number | null;- readonly doubleValue?: number | null;-}) => value.stringValue ?? value.boolValue ?? value.intValue ?? value.doubleValue;--const decodeJson = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));--it.effect("exports schema error fields as span attributes", () =>- Effect.gen(function* () {- const exportedRequest = yield* Deferred.make<ExportedRequest>();- yield* HttpServer.serveEffect(- Effect.gen(function* () {- const request = yield* HttpServerRequest.HttpServerRequest;- yield* Deferred.succeed(exportedRequest, {- authorization: request.headers.authorization,- body: yield* request.text,- dataset: request.headers["x-axiom-dataset"],- });- return HttpServerResponse.empty({ status: 204 });- }),- );-- yield* Effect.fail(- new EnvironmentConnector.EnvironmentConnectNotAuthorized({- environmentId: "environment-1",- operation: "connect",- reason: "managed_endpoint_allocation_not_ready",- }),- ).pipe(- Effect.withSpan("relay.test.schema_error"),- Effect.exit,- Effect.provide(- makeRelayTraceLayer({- tracesEndpoint: "/v1/traces",- tracesDatasetName: "relay-test-traces",- ingestToken: Redacted.make("test-token"),- }),- ),- );-- const request = yield* Deferred.await(exportedRequest).pipe(Effect.timeout("1 second"));- const payload = (yield* decodeJson(request.body)) as OtlpTracer.TraceData;- const span = payload.resourceSpans- .flatMap((resourceSpan) => resourceSpan.scopeSpans)- .flatMap((scopeSpan) => scopeSpan.spans)- .find((candidate) => candidate.name === "relay.test.schema_error");- const attributes = Object.fromEntries(- (span?.attributes ?? []).map((attribute) => [- attribute.key,- otlpAttributeValue(attribute.value),- ]),- );-- expect(request.authorization).toBe("Bearer test-token");- expect(request.dataset).toBe("relay-test-traces");- expect(attributes).toMatchObject({- "error.type": "EnvironmentConnectNotAuthorized",- "error.environmentId": "environment-1",- "error.operation": "connect",- "error.reason": "managed_endpoint_allocation_not_ready",- });- }).pipe(Effect.provide(NodeHttpServer.layerTest), Effect.scoped),-);diff --git a/infra/relay/src/observability.ts b/infra/relay/src/observability.tsdeleted file mode 100644index ca091d8cc..000000000--- a/infra/relay/src/observability.ts+++ /dev/null@@ -1,237 +0,0 @@-import * as Alchemy from "alchemy";-import * as Axiom from "alchemy/Axiom";-import * as Output from "alchemy/Output";-import * as Cause from "effect/Cause";-import * as Effect from "effect/Effect";-import * as Exit from "effect/Exit";-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 Tracer from "effect/Tracer";-import { OtlpExporter, OtlpSerialization, OtlpTracer } from "effect/unstable/observability";--import { relayResourceNameForStage } from "./deploymentConfig.ts";--const relayRecentSpansQuery = (dataset: string) =>- [- `['${dataset}']`,- `| where isnotnull(span_id) or isnotnull(trace_id)`,- `| extend requestMethod = column_ifexists('attributes.http.request.method', ''), path = column_ifexists('attributes.url.path', ''), endpoint = column_ifexists('attributes.http.route', ''), statusCode = column_ifexists('attributes.http.response.status_code', 0), customAttributes = column_ifexists('attributes.custom', dynamic({}))`,- `| extend userId = customAttributes['user']['id']`,- `| project _time, name, trace_id, span_id, duration, requestMethod, path, statusCode, endpoint, userId`,- `| order by _time desc`,- `| limit 200`,- ].join("\n");--export const RelayObservability = Effect.gen(function* () {- const { stage } = yield* Alchemy.Stack;- const traces = yield* Axiom.Dataset("RelayTracesDataset", {- name: relayResourceNameForStage("t3-code-relay-traces", stage),- kind: "otel:traces:v1",- description: "T3 Code relay Worker HTTP request spans.",- retentionDays: 30,- useRetentionPeriod: true,- });-- const workerIngestToken = yield* Axiom.ApiToken("RelayWorkerAxiomIngestToken", {- name: relayResourceNameForStage("t3-code-relay-otel-ingest", stage),- description: "Owned by Alchemy. Scoped OTLP ingest token for relay HTTP spans.",- datasetCapabilities: Output.map(traces.name, (dataset) => ({- [dataset]: { ingest: ["create" as const] },- })),- });-- const mobileIngestToken = yield* Axiom.ApiToken("RelayMobileAxiomIngestToken", {- name: relayResourceNameForStage("t3-code-mobile-otel-ingest", stage),- description: "Owned by Alchemy. Scoped OTLP ingest token for T3 Code mobile spans.",- datasetCapabilities: Output.map(traces.name, (dataset) => ({- [dataset]: { ingest: ["create" as const] },- })),- });-- const clientIngestToken = yield* Axiom.ApiToken("RelayClientAxiomIngestToken", {- name: relayResourceNameForStage("t3-code-relay-client-otel-ingest", stage),- description: "Owned by Alchemy. Scoped OTLP ingest token for first-party relay client spans.",- datasetCapabilities: Output.map(traces.name, (dataset) => ({- [dataset]: { ingest: ["create" as const] },- })),- });-- yield* Axiom.View("RelayRecentSpansView", {- name: relayResourceNameForStage("t3-code-relay-recent-spans", stage),- description: "Recent relay HTTP request spans.",- datasets: [traces.name],- aplQuery: Output.map(traces.name, relayRecentSpansQuery),- });-- return { traces, workerIngestToken, mobileIngestToken, clientIngestToken } as const;-});--export const withSpanAttributes =- (attributes: Record<string, unknown>) =>- <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>- Effect.annotateCurrentSpan(attributes).pipe(- Effect.andThen(effect.pipe(Effect.annotateSpans(attributes))),- );--const appendEncodedAttributes = (- attributes: Record<string, unknown>,- prefix: string,- value: unknown,-): void => {- if (- value === null ||- typeof value === "string" ||- typeof value === "number" ||- typeof value === "boolean" ||- typeof value === "bigint" ||- Array.isArray(value)- ) {- attributes[prefix] = value;- return;- }- if (typeof value !== "object") {- return;- }- for (const [key, child] of Object.entries(value)) {- appendEncodedAttributes(attributes, `${prefix}.${key}`, child);- }-};--const schemaErrorAttributes = (error: unknown): Record<string, unknown> | undefined => {- if (typeof error !== "object" || error === null) {- return undefined;- }- const constructor = error.constructor;- if (!Schema.isSchema(constructor)) {- return undefined;- }- const encoded = Schema.encodeUnknownOption(constructor as unknown as Schema.Encoder<unknown>)(- error,- );- if (Option.isNone(encoded) || typeof encoded.value !== "object" || encoded.value === null) {- return undefined;- }- const tag = Reflect.get(encoded.value, "_tag");- if (typeof tag !== "string") {- return undefined;- }-- const attributes: Record<string, unknown> = {- "error.type": tag,- };- for (const [key, value] of Object.entries(encoded.value)) {- if (key !== "_tag") {- appendEncodedAttributes(attributes, `error.${key}`, value);- }- }- return attributes;-};--const annotateSchemaError = (span: Tracer.Span, exit: Exit.Exit<unknown, unknown>): void => {- if (Exit.isSuccess(exit)) {- return;- }- for (const reason of exit.cause.reasons) {- const error = Cause.isFailReason(reason)- ? reason.error- : Cause.isDieReason(reason)- ? reason.defect- : undefined;- const attributes = schemaErrorAttributes(error);- if (attributes) {- for (const [key, value] of Object.entries(attributes)) {- span.attribute(key, value);- }- return;- }- }-};--class RelayTraceSpan implements Tracer.Span {- readonly _tag = "Span";- private readonly delegate: Tracer.Span;-- constructor(delegate: Tracer.Span) {- this.delegate = delegate;- }-- get name() {- return this.delegate.name;- }- get spanId() {- return this.delegate.spanId;- }- get traceId() {- return this.delegate.traceId;- }- get parent() {- return this.delegate.parent;- }- get annotations() {- return this.delegate.annotations;- }- get status() {- return this.delegate.status;- }- get attributes() {- return this.delegate.attributes;- }- get links() {- return this.delegate.links;- }- get sampled() {- return this.delegate.sampled;- }- get kind() {- return this.delegate.kind;- }-- end(endTime: bigint, exit: Exit.Exit<unknown, unknown>): void {- annotateSchemaError(this.delegate, exit);- this.delegate.end(endTime, exit);- }-- attribute(key: string, value: unknown): void {- this.delegate.attribute(key, value);- }-- event(name: string, startTime: bigint, attributes?: Record<string, unknown>): void {- this.delegate.event(name, startTime, attributes);- }-- addLinks(links: ReadonlyArray<Tracer.SpanLink>): void {- this.delegate.addLinks(links);- }-}--const withSchemaErrorAttributes = (delegate: Tracer.Tracer): Tracer.Tracer =>- Tracer.make({- span: (options) => new RelayTraceSpan(delegate.span(options)),- ...(delegate.context ? { context: delegate.context } : {}),- });--export const makeRelayTraceLayer = (input: {- readonly tracesEndpoint: string;- readonly tracesDatasetName: string;- readonly ingestToken: Redacted.Redacted<string>;-}) =>- Layer.effect(- Tracer.Tracer,- OtlpTracer.make({- url: input.tracesEndpoint,- resource: {- serviceName: "t3-code-relay-worker",- attributes: {- "service.runtime": "cloudflare-worker",- "service.component": "relay",- },- },- headers: {- Authorization: `Bearer ${Redacted.value(input.ingestToken)}`,- "X-Axiom-Dataset": input.tracesDatasetName,- },- exportInterval: "1 second",- }).pipe(Effect.map(withSchemaErrorAttributes)),- ).pipe(Layer.provideMerge(OtlpExporter.layerFlusher), Layer.provide(OtlpSerialization.layerJson));diff --git a/infra/relay/src/persistence/schema.ts b/infra/relay/src/persistence/schema.tsdeleted file mode 100644index 61b72f2df..000000000--- a/infra/relay/src/persistence/schema.ts+++ /dev/null@@ -1,191 +0,0 @@-import type {- RelayAgentActivityAggregateState,- RelayAgentActivityState,- RelayAgentAwarenessPreferences,-} from "@t3tools/contracts/relay";-import {- boolean,- index,- integer,- jsonb,- pgTable,- primaryKey,- text,- uniqueIndex,- varchar,-} from "drizzle-orm/pg-core";--export const relayMobileDevices = pgTable(- "relay_mobile_devices",- {- userId: varchar("user_id", { length: 255 }).notNull(),- deviceId: varchar("device_id", { length: 255 }).notNull(),- label: text("label").notNull().default("iOS device"),- platform: varchar("platform", { length: 16 }).notNull().$type<"ios">(),- iosMajorVersion: integer("ios_major_version").notNull(),- appVersion: varchar("app_version", { length: 64 }),- bundleId: varchar("bundle_id", { length: 255 }),- apsEnvironment: varchar("aps_environment", { length: 16 }).$type<"sandbox" | "production">(),- pushToken: text("push_token"),- pushToStartToken: text("push_to_start_token"),- preferencesJson: jsonb("preferences_json").notNull().$type<RelayAgentAwarenessPreferences>(),- createdAt: varchar("created_at", { length: 64 }).notNull(),- updatedAt: varchar("updated_at", { length: 64 }).notNull(),- },- (table) => [- primaryKey({ columns: [table.userId, table.deviceId] }),- uniqueIndex("idx_relay_mobile_devices_push_token").on(table.pushToken),- uniqueIndex("idx_relay_mobile_devices_push_to_start_token").on(table.pushToStartToken),- ],-);--export const relayLiveActivities = pgTable(- "relay_live_activities",- {- userId: varchar("user_id", { length: 255 }).notNull(),- deviceId: varchar("device_id", { length: 255 }).notNull(),- activityPushToken: text("activity_push_token"),- remoteStartQueuedAt: varchar("remote_start_queued_at", { length: 64 }),- remoteStartedAt: varchar("remote_started_at", { length: 64 }),- endedAt: varchar("ended_at", { length: 64 }),- lastAggregateJson: jsonb("last_aggregate_json").$type<RelayAgentActivityAggregateState>(),- lastLiveActivityDeliveryAt: varchar("last_live_activity_delivery_at", { length: 64 }),- createdAt: varchar("created_at", { length: 64 }).notNull(),- updatedAt: varchar("updated_at", { length: 64 }).notNull(),- },- (table) => [- primaryKey({ columns: [table.userId, table.deviceId] }),- uniqueIndex("idx_relay_live_activities_activity_push_token").on(table.activityPushToken),- ],-);--export const relayEnvironmentLinks = pgTable(- "relay_environment_links",- {- userId: varchar("user_id", { length: 191 }).notNull(),- environmentId: varchar("environment_id", { length: 191 }).notNull(),- environmentLabel: text("environment_label").notNull().default("T3 Environment"),- environmentPublicKey: text("environment_public_key").notNull(),- endpointHttpBaseUrl: text("endpoint_http_base_url").notNull(),- endpointWsBaseUrl: text("endpoint_ws_base_url").notNull(),- endpointProviderKind: varchar("endpoint_provider_kind", { length: 32 }).notNull(),- notificationsEnabled: boolean("notifications_enabled").notNull().default(true),- liveActivitiesEnabled: boolean("live_activities_enabled").notNull().default(true),- managedTunnelsEnabled: boolean("managed_tunnels_enabled").notNull().default(false),- createdByDeviceId: varchar("created_by_device_id", { length: 191 }),- revokedAt: varchar("revoked_at", { length: 64 }),- createdAt: varchar("created_at", { length: 64 }).notNull(),- updatedAt: varchar("updated_at", { length: 64 }).notNull(),- },- (table) => [- primaryKey({ columns: [table.userId, table.environmentId] }),- index("idx_relay_environment_links_environment").on(table.environmentId, table.revokedAt),- ],-);--export const relayManagedEndpointAllocations = pgTable(- "relay_managed_endpoint_allocations",- {- userId: varchar("user_id", { length: 191 }).notNull(),- environmentId: varchar("environment_id", { length: 191 }).notNull(),- hostname: text("hostname").notNull(),- tunnelId: varchar("tunnel_id", { length: 191 }),- tunnelName: text("tunnel_name").notNull(),- dnsRecordId: varchar("dns_record_id", { length: 191 }),- readyAt: varchar("ready_at", { length: 64 }),- createdAt: varchar("created_at", { length: 64 }).notNull(),- updatedAt: varchar("updated_at", { length: 64 }).notNull(),- },- (table) => [- primaryKey({ columns: [table.userId, table.environmentId] }),- uniqueIndex("idx_relay_managed_endpoint_allocations_hostname").on(table.hostname),- uniqueIndex("idx_relay_managed_endpoint_allocations_tunnel_name").on(table.tunnelName),- ],-);--export const relayManagedTunnelLimits = pgTable("relay_managed_tunnel_limits", {- userId: varchar("user_id", { length: 191 }).primaryKey(),- maxTunnels: integer("max_tunnels").notNull(),- createdAt: varchar("created_at", { length: 64 }).notNull(),- updatedAt: varchar("updated_at", { length: 64 }).notNull(),-});--export const relayEnvironmentCredentials = pgTable(- "relay_environment_credentials",- {- credentialId: varchar("credential_id", { length: 64 }).primaryKey(),- environmentId: varchar("environment_id", { length: 191 }).notNull(),- environmentPublicKey: text("environment_public_key").notNull(),- credentialHash: varchar("credential_hash", { length: 191 }).notNull(),- revokedAt: varchar("revoked_at", { length: 64 }),- createdAt: varchar("created_at", { length: 64 }).notNull(),- updatedAt: varchar("updated_at", { length: 64 }).notNull(),- },- (table) => [- uniqueIndex("idx_relay_environment_credentials_hash").on(table.credentialHash),- index("idx_relay_environment_credentials_environment").on(table.environmentId, table.revokedAt),- index("idx_relay_environment_credentials_environment_key").on(- table.environmentId,- table.environmentPublicKey,- table.revokedAt,- ),- ],-);--export const relayAgentActivityRows = pgTable(- "relay_agent_activity_rows",- {- environmentId: varchar("environment_id", { length: 191 }).notNull(),- environmentPublicKey: text("environment_public_key").notNull(),- threadId: varchar("thread_id", { length: 191 }).notNull(),- stateJson: jsonb("state_json").notNull().$type<RelayAgentActivityState>(),- updatedAt: varchar("updated_at", { length: 64 }).notNull(),- createdAt: varchar("created_at", { length: 64 }).notNull(),- },- (table) => [- primaryKey({ columns: [table.environmentId, table.environmentPublicKey, table.threadId] }),- index("idx_relay_agent_activity_rows_updated").on(table.updatedAt),- ],-);--export const relayDeliveryAttempts = pgTable(- "relay_delivery_attempts",- {- id: varchar("id", { length: 36 }).primaryKey(),- createdAt: varchar("created_at", { length: 64 }).notNull(),- userId: varchar("user_id", { length: 255 }),- environmentId: varchar("environment_id", { length: 191 }),- threadId: varchar("thread_id", { length: 191 }),- deviceId: varchar("device_id", { length: 255 }),- kind: varchar("kind", { length: 64 }).notNull(),- sourceJobId: varchar("source_job_id", { length: 64 }),- tokenSuffix: varchar("token_suffix", { length: 16 }),- apnsStatus: integer("apns_status"),- apnsReason: text("apns_reason"),- apnsId: varchar("apns_id", { length: 128 }),- transportError: text("transport_error"),- },- (table) => [- index("idx_relay_delivery_attempts_environment").on(- table.environmentId,- table.threadId,- table.createdAt,- ),- uniqueIndex("idx_relay_delivery_attempts_source_job").on(table.sourceJobId),- ],-);--export const relayDpopProofs = pgTable(- "relay_dpop_proofs",- {- thumbprint: varchar("thumbprint", { length: 128 }).notNull(),- jti: varchar("jti", { length: 255 }).notNull(),- iat: integer("iat").notNull(),- expiresAt: varchar("expires_at", { length: 64 }).notNull(),- createdAt: varchar("created_at", { length: 64 }).notNull(),- },- (table) => [- primaryKey({ columns: [table.thumbprint, table.jti] }),- index("idx_relay_dpop_proofs_expires_at").on(table.expiresAt),- ],-);diff --git a/infra/relay/src/queues.ts b/infra/relay/src/queues.tsdeleted file mode 100644index bfae5ced4..000000000--- a/infra/relay/src/queues.ts+++ /dev/null@@ -1,7 +0,0 @@-import * as Cloudflare from "alchemy/Cloudflare";--export const RelayApnsDeliveryDeadLetterQueue = Cloudflare.Queues.Queue(- "RelayApnsDeliveryDeadLetterQueue",-);--export const RelayApnsDeliveryQueue = Cloudflare.Queues.Queue("RelayApnsDeliveryQueue");diff --git a/infra/relay/src/worker.ts b/infra/relay/src/worker.tsdeleted file mode 100644index 77dfd845c..000000000--- a/infra/relay/src/worker.ts+++ /dev/null@@ -1,312 +0,0 @@-import * as Alchemy from "alchemy";-import * as Cloudflare from "alchemy/Cloudflare";-import * as Drizzle from "alchemy/Drizzle";-import * as Config from "effect/Config";-import * as DateTime from "effect/DateTime";-import * as Crypto from "effect/Crypto";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";-import * as Stream from "effect/Stream";-import * as Etag from "effect/unstable/http/Etag";-import * as HttpPlatform from "effect/unstable/http/HttpPlatform";-import * as HttpRouter from "effect/unstable/http/HttpRouter";-import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";-import * as HttpApiScalar from "effect/unstable/httpapi/HttpApiScalar";--import { RelayApi } from "@t3tools/contracts/relay";--import {- clientApi,- dpopClientApi,- healthApi,- metadataApi,- mobileApi,- relayClientAuthLayer,- relayDpopClientAuthLayer,- relayCors,- relayDocsRedirectRoute,- relayEnvironmentAuthLayer,- relayNotFoundRoute,- serverApi,- traceRelayHttpRequestWith,- tokenApi,- withoutCapturedParentSpan,-} from "./http/Api.ts";-import { ManagedEndpointZone, RelayApiZone, RelayDeploymentConfig } from "./zone.ts";-import { makeRelayTraceLayer, RelayObservability } from "./observability.ts";-import * as DeliveryAttempts from "./agentActivity/DeliveryAttempts.ts";-import * as AgentActivityRows from "./agentActivity/AgentActivityRows.ts";-import * as Devices from "./agentActivity/Devices.ts";-import * as DpopProofs from "./auth/DpopProofs.ts";-import * as RelayTokens from "./auth/RelayTokens.ts";-import * as EnvironmentCredentials from "./environments/EnvironmentCredentials.ts";-import * as EnvironmentLinks from "./environments/EnvironmentLinks.ts";-import * as ManagedEndpointAllocations from "./environments/ManagedEndpointAllocations.ts";-import * as LiveActivities from "./agentActivity/LiveActivities.ts";-import * as RelayDb from "./db.ts";-import { RelayApnsDeliveryDeadLetterQueue, RelayApnsDeliveryQueue } from "./queues.ts";-import * as RelayConfiguration from "./Config.ts";-import * as AgentActivityPublisher from "./agentActivity/AgentActivityPublisher.ts";-import * as ApnsClient from "./agentActivity/ApnsClient.ts";-import * as ApnsProviderTokens from "./agentActivity/ApnsProviderTokens.ts";-import * as ApnsDeliveryQueue from "./agentActivity/ApnsDeliveryQueue.ts";-import * as ApnsDeliveries from "./agentActivity/ApnsDeliveries.ts";-import * as EnvironmentConnector from "./environments/EnvironmentConnector.ts";-import * as EnvironmentLinker from "./environments/EnvironmentLinker.ts";-import * as EnvironmentPublishSignatures from "./environments/EnvironmentPublishSignatures.ts";-import * as ManagedEndpointProvider from "./environments/ManagedEndpointProvider.ts";-import * as ManagedTunnelLimits from "./environments/ManagedTunnelLimits.ts";-import * as MobileRegistrations from "./agentActivity/MobileRegistrations.ts";--const webcryptoLayer = 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 httpPlatformNotSupportedLayer = Layer.succeed(HttpPlatform.HttpPlatform, {- platform: "web",- compression: {- algorithms: new Set<HttpPlatform.CompressionAlgorithm>(),- compressResponse: (response) => Effect.succeed(response),- },- fileResponse: () => Effect.die("Relay API does not serve filesystem responses"),- fileWebResponse: () => Effect.die("Relay API does not serve file responses"),-});--const relayApiLayer = Layer.mergeAll(- healthApi,- metadataApi,- mobileApi,- clientApi,- tokenApi,- dpopClientApi,- serverApi,-);--const CloudMintKeyPair = Alchemy.KeyPair("CloudMintKeyPair");-const ApnsDeliveryJobSigningSecret = Alchemy.makeRandom("ApnsDeliveryJobSigningSecret", {- bytes: 32,-});--export class Api extends Cloudflare.Worker<Api, {}>()("Api") {}--export const ApiLive = Api.make(- RelayDeploymentConfig.pipe(- Effect.map(({ relayPublicDomain }) => ({- main: import.meta.filename,- compatibility: {- date: "2026-05-22",- flags: ["nodejs_compat"],- },- domain: relayPublicDomain,- })),- Effect.orDie,- ),- Effect.gen(function* () {- //- // 1. Provision Infrastructure for the Worker to use- //- const { relayPublicOrigin, stage } = yield* RelayDeploymentConfig;- const apnsDeliveryQueue = yield* RelayApnsDeliveryQueue;- const apnsDeliveryDeadLetterQueue = yield* RelayApnsDeliveryDeadLetterQueue;- const cloudMintKeyPair = yield* CloudMintKeyPair;- const relayApiZone = yield* RelayApiZone;- const managedEndpointZone = yield* ManagedEndpointZone;- const randomApnsDeliveryJobSigningSecret = yield* ApnsDeliveryJobSigningSecret;- const observability = yield* RelayObservability;-- //- // 2. Create bindings- //- const environment = yield* Config.schema(- RelayConfiguration.ApnsEnvironment,- "APNS_ENVIRONMENT",- );- const apnsTeamId = yield* Config.string("APNS_TEAM_ID");- const apnsKeyId = yield* Config.string("APNS_KEY_ID");- const apnsBundleId = yield* Config.string("APNS_BUNDLE_ID");- const apnsPrivateKey = yield* Config.redacted("APNS_PRIVATE_KEY");- const apnsDeliveryJobSigningSecret = yield* randomApnsDeliveryJobSigningSecret;- const apnsDeliveryQueueSender = yield* Cloudflare.Queues.WriteQueue(apnsDeliveryQueue);-- const axiomDatasetName = yield* observability.traces.name;- const axiomIngestToken = yield* observability.workerIngestToken.token;- const axiomTracesEndpoint = yield* observability.traces.otelTracesEndpoint;-- const clerkSecretKey = yield* Config.redacted("CLERK_SECRET_KEY");- const clerkPublishableKey = yield* Config.string("CLERK_PUBLISHABLE_KEY");- const clerkJwtAudience = yield* Config.string("CLERK_JWT_AUDIENCE");-- const cloudMintPrivateKey = yield* cloudMintKeyPair.privateKey;- const cloudMintPublicKey = yield* cloudMintKeyPair.publicKey;- const hyperdrive = yield* Cloudflare.Hyperdrive.Connect(yield* RelayDb.RelayHyperdrive);- const db = yield* Drizzle.Postgres(hyperdrive.connectionString);-- const managedEndpointTunnelBinding = yield* Cloudflare.Tunnel.ReadWriteTunnel();- // Keep Worker custom-domain reconciliation ordered after API zone provisioning.- yield* yield* relayApiZone.zoneId;- const managedEndpointDnsBinding = yield* Cloudflare.DNS.ReadWriteDns(managedEndpointZone);- const managedEndpointZoneName = yield* managedEndpointZone.name;-- //- // 3. Runtime layers and app construction- //- const alchemyRuntimeContext: Alchemy.BaseRuntimeContext = yield* Cloudflare.Worker;-- const loadSettings = Effect.gen(function* () {- return RelayConfiguration.RelayConfiguration.of({- relayIssuer: relayPublicOrigin,- apns: {- environment,- teamId: apnsTeamId,- keyId: apnsKeyId,- bundleId: apnsBundleId,- privateKey: apnsPrivateKey,- },- apnsDeliveryJobSigningSecret: yield* apnsDeliveryJobSigningSecret,- clerkSecretKey,- clerkPublishableKey,- clerkJwtAudience,- cloudMintPrivateKey: yield* cloudMintPrivateKey,- cloudMintPublicKey: yield* cloudMintPublicKey,- managedEndpointBaseDomain: yield* managedEndpointZoneName,- managedEndpointNamespace: stage,- });- });-- const relayTraceLayer = Layer.unwrap(- Effect.all({- tracesDatasetName: axiomDatasetName,- tracesEndpoint: axiomTracesEndpoint,- ingestToken: axiomIngestToken,- }).pipe(Effect.map(makeRelayTraceLayer)),- );-- const runtimeLayer = Layer.empty.pipe(- Layer.provideMerge(MobileRegistrations.layer),- Layer.provideMerge(AgentActivityPublisher.layer),- Layer.provideMerge(EnvironmentConnector.layer),- Layer.provideMerge(EnvironmentLinker.layer),- Layer.provideMerge(EnvironmentPublishSignatures.layer),- Layer.provideMerge(- ManagedEndpointProvider.layerCloudflareBindings(- managedEndpointTunnelBinding,- managedEndpointDnsBinding,- alchemyRuntimeContext,- ),- ),- Layer.provideMerge(DpopProofs.layer),- Layer.provideMerge(ApnsDeliveries.layer),- Layer.provideMerge(ApnsClient.layer.pipe(Layer.provideMerge(ApnsProviderTokens.layer))),- Layer.provideMerge(- ApnsDeliveryQueue.layerCloudflareQueues(apnsDeliveryQueueSender, alchemyRuntimeContext),- ),- Layer.provideMerge(AgentActivityRows.layer),- Layer.provideMerge(Devices.layer),- Layer.provideMerge(EnvironmentCredentials.layer),- Layer.provideMerge(- Layer.mergeAll(- EnvironmentLinks.layer,- ManagedEndpointAllocations.layer,- ManagedTunnelLimits.layer,- ),- ),- Layer.provideMerge(LiveActivities.layer),- Layer.provideMerge(DeliveryAttempts.layer),- Layer.provideMerge(RelayTokens.layer),- Layer.provideMerge(- RelayDb.RelayTransactions.layer.pipe(- Layer.provideMerge(Layer.succeed(RelayDb.RelayDb, db)),- ),- ),- Layer.provideMerge(Layer.effect(RelayConfiguration.RelayConfiguration, loadSettings)),- Layer.provideMerge(webcryptoLayer),- );-- const appLayer = relayApiLayer.pipe(- Layer.provideMerge(relayClientAuthLayer),- Layer.provideMerge(relayDpopClientAuthLayer),- Layer.provideMerge(relayEnvironmentAuthLayer),- Layer.provide(runtimeLayer),- );-- yield* Cloudflare.Queues.consumeQueueMessages<unknown>(- apnsDeliveryQueue,- {- batchSize: 10,- maxRetries: 5,- maxWaitTime: "5 seconds",- retryDelay: "30 seconds",- deadLetterQueue: apnsDeliveryDeadLetterQueue.queueName as unknown as string,- },- (stream) =>- stream.pipe(- Stream.withSpan("relay.apn_delivery_queue.process_batch"),- Stream.runForEach((message) =>- ApnsDeliveries.ApnsDeliveries.pipe(- Effect.flatMap((deliveries) => deliveries.processSignedJob(message.body)),- Effect.withSpan("relay.apn_delivery_queue.process_message"),- ),- ),- Effect.provide(runtimeLayer),- ),- );-- yield* Cloudflare.Workers.cron("*/5 * * * *", () =>- DpopProofs.DpopProofReplay.pipe(- Effect.flatMap((dpopProofs) => dpopProofs.pruneExpired),- // Terminal thread rows are kept briefly so finished agents show as- // Done/Failed in the Live Activity; sweep them once they age out.- Effect.andThen(- Effect.all([AgentActivityRows.AgentActivityRows, DateTime.now]).pipe(- Effect.flatMap(([activityRows, now]) =>- activityRows.pruneTerminal({- updatedBefore: DateTime.formatIso(DateTime.subtract(now, { minutes: 30 })),- }),- ),- ),- ),- Effect.withSpan("relay.cron.prune_expired_state"),- Effect.provide(runtimeLayer),- ),- );-- const fetch = Layer.merge(- Layer.mergeAll(- HttpApiBuilder.layer(RelayApi, { openapiPath: "/openapi.json" }).pipe(- Layer.provide(appLayer),- ),- HttpApiScalar.layer(RelayApi, { path: "/docs" }),- relayDocsRedirectRoute,- ).pipe(Layer.provide([Etag.layerWeak, httpPlatformNotSupportedLayer, relayCors])),- relayNotFoundRoute,- ).pipe(- HttpRouter.toHttpEffect,- withoutCapturedParentSpan,- Effect.flatMap((httpEffect) => traceRelayHttpRequestWith(httpEffect, relayTraceLayer)),- );-- return { fetch };- }).pipe(- Effect.provide(- Layer.empty.pipe(- Layer.provideMerge(Cloudflare.Hyperdrive.ConnectBinding),- Layer.provideMerge(Cloudflare.Workers.CronEventSourceLive),- Layer.provideMerge(Cloudflare.Queues.WriteQueueBinding),- Layer.provideMerge(Cloudflare.Queues.EventSourceLive),- Layer.provideMerge(Cloudflare.Tunnel.ReadWriteTunnelBinding),- Layer.provideMerge(Cloudflare.DNS.ReadWriteDnsHttp),- ),- ),- ),-);--export default ApiLive;diff --git a/infra/relay/src/zone.ts b/infra/relay/src/zone.tsdeleted file mode 100644index 5d1b60db2..000000000--- a/infra/relay/src/zone.ts+++ /dev/null@@ -1,74 +0,0 @@-import * as Alchemy from "alchemy";-import { adopt } from "alchemy/AdoptPolicy";-import * as Cloudflare from "alchemy/Cloudflare";-import * as Config from "effect/Config";-import * as Effect from "effect/Effect";-import * as Option from "effect/Option";--import {- MANAGED_ENDPOINT_ZONE_OWNER_STAGE,- relayOwnsManagedEndpointZone,- relayPublicDomainForStage,-} from "./deploymentConfig.ts";--function withLogicalId<Resource extends object>(resource: Resource, logicalId: string): Resource {- return new Proxy(resource, {- has: (target, property) => property === "LogicalId" || property in target,- get: (target, property, receiver) =>- property === "LogicalId" ? logicalId : Reflect.get(target, property, receiver),- });-}--export const RelayDeploymentConfig = Effect.gen(function* () {- const { stage } = yield* Alchemy.Stack;- const relayApiZoneName = yield* Config.nonEmptyString("RELAY_API_ZONE_NAME");- const managedEndpointZoneName = yield* Config.nonEmptyString("RELAY_TUNNEL_ZONE_NAME");- const relayPublicDomainOverride = yield* Config.string("RELAY_DOMAIN").pipe(- Config.option,- Config.map(- Option.flatMap((value) => {- const trimmed = value.trim();- return trimmed ? Option.some(trimmed) : Option.none();- }),- ),- );- const relayPublicDomain = Option.getOrElse(relayPublicDomainOverride, () =>- relayPublicDomainForStage(stage, relayApiZoneName),- );-- return {- stage,- relayPublicDomain,- relayPublicOrigin: `https://${relayPublicDomain}`,- relayApiZoneName,- managedEndpointZoneName,- };-});--export const ManagedEndpointZone = RelayDeploymentConfig.pipe(- Effect.flatMap(({ stage, managedEndpointZoneName }) =>- relayOwnsManagedEndpointZone(stage)- ? Cloudflare.Zone.Zone("ManagedEndpointZone", { name: managedEndpointZoneName }).pipe(- adopt(true),- )- : Cloudflare.Zone.Zone.ref("ManagedEndpointZone", {- stage: MANAGED_ENDPOINT_ZONE_OWNER_STAGE,- }).pipe(- // Alchemy beta's DNS binding policy uses LogicalId to derive a- // stable SID, but Resource.ref returns a lazy output proxy.- Effect.map((zone) => withLogicalId(zone, "ManagedEndpointZone")),- ),- ),-);--export const RelayApiZone = RelayDeploymentConfig.pipe(- Effect.flatMap(({ stage, relayApiZoneName, managedEndpointZoneName }) =>- relayApiZoneName === managedEndpointZoneName- ? ManagedEndpointZone- : relayOwnsManagedEndpointZone(stage)- ? Cloudflare.Zone.Zone("RelayApiZone", { name: relayApiZoneName }).pipe(adopt(true))- : Cloudflare.Zone.Zone.ref("RelayApiZone", {- stage: MANAGED_ENDPOINT_ZONE_OWNER_STAGE,- }),- ),-);diff --git a/infra/relay/tsconfig.json b/infra/relay/tsconfig.jsondeleted file mode 100644index 6c0840a67..000000000--- a/infra/relay/tsconfig.json+++ /dev/null@@ -1,9 +0,0 @@-{- "extends": "../../tsconfig.base.json",- "compilerOptions": {- "target": "ES2023",- "lib": ["ES2023", "WebWorker"],- "types": ["@cloudflare/workers-types", "node"]- },- "include": ["alchemy.run.ts", "scripts/**/*.ts", "src/**/*.ts"]-}diff --git a/oxlint-plugin-t3code/rules/no-manual-effect-runtime-in-tests.ts b/oxlint-plugin-t3code/rules/no-manual-effect-runtime-in-tests.tsindex e6eff1e5c..b94021261 100644--- a/oxlint-plugin-t3code/rules/no-manual-effect-runtime-in-tests.ts+++ b/oxlint-plugin-t3code/rules/no-manual-effect-runtime-in-tests.ts@@ -22,9 +22,6 @@ const EFFECT_RUNTIME_METHODS = new Set([// Existing manual runners are tracked as debt. The rule permits no net-new// occurrences in these files, while unlisted test files must have zero.const LEGACY_BASELINE = new Map<string, number>([- ["apps/mobile/src/features/agent-awareness/liveActivityPreferences.test.ts", 1],- ["apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts", 2],- ["apps/mobile/src/state/use-remote-environment-registry.test.ts", 2],["apps/server/src/orchestration/commandInvariants.test.ts", 6],["apps/server/src/orchestration/Layers/CheckpointReactor.test.ts", 42],["apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts", 5],@@ -33,7 +30,6 @@ const LEGACY_BASELINE = new Map<string, number>([["apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts", 31],["apps/server/src/orchestration/Layers/ThreadDeletionReactor.test.ts", 2],["apps/server/src/orchestration/projector.test.ts", 20],- ["apps/server/src/project/Layers/ProjectSetupScriptRunner.test.ts", 4],["apps/server/src/provider/acp/CursorAcpSupport.test.ts", 1],["apps/server/src/provider/Layers/ClaudeAdapter.test.ts", 2],["apps/server/src/provider/Layers/CodexAdapter.test.ts", 1],@@ -42,13 +38,8 @@ const LEGACY_BASELINE = new Map<string, number>([["apps/server/src/provider/Layers/CursorProvider.test.ts", 4],["apps/server/src/provider/Layers/ProviderService.test.ts", 2],["apps/server/src/provider/Layers/ProviderSessionReaper.test.ts", 21],- ["apps/server/src/relay/AgentAwarenessRelay.test.ts", 4],["apps/server/src/server.test.ts", 1],- ["apps/web/src/cloud/dpop.test.ts", 2],- ["apps/web/src/environments/runtime/service.addSavedEnvironment.test.ts", 1],["oxlint-plugin-t3code/rules/no-manual-effect-runtime-in-tests.test.ts", 7],- ["packages/client-runtime/src/relay/managedRelayState.test.ts", 1],- ["packages/client-runtime/src/wsTransport.test.ts", 2],]);const baselineFor = (filename: string): number => {diff --git a/package.json b/package.jsonindex 736232400..85e22f44c 100644--- a/package.json+++ b/package.json@@ -43,7 +43,6 @@"dist:desktop:win:arm64": "node scripts/build-desktop-artifact.ts --platform win --target nsis --arch arm64","dist:desktop:win:x64": "node scripts/build-desktop-artifact.ts --platform win --target nsis --arch x64","release:smoke": "node scripts/release-smoke.ts",- "connect:announce-ga": "node scripts/announce-connect-ga.ts","clean": "rm -rf node_modules apps/*/node_modules packages/*/node_modules apps/*/dist apps/*/dist-electron packages/*/dist .vite-plus apps/*/.vite-plus packages/*/.vite-plus","sync:repos": "node scripts/sync-reference-repos.ts"},diff --git a/packages/client-runtime/README.md b/packages/client-runtime/README.mdindex 722d6f6d3..e04c5800f 100644--- a/packages/client-runtime/README.md+++ b/packages/client-runtime/README.md@@ -7,22 +7,21 @@ subpath. The package intentionally has no root export.| Subpath | Responsibility || --------------------- | ---------------------------------------------------------------- |-| `authorization` | Bearer and DPoP authorization plus token persistence contracts |+| `authorization` | Bearer authorization and token persistence contracts || `connection` | Targets, catalog, supervision, retries, registry, and onboarding || `environment` | Environment identity, descriptors, endpoints, and scoped keys || `errors` | Shared client error inspection || `operations` | Multi-step application workflows || `operations/projects` | Multi-step project creation workflows || `platform` | Platform capability and persistence service contracts |-| `relay` | Managed relay API and environment discovery || `rpc` | HTTP/RPC clients, protocol, sessions, and subscriptions || `state/<domain>` | Focused shared state, retention, reducers, and Atom constructors |## Dependency directionPlatform applications provide `platform` services. `connection` composes those-capabilities with `authorization`, `relay`, and `rpc` to supervise environment-sessions. Independent `state` modules consume the connection registry and expose+capabilities with `authorization` and `rpc` to supervise environment sessions.+Independent `state` modules consume the connection registry and exposefocused state or Atom constructors to application-owned runtimes.Applications should import the narrowest relevant subpath. There is no broaddiff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.jsonindex 8a994a408..c5cb9c7a3 100644--- a/packages/client-runtime/package.json+++ b/packages/client-runtime/package.json@@ -51,10 +51,6 @@"types": "./src/botInbox.ts","default": "./src/botInbox.ts"},- "./relay": {- "types": "./src/relay/index.ts",- "default": "./src/relay/index.ts"- },"./state/auth": {"types": "./src/state/auth.ts","default": "./src/state/auth.ts"@@ -115,10 +111,6 @@"types": "./src/state/projectGrouping.ts","default": "./src/state/projectGrouping.ts"},- "./state/relay": {- "types": "./src/state/relayDiscovery.ts",- "default": "./src/state/relayDiscovery.ts"- },"./state/review": {"types": "./src/state/review.ts","default": "./src/state/review.ts"diff --git a/packages/client-runtime/src/authorization/index.ts b/packages/client-runtime/src/authorization/index.tsindex 6236b5922..79db7a561 100644--- a/packages/client-runtime/src/authorization/index.ts+++ b/packages/client-runtime/src/authorization/index.ts@@ -1,7 +1,2 @@export * from "./remote.ts";-export {- type AuthorizedRemoteEnvironment,- type RelayEnvironmentAuthorization,- RemoteEnvironmentAuthorization,-} from "./service.ts";-export * as TokenStore from "./tokenStore.ts";+export { type AuthorizedRemoteEnvironment, RemoteEnvironmentAuthorization } from "./service.ts";diff --git a/packages/client-runtime/src/authorization/layer.test.ts b/packages/client-runtime/src/authorization/layer.test.tsindex 466a5c2dd..a1028fd5b 100644--- a/packages/client-runtime/src/authorization/layer.test.ts+++ b/packages/client-runtime/src/authorization/layer.test.ts@@ -2,41 +2,26 @@ import { AuthStandardClientScopes, EnvironmentId } from "@t3tools/contracts";import { describe, expect, it } from "@effect/vitest";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";-import * as Option from "effect/Option";-import * as Ref from "effect/Ref";import * as TestClock from "effect/testing/TestClock";-import * as ManagedRelay from "../relay/managedRelay.ts";-import { remoteHttpClientLayer } from "../rpc/http.ts";import * as ClientCapabilities from "../platform/capabilities.ts";+import { remoteHttpClientLayer } from "../rpc/http.ts";import * as RemoteEnvironmentAuthorization from "./service.ts";-import * as TokenStore from "./tokenStore.ts";const ENVIRONMENT_ID = EnvironmentId.make("environment-1");const ENDPOINT = {httpBaseUrl: "https://environment.example.test",wsBaseUrl: "wss://environment.example.test",- providerKind: "cloudflare_tunnel" as const,};const DESCRIPTOR = {environmentId: ENVIRONMENT_ID,label: "Remote environment",- platform: {- os: "linux",- arch: "x64",- },+ platform: { os: "linux", arch: "x64" },serverVersion: "0.0.0-test",- capabilities: {- repositoryIdentity: true,- },-};-const BOOTSTRAP: RemoteEnvironmentAuthorization.RelayEnvironmentAuthorization = {- environmentId: ENVIRONMENT_ID,- endpoint: ENDPOINT,- credential: "relay-bootstrap",+ capabilities: { repositoryIdentity: true },};-function recordedFetch(responses: ReadonlyArray<Response>) {+function makeHarness(responses: ReadonlyArray<Response>) {const calls: Array<readonly [RequestInfo | URL, RequestInit]> = [];let responseIndex = 0;const fetchFn = ((input, init) => {@@ -46,125 +31,34 @@ function recordedFetch(responses: ReadonlyArray<Response>) {? Promise.reject(new Error(`Unexpected fetch call to ${String(input)}`)): Promise.resolve(response);}) satisfies typeof fetch;- return { calls, fetchFn };-}--const websocketTicket = (ticket: string) =>- Response.json({- ticket,- expiresAt: "2026-06-06T01:00:00.000Z",- });--const accessToken = (token: string) =>- Response.json({- access_token: token,- issued_token_type: "urn:ietf:params:oauth:token-type:access_token",- token_type: "DPoP",- expires_in: 3_600,- scope: AuthStandardClientScopes.join(" "),- });--const authInvalid = () =>- Response.json(- {- _tag: "EnvironmentAuthInvalidError",- code: "auth_invalid",- reason: "invalid_credential",- traceId: "trace-auth-invalid",- },- { status: 401 },- );--const makeHarness = Effect.fn("TestRemoteAuthorization.makeHarness")(function* (input: {- readonly initialToken?: TokenStore.RemoteDpopAccessToken;- readonly responses: ReadonlyArray<Response>;-}) {- const tokens = yield* Ref.make(- new Map(- input.initialToken === undefined- ? []- : [[input.initialToken.environmentId, input.initialToken]],- ),- );- const bootstrapCalls = yield* Ref.make(0);- const proofInputs = yield* Ref.make<- ReadonlyArray<{- readonly method: string;- readonly url: string;- readonly accessToken?: string;- }>- >([]);- const fetch = recordedFetch(input.responses);-- const tokenStore = TokenStore.RemoteDpopAccessTokenStore.of({- get: (environmentId) =>- Ref.get(tokens).pipe(- Effect.map((current) => Option.fromUndefinedOr(current.get(environmentId))),- ),- put: (token) =>- Ref.update(tokens, (current) => {- const next = new Map(current);- next.set(token.environmentId, token);- return next;- }),- remove: (environmentId) =>- Ref.update(tokens, (current) => {- const next = new Map(current);- next.delete(environmentId);- return next;- }),- });- const signer = ManagedRelay.ManagedRelayDpopSigner.of({- thumbprint: Effect.succeed("thumbprint-1"),- createProof: (proofInput) =>- Ref.update(proofInputs, (current) => [...current, proofInput]).pipe(- Effect.as(`proof:${proofInput.url}`),- ),- });const layer = RemoteEnvironmentAuthorization.layer.pipe(Layer.provide(Layer.mergeAll(- remoteHttpClientLayer(fetch.fetchFn),- Layer.succeed(ManagedRelay.ManagedRelayDpopSigner, signer),- Layer.succeed(TokenStore.RemoteDpopAccessTokenStore, tokenStore),+ remoteHttpClientLayer(fetchFn),Layer.succeed(ClientCapabilities.ClientPresentation,ClientCapabilities.ClientPresentation.of({- metadata: {- label: "T3 Code Test",- deviceType: "mobile",- os: "test",- },+ metadata: { label: "Akeru Bot Test", deviceType: "desktop", os: "test" },scopes: AuthStandardClientScopes,}),),),),);- const obtainBootstrap = Ref.update(bootstrapCalls, (count) => count + 1).pipe(- Effect.as(BOOTSTRAP),- );+ return { calls, layer };+}- return {- layer,- tokens,- bootstrapCalls,- proofInputs,- fetch,- obtainBootstrap,- };-});+const websocketTicket = (ticket: string) =>+ Response.json({ ticket, expiresAt: "2026-06-06T01:00:00.000Z" });describe("RemoteEnvironmentAuthorization", () => {it.effect("reuses a validated bearer descriptor while issuing fresh websocket tickets", () =>Effect.gen(function* () {- const harness = yield* makeHarness({- responses: [- Response.json(DESCRIPTOR),- websocketTicket("first-ticket"),- websocketTicket("second-ticket"),- ],- });+ const harness = makeHarness([+ Response.json(DESCRIPTOR),+ websocketTicket("first-ticket"),+ websocketTicket("second-ticket"),+ ]);const [first, second] = yield* Effect.gen(function* () {const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;@@ -181,10 +75,10 @@ describe("RemoteEnvironmentAuthorization", () => {expect(first.socketUrl).toContain("wsTicket=first-ticket");expect(second.socketUrl).toContain("wsTicket=second-ticket");expect(- harness.fetch.calls.filter(([url]) => String(url).endsWith("/.well-known/t3/environment")),+ harness.calls.filter(([url]) => String(url).endsWith("/.well-known/t3/environment")),).toHaveLength(1);expect(- harness.fetch.calls.filter(([url]) => String(url).endsWith("/api/auth/websocket-ticket")),+ harness.calls.filter(([url]) => String(url).endsWith("/api/auth/websocket-ticket")),).toHaveLength(2);}),);@@ -192,16 +86,11 @@ describe("RemoteEnvironmentAuthorization", () => {it.effect("revalidates a bearer descriptor after the cache expires", () =>Effect.gen(function* () {const reassignedEnvironmentId = EnvironmentId.make("environment-2");- const harness = yield* makeHarness({- responses: [- Response.json(DESCRIPTOR),- websocketTicket("first-ticket"),- Response.json({- ...DESCRIPTOR,- environmentId: reassignedEnvironmentId,- }),- ],- });+ const harness = makeHarness([+ Response.json(DESCRIPTOR),+ websocketTicket("first-ticket"),+ Response.json({ ...DESCRIPTOR, environmentId: reassignedEnvironmentId }),+ ]);const failure = yield* Effect.gen(function* () {const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;@@ -212,7 +101,6 @@ describe("RemoteEnvironmentAuthorization", () => {wsBaseUrl: ENDPOINT.wsBaseUrl,bearerToken: "bearer-token",});-yield* authorize();yield* TestClock.adjust("10 seconds");return yield* authorize().pipe(Effect.flip);@@ -225,182 +113,6 @@ describe("RemoteEnvironmentAuthorization", () => {detail: `Connected environment ${reassignedEnvironmentId} does not match ${ENVIRONMENT_ID}.`,}),);- expect(- harness.fetch.calls.filter(([url]) => String(url).endsWith("/.well-known/t3/environment")),- ).toHaveLength(2);- }),- );-- it.effect("reuses a valid persisted environment token without contacting the relay", () =>- Effect.gen(function* () {- const cached = new TokenStore.RemoteDpopAccessToken({- environmentId: ENVIRONMENT_ID,- label: DESCRIPTOR.label,- endpoint: ENDPOINT,- accessToken: "cached-access-token",- expiresAtEpochMs: Number.MAX_SAFE_INTEGER,- dpopThumbprint: "thumbprint-1",- });- const harness = yield* makeHarness({- initialToken: cached,- responses: [websocketTicket("cached-ticket")],- });-- const authorized = yield* Effect.gen(function* () {- const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;- return yield* remote.authorizeDpop({- expectedEnvironmentId: ENVIRONMENT_ID,- obtainBootstrap: harness.obtainBootstrap,- });- }).pipe(Effect.provide(harness.layer));-- expect(authorized.socketUrl).toContain("wsTicket=cached-ticket");- expect(yield* Ref.get(harness.bootstrapCalls)).toBe(0);- expect(harness.fetch.calls).toHaveLength(1);- expect(String(harness.fetch.calls[0]?.[0])).toBe(- "https://environment.example.test/api/auth/websocket-ticket",- );- }),- );-- it.effect("refreshes and persists an expired environment token", () =>- Effect.gen(function* () {- const expired = new TokenStore.RemoteDpopAccessToken({- environmentId: ENVIRONMENT_ID,- label: DESCRIPTOR.label,- endpoint: ENDPOINT,- accessToken: "expired-access-token",- expiresAtEpochMs: 0,- dpopThumbprint: "thumbprint-1",- });- const harness = yield* makeHarness({- initialToken: expired,- responses: [- Response.json(DESCRIPTOR),- accessToken("fresh-access-token"),- websocketTicket("fresh-ticket"),- ],- });-- const authorized = yield* Effect.gen(function* () {- const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;- return yield* remote.authorizeDpop({- expectedEnvironmentId: ENVIRONMENT_ID,- obtainBootstrap: harness.obtainBootstrap,- });- }).pipe(Effect.provide(harness.layer));-- expect(authorized.socketUrl).toContain("wsTicket=fresh-ticket");- expect(yield* Ref.get(harness.bootstrapCalls)).toBe(1);- expect((yield* Ref.get(harness.tokens)).get(ENVIRONMENT_ID)).toEqual(- expect.objectContaining({- accessToken: "fresh-access-token",- dpopThumbprint: "thumbprint-1",- }),- );- expect(harness.fetch.calls).toHaveLength(3);- }),- );-- it.effect("evicts an auth-invalid cached token and obtains a fresh bootstrap", () =>- Effect.gen(function* () {- const cached = new TokenStore.RemoteDpopAccessToken({- environmentId: ENVIRONMENT_ID,- label: DESCRIPTOR.label,- endpoint: ENDPOINT,- accessToken: "invalid-access-token",- expiresAtEpochMs: Number.MAX_SAFE_INTEGER,- dpopThumbprint: "thumbprint-1",- });- const harness = yield* makeHarness({- initialToken: cached,- responses: [- authInvalid(),- Response.json(DESCRIPTOR),- accessToken("replacement-access-token"),- websocketTicket("replacement-ticket"),- ],- });-- const authorized = yield* Effect.gen(function* () {- const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;- return yield* remote.authorizeDpop({- expectedEnvironmentId: ENVIRONMENT_ID,- obtainBootstrap: harness.obtainBootstrap,- });- }).pipe(Effect.provide(harness.layer));-- expect(authorized.socketUrl).toContain("wsTicket=replacement-ticket");- expect(yield* Ref.get(harness.bootstrapCalls)).toBe(1);- expect((yield* Ref.get(harness.tokens)).get(ENVIRONMENT_ID)).toEqual(- expect.objectContaining({- accessToken: "replacement-access-token",- }),- );- expect(harness.fetch.calls).toHaveLength(4);- }),- );-- it.effect("refreshes a cached endpoint after its first transient failure", () =>- Effect.gen(function* () {- const cached = new TokenStore.RemoteDpopAccessToken({- environmentId: ENVIRONMENT_ID,- label: DESCRIPTOR.label,- endpoint: ENDPOINT,- accessToken: "cached-access-token",- expiresAtEpochMs: Number.MAX_SAFE_INTEGER,- dpopThumbprint: "thumbprint-1",- });- const harness = yield* makeHarness({- initialToken: cached,- responses: [- new Response("endpoint unavailable", { status: 503 }),- Response.json(DESCRIPTOR),- accessToken("replacement-access-token"),- websocketTicket("replacement-ticket"),- ],- });-- const authorized = yield* Effect.gen(function* () {- const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;- return yield* remote.authorizeDpop({- expectedEnvironmentId: ENVIRONMENT_ID,- obtainBootstrap: harness.obtainBootstrap,- });- }).pipe(Effect.provide(harness.layer));-- expect(authorized.socketUrl).toContain("wsTicket=replacement-ticket");- expect(yield* Ref.get(harness.bootstrapCalls)).toBe(1);- expect((yield* Ref.get(harness.tokens)).get(ENVIRONMENT_ID)).toEqual(- expect.objectContaining({- accessToken: "replacement-access-token",- }),- );- expect(harness.fetch.calls).toHaveLength(4);- }),- );-- it.effect("does not persist a refreshed token until its websocket ticket succeeds", () =>- Effect.gen(function* () {- const harness = yield* makeHarness({- responses: [- Response.json(DESCRIPTOR),- accessToken("unusable-access-token"),- new Response("endpoint unavailable", { status: 503 }),- ],- });-- yield* Effect.gen(function* () {- const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;- return yield* remote.authorizeDpop({- expectedEnvironmentId: ENVIRONMENT_ID,- obtainBootstrap: harness.obtainBootstrap,- });- }).pipe(Effect.provide(harness.layer), Effect.flip);-- expect((yield* Ref.get(harness.tokens)).has(ENVIRONMENT_ID)).toBe(false);- expect(yield* Ref.get(harness.bootstrapCalls)).toBe(1);- expect(harness.fetch.calls).toHaveLength(3);}),);});diff --git a/packages/client-runtime/src/authorization/remote.test.ts b/packages/client-runtime/src/authorization/remote.test.tsindex 082d72b1f..6fbfd5d5c 100644--- a/packages/client-runtime/src/authorization/remote.test.ts+++ b/packages/client-runtime/src/authorization/remote.test.ts@@ -8,10 +8,7 @@ import * as TestClock from "effect/testing/TestClock";import { EnvironmentAuthInvalidError } from "@t3tools/contracts";import {bootstrapRemoteBearerSession,- exchangeRemoteDpopAccessToken,- fetchRemoteDpopSessionState,fetchRemoteSessionState,- issueRemoteDpopWebSocketTicket,issueRemoteWebSocketTicket,RemoteEnvironmentAuthInvalidJsonError,RemoteEnvironmentAuthTimeoutError,@@ -98,8 +95,7 @@ describe("remote environment authorization", () => {issued_token_type: "urn:ietf:params:oauth:token-type:access_token",token_type: "Bearer",expires_in: 3600,- scope:- "orchestration:read orchestration:operate terminal:operate review:write relay:read",+ scope: "orchestration:read orchestration:operate terminal:operate review:write",},{ status: 200 },),@@ -113,7 +109,7 @@ describe("remote environment authorization", () => {expect(result).toMatchObject({token_type: "Bearer",access_token: "bearer-token",- scope: "orchestration:read orchestration:operate terminal:operate review:write relay:read",+ scope: "orchestration:read orchestration:operate terminal:operate review:write",});expectFetchCall(fetch.calls, 1, {url: "https://remote.example.com/oauth/token",@@ -126,55 +122,6 @@ describe("remote environment authorization", () => {}),);- it.effect("exchanges managed credentials and admits websocket requests with DPoP", () =>- Effect.gen(function* () {- const fetch = recordedFetch(- Response.json({- access_token: "dpop-access-token",- issued_token_type: "urn:ietf:params:oauth:token-type:access_token",- token_type: "DPoP",- expires_in: 3600,- scope: "orchestration:read orchestration:operate terminal:operate review:write",- }),- Response.json({- ticket: "ws-ticket",- expiresAt: "2026-05-01T12:05:00.000Z",- }),- );-- const token = yield* exchangeRemoteDpopAccessToken({- httpBaseUrl: "https://remote.example.com/",- credential: "one-time-credential",- dpopProof: "token-proof",- clientMetadata: {- label: "T3 Code Mobile",- deviceType: "mobile",- os: "iOS",- },- }).pipe(provideRemoteHttp(fetch.fetchFn));- yield* issueRemoteDpopWebSocketTicket({- httpBaseUrl: "https://remote.example.com/",- accessToken: token.access_token,- dpopProof: "resource-proof",- }).pipe(provideRemoteHttp(fetch.fetchFn));-- expectFetchCall(fetch.calls, 1, {- url: "https://remote.example.com/oauth/token",- method: "POST",- headers: { dpop: "token-proof", "content-type": "application/x-www-form-urlencoded" },- body: "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Atoken-exchange&subject_token=one-time-credential&subject_token_type=urn%3At3%3Aparams%3Aoauth%3Atoken-type%3Aenvironment-bootstrap&requested_token_type=urn%3Aietf%3Aparams%3Aoauth%3Atoken-type%3Aaccess_token&client_label=T3+Code+Mobile&client_device_type=mobile&client_os=iOS",- });- expectFetchCall(fetch.calls, 2, {- url: "https://remote.example.com/api/auth/websocket-ticket",- method: "POST",- headers: {- authorization: "DPoP dpop-access-token",- dpop: "resource-proof",- },- });- }),- );-it.effect("submits optional client display metadata during bearer token exchange", () =>Effect.gen(function* () {const fetch = recordedFetch(@@ -184,8 +131,7 @@ describe("remote environment authorization", () => {issued_token_type: "urn:ietf:params:oauth:token-type:access_token",token_type: "Bearer",expires_in: 3600,- scope:- "orchestration:read orchestration:operate terminal:operate review:write relay:read",+ scope: "orchestration:read orchestration:operate terminal:operate review:write",},{ status: 200 },),@@ -270,7 +216,6 @@ describe("remote environment authorization", () => {"orchestration:operate","terminal:operate","review:write",- "relay:read",],sessionMethod: "bearer-access-token",expiresAt: "2026-05-01T12:00:00.000Z",@@ -300,13 +245,7 @@ describe("remote environment authorization", () => {}).pipe(provideRemoteHttp(fetch.fetchFn));expect(session).toMatchObject({authenticated: true,- scopes: [- "orchestration:read",- "orchestration:operate",- "terminal:operate",- "review:write",- "relay:read",- ],+ scopes: ["orchestration:read", "orchestration:operate", "terminal:operate", "review:write"],});const ticket = yield* issueRemoteWebSocketTicket({@@ -338,45 +277,6 @@ describe("remote environment authorization", () => {}),);- it.effect("loads remote session state with a DPoP-bound access token", () =>- Effect.gen(function* () {- const fetch = recordedFetch(- Response.json({- authenticated: true,- auth: {- policy: "remote-reachable",- bootstrapMethods: ["one-time-token"],- sessionMethods: ["dpop-access-token"],- sessionCookieName: "t3_session",- },- sessionMethod: "dpop-access-token",- scopes: [- "orchestration:read",- "orchestration:operate",- "terminal:operate",- "review:write",- ],- expiresAt: "2026-05-01T12:00:00.000Z",- }),- );-- yield* fetchRemoteDpopSessionState({- httpBaseUrl: "https://remote.example.com/",- accessToken: "dpop-access-token",- dpopProof: "dpop-proof",- }).pipe(provideRemoteHttp(fetch.fetchFn));-- expectFetchCall(fetch.calls, 1, {- url: "https://remote.example.com/api/auth/session",- method: "GET",- headers: {- authorization: "DPoP dpop-access-token",- dpop: "dpop-proof",- },- });- }),- );-it.effect("fails hung fetch requests on the configured timeout", () =>Effect.gen(function* () {const fetch = hangingFetch();@@ -432,8 +332,7 @@ describe("remote environment authorization", () => {issued_token_type: "urn:ietf:params:oauth:token-type:access_token",token_type: "Bearer",expires_in: 3600,- scope:- "orchestration:read orchestration:operate terminal:operate review:write relay:read",+ scope: "orchestration:read orchestration:operate terminal:operate review:write",},{ status: 200 },),diff --git a/packages/client-runtime/src/authorization/remote.ts b/packages/client-runtime/src/authorization/remote.tsindex 41a67ce8a..e9463d995 100644--- a/packages/client-runtime/src/authorization/remote.ts+++ b/packages/client-runtime/src/authorization/remote.ts@@ -57,35 +57,6 @@ export const appendClientConnectionParams = (}};-export const exchangeRemoteDpopAccessToken = Effect.fn(- "clientRuntime.authorization.exchangeRemoteDpopAccessToken",-)(function* (input: {- readonly httpBaseUrl: string;- readonly credential: string;- readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;- readonly clientMetadata?: AuthClientPresentationMetadata;- readonly dpopProof: string;- readonly timeoutMs?: number;-}) {- const client = yield* makeEnvironmentHttpApiClient(input.httpBaseUrl);- const response = yield* executeEnvironmentHttpRequest(- environmentEndpointUrl(input.httpBaseUrl, "/oauth/token"),- input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS,- client.auth.token({- headers: { dpop: input.dpopProof },- payload: {- grant_type: AuthTokenExchangeGrantType,- subject_token: input.credential,- subject_token_type: AuthEnvironmentBootstrapTokenType,- requested_token_type: AuthAccessTokenType,- ...(input.scopes ? { scope: encodeOAuthScope(input.scopes) } : {}),- ...clientMetadataTokenExchangeFields(input.clientMetadata),- },- }),- );- return response;-});-export const bootstrapRemoteBearerSession = Effect.fn("clientRuntime.authorization.bootstrapRemoteBearerSession",)(function* (input: {@@ -132,27 +103,6 @@ export const fetchRemoteSessionState = Effect.fn();});-export const fetchRemoteDpopSessionState = Effect.fn(- "clientRuntime.authorization.fetchRemoteDpopSessionState",-)(function* (input: {- readonly httpBaseUrl: string;- readonly accessToken: string;- readonly dpopProof: string;- readonly timeoutMs?: number;-}) {- const client = yield* makeEnvironmentHttpApiClient(input.httpBaseUrl);- return yield* executeEnvironmentHttpRequest(- environmentEndpointUrl(input.httpBaseUrl, "/api/auth/session"),- input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS,- client.auth.session({- headers: {- authorization: `DPoP ${input.accessToken}`,- dpop: input.dpopProof,- },- }),- );-});-export const issueRemoteWebSocketTicket = Effect.fn("clientRuntime.authorization.issueRemoteWebSocketTicket",)(function* (input: {@@ -172,27 +122,6 @@ export const issueRemoteWebSocketTicket = Effect.fn();});-export const issueRemoteDpopWebSocketTicket = Effect.fn(- "clientRuntime.authorization.issueRemoteDpopWebSocketTicket",-)(function* (input: {- readonly httpBaseUrl: string;- readonly accessToken: string;- readonly dpopProof: string;- readonly timeoutMs?: number;-}) {- const client = yield* makeEnvironmentHttpApiClient(input.httpBaseUrl);- return yield* executeEnvironmentHttpRequest(- environmentEndpointUrl(input.httpBaseUrl, "/api/auth/websocket-ticket"),- input.timeoutMs ?? DEFAULT_REMOTE_REQUEST_TIMEOUT_MS,- client.auth.webSocketTicket({- headers: {- authorization: `DPoP ${input.accessToken}`,- dpop: input.dpopProof,- },- }),- );-});-export const resolveRemoteWebSocketConnectionUrl = Effect.fn("clientRuntime.authorization.resolveRemoteWebSocketConnectionUrl",)(function* (input: {@@ -216,28 +145,3 @@ export const resolveRemoteWebSocketConnectionUrl = Effect.fn(appendClientConnectionParams(url, input.clientMetadata);return url.toString();});--export const resolveRemoteDpopWebSocketConnectionUrl = Effect.fn(- "clientRuntime.authorization.resolveRemoteDpopWebSocketConnectionUrl",-)(function* (input: {- readonly wsBaseUrl: string;- readonly httpBaseUrl: string;- readonly accessToken: string;- readonly dpopProof: string;- readonly clientMetadata?: AuthClientPresentationMetadata;- readonly timeoutMs?: number;-}) {- const issued = yield* issueRemoteDpopWebSocketTicket({- httpBaseUrl: input.httpBaseUrl,- accessToken: input.accessToken,- dpopProof: input.dpopProof,- ...(input.timeoutMs ? { timeoutMs: input.timeoutMs } : {}),- });- const url = new URL(input.wsBaseUrl);- if (url.pathname === "" || url.pathname === "/") {- url.pathname = "/ws";- }- url.searchParams.set("wsTicket", issued.ticket);- appendClientConnectionParams(url, input.clientMetadata);- return url.toString();-});diff --git a/packages/client-runtime/src/authorization/service.ts b/packages/client-runtime/src/authorization/service.tsindex fef8db274..e08c0642b 100644--- a/packages/client-runtime/src/authorization/service.ts+++ b/packages/client-runtime/src/authorization/service.ts@@ -1,35 +1,18 @@import { EnvironmentId, type ExecutionEnvironmentDescriptor } from "@t3tools/contracts";-import type { RelayManagedEndpoint } from "@t3tools/contracts/relay";-import {- exchangeRemoteDpopAccessToken,- type RemoteEnvironmentAuthError,- resolveRemoteDpopWebSocketConnectionUrl,- resolveRemoteWebSocketConnectionUrl,-} from "./remote.ts";+import { resolveRemoteWebSocketConnectionUrl } from "./remote.ts";import { environmentMismatchError, mapRemoteEnvironmentError } from "../connection/errors.ts";-import { ConnectionBlockedError, type ConnectionAttemptError } from "../connection/model.ts";+import type { ConnectionAttemptError } from "../connection/model.ts";import { fetchRemoteEnvironmentDescriptor } from "../environment/descriptor.ts";-import { environmentEndpointUrl } from "../environment/endpoint.ts";import * as ClientCapabilities from "../platform/capabilities.ts";-import * as ManagedRelay from "../relay/managedRelay.ts";-import * as TokenStore from "./tokenStore.ts";import * as Clock from "effect/Clock";import * as Context from "effect/Context";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";-import * as Option from "effect/Option";import * as Ref from "effect/Ref";-import * as Result from "effect/Result";import * as HttpClient from "effect/unstable/http/HttpClient";import type { PreparedHttpAuthorization } from "../connection/model.ts";-export interface RelayEnvironmentAuthorization {- readonly environmentId: EnvironmentId;- readonly endpoint: RelayManagedEndpoint;- readonly credential: string;-}-export interface AuthorizedRemoteEnvironment {readonly environmentId: EnvironmentId;readonly label: string;@@ -47,26 +30,11 @@ export class RemoteEnvironmentAuthorization extends Context.Service<readonly wsBaseUrl: string;readonly bearerToken: string;}) => Effect.Effect<AuthorizedRemoteEnvironment, ConnectionAttemptError>;- readonly authorizeDpop: (input: {- readonly expectedEnvironmentId: EnvironmentId;- readonly obtainBootstrap: Effect.Effect<- RelayEnvironmentAuthorization,- ConnectionAttemptError- >;- }) => Effect.Effect<AuthorizedRemoteEnvironment, ConnectionAttemptError>;}>()("@t3tools/client-runtime/authorization/service/RemoteEnvironmentAuthorization") {}-const TOKEN_EXPIRY_SAFETY_MARGIN_MS = 60_000;-const CACHED_ENDPOINT_SOCKET_TIMEOUT_MS = 3_000;const BEARER_DESCRIPTOR_CACHE_TTL_MS = 10_000;-function mapDpopSocketError(error: RemoteEnvironmentAuthError | ConnectionAttemptError) {- return error._tag === "ConnectionTransientError" || error._tag === "ConnectionBlockedError"- ? error- : mapRemoteEnvironmentError(error);-}-const fetchDescriptor = Effect.fn("clientRuntime.connection.remote.fetchDescriptor")(function* (httpBaseUrl: string,) {@@ -76,9 +44,7 @@ const fetchDescriptor = Effect.fn("clientRuntime.connection.remote.fetchDescript});export const make = Effect.gen(function* () {- const signer = yield* ManagedRelay.ManagedRelayDpopSigner;const presentation = yield* ClientCapabilities.ClientPresentation;- const tokenStore = yield* TokenStore.RemoteDpopAccessTokenStore;const httpClient = yield* HttpClient.HttpClient;const bearerDescriptors = yield* Ref.make<ReadonlyMap<@@ -149,159 +115,8 @@ export const make = Effect.gen(function* () {},);- const createDpopSocketUrl = Effect.fn("clientRuntime.connection.remote.createDpopSocketUrl")(- function* (token: TokenStore.RemoteDpopAccessToken, timeoutMs?: number) {- const ticketProof = yield* signer- .createProof({- method: "POST",- url: environmentEndpointUrl(token.endpoint.httpBaseUrl, "/api/auth/websocket-ticket"),- accessToken: token.accessToken,- })- .pipe(- Effect.mapError(- () =>- new ConnectionBlockedError({- reason: "configuration",- detail: "Could not create the websocket authorization proof.",- }),- ),- );- return yield* resolveRemoteDpopWebSocketConnectionUrl({- wsBaseUrl: token.endpoint.wsBaseUrl,- httpBaseUrl: token.endpoint.httpBaseUrl,- accessToken: token.accessToken,- dpopProof: ticketProof,- clientMetadata: presentation.metadata,- ...(timeoutMs === undefined ? {} : { timeoutMs }),- }).pipe(Effect.provideService(HttpClient.HttpClient, httpClient));- },- );-- const authorizeDpop = Effect.fn("clientRuntime.connection.remote.authorizeDpop")(- function* (input: {- readonly expectedEnvironmentId: Parameters<- RemoteEnvironmentAuthorization["Service"]["authorizeDpop"]- >[0]["expectedEnvironmentId"];- readonly obtainBootstrap: Parameters<- RemoteEnvironmentAuthorization["Service"]["authorizeDpop"]- >[0]["obtainBootstrap"];- }) {- const thumbprint = yield* signer.thumbprint.pipe(- Effect.mapError(- () =>- new ConnectionBlockedError({- reason: "configuration",- detail: "Could not load the environment authorization key.",- }),- ),- Effect.withSpan("environment.authorization.dpopKey.resolve"),- );- const now = yield* Clock.currentTimeMillis;- const cached = yield* tokenStore- .get(input.expectedEnvironmentId)- .pipe(Effect.withSpan("environment.authorization.accessToken.cache"));- if (- Option.isSome(cached) &&- cached.value.environmentId === input.expectedEnvironmentId &&- cached.value.dpopThumbprint === thumbprint &&- cached.value.expiresAtEpochMs > now + TOKEN_EXPIRY_SAFETY_MARGIN_MS- ) {- yield* Effect.annotateCurrentSpan({- "connection.remote_token_cache": "hit",- });- const cachedSocket = yield* createDpopSocketUrl(- cached.value,- CACHED_ENDPOINT_SOCKET_TIMEOUT_MS,- ).pipe(Effect.result);- if (Result.isSuccess(cachedSocket)) {- return {- environmentId: cached.value.environmentId,- label: cached.value.label,- httpBaseUrl: cached.value.endpoint.httpBaseUrl,- socketUrl: cachedSocket.success,- httpAuthorization: {- _tag: "Dpop" as const,- accessToken: cached.value.accessToken,- },- };- }- if (cachedSocket.failure._tag === "ConnectionBlockedError") {- return yield* mapDpopSocketError(cachedSocket.failure);- }- yield* tokenStore- .remove(input.expectedEnvironmentId)- .pipe(Effect.withSpan("environment.authorization.accessToken.remove"));- }-- yield* Effect.annotateCurrentSpan({- "connection.remote_token_cache": "miss",- });- const bootstrap = yield* input.obtainBootstrap;- const descriptor = yield* fetchDescriptor(bootstrap.endpoint.httpBaseUrl).pipe(- Effect.provideService(HttpClient.HttpClient, httpClient),- Effect.withSpan("environment.authorization.descriptor"),- );- if (descriptor.environmentId !== input.expectedEnvironmentId) {- return yield* environmentMismatchError({- expected: input.expectedEnvironmentId,- actual: descriptor.environmentId,- });- }- const bootstrapProof = yield* signer- .createProof({- method: "POST",- url: environmentEndpointUrl(bootstrap.endpoint.httpBaseUrl, "/oauth/token"),- })- .pipe(- Effect.mapError(- () =>- new ConnectionBlockedError({- reason: "configuration",- detail: "Could not create the environment authorization proof.",- }),- ),- );- const access = yield* exchangeRemoteDpopAccessToken({- httpBaseUrl: bootstrap.endpoint.httpBaseUrl,- credential: bootstrap.credential,- dpopProof: bootstrapProof,- scopes: presentation.scopes,- clientMetadata: presentation.metadata,- }).pipe(- Effect.mapError(mapRemoteEnvironmentError),- Effect.provideService(HttpClient.HttpClient, httpClient),- Effect.withSpan("environment.authorization.accessToken.exchange"),- );- const issuedAt = yield* Clock.currentTimeMillis;- const token = new TokenStore.RemoteDpopAccessToken({- environmentId: descriptor.environmentId,- label: descriptor.label,- endpoint: bootstrap.endpoint,- accessToken: access.access_token,- expiresAtEpochMs: issuedAt + access.expires_in * 1_000,- dpopThumbprint: thumbprint,- });- const socketUrl = yield* createDpopSocketUrl(token).pipe(Effect.mapError(mapDpopSocketError));- yield* tokenStore- .put(token)- .pipe(Effect.withSpan("environment.authorization.accessToken.persist"));- return {- environmentId: descriptor.environmentId,- label: descriptor.label,- httpBaseUrl: bootstrap.endpoint.httpBaseUrl,- socketUrl,- httpAuthorization: {- _tag: "Dpop" as const,- accessToken: token.accessToken,- },- };- },- );-return RemoteEnvironmentAuthorization.of({authorizeBearer,- authorizeDpop: (input) =>- authorizeDpop(input).pipe(Effect.withSpan("environment.authorization")),});});diff --git a/packages/client-runtime/src/authorization/tokenStore.ts b/packages/client-runtime/src/authorization/tokenStore.tsdeleted file mode 100644index c490a22da..000000000--- a/packages/client-runtime/src/authorization/tokenStore.ts+++ /dev/null@@ -1,37 +0,0 @@-import { EnvironmentId } from "@t3tools/contracts";-import { RelayManagedEndpoint } from "@t3tools/contracts/relay";-import * as Context from "effect/Context";-import type * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";-import type * as Option from "effect/Option";-import * as Schema from "effect/Schema";--import type { ConnectionAttemptError } from "../connection/model.ts";--export class RemoteDpopAccessToken extends Schema.Class<RemoteDpopAccessToken>(- "@t3tools/client-runtime/authorization/RemoteDpopAccessToken",-)({- environmentId: EnvironmentId,- label: Schema.String,- endpoint: RelayManagedEndpoint,- accessToken: Schema.String,- expiresAtEpochMs: Schema.Number,- dpopThumbprint: Schema.String,-}) {}--export class RemoteDpopAccessTokenStore extends Context.Service<- RemoteDpopAccessTokenStore,- {- readonly get: (- environmentId: EnvironmentId,- ) => Effect.Effect<Option.Option<RemoteDpopAccessToken>, ConnectionAttemptError>;- readonly put: (token: RemoteDpopAccessToken) => Effect.Effect<void, ConnectionAttemptError>;- readonly remove: (environmentId: EnvironmentId) => Effect.Effect<void, ConnectionAttemptError>;- }->()("@t3tools/client-runtime/authorization/tokenStore/RemoteDpopAccessTokenStore") {}--export const make = (service: RemoteDpopAccessTokenStore["Service"]) =>- RemoteDpopAccessTokenStore.of(service);--export const layer = (service: RemoteDpopAccessTokenStore["Service"]) =>- Layer.succeed(RemoteDpopAccessTokenStore, make(service));diff --git a/packages/client-runtime/src/connection/catalog.ts b/packages/client-runtime/src/connection/catalog.tsindex 8df3b2541..52f3c68cd 100644--- a/packages/client-runtime/src/connection/catalog.ts+++ b/packages/client-runtime/src/connection/catalog.ts@@ -5,7 +5,6 @@ import * as Schema from "effect/Schema";import {BearerConnectionTarget,PrimaryConnectionTarget,- RelayConnectionTarget,SshConnectionTarget,type ConnectionTarget,} from "./model.ts";@@ -58,13 +57,6 @@ export class PrimaryConnectionRegistration extends Schema.TaggedClass<PrimaryCon},) {}-export class RelayConnectionRegistration extends Schema.TaggedClass<RelayConnectionRegistration>()(- "RelayConnectionRegistration",- {- target: RelayConnectionTarget,- },-) {}-export class BearerConnectionRegistration extends Schema.TaggedClass<BearerConnectionRegistration>()("BearerConnectionRegistration",{@@ -83,7 +75,6 @@ export class SshConnectionRegistration extends Schema.TaggedClass<SshConnectionR) {}export const ConnectionRegistration = Schema.Union([- RelayConnectionRegistration,BearerConnectionRegistration,SshConnectionRegistration,]);@@ -115,7 +106,6 @@ export function connectionRegistrationCatalogEntry(): ConnectionCatalogEntry {switch (registration._tag) {case "PrimaryConnectionRegistration":- case "RelayConnectionRegistration":return {target: registration.target,profile: Option.none(),diff --git a/packages/client-runtime/src/connection/errors.ts b/packages/client-runtime/src/connection/errors.tsindex 66c10333d..b61252ee7 100644--- a/packages/client-runtime/src/connection/errors.ts+++ b/packages/client-runtime/src/connection/errors.ts@@ -1,6 +1,4 @@import type { EnvironmentId } from "@t3tools/contracts";-import type { RelayProtectedError } from "@t3tools/contracts/relay";-import type { ManagedRelayClientError } from "../relay/managedRelay.ts";import type { RemoteEnvironmentAuthError } from "../authorization/remote.ts";import {ConnectionBlockedError,@@ -32,84 +30,6 @@ export function environmentMismatchError(input: {});}-function relayProtectedError(error: RelayProtectedError): ConnectionAttemptError {- switch (error._tag) {- case "RelayAuthInvalidError":- case "RelayEnvironmentLinkProofExpiredError":- case "RelayAgentActivityPublishProofExpiredError":- case "RelayAgentActivityPublishProofInvalidError":- return new ConnectionBlockedError({- reason: "authentication",- detail: error.message,- traceId: error.traceId,- });- case "RelayEnvironmentConnectNotAuthorizedError":- case "RelayEnvironmentLinkProofInvalidError":- case "RelayEnvironmentLinkLimitExceededError":- return new ConnectionBlockedError({- reason: "permission",- detail: error.message,- traceId: error.traceId,- });- case "RelayEnvironmentEndpointTimedOutError":- return new ConnectionTransientError({- reason: "timeout",- detail: error.message,- traceId: error.traceId,- });- case "RelayEnvironmentEndpointUnavailableError":- case "RelayEnvironmentLinkUnavailableError":- return new ConnectionTransientError({- reason: "endpoint-unavailable",- detail: error.message,- traceId: error.traceId,- });- case "RelayEnvironmentLinkFailedError":- case "RelayInternalError":- return new ConnectionTransientError({- reason: "relay-unavailable",- detail: error.message,- traceId: error.traceId,- });- }-}--export function mapManagedRelayError(error: ManagedRelayClientError): ConnectionAttemptError {- switch (error._tag) {- case "ManagedRelayRequestFailedError":- if (error.relayError) {- return relayProtectedError(error.relayError);- }- return new ConnectionTransientError({- reason: "relay-unavailable",- detail: error.message,- ...(error.traceId ? { traceId: error.traceId } : {}),- });- case "ManagedRelayRequestTimeoutError":- return new ConnectionTransientError({- reason: "timeout",- detail: error.message,- });- case "ManagedRelayUrlInvalidError":- return new ConnectionBlockedError({- reason: "configuration",- detail: error.message,- });- case "ManagedRelayAccessTokenScopesUnexpectedError":- return new ConnectionBlockedError({- reason: "permission",- detail: error.message,- });- case "ManagedRelayDpopKeyLoadError":- case "ManagedRelayTokenProofCreationError":- case "ManagedRelayRequestProofCreationError":- return new ConnectionBlockedError({- reason: "authentication",- detail: error.message,- });- }-}-export function mapRemoteEnvironmentError(error: RemoteEnvironmentAuthError,): ConnectionAttemptError {diff --git a/packages/client-runtime/src/connection/layer.ts b/packages/client-runtime/src/connection/layer.tsindex 798ec01e2..db48da3c9 100644--- a/packages/client-runtime/src/connection/layer.ts+++ b/packages/client-runtime/src/connection/layer.ts@@ -7,7 +7,6 @@ import * as ConnectionDriver from "./driver.ts";import * as EnvironmentRegistry from "./registry.ts";import * as ConnectionOnboarding from "./onboarding.ts";import * as PlatformConnectionSource from "../platform/source.ts";-import * as RelayEnvironmentDiscovery from "../relay/discovery.ts";import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";import * as RpcSession from "../rpc/session.ts";@@ -23,11 +22,7 @@ const registryLayer = EnvironmentRegistry.layer.pipe(Layer.provide(driverLayer))const onboardingLayer = ConnectionOnboarding.layer.pipe(Layer.provide(registryLayer));-const connectionServicesLayer = Layer.mergeAll(- registryLayer,- RelayEnvironmentDiscovery.layer,- onboardingLayer,-);+const connectionServicesLayer = Layer.mergeAll(registryLayer, onboardingLayer);const connectionStartupLayer = Layer.effectDiscard(Effect.gen(function* () {diff --git a/packages/client-runtime/src/connection/model.ts b/packages/client-runtime/src/connection/model.tsindex fbcb302ed..a7bd21a41 100644--- a/packages/client-runtime/src/connection/model.ts+++ b/packages/client-runtime/src/connection/model.ts@@ -23,13 +23,6 @@ export class BearerConnectionTarget extends Schema.TaggedClass<BearerConnectionT},) {}-export class RelayConnectionTarget extends Schema.TaggedClass<RelayConnectionTarget>()(- "RelayConnectionTarget",- {- ...ConnectionTargetBase,- },-) {}-export class SshConnectionTarget extends Schema.TaggedClass<SshConnectionTarget>()("SshConnectionTarget",{@@ -41,14 +34,12 @@ export class SshConnectionTarget extends Schema.TaggedClass<SshConnectionTarget>export const ConnectionTarget = Schema.Union([PrimaryConnectionTarget,BearerConnectionTarget,- RelayConnectionTarget,SshConnectionTarget,]);export type ConnectionTarget = typeof ConnectionTarget.Type;export const PersistedConnectionTarget = Schema.Union([BearerConnectionTarget,- RelayConnectionTarget,SshConnectionTarget,]);export type PersistedConnectionTarget = typeof PersistedConnectionTarget.Type;@@ -62,7 +53,6 @@ export const ConnectionTransientReason = Schema.Literals(["timeout","transport","endpoint-unavailable",- "relay-unavailable","remote-unavailable",]);export type ConnectionTransientReason = typeof ConnectionTransientReason.Type;@@ -103,15 +93,10 @@ export class ConnectionBlockedError extends Schema.TaggedErrorClass<ConnectionBlexport type ConnectionAttemptError = ConnectionTransientError | ConnectionBlockedError;-export type PreparedHttpAuthorization =- | {- readonly _tag: "Bearer";- readonly token: string;- }- | {- readonly _tag: "Dpop";- readonly accessToken: string;- };+export type PreparedHttpAuthorization = {+ readonly _tag: "Bearer";+ readonly token: string;+};export interface PreparedConnection {readonly environmentId: EnvironmentId;diff --git a/packages/client-runtime/src/connection/presentation.ts b/packages/client-runtime/src/connection/presentation.tsindex 168443dec..2d8c9cfef 100644--- a/packages/client-runtime/src/connection/presentation.ts+++ b/packages/client-runtime/src/connection/presentation.ts@@ -93,8 +93,6 @@ export function connectionCatalogDisplayUrl(entry: ConnectionCatalogEntry): striswitch (entry.target._tag) {case "PrimaryConnectionTarget":return entry.target.httpBaseUrl;- case "RelayConnectionTarget":- return null;case "BearerConnectionTarget":return Option.isSome(entry.profile) && entry.profile.value._tag === "BearerConnectionProfile"? entry.profile.value.httpBaseUrldiff --git a/packages/client-runtime/src/connection/registry.test.ts b/packages/client-runtime/src/connection/registry.test.tsindex eb4edfad5..e78766fa8 100644--- a/packages/client-runtime/src/connection/registry.test.ts+++ b/packages/client-runtime/src/connection/registry.test.ts@@ -15,14 +15,12 @@ import * as Stream from "effect/Stream";import * as SubscriptionRef from "effect/SubscriptionRef";import * as ClientCapabilities from "../platform/capabilities.ts";-import * as TokenStore from "../authorization/tokenStore.ts";import {BearerConnectionCredential,BearerConnectionProfile,BearerConnectionRegistration,type ConnectionRegistration,PrimaryConnectionRegistration,- RelayConnectionRegistration,SshConnectionProfile,type ConnectionCredential,type ConnectionProfile,@@ -34,7 +32,6 @@ import {ConnectionTransientError,BearerConnectionTarget,PrimaryConnectionTarget,- RelayConnectionTarget,SshConnectionTarget,type ConnectionTarget,type PreparedConnection,@@ -69,15 +66,6 @@ const PREPARED: PreparedConnection = {target: TARGET,};-const RELAY_TARGET = new RelayConnectionTarget({- environmentId: EnvironmentId.make("environment-relay"),- label: "Relay environment",-});-const SECOND_RELAY_TARGET = new RelayConnectionTarget({- environmentId: EnvironmentId.make("environment-relay-2"),- label: "Second relay environment",-});-const BEARER_TARGET = new BearerConnectionTarget({environmentId: EnvironmentId.make("environment-bearer"),label: "Bearer environment",@@ -94,6 +82,20 @@ const BEARER_CREDENTIAL = new BearerConnectionCredential({token: "bearer-token",});+function bearerRegistration(target: BearerConnectionTarget = BEARER_TARGET) {+ return new BearerConnectionRegistration({+ target,+ profile: new BearerConnectionProfile({+ connectionId: target.connectionId,+ environmentId: target.environmentId,+ label: target.label,+ httpBaseUrl: "https://bearer.example.test",+ wsBaseUrl: "wss://bearer.example.test",+ }),+ credential: BEARER_CREDENTIAL,+ });+}+const SSH_TARGET: DesktopSshEnvironmentTarget = {alias: "test",hostname: "test.example.test",@@ -153,25 +155,6 @@ const makeHarness = Effect.fn("TestEnvironmentRegistry.makeHarness")(function* ();const profileReadCount = yield* Ref.make(0);const storedCredentials = yield* Ref.make(new Map(initialCredentials));- const storedRemoteTokens = yield* Ref.make(- new Map([- [- SSH_CONNECTION.environmentId,- new TokenStore.RemoteDpopAccessToken({- environmentId: SSH_CONNECTION.environmentId,- label: SSH_CONNECTION.label,- endpoint: {- httpBaseUrl: "https://ssh.example.test",- wsBaseUrl: "wss://ssh.example.test",- providerKind: "cloudflare_tunnel",- },- accessToken: "cached-token",- expiresAtEpochMs: Number.MAX_SAFE_INTEGER,- dpopThumbprint: "thumbprint",- }),- ],- ]),- );const disconnectedSshTargets = yield* Ref.make<ReadonlyArray<DesktopSshEnvironmentTarget>>([]);const targetStore = Persistence.ConnectionTargetStore.of({@@ -187,8 +170,6 @@ const makeHarness = Effect.fn("TestEnvironmentRegistry.makeHarness")(function* (return next;});switch (registration._tag) {- case "RelayConnectionRegistration":- return;case "BearerConnectionRegistration":yield* Ref.update(storedProfiles, (current) => {const next = new Map(current);@@ -229,11 +210,6 @@ const makeHarness = Effect.fn("TestEnvironmentRegistry.makeHarness")(function* (return next;});}- yield* Ref.update(storedRemoteTokens, (current) => {- const next = new Map(current);- next.delete(target.environmentId);- return next;- });}),});const cacheStore = Persistence.EnvironmentCacheStore.of({@@ -313,24 +289,6 @@ const makeHarness = Effect.fn("TestEnvironmentRegistry.makeHarness")(function* (return next;}),});- const tokenStore = TokenStore.RemoteDpopAccessTokenStore.of({- get: (environmentId) =>- Ref.get(storedRemoteTokens).pipe(- Effect.map((current) => Option.fromUndefinedOr(current.get(environmentId))),- ),- put: (token) =>- Ref.update(storedRemoteTokens, (current) => {- const next = new Map(current);- next.set(token.environmentId, token);- return next;- }),- remove: (environmentId) =>- Ref.update(storedRemoteTokens, (current) => {- const next = new Map(current);- next.delete(environmentId);- return next;- }),- });const sshGateway = ClientCapabilities.SshEnvironmentGateway.of({provision: () => Effect.die(new Error("SSH provisioning is not used.")),prepare: () => Effect.die(new Error("SSH preparation is not used.")),@@ -375,7 +333,6 @@ const makeHarness = Effect.fn("TestEnvironmentRegistry.makeHarness")(function* (Layer.succeed(Persistence.ConnectionRegistrationStore, registrationStore),Layer.succeed(ConnectionProfileStore.ConnectionProfileStore, profileStore),Layer.succeed(ConnectionCredentialStore.ConnectionCredentialStore, credentialStore),- Layer.succeed(TokenStore.RemoteDpopAccessTokenStore, tokenStore),Layer.succeed(ClientCapabilities.SshEnvironmentGateway, sshGateway),Layer.succeed(Connectivity.Connectivity, connectivity),Layer.succeed(@@ -400,7 +357,6 @@ const makeHarness = Effect.fn("TestEnvironmentRegistry.makeHarness")(function* (storedProfiles,profileReadCount,storedCredentials,- storedRemoteTokens,disconnectedSshTargets,networkStatus,};@@ -585,15 +541,15 @@ describe("EnvironmentRegistry", () => {yield* Effect.gen(function* () {const registry = yield* EnvironmentRegistry.EnvironmentRegistry;- yield* registry.register(new RelayConnectionRegistration({ target: RELAY_TARGET }));+ yield* registry.register(bearerRegistration());yield* awaitConnectionState(registry,- RELAY_TARGET.environmentId,+ BEARER_TARGET.environmentId,(state) => state.phase === "connected",);- expect((yield* Ref.get(harness.storedTargets)).get(RELAY_TARGET.environmentId)).toEqual(- RELAY_TARGET,+ expect((yield* Ref.get(harness.storedTargets)).get(BEARER_TARGET.environmentId)).toEqual(+ BEARER_TARGET,);expect(yield* Ref.get(harness.sessions)).toHaveLength(1);}).pipe(Effect.provide(harness.layer));@@ -602,11 +558,12 @@ describe("EnvironmentRegistry", () => {it.effect("moves durable streams to a replacement supervisor", () =>Effect.gen(function* () {- const replacement = new RelayConnectionTarget({- environmentId: RELAY_TARGET.environmentId,- label: "Replacement relay environment",+ const replacement = new BearerConnectionTarget({+ environmentId: BEARER_TARGET.environmentId,+ label: "Replacement bearer environment",+ connectionId: "replacement-bearer-connection",});- const harness = yield* makeHarness([RELAY_TARGET]);+ const harness = yield* makeHarness([BEARER_TARGET], [BEARER_PROFILE]);yield* Effect.gen(function* () {const registry = yield* EnvironmentRegistry.EnvironmentRegistry;@@ -616,14 +573,14 @@ describe("EnvironmentRegistry", () => {yield* registry.start;yield* awaitConnectionState(registry,- RELAY_TARGET.environmentId,+ BEARER_TARGET.environmentId,(state) => state.phase === "connected",);const subscription = yield* Effect.forkChild(registry.followStream(- RELAY_TARGET.environmentId,+ BEARER_TARGET.environmentId,Stream.unwrap(EnvironmentSupervisor.EnvironmentSupervisor.pipe(Effect.map((supervisor) =>@@ -647,11 +604,11 @@ describe("EnvironmentRegistry", () => {);yield* Deferred.await(firstObserved).pipe(Effect.timeout("1 second"));- yield* registry.register(new RelayConnectionRegistration({ target: replacement }));+ yield* registry.register(bearerRegistration(replacement));yield* Deferred.await(secondObserved).pipe(Effect.timeout("1 second"));yield* Fiber.interrupt(subscription);- expect(yield* Ref.get(labels)).toEqual([RELAY_TARGET.label, replacement.label]);+ expect(yield* Ref.get(labels)).toEqual([BEARER_TARGET.label, replacement.label]);}).pipe(Effect.provide(harness.layer), Effect.scoped);}),);@@ -667,38 +624,9 @@ describe("EnvironmentRegistry", () => {}),);- it.effect("removes all relay-owned data without touching non-cloud connections", () =>- Effect.gen(function* () {- const harness = yield* makeHarness(- [RELAY_TARGET, SECOND_RELAY_TARGET, BEARER_TARGET],- [BEARER_PROFILE],- [[BEARER_TARGET.connectionId, BEARER_CREDENTIAL]],- );-- yield* Effect.gen(function* () {- const registry = yield* EnvironmentRegistry.EnvironmentRegistry;- yield* registry.removeRelayEnvironments();-- const targets = yield* Ref.get(harness.storedTargets);- expect(targets.has(RELAY_TARGET.environmentId)).toBe(false);- expect(targets.has(SECOND_RELAY_TARGET.environmentId)).toBe(false);- expect(targets.get(BEARER_TARGET.environmentId)).toEqual(BEARER_TARGET);- expect(yield* Ref.get(harness.cacheClears)).toEqual(- expect.arrayContaining([RELAY_TARGET.environmentId, SECOND_RELAY_TARGET.environmentId]),- );- expect(yield* Ref.get(harness.ownedDataClears)).toEqual(- expect.arrayContaining([RELAY_TARGET.environmentId, SECOND_RELAY_TARGET.environmentId]),- );- expect(- (yield* SubscriptionRef.get(registry.entries)).has(BEARER_TARGET.environmentId),- ).toBe(true);- }).pipe(Effect.provide(harness.layer), Effect.scoped);- }),- );-it.effect("keeps the runtime registered when durable removal fails", () =>Effect.gen(function* () {- const harness = yield* makeHarness([RELAY_TARGET], [], [], {+ const harness = yield* makeHarness([BEARER_TARGET], [BEARER_PROFILE], [], {beforeRegistrationRemove: () =>Effect.fail(new Persistence.ConnectionPersistenceError({@@ -713,18 +641,18 @@ describe("EnvironmentRegistry", () => {yield* registry.start;yield* awaitConnectionState(registry,- RELAY_TARGET.environmentId,+ BEARER_TARGET.environmentId,(state) => state.phase === "connected",);- const error = yield* Effect.flip(registry.removeRelayEnvironments());+ const error = yield* Effect.flip(registry.remove(BEARER_TARGET.environmentId));expect(error._tag).toBe("ConnectionPersistenceError");expect(yield* Ref.get(harness.releasedSessions)).toBe(0);- expect((yield* SubscriptionRef.get(registry.entries)).has(RELAY_TARGET.environmentId)).toBe(- true,- );- expect((yield* Ref.get(harness.storedTargets)).has(RELAY_TARGET.environmentId)).toBe(true);+ expect(+ (yield* SubscriptionRef.get(registry.entries)).has(BEARER_TARGET.environmentId),+ ).toBe(true);+ expect((yield* Ref.get(harness.storedTargets)).has(BEARER_TARGET.environmentId)).toBe(true);expect(yield* Ref.get(harness.cacheClears)).toEqual([]);expect(yield* Ref.get(harness.ownedDataClears)).toEqual([]);}).pipe(Effect.provide(harness.layer), Effect.scoped);@@ -790,9 +718,10 @@ describe("EnvironmentRegistry", () => {it.effect("gives a primary platform registration precedence over persisted registrations", () =>Effect.gen(function* () {- const shadowedTarget = new RelayConnectionTarget({+ const shadowedTarget = new BearerConnectionTarget({environmentId: TARGET.environmentId,- label: "Shadowed relay environment",+ label: "Shadowed bearer environment",+ connectionId: "shadowed-bearer-connection",});const harness = yield* makeHarness([shadowedTarget]);@@ -805,7 +734,7 @@ describe("EnvironmentRegistry", () => {).toEqual(TARGET);expect((yield* Ref.get(harness.storedTargets)).has(TARGET.environmentId)).toBe(false);- yield* registry.register(new RelayConnectionRegistration({ target: shadowedTarget }));+ yield* registry.register(bearerRegistration(shadowedTarget));expect((yield* SubscriptionRef.get(registry.entries)).get(TARGET.environmentId)?.target,@@ -819,9 +748,10 @@ describe("EnvironmentRegistry", () => {Effect.gen(function* () {const registrationStarted = yield* Deferred.make<void>();const continueRegistration = yield* Deferred.make<void>();- const shadowedTarget = new RelayConnectionTarget({+ const shadowedTarget = new BearerConnectionTarget({environmentId: TARGET.environmentId,- label: "Shadowed relay environment",+ label: "Shadowed bearer environment",+ connectionId: "shadowed-bearer-connection",});const harness = yield* makeHarness([], [], [], {beforeRegistrationRegister: () =>@@ -833,7 +763,7 @@ describe("EnvironmentRegistry", () => {yield* Effect.gen(function* () {const registry = yield* EnvironmentRegistry.EnvironmentRegistry;const persistedRegistration = yield* registry- .register(new RelayConnectionRegistration({ target: shadowedTarget }))+ .register(bearerRegistration(shadowedTarget)).pipe(Effect.forkChild({ startImmediately: true }));yield* Deferred.await(registrationStarted);@@ -940,9 +870,6 @@ describe("EnvironmentRegistry", () => {expect((yield* Ref.get(harness.storedCredentials)).has(SSH_CONNECTION.connectionId)).toBe(false,);- expect((yield* Ref.get(harness.storedRemoteTokens)).has(SSH_CONNECTION.environmentId)).toBe(- false,- );expect(yield* Ref.get(harness.disconnectedSshTargets)).toEqual([SSH_TARGET]);}).pipe(Effect.provide(harness.layer));}),diff --git a/packages/client-runtime/src/connection/registry.ts b/packages/client-runtime/src/connection/registry.tsindex a3a36272f..3e19c8d51 100644--- a/packages/client-runtime/src/connection/registry.ts+++ b/packages/client-runtime/src/connection/registry.ts@@ -83,12 +83,6 @@ export class EnvironmentRegistry extends Context.Service<| EnvironmentNotRegisteredError| PlatformEnvironmentRemovalError>;- readonly removeRelayEnvironments: () => Effect.Effect<- void,- | Persistence.ConnectionPersistenceError- | ConnectionAttemptError- | PlatformEnvironmentRemovalError- >;readonly retryNow: (environmentId: EnvironmentId) => Effect.Effect<void>;readonly state: (environmentId: EnvironmentId,@@ -602,26 +596,6 @@ export const make = Effect.gen(function* () {);});- const removeRelayEnvironments = Effect.fn("EnvironmentRegistry.removeRelayEnvironments")(- function* () {- const relayEnvironmentIds = [...(yield* SubscriptionRef.get(entries)).values()]- .filter((entry) => entry.target._tag === "RelayConnectionTarget")- .map((entry) => entry.target.environmentId);-- yield* Effect.forEach(- relayEnvironmentIds,- (environmentId) =>- remove(environmentId).pipe(- Effect.catchTag("EnvironmentNotRegisteredError", () => Effect.void),- ),- {- concurrency: "unbounded",- discard: true,- },- );- },- );-const retryNow = (environmentId: EnvironmentId) =>acquireSupervisor(environmentId).pipe(Effect.flatMap((supervisor) => supervisor.retryNow),@@ -665,7 +639,6 @@ export const make = Effect.gen(function* () {registerPlatform,reconcilePlatform,remove,- removeRelayEnvironments,retryNow,state,stateChanges,diff --git a/packages/client-runtime/src/connection/resolver.test.ts b/packages/client-runtime/src/connection/resolver.test.tsindex d71c0f960..4f683f68d 100644--- a/packages/client-runtime/src/connection/resolver.test.ts+++ b/packages/client-runtime/src/connection/resolver.test.ts@@ -1,471 +1,85 @@-import { EnvironmentId, type DesktopSshEnvironmentTarget } from "@t3tools/contracts";-import { RelayEnvironmentConnectScope } from "@t3tools/contracts/relay";-import { RelayClientTracer } from "@t3tools/shared/relayTracing";-import { describe, expect, it } from "@effect/vitest";+import { EnvironmentId } from "@t3tools/contracts";+import { expect, it } from "@effect/vitest";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";import * as Option from "effect/Option";-import * as Ref from "effect/Ref";-import * as Tracer from "effect/Tracer";-import * as ManagedRelay from "../relay/managedRelay.ts";-import * as ConnectionResolver from "./resolver.ts";-import * as ClientCapabilities from "../platform/capabilities.ts";import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";-import {- BearerConnectionCredential,- BearerConnectionProfile,- type ConnectionCatalogEntry,- SshConnectionProfile,- type ConnectionCredential,- type ConnectionProfile,-} from "./catalog.ts";+import * as ClientCapabilities from "../platform/capabilities.ts";+import { BearerConnectionCredential, BearerConnectionProfile } from "./catalog.ts";import * as ConnectionCredentialStore from "./credentialStore.ts";-import {- BearerConnectionTarget,- ConnectionTransientError,- PrimaryConnectionTarget,- RelayConnectionTarget,- SshConnectionTarget,- type ConnectionTarget,-} from "./model.ts";+import { BearerConnectionTarget } from "./model.ts";import * as ConnectionProfileStore from "./profileStore.ts";+import * as ConnectionResolver from "./resolver.ts";++const target = new BearerConnectionTarget({+ environmentId: EnvironmentId.make("environment-bearer"),+ label: "Bearer environment",+ connectionId: "bearer-connection",+});-const ENVIRONMENT_ID = EnvironmentId.make("environment-1");-const ENDPOINT = {+const profile = new BearerConnectionProfile({+ connectionId: target.connectionId,+ environmentId: target.environmentId,+ label: target.label,httpBaseUrl: "https://environment.example.test",wsBaseUrl: "wss://environment.example.test",- providerKind: "cloudflare_tunnel" as const,-};-const SSH_TARGET: DesktopSshEnvironmentTarget = {- alias: "development",- hostname: "development.example.test",- username: "developer",- port: 22,-};--function catalogEntry(- target: ConnectionTarget,- profile: Option.Option<ConnectionProfile> = Option.none(),-): ConnectionCatalogEntry {- return { target, profile };-}--function unsupported<A>(name: string): Effect.Effect<A> {- return Effect.die(new Error(`Unexpected relay call: ${name}`));-}--function collectingTracer(spans: Array<string>): Tracer.Tracer {- return Tracer.make({- span: (options) => {- const span = new Tracer.NativeSpan(options);- const end = span.end.bind(span);- span.end = (endTime, exit) => {- end(endTime, exit);- spans.push(span.name);- };- return span;- },- });-}--function relayClient(- connectEnvironment: ManagedRelay.ManagedRelayClient["Service"]["connectEnvironment"],-) {- return ManagedRelay.ManagedRelayClient.of({- relayUrl: "https://relay.example.test",- listEnvironments: () => unsupported("listEnvironments"),- listDevices: () => unsupported("listDevices"),- createEnvironmentLinkChallenge: () => unsupported("createEnvironmentLinkChallenge"),- linkEnvironment: () => unsupported("linkEnvironment"),- unlinkEnvironment: () => unsupported("unlinkEnvironment"),- getEnvironmentStatus: () => unsupported("getEnvironmentStatus"),- connectEnvironment,- registerDevice: () => unsupported("registerDevice"),- unregisterDevice: () => unsupported("unregisterDevice"),- registerLiveActivity: () => unsupported("registerLiveActivity"),- getAgentActivitySnapshot: () => unsupported("getAgentActivitySnapshot"),- resetTokenCache: Effect.void,- });-}--const makeDependencies = Effect.fn("TestConnectionResolver.makeDependencies")((options?: {- readonly profiles?: ReadonlyArray<ConnectionProfile>;- readonly credentials?: ReadonlyArray<readonly [string, ConnectionCredential]>;- readonly connectEnvironment?: ManagedRelay.ManagedRelayClient["Service"]["connectEnvironment"];- readonly authorizeBearer?: RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization["Service"]["authorizeBearer"];- readonly authorizeDpop?: RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization["Service"]["authorizeDpop"];- readonly primaryBearerToken?: string;- readonly prepareSsh?: ClientCapabilities.SshEnvironmentGateway["Service"]["prepare"];-}) => {- const profiles = new Map(- (options?.profiles ?? []).map((profile) => [profile.connectionId, profile]),- );- const credentials = new Map(options?.credentials ?? []);+});- const profileStore = ConnectionProfileStore.ConnectionProfileStore.of({- get: (connectionId) => Effect.succeed(Option.fromNullishOr(profiles.get(connectionId))),- put: (profile) => Effect.sync(() => void profiles.set(profile.connectionId, profile)),- remove: (connectionId) => Effect.sync(() => void profiles.delete(connectionId)),- });- const credentialStore = ConnectionCredentialStore.ConnectionCredentialStore.of({- get: (connectionId) => Effect.succeed(Option.fromNullishOr(credentials.get(connectionId))),- put: (connectionId, credential) =>- Effect.sync(() => void credentials.set(connectionId, credential)),- remove: (connectionId) => Effect.sync(() => void credentials.delete(connectionId)),- });- const remote = RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization.of({- authorizeBearer:- options?.authorizeBearer ??- ((input) =>+const dependencies = Layer.mergeAll(+ ConnectionCredentialStore.layer({+ get: () => Effect.succeed(Option.some(new BearerConnectionCredential({ token: "secret" }))),+ put: () => Effect.void,+ remove: () => Effect.void,+ }),+ ConnectionProfileStore.layer({+ get: () => Effect.succeed(Option.some(profile)),+ put: () => Effect.void,+ remove: () => Effect.void,+ }),+ Layer.succeed(+ ClientCapabilities.PrimaryEnvironmentAuth,+ ClientCapabilities.PrimaryEnvironmentAuth.of({ bearerToken: Effect.succeed(Option.none()) }),+ ),+ Layer.succeed(+ ClientCapabilities.ClientPresentation,+ ClientCapabilities.ClientPresentation.of({ metadata: {}, scopes: [] }),+ ),+ Layer.succeed(+ ClientCapabilities.SshEnvironmentGateway,+ ClientCapabilities.SshEnvironmentGateway.of({+ provision: () => Effect.die("unused"),+ prepare: () => Effect.die("unused"),+ disconnect: () => Effect.die("unused"),+ }),+ ),+ Layer.succeed(+ RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization,+ RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization.of({+ authorizeBearer: (input) =>Effect.succeed({environmentId: input.expectedEnvironmentId,- label: "Authorized bearer environment",+ label: "Authorized environment",httpBaseUrl: input.httpBaseUrl,- socketUrl: "wss://authorized.example.test/ws?wsTicket=bearer",- httpAuthorization: {- _tag: "Bearer" as const,- token: input.bearerToken,- },- })),- authorizeDpop:- options?.authorizeDpop ??- ((input) =>- input.obtainBootstrap.pipe(- Effect.as({- environmentId: input.expectedEnvironmentId,- label: "Authorized relay environment",- httpBaseUrl: ENDPOINT.httpBaseUrl,- socketUrl: "wss://authorized.example.test/ws?wsTicket=dpop",- httpAuthorization: {- _tag: "Dpop" as const,- accessToken: "dpop-access-token",- },- }),- )),- });- const ssh = ClientCapabilities.SshEnvironmentGateway.of({- provision: () => Effect.die("unused"),- prepare:- options?.prepareSsh ??- (() =>- Effect.succeed({- bootstrap: {- target: SSH_TARGET,- httpBaseUrl: "http://127.0.0.1:4010",- wsBaseUrl: "ws://127.0.0.1:4010",- pairingToken: null,- },- bearerToken: "ssh-bearer",- })),- disconnect: () => Effect.void,- });-- const dependencies = Layer.mergeAll(- Layer.succeed(ConnectionProfileStore.ConnectionProfileStore, profileStore),- Layer.succeed(ConnectionCredentialStore.ConnectionCredentialStore, credentialStore),- Layer.succeed(- ClientCapabilities.CloudSession,- ClientCapabilities.CloudSession.of({ clerkToken: Effect.succeed("clerk-session") }),- ),- Layer.succeed(- ClientCapabilities.PrimaryEnvironmentAuth,- ClientCapabilities.PrimaryEnvironmentAuth.of({- bearerToken: Effect.succeed(Option.fromNullishOr(options?.primaryBearerToken)),- }),- ),- Layer.succeed(- ClientCapabilities.ClientPresentation,- ClientCapabilities.ClientPresentation.of({- metadata: { label: "Test Client", deviceType: "desktop", surface: "web" },- scopes: [],- }),- ),- Layer.succeed(- ClientCapabilities.RelayDeviceIdentity,- ClientCapabilities.RelayDeviceIdentity.of({- deviceId: Effect.succeed(Option.some("device-1")),- }),- ),- Layer.succeed(RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization, remote),- Layer.succeed(ClientCapabilities.SshEnvironmentGateway, ssh),- Layer.succeed(- ManagedRelay.ManagedRelayClient,- relayClient(- options?.connectEnvironment ??- ((input) =>- Effect.succeed({- environmentId: input.environmentId,- endpoint: ENDPOINT,- credential: "relay-bootstrap",- expiresAt: "2026-06-06T00:00:00.000Z",- })),- ),- ),- );-- return Effect.succeed(ConnectionResolver.layer.pipe(Layer.provide(dependencies)));-});--describe("ConnectionResolver", () => {- it.effect("prepares a primary environment without remote capabilities", () =>- Effect.gen(function* () {- const brokerLayer = yield* makeDependencies();- const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));- const target = new PrimaryConnectionTarget({- environmentId: ENVIRONMENT_ID,- label: "Primary",- httpBaseUrl: "http://127.0.0.1:3777",- wsBaseUrl: "ws://127.0.0.1:3777",- });-- expect(yield* broker.prepare(catalogEntry(target))).toEqual({- environmentId: ENVIRONMENT_ID,- label: "Primary",- httpBaseUrl: "http://127.0.0.1:3777",- socketUrl: "ws://127.0.0.1:3777/ws?clientSurface=web",- httpAuthorization: null,- target,- });+ socketUrl: "wss://environment.example.test/ws?wsTicket=ticket",+ httpAuthorization: { _tag: "Bearer", token: input.bearerToken },+ }),}),- );-- it.effect("authorizes a desktop primary environment with its platform bearer token", () =>- Effect.gen(function* () {- const bearerInputs = yield* Ref.make<ReadonlyArray<string>>([]);- const brokerLayer = yield* makeDependencies({- primaryBearerToken: "desktop-bearer",- authorizeBearer: (input) =>- Ref.update(bearerInputs, (values) => [...values, input.bearerToken]).pipe(- Effect.as({- environmentId: input.expectedEnvironmentId,- label: "Primary",- httpBaseUrl: input.httpBaseUrl,- socketUrl: "ws://127.0.0.1:3777/ws?wsTicket=desktop",- httpAuthorization: {- _tag: "Bearer" as const,- token: input.bearerToken,- },- }),- ),- });- const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));- const target = new PrimaryConnectionTarget({- environmentId: ENVIRONMENT_ID,- label: "Primary",- httpBaseUrl: "http://127.0.0.1:3777",- wsBaseUrl: "ws://127.0.0.1:3777",- });-- expect(yield* broker.prepare(catalogEntry(target))).toMatchObject({- socketUrl: "ws://127.0.0.1:3777/ws?wsTicket=desktop",- httpAuthorization: { _tag: "Bearer", token: "desktop-bearer" },- target,- });- expect(yield* Ref.get(bearerInputs)).toEqual(["desktop-bearer"]);- }),- );-- it.effect("uses the registered bearer profile without re-reading the profile store", () =>- Effect.gen(function* () {- const bearerInputs = yield* Ref.make<ReadonlyArray<string>>([]);- const target = new BearerConnectionTarget({- environmentId: ENVIRONMENT_ID,- label: "Saved",- connectionId: "saved-1",- });- const profile = new BearerConnectionProfile({- connectionId: "saved-1",- environmentId: ENVIRONMENT_ID,- label: "Saved",- httpBaseUrl: ENDPOINT.httpBaseUrl,- wsBaseUrl: ENDPOINT.wsBaseUrl,- });- const brokerLayer = yield* makeDependencies({- credentials: [["saved-1", new BearerConnectionCredential({ token: "secret-bearer" })]],- authorizeBearer: (input) =>- Ref.update(bearerInputs, (values) => [...values, input.bearerToken]).pipe(- Effect.as({- environmentId: input.expectedEnvironmentId,- label: "Saved",- httpBaseUrl: input.httpBaseUrl,- socketUrl: "wss://environment.example.test/ws?wsTicket=ticket",- httpAuthorization: {- _tag: "Bearer" as const,- token: input.bearerToken,- },- }),- ),- });- const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));-- expect(- (yield* broker.prepare(catalogEntry(target, Option.some(profile)))).socketUrl,- ).toContain("wsTicket=ticket");- expect(yield* Ref.get(bearerInputs)).toEqual(["secret-bearer"]);- }),- );-- it.effect("brokers relay credentials with the current cloud session and device identity", () =>- Effect.gen(function* () {- const relayInputs = yield* Ref.make<- ReadonlyArray<{- readonly clerkToken: string;- readonly scopes: ReadonlyArray<string>;- readonly deviceId?: string;- }>- >([]);- const bootstrapCredentials = yield* Ref.make<ReadonlyArray<string>>([]);- const target = new RelayConnectionTarget({- environmentId: ENVIRONMENT_ID,- label: "Cloud",- });- const brokerLayer = yield* makeDependencies({- connectEnvironment: (input) =>- Ref.update(relayInputs, (values) => [- ...values,- {- clerkToken: input.clerkToken,- scopes: input.scopes,- ...(input.deviceId ? { deviceId: input.deviceId } : {}),- },- ]).pipe(- Effect.as({- environmentId: input.environmentId,- endpoint: ENDPOINT,- credential: "relay-bootstrap",- expiresAt: "2026-06-06T00:00:00.000Z",- }),- ),- authorizeDpop: (input) =>- input.obtainBootstrap.pipe(- Effect.tap((bootstrap) =>- Ref.update(bootstrapCredentials, (values) => [...values, bootstrap.credential]),- ),- Effect.as({- environmentId: input.expectedEnvironmentId,- label: "Cloud",- httpBaseUrl: ENDPOINT.httpBaseUrl,- socketUrl: "wss://environment.example.test/ws?wsTicket=dpop",- httpAuthorization: {- _tag: "Dpop" as const,- accessToken: "dpop-access-token",- },- }),- ),- });- const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));-- expect((yield* broker.prepare(catalogEntry(target))).socketUrl).toContain("wsTicket=dpop");- expect(yield* Ref.get(relayInputs)).toEqual([- {- clerkToken: "clerk-session",- scopes: [RelayEnvironmentConnectScope],- deviceId: "device-1",- },- ]);- expect(yield* Ref.get(bootstrapCredentials)).toEqual(["relay-bootstrap"]);- }),- );-- it.effect("exports the complete relay authorization flow through the product tracer", () =>- Effect.gen(function* () {- const userSpans: Array<string> = [];- const productSpans: Array<string> = [];- const target = new RelayConnectionTarget({- environmentId: ENVIRONMENT_ID,- label: "Cloud",- });- const brokerLayer = yield* makeDependencies({- authorizeDpop: (input) =>- input.obtainBootstrap.pipe(- Effect.as({- environmentId: input.expectedEnvironmentId,- label: "Cloud",- httpBaseUrl: ENDPOINT.httpBaseUrl,- socketUrl: "wss://environment.example.test/ws?wsTicket=dpop",- httpAuthorization: {- _tag: "Dpop" as const,- accessToken: "dpop-access-token",- },- }),- Effect.withSpan("test.remote.authorizeDpop"),- ),- });- const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));-- yield* broker- .prepare(catalogEntry(target))- .pipe(- Effect.provideService(RelayClientTracer, Option.some(collectingTracer(productSpans))),- Effect.withTracer(collectingTracer(userSpans)),- );-- expect(productSpans).toContain("clientRuntime.connection.broker.relay");- expect(productSpans).toContain("test.remote.authorizeDpop");- expect(userSpans).toContain("clientRuntime.connection.broker.prepare");- expect(userSpans).not.toContain("test.remote.authorizeDpop");- }),- );-- it.effect("delegates SSH launch to the platform gateway before remote authorization", () =>- Effect.gen(function* () {- const preparedTargets = yield* Ref.make<ReadonlyArray<DesktopSshEnvironmentTarget>>([]);- const target = new SshConnectionTarget({- environmentId: ENVIRONMENT_ID,- label: "SSH",- connectionId: "ssh-1",- });- const profile = new SshConnectionProfile({- connectionId: "ssh-1",- environmentId: ENVIRONMENT_ID,- label: "SSH",- target: SSH_TARGET,- });- const brokerLayer = yield* makeDependencies({- prepareSsh: (input) =>- Ref.update(preparedTargets, (values) => [...values, input.target]).pipe(- Effect.as({- bootstrap: {- target: input.target,- httpBaseUrl: "http://127.0.0.1:4010",- wsBaseUrl: "ws://127.0.0.1:4010",- pairingToken: null,- },- bearerToken: "ssh-bearer",- }),- ),- });- const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));-- expect(- (yield* broker.prepare(catalogEntry(target, Option.some(profile)))).socketUrl,- ).toContain("wsTicket=bearer");- expect(yield* Ref.get(preparedTargets)).toEqual([SSH_TARGET]);- }),- );-- it.effect("classifies relay request timeouts as retryable connection failures", () =>- Effect.gen(function* () {- const target = new RelayConnectionTarget({- environmentId: ENVIRONMENT_ID,- label: "Cloud",- });- const brokerLayer = yield* makeDependencies({- connectEnvironment: () =>- Effect.fail(- new ManagedRelay.ManagedRelayRequestTimeoutError({- activity: "Relay environment connection",- timeoutMs: ManagedRelay.MANAGED_RELAY_REQUEST_TIMEOUT_MS,- traceId: null,- }),- ),- });- const broker = yield* ConnectionResolver.ConnectionResolver.pipe(Effect.provide(brokerLayer));- const error = yield* Effect.flip(broker.prepare(catalogEntry(target)));-- expect(error).toBeInstanceOf(ConnectionTransientError);- expect(error).toMatchObject({ reason: "timeout" });- }),- );-});+ ),+);++it.effect("prepares a saved bearer connection", () =>+ Effect.gen(function* () {+ const resolver = yield* ConnectionResolver.ConnectionResolver;+ const prepared = yield* resolver.prepare({ target, profile: Option.some(profile) });++ expect(prepared).toEqual({+ environmentId: target.environmentId,+ label: "Authorized environment",+ httpBaseUrl: profile.httpBaseUrl,+ socketUrl: "wss://environment.example.test/ws?wsTicket=ticket",+ httpAuthorization: { _tag: "Bearer", token: "secret" },+ target,+ });+ }).pipe(Effect.provide(ConnectionResolver.layer.pipe(Layer.provide(dependencies)))),+);diff --git a/packages/client-runtime/src/connection/resolver.ts b/packages/client-runtime/src/connection/resolver.tsindex 3a5d5437a..6d5f1b2b5 100644--- a/packages/client-runtime/src/connection/resolver.ts+++ b/packages/client-runtime/src/connection/resolver.ts@@ -1,6 +1,4 @@import type { AuthClientPresentationMetadata } from "@t3tools/contracts";-import { RelayEnvironmentConnectScope } from "@t3tools/contracts/relay";-import { withRelayClientTracing } from "@t3tools/shared/relayTracing";import * as Context from "effect/Context";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";@@ -9,7 +7,6 @@ import * as Schema from "effect/Schema";import { appendClientConnectionParams } from "../authorization/remote.ts";import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";-import * as ManagedRelay from "../relay/managedRelay.ts";import * as ClientCapabilities from "../platform/capabilities.ts";import {BearerConnectionCredential,@@ -18,18 +15,12 @@ import {SshConnectionProfile,} from "./catalog.ts";import * as ConnectionCredentialStore from "./credentialStore.ts";-import {- credentialMissingError,- environmentMismatchError,- mapManagedRelayError,- profileMissingError,-} from "./errors.ts";+import { credentialMissingError, environmentMismatchError, profileMissingError } from "./errors.ts";import type {BearerConnectionTarget,ConnectionTarget,PreparedConnection,PrimaryConnectionTarget,- RelayConnectionTarget,SshConnectionTarget,} from "./model.ts";import { ConnectionBlockedError, type ConnectionAttemptError } from "./model.ts";@@ -145,54 +136,6 @@ const makeBearerBroker = Effect.fn("clientRuntime.connection.broker.makeBearer")});});-const makeRelayBroker = Effect.fn("clientRuntime.connection.broker.makeRelay")(function* () {- const relay = yield* ManagedRelay.ManagedRelayClient;- const session = yield* ClientCapabilities.CloudSession;- const identity = yield* ClientCapabilities.RelayDeviceIdentity;- const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;-- return Effect.fnUntraced(- function* (target: RelayConnectionTarget) {- const authorized = yield* remote.authorizeDpop({- expectedEnvironmentId: target.environmentId,- obtainBootstrap: Effect.gen(function* () {- const clerkToken = yield* session.clerkToken.pipe(- Effect.withSpan("relay.connection.cloudSessionToken.resolve"),- );- const deviceId = yield* identity.deviceId.pipe(- Effect.withSpan("relay.connection.deviceIdentity.resolve"),- );- const connected = yield* relay- .connectEnvironment({- clerkToken,- scopes: [RelayEnvironmentConnectScope],- environmentId: target.environmentId,- ...(Option.isSome(deviceId) ? { deviceId: deviceId.value } : {}),- })- .pipe(Effect.mapError(mapManagedRelayError));- if (connected.environmentId !== target.environmentId) {- return yield* environmentMismatchError({- expected: target.environmentId,- actual: connected.environmentId,- });- }- return connected;- }).pipe(Effect.withSpan("relay.connection.bootstrap.obtain")),- });- return {- environmentId: authorized.environmentId,- label: authorized.label,- httpBaseUrl: authorized.httpBaseUrl,- socketUrl: authorized.socketUrl,- httpAuthorization: authorized.httpAuthorization,- target,- } satisfies PreparedConnection;- },- Effect.withSpan("clientRuntime.connection.broker.relay"),- withRelayClientTracing,- );-});-const makeSshBroker = Effect.fn("clientRuntime.connection.broker.makeSsh")(function* () {const profiles = yield* ConnectionProfileStore.ConnectionProfileStore;const ssh = yield* ClientCapabilities.SshEnvironmentGateway;@@ -251,7 +194,6 @@ const makeSshBroker = Effect.fn("clientRuntime.connection.broker.makeSsh")(functexport const make = Effect.gen(function* () {const primary = yield* makePrimaryBroker();const bearer = yield* makeBearerBroker();- const relay = yield* makeRelayBroker();const ssh = yield* makeSshBroker();const prepare = Effect.fn("clientRuntime.connection.broker.prepare")(function* (@@ -267,8 +209,6 @@ export const make = Effect.gen(function* () {return yield* primary(target);case "BearerConnectionTarget":return yield* bearer({ ...entry, target });- case "RelayConnectionTarget":- return yield* relay(target);case "SshConnectionTarget":return yield* ssh({ ...entry, target });}diff --git a/packages/client-runtime/src/connection/supervisor.test.ts b/packages/client-runtime/src/connection/supervisor.test.tsindex 5e50c44d9..6de84c66e 100644--- a/packages/client-runtime/src/connection/supervisor.test.ts+++ b/packages/client-runtime/src/connection/supervisor.test.ts@@ -1,5 +1,4 @@import { EnvironmentId } from "@t3tools/contracts";-import { RelayClientTracer } from "@t3tools/shared/relayTracing";import { describe, expect, it } from "@effect/vitest";import * as Deferred from "effect/Deferred";import * as Effect from "effect/Effect";@@ -9,7 +8,6 @@ import * as Ref from "effect/Ref";import * as Stream from "effect/Stream";import * as SubscriptionRef from "effect/SubscriptionRef";import * as TestClock from "effect/testing/TestClock";-import * as Tracer from "effect/Tracer";import type { WsRpcProtocolClient } from "../rpc/protocol.ts";import type { ConnectionCatalogEntry } from "./catalog.ts";@@ -19,7 +17,6 @@ import {ConnectionBlockedError,ConnectionTransientError,PrimaryConnectionTarget,- RelayConnectionTarget,type ConnectionAttemptError,type ConnectionTarget,type NetworkStatus,@@ -37,21 +34,11 @@ const TARGET = new PrimaryConnectionTarget({wsBaseUrl: "wss://environment.example.test",});-const RELAY_TARGET = new RelayConnectionTarget({- environmentId: TARGET.environmentId,- label: TARGET.label,-});-const TARGET_ENTRY: ConnectionCatalogEntry = {target: TARGET,profile: Option.none(),};-const RELAY_ENTRY: ConnectionCatalogEntry = {- target: RELAY_TARGET,- profile: Option.none(),-};-const PREPARED_CONNECTION: PreparedConnection = {environmentId: TARGET.environmentId,label: TARGET.label,@@ -216,49 +203,6 @@ const makeHarness = Effect.fn("TestConnectionHarness.make")(function* (options?:});describe("EnvironmentSupervisor", () => {- it.effect("exports each relay setup as a standalone linked trace that ends at readiness", () =>- Effect.gen(function* () {- const spans: Array<Tracer.NativeSpan> = [];- const tracer = Tracer.make({- span: (options) => {- const span = new Tracer.NativeSpan(options);- const end = span.end.bind(span);- span.end = (endTime, exit) => {- end(endTime, exit);- spans.push(span);- };- return span;- },- });- const harness = yield* makeHarness({- prepare: (attempt) =>- attempt === 1 ? Effect.fail(transient()) : Effect.succeed(PREPARED_CONNECTION),- });- const supervisor = yield* EnvironmentSupervisor.make(RELAY_ENTRY, {- initiallyDesired: true,- }).pipe(- Effect.provide(harness.dependencies),- Effect.provideService(RelayClientTracer, Option.some(tracer)),- );-- yield* awaitState(- supervisor.state,- (state) => state.phase === "backoff" && state.attempt === 1,- );- const firstAttempt = spans.find((span) => span.name === "relay.connection.attempt");- expect(firstAttempt).toBeDefined();-- yield* TestClock.adjust("3 seconds");- yield* awaitState(supervisor.state, (state) => state.phase === "connected");-- const attempts = spans.filter((span) => span.name === "relay.connection.attempt");- expect(attempts).toHaveLength(2);- expect(attempts[0]?.traceId).not.toBe(attempts[1]?.traceId);- expect(attempts[1]?.links.map((link) => link.span.spanId)).toContain(attempts[0]?.spanId);- expect(yield* Ref.get(harness.releaseCount)).toBe(0);- }).pipe(Effect.provide(TestClock.layer())),- );-it.effect("does not attempt a connection until it is desired", () =>Effect.gen(function* () {const harness = yield* makeHarness();@@ -1076,47 +1020,6 @@ describe("EnvironmentSupervisor", () => {}),);- it.effect("releases and reconnects a relay session when credentials change", () =>- Effect.gen(function* () {- const harness = yield* makeHarness();- const supervisor = yield* EnvironmentSupervisor.make(RELAY_ENTRY, {- initiallyDesired: true,- }).pipe(Effect.provide(harness.dependencies));-- yield* awaitState(supervisor.state, (state) => state.phase === "connected");- yield* harness.wake("credentials-changed");- yield* awaitState(- supervisor.state,- (state) => state.phase === "connected" && state.generation === 2,- );-- expect(yield* Ref.get(harness.sessionCount)).toBe(2);- expect(yield* Ref.get(harness.releaseCount)).toBe(1);- }),- );-- it.effect("interrupts relay setup when credentials change", () =>- Effect.gen(function* () {- const firstAttemptStarted = yield* Deferred.make<void>();- const harness = yield* makeHarness({- prepare: (attempt) =>- attempt === 1- ? Deferred.succeed(firstAttemptStarted, undefined).pipe(Effect.andThen(Effect.never))- : Effect.succeed(PREPARED_CONNECTION),- });- const supervisor = yield* EnvironmentSupervisor.make(RELAY_ENTRY, {- initiallyDesired: true,- }).pipe(Effect.provide(harness.dependencies));-- yield* Deferred.await(firstAttemptStarted);- yield* harness.wake("credentials-changed");- yield* awaitState(supervisor.state, (state) => state.phase === "connected");-- expect(yield* Ref.get(harness.prepareCount)).toBe(2);- expect(yield* Ref.get(harness.sessionCount)).toBe(1);- }),- );-it.effect("explicit disconnect releases the session and returns to available", () =>Effect.gen(function* () {const harness = yield* makeHarness();diff --git a/packages/client-runtime/src/connection/supervisor.ts b/packages/client-runtime/src/connection/supervisor.tsindex 85fda10ef..4cf5286b0 100644--- a/packages/client-runtime/src/connection/supervisor.ts+++ b/packages/client-runtime/src/connection/supervisor.ts@@ -1,4 +1,3 @@-import { withRelayClientTracing } from "@t3tools/shared/relayTracing";import * as Cause from "effect/Cause";import * as Clock from "effect/Clock";import * as Context from "effect/Context";@@ -261,15 +260,6 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (yield* Queue.offer(signals, next);});- const logManagedRelayAccountChange = Effect.logInfo(- "Managed relay account changed; restarting the environment connection.",- ).pipe(- Effect.annotateLogs({- "environment.id": target.environmentId,- "environment.label": target.label,- }),- );-const reportProgress = Effect.fn("EnvironmentSupervisor.reportProgress")(function* (attempt: number,generation: number,@@ -294,64 +284,12 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* ();});- const traceRelayEstablishment = (- effect: Effect.Effect<- ConnectionDriver.EnvironmentConnectionLease,- ConnectionAttemptError,- Scope.Scope- >,- attempt: number,- generation: number,- pendingRetry: Option.Option<PendingRetryTrace>,- ) => {- const traced = Effect.gen(function* () {- const attemptSpan = yield* Effect.currentSpan.pipe(Effect.orDie);- yield* annotateTarget(target);- yield* Effect.annotateCurrentSpan({- "connection.attempt": attempt,- "connection.generation": generation,- "connection.retry.failure_count": Option.match(pendingRetry, {- onNone: () => 0,- onSome: (retry) => retry.failureCount,- }),- });- const lease = yield* effect.pipe(- Effect.mapError(- (error): TracedAttemptFailure => ({- error,- attemptSpan: Option.some(attemptSpan),- }),- ),- );- return { attemptSpan: Option.some(attemptSpan), lease };- }).pipe(Effect.withSpan("relay.connection.attempt", { root: true }));-- return Option.match(pendingRetry, {- onNone: () => traced,- onSome: (retry) =>- traced.pipe(- Effect.linkSpans(retry.previousAttempt, {- "connection.retry.delay_ms": retry.delayMs,- "connection.retry.reason": retry.reason,- }),- ),- }).pipe(withRelayClientTracing);- };-const establishTracedConnection = Effect.fnUntraced(function* (attempt: number,generation: number,lastFailure: ConnectionAttemptError | null,pendingRetry: Option.Option<PendingRetryTrace>,) {- if (target._tag === "RelayConnectionTarget") {- return yield* traceRelayEstablishment(- establishConnection(attempt, generation, lastFailure),- attempt,- generation,- pendingRetry,- );- }return yield* establishConnection(attempt, generation, lastFailure).pipe(Effect.map((lease) => ({attemptSpan: Option.none<Tracer.Span>(),@@ -384,10 +322,6 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (if (next.reason === "application-active-reconnect") {return true;}- if (next.reason === "credentials-changed" && target._tag === "RelayConnectionTarget") {- yield* logManagedRelayAccountChange;- return false;- }break;}}@@ -408,10 +342,6 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (}break;case "Wakeup":- if (next.reason === "credentials-changed" && target._tag === "RelayConnectionTarget") {- yield* logManagedRelayAccountChange;- return false;- }if (next.reason === "application-active-reconnect") {// Mobile operating systems commonly suspend sockets without// delivering a close event. A long background resume deliberately@@ -467,13 +397,6 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (yield* Fiber.interrupt(probe);return true;}- if (- probeEvent.signal.reason === "credentials-changed" &&- target._tag === "RelayConnectionTarget"- ) {- yield* Fiber.interrupt(probe);- return false;- }break;case "ConnectRequested":break;diff --git a/packages/client-runtime/src/platform/capabilities.ts b/packages/client-runtime/src/platform/capabilities.tsindex a20b7d404..e02b51c39 100644--- a/packages/client-runtime/src/platform/capabilities.ts+++ b/packages/client-runtime/src/platform/capabilities.ts@@ -21,20 +21,6 @@ export interface ProvisionedSshEnvironment extends PreparedSshEnvironment {readonly label: string;}-export class CloudSession extends Context.Service<- CloudSession,- {- readonly clerkToken: Effect.Effect<string, ConnectionAttemptError>;- }->()("@t3tools/client-runtime/platform/capabilities/CloudSession") {}--export class RelayDeviceIdentity extends Context.Service<- RelayDeviceIdentity,- {- readonly deviceId: Effect.Effect<Option.Option<string>, ConnectionAttemptError>;- }->()("@t3tools/client-runtime/platform/capabilities/RelayDeviceIdentity") {}-export class ClientPresentation extends Context.Service<ClientPresentation,{diff --git a/packages/client-runtime/src/platform/storageDocument.test.ts b/packages/client-runtime/src/platform/storageDocument.test.tsindex 8ad6b81e1..69fed7ed4 100644--- a/packages/client-runtime/src/platform/storageDocument.test.ts+++ b/packages/client-runtime/src/platform/storageDocument.test.ts@@ -1,20 +1,14 @@import { EnvironmentId } from "@t3tools/contracts";import { describe, expect, it } from "@effect/vitest";-import * as TokenStore from "../authorization/tokenStore.ts";import {BearerConnectionCredential,BearerConnectionProfile,BearerConnectionRegistration,- RelayConnectionRegistration,SshConnectionProfile,SshConnectionRegistration,} from "../connection/catalog.ts";-import {- BearerConnectionTarget,- RelayConnectionTarget,- SshConnectionTarget,-} from "../connection/model.ts";+import { BearerConnectionTarget, SshConnectionTarget } from "../connection/model.ts";import {EMPTY_CONNECTION_CATALOG_DOCUMENT,registerConnectionInCatalog,@@ -38,19 +32,6 @@ const BEARER_PROFILE = new BearerConnectionProfile({const BEARER_CREDENTIAL = new BearerConnectionCredential({token: "bearer-token",});-const REMOTE_TOKEN = new TokenStore.RemoteDpopAccessToken({- environmentId: ENVIRONMENT_ID,- label: "Remote",- endpoint: {- httpBaseUrl: "https://remote.example.test",- wsBaseUrl: "wss://remote.example.test",- providerKind: "cloudflare_tunnel",- },- accessToken: "dpop-token",- expiresAtEpochMs: 1_000_000,- dpopThumbprint: "thumbprint",-});-describe("ConnectionCatalogDocument", () => {it("registers a bearer connection as one catalog mutation", () => {const document = registerConnectionInCatalog(@@ -72,39 +53,9 @@ describe("ConnectionCatalogDocument", () => {]);});- it("replaces obsolete connection metadata without discarding a reusable DPoP token", () => {- const bearer = registerConnectionInCatalog(- {- ...EMPTY_CONNECTION_CATALOG_DOCUMENT,- remoteDpopTokens: [REMOTE_TOKEN],- },- new BearerConnectionRegistration({- target: BEARER_TARGET,- profile: BEARER_PROFILE,- credential: BEARER_CREDENTIAL,- }),- );- const relayTarget = new RelayConnectionTarget({- environmentId: ENVIRONMENT_ID,- label: "Remote",- });- const relay = registerConnectionInCatalog(- bearer,- new RelayConnectionRegistration({ target: relayTarget }),- );-- expect(relay.targets).toEqual([relayTarget]);- expect(relay.profiles).toEqual([]);- expect(relay.credentials).toEqual([]);- expect(relay.remoteDpopTokens).toEqual([REMOTE_TOKEN]);- });-it("removes every catalog record owned by an explicit disconnect", () => {const registered = registerConnectionInCatalog(- {- ...EMPTY_CONNECTION_CATALOG_DOCUMENT,- remoteDpopTokens: [REMOTE_TOKEN],- },+ EMPTY_CONNECTION_CATALOG_DOCUMENT,new BearerConnectionRegistration({target: BEARER_TARGET,profile: BEARER_PROFILE,diff --git a/packages/client-runtime/src/platform/storageDocument.ts b/packages/client-runtime/src/platform/storageDocument.tsindex 0ba55dfa2..996ad1372 100644--- a/packages/client-runtime/src/platform/storageDocument.ts+++ b/packages/client-runtime/src/platform/storageDocument.ts@@ -6,7 +6,6 @@ import {ConnectionProfile,} from "../connection/catalog.ts";import { type ConnectionTarget, PersistedConnectionTarget } from "../connection/model.ts";-import * as TokenStore from "../authorization/tokenStore.ts";export const StoredConnectionCredential = Schema.Struct({connectionId: Schema.String,@@ -19,7 +18,6 @@ export const ConnectionCatalogDocument = Schema.Struct({targets: Schema.Array(PersistedConnectionTarget),profiles: Schema.Array(ConnectionProfile),credentials: Schema.Array(StoredConnectionCredential),- remoteDpopTokens: Schema.Array(TokenStore.RemoteDpopAccessToken),});export type ConnectionCatalogDocument = typeof ConnectionCatalogDocument.Type;@@ -28,7 +26,6 @@ export const EMPTY_CONNECTION_CATALOG_DOCUMENT: ConnectionCatalogDocument = Objetargets: [],profiles: [],credentials: [],- remoteDpopTokens: [],});export function replaceCatalogValue<A>(@@ -51,7 +48,6 @@ export function removeCatalogValue<A>(function connectionIdOf(target: ConnectionTarget): string | null {switch (target._tag) {case "PrimaryConnectionTarget":- case "RelayConnectionTarget":return null;case "BearerConnectionTarget":case "SshConnectionTarget":@@ -62,7 +58,6 @@ function connectionIdOf(target: ConnectionTarget): string | null {function removeConnectionMetadata(document: ConnectionCatalogDocument,target: ConnectionTarget,- removeRemoteToken: boolean,): ConnectionCatalogDocument {const connectionId = connectionIdOf(target);return {@@ -80,13 +75,6 @@ function removeConnectionMetadata(connectionId === null? document.credentials: removeCatalogValue(document.credentials, (value) => value.connectionId, connectionId),- remoteDpopTokens: removeRemoteToken- ? removeCatalogValue(- document.remoteDpopTokens,- (value) => value.environmentId,- target.environmentId,- )- : document.remoteDpopTokens,};}@@ -98,16 +86,13 @@ export function registerConnectionInCatalog(const previous = document.targets.find((candidate) => candidate.environmentId === target.environmentId,);- const cleaned =- previous === undefined ? document : removeConnectionMetadata(document, previous, false);+ const cleaned = previous === undefined ? document : removeConnectionMetadata(document, previous);const next: ConnectionCatalogDocument = {...cleaned,targets: replaceCatalogValue(cleaned.targets, (value) => value.environmentId, target),};switch (registration._tag) {- case "RelayConnectionRegistration":- return next;case "BearerConnectionRegistration":return {...next,@@ -137,5 +122,5 @@ export function removeConnectionFromCatalog(document: ConnectionCatalogDocument,target: ConnectionTarget,): ConnectionCatalogDocument {- return removeConnectionMetadata(document, target, true);+ return removeConnectionMetadata(document, target);}diff --git a/packages/client-runtime/src/relay/discovery.test.ts b/packages/client-runtime/src/relay/discovery.test.tsdeleted file mode 100644index 8cb963000..000000000--- a/packages/client-runtime/src/relay/discovery.test.ts+++ /dev/null@@ -1,426 +0,0 @@-import { EnvironmentId } from "@t3tools/contracts";-import type {- RelayClientEnvironmentRecord,- RelayEnvironmentStatusResponse,-} from "@t3tools/contracts/relay";-import { describe, expect, it } from "@effect/vitest";-import * as Deferred from "effect/Deferred";-import * as Effect from "effect/Effect";-import * as Fiber from "effect/Fiber";-import * as Layer from "effect/Layer";-import * as Option from "effect/Option";-import * as Ref from "effect/Ref";-import * as Stream from "effect/Stream";-import * as SubscriptionRef from "effect/SubscriptionRef";--import * as ManagedRelay from "./managedRelay.ts";-import * as ClientCapabilities from "../platform/capabilities.ts";-import * as Connectivity from "../connection/connectivity.ts";-import { ConnectionBlockedError, type NetworkStatus } from "../connection/model.ts";-import * as ConnectionWakeups from "../connection/wakeups.ts";-import * as RelayEnvironmentDiscovery from "./discovery.ts";--const environments = [- {- environmentId: EnvironmentId.make("environment-1"),- label: "Environment One",- endpoint: {- httpBaseUrl: "https://one.example.test",- wsBaseUrl: "wss://one.example.test",- providerKind: "cloudflare_tunnel",- },- linkedAt: "2026-06-01T00:00:00.000Z",- },- {- environmentId: EnvironmentId.make("environment-2"),- label: "Environment Two",- endpoint: {- httpBaseUrl: "https://two.example.test",- wsBaseUrl: "wss://two.example.test",- providerKind: "cloudflare_tunnel",- },- linkedAt: "2026-06-01T00:00:00.000Z",- },-] satisfies ReadonlyArray<RelayClientEnvironmentRecord>;--function status(- environment: RelayClientEnvironmentRecord,- value: "online" | "offline",-): RelayEnvironmentStatusResponse {- return {- environmentId: environment.environmentId,- endpoint: environment.endpoint,- status: value,- checkedAt: "2026-06-01T00:00:00.000Z",- };-}--const makeHarness = Effect.fn("RelayDiscoveryTest.makeHarness")(function* () {- const networkStatus = yield* SubscriptionRef.make<NetworkStatus>("online");- const listCalls = yield* Ref.make(0);- const listFailure = yield* Ref.make<ManagedRelay.ManagedRelayClientError | null>(null);- const secondListCall = yield* Deferred.make<void>();- const clerkToken = yield* Ref.make<string | null>("clerk-token");- const wakeups = yield* SubscriptionRef.make<{- readonly sequence: number;- readonly reason: "application-active" | "credentials-changed";- }>({- sequence: 0,- reason: "application-active",- });- const statusRequests = yield* Ref.make(- new Map<- string,- Deferred.Deferred<RelayEnvironmentStatusResponse, ManagedRelay.ManagedRelayClientError>- >(),- );- for (const environment of environments) {- const request = yield* Deferred.make<- RelayEnvironmentStatusResponse,- ManagedRelay.ManagedRelayClientError- >();- yield* Ref.update(statusRequests, (current) => {- const next = new Map(current);- next.set(environment.environmentId, request);- return next;- });- }-- const client = ManagedRelay.ManagedRelayClient.of({- relayUrl: "https://relay.example.test",- listEnvironments: () =>- Effect.gen(function* () {- const count = yield* Ref.updateAndGet(listCalls, (current) => current + 1);- if (count >= 2) {- yield* Deferred.succeed(secondListCall, undefined);- }- const failure = yield* Ref.get(listFailure);- if (failure) {- return yield* failure;- }- return environments;- }),- getEnvironmentStatus: ({ environmentId }) =>- Ref.get(statusRequests).pipe(- Effect.flatMap((requests) => Deferred.await(requests.get(environmentId)!)),- ),- listDevices: () => Effect.die("unused"),- createEnvironmentLinkChallenge: () => Effect.die("unused"),- linkEnvironment: () => Effect.die("unused"),- unlinkEnvironment: () => Effect.die("unused"),- connectEnvironment: () => Effect.die("unused"),- registerDevice: () => Effect.die("unused"),- unregisterDevice: () => Effect.die("unused"),- registerLiveActivity: () => Effect.die("unused"),- getAgentActivitySnapshot: () => Effect.die("unused"),- resetTokenCache: Effect.void,- } satisfies ManagedRelay.ManagedRelayClient["Service"]);- const connectivity = Connectivity.Connectivity.of({- status: SubscriptionRef.get(networkStatus),- changes: SubscriptionRef.changes(networkStatus),- });- const layer = RelayEnvironmentDiscovery.layer.pipe(- Layer.provide(- Layer.mergeAll(- Layer.succeed(ManagedRelay.ManagedRelayClient, client),- Layer.succeed(- ClientCapabilities.CloudSession,- ClientCapabilities.CloudSession.of({- clerkToken: Ref.get(clerkToken).pipe(- Effect.flatMap((token) =>- token === null- ? Effect.fail(- new ConnectionBlockedError({- reason: "authentication",- detail: "Signed out.",- }),- )- : Effect.succeed(token),- ),- ),- }),- ),- Layer.succeed(Connectivity.Connectivity, connectivity),- Layer.succeed(- ConnectionWakeups.ConnectionWakeups,- ConnectionWakeups.ConnectionWakeups.of({- changes: SubscriptionRef.changes(wakeups).pipe(- Stream.drop(1),- Stream.map((event) => event.reason),- ),- }),- ),- ),- ),- );-- return {- layer,- listCalls,- listFailure,- clerkToken,- networkStatus,- secondListCall,- statusRequests,- wake: (reason: "application-active" | "credentials-changed") =>- SubscriptionRef.update(wakeups, (event) => ({- sequence: event.sequence + 1,- reason,- })),- };-});--describe("RelayEnvironmentDiscovery", () => {- it.effect("publishes each environment status as soon as that lookup completes", () =>- Effect.gen(function* () {- const harness = yield* makeHarness();- yield* Effect.gen(function* () {- const discovery = yield* RelayEnvironmentDiscovery.RelayEnvironmentDiscovery;- const refreshFiber = yield* Effect.forkChild(discovery.refresh);-- const checking = yield* SubscriptionRef.changes(discovery.state).pipe(- Stream.filter((state) => state.environments.size === 2),- Stream.runHead,- Effect.map(Option.getOrThrow),- );- expect(- [...checking.environments.values()].every((entry) => entry.availability === "checking"),- ).toBe(true);-- const requests = yield* Ref.get(harness.statusRequests);- yield* Deferred.succeed(- requests.get(environments[1]!.environmentId)!,- status(environments[1]!, "online"),- );-- const partiallyResolved = yield* SubscriptionRef.changes(discovery.state).pipe(- Stream.filter(- (state) =>- state.environments.get(environments[1]!.environmentId)?.availability === "online",- ),- Stream.runHead,- Effect.map(Option.getOrThrow),- );- expect(- partiallyResolved.environments.get(environments[0]!.environmentId)?.availability,- ).toBe("checking");-- yield* Deferred.succeed(- requests.get(environments[0]!.environmentId)!,- status(environments[0]!, "offline"),- );- yield* Fiber.join(refreshFiber);-- const complete = yield* SubscriptionRef.get(discovery.state);- expect(complete.environments.get(environments[0]!.environmentId)?.availability).toBe(- "offline",- );- expect(complete.refreshing).toBe(false);- }).pipe(Effect.provide(harness.layer));- }),- );-- it.effect(- "preserves discovered rows while offline and refreshes after connectivity returns",- () =>- Effect.gen(function* () {- const harness = yield* makeHarness();- yield* Effect.gen(function* () {- const discovery = yield* RelayEnvironmentDiscovery.RelayEnvironmentDiscovery;- const requests = yield* Ref.get(harness.statusRequests);- for (const environment of environments) {- yield* Deferred.succeed(- requests.get(environment.environmentId)!,- status(environment, "online"),- );- }- yield* discovery.refresh;-- const offlineFiber = yield* SubscriptionRef.changes(discovery.state).pipe(- Stream.filter((state) => state.offline),- Stream.runHead,- Effect.forkChild,- );- yield* SubscriptionRef.set(harness.networkStatus, "offline");- yield* Fiber.join(offlineFiber);- expect((yield* SubscriptionRef.get(discovery.state)).environments.size).toBe(2);-- yield* SubscriptionRef.set(harness.networkStatus, "online");- yield* Deferred.await(harness.secondListCall);- expect(yield* Ref.get(harness.listCalls)).toBe(2);- }).pipe(Effect.provide(harness.layer));- }),- );-- it.effect("publishes listing failures without rejecting the refresh command", () =>- Effect.gen(function* () {- const networkStatus = yield* SubscriptionRef.make<NetworkStatus>("online");- const client = ManagedRelay.ManagedRelayClient.of({- relayUrl: "https://relay.example.test",- listEnvironments: () =>- Effect.fail(- new ManagedRelay.ManagedRelayRequestTimeoutError({- activity: "Relay environment listing",- timeoutMs: ManagedRelay.MANAGED_RELAY_REQUEST_TIMEOUT_MS,- traceId: null,- }),- ),- getEnvironmentStatus: () => Effect.die("unused"),- listDevices: () => Effect.die("unused"),- createEnvironmentLinkChallenge: () => Effect.die("unused"),- linkEnvironment: () => Effect.die("unused"),- unlinkEnvironment: () => Effect.die("unused"),- connectEnvironment: () => Effect.die("unused"),- registerDevice: () => Effect.die("unused"),- unregisterDevice: () => Effect.die("unused"),- registerLiveActivity: () => Effect.die("unused"),- getAgentActivitySnapshot: () => Effect.die("unused"),- resetTokenCache: Effect.void,- } satisfies ManagedRelay.ManagedRelayClient["Service"]);- const layer = RelayEnvironmentDiscovery.layer.pipe(- Layer.provide(- Layer.mergeAll(- Layer.succeed(ManagedRelay.ManagedRelayClient, client),- Layer.succeed(ClientCapabilities.CloudSession, {- clerkToken: Effect.succeed("clerk-token"),- }),- Layer.succeed(Connectivity.Connectivity, {- status: SubscriptionRef.get(networkStatus),- changes: SubscriptionRef.changes(networkStatus),- }),- Layer.succeed(- ConnectionWakeups.ConnectionWakeups,- ConnectionWakeups.ConnectionWakeups.of({ changes: Stream.never }),- ),- ),- ),- );-- yield* Effect.gen(function* () {- const discovery = yield* RelayEnvironmentDiscovery.RelayEnvironmentDiscovery;- yield* discovery.refresh;-- const state = yield* SubscriptionRef.get(discovery.state);- expect(state.refreshing).toBe(false);- expect(Option.getOrThrow(state.error)).toMatchObject({- _tag: "ConnectionTransientError",- reason: "timeout",- message: "Relay environment listing timed out.",- });- }).pipe(Effect.provide(layer));- }),- );-- it.effect("clears previously discovered rows when a refresh fails", () =>- Effect.gen(function* () {- const harness = yield* makeHarness();- yield* Effect.gen(function* () {- const discovery = yield* RelayEnvironmentDiscovery.RelayEnvironmentDiscovery;- const requests = yield* Ref.get(harness.statusRequests);- for (const environment of environments) {- yield* Deferred.succeed(- requests.get(environment.environmentId)!,- status(environment, "online"),- );- }- yield* discovery.refresh;- expect((yield* SubscriptionRef.get(discovery.state)).environments.size).toBe(2);-- yield* Ref.set(- harness.listFailure,- new ManagedRelay.ManagedRelayRequestFailedError({- action: "list relay-managed environments",- cause: new Error("Relay request failed."),- }),- );- yield* discovery.refresh;-- const failed = yield* SubscriptionRef.get(discovery.state);- expect(failed.environments.size).toBe(0);- expect(Option.isSome(failed.error)).toBe(true);- }).pipe(Effect.provide(harness.layer));- }),- );-- it.effect("refreshes proactively when credentials change before any manual refresh", () =>- Effect.gen(function* () {- const harness = yield* makeHarness();- yield* Effect.gen(function* () {- const discovery = yield* RelayEnvironmentDiscovery.RelayEnvironmentDiscovery;- const requests = yield* Ref.get(harness.statusRequests);- for (const environment of environments) {- yield* Deferred.succeed(- requests.get(environment.environmentId)!,- status(environment, "online"),- );- }-- // Let the scoped wakeup subscription start before emitting, mirroring- // a real sign-in which always happens long after service start.- yield* Effect.yieldNow;-- // Sign-in activates the session and emits credentials-changed; the- // list must populate without any screen having asked for a refresh.- yield* harness.wake("credentials-changed");- const populated = yield* SubscriptionRef.changes(discovery.state).pipe(- Stream.filter(- (state) => state.environments.size === environments.length && !state.refreshing,- ),- Stream.runHead,- Effect.map(Option.getOrThrow),- );- expect(Option.isNone(populated.error)).toBe(true);- expect(yield* Ref.get(harness.listCalls)).toBe(1);- }).pipe(Effect.provide(harness.layer), Effect.scoped);- }),- );-- it.effect("settles to a clean empty state when refreshed while signed out", () =>- Effect.gen(function* () {- const harness = yield* makeHarness();- yield* Effect.gen(function* () {- const discovery = yield* RelayEnvironmentDiscovery.RelayEnvironmentDiscovery;- yield* Ref.set(harness.clerkToken, null);- yield* discovery.refresh;-- const state = yield* SubscriptionRef.get(discovery.state);- expect(state.environments.size).toBe(0);- expect(state.refreshing).toBe(false);- expect(Option.isNone(state.error)).toBe(true);- }).pipe(Effect.provide(harness.layer));- }),- );-- it.effect("does not republish stale rows after sign-out invalidates an in-flight refresh", () =>- Effect.gen(function* () {- const harness = yield* makeHarness();- yield* Effect.gen(function* () {- const discovery = yield* RelayEnvironmentDiscovery.RelayEnvironmentDiscovery;- const refreshFiber = yield* Effect.forkChild(discovery.refresh);- yield* SubscriptionRef.changes(discovery.state).pipe(- Stream.filter((state) => state.environments.size === environments.length),- Stream.runHead,- );-- yield* Ref.set(harness.clerkToken, null);- yield* harness.wake("credentials-changed");- yield* SubscriptionRef.changes(discovery.state).pipe(- Stream.filter((state) => state.environments.size === 0),- Stream.runHead,- );-- const requests = yield* Ref.get(harness.statusRequests);- for (const environment of environments) {- yield* Deferred.succeed(- requests.get(environment.environmentId)!,- status(environment, "online"),- );- }- yield* Fiber.join(refreshFiber);- yield* Effect.yieldNow;-- expect((yield* SubscriptionRef.get(discovery.state)).environments.size).toBe(0);- }).pipe(Effect.provide(harness.layer), Effect.scoped);- }),- );-});diff --git a/packages/client-runtime/src/relay/discovery.ts b/packages/client-runtime/src/relay/discovery.tsdeleted file mode 100644index 855bb2654..000000000--- a/packages/client-runtime/src/relay/discovery.ts+++ /dev/null@@ -1,349 +0,0 @@-import type {- RelayClientEnvironmentRecord,- RelayEnvironmentStatusResponse,-} from "@t3tools/contracts/relay";-import { decodeRelayJwt } from "@t3tools/shared/relayJwt";-import {- RelayEnvironmentConnectScope,- RelayEnvironmentStatusScope,-} from "@t3tools/contracts/relay";-import * as Context from "effect/Context";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";-import * as Option from "effect/Option";-import * as Ref from "effect/Ref";-import * as Semaphore from "effect/Semaphore";-import * as Stream from "effect/Stream";-import * as SubscriptionRef from "effect/SubscriptionRef";--import * as ManagedRelay from "./managedRelay.ts";-import * as ClientCapabilities from "../platform/capabilities.ts";-import * as Connectivity from "../connection/connectivity.ts";-import { mapManagedRelayError } from "../connection/errors.ts";-import { ConnectionBlockedError, type ConnectionAttemptError } from "../connection/model.ts";-import * as ConnectionWakeups from "../connection/wakeups.ts";--export type RelayEnvironmentAvailability = "checking" | "online" | "offline" | "error";--export interface RelayDiscoveredEnvironment {- readonly environment: RelayClientEnvironmentRecord;- readonly availability: RelayEnvironmentAvailability;- readonly status: Option.Option<RelayEnvironmentStatusResponse>;- readonly error: Option.Option<ConnectionAttemptError>;-}--export interface RelayEnvironmentDiscoveryState {- readonly environments: ReadonlyMap<string, RelayDiscoveredEnvironment>;- readonly refreshing: boolean;- readonly offline: boolean;- readonly error: Option.Option<ConnectionAttemptError>;-}--export class RelayEnvironmentDiscovery extends Context.Service<- RelayEnvironmentDiscovery,- {- readonly state: SubscriptionRef.SubscriptionRef<RelayEnvironmentDiscoveryState>;- readonly refresh: Effect.Effect<void>;- }->()("@t3tools/client-runtime/relay/discovery/RelayEnvironmentDiscovery") {}--export const EMPTY_RELAY_ENVIRONMENT_DISCOVERY_STATE: RelayEnvironmentDiscoveryState = {- environments: new Map(),- refreshing: false,- offline: false,- error: Option.none(),-};--function validateStatus(- environment: RelayClientEnvironmentRecord,- status: RelayEnvironmentStatusResponse,-): Effect.Effect<RelayEnvironmentStatusResponse, ConnectionAttemptError> {- if (status.environmentId !== environment.environmentId) {- return Effect.fail(- new ConnectionBlockedError({- reason: "configuration",- detail: "Relay returned status for a different environment.",- }),- );- }- if (- status.endpoint.httpBaseUrl !== environment.endpoint.httpBaseUrl ||- status.endpoint.wsBaseUrl !== environment.endpoint.wsBaseUrl ||- status.endpoint.providerKind !== environment.endpoint.providerKind- ) {- return Effect.fail(- new ConnectionBlockedError({- reason: "configuration",- detail: "Relay returned status for a different environment endpoint.",- }),- );- }- if (- status.descriptor !== undefined &&- status.descriptor.environmentId !== environment.environmentId- ) {- return Effect.fail(- new ConnectionBlockedError({- reason: "configuration",- detail: "Relay returned a descriptor for a different environment.",- }),- );- }- return Effect.succeed(status);-}--function relayAccountId(clerkToken: string): Option.Option<string> {- try {- return Option.fromNullishOr(decodeRelayJwt(clerkToken).sub).pipe(- Option.filter((subject) => subject.length > 0),- );- } catch {- return Option.none();- }-}--export const make = Effect.fn("RelayEnvironmentDiscovery.make")(function* () {- const relay = yield* ManagedRelay.ManagedRelayClient;- const session = yield* ClientCapabilities.CloudSession;- const connectivity = yield* Connectivity.Connectivity;- const wakeups = yield* ConnectionWakeups.ConnectionWakeups;- const state = yield* SubscriptionRef.make(EMPTY_RELAY_ENVIRONMENT_DISCOVERY_STATE);- const refreshLock = yield* Semaphore.make(1);- const hasRefreshed = yield* Ref.make(false);- const accountGeneration = yield* Ref.make(0);- const activeAccountId = yield* Ref.make<Option.Option<string>>(Option.none());- const refreshGeneration = yield* Ref.make(0);- const offlineReportFingerprints = yield* Ref.make<ReadonlyMap<string, string>>(new Map());-- const clearOfflineReport = Effect.fn("RelayEnvironmentDiscovery.clearOfflineReport")(function* (- environmentId: string,- ) {- yield* Ref.update(offlineReportFingerprints, (current) => {- if (!current.has(environmentId)) {- return current;- }- const next = new Map(current);- next.delete(environmentId);- return next;- });- });-- const updateEnvironment = Effect.fn("RelayEnvironmentDiscovery.updateEnvironment")(function* (- generation: number,- environmentId: string,- update: (current: RelayDiscoveredEnvironment) => RelayDiscoveredEnvironment,- ) {- if ((yield* Ref.get(accountGeneration)) !== generation) {- return;- }- yield* SubscriptionRef.update(state, (current) => {- const entry = current.environments.get(environmentId);- if (entry === undefined) {- return current;- }- const environments = new Map(current.environments);- environments.set(environmentId, update(entry));- return { ...current, environments };- });- });-- const refreshStatus = Effect.fn("RelayEnvironmentDiscovery.refreshStatus")(function* (- generation: number,- clerkToken: string,- environment: RelayClientEnvironmentRecord,- ) {- const result = yield* relay- .getEnvironmentStatus({- clerkToken,- scopes: [RelayEnvironmentStatusScope, RelayEnvironmentConnectScope],- environmentId: environment.environmentId,- })- .pipe(- Effect.mapError(mapManagedRelayError),- Effect.flatMap((status) => validateStatus(environment, status)),- Effect.result,- );-- if (result._tag === "Success") {- if (result.success.status === "offline") {- const fingerprint = `${result.success.endpoint.httpBaseUrl}\n${result.success.error ?? ""}`;- const shouldReport = yield* Ref.modify(offlineReportFingerprints, (current) => {- if (current.get(environment.environmentId) === fingerprint) {- return [false, current];- }- return [true, new Map(current).set(environment.environmentId, fingerprint)];- });- if (shouldReport) {- yield* Effect.logWarning("Relay environment health check reported offline", {- environmentId: result.success.environmentId,- endpoint: result.success.endpoint.httpBaseUrl,- message: result.success.error,- traceId: result.success.traceId,- });- }- } else {- yield* clearOfflineReport(environment.environmentId);- }- yield* updateEnvironment(generation, environment.environmentId, (current) => ({- ...current,- availability: result.success.status,- status: Option.some(result.success),- error: Option.none(),- }));- return;- }-- yield* clearOfflineReport(environment.environmentId);- yield* updateEnvironment(generation, environment.environmentId, (current) => ({- ...current,- availability: "error",- error: Option.some(result.failure),- }));- });-- const refresh = refreshLock.withPermits(1)(- Effect.gen(function* () {- yield* Ref.set(hasRefreshed, true);- if ((yield* connectivity.status) === "offline") {- yield* SubscriptionRef.update(state, (current) => ({- ...current,- refreshing: false,- offline: true,- }));- return;- }-- let generation = yield* Ref.get(accountGeneration);- yield* Ref.set(refreshGeneration, generation);- yield* SubscriptionRef.set(state, {- environments: new Map(),- refreshing: true,- offline: false,- error: Option.none(),- });-- // Signed out is the idle state, not a failure: the proactive refresh on- // credentials-changed also runs on sign-out and must settle back to a- // clean empty list. Only the session-level "no credentials" error is- // benign — relay-side auth failures (expired/invalid tokens) happen- // after this point and must surface as errors.- const tokenResult = yield* Effect.result(session.clerkToken);- if (tokenResult._tag === "Failure") {- const failure = tokenResult.failure;- if (failure._tag === "ConnectionBlockedError" && failure.reason === "authentication") {- if ((yield* Ref.get(accountGeneration)) !== generation) {- return;- }- yield* SubscriptionRef.update(state, (current) => ({- ...current,- refreshing: false,- }));- return;- }- return yield* Effect.fail(failure);- }- const clerkToken = tokenResult.success;- if ((yield* Ref.get(accountGeneration)) !== generation) {- return;- }- const accountId = relayAccountId(clerkToken);- const previousAccountId = yield* Ref.get(activeAccountId);- if (- Option.isSome(previousAccountId) &&- (!Option.isSome(accountId) || previousAccountId.value !== accountId.value)- ) {- generation = yield* Ref.updateAndGet(accountGeneration, (current) => current + 1);- yield* Ref.set(refreshGeneration, generation);- }- yield* Ref.set(activeAccountId, accountId);-- const environments = yield* relay- .listEnvironments({ clerkToken })- .pipe(Effect.mapError(mapManagedRelayError));- if ((yield* Ref.get(accountGeneration)) !== generation) {- return;- }- const next = new Map<string, RelayDiscoveredEnvironment>();- for (const environment of environments) {- next.set(environment.environmentId, {- environment,- availability: "checking",- status: Option.none(),- error: Option.none(),- });- }- yield* SubscriptionRef.update(state, (current) => ({- ...current,- environments: next,- }));-- yield* Effect.forEach(- environments,- (environment) => refreshStatus(generation, clerkToken, environment),- {- concurrency: "unbounded",- discard: true,- },- );- if ((yield* Ref.get(accountGeneration)) !== generation) {- return;- }- yield* SubscriptionRef.update(state, (current) => ({- ...current,- refreshing: false,- }));- }).pipe(- Effect.catch((error) =>- Effect.gen(function* () {- const generation = yield* Ref.get(refreshGeneration);- if ((yield* Ref.get(accountGeneration)) !== generation) {- return;- }- yield* SubscriptionRef.update(state, (current) => ({- ...current,- refreshing: false,- error: Option.some(error),- }));- }),- ),- ),- );-- yield* connectivity.changes.pipe(- Stream.changes,- Stream.runForEach((networkStatus) =>- networkStatus === "offline"- ? SubscriptionRef.update(state, (current) => ({- ...current,- refreshing: false,- offline: true,- }))- : Ref.get(hasRefreshed).pipe(- Effect.flatMap((shouldRefresh) => (shouldRefresh ? refresh : Effect.void)),- ),- ),- Effect.forkScoped,- );- yield* wakeups.changes.pipe(- Stream.runForEach((reason) =>- reason === "credentials-changed"- ? Effect.gen(function* () {- yield* Ref.update(accountGeneration, (current) => current + 1);- yield* Ref.set(activeAccountId, Option.none());- yield* Ref.set(offlineReportFingerprints, new Map());- yield* SubscriptionRef.set(state, EMPTY_RELAY_ENVIRONMENT_DISCOVERY_STATE);- // Refresh proactively — this wakeup fires when a session activates- // (sign-in or cold start), and the list should be populated before- // any screen asks for it. A signed-out refresh settles back to the- // clean empty state.- yield* refresh.pipe(Effect.forkScoped);- })- : Effect.void,- ),- Effect.forkScoped,- );-- return RelayEnvironmentDiscovery.of({ state, refresh });-});--export const layer = Layer.effect(RelayEnvironmentDiscovery, make());diff --git a/packages/client-runtime/src/relay/index.ts b/packages/client-runtime/src/relay/index.tsdeleted file mode 100644index 76f755353..000000000--- a/packages/client-runtime/src/relay/index.ts+++ /dev/null@@ -1,3 +0,0 @@-export * as Discovery from "./discovery.ts";-export * as ManagedRelay from "./managedRelay.ts";-export * from "./managedRelayState.ts";diff --git a/packages/client-runtime/src/relay/managedRelay.test.ts b/packages/client-runtime/src/relay/managedRelay.test.tsdeleted file mode 100644index 278c20588..000000000--- a/packages/client-runtime/src/relay/managedRelay.test.ts+++ /dev/null@@ -1,511 +0,0 @@-import { EnvironmentId } from "@t3tools/contracts";-import { RelayEnvironmentStatusScope } from "@t3tools/contracts/relay";-import { describe, expect, it } from "@effect/vitest";-import * as Duration from "effect/Duration";-import * as Effect from "effect/Effect";-import * as Fiber from "effect/Fiber";-import * as Layer from "effect/Layer";-import * as Tracer from "effect/Tracer";-import * as TestClock from "effect/testing/TestClock";--import * as ManagedRelay from "./managedRelay.ts";-import { remoteHttpClientLayer } from "../rpc/http.ts";--function managedRelayTestLayer(- fetchFn: typeof globalThis.fetch,- relayUrl = "https://relay.example.test",- accessTokenStore?: ManagedRelay.ManagedRelayAccessTokenStore,-) {- const httpClientLayer = remoteHttpClientLayer(fetchFn);- const signerLayer = Layer.succeed(- ManagedRelay.ManagedRelayDpopSigner,- ManagedRelay.ManagedRelayDpopSigner.of({- thumbprint: Effect.succeed("client-thumbprint"),- createProof: (input: ManagedRelay.ManagedRelayDpopProofInput) =>- Effect.succeed(`proof:${input.url}`),- }),- );- return ManagedRelay.layer({- relayUrl,- clientId: "t3-mobile",- ...(accessTokenStore ? { accessTokenStore } : {}),- }).pipe(Layer.provide(signerLayer), Layer.provide(httpClientLayer));-}--function clerkToken(subject: string, nonce: string): string {- const encode = (value: unknown) =>- btoa(JSON.stringify(value)).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");- return `${encode({ alg: "none" })}.${encode({ sub: subject, nonce })}.signature`;-}--describe("ManagedRelayClient", () => {- it.effect("owns tracing at service and implementation boundaries", () => {- const spanNames: Array<string> = [];- const tracer = Tracer.make({- span: (options) => {- const span = new Tracer.NativeSpan(options);- spanNames.push(span.name);- return span;- },- });- const fetchFn = ((input) => {- const url = String(input);- if (url.endsWith("/v1/client/dpop-token")) {- return Promise.resolve(- Response.json({- access_token: "relay-token",- issued_token_type: "urn:ietf:params:oauth:token-type:access_token",- token_type: "DPoP",- expires_in: 1_800,- scope: RelayEnvironmentStatusScope,- }),- );- }- return Promise.resolve(- Response.json({- environmentId: "env-1",- endpoint: {- httpBaseUrl: "https://desktop.example.test/",- wsBaseUrl: "wss://desktop.example.test/ws",- providerKind: "cloudflare_tunnel",- },- status: "online",- checkedAt: "2026-06-05T20:00:00.000Z",- descriptor: {- environmentId: "env-1",- label: "Desktop",- platform: { os: "darwin", arch: "arm64" },- serverVersion: "0.0.0-test",- capabilities: { repositoryIdentity: true },- },- }),- );- }) satisfies typeof globalThis.fetch;-- return Effect.gen(function* () {- const relayClient = yield* ManagedRelay.ManagedRelayClient;- yield* relayClient.getEnvironmentStatus({- clerkToken: clerkToken("user-1", "session-1"),- scopes: [RelayEnvironmentStatusScope],- environmentId: EnvironmentId.make("env-1"),- });-- expect(spanNames).toEqual(- expect.arrayContaining([- "clientRuntime.managedRelay.getEnvironmentStatus",- "clientRuntime.managedRelay.authorize",- "clientRuntime.managedRelay.obtainAccessToken",- "clientRuntime.managedRelay.tokenCacheCriticalSection",- "clientRuntime.managedRelay.exchangeAccessToken",- ]),- );- expect(spanNames).not.toEqual(- expect.arrayContaining([- "clientRuntime.managedRelay.createTokenExchangeProof",- "clientRuntime.managedRelay.exchangeAccessTokenRequest",- "clientRuntime.managedRelay.createRequestProof",- ]),- );- }).pipe(Effect.withTracer(tracer), Effect.provide(managedRelayTestLayer(fetchFn)));- });-- it.effect("rejects unsafe relay URLs before sending credentials", () => {- let requestCount = 0;- const fetchFn = (() => {- requestCount += 1;- return Promise.resolve(Response.json({}));- }) satisfies typeof globalThis.fetch;-- return Effect.gen(function* () {- const relayClient = yield* ManagedRelay.ManagedRelayClient;- const error = yield* relayClient- .listEnvironments({ clerkToken: "clerk-token" })- .pipe(Effect.flip);-- expect(error).toMatchObject({- _tag: "ManagedRelayUrlInvalidError",- relayUrl: "http://relay.example.test",- message: "Relay URL must be a secure absolute HTTPS origin.",- });- expect(requestCount).toBe(0);- }).pipe(Effect.provide(managedRelayTestLayer(fetchFn, "http://relay.example.test")));- });-- it.effect("reuses usable DPoP tokens and refreshes cleared or expiring cache entries", () => {- let tokenExchangeCount = 0;- const fetchFn = ((input) => {- const url = String(input);- if (url.endsWith("/v1/client/dpop-token")) {- tokenExchangeCount += 1;- return Promise.resolve(- Response.json({- access_token: `relay-token-${tokenExchangeCount}`,- issued_token_type: "urn:ietf:params:oauth:token-type:access_token",- token_type: "DPoP",- expires_in: 10,- scope: RelayEnvironmentStatusScope,- }),- );- }- return Promise.resolve(- Response.json({- environmentId: "env-1",- endpoint: {- httpBaseUrl: "https://desktop.example.test/",- wsBaseUrl: "wss://desktop.example.test/ws",- providerKind: "cloudflare_tunnel",- },- status: "online",- checkedAt: "2026-05-25T00:01:00.000Z",- descriptor: {- environmentId: "env-1",- label: "Desktop",- platform: { os: "darwin", arch: "arm64" },- serverVersion: "0.0.0-test",- capabilities: { repositoryIdentity: true },- },- }),- );- }) satisfies typeof globalThis.fetch;-- return Effect.gen(function* () {- const relayClient = yield* ManagedRelay.ManagedRelayClient;- const statusInput = {- clerkToken: clerkToken("user-1", "session-1"),- scopes: [RelayEnvironmentStatusScope],- environmentId: EnvironmentId.make("env-1"),- } as const;-- yield* relayClient.getEnvironmentStatus(statusInput);- yield* relayClient.getEnvironmentStatus(statusInput);- expect(tokenExchangeCount).toBe(1);-- yield* TestClock.adjust(Duration.seconds(6));- yield* relayClient.getEnvironmentStatus(statusInput);- expect(tokenExchangeCount).toBe(2);-- yield* relayClient.resetTokenCache;- yield* relayClient.getEnvironmentStatus(statusInput);- expect(tokenExchangeCount).toBe(3);- }).pipe(Effect.provide(managedRelayTestLayer(fetchFn)));- });-- it.effect("reuses a persisted token across runtimes and Clerk session token rotation", () => {- let tokenExchangeCount = 0;- let persistedTokens: ReadonlyArray<ManagedRelay.ManagedRelayAccessTokenCacheEntry> = [];- const accessTokenStore: ManagedRelay.ManagedRelayAccessTokenStore = {- load: Effect.sync(() => persistedTokens),- save: (entries) =>- Effect.sync(() => {- persistedTokens = entries;- }),- clear: Effect.sync(() => {- persistedTokens = [];- }),- };- const fetchFn = ((input) => {- const url = String(input);- if (url.endsWith("/v1/client/dpop-token")) {- tokenExchangeCount += 1;- return Promise.resolve(- Response.json({- access_token: "persisted-relay-token",- issued_token_type: "urn:ietf:params:oauth:token-type:access_token",- token_type: "DPoP",- expires_in: 1_800,- scope: RelayEnvironmentStatusScope,- }),- );- }- return Promise.resolve(- Response.json({- environmentId: "env-1",- endpoint: {- httpBaseUrl: "https://desktop.example.test/",- wsBaseUrl: "wss://desktop.example.test/ws",- providerKind: "cloudflare_tunnel",- },- status: "online",- checkedAt: "2026-06-05T20:00:00.000Z",- descriptor: {- environmentId: "env-1",- label: "Desktop",- platform: { os: "darwin", arch: "arm64" },- serverVersion: "0.0.0-test",- capabilities: { repositoryIdentity: true },- },- }),- );- }) satisfies typeof globalThis.fetch;- const statusInput = (token: string) =>- ({- clerkToken: token,- scopes: [RelayEnvironmentStatusScope],- environmentId: EnvironmentId.make("env-1"),- }) as const;-- return Effect.gen(function* () {- yield* Effect.gen(function* () {- const relayClient = yield* ManagedRelay.ManagedRelayClient;- yield* relayClient.getEnvironmentStatus(statusInput(clerkToken("user-1", "session-1")));- }).pipe(Effect.provide(managedRelayTestLayer(fetchFn, undefined, accessTokenStore)));-- expect(tokenExchangeCount).toBe(1);- expect(persistedTokens).toHaveLength(1);-- yield* Effect.gen(function* () {- const relayClient = yield* ManagedRelay.ManagedRelayClient;- yield* relayClient.getEnvironmentStatus(statusInput(clerkToken("user-1", "session-2")));- }).pipe(Effect.provide(managedRelayTestLayer(fetchFn, undefined, accessTokenStore)));-- expect(tokenExchangeCount).toBe(1);- });- });-- it.effect("refreshes a persisted DPoP token once when the relay rejects it", () => {- let tokenExchangeCount = 0;- const statusTokens: Array<string | null> = [];- let persistedTokens: ReadonlyArray<ManagedRelay.ManagedRelayAccessTokenCacheEntry> = [- {- accountId: "user-1",- clientId: "t3-mobile",- relayUrl: "https://relay.example.test",- thumbprint: "client-thumbprint",- scopes: [RelayEnvironmentStatusScope],- accessToken: "stale-relay-token",- expiresAtMillis: Number.MAX_SAFE_INTEGER,- },- ];- const accessTokenStore: ManagedRelay.ManagedRelayAccessTokenStore = {- load: Effect.sync(() => persistedTokens),- save: (entries) =>- Effect.sync(() => {- persistedTokens = entries;- }),- clear: Effect.sync(() => {- persistedTokens = [];- }),- };- const fetchFn = ((input, init) => {- const url = String(input);- if (url.endsWith("/v1/client/dpop-token")) {- tokenExchangeCount += 1;- return Promise.resolve(- Response.json({- access_token: "fresh-relay-token",- issued_token_type: "urn:ietf:params:oauth:token-type:access_token",- token_type: "DPoP",- expires_in: 1_800,- scope: RelayEnvironmentStatusScope,- }),- );- }-- const authorization = new Headers(init?.headers).get("authorization");- statusTokens.push(authorization);- if (authorization === "DPoP stale-relay-token") {- return Promise.resolve(- Response.json(- {- _tag: "RelayAuthInvalidError",- code: "auth_invalid",- reason: "invalid_bearer",- traceId: "trace-stale-token",- },- { status: 401 },- ),- );- }- return Promise.resolve(- Response.json({- environmentId: "env-1",- endpoint: {- httpBaseUrl: "https://desktop.example.test/",- wsBaseUrl: "wss://desktop.example.test/ws",- providerKind: "cloudflare_tunnel",- },- status: "online",- checkedAt: "2026-06-05T20:00:00.000Z",- descriptor: {- environmentId: "env-1",- label: "Desktop",- platform: { os: "darwin", arch: "arm64" },- serverVersion: "0.0.0-test",- capabilities: { repositoryIdentity: true },- },- }),- );- }) satisfies typeof globalThis.fetch;-- return Effect.gen(function* () {- const relayClient = yield* ManagedRelay.ManagedRelayClient;- const result = yield* relayClient.getEnvironmentStatus({- clerkToken: clerkToken("user-1", "session-1"),- scopes: [RelayEnvironmentStatusScope],- environmentId: EnvironmentId.make("env-1"),- });-- expect(result.status).toBe("online");- expect(statusTokens).toEqual(["DPoP stale-relay-token", "DPoP fresh-relay-token"]);- expect(tokenExchangeCount).toBe(1);- expect(persistedTokens).toMatchObject([- {- accessToken: "fresh-relay-token",- },- ]);- }).pipe(Effect.provide(managedRelayTestLayer(fetchFn, undefined, accessTokenStore)));- });-- it.effect("does not persist tokens when the Clerk subject cannot be decoded", () => {- let persistedTokens: ReadonlyArray<ManagedRelay.ManagedRelayAccessTokenCacheEntry> = [];- const accessTokenStore: ManagedRelay.ManagedRelayAccessTokenStore = {- load: Effect.succeed([]),- save: (entries) =>- Effect.sync(() => {- persistedTokens = entries;- }),- clear: Effect.void,- };- const fetchFn = ((input) => {- const url = String(input);- if (url.endsWith("/v1/client/dpop-token")) {- return Promise.resolve(- Response.json({- access_token: "relay-token",- issued_token_type: "urn:ietf:params:oauth:token-type:access_token",- token_type: "DPoP",- expires_in: 1_800,- scope: RelayEnvironmentStatusScope,- }),- );- }- return Promise.resolve(- Response.json({- environmentId: "env-1",- endpoint: {- httpBaseUrl: "https://desktop.example.test/",- wsBaseUrl: "wss://desktop.example.test/ws",- providerKind: "cloudflare_tunnel",- },- status: "online",- checkedAt: "2026-06-05T20:00:00.000Z",- descriptor: {- environmentId: "env-1",- label: "Desktop",- platform: { os: "darwin", arch: "arm64" },- serverVersion: "0.0.0-test",- capabilities: { repositoryIdentity: true },- },- }),- );- }) satisfies typeof globalThis.fetch;-- return Effect.gen(function* () {- const relayClient = yield* ManagedRelay.ManagedRelayClient;- yield* relayClient.getEnvironmentStatus({- clerkToken: "not-a-jwt",- scopes: [RelayEnvironmentStatusScope],- environmentId: EnvironmentId.make("env-1"),- });-- expect(persistedTokens).toEqual([]);- }).pipe(Effect.provide(managedRelayTestLayer(fetchFn, undefined, accessTokenStore)));- });-- it.effect("times out stalled relay environment listing requests", () => {- const fetchFn = (() =>- new Promise<Response>(() => undefined)) satisfies typeof globalThis.fetch;-- return Effect.gen(function* () {- const relayClient = yield* ManagedRelay.ManagedRelayClient;- const errorFiber = yield* relayClient- .listEnvironments({ clerkToken: "clerk-token" })- .pipe(Effect.flip, Effect.forkScoped);-- yield* Effect.yieldNow;- yield* TestClock.adjust(Duration.millis(ManagedRelay.MANAGED_RELAY_REQUEST_TIMEOUT_MS));- const error = yield* Fiber.join(errorFiber);-- expect(error).toMatchObject({- _tag: "ManagedRelayRequestTimeoutError",- activity: "Relay environment listing",- timeoutMs: ManagedRelay.MANAGED_RELAY_REQUEST_TIMEOUT_MS,- message: "Relay environment listing timed out.",- });- }).pipe(Effect.provide(Layer.merge(TestClock.layer(), managedRelayTestLayer(fetchFn))));- });-- it.effect("preserves typed relay trace IDs on client errors", () => {- const fetchFn = (() =>- Promise.resolve(- Response.json(- {- _tag: "RelayAuthInvalidError",- code: "auth_invalid",- reason: "invalid_bearer",- traceId: "trace-managed-relay",- },- { status: 401 },- ),- )) satisfies typeof globalThis.fetch;-- return Effect.gen(function* () {- const relayClient = yield* ManagedRelay.ManagedRelayClient;- const error = yield* relayClient- .listEnvironments({ clerkToken: "clerk-token" })- .pipe(Effect.flip);-- expect(error).toMatchObject({- _tag: "ManagedRelayRequestFailedError",- traceId: "trace-managed-relay",- });- }).pipe(Effect.provide(managedRelayTestLayer(fetchFn)));- });-- it.effect("lists account devices through the Clerk bearer client endpoint", () => {- const fetchFn = ((input, init) => {- expect(String(input)).toBe("https://relay.example.test/v1/client/devices");- expect(init?.headers).toMatchObject({- authorization: "Bearer clerk-token",- });- return Promise.resolve(- Response.json({- devices: [- {- deviceId: "device-1",- label: "Julius's iPhone",- platform: "ios",- iosMajorVersion: 18,- appVersion: "1.0.0",- notifications: {- enabled: false,- notifyOnApproval: true,- notifyOnInput: true,- notifyOnCompletion: true,- notifyOnFailure: true,- },- liveActivities: {- enabled: true,- },- updatedAt: "2026-06-01T00:00:00.000Z",- },- ],- }),- );- }) satisfies typeof globalThis.fetch;-- return Effect.gen(function* () {- const relayClient = yield* ManagedRelay.ManagedRelayClient;- const devices = yield* relayClient.listDevices({ clerkToken: "clerk-token" });- expect(devices).toMatchObject([- {- deviceId: "device-1",- label: "Julius's iPhone",- notifications: {- enabled: false,- },- },- ]);- }).pipe(Effect.provide(managedRelayTestLayer(fetchFn)));- });-});diff --git a/packages/client-runtime/src/relay/managedRelay.ts b/packages/client-runtime/src/relay/managedRelay.tsdeleted file mode 100644index 06769a437..000000000--- a/packages/client-runtime/src/relay/managedRelay.ts+++ /dev/null@@ -1,923 +0,0 @@-import {- RelayAccessTokenType,- RelayApi,- type RelayClientEnvironmentRecord,- type RelayClientDeviceRecord,- RelayConnectEnvironmentEndpoint,- type RelayDeviceRegistrationRequest,- RelayDpopAccessTokenScope,- RelayDpopTokenExchangeGrantType,- type RelayEnvironmentConnectRequest,- type RelayEnvironmentConnectResponse,- type RelayEnvironmentLinkChallengeRequest,- type RelayEnvironmentLinkChallengeResponse,- type RelayEnvironmentLinkRequest,- type RelayEnvironmentLinkResponse,- type RelayEnvironmentStatusResponse,- RelayExchangeDpopAccessTokenEndpoint,- RelayGetEnvironmentStatusEndpoint,- RelayJwtSubjectTokenType,- type RelayAgentActivitySnapshotResponse,- type RelayLiveActivityRegistrationRequest,- RelayMobileRegistrationScope,- type RelayOkResponse,- type RelayPublicClientId,- RelayRegisterDeviceEndpoint,- RelayAgentActivitySnapshotEndpoint,- RelayRegisterLiveActivityEndpoint,- RelayProtectedError,- type RelayProtectedError as RelayProtectedErrorType,- RelayUnregisterDeviceEndpoint,-} from "@t3tools/contracts/relay";-import { encodeOAuthScope, oauthScopeSetEquals } from "@t3tools/shared/oauthScope";-import { decodeRelayJwt } from "@t3tools/shared/relayJwt";-import { withRelayClientTracing } from "@t3tools/shared/relayTracing";-import { normalizeSecureRelayUrl } from "@t3tools/shared/relayUrl";-import * as Clock from "effect/Clock";-import * as Context from "effect/Context";-import * as Duration from "effect/Duration";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";-import * as Option from "effect/Option";-import * as Schema from "effect/Schema";-import * as SynchronizedRef from "effect/SynchronizedRef";-import * as HttpClientError from "effect/unstable/http/HttpClientError";-import type * as HttpMethod from "effect/unstable/http/HttpMethod";-import * as HttpApiClient from "effect/unstable/httpapi/HttpApiClient";--export interface ManagedRelayDpopProofInput {- readonly method: HttpMethod.HttpMethod;- readonly url: string;- readonly accessToken?: string;-}--export class ManagedRelayDpopKeyLoadError extends Schema.TaggedErrorClass<ManagedRelayDpopKeyLoadError>()(- "ManagedRelayDpopKeyLoadError",- {- keyStore: Schema.Literals(["expo-secure-store", "indexed-db"]),- cause: Schema.Defect(),- },-) {- override get message(): string {- return "Could not load relay DPoP proof key.";- }-}--export class ManagedRelayDpopProofCreationError extends Schema.TaggedErrorClass<ManagedRelayDpopProofCreationError>()(- "ManagedRelayDpopProofCreationError",- {- method: Schema.String,- url: Schema.String,- cause: Schema.Defect(),- },-) {- override get message(): string {- return `Could not create the relay DPoP proof for ${this.method} ${this.url}.`;- }-}--export const ManagedRelayDpopSignerError = Schema.Union([- ManagedRelayDpopKeyLoadError,- ManagedRelayDpopProofCreationError,-]);-export type ManagedRelayDpopSignerError = typeof ManagedRelayDpopSignerError.Type;--export const ManagedRelayRequestAction = Schema.Literals([- "exchange relay DPoP access token",- "list relay-managed environments",- "list relay client devices",- "create relay environment link challenge",- "link relay environment",- "unlink relay environment",- "get relay environment status",- "connect relay environment",- "register relay mobile device",- "unregister relay mobile device",- "register relay live activity",- "read relay agent activity snapshot",-]);-export type ManagedRelayRequestAction = typeof ManagedRelayRequestAction.Type;--export const ManagedRelayRequestActivity = Schema.Literals([- "Relay DPoP access token exchange",- "Relay environment listing",- "Relay client device listing",- "Relay environment link challenge",- "Relay environment linking",- "Relay environment unlinking",- "Relay environment status request",- "Relay environment connection",- "Relay mobile device registration",- "Relay mobile device unregistration",- "Relay Live Activity registration",- "Relay agent activity snapshot",-]);-export type ManagedRelayRequestActivity = typeof ManagedRelayRequestActivity.Type;--export class ManagedRelayRequestTimeoutError extends Schema.TaggedErrorClass<ManagedRelayRequestTimeoutError>()(- "ManagedRelayRequestTimeoutError",- {- activity: ManagedRelayRequestActivity,- timeoutMs: Schema.Number,- // The CLIENT span's trace id. A timed-out request has no server response- // to take an id from, but the client span was exported, so carrying its id- // makes the failure searchable instead of logging `traceId: null`.- traceId: Schema.NullOr(Schema.String),- },-) {- override get message(): string {- return `${this.activity} timed out.`;- }-}--export class ManagedRelayUrlInvalidError extends Schema.TaggedErrorClass<ManagedRelayUrlInvalidError>()(- "ManagedRelayUrlInvalidError",- {- relayUrl: Schema.String,- },-) {- override get message(): string {- return "Relay URL must be a secure absolute HTTPS origin.";- }-}--export class ManagedRelayRequestFailedError extends Schema.TaggedErrorClass<ManagedRelayRequestFailedError>()(- "ManagedRelayRequestFailedError",- {- action: ManagedRelayRequestAction,- cause: Schema.Defect(),- relayError: Schema.optional(RelayProtectedError),- traceId: Schema.optional(Schema.String),- },-) {- override get message(): string {- return `Could not ${this.action}.`;- }-}--export class ManagedRelayAccessTokenScopesUnexpectedError extends Schema.TaggedErrorClass<ManagedRelayAccessTokenScopesUnexpectedError>()(- "ManagedRelayAccessTokenScopesUnexpectedError",- {- requestedScopes: Schema.Array(RelayDpopAccessTokenScope),- grantedScope: Schema.String,- },-) {- override get message(): string {- return "Relay granted unexpected DPoP access token scopes.";- }-}--export class ManagedRelayTokenProofCreationError extends Schema.TaggedErrorClass<ManagedRelayTokenProofCreationError>()(- "ManagedRelayTokenProofCreationError",- {- method: Schema.String,- url: Schema.String,- cause: Schema.Defect(),- },-) {- override get message(): string {- return "Could not create relay token DPoP proof.";- }-}--export class ManagedRelayRequestProofCreationError extends Schema.TaggedErrorClass<ManagedRelayRequestProofCreationError>()(- "ManagedRelayRequestProofCreationError",- {- method: Schema.String,- url: Schema.String,- cause: Schema.Defect(),- },-) {- override get message(): string {- return "Could not create relay request DPoP proof.";- }-}--export const ManagedRelayClientError = Schema.Union([- ManagedRelayUrlInvalidError,- ManagedRelayRequestFailedError,- ManagedRelayRequestTimeoutError,- ManagedRelayAccessTokenScopesUnexpectedError,- ManagedRelayDpopKeyLoadError,- ManagedRelayTokenProofCreationError,- ManagedRelayRequestProofCreationError,-]);-export type ManagedRelayClientError = typeof ManagedRelayClientError.Type;--type RelayHttpRequestError =- | RelayProtectedErrorType- | HttpClientError.HttpClientError- | Schema.SchemaError;--export class ManagedRelayDpopSigner extends Context.Service<- ManagedRelayDpopSigner,- {- readonly thumbprint: Effect.Effect<string, ManagedRelayDpopKeyLoadError>;- readonly createProof: (- input: ManagedRelayDpopProofInput,- ) => Effect.Effect<string, ManagedRelayDpopProofCreationError>;- }->()("@t3tools/client-runtime/relay/managedRelay/ManagedRelayDpopSigner") {}--export const MANAGED_RELAY_REQUEST_TIMEOUT_MS = 10_000;--export interface ManagedRelayAccessTokenCacheEntry {- readonly accountId: string;- readonly clientId: RelayPublicClientId;- readonly relayUrl: string;- readonly thumbprint: string;- readonly scopes: ReadonlyArray<RelayDpopAccessTokenScope>;- readonly accessToken: string;- readonly expiresAtMillis: number;-}--export interface ManagedRelayAccessTokenStore {- readonly load: Effect.Effect<ReadonlyArray<ManagedRelayAccessTokenCacheEntry>>;- readonly save: (entries: ReadonlyArray<ManagedRelayAccessTokenCacheEntry>) => Effect.Effect<void>;- readonly clear: Effect.Effect<void>;-}--export interface ManagedRelayAuthorization {- readonly accessToken: string;- readonly proof: string;- readonly thumbprint: string;-}--export interface ManagedRelayClientLayerOptions {- readonly relayUrl: string;- readonly clientId: RelayPublicClientId;- readonly accessTokenStore?: ManagedRelayAccessTokenStore;-}--export class ManagedRelayClient extends Context.Service<- ManagedRelayClient,- {- readonly relayUrl: string;- readonly listEnvironments: (input: {- readonly clerkToken: string;- }) => Effect.Effect<ReadonlyArray<RelayClientEnvironmentRecord>, ManagedRelayClientError>;- readonly listDevices: (input: {- readonly clerkToken: string;- }) => Effect.Effect<ReadonlyArray<RelayClientDeviceRecord>, ManagedRelayClientError>;- readonly createEnvironmentLinkChallenge: (input: {- readonly clerkToken: string;- readonly payload: RelayEnvironmentLinkChallengeRequest;- }) => Effect.Effect<RelayEnvironmentLinkChallengeResponse, ManagedRelayClientError>;- readonly linkEnvironment: (input: {- readonly clerkToken: string;- readonly payload: RelayEnvironmentLinkRequest;- }) => Effect.Effect<RelayEnvironmentLinkResponse, ManagedRelayClientError>;- readonly unlinkEnvironment: (input: {- readonly clerkToken: string;- readonly environmentId: RelayClientEnvironmentRecord["environmentId"];- }) => Effect.Effect<RelayOkResponse, ManagedRelayClientError>;- readonly getEnvironmentStatus: (input: {- readonly clerkToken: string;- readonly scopes: ReadonlyArray<RelayDpopAccessTokenScope>;- readonly environmentId: RelayClientEnvironmentRecord["environmentId"];- }) => Effect.Effect<RelayEnvironmentStatusResponse, ManagedRelayClientError>;- readonly connectEnvironment: (input: {- readonly clerkToken: string;- readonly scopes: ReadonlyArray<RelayDpopAccessTokenScope>;- readonly environmentId: RelayClientEnvironmentRecord["environmentId"];- readonly deviceId?: string;- }) => Effect.Effect<RelayEnvironmentConnectResponse, ManagedRelayClientError>;- readonly registerDevice: (input: {- readonly clerkToken: string;- readonly payload: RelayDeviceRegistrationRequest;- }) => Effect.Effect<RelayOkResponse, ManagedRelayClientError>;- readonly unregisterDevice: (input: {- readonly clerkToken: string;- readonly deviceId: string;- }) => Effect.Effect<RelayOkResponse, ManagedRelayClientError>;- readonly registerLiveActivity: (input: {- readonly clerkToken: string;- readonly payload: RelayLiveActivityRegistrationRequest;- }) => Effect.Effect<RelayOkResponse, ManagedRelayClientError>;- readonly getAgentActivitySnapshot: (input: {- readonly clerkToken: string;- }) => Effect.Effect<RelayAgentActivitySnapshotResponse, ManagedRelayClientError>;- readonly resetTokenCache: Effect.Effect<void>;- }->()("@t3tools/client-runtime/relay/managedRelay/ManagedRelayClient") {}--const isRelayProtectedError = Schema.is(RelayProtectedError);--function relayRequestError(action: ManagedRelayRequestAction) {- return (cause: RelayHttpRequestError): ManagedRelayClientError =>- new ManagedRelayRequestFailedError({- action,- cause,- ...(isRelayProtectedError(cause) ? { relayError: cause, traceId: cause.traceId } : {}),- });-}--function proofCreationErrorFields(error: ManagedRelayDpopProofCreationError) {- return {- method: error.method,- url: error.url,- cause: error,- };-}--function isRejectedDpopAccessToken(error: ManagedRelayClientError): boolean {- return (- error._tag === "ManagedRelayRequestFailedError" &&- error.relayError?._tag === "RelayAuthInvalidError" &&- error.relayError.reason === "invalid_bearer"- );-}--function timeoutRelayRequest(activity: ManagedRelayRequestActivity) {- return <A, E, R>(- effect: Effect.Effect<A, E, R>,- ): Effect.Effect<A, E | ManagedRelayClientError, R> =>- effect.pipe(- Effect.timeoutOption(Duration.millis(MANAGED_RELAY_REQUEST_TIMEOUT_MS)),- Effect.flatMap(- Option.match({- onNone: () =>- Effect.currentParentSpan.pipe(- Effect.map((span) => span.traceId),- Effect.orElseSucceed(() => null),- Effect.flatMap((traceId) =>- Effect.fail(- new ManagedRelayRequestTimeoutError({- activity,- timeoutMs: MANAGED_RELAY_REQUEST_TIMEOUT_MS,- traceId,- }),- ),- ),- ),- onSome: Effect.succeed,- }),- ),- );-}--function tokenMatches(- token: ManagedRelayAccessTokenCacheEntry,- input: {- readonly accountId: string;- readonly clientId: RelayPublicClientId;- readonly relayUrl: string;- readonly thumbprint: string;- readonly scopes: ReadonlyArray<RelayDpopAccessTokenScope>;- readonly nowMillis: number;- },-): boolean {- return (- token.accountId === input.accountId &&- token.clientId === input.clientId &&- token.relayUrl === input.relayUrl &&- token.thumbprint === input.thumbprint &&- token.expiresAtMillis > input.nowMillis + 5_000 &&- input.scopes.every((scope) => token.scopes.includes(scope))- );-}--function relayAccountId(clerkToken: string): Option.Option<string> {- try {- return Option.fromNullishOr(decodeRelayJwt(clerkToken).sub).pipe(- Option.filter((subject) => subject.length > 0),- );- } catch {- return Option.none();- }-}--function bearerHeaders(clerkToken: string) {- return { authorization: `Bearer ${clerkToken}` };-}--function dpopHeaders(authorization: ManagedRelayAuthorization) {- return {- authorization: `DPoP ${authorization.accessToken}`,- dpop: authorization.proof,- };-}--function disabledManagedRelayClient(relayUrl: string): ManagedRelayClient["Service"] {- const unavailable = (spanName: string) =>- Effect.fn(spanName)(function* () {- return yield* new ManagedRelayUrlInvalidError({ relayUrl });- });- return ManagedRelayClient.of({- relayUrl,- listEnvironments: unavailable("clientRuntime.managedRelay.listEnvironments"),- listDevices: unavailable("clientRuntime.managedRelay.listDevices"),- createEnvironmentLinkChallenge: unavailable(- "clientRuntime.managedRelay.createEnvironmentLinkChallenge",- ),- linkEnvironment: unavailable("clientRuntime.managedRelay.linkEnvironment"),- unlinkEnvironment: unavailable("clientRuntime.managedRelay.unlinkEnvironment"),- getEnvironmentStatus: unavailable("clientRuntime.managedRelay.getEnvironmentStatus"),- connectEnvironment: unavailable("clientRuntime.managedRelay.connectEnvironment"),- registerDevice: unavailable("clientRuntime.managedRelay.registerDevice"),- unregisterDevice: unavailable("clientRuntime.managedRelay.unregisterDevice"),- registerLiveActivity: unavailable("clientRuntime.managedRelay.registerLiveActivity"),- getAgentActivitySnapshot: unavailable("clientRuntime.managedRelay.getAgentActivitySnapshot"),- resetTokenCache: Effect.void.pipe(- Effect.withSpan("clientRuntime.managedRelay.resetTokenCache"),- ),- });-}--export const make = Effect.fn("ManagedRelayClient.make")(function* (- options: ManagedRelayClientLayerOptions,-) {- const relayUrl = normalizeSecureRelayUrl(options.relayUrl);- if (relayUrl === null) {- return disabledManagedRelayClient(options.relayUrl);- }- const signer = yield* ManagedRelayDpopSigner;- const client = yield* HttpApiClient.make(RelayApi, { baseUrl: relayUrl });- const initialTokens = options.accessTokenStore ? yield* options.accessTokenStore.load : [];- const cachedTokens = yield* SynchronizedRef.make<- ReadonlyArray<ManagedRelayAccessTokenCacheEntry>- >(initialTokens.filter((token) => token.clientId === options.clientId));- const urlBuilder = HttpApiClient.urlBuilder(RelayApi, { baseUrl: relayUrl });-- type DpopProofTarget = Pick<ManagedRelayDpopProofInput, "method" | "url">;- const dpopProofTargets = {- exchangeAccessToken: (): DpopProofTarget => ({- method: RelayExchangeDpopAccessTokenEndpoint.method,- url: urlBuilder.token.exchangeDpopAccessToken(),- }),- getEnvironmentStatus: (- environmentId: RelayClientEnvironmentRecord["environmentId"],- ): DpopProofTarget => ({- method: RelayGetEnvironmentStatusEndpoint.method,- url: urlBuilder.dpopClient.getEnvironmentStatus({ params: { environmentId } }),- }),- connectEnvironment: (- environmentId: RelayClientEnvironmentRecord["environmentId"],- ): DpopProofTarget => ({- method: RelayConnectEnvironmentEndpoint.method,- url: urlBuilder.dpopClient.connectEnvironment({ params: { environmentId } }),- }),- registerDevice: (): DpopProofTarget => ({- method: RelayRegisterDeviceEndpoint.method,- url: urlBuilder.mobile.registerDevice(),- }),- unregisterDevice: (deviceId: string): DpopProofTarget => ({- method: RelayUnregisterDeviceEndpoint.method,- url: urlBuilder.mobile.unregisterDevice({ params: { deviceId } }),- }),- getAgentActivitySnapshot: (): DpopProofTarget => ({- method: RelayAgentActivitySnapshotEndpoint.method,- url: urlBuilder.mobile.getAgentActivitySnapshot(),- }),- registerLiveActivity: (): DpopProofTarget => ({- method: RelayRegisterLiveActivityEndpoint.method,- url: urlBuilder.mobile.registerLiveActivity(),- }),- };-- const exchangeAccessToken = Effect.fn("clientRuntime.managedRelay.exchangeAccessToken")(- function* (input: {- readonly clerkToken: string;- readonly scopes: ReadonlyArray<RelayDpopAccessTokenScope>;- }) {- yield* Effect.annotateCurrentSpan({- "relay.client_id": options.clientId,- "relay.scopes": input.scopes.join(" "),- });- const proof = yield* signer- .createProof(dpopProofTargets.exchangeAccessToken())- .pipe(- Effect.mapError(- (error) => new ManagedRelayTokenProofCreationError(proofCreationErrorFields(error)),- ),- );- const response = yield* client.token- .exchangeDpopAccessToken({- headers: { dpop: proof },- payload: {- grant_type: RelayDpopTokenExchangeGrantType,- subject_token: input.clerkToken,- subject_token_type: RelayJwtSubjectTokenType,- requested_token_type: RelayAccessTokenType,- resource: relayUrl,- scope: encodeOAuthScope(input.scopes),- client_id: options.clientId,- },- })- .pipe(- Effect.mapError(relayRequestError("exchange relay DPoP access token")),- timeoutRelayRequest("Relay DPoP access token exchange"),- );- if (!oauthScopeSetEquals(response.scope, input.scopes)) {- return yield* new ManagedRelayAccessTokenScopesUnexpectedError({- requestedScopes: input.scopes,- grantedScope: response.scope,- });- }- return response;- },- );-- const obtainAccessToken = Effect.fn("clientRuntime.managedRelay.obtainAccessToken")(- function* (input: {- readonly clerkToken: string;- readonly scopes: ReadonlyArray<RelayDpopAccessTokenScope>;- readonly thumbprint: string;- }) {- yield* Effect.annotateCurrentSpan({- "relay.client_id": options.clientId,- "relay.scopes": input.scopes.join(" "),- });- const nowMillis = yield* Clock.currentTimeMillis;- const accountId = relayAccountId(input.clerkToken);- if (Option.isNone(accountId)) {- yield* Effect.annotateCurrentSpan({- "relay.token_cache.result": "bypass",- "relay.token_cache.bypass_reason": "invalid_subject_token",- });- const response = yield* exchangeAccessToken(input);- return {- accountId: "",- clientId: options.clientId,- relayUrl,- thumbprint: input.thumbprint,- scopes: input.scopes,- accessToken: response.access_token,- expiresAtMillis: nowMillis + response.expires_in * 1_000,- } satisfies ManagedRelayAccessTokenCacheEntry;- }- return yield* SynchronizedRef.modifyEffect(cachedTokens, (tokens) =>- Effect.gen(function* () {- const activeTokens = tokens.filter((token) => token.expiresAtMillis > nowMillis + 5_000);- const cached = activeTokens.find((token) =>- tokenMatches(token, {- accountId: accountId.value,- clientId: options.clientId,- relayUrl,- thumbprint: input.thumbprint,- scopes: input.scopes,- nowMillis,- }),- );- if (cached) {- yield* Effect.annotateCurrentSpan({- "relay.token_cache.result": "hit",- });- return [cached, activeTokens] as const;- }- yield* Effect.annotateCurrentSpan({- "relay.token_cache.result": "miss",- });- const response = yield* exchangeAccessToken(input);- const next: ManagedRelayAccessTokenCacheEntry = {- accountId: accountId.value,- clientId: options.clientId,- relayUrl,- thumbprint: input.thumbprint,- scopes: input.scopes,- accessToken: response.access_token,- expiresAtMillis: nowMillis + response.expires_in * 1_000,- };- const nextTokens = [...activeTokens, next];- if (options.accessTokenStore) {- yield* options.accessTokenStore.save(nextTokens);- }- return [next, nextTokens] as const;- }),- ).pipe(Effect.withSpan("clientRuntime.managedRelay.tokenCacheCriticalSection"));- },- );-- const authorize = Effect.fn("clientRuntime.managedRelay.authorize")(function* (input: {- readonly clerkToken: string;- readonly scopes: ReadonlyArray<RelayDpopAccessTokenScope>;- readonly target: DpopProofTarget;- }) {- yield* Effect.annotateCurrentSpan({- "relay.client_id": options.clientId,- "relay.scopes": input.scopes.join(" "),- "http.request.method": input.target.method,- "url.full": input.target.url,- });- const thumbprint = yield* signer.thumbprint;- const token = yield* obtainAccessToken({- clerkToken: input.clerkToken,- scopes: input.scopes,- thumbprint,- });- const proof = yield* signer- .createProof({- ...input.target,- accessToken: token.accessToken,- })- .pipe(- Effect.mapError(- (error) => new ManagedRelayRequestProofCreationError(proofCreationErrorFields(error)),- ),- );- return { accessToken: token.accessToken, proof, thumbprint };- });-- const invalidateAccessToken = Effect.fn("clientRuntime.managedRelay.invalidateAccessToken")(- function* (accessToken: string) {- return yield* SynchronizedRef.modifyEffect(cachedTokens, (tokens) => {- const nextTokens = tokens.filter((token) => token.accessToken !== accessToken);- if (nextTokens.length === tokens.length) {- return Effect.succeed([false, tokens] as const);- }- return (- options.accessTokenStore ? options.accessTokenStore.save(nextTokens) : Effect.void- ).pipe(Effect.as([true, nextTokens] as const));- });- },- );-- const runDpopRequest = <A>(- input: {- readonly clerkToken: string;- readonly scopes: ReadonlyArray<RelayDpopAccessTokenScope>;- readonly target: DpopProofTarget;- },- request: (- authorization: ManagedRelayAuthorization,- ) => Effect.Effect<A, ManagedRelayClientError>,- ): Effect.Effect<A, ManagedRelayClientError> => {- const attempt = (refreshRejectedToken: boolean): Effect.Effect<A, ManagedRelayClientError> =>- authorize(input).pipe(- Effect.flatMap((authorization) =>- request(authorization).pipe(- Effect.catch((error) => {- if (!isRejectedDpopAccessToken(error)) {- return Effect.fail(error);- }- return invalidateAccessToken(authorization.accessToken).pipe(- Effect.tap((invalidated) =>- Effect.annotateCurrentSpan({- "relay.token_cache.invalidated": invalidated,- "relay.token_cache.invalidation_reason": "invalid_bearer",- "relay.token_cache.retry_after_invalidation": refreshRejectedToken,- }),- ),- Effect.tap((invalidated) =>- invalidated && refreshRejectedToken- ? Effect.logWarning(- "Relay rejected a cached DPoP access token; refreshing it once.",- )- : Effect.void,- ),- Effect.andThen(refreshRejectedToken ? attempt(false) : Effect.fail(error)),- );- }),- ),- ),- );- return attempt(true);- };-- const mobileRegistrationRequest = <A>(- input: {- readonly clerkToken: string;- readonly target: DpopProofTarget;- },- request: (- authorization: ManagedRelayAuthorization,- ) => Effect.Effect<A, ManagedRelayClientError>,- ) =>- runDpopRequest(- {- ...input,- scopes: [RelayMobileRegistrationScope],- },- request,- );-- return ManagedRelayClient.of({- relayUrl,- listEnvironments: Effect.fnUntraced(- function* (input) {- return yield* client.client- .listEnvironments({ headers: bearerHeaders(input.clerkToken) })- .pipe(- Effect.map((response) => response.environments),- Effect.mapError(relayRequestError("list relay-managed environments")),- timeoutRelayRequest("Relay environment listing"),- );- },- Effect.withSpan("clientRuntime.managedRelay.listEnvironments"),- withRelayClientTracing,- ),- listDevices: Effect.fnUntraced(- function* (input) {- return yield* client.client- .listDevices({- headers: bearerHeaders(input.clerkToken),- })- .pipe(- Effect.map((response) => response.devices),- Effect.mapError(relayRequestError("list relay client devices")),- timeoutRelayRequest("Relay client device listing"),- );- },- Effect.withSpan("clientRuntime.managedRelay.listDevices"),- withRelayClientTracing,- ),- createEnvironmentLinkChallenge: Effect.fnUntraced(- function* (input) {- return yield* client.client- .createEnvironmentLinkChallenge({- headers: bearerHeaders(input.clerkToken),- payload: input.payload,- })- .pipe(- Effect.mapError(relayRequestError("create relay environment link challenge")),- timeoutRelayRequest("Relay environment link challenge"),- );- },- Effect.withSpan("clientRuntime.managedRelay.createEnvironmentLinkChallenge"),- withRelayClientTracing,- ),- linkEnvironment: Effect.fnUntraced(- function* (input) {- return yield* client.client- .linkEnvironment({- headers: bearerHeaders(input.clerkToken),- payload: input.payload,- })- .pipe(- Effect.mapError(relayRequestError("link relay environment")),- timeoutRelayRequest("Relay environment linking"),- );- },- Effect.withSpan("clientRuntime.managedRelay.linkEnvironment"),- withRelayClientTracing,- ),- unlinkEnvironment: Effect.fnUntraced(- function* (input) {- return yield* client.client- .unlinkEnvironment({- headers: bearerHeaders(input.clerkToken),- params: { environmentId: input.environmentId },- })- .pipe(- Effect.mapError(relayRequestError("unlink relay environment")),- timeoutRelayRequest("Relay environment unlinking"),- );- },- Effect.withSpan("clientRuntime.managedRelay.unlinkEnvironment"),- withRelayClientTracing,- ),- getEnvironmentStatus: Effect.fnUntraced(- function* (input) {- yield* Effect.annotateCurrentSpan({- "environment.id": input.environmentId,- });- return yield* runDpopRequest(- {- clerkToken: input.clerkToken,- scopes: input.scopes,- target: dpopProofTargets.getEnvironmentStatus(input.environmentId),- },- (authorization) =>- client.dpopClient- .getEnvironmentStatus({- headers: dpopHeaders(authorization),- params: { environmentId: input.environmentId },- })- .pipe(- Effect.mapError(relayRequestError("get relay environment status")),- timeoutRelayRequest("Relay environment status request"),- ),- );- },- Effect.withSpan("clientRuntime.managedRelay.getEnvironmentStatus"),- withRelayClientTracing,- ),- connectEnvironment: Effect.fnUntraced(- function* (input) {- yield* Effect.annotateCurrentSpan({- "environment.id": input.environmentId,- });- return yield* runDpopRequest(- {- clerkToken: input.clerkToken,- scopes: input.scopes,- target: dpopProofTargets.connectEnvironment(input.environmentId),- },- (authorization) => {- const payload: RelayEnvironmentConnectRequest = {- ...(input.deviceId ? { deviceId: input.deviceId } : {}),- clientKeyThumbprint: authorization.thumbprint,- };- return client.dpopClient- .connectEnvironment({- headers: dpopHeaders(authorization),- params: { environmentId: input.environmentId },- payload,- })- .pipe(- Effect.mapError(relayRequestError("connect relay environment")),- timeoutRelayRequest("Relay environment connection"),- );- },- );- },- Effect.withSpan("clientRuntime.managedRelay.connectEnvironment"),- withRelayClientTracing,- ),- registerDevice: Effect.fnUntraced(- function* (input) {- return yield* mobileRegistrationRequest(- {- clerkToken: input.clerkToken,- target: dpopProofTargets.registerDevice(),- },- (authorization) =>- client.mobile- .registerDevice({- headers: dpopHeaders(authorization),- payload: input.payload,- })- .pipe(- Effect.mapError(relayRequestError("register relay mobile device")),- timeoutRelayRequest("Relay mobile device registration"),- ),- );- },- Effect.withSpan("clientRuntime.managedRelay.registerDevice"),- withRelayClientTracing,- ),- unregisterDevice: Effect.fnUntraced(- function* (input) {- return yield* mobileRegistrationRequest(- {- clerkToken: input.clerkToken,- target: dpopProofTargets.unregisterDevice(input.deviceId),- },- (authorization) =>- client.mobile- .unregisterDevice({- headers: dpopHeaders(authorization),- params: { deviceId: input.deviceId },- })- .pipe(- Effect.mapError(relayRequestError("unregister relay mobile device")),- timeoutRelayRequest("Relay mobile device unregistration"),- ),- );- },- Effect.withSpan("clientRuntime.managedRelay.unregisterDevice"),- withRelayClientTracing,- ),- getAgentActivitySnapshot: Effect.fnUntraced(- function* (input) {- return yield* mobileRegistrationRequest(- {- clerkToken: input.clerkToken,- target: dpopProofTargets.getAgentActivitySnapshot(),- },- (authorization) =>- client.mobile- .getAgentActivitySnapshot({- headers: dpopHeaders(authorization),- })- .pipe(- Effect.mapError(relayRequestError("read relay agent activity snapshot")),- timeoutRelayRequest("Relay agent activity snapshot"),- ),- );- },- Effect.withSpan("clientRuntime.managedRelay.getAgentActivitySnapshot"),- withRelayClientTracing,- ),- registerLiveActivity: Effect.fnUntraced(- function* (input) {- return yield* mobileRegistrationRequest(- {- clerkToken: input.clerkToken,- target: dpopProofTargets.registerLiveActivity(),- },- (authorization) =>- client.mobile- .registerLiveActivity({- headers: dpopHeaders(authorization),- payload: input.payload,- })- .pipe(- Effect.mapError(relayRequestError("register relay live activity")),- timeoutRelayRequest("Relay Live Activity registration"),- ),- );- },- Effect.withSpan("clientRuntime.managedRelay.registerLiveActivity"),- withRelayClientTracing,- ),- resetTokenCache: SynchronizedRef.set(cachedTokens, []).pipe(- Effect.andThen(options.accessTokenStore ? options.accessTokenStore.clear : Effect.void),- Effect.withSpan("clientRuntime.managedRelay.resetTokenCache"),- withRelayClientTracing,- ),- });-});--export const layer = (options: ManagedRelayClientLayerOptions) =>- Layer.effect(ManagedRelayClient, make(options));diff --git a/packages/client-runtime/src/relay/managedRelayState.test.ts b/packages/client-runtime/src/relay/managedRelayState.test.tsdeleted file mode 100644index 00ac73376..000000000--- a/packages/client-runtime/src/relay/managedRelayState.test.ts+++ /dev/null@@ -1,424 +0,0 @@-import { EnvironmentId } from "@t3tools/contracts";-import type {- RelayClientDeviceRecord,- RelayClientEnvironmentRecord,- RelayEnvironmentStatusResponse,-} from "@t3tools/contracts/relay";-import { describe, expect, it } from "@effect/vitest";-import * as Effect from "effect/Effect";-import * as Fiber from "effect/Fiber";-import * as Layer from "effect/Layer";-import * as Stream from "effect/Stream";-import { Atom, AtomRegistry } from "effect/unstable/reactivity";-import { afterEach, vi } from "vite-plus/test";--import * as ManagedRelay from "./managedRelay.ts";-import {- createManagedRelayQueryManager,- createManagedRelaySession,- deregisterManagedRelayEnvironment,- managedRelayAccountChanges,- type ManagedRelayQueryEvent,- ManagedRelaySessionError,- managedRelaySessionAtom,- readManagedRelaySnapshotState,- setManagedRelaySession,- waitForManagedRelayClerkToken,-} from "./managedRelayState.ts";--let registry = AtomRegistry.make();--const environment = {- environmentId: EnvironmentId.make("environment-1"),- label: "Main environment",- endpoint: {- httpBaseUrl: "https://environment.example.test",- wsBaseUrl: "wss://environment.example.test",- providerKind: "cloudflare_tunnel",- },- linkedAt: "2026-06-01T00:00:00.000Z",-} satisfies RelayClientEnvironmentRecord;--const device = {- deviceId: "device-1",- label: "Julius iPhone",- platform: "ios",- iosMajorVersion: 18,- appVersion: null,- notifications: {- enabled: true,- notifyOnApproval: true,- notifyOnInput: true,- notifyOnCompletion: true,- notifyOnFailure: true,- },- liveActivities: {- enabled: true,- },- updatedAt: "2026-06-01T00:00:00.000Z",-} satisfies RelayClientDeviceRecord;--function resetRegistry() {- registry.dispose();- registry = AtomRegistry.make();-}--function createClient(overrides?: Partial<ManagedRelay.ManagedRelayClient["Service"]>) {- return ManagedRelay.ManagedRelayClient.of({- relayUrl: "https://relay.example.test",- listEnvironments: () => Effect.succeed([environment]),- listDevices: () => Effect.succeed([device]),- createEnvironmentLinkChallenge: () => Effect.die("unused"),- linkEnvironment: () => Effect.die("unused"),- unlinkEnvironment: () => Effect.die("unused"),- getEnvironmentStatus: () =>- Effect.succeed({- environmentId: environment.environmentId,- endpoint: environment.endpoint,- status: "online",- checkedAt: "2026-06-01T00:00:00.000Z",- }),- connectEnvironment: () => Effect.die("unused"),- registerDevice: () => Effect.die("unused"),- unregisterDevice: () => Effect.die("unused"),- registerLiveActivity: () => Effect.die("unused"),- getAgentActivitySnapshot: () => Effect.die("unused"),- resetTokenCache: Effect.void,- ...overrides,- });-}--function createManager(- overrides?: Partial<ManagedRelay.ManagedRelayClient["Service"]>,- onQueryEvent?: (event: ManagedRelayQueryEvent) => void,-) {- const client = createClient(overrides);- const runtime = Atom.runtime(Layer.succeed(ManagedRelay.ManagedRelayClient, client));- return createManagedRelayQueryManager(runtime, {- staleTimeMs: 60_000,- ...(onQueryEvent ? { onQueryEvent } : {}),- });-}--function setSession() {- setManagedRelaySession(registry, {- accountId: "account-1",- readClerkToken: () => Promise.resolve("clerk-token"),- });-}--function clerkToken(expiresAtSeconds: number): string {- const encode = (value: unknown) =>- btoa(JSON.stringify(value)).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/u, "");- return `${encode({ alg: "none" })}.${encode({ exp: expiresAtSeconds })}.signature`;-}--describe("createManagedRelayQueryManager", () => {- afterEach(resetRegistry);-- it.effect("waits for the current cloud session before reading its token", () =>- Effect.gen(function* () {- const tokenFiber = yield* waitForManagedRelayClerkToken(registry).pipe(Effect.forkChild);-- setSession();-- expect(yield* Fiber.join(tokenFiber)).toBe("clerk-token");- expect(registry.getNodes().get(managedRelaySessionAtom)?.listeners.size).toBe(0);- }),- );-- it.effect("deregisters an environment through the current Clerk session", () =>- Effect.gen(function* () {- const unlinkEnvironment = vi.fn(() => Effect.succeed({ ok: true }));- setSession();-- yield* deregisterManagedRelayEnvironment(registry, {- accountId: "account-1",- environmentId: environment.environmentId,- }).pipe(- Effect.provideService(ManagedRelay.ManagedRelayClient, createClient({ unlinkEnvironment })),- );-- expect(unlinkEnvironment).toHaveBeenCalledWith({- clerkToken: "clerk-token",- environmentId: environment.environmentId,- });- }),- );-- it.effect("rejects deregistration after the account changes", () =>- Effect.gen(function* () {- const unlinkEnvironment = vi.fn(() => Effect.succeed({ ok: true }));- setSession();-- const error = yield* deregisterManagedRelayEnvironment(registry, {- accountId: "previous-account",- environmentId: environment.environmentId,- }).pipe(- Effect.provideService(ManagedRelay.ManagedRelayClient, createClient({ unlinkEnvironment })),- Effect.flip,- );-- expect(error).toBeInstanceOf(ManagedRelaySessionError);- expect(unlinkEnvironment).not.toHaveBeenCalled();- }),- );-- it.effect("deduplicates concurrent Clerk token reads and reuses the token until JWT expiry", () =>- Effect.gen(function* () {- const token = clerkToken(4_102_444_800);- let resolveToken!: (value: string) => void;- const readClerkToken = vi.fn(- () =>- new Promise<string>((resolve) => {- resolveToken = resolve;- }),- );- const session = createManagedRelaySession({- accountId: "account-1",- readClerkToken,- });-- const readsFiber = yield* Effect.all([session.readClerkToken(), session.readClerkToken()], {- concurrency: "unbounded",- }).pipe(Effect.forkChild);- yield* Effect.yieldNow;- expect(readClerkToken).toHaveBeenCalledTimes(1);-- resolveToken(token);- expect(yield* Fiber.join(readsFiber)).toEqual([token, token]);- expect(yield* session.readClerkToken()).toBe(token);- expect(readClerkToken).toHaveBeenCalledTimes(1);- }),- );-- it.effect("updates the token provider without replacing a same-account session", () =>- Effect.gen(function* () {- const firstRead = vi.fn(() => Promise.resolve<string | null>(null));- setManagedRelaySession(registry, {- accountId: "account-1",- readClerkToken: firstRead,- });- const firstSession = registry.get(managedRelaySessionAtom);- expect(firstSession).not.toBeNull();- expect(yield* firstSession!.readClerkToken()).toBeNull();-- const secondRead = vi.fn(() => Promise.resolve<string | null>("refreshed-token"));- setManagedRelaySession(registry, {- accountId: "account-1",- readClerkToken: secondRead,- });-- expect(registry.get(managedRelaySessionAtom)).toBe(firstSession);- expect(yield* firstSession!.readClerkToken()).toBe("refreshed-token");- expect(firstRead).toHaveBeenCalledTimes(1);- expect(secondRead).toHaveBeenCalledTimes(1);- }),- );-- it.effect("does not pin a refreshed session to an older pending token read", () =>- Effect.gen(function* () {- let resolveFirst!: (token: string) => void;- setManagedRelaySession(registry, {- accountId: "account-1",- readClerkToken: () =>- new Promise<string>((resolve) => {- resolveFirst = resolve;- }),- });- const session = registry.get(managedRelaySessionAtom);- const firstRead = yield* session!.readClerkToken().pipe(Effect.forkChild);- yield* Effect.yieldNow;-- setManagedRelaySession(registry, {- accountId: "account-1",- readClerkToken: () => Promise.resolve("refreshed-token"),- });-- expect(yield* session!.readClerkToken()).toBe("refreshed-token");- resolveFirst("older-token");- expect(yield* Fiber.join(firstRead)).toBe("older-token");- }),- );-- it("emits credential changes only when the managed relay account changes", async () => {- setManagedRelaySession(registry, {- accountId: "account-1",- readClerkToken: () => Promise.resolve("first-token"),- });- const changes = Effect.runPromise(- managedRelayAccountChanges(registry).pipe(Stream.take(2), Stream.runCollect),- );- await vi.waitFor(() => {- expect(registry.getNodes().get(managedRelaySessionAtom)?.listeners.size).toBeGreaterThan(0);- });-- setManagedRelaySession(registry, {- accountId: "account-1",- readClerkToken: () => Promise.resolve("refreshed-token"),- });- setManagedRelaySession(registry, {- accountId: "account-2",- readClerkToken: () => Promise.resolve("second-token"),- });- setManagedRelaySession(registry, null);-- expect(Array.from(await changes)).toEqual(["account-2", null]);- });-- it("shares one Clerk token read across concurrent relay list and status queries", async () => {- const secondEnvironment = {- ...environment,- environmentId: EnvironmentId.make("environment-2"),- label: "Second environment",- endpoint: {- ...environment.endpoint,- httpBaseUrl: "https://environment-2.example.test",- wsBaseUrl: "wss://environment-2.example.test",- },- } satisfies RelayClientEnvironmentRecord;- const token = clerkToken(4_102_444_800);- const readClerkToken = vi.fn(() => Promise.resolve(token));- const manager = createManager({- listEnvironments: () => Effect.succeed([environment, secondEnvironment]),- getEnvironmentStatus: ({ environmentId }) => {- const current =- environmentId === environment.environmentId ? environment : secondEnvironment;- return Effect.succeed({- environmentId: current.environmentId,- endpoint: current.endpoint,- status: "online" as const,- checkedAt: "2026-06-01T00:00:00.000Z",- });- },- });- setManagedRelaySession(registry, {- accountId: "account-1",- readClerkToken,- });-- const environmentsAtom = manager.environmentsAtom("account-1");- const firstStatusAtom = manager.environmentStatusAtom({- accountId: "account-1",- environment,- });- const secondStatusAtom = manager.environmentStatusAtom({- accountId: "account-1",- environment: secondEnvironment,- });- registry.get(environmentsAtom);- registry.get(firstStatusAtom);- registry.get(secondStatusAtom);-- await vi.waitFor(() => {- expect(readManagedRelaySnapshotState(registry.get(firstStatusAtom)).data?.status).toBe(- "online",- );- expect(readManagedRelaySnapshotState(registry.get(secondStatusAtom)).data?.status).toBe(- "online",- );- });- expect(readClerkToken).toHaveBeenCalledTimes(1);- });-- it("keeps environment snapshots cached and refreshes them explicitly", async () => {- const listEnvironments = vi.fn(() => Effect.succeed([environment]));- const manager = createManager({ listEnvironments });- setSession();- const atom = manager.environmentsAtom("account-1");-- registry.get(atom);- await vi.waitFor(() => expect(listEnvironments).toHaveBeenCalledTimes(1));-- registry.get(manager.environmentsAtom("account-1"));- expect(listEnvironments).toHaveBeenCalledTimes(1);-- manager.refreshEnvironments(registry, "account-1");- await vi.waitFor(() => expect(listEnvironments).toHaveBeenCalledTimes(2));- });-- it("loads device snapshots through the current account session", async () => {- const listDevices = vi.fn(() => Effect.succeed([device]));- const manager = createManager({ listDevices });- setSession();- const atom = manager.devicesAtom("account-1");-- registry.get(atom);- await vi.waitFor(() => {- expect(readManagedRelaySnapshotState(registry.get(atom)).data).toEqual([device]);- });- });-- it("reports token and relay request phases for environment status queries", async () => {- const onQueryEvent = vi.fn();- const manager = createManager(undefined, onQueryEvent);- setSession();- const atom = manager.environmentStatusAtom({ accountId: "account-1", environment });-- registry.get(atom);- await vi.waitFor(() => {- expect(readManagedRelaySnapshotState(registry.get(atom)).data?.status).toBe("online");- });-- expect(onQueryEvent).toHaveBeenCalledWith({- operation: "environment-status",- stage: "clerk-token",- phase: "start",- accountId: "account-1",- environmentId: environment.environmentId,- });- expect(onQueryEvent).toHaveBeenCalledWith(- expect.objectContaining({- operation: "environment-status",- stage: "relay-request",- phase: "success",- accountId: "account-1",- environmentId: environment.environmentId,- }),- );- });-- it("rejects status responses for a different environment", async () => {- const mismatchedStatus = {- environmentId: EnvironmentId.make("environment-2"),- endpoint: environment.endpoint,- status: "online",- checkedAt: "2026-06-01T00:00:00.000Z",- } satisfies RelayEnvironmentStatusResponse;- const manager = createManager({- getEnvironmentStatus: () => Effect.succeed(mismatchedStatus),- });- setSession();- const atom = manager.environmentStatusAtom({ accountId: "account-1", environment });-- registry.get(atom);- await vi.waitFor(() => {- expect(readManagedRelaySnapshotState(registry.get(atom)).error).toBe(- "Relay returned status for a different environment.",- );- });- });-- it("exposes relay trace IDs alongside snapshot errors", async () => {- const manager = createManager({- getEnvironmentStatus: () =>- Effect.fail(- new ManagedRelay.ManagedRelayRequestFailedError({- action: "get relay environment status",- cause: new Error("Relay request failed."),- traceId: "trace-status",- }),- ),- });- setSession();- const atom = manager.environmentStatusAtom({ accountId: "account-1", environment });-- registry.get(atom);- await vi.waitFor(() => {- expect(readManagedRelaySnapshotState(registry.get(atom))).toMatchObject({- error: "Could not get relay environment status.",- errorTraceId: "trace-status",- });- });- });-});diff --git a/packages/client-runtime/src/relay/managedRelayState.ts b/packages/client-runtime/src/relay/managedRelayState.tsdeleted file mode 100644index eee3dcd34..000000000--- a/packages/client-runtime/src/relay/managedRelayState.ts+++ /dev/null@@ -1,469 +0,0 @@-import type {- RelayClientEnvironmentRecord,- RelayEnvironmentStatusResponse,-} from "@t3tools/contracts/relay";-import type { EnvironmentId } from "@t3tools/contracts";-import {- RelayEnvironmentConnectScope,- RelayEnvironmentStatusScope,-} from "@t3tools/contracts/relay";-import { decodeRelayJwt } from "@t3tools/shared/relayJwt";-import * as Cause from "effect/Cause";-import * as Clock from "effect/Clock";-import * as Data from "effect/Data";-import * as Effect from "effect/Effect";-import * as Option from "effect/Option";-import * as Stream from "effect/Stream";-import { AsyncResult, Atom, AtomRegistry } from "effect/unstable/reactivity";--import { findErrorTraceId } from "../errors/errorTrace.ts";-import * as ManagedRelay from "./managedRelay.ts";--const DEFAULT_STALE_TIME_MS = 15_000;-const DEFAULT_IDLE_TTL_MS = 5 * 60_000;-const CLERK_TOKEN_EXPIRY_SKEW_MS = 5_000;--export interface ManagedRelaySession {- readonly accountId: string;- readonly readClerkToken: () => Effect.Effect<string | null, ManagedRelaySessionError>;-}--export interface ManagedRelaySessionInput {- readonly accountId: string;- readonly readClerkToken: () => Promise<string | null>;-}--interface ManagedRelaySessionControl {- readonly updateReadClerkToken: (- readClerkToken: ManagedRelaySessionInput["readClerkToken"],- ) => void;-}--export interface ManagedRelaySnapshotState<A> {- readonly data: A | null;- readonly error: string | null;- readonly errorTraceId: string | null;- readonly isPending: boolean;-}--export interface ManagedRelayQueryEvent {- readonly operation: "environments" | "devices" | "environment-status";- readonly stage: "clerk-token" | "relay-request" | "validation";- readonly phase: "start" | "success" | "failure";- readonly accountId: string;- readonly environmentId?: string;- readonly message?: string;- readonly traceId?: string | null;-}--export class ManagedRelaySessionError extends Data.TaggedError("ManagedRelaySessionError")<{- readonly message: string;- readonly cause?: unknown;-}> {}--export class ManagedRelaySnapshotError extends Data.TaggedError("ManagedRelaySnapshotError")<{- readonly message: string;-}> {}--export const managedRelaySessionAtom = Atom.make<ManagedRelaySession | null>(null).pipe(- Atom.keepAlive,- Atom.withLabel("managed-relay:session"),-);--const managedRelaySessionControls = new WeakMap<ManagedRelaySession, ManagedRelaySessionControl>();--export function createManagedRelaySession(input: ManagedRelaySessionInput): ManagedRelaySession {- let cachedToken: { readonly token: string; readonly expiresAtMillis: number } | null = null;- let pendingToken: Promise<string | null> | null = null;- let readClerkToken = input.readClerkToken;- let tokenProviderGeneration = 0;-- const readCachedClerkToken = async (nowMillis: number): Promise<string | null> => {- if (cachedToken && cachedToken.expiresAtMillis > nowMillis + CLERK_TOKEN_EXPIRY_SKEW_MS) {- return cachedToken.token;- }- if (pendingToken) {- return await pendingToken;- }-- const operationGeneration = tokenProviderGeneration;- const operation = readClerkToken().then((token) => {- if (operationGeneration !== tokenProviderGeneration) {- return token;- }- if (!token) {- cachedToken = null;- return null;- }- try {- const expiresAtSeconds = decodeRelayJwt(token).exp;- cachedToken =- typeof expiresAtSeconds === "number"- ? { token, expiresAtMillis: expiresAtSeconds * 1_000 }- : null;- } catch {- cachedToken = null;- }- return token;- });- pendingToken = operation;- try {- return await operation;- } finally {- if (pendingToken === operation) {- pendingToken = null;- }- }- };-- const session: ManagedRelaySession = {- accountId: input.accountId,- readClerkToken: Effect.fn("clientRuntime.managedRelaySession.readClerkToken")(function* () {- const nowMillis = yield* Clock.currentTimeMillis;- return yield* Effect.tryPromise({- try: () => readCachedClerkToken(nowMillis),- catch: (cause) =>- new ManagedRelaySessionError({- message: "Could not obtain the relay session token.",- cause,- }),- });- }),- };- managedRelaySessionControls.set(session, {- updateReadClerkToken: (nextReadClerkToken) => {- readClerkToken = nextReadClerkToken;- tokenProviderGeneration += 1;- pendingToken = null;- },- });- return session;-}--export function setManagedRelaySession(- registry: AtomRegistry.AtomRegistry,- input: ManagedRelaySessionInput | null,-): void {- const current = registry.get(managedRelaySessionAtom);- if (input === null) {- if (current !== null) {- registry.set(managedRelaySessionAtom, null);- }- return;- }- if (current?.accountId === input.accountId) {- const control = managedRelaySessionControls.get(current);- if (control) {- // Clerk can replace its token reader during routine same-account refreshes.- // Keep the session stable so those refreshes do not invalidate queries or reconnect leases.- control.updateReadClerkToken(input.readClerkToken);- return;- }- }- registry.set(managedRelaySessionAtom, createManagedRelaySession(input));-}--export function managedRelayAccountChanges(- registry: AtomRegistry.AtomRegistry,-): Stream.Stream<string | null> {- return AtomRegistry.toStream(registry, managedRelaySessionAtom).pipe(- Stream.map((session) => session?.accountId ?? null),- Stream.changes,- Stream.drop(1),- );-}--function readSessionClerkToken(- session: ManagedRelaySession,-): Effect.Effect<string, ManagedRelaySessionError> {- return session.readClerkToken().pipe(- Effect.flatMap((token) =>- token- ? Effect.succeed(token)- : Effect.fail(- new ManagedRelaySessionError({- message: "The relay session token is unavailable.",- }),- ),- ),- );-}--export const waitForManagedRelayClerkToken = Effect.fn(- "clientRuntime.managedRelaySession.waitForClerkToken",-)(function* (registry: AtomRegistry.AtomRegistry) {- return yield* Effect.callback<string, ManagedRelaySessionError>((resume) => {- let unsubscribe: (() => void) | undefined;- let completed = false;- const readCurrentSession = () => {- if (completed) {- return true;- }- const session = registry.get(managedRelaySessionAtom);- if (!session) {- return false;- }- completed = true;- unsubscribe?.();- resume(readSessionClerkToken(session));- return true;- };-- if (readCurrentSession()) {- return;- }-- unsubscribe = registry.subscribe(managedRelaySessionAtom, readCurrentSession);- readCurrentSession();- return Effect.sync(() => unsubscribe?.());- });-});--/** Removes an environment from the signed-in account without contacting that environment. */-export const deregisterManagedRelayEnvironment = Effect.fn(- "clientRuntime.managedRelaySession.deregisterEnvironment",-)(function* (- registry: AtomRegistry.AtomRegistry,- input: { readonly accountId: string; readonly environmentId: EnvironmentId },-) {- const session = registry.get(managedRelaySessionAtom);- if (!session || session.accountId !== input.accountId) {- return yield* new ManagedRelaySessionError({- message: "Sign in before deregistering an environment.",- });- }- const clerkToken = yield* readSessionClerkToken(session);- const relay = yield* ManagedRelay.ManagedRelayClient;- yield* relay.unlinkEnvironment({ clerkToken, environmentId: input.environmentId });-});--function requireClerkToken(- get: Atom.AtomContext,- accountId: string,-): Effect.Effect<string, ManagedRelaySessionError> {- const session = get(managedRelaySessionAtom);- if (!session || session.accountId !== accountId) {- return Effect.fail(- new ManagedRelaySessionError({- message: "Sign in before loading relay data.",- }),- );- }- return readSessionClerkToken(session);-}--function statusKey(input: {- readonly accountId: string;- readonly environment: RelayClientEnvironmentRecord;-}): string {- return JSON.stringify(input);-}--function parseStatusKey(key: string): {- readonly accountId: string;- readonly environment: RelayClientEnvironmentRecord;-} {- return JSON.parse(key) as {- readonly accountId: string;- readonly environment: RelayClientEnvironmentRecord;- };-}--function endpointMatches(- left: RelayClientEnvironmentRecord["endpoint"],- right: RelayClientEnvironmentRecord["endpoint"],-): boolean {- return (- left.httpBaseUrl === right.httpBaseUrl &&- left.wsBaseUrl === right.wsBaseUrl &&- left.providerKind === right.providerKind- );-}--function validateEnvironmentStatus(- environment: RelayClientEnvironmentRecord,- status: RelayEnvironmentStatusResponse,-): Effect.Effect<RelayEnvironmentStatusResponse, ManagedRelaySnapshotError> {- if (status.environmentId !== environment.environmentId) {- return Effect.fail(- new ManagedRelaySnapshotError({- message: "Relay returned status for a different environment.",- }),- );- }- if (!endpointMatches(status.endpoint, environment.endpoint)) {- return Effect.fail(- new ManagedRelaySnapshotError({- message: "Relay returned status for a different endpoint.",- }),- );- }- if (status.descriptor && status.descriptor.environmentId !== environment.environmentId) {- return Effect.fail(- new ManagedRelaySnapshotError({- message: "Relay returned status descriptor for a different environment.",- }),- );- }- return Effect.succeed(status);-}--export function readManagedRelaySnapshotState<A>(- result: AsyncResult.AsyncResult<A, unknown>,-): ManagedRelaySnapshotState<A> {- let error: string | null = null;- let errorTraceId: string | null = null;- if (result._tag === "Failure") {- const cause = Cause.squash(result.cause);- error = cause instanceof Error ? cause.message : "Could not load relay data.";- errorTraceId = findErrorTraceId(cause);- }- return {- data: Option.getOrNull(AsyncResult.value(result)),- error,- errorTraceId,- isPending: result.waiting,- };-}--export function createManagedRelayQueryManager(- runtime: Atom.AtomRuntime<ManagedRelay.ManagedRelayClient>,- options?: {- readonly staleTimeMs?: number;- readonly idleTtlMs?: number;- readonly onQueryEvent?: (event: ManagedRelayQueryEvent) => void;- },-) {- const staleTime = options?.staleTimeMs ?? DEFAULT_STALE_TIME_MS;- const idleTtl = options?.idleTtlMs ?? DEFAULT_IDLE_TTL_MS;- const observe = <A, E, R>(- input: Omit<ManagedRelayQueryEvent, "phase" | "message" | "traceId">,- effect: Effect.Effect<A, E, R>,- ): Effect.Effect<A, E, R> =>- Effect.gen(function* () {- options?.onQueryEvent?.({ ...input, phase: "start" });- return yield* effect.pipe(- Effect.onExit((exit) =>- Effect.sync(() => {- if (exit._tag === "Success") {- options?.onQueryEvent?.({ ...input, phase: "success" });- return;- }- const error = Cause.squash(exit.cause);- options?.onQueryEvent?.({- ...input,- phase: "failure",- message: error instanceof Error ? error.message : String(error),- traceId: findErrorTraceId(error),- });- }),- ),- );- });-- const environmentsAtom = Atom.family((accountId: string) =>- runtime- .atom((get) =>- Effect.gen(function* () {- const base = { operation: "environments" as const, accountId };- const clerkToken = yield* observe(- { ...base, stage: "clerk-token" },- requireClerkToken(get, accountId),- );- const relay = yield* ManagedRelay.ManagedRelayClient;- return yield* observe(- { ...base, stage: "relay-request" },- relay.listEnvironments({ clerkToken }),- );- }),- )- .pipe(- Atom.swr({ staleTime, revalidateOnMount: true }),- Atom.setIdleTTL(idleTtl),- Atom.withLabel(`managed-relay:environments:${accountId}`),- ),- );-- const devicesAtom = Atom.family((accountId: string) =>- runtime- .atom((get) =>- Effect.gen(function* () {- const base = { operation: "devices" as const, accountId };- const clerkToken = yield* observe(- { ...base, stage: "clerk-token" },- requireClerkToken(get, accountId),- );- const relay = yield* ManagedRelay.ManagedRelayClient;- return yield* observe(- { ...base, stage: "relay-request" },- relay.listDevices({ clerkToken }),- );- }),- )- .pipe(- Atom.swr({ staleTime, revalidateOnMount: true }),- Atom.setIdleTTL(idleTtl),- Atom.withLabel(`managed-relay:devices:${accountId}`),- ),- );-- const environmentStatusAtom = Atom.family((key: string) => {- const { accountId, environment } = parseStatusKey(key);- return runtime- .atom((get) =>- Effect.gen(function* () {- const base = {- operation: "environment-status" as const,- accountId,- environmentId: environment.environmentId,- };- const clerkToken = yield* observe(- { ...base, stage: "clerk-token" },- requireClerkToken(get, accountId),- );- const relay = yield* ManagedRelay.ManagedRelayClient;- const status = yield* observe(- { ...base, stage: "relay-request" },- relay.getEnvironmentStatus({- clerkToken,- scopes: [RelayEnvironmentStatusScope, RelayEnvironmentConnectScope],- environmentId: environment.environmentId,- }),- );- return yield* observe(- { ...base, stage: "validation" },- validateEnvironmentStatus(environment, status),- );- }),- )- .pipe(- Atom.swr({ staleTime, revalidateOnMount: true }),- Atom.setIdleTTL(idleTtl),- Atom.withLabel(`managed-relay:environment-status:${key}`),- );- });-- return {- environmentsAtom,- devicesAtom,- environmentStatusAtom: (input: {- readonly accountId: string;- readonly environment: RelayClientEnvironmentRecord;- }) => environmentStatusAtom(statusKey(input)),- refreshEnvironments(registry: AtomRegistry.AtomRegistry, accountId: string): void {- registry.refresh(environmentsAtom(accountId));- },- refreshDevices(registry: AtomRegistry.AtomRegistry, accountId: string): void {- registry.refresh(devicesAtom(accountId));- },- refreshEnvironmentStatus(- registry: AtomRegistry.AtomRegistry,- input: {- readonly accountId: string;- readonly environment: RelayClientEnvironmentRecord;- },- ): void {- registry.refresh(environmentStatusAtom(statusKey(input)));- },- };-}diff --git a/packages/client-runtime/src/rpc/client.test.ts b/packages/client-runtime/src/rpc/client.test.tsindex 507d137ca..0284d20ff 100644--- a/packages/client-runtime/src/rpc/client.test.ts+++ b/packages/client-runtime/src/rpc/client.test.ts@@ -1,8 +1,4 @@-import {- EnvironmentId,- type RelayClientInstallProgressEvent,- WS_METHODS,-} from "@t3tools/contracts";+import { EnvironmentId, type ServerSelfUpdateProgressEvent, WS_METHODS } from "@t3tools/contracts";import { describe, expect, it } from "@effect/vitest";import * as Cause from "effect/Cause";import * as Effect from "effect/Effect";@@ -34,13 +30,13 @@ const TARGET = new PrimaryConnectionTarget({wsBaseUrl: "wss://environment.example.test",});-const INSTALL_CHECKING: RelayClientInstallProgressEvent = {+const UPDATE_DOWNLOADING: ServerSelfUpdateProgressEvent = {type: "progress",- stage: "checking",+ stage: "downloading",};-const INSTALL_DOWNLOADING: RelayClientInstallProgressEvent = {+const UPDATE_INSTALLING: ServerSelfUpdateProgressEvent = {type: "progress",- stage: "downloading",+ stage: "installing",};function session(client: WsRpcProtocolClient): RpcSession.RpcSession {@@ -81,13 +77,12 @@ describe("environment RPC", () => {Effect.gen(function* () {const observations: string[] = [];const client = {- [WS_METHODS.cloudGetRelayClientStatus]: () =>- Effect.succeed({ status: "available", version: "2026.6.0" }),+ [WS_METHODS.serverProbe]: () => Effect.succeed({}),} as unknown as WsRpcProtocolClient;const { activeSession, supervisor } = yield* makeHarness();yield* SubscriptionRef.set(activeSession, Option.some(session(client)));- const result = yield* request(WS_METHODS.cloudGetRelayClientStatus, {}).pipe(+ const result = yield* request(WS_METHODS.serverProbe, {}).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),Effect.provideService(EnvironmentRpcRequestObserver,@@ -103,28 +98,30 @@ describe("environment RPC", () => {),);- expect(result).toEqual({ status: "available", version: "2026.6.0" });+ expect(result).toEqual({});expect(observations).toEqual([- `start:${TARGET.environmentId}:${WS_METHODS.cloudGetRelayClientStatus}`,- `finish:${TARGET.environmentId}:${WS_METHODS.cloudGetRelayClientStatus}`,+ `start:${TARGET.environmentId}:${WS_METHODS.serverProbe}`,+ `finish:${TARGET.environmentId}:${WS_METHODS.serverProbe}`,]);}),);it.effect("binds finite streaming commands to one active session", () =>Effect.gen(function* () {- const firstEvents = yield* Queue.unbounded<RelayClientInstallProgressEvent>();- const secondEvents = yield* Queue.unbounded<RelayClientInstallProgressEvent>();+ const firstEvents = yield* Queue.unbounded<ServerSelfUpdateProgressEvent>();+ const secondEvents = yield* Queue.unbounded<ServerSelfUpdateProgressEvent>();const firstClient = {- [WS_METHODS.cloudInstallRelayClient]: () => Stream.fromQueue(firstEvents),+ [WS_METHODS.serverUpdateServerWithProgress]: () => Stream.fromQueue(firstEvents),} as unknown as WsRpcProtocolClient;const secondClient = {- [WS_METHODS.cloudInstallRelayClient]: () => Stream.fromQueue(secondEvents),+ [WS_METHODS.serverUpdateServerWithProgress]: () => Stream.fromQueue(secondEvents),} as unknown as WsRpcProtocolClient;const { activeSession, supervisor } = yield* makeHarness();yield* SubscriptionRef.set(activeSession, Option.some(session(firstClient)));- const resultFiber = yield* runStream(WS_METHODS.cloudInstallRelayClient, {}).pipe(+ const resultFiber = yield* runStream(WS_METHODS.serverUpdateServerWithProgress, {+ targetVersion: "1.2.3",+ }).pipe(Stream.take(2),Stream.runCollect,Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),@@ -132,12 +129,12 @@ describe("environment RPC", () => {);yield* Effect.yieldNow;- yield* Queue.offer(firstEvents, INSTALL_CHECKING);+ yield* Queue.offer(firstEvents, UPDATE_DOWNLOADING);yield* SubscriptionRef.set(activeSession, Option.some(session(secondClient)));- yield* Queue.offer(secondEvents, INSTALL_DOWNLOADING);- yield* Queue.offer(firstEvents, INSTALL_DOWNLOADING);+ yield* Queue.offer(secondEvents, UPDATE_INSTALLING);+ yield* Queue.offer(firstEvents, UPDATE_INSTALLING);- expect(yield* Fiber.join(resultFiber)).toEqual([INSTALL_CHECKING, INSTALL_DOWNLOADING]);+ expect(yield* Fiber.join(resultFiber)).toEqual([UPDATE_DOWNLOADING, UPDATE_INSTALLING]);}),);diff --git a/packages/client-runtime/src/rpc/client.ts b/packages/client-runtime/src/rpc/client.tsindex bfe57a6c0..c1d4cd549 100644--- a/packages/client-runtime/src/rpc/client.ts+++ b/packages/client-runtime/src/rpc/client.ts@@ -55,7 +55,6 @@ export type EnvironmentSubscriptionRpcTag =| typeof WS_METHODS.terminalAttach;export type EnvironmentStreamCommandRpcTag =- | typeof WS_METHODS.cloudInstallRelayClient| typeof WS_METHODS.serverUpdateServerWithProgress| typeof WS_METHODS.gitRunStackedAction;diff --git a/packages/client-runtime/src/rpc/http.ts b/packages/client-runtime/src/rpc/http.tsindex e52e01295..a1248e0db 100644--- a/packages/client-runtime/src/rpc/http.ts+++ b/packages/client-runtime/src/rpc/http.ts@@ -8,7 +8,6 @@ import {type EnvironmentResourceNotFoundError,type EnvironmentScopeRequiredError,} from "@t3tools/contracts";-import { httpHeaderRedactionLayer } from "@t3tools/shared/httpObservability";import * as Data from "effect/Data";import * as Duration from "effect/Duration";import * as Effect from "effect/Effect";@@ -81,10 +80,7 @@ export type RemoteEnvironmentRequestError =export const remoteHttpClientLayer = (fetchFn: typeof globalThis.fetch,): Layer.Layer<HttpClient.HttpClient> =>- Layer.merge(- FetchHttpClient.layer.pipe(Layer.provide(Layer.succeed(FetchHttpClient.Fetch, fetchFn))),- httpHeaderRedactionLayer,- );+ FetchHttpClient.layer.pipe(Layer.provide(Layer.succeed(FetchHttpClient.Fetch, fetchFn)));const remoteApiBaseUrl = (httpBaseUrl: string): string => {const url = new URL(httpBaseUrl);diff --git a/packages/client-runtime/src/state/connections.ts b/packages/client-runtime/src/state/connections.tsindex 6dfa5001a..ed59ecfe5 100644--- a/packages/client-runtime/src/state/connections.ts+++ b/packages/client-runtime/src/state/connections.ts@@ -97,15 +97,6 @@ export function createEnvironmentCatalogAtoms<R, E>(Effect.flatMap((registry) => registry.remove(environmentId)),),});- const removeRelayEnvironments = createRuntimeCommand(runtime, {- label: "environment-catalog:remove-relay-environments",- scheduler: commandScheduler,- concurrency: serial,- execute: (_input: void) =>- EnvironmentRegistry.EnvironmentRegistry.pipe(- Effect.flatMap((registry) => registry.removeRelayEnvironments()),- ),- });const retryNow = createRuntimeCommand(runtime, {label: "environment-catalog:retry-now",scheduler: commandScheduler,@@ -124,7 +115,6 @@ export function createEnvironmentCatalogAtoms<R, E>(stateAtom,register,remove,- removeRelayEnvironments,retryNow,};}diff --git a/packages/client-runtime/src/state/environmentHttpAuth.ts b/packages/client-runtime/src/state/environmentHttpAuth.tsindex 097708066..e064f0fa1 100644--- a/packages/client-runtime/src/state/environmentHttpAuth.ts+++ b/packages/client-runtime/src/state/environmentHttpAuth.ts@@ -1,20 +1,16 @@import * as Effect from "effect/Effect";-import * as Option from "effect/Option";-import { FetchHttpClient, type HttpMethod } from "effect/unstable/http";+import { FetchHttpClient } from "effect/unstable/http";import type { PreparedHttpAuthorization } from "../connection/model.ts";-import type { ManagedRelayDpopSigner } from "../relay/managedRelay.ts";-import { RemoteEnvironmentAuthFetchError } from "../rpc/http.ts";export interface EnvironmentHttpAuthHeaders {readonly authorization?: string;- readonly dpop?: string;}/**- * Primary/local environments with no bearer or DPoP credential authenticate the+ * Primary/local environments with no bearer credential authenticate the* browser via a session cookie. A cross-origin `fetch` does not send cookies by- * default, so those requests must opt into credentialed mode; bearer/DPoP+ * default, so those requests must opt into credentialed mode; bearer* connections carry their credential in a header and need no cookies. Applied* per-request via `FetchHttpClient.RequestInit`, which the fetch client reads* from the fiber context at request time.@@ -32,42 +28,8 @@ export const withEnvironmentCredentials = <A, E, R>(* request, matching the credential the connection was prepared with:* - primary/local connections carry no credential,* - bearer connections send a static `Bearer` token,- * - relay connections send a `DPoP` access token with a freshly signed proof- * bound to this request's method and URL.- *- * The DPoP signer is passed in (not resolved from context) and is only required- * for relay/DPoP connections, so bearer/primary connections work even when no- * signer is available.*/export const buildEnvironmentAuthHeaders = (authorization: PreparedHttpAuthorization | null,- method: HttpMethod.HttpMethod,- url: string,- signer: Option.Option<ManagedRelayDpopSigner["Service"]>,-): Effect.Effect<EnvironmentHttpAuthHeaders, RemoteEnvironmentAuthFetchError> =>- Effect.gen(function* () {- if (authorization === null) {- return {};- }- if (authorization._tag === "Bearer") {- return { authorization: `Bearer ${authorization.token}` };- }- if (Option.isNone(signer)) {- return yield* new RemoteEnvironmentAuthFetchError({- message: "No DPoP signer is available to authorize the environment request.",- cause: authorization._tag,- });- }- const proof = yield* signer.value- .createProof({ method, url, accessToken: authorization.accessToken })- .pipe(- Effect.mapError(- (cause) =>- new RemoteEnvironmentAuthFetchError({- message: "Could not create the environment request authorization proof.",- cause,- }),- ),- );- return { authorization: `DPoP ${authorization.accessToken}`, dpop: proof };- });+): Effect.Effect<EnvironmentHttpAuthHeaders> =>+ Effect.succeed(authorization === null ? {} : { authorization: `Bearer ${authorization.token}` });diff --git a/packages/client-runtime/src/state/relayDiscovery.ts b/packages/client-runtime/src/state/relayDiscovery.tsdeleted file mode 100644index bdf217d08..000000000--- a/packages/client-runtime/src/state/relayDiscovery.ts+++ /dev/null@@ -1,41 +0,0 @@-import * as Effect from "effect/Effect";-import * as Option from "effect/Option";-import * as Stream from "effect/Stream";-import * as SubscriptionRef from "effect/SubscriptionRef";-import { AsyncResult, Atom } from "effect/unstable/reactivity";--import * as RelayEnvironmentDiscovery from "../relay/discovery.ts";-import { createRuntimeCommand } from "./runtime.ts";--export function createRelayEnvironmentDiscoveryAtoms<R, E>(- runtime: Atom.AtomRuntime<RelayEnvironmentDiscovery.RelayEnvironmentDiscovery | R, E>,-) {- const stateAtom = runtime.atom(- Stream.unwrap(- RelayEnvironmentDiscovery.RelayEnvironmentDiscovery.pipe(- Effect.map((discovery) => SubscriptionRef.changes(discovery.state)),- ),- ),- { initialValue: RelayEnvironmentDiscovery.EMPTY_RELAY_ENVIRONMENT_DISCOVERY_STATE },- );- const stateValueAtom = Atom.make((get) =>- Option.getOrElse(- AsyncResult.value(get(stateAtom)),- () => RelayEnvironmentDiscovery.EMPTY_RELAY_ENVIRONMENT_DISCOVERY_STATE,- ),- ).pipe(Atom.withLabel("relay-environment-discovery-value"));- const refresh = createRuntimeCommand(runtime, {- label: "relay-environment-discovery:refresh",- concurrency: { mode: "singleFlight", key: () => "refresh" },- execute: (_input: void) =>- RelayEnvironmentDiscovery.RelayEnvironmentDiscovery.pipe(- Effect.flatMap((discovery) => discovery.refresh),- ),- });-- return {- stateAtom,- stateValueAtom,- refresh,- };-}diff --git a/packages/client-runtime/src/state/session.ts b/packages/client-runtime/src/state/session.tsindex 31fd297da..bc453c06b 100644--- a/packages/client-runtime/src/state/session.ts+++ b/packages/client-runtime/src/state/session.ts@@ -10,7 +10,6 @@ import { EnvironmentRegistry } from "../connection/registry.ts";import type { PreparedConnection } from "../connection/model.ts";import { EnvironmentSupervisor } from "../connection/supervisor.ts";import { environmentEndpointUrl } from "../environment/endpoint.ts";-import { ManagedRelayDpopSigner } from "../relay/managedRelay.ts";import { safeErrorLogAttributes } from "../errors/safeLog.ts";import { executeEnvironmentHttpRequest, makeEnvironmentHttpApiClient } from "../rpc/http.ts";import { buildEnvironmentAuthHeaders, withEnvironmentCredentials } from "./environmentHttpAuth.ts";@@ -37,23 +36,14 @@ const DEFAULT_SESSION_STATE_TIMEOUT_MS = 6_000;/*** Read the granted scopes of this client's session on one environment via its* `/api/auth/session` endpoint, authenticated with whatever credential the- * connection was prepared with (cookie, bearer, or DPoP).+ * connection was prepared with (cookie or bearer).*/export const fetchEnvironmentSessionState = Effect.fn("clientRuntime.state.fetchEnvironmentSessionState",-)(function* (input: {- readonly prepared: PreparedConnection;- readonly signer: Option.Option<ManagedRelayDpopSigner["Service"]>;- readonly timeoutMs?: number;-}) {+)(function* (input: { readonly prepared: PreparedConnection; readonly timeoutMs?: number }) {const requestUrl = environmentEndpointUrl(input.prepared.httpBaseUrl, "/api/auth/session");const client = yield* makeEnvironmentHttpApiClient(input.prepared.httpBaseUrl);- const headers = yield* buildEnvironmentAuthHeaders(- input.prepared.httpAuthorization,- "GET",- requestUrl,- input.signer,- );+ const headers = yield* buildEnvironmentAuthHeaders(input.prepared.httpAuthorization);return yield* executeEnvironmentHttpRequest(requestUrl,input.timeoutMs ?? DEFAULT_SESSION_STATE_TIMEOUT_MS,@@ -133,8 +123,7 @@ export function createEnvironmentSessionAtoms<R, E>(return Effect.never;}return Effect.gen(function* () {- const signer = yield* Effect.serviceOption(ManagedRelayDpopSigner);- return yield* fetchEnvironmentSessionState({ prepared, signer });+ return yield* fetchEnvironmentSessionState({ prepared });});}).pipe(diff --git a/packages/client-runtime/src/state/shellSnapshotHttp.ts b/packages/client-runtime/src/state/shellSnapshotHttp.tsindex b0a492a13..b642ffdf9 100644--- a/packages/client-runtime/src/state/shellSnapshotHttp.ts+++ b/packages/client-runtime/src/state/shellSnapshotHttp.ts@@ -8,7 +8,6 @@ import { HttpClient } from "effect/unstable/http";import type { PreparedConnection } from "../connection/model.ts";import { environmentEndpointUrl } from "../environment/endpoint.ts";-import { ManagedRelayDpopSigner } from "../relay/managedRelay.ts";import { executeEnvironmentHttpRequest, makeEnvironmentHttpApiClient } from "../rpc/http.ts";import { buildEnvironmentAuthHeaders, withEnvironmentCredentials } from "./environmentHttpAuth.ts";@@ -24,19 +23,10 @@ const DEFAULT_SHELL_SNAPSHOT_TIMEOUT_MS = 6_000;*/export const fetchEnvironmentShellSnapshot = Effect.fn("clientRuntime.state.fetchEnvironmentShellSnapshot",-)(function* (input: {- readonly prepared: PreparedConnection;- readonly signer: Option.Option<ManagedRelayDpopSigner["Service"]>;- readonly timeoutMs?: number;-}) {+)(function* (input: { readonly prepared: PreparedConnection; readonly timeoutMs?: number }) {const requestUrl = environmentEndpointUrl(input.prepared.httpBaseUrl, "/api/orchestration/shell");const client = yield* makeEnvironmentHttpApiClient(input.prepared.httpBaseUrl);- const headers = yield* buildEnvironmentAuthHeaders(- input.prepared.httpAuthorization,- "GET",- requestUrl,- input.signer,- );+ const headers = yield* buildEnvironmentAuthHeaders(input.prepared.httpAuthorization);return yield* executeEnvironmentHttpRequest(requestUrl,input.timeoutMs ?? DEFAULT_SHELL_SNAPSHOT_TIMEOUT_MS,@@ -50,7 +40,7 @@ export const fetchEnvironmentShellSnapshot = Effect.fn(/*** Loads the environment shell snapshot over HTTP, returning `Option.none()` when* it cannot be loaded (so the caller falls back to the socket-embedded snapshot).- * Decouples the shell state machine from the underlying HTTP + DPoP details and+ * Decouples the shell state machine from the underlying HTTP details and* keeps them out of test contexts.*/export class ShellSnapshotLoader extends Context.Service<@@ -70,12 +60,9 @@ export const shellSnapshotLoaderLayer: Layer.Layer<ShellSnapshotLoader,Effect.gen(function* () {const httpClient = yield* HttpClient.HttpClient;- // Resolve the DPoP signer optionally: it is only needed for relay/DPoP- // connections, so the loader must not hard-require it.- const signer = yield* Effect.serviceOption(ManagedRelayDpopSigner);return ShellSnapshotLoader.of({load: (prepared: PreparedConnection) =>- fetchEnvironmentShellSnapshot({ prepared, signer }).pipe(+ fetchEnvironmentShellSnapshot({ prepared }).pipe(Effect.map(Option.some<OrchestrationShellSnapshot>),Effect.provideService(HttpClient.HttpClient, httpClient),Effect.catchCause((cause) =>diff --git a/packages/client-runtime/src/state/threadSnapshotHttp.ts b/packages/client-runtime/src/state/threadSnapshotHttp.tsindex 6acc3b5d8..52c3f11e8 100644--- a/packages/client-runtime/src/state/threadSnapshotHttp.ts+++ b/packages/client-runtime/src/state/threadSnapshotHttp.ts@@ -8,7 +8,6 @@ import { HttpClient } from "effect/unstable/http";import type { PreparedConnection } from "../connection/model.ts";import { environmentEndpointUrl } from "../environment/endpoint.ts";-import { ManagedRelayDpopSigner } from "../relay/managedRelay.ts";import {executeEnvironmentHttpRequest,makeEnvironmentHttpApiClient,@@ -41,7 +40,6 @@ export const fetchEnvironmentThreadSnapshot = Effect.fn()(function* (input: {readonly prepared: PreparedConnection;readonly threadId: ThreadId;- readonly signer: Option.Option<ManagedRelayDpopSigner["Service"]>;readonly timeoutMs?: number;readonly window?: ThreadSnapshotWindow;}) {@@ -50,12 +48,7 @@ export const fetchEnvironmentThreadSnapshot = Effect.fn(`/api/orchestration/threads/${input.threadId}`,);const client = yield* makeEnvironmentHttpApiClient(input.prepared.httpBaseUrl);- const headers = yield* buildEnvironmentAuthHeaders(- input.prepared.httpAuthorization,- "GET",- requestUrl,- input.signer,- );+ const headers = yield* buildEnvironmentAuthHeaders(input.prepared.httpAuthorization);return yield* executeEnvironmentHttpRequest(requestUrl,input.timeoutMs ?? DEFAULT_THREAD_SNAPSHOT_TIMEOUT_MS,@@ -80,7 +73,7 @@ export type FetchEnvironmentThreadSnapshotError = RemoteEnvironmentRequestError;/*** Loads a thread's detail snapshot over HTTP, returning `Option.none()` when it* cannot be loaded (so the caller falls back to the socket-embedded snapshot).- * Decouples the thread state machine from the underlying HTTP + DPoP details and+ * Decouples the thread state machine from the underlying HTTP details and* keeps them out of test contexts.*/export class ThreadSnapshotLoader extends Context.Service<@@ -102,16 +95,11 @@ export const threadSnapshotLoaderLayer: Layer.Layer<ThreadSnapshotLoader,Effect.gen(function* () {const httpClient = yield* HttpClient.HttpClient;- // Resolve the DPoP signer optionally: it is only needed for relay/DPoP- // connections, so the loader must not hard-require it (bearer/primary- // connections work without one).- const signer = yield* Effect.serviceOption(ManagedRelayDpopSigner);return ThreadSnapshotLoader.of({load: (prepared: PreparedConnection, threadId: ThreadId, window?: ThreadSnapshotWindow) =>fetchEnvironmentThreadSnapshot({prepared,threadId,- signer,...(window !== undefined ? { window } : {}),}).pipe(Effect.map(Option.some<OrchestrationThreadDetailSnapshot>),diff --git a/packages/contracts/package.json b/packages/contracts/package.jsonindex f84242d71..85784538f 100644--- a/packages/contracts/package.json+++ b/packages/contracts/package.json@@ -14,10 +14,6 @@"./settings": {"types": "./src/settings.ts","import": "./src/settings.ts"- },- "./relay": {- "types": "./src/relay.ts",- "import": "./src/relay.ts"}},"scripts": {diff --git a/packages/contracts/src/akeruUsage.test.ts b/packages/contracts/src/akeruUsage.test.tsindex d9985840c..e31933d82 100644--- a/packages/contracts/src/akeruUsage.test.ts+++ b/packages/contracts/src/akeruUsage.test.ts@@ -2,7 +2,7 @@ import { assert, it } from "@effect/vitest";import * as Effect from "effect/Effect";import * as Schema from "effect/Schema";-import { AkeruBotUsageSnapshot } from "./akeruUsage.ts";+import { AkeruBotUsageSnapshot, AkeruStepUsageSnapshot } from "./akeruUsage.ts";it.effect("decodes bot usage with unavailable provider totals", () =>Effect.gen(function* () {@@ -26,3 +26,17 @@ it.effect("decodes bot usage with unavailable provider totals", () =>assert.strictEqual(snapshot.estimatedCost.status, "unavailable");}),);++it.effect("decodes settled step usage with an estimated cost", () =>+ Effect.gen(function* () {+ const snapshot = yield* Schema.decodeUnknownEffect(AkeruStepUsageSnapshot)({+ botId: "bot-1",+ engine: { provider: "codex", model: "gpt-5.6-sol" },+ tokens: 1_500,+ estimatedCost: { status: "available", usd: 0.42 },+ });++ assert.strictEqual(snapshot.tokens, 1_500);+ assert.deepStrictEqual(snapshot.estimatedCost, { status: "available", usd: 0.42 });+ }),+);diff --git a/packages/contracts/src/akeruUsage.ts b/packages/contracts/src/akeruUsage.tsindex 7f613bd2f..bf3d54ab3 100644--- a/packages/contracts/src/akeruUsage.ts+++ b/packages/contracts/src/akeruUsage.ts@@ -9,7 +9,7 @@ import {TurnId,} from "./baseSchemas.ts";import { ProviderDriverKind } from "./providerInstance.ts";-import { BotUsageCap } from "./orchestration.ts";+import { BotEngine, BotUsageCap } from "./orchestration.ts";export const AkeruUsageReservationId = TrimmedNonEmptyString.pipe(Schema.brand("AkeruUsageReservationId"),@@ -68,16 +68,27 @@ export type AkeruBotUsageSummary = typeof AkeruBotUsageSummary.Type;export const AkeruBotUsageInput = Schema.Struct({ botId: BotId });export type AkeruBotUsageInput = typeof AkeruBotUsageInput.Type;+export const AkeruEstimatedCost = Schema.Union([+ Schema.Struct({+ status: Schema.Literal("available"),+ usd: Schema.Number.check(Schema.isFinite(), Schema.isGreaterThanOrEqualTo(0)),+ }),+ Schema.Struct({ status: Schema.Literal("unavailable"), usd: Schema.Null }),+]);+export type AkeruEstimatedCost = typeof AkeruEstimatedCost.Type;++export const AkeruStepUsageSnapshot = Schema.Struct({+ botId: BotId,+ engine: BotEngine,+ tokens: Schema.NullOr(NonNegativeInt),+ estimatedCost: AkeruEstimatedCost,+});+export type AkeruStepUsageSnapshot = typeof AkeruStepUsageSnapshot.Type;+export const AkeruBotUsageSnapshot = Schema.Struct({...AkeruBotUsageSummary.fields,usageCap: Schema.NullOr(BotUsageCap),- estimatedCost: Schema.Union([- Schema.Struct({- status: Schema.Literal("available"),- usd: Schema.Number.check(Schema.isFinite(), Schema.isGreaterThanOrEqualTo(0)),- }),- Schema.Struct({ status: Schema.Literal("unavailable"), usd: Schema.Null }),- ]),+ estimatedCost: AkeruEstimatedCost,subscriptionPool: Schema.Union([Schema.Struct({status: Schema.Literal("available"),diff --git a/packages/contracts/src/analytics.test.ts b/packages/contracts/src/analytics.test.tsindex 15d26b0bf..2893e18fd 100644--- a/packages/contracts/src/analytics.test.ts+++ b/packages/contracts/src/analytics.test.ts@@ -55,6 +55,21 @@ describe("Usage3hEvent", () => {expect(USAGE_3H_COUNTER_KEYS).toHaveLength(96);});+ it("accepts current remote sandboxes and rejects the retired hosted sandbox", () => {+ for (const sandbox_provider of ["e2b", "daytona", "vercel", "upstash"] as const) {+ expect(+ decodeUsage3hEvent({+ ...event,+ properties: { ...event.properties, sandbox_provider },+ }).properties.sandbox_provider,+ ).toBe(sandbox_provider);+ }+ rejects({+ ...event,+ properties: { ...event.properties, sandbox_provider: "akeru-cloud" },+ });+ });+it("defaults queued events from before install tracking to zero", () => {const legacyProperties = Object.fromEntries(Object.entries(event.properties).filter(([key]) => key !== "new_installations"),diff --git a/packages/contracts/src/analytics.ts b/packages/contracts/src/analytics.tsindex 0b7d8814d..9775d0ffd 100644--- a/packages/contracts/src/analytics.ts+++ b/packages/contracts/src/analytics.ts@@ -173,8 +173,9 @@ export type UsageAnalyticsProvider = typeof UsageAnalyticsProvider.Type;export const UsageSandboxProvider = Schema.Literals(["none","local",+ "e2b",+ "daytona","vercel",- "akeru-cloud","upstash","mixed","other",diff --git a/packages/contracts/src/auth.ts b/packages/contracts/src/auth.tsindex a0d3d89b7..defb96e5d 100644--- a/packages/contracts/src/auth.ts+++ b/packages/contracts/src/auth.ts@@ -63,13 +63,10 @@ export type ServerAuthBootstrapMethod = typeof ServerAuthBootstrapMethod.Type;* app after bootstrap/pairing* - `bearer-access-token`: scoped token suitable for non-cookie or* non-browser clients- * - `dpop-access-token`: scoped proof-of-possession token used by managed- * relay connections*/export const ServerAuthSessionMethod = Schema.Literals(["browser-session-cookie","bearer-access-token",- "dpop-access-token",]);export type ServerAuthSessionMethod = typeof ServerAuthSessionMethod.Type;@@ -79,8 +76,6 @@ export const AuthTerminalOperateScope = "terminal:operate" as const;export const AuthReviewWriteScope = "review:write" as const;export const AuthAccessReadScope = "access:read" as const;export const AuthAccessWriteScope = "access:write" as const;-export const AuthRelayReadScope = "relay:read" as const;-export const AuthRelayWriteScope = "relay:write" as const;export const AuthEnvironmentScope = Schema.Literals([AuthOrchestrationReadScope,AuthOrchestrationOperateScope,@@ -88,8 +83,6 @@ export const AuthEnvironmentScope = Schema.Literals([AuthReviewWriteScope,AuthAccessReadScope,AuthAccessWriteScope,- AuthRelayReadScope,- AuthRelayWriteScope,]);export type AuthEnvironmentScope = typeof AuthEnvironmentScope.Type;export const AuthEnvironmentScopes = Schema.Array(AuthEnvironmentScope);@@ -100,13 +93,11 @@ export const AuthStandardClientScopes = [AuthOrchestrationOperateScope,AuthTerminalOperateScope,AuthReviewWriteScope,- AuthRelayReadScope,] as const;export const AuthAdministrativeScopes = [...AuthStandardClientScopes,AuthAccessReadScope,AuthAccessWriteScope,- AuthRelayWriteScope,] as const;export const AuthTokenExchangeGrantType =@@ -191,7 +182,7 @@ export type AuthTokenExchangeRequest = typeof AuthTokenExchangeRequest.Type;export const AuthAccessTokenResult = Schema.Struct({access_token: TrimmedNonEmptyString,issued_token_type: Schema.Literal(AuthAccessTokenType),- token_type: Schema.Literals(["Bearer", "DPoP"]),+ token_type: Schema.Literal("Bearer"),expires_in: Schema.Number,scope: TrimmedNonEmptyString,});diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.tsindex 939313e8c..f80575910 100644--- a/packages/contracts/src/environment.ts+++ b/packages/contracts/src/environment.ts@@ -78,12 +78,6 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({/** Server can stream self-update progress before acknowledging therestart. Clients fall back to server.updateServer when absent. */serverSelfUpdateProgress: Schema.optionalKey(Schema.Boolean),- /** Agent-activity publishes (push notifications and Live Activities)- currently leave this environment: the publish opt-in is enabled and the- relay link credentials exist. Clients skip seeding a Live Activity when- this is false — no update would ever repaint it. Absent on older- servers, which may still publish, so only an explicit false skips. */- agentActivityPublishing: Schema.optionalKey(Schema.Boolean),});export type ExecutionEnvironmentCapabilities = typeof ExecutionEnvironmentCapabilities.Type;diff --git a/packages/contracts/src/environmentHttp.ts b/packages/contracts/src/environmentHttp.tsindex 999825eef..cf4419272 100644--- a/packages/contracts/src/environmentHttp.ts+++ b/packages/contracts/src/environmentHttp.ts@@ -33,23 +33,9 @@ import {OrchestrationShellSnapshot,OrchestrationThreadDetailSnapshot,} from "./orchestration.ts";-import {- RelayCloudEnvironmentHealthRequest,- RelayCloudMintCredentialRequest,- RelayEnvironmentConfigRequest,- RelayEnvironmentHealthResponse,- RelayEnvironmentLinkProof,- RelayEnvironmentMintResponse,- RelayLinkProofRequest,-} from "./relay.ts";const OptionalBearerHeaders = Schema.Struct({authorization: Schema.optionalKey(Schema.String),- dpop: Schema.optionalKey(Schema.String),-});--const OptionalDpopProofHeaders = Schema.Struct({- dpop: Schema.optionalKey(Schema.String),});export const EnvironmentRequestInvalidReason = Schema.Literals([@@ -274,20 +260,6 @@ export class EnvironmentHttpConflictError extends Schema.TaggedErrorClass<Enviro}}-export class EnvironmentCloudEndpointUnavailableError extends Schema.TaggedErrorClass<EnvironmentCloudEndpointUnavailableError>()(- "EnvironmentCloudEndpointUnavailableError",- {- message: Schema.String,- endpointRuntimeStatus: Schema.Unknown,- },- { httpApiStatus: 503 },-) {- [HttpServerRespondable.symbol]() {- return HttpServerResponse.schemaJson(EnvironmentCloudEndpointUnavailableError)(this, {- status: 503,- });- }-}const EnvironmentSessionCreationErrors = [EnvironmentAuthInvalidError,EnvironmentInternalError,@@ -330,7 +302,6 @@ export interface EnvironmentSessionPrincipalShape {readonly subject: string;readonly method: ServerAuthSessionMethod;readonly scopes: ReadonlySet<AuthEnvironmentScope>;- readonly proofKeyThumbprint?: string;readonly expiresAt?: DateTime.DateTime;}@@ -346,40 +317,6 @@ export class EnvironmentAuthenticatedAuth extends HttpApiMiddleware.Service<error: EnvironmentAuthenticationErrors,}) {}-const EnvironmentHttpCloudErrors = [- EnvironmentHttpBadRequestError,- EnvironmentHttpUnauthorizedError,- EnvironmentHttpForbiddenError,- EnvironmentHttpConflictError,- EnvironmentHttpInternalServerError,- EnvironmentScopeRequiredError,-] as const;--export const EnvironmentCloudRelayConfigResult = Schema.Struct({- ok: Schema.Boolean,- endpointRuntimeStatus: Schema.Unknown,-});-export type EnvironmentCloudRelayConfigResult = typeof EnvironmentCloudRelayConfigResult.Type;--export const EnvironmentCloudLinkStateResult = Schema.Struct({- linked: Schema.Boolean,- cloudUserId: Schema.NullOr(Schema.String),- relayUrl: Schema.NullOr(Schema.String),- relayIssuer: Schema.NullOr(Schema.String),- // A managed Cloudflare tunnel is provisioned for this link. False for a- // publish-only link (activity publishing without a relay-managed tunnel), so- // clients can present the two capabilities as independent settings.- // Optional so newer clients tolerate older environment servers.- managedTunnelActive: Schema.optional(Schema.Boolean),- publishAgentActivity: Schema.Boolean,-});-export type EnvironmentCloudLinkStateResult = typeof EnvironmentCloudLinkStateResult.Type;--export const EnvironmentCloudPreferencesRequest = Schema.Struct({- publishAgentActivity: Schema.Boolean,-});-export type EnvironmentCloudPreferencesRequest = typeof EnvironmentCloudPreferencesRequest.Type;-export const AuthPairingLinkRevokeResult = Schema.Struct({revoked: Schema.Boolean,});@@ -418,7 +355,7 @@ export class EnvironmentAuthHttpApi extends HttpApiGroup.make("auth")).add(HttpApiEndpoint.post("token", "/oauth/token", {- headers: OptionalDpopProofHeaders,+ headers: OptionalBearerHeaders,payload: AuthTokenExchangeRequest,success: AuthAccessTokenResult,error: EnvironmentTokenExchangeErrors,@@ -524,69 +461,7 @@ export class EnvironmentOrchestrationHttpApi extends HttpApiGroup.make("orchestr}).middleware(EnvironmentAuthenticatedAuth),) {}-export class EnvironmentConnectHttpApi extends HttpApiGroup.make("connect")- .add(- HttpApiEndpoint.post("linkProof", "/api/connect/link-proof", {- headers: OptionalBearerHeaders,- payload: RelayLinkProofRequest,- success: RelayEnvironmentLinkProof,- error: EnvironmentHttpCloudErrors,- }).middleware(EnvironmentAuthenticatedAuth),- )- .add(- HttpApiEndpoint.post("relayConfig", "/api/connect/relay-config", {- headers: OptionalBearerHeaders,- payload: RelayEnvironmentConfigRequest,- success: EnvironmentCloudRelayConfigResult,- error: [...EnvironmentHttpCloudErrors, EnvironmentCloudEndpointUnavailableError],- }).middleware(EnvironmentAuthenticatedAuth),- )- .add(- HttpApiEndpoint.get("linkState", "/api/connect/link-state", {- headers: OptionalBearerHeaders,- success: EnvironmentCloudLinkStateResult,- error: EnvironmentHttpCloudErrors,- }).middleware(EnvironmentAuthenticatedAuth),- )- .add(- HttpApiEndpoint.post("unlink", "/api/connect/unlink", {- headers: OptionalBearerHeaders,- success: EnvironmentCloudRelayConfigResult,- error: EnvironmentHttpCloudErrors,- }).middleware(EnvironmentAuthenticatedAuth),- )- .add(- HttpApiEndpoint.post("preferences", "/api/connect/preferences", {- headers: OptionalBearerHeaders,- payload: EnvironmentCloudPreferencesRequest,- success: EnvironmentCloudLinkStateResult,- error: EnvironmentHttpCloudErrors,- }).middleware(EnvironmentAuthenticatedAuth),- )- .add(- HttpApiEndpoint.post("health", "/api/t3-connect/health", {- payload: RelayCloudEnvironmentHealthRequest,- success: RelayEnvironmentHealthResponse,- error: EnvironmentHttpCloudErrors,- }),- )- .add(- HttpApiEndpoint.post("mintCredential", "/api/connect/mint-credential", {- payload: RelayCloudMintCredentialRequest,- success: RelayEnvironmentMintResponse,- error: EnvironmentHttpCloudErrors,- }),- )- .add(- HttpApiEndpoint.post("t3MintCredential", "/api/t3-connect/mint-credential", {- payload: RelayCloudMintCredentialRequest,- success: RelayEnvironmentMintResponse,- error: EnvironmentHttpCloudErrors,- }),- ) {}-export class EnvironmentHttpApi extends HttpApi.make("environment").add(EnvironmentMetadataHttpApi).add(EnvironmentAuthHttpApi)- .add(EnvironmentOrchestrationHttpApi)- .add(EnvironmentConnectHttpApi) {}+ .add(EnvironmentOrchestrationHttpApi) {}diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.tsindex b9a10acf0..912f55d99 100644--- a/packages/contracts/src/index.ts+++ b/packages/contracts/src/index.ts@@ -9,7 +9,6 @@ export * from "./analytics.ts";export * from "./auth.ts";export * from "./environment.ts";export * from "./environmentHttp.ts";-export * from "./relayClient.ts";export * from "./desktopBootstrap.ts";export * from "./remoteAccess.ts";export * from "./ipc.ts";diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.tsindex e753596f3..7d135d47c 100644--- a/packages/contracts/src/ipc.ts+++ b/packages/contracts/src/ipc.ts@@ -176,12 +176,14 @@ export interface DesktopAppBranding {baseName: string;stageLabel: DesktopAppStageLabel;displayName: string;+ isPackaged: boolean;}export const DesktopAppBrandingSchema = Schema.Struct({baseName: Schema.String,stageLabel: DesktopAppStageLabelSchema,displayName: Schema.String,+ isPackaged: Schema.Boolean,});export interface DesktopRuntimeInfo {@@ -399,11 +401,6 @@ export const PersistedSavedEnvironmentRecordSchema = Schema.Struct({createdAt: Schema.String,lastConnectedAt: Schema.NullOr(Schema.String),desktopSsh: Schema.optionalKey(DesktopSshEnvironmentTargetSchema),- relayManaged: Schema.optionalKey(- Schema.Struct({- relayUrl: Schema.String,- }),- ),});export type PersistedSavedEnvironmentRecord = typeof PersistedSavedEnvironmentRecordSchema.Type;diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.tsindex 815d1777e..1ace69be3 100644--- a/packages/contracts/src/orchestration.ts+++ b/packages/contracts/src/orchestration.ts@@ -305,6 +305,19 @@ export type BotEngine = typeof BotEngine.Type;export const BotSandbox = Schema.Literals(["local", "e2b", "daytona", "vercel", "upstash"]);export type BotSandbox = typeof BotSandbox.Type;+export const PersistedBotSandbox = Schema.Union([+ Schema.NullOr(BotSandbox),+ Schema.Literal("akeru-cloud"),+]).pipe(+ Schema.decodeTo(+ Schema.NullOr(BotSandbox),+ SchemaTransformation.transform({+ decode: (value) => (value === "akeru-cloud" ? null : value),+ encode: (value) => value,+ }),+ ),+);+export const BotSandboxBrowserSharing = Schema.Literals(["shared", "separate"]);export type BotSandboxBrowserSharing = typeof BotSandboxBrowserSharing.Type;export const DEFAULT_BOT_SANDBOX_BROWSER_SHARING: BotSandboxBrowserSharing = "separate";@@ -328,7 +341,7 @@ export const OrchestrationBot = Schema.Struct({),avatar: BotAvatar,engine: Schema.NullOr(BotEngine),- sandbox: Schema.NullOr(BotSandbox),+ sandbox: PersistedBotSandbox,runtimeMode: RuntimeMode.pipe(Schema.withDecodingDefault(Effect.succeed(DEFAULT_RUNTIME_MODE))),usageCap: Schema.NullOr(BotUsageCap).pipe(Schema.withDecodingDefault(Effect.succeed(null))),voiceEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),@@ -1605,7 +1618,7 @@ export const BotCreatedPayload = Schema.Struct({),avatar: BotAvatar,engine: Schema.NullOr(BotEngine),- sandbox: Schema.NullOr(BotSandbox),+ sandbox: PersistedBotSandbox,runtimeMode: RuntimeMode.pipe(Schema.withDecodingDefault(Effect.succeed(DEFAULT_RUNTIME_MODE))),usageCap: Schema.NullOr(BotUsageCap).pipe(Schema.withDecodingDefault(Effect.succeed(null))),voiceEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),@@ -1623,7 +1636,7 @@ export const BotUpdatedPayload = Schema.Struct({disabledMcpServerIds: Schema.optional(Schema.Array(McpServerId)),avatar: Schema.optional(BotAvatar),engine: Schema.optional(Schema.NullOr(BotEngine)),- sandbox: Schema.optional(Schema.NullOr(BotSandbox)),+ sandbox: Schema.optional(PersistedBotSandbox),runtimeMode: Schema.optional(RuntimeMode),usageCap: Schema.optional(Schema.NullOr(BotUsageCap)),voiceEnabled: Schema.optional(Schema.Boolean),diff --git a/packages/contracts/src/portability.ts b/packages/contracts/src/portability.tsindex c0c1cf4b6..27d6a9476 100644--- a/packages/contracts/src/portability.ts+++ b/packages/contracts/src/portability.ts@@ -17,8 +17,8 @@ import { McpServerConfiguration, McpServerId } from "./mcpServer.ts";import {BotAvatar,BotEngine,- BotSandbox,BotSandboxBrowserSharing,+ PersistedBotSandbox,BotUsageCap,GroupMembership,ModelSelection,@@ -89,7 +89,7 @@ export const PortabilityBotData = Schema.Struct({disabledMcpServerIds: Schema.Array(McpServerId),avatar: BotAvatar,engine: Schema.NullOr(BotEngine),- sandbox: Schema.NullOr(BotSandbox),+ sandbox: PersistedBotSandbox,runtimeMode: RuntimeMode,usageCap: Schema.NullOr(BotUsageCap),voiceEnabled: Schema.Boolean,@@ -175,6 +175,10 @@ export const PortabilityThreadData = Schema.Struct({requestKind: Schema.optional(TrimmedNonEmptyString),requestType: Schema.optional(TrimmedNonEmptyString),decision: Schema.optional(TrimmedNonEmptyString),+ actor: Schema.optional(TrimmedNonEmptyString),+ target: Schema.optional(TrimmedNonEmptyString),+ action: Schema.optional(TrimmedNonEmptyString),+ outcome: Schema.optional(TrimmedNonEmptyString),provider: TrimmedNonEmptyString,createdAt: IsoDateTime,}),diff --git a/packages/contracts/src/providerRuntime.ts b/packages/contracts/src/providerRuntime.tsindex f052e75d9..c64e1a971 100644--- a/packages/contracts/src/providerRuntime.ts+++ b/packages/contracts/src/providerRuntime.ts@@ -438,6 +438,8 @@ export type ContentDeltaPayload = typeof ContentDeltaPayload.Type;const RequestOpenedPayload = Schema.Struct({requestType: CanonicalRequestType,detail: Schema.optional(TrimmedNonEmptyStringSchema),+ actor: Schema.optional(TrimmedNonEmptyStringSchema),+ target: Schema.optional(TrimmedNonEmptyStringSchema),appName: Schema.optional(TrimmedNonEmptyStringSchema),options: Schema.optional(Schema.Array(ProviderApprovalOption)),toolName: Schema.optional(TrimmedNonEmptyStringSchema),@@ -451,6 +453,10 @@ export type RequestOpenedPayload = typeof RequestOpenedPayload.Type;const RequestResolvedPayload = Schema.Struct({requestType: CanonicalRequestType,decision: Schema.optional(TrimmedNonEmptyStringSchema),+ actor: Schema.optional(TrimmedNonEmptyStringSchema),+ target: Schema.optional(TrimmedNonEmptyStringSchema),+ action: Schema.optional(TrimmedNonEmptyStringSchema),+ outcome: Schema.optional(TrimmedNonEmptyStringSchema),resolution: Schema.optional(Schema.Unknown),});export type RequestResolvedPayload = typeof RequestResolvedPayload.Type;diff --git a/packages/contracts/src/relay.test.ts b/packages/contracts/src/relay.test.tsdeleted file mode 100644index 4ad600953..000000000--- a/packages/contracts/src/relay.test.ts+++ /dev/null@@ -1,16 +0,0 @@-import { describe, expect, it } from "vite-plus/test";-import * as OpenApi from "effect/unstable/httpapi/OpenApi";--import { RelayApi } from "./relay.ts";--describe("RelayApi security", () => {- it("describes DPoP access tokens using the HTTP DPoP authorization scheme", () => {- const document = OpenApi.fromApi(RelayApi);-- expect(document.components.securitySchemes?.relayDpop).toEqual({- type: "http",- scheme: "DPoP",- description: "DPoP-bound access token. Requests must also include the DPoP proof JWT header.",- });- });-});diff --git a/packages/contracts/src/relay.ts b/packages/contracts/src/relay.tsdeleted file mode 100644index 52f7d7d43..000000000--- a/packages/contracts/src/relay.ts+++ /dev/null@@ -1,1089 +0,0 @@-import * as Context from "effect/Context";-import * as Schema from "effect/Schema";-import * as HttpApi from "effect/unstable/httpapi/HttpApi";-import * as HttpApiEndpoint from "effect/unstable/httpapi/HttpApiEndpoint";-import * as HttpApiGroup from "effect/unstable/httpapi/HttpApiGroup";-import * as HttpApiMiddleware from "effect/unstable/httpapi/HttpApiMiddleware";-import * as HttpApiSchema from "effect/unstable/httpapi/HttpApiSchema";-import * as HttpApiSecurity from "effect/unstable/httpapi/HttpApiSecurity";-import * as OpenApi from "effect/unstable/httpapi/OpenApi";--import { EnvironmentId, ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts";-import { ExecutionEnvironmentDescriptor } from "./environment.ts";--export const RelayAgentAwarenessPlatform = Schema.Literal("ios");-export type RelayAgentAwarenessPlatform = typeof RelayAgentAwarenessPlatform.Type;--export const RelayAgentAwarenessPhase = Schema.Literals([- "starting",- "running",- "waiting_for_approval",- "waiting_for_input",- "completed",- "failed",- "stale",-]);-export type RelayAgentAwarenessPhase = typeof RelayAgentAwarenessPhase.Type;--export const RelayAgentAwarenessPreferences = Schema.Struct({- liveActivitiesEnabled: Schema.Boolean,- notificationsEnabled: Schema.Boolean,- notifyOnApproval: Schema.Boolean,- notifyOnInput: Schema.Boolean,- notifyOnCompletion: Schema.Boolean,- notifyOnFailure: Schema.Boolean,-});-export type RelayAgentAwarenessPreferences = typeof RelayAgentAwarenessPreferences.Type;--export const RelayApnsEnvironment = Schema.Literals(["sandbox", "production"]);-export type RelayApnsEnvironment = typeof RelayApnsEnvironment.Type;--export const RelayDeviceRegistrationRequest = Schema.Struct({- deviceId: TrimmedNonEmptyString,- label: TrimmedNonEmptyString,- platform: RelayAgentAwarenessPlatform,- iosMajorVersion: Schema.Int.check(Schema.isGreaterThanOrEqualTo(18)),- appVersion: Schema.optional(TrimmedNonEmptyString),- // APNs routing for this install: the topic must match the app's bundle id- // (dev/preview/prod variants differ) and development-signed builds receive- // sandbox tokens. Optional so older app builds keep registering; the relay- // falls back to its configured defaults.- bundleId: Schema.optional(TrimmedNonEmptyString),- apsEnvironment: Schema.optional(RelayApnsEnvironment),- pushToken: Schema.optional(TrimmedNonEmptyString),- pushToStartToken: Schema.optional(TrimmedNonEmptyString),- preferences: RelayAgentAwarenessPreferences,-});-export type RelayDeviceRegistrationRequest = typeof RelayDeviceRegistrationRequest.Type;--export const RelayClientDeviceRecord = Schema.Struct({- deviceId: TrimmedNonEmptyString,- label: TrimmedNonEmptyString,- platform: RelayAgentAwarenessPlatform,- iosMajorVersion: Schema.Int.check(Schema.isGreaterThanOrEqualTo(18)),- appVersion: Schema.NullOr(TrimmedNonEmptyString),- notifications: Schema.Struct({- enabled: Schema.Boolean,- notifyOnApproval: Schema.Boolean,- notifyOnInput: Schema.Boolean,- notifyOnCompletion: Schema.Boolean,- notifyOnFailure: Schema.Boolean,- }),- liveActivities: Schema.Struct({- enabled: Schema.Boolean,- }),- updatedAt: TrimmedNonEmptyString,-});-export type RelayClientDeviceRecord = typeof RelayClientDeviceRecord.Type;--export const RelayListDevicesResponse = Schema.Struct({- devices: Schema.Array(RelayClientDeviceRecord),-});-export type RelayListDevicesResponse = typeof RelayListDevicesResponse.Type;--export const RelayLiveActivityRegistrationRequest = Schema.Struct({- deviceId: TrimmedNonEmptyString,- activityPushToken: TrimmedNonEmptyString,-});-export type RelayLiveActivityRegistrationRequest = typeof RelayLiveActivityRegistrationRequest.Type;--export const RelayDeviceUnregistrationParams = Schema.Struct({- deviceId: TrimmedNonEmptyString,-});-export type RelayDeviceUnregistrationParams = typeof RelayDeviceUnregistrationParams.Type;--export const RelayAgentActivityState = Schema.Struct({- environmentId: EnvironmentId,- threadId: ThreadId,- projectTitle: TrimmedNonEmptyString,- threadTitle: TrimmedNonEmptyString,- phase: RelayAgentAwarenessPhase,- headline: TrimmedNonEmptyString,- detail: Schema.optional(TrimmedNonEmptyString),- modelTitle: TrimmedNonEmptyString,- updatedAt: TrimmedNonEmptyString,- deepLink: TrimmedNonEmptyString,-});-export type RelayAgentActivityState = typeof RelayAgentActivityState.Type;--export const RelayAgentActivityAggregateRow = Schema.Struct({- environmentId: EnvironmentId,- threadId: ThreadId,- projectTitle: TrimmedNonEmptyString,- threadTitle: TrimmedNonEmptyString,- modelTitle: TrimmedNonEmptyString,- phase: RelayAgentAwarenessPhase,- status: TrimmedNonEmptyString,- updatedAt: TrimmedNonEmptyString,- deepLink: TrimmedNonEmptyString,-});-export type RelayAgentActivityAggregateRow = typeof RelayAgentActivityAggregateRow.Type;--export const RelayAgentActivityAggregateState = Schema.Struct({- title: TrimmedNonEmptyString,- subtitle: TrimmedNonEmptyString,- activeCount: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),- updatedAt: TrimmedNonEmptyString,- activities: Schema.Array(RelayAgentActivityAggregateRow),-});-export type RelayAgentActivityAggregateState = typeof RelayAgentActivityAggregateState.Type;--export const RelayManagedEndpointProviderKind = Schema.Literals([- "manual",- "cloudflare_tunnel",- "t3_relay",-]);-export type RelayManagedEndpointProviderKind = typeof RelayManagedEndpointProviderKind.Type;--export const RelayManagedEndpoint = Schema.Struct({- httpBaseUrl: TrimmedNonEmptyString,- wsBaseUrl: TrimmedNonEmptyString,- providerKind: RelayManagedEndpointProviderKind,-});-export type RelayManagedEndpoint = typeof RelayManagedEndpoint.Type;--export const RelayManagedEndpointOrigin = Schema.Struct({- localHttpHost: TrimmedNonEmptyString,- localHttpPort: Schema.Int.check(- Schema.isGreaterThanOrEqualTo(1),- Schema.isLessThanOrEqualTo(65_535),- ),-});-export type RelayManagedEndpointOrigin = typeof RelayManagedEndpointOrigin.Type;--export const RelayManagedEndpointRuntimeConfig = Schema.Struct({- providerKind: RelayManagedEndpointProviderKind,- connectorToken: TrimmedNonEmptyString,- tunnelId: Schema.optional(TrimmedNonEmptyString),- tunnelName: Schema.optional(TrimmedNonEmptyString),-});-export type RelayManagedEndpointRuntimeConfig = typeof RelayManagedEndpointRuntimeConfig.Type;--export const RelayLinkProofRequest = Schema.Struct({- challenge: Schema.String,- relayIssuer: Schema.String,- endpoint: RelayManagedEndpoint,- origin: RelayManagedEndpointOrigin,-});-export type RelayLinkProofRequest = typeof RelayLinkProofRequest.Type;--export const RelayEnvironmentConfigRequest = Schema.Struct({- relayUrl: Schema.String,- relayIssuer: Schema.optional(Schema.String),- cloudUserId: Schema.String,- environmentCredential: Schema.String,- cloudMintPublicKey: Schema.String,- endpointRuntime: Schema.NullOr(RelayManagedEndpointRuntimeConfig),-});-export type RelayEnvironmentConfigRequest = typeof RelayEnvironmentConfigRequest.Type;--const RelaySignedJwtRegisteredClaims = {- iss: TrimmedNonEmptyString,- aud: TrimmedNonEmptyString,- sub: TrimmedNonEmptyString,- jti: TrimmedNonEmptyString,- iat: Schema.Int,- exp: Schema.Int,-} as const;--export const RelayAgentActivityPublishProofPayload = Schema.Struct({- ...RelaySignedJwtRegisteredClaims,- environmentId: EnvironmentId,- threadId: ThreadId,- state: Schema.NullOr(RelayAgentActivityState),-});-export type RelayAgentActivityPublishProofPayload =- typeof RelayAgentActivityPublishProofPayload.Type;-export type RelayAgentActivityPublishProof = string;--export const RelayAgentActivityPublishRequest = Schema.Struct({- state: Schema.NullOr(RelayAgentActivityState).annotate({- description: "Current agent-awareness state, or null to remove the published state.",- }),- proof: TrimmedNonEmptyString.annotate({- description: "Environment-signed JWT covering this published activity state.",- }),-}).annotate({ description: "Publishes a signed agent-awareness update from an environment." });-export type RelayAgentActivityPublishRequest = typeof RelayAgentActivityPublishRequest.Type;--export const RelayEnvironmentLinkScope = Schema.Literals([- "agent_activity_notifications",- "managed_tunnels",-]);-export type RelayEnvironmentLinkScope = typeof RelayEnvironmentLinkScope.Type;--export const RelayEnvironmentLinkProofPayload = Schema.Struct({- ...RelaySignedJwtRegisteredClaims,- challenge: TrimmedNonEmptyString,- descriptor: ExecutionEnvironmentDescriptor,- environmentId: EnvironmentId,- environmentPublicKey: TrimmedNonEmptyString,- endpoint: RelayManagedEndpoint,- origin: RelayManagedEndpointOrigin,- scopes: Schema.Array(RelayEnvironmentLinkScope),-});-export type RelayEnvironmentLinkProofPayload = typeof RelayEnvironmentLinkProofPayload.Type;--export const RelayEnvironmentLinkProof = TrimmedNonEmptyString;-export type RelayEnvironmentLinkProof = typeof RelayEnvironmentLinkProof.Type;--export const RelayEnvironmentLinkChallengeRequest = Schema.Struct({- notificationsEnabled: Schema.Boolean.annotate({- description: "Whether this link may deliver push notifications.",- }),- liveActivitiesEnabled: Schema.Boolean.annotate({- description: "Whether this link may update Live Activities.",- }),- managedTunnelsEnabled: Schema.Boolean.annotate({- description: "Whether the relay should provision a managed tunnel for this environment.",- }),-}).annotate({ description: "Requested capabilities for a new environment-link challenge." });-export type RelayEnvironmentLinkChallengeRequest = typeof RelayEnvironmentLinkChallengeRequest.Type;--export const RelayEnvironmentLinkChallengeResponse = Schema.Struct({- challenge: TrimmedNonEmptyString,- expiresAt: TrimmedNonEmptyString,-});-export type RelayEnvironmentLinkChallengeResponse =- typeof RelayEnvironmentLinkChallengeResponse.Type;--export const RelayEnvironmentLinkRequest = Schema.Struct({- deviceId: Schema.optional(- TrimmedNonEmptyString.annotate({- description: "Optional client device identifier associated with this link.",- }),- ),- proof: RelayEnvironmentLinkProof.annotate({- description: "Environment-signed proof bound to a previously issued link challenge.",- }),- notificationsEnabled: Schema.Boolean,- liveActivitiesEnabled: Schema.Boolean,- managedTunnelsEnabled: Schema.Boolean,-}).annotate({ description: "Links an authenticated cloud user to a T3 environment." });-export type RelayEnvironmentLinkRequest = typeof RelayEnvironmentLinkRequest.Type;--export const RelayEnvironmentLinkResponse = Schema.Struct({- ok: Schema.Boolean,- cloudUserId: TrimmedNonEmptyString,- environmentId: EnvironmentId,- endpoint: RelayManagedEndpoint,- endpointRuntime: Schema.NullOr(RelayManagedEndpointRuntimeConfig),- relayIssuer: TrimmedNonEmptyString,- environmentCredential: TrimmedNonEmptyString,- cloudMintPublicKey: TrimmedNonEmptyString,-});-export type RelayEnvironmentLinkResponse = typeof RelayEnvironmentLinkResponse.Type;--export const RelayEnvironmentLinkProofInvalidReason = Schema.Literals([- "invalid_signature_or_scope",- "descriptor_mismatch",- "replayed_nonce",- "challenge_invalid",- "origin_not_allowed",- "endpoint_not_secure",-]);-export type RelayEnvironmentLinkProofInvalidReason =- typeof RelayEnvironmentLinkProofInvalidReason.Type;--export const RelayEnvironmentLinkFailedReason = Schema.Literals([- "link_persistence_failed",- "credential_persistence_failed",- "replay_persistence_failed",- "internal_error",-]);-export type RelayEnvironmentLinkFailedReason = typeof RelayEnvironmentLinkFailedReason.Type;--export const RelayEnvironmentLinkUnavailableReason = Schema.Literals([- "managed_endpoint_not_configured",- "managed_endpoint_provisioning_failed",-]);-export type RelayEnvironmentLinkUnavailableReason =- typeof RelayEnvironmentLinkUnavailableReason.Type;--export const RelayEnvironmentEndpointUnavailableReason = Schema.Literals([- "endpoint_request_failed",- "endpoint_response_invalid",-]);-export type RelayEnvironmentEndpointUnavailableReason =- typeof RelayEnvironmentEndpointUnavailableReason.Type;--export const RelayAgentActivityPublishProofInvalidReason = Schema.Literals([- "invalid_signature_or_payload",- "replayed_nonce",-]);-export type RelayAgentActivityPublishProofInvalidReason =- typeof RelayAgentActivityPublishProofInvalidReason.Type;--export const RelayAuthInvalidReason = Schema.Literals([- "missing_bearer",- "invalid_bearer",- "invalid_dpop",- "not_authorized",-]);-export type RelayAuthInvalidReason = typeof RelayAuthInvalidReason.Type;--export const RelayInternalErrorReason = Schema.Literals([- "database_unavailable",- "persistence_failed",- "upstream_unavailable",- "internal_error",-]);-export type RelayInternalErrorReason = typeof RelayInternalErrorReason.Type;--export class RelayAuthInvalidError extends Schema.TaggedErrorClass<RelayAuthInvalidError>()(- "RelayAuthInvalidError",- {- code: Schema.Literal("auth_invalid"),- reason: RelayAuthInvalidReason,- traceId: TrimmedNonEmptyString,- },- { httpApiStatus: 401 },-) {- override get message(): string {- return `Relay authentication failed: ${this.reason}`;- }-}--export class RelayEnvironmentLinkProofExpiredError extends Schema.TaggedErrorClass<RelayEnvironmentLinkProofExpiredError>()(- "RelayEnvironmentLinkProofExpiredError",- {- code: Schema.Literal("environment_link_proof_expired"),- traceId: TrimmedNonEmptyString,- },- { httpApiStatus: 401 },-) {- override get message(): string {- return "Relay environment link proof expired";- }-}--export class RelayEnvironmentLinkProofInvalidError extends Schema.TaggedErrorClass<RelayEnvironmentLinkProofInvalidError>()(- "RelayEnvironmentLinkProofInvalidError",- {- code: Schema.Literal("environment_link_proof_invalid"),- reason: RelayEnvironmentLinkProofInvalidReason,- traceId: TrimmedNonEmptyString,- },- { httpApiStatus: 400 },-) {- override get message(): string {- return `Relay environment link proof is invalid: ${this.reason}`;- }-}--export const RelayEnvironmentConnectNotAuthorizedReason = Schema.Literals([- "client_proof_key_thumbprint_missing",- "environment_link_not_found",- "endpoint_provider_not_managed",- "managed_endpoint_allocation_not_found",- "managed_endpoint_base_domain_not_configured",- "managed_endpoint_allocation_not_ready",- "managed_endpoint_hostname_invalid",- "managed_endpoint_mismatch",-]);-export type RelayEnvironmentConnectNotAuthorizedReason =- typeof RelayEnvironmentConnectNotAuthorizedReason.Type;--export class RelayEnvironmentConnectNotAuthorizedError extends Schema.TaggedErrorClass<RelayEnvironmentConnectNotAuthorizedError>()(- "RelayEnvironmentConnectNotAuthorizedError",- {- code: Schema.Literal("environment_connect_not_authorized"),- // Optional so responses from relays deployed before the reason was- // threaded through still decode.- reason: Schema.optional(RelayEnvironmentConnectNotAuthorizedReason),- traceId: TrimmedNonEmptyString,- },- { httpApiStatus: 403 },-) {- override get message(): string {- return this.reason- ? `Relay environment connection is not authorized: ${this.reason}`- : "Relay environment connection is not authorized";- }-}--export class RelayEnvironmentEndpointUnavailableError extends Schema.TaggedErrorClass<RelayEnvironmentEndpointUnavailableError>()(- "RelayEnvironmentEndpointUnavailableError",- {- code: Schema.Literal("environment_endpoint_unavailable"),- reason: RelayEnvironmentEndpointUnavailableReason,- traceId: TrimmedNonEmptyString,- },- { httpApiStatus: 502 },-) {- override get message(): string {- return `Relay environment endpoint is unavailable: ${this.reason}`;- }-}--export class RelayEnvironmentEndpointTimedOutError extends Schema.TaggedErrorClass<RelayEnvironmentEndpointTimedOutError>()(- "RelayEnvironmentEndpointTimedOutError",- {- code: Schema.Literal("environment_endpoint_timed_out"),- traceId: TrimmedNonEmptyString,- },- { httpApiStatus: 504 },-) {- override get message(): string {- return "Relay environment endpoint request timed out";- }-}--export class RelayEnvironmentLinkFailedError extends Schema.TaggedErrorClass<RelayEnvironmentLinkFailedError>()(- "RelayEnvironmentLinkFailedError",- {- code: Schema.Literal("environment_link_failed"),- reason: RelayEnvironmentLinkFailedReason,- traceId: TrimmedNonEmptyString,- },- { httpApiStatus: 500 },-) {- override get message(): string {- return `Relay environment link failed: ${this.reason}`;- }-}--export class RelayEnvironmentLinkUnavailableError extends Schema.TaggedErrorClass<RelayEnvironmentLinkUnavailableError>()(- "RelayEnvironmentLinkUnavailableError",- {- code: Schema.Literal("environment_link_unavailable"),- reason: RelayEnvironmentLinkUnavailableReason,- traceId: TrimmedNonEmptyString,- },- { httpApiStatus: 503 },-) {- override get message(): string {- return `Relay environment link is unavailable: ${this.reason}`;- }-}--export class RelayEnvironmentLinkLimitExceededError extends Schema.TaggedErrorClass<RelayEnvironmentLinkLimitExceededError>()(- "RelayEnvironmentLinkLimitExceededError",- {- code: Schema.Literal("environment_link_limit_exceeded"),- maxTunnels: Schema.Number,- traceId: TrimmedNonEmptyString,- },- { httpApiStatus: 403 },-) {- override get message(): string {- return `Relay managed tunnel limit reached: this account allows at most ${this.maxTunnels} tunnels`;- }-}--export class RelayAgentActivityPublishProofExpiredError extends Schema.TaggedErrorClass<RelayAgentActivityPublishProofExpiredError>()(- "RelayAgentActivityPublishProofExpiredError",- {- code: Schema.Literal("agent_activity_publish_proof_expired"),- traceId: TrimmedNonEmptyString,- },- { httpApiStatus: 401 },-) {- override get message(): string {- return "Relay agent activity publish proof expired";- }-}--export class RelayAgentActivityPublishProofInvalidError extends Schema.TaggedErrorClass<RelayAgentActivityPublishProofInvalidError>()(- "RelayAgentActivityPublishProofInvalidError",- {- code: Schema.Literal("agent_activity_publish_proof_invalid"),- reason: RelayAgentActivityPublishProofInvalidReason,- traceId: TrimmedNonEmptyString,- },- { httpApiStatus: 401 },-) {- override get message(): string {- return `Relay agent activity publish proof is invalid: ${this.reason}`;- }-}--export class RelayInternalError extends Schema.TaggedErrorClass<RelayInternalError>()(- "RelayInternalError",- {- code: Schema.Literal("internal_error"),- reason: RelayInternalErrorReason,- traceId: TrimmedNonEmptyString,- },- { httpApiStatus: 500 },-) {- override get message(): string {- return `Relay internal error: ${this.reason}`;- }-}--export const RelayProtectedError = Schema.Union([- RelayAuthInvalidError,- RelayEnvironmentLinkProofExpiredError,- RelayEnvironmentLinkProofInvalidError,- RelayEnvironmentConnectNotAuthorizedError,- RelayEnvironmentEndpointUnavailableError,- RelayEnvironmentEndpointTimedOutError,- RelayEnvironmentLinkFailedError,- RelayEnvironmentLinkUnavailableError,- RelayEnvironmentLinkLimitExceededError,- RelayAgentActivityPublishProofExpiredError,- RelayAgentActivityPublishProofInvalidError,- RelayInternalError,-]);-export type RelayProtectedError = typeof RelayProtectedError.Type;--const RelayAuthAndInternalErrors = [RelayAuthInvalidError, RelayInternalError] as const;--const RelayEnvironmentLinkErrors = [- RelayAuthInvalidError,- RelayEnvironmentLinkProofExpiredError,- RelayEnvironmentLinkProofInvalidError,- RelayEnvironmentLinkUnavailableError,- RelayEnvironmentLinkLimitExceededError,- RelayEnvironmentLinkFailedError,- RelayInternalError,-] as const;--const RelayEnvironmentConnectErrors = [- RelayAuthInvalidError,- RelayEnvironmentConnectNotAuthorizedError,- RelayEnvironmentEndpointUnavailableError,- RelayEnvironmentEndpointTimedOutError,- RelayInternalError,-] as const;--const RelayAgentActivityPublishErrors = [- RelayAuthInvalidError,- RelayAgentActivityPublishProofExpiredError,- RelayAgentActivityPublishProofInvalidError,- RelayInternalError,-] as const;--export class RelayClientPrincipal extends Context.Service<- RelayClientPrincipal,- {- readonly userId: string;- readonly token: string;- readonly proofKeyThumbprint?: string;- readonly dpopScopes?: ReadonlyArray<RelayDpopAccessTokenScope>;- }->()("@t3tools/contracts/relay/RelayClientPrincipal") {}--export class RelayEnvironmentPrincipal extends Context.Service<- RelayEnvironmentPrincipal,- {- readonly environmentId: string;- readonly environmentPublicKey: string;- }->()("@t3tools/contracts/relay/RelayEnvironmentPrincipal") {}--const RelayClientBearerAuthorization = HttpApiSecurity.http({ scheme: "bearer" }).pipe(- HttpApiSecurity.annotate(- OpenApi.Description,- "Clerk session or OAuth bearer token for the signed-in T3 Connect user.",- ),-);--export class RelayClientAuth extends HttpApiMiddleware.Service<- RelayClientAuth,- { provides: RelayClientPrincipal }->()("RelayClientAuth", {- error: RelayAuthInvalidError,- security: { clientBearer: RelayClientBearerAuthorization },-}) {}--const RelayEnvironmentBearerAuthorization = HttpApiSecurity.http({ scheme: "bearer" }).pipe(- HttpApiSecurity.annotate(- OpenApi.Description,- "Relay-issued environment credential installed when the environment is linked.",- ),-);--export class RelayEnvironmentAuth extends HttpApiMiddleware.Service<- RelayEnvironmentAuth,- { provides: RelayEnvironmentPrincipal }->()("RelayEnvironmentAuth", {- error: [RelayAuthInvalidError, RelayInternalError],- security: { environmentBearer: RelayEnvironmentBearerAuthorization },-}) {}--const RelayDpopAuthorization = HttpApiSecurity.http({ scheme: "DPoP" }).pipe(- HttpApiSecurity.annotate(- OpenApi.Description,- "DPoP-bound access token. Requests must also include the DPoP proof JWT header.",- ),-);--export class RelayDpopClientAuth extends HttpApiMiddleware.Service<- RelayDpopClientAuth,- { provides: RelayClientPrincipal }->()("RelayDpopClientAuth", {- error: RelayAuthInvalidError,- security: { relayDpop: RelayDpopAuthorization },-}) {}--export const RelayClientEnvironmentRecord = Schema.Struct({- environmentId: EnvironmentId,- label: TrimmedNonEmptyString,- endpoint: RelayManagedEndpoint,- linkedAt: TrimmedNonEmptyString,-});-export type RelayClientEnvironmentRecord = typeof RelayClientEnvironmentRecord.Type;--export const RelayListEnvironmentsResponse = Schema.Struct({- environments: Schema.Array(RelayClientEnvironmentRecord),-});-export type RelayListEnvironmentsResponse = typeof RelayListEnvironmentsResponse.Type;--export const RelayEnvironmentConnectRequest = Schema.Struct({- deviceId: Schema.optional(- TrimmedNonEmptyString.annotate({- description: "Optional client device identifier requesting the connection.",- }),- ),- clientKeyThumbprint: Schema.optional(- TrimmedNonEmptyString.annotate({- description: "Deprecated alias for clientProofKeyThumbprint.",- }),- ),- clientProofKeyThumbprint: Schema.optional(- TrimmedNonEmptyString.annotate({- description: "JWK thumbprint that the minted environment credential must be bound to.",- }),- ),-}).annotate({ description: "Requests a short-lived credential for connecting to an environment." });-export type RelayEnvironmentConnectRequest = typeof RelayEnvironmentConnectRequest.Type;--export const RelayEnvironmentConnectScope = "environment:connect" as const;-export const RelayEnvironmentStatusScope = "environment:status" as const;-export const RelayMobileRegistrationScope = "mobile:registration" as const;-export const RelayDpopAccessTokenScope = Schema.Literals([- RelayEnvironmentConnectScope,- RelayEnvironmentStatusScope,- RelayMobileRegistrationScope,-]);-export type RelayDpopAccessTokenScope = typeof RelayDpopAccessTokenScope.Type;--export const RelayDpopTokenExchangeGrantType =- "urn:ietf:params:oauth:grant-type:token-exchange" as const;-export const RelayJwtSubjectTokenType = "urn:ietf:params:oauth:token-type:jwt" as const;-export const RelayAccessTokenType = "urn:ietf:params:oauth:token-type:access_token" as const;-export const RelayPublicClientId = Schema.Literals(["t3-mobile", "t3-web"]);-export type RelayPublicClientId = typeof RelayPublicClientId.Type;-export const RelayMobileClientId = "t3-mobile" as const;-export const RelayWebClientId = "t3-web" as const;--export const RelayDpopAccessTokenRequest = Schema.Struct({- grant_type: Schema.Literal(RelayDpopTokenExchangeGrantType),- subject_token: TrimmedNonEmptyString.annotate({- description: "Clerk bearer token for the signed-in cloud user.",- }),- subject_token_type: Schema.Literal(RelayJwtSubjectTokenType),- requested_token_type: Schema.Literal(RelayAccessTokenType),- resource: TrimmedNonEmptyString.annotate({- description: "Relay issuer URL that will receive the DPoP-bound access token.",- }),- scope: TrimmedNonEmptyString.annotate({- description: "Space-separated relay scopes requested by the client.",- }),- client_id: RelayPublicClientId,-})- .annotate({ description: "OAuth token exchange request for a DPoP-bound relay access token." })- .pipe(HttpApiSchema.asFormUrlEncoded());-export type RelayDpopAccessTokenRequest = typeof RelayDpopAccessTokenRequest.Type;--export const RelayDpopAccessTokenResponse = Schema.Struct({- access_token: TrimmedNonEmptyString,- issued_token_type: Schema.Literal(RelayAccessTokenType),- token_type: Schema.Literal("DPoP"),- expires_in: Schema.Int.check(Schema.isGreaterThan(0)),- scope: TrimmedNonEmptyString,-});-export type RelayDpopAccessTokenResponse = typeof RelayDpopAccessTokenResponse.Type;--export const RelayBearerRequestHeaders = Schema.Struct({- authorization: TrimmedNonEmptyString,-});--export const RelayDpopProofRequestHeaders = Schema.Struct({- dpop: TrimmedNonEmptyString,-});--export const RelayDpopRequestHeaders = Schema.Struct({- authorization: TrimmedNonEmptyString,- dpop: TrimmedNonEmptyString,-});--export const RelayAuthorizationServerMetadata = Schema.Struct({- issuer: TrimmedNonEmptyString,- token_endpoint: TrimmedNonEmptyString,- grant_types_supported: Schema.Array(Schema.Literal(RelayDpopTokenExchangeGrantType)),- token_endpoint_auth_methods_supported: Schema.Array(Schema.Literal("none")),- dpop_signing_alg_values_supported: Schema.Array(Schema.Literal("ES256")),- scopes_supported: Schema.Array(RelayDpopAccessTokenScope),-});--export const RelayProtectedResourceMetadata = Schema.Struct({- resource: TrimmedNonEmptyString,- authorization_servers: Schema.Array(TrimmedNonEmptyString),- scopes_supported: Schema.Array(RelayDpopAccessTokenScope),- dpop_bound_access_tokens_required: Schema.Boolean,- dpop_signing_alg_values_supported: Schema.Array(Schema.Literal("ES256")),-});--export const RelayEnvironmentUnlinkParams = Schema.Struct({- environmentId: EnvironmentId,-});-export type RelayEnvironmentUnlinkParams = typeof RelayEnvironmentUnlinkParams.Type;--export const RelayEnvironmentConnectResponse = Schema.Struct({- environmentId: EnvironmentId,- endpoint: RelayManagedEndpoint,- credential: TrimmedNonEmptyString,- expiresAt: TrimmedNonEmptyString,-});-export type RelayEnvironmentConnectResponse = typeof RelayEnvironmentConnectResponse.Type;--export const RelayEnvironmentStatusValue = Schema.Literals(["online", "offline"]);-export type RelayEnvironmentStatusValue = typeof RelayEnvironmentStatusValue.Type;--export const RelayEnvironmentStatusResponse = Schema.Struct({- environmentId: EnvironmentId,- endpoint: RelayManagedEndpoint,- status: RelayEnvironmentStatusValue,- checkedAt: TrimmedNonEmptyString,- descriptor: Schema.optional(ExecutionEnvironmentDescriptor),- error: Schema.optional(TrimmedNonEmptyString),- traceId: Schema.optional(TrimmedNonEmptyString),-});-export type RelayEnvironmentStatusResponse = typeof RelayEnvironmentStatusResponse.Type;--export const RelayCloudMintCredentialProofPayload = Schema.Struct({- ...RelaySignedJwtRegisteredClaims,- environmentId: EnvironmentId,- clientProofKeyThumbprint: TrimmedNonEmptyString,- cnf: Schema.Struct({- jkt: TrimmedNonEmptyString,- }),- deviceId: Schema.optional(TrimmedNonEmptyString),- nonce: TrimmedNonEmptyString,- scope: Schema.Array(Schema.Literal("environment:connect")),-});-export type RelayCloudMintCredentialProofPayload = typeof RelayCloudMintCredentialProofPayload.Type;--export const RelayCloudMintCredentialProof = TrimmedNonEmptyString;-export type RelayCloudMintCredentialProof = typeof RelayCloudMintCredentialProof.Type;--export const RelayCloudMintCredentialRequest = Schema.Struct({- proof: RelayCloudMintCredentialProof,-});-export type RelayCloudMintCredentialRequest = typeof RelayCloudMintCredentialRequest.Type;--export const RelayCloudEnvironmentHealthProofPayload = Schema.Struct({- ...RelaySignedJwtRegisteredClaims,- environmentId: EnvironmentId,- nonce: TrimmedNonEmptyString,- scope: Schema.Array(Schema.Literal("environment:status")),-});-export type RelayCloudEnvironmentHealthProofPayload =- typeof RelayCloudEnvironmentHealthProofPayload.Type;--export const RelayCloudEnvironmentHealthProof = TrimmedNonEmptyString;-export type RelayCloudEnvironmentHealthProof = typeof RelayCloudEnvironmentHealthProof.Type;--export const RelayCloudEnvironmentHealthRequest = Schema.Struct({- proof: RelayCloudEnvironmentHealthProof,-});-export type RelayCloudEnvironmentHealthRequest = typeof RelayCloudEnvironmentHealthRequest.Type;--export const RelayEnvironmentHealthResponseProofPayload = Schema.Struct({- ...RelaySignedJwtRegisteredClaims,- environmentId: EnvironmentId,- requestNonce: TrimmedNonEmptyString,- status: Schema.Literal("online"),- descriptor: ExecutionEnvironmentDescriptor,- checkedAt: TrimmedNonEmptyString,-});-export type RelayEnvironmentHealthResponseProofPayload =- typeof RelayEnvironmentHealthResponseProofPayload.Type;--export const RelayEnvironmentHealthResponse = Schema.Struct({- environmentId: EnvironmentId,- status: Schema.Literal("online"),- descriptor: ExecutionEnvironmentDescriptor,- checkedAt: TrimmedNonEmptyString,- proof: TrimmedNonEmptyString,-});-export type RelayEnvironmentHealthResponse = typeof RelayEnvironmentHealthResponse.Type;--export const RelayEnvironmentMintResponseProofPayload = Schema.Struct({- ...RelaySignedJwtRegisteredClaims,- environmentId: EnvironmentId,- clientProofKeyThumbprint: TrimmedNonEmptyString,- requestNonce: TrimmedNonEmptyString,- credential: TrimmedNonEmptyString,-});-export type RelayEnvironmentMintResponseProofPayload =- typeof RelayEnvironmentMintResponseProofPayload.Type;--export const RelayEnvironmentMintResponse = Schema.Struct({- credential: TrimmedNonEmptyString,- expiresAt: TrimmedNonEmptyString,- proof: TrimmedNonEmptyString,-});-export type RelayEnvironmentMintResponse = typeof RelayEnvironmentMintResponse.Type;--export const RelayDeliveryKind = Schema.Literals([- "live_activity_start",- "live_activity_update",- "live_activity_end",- "push_notification",-]);-export type RelayDeliveryKind = typeof RelayDeliveryKind.Type;--export const RelayDeliveryResult = Schema.Struct({- deviceId: TrimmedNonEmptyString,- kind: RelayDeliveryKind,- ok: Schema.Boolean,- queued: Schema.optional(Schema.Boolean),- apnsStatus: Schema.NullOr(Schema.Number),- apnsReason: Schema.NullOr(Schema.String),- apnsId: Schema.NullOr(Schema.String),-});-export type RelayDeliveryResult = typeof RelayDeliveryResult.Type;--export const RelayOkResponse = Schema.Struct({- ok: Schema.Boolean,-});-export type RelayOkResponse = typeof RelayOkResponse.Type;--export const RelayPublishResponse = Schema.Struct({- ok: Schema.Boolean,- deliveries: Schema.Array(RelayDeliveryResult),-});-export type RelayPublishResponse = typeof RelayPublishResponse.Type;--export const RelayHealthResponse = Schema.Struct({- ok: Schema.Boolean,- service: Schema.Literal("relay"),-});-export type RelayHealthResponse = typeof RelayHealthResponse.Type;--export const RelayHealthGroup = HttpApiGroup.make("health")- .add(- HttpApiEndpoint.get("health", "/health", {- success: RelayHealthResponse,- error: RelayInternalError,- }).annotate(OpenApi.Summary, "Check relay health"),- )- .annotate(OpenApi.Description, "Service health and readiness.");--export const RelayMetadataGroup = HttpApiGroup.make("metadata")- .add(- HttpApiEndpoint.get("authorizationServer", "/.well-known/oauth-authorization-server", {- success: RelayAuthorizationServerMetadata,- }).annotate(OpenApi.Summary, "Read OAuth authorization-server metadata"),- HttpApiEndpoint.get("protectedResource", "/.well-known/oauth-protected-resource", {- success: RelayProtectedResourceMetadata,- }).annotate(OpenApi.Summary, "Read OAuth protected-resource metadata"),- )- .annotate(OpenApi.Description, "OAuth and DPoP discovery metadata.");--export const RelayRegisterDeviceEndpoint = HttpApiEndpoint.post(- "registerDevice",- "/v1/mobile/devices",- {- headers: RelayDpopRequestHeaders,- payload: RelayDeviceRegistrationRequest,- success: RelayOkResponse,- error: RelayAuthAndInternalErrors,- },-).annotate(OpenApi.Summary, "Register or update a mobile device");--export const RelayRegisterLiveActivityEndpoint = HttpApiEndpoint.post(- "registerLiveActivity",- "/v1/mobile/live-activities",- {- headers: RelayDpopRequestHeaders,- payload: RelayLiveActivityRegistrationRequest,- success: RelayOkResponse,- error: RelayAuthAndInternalErrors,- },-).annotate(OpenApi.Summary, "Register a Live Activity push token");--export const RelayAgentActivitySnapshotResponse = Schema.Struct({- aggregate: Schema.NullOr(RelayAgentActivityAggregateState),-});-export type RelayAgentActivitySnapshotResponse = typeof RelayAgentActivitySnapshotResponse.Type;--// Lets the app decide whether arming a Live Activity is worthwhile before-// creating one (no empty lock-screen card when nothing is running) and seed-// the card with the real aggregate instead of a placeholder.-export const RelayAgentActivitySnapshotEndpoint = HttpApiEndpoint.get(- "getAgentActivitySnapshot",- "/v1/mobile/agent-activity",- {- headers: RelayDpopRequestHeaders,- success: RelayAgentActivitySnapshotResponse,- error: RelayAuthAndInternalErrors,- },-).annotate(OpenApi.Summary, "Read the current Live Activity aggregate");--export const RelayUnregisterDeviceEndpoint = HttpApiEndpoint.delete(- "unregisterDevice",- "/v1/mobile/devices/:deviceId",- {- headers: RelayDpopRequestHeaders,- params: RelayDeviceUnregistrationParams,- success: RelayOkResponse,- error: RelayAuthAndInternalErrors,- },-).annotate(OpenApi.Summary, "Unregister a mobile device");--export const RelayMobileGroup = HttpApiGroup.make("mobile")- .add(- RelayRegisterDeviceEndpoint,- RelayRegisterLiveActivityEndpoint,- RelayAgentActivitySnapshotEndpoint,- RelayUnregisterDeviceEndpoint,- )- .annotate(OpenApi.Description, "Mobile push-notification and Live Activity registration.")- .middleware(RelayDpopClientAuth);--export const RelayClientGroup = HttpApiGroup.make("client")- .add(- HttpApiEndpoint.get("listEnvironments", "/v1/environments", {- headers: RelayBearerRequestHeaders,- success: RelayListEnvironmentsResponse,- error: RelayAuthAndInternalErrors,- }).annotate(OpenApi.Summary, "List linked environments"),- HttpApiEndpoint.get("listDevices", "/v1/client/devices", {- headers: RelayBearerRequestHeaders,- success: RelayListDevicesResponse,- error: RelayAuthAndInternalErrors,- }).annotate(OpenApi.Summary, "List registered mobile devices"),- HttpApiEndpoint.post("linkEnvironment", "/v1/client/environment-links", {- headers: RelayBearerRequestHeaders,- payload: RelayEnvironmentLinkRequest,- success: RelayEnvironmentLinkResponse,- error: RelayEnvironmentLinkErrors,- }).annotate(OpenApi.Summary, "Link an environment"),- HttpApiEndpoint.post(- "createEnvironmentLinkChallenge",- "/v1/client/environment-link-challenges",- {- headers: RelayBearerRequestHeaders,- payload: RelayEnvironmentLinkChallengeRequest,- success: RelayEnvironmentLinkChallengeResponse,- error: RelayAuthAndInternalErrors,- },- ).annotate(OpenApi.Summary, "Create an environment-link challenge"),- HttpApiEndpoint.delete("unlinkEnvironment", "/v1/client/environment-links/:environmentId", {- headers: RelayBearerRequestHeaders,- params: RelayEnvironmentUnlinkParams,- success: RelayOkResponse,- error: RelayAuthAndInternalErrors,- }).annotate(OpenApi.Summary, "Unlink an environment"),- HttpApiEndpoint.delete(- "releaseEnvironmentTunnel",- "/v1/client/environment-links/:environmentId/tunnel",- {- headers: RelayBearerRequestHeaders,- params: RelayEnvironmentUnlinkParams,- success: RelayOkResponse,- error: RelayAuthAndInternalErrors,- },- )- .annotate(OpenApi.Summary, "Release an environment's managed tunnel")- .annotate(- OpenApi.Description,- "Deletes the provisioned Cloudflare tunnel while keeping the environment link and its hostname reservation, so a later link re-provisions the tunnel under the same URL. Environments call this when they shut down; Cloudflare bills per provisioned tunnel, so idle tunnels should not outlive their environment.",- ),- )- .annotate(OpenApi.Description, "Cloud-user environment links and registered devices.")- .middleware(RelayClientAuth);--export const RelayExchangeDpopAccessTokenEndpoint = HttpApiEndpoint.post(- "exchangeDpopAccessToken",- "/v1/client/dpop-token",- {- headers: RelayDpopProofRequestHeaders,- payload: RelayDpopAccessTokenRequest,- success: RelayDpopAccessTokenResponse,- error: RelayAuthAndInternalErrors,- },-)- .annotate(OpenApi.Summary, "Exchange a Clerk token for a DPoP access token")- .annotate(- OpenApi.Description,- "Bootstrap endpoint. Send the DPoP proof JWT in the dpop header and the Clerk token in subject_token. The returned access token is bound to the proof key.",- );--export const RelayTokenGroup = HttpApiGroup.make("token")- .add(RelayExchangeDpopAccessTokenEndpoint)- .annotate(OpenApi.Description, "OAuth token exchange for DPoP-bound client access.");--export const RelayConnectEnvironmentEndpoint = HttpApiEndpoint.post(- "connectEnvironment",- "/v1/environments/:environmentId/connect",- {- headers: RelayDpopRequestHeaders,- params: Schema.Struct({- environmentId: EnvironmentId,- }),- payload: RelayEnvironmentConnectRequest,- success: RelayEnvironmentConnectResponse,- error: RelayEnvironmentConnectErrors,- },-).annotate(OpenApi.Summary, "Connect to an environment");--export const RelayGetEnvironmentStatusEndpoint = HttpApiEndpoint.post(- "getEnvironmentStatus",- "/v1/environments/:environmentId/status",- {- headers: RelayDpopRequestHeaders,- params: Schema.Struct({- environmentId: EnvironmentId,- }),- success: RelayEnvironmentStatusResponse,- error: RelayEnvironmentConnectErrors,- },-).annotate(OpenApi.Summary, "Check environment status");--export const RelayDpopClientGroup = HttpApiGroup.make("dpopClient")- .add(RelayConnectEnvironmentEndpoint, RelayGetEnvironmentStatusEndpoint)- .annotate(OpenApi.Description, "DPoP-authenticated client access to linked environments.")- .middleware(RelayDpopClientAuth);--export const RelayServerGroup = HttpApiGroup.make("server")- .add(- HttpApiEndpoint.post(- "publishAgentActivity",- "/v1/environments/:environmentId/threads/:threadId/agent-activity",- {- params: Schema.Struct({- environmentId: EnvironmentId,- threadId: ThreadId,- }),- payload: RelayAgentActivityPublishRequest,- success: RelayPublishResponse,- error: RelayAgentActivityPublishErrors,- },- ).annotate(OpenApi.Summary, "Publish agent activity"),- )- .annotate(OpenApi.Description, "Environment-authenticated activity publication.")- .middleware(RelayEnvironmentAuth);--export const RelayApi = HttpApi.make("RelayApi")- .add(- RelayHealthGroup,- RelayMetadataGroup,- RelayMobileGroup,- RelayClientGroup,- RelayTokenGroup,- RelayDpopClientGroup,- RelayServerGroup,- )- .annotate(OpenApi.Title, "T3 Code Relay API")- .annotate(OpenApi.Version, "1.0.0")- .annotate(- OpenApi.Description,- "Control-plane API for linking T3 environments, connecting authorized clients, and publishing agent activity.",- );-export type RelayApi = typeof RelayApi;diff --git a/packages/contracts/src/relayClient.ts b/packages/contracts/src/relayClient.tsdeleted file mode 100644index e78078d1e..000000000--- a/packages/contracts/src/relayClient.ts+++ /dev/null@@ -1,63 +0,0 @@-import * as Schema from "effect/Schema";--export const RelayClientStatusSchema = Schema.Union([- Schema.Struct({- status: Schema.Literal("available"),- executablePath: Schema.String,- source: Schema.Literals(["override", "managed", "path"]),- version: Schema.String,- }),- Schema.Struct({- status: Schema.Literal("missing"),- version: Schema.String,- }),- Schema.Struct({- status: Schema.Literal("unsupported"),- platform: Schema.String,- arch: Schema.String,- version: Schema.String,- }),-]);-export type RelayClientStatus = typeof RelayClientStatusSchema.Type;--export const RelayClientInstallProgressStageSchema = Schema.Literals([- "checking",- "waiting_for_lock",- "downloading",- "verifying",- "installing",- "validating",- "activating",-]);-export type RelayClientInstallProgressStage = typeof RelayClientInstallProgressStageSchema.Type;--export const RelayClientInstallProgressEventSchema = Schema.Union([- Schema.Struct({- type: Schema.Literal("progress"),- stage: RelayClientInstallProgressStageSchema,- }),- Schema.Struct({- type: Schema.Literal("complete"),- status: RelayClientStatusSchema,- }),-]);-export type RelayClientInstallProgressEvent = typeof RelayClientInstallProgressEventSchema.Type;--export const RelayClientInstallFailureReasonSchema = Schema.Literals([- "download_failed",- "invalid_checksum",- "install_locked",- "override_missing",- "unsupported_platform",- "validation_failed",- "write_failed",-]);-export type RelayClientInstallFailureReason = typeof RelayClientInstallFailureReasonSchema.Type;--export class RelayClientInstallFailedError extends Schema.TaggedErrorClass<RelayClientInstallFailedError>()(- "RelayClientInstallFailedError",- {- reason: RelayClientInstallFailureReasonSchema,- message: Schema.String,- },-) {}diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.tsindex 14496141a..72eeac6f3 100644--- a/packages/contracts/src/rpc.ts+++ b/packages/contracts/src/rpc.ts@@ -95,11 +95,6 @@ import {ProviderUploadFeedbackResult,} from "./provider.ts";import { ProviderInstanceId } from "./providerInstance.ts";-import {- RelayClientInstallFailedError,- RelayClientInstallProgressEventSchema,- RelayClientStatusSchema,-} from "./relayClient.ts";import {ProjectListEntriesError,ProjectListEntriesInput,@@ -330,10 +325,6 @@ export const WS_METHODS = {portabilityPreviewImport: "portability.previewImport",portabilityApplyImport: "portability.applyImport",- // Cloud environment methods- cloudGetRelayClientStatus: "cloud.getRelayClientStatus",- cloudInstallRelayClient: "cloud.installRelayClient",-// Source control methodssourceControlLookupRepository: "sourceControl.lookupRepository",sourceControlCloneRepository: "sourceControl.cloneRepository",@@ -550,19 +541,6 @@ export const WsServerSignalProcessRpc = Rpc.make(WS_METHODS.serverSignalProcess,error: EnvironmentAuthorizationError,});-export const WsCloudGetRelayClientStatusRpc = Rpc.make(WS_METHODS.cloudGetRelayClientStatus, {- payload: Schema.Struct({}),- success: RelayClientStatusSchema,- error: EnvironmentAuthorizationError,-});--export const WsCloudInstallRelayClientRpc = Rpc.make(WS_METHODS.cloudInstallRelayClient, {- payload: Schema.Struct({}),- success: RelayClientInstallProgressEventSchema,- error: Schema.Union([RelayClientInstallFailedError, EnvironmentAuthorizationError]),- stream: true,-});-export const WsServerReportClientActivityRpc = Rpc.make(WS_METHODS.serverReportClientActivity, {payload: ClientActivityReportInput,error: EnvironmentAuthorizationError,@@ -1081,8 +1059,6 @@ export const WsRpcGroup = RpcGroup.make(WsPortabilityExportRpc,WsPortabilityPreviewImportRpc,WsPortabilityApplyImportRpc,- WsCloudGetRelayClientStatusRpc,- WsCloudInstallRelayClientRpc,WsSourceControlLookupRepositoryRpc,WsSourceControlCloneRepositoryRpc,WsSourceControlPublishRepositoryRpc,diff --git a/packages/contracts/src/settings.test.ts b/packages/contracts/src/settings.test.tsindex cfee9be2e..ed1593a84 100644--- a/packages/contracts/src/settings.test.ts+++ b/packages/contracts/src/settings.test.ts@@ -80,6 +80,24 @@ describe("ServerSettings analytics", () => {});});+describe("policy records", () => {+ it("keeps policy acceptance local", () => {+ expect(decodeClientSettings({})).toMatchObject({+ reviewedPrivacyPolicyVersion: "",+ reviewedTermsVersion: "",+ });+ expect(+ decodeClientSettingsPatch({+ reviewedPrivacyPolicyVersion: "2026-08-31",+ reviewedTermsVersion: "2026-08-31",+ }),+ ).toEqual({+ reviewedPrivacyPolicyVersion: "2026-08-31",+ reviewedTermsVersion: "2026-08-31",+ });+ });+});+describe("ClaudeSettings auto-compaction", () => {it("uses Claude's default threshold when no override is configured", () => {expect(decodeClaudeSettings({}).autoCompactWindow).toBe("");@@ -249,6 +267,16 @@ describe("ServerSettings bot sandbox and browser sharing", () => {});});+describe("ServerSettings local execution", () => {+ it("asks first by default and accepts full access only as an opt-in", () => {+ expect(decodeServerSettings({}).localExecutionMode).toBe("approval-required");+ expect(+ decodeServerSettingsPatch({ localExecutionMode: "full-access" }).localExecutionMode,+ ).toBe("full-access");+ expect(() => decodeServerSettingsPatch({ localExecutionMode: "auto" })).toThrow();+ });+});+describe("ServerSettings.providerInstances (slice-2 invariant)", () => {it("defaults text generation to Luna at low reasoning effort", () => {expect(DEFAULT_SERVER_SETTINGS.textGenerationModelSelection).toEqual({diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.tsindex 35f4bb68f..d3bb4c44c 100644--- a/packages/contracts/src/settings.ts+++ b/packages/contracts/src/settings.ts@@ -150,6 +150,9 @@ export const FontFamilyPreference = Schema.String.check(Schema.isMaxLength(200))export type FontFamilyPreference = typeof FontFamilyPreference.Type;export const DEFAULT_PRODUCT_FEEDBACK_ENDPOINT = "https://feedback.akeru.bot/v1/feedback";+export const AKERU_MARKETING_SITE_URL = "https://akeru.bot";+export const AKERU_PRIVACY_POLICY_VERSION = "2026-08-31";+export const AKERU_TERMS_VERSION = "2026-08-31";export const ProductFeedbackEndpoint = TrimmedNonEmptyString.check(Schema.isMaxLength(2_048),Schema.isPattern(@@ -168,6 +171,8 @@ export const DEFAULT_BROWSER_VIEWPORT: PreviewViewportSetting = FILL_PREVIEW_VIEexport const DEFAULT_BROWSER_AUTO_SHOW_FLOATING_PREVIEW = true;export const ClientSettingsSchema = Schema.Struct({+ reviewedPrivacyPolicyVersion: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),+ reviewedTermsVersion: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),appearanceContrast: AppearanceContrast.pipe(Schema.withDecodingDefault(Effect.succeed(DEFAULT_APPEARANCE_CONTRAST)),),@@ -674,6 +679,9 @@ export const ServerSettings = Schema.Struct({botSandboxBrowserSharing: BotSandboxBrowserSharing.pipe(Schema.withDecodingDefault(Effect.succeed(DEFAULT_BOT_SANDBOX_BROWSER_SHARING)),),+ localExecutionMode: LocalExecutionMode.pipe(+ Schema.withDecodingDefault(Effect.succeed(DEFAULT_LOCAL_EXECUTION_MODE)),+ ),/*** Whether agents may drive the in-app preview browser. Turning this off* withholds the MCP credential, so the `t3-code` server (and with it every@@ -686,9 +694,6 @@ export const ServerSettings = Schema.Struct({* between a desktop window and a phone attached to the same server.*/enableAgentBrowserAccess: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),- localExecutionMode: LocalExecutionMode.pipe(- Schema.withDecodingDefault(Effect.succeed(DEFAULT_LOCAL_EXECUTION_MODE)),- ),voice: VoiceSettings,backgroundActivity: BackgroundActivitySettings,// Legacy flat fields retained for old settings files and old clients. New@@ -911,11 +916,11 @@ export const ServerSettingsPatch = Schema.Struct({enableLegacyTokenStreaming: Schema.optionalKey(Schema.Boolean),enableProviderUpdateChecks: Schema.optionalKey(Schema.Boolean),analyticsEnabled: Schema.optionalKey(Schema.Boolean),+ localExecutionMode: Schema.optionalKey(LocalExecutionMode),productFeedbackEnabled: Schema.optionalKey(Schema.Boolean),productFeedbackEndpoint: Schema.optionalKey(ProductFeedbackEndpoint),botSandboxBrowserSharing: Schema.optionalKey(BotSandboxBrowserSharing),enableAgentBrowserAccess: Schema.optionalKey(Schema.Boolean),- localExecutionMode: Schema.optionalKey(LocalExecutionMode),voice: Schema.optionalKey(Schema.Struct({enabled: Schema.optionalKey(Schema.Boolean),@@ -971,6 +976,8 @@ export const ServerSettingsPatch = Schema.Struct({export type ServerSettingsPatch = typeof ServerSettingsPatch.Type;export const ClientSettingsPatch = Schema.Struct({+ reviewedPrivacyPolicyVersion: Schema.optionalKey(TrimmedString),+ reviewedTermsVersion: Schema.optionalKey(TrimmedString),appearanceContrast: Schema.optionalKey(AppearanceContrast),browserDefaultViewport: Schema.optionalKey(PreviewViewportSetting),browserDefaultZoomFactor: Schema.optionalKey(PreviewZoomFactor),diff --git a/packages/shared/package.json b/packages/shared/package.jsonindex eeaa5f59e..3773b16ac 100644--- a/packages/shared/package.json+++ b/packages/shared/package.json@@ -43,10 +43,6 @@"types": "./src/observability.ts","import": "./src/observability.ts"},- "./httpObservability": {- "types": "./src/httpObservability.ts",- "import": "./src/httpObservability.ts"- },"./shell": {"types": "./src/shell.ts","import": "./src/shell.ts"@@ -87,6 +83,10 @@"types": "./src/serverSettings.ts","import": "./src/serverSettings.ts"},+ "./sensitiveDataRedaction": {+ "types": "./src/sensitiveDataRedaction.ts",+ "import": "./src/sensitiveDataRedaction.ts"+ },"./backgroundActivitySettings": {"types": "./src/backgroundActivitySettings.ts","import": "./src/backgroundActivitySettings.ts"@@ -115,30 +115,6 @@"types": "./src/remote.ts","import": "./src/remote.ts"},- "./relaySigning": {- "types": "./src/relaySigning.ts",- "import": "./src/relaySigning.ts"- },- "./dpop": {- "types": "./src/dpop.ts",- "import": "./src/dpop.ts"- },- "./dpopCommon": {- "types": "./src/dpopCommon.ts",- "import": "./src/dpopCommon.ts"- },- "./relayAuth": {- "types": "./src/relayAuth.ts",- "import": "./src/relayAuth.ts"- },- "./relayUrl": {- "types": "./src/relayUrl.ts",- "import": "./src/relayUrl.ts"- },- "./relayJwt": {- "types": "./src/relayJwt.ts",- "import": "./src/relayJwt.ts"- },"./oauthScope": {"types": "./src/oauthScope.ts","import": "./src/oauthScope.ts"@@ -155,10 +131,6 @@"types": "./src/cliArgs.ts","import": "./src/cliArgs.ts"},- "./connectAuth": {- "types": "./src/connectAuth.ts",- "import": "./src/connectAuth.ts"- },"./path": {"types": "./src/path.ts","import": "./src/path.ts"@@ -179,14 +151,6 @@"types": "./src/terminalLabels.ts","import": "./src/terminalLabels.ts"},- "./relayClient": {- "types": "./src/relayClient.ts",- "import": "./src/relayClient.ts"- },- "./relayTracing": {- "types": "./src/relayTracing.ts",- "import": "./src/relayTracing.ts"- },"./preview": {"types": "./src/preview.ts","import": "./src/preview.ts"@@ -237,11 +201,8 @@"test": "vp test run"},"dependencies": {- "@noble/curves": "catalog:",- "@noble/hashes": "catalog:","@t3tools/contracts": "workspace:*","effect": "catalog:",- "jose": "catalog:","yaml": "catalog:"},"devDependencies": {diff --git a/packages/shared/src/connectAuth.test.ts b/packages/shared/src/connectAuth.test.tsdeleted file mode 100644index 8e854d780..000000000--- a/packages/shared/src/connectAuth.test.ts+++ /dev/null@@ -1,117 +0,0 @@-import { describe, expect, it } from "vite-plus/test";--import {- buildConnectAuthorizeRequestUrl,- buildConnectClerkAuthorizeUrl,- checkConnectAuthCode,- connectCallbackUrl,- connectLoopbackRedirectUri,- encodeConnectAuthCode,- parseConnectAuthCode,- readConnectAuthorizeRequest,-} from "./connectAuth.ts";--describe("connectAuth", () => {- it("round-trips state and challenge through the authorize URL fragment", () => {- const url = buildConnectAuthorizeRequestUrl({- hostedAppUrl: "https://app.t3.codes",- state: "q7mK9xV2pL4nR8sT6wYzAQ",- challenge: "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM",- });- const parsed = new URL(url);-- expect(parsed.origin).toBe("https://app.t3.codes");- expect(parsed.pathname).toBe("/connect");- expect(parsed.search).toBe("");- expect(readConnectAuthorizeRequest(parsed)).toEqual({- state: "q7mK9xV2pL4nR8sT6wYzAQ",- challenge: "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM",- });- });-- it("rejects authorize requests missing state or challenge", () => {- expect(readConnectAuthorizeRequest(new URL("https://app.t3.codes/connect"))).toBeNull();- expect(- readConnectAuthorizeRequest(new URL("https://app.t3.codes/connect#state=abc")),- ).toBeNull();- expect(- readConnectAuthorizeRequest(new URL("https://app.t3.codes/connect#challenge=abc")),- ).toBeNull();- });-- it("round-trips the loopback port through the authorize URL fragment", () => {- const url = buildConnectAuthorizeRequestUrl({- hostedAppUrl: "https://app.t3.codes",- state: "state-1",- challenge: "challenge-1",- loopbackPort: 34338,- });-- expect(readConnectAuthorizeRequest(new URL(url))).toEqual({- state: "state-1",- challenge: "challenge-1",- loopbackPort: 34338,- });- expect(connectLoopbackRedirectUri(34338)).toBe("http://127.0.0.1:34338/callback");- });-- it("rejects authorize requests whose loopback port is corrupted", () => {- for (const port of ["", "abc", "-1", "0", "65536", "34338x", "34 38"]) {- const url = new URL(- `https://app.t3.codes/connect#state=state-1&challenge=challenge-1&port=${encodeURIComponent(port)}`,- );- expect(readConnectAuthorizeRequest(url), port).toBeNull();- }- });-- it("builds a PKCE authorize URL against the Clerk endpoint", () => {- const url = new URL(- buildConnectClerkAuthorizeUrl({- authorizationEndpoint: "https://clerk.t3.codes/oauth/authorize",- clientId: "oauthapp_123",- redirectUri: connectCallbackUrl("https://app.t3.codes"),- scopes: ["openid", "profile", "email"],- state: "state-1",- challenge: "challenge-1",- }),- );-- expect(url.origin).toBe("https://clerk.t3.codes");- expect(url.pathname).toBe("/oauth/authorize");- expect(url.searchParams.get("client_id")).toBe("oauthapp_123");- expect(url.searchParams.get("redirect_uri")).toBe("https://app.t3.codes/connect/callback");- expect(url.searchParams.get("response_type")).toBe("code");- expect(url.searchParams.get("scope")).toBe("openid profile email");- expect(url.searchParams.get("state")).toBe("state-1");- expect(url.searchParams.get("code_challenge")).toBe("challenge-1");- expect(url.searchParams.get("code_challenge_method")).toBe("S256");- });-- it("round-trips the out-of-band authorization code and preserves dots inside it", () => {- const blob = encodeConnectAuthCode({ code: "az9.code.chunk", state: "state-uuid" });- expect(parseConnectAuthCode(blob)).toEqual({ code: "az9.code.chunk", state: "state-uuid" });- expect(parseConnectAuthCode(` ${blob}\n`)).toEqual({- code: "az9.code.chunk",- state: "state-uuid",- });- });-- it("rejects malformed out-of-band authorization codes", () => {- expect(parseConnectAuthCode("")).toBeNull();- expect(parseConnectAuthCode("no-separator")).toBeNull();- expect(parseConnectAuthCode(".leading")).toBeNull();- expect(parseConnectAuthCode("trailing.")).toBeNull();- });-- it("explains a malformed pasted code without naming a product", () => {- const message = checkConnectAuthCode("no-separator", "state-1");-- expect(message).toBe("That does not look like a connect code. Copy the full code.");- expect(- checkConnectAuthCode(encodeConnectAuthCode({ code: "c1", state: "state-1" }), "state-1"),- ).toEqual({- code: "c1",- state: "state-1",- });- });-});diff --git a/packages/shared/src/connectAuth.ts b/packages/shared/src/connectAuth.tsdeleted file mode 100644index dbac5e5ae..000000000--- a/packages/shared/src/connectAuth.ts+++ /dev/null@@ -1,170 +0,0 @@-import { readHashParams } from "./remote.ts";--const CONNECT_AUTH_STATE_PARAM = "state";-const CONNECT_AUTH_CHALLENGE_PARAM = "challenge";-const CONNECT_AUTH_PORT_PARAM = "port";-const CONNECT_AUTH_CODE_SEPARATOR = ".";-const CONNECT_LOOPBACK_CALLBACK_PATH = "/callback";--const CONNECT_AUTHORIZE_PATH = "/connect";-const CONNECT_CALLBACK_PATH = "/connect/callback";--/**- * The CLI prints URLs against this origin and the web bundle uses it to- * decide whether it is the hosted deployment — the two must agree, so the- * default lives here.- */-export const DEFAULT_HOSTED_APP_URL = "https://app.t3.codes";--/**- * Requested at authorize time by the hosted page and honored by the CLI's- * token exchange; keep both sides on this single definition.- */-export const CONNECT_OAUTH_SCOPES = ["openid", "profile", "email"] as const;--export interface ConnectAuthorizeRequest {- readonly state: string;- readonly challenge: string;- /**- * Present when a loopback CLI initiated the request: the hosted /connect- * page then asks Clerk to redirect the authorization code straight to- * `http://127.0.0.1:<port>/callback` instead of the hosted callback page.- */- readonly loopbackPort?: number;-}--/**- * The URL the CLI prints for the user to open in a browser. `state` and- * `code_challenge` ride the fragment so they never reach the hosted app's- * server or CDN logs; neither is a secret.- *- * Both CLI flows route through the hosted /connect page rather than hitting- * Clerk's /oauth/authorize directly: a signed-out browser sent straight to- * /oauth/authorize goes through Clerk's sign-in redirect, which does not- * reliably preserve the authorize query parameters (state, response_type,- * code_challenge). The hosted page waits for a Clerk session first, then- * forwards the request with the parameters intact.- */-export function buildConnectAuthorizeRequestUrl(input: {- readonly hostedAppUrl: string;- readonly state: string;- readonly challenge: string;- readonly loopbackPort?: number;-}): string {- const url = new URL(CONNECT_AUTHORIZE_PATH, input.hostedAppUrl);- url.hash = new URLSearchParams([- [CONNECT_AUTH_STATE_PARAM, input.state],- [CONNECT_AUTH_CHALLENGE_PARAM, input.challenge],- ...(input.loopbackPort === undefined- ? []- : [[CONNECT_AUTH_PORT_PARAM, String(input.loopbackPort)] as [string, string]]),- ]).toString();- return url.toString();-}--export function readConnectAuthorizeRequest(url: URL): ConnectAuthorizeRequest | null {- const params = readHashParams(url);- const state = params.get(CONNECT_AUTH_STATE_PARAM)?.trim() ?? "";- const challenge = params.get(CONNECT_AUTH_CHALLENGE_PARAM)?.trim() ?? "";- if (!state || !challenge) {- return null;- }- const port = params.get(CONNECT_AUTH_PORT_PARAM);- if (port === null) {- return { state, challenge };- }- // A present-but-invalid port means the link was corrupted; reject the whole- // request rather than silently downgrading a loopback flow to the- // out-of-band one, which would strand the waiting CLI.- const loopbackPort = parseLoopbackPort(port.trim());- if (loopbackPort === null) {- return null;- }- return { state, challenge, loopbackPort };-}--function parseLoopbackPort(value: string): number | null {- if (!/^\d{1,5}$/.test(value)) {- return null;- }- const port = Number(value);- return port >= 1 && port <= 65535 ? port : null;-}--/**- * Redirect URI for the CLI's local callback listener. Must stay in sync with- * the redirect URI registered on the Clerk CLI OAuth application.- */-export function connectLoopbackRedirectUri(port: number): string {- return `http://127.0.0.1:${port}${CONNECT_LOOPBACK_CALLBACK_PATH}`;-}--export function connectCallbackUrl(hostedAppUrl: string): string {- return new URL(CONNECT_CALLBACK_PATH, hostedAppUrl).toString();-}--export function buildConnectClerkAuthorizeUrl(input: {- readonly authorizationEndpoint: string;- readonly clientId: string;- readonly redirectUri: string;- readonly scopes: ReadonlyArray<string>;- readonly state: string;- readonly challenge: string;-}): string {- const url = new URL(input.authorizationEndpoint);- url.searchParams.set("client_id", input.clientId);- url.searchParams.set("redirect_uri", input.redirectUri);- url.searchParams.set("response_type", "code");- url.searchParams.set("scope", input.scopes.join(" "));- url.searchParams.set("state", input.state);- url.searchParams.set("code_challenge", input.challenge);- url.searchParams.set("code_challenge_method", "S256");- return url.toString();-}--export interface ConnectAuthCode {- readonly code: string;- readonly state: string;-}--/**- * The single blob the hosted callback page displays and the CLI accepts.- * Bundling `state` with the authorization code lets the CLI keep the loopback- * flow's CSRF check without any backend: it verifies the returned state- * matches the one it generated. Clerk authorization codes and the CLI's- * base64url states never contain ".".- */-export function encodeConnectAuthCode(input: ConnectAuthCode): string {- return `${input.code}${CONNECT_AUTH_CODE_SEPARATOR}${input.state}`;-}--/**- * Validates an out-of-band authorization code against the state of the request this process- * generated. Returns the parsed code or a user-facing error message; both- * the prompt's live validation and the authoritative post-prompt check go- * through here so they cannot drift.- */-export function checkConnectAuthCode(- blob: string,- expectedState: string,-): ConnectAuthCode | string {- const parsed = parseConnectAuthCode(blob);- if (parsed === null) {- return "That does not look like a connect code. Copy the full code.";- }- if (parsed.state !== expectedState) {- return "That code belongs to a different connect request. Open the URL above and try again.";- }- return parsed;-}--export function parseConnectAuthCode(blob: string): ConnectAuthCode | null {- const trimmed = blob.trim();- const separatorIndex = trimmed.lastIndexOf(CONNECT_AUTH_CODE_SEPARATOR);- if (separatorIndex <= 0 || separatorIndex === trimmed.length - 1) {- return null;- }- const code = trimmed.slice(0, separatorIndex);- const state = trimmed.slice(separatorIndex + 1);- return { code, state };-}diff --git a/packages/shared/src/dpop.test.ts b/packages/shared/src/dpop.test.tsdeleted file mode 100644index c4ba298f6..000000000--- a/packages/shared/src/dpop.test.ts+++ /dev/null@@ -1,251 +0,0 @@-import * as NodeCrypto from "node:crypto";--import { assert, describe, it } from "@effect/vitest";--import {- computeDpopAccessTokenHash,- computeDpopJwkThumbprint,- normalizeDpopHtu,- type DpopPublicJwk,- verifyDpopProof,-} from "./dpop.ts";--function signDpopProof(input: {- readonly method: string;- readonly url: string;- readonly iat: number;- readonly privateKey: NodeCrypto.KeyObject;- readonly publicJwk: DpopPublicJwk | (DpopPublicJwk & { readonly d: string });- readonly accessToken?: string;-}) {- const header = Buffer.from(- JSON.stringify({- typ: "dpop+jwt",- alg: "ES256",- jwk: input.publicJwk,- }),- ).toString("base64url");- const payload = Buffer.from(- JSON.stringify({- htm: input.method,- htu: input.url,- jti: "proof-1",- iat: input.iat,- ...(input.accessToken ? { ath: computeDpopAccessTokenHash(input.accessToken) } : {}),- }),- ).toString("base64url");- const signature = NodeCrypto.sign("sha256", Buffer.from(`${header}.${payload}`), {- key: input.privateKey,- dsaEncoding: "ieee-p1363",- }).toString("base64url");- return `${header}.${payload}.${signature}`;-}--describe("verifyDpopProof", () => {- const { privateKey, publicKey } = NodeCrypto.generateKeyPairSync("ec", {- namedCurve: "P-256",- });- const publicJwk = publicKey.export({ format: "jwk" }) as DpopPublicJwk;- const proof = signDpopProof({- method: "POST",- url: "https://example.com/oauth/token",- iat: 100,- privateKey,- publicJwk,- });-- it("verifies an ES256 DPoP proof and returns the RFC 7638 thumbprint", () => {- const thumbprint = computeDpopJwkThumbprint(publicJwk);- const result = verifyDpopProof({- proof,- method: "POST",- url: "https://example.com/oauth/token",- nowEpochSeconds: 101,- expectedThumbprint: thumbprint,- });-- if (!result.ok) {- assert.fail(result.reason);- }- assert.equal(result.thumbprint, thumbprint);- assert.equal(result.jti, "proof-1");- });-- it("rejects malformed DPoP header and payload JSON", () => {- const [header, payload, signature] = proof.split(".");- if (!header || !payload || !signature) {- assert.fail("Expected the test DPoP proof to use compact JWT format.");- }- const malformedJson = Buffer.from("{").toString("base64url");-- const malformedHeader = verifyDpopProof({- proof: `${malformedJson}.${payload}.${signature}`,- method: "POST",- url: "https://example.com/oauth/token",- nowEpochSeconds: 101,- });- if (malformedHeader.ok) {- assert.fail("Expected malformed DPoP header JSON to fail.");- }- assert.equal(malformedHeader.reason, "Invalid DPoP JWT header.");-- const malformedPayload = verifyDpopProof({- proof: `${header}.${malformedJson}.${signature}`,- method: "POST",- url: "https://example.com/oauth/token",- nowEpochSeconds: 101,- });- if (malformedPayload.ok) {- assert.fail("Expected malformed DPoP payload JSON to fail.");- }- assert.equal(malformedPayload.reason, "Invalid DPoP JWT payload.");- });-- it("rejects method, URL, thumbprint, and time-window mismatches", () => {- const thumbprint = computeDpopJwkThumbprint(publicJwk);- assert.equal(- verifyDpopProof({- proof,- method: "GET",- url: "https://example.com/oauth/token",- nowEpochSeconds: 101,- expectedThumbprint: thumbprint,- }).ok,- false,- );- assert.equal(- verifyDpopProof({- proof,- method: "POST",- url: "https://example.com/other",- nowEpochSeconds: 101,- expectedThumbprint: thumbprint,- }).ok,- false,- );- assert.equal(- verifyDpopProof({- proof,- method: "POST",- url: "https://example.com/oauth/token",- nowEpochSeconds: 101,- expectedThumbprint: "other-thumbprint",- }).ok,- false,- );- assert.equal(- verifyDpopProof({- proof,- method: "POST",- url: "https://example.com/oauth/token",- nowEpochSeconds: 1_000,- expectedThumbprint: thumbprint,- }).ok,- false,- );- });-- it("requires the RFC 9449 access token hash when an access token is expected", () => {- const thumbprint = computeDpopJwkThumbprint(publicJwk);- const accessTokenProof = signDpopProof({- method: "POST",- url: "https://example.com/v1/environments/env/connect",- iat: 100,- privateKey,- publicJwk,- accessToken: "clerk-access-token",- });-- assert.equal(- verifyDpopProof({- proof: accessTokenProof,- method: "POST",- url: "https://example.com/v1/environments/env/connect",- nowEpochSeconds: 101,- expectedThumbprint: thumbprint,- expectedAccessToken: "clerk-access-token",- }).ok,- true,- );-- const missingHash = verifyDpopProof({- proof,- method: "POST",- url: "https://example.com/oauth/token",- nowEpochSeconds: 101,- expectedThumbprint: thumbprint,- expectedAccessToken: "clerk-access-token",- });- if (missingHash.ok) {- assert.fail("Expected DPoP proof without an access token hash to fail.");- }- assert.equal(missingHash.reason, "DPoP access token hash mismatch.");-- const mismatchedHash = verifyDpopProof({- proof: accessTokenProof,- method: "POST",- url: "https://example.com/v1/environments/env/connect",- nowEpochSeconds: 101,- expectedThumbprint: thumbprint,- expectedAccessToken: "other-access-token",- });- if (mismatchedHash.ok) {- assert.fail("Expected DPoP proof with a mismatched access token hash to fail.");- }- assert.equal(mismatchedHash.reason, "DPoP access token hash mismatch.");- });-- it("normalizes htu by excluding query and fragment components per RFC 9449", () => {- assert.equal(- normalizeDpopHtu("https://example.com/v1/environments/env/connect?foo=bar#frag"),- "https://example.com/v1/environments/env/connect",- );-- const thumbprint = computeDpopJwkThumbprint(publicJwk);- const queryProof = signDpopProof({- method: "POST",- url: "https://example.com/v1/environments/env/connect",- iat: 100,- privateKey,- publicJwk,- });-- assert.equal(- verifyDpopProof({- proof: queryProof,- method: "POST",- url: "https://example.com/v1/environments/env/connect?foo=bar#frag",- nowEpochSeconds: 101,- expectedThumbprint: thumbprint,- }).ok,- true,- );- });-- it("rejects DPoP public JWK headers that expose private key material", () => {- const thumbprint = computeDpopJwkThumbprint(publicJwk);- const privateJwk = privateKey.export({ format: "jwk" }) as DpopPublicJwk & {- readonly d: string;- };- const proofWithPrivateJwk = signDpopProof({- method: "POST",- url: "https://example.com/oauth/token",- iat: 100,- privateKey,- publicJwk: privateJwk,- });-- const result = verifyDpopProof({- proof: proofWithPrivateJwk,- method: "POST",- url: "https://example.com/oauth/token",- nowEpochSeconds: 101,- expectedThumbprint: thumbprint,- });-- if (result.ok) {- assert.fail("Expected DPoP proof with private JWK material to fail.");- }- assert.equal(result.reason, "Invalid DPoP JWT header.");- });-});diff --git a/packages/shared/src/dpop.ts b/packages/shared/src/dpop.tsdeleted file mode 100644index dabfaffa4..000000000--- a/packages/shared/src/dpop.ts+++ /dev/null@@ -1,175 +0,0 @@-import { p256 } from "@noble/curves/nist";-import { sha256 } from "@noble/hashes/sha2";-import * as Encoding from "effect/Encoding";-import * as Option from "effect/Option";-import * as Result from "effect/Result";-import * as Schema from "effect/Schema";--import { DpopPublicJwk as DpopPublicJwkSchema, normalizeDpopHtu } from "./dpopCommon.ts";-import type { DpopPublicJwk as DpopPublicJwkType } from "./dpopCommon.ts";-import { stableStringify } from "./relaySigning.ts";--const DPOP_TYP = "dpop+jwt";-const DPOP_ALG = "ES256";-const DEFAULT_MAX_AGE_SECONDS = 300;--export const DpopPublicJwk = DpopPublicJwkSchema;-export type DpopPublicJwk = DpopPublicJwkType;-export { normalizeDpopHtu };--const DpopJwtHeaderPublicJwk = Schema.Struct({- ...DpopPublicJwkSchema.fields,- d: Schema.optionalKey(Schema.Never),-});--const DpopJwtHeaderJson = Schema.fromJsonString(- Schema.Struct({- typ: Schema.Literal(DPOP_TYP),- alg: Schema.Literal(DPOP_ALG),- jwk: DpopJwtHeaderPublicJwk,- }),-);-const decodeDpopJwtHeaderJson = Schema.decodeUnknownOption(DpopJwtHeaderJson);--const DpopJwtPayloadJson = Schema.fromJsonString(- Schema.Struct({- htm: Schema.String.check(Schema.isNonEmpty()),- htu: Schema.String.check(Schema.isNonEmpty()),- jti: Schema.String.check(Schema.isNonEmpty()),- iat: Schema.Int,- ath: Schema.optionalKey(Schema.String),- }),-);-const decodeDpopJwtPayloadJson = Schema.decodeUnknownOption(DpopJwtPayloadJson);--export type DpopVerificationResult =- | {- readonly ok: true;- readonly thumbprint: string;- readonly jti: string;- readonly iat: number;- }- | {- readonly ok: false;- readonly reason: string;- };--function base64UrlToBytes(value: string): Uint8Array {- return Result.getOrThrow(Encoding.decodeBase64Url(value));-}--function decodeBase64UrlDpopJwtHeader(value: string) {- return decodeDpopJwtHeaderJson(Result.getOrThrow(Encoding.decodeBase64UrlString(value)));-}--function decodeBase64UrlDpopJwtPayload(value: string) {- return decodeDpopJwtPayloadJson(Result.getOrThrow(Encoding.decodeBase64UrlString(value)));-}--function dpopThumbprintInput(jwk: DpopPublicJwkType): string {- return stableStringify({- crv: jwk.crv,- kty: jwk.kty,- x: jwk.x,- y: jwk.y,- });-}--export function computeDpopJwkThumbprint(jwk: DpopPublicJwkType): string {- return Encoding.encodeBase64Url(sha256(new TextEncoder().encode(dpopThumbprintInput(jwk))));-}--export function computeDpopAccessTokenHash(accessToken: string): string {- return Encoding.encodeBase64Url(sha256(new TextEncoder().encode(accessToken)));-}--function publicKeyBytesFromJwk(jwk: DpopPublicJwkType): Uint8Array {- const x = base64UrlToBytes(jwk.x);- const y = base64UrlToBytes(jwk.y);- if (x.length !== 32 || y.length !== 32) {- throw new Error("Invalid P-256 public key coordinate length.");- }- const publicKey = new Uint8Array(65);- publicKey[0] = 0x04;- publicKey.set(x, 1);- publicKey.set(y, 33);- return publicKey;-}--export function verifyDpopProof(input: {- readonly proof: string | null | undefined;- readonly method: string;- readonly url: string;- readonly nowEpochSeconds: number;- readonly expectedThumbprint?: string;- readonly expectedAccessToken?: string;- readonly maxAgeSeconds?: number;-}): DpopVerificationResult {- if (!input.proof?.trim()) {- return { ok: false, reason: "Missing DPoP proof." };- }-- const parts = input.proof.split(".");- if (parts.length !== 3 || !parts[0] || !parts[1] || !parts[2]) {- return { ok: false, reason: "Invalid DPoP compact JWT." };- }-- try {- const header = decodeBase64UrlDpopJwtHeader(parts[0]);- const payload = decodeBase64UrlDpopJwtPayload(parts[1]);- if (Option.isNone(header)) {- return { ok: false, reason: "Invalid DPoP JWT header." };- }- if (Option.isNone(payload)) {- return { ok: false, reason: "Invalid DPoP JWT payload." };- }-- const thumbprint = computeDpopJwkThumbprint(header.value.jwk);- if (input.expectedThumbprint && thumbprint !== input.expectedThumbprint) {- return { ok: false, reason: "DPoP key thumbprint mismatch." };- }- if (payload.value.htm.toUpperCase() !== input.method.toUpperCase()) {- return { ok: false, reason: "DPoP method mismatch." };- }- const normalizedHtu = normalizeDpopHtu(input.url);- if (normalizedHtu === null || payload.value.htu !== normalizedHtu) {- return { ok: false, reason: "DPoP URL mismatch." };- }- if (input.expectedAccessToken) {- const expectedAth = computeDpopAccessTokenHash(input.expectedAccessToken);- if (payload.value.ath !== expectedAth) {- return { ok: false, reason: "DPoP access token hash mismatch." };- }- }-- const maxAgeSeconds = input.maxAgeSeconds ?? DEFAULT_MAX_AGE_SECONDS;- if (- payload.value.iat > input.nowEpochSeconds + 5 ||- input.nowEpochSeconds - payload.value.iat > maxAgeSeconds- ) {- return { ok: false, reason: "DPoP proof is outside the allowed time window." };- }-- const signature = base64UrlToBytes(parts[2]);- const signatureInputHash = sha256(new TextEncoder().encode(`${parts[0]}.${parts[1]}`));- const verified = p256.verify(- signature,- signatureInputHash,- publicKeyBytesFromJwk(header.value.jwk),- {- prehash: false,- format: "compact",- },- );- return verified- ? {- ok: true,- thumbprint,- jti: payload.value.jti,- iat: payload.value.iat,- }- : { ok: false, reason: "Invalid DPoP signature." };- } catch {- return { ok: false, reason: "Invalid DPoP proof." };- }-}diff --git a/packages/shared/src/dpopCommon.ts b/packages/shared/src/dpopCommon.tsdeleted file mode 100644index ba57b016c..000000000--- a/packages/shared/src/dpopCommon.ts+++ /dev/null@@ -1,20 +0,0 @@-import * as Schema from "effect/Schema";--export const DpopPublicJwk = Schema.Struct({- kty: Schema.Literal("EC"),- crv: Schema.Literal("P-256"),- x: Schema.String.check(Schema.isNonEmpty()),- y: Schema.String.check(Schema.isNonEmpty()),-});-export type DpopPublicJwk = typeof DpopPublicJwk.Type;--export function normalizeDpopHtu(url: string): string | null {- try {- const parsed = new URL(url);- parsed.hash = "";- parsed.search = "";- return parsed.toString();- } catch {- return null;- }-}diff --git a/packages/shared/src/httpObservability.ts b/packages/shared/src/httpObservability.tsdeleted file mode 100644index 82ce05003..000000000--- a/packages/shared/src/httpObservability.ts+++ /dev/null@@ -1,8 +0,0 @@-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";-import * as Headers from "effect/unstable/http/Headers";--export const httpHeaderRedactionLayer = Layer.effect(- Headers.CurrentRedactedNames,- Effect.map(Headers.CurrentRedactedNames, (names) => [...names, "dpop"]),-);diff --git a/packages/shared/src/oauthScope.test.ts b/packages/shared/src/oauthScope.test.tsindex f5cc247a2..8474c543a 100644--- a/packages/shared/src/oauthScope.test.ts+++ b/packages/shared/src/oauthScope.test.ts@@ -35,7 +35,7 @@ describe("OAuth scopes", () => {).toEqual(["orchestration:read", "access:write"]);expect(parseAllowedOAuthScope({- value: "orchestration:read relay:write",+ value: "orchestration:read admin:write",allowedScopes: new Set(["orchestration:read", "access:write"] as const),}),).toBeNull();diff --git a/packages/shared/src/relayAuth.test.ts b/packages/shared/src/relayAuth.test.tsdeleted file mode 100644index 3abff9b52..000000000--- a/packages/shared/src/relayAuth.test.ts+++ /dev/null@@ -1,88 +0,0 @@-import { describe, expect, it } from "vite-plus/test";--import {- ClerkPublishableKeyDecodeError,- ClerkPublishableKeyFrontendApiError,- clerkFrontendApiHostnameFromPublishableKey,- clerkFrontendApiUrlFromPublishableKey,- isAllowedClerkFrontendApiHostname,-} from "./relayAuth.ts";--const clerkPublishableKey = (hostname: string): string => `pk_test_${btoa(`${hostname}$`)}`;--const captureError = (run: () => unknown): unknown => {- try {- run();- } catch (cause) {- return cause;- }- throw new Error("Expected operation to throw");-};--describe("Clerk relay auth", () => {- it("derives a custom Frontend API hostname from a Clerk publishable key", () => {- expect(clerkFrontendApiHostnameFromPublishableKey(clerkPublishableKey("clerk.t3.codes"))).toBe(- "clerk.t3.codes",- );- expect(clerkFrontendApiUrlFromPublishableKey(clerkPublishableKey("clerk.t3.codes"))).toBe(- "https://clerk.t3.codes",- );- });-- it("preserves Clerk publishable key decoding failures", () => {- const error = captureError(() => clerkFrontendApiUrlFromPublishableKey("pk_test_%"));-- expect(error).toBeInstanceOf(ClerkPublishableKeyDecodeError);- expect(error).toMatchObject({ keyPrefix: "pk_test" });- expect((error as ClerkPublishableKeyDecodeError).cause).toBeInstanceOf(Error);- expect((error as Error).message).toBe("Failed to decode Clerk publishable key (pk_test).");- });-- it("reports semantic frontend API failures without inventing a cause", () => {- const emptyError = captureError(() => clerkFrontendApiUrlFromPublishableKey("pk_test_"));- const pathFrontendApi = "clerk.t3.codes/path";- const pathError = captureError(() =>- clerkFrontendApiUrlFromPublishableKey(clerkPublishableKey(pathFrontendApi)),- );-- expect(emptyError).toBeInstanceOf(ClerkPublishableKeyFrontendApiError);- expect(emptyError).toMatchObject({- keyPrefix: "pk_test",- frontendApi: "",- reason: "empty",- });- expect((emptyError as Error & { cause?: unknown }).cause).toBeUndefined();- expect(pathError).toBeInstanceOf(ClerkPublishableKeyFrontendApiError);- expect(pathError).toMatchObject({- keyPrefix: "pk_test",- frontendApi: pathFrontendApi,- reason: "contains-path",- });- expect((pathError as Error & { cause?: unknown }).cause).toBeUndefined();- });-- it("preserves URL parser failures for decoded frontend APIs", () => {- const frontendApi = "[invalid-host";- const error = captureError(() =>- clerkFrontendApiHostnameFromPublishableKey(clerkPublishableKey(frontendApi)),- );-- expect(error).toBeInstanceOf(ClerkPublishableKeyFrontendApiError);- expect(error).toMatchObject({- keyPrefix: "pk_test",- frontendApi,- reason: "invalid-url",- });- expect((error as ClerkPublishableKeyFrontendApiError).cause).toBeInstanceOf(Error);- });-- it("allows standard Clerk hosts and an exact configured custom hostname", () => {- expect(isAllowedClerkFrontendApiHostname("example.clerk.accounts.dev", null)).toBe(true);- expect(isAllowedClerkFrontendApiHostname("example.clerk.accounts.com", null)).toBe(true);- expect(isAllowedClerkFrontendApiHostname("clerk.t3.codes", "clerk.t3.codes")).toBe(true);- expect(isAllowedClerkFrontendApiHostname("attacker.example", "clerk.t3.codes")).toBe(false);- expect(isAllowedClerkFrontendApiHostname("nested.clerk.t3.codes", "clerk.t3.codes")).toBe(- false,- );- });-});diff --git a/packages/shared/src/relayAuth.ts b/packages/shared/src/relayAuth.tsdeleted file mode 100644index a384db77d..000000000--- a/packages/shared/src/relayAuth.ts+++ /dev/null@@ -1,100 +0,0 @@-import * as Schema from "effect/Schema";--const ClerkPublishableKeyPrefix = Schema.Literals(["pk_test", "pk_live", "unknown"]);--export class ClerkPublishableKeyDecodeError extends Schema.TaggedErrorClass<ClerkPublishableKeyDecodeError>()(- "ClerkPublishableKeyDecodeError",- {- keyPrefix: ClerkPublishableKeyPrefix,- cause: Schema.Defect(),- },-) {- override get message(): string {- return `Failed to decode Clerk publishable key (${this.keyPrefix}).`;- }-}--export class ClerkPublishableKeyFrontendApiError extends Schema.TaggedErrorClass<ClerkPublishableKeyFrontendApiError>()(- "ClerkPublishableKeyFrontendApiError",- {- keyPrefix: ClerkPublishableKeyPrefix,- frontendApi: Schema.String,- reason: Schema.Literals(["empty", "contains-path", "invalid-url"]),- cause: Schema.optional(Schema.Defect()),- },-) {- override get message(): string {- return `Invalid Clerk frontend API decoded from publishable key (${this.keyPrefix}; ${this.reason}).`;- }-}--function parseClerkFrontendApi(publishableKey: string): {- readonly hostname: string;- readonly url: string;-} {- const keyPrefix = publishableKey.startsWith("pk_test_")- ? "pk_test"- : publishableKey.startsWith("pk_live_")- ? "pk_live"- : "unknown";- const encodedFrontendApi = publishableKey.split("_").slice(2).join("_");- let frontendApi: string;- try {- frontendApi = globalThis.atob(encodedFrontendApi).replace(/\$$/u, "");- } catch (cause) {- throw new ClerkPublishableKeyDecodeError({ keyPrefix, cause });- }-- if (frontendApi.length === 0) {- throw new ClerkPublishableKeyFrontendApiError({- keyPrefix,- frontendApi,- reason: "empty",- });- }- if (frontendApi.includes("/")) {- throw new ClerkPublishableKeyFrontendApiError({- keyPrefix,- frontendApi,- reason: "contains-path",- });- }-- const url = `https://${frontendApi}`;- try {- return { hostname: new URL(url).hostname, url };- } catch (cause) {- throw new ClerkPublishableKeyFrontendApiError({- keyPrefix,- frontendApi,- reason: "invalid-url",- cause,- });- }-}--export function clerkFrontendApiUrlFromPublishableKey(publishableKey: string): string {- return parseClerkFrontendApi(publishableKey).url;-}--export function clerkFrontendApiHostnameFromPublishableKey(publishableKey: string): string {- return parseClerkFrontendApi(publishableKey).hostname;-}--export function isAllowedClerkFrontendApiHostname(- hostname: string,- configuredHostname: string | null,-): boolean {- return (- hostname.endsWith(".clerk.accounts.dev") ||- hostname.endsWith(".clerk.accounts.com") ||- hostname === configuredHostname- );-}--export function relayClerkTokenOptions(template: string) {- return {- template,- skipCache: true,- } as const;-}diff --git a/packages/shared/src/relayClient.test.ts b/packages/shared/src/relayClient.test.tsdeleted file mode 100644index df39ef0b1..000000000--- a/packages/shared/src/relayClient.test.ts+++ /dev/null@@ -1,271 +0,0 @@-import { sha256 } from "@noble/hashes/sha2";-import * as NodeServices from "@effect/platform-node/NodeServices";-import { describe, expect, it } from "@effect/vitest";-import * as ConfigProvider from "effect/ConfigProvider";-import * as Effect from "effect/Effect";-import * as Encoding from "effect/Encoding";-import * as FileSystem from "effect/FileSystem";-import * as Layer from "effect/Layer";-import * as Sink from "effect/Sink";-import * as Stream from "effect/Stream";-import { HttpClient, HttpClientResponse } from "effect/unstable/http";-import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";-import { HostProcessArchitecture, HostProcessPlatform } from "./hostProcess.ts";--import {- RelayClientInstallError,- CLOUDFLARED_VERSION,- makeCloudflaredRelayClient,-} from "./relayClient.ts";--const hostRuntimeLayer = (env: Record<string, string> = {}) =>- Layer.mergeAll(- Layer.succeed(HostProcessPlatform, "linux"),- Layer.succeed(HostProcessArchitecture, "x64"),- ConfigProvider.layer(ConfigProvider.fromEnv({ env })),- );--function makeHandle(exitCode = 0) {- return ChildProcessSpawner.makeHandle({- pid: ChildProcessSpawner.ProcessId(100),- exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(exitCode)),- isRunning: Effect.succeed(false),- kill: () => Effect.void,- unref: Effect.succeed(Effect.void),- stdin: Sink.drain,- stdout: Stream.empty,- stderr: Stream.empty,- all: Stream.empty,- getInputFd: () => Sink.drain,- getOutputFd: () => Stream.empty,- });-}--const makeHttpClientLayer = (bytes: Uint8Array) =>- Layer.succeed(- HttpClient.HttpClient,- HttpClient.make((request) =>- Effect.succeed(- HttpClientResponse.fromWeb(request, new Response(bytes.buffer as ArrayBuffer)),- ),- ),- );--const makeSpawnerLayer = (commands: Array<string>) =>- Layer.succeed(- ChildProcessSpawner.ChildProcessSpawner,- ChildProcessSpawner.make((command) =>- Effect.sync(() => {- commands.push(ChildProcess.isStandardCommand(command) ? command.command : "piped-command");- return makeHandle();- }),- ),- );--describe("RelayClient", () => {- it.effect("resolves explicit overrides before managed and PATH executables", () =>- Effect.gen(function* () {- const fileSystem = yield* FileSystem.FileSystem;- const baseDir = yield* fileSystem.makeTempDirectoryScoped({- prefix: "t3-cloudflared-test-",- });- const overridePath = `${baseDir}/override-cloudflared`;- yield* fileSystem.writeFileString(overridePath, "override");- yield* fileSystem.chmod(overridePath, 0o755);- const manager = yield* makeCloudflaredRelayClient({- baseDir,- });-- expect(- yield* manager.resolve.pipe(- Effect.provideService(- ConfigProvider.ConfigProvider,- ConfigProvider.fromEnv({- env: { PATH: "", T3CODE_CLOUDFLARED_PATH: overridePath },- }),- ),- ),- ).toEqual({- status: "available",- executablePath: overridePath,- source: "override",- version: CLOUDFLARED_VERSION,- });- }).pipe(- Effect.scoped,- Effect.provide(- Layer.mergeAll(- NodeServices.layer,- makeHttpClientLayer(new Uint8Array()),- makeSpawnerLayer([]),- hostRuntimeLayer(),- ),- ),- ),- );-- it.effect("downloads, verifies, validates, and atomically installs the managed executable", () =>- Effect.gen(function* () {- const fileSystem = yield* FileSystem.FileSystem;- const baseDir = yield* fileSystem.makeTempDirectoryScoped({- prefix: "t3-cloudflared-test-",- });- const bytes = new TextEncoder().encode("test-cloudflared-binary");- const manager = yield* makeCloudflaredRelayClient({- baseDir,- releaseAsset: {- url: "https://example.test/cloudflared",- sha256: Encoding.encodeHex(sha256(bytes)),- archive: "binary",- },- });-- const progress: Array<string> = [];- const installed = yield* manager.installWithProgress((event) =>- Effect.sync(() => {- if (event.type === "progress") {- progress.push(event.stage);- }- }),- );- const managedPath = `${baseDir}/tools/cloudflared/${CLOUDFLARED_VERSION}/linux-x64/cloudflared`;- expect(installed).toEqual({- status: "available",- executablePath: managedPath,- source: "managed",- version: CLOUDFLARED_VERSION,- });- expect(new TextDecoder().decode(yield* fileSystem.readFile(managedPath))).toBe(- "test-cloudflared-binary",- );- expect(progress).toEqual([- "checking",- "waiting_for_lock",- "downloading",- "verifying",- "installing",- "validating",- "activating",- ]);- expect(yield* manager.resolve).toEqual(installed);- }).pipe(- Effect.scoped,- Effect.provide(- Layer.mergeAll(- NodeServices.layer,- makeHttpClientLayer(new TextEncoder().encode("test-cloudflared-binary")),- makeSpawnerLayer([]),- hostRuntimeLayer(),- ),- ),- ),- );-- it.effect("rejects downloads whose checksum does not match the pinned manifest", () =>- Effect.gen(function* () {- const fileSystem = yield* FileSystem.FileSystem;- const baseDir = yield* fileSystem.makeTempDirectoryScoped({- prefix: "t3-cloudflared-test-",- });- const manager = yield* makeCloudflaredRelayClient({- baseDir,- releaseAsset: {- url: "https://example.test/cloudflared",- sha256: Encoding.encodeHex(sha256(new TextEncoder().encode("expected"))),- archive: "binary",- },- });-- const error = yield* manager.install.pipe(Effect.flip);- expect(error).toBeInstanceOf(RelayClientInstallError);- expect(error.reason).toBe("invalid_checksum");- }).pipe(- Effect.scoped,- Effect.provide(- Layer.mergeAll(- NodeServices.layer,- makeHttpClientLayer(new TextEncoder().encode("tampered")),- makeSpawnerLayer([]),- hostRuntimeLayer(),- ),- ),- ),- );-- it.effect("serializes concurrent installs within one runtime", () => {- const commands: Array<string> = [];- const bytes = new TextEncoder().encode("test-cloudflared-binary");- return Effect.gen(function* () {- const fileSystem = yield* FileSystem.FileSystem;- const baseDir = yield* fileSystem.makeTempDirectoryScoped({- prefix: "t3-cloudflared-test-",- });- const manager = yield* makeCloudflaredRelayClient({- baseDir,- releaseAsset: {- url: "https://example.test/cloudflared",- sha256: Encoding.encodeHex(sha256(bytes)),- archive: "binary",- },- });-- const [first, second] = yield* Effect.all([manager.install, manager.install], {- concurrency: "unbounded",- });- expect(second).toEqual(first);- expect(commands).toHaveLength(1);- }).pipe(- Effect.scoped,- Effect.provide(- Layer.mergeAll(- NodeServices.layer,- makeHttpClientLayer(bytes),- makeSpawnerLayer(commands),- hostRuntimeLayer(),- ),- ),- );- });-- it.effect("observes PATH changes after the manager has been constructed", () => {- const env = { PATH: "" };- return Effect.gen(function* () {- const fileSystem = yield* FileSystem.FileSystem;- const baseDir = yield* fileSystem.makeTempDirectoryScoped({- prefix: "t3-cloudflared-test-",- });- const binDir = `${baseDir}/bin`;- const executablePath = `${binDir}/cloudflared`;- const manager = yield* makeCloudflaredRelayClient({- baseDir,- });-- expect(yield* manager.resolve).toEqual({- status: "missing",- version: CLOUDFLARED_VERSION,- });-- yield* fileSystem.makeDirectory(binDir);- yield* fileSystem.writeFileString(executablePath, "cloudflared");- yield* fileSystem.chmod(executablePath, 0o755);- env.PATH = binDir;-- expect(yield* manager.resolve).toEqual({- status: "available",- executablePath,- source: "path",- version: CLOUDFLARED_VERSION,- });- }).pipe(- Effect.scoped,- Effect.provide(- Layer.mergeAll(- NodeServices.layer,- makeHttpClientLayer(new Uint8Array()),- makeSpawnerLayer([]),- hostRuntimeLayer(env),- ),- ),- );- });-});diff --git a/packages/shared/src/relayClient.ts b/packages/shared/src/relayClient.tsdeleted file mode 100644index c715d9cfd..000000000--- a/packages/shared/src/relayClient.ts+++ /dev/null@@ -1,476 +0,0 @@-import * as Clock from "effect/Clock";-import type {- RelayClientInstallProgressEvent,- RelayClientInstallProgressStage,-} from "@t3tools/contracts";-import * as Config from "effect/Config";-import * as Context from "effect/Context";-import * as Crypto from "effect/Crypto";-import * as Data from "effect/Data";-import * as Effect from "effect/Effect";-import * as Encoding from "effect/Encoding";-import * as FileSystem from "effect/FileSystem";-import * as Layer from "effect/Layer";-import * as Option from "effect/Option";-import * as Path from "effect/Path";-import * as PlatformError from "effect/PlatformError";-import * as Semaphore from "effect/Semaphore";-import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";-import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";-import { HostProcessArchitecture, HostProcessPlatform } from "./hostProcess.ts";--export const CLOUDFLARED_VERSION = "2026.5.2";-export const CLOUDFLARED_PATH_ENV_NAME = "T3CODE_CLOUDFLARED_PATH";--export type RelayClientExecutableSource = "override" | "managed" | "path";--export type RelayClientStatus =- | {- readonly status: "available";- readonly executablePath: string;- readonly source: RelayClientExecutableSource;- readonly version: string;- }- | {- readonly status: "missing";- readonly version: string;- }- | {- readonly status: "unsupported";- readonly platform: NodeJS.Platform;- readonly arch: string;- readonly version: string;- };--export type AvailableRelayClient = Extract<RelayClientStatus, { readonly status: "available" }>;--export class RelayClientInstallError extends Data.TaggedError("RelayClientInstallError")<{- readonly reason:- | "download_failed"- | "invalid_checksum"- | "install_locked"- | "override_missing"- | "unsupported_platform"- | "validation_failed"- | "write_failed";- readonly message: string;- readonly cause?: unknown;-}> {}--class CloudflaredCommandError extends Data.TaggedError("CloudflaredCommandError")<{- readonly command: string;- readonly exitCode: number;-}> {}--export interface CloudflaredReleaseAsset {- readonly url: string;- readonly sha256: string;- readonly archive: "binary" | "tgz";-}--const CLOUDFLARED_RELEASE_ASSETS: Readonly<- Partial<Record<`${NodeJS.Platform}-${string}`, CloudflaredReleaseAsset>>-> = {- "darwin-arm64": {- url: "https://github.com/cloudflare/cloudflared/releases/download/2026.5.2/cloudflared-darwin-arm64.tgz",- sha256: "ba94054c9fd4297645093d59d51442e5e546d07bb0516120e694a13d5b216d38",- archive: "tgz",- },- "darwin-x64": {- url: "https://github.com/cloudflare/cloudflared/releases/download/2026.5.2/cloudflared-darwin-amd64.tgz",- sha256: "7240f709506bc2c1eb9da4d89cf2555499c60280ecb854b7d80e8f17d4b7903d",- archive: "tgz",- },- "linux-arm64": {- url: "https://github.com/cloudflare/cloudflared/releases/download/2026.5.2/cloudflared-linux-arm64",- sha256: "5a4e8ce2701105271412059f44b6a0bf1ae4542b4d98ff3180c0c019443a5815",- archive: "binary",- },- "linux-x64": {- url: "https://github.com/cloudflare/cloudflared/releases/download/2026.5.2/cloudflared-linux-amd64",- sha256: "5286698547f03df745adb2355f04c12dde52ef425491e81f433642d695521886",- archive: "binary",- },- "win32-x64": {- url: "https://github.com/cloudflare/cloudflared/releases/download/2026.5.2/cloudflared-windows-amd64.exe",- sha256: "20b9638f685333d623798e733effbad2487093f15ba592f6c7752360ff3b7ab7",- archive: "binary",- },-};--const INSTALL_LOCK_RETRY_COUNT = 100;-const INSTALL_LOCK_RETRY_DELAY = "100 millis";-const INSTALL_LOCK_STALE_MS = 5 * 60 * 1_000;--const trimmedString = (name: string) =>- Config.string(name).pipe(- Config.option,- Config.map(- Option.flatMap((value) => {- const trimmed = value.trim();- return trimmed.length > 0 ? Option.some(trimmed) : Option.none();- }),- ),- );--const CloudflaredConfig = Config.all({- executableOverride: trimmedString(CLOUDFLARED_PATH_ENV_NAME),- path: trimmedString("PATH"),-});--export interface CloudflaredRelayClientOptions {- readonly baseDir: string;- readonly releaseAsset?: CloudflaredReleaseAsset;-}--export interface RelayClientShape {- readonly resolve: Effect.Effect<RelayClientStatus>;- readonly install: Effect.Effect<AvailableRelayClient, RelayClientInstallError>;- readonly installWithProgress: (- report: (event: RelayClientInstallProgressEvent) => Effect.Effect<void>,- ) => Effect.Effect<AvailableRelayClient, RelayClientInstallError>;-}--export class RelayClient extends Context.Service<RelayClient, RelayClientShape>()(- "@t3tools/shared/relayClient",-) {}--function executableFileName(platform: NodeJS.Platform): string {- return platform === "win32" ? "cloudflared.exe" : "cloudflared";-}--function resolveReleaseAsset(- platform: NodeJS.Platform,- arch: string,-): CloudflaredReleaseAsset | null {- return CLOUDFLARED_RELEASE_ASSETS[`${platform}-${arch}`] ?? null;-}--function isAlreadyExists(error: PlatformError.PlatformError): boolean {- return error.reason._tag === "AlreadyExists";-}--const wrapInstallFailure =- (- reason: RelayClientInstallError["reason"],- message: string,- ): (<E, R>(- effect: Effect.Effect<void, E, R>,- ) => Effect.Effect<void, RelayClientInstallError, R>) =>- (effect) =>- effect.pipe(- Effect.mapError(- (cause) =>- new RelayClientInstallError({- reason,- message,- cause,- }),- ),- );--export const makeCloudflaredRelayClient = Effect.fn("cloudflared.make")(function* (- options: CloudflaredRelayClientOptions,-): Effect.fn.Return<- RelayClientShape,- never,- | ChildProcessSpawner.ChildProcessSpawner- | Crypto.Crypto- | FileSystem.FileSystem- | HttpClient.HttpClient- | Path.Path-> {- const crypto = yield* Crypto.Crypto;- const fileSystem = yield* FileSystem.FileSystem;- const httpClient = yield* HttpClient.HttpClient;- const path = yield* Path.Path;- const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;- const installSemaphore = yield* Semaphore.make(1);- const platform = yield* HostProcessPlatform;- const arch = yield* HostProcessArchitecture;- const releaseAsset = options.releaseAsset ?? resolveReleaseAsset(platform, arch);- const loadCloudflaredConfig = Effect.suspend(() => CloudflaredConfig).pipe(Effect.orDie);- const managedPath = path.join(- options.baseDir,- "tools",- "cloudflared",- CLOUDFLARED_VERSION,- `${platform}-${arch}`,- executableFileName(platform),- );-- const isExecutableFile = Effect.fn("cloudflared.isExecutableFile")(function* (- executablePath: string,- ) {- const info = yield* fileSystem.stat(executablePath).pipe(Effect.option);- if (Option.isNone(info) || info.value.type !== "File") return false;- return platform === "win32" || (info.value.mode & 0o111) !== 0;- });-- const resolvePathExecutable = Effect.gen(function* () {- const config = yield* loadCloudflaredConfig;- const pathValue = Option.getOrUndefined(config.path);- if (!pathValue) return null;- const delimiter = platform === "win32" ? ";" : ":";- for (const directory of pathValue.split(delimiter)) {- const trimmed = directory.trim().replace(/^"|"$/gu, "");- if (trimmed.length === 0) continue;- const candidate = path.join(trimmed, executableFileName(platform));- if (yield* isExecutableFile(candidate)) return candidate;- }- return null;- });-- const resolve: RelayClientShape["resolve"] = Effect.gen(function* () {- const config = yield* loadCloudflaredConfig;- if (Option.isSome(config.executableOverride)) {- return (yield* isExecutableFile(config.executableOverride.value))- ? {- status: "available",- executablePath: config.executableOverride.value,- source: "override",- version: CLOUDFLARED_VERSION,- }- : { status: "missing", version: CLOUDFLARED_VERSION };- }- if (yield* isExecutableFile(managedPath)) {- return {- status: "available",- executablePath: managedPath,- source: "managed",- version: CLOUDFLARED_VERSION,- };- }- const pathExecutable = yield* resolvePathExecutable;- if (pathExecutable) {- return {- status: "available",- executablePath: pathExecutable,- source: "path",- version: CLOUDFLARED_VERSION,- };- }- return releaseAsset- ? { status: "missing", version: CLOUDFLARED_VERSION }- : {- status: "unsupported",- platform,- arch,- version: CLOUDFLARED_VERSION,- };- });-- const runCommand = Effect.fn("cloudflared.runCommand")(function* (- command: string,- args: ReadonlyArray<string>,- ) {- const child = yield* spawner.spawn(- ChildProcess.make(command, args, {- shell: false,- stdout: "ignore",- stderr: "ignore",- }),- );- const exitCode = Number(yield* child.exitCode);- if (exitCode !== 0) {- return yield* new CloudflaredCommandError({ command, exitCode });- }- });-- const downloadAsset = Effect.fn("cloudflared.downloadAsset")(function* (- asset: CloudflaredReleaseAsset,- report: (stage: RelayClientInstallProgressStage) => Effect.Effect<void>,- ) {- yield* report("downloading");- const response = yield* httpClient.execute(HttpClientRequest.get(asset.url)).pipe(- Effect.flatMap(HttpClientResponse.filterStatusOk),- Effect.mapError(- (cause) =>- new RelayClientInstallError({- reason: "download_failed",- message: "Could not download the relay client.",- cause,- }),- ),- );- const bytes = new Uint8Array(- yield* response.arrayBuffer.pipe(- Effect.mapError(- (cause) =>- new RelayClientInstallError({- reason: "download_failed",- message: "Could not read the downloaded relay client binary.",- cause,- }),- ),- ),- );- yield* report("verifying");- const checksum = yield* crypto.digest("SHA-256", bytes).pipe(- Effect.mapError(- (cause) =>- new RelayClientInstallError({- reason: "validation_failed",- message: "Could not verify the downloaded relay client checksum.",- cause,- }),- ),- );- if (Encoding.encodeHex(checksum) !== asset.sha256) {- return yield* new RelayClientInstallError({- reason: "invalid_checksum",- message: "Downloaded relay client checksum did not match the pinned release.",- });- }- return bytes;- });-- const acquireInstallLock = Effect.fn("cloudflared.acquireInstallLock")(function* (- lockPath: string,- ) {- for (let attempt = 0; attempt < INSTALL_LOCK_RETRY_COUNT; attempt += 1) {- const acquired = yield* fileSystem.writeFileString(lockPath, "", { flag: "wx" }).pipe(- Effect.as(true),- Effect.catch((error) =>- isAlreadyExists(error) ? Effect.succeed(false) : Effect.fail(error),- ),- );- if (acquired) return;-- const now = yield* Clock.currentTimeMillis;- const lockInfo = yield* fileSystem.stat(lockPath).pipe(Effect.option);- const mtime = Option.flatMap(lockInfo, (info) => info.mtime);- if (Option.isSome(mtime) && now - mtime.value.getTime() > INSTALL_LOCK_STALE_MS) {- yield* fileSystem.remove(lockPath, { force: true });- continue;- }- yield* Effect.sleep(INSTALL_LOCK_RETRY_DELAY);- }- return yield* new RelayClientInstallError({- reason: "install_locked",- message: "Another relay client installation is still in progress.",- });- });-- const installUnlocked = Effect.fn("cloudflared.installUnlocked")(function* (- report: (stage: RelayClientInstallProgressStage) => Effect.Effect<void>,- ) {- yield* report("checking");- const existing = yield* resolve;- if (existing.status === "available") return existing;- const config = yield* loadCloudflaredConfig;- if (Option.isSome(config.executableOverride)) {- return yield* new RelayClientInstallError({- reason: "override_missing",- message: `${CLOUDFLARED_PATH_ENV_NAME} does not point to an executable file.`,- });- }- if (!releaseAsset) {- return yield* new RelayClientInstallError({- reason: "unsupported_platform",- message: `Akeru Bot does not provide a managed relay client binary for ${platform}-${arch}.`,- });- }-- const managedDirectory = path.dirname(managedPath);- const lockPath = `${managedPath}.lock`;- yield* fileSystem- .makeDirectory(managedDirectory, { recursive: true })- .pipe(- wrapInstallFailure("write_failed", "Could not create the relay client tool directory."),- );- yield* report("waiting_for_lock");- yield* acquireInstallLock(lockPath).pipe(- Effect.catchTag("PlatformError", (cause) =>- Effect.fail(- new RelayClientInstallError({- reason: "write_failed",- message: "Could not acquire the relay client installation lock.",- cause,- }),- ),- ),- );- return yield* Effect.gen(function* () {- const afterLock = yield* resolve;- if (afterLock.status === "available") return afterLock;-- const tempDirectory = yield* fileSystem.makeTempDirectoryScoped({- directory: managedDirectory,- prefix: ".install-",- });- const archivePath = path.join(- tempDirectory,- releaseAsset.archive === "tgz" ? "cloudflared.tgz" : executableFileName(platform),- );- const download = yield* downloadAsset(releaseAsset, report);- yield* report("installing");- yield* fileSystem- .writeFile(archivePath, download)- .pipe(wrapInstallFailure("write_failed", "Could not write the relay client download."));-- const executablePath = path.join(tempDirectory, executableFileName(platform));- if (releaseAsset.archive === "tgz") {- yield* runCommand("tar", ["-xzf", archivePath, "-C", tempDirectory]).pipe(- wrapInstallFailure("write_failed", "Could not extract the relay client."),- );- }- if (platform !== "win32") {- yield* fileSystem- .chmod(executablePath, 0o755)- .pipe(wrapInstallFailure("write_failed", "Could not make the relay client executable."));- }- yield* report("validating");- yield* runCommand(executablePath, ["--version"]).pipe(- wrapInstallFailure("validation_failed", "The downloaded relay client binary did not run."),- );-- const stagedPath = `${managedPath}.${yield* crypto.randomUUIDv4}.tmp`;- yield* report("activating");- yield* fileSystem- .rename(executablePath, stagedPath)- .pipe(wrapInstallFailure("write_failed", "Could not stage the relay client."));- yield* fileSystem- .rename(stagedPath, managedPath)- .pipe(- wrapInstallFailure("write_failed", "Could not activate the relay client."),- Effect.ensuring(fileSystem.remove(stagedPath, { force: true }).pipe(Effect.ignore)),- );- return {- status: "available",- executablePath: managedPath,- source: "managed",- version: CLOUDFLARED_VERSION,- } satisfies AvailableRelayClient;- }).pipe(- Effect.scoped,- Effect.ensuring(fileSystem.remove(lockPath, { force: true }).pipe(Effect.ignore)),- Effect.catch((cause) =>- cause instanceof RelayClientInstallError- ? Effect.fail(cause)- : Effect.fail(- new RelayClientInstallError({- reason: "write_failed",- message: "Could not install the relay client.",- cause,- }),- ),- ),- );- });- const installWithProgress: RelayClientShape["installWithProgress"] = (report) =>- installSemaphore.withPermit(- installUnlocked((stage) =>- report({- type: "progress",- stage,- }),- ),- );- const install = installWithProgress(() => Effect.void);-- return RelayClient.of({ resolve, install, installWithProgress });-});--export const layerCloudflared = (options: CloudflaredRelayClientOptions) =>- Layer.effect(RelayClient, makeCloudflaredRelayClient(options));diff --git a/packages/shared/src/relayJwt.test.ts b/packages/shared/src/relayJwt.test.tsdeleted file mode 100644index 4e863af48..000000000--- a/packages/shared/src/relayJwt.test.ts+++ /dev/null@@ -1,58 +0,0 @@-import * as NodeCrypto from "node:crypto";--import { describe, expect, it } from "@effect/vitest";-import * as Effect from "effect/Effect";--import { RelayJwtError, signRelayJwt, verifyRelayJwt } from "./relayJwt.ts";--describe("relayJwt", () => {- it.effect("preserves signing context and the JOSE cause", () =>- Effect.gen(function* () {- const error = yield* signRelayJwt({- privateKey: "not-a-private-key",- typ: "test-sign+jwt",- payload: { sub: "subject" },- }).pipe(Effect.flip);-- expect(error.operation).toBe("sign");- expect(error.typ).toBe("test-sign+jwt");- expect(error.cause).toBeInstanceOf(Error);- expect(error.message).toBe('Failed to sign relay JWT of type "test-sign+jwt".');- }),- );-- it.effect("preserves verification request context and the JOSE cause", () =>- Effect.gen(function* () {- const keyPair = NodeCrypto.generateKeyPairSync("ed25519", {- publicKeyEncoding: { format: "pem", type: "spki" },- privateKeyEncoding: { format: "pem", type: "pkcs8" },- });- const error = yield* verifyRelayJwt({- publicKey: keyPair.publicKey,- token: "not-a-jwt",- typ: "test-verify+jwt",- issuer: "https://issuer.example.test",- audience: "test-audience",- nowEpochSeconds: 100,- }).pipe(Effect.flip);-- expect(error.operation).toBe("verify");- expect(error.typ).toBe("test-verify+jwt");- expect(error.issuer).toBe("https://issuer.example.test");- expect(error.audience).toBe("test-audience");- expect(error.cause).toBeInstanceOf(Error);- expect(error.message).toBe('Failed to verify relay JWT of type "test-verify+jwt".');- }),- );-- it("extracts stable diagnostic codes without copying cause text into the error message", () => {- const error = new RelayJwtError({- operation: "verify",- typ: "test+jwt",- cause: { code: "ERR_JWT_EXPIRED", message: "sensitive library detail" },- });-- expect(RelayJwtError.diagnosticCode(error)).toBe("ERR_JWT_EXPIRED");- expect(error.message).not.toContain("sensitive library detail");- });-});diff --git a/packages/shared/src/relayJwt.ts b/packages/shared/src/relayJwt.tsdeleted file mode 100644index 9e848bedf..000000000--- a/packages/shared/src/relayJwt.ts+++ /dev/null@@ -1,99 +0,0 @@-import { decodeJwt, importPKCS8, importSPKI, jwtVerify, SignJWT, type JWTPayload } from "jose";-import * as DateTime from "effect/DateTime";-import * as Effect from "effect/Effect";-import * as Predicate from "effect/Predicate";-import * as Schema from "effect/Schema";--export const RELAY_LINK_PROOF_TYP = "t3-env-link+jwt";-export const RELAY_MINT_REQUEST_TYP = "t3-cloud-mint+jwt";-export const RELAY_HEALTH_REQUEST_TYP = "t3-cloud-health+jwt";-export const RELAY_MINT_RESPONSE_TYP = "t3-env-mint+jwt";-export const RELAY_HEALTH_RESPONSE_TYP = "t3-env-health+jwt";-export const RELAY_ACTIVITY_PUBLISH_TYP = "t3-env-activity+jwt";--export class RelayJwtError extends Schema.TaggedErrorClass<RelayJwtError>()("RelayJwtError", {- operation: Schema.Literals(["sign", "verify"]),- typ: Schema.String,- issuer: Schema.optional(Schema.String),- audience: Schema.optional(Schema.String),- cause: Schema.Defect(),-}) {- override get message(): string {- return `Failed to ${this.operation} relay JWT of type "${this.typ}".`;- }-- static diagnosticCode(error: RelayJwtError): string {- if (- Predicate.isObject(error.cause) &&- Predicate.hasProperty(error.cause, "code") &&- Predicate.isString(error.cause.code) &&- error.cause.code.length > 0- ) {- return error.cause.code;- }-- return error.cause instanceof Error && error.cause.name ? error.cause.name : "unknown";- }-}--export function normalizeRelayIssuer(value: string): string {- return value.trim().replace(/\/+$/gu, "");-}--export function decodeRelayJwt(token: string): JWTPayload {- return decodeJwt(token);-}--function normalizePem(value: string): string {- return value.replace(/\\n/gu, "\n").trim();-}--export function signRelayJwt(input: {- readonly privateKey: string;- readonly typ: string;- readonly payload: JWTPayload;-}): Effect.Effect<string, RelayJwtError> {- return Effect.tryPromise({- try: async () => {- const key = await importPKCS8(normalizePem(input.privateKey), "EdDSA");- return new SignJWT(input.payload)- .setProtectedHeader({ alg: "EdDSA", typ: input.typ })- .sign(key);- },- catch: (cause) => new RelayJwtError({ operation: "sign", typ: input.typ, cause }),- });-}--export function verifyRelayJwt(input: {- readonly publicKey: string;- readonly token: string;- readonly typ: string;- readonly issuer: string;- readonly audience: string;- readonly nowEpochSeconds: number;- readonly maxTokenAge?: string | number;-}): Effect.Effect<JWTPayload, RelayJwtError> {- return Effect.tryPromise({- try: async () => {- const key = await importSPKI(normalizePem(input.publicKey), "EdDSA");- const verified = await jwtVerify(input.token, key, {- algorithms: ["EdDSA"],- typ: input.typ,- issuer: input.issuer,- audience: input.audience,- maxTokenAge: input.maxTokenAge ?? "5 minutes",- clockTolerance: 60,- currentDate: DateTime.toDate(DateTime.makeUnsafe(input.nowEpochSeconds * 1_000)),- });- return verified.payload;- },- catch: (cause) =>- new RelayJwtError({- operation: "verify",- typ: input.typ,- issuer: input.issuer,- audience: input.audience,- cause,- }),- });-}diff --git a/packages/shared/src/relaySigning.test.ts b/packages/shared/src/relaySigning.test.tsdeleted file mode 100644index f847d9457..000000000--- a/packages/shared/src/relaySigning.test.ts+++ /dev/null@@ -1,18 +0,0 @@-import { describe, expect, it } from "@effect/vitest";--import { stableStringify } from "./relaySigning.ts";--describe("relaySigning", () => {- it("canonicalizes object keys recursively", () => {- expect(- stableStringify({- z: 1,- a: {- y: true,- b: null,- },- list: [{ c: "three", a: "one" }],- }),- ).toBe('{"a":{"b":null,"y":true},"list":[{"a":"one","c":"three"}],"z":1}');- });-});diff --git a/packages/shared/src/relaySigning.ts b/packages/shared/src/relaySigning.tsdeleted file mode 100644index 6b8b8cb2c..000000000--- a/packages/shared/src/relaySigning.ts+++ /dev/null@@ -1,17 +0,0 @@-function isRecord(value: unknown): value is Record<string, unknown> {- return typeof value === "object" && value !== null && !Array.isArray(value);-}--export function stableStringify(value: unknown): string {- if (Array.isArray(value)) {- return `[${value.map(stableStringify).join(",")}]`;- }- if (isRecord(value)) {- return `{${Object.entries(value)- .filter(([, entryValue]) => entryValue !== undefined)- .sort(([left], [right]) => left.localeCompare(right))- .map(([key, entryValue]) => `${JSON.stringify(key)}:${stableStringify(entryValue)}`)- .join(",")}}`;- }- return JSON.stringify(value) ?? "null";-}diff --git a/packages/shared/src/relayTracing.test.ts b/packages/shared/src/relayTracing.test.tsdeleted file mode 100644index 3bb7f1ea1..000000000--- a/packages/shared/src/relayTracing.test.ts+++ /dev/null@@ -1,104 +0,0 @@-import { describe, expect, it } from "@effect/vitest";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";-import * as Option from "effect/Option";-import * as Tracer from "effect/Tracer";-import { FetchHttpClient } from "effect/unstable/http";-import { vi } from "vite-plus/test";--import {- makeRelayClientTracingLayer,- RelayClientTracer,- withRelayClientTracing,-} from "./relayTracing.ts";--function collectingTracer(spans: Array<string>): Tracer.Tracer {- return Tracer.make({- span: (options) => {- const span = new Tracer.NativeSpan(options);- const end = span.end.bind(span);- span.end = (endTime, exit) => {- end(endTime, exit);- spans.push(span.name);- };- return span;- },- });-}--describe("withRelayClientTracing", () => {- it.effect("uses the product tracer only for relay operations", () =>- Effect.gen(function* () {- const userSpans: Array<string> = [];- const productSpans: Array<string> = [];- const userTracer = collectingTracer(userSpans);- const productTracer = collectingTracer(productSpans);-- yield* Effect.void.pipe(Effect.withSpan("user.operation"), Effect.withTracer(userTracer));- yield* Effect.void.pipe(- Effect.withSpan("relay.operation"),- withRelayClientTracing,- Effect.provideService(RelayClientTracer, Option.some(productTracer)),- Effect.withTracer(userTracer),- );-- expect(userSpans).toEqual(["user.operation"]);- expect(productSpans).toEqual(["relay.operation"]);- }),- );-- it.effect("preserves the active tracer when product tracing is disabled", () =>- Effect.gen(function* () {- const userSpans: Array<string> = [];- const userTracer = collectingTracer(userSpans);-- yield* Effect.void.pipe(- Effect.withSpan("relay.operation"),- withRelayClientTracing,- Effect.withTracer(userTracer),- );-- expect(userSpans).toEqual(["relay.operation"]);- }),- );-- it.effect("preserves nested error causes in exported relay spans", () => {- const fetchFn = vi.fn<typeof fetch>(async () => new Response(null, { status: 202 }));- const httpClientLayer = FetchHttpClient.layer.pipe(- Layer.provide(Layer.succeed(FetchHttpClient.Fetch, fetchFn)),- );- const tracingLayer = makeRelayClientTracingLayer(- {- tracesUrl: "https://api.axiom.test/v1/traces",- tracesDataset: "relay-traces",- tracesToken: "public-ingest-token",- },- {- serviceName: "relay-test",- runtime: "test",- client: "test",- },- ).pipe(Layer.provide(httpClientLayer));- const rootCause = new Error("relay socket closed");- const failure = new Error("relay request failed", { cause: rootCause });- const tracedApplication = Layer.effectDiscard(- Effect.fail(failure).pipe(- Effect.withSpan("relay.failed-operation"),- withRelayClientTracing,- Effect.exit,- ),- ).pipe(Layer.provide(tracingLayer));-- return Layer.build(tracedApplication).pipe(- Effect.scoped,- Effect.andThen(- Effect.sync(() => {- expect(fetchFn).toHaveBeenCalledOnce();- const payload = new TextDecoder().decode(fetchFn.mock.calls[0]?.[1]?.body as Uint8Array);- expect(payload).toContain("relay request failed");- expect(payload).toContain("relay socket closed");- }),- ),- );- });-});diff --git a/packages/shared/src/relayTracing.ts b/packages/shared/src/relayTracing.tsdeleted file mode 100644index 1259984ea..000000000--- a/packages/shared/src/relayTracing.ts+++ /dev/null@@ -1,156 +0,0 @@-import * as Cause from "effect/Cause";-import * as Context from "effect/Context";-import * as Effect from "effect/Effect";-import * as Exit from "effect/Exit";-import * as Layer from "effect/Layer";-import * as Option from "effect/Option";-import * as Tracer from "effect/Tracer";-import type { HttpClient } from "effect/unstable/http";-import { OtlpSerialization, OtlpTracer } from "effect/unstable/observability";--export interface RelayClientTracingConfig {- readonly tracesUrl: string;- readonly tracesDataset: string;- readonly tracesToken: string;-}--export interface RelayClientTracingResource {- readonly serviceName: string;- readonly serviceVersion?: string;- readonly runtime: string;- readonly client: string;- readonly component?: string;-}--export class RelayClientTracer extends Context.Reference(- "@t3tools/shared/relayTracing/RelayClientTracer",- {- defaultValue: () => Option.none<Tracer.Tracer>(),- },-) {}--export const withRelayClientTracing = <A, E, R>(- effect: Effect.Effect<A, E, R>,-): Effect.Effect<A, E, R> =>- RelayClientTracer.pipe(- Effect.flatMap(- Option.match({- onNone: () => effect,- onSome: (tracer) => effect.pipe(Effect.provideService(Tracer.Tracer, tracer)),- }),- ),- );--function cleanTraceStack(error: Error): string {- const stack = error.stack ?? `${error.name}: ${error.message}`;- const lines = stack.split("\n");- const effectFrameIndex = lines.findIndex(- (line, index) => index > 0 && /(?:Generator\.next|~effect\/Effect)/.test(line),- );- return effectFrameIndex < 0 ? stack : lines.slice(0, effectFrameIndex).join("\n");-}--function traceSafeError(value: unknown, seen = new WeakSet<object>()): Error {- const message =- value instanceof Error- ? value.message- : typeof value === "object" &&- value !== null &&- "message" in value &&- typeof value.message === "string"- ? value.message- : String(value);-- let cause: Error | undefined;- if (typeof value === "object" && value !== null && !seen.has(value)) {- seen.add(value);- if ("cause" in value && value.cause !== undefined) {- cause = traceSafeError(value.cause, seen);- }- }-- const error = new Error(message, cause ? { cause } : undefined);- if (value instanceof Error) {- error.name = value.name;- error.stack = cleanTraceStack(value);- } else if (- typeof value === "object" &&- value !== null &&- "name" in value &&- typeof value.name === "string"- ) {- error.name = value.name;- }- if (cause) {- error.stack = `${error.stack ?? `${error.name}: ${error.message}`}\nCaused by: ${cause.stack ?? `${cause.name}: ${cause.message}`}`;- }- return error;-}--function traceSafeExit(exit: Exit.Exit<unknown, unknown>): Exit.Exit<unknown, unknown> {- if (Exit.isSuccess(exit)) {- return exit;- }- return Exit.failCause(- Cause.fromReasons(- exit.cause.reasons.map((reason) => {- if (Cause.isFailReason(reason)) {- return Cause.makeFailReason(traceSafeError(reason.error));- }- if (Cause.isDieReason(reason)) {- return Cause.makeDieReason(traceSafeError(reason.defect));- }- return reason;- }),- ),- );-}--function nonInterferingTracer(delegate: Tracer.Tracer): Tracer.Tracer {- return Tracer.make({- span(options) {- const span = delegate.span(options);- const end = span.end.bind(span);- span.end = (endTime, exit) => {- try {- end(endTime, traceSafeExit(exit));- } catch {- // Telemetry is best-effort and must never change application behavior.- }- };- return span;- },- ...(delegate.context ? { context: delegate.context } : {}),- });-}--export function makeRelayClientTracingLayer(- config: RelayClientTracingConfig | null,- resource: RelayClientTracingResource,-): Layer.Layer<never, never, HttpClient.HttpClient> {- if (config === null) {- return Layer.succeed(RelayClientTracer, Option.none());- }-- const tracerLayer = OtlpTracer.layer({- url: config.tracesUrl,- headers: {- Authorization: `Bearer ${config.tracesToken}`,- "X-Axiom-Dataset": config.tracesDataset,- },- resource: {- serviceName: resource.serviceName,- serviceVersion: resource.serviceVersion,- attributes: {- "service.runtime": resource.runtime,- "service.component": resource.component ?? "relay-client",- "t3.client.surface": resource.client,- },- },- }).pipe(Layer.provide(OtlpSerialization.layerJson));-- return Layer.effect(- RelayClientTracer,- Tracer.Tracer.pipe(Effect.map(nonInterferingTracer), Effect.map(Option.some)),- ).pipe(Layer.provide(tracerLayer));-}diff --git a/packages/shared/src/relayUrl.test.ts b/packages/shared/src/relayUrl.test.tsdeleted file mode 100644index 5127db85d..000000000--- a/packages/shared/src/relayUrl.test.ts+++ /dev/null@@ -1,26 +0,0 @@-import { describe, expect, it } from "vite-plus/test";--import { isSecureRelayUrl, normalizeSecureRelayUrl } from "./relayUrl.ts";--describe("normalizeSecureRelayUrl", () => {- it("normalizes secure relay origins", () => {- expect(normalizeSecureRelayUrl(" https://relay.example.test/// ")).toBe(- "https://relay.example.test",- );- expect(normalizeSecureRelayUrl("https://relay.example.test:8443/")).toBe(- "https://relay.example.test:8443",- );- });-- it.each([- "http://relay.example.test",- "https://user:[email protected]",- "https://relay.example.test/path",- "https://relay.example.test?query=value",- "https://relay.example.test#fragment",- "not a url",- ])("rejects unsafe relay URL %s", (value) => {- expect(normalizeSecureRelayUrl(value)).toBeNull();- expect(isSecureRelayUrl(value)).toBe(false);- });-});diff --git a/packages/shared/src/relayUrl.ts b/packages/shared/src/relayUrl.tsdeleted file mode 100644index 4e5f39770..000000000--- a/packages/shared/src/relayUrl.ts+++ /dev/null@@ -1,22 +0,0 @@-export function normalizeSecureRelayUrl(value: string): string | null {- try {- const url = new URL(value.trim());- if (- url.protocol !== "https:" ||- url.username.length > 0 ||- url.password.length > 0 ||- url.search.length > 0 ||- url.hash.length > 0 ||- !/^\/+$/u.test(url.pathname)- ) {- return null;- }- return url.origin;- } catch {- return null;- }-}--export function isSecureRelayUrl(value: string): boolean {- return normalizeSecureRelayUrl(value) !== null;-}diff --git a/apps/server/src/mcp/SensitiveDataRedaction.ts b/packages/shared/src/sensitiveDataRedaction.tssimilarity index 100%rename from apps/server/src/mcp/SensitiveDataRedaction.tsrename to packages/shared/src/sensitiveDataRedaction.tsdiff --git a/packages/shared/src/usageFormat.test.ts b/packages/shared/src/usageFormat.test.tsindex fb231fbac..9863525f0 100644--- a/packages/shared/src/usageFormat.test.ts+++ b/packages/shared/src/usageFormat.test.ts@@ -7,8 +7,33 @@ import {formatHourShort,formatRelativeHourShort,makeWindow,+ stepTokenCount,+ stepUsageTokenTotals,} from "./usageFormat.ts";+describe("step usage", () => {+ it("accounts for per-step tokens without using context occupancy", () => {+ const usage = {+ usedTokens: 90_000,+ lastUsedTokens: 90_000,+ lastInputTokens: 1_200,+ lastCachedInputTokens: 200,+ lastOutputTokens: 300,+ lastReasoningOutputTokens: 100,+ };++ expect(stepTokenCount(usage)).toBe(1_500);+ expect(stepUsageTokenTotals(usage)).toEqual({+ uncachedInputTokens: 1_000,+ cachedInputTokens: 200,+ cacheCreationTokens: 0,+ outputTokens: 300,+ reasoningTokens: 100,+ });+ expect(stepTokenCount({ usedTokens: 90_000 })).toBeNull();+ });+});+describe("hourly usage formatting", () => {it("enumerates 24 fixed buckets across a rolling window", () => {const hours = enumerateHourStarts("2026-08-10T12:37:00.000Z", "2026-08-11T12:37:00.000Z");diff --git a/packages/shared/src/usageFormat.ts b/packages/shared/src/usageFormat.tsindex bd751829d..a936c00d8 100644--- a/packages/shared/src/usageFormat.ts+++ b/packages/shared/src/usageFormat.ts@@ -4,7 +4,13 @@** @module usageFormat*/-import { UsageDay, type UsageResolution, type UsageSummaryInput } from "@t3tools/contracts";+import {+ UsageDay,+ type ThreadTokenUsageSnapshot,+ type UsageResolution,+ type UsageSummaryInput,+ type UsageTokenTotals,+} from "@t3tools/contracts";const CURRENCY = new Intl.NumberFormat("en-US", {style: "currency",@@ -36,6 +42,26 @@ export function formatTokens(value: number): string {return INTEGER.format(Math.round(value));}+export function stepTokenCount(usage: ThreadTokenUsageSnapshot): number | null {+ if (usage.lastInputTokens !== undefined || usage.lastOutputTokens !== undefined) {+ return (usage.lastInputTokens ?? 0) + (usage.lastOutputTokens ?? 0);+ }+ return usage.lastUsedTokens ?? null;+}++export function stepUsageTokenTotals(usage: ThreadTokenUsageSnapshot): UsageTokenTotals {+ const inputTokens = usage.lastInputTokens ?? 0;+ const cachedInputTokens = Math.min(inputTokens, usage.lastCachedInputTokens ?? 0);+ const outputTokens = usage.lastOutputTokens ?? 0;+ return {+ uncachedInputTokens: Math.max(0, inputTokens - cachedInputTokens),+ cachedInputTokens,+ cacheCreationTokens: 0,+ outputTokens,+ reasoningTokens: Math.min(outputTokens, usage.lastReasoningOutputTokens ?? 0),+ };+}+function trim(value: number): string {const abs = Math.abs(value);const digits = abs >= 100 ? 0 : abs >= 10 ? 1 : 2;diff --git a/patches/@[email protected] b/patches/@[email protected]deleted file mode 100644index 2d4a9287c..000000000--- a/patches/@[email protected]+++ /dev/null@@ -1,79 +0,0 @@-diff --git a/ios/ClerkAuthNativeView.swift b/ios/ClerkAuthNativeView.swift-index e76a8be1b1c8faa64ec6dfa83764764094133aff..17b36ad1319765e2b6db0551d32e07d7140e482f 100644---- a/ios/ClerkAuthNativeView.swift-+++ b/ios/ClerkAuthNativeView.swift-@@ -108,7 +108,12 @@ public class ClerkAuthNativeView: ClerkNativeViewHost {-- override func makeHostedController() -> UIViewController? {- let hostBackAction: (() -> Void)? = currentHostBackButton-- ? { [weak self] in self?.onHostBack([:]) }-+ ? { [weak self] in-+ guard let self else { return }-+ if !self.popEnclosingNavigationRoute() {-+ self.onHostBack([:])-+ }-+ }- : nil-- return ClerkNativeBridge.shared.makeAuthViewController(-diff --git a/ios/ClerkNativeViewHost.swift b/ios/ClerkNativeViewHost.swift-index 0d91f0e749f121595c17bc803663df6ac90e4163..8f8a89df97a54168b8b45d0e9c197ca3953b7028 100644---- a/ios/ClerkNativeViewHost.swift-+++ b/ios/ClerkNativeViewHost.swift-@@ -5,6 +5,7 @@ public class ClerkNativeViewHost: ExpoView {- private lazy var hostingCoordinator = ClerkNativeHostingCoordinator(containerView: self)- private var hasInitialized: Bool = false- private var configuredObserver: NSObjectProtocol?-+ private var isPoppingHostRoute = false-- public required init(appContext: AppContext? = nil) {- super.init(appContext: appContext)-@@ -58,6 +59,30 @@ public class ClerkNativeViewHost: ExpoView {-- func hostedViewDidDetachFromWindow() {}--+ /// Pops the React Navigation route that contains this view without waiting for-+ /// the JavaScript event loop. React Native Screens reports the native dismissal-+ /// back to React Navigation so its state remains synchronized.-+ func popEnclosingNavigationRoute() -> Bool {-+ guard !isPoppingHostRoute else { return true }-+-+ var responder: UIResponder? = self-+-+ while let nextResponder = responder?.next {-+ if let viewController = nextResponder as? UIViewController,-+ let navigationController = viewController.navigationController,-+ navigationController.viewControllers.count > 1 {-+ isPoppingHostRoute = true-+ if navigationController.popViewController(animated: true) != nil {-+ return true-+ }-+ isPoppingHostRoute = false-+ }-+ responder = nextResponder-+ }-+-+ return false-+ }-+- private func addConfiguredObserver() {- guard configuredObserver == nil else { return }--diff --git a/ios/ClerkUserProfileNativeView.swift b/ios/ClerkUserProfileNativeView.swift-index 12d6248b1dc4b4779b252c9954c2f89145907310..d838283b7adcf49fec2a63bff53251b9bee31bf8 100644---- a/ios/ClerkUserProfileNativeView.swift-+++ b/ios/ClerkUserProfileNativeView.swift-@@ -44,7 +44,12 @@ public class ClerkUserProfileNativeView: ClerkNativeViewHost {-- override func makeHostedController() -> UIViewController? {- let hostBackAction: (() -> Void)? = currentHostBackButton-- ? { [weak self] in self?.onHostBack([:]) }-+ ? { [weak self] in-+ guard let self else { return }-+ if !self.popEnclosingNavigationRoute() {-+ self.onHostBack([:])-+ }-+ }- : nil-- return ClerkNativeBridge.shared.makeUserProfileViewController(diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex ad5d15d22..7d73986a0 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -46,19 +46,6 @@ overrides:'@anthropic-ai/claude-agent-sdk>@anthropic-ai/claude-agent-sdk-linux-x64-musl': '-''@anthropic-ai/claude-agent-sdk>@anthropic-ai/claude-agent-sdk-win32-arm64': '-''@anthropic-ai/claude-agent-sdk>@anthropic-ai/claude-agent-sdk-win32-x64': '-'- '@clerk/backend': 3.14.0- '@clerk/clerk-js': 6.30.1- '@clerk/clerk-js>@base-org/account': '-'- '@clerk/clerk-js>@coinbase/wallet-sdk': '-'- '@clerk/clerk-js>@solana/wallet-adapter-base': '-'- '@clerk/clerk-js>@solana/wallet-adapter-react': '-'- '@clerk/clerk-js>@solana/wallet-standard': '-'- '@clerk/clerk-js>@wallet-standard/core': '-'- '@clerk/electron': 0.0.37- '@clerk/electron-passkeys': 0.0.3- '@clerk/expo': 4.2.0- '@clerk/react': 6.14.7- '@clerk/shared': 4.30.1'@effect/atom-react': 4.0.0-beta.103'@effect/platform-bun': 4.0.0-beta.103'@effect/platform-node': 4.0.0-beta.103@@ -77,10 +64,9 @@ overrides:vite: npm:@voidzero-dev/[email protected]yaml: ^2.9.0-packageExtensionsChecksum: sha256-CUzzeefpj3gNFrCKNBhV9FOaniNbrLdKyIhWQyXuaiE=+packageExtensionsChecksum: sha256-FV3+2NW/9MFbunJaPsMxvO0LAzyfccoPtPiKoIXAwUU=patchedDependencies:- '@clerk/[email protected]': 72e426f44fc1cde16fc2cbba3d1e96cdca7c6d957faa73d0fe6b43948608a6c1'@effect/[email protected]': a16b1e870d8c29e4a98b17cc4c638a4ff471753d8ca3487f78a22b759caf951b'@expo/[email protected]': 8cb08b5bb7051ed9d2dbe46a2c293c5a1e17f1bd6ddf30de27909e18c921ff46'@ff-labs/[email protected]': ab9ff544009e1891cfe3930105862d3699007f38922a79f3c98d90018deca368@@ -121,12 +107,6 @@ importers:apps/desktop:dependencies:- '@clerk/electron':- specifier: 0.0.37- version: 0.0.37(@clerk/[email protected])([email protected])([email protected])([email protected]([email protected]))([email protected])- '@clerk/electron-passkeys':- specifier: 0.0.3- version: 0.0.3'@effect/platform-node':specifier: 4.0.0-beta.103version: 4.0.0-beta.103([email protected])([email protected](patch_hash=af36b7948b6f9c56623074662b51dade5699880c1a7c71245de73e13c3185fb6))([email protected])([email protected])@@ -207,9 +187,6 @@ importers:'@callstack/liquid-glass':specifier: ^0.7.1version: 0.7.1([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])- '@clerk/expo':- specifier: 4.2.0- version: 4.2.0(patch_hash=72e426f44fc1cde16fc2cbba3d1e96cdca7c6d957faa73d0fe6b43948608a6c1)([email protected]([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected]([email protected]))([email protected]([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])))([email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])([email protected])'@effect/atom-react':specifier: 4.0.0-beta.103version: 4.0.0-beta.103([email protected](patch_hash=af36b7948b6f9c56623074662b51dade5699880c1a7c71245de73e13c3185fb6))([email protected])([email protected])@@ -442,6 +419,9 @@ importers:'@pierre/trees':specifier: 1.0.0-beta.4+ '@types/node':+ specifier: 24.12.4+ version: 24.12.4'@types/react':specifier: ~19.2.0version: 19.2.16@@ -566,12 +546,6 @@ importers:'@base-ui/react':specifier: ^1.4.1- '@clerk/electron':- specifier: 0.0.37- version: 0.0.37(@clerk/[email protected])([email protected])([email protected])([email protected]([email protected]))([email protected])- '@clerk/react':- specifier: 6.14.7'@dnd-kit/core':specifier: ^6.3.1@@ -797,61 +771,6 @@ importers:specifier: 'catalog:'version: 0.2.2(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])- infra/relay:- dependencies:- '@clerk/backend':- specifier: 3.14.0- '@effect/sql-pg':- specifier: 4.0.0-beta.103- version: 4.0.0-beta.103([email protected](patch_hash=af36b7948b6f9c56623074662b51dade5699880c1a7c71245de73e13c3185fb6))- '@noble/curves':- specifier: 'catalog:'- version: 1.9.1- '@noble/hashes':- specifier: 'catalog:'- version: 1.8.0- '@t3tools/client-runtime':- specifier: workspace:*- version: link:../../packages/client-runtime- '@t3tools/contracts':- specifier: workspace:*- version: link:../../packages/contracts- '@t3tools/shared':- specifier: workspace:*- version: link:../../packages/shared- alchemy:- specifier: 2.0.0-beta.65- version: 2.0.0-beta.65(d49cefd000f1d9b608f5da03fcefc18f)- drizzle-orm:- specifier: 1.0.0-rc.4- version: 1.0.0-rc.4(364f9547bd74875ecdea197c1b3898c3)- effect:- specifier: 4.0.0-beta.103- version: 4.0.0-beta.103(patch_hash=af36b7948b6f9c56623074662b51dade5699880c1a7c71245de73e13c3185fb6)- devDependencies:- '@cloudflare/workers-types':- specifier: ^4.20260601.1- version: 4.20260604.1- '@effect/platform-node':- specifier: 4.0.0-beta.103- version: 4.0.0-beta.103([email protected])([email protected](patch_hash=af36b7948b6f9c56623074662b51dade5699880c1a7c71245de73e13c3185fb6))([email protected])([email protected])- '@effect/vitest':- specifier: 4.0.0-beta.103- version: 4.0.0-beta.103(patch_hash=a16b1e870d8c29e4a98b17cc4c638a4ff471753d8ca3487f78a22b759caf951b)([email protected](patch_hash=af36b7948b6f9c56623074662b51dade5699880c1a7c71245de73e13c3185fb6))- '@types/node':- specifier: 24.12.4- version: 24.12.4- drizzle-kit:- specifier: 1.0.0-rc.4- version: 1.0.0-rc.4- vite:- specifier: npm:@voidzero-dev/[email protected]- version: '@voidzero-dev/[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])'- vite-plus:- specifier: 'catalog:'- version: 0.2.2(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])-oxlint-plugin-t3code:dependencies:'@effect/platform-node':@@ -949,21 +868,12 @@ importers:packages/shared:dependencies:- '@noble/curves':- specifier: 'catalog:'- version: 1.9.1- '@noble/hashes':- specifier: 'catalog:'- version: 1.8.0'@t3tools/contracts':specifier: workspace:*version: link:../contractseffect:specifier: 4.0.0-beta.103version: 4.0.0-beta.103(patch_hash=af36b7948b6f9c56623074662b51dade5699880c1a7c71245de73e13c3185fb6)- jose:- specifier: 'catalog:'- version: 6.2.2yaml:specifier: ^2.9.0version: 2.9.0@@ -2213,113 +2123,6 @@ packages:resolution: {integrity: sha512-EYlRokl8szrP9Z25qT5aepMdBjzBvHF9ZEhzIiUBc9guz/T31EqRgvD0QSgZcpE93xiwrr+OkB4nz0BZyF6fSA==}engines: {node: '>= 20.12.0'}- '@clerk/[email protected]':- resolution: {integrity: sha512-WsphTvDFHDuQilKI7dyVE5qmt7USu8qSrujAq6SqpEHbVFfNBfINDNuzxlF9M2skOTfHFfgiTE8Jjb1egIBGLg==}- engines: {node: '>=20.9.0'}-- '@clerk/[email protected]':- resolution: {integrity: sha512-ipsUhTf1uPJ5az4eiLOCM1Qz8z0I4kl54N6RtnL3VbxezwptPEUHx1PlHnHKUjTCV/PHNVq/3vht9w+8VLOoHw==}- engines: {node: '>=20.9.0'}-- '@clerk/[email protected]':- resolution: {integrity: sha512-oAlrd+GLqP0oREP3hNRc6yNZhXGaQgJss9iCWRQqXjpw1yZD1ZU+L+E2Gfg84vMj/NSUhxbU0Djy0RXhmeUwgg==}- cpu: [arm64]- os: [darwin]-- '@clerk/[email protected]':- resolution: {integrity: sha512-0UPAWQEni7o8gjWwd2sP97fPshJmT2w5b8eV/jOPVSP8NqIcFCm5yIFSEx1SfB53LGfzB01A4iEGi2pxiCHqyQ==}- cpu: [x64]- os: [darwin]-- '@clerk/[email protected]':- resolution: {integrity: sha512-bbRvifm9A/gfPkwC1UyMyF9sYGEs0aen7J2kCcaOIW3K0PXcAbHtsR/gnx4dT0bjFdd21vSa2zlIdERvHc1BiA==}- cpu: [arm64]- os: [win32]-- '@clerk/[email protected]':- resolution: {integrity: sha512-gFaVqKlOKTF2SJ3lMwkZ0oonycQn93p1qSrp5kzzeZBeQ+tGB3gQnjXecrhQy21AzDUyWqVJJ8KrP2HRAwifWg==}- cpu: [x64]- os: [win32]-- '@clerk/[email protected]':- resolution: {integrity: sha512-OHhIe88qDL+FxyBalXdXNHAS5eEramr6Rerp+6iNkfkjqT8rx4hHNmfpmjg5/T1/am8QfknbOBZkqoXZlCrjPg==}- engines: {node: '>=20.9.0'}-- '@clerk/[email protected]':- resolution: {integrity: sha512-NsATM6rMISdL1K3mlKVPqZpDUA4h+uWmbGv8h9PK3zYfnwMgSpDKRX2y341Lt0fhz+eWkZpMU5SQmlZPNqwiww==}- engines: {node: '>=20.9.0'}- peerDependencies:- '@clerk/electron-passkeys': 0.0.3- electron: '>=28'- electron-store: ^8.2.0- react: ^18.0.0 || ~19.0.3 || ~19.1.4 || ~19.2.3 || ~19.3.0-0- react-dom: ^18.0.0 || ~19.0.3 || ~19.1.4 || ~19.2.3 || ~19.3.0-0- peerDependenciesMeta:- '@clerk/electron-passkeys':- optional: true- electron-store:- optional: true- react-dom:- optional: true-- '@clerk/[email protected]':- resolution: {integrity: sha512-S2TYZn1Tltm/gXfe9J1NCuLRCmQX/3gfD0c+i/B1RWGbIJpSZX7KGRzvW70ABaqrK9IUcribLVmMN6unmpuCtQ==}- engines: {node: '>=20.9.0'}- peerDependencies:- '@clerk/expo-google-signin': '>=0.1.0'- '@clerk/expo-passkeys': '>=0.0.6'- expo: '>=54 <58'- expo-apple-authentication: '>=7.0.0'- expo-auth-session: '>=5'- expo-constants: '>=12'- expo-crypto: '>=12'- expo-local-authentication: '>=13.5.0'- expo-secure-store: '>=12.4.0'- expo-web-browser: '>=12.5.0'- react: ^18.0.0 || ^19.0.0- react-dom: ^18.0.0 || ^19.0.0- react-native: '>=0.75'- peerDependenciesMeta:- '@clerk/expo-google-signin':- optional: true- '@clerk/expo-passkeys':- optional: true- expo-apple-authentication:- optional: true- expo-auth-session:- optional: true- expo-constants:- optional: true- expo-crypto:- optional: true- expo-local-authentication:- optional: true- expo-secure-store:- optional: true- expo-web-browser:- optional: true- react-dom:- optional: true-- '@clerk/[email protected]':- resolution: {integrity: sha512-+d+VqD4nZR3vBn5UU++H96zloHFDe+Ll0sGwMmLXnHtoIs9oMx91GaGXzXo9rU83kl660EfAmgeWcsLMfWnOYg==}- engines: {node: '>=20.9.0'}- peerDependencies:- react: ^18.0.0 || ~19.0.3 || ~19.1.4 || ~19.2.3 || ~19.3.0-0- react-dom: ^18.0.0 || ~19.0.3 || ~19.1.4 || ~19.2.3 || ~19.3.0-0-- '@clerk/[email protected]':- resolution: {integrity: sha512-Mawatm7CTKZXBqIW8t/z9LfoAKgOHtRRxROpnJ4VIkTdgzj/mmAZhPOPjzUttPXXtulR1uLWisvQXEMNeF/jTQ==}- engines: {node: '>=20.9.0'}- peerDependencies:- react: ^18.0.0 || ~19.0.3 || ~19.1.4 || ~19.2.3 || ~19.3.0-0- react-dom: ^18.0.0 || ~19.0.3 || ~19.1.4 || ~19.2.3 || ~19.3.0-0- peerDependenciesMeta:- react:- optional: true- react-dom:- optional: true-'@cloudflare/[email protected]':resolution: {integrity: sha512-ECxObrMfyTl5bhQf/lZCXwo5G6xX9IAUo+nDMKK4SZ8m4Jvvxp52vilxyySSWh2YTZz8+HQ07qGH/2rEom1vDw==}peerDependencies:@@ -5639,19 +5442,9 @@ packages:'@socket.io/[email protected]':resolution: {integrity: sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA==}- '@stablelib/[email protected]':- resolution: {integrity: sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==}-'@standard-schema/[email protected]':resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==}- '@stripe/[email protected]':- resolution: {integrity: sha512-w8CEY73X/7tw2KKlL3iOk679V9bWseE4GzNz3zlaYxcTjmcmWOathRb0emgo/QQ3eoNzmq68+2Y2gxluAv3xGw==}- engines: {node: '>=12.16'}-- '@swc/[email protected]':- resolution: {integrity: sha512-jI/VAmtdjB/RnI8GTnokyX7Ug8c+g+ffD6QRLa6XQewtnGyukKkKSk3wLTM3b5cjt1jNh9x0jfVlagdN2gDKQg==}-'@szmarczak/[email protected]':resolution: {integrity: sha512-4BAffykYOgO+5nzBWYwE3W90sBgLJoUPRWWcL8wlyiM8IB8ipJz3UMJ9KXQd1RKQXpKp8Tutn80HZtWsu2u76w==}engines: {node: '>=10'}@@ -5878,9 +5671,6 @@ packages:resolution: {integrity: sha512-qhCRSFei0hokQr3xYcQXqxsRD/LKlgHCxHXtKHrQoImp4x2Zu6tUOpUGVH4y2qexIrzSu3aibQBNNfC3Eay6Mg==}engines: {node: '>=18'}- '@tanstack/[email protected]':- resolution: {integrity: sha512-5X41dGpxgeaHISCRW2oYwcSycZeULZzAunaudXT9ov1KOTj9xwt0CH6hbwqP1/z74ZWF7rYFnDpyYH07XFcZew==}-'@tanstack/[email protected]':resolution: {integrity: sha512-coj8ULAuR0qFpjAKD44gTgRuZyjxU6Xu+IX5MwwYvr4e61OtZcJshaExoOBKpCGde0Edb12jDnzzj2Im13Qm9Q==}engines: {node: '>=18'}@@ -6622,12 +6412,6 @@ packages:resolution: {integrity: sha512-pULv0waMlnKAUUxrsuAOa0ADONGRuhdHORtuXVgClNlScDB5YjImCV8DZrE1SicaROyE6MwGkH8CLJ+o4Nx07g==}engines: {bun: '>=0.7.0', deno: '>=1.0.0', node: '>=18.0.0'}- '@zxcvbn-ts/[email protected]':- resolution: {integrity: sha512-aQeiT0F09FuJaAqNrxynlAwZ2mW/1MdXakKWNmGM1Qp/VaY6CnB/GfnMS2T8gB2231Esp1/maCWd8vTG4OuShw==}-- '@zxcvbn-ts/[email protected]':- resolution: {integrity: sha512-viSNNnRYtc7ULXzxrQIVUNwHAPSXRtoIwy/Tq4XQQdIknBzw4vz36lQLF6mvhMlTIlpjoN/Z1GFu/fwiAlUSsw==}-resolution: {integrity: sha512-a1wflyaL0tHtJSmLSOVybYhy22vRih4eduhhrkcjgrWGnRfrZtovJ2FRjxuTtkkj47O/baf0R86QU5OuYpz8fA==}engines: {node: ^20.17.0 || >=22.9.0}@@ -6755,9 +6539,6 @@ packages:ws:optional: true- resolution: {integrity: sha512-P3TxJSe31bUHBiblg59oU1PpaWPtmxF9GhJ/cB7OkgJ0qN/ifFSKUI25/v8ZhsT+lIG6ac8DpTOplXxORX6F3Q==}-resolution: {integrity: sha512-MxT4XZL7pzLHpuvhDKdMaQHMGGkJDLluKBLsbstn+8wv9sWcFT6h+0ve9qkml95amVTZtZV83gQe2hY+ojgHLg==}hasBin: true@@ -7052,9 +6833,6 @@ packages:resolution: {integrity: sha512-L13PCJzKG8RGvx8V1/DdMi12ERhC3tprr7/8a94BxpmnRsFqxh5XZNdhtMxu5HPkRshYOOWRGY8lDP7ZhpG9Cg==}- resolution: {integrity: sha512-kwDPIFCGx0NZHog36dj+tHiwP4QMzsZ3AgMViUBKI0+V5n4U0ufTCUMhnQ04diaRI8EX/QcPfql7zlhZ7j4zgg==}-resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==}@@ -7139,9 +6917,6 @@ packages:resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==}engines: {node: '>=8'}- resolution: {integrity: sha512-g6nHaobTiT0eMZ7jh16YpD2kcjAp+PInbiVq3M1x6KKaEIVhT4v9oURNIpZLOZ3LQbQ3XYfNhMAb/9hzNLIWrw==}-resolution: {integrity: sha512-48xSriZYYg+8qXna9kwqjIVzuQxi+KYWp2+5nCYnYKPTr0LvD89Jqk2Or5ogxz0NUMfIjhh2lIUX/LyX9B4oIg==}engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7}@@ -7541,9 +7316,6 @@ packages:resolution: {integrity: sha512-VQXt1jr9cBz03b331DFDCCP90b3fanciLkgiOoy8SBHy06gNf+vQ1A3WFLqG7I8TipYIKeYK9wxd0tUrvHcOZA==}- resolution: {integrity: sha512-c3Q2VVkGAUyupsjRnaNX6u8Dq2vAdzm9iuPj5FW0fRxzlxgq9Q39MDq10IvmQSpLgHQNyQzQmOo6bgGHmH3NNg==}-resolution: {integrity: sha512-3lqz5YjWTYnW6dlDa5TLaTCcShfar1e40rmcJVwCBJC6mWlFuj0eCHIElmG1g5kyuJ/GD+8Wn4FFCcz4gJPfaQ==}@@ -7585,10 +7357,6 @@ packages:resolution: {integrity: sha512-ojKiDvcmByhwa8YYqbQI/hg7MEU0NC03+pSdEq4ZUnZR9xXpwk7E43SMNGkn+JxJGPFtNvQ48+vV2p+P1ml5PA==}- resolution: {integrity: sha512-KALDyEYgpY+Rlob/iriUtjV6d5Eq+Y191A5g4UqLAi8CyGP9N1+FdVbkc1SxKc2r4YAYqG8JzO2KGL+AizD70Q==}- deprecated: Active development of CryptoJS has been discontinued. This library is no longer maintained.-resolution: {integrity: sha512-TizTzUddG/xYLA3NXodFM0fSbNizXjOKhqiQQwvhlspadZokn1KDy0NZFS0wuEubIYAV5/c1/lAr0TaaFXEXzw==}@@ -8777,9 +8545,6 @@ packages:resolution: {integrity: sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==}- resolution: {integrity: sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==}-resolution: {integrity: sha512-0jjjIEL6+0jag3l2XWWizO64/aZVtpiGE3t0Zgqxv0DPuxiMjvB3M24fCyhZUO4KomJQPj3LTSUnDP3GpdwC0g==}@@ -8806,10 +8571,6 @@ packages:resolution: {integrity: sha512-LB+xjSTEbjHE1cWsxu+tN2Xqr1kpi+V9aADI7sVM5ZMaXyYGPHULQMzpJMYqOTULK/73pUkWVzzObFRBkPr+hg==}- resolution: {integrity: sha512-eRnCtTTtGZFpQCwhJiUOuxPQWRXVKYDn0b2PeHfXL6/Zi53SLAzAHfVhVWK2AryC/WH05kGfxhFIPvTF0SXQzg==}- engines: {node: '>= 4.9.1'}-resolution: {integrity: sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw==}@@ -9068,9 +8829,6 @@ packages:resolution: {integrity: sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==}engines: {node: '>= 6'}- resolution: {integrity: sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw==}-resolution: {integrity: sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==}deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting [email protected]@@ -9580,10 +9338,6 @@ packages:resolution: {integrity: sha512-hNngCeKxIUQiEUN3GPJOkz4wF/YvdUdbNL9hsBcMQTkKzboD7T/q3OYOuuPZLUE6dBxSGpwhk5mwuDud7JVAow==}- resolution: {integrity: sha512-z/wZZgDrkNV1eA0ULjM/F9/50Ya8fbzgKneSpoPsXSGd0KnpdtHfOZWK+GcwLk+EZbS4F9RBhU+K2RgzuDaItw==}- engines: {node: '>=20'}-resolution: {integrity: sha512-biOj/6M5qdgx5TKjDnFT1ymSpM5tbd3ylwDtrQvFQSu0Z7bBYko2dF+W/aUkXUPuk6IVpRxk/3Q2sHOzGlS36g==}@@ -11581,11 +11335,6 @@ packages:react: '*'react-native: '*'- resolution: {integrity: sha512-eqYM3wBAA0eL1sPYbBAoNfbES3+NkgcxUdelQ7QzmoVtqKB5qGG0U13MPTRUroAWK+y2EoJFS3MZUK0fwTf0pA==}- peerDependencies:- react-native: '*'-resolution: {integrity: sha512-If0eHhoEdOYDcHsX+xBFwHMbWBGK1BvGDQDQdVkwtSIXiq1uiqjkpWVP2uQ1as94J0CzvFE9PUNDuhiX0Z6ubw==}peerDependencies:@@ -12238,9 +11987,6 @@ packages:resolution: {integrity: sha512-NCGLCNyuXrFOkGHxdNZFnpsehGtiq1oXbPhKl7ZuxFO5J//H2evqqOchmD4YwEUJnkjO4kH9Xp4hQX6hdAYCKQ==}- resolution: {integrity: sha512-BbHGOQK9olHPMvQNHWul6MYlrRTAOKn03rOe4A8O3CLWhNf4YHBqq2HJKKC+sfqpxiBY52pNeesD6jIiLDz8jg==}-resolution: {integrity: sha512-jH9EhtKIjuXZ2cWxmXS8ZP80XyC3iasQxMDV8jzhNJpfDb7VbQLVW4Wvsxz9QZvzV+G4YoSfBUVKDOyxLzi/sg==}engines: {node: '>= 6'}@@ -14967,138 +14713,6 @@ snapshots:fast-wrap-ansi: 0.2.2sisteransi: 1.0.5- dependencies:- standardwebhooks: 1.0.0- tslib: 2.8.1- transitivePeerDependencies:- - react- - react-dom-- dependencies:- '@stripe/stripe-js': 5.6.0- '@swc/helpers': 0.5.21- '@tanstack/query-core': 5.100.14- '@zxcvbn-ts/core': 3.0.4- '@zxcvbn-ts/language-common': 3.0.4- alien-signals: 2.0.6- browser-tabs-lock: 1.3.0- core-js: 3.47.0- crypto-js: 4.2.0- dequal: 2.0.3- transitivePeerDependencies:- - react- - react-dom-- dependencies:- '@stripe/stripe-js': 5.6.0- '@swc/helpers': 0.5.21- '@tanstack/query-core': 5.100.14- '@zxcvbn-ts/core': 3.0.4- '@zxcvbn-ts/language-common': 3.0.4- alien-signals: 2.0.6- browser-tabs-lock: 1.3.0- core-js: 3.47.0- crypto-js: 4.2.0- dequal: 2.0.3- transitivePeerDependencies:- - react- - react-dom-- '@clerk/[email protected]':- optional: true-- '@clerk/[email protected]':- optional: true-- '@clerk/[email protected]':- optional: true-- '@clerk/[email protected]':- optional: true-- '@clerk/[email protected]':- optionalDependencies:- '@clerk/electron-passkeys-darwin-arm64': 0.0.3- '@clerk/electron-passkeys-darwin-x64': 0.0.3- '@clerk/electron-passkeys-win32-arm64-msvc': 0.0.3- '@clerk/electron-passkeys-win32-x64-msvc': 0.0.3-- '@clerk/[email protected](@clerk/[email protected])([email protected])([email protected])([email protected]([email protected]))([email protected])':- dependencies:- electron: 41.5.0- react: 19.2.6- tslib: 2.8.1- optionalDependencies:- '@clerk/electron-passkeys': 0.0.3- electron-store: 8.2.0- react-dom: 19.2.6([email protected])-- '@clerk/[email protected](patch_hash=72e426f44fc1cde16fc2cbba3d1e96cdca7c6d957faa73d0fe6b43948608a6c1)([email protected]([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected]([email protected]))([email protected]([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])))([email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])([email protected])':- dependencies:- '@expo/config-plugins': 56.0.9([email protected])- base-64: 1.0.0- expo: 56.0.12(8895228379997a2a064f9644cda56ed0)- react: 19.2.3- react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])- react-native-url-polyfill: 4.0.0([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))- tslib: 2.8.1- optionalDependencies:- expo-auth-session: 56.0.14([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])- expo-constants: 56.0.18([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))- expo-crypto: 56.0.4([email protected])- expo-secure-store: 56.0.4([email protected])- expo-web-browser: 56.0.5([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))- react-dom: 19.2.3([email protected])- transitivePeerDependencies:- - supports-color- - typescript-- dependencies:- react: 19.2.3- react-dom: 19.2.3([email protected])- tslib: 2.8.1-- dependencies:- react: 19.2.6- react-dom: 19.2.6([email protected])- tslib: 2.8.1-- dependencies:- '@tanstack/query-core': 5.100.14- dequal: 2.0.3- glob-to-regexp: 0.4.1- js-cookie: 3.0.7- optionalDependencies:- react: 19.2.3- react-dom: 19.2.3([email protected])-- dependencies:- '@tanstack/query-core': 5.100.14- dequal: 2.0.3- glob-to-regexp: 0.4.1- js-cookie: 3.0.7- optionalDependencies:- react: 19.2.6- react-dom: 19.2.6([email protected])-dependencies:unenv: 2.0.0-rc.24@@ -15208,17 +14822,6 @@ snapshots:'@distilled.cloud/core': 0.30.2([email protected](patch_hash=af36b7948b6f9c56623074662b51dade5699880c1a7c71245de73e13c3185fb6))effect: 4.0.0-beta.103(patch_hash=af36b7948b6f9c56623074662b51dade5699880c1a7c71245de73e13c3185fb6)- '@distilled.cloud/[email protected](@voidzero-dev/[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])([email protected])':- dependencies:- '@cloudflare/unenv-preset': 2.16.1([email protected])([email protected])- magic-string: 0.30.21- unenv: 2.0.0-rc.24- optionalDependencies:- rolldown: 1.1.5- vite: '@voidzero-dev/[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])'- transitivePeerDependencies:- - workerd-'@distilled.cloud/[email protected]([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])':dependencies:'@cloudflare/unenv-preset': 2.16.1([email protected])([email protected])@@ -15254,20 +14857,6 @@ snapshots:- rolldown- workerd- '@distilled.cloud/[email protected](f97c3167f1a1990dddb83bff73e575e5)':- dependencies:- '@distilled.cloud/cloudflare': 0.30.2([email protected](patch_hash=af36b7948b6f9c56623074662b51dade5699880c1a7c71245de73e13c3185fb6))- '@distilled.cloud/cloudflare-rolldown-plugin': 0.13.10(@voidzero-dev/[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])([email protected])- '@distilled.cloud/cloudflare-runtime': 0.13.10(@distilled.cloud/[email protected]([email protected](patch_hash=af36b7948b6f9c56623074662b51dade5699880c1a7c71245de73e13c3185fb6)))(@effect/[email protected]([email protected])([email protected](patch_hash=af36b7948b6f9c56623074662b51dade5699880c1a7c71245de73e13c3185fb6))([email protected]))(@effect/[email protected]([email protected])([email protected](patch_hash=af36b7948b6f9c56623074662b51dade5699880c1a7c71245de73e13c3185fb6))([email protected])([email protected]))([email protected](patch_hash=af36b7948b6f9c56623074662b51dade5699880c1a7c71245de73e13c3185fb6))- effect: 4.0.0-beta.103(patch_hash=af36b7948b6f9c56623074662b51dade5699880c1a7c71245de73e13c3185fb6)- vite: '@voidzero-dev/[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])'- optionalDependencies:- '@effect/platform-bun': 4.0.0-beta.103([email protected])([email protected](patch_hash=af36b7948b6f9c56623074662b51dade5699880c1a7c71245de73e13c3185fb6))([email protected])- '@effect/platform-node': 4.0.0-beta.103([email protected])([email protected](patch_hash=af36b7948b6f9c56623074662b51dade5699880c1a7c71245de73e13c3185fb6))([email protected])([email protected])- transitivePeerDependencies:- - rolldown- - workerd-'@distilled.cloud/[email protected]([email protected](patch_hash=af36b7948b6f9c56623074662b51dade5699880c1a7c71245de73e13c3185fb6))':dependencies:'@distilled.cloud/core': 0.30.2([email protected](patch_hash=af36b7948b6f9c56623074662b51dade5699880c1a7c71245de73e13c3185fb6))@@ -15319,7 +14908,8 @@ snapshots:react: 19.2.6tslib: 2.8.1- '@drizzle-team/[email protected]': {}+ '@drizzle-team/[email protected]':+ optional: true'@duckdb/[email protected]':dependencies:@@ -15425,6 +15015,7 @@ snapshots:pg-types: 4.1.0transitivePeerDependencies:- pg-native+ optional: true'@effect/[email protected]([email protected](patch_hash=af36b7948b6f9c56623074662b51dade5699880c1a7c71245de73e13c3185fb6))':dependencies:@@ -16658,6 +16249,7 @@ snapshots:'@js-temporal/[email protected]':dependencies:jsbi: 4.3.2+ optional: true'@legendapp/[email protected](patch_hash=064530db83875fa671559a81ae42dc159726dc2dd6ec4c982da44ff7c7a74706)([email protected]([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])':dependencies:@@ -18993,16 +18585,8 @@ snapshots:'@socket.io/[email protected]': {}- '@stablelib/[email protected]': {}-'@standard-schema/[email protected]': {}- '@stripe/[email protected]': {}-- '@swc/[email protected]':- dependencies:- tslib: 2.8.1-'@szmarczak/[email protected]':dependencies:defer-to-connect: 2.0.1@@ -19167,8 +18751,6 @@ snapshots:'@tanstack/devtools-event-client': 0.4.3'@tanstack/store': 0.8.1- '@tanstack/[email protected]': {}-dependencies:'@tanstack/pacer': 0.18.0@@ -19968,12 +19550,6 @@ snapshots:'@zip.js/[email protected]': {}- '@zxcvbn-ts/[email protected]':- dependencies:- fastest-levenshtein: 1.0.16-- '@zxcvbn-ts/[email protected]': {}-@@ -20088,69 +19664,6 @@ snapshots:json-schema-traverse: 1.0.0require-from-string: 2.0.2- [email protected](d49cefd000f1d9b608f5da03fcefc18f):- dependencies:- '@alchemy.run/node-utils': 0.0.5- '@aws-sdk/credential-providers': 3.1062.0- '@clack/prompts': 0.11.0- '@distilled.cloud/aws': 0.30.2([email protected](patch_hash=af36b7948b6f9c56623074662b51dade5699880c1a7c71245de73e13c3185fb6))- '@distilled.cloud/axiom': 0.30.2([email protected](patch_hash=af36b7948b6f9c56623074662b51dade5699880c1a7c71245de73e13c3185fb6))- '@distilled.cloud/cloudflare': 0.30.2([email protected](patch_hash=af36b7948b6f9c56623074662b51dade5699880c1a7c71245de73e13c3185fb6))- '@distilled.cloud/cloudflare-rolldown-plugin': 0.13.10(@voidzero-dev/[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])([email protected])- '@distilled.cloud/cloudflare-runtime': 0.13.10(@distilled.cloud/[email protected]([email protected](patch_hash=af36b7948b6f9c56623074662b51dade5699880c1a7c71245de73e13c3185fb6)))(@effect/[email protected]([email protected])([email protected](patch_hash=af36b7948b6f9c56623074662b51dade5699880c1a7c71245de73e13c3185fb6))([email protected]))(@effect/[email protected]([email protected])([email protected](patch_hash=af36b7948b6f9c56623074662b51dade5699880c1a7c71245de73e13c3185fb6))([email protected])([email protected]))([email protected](patch_hash=af36b7948b6f9c56623074662b51dade5699880c1a7c71245de73e13c3185fb6))- '@distilled.cloud/cloudflare-vite-plugin': 0.13.10(f97c3167f1a1990dddb83bff73e575e5)- '@distilled.cloud/core': 0.30.2([email protected](patch_hash=af36b7948b6f9c56623074662b51dade5699880c1a7c71245de73e13c3185fb6))- '@distilled.cloud/neon': 0.30.2([email protected](patch_hash=af36b7948b6f9c56623074662b51dade5699880c1a7c71245de73e13c3185fb6))- '@distilled.cloud/planetscale': 0.30.2([email protected](patch_hash=af36b7948b6f9c56623074662b51dade5699880c1a7c71245de73e13c3185fb6))- '@effect/sql-d1': 4.0.0-beta.101([email protected](patch_hash=af36b7948b6f9c56623074662b51dade5699880c1a7c71245de73e13c3185fb6))- '@effect/vitest': 4.0.0-beta.103(patch_hash=a16b1e870d8c29e4a98b17cc4c638a4ff471753d8ca3487f78a22b759caf951b)([email protected](patch_hash=af36b7948b6f9c56623074662b51dade5699880c1a7c71245de73e13c3185fb6))- '@libsql/client': 0.17.3([email protected])([email protected])- '@octokit/rest': 22.0.1- '@octokit/webhooks': 14.2.0- '@smithy/node-config-provider': 4.4.6- '@smithy/shared-ini-file-loader': 4.5.6- '@smithy/types': 4.14.3- '@types/aws-lambda': 8.10.161- aws4fetch: 1.0.20- capnweb: 0.6.1- effect: 4.0.0-beta.103(patch_hash=af36b7948b6f9c56623074662b51dade5699880c1a7c71245de73e13c3185fb6)- fast-glob: 3.3.3- fast-xml-parser: 5.8.0- ink: 6.8.0(@types/[email protected])([email protected])([email protected]([email protected])([email protected]))([email protected])([email protected])- jszip: 3.10.1- libsodium-wrappers: 0.8.4- mongodb: 6.21.0(@aws-sdk/[email protected])([email protected])- mysql2: 3.22.4(@types/[email protected])- pathe: 2.0.3- pg: 8.21.0- picomatch: 4.0.4- react: 19.2.6- rolldown: 1.1.5- undici: 7.27.1- yaml: 2.9.0- optionalDependencies:- '@effect/platform-bun': 4.0.0-beta.103([email protected])([email protected](patch_hash=af36b7948b6f9c56623074662b51dade5699880c1a7c71245de73e13c3185fb6))([email protected])- '@effect/platform-node': 4.0.0-beta.103([email protected])([email protected](patch_hash=af36b7948b6f9c56623074662b51dade5699880c1a7c71245de73e13c3185fb6))([email protected])([email protected])- '@effect/sql-pg': 4.0.0-beta.103([email protected](patch_hash=af36b7948b6f9c56623074662b51dade5699880c1a7c71245de73e13c3185fb6))- drizzle-kit: 1.0.0-rc.4- drizzle-orm: 1.0.0-rc.4(364f9547bd74875ecdea197c1b3898c3)- vite: '@voidzero-dev/[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])'- ws: 8.21.3([email protected])([email protected])- transitivePeerDependencies:- - '@mongodb-js/zstd'- - '@types/node'- - '@types/react'- - bufferutil- - gcp-metadata- - kerberos- - mongodb-client-encryption- - pg-native- - react-devtools-core- - snappy- - socks- - utf-8-validate- - workerd-[email protected](e68f28a6469d89012c3f6d03370f8faf):dependencies:'@alchemy.run/node-utils': 0.0.5@@ -20214,8 +19727,6 @@ snapshots:- utf-8-validate- workerd- [email protected]: {}-dependencies:process-ancestry: 0.1.0@@ -20713,8 +20224,6 @@ snapshots:dependencies:bare-path: 3.1.1- [email protected]: {}-@@ -20805,10 +20314,6 @@ snapshots:dependencies:fill-range: 7.1.1- dependencies:- lodash: 4.18.1-dependencies:baseline-browser-mapping: 2.10.33@@ -21227,8 +20732,6 @@ snapshots:dependencies:browserslist: 4.28.2- [email protected]: {}-@@ -21271,8 +20774,6 @@ snapshots:dependencies:uncrypto: 0.1.3- [email protected]: {}-dependencies:boolbase: 1.0.0@@ -21671,6 +21172,7 @@ snapshots:esbuild: 0.25.12get-tsconfig: 4.14.0jiti: 2.7.0+ optional: true[email protected](364f9547bd74875ecdea197c1b3898c3):optionalDependencies:@@ -21688,6 +21190,7 @@ snapshots:mysql2: 3.22.4(@types/[email protected])pg: 8.21.0zod: 4.4.3+ optional: true@@ -21952,6 +21455,7 @@ snapshots:'@esbuild/win32-arm64': 0.25.12'@esbuild/win32-ia32': 0.25.12'@esbuild/win32-x64': 0.25.12+ optional: trueoptionalDependencies:@@ -22742,8 +22246,6 @@ snapshots:- [email protected]: {}-@@ -22780,8 +22282,6 @@ snapshots:dependencies:strictdom: 1.0.1- [email protected]: {}-dependencies:reusify: 1.1.0@@ -23049,6 +22549,7 @@ snapshots:dependencies:resolve-pkg-maps: 1.0.0+ optional: truedependencies:@@ -23073,8 +22574,6 @@ snapshots:dependencies:is-glob: 4.0.3- [email protected]: {}-dependencies:foreground-child: 3.3.1@@ -23668,8 +23167,6 @@ snapshots:- [email protected]: {}-dependencies:base64-js: 1.5.1@@ -23685,7 +23182,8 @@ snapshots:dependencies:argparse: 2.0.1- [email protected]: {}+ optional: true@@ -25089,7 +24587,8 @@ snapshots:- [email protected]: {}+ optional: true@@ -25415,10 +24914,12 @@ snapshots:dependencies:pg: 8.22.0+ optional: true- [email protected]: {}+ optional: truedependencies:@@ -25449,6 +24950,7 @@ snapshots:postgres-date: 2.1.0postgres-interval: 3.0.0postgres-range: 1.1.4+ optional: truedependencies:@@ -25580,25 +25082,30 @@ snapshots:- [email protected]: {}+ optional: truedependencies:obuf: 1.1.2+ optional: true- [email protected]: {}+ optional: truedependencies:xtend: 4.0.2- [email protected]: {}+ optional: true- [email protected]: {}+ optional: truedependencies:@@ -26002,10 +25509,6 @@ snapshots:react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])warn-once: 0.1.1- [email protected]([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])):- dependencies:- react-native: 0.85.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])-[email protected]([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]):dependencies:escape-string-regexp: 4.0.0@@ -27026,11 +26529,6 @@ snapshots:- dependencies:- '@stablelib/base64': 1.0.1- fast-sha256: 1.3.0-diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex 4d3474850..2ac8a9d55 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -32,13 +32,6 @@ allowBuilds:workerd: falsecatalog:- "@clerk/backend": 3.14.0- "@clerk/clerk-js": 6.30.1- "@clerk/electron": 0.0.37- "@clerk/electron-passkeys": 0.0.3- "@clerk/expo": 4.2.0- "@clerk/react": 6.14.7- "@clerk/shared": 4.30.1"@effect/atom-react": 4.0.0-beta.103"@effect/openapi-generator": 4.0.0-beta.103"@effect/platform-bun": 4.0.0-beta.103@@ -62,12 +55,6 @@ catalog:yaml: ^2.9.0minimumReleaseAgeExclude:- - "@clerk/[email protected]"- - "@clerk/[email protected]"- - "@clerk/[email protected]"- - "@clerk/[email protected]"- - "@clerk/[email protected]"- - "@clerk/[email protected]"- "@distilled.cloud/[email protected]"- "@distilled.cloud/[email protected]"- "@distilled.cloud/[email protected]"@@ -99,19 +86,6 @@ overrides:"@anthropic-ai/claude-agent-sdk>@anthropic-ai/claude-agent-sdk-linux-x64-musl": "-""@anthropic-ai/claude-agent-sdk>@anthropic-ai/claude-agent-sdk-win32-arm64": "-""@anthropic-ai/claude-agent-sdk>@anthropic-ai/claude-agent-sdk-win32-x64": "-"- "@clerk/backend": "catalog:"- "@clerk/clerk-js": "catalog:"- "@clerk/clerk-js>@base-org/account": "-"- "@clerk/clerk-js>@coinbase/wallet-sdk": "-"- "@clerk/clerk-js>@solana/wallet-adapter-base": "-"- "@clerk/clerk-js>@solana/wallet-adapter-react": "-"- "@clerk/clerk-js>@solana/wallet-standard": "-"- "@clerk/clerk-js>@wallet-standard/core": "-"- "@clerk/electron": "catalog:"- "@clerk/electron-passkeys": "catalog:"- "@clerk/expo": "catalog:"- "@clerk/react": "catalog:"- "@clerk/shared": "catalog:""@effect/atom-react": "catalog:""@effect/platform-bun": "catalog:""@effect/platform-node": "catalog:"@@ -131,9 +105,6 @@ overrides:yaml: "catalog:"packageExtensions:- "@clerk/expo@*":- dependencies:- "@expo/config-plugins": 56.0.9"@effect/vitest@*":dependencies:vite-plus: "catalog:"@@ -145,7 +116,6 @@ packageExtensions:vite: "catalog:"patchedDependencies:- "@clerk/[email protected]": patches/@[email protected]"@effect/[email protected]": patches/@[email protected]"@expo/[email protected]": patches/@expo%[email protected]"@ff-labs/[email protected]": patches/@[email protected]diff --git a/scripts/announce-connect-ga.ts b/scripts/announce-connect-ga.tsdeleted file mode 100644index 88a4db56c..000000000--- a/scripts/announce-connect-ga.ts+++ /dev/null@@ -1,226 +0,0 @@-#!/usr/bin/env node--import * as NodeRuntime from "@effect/platform-node/NodeRuntime";-import * as NodeServices from "@effect/platform-node/NodeServices";-import * as Config from "effect/Config";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";-import * as Logger from "effect/Logger";-import * as Option from "effect/Option";-import * as Schema from "effect/Schema";-import { Command, Flag } from "effect/unstable/cli";-import {- FetchHttpClient,- HttpClient,- HttpClientRequest,- HttpClientResponse,-} from "effect/unstable/http";--const CLERK_API_URL = "https://api.clerk.com/v1";-const PAGE_SIZE = 500;--export class WaitlistEntry extends Schema.Class<WaitlistEntry>("WaitlistEntry")({- id: Schema.String,- email_address: Schema.String,- status: Schema.Literals(["pending", "invited", "completed", "rejected"]),-}) {}--const ClerkWaitlistResponse = Schema.Struct({- data: Schema.Array(WaitlistEntry),- total_count: Schema.Int,-});-const PositiveInteger = Schema.Int.check(Schema.isGreaterThan(0));-const ClerkSecretKey = Config.string("CLERK_SECRET_KEY");--export interface ConnectGaOptions {- readonly invite: boolean;- readonly limit: number | undefined;-}--export class ConnectGaRequestError extends Schema.TaggedErrorClass<ConnectGaRequestError>()(- "ConnectGaRequestError",- {- operation: Schema.String,- cause: Schema.Defect(),- },-) {- override get message(): string {- return `Clerk ${this.operation} request failed.`;- }-}--export class ConnectGaResponseError extends Schema.TaggedErrorClass<ConnectGaResponseError>()(- "ConnectGaResponseError",- {- operation: Schema.String,- status: Schema.Int,- cause: Schema.Defect(),- },-) {- override get message(): string {- return `Clerk ${this.operation} returned status ${this.status}.`;- }-}--const executeClerkJsonRequest = Effect.fn("executeClerkJsonRequest")(function* <- S extends Schema.Top,->(request: HttpClientRequest.HttpClientRequest, schema: S, operation: string) {- const client = (yield* HttpClient.HttpClient).pipe(- HttpClient.retryTransient({- retryOn: "errors-and-responses",- times: 3,- }),- );- const response = yield* client- .execute(request)- .pipe(Effect.mapError((cause) => new ConnectGaRequestError({ operation, cause })));- const success = yield* HttpClientResponse.filterStatusOk(response).pipe(- Effect.mapError(- (cause) =>- new ConnectGaResponseError({- operation,- status: response.status,- cause,- }),- ),- );- return yield* HttpClientResponse.schemaBodyJson(schema)(success).pipe(- Effect.mapError(- (cause) =>- new ConnectGaResponseError({- operation,- status: response.status,- cause,- }),- ),- );-});--const fetchWaitlistPage = Effect.fn("fetchWaitlistPage")(function* (- secretKey: string,- offset: number,-) {- const url = new URL(`${CLERK_API_URL}/waitlist_entries`);- url.searchParams.set("status", "pending");- url.searchParams.set("limit", String(PAGE_SIZE));- url.searchParams.set("offset", String(offset));- url.searchParams.set("order_by", "+created_at");- const request = HttpClientRequest.get(url.href).pipe(- HttpClientRequest.bearerToken(secretKey),- HttpClientRequest.setHeader("Clerk-API-Version", "2026-05-12"),- );- return yield* executeClerkJsonRequest(- request,- ClerkWaitlistResponse,- "list pending waitlist entries",- );-});--export const fetchPendingWaitlistEntries = Effect.fn("fetchPendingWaitlistEntries")(function* (- secretKey: string,- limit?: number,-) {- const entries: Array<WaitlistEntry> = [];- while (true) {- if (limit !== undefined && entries.length >= limit) break;- const page = yield* fetchWaitlistPage(secretKey, entries.length);- entries.push(...page.data);- if (entries.length >= page.total_count || page.data.length === 0) break;- }- return limit === undefined ? entries : entries.slice(0, limit);-});--export const inviteWaitlistEntry = Effect.fn("inviteWaitlistEntry")(function* (- secretKey: string,- entry: WaitlistEntry,-) {- const request = HttpClientRequest.post(- `${CLERK_API_URL}/waitlist_entries/${encodeURIComponent(entry.id)}/invite`,- ).pipe(- HttpClientRequest.bearerToken(secretKey),- HttpClientRequest.setHeader("Clerk-API-Version", "2026-05-12"),- );- return yield* executeClerkJsonRequest(- request,- WaitlistEntry,- `invite waitlist entry ${entry.id}`,- );-});--export const announceConnectGa = Effect.fn("announceConnectGa")(function* (- options: ConnectGaOptions,-) {- const clerkSecretKey = yield* ClerkSecretKey;- const entries = yield* fetchPendingWaitlistEntries(clerkSecretKey, options.limit);-- yield* Effect.logInfo(- options.invite ? "Connect GA waitlist invitations starting" : "Connect GA dry run",- ).pipe(- Effect.annotateLogs({- pendingEntries: entries.length,- }),- );-- if (!options.invite) {- for (const entry of entries) {- yield* Effect.logInfo("pending waitlist entry").pipe(- Effect.annotateLogs({- waitlistEntryId: entry.id,- emailAddress: entry.email_address,- }),- );- }- yield* Effect.logInfo("No invitation was sent. Re-run with --invite after reviewing the list.");- return;- }-- for (const [index, entry] of entries.entries()) {- const invited = yield* inviteWaitlistEntry(clerkSecretKey, entry);- yield* Effect.logInfo("Clerk waitlist invitation sent").pipe(- Effect.annotateLogs({- waitlistEntryId: invited.id,- completed: index + 1,- total: entries.length,- }),- );- }-});--export const announceConnectGaCommand = Command.make(- "announce-connect-ga",- {- invite: Flag.boolean("invite").pipe(- Flag.withDefault(false),- Flag.withDescription(- "Invite pending entries through Clerk. Without this flag, only print a dry-run list.",- ),- ),- limit: Flag.integer("limit").pipe(- Flag.withSchema(PositiveInteger),- Flag.optional,- Flag.withDescription("Process at most this many pending waitlist entries."),- ),- },- ({ invite, limit }) =>- announceConnectGa({- invite,- limit: Option.getOrUndefined(limit),- }),-).pipe(- Command.withDescription(- "Invite pending Clerk waitlist members now that T3 Connect is generally available.",- ),-);--if (import.meta.main) {- Command.run(announceConnectGaCommand, { version: "0.0.0" }).pipe(- Effect.provide(- Layer.mergeAll(- Logger.layer([Logger.consolePretty()]),- NodeServices.layer,- FetchHttpClient.layer,- ),- ),- NodeRuntime.runMain,- );-}diff --git a/scripts/build-desktop-artifact.test.ts b/scripts/build-desktop-artifact.test.tsindex 35636da34..c665b7b21 100644--- a/scripts/build-desktop-artifact.test.ts+++ b/scripts/build-desktop-artifact.test.ts@@ -21,19 +21,11 @@ import {DESKTOP_FILE_EXCLUSIONS,DESKTOP_EXTRA_RESOURCES,MAC_FILE_EXCLUSIONS,- InvalidMacPasskeyRpDomainError,- InvalidMacPasskeyPublishableKeyError,InvalidMockUpdateServerPortError,UnsupportedDesktopBuildArchitectureError,- isMacPasskeySigningConfigurationError,LinuxIconResizeError,- MacPasskeySigningConfigurationResolutionError,- MissingMacPasskeyProvisioningProfileError,packWindowsServerAsar,renderMacEntitlements,- resolveClerkPasskeyNativeArtifacts,- resolveMacPasskeySigningConfiguration,- resolveOptionalMacPasskeySigningConfiguration,resolveDesktopRuntimeDependencies,resolveMacStageDependencies,resolveFffNativeDependencies,@@ -555,7 +547,7 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {"node-pty": "1.1.0",},desktopDependencies: {- "@clerk/electron": "0.0.34",+ "@example/desktop-runtime": "1.0.0",effect: "4.0.0-beta.103",},arch: "arm64",@@ -565,7 +557,7 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {"@ff-labs/fff-node": "0.9.4","msgpackr-extract": "3.0.4","node-pty": "1.1.0",- "@clerk/electron": "0.0.34",+ "@example/desktop-runtime": "1.0.0",effect: "4.0.0-beta.103","@ff-labs/fff-bin-darwin-arm64": "0.9.4",},@@ -1072,105 +1064,7 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {),);- it("derives macOS passkey signing configuration from the Clerk publishable key", () => {- const configuration = resolveMacPasskeySigningConfiguration({- T3CODE_APPLE_TEAM_ID: "abc1234567",- T3CODE_MACOS_PROVISIONING_PROFILE: "/tmp/t3code.provisionprofile",- T3CODE_CLERK_PUBLISHABLE_KEY: `pk_test_${btoa("example.clerk.accounts.dev$")}`,- });-- assert.deepStrictEqual(configuration, {- appId: "dev.leodoes.akeru",- teamId: "ABC1234567",- rpDomains: ["example.clerk.accounts.dev"],- provisioningProfilePath: "/tmp/t3code.provisionprofile",- });- });-- it("normalizes explicit macOS passkey RP domains and renders required entitlements", () => {- const configuration = resolveMacPasskeySigningConfiguration({- T3CODE_APPLE_TEAM_ID: "ABC1234567",- T3CODE_MACOS_PROVISIONING_PROFILE: "/tmp/t3code.provisionprofile",- T3CODE_CLERK_PASSKEY_RP_DOMAINS:- " Clerk.Example.com,example.clerk.accounts.dev,clerk.example.com ",- });- const entitlements = renderMacEntitlements(configuration);-- assert.deepStrictEqual(configuration.rpDomains, [- "clerk.example.com",- "example.clerk.accounts.dev",- ]);- assert.include(entitlements, "<string>ABC1234567.dev.leodoes.akeru</string>");- assert.include(entitlements, "<string>webcredentials:clerk.example.com</string>");- assert.include(entitlements, "<string>webcredentials:example.clerk.accounts.dev</string>");- assert.include(entitlements, "<key>com.apple.security.cs.allow-jit</key>");- assert.include(entitlements, "<key>com.apple.security.device.audio-input</key>");- });-- it("rejects incomplete macOS passkey signing configuration", () => {- const captureError = (env: Readonly<Record<string, string | undefined>>) => {- try {- resolveMacPasskeySigningConfiguration(env);- } catch (error) {- return error;- }- return assert.fail("Expected passkey signing configuration to fail.");- };-- const missingProfileError = captureError({- T3CODE_APPLE_TEAM_ID: "ABC1234567",- T3CODE_CLERK_PASSKEY_RP_DOMAINS: "example.clerk.accounts.dev",- });- assert.instanceOf(missingProfileError, MissingMacPasskeyProvisioningProfileError);- assert.equal(- missingProfileError.message,- "T3CODE_MACOS_PROVISIONING_PROFILE must point to an Associated Domains provisioning profile.",- );-- const unsafeDomain =- "https://domain-user:[email protected]/path?token=query-secret";- const invalidDomainError = captureError({- T3CODE_APPLE_TEAM_ID: "ABC1234567",- T3CODE_MACOS_PROVISIONING_PROFILE: "/tmp/t3code.provisionprofile",- T3CODE_CLERK_PASSKEY_RP_DOMAINS: unsafeDomain,- });- assert.instanceOf(invalidDomainError, InvalidMacPasskeyRpDomainError);- assert.equal(invalidDomainError.reason, "scheme-not-allowed");- assert.equal(invalidDomainError.inputLength, unsafeDomain.length);- assert.equal(invalidDomainError.message, "Invalid passkey RP domain (scheme-not-allowed).");- assert.notProperty(invalidDomainError, "domain");- assert.notProperty(invalidDomainError, "cause");- const serializedInvalidDomainError = JSON.stringify(invalidDomainError);- assert.notInclude(serializedInvalidDomainError, unsafeDomain);- assert.notInclude(serializedInvalidDomainError, "domain-user");- assert.notInclude(serializedInvalidDomainError, "domain-secret");- assert.notInclude(serializedInvalidDomainError, "query-secret");- assert.throws(- () =>- resolveMacPasskeySigningConfiguration({- T3CODE_APPLE_TEAM_ID: "ABC1234567",- T3CODE_MACOS_PROVISIONING_PROFILE: "/tmp/t3code.provisionprofile",- T3CODE_CLERK_PASSKEY_RP_DOMAINS: "example.clerk.accounts.dev:8443",- }),- /Invalid passkey RP domain/u,- );- const invalidPublishableKeyError = captureError({- T3CODE_APPLE_TEAM_ID: "ABC1234567",- T3CODE_MACOS_PROVISIONING_PROFILE: "/tmp/t3code.provisionprofile",- T3CODE_CLERK_PUBLISHABLE_KEY: "pk_test_%",- });- assert.instanceOf(invalidPublishableKeyError, InvalidMacPasskeyPublishableKeyError);- assert.ok(invalidPublishableKeyError.cause);- assert.equal(invalidPublishableKeyError.message, "T3CODE_CLERK_PUBLISHABLE_KEY is invalid.");- assert.notProperty(invalidPublishableKeyError, "publishableKey");- assert.notInclude(invalidPublishableKeyError.message, "pk_test_%");- });-- it("does not require Clerk passkey configuration for signed macOS builds", () => {- assert.isUndefined(resolveOptionalMacPasskeySigningConfiguration({}));- });-- it("renders signed macOS entitlements without Clerk passkey configuration", () => {+ it("renders signed macOS entitlements", () => {const entitlements = renderMacEntitlements();assert.include(entitlements, "<key>com.apple.security.cs.allow-jit</key>");@@ -1184,39 +1078,15 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {assert.notInclude(entitlements, "com.apple.application-identifier");});- it("preserves known passkey signing configuration errors at the build boundary", () => {- const decodingCause = new Error("publishable-key-decode-failed");- const knownError = new InvalidMacPasskeyPublishableKeyError({ cause: decodingCause });- const error = MacPasskeySigningConfigurationResolutionError.fromCause(knownError);-- assert.strictEqual(error, knownError);- assert.instanceOf(error, InvalidMacPasskeyPublishableKeyError);- assert.strictEqual(error.cause, decodingCause);- assert.isTrue(isMacPasskeySigningConfigurationError(error));- });-- it("wraps unknown passkey signing configuration defects without copying cause text", () => {- const secret = "pk_test_do-not-retain";- const cause = new Error(secret);- const error = MacPasskeySigningConfigurationResolutionError.fromCause(cause);-- assert.instanceOf(error, MacPasskeySigningConfigurationResolutionError);- assert.strictEqual(error.cause, cause);- assert.equal(error.message, "Failed to resolve macOS passkey signing configuration.");- assert.notInclude(error.message, secret);- });-- it.effect("adds passkey entitlements and both renderer protocols to signed macOS builds", () =>+ it.effect("adds entitlements and both renderer protocols to signed macOS builds", () =>Effect.gen(function* () {const config = yield* createBuildConfig("mac", "dmg", "1.2.3", true, false, undefined, {entitlementsPath: "/tmp/entitlements.mac.plist",- provisioningProfilePath: "/tmp/t3code.provisionprofile",});const mac = config.mac as Record<string, unknown>;assert.equal(config.appId, "dev.leodoes.akeru");assert.equal(mac.entitlements, "/tmp/entitlements.mac.plist");- assert.equal(mac.provisioningProfile, "/tmp/t3code.provisionprofile");assert.equal(mac.notarize, true);assert.match(String(mac.sign), /\/scripts\/sign-macos\.ts$/);assert.deepStrictEqual(mac.protocols, [@@ -1225,7 +1095,7 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {}).pipe(Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })))),);- it.effect("keeps signed macOS entitlements explicit without Clerk passkeys", () =>+ it.effect("keeps signed macOS entitlements explicit", () =>Effect.gen(function* () {const config = yield* createBuildConfig("mac", "dmg", "1.2.3", true, false, undefined, {entitlementsPath: "/tmp/entitlements.mac.plist",@@ -1338,26 +1208,6 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {});});- it("resolves target Clerk passkey native artifacts", () => {- assert.deepStrictEqual(resolveClerkPasskeyNativeArtifacts("mac", "universal"), [- {- packageName: "@clerk/electron-passkeys-darwin-arm64",- binaryFileName: "electron-passkeys.darwin-arm64.node",- },- {- packageName: "@clerk/electron-passkeys-darwin-x64",- binaryFileName: "electron-passkeys.darwin-x64.node",- },- ]);- assert.deepStrictEqual(resolveClerkPasskeyNativeArtifacts("win", "x64"), [- {- packageName: "@clerk/electron-passkeys-win32-x64-msvc",- binaryFileName: "electron-passkeys.win32-x64-msvc.node",- },- ]);- assert.deepStrictEqual(resolveClerkPasskeyNativeArtifacts("linux", "x64"), []);- });-it("falls back to the default mock update port when the configured port is blank", () => {assert.equal(resolveMockUpdateServerUrl(undefined), "http://localhost:3000");assert.equal(resolveMockUpdateServerUrl(4123), "http://localhost:4123");diff --git a/scripts/build-desktop-artifact.ts b/scripts/build-desktop-artifact.tsindex 2f4260f39..5757cf6e3 100644--- a/scripts/build-desktop-artifact.ts+++ b/scripts/build-desktop-artifact.ts@@ -2,7 +2,6 @@// @effect-diagnostics nodeBuiltinImport:off - Node's typed junction API avoids Windows symlink privileges while keeping the probe isolated.import * as NodeFSP from "node:fs/promises";-import * as NodeModule from "node:module";import {createPackageWithOptions,@@ -14,7 +13,6 @@ import {import { fromYaml } from "@t3tools/shared/schemaYaml";import { HostProcessArchitecture, HostProcessPlatform } from "@t3tools/shared/hostProcess";-import { clerkFrontendApiHostnameFromPublishableKey } from "@t3tools/shared/relayAuth";import { resolveSpawnCommand } from "@t3tools/shared/shell";import rootPackageJson from "../package.json" with { type: "json" };import desktopPackageJson from "../apps/desktop/package.json" with { type: "json" };@@ -198,41 +196,6 @@ const getDefaultArch = Effect.fn("getDefaultArch")(function* (platform: typeof Breturn yield* getDefaultBuildArch(platform, config);});-export class MacPasskeySigningConfigurationResolutionError extends Schema.TaggedErrorClass<MacPasskeySigningConfigurationResolutionError>()(- "MacPasskeySigningConfigurationResolutionError",- {- cause: Schema.Defect(),- },-) {- static fromCause(- cause: unknown,- ): MacPasskeySigningConfigurationError | MacPasskeySigningConfigurationResolutionError {- return isMacPasskeySigningConfigurationError(cause)- ? cause- : new MacPasskeySigningConfigurationResolutionError({ cause });- }-- override get message(): string {- return "Failed to resolve macOS passkey signing configuration.";- }-}--export class ClerkPasskeyNativePackageMissingError extends Schema.TaggedErrorClass<ClerkPasskeyNativePackageMissingError>()(- "ClerkPasskeyNativePackageMissingError",- {- packageName: Schema.String,- binaryFileName: Schema.String,- packageEntryPath: Schema.String,- platform: BuildPlatform,- arch: BuildArch,- cause: Schema.Defect(),- },-) {- override get message(): string {- return `Clerk passkey native package is missing: ${this.packageName}`;- }-}-export class UnsupportedHostBuildPlatformError extends Schema.TaggedErrorClass<UnsupportedHostBuildPlatformError>()("UnsupportedHostBuildPlatformError",{@@ -877,228 +840,12 @@ export const DESKTOP_EXTRA_RESOURCES = [},] as const;-export interface MacPasskeySigningConfiguration {- readonly appId: string;- readonly teamId: string;- readonly rpDomains: readonly string[];- readonly provisioningProfilePath: string;-}--export const InvalidMacPasskeyRpDomainReason = Schema.Literals([- "empty",- "scheme-not-allowed",- "parse-failed",- "credentials-not-allowed",- "port-not-allowed",- "path-not-allowed",- "query-not-allowed",- "fragment-not-allowed",- "hostname-mismatch",-]);-export type InvalidMacPasskeyRpDomainReason = typeof InvalidMacPasskeyRpDomainReason.Type;--export class InvalidMacPasskeyRpDomainError extends Schema.TaggedErrorClass<InvalidMacPasskeyRpDomainError>()(- "InvalidMacPasskeyRpDomainError",- {- reason: InvalidMacPasskeyRpDomainReason,- inputLength: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),- cause: Schema.optionalKey(Schema.Defect()),- },-) {- override get message(): string {- return `Invalid passkey RP domain (${this.reason}).`;- }-}--export class InvalidAppleTeamIdError extends Schema.TaggedErrorClass<InvalidAppleTeamIdError>()(- "InvalidAppleTeamIdError",- {- teamId: Schema.String,- },-) {- override get message(): string {- return `T3CODE_APPLE_TEAM_ID '${this.teamId}' must be a 10-character Apple Developer Team ID.`;- }-}--export class MissingMacPasskeyProvisioningProfileError extends Schema.TaggedErrorClass<MissingMacPasskeyProvisioningProfileError>()(- "MissingMacPasskeyProvisioningProfileError",- {},-) {- override get message(): string {- return "T3CODE_MACOS_PROVISIONING_PROFILE must point to an Associated Domains provisioning profile.";- }-}--export class MissingMacPasskeyDomainConfigurationError extends Schema.TaggedErrorClass<MissingMacPasskeyDomainConfigurationError>()(- "MissingMacPasskeyDomainConfigurationError",- {},-) {- override get message(): string {- return "T3CODE_CLERK_PUBLISHABLE_KEY or T3CODE_CLERK_PASSKEY_RP_DOMAINS is required for signed macOS passkey builds.";- }-}--export class InvalidMacPasskeyPublishableKeyError extends Schema.TaggedErrorClass<InvalidMacPasskeyPublishableKeyError>()(- "InvalidMacPasskeyPublishableKeyError",- {- cause: Schema.Defect(),- },-) {- override get message(): string {- return "T3CODE_CLERK_PUBLISHABLE_KEY is invalid.";- }-}--export class MissingMacPasskeyRpDomainError extends Schema.TaggedErrorClass<MissingMacPasskeyRpDomainError>()(- "MissingMacPasskeyRpDomainError",- {},-) {- override get message(): string {- return "At least one Clerk passkey RP domain is required.";- }-}--export const MacPasskeySigningConfigurationError = Schema.Union([- InvalidMacPasskeyRpDomainError,- InvalidAppleTeamIdError,- MissingMacPasskeyProvisioningProfileError,- MissingMacPasskeyDomainConfigurationError,- InvalidMacPasskeyPublishableKeyError,- MissingMacPasskeyRpDomainError,-]);-export type MacPasskeySigningConfigurationError = typeof MacPasskeySigningConfigurationError.Type;-export const isMacPasskeySigningConfigurationError = Schema.is(MacPasskeySigningConfigurationError);--function normalizePasskeyRpDomain(value: string): string {- const normalized = value.trim().toLowerCase();- const inputLength = value.length;- if (normalized.length === 0) {- throw new InvalidMacPasskeyRpDomainError({ reason: "empty", inputLength });- }- if (/^[a-z][a-z\d+.-]*:\/\//u.test(normalized)) {- throw new InvalidMacPasskeyRpDomainError({- reason: "scheme-not-allowed",- inputLength,- });- }-- let parsed: URL;- try {- parsed = new URL(`https://${normalized}`);- } catch (cause) {- throw new InvalidMacPasskeyRpDomainError({ reason: "parse-failed", inputLength, cause });- }-- let reason: InvalidMacPasskeyRpDomainReason | undefined;- if (parsed.username.length > 0 || parsed.password.length > 0) {- reason = "credentials-not-allowed";- } else if (parsed.port.length > 0) {- reason = "port-not-allowed";- } else if (parsed.pathname !== "/") {- reason = "path-not-allowed";- } else if (parsed.search.length > 0) {- reason = "query-not-allowed";- } else if (parsed.hash.length > 0) {- reason = "fragment-not-allowed";- } else if (parsed.host !== normalized) {- reason = "hostname-mismatch";- }- if (reason) {- throw new InvalidMacPasskeyRpDomainError({ reason, inputLength });- }-- return parsed.hostname;-}--export function resolveMacPasskeySigningConfiguration(- env: Readonly<Record<string, string | undefined>>,-): MacPasskeySigningConfiguration {- const teamId = env.T3CODE_APPLE_TEAM_ID?.trim().toUpperCase() ?? "";- if (!APPLE_TEAM_ID_PATTERN.test(teamId)) {- throw new InvalidAppleTeamIdError({ teamId });- }-- const provisioningProfilePath = env.T3CODE_MACOS_PROVISIONING_PROFILE?.trim() ?? "";- if (provisioningProfilePath.length === 0) {- throw new MissingMacPasskeyProvisioningProfileError();- }-- const configuredRpDomains = env.T3CODE_CLERK_PASSKEY_RP_DOMAINS?.trim();- let rpDomains: readonly string[];- if (configuredRpDomains) {- rpDomains = configuredRpDomains.split(",").map(normalizePasskeyRpDomain);- } else {- const publishableKey = env.T3CODE_CLERK_PUBLISHABLE_KEY?.trim();- if (!publishableKey) {- throw new MissingMacPasskeyDomainConfigurationError();- }- let hostname: string;- try {- hostname = clerkFrontendApiHostnameFromPublishableKey(publishableKey);- } catch (cause) {- throw new InvalidMacPasskeyPublishableKeyError({ cause });- }- rpDomains = [normalizePasskeyRpDomain(hostname)];- }-- const uniqueRpDomains = [...new Set(rpDomains)];- if (uniqueRpDomains.length === 0) {- throw new MissingMacPasskeyRpDomainError();- }-- return {- appId: DESKTOP_APP_ID,- teamId,- rpDomains: uniqueRpDomains,- provisioningProfilePath,- };-}--export function resolveOptionalMacPasskeySigningConfiguration(- env: Readonly<Record<string, string | undefined>>,-): MacPasskeySigningConfiguration | undefined {- const hasPasskeyConfiguration = [- env.T3CODE_APPLE_TEAM_ID,- env.T3CODE_MACOS_PROVISIONING_PROFILE,- env.T3CODE_CLERK_PASSKEY_RP_DOMAINS,- env.T3CODE_CLERK_PUBLISHABLE_KEY,- ].some((value) => Boolean(value?.trim()));- if (!hasPasskeyConfiguration) {- return undefined;- }- return resolveMacPasskeySigningConfiguration(env);-}--function escapeXml(value: string): string {- return value- .replaceAll("&", "&")- .replaceAll("<", "<")- .replaceAll(">", ">")- .replaceAll('"', """)- .replaceAll("'", "'");-}--export function renderMacEntitlements(configuration?: MacPasskeySigningConfiguration): string {- const passkeyEntitlements = configuration- ? ` <key>com.apple.application-identifier</key>- <string>${escapeXml(`${configuration.teamId}.${configuration.appId}`)}</string>- <key>com.apple.developer.team-identifier</key>- <string>${escapeXml(configuration.teamId)}</string>- <key>com.apple.developer.associated-domains</key>- <array>-${configuration.rpDomains- .map((domain) => ` <string>webcredentials:${escapeXml(domain)}</string>`)- .join("\n")}- </array>-`- : "";-+export function renderMacEntitlements(): string {return `<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict>-${passkeyEntitlements} <key>com.apple.security.cs.allow-jit</key>+ <key>com.apple.security.cs.allow-jit</key><true/><key>com.apple.security.cs.allow-unsigned-executable-memory</key><true/>@@ -1150,67 +897,6 @@ export function resolveMacStageDependencies(input: {};}-export interface ClerkPasskeyNativeArtifact {- readonly packageName: string;- readonly binaryFileName: string;-}--export function resolveClerkPasskeyNativeArtifacts(- platform: typeof BuildPlatform.Type,- arch: typeof BuildArch.Type,-): readonly ClerkPasskeyNativeArtifact[] {- const architectures = arch === "universal" ? (["arm64", "x64"] as const) : [arch];-- if (platform === "mac") {- return architectures.map((architecture) => ({- packageName: `@clerk/electron-passkeys-darwin-${architecture}`,- binaryFileName: `electron-passkeys.darwin-${architecture}.node`,- }));- }-- if (platform === "win") {- return architectures.map((architecture) => ({- packageName: `@clerk/electron-passkeys-win32-${architecture}-msvc`,- binaryFileName: `electron-passkeys.win32-${architecture}-msvc.node`,- }));- }-- return [];-}--// pnpm nests the architecture package under @clerk/electron-passkeys, while electron-builder only-// retains collected top-level dependencies. The SDK loader checks beside index.js first, so stage-// the binary there and let electron-builder's native-addon handling unpack it from the ASAR.-const stageClerkPasskeyNativeBinaries = Effect.fn("stageClerkPasskeyNativeBinaries")(function* (- stageAppDir: string,- platform: typeof BuildPlatform.Type,- arch: typeof BuildArch.Type,-) {- const fs = yield* FileSystem.FileSystem;- const path = yield* Path.Path;- const packageEntryPath = yield* fs.realPath(- path.join(stageAppDir, "node_modules", "@clerk", "electron-passkeys", "index.js"),- );- const packageDir = path.dirname(packageEntryPath);- const packageRequire = NodeModule.createRequire(packageEntryPath);-- for (const artifact of resolveClerkPasskeyNativeArtifacts(platform, arch)) {- const sourcePath = yield* Effect.try({- try: () => packageRequire.resolve(artifact.packageName),- catch: (cause) =>- new ClerkPasskeyNativePackageMissingError({- packageName: artifact.packageName,- binaryFileName: artifact.binaryFileName,- packageEntryPath,- platform,- arch,- cause,- }),- });- yield* fs.copyFile(sourcePath, path.join(packageDir, artifact.binaryFileName));- }-});-export function createStageWorkspaceConfig(input: {readonly platform: typeof BuildPlatform.Type;readonly arch: typeof BuildArch.Type;@@ -2929,33 +2615,12 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (const stageProdResourcesDir = path.join(stageAppDir, "apps/desktop/prod-resources");yield* fs.copy(stageResourcesDir, stageProdResourcesDir);- const configuredMacPasskeySigning =- options.platform === "mac" && options.signed- ? yield* Effect.try({- try: () => resolveOptionalMacPasskeySigningConfiguration(loadRepoEnv({ repoRoot })),- catch: MacPasskeySigningConfigurationResolutionError.fromCause,- })- : undefined;- const macPasskeySigning = configuredMacPasskeySigning- ? {- ...configuredMacPasskeySigning,- provisioningProfilePath: path.resolve(- repoRoot,- configuredMacPasskeySigning.provisioningProfilePath,- ),- }- : undefined;const macEntitlementsPath =options.platform === "mac" && options.signed? path.join(stageAppDir, "entitlements.mac.plist"): undefined;if (macEntitlementsPath) {- if (macPasskeySigning && !(yield* fs.exists(macPasskeySigning.provisioningProfilePath))) {- return yield* new MacProvisioningProfileNotFoundError({- provisioningProfilePath: macPasskeySigning.provisioningProfilePath,- });- }- yield* fs.writeFileString(macEntitlementsPath, renderMacEntitlements(macPasskeySigning));+ yield* fs.writeFileString(macEntitlementsPath, renderMacEntitlements());}// Windows splits dependencies per process: app.asar carries only the@@ -3007,14 +2672,7 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (options.signed,options.mockUpdates,options.mockUpdateServerPort,- macEntitlementsPath- ? {- entitlementsPath: macEntitlementsPath,- ...(macPasskeySigning- ? { provisioningProfilePath: macPasskeySigning.provisioningProfilePath }- : {}),- }- : undefined,+ macEntitlementsPath ? { entitlementsPath: macEntitlementsPath } : undefined,),dependencies: stageDependencies,devDependencies: {@@ -3050,7 +2708,6 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (}),{ label: "vp install --prod", verbose: options.verbose },);- yield* stageClerkPasskeyNativeBinaries(stageAppDir, options.platform, options.arch);// WSL is Windows-only, so only the Windows artifact carries the server// sidecar (which embeds the Linux node-pty prebuild); other platformsdiff --git a/scripts/lib/cli-external-packages.test.ts b/scripts/lib/cli-external-packages.test.tsindex 754cd646f..61debf050 100644--- a/scripts/lib/cli-external-packages.test.ts+++ b/scripts/lib/cli-external-packages.test.ts@@ -47,7 +47,6 @@ describe("shouldBundleCliDependency", () => {"ffi-rs","@yuuang/ffi-rs-win32-x64-msvc","@ff-labs/fff-node",- "@clerk/electron-passkeys","msgpackr-extract","@msgpackr-extract/msgpackr-extract-win32-x64",]) {diff --git a/scripts/lib/cli-external-packages.ts b/scripts/lib/cli-external-packages.tsindex d7a89bc40..94d164a95 100644--- a/scripts/lib/cli-external-packages.ts+++ b/scripts/lib/cli-external-packages.ts@@ -30,7 +30,6 @@ export const CLI_RUNTIME_EXTERNAL_PREFIXES = ["ffi-rs","@yuuang/","@ff-labs/",- "@clerk/electron-passkeys","@msgpackr-extract/","msgpackr-extract","node-gyp-build",diff --git a/scripts/lib/public-config.test.ts b/scripts/lib/public-config.test.tsindex 62d383484..420b5d0b7 100644--- a/scripts/lib/public-config.test.ts+++ b/scripts/lib/public-config.test.ts@@ -15,111 +15,55 @@ afterEach(() => {});describe("loadRepoEnv", () => {- it("does not project cloud configuration for an unconfigured clone", () => {+ it("does not project mobile tracing configuration for an unconfigured clone", () => {const env = loadRepoEnv({ baseEnv: {}, repoRoot: makeTemporaryDirectory() });- expect(env.T3CODE_CLERK_PUBLISHABLE_KEY).toBeUndefined();- expect(env.T3CODE_CLERK_CLI_OAUTH_CLIENT_ID).toBeUndefined();- expect(env.VITE_CLERK_PUBLISHABLE_KEY).toBeUndefined();- expect(env.EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY).toBeUndefined();- expect(env.T3CODE_CLERK_JWT_TEMPLATE).toBeUndefined();- expect(env.VITE_CLERK_JWT_TEMPLATE).toBeUndefined();- expect(env.EXPO_PUBLIC_CLERK_JWT_TEMPLATE).toBeUndefined();- expect(env.T3CODE_RELAY_URL).toBeUndefined();- expect(env.VITE_T3CODE_RELAY_URL).toBeUndefined();expect(env.T3CODE_MOBILE_OTLP_TRACES_URL).toBeUndefined();expect(env.T3CODE_MOBILE_OTLP_TRACES_DATASET).toBeUndefined();expect(env.T3CODE_MOBILE_OTLP_TRACES_TOKEN).toBeUndefined();expect(env.EXPO_PUBLIC_OTLP_TRACES_URL).toBeUndefined();expect(env.EXPO_PUBLIC_OTLP_TRACES_DATASET).toBeUndefined();expect(env.EXPO_PUBLIC_OTLP_TRACES_TOKEN).toBeUndefined();- expect(env.T3CODE_RELAY_CLIENT_OTLP_TRACES_URL).toBeUndefined();- expect(env.T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET).toBeUndefined();- expect(env.T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN).toBeUndefined();- expect(env.VITE_RELAY_OTLP_TRACES_URL).toBeUndefined();- expect(env.VITE_RELAY_OTLP_TRACES_DATASET).toBeUndefined();- expect(env.VITE_RELAY_OTLP_TRACES_TOKEN).toBeUndefined();});it("applies process, root local, and root precedence in that order", () => {const repoRoot = makeTemporaryDirectory();NodeFS.writeFileSync(NodePath.join(repoRoot, ".env"),- "T3CODE_CLERK_PUBLISHABLE_KEY=pk_root\nT3CODE_CLERK_JWT_TEMPLATE=template_root\nT3CODE_CLERK_CLI_OAUTH_CLIENT_ID=oauth_root\nT3CODE_RELAY_URL=https://root.example.test\n",+ "T3CODE_MOBILE_OTLP_TRACES_DATASET=root-traces\n",);NodeFS.writeFileSync(NodePath.join(repoRoot, ".env.local"),- "T3CODE_CLERK_PUBLISHABLE_KEY=pk_local\nT3CODE_CLERK_JWT_TEMPLATE=template_local\nT3CODE_CLERK_CLI_OAUTH_CLIENT_ID=oauth_local\nT3CODE_RELAY_URL=https://local.example.test\n",+ "T3CODE_MOBILE_OTLP_TRACES_DATASET=local-traces\n",);- expect(loadRepoEnv({ baseEnv: {}, repoRoot }).T3CODE_RELAY_URL).toBe(- "https://local.example.test",+ expect(loadRepoEnv({ baseEnv: {}, repoRoot }).T3CODE_MOBILE_OTLP_TRACES_DATASET).toBe(+ "local-traces",);expect(loadRepoEnv({baseEnv: {- T3CODE_CLERK_PUBLISHABLE_KEY: "pk_ci",- T3CODE_CLERK_JWT_TEMPLATE: "template_ci",- T3CODE_CLERK_CLI_OAUTH_CLIENT_ID: "oauth_ci",- T3CODE_RELAY_URL: "https://ci.example.test",+ T3CODE_MOBILE_OTLP_TRACES_DATASET: "ci-traces",},repoRoot,}),).toMatchObject({- T3CODE_CLERK_PUBLISHABLE_KEY: "pk_ci",- T3CODE_CLERK_CLI_OAUTH_CLIENT_ID: "oauth_ci",- VITE_CLERK_PUBLISHABLE_KEY: "pk_ci",- EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY: "pk_ci",- T3CODE_CLERK_JWT_TEMPLATE: "template_ci",- VITE_CLERK_JWT_TEMPLATE: "template_ci",- EXPO_PUBLIC_CLERK_JWT_TEMPLATE: "template_ci",- T3CODE_RELAY_URL: "https://ci.example.test",- VITE_T3CODE_RELAY_URL: "https://ci.example.test",+ T3CODE_MOBILE_OTLP_TRACES_DATASET: "ci-traces",+ EXPO_PUBLIC_OTLP_TRACES_DATASET: "ci-traces",});});it("accepts legacy framework aliases as root overrides", () => {expect(resolvePublicConfig({- VITE_CLERK_PUBLISHABLE_KEY: "pk_legacy",- VITE_CLERK_JWT_TEMPLATE: "template_legacy",- T3CODE_CLERK_CLI_OAUTH_CLIENT_ID: "oauth_canonical",- VITE_T3CODE_RELAY_URL: "https://legacy.example.test",EXPO_PUBLIC_OTLP_TRACES_URL: "https://api.axiom.co/v1/traces",EXPO_PUBLIC_OTLP_TRACES_DATASET: "mobile-traces",EXPO_PUBLIC_OTLP_TRACES_TOKEN: "mobile-token",}),).toEqual({- clerkPublishableKey: "pk_legacy",- clerkJwtTemplate: "template_legacy",- clerkCliOAuthClientId: "oauth_canonical",- relayUrl: "https://legacy.example.test",mobileOtlpTracesUrl: "https://api.axiom.co/v1/traces",mobileOtlpTracesDataset: "mobile-traces",mobileOtlpTracesToken: "mobile-token",- relayClientOtlpTracesUrl: undefined,- relayClientOtlpTracesDataset: undefined,- relayClientOtlpTracesToken: undefined,- });- });-- it("projects canonical relay client tracing values to web build aliases", () => {- expect(- loadRepoEnv({- baseEnv: {- T3CODE_RELAY_CLIENT_OTLP_TRACES_URL: "https://api.axiom.co/v1/traces",- T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET: "relay-client-traces",- T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN: "relay-client-token",- },- repoRoot: makeTemporaryDirectory(),- }),- ).toEqual({- T3CODE_RELAY_CLIENT_OTLP_TRACES_URL: "https://api.axiom.co/v1/traces",- T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET: "relay-client-traces",- T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN: "relay-client-token",- VITE_RELAY_OTLP_TRACES_URL: "https://api.axiom.co/v1/traces",- VITE_RELAY_OTLP_TRACES_DATASET: "relay-client-traces",- VITE_RELAY_OTLP_TRACES_TOKEN: "relay-client-token",});});@@ -127,7 +71,6 @@ describe("loadRepoEnv", () => {expect(loadRepoEnv({baseEnv: {- T3CODE_RELAY_URL: "https://relay.example.test",T3CODE_MOBILE_OTLP_TRACES_URL: "https://api.axiom.co/v1/traces",T3CODE_MOBILE_OTLP_TRACES_DATASET: "mobile-traces",T3CODE_MOBILE_OTLP_TRACES_TOKEN: "mobile-token",@@ -135,8 +78,6 @@ describe("loadRepoEnv", () => {repoRoot: makeTemporaryDirectory(),}),).toEqual({- T3CODE_RELAY_URL: "https://relay.example.test",- VITE_T3CODE_RELAY_URL: "https://relay.example.test",T3CODE_MOBILE_OTLP_TRACES_URL: "https://api.axiom.co/v1/traces",T3CODE_MOBILE_OTLP_TRACES_DATASET: "mobile-traces",T3CODE_MOBILE_OTLP_TRACES_TOKEN: "mobile-token",diff --git a/scripts/lib/public-config.ts b/scripts/lib/public-config.tsindex 36ca5497f..ee70fdea1 100644--- a/scripts/lib/public-config.ts+++ b/scripts/lib/public-config.ts@@ -5,16 +5,9 @@ import * as NodeURL from "node:url";import * as NodeUtil from "node:util";export interface T3CodePublicConfig {- readonly clerkPublishableKey: string | undefined;- readonly clerkJwtTemplate: string | undefined;- readonly clerkCliOAuthClientId: string | undefined;- readonly relayUrl: string | undefined;readonly mobileOtlpTracesUrl: string | undefined;readonly mobileOtlpTracesDataset: string | undefined;readonly mobileOtlpTracesToken: string | undefined;- readonly relayClientOtlpTracesUrl: string | undefined;- readonly relayClientOtlpTracesDataset: string | undefined;- readonly relayClientOtlpTracesToken: string | undefined;}type Environment = Readonly<Record<string, string | undefined>>;@@ -38,32 +31,6 @@ export function loadRepoEnv({...rootEnv,...localEnv,...baseEnv,- ...(config.clerkPublishableKey- ? {- T3CODE_CLERK_PUBLISHABLE_KEY: config.clerkPublishableKey,- VITE_CLERK_PUBLISHABLE_KEY: config.clerkPublishableKey,- EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY: config.clerkPublishableKey,- }- : {}),- ...(config.clerkJwtTemplate- ? {- T3CODE_CLERK_JWT_TEMPLATE: config.clerkJwtTemplate,- VITE_CLERK_JWT_TEMPLATE: config.clerkJwtTemplate,- EXPO_PUBLIC_CLERK_JWT_TEMPLATE: config.clerkJwtTemplate,- }- : {}),- ...(config.clerkCliOAuthClientId- ? {- T3CODE_CLERK_CLI_OAUTH_CLIENT_ID: config.clerkCliOAuthClientId,- VITE_CLERK_CLI_OAUTH_CLIENT_ID: config.clerkCliOAuthClientId,- }- : {}),- ...(config.relayUrl- ? {- T3CODE_RELAY_URL: config.relayUrl,- VITE_T3CODE_RELAY_URL: config.relayUrl,- }- : {}),...(config.mobileOtlpTracesUrl? {T3CODE_MOBILE_OTLP_TRACES_URL: config.mobileOtlpTracesUrl,@@ -82,47 +49,11 @@ export function loadRepoEnv({EXPO_PUBLIC_OTLP_TRACES_TOKEN: config.mobileOtlpTracesToken,}: {}),- ...(config.relayClientOtlpTracesUrl- ? {- T3CODE_RELAY_CLIENT_OTLP_TRACES_URL: config.relayClientOtlpTracesUrl,- VITE_RELAY_OTLP_TRACES_URL: config.relayClientOtlpTracesUrl,- }- : {}),- ...(config.relayClientOtlpTracesDataset- ? {- T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET: config.relayClientOtlpTracesDataset,- VITE_RELAY_OTLP_TRACES_DATASET: config.relayClientOtlpTracesDataset,- }- : {}),- ...(config.relayClientOtlpTracesToken- ? {- T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN: config.relayClientOtlpTracesToken,- VITE_RELAY_OTLP_TRACES_TOKEN: config.relayClientOtlpTracesToken,- }- : {}),};}export function resolvePublicConfig(...sources: readonly Environment[]): T3CodePublicConfig {return {- clerkPublishableKey: firstNonEmpty(- sources,- "T3CODE_CLERK_PUBLISHABLE_KEY",- "VITE_CLERK_PUBLISHABLE_KEY",- "EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY",- ),- clerkJwtTemplate: firstNonEmpty(- sources,- "T3CODE_CLERK_JWT_TEMPLATE",- "VITE_CLERK_JWT_TEMPLATE",- "EXPO_PUBLIC_CLERK_JWT_TEMPLATE",- ),- clerkCliOAuthClientId: firstNonEmpty(- sources,- "T3CODE_CLERK_CLI_OAUTH_CLIENT_ID",- "VITE_CLERK_CLI_OAUTH_CLIENT_ID",- ),- relayUrl: firstNonEmpty(sources, "T3CODE_RELAY_URL", "VITE_T3CODE_RELAY_URL"),mobileOtlpTracesUrl: firstNonEmpty(sources,"T3CODE_MOBILE_OTLP_TRACES_URL",@@ -138,21 +69,6 @@ export function resolvePublicConfig(...sources: readonly Environment[]): T3CodeP"T3CODE_MOBILE_OTLP_TRACES_TOKEN","EXPO_PUBLIC_OTLP_TRACES_TOKEN",),- relayClientOtlpTracesUrl: firstNonEmpty(- sources,- "T3CODE_RELAY_CLIENT_OTLP_TRACES_URL",- "VITE_RELAY_OTLP_TRACES_URL",- ),- relayClientOtlpTracesDataset: firstNonEmpty(- sources,- "T3CODE_RELAY_CLIENT_OTLP_TRACES_DATASET",- "VITE_RELAY_OTLP_TRACES_DATASET",- ),- relayClientOtlpTracesToken: firstNonEmpty(- sources,- "T3CODE_RELAY_CLIENT_OTLP_TRACES_TOKEN",- "VITE_RELAY_OTLP_TRACES_TOKEN",- ),};}diff --git a/scripts/lib/reference-repos.ts b/scripts/lib/reference-repos.tsindex 005c619ff..00a062713 100644--- a/scripts/lib/reference-repos.ts+++ b/scripts/lib/reference-repos.ts@@ -18,13 +18,4 @@ export const referenceRepos: ReadonlyArray<ReferenceRepo> = [packageVersionPath: ["catalog", "effect"],versionTagPrefix: "effect@",},- {- id: "alchemy-effect",- prefix: ".repos/alchemy-effect",- repository: "https://github.com/alchemy-run/alchemy-effect.git",- latestRef: "main",- versionSourcePath: "infra/relay/package.json",- packageVersionPath: ["dependencies", "alchemy"],- versionTagPrefix: "v",- },];diff --git a/scripts/release-smoke.ts b/scripts/release-smoke.tsindex 773661f91..f4891ee34 100644--- a/scripts/release-smoke.ts+++ b/scripts/release-smoke.ts@@ -74,8 +74,8 @@ for (const [needle, label] of [}for (const [needle, label] of [- ["clerk", "Clerk configuration"],["relay", "relay configuration"],+ ["clerk", "Clerk configuration"],["publish-aur", "AUR publishing"],["action-gh-release", "GitHub release publishing"],["vercel deploy", "hosted deployment"],@@ -90,7 +90,6 @@ for (const [needle, label] of [["blacksmith", "private CI runners"],["thread-transfer", "thread transfer reporting"],["mobile_native", "mobile production checks"],- ["clerk", "Clerk bundle checks"],] as const) {assertOmits(ciWorkflow, needle, `CI workflow still contains ${label}.`);}diff --git a/scripts/sync-reference-repos.test.ts b/scripts/sync-reference-repos.test.tsindex e31899363..663aa4ccf 100644--- a/scripts/sync-reference-repos.test.ts+++ b/scripts/sync-reference-repos.test.ts@@ -17,7 +17,6 @@ import {const encoder = new TextEncoder();const effectSmol = referenceRepos[0]!;-const alchemyEffect = referenceRepos[1]!;function mockHandle(options: {@@ -121,63 +120,23 @@ it.layer(NodeServices.layer)("sync-reference-repos", (it) => {const rootDir = yield* fs.makeTempDirectoryScoped({prefix: "sync-reference-repos-parse-error-",});- const sourcePath = path.join(rootDir, alchemyEffect.versionSourcePath);+ const sourcePath = path.join(rootDir, effectSmol.versionSourcePath);yield* fs.makeDirectory(path.dirname(sourcePath), { recursive: true });yield* fs.writeFileString(sourcePath, "{");- const error = yield* resolveReferenceRepoRef(alchemyEffect, rootDir, false).pipe(Effect.flip);+ const error = yield* resolveReferenceRepoRef(effectSmol, rootDir, false).pipe(Effect.flip);if (error._tag !== "ReferenceRepoVersionSourceError") {assert.fail(`Unexpected error: ${error._tag}`);}assert.equal(error.operation, "parse");- assert.equal(error.repoId, alchemyEffect.id);+ assert.equal(error.repoId, effectSmol.id);assert.equal(error.sourcePath, sourcePath);assert.ok(error.cause !== undefined);assert.ok(!error.message.includes(String((error.cause as Error).message)));}),);- it.effect("reports the unresolved package path without inventing a cause", () =>- Effect.gen(function* () {- const fs = yield* FileSystem.FileSystem;- const path = yield* Path.Path;- const rootDir = yield* fs.makeTempDirectoryScoped({- prefix: "sync-reference-repos-resolution-error-",- });- const sourcePath = path.join(rootDir, alchemyEffect.versionSourcePath);- yield* fs.makeDirectory(path.dirname(sourcePath), { recursive: true });- yield* fs.writeFileString(sourcePath, '{"dependencies":{}}');-- const error = yield* resolveReferenceRepoRef(alchemyEffect, rootDir, false).pipe(Effect.flip);-- if (error._tag !== "ReferenceRepoVersionResolutionError") {- assert.fail(`Unexpected error: ${error._tag}`);- }- assert.equal(error.repoId, alchemyEffect.id);- assert.equal(error.sourcePath, sourcePath);- assert.deepStrictEqual(error.packageVersionPath, ["dependencies", "alchemy"]);- assert.ok(!("cause" in error));- }),- );-- it.effect("resolves the alchemy-effect tag from the relay package", () =>- Effect.gen(function* () {- const fs = yield* FileSystem.FileSystem;- const path = yield* Path.Path;- const rootDir = yield* fs.makeTempDirectoryScoped({- prefix: "sync-reference-repos-alchemy-version-",- });- yield* fs.makeDirectory(path.join(rootDir, "infra", "relay"), { recursive: true });- yield* fs.writeFileString(- path.join(rootDir, "infra", "relay", "package.json"),- '{"dependencies":{"alchemy":"2.0.0-beta.49"}}',- );-- assert.equal(yield* resolveReferenceRepoRef(alchemyEffect, rootDir, false), "v2.0.0-beta.49");- }),- );-it.effect("plans an add for a missing subtree and a pull for an existing subtree", () =>Effect.gen(function* () {const fs = yield* FileSystem.FileSystem;@@ -251,7 +210,7 @@ it.layer(NodeServices.layer)("sync-reference-repos", (it) => {assert.fail(`Unexpected error: ${error._tag}`);}assert.equal(error.repoId, "missing");- assert.deepStrictEqual(error.expectedRepoIds, ["effect-smol", "alchemy-effect"]);+ assert.deepStrictEqual(error.expectedRepoIds, ["effect-smol"]);assert.ok(!("cause" in error));}),);diff --git a/t3.json b/t3.jsonindex 007e8f961..f7e4221a8 100644--- a/t3.json+++ b/t3.json@@ -4,7 +4,7 @@"scripts": [{"name": "Setup Worktree",- "command": "vp i && ln -sf $T3CODE_PROJECT_ROOT/.env .env && ln -sf $T3CODE_PROJECT_ROOT/infra/relay/.env infra/relay/.env && node apps/web/scripts/warm-dep-cache.ts",+ "command": "vp i && ln -sf $T3CODE_PROJECT_ROOT/.env .env && node apps/web/scripts/warm-dep-cache.ts","icon": "configure","runOnWorktreeCreate": true}