Skip to content
TypeScript

feat: managed policy for organization-wide T3 Code configuration (#27197)

Julius Marminged897d3f3f00f
diff --git a/apps/desktop/src/app/DesktopManagedPolicy.ts b/apps/desktop/src/app/DesktopManagedPolicy.ts
new file mode 100644
index 00000000000..6dc9e8c21b2
--- /dev/null
+++ b/apps/desktop/src/app/DesktopManagedPolicy.ts
@@ -0,0 +1,65 @@
+/**
+ * DesktopManagedPolicy - the administrator's managed policy as the desktop app reads it, at most
+ * once: every desktop check needs the same answer.
+ *
+ * @module DesktopManagedPolicy
+ */
+import type { ManagedPolicyDocument } from "@t3tools/contracts";
+import {
+ layerWindowsRegistry,
+ ManagedPolicyFileError,
+ readManagedPolicy,
+ WindowsRegistry,
+} from "@t3tools/shared/managedPolicyFile";
+import * as Context from "effect/Context";
+import * as Effect from "effect/Effect";
+import * as FileSystem from "effect/FileSystem";
+import * as Layer from "effect/Layer";
+import * as Schema from "effect/Schema";
+import { ChildProcessSpawner } from "effect/process";
+
+import * as DesktopEnvironment from "./DesktopEnvironment.ts";
+
+type FoundPolicy = Effect.Success<ReturnType<typeof readManagedPolicy>>;
+const isManagedPolicyFileError = Schema.is(ManagedPolicyFileError);
+
+export class DesktopManagedPolicy extends Context.Service<
+ DesktopManagedPolicy,
+ {
+ /** The policy on this machine, undefined without one; fails when it cannot be used. */
+ readonly read: Effect.Effect<FoundPolicy, ManagedPolicyFileError>;
+ }
+>()("@t3tools/desktop/app/DesktopManagedPolicy") {}
+
+export const layer = Layer.effect(
+ DesktopManagedPolicy,
+ Effect.gen(function* () {
+ const { platform } = yield* DesktopEnvironment.DesktopEnvironment;
+ const read = yield* Effect.cached(
+ readManagedPolicy(platform).pipe(
+ Effect.provideService(FileSystem.FileSystem, yield* FileSystem.FileSystem),
+ Effect.provideService(
+ ChildProcessSpawner.ChildProcessSpawner,
+ yield* ChildProcessSpawner.ChildProcessSpawner,
+ ),
+ Effect.provideService(WindowsRegistry, yield* WindowsRegistry),
+ ),
+ );
+ return DesktopManagedPolicy.of({ read });
+ }),
+).pipe(Layer.provide(layerWindowsRegistry(() => import("ffi-rs"))));
+
+/** A machine with `policy` deployed, one whose policy cannot be used, or none. */
+export const layerTest = (policy?: ManagedPolicyDocument | ManagedPolicyFileError) =>
+ Layer.succeed(
+ DesktopManagedPolicy,
+ DesktopManagedPolicy.of({
+ read:
+ policy === undefined
+ ? // @effect-diagnostics-next-line effectSucceedWithVoid:off - No policy is undefined, not void.
+ Effect.succeed(undefined)
+ : isManagedPolicyFileError(policy)
+ ? Effect.fail(policy)
+ : Effect.succeed({ source: "/test/policy.json", document: policy }),
+ }),
+ );
diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts
index 26f6dbe0268..b973f8177c9 100644
--- a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts
+++ b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts
@@ -12,6 +12,7 @@ import * as Stream from "effect/Stream";
import { ChildProcessSpawner } from "effect/process";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
+import * as DesktopManagedPolicy from "../app/DesktopManagedPolicy.ts";
import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
import * as DesktopShellEnvironment from "../shell/DesktopShellEnvironment.ts";
import * as DesktopConfig from "../app/DesktopConfig.ts";
@@ -972,6 +973,7 @@ describe("DesktopBackendConfiguration", () => {
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(DesktopWslServerTree.layerTest()),
Layer.provideMerge(DesktopWslEnvironment.layer),
+ Layer.provideMerge(DesktopManagedPolicy.layerTest()),
Layer.provideMerge(
Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
diff --git a/apps/desktop/src/backend/DesktopServerExposure.test.ts b/apps/desktop/src/backend/DesktopServerExposure.test.ts
index 67ac6a51e65..23732860e05 100644
--- a/apps/desktop/src/backend/DesktopServerExposure.test.ts
+++ b/apps/desktop/src/backend/DesktopServerExposure.test.ts
@@ -7,12 +7,14 @@ import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
+import * as Option from "effect/Option";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopConfig from "../app/DesktopConfig.ts";
+import * as DesktopManagedPolicy from "../app/DesktopManagedPolicy.ts";
import * as DesktopNetworkInterfaces from "./DesktopNetworkInterfaces.ts";
import * as DesktopServerExposure from "./DesktopServerExposure.ts";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
@@ -90,6 +92,7 @@ function layer(input: {
readonly env?: Record<string, string | undefined>;
readonly spawnerLayer?: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>;
readonly desktopSettingsLayer?: Layer.Layer<DesktopAppSettings.DesktopAppSettings>;
+ readonly managedPolicyLayer?: Layer.Layer<DesktopManagedPolicy.DesktopManagedPolicy>;
}) {
const env = { T3CODE_HOME: input.baseDir, ...input.env };
const layerEnvironment = layerEnvironmentFor(input.baseDir, env);
@@ -99,6 +102,7 @@ function layer(input: {
return DesktopServerExposure.layer.pipe(
Layer.provideMerge(input.desktopSettingsLayer ?? DesktopAppSettings.layer),
+ Layer.provideMerge(input.managedPolicyLayer ?? DesktopManagedPolicy.layerTest()),
Layer.provideMerge(NodeFileSystem.layer),
Layer.provideMerge(NodeHttpClient.layerUndici),
Layer.provideMerge(input.spawnerLayer ?? layerMockSpawner()),
@@ -122,6 +126,7 @@ const withHarness = <A, E, R>(
env: Record<string, string | undefined> = {},
spawnerLayer?: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>,
desktopSettingsLayer?: Layer.Layer<DesktopAppSettings.DesktopAppSettings>,
+ managedPolicyLayer?: Layer.Layer<DesktopManagedPolicy.DesktopManagedPolicy>,
) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
@@ -136,6 +141,7 @@ const withHarness = <A, E, R>(
env,
...(spawnerLayer ? { spawnerLayer } : {}),
...(desktopSettingsLayer ? { desktopSettingsLayer } : {}),
+ ...(managedPolicyLayer ? { managedPolicyLayer } : {}),
}),
),
);
@@ -191,6 +197,41 @@ describe("DesktopServerExposure", () => {
),
);
+ it.effect("starts local-only, Serve off, when a managed policy keeps clients local", () =>
+ withHarness(
+ lanNetworkInterfaces,
+ Effect.gen(function* () {
+ const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
+ const settings = yield* DesktopAppSettings.DesktopAppSettings;
+ yield* settings.setServerExposureMode("network-accessible");
+ yield* settings.setTailscaleServe({ enabled: true, port: Option.none() });
+
+ const state = yield* serverExposure.configureFromSettings({ port: 4173 });
+ assert.equal(state.mode, "local-only");
+ const backendConfig = yield* serverExposure.backendConfig;
+ assert.equal(backendConfig.bindHost, "127.0.0.1");
+ assert.isFalse(backendConfig.tailscaleServeEnabled);
+ // Choosing them again while the policy applies does not widen the backend either.
+ yield* serverExposure.setMode("network-accessible");
+ yield* serverExposure.setTailscaleServeEnabled({ enabled: true });
+ assert.equal((yield* serverExposure.backendConfig).bindHost, "127.0.0.1");
+ assert.isFalse((yield* serverExposure.backendConfig).tailscaleServeEnabled);
+ // The saved choice returns once the policy allows it.
+ const saved = yield* settings.get;
+ assert.equal(saved.serverExposureMode, "network-accessible");
+ assert.isTrue(saved.tailscaleServeEnabled);
+ }),
+ {},
+ undefined,
+ undefined,
+ DesktopManagedPolicy.layerTest({
+ schemaVersion: 1,
+ organization: "Example Corp",
+ limits: { clients: ["desktop"] },
+ }),
+ ),
+ );
+
it.effect("persists network-accessible mode and updates backend binding state", () =>
withHarness(
lanNetworkInterfaces,
diff --git a/apps/desktop/src/backend/DesktopServerExposure.ts b/apps/desktop/src/backend/DesktopServerExposure.ts
index 288d969d662..76c2392c0bd 100644
--- a/apps/desktop/src/backend/DesktopServerExposure.ts
+++ b/apps/desktop/src/backend/DesktopServerExposure.ts
@@ -22,6 +22,7 @@ import * as Semaphore from "effect/Semaphore";
import * as HttpClient from "effect/http/HttpClient";
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
+import * as DesktopManagedPolicy from "../app/DesktopManagedPolicy.ts";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
import * as DesktopConfig from "../app/DesktopConfig.ts";
import * as DesktopNetworkInterfaces from "./DesktopNetworkInterfaces.ts";
@@ -482,6 +483,18 @@ export const make = Effect.gen(function* () {
const readNetworkInterfaces = networkInterfaces.read;
+ // The server refuses to bind wider than the policy's clients allow, so network access or Serve
+ // saved before the policy would keep the backend from starting. The backend runs without them;
+ // the saved choice stays for when the policy allows it.
+ const remoteAllowed = yield* (yield* DesktopManagedPolicy.DesktopManagedPolicy).read.pipe(
+ Effect.map((found) => found?.document.limits?.clients?.includes("remote") ?? true),
+ Effect.orElseSucceed(() => false),
+ );
+ const withinPolicy = (settings: DesktopAppSettings.DesktopSettings) =>
+ remoteAllowed
+ ? settings
+ : { ...settings, serverExposureMode: "local-only" as const, tailscaleServeEnabled: false };
+
const readCurrentState = (currentNetworkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces) =>
Ref.get(stateRef).pipe(
Effect.map((state) =>
@@ -501,8 +514,8 @@ export const make = Effect.gen(function* () {
const settings = yield* desktopSettings.get;
const currentNetworkInterfaces = yield* readNetworkInterfaces;
const resolved = resolveRuntimeState({
- requestedMode: settings.serverExposureMode,
- settings,
+ requestedMode: withinPolicy(settings).serverExposureMode,
+ settings: withinPolicy(settings),
port,
networkInterfaces: currentNetworkInterfaces,
advertisedHostOverride: config.desktopLanHostOverride,
@@ -524,8 +537,8 @@ export const make = Effect.gen(function* () {
};
const currentNetworkInterfaces = yield* readNetworkInterfaces;
const resolved = resolveRuntimeState({
- requestedMode: mode,
- settings: nextSettings,
+ requestedMode: withinPolicy(nextSettings).serverExposureMode,
+ settings: withinPolicy(nextSettings),
port: previous.port,
networkInterfaces: currentNetworkInterfaces,
advertisedHostOverride: config.desktopLanHostOverride,
@@ -576,7 +589,7 @@ export const make = Effect.gen(function* () {
const nextState = yield* Ref.updateAndGet(stateRef, (current) => ({
...current,
- tailscaleServeEnabled: result.settings.tailscaleServeEnabled,
+ tailscaleServeEnabled: withinPolicy(result.settings).tailscaleServeEnabled,
tailscaleServePort: result.settings.tailscaleServePort,
}));
diff --git a/apps/desktop/src/ipc/DesktopIpcHandlers.ts b/apps/desktop/src/ipc/DesktopIpcHandlers.ts
index 35333ac3d33..dc9c47e0427 100644
--- a/apps/desktop/src/ipc/DesktopIpcHandlers.ts
+++ b/apps/desktop/src/ipc/DesktopIpcHandlers.ts
@@ -36,7 +36,7 @@ import {
getAppBranding,
getLocalEnvironmentBootstraps,
getLocalEnvironmentBearerToken,
- getRelayTelemetryEnabled,
+ installRelayTelemetryEnabled,
getSystemLocale,
getWindowFullscreenState,
openExternal,
@@ -91,7 +91,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
yield* ipc.handleSync(takeLegacyLocalStorage);
yield* ipc.handle(completeLegacyLocalStorage);
yield* ipc.handleSync(getAppBranding);
- yield* ipc.handleSync(getRelayTelemetryEnabled);
+ yield* installRelayTelemetryEnabled();
yield* ipc.handleSync(getSystemLocale);
yield* ipc.handleSync(getWindowFullscreenState);
yield* ipc.handleSync(getLocalEnvironmentBootstraps);
diff --git a/apps/desktop/src/ipc/methods/window.test.ts b/apps/desktop/src/ipc/methods/window.test.ts
index ed821165b40..eacc92c9499 100644
--- a/apps/desktop/src/ipc/methods/window.test.ts
+++ b/apps/desktop/src/ipc/methods/window.test.ts
@@ -1,6 +1,8 @@
import { assert, describe, it } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
+import type { ManagedPolicyLimits } from "@t3tools/contracts";
import * as HostProcess from "@t3tools/shared/HostProcess";
+import { ManagedPolicyFileError } from "@t3tools/shared/managedPolicyFile";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as Effect from "effect/Effect";
@@ -21,11 +23,14 @@ import * as DesktopBackendConfiguration from "../../backend/DesktopBackendConfig
import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts";
import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts";
import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts";
+import * as DesktopManagedPolicy from "../../app/DesktopManagedPolicy.ts";
import * as ElectronDialog from "../../electron/ElectronDialog.ts";
import * as ElectronWindow from "../../electron/ElectronWindow.ts";
+import * as IpcChannels from "../channels.ts";
+import * as DesktopIpc from "../DesktopIpc.ts";
import {
getLocalEnvironmentBootstraps,
- getRelayTelemetryEnabled,
+ installRelayTelemetryEnabled,
pickProjectFavicon,
probeRemoteEditors,
} from "./window.ts";
@@ -177,21 +182,54 @@ describe("getLocalEnvironmentBootstraps", () => {
});
});
-describe("getRelayTelemetryEnabled", () => {
+describe("installRelayTelemetryEnabled", () => {
+ // The renderer reads this over sync IPC, so the answer must not wait on the filesystem.
+ const relayTelemetryEnabled = (
+ env: NodeJS.ProcessEnv,
+ policy?: Parameters<typeof DesktopManagedPolicy.layerTest>[0],
+ ) =>
+ Effect.gen(function* () {
+ const listeners = new Map<string, DesktopIpc.DesktopIpcSyncListener>();
+ const ipcMain: DesktopIpc.DesktopIpcMain = {
+ removeHandler: () => undefined,
+ handle: () => undefined,
+ removeAllListeners: (channel) => void listeners.delete(channel),
+ on: (channel, listener) => void listeners.set(channel, listener),
+ };
+ yield* installRelayTelemetryEnabled().pipe(
+ Effect.provideService(HostProcess.Environment, env),
+ Effect.provide(
+ Layer.mergeAll(DesktopIpc.layer(ipcMain), DesktopManagedPolicy.layerTest(policy)),
+ ),
+ );
+ const event = { returnValue: undefined as unknown };
+ listeners.get(IpcChannels.GET_RELAY_TELEMETRY_ENABLED_CHANNEL)?.(event as never);
+ return event.returnValue;
+ }).pipe(Effect.scoped);
+
it.effect("reads the desktop host opt-out before returning the renderer policy", () =>
Effect.gen(function* () {
+ assert.isFalse(yield* relayTelemetryEnabled({ T3CODE_TELEMETRY_ENABLED: "false" }));
+ assert.isTrue(yield* relayTelemetryEnabled({}));
+ }),
+ );
+
+ it.effect("turns relay tracing off when the managed policy turns telemetry off", () =>
+ Effect.gen(function* () {
+ const policy = (limits: ManagedPolicyLimits) => ({
+ schemaVersion: 1 as const,
+ organization: "Example Corp",
+ limits,
+ });
+ assert.isFalse(yield* relayTelemetryEnabled({}, policy({ telemetry: false })));
+ assert.isTrue(yield* relayTelemetryEnabled({}, policy({ webhookTasks: false })));
+ // A policy that cannot be read fails closed.
assert.isFalse(
- yield* getRelayTelemetryEnabled.handler().pipe(
- Effect.provideService(HostProcess.Environment, {
- T3CODE_TELEMETRY_ENABLED: "false",
- }),
+ yield* relayTelemetryEnabled(
+ {},
+ new ManagedPolicyFileError({ path: "/test", reason: "bad JSON" }),
),
);
- assert.isTrue(
- yield* getRelayTelemetryEnabled
- .handler()
- .pipe(Effect.provideService(HostProcess.Environment, {})),
- );
}),
);
});
diff --git a/apps/desktop/src/ipc/methods/window.ts b/apps/desktop/src/ipc/methods/window.ts
index f0d661b58bc..473d1874078 100644
--- a/apps/desktop/src/ipc/methods/window.ts
+++ b/apps/desktop/src/ipc/methods/window.ts
@@ -27,6 +27,7 @@ import * as DesktopBackendConfiguration from "../../backend/DesktopBackendConfig
import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts";
import * as DesktopLocalEnvironmentAuth from "../../backend/DesktopLocalEnvironmentAuth.ts";
import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts";
+import * as DesktopManagedPolicy from "../../app/DesktopManagedPolicy.ts";
import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts";
import * as DesktopWslBackend from "../../wsl/DesktopWslBackend.ts";
import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts";
@@ -72,13 +73,28 @@ export const getAppBranding = DesktopIpc.makeSyncIpcMethod({
}),
});
-export const getRelayTelemetryEnabled = DesktopIpc.makeSyncIpcMethod({
- channel: IpcChannels.GET_RELAY_TELEMETRY_ENABLED_CHANNEL,
- result: Schema.Boolean,
- handler: Effect.fn("desktop.ipc.window.getRelayTelemetryEnabled")(function* () {
- return isRelayTracingEnabled(yield* HostProcess.Environment);
- }),
-});
+/**
+ * Relay traces leave the machine, so a policy with `telemetry: false`, or one that cannot be read,
+ * stops them. Read once here: a sync IPC handler cannot wait on the filesystem.
+ */
+export const installRelayTelemetryEnabled = Effect.fn("desktop.ipc.window.installRelayTelemetry")(
+ function* () {
+ const ipc = yield* DesktopIpc.DesktopIpc;
+ const enabled =
+ isRelayTracingEnabled(yield* HostProcess.Environment) &&
+ (yield* (yield* DesktopManagedPolicy.DesktopManagedPolicy).read.pipe(
+ Effect.map((found) => found?.document.limits?.telemetry !== false),
+ Effect.orElseSucceed(() => false),
+ ));
+ yield* ipc.handleSync(
+ DesktopIpc.makeSyncIpcMethod({
+ channel: IpcChannels.GET_RELAY_TELEMETRY_ENABLED_CHANNEL,
+ result: Schema.Boolean,
+ handler: () => Effect.succeed(enabled),
+ }),
+ );
+ },
+);
export const getSystemLocale = DesktopIpc.makeSyncIpcMethod({
channel: IpcChannels.GET_SYSTEM_LOCALE_CHANNEL,
diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts
index 2890f164f6f..2fcb8d968c5 100644
--- a/apps/desktop/src/main.ts
+++ b/apps/desktop/src/main.ts
@@ -47,6 +47,7 @@ import * as DesktopBackendPool from "./backend/DesktopBackendPool.ts";
import * as DesktopLocalEnvironmentAuth from "./backend/DesktopLocalEnvironmentAuth.ts";
import * as DesktopNetworkInterfaces from "./backend/DesktopNetworkInterfaces.ts";
import * as DesktopEnvironment from "./app/DesktopEnvironment.ts";
+import * as DesktopManagedPolicy from "./app/DesktopManagedPolicy.ts";
import * as DesktopLifecycle from "./app/DesktopLifecycle.ts";
import * as DesktopLinuxUrlHandler from "./app/DesktopLinuxUrlHandler.ts";
import * as DesktopShutdown from "./app/DesktopShutdown.ts";
@@ -65,6 +66,7 @@ import * as DesktopState from "./app/DesktopState.ts";
import * as DesktopLegacyLocalStorage from "./app/DesktopLegacyLocalStorage.ts";
import * as DesktopTelemetryPublisher from "./telemetry/DesktopTelemetryPublisher.ts";
import * as DesktopRendererHistory from "./telemetry/DesktopRendererHistory.ts";
+import * as DesktopUpdatePolicy from "./updates/DesktopUpdatePolicy.ts";
import * as DesktopUpdates from "./updates/DesktopUpdates.ts";
import * as BrowserImport from "./preview/BrowserImport/BrowserImport.ts";
import * as LinuxBrowserSecret from "./preview/BrowserImport/LinuxBrowserSecret.ts";
@@ -141,6 +143,7 @@ const layerElectron = Layer.mergeAll(
const layerDesktopFoundation = Layer.mergeAll(
MacPermissions.layer,
+ DesktopManagedPolicy.layer,
DesktopState.layer,
DesktopShutdown.layer,
DesktopLegacyLocalStorage.layer,
@@ -211,7 +214,13 @@ const layerDesktopApplication = Layer.mergeAll(
layerDesktopSsh,
).pipe(
Layer.provideMerge(layerDesktopSnapShot),
- Layer.provideMerge(DesktopUpdates.layer),
+ Layer.provideMerge(
+ DesktopUpdates.layer.pipe(
+ Layer.provide(DesktopUpdatePolicy.layer),
+ // The same layer as the foundation's, so the policy is still read once.
+ Layer.provide(DesktopManagedPolicy.layer),
+ ),
+ ),
Layer.provideMerge(layerDesktopWslBackend),
Layer.provideMerge(layerDesktopLocalEnvironmentAuth),
);
diff --git a/apps/desktop/src/preview/BrowserImport/BrowserImport.test.ts b/apps/desktop/src/preview/BrowserImport/BrowserImport.test.ts
index c691ac15174..9528cd5d2e8 100644
--- a/apps/desktop/src/preview/BrowserImport/BrowserImport.test.ts
+++ b/apps/desktop/src/preview/BrowserImport/BrowserImport.test.ts
@@ -6,6 +6,8 @@ import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as BrowserSession from "../BrowserSession.ts";
+import { readManagedPolicyFile } from "@t3tools/shared/managedPolicyFile";
+import * as DesktopManagedPolicy from "../../app/DesktopManagedPolicy.ts";
import * as BrowserImport from "./BrowserImport.ts";
import { BROWSER_IMPORT_SOURCES, sourcePathContext } from "./Sources.ts";
import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
@@ -52,6 +54,7 @@ const withImporter = Effect.fnUntraced(function* () {
Effect.provide(
BrowserImport.layer.pipe(
Layer.provide(layerRejectedBeforeSession),
+ Layer.provide(DesktopManagedPolicy.layerTest()),
Layer.provide(layerEnvironment),
Layer.provide(Layer.succeed(HostProcess.Platform, "darwin")),
Layer.provide(Layer.succeed(HostProcess.ExecutablePath, "/Applications/T3 Code.app")),
@@ -108,11 +111,46 @@ describe("BrowserImport.importCookies", () => {
})
.pipe(Effect.flip);
+ assert.instanceOf(error, BrowserImport.BrowserImportFailedError);
assert.equal(error.reason, "browserRunning");
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
);
});
+describe("BrowserImport.checkBrowserImportPolicy", () => {
+ it.effect("allows imports unless a readable policy turns them off, and fails closed", () =>
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const dir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-import-policy-" });
+ const outcome = (contents: string | undefined) =>
+ Effect.gen(function* () {
+ const policyPath = `${dir}/policy.json`;
+ yield* fileSystem.remove(policyPath, { force: true });
+ if (contents !== undefined) yield* fileSystem.writeFileString(policyPath, contents);
+ const readPolicy = readManagedPolicyFile(policyPath).pipe(
+ Effect.map((document) => document && { source: policyPath, document }),
+ );
+ return yield* BrowserImport.checkBrowserImportPolicy(readPolicy).pipe(
+ Effect.match({ onFailure: (error) => error.message, onSuccess: () => "allowed" }),
+ );
+ });
+ const policy = (limits?: object) =>
+ JSON.stringify({ schemaVersion: 1, organization: "Example Corp", limits });
+
+ assert.equal(yield* outcome(undefined), "allowed");
+ assert.equal(yield* outcome(policy()), "allowed");
+ assert.equal(yield* outcome(policy({ browserCookieImport: true })), "allowed");
+ assert.equal(
+ yield* outcome(policy({ browserCookieImport: false })),
+ "Example Corp's policy does not allow importing browser cookies.",
+ );
+ for (const unreadable of ["{ not json", policy({ notALimit: false })]) {
+ assert.include(yield* outcome(unreadable), "could not be read");
+ }
+ }).pipe(Effect.provide(NodeServices.layer)),
+ );
+});
+
describe("BrowserImport.writeCookies", () => {
it.effect("flushes the store after writing, and reports success if the flush fails", () =>
Effect.gen(function* () {
diff --git a/apps/desktop/src/preview/BrowserImport/BrowserImport.ts b/apps/desktop/src/preview/BrowserImport/BrowserImport.ts
index c567b27411c..0bf95cd641c 100644
--- a/apps/desktop/src/preview/BrowserImport/BrowserImport.ts
+++ b/apps/desktop/src/preview/BrowserImport/BrowserImport.ts
@@ -4,7 +4,11 @@ import type {
BrowserImportSource,
BrowserImportUnavailableReason,
} from "@t3tools/contracts";
-import { BrowserImportFailureReason } from "@t3tools/contracts";
+import {
+ BrowserImportFailureReason,
+ type ManagedPolicyDocument,
+ managedPolicyDeniedMessage,
+} from "@t3tools/contracts";
import * as Context from "effect/Context";
import type { Session } from "electron";
import * as Effect from "effect/Effect";
@@ -16,7 +20,9 @@ import * as Scope from "effect/Scope";
import { ChildProcessSpawner } from "effect/process";
import * as HostProcess from "@t3tools/shared/HostProcess";
+import type { ManagedPolicyFileError } from "@t3tools/shared/managedPolicyFile";
+import * as DesktopManagedPolicy from "../../app/DesktopManagedPolicy.ts";
import * as BrowserSession from "../BrowserSession.ts";
import { ChromiumCookieReadError, readChromiumCookies } from "./ChromiumCookies.ts";
import type { CookieReadResult } from "./CookieDatabase.ts";
@@ -47,6 +53,45 @@ export class BrowserImportFailedError extends Schema.TaggedError<BrowserImportFa
}
}
+/** An administrator's policy forbids the import, or the policy file could not be checked. */
+export class BrowserImportPolicyError extends Schema.TaggedError<BrowserImportPolicyError>()(
+ "BrowserImportPolicyError",
+ {
+ policyPath: Schema.String,
+ /** Absent when the policy could not be read or decoded. */
+ organization: Schema.optional(Schema.String),
+ cause: Schema.optional(Schema.Defect()),
+ },
+) {
+ override get message(): string {
+ return this.organization === undefined
+ ? `The managed policy at ${this.policyPath} could not be read, so importing browser cookies is not allowed.`
+ : managedPolicyDeniedMessage(this.organization, "importing browser cookies");
+ }
+}
+
+/**
+ * A policy that cannot be read or decoded denies the import: cookies are credentials, and the
+ * server refuses to start on the same policy anyway.
+ */
+export const checkBrowserImportPolicy = Effect.fn("BrowserImport.checkPolicy")(function* <R>(
+ readPolicy: Effect.Effect<
+ { readonly source: string; readonly document: ManagedPolicyDocument } | undefined,
+ ManagedPolicyFileError,
+ R
+ >,
+) {
+ const policy = yield* readPolicy.pipe(
+ Effect.mapError((cause) => new BrowserImportPolicyError({ policyPath: cause.path, cause })),
+ );
+ if (policy?.document.limits?.browserCookieImport === false) {
+ return yield* new BrowserImportPolicyError({
+ policyPath: policy.source,
+ organization: policy.document.organization,
+ });
+ }
+});
+
export class BrowserCookieWriteError extends Schema.TaggedError<BrowserCookieWriteError>()(
"BrowserCookieWriteError",
{
@@ -69,7 +114,7 @@ export class BrowserImport extends Context.Service<
readonly scope: string;
readonly persistent: boolean;
readonly namespace?: BrowserSession.BrowserSessionPartitionNamespace;
- }) => Effect.Effect<BrowserImportResult, BrowserImportFailedError>;
+ }) => Effect.Effect<BrowserImportResult, BrowserImportFailedError | BrowserImportPolicyError>;
}
>()("@t3tools/desktop/preview/BrowserImport/BrowserImport") {}
@@ -150,6 +195,7 @@ export const writeCookies = Effect.fn("BrowserImport.writeCookies")(function* (
/** @public */
export const make = Effect.gen(function* BrowserImportMake() {
const browserSession = yield* BrowserSession.BrowserSession;
+ const managedPolicy = yield* DesktopManagedPolicy.DesktopManagedPolicy;
const platform = yield* HostProcess.Platform;
const executablePath = yield* HostProcess.ExecutablePath;
const platformServices = yield* Effect.context<
@@ -177,6 +223,7 @@ export const make = Effect.gen(function* BrowserImportMake() {
readonly persistent: boolean;
readonly namespace?: BrowserSession.BrowserSessionPartitionNamespace;
}) {
+ yield* checkBrowserImportPolicy(managedPolicy.read);
const definition = BROWSER_IMPORT_SOURCES.find(
(candidate) => candidate.id === input.input.sourceId,
);
diff --git a/apps/desktop/src/updates/DesktopUpdatePolicy.ts b/apps/desktop/src/updates/DesktopUpdatePolicy.ts
new file mode 100644
index 00000000000..757db8316c6
--- /dev/null
+++ b/apps/desktop/src/updates/DesktopUpdatePolicy.ts
@@ -0,0 +1,89 @@
+/**
+ * DesktopUpdatePolicy - what the administrator's managed policy allows the desktop updater to do.
+ * The desktop reads the policy file itself, before any backend runs, and fails closed: a policy it
+ * cannot read turns updates off.
+ *
+ * @module DesktopUpdatePolicy
+ */
+import {
+ managedUpdatesMessage,
+ type ManagedPolicyDocument,
+ type ManagedUpdatesMode,
+} from "@t3tools/contracts";
+import * as Context from "effect/Context";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+
+import * as DesktopManagedPolicy from "../app/DesktopManagedPolicy.ts";
+import * as DesktopObservability from "../app/DesktopObservability.ts";
+
+export interface UpdatePolicy {
+ readonly mode: ManagedUpdatesMode;
+ readonly feedUrl: string | undefined;
+ readonly allowNightly: boolean;
+ /** Why the updater is restricted, shown in place of update actions; `null` when unmanaged. */
+ readonly message: string | null;
+}
+
+export class DesktopUpdatePolicy extends Context.Service<DesktopUpdatePolicy, UpdatePolicy>()(
+ "@t3tools/desktop/updates/DesktopUpdatePolicy",
+) {}
+
+export const unmanagedUpdatePolicy: UpdatePolicy = {
+ mode: "auto",
+ feedUrl: undefined,
+ allowNightly: true,
+ message: null,
+};
+
+function resolveUpdatePolicy(document: ManagedPolicyDocument | undefined): UpdatePolicy {
+ const updates = document?.limits?.updates;
+ if (document === undefined || updates === undefined) return unmanagedUpdatePolicy;
+ return {
+ mode: updates.mode,
+ feedUrl: updates.feedUrl,
+ allowNightly: updates.allowNightly ?? true,
+ message: managedUpdatesMessage(document.organization),
+ };
+}
+
+const { logInfo, logError } = DesktopObservability.makeComponentLogger("desktop-update-policy");
+
+const make = Effect.gen(function* () {
+ return yield* (yield* DesktopManagedPolicy.DesktopManagedPolicy).read.pipe(
+ Effect.map((found) => ({
+ source: found?.source,
+ policy: resolveUpdatePolicy(found?.document),
+ })),
+ Effect.tap(({ source, policy }) =>
+ policy.message === null
+ ? Effect.void
+ : logInfo("managed policy restricts updates", {
+ source,
+ mode: policy.mode,
+ customFeed: policy.feedUrl !== undefined,
+ allowNightly: policy.allowNightly,
+ }),
+ ),
+ Effect.map(({ policy }) => policy),
+ Effect.catchTags({
+ ManagedPolicyFileError: (error) =>
+ logError("updates are off because the managed policy cannot be used", {
+ path: error.path,
+ reason: error.reason,
+ }).pipe(
+ Effect.as<UpdatePolicy>({
+ mode: "off",
+ feedUrl: undefined,
+ allowNightly: false,
+ message: `Updates are off because T3 Code cannot use the managed policy at ${error.path}. Contact your administrator.`,
+ }),
+ ),
+ }),
+ );
+});
+
+export const layer = Layer.effect(DesktopUpdatePolicy, make);
+
+export const layerTest = (policy: UpdatePolicy = unmanagedUpdatePolicy) =>
+ Layer.succeed(DesktopUpdatePolicy, policy);
diff --git a/apps/desktop/src/updates/DesktopUpdates.test.ts b/apps/desktop/src/updates/DesktopUpdates.test.ts
index c6bcd46b8c2..3b45d80bbc6 100644
--- a/apps/desktop/src/updates/DesktopUpdates.test.ts
+++ b/apps/desktop/src/updates/DesktopUpdates.test.ts
@@ -18,6 +18,7 @@ import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopState from "../app/DesktopState.ts";
+import * as DesktopUpdatePolicy from "./DesktopUpdatePolicy.ts";
import * as DesktopUpdates from "./DesktopUpdates.ts";
import { flushCallbacks, makeHarness } from "./updatesTestHarness.ts";
@@ -963,3 +964,115 @@ describe("describeUpdateErrorCause", () => {
assert.equal(DesktopUpdates.describeUpdateErrorCause(unreadable), "UnknownError");
});
});
+
+describe("DesktopUpdates under a managed policy", () => {
+ const message = "Example Corp manages T3 Code updates.";
+ const managed = (
+ policy: Partial<DesktopUpdatePolicy.UpdatePolicy>,
+ ): DesktopUpdatePolicy.UpdatePolicy => ({
+ ...DesktopUpdatePolicy.unmanagedUpdatePolicy,
+ message,
+ ...policy,
+ });
+
+ it.effect("never checks when updates are off", () => {
+ const harness = makeHarness({ policy: managed({ mode: "off" }) });
+
+ return Effect.scoped(
+ Effect.gen(function* () {
+ const updates = yield* DesktopUpdates.DesktopUpdates;
+ yield* updates.configure;
+ yield* TestClock.adjust("10 minutes");
+
+ const state = yield* updates.getState;
+ assert.equal(state.status, "disabled");
+ assert.equal(state.message, message);
+ assert.isFalse((yield* updates.check("menu")).checked);
+ assert.deepEqual(yield* updates.disabledReason, Option.some(message));
+ assert.equal(harness.checkCount(), 0);
+ assert.equal(harness.listenerCount(), 0);
+ }),
+ ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
+ });
+
+ it.effect("updates from the administrator's feed", () => {
+ const harness = makeHarness({
+ // Any user can set the mock flag; it must not redirect a managed feed.
+ env: { T3CODE_DESKTOP_MOCK_UPDATES: "true" },
+ policy: managed({ feedUrl: "https://updates.example.com/t3code" }),
+ });
+
+ return Effect.scoped(
+ Effect.gen(function* () {
+ const updates = yield* DesktopUpdates.DesktopUpdates;
+ yield* updates.configure;
+ assert.equal((yield* updates.getState).status, "idle");
+ assert.deepEqual(harness.feedUrls(), [
+ { provider: "generic", url: "https://updates.example.com/t3code" },
+ ]);
+ }),
+ ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
+ });
+
+ it.effect("refuses the nightly channel without nightly", () => {
+ const harness = makeHarness({ policy: managed({ allowNightly: false }) });
+
+ return Effect.scoped(
+ Effect.gen(function* () {
+ const updates = yield* DesktopUpdates.DesktopUpdates;
+ yield* updates.configure;
+ const error = yield* updates.setChannel("nightly").pipe(Effect.flip);
+ assert.equal(error._tag, "DesktopUpdateChannelManagedError");
+ assert.equal((yield* updates.getState).channel, "latest");
+ }),
+ ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
+ });
+
+ it.effect("does not report the channel as the only block when updates are off anyway", () => {
+ const harness = makeHarness({
+ appVersion: "1.2.3-nightly.20261028.1",
+ env: { T3CODE_DISABLE_AUTO_UPDATE: "true" },
+ policy: managed({ allowNightly: false, feedUrl: "https://updates.example.com/t3code" }),
+ });
+
+ return Effect.scoped(
+ Effect.gen(function* () {
+ const updates = yield* DesktopUpdates.DesktopUpdates;
+ yield* updates.configure;
+ const state = yield* updates.getState;
+ assert.isFalse(state.enabled);
+ assert.isUndefined(state.channelBlockedByPolicy);
+ }),
+ ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
+ });
+
+ it.effect("holds a nightly install until its user switches to stable", () => {
+ const harness = makeHarness({
+ appVersion: "1.2.3-nightly.20261028.1",
+ // A managed app ignores the mock feed, so give it a real one.
+ policy: managed({ allowNightly: false, feedUrl: "https://updates.example.com/t3code" }),
+ });
+
+ return Effect.scoped(
+ Effect.gen(function* () {
+ const updates = yield* DesktopUpdates.DesktopUpdates;
+ yield* updates.configure;
+ yield* TestClock.adjust("10 minutes");
+
+ const held = yield* updates.getState;
+ assert.equal(held.channel, "nightly");
+ assert.equal(held.status, "disabled");
+ assert.include(held.message ?? "", message);
+ assert.isTrue(held.channelBlockedByPolicy);
+ assert.isFalse((yield* updates.check("menu")).checked);
+ assert.equal(harness.checkCount(), 0);
+
+ const stable = yield* updates.setChannel("latest");
+ assert.equal(stable.channel, "latest");
+ assert.isTrue(stable.enabled);
+ assert.isUndefined(stable.channelBlockedByPolicy);
+ assert.equal(harness.checkCount(), 1);
+ }),
+ ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
+ });
+});
diff --git a/apps/desktop/src/updates/DesktopUpdates.ts b/apps/desktop/src/updates/DesktopUpdates.ts
index 3a0b41cd9e3..6279e8b6141 100644
--- a/apps/desktop/src/updates/DesktopUpdates.ts
+++ b/apps/desktop/src/updates/DesktopUpdates.ts
@@ -34,6 +34,7 @@ import * as ElectronUpdater from "../electron/ElectronUpdater.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import * as IpcChannels from "../ipc/channels.ts";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
+import * as DesktopUpdatePolicy from "./DesktopUpdatePolicy.ts";
import { normalizeDesktopUpdateReleaseNotes } from "./releaseNotes.ts";
import { desktopUpdateChannelOf } from "@t3tools/shared/cliRelease";
import { compareSemverVersions } from "@t3tools/shared/semver";
@@ -161,9 +162,22 @@ export class DesktopUpdateUnexpectedActionError extends Schema.TaggedError<Deskt
}
}
+export class DesktopUpdateChannelManagedError extends Schema.TaggedError<DesktopUpdateChannelManagedError>()(
+ "DesktopUpdateChannelManagedError",
+ {
+ channel: DesktopUpdateChannelSchema,
+ policyMessage: Schema.String,
+ },
+) {
+ override get message(): string {
+ return `${this.policyMessage} The ${this.channel} channel is not available.`;
+ }
+}
+
export const DesktopUpdateSetChannelError = Schema.Union([
DesktopUpdateActionInProgressError,
DesktopUpdateChannelPersistenceError,
+ DesktopUpdateChannelManagedError,
]);
export type DesktopUpdateSetChannelError = typeof DesktopUpdateSetChannelError.Type;
@@ -315,6 +329,7 @@ function shouldBroadcastDownloadProgress(
}
function getAutoUpdateDisabledReason(args: {
+ policy: DesktopUpdatePolicy.UpdatePolicy;
isDevelopment: boolean;
isPackaged: boolean;
platform: NodeJS.Platform;
@@ -323,6 +338,9 @@ function getAutoUpdateDisabledReason(args: {
disabledByEnv: boolean;
hasUpdateFeedConfig: boolean;
}): string | null {
+ if (args.policy.mode === "off") {
+ return args.policy.message ?? "Updates are turned off on this machine.";
+ }
if (!args.hasUpdateFeedConfig) {
return "Automatic updates are not available because no update feed is configured.";
}
@@ -352,6 +370,9 @@ export const make = Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
+ const policy = yield* DesktopUpdatePolicy.DesktopUpdatePolicy;
+ // Any user can set the mock flag, so it never replaces an administrator's update source.
+ const mockUpdates = config.mockUpdates && policy.message === null;
const appUpdateYmlConfigRef = yield* Ref.make<Option.Option<AppUpdateYmlConfig>>(Option.none());
const activeUpdateActionRef = yield* Ref.make<Option.Option<UpdateAction>>(Option.none());
@@ -431,13 +452,17 @@ export const make = Effect.gen(function* () {
: false;
const hasUpdateFeedConfig = Ref.get(appUpdateYmlConfigRef).pipe(
- Effect.map((appUpdateYmlConfig) => Option.isSome(appUpdateYmlConfig) || config.mockUpdates),
+ Effect.map(
+ (appUpdateYmlConfig) =>
+ Option.isSome(appUpdateYmlConfig) || mockUpdates || policy.feedUrl !== undefined,
+ ),
);
const resolveDisabledReason = Effect.gen(function* () {
const hasFeedConfig = yield* hasUpdateFeedConfig;
return Option.fromNullishOr(
getAutoUpdateDisabledReason({
+ policy,
isDevelopment: environment.isDevelopment,
isPackaged: environment.isPackaged,
platform: environment.platform,
@@ -449,6 +474,18 @@ export const make = Effect.gen(function* () {
);
});
+ // Without nightly, an install on that channel stays put until its user picks stable: moving it
+ // silently would be a downgrade nobody asked for, and checking nightly would break the policy.
+ const channelBlockedReason = (channel: DesktopUpdateChannel): Option.Option<string> =>
+ channel === "nightly" && !policy.allowNightly
+ ? Option.some(
+ `${policy.message ?? "Nightly updates are turned off on this machine."} Switch to the stable channel to keep getting updates.`,
+ )
+ : Option.none();
+
+ const resolveStateDisabledReason = (channel: DesktopUpdateChannel) =>
+ resolveDisabledReason.pipe(Effect.map(Option.orElse(() => channelBlockedReason(channel))));
+
const activeUpdateAction = Ref.get(activeUpdateActionRef);
const tryStartUpdateAction = (action: UpdateAction): Effect.Effect<boolean> =>
@@ -500,6 +537,8 @@ export const make = Effect.gen(function* () {
if (!(yield* Ref.get(updaterConfiguredRef))) return false;
const state = yield* Ref.get(updateStateRef);
+ // A configured updater is disabled only by a channel the managed policy blocks.
+ if (state.status === "disabled") return false;
if (state.status === "downloading") {
yield* logUpdaterInfo("skipping update check while update is active", {
reason,
@@ -659,6 +698,11 @@ export const make = Effect.gen(function* () {
Ref.get(notAppliedVersionRef).pipe(
Effect.map((notAppliedVersion) => ({
...createBaseUpdateState(channel, disabledReason, environment),
+ // Callers fall back to the channel's reason only when nothing else turns updates off.
+ ...(Option.isSome(disabledReason) &&
+ disabledReason.value === Option.getOrUndefined(channelBlockedReason(channel))
+ ? { channelBlockedByPolicy: true as const }
+ : {}),
...Option.match(notAppliedVersion, {
onNone: () => ({}),
onSome: (version) => ({ notAppliedVersion: version }),
@@ -1064,7 +1108,9 @@ export const make = Effect.gen(function* () {
}),
),
emitState,
- disabledReason: resolveDisabledReason,
+ disabledReason: Ref.get(updateStateRef).pipe(
+ Effect.flatMap((state) => resolveStateDisabledReason(state.channel)),
+ ),
configure: Effect.gen(function* () {
const context = yield* Effect.context<never>();
const runEffect = (effect: Effect.Effect<void>) => {
@@ -1083,16 +1129,27 @@ export const make = Effect.gen(function* () {
});
}
- if (config.mockUpdates) {
+ if (mockUpdates) {
yield* electronUpdater.setFeedURL({
provider: "generic",
url: `http://localhost:${config.mockUpdateServerPort}`,
} as ElectronUpdater.ElectronUpdaterFeedUrl);
+ } else if (policy.feedUrl !== undefined) {
+ // The administrator's mirror replaces the GitHub feed baked into app-update.yml.
+ yield* electronUpdater.setFeedURL({
+ provider: "generic",
+ url: policy.feedUrl,
+ } as ElectronUpdater.ElectronUpdaterFeedUrl);
}
const settings = yield* desktopSettings.get;
const disabledReason = yield* resolveDisabledReason;
- yield* setState(yield* baseUpdateState(settings.updateChannel, disabledReason));
+ yield* setState(
+ yield* baseUpdateState(
+ settings.updateChannel,
+ Option.orElse(disabledReason, () => channelBlockedReason(settings.updateChannel)),
+ ),
+ );
if (Option.isSome(disabledReason)) {
return;
}
@@ -1141,6 +1198,12 @@ export const make = Effect.gen(function* () {
options?: { readonly minimumVersion?: string | undefined },
) {
yield* Effect.annotateCurrentSpan({ channel: nextChannel });
+ if (Option.isSome(channelBlockedReason(nextChannel))) {
+ return yield* new DesktopUpdateChannelManagedError({
+ channel: nextChannel,
+ policyMessage: policy.message ?? "Your administrator manages T3 Code updates.",
+ });
+ }
// A background check holds the updater only briefly, so wait it out instead of refusing.
const activeAction = yield* tryStartChannelChange.pipe(
Effect.repeat({
diff --git a/apps/desktop/src/updates/updatesTestHarness.ts b/apps/desktop/src/updates/updatesTestHarness.ts
index d8d16b7dbfd..ec3b1ce9a1d 100644
--- a/apps/desktop/src/updates/updatesTestHarness.ts
+++ b/apps/desktop/src/updates/updatesTestHarness.ts
@@ -13,6 +13,7 @@ import * as ElectronUpdater from "../electron/ElectronUpdater.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
import * as DesktopState from "../app/DesktopState.ts";
+import * as DesktopUpdatePolicy from "./DesktopUpdatePolicy.ts";
import * as DesktopUpdates from "./DesktopUpdates.ts";
export const flushCallbacks = Effect.yieldNow;
@@ -35,6 +36,7 @@ export interface UpdatesHarnessOptions {
readonly platform?: NodeJS.Platform;
readonly packageType?: string | undefined;
readonly installRecord?: string | undefined;
+ readonly policy?: DesktopUpdatePolicy.UpdatePolicy;
readonly appVersion?: string;
/** Starts from in-memory settings with this track saved, as after a restart. */
readonly savedChannel?: DesktopAppSettings.DesktopSettings["updateChannel"];
@@ -271,6 +273,7 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) {
const layer = DesktopUpdates.layer.pipe(
Layer.provide(layerFileSystem),
+ Layer.provide(DesktopUpdatePolicy.layerTest(options.policy)),
Layer.provideMerge(layerUpdater),
Layer.provideMerge(layerWindow),
Layer.provideMerge(layerBackend),
diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts
index 67549f6b8a5..69962f52e4f 100644
--- a/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts
+++ b/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts
@@ -1,10 +1,18 @@
// @effect-diagnostics nodeBuiltinImport:off - the executed suite runs the generated install script through a real POSIX shell.
-import { describe, it } from "@effect/vitest";
+import { assert, describe, it } from "@effect/vitest";
+import * as Effect from "effect/Effect";
+import * as FileSystem from "effect/FileSystem";
+import * as Layer from "effect/Layer";
+import * as Path from "effect/Path";
import { afterAll, expect } from "vite-plus/test";
import * as NodeChildProcess from "node:child_process";
+import { ManagedPolicyFileError } from "@t3tools/shared/managedPolicyFile";
+
+import * as DesktopManagedPolicy from "../app/DesktopManagedPolicy.ts";
import {
buildWslRuntimeInstallScript,
+ makeIsAvailable,
buildWslRuntimeInvalidateScript,
buildWslRuntimePruneScript,
buildWslRuntimeProbeScript,
@@ -425,3 +433,29 @@ describe("parseResolvedPath", () => {
);
});
});
+
+// Path.layer joins with POSIX separators here, so the test windir is a POSIX path.
+const WSL_EXE = "/windows/System32/wsl.exe";
+
+const isAvailable = (policy?: Parameters<typeof DesktopManagedPolicy.layerTest>[0]) =>
+ makeIsAvailable("win32", "/windows").pipe(
+ Effect.provide(
+ Layer.mergeAll(
+ FileSystem.layerNoop({ exists: (path) => Effect.succeed(path === WSL_EXE) }),
+ Path.layer,
+ DesktopManagedPolicy.layerTest(policy),
+ ),
+ ),
+ );
+
+describe("makeIsAvailable", () => {
+ it.effect("turns WSL off on a machine with a managed policy, even an invalid one", () =>
+ Effect.gen(function* () {
+ assert.isTrue(yield* isAvailable());
+ assert.isFalse(yield* isAvailable({ schemaVersion: 1, organization: "Example Corp" }));
+ assert.isFalse(
+ yield* isAvailable(new ManagedPolicyFileError({ path: "/test", reason: "bad JSON" })),
+ );
+ }),
+ );
+});
diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.ts
index ab52ca07a0d..f65fc11f59a 100644
--- a/apps/desktop/src/wsl/DesktopWslEnvironment.ts
+++ b/apps/desktop/src/wsl/DesktopWslEnvironment.ts
@@ -13,6 +13,7 @@ import { buildRemoteNodeEnvScript } from "@t3tools/ssh/tunnel";
import { satisfiesSemverRange } from "@t3tools/shared/semver";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
+import * as DesktopManagedPolicy from "../app/DesktopManagedPolicy.ts";
import { parseWslDistroList, type WslDistro } from "./wslPathParsing.ts";
const PROCESS_TERMINATE_GRACE = Duration.seconds(1);
@@ -1027,15 +1028,26 @@ const getUserHomeImpl = (
Effect.orElseSucceed(() => Option.none<string>()),
);
-const makeIsAvailable = Effect.fn("DesktopWslEnvironment.makeIsAvailable")(function* (
+export const makeIsAvailable = Effect.fn("DesktopWslEnvironment.makeIsAvailable")(function* (
platform: NodeJS.Platform,
windir: string,
-): Effect.fn.Return<boolean, never, FileSystem.FileSystem | Path.Path> {
+): Effect.fn.Return<
+ boolean,
+ never,
+ FileSystem.FileSystem | Path.Path | DesktopManagedPolicy.DesktopManagedPolicy
+> {
if (platform !== "win32") return false;
const path = yield* Path.Path;
const fileSystem = yield* FileSystem.FileSystem;
const wslExePath = path.join(windir, "System32", "wsl.exe");
- return yield* fileSystem.exists(wslExePath).pipe(Effect.orElseSucceed(() => false));
+ if (!(yield* fileSystem.exists(wslExePath).pipe(Effect.orElseSucceed(() => false)))) {
+ return false;
+ }
+ // A server in WSL reads Linux's policy, never this machine's, so a managed machine runs none.
+ return yield* (yield* DesktopManagedPolicy.DesktopManagedPolicy).read.pipe(
+ Effect.map((found) => found === undefined),
+ Effect.orElseSucceed(() => false),
+ );
});
export interface DesktopWslEnvironmentTestStub {
@@ -1140,6 +1152,10 @@ export const layer = Layer.effect(
const wslAvailable = yield* makeIsAvailable(environment.platform, windir).pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(Path.Path, environment.path),
+ Effect.provideService(
+ DesktopManagedPolicy.DesktopManagedPolicy,
+ yield* DesktopManagedPolicy.DesktopManagedPolicy,
+ ),
Effect.withSpan("desktop.wsl.isAvailable"),
);
const isAvailable = Effect.succeed(wslAvailable);
diff --git a/apps/mobile/src/features/settings/SettingsEnvironmentDetailRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsEnvironmentDetailRouteScreen.tsx
index 5f83979197b..21edb7f9edc 100644
--- a/apps/mobile/src/features/settings/SettingsEnvironmentDetailRouteScreen.tsx
+++ b/apps/mobile/src/features/settings/SettingsEnvironmentDetailRouteScreen.tsx
@@ -4,6 +4,7 @@ import { useNavigation, type StaticScreenProps } from "@react-navigation/native"
import {
AuthProvidersManageScope,
AuthOrchestrationReadScope,
+ managedUpdatesDenial,
type EnvironmentId,
type ServerProvider,
} from "@t3tools/contracts";
@@ -13,7 +14,7 @@ import * as Cause from "effect/Cause";
import * as Exit from "effect/Exit";
import { AsyncResult } from "effect/reactivity";
import { useRef, useState } from "react";
-import { View } from "react-native";
+import { Linking, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AppText as Text } from "../../components/ui/AppText";
@@ -94,6 +95,10 @@ function EnvironmentDetail({ environmentId }: { readonly environmentId: Environm
const version = config?.environment.serverVersion;
const checkedRelease = release?.fromVersion === version ? release : null;
const capabilities = config?.environment.capabilities;
+ const managedPolicy = config?.managedPolicy;
+ const supportUrl = managedPolicy?.supportUrl;
+ // The server refuses checks and installs; say so instead of offering them.
+ const updatesDenial = managedUpdatesDenial(managedPolicy);
async function run(label: string, action: () => Promise<void>) {
if (pendingRef.current) return;
@@ -230,6 +235,14 @@ function EnvironmentDetail({ environmentId }: { readonly environmentId: Environm
<SettingsSection title="T3 Code">
<View className="gap-1 p-4">
<Text className="text-base text-foreground">Version {version}</Text>
+ {managedPolicy ? (
+ <Text className="text-sm text-foreground-muted">
+ Managed by {managedPolicy.organization}
+ </Text>
+ ) : null}
+ {updatesDenial ? (
+ <Text className="text-sm text-foreground-muted">{updatesDenial}</Text>
+ ) : null}
{running ? (
<Text className="text-sm text-foreground-muted">
{updateState.stage === "resuming"
@@ -241,7 +254,7 @@ function EnvironmentDetail({ environmentId }: { readonly environmentId: Environm
{updateState.message}
</Text>
) : null}
- {checkedRelease ? (
+ {checkedRelease && !updatesDenial ? (
<Text className="text-sm text-foreground-muted">
{checkedRelease.targetVersion
? `Version ${checkedRelease.targetVersion} is available.`
@@ -249,6 +262,7 @@ function EnvironmentDetail({ environmentId }: { readonly environmentId: Environm
</Text>
) : null}
{checkedRelease?.targetVersion &&
+ !updatesDenial &&
!supportsEnvironmentUpdate(config.environment.capabilities) ? (
<Text className="text-sm text-foreground-muted">
{capabilities?.serverSelfUpdate === "desktop-managed"
@@ -257,22 +271,32 @@ function EnvironmentDetail({ environmentId }: { readonly environmentId: Environm
</Text>
) : null}
</View>
- <SettingsActionRow
- icon="arrow.clockwise"
- label="Check for updates"
- disabled={disabled}
- loading={pending === "check"}
- onPress={() => {
- if (disabled) return;
- const fromVersion = config.environment.serverVersion;
- void run("check", async () => {
- const exit = await checkRelease(async () => fromVersion);
- // `run` owns the error message, so a failed lookup rethrows to it.
- if (Exit.isFailure(exit)) throw Cause.squash(exit.cause);
- });
- }}
- />
+ {supportUrl ? (
+ <SettingsActionRow
+ icon="questionmark.bubble"
+ label={`Get help from ${managedPolicy.organization}`}
+ onPress={() => void Linking.openURL(supportUrl).catch(() => undefined)}
+ />
+ ) : null}
+ {updatesDenial ? null : (
+ <SettingsActionRow
+ icon="arrow.clockwise"
+ label="Check for updates"
+ disabled={disabled}
+ loading={pending === "check"}
+ onPress={() => {
+ if (disabled) return;
+ const fromVersion = config.environment.serverVersion;
+ void run("check", async () => {
+ const exit = await checkRelease(async () => fromVersion);
+ // `run` owns the error message, so a failed lookup rethrows to it.
+ if (Exit.isFailure(exit)) throw Cause.squash(exit.cause);
+ });
+ }}
+ />
+ )}
{checkedRelease?.targetVersion &&
+ !updatesDenial &&
supportsEnvironmentUpdate(config.environment.capabilities) ? (
<SettingsActionRow
icon="arrow.up.circle"
diff --git a/apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx
index 4aa5cc4c70b..cabe229f9a2 100644
--- a/apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx
+++ b/apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx
@@ -1,6 +1,12 @@
import * as Dialog from "../../components/ui/Dialog";
-import { AuthRelayWriteScope } from "@t3tools/contracts";
+import {
+ AuthRelayWriteScope,
+ managedCapabilityDenial,
+ type EnvironmentId,
+} from "@t3tools/contracts";
import { readEnvironmentScope } from "../../state/session";
+import { appAtomRegistry } from "../../state/atom-registry";
+import { serverEnvironment } from "../../state/server";
import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView";
import { useAuth } from "@clerk/expo";
import { useAtomSet, useAtomValue } from "@effect/atom-react";
@@ -44,6 +50,20 @@ import { SettingsSwitchRow } from "./components/SettingsSwitchRow";
import { SettingsScreen } from "./components/SettingsScreen";
import { resolveAgentAwarenessPlatformPresentation } from "./SettingsRouteScreen.logic";
+/**
+ * A policy that turns Connect off refuses relay links and preferences, which would fail the
+ * whole batch, so those environments are skipped like ones this session cannot configure.
+ */
+function canLinkEnvironmentToConnect(environmentId: EnvironmentId) {
+ const policy = appAtomRegistry.get(
+ serverEnvironment.configValueAtom(environmentId),
+ )?.managedPolicy;
+ return (
+ readEnvironmentScope(environmentId, AuthRelayWriteScope) &&
+ managedCapabilityDenial(policy, "connect") === undefined
+ );
+}
+
type NotificationStatus = "checking" | "enabled" | "disabled" | "unsupported";
type LiveActivityStatus = "checking" | "enabled" | "disabled" | "signed-out" | "linking";
@@ -272,8 +292,7 @@ function ConfiguredSettingsNotificationsRouteScreen() {
const updateResult = await settleAsyncResult(() =>
runtime.runPromiseExit(
setLiveActivityUpdatesEnabled({
- canConfigureEnvironment: (environmentId) =>
- readEnvironmentScope(environmentId, AuthRelayWriteScope),
+ canConfigureEnvironment: canLinkEnvironmentToConnect,
enabled: true,
previousEnabled: liveActivitiesPreferenceEnabled,
clerkToken: tokenResult.value,
@@ -351,8 +370,7 @@ function ConfiguredSettingsNotificationsRouteScreen() {
const updateResult = await settleAsyncResult(() =>
runtime.runPromiseExit(
setLiveActivityUpdatesEnabled({
- canConfigureEnvironment: (environmentId) =>
- readEnvironmentScope(environmentId, AuthRelayWriteScope),
+ canConfigureEnvironment: canLinkEnvironmentToConnect,
enabled: false,
previousEnabled: liveActivitiesPreferenceEnabled,
clerkToken: token,
diff --git a/apps/mobile/src/features/settings/SettingsProviderAccountsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsProviderAccountsRouteScreen.tsx
index 6dfb8745ed9..38ffbaa68f2 100644
--- a/apps/mobile/src/features/settings/SettingsProviderAccountsRouteScreen.tsx
+++ b/apps/mobile/src/features/settings/SettingsProviderAccountsRouteScreen.tsx
@@ -6,6 +6,7 @@ import {
} from "@t3tools/client-runtime/state/runtime";
import {
AuthProvidersManageScope,
+ isManagedDriverAllowed,
type ProviderAuthResponse,
type ServerProvider,
} from "@t3tools/contracts";
@@ -64,7 +65,7 @@ export function SettingsProviderAccountsRouteScreen() {
</View>
) : (
<>
- {(providersByEnvironment.get(environment.environmentId) ?? [])
+ {managedProviders(environment, providersByEnvironment)
.filter(canManageProvider)
.map((provider, index) => (
<ProviderAccount
@@ -74,7 +75,7 @@ export function SettingsProviderAccountsRouteScreen() {
divider={index > 0}
/>
))}
- {!(providersByEnvironment.get(environment.environmentId) ?? []).some(
+ {!managedProviders(environment, providersByEnvironment).some(
canManageProvider,
) ? (
<Text className="p-4 text-foreground-muted">
@@ -92,6 +93,16 @@ export function SettingsProviderAccountsRouteScreen() {
);
}
+/** Providers the environment's managed policy allows; the rest cannot run or sign in. */
+function managedProviders(
+ environment: SettingsTarget,
+ providersByEnvironment: ReadonlyMap<string, ReadonlyArray<ServerProvider>>,
+) {
+ return (providersByEnvironment.get(environment.environmentId) ?? []).filter((provider) =>
+ isManagedDriverAllowed(environment.serverConfig.managedPolicy, provider.driver),
+ );
+}
+
function canManageProvider(provider: ServerProvider) {
return Boolean(
provider.setup?.canAuthenticate || (provider.driver === "acpRegistry" && provider.installed),
diff --git a/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx
index fdf352c2744..5aea04f201f 100644
--- a/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx
+++ b/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx
@@ -2,6 +2,8 @@ import * as Dialog from "../../components/ui/Dialog";
import { useAtomValue } from "@effect/atom-react";
import {
AuthOrchestrationOperateScope,
+ clampManagedRuntimeMode,
+ managedCapabilityDenial,
resolveProjectProviderInstanceEnabled,
} from "@t3tools/contracts";
import { readEnvironmentScope } from "../../state/session";
@@ -690,6 +692,8 @@ function TaskForm({
.sort((left, right) => Number(right.pinnedAt != null) - Number(left.pinnedAt != null));
const config = useEnvironmentServerConfig(environmentId);
const modelOptions = buildModelOptions(config, null, undefined, draft.projectId);
+ // Existing webhook tasks keep the option so they can still switch to a timer.
+ const webhookDenial = managedCapabilityDenial(config?.managedPolicy, "webhookTasks");
const canOperate = useAtomValue(
serverEnvironment.upsertScheduledTask.permissionAtom(environmentId),
);
@@ -800,7 +804,9 @@ function TaskForm({
baseRef: draft.baseRef.trim() || "main",
startFromOrigin: draft.startFromOrigin,
},
- runtimeMode: draft.runtimeMode,
+ // Tasks have no mode picker; a mode above the administrator's ceiling is refused.
+ runtimeMode:
+ clampManagedRuntimeMode(config?.managedPolicy, draft.runtimeMode) ?? draft.runtimeMode,
interactionMode: draft.task?.interactionMode ?? "default",
creationSource: draft.task?.creationSource ?? "mobile",
};
@@ -992,7 +998,9 @@ function TaskForm({
? [{ value: "once" as const, label: "Once" }]
: []),
{ value: "interval", label: "Interval" },
- { value: "webhook", label: "On webhook" },
+ ...(webhookDenial === undefined || draft.schedule.mode === "webhook"
+ ? [{ value: "webhook" as const, label: "On webhook" }]
+ : []),
]}
selected={draft.schedule.mode}
onSelect={(mode) => {
@@ -1093,6 +1101,10 @@ function TaskForm({
}}
/>
</>
+ ) : draft.schedule.mode === "webhook" && webhookDenial !== undefined && draft.enabled ? (
+ <Text className="border-t border-border-subtle px-4 py-3 text-sm text-foreground-muted">
+ {`${webhookDenial} Switch the task to a timer, or turn it off, to save it.`}
+ </Text>
) : draft.schedule.mode === "once" ? (
(["date", "time"] as const).map((field) => {
const runAt = new Date(draft.schedule.runAt);
@@ -1256,7 +1268,14 @@ function TaskForm({
tone="primary"
fullWidth
loading={saving}
- disabled={!canOperate || dictationPending || taskMissing || environmentUnavailable}
+ disabled={
+ !canOperate ||
+ dictationPending ||
+ taskMissing ||
+ environmentUnavailable ||
+ // The server refuses an enabled webhook task under this policy.
+ (draft.enabled && draft.schedule.mode === "webhook" && webhookDenial !== undefined)
+ }
onPress={() => void save()}
label={saving ? "Saving…" : draft.task ? "Save changes" : "Create task"}
/>
@@ -1452,6 +1471,11 @@ function EnvironmentTasks({
? ` · ${formatNextScheduledTaskRun(task.nextRunAt, now)}`
: ""}
</Text>
+ {task.blockedByPolicy ? (
+ <Text className="text-sm text-foreground-muted" numberOfLines={2}>
+ {task.blockedByPolicy}
+ </Text>
+ ) : null}
{task.lastRunError ? (
<Text className="text-sm text-danger-foreground" numberOfLines={2}>
Last run failed: {task.lastRunError}
diff --git a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.test.tsx b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.test.tsx
index 4fa4874da13..698536b9ec1 100644
--- a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.test.tsx
+++ b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.test.tsx
@@ -64,7 +64,10 @@ vi.mock("../../state/environments", () => ({ useEnvironments: () => ({ environme
vi.mock("../../state/use-atom-command", () => ({
useAtomCommand: () => mocks.updateSettings,
}));
-vi.mock("../threads/thread-settings-options", () => ({ RUNTIME_MODE_CHOICES: [] }));
+vi.mock("../threads/thread-settings-options", () => ({
+ RUNTIME_MODE_CHOICES: [],
+ withManagedRuntimeModeLimits: (choices: readonly unknown[]) => choices,
+}));
vi.mock("../../components/ui/ScreenScrollView", () => ({ ScreenScrollView: Children }));
vi.mock("../../components/ui/AppText", () => ({ AppText: Children }));
vi.mock("../../components/ui/Button", () => ({
diff --git a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx
index 91b0b1b044e..f35c6a29bd8 100644
--- a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx
+++ b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx
@@ -17,7 +17,10 @@ import { useRef, useState } from "react";
import { View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
-import { RUNTIME_MODE_CHOICES } from "../threads/thread-settings-options";
+import {
+ RUNTIME_MODE_CHOICES,
+ withManagedRuntimeModeLimits,
+} from "../threads/thread-settings-options";
import { SettingsScreen } from "./components/SettingsScreen";
import {
AndroidSettingsEnvironmentFilter,
@@ -33,6 +36,7 @@ import { SettingsProjectOverridesSection } from "./components/SettingsProjectOve
import { useSettingsEnvironmentFilter } from "./settings-environment-filter";
import { useSettingsWriter } from "./useSettingsWriter";
import {
+ managedSettingReason,
planMobileScopedSettingsClear,
planMobileScopedSettingsPatch,
resolveMobileSettingsTargets,
@@ -260,8 +264,19 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
});
};
const disabled = !canWriteSettings || pendingWrites > 0 || !hasConnectedSelection;
+ const managed = (...keys: string[]) => managedSettingReason(targets, ...keys);
+ // A locked row keeps its explanation and says who manages it.
+ const managedSubtitle = (key: string, subtitle: string) => {
+ const reason = managed(key);
+ return reason === undefined ? subtitle : `${subtitle} ${reason}`;
+ };
+ const runtimeModeChoices = withManagedRuntimeModeLimits(
+ RUNTIME_MODE_CHOICES,
+ targets.map((target) => target.environment.serverConfig.managedPolicy),
+ );
const disabledFor = (key: string) =>
disabled ||
+ managed(key) !== undefined ||
(projectSelected &&
!PROJECT_SCOPED_SERVER_SETTING_KEYS.includes(
key as (typeof PROJECT_SCOPED_SERVER_SETTING_KEYS)[number],
@@ -289,6 +304,7 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
</Text>
) : (
<>
+ <ManagedPolicyNotice targets={targets} />
{projectSelected ? (
<SettingsProjectOverridesSection
projectLabel={selectedProject?.label ?? "Unavailable project"}
@@ -304,6 +320,7 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
<>
<SettingsSection
title="Default workspace"
+ footer={managed("defaultThreadEnvMode")}
trailing={
pendingWrites === 0 && isMixed("defaultThreadEnvMode") ? (
<MixedValuesLabel projectSelected={projectSelected} />
@@ -329,26 +346,30 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
</SettingsSection>
<SettingsSection
title="Default permissions"
+ footer={managed("defaultRuntimeMode")}
trailing={
pendingWrites === 0 && uniform("defaultRuntimeMode") === null ? (
<MixedValuesLabel projectSelected={projectSelected} />
) : null
}
>
- {RUNTIME_MODE_CHOICES.map((choice, index) => (
+ {runtimeModeChoices.map((choice, index) => (
<SettingsChoiceRow
key={choice.mode}
label={choice.label}
- description={choice.description}
+ description={choice.disabledReason ?? choice.description}
selected={uniform("defaultRuntimeMode") === choice.mode}
separated={index > 0}
- disabled={disabledFor("defaultRuntimeMode")}
+ disabled={
+ disabledFor("defaultRuntimeMode") || choice.disabledReason !== undefined
+ }
onPress={() => write({ defaultRuntimeMode: choice.mode })}
/>
))}
</SettingsSection>
<SettingsSection
title="Response streaming"
+ footer={managed("responseStreamingMode")}
trailing={
pendingWrites === 0 && uniform("responseStreamingMode") === null ? (
<MixedValuesLabel projectSelected={projectSelected} />
@@ -371,7 +392,10 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
<SettingsSwitchRow
icon="globe"
label="Agent browser access"
- subtitle="Allow agents to use the in-app preview browser."
+ subtitle={managedSubtitle(
+ "enableAgentBrowserAccess",
+ "Allow agents to use the in-app preview browser.",
+ )}
value={uniform("enableAgentBrowserAccess")}
disabled={disabledFor("enableAgentBrowserAccess")}
onValueChange={(value) => write({ enableAgentBrowserAccess: value })}
@@ -393,7 +417,10 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
<SettingsSwitchRow
icon={PullRequestGlyph.merged}
label="Remove agent credits when merging"
- subtitle="Remove recognized agent credits from merge and squash messages on hosts that support it, keeping human co-authors. Includes auto-merge. Excludes merge queues, stack merges, and existing commits."
+ subtitle={managedSubtitle(
+ "removeAgentCreditsOnMerge",
+ "Remove recognized agent credits from merge and squash messages on hosts that support it, keeping human co-authors. Includes auto-merge. Excludes merge queues, stack merges, and existing commits.",
+ )}
value={uniform("removeAgentCreditsOnMerge")}
disabled={disabledFor("removeAgentCreditsOnMerge")}
onValueChange={(value) => write({ removeAgentCreditsOnMerge: value })}
@@ -403,7 +430,10 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
<SettingsSwitchRow
icon="arrow.down.circle"
label="Automatically pull"
- subtitle="Keep the default branch current when there are no local changes."
+ subtitle={managedSubtitle(
+ "defaultAutoPull",
+ "Keep the default branch current when there are no local changes.",
+ )}
value={uniform("defaultAutoPull")}
disabled={disabledFor("defaultAutoPull")}
onValueChange={(value) => write({ defaultAutoPull: value })}
@@ -418,7 +448,10 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
<SettingsSwitchRow
icon="arrow.triangle.branch"
label="Start from remote"
- subtitle="Uses the latest commit of the base branch’s tracked remote branch, even if its name differs. Otherwise uses the same-named branch on origin. Uses your local branch if that remote branch is missing."
+ subtitle={managedSubtitle(
+ "newWorktreesStartFromOrigin",
+ "Uses the latest commit of the base branch’s tracked remote branch, even if its name differs. Otherwise uses the same-named branch on origin. Uses your local branch if that remote branch is missing.",
+ )}
value={uniform("newWorktreesStartFromOrigin")}
disabled={disabledFor("newWorktreesStartFromOrigin")}
onValueChange={(value) => write({ newWorktreesStartFromOrigin: value })}
@@ -426,6 +459,7 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
</SettingsSection>
<SettingsSection
title="Worktree submodules"
+ footer={managed("worktreeSubmodules")}
trailing={
pendingWrites === 0 && isMixed("worktreeSubmodules") ? (
<MixedValuesLabel projectSelected={projectSelected} />
@@ -454,7 +488,11 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
mode={uniform("branchNamingMode")}
prefix={uniform("branchNamePrefix")}
instructions={uniform("branchNameInstructions")}
- disabled={disabledFor("branchNamingMode")}
+ disabled={{
+ mode: disabledFor("branchNamingMode"),
+ prefix: disabledFor("branchNamePrefix"),
+ instructions: disabledFor("branchNameInstructions"),
+ }}
onChange={write}
/>
</>
@@ -491,11 +529,12 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
<SettingsSwitchRow
icon="arrow.clockwise"
label="Check provider updates"
- subtitle={
+ subtitle={managedSubtitle(
+ "enableProviderUpdateChecks",
projectSelected
? "Environment-wide setting. Select All projects to change it."
- : "Check installed provider CLIs for newer versions and fetch model catalog updates. When off, new models may not appear."
- }
+ : "Check installed provider CLIs for newer versions and fetch model catalog updates. When off, new models may not appear.",
+ )}
value={uniform("enableProviderUpdateChecks")}
disabled={disabledFor("enableProviderUpdateChecks")}
onValueChange={(value) => write({ enableProviderUpdateChecks: value })}
@@ -504,7 +543,10 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
<SettingsSwitchRow
icon="arrow.uturn.forward"
label="Continue after restart"
- subtitle="Resume interrupted threads after an update or restart."
+ subtitle={managedSubtitle(
+ "continueThreadsAfterServerUpdate",
+ "Resume interrupted threads after an update or restart.",
+ )}
value={uniform("continueThreadsAfterServerUpdate")}
disabled={disabledFor("continueThreadsAfterServerUpdate")}
onValueChange={(value) =>
@@ -537,3 +579,23 @@ function MixedValuesLabel(props: { readonly projectSelected: boolean }) {
</Text>
);
}
+
+/** Locked settings are refused when saved; say so before the user tries. */
+function ManagedPolicyNotice(props: { readonly targets: readonly ScopedMobileSettingsTarget[] }) {
+ const organizations = [
+ ...new Set(
+ props.targets.flatMap((target) => {
+ const policy = target.environment.serverConfig.managedPolicy;
+ return policy !== undefined && policy.lockedSettings.length > 0
+ ? [policy.organization]
+ : [];
+ }),
+ ),
+ ];
+ if (organizations.length === 0) return null;
+ return (
+ <Text className="px-2 text-sm text-foreground-muted android:px-4">
+ Some settings are managed by {organizations.join(", ")} and cannot be changed here.
+ </Text>
+ );
+}
diff --git a/apps/mobile/src/features/settings/ThreadSettingsSections.tsx b/apps/mobile/src/features/settings/ThreadSettingsSections.tsx
index 244e2d18680..4952f9a2f20 100644
--- a/apps/mobile/src/features/settings/ThreadSettingsSections.tsx
+++ b/apps/mobile/src/features/settings/ThreadSettingsSections.tsx
@@ -1,5 +1,9 @@
import { Button } from "../../components/ui/Button";
-import { AuthSettingsWriteScope, type ServerSettingsPatch } from "@t3tools/contracts";
+import {
+ AuthSettingsWriteScope,
+ isManagedSettingPath,
+ type ServerSettingsPatch,
+} from "@t3tools/contracts";
import { useEnvironmentsWithScope } from "../../state/session";
import { AutoSettleDaysField } from "./components/AutoSettleDaysField";
import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView";
@@ -20,7 +24,11 @@ import { SettingsSwitchRow } from "./components/SettingsSwitchRow";
import { SettingsScreen } from "./components/SettingsScreen";
import { planAutoSettleSettingsSync, type AutoSettleSettings } from "./autoSettleSettingsSync";
import { useSettingsEnvironmentFilter } from "./settings-environment-filter";
-import { resolveMobileSettingsTargets, uniformMobileSetting } from "./settings-scoped-server";
+import {
+ managedSettingReason,
+ resolveMobileSettingsTargets,
+ uniformMobileSetting,
+} from "./settings-scoped-server";
export function SettingsLabsRouteScreen() {
const insets = useSafeAreaInsets();
@@ -98,6 +106,8 @@ export function AutoSettleSettingsRows(props: {
);
const disabled = !canWriteSettings || props.pending;
+ const disabledFor = (...keys: string[]) =>
+ disabled || managedSettingReason(displayTargets, ...keys) !== undefined;
const afterDays = referenceSettings.sidebarAutoSettleAfterDays;
return (
@@ -109,7 +119,7 @@ export function AutoSettleSettingsRows(props: {
label="Resume after usage limits"
subtitle="Automatically resume threads when their usage limits reset. You can cancel auto-resume in each thread."
value={uniformMobileSetting(displayTargets, "autoResumeLimitedThreads")}
- disabled={disabled}
+ disabled={disabledFor("autoResumeLimitedThreads")}
onValueChange={(value) => writeToAll({ autoResumeLimitedThreads: value })}
/>
<SettingsSwitchRow
@@ -117,7 +127,7 @@ export function AutoSettleSettingsRows(props: {
label="Snooze until limits reset"
subtitle="Snooze threads until their usage limits reset. Enable auto-resume to continue the agent after the reset."
value={uniformMobileSetting(displayTargets, "snoozeLimitedThreads")}
- disabled={disabled}
+ disabled={disabledFor("snoozeLimitedThreads")}
onValueChange={(value) => writeToAll({ snoozeLimitedThreads: value })}
/>
</SettingsSection>
@@ -127,14 +137,14 @@ export function AutoSettleSettingsRows(props: {
icon="arrow.triangle.branch"
label="Auto-settle merged threads"
value={referenceSettings.sidebarAutoSettleOnMerge}
- disabled={disabled}
+ disabled={disabledFor("sidebarAutoSettleOnMerge")}
onValueChange={(value) => writeToAll({ sidebarAutoSettleOnMerge: value })}
/>
<SettingsSwitchRow
icon="clock"
label="Auto-settle inactive threads"
value={afterDays !== null}
- disabled={disabled}
+ disabled={disabledFor("sidebarAutoSettleAfterDays")}
onValueChange={(value) =>
writeToAll({ sidebarAutoSettleAfterDays: value ? AUTO_SETTLE_DEFAULT_DAYS : null })
}
@@ -145,7 +155,7 @@ export function AutoSettleSettingsRows(props: {
<Text className="flex-1 text-foreground text-lg android:text-base">Inactive days</Text>
<AutoSettleDaysField
value={afterDays}
- disabled={disabled}
+ disabled={disabledFor("sidebarAutoSettleAfterDays")}
onValueChange={(value) => writeToAll({ sidebarAutoSettleAfterDays: value })}
/>
</View>
@@ -161,7 +171,7 @@ export function AutoSettleSettingsRows(props: {
<Button
label="Apply auto-settle defaults"
tone="secondary"
- disabled={disabled}
+ disabled={disabledFor("sidebarAutoSettleOnMerge", "sidebarAutoSettleAfterDays")}
onPress={() => writeToAll(autoSettlePatch)}
/>
</View>
@@ -232,21 +242,26 @@ function BetaSettingsSection() {
return (
<View className="gap-3">
<SettingsSection title="Beta: Linked environments">
- {supported.map((environment) => (
- <SettingsSwitchRow
- key={environment.environmentId}
- icon="link"
- label={environment.label}
- value={environment.serverConfig?.settings.linkedEnvironmentsEnabled === true}
- disabled={!writable.has(environment.environmentId)}
- onValueChange={(value) =>
- void updateSettings({
- environmentId: environment.environmentId,
- input: { patch: { linkedEnvironmentsEnabled: value } },
- })
- }
- />
- ))}
+ {supported.map((environment) => {
+ const policy = environment.serverConfig?.managedPolicy;
+ const managed = isManagedSettingPath(policy, "linkedEnvironmentsEnabled");
+ return (
+ <SettingsSwitchRow
+ key={environment.environmentId}
+ icon="link"
+ label={environment.label}
+ {...(managed ? { subtitle: `Managed by ${policy?.organization}.` } : {})}
+ value={environment.serverConfig?.settings.linkedEnvironmentsEnabled === true}
+ disabled={managed || !writable.has(environment.environmentId)}
+ onValueChange={(value) =>
+ void updateSettings({
+ environmentId: environment.environmentId,
+ input: { patch: { linkedEnvironmentsEnabled: value } },
+ })
+ }
+ />
+ );
+ })}
</SettingsSection>
<Text className="px-2 text-sm text-foreground-muted">
Let agents on a machine work on your other machines, and theirs on it. Turn it on for each
diff --git a/apps/mobile/src/features/settings/components/BranchNamingSettings.test.tsx b/apps/mobile/src/features/settings/components/BranchNamingSettings.test.tsx
index de6ba2d19bf..9a6db23f8e6 100644
--- a/apps/mobile/src/features/settings/components/BranchNamingSettings.test.tsx
+++ b/apps/mobile/src/features/settings/components/BranchNamingSettings.test.tsx
@@ -47,7 +47,7 @@ function render(
mode={mode}
prefix={saved.prefix ?? "t3"}
instructions={saved.instructions ?? "Use issue IDs."}
- disabled={disabled}
+ disabled={{ mode: disabled, prefix: disabled, instructions: disabled }}
onChange={onChange}
/>,
),
diff --git a/apps/mobile/src/features/settings/components/BranchNamingSettings.tsx b/apps/mobile/src/features/settings/components/BranchNamingSettings.tsx
index d77451d55e9..827251ad9f2 100644
--- a/apps/mobile/src/features/settings/components/BranchNamingSettings.tsx
+++ b/apps/mobile/src/features/settings/components/BranchNamingSettings.tsx
@@ -22,7 +22,8 @@ export function BranchNamingSettings(props: {
mode: BranchNamingMode | null;
prefix: string | null;
instructions: string | null;
- disabled: boolean;
+ /** Per setting, since a policy can lock one and leave the others to the user. */
+ disabled: Readonly<Record<"mode" | "prefix" | "instructions", boolean>>;
onChange: (patch: ServerSettingsPatch) => void;
}) {
// Save on exit too: Android Back hides the keyboard without ending editing.
@@ -66,7 +67,7 @@ export function BranchNamingSettings(props: {
description={MODES[mode].description}
selected={props.mode === mode}
separated={index > 0}
- disabled={props.disabled}
+ disabled={props.disabled.mode}
onPress={() => props.onChange({ branchNamingMode: mode })}
/>
))}
@@ -81,7 +82,7 @@ export function BranchNamingSettings(props: {
onChangeText={(text) => edit("branchNamePrefix", text)}
defaultValue={props.prefix ?? ""}
placeholder={props.prefix === null ? "Mixed" : "No prefix"}
- editable={!props.disabled}
+ editable={!props.disabled.prefix}
autoCapitalize="none"
autoCorrect={false}
className="min-h-10 rounded-xl px-3 py-2 text-base text-foreground"
@@ -104,7 +105,7 @@ export function BranchNamingSettings(props: {
? "Mixed. Enter instructions for all selected targets."
: "Use julius/ followed by the issue ID and a short description."
}
- editable={!props.disabled}
+ editable={!props.disabled.instructions}
multiline
autoCapitalize="sentences"
className="min-h-24 rounded-xl px-3 py-2 text-base text-foreground"
diff --git a/apps/mobile/src/features/settings/settings-scoped-server.test.ts b/apps/mobile/src/features/settings/settings-scoped-server.test.ts
index 1c2de9b662f..4af458c8c2f 100644
--- a/apps/mobile/src/features/settings/settings-scoped-server.test.ts
+++ b/apps/mobile/src/features/settings/settings-scoped-server.test.ts
@@ -8,6 +8,7 @@ import { describe, expect, it } from "vite-plus/test";
import type { SettingsTarget } from "./settings-environment-filter";
import {
+ managedSettingReason,
planMobileScopedSettingsClear,
planMobileScopedSettingsPatch,
resolveMobileSettingsTargets,
@@ -162,3 +163,28 @@ describe("mobile project settings scope", () => {
).toEqual([]);
});
});
+
+describe("managed settings across environments", () => {
+ it("names the manager when any selected environment locks the setting", () => {
+ const managed = {
+ ...environment(secondId, DEFAULT_SERVER_SETTINGS),
+ serverConfig: {
+ ...environment(secondId, DEFAULT_SERVER_SETTINGS).serverConfig,
+ managedPolicy: { organization: "Example Corp", lockedSettings: ["storageCleanup"] },
+ },
+ } as SettingsTarget;
+ const targets = resolveMobileSettingsTargets(
+ [environment(firstId, DEFAULT_SERVER_SETTINGS), managed],
+ null,
+ );
+
+ expect(managedSettingReason(targets, "storageCleanup.logsAfterDays")).toBe(
+ "Managed by Example Corp.",
+ );
+ expect(managedSettingReason(targets, "defaultAutoPull", "storageCleanup")).toBe(
+ "Managed by Example Corp.",
+ );
+ expect(managedSettingReason(targets, "defaultAutoPull")).toBeUndefined();
+ expect(managedSettingReason(targets.slice(0, 1), "storageCleanup")).toBeUndefined();
+ });
+});
diff --git a/apps/mobile/src/features/settings/settings-scoped-server.ts b/apps/mobile/src/features/settings/settings-scoped-server.ts
index 39ba1838ff8..2e16dc73a0a 100644
--- a/apps/mobile/src/features/settings/settings-scoped-server.ts
+++ b/apps/mobile/src/features/settings/settings-scoped-server.ts
@@ -1,4 +1,5 @@
import {
+ isManagedSettingPath,
isNullableProjectSettingsOverride,
PROJECT_SCOPED_SERVER_SETTING_KEYS,
type EnvironmentId,
@@ -21,6 +22,20 @@ export interface ScopedMobileSettingsTarget {
readonly sources: ReturnType<typeof resolveProjectSettings>["sources"];
}
+/**
+ * "Managed by <organization>." when any target's policy locks `path`: the server refuses the
+ * whole write then, so the control is managed for the selection.
+ */
+export function managedSettingReason(
+ targets: readonly ScopedMobileSettingsTarget[],
+ ...paths: readonly string[]
+): string | undefined {
+ const policy = targets
+ .map((target) => target.environment.serverConfig.managedPolicy)
+ .find((candidate) => paths.some((path) => isManagedSettingPath(candidate, path)));
+ return policy === undefined ? undefined : `Managed by ${policy.organization}.`;
+}
+
export function resolveMobileSettingsTargets(
environments: readonly SettingsTarget[],
members: readonly { readonly environmentId: EnvironmentId; readonly id: ProjectId }[] | null,
diff --git a/apps/mobile/src/features/threads/ManagedRuntimeModeNotice.tsx b/apps/mobile/src/features/threads/ManagedRuntimeModeNotice.tsx
new file mode 100644
index 00000000000..bc473741a1d
--- /dev/null
+++ b/apps/mobile/src/features/threads/ManagedRuntimeModeNotice.tsx
@@ -0,0 +1,51 @@
+import {
+ clampManagedRuntimeMode,
+ managedRuntimeModeDenial,
+ type ManagedPolicySummary,
+ type RuntimeMode,
+} from "@t3tools/contracts";
+import { View } from "react-native";
+
+import { AppText } from "../../components/ui/AppText";
+import { Button } from "../../components/ui/Button";
+import {
+ updateComposerDraftSettings,
+ useComposerDraftSettings,
+} from "../../state/use-composer-drafts";
+import { runtimeModeChoicesForSupportedModes } from "./thread-settings-options";
+
+/**
+ * Shown while a thread's mode is above its environment's managed ceiling, where the server
+ * refuses every turn. Switching sets the draft's mode, which the next send applies first.
+ */
+export function ManagedRuntimeModeNotice(props: {
+ readonly threadKey: string;
+ readonly threadRuntimeMode: RuntimeMode;
+ readonly supportedRuntimeModes: ReadonlyArray<RuntimeMode> | undefined;
+ readonly policy: ManagedPolicySummary | undefined;
+}) {
+ const draftSettings = useComposerDraftSettings(props.threadKey);
+ const runtimeMode = draftSettings.runtimeMode ?? props.threadRuntimeMode;
+ const denial = managedRuntimeModeDenial(props.policy, runtimeMode);
+ if (denial === undefined) return null;
+ const choices = runtimeModeChoicesForSupportedModes(props.supportedRuntimeModes);
+ const target = clampManagedRuntimeMode(
+ props.policy,
+ runtimeMode,
+ choices.map((choice) => choice.mode),
+ );
+ const targetLabel = choices.find((choice) => choice.mode === target)?.label;
+ return (
+ <View className="gap-2 px-4 pb-3">
+ <AppText textRole="footnote" className="text-foreground-muted">
+ {`${denial} Switch this thread's mode to continue.`}
+ </AppText>
+ {target === undefined || targetLabel === undefined ? null : (
+ <Button
+ label={`Switch to ${targetLabel}`}
+ onPress={() => updateComposerDraftSettings(props.threadKey, { runtimeMode: target })}
+ />
+ )}
+ </View>
+ );
+}
diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
index a71920c199f..e8bf327a38a 100644
--- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
+++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
@@ -170,6 +170,7 @@ import type {
} from "../../lib/threadActivity";
import { PendingApprovalCard } from "./PendingApprovalCard";
import { ComposerErrorNotice } from "./ComposerErrorNotice";
+import { ManagedRuntimeModeNotice } from "./ManagedRuntimeModeNotice";
import { ComposerFeedback } from "./ComposerFeedback";
import { ComposerUsageLimits } from "./ComposerUsageLimits";
import { PendingUserInputCard } from "./PendingUserInputCard";
@@ -1562,6 +1563,20 @@ function ThreadDetailBody(props: ThreadDetailScreenProps) {
onDismiss={() => props.onDismissFeedback(submission.id)}
/>
))}
+ {props.canOperateThread ? (
+ <ManagedRuntimeModeNotice
+ threadKey={selectedThreadKey}
+ threadRuntimeMode={props.selectedThread.runtimeMode}
+ supportedRuntimeModes={
+ props.serverConfig?.providers.find(
+ (provider) =>
+ provider.instanceId ===
+ props.selectedThread.modelSelection.instanceId,
+ )?.supportedRuntimeModes
+ }
+ policy={props.serverConfig?.managedPolicy}
+ />
+ ) : null}
{composerError !== null ? (
<Animated.View
className="shrink-0"
diff --git a/apps/mobile/src/features/threads/ThreadSettingsRows.shared.tsx b/apps/mobile/src/features/threads/ThreadSettingsRows.shared.tsx
index 384195ec5fa..40841697892 100644
--- a/apps/mobile/src/features/threads/ThreadSettingsRows.shared.tsx
+++ b/apps/mobile/src/features/threads/ThreadSettingsRows.shared.tsx
@@ -22,6 +22,7 @@ export type ChoiceRowProps = {
readonly label: string;
readonly description?: string;
readonly selected: boolean;
+ readonly disabled?: boolean;
readonly onPress: () => void;
readonly isLast: boolean;
};
@@ -140,7 +141,8 @@ export function ChoiceRowContent(props: ChoiceRowProps & RowSelectionProps) {
<Pressable
accessibilityLabel={props.description ? `${props.label}. ${props.description}` : props.label}
accessibilityRole="radio"
- accessibilityState={{ checked: props.selected }}
+ accessibilityState={{ checked: props.selected, disabled: props.disabled === true }}
+ disabled={props.disabled}
onPress={props.onPress}
style={props.minimumHeight === undefined ? undefined : { minHeight: props.minimumHeight }}
className={cn(
@@ -149,7 +151,7 @@ export function ChoiceRowContent(props: ChoiceRowProps & RowSelectionProps) {
)}
>
{props.leadingSelection}
- <View className="min-w-0 flex-1 gap-0.5">
+ <View className={cn("min-w-0 flex-1 gap-0.5", props.disabled && "opacity-50")}>
<Text className="text-base font-t3-medium text-foreground">{props.label}</Text>
{props.description ? (
<Text className="text-sm leading-5 text-foreground-muted">{props.description}</Text>
diff --git a/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx b/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx
index a80ec751515..ce4a8a8833b 100644
--- a/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx
+++ b/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx
@@ -116,6 +116,8 @@ import { ModelRow, ChoiceRow } from "./ThreadSettingsRows";
import {
compatibleRuntimeModeForChoices,
runtimeModeChoicesForSupportedModes,
+ withManagedRuntimeModeLimits,
+ type RuntimeModeChoice,
selectableChoices,
} from "./thread-settings-options";
import {
@@ -304,7 +306,7 @@ type ThreadSettingsSessionValue = {
readonly manageHidden: boolean;
readonly setManageHidden: (value: boolean) => void;
readonly runtimeMode: RuntimeMode;
- readonly runtimeModeChoices: ReturnType<typeof runtimeModeChoicesForSupportedModes>;
+ readonly runtimeModeChoices: ReadonlyArray<RuntimeModeChoice>;
readonly onUpdateRuntimeMode: (mode: RuntimeMode) => void;
readonly displayedDescriptors: ReadonlyArray<ProviderOptionDescriptor>;
readonly promptTraits: ReturnType<typeof getPromptControlledTraits>;
@@ -511,8 +513,9 @@ function ThreadSettingsSessionProvider(
pendingModel ??
props.providerGroups.flatMap((group) => group.models).find((option) => isApplied(option)) ??
null;
- const runtimeModeChoices = runtimeModeChoicesForSupportedModes(
- displayedModel?.supportedRuntimeModes,
+ const runtimeModeChoices = withManagedRuntimeModeLimits(
+ runtimeModeChoicesForSupportedModes(displayedModel?.supportedRuntimeModes),
+ [config?.managedPolicy],
);
const compatibleRuntimeMode = compatibleRuntimeModeForChoices(
props.runtimeMode,
@@ -1100,7 +1103,8 @@ function ThreadSettingsChoiceContent(props: {
rows: session.runtimeModeChoices.map((choice) => ({
id: choice.mode,
label: choice.label,
- description: choice.description,
+ description: choice.disabledReason ?? choice.description,
+ disabled: choice.disabledReason !== undefined,
selected: choice.mode === session.runtimeMode,
onPress: () => {
void Haptics.selectionAsync();
@@ -1115,6 +1119,7 @@ function ThreadSettingsChoiceContent(props: {
id: choice.id,
label: choice.label,
description: choice.description,
+ disabled: false,
selected:
choice.id ===
(session.promptTraits.ultrathinkPromptControlled &&
@@ -1172,6 +1177,7 @@ function ThreadSettingsChoiceContent(props: {
isLast={index === submenuContent.rows.length - 1}
label={row.label}
selected={row.selected}
+ disabled={row.disabled}
onPress={row.onPress}
/>
))}
diff --git a/apps/mobile/src/features/threads/new-task-flow-provider.tsx b/apps/mobile/src/features/threads/new-task-flow-provider.tsx
index 2eaae98e295..3876fd2f83d 100644
--- a/apps/mobile/src/features/threads/new-task-flow-provider.tsx
+++ b/apps/mobile/src/features/threads/new-task-flow-provider.tsx
@@ -95,6 +95,7 @@ import {
} from "./new-task-context-presentation";
import { resolveEnvironmentProjectMatch } from "./new-task-project-selection";
import { useNewTaskProjectDefaults } from "./use-new-task-project-defaults";
+import { resolveNewThreadRuntimeMode } from "./thread-settings-options";
import { resolveProjectThreadCreationBranch } from "./projectThreadCreationValidation";
import {
INACTIVE_FLOW_KEY,
@@ -417,7 +418,12 @@ export function NewTaskFlowProvider(
const startFromOrigin =
isGitRepo && (draftStartFromOrigin ?? projectSettings.settings.newWorktreesStartFromOrigin);
const defaultRuntimeMode = projectSettings.settings.defaultRuntimeMode;
- const runtimeMode = selectedProjectDraft.runtimeMode ?? defaultRuntimeMode;
+ const managedPolicy = selectedEnvironmentServerConfig?.managedPolicy;
+ const runtimeMode = resolveNewThreadRuntimeMode(
+ selectedProjectDraft.runtimeMode,
+ defaultRuntimeMode,
+ managedPolicy,
+ );
// Antigravity keeps unavailable selections so sign-out or a catalog change
// cannot switch the user's model.
@@ -750,7 +756,11 @@ export function NewTaskFlowProvider(
attachments: draft.attachments,
context: draft.context,
modelSelection: draftModelSelection,
- runtimeMode: draft.runtimeMode ?? defaultRuntimeMode,
+ runtimeMode: resolveNewThreadRuntimeMode(
+ draft.runtimeMode,
+ defaultRuntimeMode,
+ managedPolicy,
+ ),
interactionMode: resolvePendingTaskInteractionMode({
planModeEnabled: legacyPlanModeEnabled,
draftInteractionMode: draft.interactionMode,
diff --git a/apps/mobile/src/features/threads/thread-settings-options.test.ts b/apps/mobile/src/features/threads/thread-settings-options.test.ts
index 5cba64375a2..fb15c080e0f 100644
--- a/apps/mobile/src/features/threads/thread-settings-options.test.ts
+++ b/apps/mobile/src/features/threads/thread-settings-options.test.ts
@@ -2,10 +2,52 @@ import {
getPromptControlledTraits,
getTraitSelectChange,
} from "@t3tools/client-runtime/model-traits";
-import type { ProviderOptionDescriptor } from "@t3tools/contracts";
+import type {
+ ManagedPolicySummary,
+ ProviderOptionDescriptor,
+ RuntimeMode,
+} from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
-import { selectableChoices } from "./thread-settings-options";
+import {
+ RUNTIME_MODE_CHOICES,
+ resolveNewThreadRuntimeMode,
+ selectableChoices,
+ withManagedRuntimeModeLimits,
+} from "./thread-settings-options";
+
+const policy = (organization: string, maxRuntimeMode?: RuntimeMode): ManagedPolicySummary => ({
+ organization,
+ lockedSettings: [],
+ ...(maxRuntimeMode === undefined ? {} : { limits: { maxRuntimeMode } }),
+});
+
+describe("managed runtime mode limits", () => {
+ it("disables modes above the strictest target's ceiling with that target's reason", () => {
+ const choices = withManagedRuntimeModeLimits(RUNTIME_MODE_CHOICES, [
+ policy("Wide Corp", "auto"),
+ undefined,
+ policy("Narrow Corp", "auto-accept-edits"),
+ ]);
+
+ expect(choices.map((choice) => [choice.mode, choice.disabledReason])).toEqual([
+ ["approval-required", undefined],
+ ["auto-accept-edits", undefined],
+ ["auto", "Narrow Corp limits threads to Auto-accept edits."],
+ ["full-access", "Wide Corp limits threads to Auto."],
+ ]);
+ });
+
+ it("drops a new thread's draft mode above the ceiling for the default", () => {
+ const capped = policy("Corp", "auto");
+ expect(resolveNewThreadRuntimeMode("full-access", "auto", capped)).toBe("auto");
+ expect(resolveNewThreadRuntimeMode("approval-required", "auto", capped)).toBe(
+ "approval-required",
+ );
+ expect(resolveNewThreadRuntimeMode(undefined, "auto", capped)).toBe("auto");
+ expect(resolveNewThreadRuntimeMode("full-access", "auto", undefined)).toBe("full-access");
+ });
+});
const effortDescriptor: Extract<ProviderOptionDescriptor, { type: "select" }> = {
id: "effort",
diff --git a/apps/mobile/src/features/threads/thread-settings-options.ts b/apps/mobile/src/features/threads/thread-settings-options.ts
index 1fa369d072a..9f9d4f32b7d 100644
--- a/apps/mobile/src/features/threads/thread-settings-options.ts
+++ b/apps/mobile/src/features/threads/thread-settings-options.ts
@@ -1,4 +1,8 @@
-import type { RuntimeMode } from "@t3tools/contracts";
+import {
+ managedRuntimeModeDenial,
+ type ManagedPolicySummary,
+ type RuntimeMode,
+} from "@t3tools/contracts";
export const RUNTIME_MODE_CHOICES: ReadonlyArray<{
readonly mode: RuntimeMode;
@@ -35,6 +39,41 @@ export function runtimeModeChoicesForSupportedModes(
: RUNTIME_MODE_CHOICES;
}
+export type RuntimeModeChoice = (typeof RUNTIME_MODE_CHOICES)[number] & {
+ /** Set when a target environment's managed policy caps runtime modes below this one. */
+ readonly disabledReason?: string;
+};
+
+/**
+ * Marks modes above a managed runtime ceiling. A control acting on several environments is
+ * managed when any of them is, so the first target that refuses a mode supplies its reason.
+ */
+export function withManagedRuntimeModeLimits(
+ choices: ReadonlyArray<RuntimeModeChoice>,
+ policies: ReadonlyArray<ManagedPolicySummary | undefined>,
+): ReadonlyArray<RuntimeModeChoice> {
+ return choices.map((choice) => {
+ const reason = policies
+ .map((policy) => managedRuntimeModeDenial(policy, choice.mode))
+ .find((denial) => denial !== undefined);
+ return reason === undefined ? choice : { ...choice, disabledReason: reason };
+ });
+}
+
+/**
+ * A new thread's mode: the draft's choice unless the managed ceiling refuses it, then the
+ * default, which the server already reads back at or below the ceiling.
+ */
+export function resolveNewThreadRuntimeMode(
+ draftMode: RuntimeMode | undefined,
+ defaultMode: RuntimeMode,
+ policy: ManagedPolicySummary | undefined,
+): RuntimeMode {
+ return draftMode !== undefined && managedRuntimeModeDenial(policy, draftMode) === undefined
+ ? draftMode
+ : defaultMode;
+}
+
export function compatibleRuntimeModeForChoices(
runtimeMode: RuntimeMode,
choices: ReadonlyArray<{ readonly mode: RuntimeMode }>,
diff --git a/apps/mobile/src/lib/modelOptions.test.ts b/apps/mobile/src/lib/modelOptions.test.ts
index 11b9b0603be..bf03fed3510 100644
--- a/apps/mobile/src/lib/modelOptions.test.ts
+++ b/apps/mobile/src/lib/modelOptions.test.ts
@@ -802,4 +802,57 @@ describe("synchronized mobile model visibility", () => {
buildModelOptions(cleared, null, provider, null).map((option) => option.selection.model),
).toEqual(["hidden", "first", "second", "custom"]);
});
+
+ describe("managed provider policy", () => {
+ const config = {
+ providers: [
+ {
+ instanceId: "codex",
+ driver: "codex",
+ enabled: true,
+ installed: true,
+ auth: { status: "authenticated" },
+ models: [{ slug: "gpt-5.6-sol", name: "GPT", isCustom: false, capabilities: null }],
+ },
+ {
+ instanceId: "claudeAgent",
+ driver: "claudeAgent",
+ enabled: true,
+ installed: true,
+ auth: { status: "authenticated" },
+ models: [
+ { slug: "claude-sonnet-5", name: "Sonnet", isCustom: false, capabilities: null },
+ ],
+ },
+ ],
+ managedPolicy: {
+ organization: "Example Corp",
+ lockedSettings: [],
+ limits: { providers: { allowedDrivers: [ProviderDriverKind.make("codex")] } },
+ },
+ } as unknown as ServerConfig;
+ const disallowed = {
+ instanceId: ProviderInstanceId.make("claudeAgent"),
+ model: "claude-sonnet-5",
+ };
+
+ it("leaves drivers the policy does not allow out of the picker", () => {
+ expect(
+ buildModelOptions(config, null, undefined, null).map((option) => option.providerKey),
+ ).toEqual(["codex"]);
+ });
+
+ it("marks a thread's selection on a disallowed driver unavailable with the policy reason", () => {
+ expect(
+ buildModelOptions(config, disallowed, undefined, null).find(
+ (option) => option.providerKey === "claudeAgent",
+ )?.isUnavailable,
+ ).toBe(true);
+ expect(isModelSelectionUnavailable(config, disallowed, null)).toBe(true);
+ expect(describeUnavailableModelSelection(config, disallowed, null)).toEqual({
+ title: "Provider not allowed",
+ detail: "Example Corp's policy does not allow the Claude provider. Choose another model.",
+ });
+ });
+ });
});
diff --git a/apps/mobile/src/lib/modelOptions.ts b/apps/mobile/src/lib/modelOptions.ts
index 00c6cb74ed6..7771c738042 100644
--- a/apps/mobile/src/lib/modelOptions.ts
+++ b/apps/mobile/src/lib/modelOptions.ts
@@ -11,7 +11,12 @@ import type {
RuntimeMode,
ServerConfig as T3ServerConfig,
} from "@t3tools/contracts";
-import { isProviderDriverKind, resolveProjectProviderInstanceEnabled } from "@t3tools/contracts";
+import {
+ disallowedProviderMessage,
+ isManagedDriverAllowed,
+ isProviderDriverKind,
+ resolveProjectProviderInstanceEnabled,
+} from "@t3tools/contracts";
import {
buildExplicitProviderOptionSelectionsFromDescriptors,
getProviderOptionDescriptors,
@@ -110,6 +115,25 @@ function isDisabledForProject(
return provider !== undefined && !isProviderEnabledForProject(config, provider, projectId);
}
+function selectionDriver(
+ config: T3ServerConfig | null | undefined,
+ instanceId: ModelSelection["instanceId"],
+): string | undefined {
+ return (
+ config?.providers.find((candidate) => candidate.instanceId === instanceId)?.driver ??
+ config?.settings?.providerInstances[instanceId]?.driver
+ );
+}
+
+/** Whether the environment's managed policy leaves this driver out; the server refuses its turns. */
+function isDriverDisallowed(config: T3ServerConfig | null | undefined, driver: string | undefined) {
+ return (
+ driver !== undefined &&
+ isProviderDriverKind(driver) &&
+ !isManagedDriverAllowed(config?.managedPolicy, driver)
+ );
+}
+
function normalizeSelectionOptions(
selection: ModelSelection,
capabilities: ModelCapabilities | null,
@@ -152,6 +176,9 @@ export function isModelSelectionUnavailable(
}
const driver =
provider?.driver ?? config.settings?.providerInstances[selection.instanceId]?.driver;
+ if (isDriverDisallowed(config, driver)) {
+ return true;
+ }
return (
driver === "antigravity" &&
(!provider ||
@@ -170,6 +197,20 @@ export function describeUnavailableModelSelection(
const provider = config?.providers.find(
(candidate) => candidate.instanceId === selection.instanceId,
);
+ const driver = selectionDriver(config, selection.instanceId);
+ if (isDriverDisallowed(config, driver)) {
+ const label = providerDisplayLabel({
+ driver: driver ?? selection.instanceId,
+ displayName:
+ provider?.displayName ??
+ config?.settings?.providerInstances[selection.instanceId]?.displayName,
+ instanceId: selection.instanceId,
+ });
+ return {
+ title: "Provider not allowed",
+ detail: `${disallowedProviderMessage(config?.managedPolicy?.organization, label)} Choose another model.`,
+ };
+ }
return isDisabledForProject(config, provider, selection.instanceId, projectId)
? {
title: "Model turned off for this project",
@@ -298,6 +339,7 @@ export function buildModelOptions(
for (const provider of config?.providers ?? []) {
if (
!matchesLockedProvider(provider) ||
+ isDriverDisallowed(config, provider.driver) ||
!isProviderEnabledForProject(config, provider, projectId) ||
!provider.installed ||
provider.auth.status === "unauthenticated" ||
diff --git a/apps/mobile/src/state/threadOutboxDelivery.ts b/apps/mobile/src/state/threadOutboxDelivery.ts
index 4a20db3b9e9..89d7b68b920 100644
--- a/apps/mobile/src/state/threadOutboxDelivery.ts
+++ b/apps/mobile/src/state/threadOutboxDelivery.ts
@@ -16,6 +16,7 @@ import {
CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
DEFAULT_RUNTIME_MODE,
+ managedRuntimeModeDenial,
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
type EnvironmentId,
type MessageId,
@@ -782,6 +783,14 @@ export function createThreadOutboxDelivery(): {
);
return restoreQueuedMessage(queuedMessage, `${title}. ${detail}`);
}
+ // The server would refuse this mode in settings sync, which retries forever; stop first.
+ const runtimeModeDenial = managedRuntimeModeDenial(
+ serverConfig.managedPolicy,
+ settings.runtimeMode,
+ );
+ if (runtimeModeDenial !== undefined) {
+ return restoreQueuedMessage(queuedMessage, runtimeModeDenial);
+ }
if (settings.runtimeMode !== thread.runtimeMode) {
if (!hasAccess()) return true;
@@ -949,6 +958,13 @@ export function createThreadOutboxDelivery(): {
);
return restoreQueuedMessage(queuedMessage, `${title}. ${detail}`);
}
+ const runtimeModeDenial = managedRuntimeModeDenial(
+ serverConfig.managedPolicy,
+ settings.runtimeMode,
+ );
+ if (runtimeModeDenial !== undefined) {
+ return restoreQueuedMessage(queuedMessage, runtimeModeDenial);
+ }
let prepared: PreparedTurnAttachments;
let persistedMessage: QueuedThreadMessage;
let deliveryRevision: number;
diff --git a/apps/server/package.json b/apps/server/package.json
index 0dacbbe9072..5d6c7e8d460 100644
--- a/apps/server/package.json
+++ b/apps/server/package.json
@@ -60,6 +60,7 @@
"character-entities": "2.0.2",
"diff": "8.0.3",
"effect": "catalog:",
+ "ffi-rs": "1.3.2",
"jose": "catalog:",
"node-pty": "^1.2.0-beta.15",
"playwright-core": "1.60.0",
diff --git a/apps/server/src/auth/EnvironmentAuth.test.ts b/apps/server/src/auth/EnvironmentAuth.test.ts
index 20efa88f3b0..7a9e8de1867 100644
--- a/apps/server/src/auth/EnvironmentAuth.test.ts
+++ b/apps/server/src/auth/EnvironmentAuth.test.ts
@@ -21,6 +21,7 @@ import * as EnvironmentAuth from "./EnvironmentAuth.ts";
import * as ServerSecretStore from "./ServerSecretStore.ts";
import * as SessionStore from "./SessionStore.ts";
+import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
const TEST_SERVER_PORT = 13_773;
@@ -39,6 +40,7 @@ const layerServerConfig = (overrides?: Partial<ServerConfig.ServerConfig["Servic
const layerEnvironmentAuth = (overrides?: Partial<ServerConfig.ServerConfig["Service"]>) =>
EnvironmentAuth.layer.pipe(
+ Layer.provide(ManagedPolicy.layerTest()),
Layer.provideMerge(SqlitePersistence.layerMemory),
Layer.provide(ServerSecretStore.layer),
Layer.provide(ServerEnvironment.layerIdentity),
diff --git a/apps/server/src/auth/EnvironmentAuth.ts b/apps/server/src/auth/EnvironmentAuth.ts
index ffc2a0a1ebd..9bc8af57114 100644
--- a/apps/server/src/auth/EnvironmentAuth.ts
+++ b/apps/server/src/auth/EnvironmentAuth.ts
@@ -23,6 +23,7 @@ import {
type DpopFailureReason as DpopFailureReasonType,
mcpClientScopes,
} from "@t3tools/contracts";
+import { isLocalLoopbackHost } from "@t3tools/shared/hostClassification";
import { encodeOAuthScope } from "@t3tools/shared/oauthScope";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
@@ -45,6 +46,8 @@ import { REUSABLE_DEV_SESSION_EXPIRES_AT, resolveReusableDevAuth } from "./Reusa
import { verifyRequestDpopProof } from "./dpop.ts";
import { DESKTOP_RENDERER_ORIGINS } from "../httpCors.ts";
import * as SqlitePersistence from "../persistence/Sqlite.ts";
+import * as ManagedLimits from "../policy/managedLimits.ts";
+import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
const DEFAULT_SESSION_SUBJECT = "cli-issued-session";
export const INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT = "administrative-bootstrap";
@@ -484,10 +487,16 @@ export class EnvironmentAuth extends Context.Service<
readonly subject?: string;
readonly proofKeyThumbprint?: string;
readonly purpose?: "startup";
- }) => Effect.Effect<IssuedPairingLink, ServerAuthInternalError>;
+ }) => Effect.Effect<
+ IssuedPairingLink,
+ ServerAuthInternalError | ManagedLimits.ManagedPolicyRefusedError
+ >;
readonly issuePairingCredential: (
input?: AuthCreatePairingCredentialInput,
- ) => Effect.Effect<AuthPairingCredentialResult, ServerAuthInternalError>;
+ ) => Effect.Effect<
+ AuthPairingCredentialResult,
+ ServerAuthInternalError | ManagedLimits.ManagedPolicyRefusedError
+ >;
readonly issueStartupPairingCredential: () => Effect.Effect<
AuthPairingCredentialResult,
ServerAuthInternalError
@@ -707,6 +716,7 @@ export const make = Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const descriptor = yield* policy.getDescriptor();
const config = yield* ServerConfig.ServerConfig;
+ const managedPolicy = yield* ManagedPolicy.ManagedPolicy;
const devAuth = resolveReusableDevAuth(config);
const authenticateToken = (
@@ -1004,33 +1014,15 @@ export const make = Effect.gen(function* () {
);
};
- const issuePairingCredentialForSubject = (input: {
- readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
- readonly subject: string;
- readonly label?: string;
- readonly purpose?: "startup";
- }) =>
- createPairingLink({
- scopes: input.scopes,
- subject: input.subject,
- ...(input.label ? { label: input.label } : {}),
- ...(input.purpose ? { purpose: input.purpose } : {}),
- }).pipe(
- Effect.map(
- (issued) =>
- ({
- id: issued.id,
- credential: issued.credential,
- ...(issued.label ? { label: issued.label } : {}),
- expiresAt: issued.expiresAt,
- }) satisfies AuthPairingCredentialResult,
- ),
- );
+ const toPairingCredential = (issued: IssuedPairingLink): AuthPairingCredentialResult => ({
+ id: issued.id,
+ credential: issued.credential,
+ ...(issued.label ? { label: issued.label } : {}),
+ expiresAt: issued.expiresAt,
+ });
- const createPairingLink: EnvironmentAuth["Service"]["createPairingLink"] = Effect.fn(
- "EnvironmentAuth.createPairingLink",
- )(
- function* (input) {
+ const issuePairingLink = Effect.fn("EnvironmentAuth.issuePairingLink")(
+ function* (input: Parameters<EnvironmentAuth["Service"]["createPairingLink"]>[0]) {
const createdAt = yield* DateTime.now;
const issued = yield* bootstrapCredentials.issueOneTimeToken({
scopes: input?.scopes ?? AuthStandardClientScopes,
@@ -1053,6 +1045,19 @@ export const make = Effect.gen(function* () {
Effect.mapError((cause) => new ServerAuthPairingLinkCreationError({ cause })),
);
+ const createPairingLink: EnvironmentAuth["Service"]["createPairingLink"] = Effect.fn(
+ "EnvironmentAuth.createPairingLink",
+ )(function* (input) {
+ // The startup link is for a browser on this machine; every other link lets a device pair.
+ if (input?.purpose !== "startup" && !ManagedLimits.allowsRemoteClients(managedPolicy)) {
+ return yield* ManagedLimits.refuseRemoteClients(
+ managedPolicy,
+ "so this server cannot create pairing links",
+ );
+ }
+ return yield* issuePairingLink(input);
+ });
+
const listPairingLinks: EnvironmentAuth["Service"]["listPairingLinks"] = (input) =>
bootstrapCredentials.listActive().pipe(
Effect.map((pairingLinks) => {
@@ -1125,19 +1130,23 @@ export const make = Effect.gen(function* () {
);
const issuePairingCredential: EnvironmentAuth["Service"]["issuePairingCredential"] = (input) =>
- issuePairingCredentialForSubject({
+ createPairingLink({
scopes: input?.scopes ?? AuthStandardClientScopes,
subject: "one-time-token",
...(input?.label ? { label: input.label } : {}),
- }).pipe(Effect.withSpan("EnvironmentAuth.issuePairingCredential"));
+ }).pipe(
+ Effect.map(toPairingCredential),
+ Effect.withSpan("EnvironmentAuth.issuePairingCredential"),
+ );
const issueStartupPairingCredential: EnvironmentAuth["Service"]["issueStartupPairingCredential"] =
() => {
- const fallback = issuePairingCredentialForSubject({
+ // Unguarded: startup already refused auth policies the managed policy leaves out.
+ const fallback = issuePairingLink({
scopes: AuthStandardClientScopes,
subject: INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT,
purpose: "startup",
- });
+ }).pipe(Effect.map(toPairingCredential));
if (!devAuth) {
return fallback.pipe(Effect.withSpan("EnvironmentAuth.issueStartupPairingCredential"));
}
@@ -1366,6 +1375,11 @@ export const make = Effect.gen(function* () {
Effect.withSpan("EnvironmentAuth.consumeMcpApprovalCode"),
);
+ yield* revokePairedClientsThePolicyDisallows(managedPolicy, {
+ sessions,
+ pairingLinks: bootstrapCredentials,
+ });
+
return EnvironmentAuth.of({
getDescriptor: Effect.fn("EnvironmentAuth.getDescriptor")(function () {
return Effect.succeed(descriptor);
@@ -1395,6 +1409,51 @@ export const make = Effect.gen(function* () {
});
});
+/** Subjects of sessions and links a pairing link created, keyed by how the client paired. */
+const LINK_PAIRED_SUBJECTS = { link: "one-time-token", connect: "cloud-connect" } as const;
+
+/**
+ * Revokes sessions and unused links from pairing the policy no longer allows, so a policy rolled
+ * out to a machine that already had phones paired takes effect on the next start.
+ */
+const revokePairedClientsThePolicyDisallows = Effect.fn(
+ "EnvironmentAuth.revokePairedClientsThePolicyDisallows",
+)(function* (
+ policy: ManagedPolicy.ManagedPolicy["Service"],
+ stores: {
+ readonly sessions: SessionStore.SessionStore["Service"];
+ readonly pairingLinks: PairingGrantStore.PairingGrantStore["Service"];
+ },
+) {
+ const remoteAllowed = ManagedLimits.allowsRemoteClients(policy);
+ const disallowed = new Set<string>();
+ if (!remoteAllowed) disallowed.add(LINK_PAIRED_SUBJECTS.link);
+ if (!ManagedLimits.allowsConnect(policy)) disallowed.add(LINK_PAIRED_SUBJECTS.connect);
+ if (disallowed.size === 0) return;
+ const sessions = (yield* stores.sessions.listActive()).filter(
+ (session) =>
+ disallowed.has(session.subject) ||
+ // The startup link also pairs browsers on this machine; only a device elsewhere goes.
+ (!remoteAllowed &&
+ session.subject === INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT &&
+ session.client.ipAddress !== undefined &&
+ !isLocalLoopbackHost(session.client.ipAddress)),
+ );
+ const links = (yield* stores.pairingLinks.listActive()).filter((link) =>
+ disallowed.has(link.subject),
+ );
+ yield* Effect.forEach(sessions, (session) => stores.sessions.revoke(session.sessionId), {
+ discard: true,
+ });
+ yield* Effect.forEach(links, (link) => stores.pairingLinks.revoke(link.id), { discard: true });
+ if (sessions.length > 0 || links.length > 0) {
+ yield* Effect.logInfo("Revoked clients the managed policy does not allow.", {
+ sessions: sessions.length,
+ pairingLinks: links.length,
+ });
+ }
+});
+
export const layer = Layer.effect(EnvironmentAuth, make).pipe(
Layer.provideMerge(PairingGrantStore.layer),
Layer.provideMerge(SessionStore.layer),
@@ -1404,6 +1463,7 @@ export const layer = Layer.effect(EnvironmentAuth, make).pipe(
const layerStorage = Layer.mergeAll(ServerSecretStore.layer, SqlitePersistence.layerConfig);
export const layerRuntime = layer.pipe(
+ Layer.provideMerge(ManagedPolicy.layer),
Layer.provideMerge(layerStorage),
Layer.provideMerge(ServerEnvironment.layerIdentity),
);
diff --git a/apps/server/src/auth/EnvironmentAuthAdmin.test.ts b/apps/server/src/auth/EnvironmentAuthAdmin.test.ts
index 9801e069c2c..cca9a729f3c 100644
--- a/apps/server/src/auth/EnvironmentAuthAdmin.test.ts
+++ b/apps/server/src/auth/EnvironmentAuthAdmin.test.ts
@@ -1,6 +1,6 @@
-import { AuthStandardClientScopes } from "@t3tools/contracts";
+import { AuthStandardClientScopes, type ManagedPolicyDocument } from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
-import { expect, it } from "@effect/vitest";
+import { assert, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -10,6 +10,8 @@ import * as SqlitePersistence from "../persistence/Sqlite.ts";
import * as EnvironmentAuth from "./EnvironmentAuth.ts";
import * as ServerSecretStore from "./ServerSecretStore.ts";
import * as SessionStore from "./SessionStore.ts";
+import * as PairingGrantStore from "./PairingGrantStore.ts";
+import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
const layerServerConfig = (
overrides?: Partial<Pick<ServerConfig.ServerConfig["Service"], "desktopBootstrapToken">>,
@@ -33,15 +35,94 @@ const layerServerConfig = (
const layerEnvironmentAuth = (
overrides?: Partial<Pick<ServerConfig.ServerConfig["Service"], "desktopBootstrapToken">>,
+ policy?: ManagedPolicyDocument,
) =>
EnvironmentAuth.layer.pipe(
+ Layer.provide(ManagedPolicy.layerTest(policy)),
Layer.provideMerge(ServerSecretStore.layer),
Layer.provideMerge(SqlitePersistence.layerMemory),
Layer.provide(ServerEnvironment.layerIdentity),
Layer.provide(layerServerConfig(overrides)),
);
+const desktopAndLocalOnly: ManagedPolicyDocument = {
+ schemaVersion: 1,
+ organization: "Example Corp",
+ limits: { clients: ["desktop", "local-browser"] },
+};
+
it.layer(NodeServices.layer)("EnvironmentAuth administrative operations", (it) => {
+ it.effect("refuses pairing links when the policy does not allow remote clients", () =>
+ Effect.gen(function* () {
+ const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
+
+ const error = yield* environmentAuth.issuePairingCredential().pipe(Effect.flip);
+ const startup = yield* environmentAuth.issueStartupPairingCredential();
+
+ assert.equal(
+ error.message,
+ "Example Corp's policy does not allow remote clients, so this server cannot create pairing links.",
+ );
+ assert.isAbove(startup.credential.length, 0);
+ }).pipe(Effect.provide(layerEnvironmentAuth(undefined, desktopAndLocalOnly))),
+ );
+
+ it.effect("revokes link-paired clients on startup under a policy without remote clients", () =>
+ Effect.gen(function* () {
+ const sessions = yield* SessionStore.SessionStore;
+ const pairingLinks = yield* PairingGrantStore.PairingGrantStore;
+ const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
+ const phone = yield* sessions.issue({ subject: "one-time-token" });
+ const bot = yield* sessions.issue({ subject: "cli-issued-session" });
+ const startup = (ipAddress: string) =>
+ sessions.issue({
+ subject: EnvironmentAuth.INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT,
+ client: { deviceType: "unknown", ipAddress },
+ });
+ const startupPhone = yield* startup("192.168.1.20");
+ const startupBrowser = yield* startup("127.0.0.1");
+ yield* environmentAuth.createPairingLink({ subject: "one-time-token" });
+
+ yield* EnvironmentAuth.make.pipe(
+ Effect.provide(
+ Layer.merge(ManagedPolicy.layerTest(desktopAndLocalOnly), layerServerConfig()),
+ ),
+ );
+
+ const remaining = (yield* sessions.listActive()).map((session) => session.sessionId);
+ assert.notInclude(remaining, phone.sessionId);
+ assert.notInclude(remaining, startupPhone.sessionId);
+ assert.include(remaining, startupBrowser.sessionId);
+ assert.include(remaining, bot.sessionId);
+ assert.lengthOf(yield* pairingLinks.listActive(), 0);
+ }).pipe(Effect.provide(layerEnvironmentAuth())),
+ );
+
+ it.effect("revokes only T3 Connect clients when the policy keeps remote clients", () =>
+ Effect.gen(function* () {
+ const sessions = yield* SessionStore.SessionStore;
+ const phone = yield* sessions.issue({ subject: "one-time-token" });
+ const connect = yield* sessions.issue({ subject: "cloud-connect" });
+
+ yield* EnvironmentAuth.make.pipe(
+ Effect.provide(
+ Layer.merge(
+ ManagedPolicy.layerTest({
+ schemaVersion: 1,
+ organization: "Example Corp",
+ limits: { connect: false },
+ }),
+ layerServerConfig(),
+ ),
+ ),
+ );
+
+ const remaining = (yield* sessions.listActive()).map((session) => session.sessionId);
+ assert.include(remaining, phone.sessionId);
+ assert.notInclude(remaining, connect.sessionId);
+ }).pipe(Effect.provide(layerEnvironmentAuth())),
+ );
+
it.effect("creates, lists, and revokes client pairing links", () =>
Effect.gen(function* () {
const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
diff --git a/apps/server/src/auth/EnvironmentAuthPolicy.ts b/apps/server/src/auth/EnvironmentAuthPolicy.ts
index 141fd86aa52..1a5ad39c358 100644
--- a/apps/server/src/auth/EnvironmentAuthPolicy.ts
+++ b/apps/server/src/auth/EnvironmentAuthPolicy.ts
@@ -1,4 +1,8 @@
-import { AuthEnvironmentMaintainScope, type ServerAuthDescriptor } from "@t3tools/contracts";
+import {
+ AuthEnvironmentMaintainScope,
+ type ServerAuthDescriptor,
+ type ServerAuthPolicy,
+} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -14,20 +18,19 @@ export class EnvironmentAuthPolicy extends Context.Service<
}
>()("t3/auth/EnvironmentAuthPolicy") {}
+/** The auth policy a server started with `config` runs under. */
+export function resolveServerAuthPolicy(
+ config: Pick<ServerConfig.ServerConfig["Service"], "mode" | "host">,
+): ServerAuthPolicy {
+ if (isRemoteReachableHost(config.host)) return "remote-reachable";
+ return config.mode === "desktop" ? "desktop-managed-local" : "loopback-browser";
+}
+
/** @public */
export const make = Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
const serverEnvironment = yield* ServerEnvironment.ServerEnvironmentIdentity;
- const isRemoteReachable = isRemoteReachableHost(config.host);
-
- const policy =
- config.mode === "desktop"
- ? isRemoteReachable
- ? "remote-reachable"
- : "desktop-managed-local"
- : isRemoteReachable
- ? "remote-reachable"
- : "loopback-browser";
+ const policy = resolveServerAuthPolicy(config);
const bootstrapMethods: ServerAuthDescriptor["bootstrapMethods"] =
policy === "desktop-managed-local"
diff --git a/apps/server/src/auth/McpOAuth.test.ts b/apps/server/src/auth/McpOAuth.test.ts
index 29588040217..5e6e6a5ac0f 100644
--- a/apps/server/src/auth/McpOAuth.test.ts
+++ b/apps/server/src/auth/McpOAuth.test.ts
@@ -28,6 +28,7 @@ import * as McpOAuth from "./McpOAuth.ts";
import * as McpOAuthHttp from "./mcpOAuthHttp.ts";
import * as ServerSecretStore from "./ServerSecretStore.ts";
import * as AuthHttp from "./http.ts";
+import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
class AuthTestApi extends HttpApi.make("environment")
.add(EnvironmentHttpApi.groups.auth)
@@ -35,6 +36,7 @@ class AuthTestApi extends HttpApi.make("environment")
const layerConfig = ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-oauth-test-" });
const layerEnvironmentAuth = EnvironmentAuth.layer.pipe(
+ Layer.provide(ManagedPolicy.layerTest()),
Layer.provide(Sqlite.layerMemory),
Layer.provideMerge(ServerSecretStore.layer),
Layer.provideMerge(ServerEnvironment.layerIdentity),
diff --git a/apps/server/src/auth/McpOAuth.ts b/apps/server/src/auth/McpOAuth.ts
index 7416f391ed6..567b39b7dc0 100644
--- a/apps/server/src/auth/McpOAuth.ts
+++ b/apps/server/src/auth/McpOAuth.ts
@@ -15,6 +15,7 @@ import {
AuthOrchestrationReadScope,
MCP_PEER_LINK_SOFTWARE_ID,
mcpClientScopes,
+ type RuntimeMode,
} from "@t3tools/contracts";
import { encodeOAuthScope } from "@t3tools/shared/oauthScope";
import * as Clock from "effect/Clock";
@@ -213,6 +214,10 @@ export class McpOAuth extends Context.Service<
readonly decision: ApprovalDecision;
}) => Effect.Effect<string, EnvironmentAuth.ServerAuthMcpApprovalCodeError | McpOAuthPageError>;
readonly deny: (authorization: AuthorizationRequest) => string;
+ /** A managed policy's runtime-mode ceiling, shown on the approval page. */
+ readonly runtimeModeCeiling:
+ | { readonly organization: string; readonly maxRuntimeMode: RuntimeMode }
+ | undefined;
readonly exchangeCode: (input: {
readonly request: HttpServerRequest.HttpServerRequest;
readonly urls: McpOAuthUrls;
@@ -547,7 +552,13 @@ const make = Effect.gen(function* () {
},
);
+ const managedPolicy = serverSettings.managedPolicy;
+ const maxRuntimeMode = managedPolicy?.limits?.maxRuntimeMode;
return McpOAuth.of({
+ runtimeModeCeiling:
+ managedPolicy === undefined || maxRuntimeMode === undefined
+ ? undefined
+ : { organization: managedPolicy.organization, maxRuntimeMode },
register,
validateAuthorization,
approvingBrowserSession,
diff --git a/apps/server/src/auth/http.test.ts b/apps/server/src/auth/http.test.ts
index 325f0f991e9..4047974500c 100644
--- a/apps/server/src/auth/http.test.ts
+++ b/apps/server/src/auth/http.test.ts
@@ -24,6 +24,7 @@ import * as SqlitePersistence from "../persistence/Sqlite.ts";
import * as EnvironmentAuth from "./EnvironmentAuth.ts";
import * as ServerSecretStore from "./ServerSecretStore.ts";
import * as AuthHttp from "./http.ts";
+import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
const DEV_TOKEN = "reusable-dev-auth-token-that-is-long-enough";
class AuthTestApi extends HttpApi.make("environment").add(EnvironmentHttpApi.groups.auth) {}
@@ -42,6 +43,7 @@ const layerConfig = Layer.effect(
).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-http-test-" })));
const layerEnvironmentAuth = EnvironmentAuth.layer.pipe(
+ Layer.provide(ManagedPolicy.layerTest()),
Layer.provide(SqlitePersistence.layerMemory),
Layer.provide(ServerSecretStore.layer),
Layer.provide(ServerEnvironment.layerIdentity),
diff --git a/apps/server/src/auth/http.ts b/apps/server/src/auth/http.ts
index e570be1b479..2358e73d6d8 100644
--- a/apps/server/src/auth/http.ts
+++ b/apps/server/src/auth/http.ts
@@ -6,6 +6,7 @@ import {
EnvironmentAuthInvalidError,
type EnvironmentAuthInvalidReason,
EnvironmentHttpApi,
+ EnvironmentHttpForbiddenError,
EnvironmentInternalError,
type EnvironmentInternalErrorReason,
EnvironmentOperationForbiddenError,
@@ -461,6 +462,10 @@ export const layer = HttpApiBuilder.group(
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
failEnvironmentInternal("pairing_credential_issuance_failed", error),
),
+ Effect.catchTags({
+ ManagedPolicyRefusedError: (error) =>
+ Effect.fail(new EnvironmentHttpForbiddenError({ message: error.message })),
+ }),
),
)
.handle(
diff --git a/apps/server/src/auth/mcpOAuthHttp.ts b/apps/server/src/auth/mcpOAuthHttp.ts
index 8a2c439d9bb..c62b25cc2a6 100644
--- a/apps/server/src/auth/mcpOAuthHttp.ts
+++ b/apps/server/src/auth/mcpOAuthHttp.ts
@@ -121,6 +121,9 @@ export const layer = HttpApiBuilder.group(
clientName: resolved.client.name,
redirectHost: new URL(resolved.redirectUri).host,
environmentHost: new URL(urls.issuer).host,
+ ...(oauth.runtimeModeCeiling === undefined
+ ? {}
+ : { runtimeModeCeiling: oauth.runtimeModeCeiling }),
...(session === undefined
? {}
: {
diff --git a/apps/server/src/auth/utils.ts b/apps/server/src/auth/utils.ts
index 29c0c5100a1..77235946ca7 100644
--- a/apps/server/src/auth/utils.ts
+++ b/apps/server/src/auth/utils.ts
@@ -6,6 +6,8 @@ import type {
import type * as HttpServerRequest from "effect/http/HttpServerRequest";
// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no createHmac or timingSafeEqual.
import * as NodeCrypto from "node:crypto";
+import * as NodeNet from "node:net";
+import { normalizeHostname } from "@t3tools/shared/hostClassification";
import * as Base64Url from "effect/encoding/Base64Url";
import * as Result from "effect/Result";
@@ -50,22 +52,23 @@ export function resolveLegacySessionCookieName(input: {
: undefined;
}
-export function isRemoteReachableHost(host: string | undefined): boolean {
- if (host === "0.0.0.0" || host === "::" || host === "[::]") {
- return true;
- }
- if (!host || host.length === 0) {
- return false;
- }
- return !(
- host === "localhost" ||
- host === "127.0.0.1" ||
- host === "::1" ||
- host === "[::1]" ||
- host.startsWith("127.")
- );
+/**
+ * The loopback address a server given `host` listens on, or undefined when it may listen beyond
+ * this machine. Unset means 127.0.0.1. Only a loopback literal or `localhost` counts: Node listens
+ * on every interface for an empty host, and any other name resolves through DNS.
+ */
+export function loopbackBindAddress(host: string | undefined): string | undefined {
+ if (host === undefined) return "127.0.0.1";
+ const address = normalizeHostname(host);
+ if (address === "localhost") return "127.0.0.1";
+ return (NodeNet.isIPv4(address) && address.startsWith("127.")) || address === "::1"
+ ? address
+ : undefined;
}
+export const isRemoteReachableHost = (host: string | undefined): boolean =>
+ loopbackBindAddress(host) === undefined;
+
export function base64UrlEncode(input: string | Uint8Array): string {
return typeof input === "string"
? Base64Url.encode(new TextEncoder().encode(input))
diff --git a/apps/server/src/binCli.ts b/apps/server/src/binCli.ts
index 7c136ae5326..32f00bde639 100644
--- a/apps/server/src/binCli.ts
+++ b/apps/server/src/binCli.ts
@@ -1,4 +1,5 @@
import { doctorCommand } from "./cli/doctor.ts";
+import { policyCommand } from "./cli/policy.ts";
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Effect from "effect/Effect";
@@ -95,6 +96,7 @@ export const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) =>
themeCommand,
traceCommand,
doctorCommand,
+ policyCommand,
triageCommand,
cloudEnabled ? connectCommand : connectUnavailableCommand,
]),
diff --git a/apps/server/src/cli/connect.ts b/apps/server/src/cli/connect.ts
index e0aea76ef04..28a6f464344 100644
--- a/apps/server/src/cli/connect.ts
+++ b/apps/server/src/cli/connect.ts
@@ -30,6 +30,8 @@ import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } fr
import * as HttpApiClient from "effect/http-api/HttpApiClient";
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
+import * as ManagedLimits from "../policy/managedLimits.ts";
+import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import * as BootService from "../cloud/bootService.ts";
import * as CliState from "../cloud/CliState.ts";
@@ -523,6 +525,7 @@ export const runCloudCommand = Effect.fn("cloud.cli.run_cloud_command")(function
| Prompt.Environment
| ServerConfig.ServerConfig
| ServerEnvironment.ServerEnvironmentIdentity
+ | ManagedPolicy.ManagedPolicy
>,
options?: {
readonly quietLogs?: boolean;
@@ -540,7 +543,7 @@ export const runCloudCommand = Effect.fn("cloud.cli.run_cloud_command")(function
RelayClient.layerCloudflared({ baseDir: config.baseDir }),
EnvironmentAuth.layerRuntime,
CliService.layer(config),
- RelayTracing.layerHeadlessRelayClient,
+ RelayTracing.layerHeadlessRelayClient.pipe(Layer.provide(ManagedPolicy.layer)),
).pipe(
Layer.provideMerge(FetchHttpClient.layer),
Layer.provideMerge(ServerConfig.layer(config)),
@@ -549,6 +552,14 @@ export const runCloudCommand = Effect.fn("cloud.cli.run_cloud_command")(function
return yield* run.pipe(Effect.provide(layerRuntime));
});
+/** Status, unlink, and logout stay available so a machine can leave Connect the policy turned off. */
+export const requireConnectAllowed = Effect.gen(function* () {
+ const policy = yield* ManagedPolicy.ManagedPolicy;
+ if (!ManagedLimits.allowsConnect(policy)) {
+ return yield* ManagedLimits.refuseConnect(policy);
+ }
+});
+
const connectedAs = (identity: string | null): string => (identity ? ` as ${identity}` : "");
function formatRelayClientReady(version: string): string {
@@ -605,6 +616,7 @@ const connectLoginCommand = Command.make("login", {
runCloudCommand(
flags,
Effect.gen(function* () {
+ yield* requireConnectAllowed;
yield* Console.log("T3 Connect\n");
const identity = yield* authorizeCli(flags);
yield* Console.log(`✓ Signed in${connectedAs(identity)}`);
@@ -628,6 +640,7 @@ const connectLinkCommand = Command.make("link", {
runCloudCommand(
flags,
Effect.gen(function* () {
+ yield* requireConnectAllowed;
yield* Console.log("T3 Connect\n");
const linked = yield* linkEnvironmentForConnect(flags);
if (linked) {
@@ -722,6 +735,7 @@ const connectPublishCommand = Command.make("publish", {
const secrets = yield* ServerSecretStore.ServerSecretStore;
const tokens = yield* CliTokenManager.CloudCliTokenManager;
const enabled = !flags.disable;
+ if (enabled) yield* requireConnectAllowed;
yield* secrets.set(
PUBLISH_AGENT_ACTIVITY_SECRET,
stringToBytes(enabled ? "true" : "false"),
diff --git a/apps/server/src/cli/environment.ts b/apps/server/src/cli/environment.ts
index 2b023f6562e..869c085cbad 100644
--- a/apps/server/src/cli/environment.ts
+++ b/apps/server/src/cli/environment.ts
@@ -16,6 +16,7 @@ import * as ServerConfig from "../config.ts";
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
import * as PeerLinks from "../peer/PeerLinks.ts";
import * as ServerSettings from "../serverSettings.ts";
+import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
import * as SqlitePersistence from "../persistence/Sqlite.ts";
import { authLocationFlags, type CliAuthLocationFlags, resolveCliAuthConfig } from "./config.ts";
@@ -44,7 +45,13 @@ const runWithPeerLinks = Effect.fn("environment.runWithPeerLinks")(function* <A,
Layer.provide(ServerEnvironment.layer.pipe(Layer.provide(ServerSecretStore.layer))),
Layer.provide(
ServerSettings.layer.pipe(
- Layer.provide(Layer.mergeAll(ServerSecretStore.layer, SqlitePersistence.layerConfig)),
+ Layer.provide(
+ Layer.mergeAll(
+ ServerSecretStore.layer,
+ SqlitePersistence.layerConfig,
+ ManagedPolicy.layer,
+ ),
+ ),
),
),
Layer.provide(ServerConfig.layer(config)),
diff --git a/apps/server/src/cli/pair.test.ts b/apps/server/src/cli/pair.test.ts
index 88717f9a7f5..a3b694f4933 100644
--- a/apps/server/src/cli/pair.test.ts
+++ b/apps/server/src/cli/pair.test.ts
@@ -267,6 +267,50 @@ describe("t3 pair", () => {
).pipe(Effect.provide(NodeServices.layer)),
);
+ it.effect("refuses --tailscale before turning on Serve when the policy keeps clients local", () =>
+ withDescriptorServer((origin) =>
+ Effect.gen(function* () {
+ const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-policy-test-"));
+ const policyPath = NodePath.join(baseDir, "policy.json");
+ NodeFS.writeFileSync(
+ policyPath,
+ JSON.stringify({
+ schemaVersion: 1,
+ organization: "Example Corp",
+ limits: { clients: ["desktop", "local-browser"] },
+ }),
+ );
+ yield* persistServerRuntimeState({
+ path: NodePath.join(baseDir, "userdata", "server-runtime.json"),
+ state: yield* makePersistedServerRuntimeState({
+ config: { host: "127.0.0.1", devUrl: undefined },
+ port: Number(new URL(origin).port),
+ }),
+ });
+
+ const error = yield* provideCliTestLayers(
+ runCli(["pair", "--base-dir", baseDir, "--tailscale"]).pipe(
+ Effect.provideService(
+ ChildProcessSpawner.ChildProcessSpawner,
+ ChildProcessSpawner.make(() => Effect.die("tailscale must not run")),
+ ),
+ Effect.provide(
+ ConfigProvider.layer(
+ ConfigProvider.fromEnv({ env: { T3CODE_DEV_MANAGED_POLICY_PATH: policyPath } }),
+ ),
+ ),
+ Effect.flip,
+ ),
+ );
+
+ assert.include(
+ String(error),
+ "Example Corp's policy does not allow remote clients, so Tailscale Serve cannot be turned on.",
+ );
+ }),
+ ).pipe(Effect.provide(NodeServices.layer)),
+ );
+
it.effect("ignores runtime state whose recorded pid is no longer alive", () =>
withDescriptorServer((origin) =>
Effect.gen(function* () {
diff --git a/apps/server/src/cli/pair.ts b/apps/server/src/cli/pair.ts
index 92615b9c837..168946adc5e 100644
--- a/apps/server/src/cli/pair.ts
+++ b/apps/server/src/cli/pair.ts
@@ -30,6 +30,8 @@ import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } fr
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
import * as ServerConfig from "../config.ts";
+import * as ManagedLimits from "../policy/managedLimits.ts";
+import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
import { resolveBaseDir } from "../os-jank.ts";
import {
type PersistedServerRuntimeState,
@@ -404,7 +406,7 @@ const resolveTailscalePairingBase = Effect.fn("pair.resolveTailscalePairingBase"
),
);
notes.push(
- `Tailscale Serve now maps ${baseUrl} to this server and persists across restarts. Remove it with \`tailscale serve --https=${String(input.servePort)} off\`.`,
+ `Tailscale Serve now maps ${baseUrl} to this server and persists across restarts. Remove it with \`tailscale serve --https=${String(input.servePort)} --set-path=/ off\`.`,
);
const probed = yield* awaitEnvironmentDescriptor(baseUrl);
@@ -502,6 +504,14 @@ export const pairCommand = Command.make("pair", {
const notes: Array<string> = [];
let pairingBaseUrl: string;
if (flags.tailscale) {
+ // Serve stays on after this command exits, so refuse before turning it on.
+ const policy = yield* ManagedPolicy.ManagedPolicy.pipe(Effect.provide(ManagedPolicy.layer));
+ if (!ManagedLimits.allowsRemoteClients(policy)) {
+ return yield* ManagedLimits.refuseRemoteClients(
+ policy,
+ "so Tailscale Serve cannot be turned on",
+ );
+ }
const resolved = yield* resolveTailscalePairingBase({
target,
servePort: flags.tailscaleServePort,
diff --git a/apps/server/src/cli/policy.test.ts b/apps/server/src/cli/policy.test.ts
new file mode 100644
index 00000000000..a949f70104b
--- /dev/null
+++ b/apps/server/src/cli/policy.test.ts
@@ -0,0 +1,55 @@
+import * as NodeServices from "@effect/platform-node/NodeServices";
+import { assert, it } from "@effect/vitest";
+import * as Effect from "effect/Effect";
+import * as FileSystem from "effect/FileSystem";
+import * as Path from "effect/Path";
+import * as Schema from "effect/Schema";
+
+import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
+import {
+ makePersistedServerRuntimeState,
+ PersistedServerRuntimeState,
+} from "../serverRuntimeState.ts";
+import { describeRunningServer } from "./policy.ts";
+
+const encodeState = Schema.encodeEffect(Schema.fromJsonString(PersistedServerRuntimeState));
+
+it.layer(NodeServices.layer)((it) =>
+ it.effect("tells whether the running server loaded the installed policy", () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const statePath = (yield* Path.Path).join(
+ yield* fs.makeTempDirectoryScoped({ prefix: "t3-policy-show-" }),
+ "server-runtime.json",
+ );
+ const loaded = (organization: string) =>
+ ManagedPolicy.loadedPolicy({
+ path: "/etc/t3code/policy.json",
+ document: { schemaVersion: 1, organization },
+ });
+ const installed = yield* loaded("Example Corp");
+ // A live server (this process) that loaded `managedPolicy`; undefined is an older server.
+ const running = (managedPolicy: typeof installed | undefined, current = installed) =>
+ Effect.gen(function* () {
+ const state = yield* makePersistedServerRuntimeState({
+ config: { host: undefined, devUrl: undefined },
+ port: 3773,
+ ...(managedPolicy === undefined ? {} : { managedPolicy }),
+ });
+ yield* fs.writeFileString(statePath, yield* encodeState(state));
+ return yield* describeRunningServer(statePath, current);
+ });
+
+ assert.include(yield* describeRunningServer(statePath, installed), "No T3 Code server");
+ assert.include(yield* running(installed), "loaded this policy.");
+ assert.include(
+ yield* running(yield* loaded("Other Corp")),
+ "loaded Other Corp's policy from /etc/t3code/policy.json",
+ );
+ assert.include(yield* running(null), "loaded no policy. Restart T3 Code");
+ assert.include(yield* running(installed, null), "Restart T3 Code to apply");
+ assert.include(yield* running(null, null), "runs without a policy, as installed");
+ assert.include(yield* running(undefined), "does not report which policy it loaded");
+ }),
+ ),
+);
diff --git a/apps/server/src/cli/policy.ts b/apps/server/src/cli/policy.ts
new file mode 100644
index 00000000000..99275968fd6
--- /dev/null
+++ b/apps/server/src/cli/policy.ts
@@ -0,0 +1,109 @@
+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 References from "effect/References";
+import { Argument, Command, GlobalFlag } from "effect/cli";
+import * as CliError from "effect/cli/CliError";
+
+import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
+import { isProcessAlive, readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
+import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
+
+const describePolicy = (
+ policy: ManagedPolicy.ManagedPolicy["Service"],
+ loaded: Effect.Success<ReturnType<typeof ManagedPolicy.loadedPolicy>>,
+) => {
+ const { document } = policy;
+ if (document === undefined || loaded === null) {
+ return "No managed policy on this machine. Every setting belongs to the user.\n";
+ }
+ const settings = Object.entries(document.settings ?? {});
+ const lines = [
+ `Managed by ${document.organization} (${policy.path}, fingerprint ${loaded.fingerprint}).`,
+ ...(document.supportUrl === undefined ? [] : [`Support: ${document.supportUrl}`]),
+ "",
+ settings.length === 0 ? "No managed settings." : "Settings:",
+ ...settings.map(
+ ([path, setting]) =>
+ ` ${path} = ${JSON.stringify(setting.value)} (${setting.locked ? "locked" : "default"})`,
+ ),
+ ];
+ if (document.limits !== undefined) {
+ lines.push("", "Limits:", JSON.stringify(document.limits, null, 2));
+ }
+ return `${lines.join("\n")}\n`;
+};
+
+/** Whether the server running from this T3 home loaded the installed policy, which waits for a restart. */
+export const describeRunningServer = Effect.fn("cli.policy.describeRunningServer")(function* (
+ statePath: string,
+ installed: Effect.Success<ReturnType<typeof ManagedPolicy.loadedPolicy>>,
+) {
+ const state = yield* readPersistedServerRuntimeState(statePath);
+ if (Option.isNone(state) || !isProcessAlive(state.value.pid)) {
+ return "No T3 Code server is running from this T3 home. The installed policy applies when one starts.";
+ }
+ const { pid, startedAt, managedPolicy: loaded } = state.value;
+ const server = `The running server (pid ${pid}, started ${startedAt})`;
+ if (loaded === undefined) {
+ return `${server} does not report which policy it loaded. Restart it to apply the installed policy.`;
+ }
+ if ((loaded?.fingerprint ?? null) === (installed?.fingerprint ?? null)) {
+ return loaded === null
+ ? `${server} runs without a policy, as installed.`
+ : `${server} loaded this policy.`;
+ }
+ const what =
+ loaded === null
+ ? "no policy"
+ : `${loaded.organization}'s policy from ${loaded.source} (fingerprint ${loaded.fingerprint})`;
+ return `${server} loaded ${what}. Restart T3 Code to apply the installed policy.`;
+});
+
+const showCommand = Command.make("show", projectLocationFlags).pipe(
+ Command.withDescription(
+ "Show the policy installed on this machine, and whether the running server loaded it.",
+ ),
+ Command.withHandler(
+ Effect.fn("cli.policy.show")(function* (flags) {
+ // The command prints the policy itself; the server's startup log line would repeat it.
+ const policy = yield* ManagedPolicy.ManagedPolicy.pipe(
+ Effect.provide(
+ ManagedPolicy.layer.pipe(
+ Layer.provide(Layer.succeed(References.MinimumLogLevel, "Warn")),
+ ),
+ ),
+ );
+ const installed = yield* ManagedPolicy.loadedPolicy(policy);
+ yield* Console.log(describePolicy(policy, installed));
+ const config = yield* resolveCliAuthConfig(flags, yield* GlobalFlag.LogLevel);
+ yield* Console.log(yield* describeRunningServer(config.serverRuntimeStatePath, installed));
+ }),
+ ),
+);
+
+const checkCommand = Command.make("check", {
+ file: Argument.String("file").pipe(Argument.withDescription("Policy file to validate.")),
+}).pipe(
+ Command.withDescription("Validate a policy file before deploying it."),
+ Command.withHandler(
+ Effect.fn("cli.policy.check")(function* ({ file }) {
+ // Startup treats a missing file as no policy; a draft that is not there checks nothing.
+ if (!(yield* (yield* FileSystem.FileSystem).exists(file))) {
+ return yield* new CliError.UserError({
+ cause: file,
+ userMessage: `No policy file at ${file}.`,
+ });
+ }
+ const policy = yield* ManagedPolicy.load(file);
+ yield* Console.log(describePolicy(policy, yield* ManagedPolicy.loadedPolicy(policy)));
+ }),
+ ),
+);
+
+export const policyCommand = Command.make("policy").pipe(
+ Command.withDescription("Inspect the administrator's managed policy."),
+ Command.withSubcommands([showCommand, checkCommand]),
+);
diff --git a/apps/server/src/cli/project.test.ts b/apps/server/src/cli/project.test.ts
index 723f5254e7a..9367ce7bdf1 100644
--- a/apps/server/src/cli/project.test.ts
+++ b/apps/server/src/cli/project.test.ts
@@ -45,6 +45,7 @@ import {
persistServerRuntimeState,
} from "../serverRuntimeState.ts";
import * as ServerSettings from "../serverSettings.ts";
+import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
const layerCliRuntime = Layer.mergeAll(NodeServices.layer, NetService.layer);
@@ -96,7 +97,11 @@ const readProjects = (baseDir: string) =>
Layer.provideMerge(ProjectFaviconResolver.layer),
Layer.provideMerge(T3ProjectFileLoader.layer),
Layer.provideMerge(WorkspacePaths.layer),
- Layer.provideMerge(ServerSettings.layer.pipe(Layer.provide(ServerSecretStore.layer))),
+ Layer.provideMerge(
+ ServerSettings.layer.pipe(
+ Layer.provide(Layer.merge(ServerSecretStore.layer, ManagedPolicy.layerTest())),
+ ),
+ ),
Layer.provideMerge(SqlitePersistence.layerConfig),
Layer.provideMerge(NodeServices.layer),
Layer.provide(ServerConfig.layer(config)),
diff --git a/apps/server/src/cli/project.ts b/apps/server/src/cli/project.ts
index 3d02f9c921f..d1c8c8a4959 100644
--- a/apps/server/src/cli/project.ts
+++ b/apps/server/src/cli/project.ts
@@ -36,6 +36,7 @@ import * as ProjectService from "../project/ProjectService.ts";
import { projectMutationOperation } from "../project/ProjectMutation.ts";
import * as T3ProjectFileLoader from "../project/T3ProjectFileLoader.ts";
import * as ServerSettings from "../serverSettings.ts";
+import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
import {
clearPersistedServerRuntimeState,
readPersistedServerRuntimeState,
@@ -210,7 +211,11 @@ const layerProjectCliRuntime = RuntimeLayer.layerProjectService.pipe(
),
),
Layer.provideMerge(WorkspacePaths.layer),
- Layer.provideMerge(ServerSettings.layer.pipe(Layer.provide(ServerSecretStore.layer))),
+ Layer.provideMerge(
+ ServerSettings.layer.pipe(
+ Layer.provide(Layer.merge(ServerSecretStore.layer, ManagedPolicy.layer)),
+ ),
+ ),
Layer.provideMerge(SqlitePersistence.layerConfig),
);
diff --git a/apps/server/src/cli/up.ts b/apps/server/src/cli/up.ts
index 7f307aec4b3..b04b6fea7d3 100644
--- a/apps/server/src/cli/up.ts
+++ b/apps/server/src/cli/up.ts
@@ -16,12 +16,15 @@ import { CLOUD_ENDPOINT_RUNTIME_CONFIG, CLOUD_LINK_REVOKED } from "../cloud/conf
import { hasCloudPublicConfig } from "../cloud/publicConfig.ts";
import { compareExactServiceVersions } from "../cloud/serviceProtocol.ts";
import * as ServerConfig from "../config.ts";
+import * as ManagedLimits from "../policy/managedLimits.ts";
+import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
import {
connectSubcommands,
disconnectCloud,
headlessFlag,
linkEnvironmentForConnect,
+ requireConnectAllowed,
runCloudCommand,
waitForReachability,
} from "./connect.ts";
@@ -236,6 +239,13 @@ const setUp = Effect.fn("cli.up")(function* (flags: {
}, or use --yes for the default. See \`t3 up --help\`.`,
});
}
+ if (routes.connect && !current.connect) yield* requireConnectAllowed;
+ if (routes.lan && !current.lan) {
+ const policy = yield* ManagedPolicy.ManagedPolicy;
+ if (!ManagedLimits.allowsRemoteClients(policy)) {
+ return yield* ManagedLimits.refuseRemoteClients(policy);
+ }
+ }
// Nothing to run in the background, but a route left on still gets turned off.
if (!before.service.installed && !routes.connect && !routes.lan) {
if (current.connect || before.connectRevoked) {
diff --git a/apps/server/src/cli/update.test.ts b/apps/server/src/cli/update.test.ts
index 0f28a68c3b4..848c2c798df 100644
--- a/apps/server/src/cli/update.test.ts
+++ b/apps/server/src/cli/update.test.ts
@@ -1,10 +1,12 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
+import type { ManagedUpdatesPolicy } from "@t3tools/contracts";
import * as HostProcess from "@t3tools/shared/HostProcess";
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 Path from "effect/Path";
import * as TestClock from "effect/testing/TestClock";
@@ -12,9 +14,11 @@ import { HttpClient, HttpClientResponse } from "effect/http";
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
import { afterEach, vi } from "vite-plus/test";
+import * as BootService from "../cloud/bootService.ts";
import { prunePinnedRuntimes } from "../cloud/pinnedRuntime.ts";
+import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
import * as ProcessRunner from "../processRunner.ts";
-import { repointLauncher, resolveLauncherPath, resolveNewestVersion } from "./update.ts";
+import { repointLauncher, resolveLauncherPath, resolveNewestVersion, runUpdate } from "./update.ts";
// lsof listing one process, so prune sees a process list in which no runtime is running.
const unrelatedLsof = ProcessRunner.ProcessRunner.of({
@@ -56,6 +60,66 @@ it.effect("authenticates each release page until the requested channel is found"
}),
);
+it.layer(NodeServices.layer)("t3 update under a managed policy", (it) => {
+ const runWithPolicy = (
+ updates: ManagedUpdatesPolicy,
+ input: { readonly channel?: "stable" | "nightly"; readonly requestedVersion?: string } = {},
+ ) =>
+ runUpdate({
+ baseDir: "/unused",
+ logsDir: "/unused",
+ serverRuntimeStatePath: "/unused",
+ channel: input.channel,
+ requestedVersion: input.requestedVersion,
+ allowDowngrade: false,
+ assumeYes: true,
+ }).pipe(
+ Effect.flip,
+ Effect.provide(
+ Layer.mergeAll(
+ ManagedPolicy.layerTest({
+ schemaVersion: 1,
+ organization: "Example Corp",
+ limits: { updates },
+ }),
+ // Refusals happen before the update touches the network, the service, or a process.
+ Layer.mock(BootService.BootService, {}),
+ Layer.mock(ProcessRunner.ProcessRunner, {}),
+ Layer.succeed(
+ HttpClient.HttpClient,
+ HttpClient.make(() => Effect.die("unexpected release lookup")),
+ ),
+ ),
+ ),
+ );
+
+ it.effect("refuses to update when updates are off", () =>
+ Effect.gen(function* () {
+ const error = yield* runWithPolicy({ mode: "off" });
+ assert.equal(error.message, "Example Corp manages T3 Code updates.");
+ }),
+ );
+
+ it.effect("refuses nightly releases when the policy disallows them", () =>
+ Effect.gen(function* () {
+ const byChannel = yield* runWithPolicy(
+ { mode: "auto", allowNightly: false },
+ { channel: "nightly" },
+ );
+ const byVersion = yield* runWithPolicy(
+ { mode: "auto", allowNightly: false },
+ { channel: "stable", requestedVersion: "1.2.0-nightly.20261028.1" },
+ );
+ for (const error of [byChannel, byVersion]) {
+ assert.equal(
+ error.message,
+ "Example Corp manages T3 Code updates. Only stable releases can be installed.",
+ );
+ }
+ }),
+ );
+});
+
it.layer(NodeServices.layer)("t3 update launcher", (it) => {
it.effect("repoints a symlink that lives in a runtime versions tree", () =>
Effect.gen(function* () {
diff --git a/apps/server/src/cli/update.ts b/apps/server/src/cli/update.ts
index 1fb4b14c078..dc2e2934586 100644
--- a/apps/server/src/cli/update.ts
+++ b/apps/server/src/cli/update.ts
@@ -32,6 +32,8 @@ import {
windowsShimTarget,
} from "../cloud/pinnedRuntime.ts";
import { compareExactServiceVersions, isExactServiceVersion } from "../cloud/serviceProtocol.ts";
+import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
+import { managedUpdateRefusal } from "../policy/managedUpdates.ts";
import * as ProcessRunner from "../processRunner.ts";
import { isProcessAlive, readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
@@ -245,7 +247,12 @@ export const updateCommand = Command.make("update", {
assumeYes: flags.yes,
}).pipe(
Effect.provide(
- Layer.mergeAll(CliService.layer(config), ProcessRunner.layer, FetchHttpClient.layer),
+ Layer.mergeAll(
+ CliService.layer(config),
+ ProcessRunner.layer,
+ FetchHttpClient.layer,
+ ManagedPolicy.layer,
+ ),
),
);
}),
@@ -295,7 +302,7 @@ const belongsToBootService = Effect.fn("cli.update.belongs_to_boot_service")(fun
return false;
});
-const runUpdate = Effect.fn("cli.update.run")(function* (input: {
+export const runUpdate = Effect.fn("cli.update.run")(function* (input: {
readonly baseDir: string;
readonly logsDir: string;
readonly serverRuntimeStatePath: string;
@@ -312,9 +319,17 @@ const runUpdate = Effect.fn("cli.update.run")(function* (input: {
const environment = yield* HostProcess.Environment;
const httpClient = yield* HttpClient.HttpClient;
const service = yield* BootService.BootService;
+ const policy = yield* ManagedPolicy.ManagedPolicy;
const currentVersion = packageJson.version;
const channel = input.channel ?? cliReleaseChannelOf(currentVersion);
+ const refusal = managedUpdateRefusal(
+ policy.document,
+ input.requestedVersion === undefined ? channel : cliReleaseChannelOf(input.requestedVersion),
+ );
+ if (refusal !== undefined) {
+ return yield* new CliUpdateError({ reason: refusal });
+ }
if (input.requestedVersion !== undefined && !isExactServiceVersion(input.requestedVersion)) {
return yield* new CliUpdateError({
reason: `'${input.requestedVersion}' is not an exact t3 version.`,
diff --git a/apps/server/src/cloud/CloudLink.lifecycle.test.ts b/apps/server/src/cloud/CloudLink.lifecycle.test.ts
index facd9f8912e..ad1ed1f34a2 100644
--- a/apps/server/src/cloud/CloudLink.lifecycle.test.ts
+++ b/apps/server/src/cloud/CloudLink.lifecycle.test.ts
@@ -43,6 +43,7 @@ import { consumeCloudReplayGuards } from "./CloudLink.ts";
import { pendingServiceUpdateExists } from "./updateHandoff.ts";
import { managedTunnelStartupAction } from "./managedTunnelStartup.ts";
import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
+import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
const storeFailure = (tag: "AlreadyExists" | "PermissionDenied") =>
new ServerSecretStore.SecretStorePersistError({
@@ -158,7 +159,7 @@ describe("releaseManagedTunnelOnShutdown", () => {
(harness: ReleaseHarness) =>
<A, E, R>(effect: Effect.Effect<A, E, R>) =>
effect.pipe(
- Effect.provide(CloudLink.layer),
+ Effect.provide(CloudLink.layer.pipe(Layer.provide(ManagedPolicy.layerTest()))),
Effect.provideService(
ConnectReachability.ConnectReachability,
ConnectReachability.ConnectReachability.of({
diff --git a/apps/server/src/cloud/CloudLink.test.ts b/apps/server/src/cloud/CloudLink.test.ts
index 6851117d38e..a077d3180fe 100644
--- a/apps/server/src/cloud/CloudLink.test.ts
+++ b/apps/server/src/cloud/CloudLink.test.ts
@@ -19,11 +19,13 @@ import * as CloudLink from "./CloudLink.ts";
import * as ConnectReachability from "./ConnectReachability.ts";
import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
import {
+ CLOUD_LINKED_USER_ID,
HOLD_WEBHOOKS_WHILE_OFFLINE_SECRET,
PUBLISH_AGENT_ACTIVITY_SECRET,
RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
RELAY_URL_SECRET,
} from "./config.ts";
+import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
const encode = (value: string) => new TextEncoder().encode(value);
@@ -95,6 +97,7 @@ const withService = <A, E>(
}),
Layer.mock(AgentAwarenessRelay.AgentAwarenessRelay)({ requestCatchUp: () => Effect.void }),
Layer.mock(ManagedEndpointRuntime.CloudManagedEndpointRuntime)({}),
+ ManagedPolicy.layerTest(),
Layer.mock(ConnectReachability.ConnectReachability)({
latest: Effect.succeedNone,
}),
@@ -244,3 +247,57 @@ it.effect("an update the client walks away from still finishes", () => {
}),
);
});
+
+it.effect("unlinks on startup and refuses to link when the policy turns Connect off", () =>
+ Effect.gen(function* () {
+ const stored = new Map<string, Uint8Array>([
+ [CLOUD_LINKED_USER_ID, encode("user-1")],
+ [RELAY_URL_SECRET, encode("https://relay.test")],
+ ]);
+ const appliedConfigs: Array<unknown> = [];
+ const layerDependencies = Layer.mergeAll(
+ Layer.mock(ServerSecretStore.ServerSecretStore)({
+ get: (name) => Effect.succeed(Option.fromNullishOr(stored.get(name))),
+ set: (name, value) => Effect.sync(() => void stored.set(name, value)),
+ remove: (name) => Effect.sync(() => void stored.delete(name)),
+ }),
+ Layer.mock(ServerEnvironment.ServerEnvironment)({}),
+ Layer.mock(AgentAwarenessRelay.AgentAwarenessRelay)({}),
+ Layer.mock(ManagedEndpointRuntime.CloudManagedEndpointRuntime)({
+ withLinkStateLock: (effect) => effect,
+ applyConfig: (config) =>
+ Effect.sync(() => {
+ appliedConfigs.push(config);
+ return { status: "disabled" as const };
+ }),
+ }),
+ ManagedPolicy.layerTest({
+ schemaVersion: 1,
+ organization: "Example Corp",
+ limits: { connect: false },
+ }),
+ Layer.mock(ConnectReachability.ConnectReachability)({}),
+ Layer.mock(EnvironmentAuth.EnvironmentAuth)({}),
+ Layer.mock(CliTokenManager.CloudCliTokenManager)({}),
+ Layer.mock(HttpServer.HttpServer)({
+ address: NetAddress.inetAddressFromIpStringUnsafe("127.0.0.1", 3773),
+ }),
+ Layer.mock(ServerConfig.ServerConfig)({} as ServerConfig.ServerConfig["Service"]),
+ Layer.succeed(
+ HttpClient.HttpClient,
+ HttpClient.make(() => Effect.die("unused")),
+ ),
+ NodeServices.layer,
+ );
+ yield* Effect.gen(function* () {
+ const link = yield* CloudLink.CloudLink;
+ assert.isFalse(stored.has(CLOUD_LINKED_USER_ID));
+ assert.deepEqual(appliedConfigs, [null]);
+
+ const applyError = yield* link.applyRelayConfig({} as never).pipe(Effect.flip);
+ const mintError = yield* link.mintCredential({} as never).pipe(Effect.flip);
+ assert.equal(applyError.message, "Example Corp's policy does not allow T3 Connect.");
+ assert.equal(mintError._tag, "ManagedPolicyRefusedError");
+ }).pipe(Effect.provide(CloudLink.layer.pipe(Layer.provide(layerDependencies))));
+ }),
+);
diff --git a/apps/server/src/cloud/CloudLink.ts b/apps/server/src/cloud/CloudLink.ts
index 99530612463..6909d66fe28 100644
--- a/apps/server/src/cloud/CloudLink.ts
+++ b/apps/server/src/cloud/CloudLink.ts
@@ -98,6 +98,8 @@ import {
import { getOrCreateEnvironmentKeyPairFromSecretStore } from "./environmentKeys.ts";
import * as ConnectReachability from "./ConnectReachability.ts";
import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
+import * as ManagedLimits from "../policy/managedLimits.ts";
+import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
import { relayUrlConfig } from "./publicConfig.ts";
import {
filterRelayResponse,
@@ -432,7 +434,8 @@ export class CloudLink extends Context.Service<
RelayEnvironmentLinkProof,
| CloudLinkOriginInvalidError
| CloudLinkInternalError
- | EnvironmentAuth.ServerAuthInternalError,
+ | EnvironmentAuth.ServerAuthInternalError
+ | ManagedLimits.ManagedPolicyRefusedError,
EnvironmentAuthenticatedPrincipal
>;
readonly applyRelayConfig: (
@@ -446,6 +449,7 @@ export class CloudLink extends Context.Service<
| CloudLinkRelayConfigInvalidError
| CloudLinkTunnelSupersededError
| EnvironmentAuth.ServerAuthInternalError
+ | ManagedLimits.ManagedPolicyRefusedError
| RelayRequestError
>;
readonly linkState: () => Effect.Effect<
@@ -457,7 +461,7 @@ export class CloudLink extends Context.Service<
input: EnvironmentCloudPreferencesRequest,
) => Effect.Effect<
EnvironmentCloudLinkStateResult,
- CloudLinkNotLinkedError | CloudLinkInternalError
+ CloudLinkNotLinkedError | CloudLinkInternalError | ManagedLimits.ManagedPolicyRefusedError
>;
readonly answerHealthRequest: (
request: RelayCloudEnvironmentHealthRequest,
@@ -467,6 +471,7 @@ export class CloudLink extends Context.Service<
| CloudLinkProofReplayedError
| CloudLinkInternalError
| EnvironmentAuth.ServerAuthInternalError
+ | ManagedLimits.ManagedPolicyRefusedError
>;
readonly mintCredential: (
request: RelayCloudMintCredentialRequest,
@@ -476,6 +481,7 @@ export class CloudLink extends Context.Service<
| CloudLinkProofReplayedError
| CloudLinkInternalError
| EnvironmentAuth.ServerAuthInternalError
+ | ManagedLimits.ManagedPolicyRefusedError
>;
readonly reconcileDesiredLinkIfStillDesired: (
localOrigin: string,
@@ -529,6 +535,7 @@ const make = Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
+ const managedPolicy = yield* ManagedPolicy.ManagedPolicy;
const withSecrets = Effect.provideService(ServerSecretStore.ServerSecretStore, secrets);
const withRuntimeFiles = <A, E>(
@@ -1618,6 +1625,38 @@ const make = Effect.gen(function* () {
Effect.catchTags({ PlatformError: internalError("issue-credential") }),
);
+ if (!ManagedLimits.allowsConnect(managedPolicy)) {
+ // Reading state and unlinking stay available so clients can show and leave the old link.
+ yield* unlink().pipe(
+ Effect.tap(() => Effect.logInfo("T3 Connect is off by managed policy; unlinked.")),
+ Effect.catch((cause) =>
+ Effect.logWarning("Failed to unlink T3 Connect turned off by managed policy", { cause }),
+ ),
+ );
+ const refused = Effect.fn("CloudLink.refusedByPolicy")(function* () {
+ return yield* ManagedLimits.refuseConnect(managedPolicy);
+ });
+ const notLinked = Effect.fn("CloudLink.notLinkedByPolicy")(() =>
+ Effect.succeed({ status: "not_linked" as const }),
+ );
+ const notDesired = Effect.fn("CloudLink.notDesiredByPolicy")(() => Effect.succeed(null));
+ const notStarted = Effect.fn("CloudLink.notStartedByPolicy")(() => Effect.succeed(false));
+ return CloudLink.of({
+ linkProof: refused,
+ applyRelayConfig: refused,
+ linkState,
+ unlink,
+ updatePreferences: refused,
+ answerHealthRequest: refused,
+ mintCredential: refused,
+ reconcileDesiredLinkIfStillDesired: notDesired,
+ registerManagedTunnelRecovery: notLinked,
+ recoverManagedTunnel: notStarted,
+ startManagedTunnelIfOriginConfirmed: notStarted,
+ releaseManagedTunnelOnShutdown,
+ });
+ }
+
return CloudLink.of({
linkProof,
applyRelayConfig,
diff --git a/apps/server/src/cloud/ManagedEndpointRuntime.test.ts b/apps/server/src/cloud/ManagedEndpointRuntime.test.ts
index b6d455f3a88..f052b08f01d 100644
--- a/apps/server/src/cloud/ManagedEndpointRuntime.test.ts
+++ b/apps/server/src/cloud/ManagedEndpointRuntime.test.ts
@@ -23,6 +23,7 @@ import * as RelayClient from "@t3tools/shared/relayClient";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import * as ServerConfig from "../config.ts";
import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
+import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
const layerRelayClientAvailable = Layer.succeed(
RelayClient.RelayClient,
@@ -53,6 +54,7 @@ const runtimeDependencies = (
secretStoreLayer = emptySecretStoreLayer,
) =>
Layer.mergeAll(
+ ManagedPolicy.layerTest(),
Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
Layer.succeed(HttpClient.HttpClient, httpClient),
relayClientLayer,
diff --git a/apps/server/src/cloud/ManagedEndpointRuntime.ts b/apps/server/src/cloud/ManagedEndpointRuntime.ts
index de4ad782cef..09211160242 100644
--- a/apps/server/src/cloud/ManagedEndpointRuntime.ts
+++ b/apps/server/src/cloud/ManagedEndpointRuntime.ts
@@ -20,6 +20,8 @@ import * as ChildProcess from "effect/process/ChildProcess";
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
+import * as ManagedLimits from "../policy/managedLimits.ts";
+import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
export type CloudManagedEndpointRuntimeStatus =
| {
@@ -192,6 +194,8 @@ export const make = Effect.gen(function* () {
const relayClient = yield* RelayClient.RelayClient;
const secrets = yield* ServerSecretStore.ServerSecretStore;
const httpClient = HttpClient.withScope(yield* HttpClient.HttpClient);
+ // Without T3 Connect no connector ever runs, whoever asks for one.
+ const connectAllowed = ManagedLimits.allowsConnect(yield* ManagedPolicy.ManagedPolicy);
const activeRef = yield* Ref.make<ActiveConnector | null>(null);
const desiredConfigRef = yield* Ref.make<RelayManagedEndpointRuntimeConfig | null>(null);
const recoveryRequests = yield* Queue.sliding<RelayManagedEndpointRuntimeConfig>(1);
@@ -739,9 +743,10 @@ export const make = Effect.gen(function* () {
});
const applyConfig = Effect.fn("CloudManagedEndpointRuntime.applyConfig")(
- (config: RelayManagedEndpointRuntimeConfig | null) =>
+ (requested: RelayManagedEndpointRuntimeConfig | null) =>
reconcileSemaphore.withPermits(1)(
Effect.gen(function* () {
+ const config = connectAllowed ? requested : null;
// Keep backoff when recovery returns the same tunnel/token, or every recovery respawns a crash loop.
const desired = yield* Ref.get(desiredConfigRef);
const unchanged =
diff --git a/apps/server/src/cloud/http.test.ts b/apps/server/src/cloud/http.test.ts
index 094204561cb..675d4fe9da8 100644
--- a/apps/server/src/cloud/http.test.ts
+++ b/apps/server/src/cloud/http.test.ts
@@ -36,6 +36,7 @@ import * as CloudLink from "./CloudLink.ts";
import * as ConnectHttp from "./http.ts";
import * as ConnectReachability from "./ConnectReachability.ts";
import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
+import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
const DESKTOP_BOOTSTRAP_TOKEN = "test-desktop-bootstrap-token";
const NON_LOOPBACK_ORIGIN = "http://172.24.162.233:3773";
@@ -81,6 +82,7 @@ const layerLinkProofRoutes = HttpApiBuilder.layer(LinkProofTestApi).pipe(
),
Layer.provide(EnvironmentAuth.layer),
Layer.provide([
+ ManagedPolicy.layerTest(),
SqlitePersistence.layerMemory,
ServerEnvironment.layerIdentity,
Layer.mock(ServerEnvironment.ServerEnvironment)({
diff --git a/apps/server/src/cloud/http.ts b/apps/server/src/cloud/http.ts
index 52612f22825..857cb235f26 100644
--- a/apps/server/src/cloud/http.ts
+++ b/apps/server/src/cloud/http.ts
@@ -16,6 +16,7 @@ import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
import { requireEnvironmentScope } from "../auth/http.ts";
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
+import * as ManagedLimits from "../policy/managedLimits.ts";
import * as CloudLink from "./CloudLink.ts";
import * as ConnectReachability from "./ConnectReachability.ts";
import type { RelayRequestError } from "./relayResponse.ts";
@@ -66,6 +67,8 @@ const connectErrorCases = {
CloudLinkProofRejectedError: unauthorized,
CloudLinkProofReplayedError: conflict,
CloudLinkTunnelSupersededError: conflict,
+ ManagedPolicyRefusedError: (error: ManagedLimits.ManagedPolicyRefusedError) =>
+ Effect.fail(new EnvironmentHttpForbiddenError({ message: error.message })),
CloudLinkInternalError: (error: CloudLink.CloudLinkInternalError) =>
internalServerError(error, error.cause),
RelayRequestError: relayFailure,
@@ -74,6 +77,7 @@ const connectErrorCases = {
type ConnectFailure =
| Exclude<CloudLink.CloudLinkError, CloudLink.CloudLinkEndpointUnavailableError>
| EnvironmentAuth.ServerAuthInternalError
+ | ManagedLimits.ManagedPolicyRefusedError
| RelayRequestError;
const toHttpError = <A, R>(effect: Effect.Effect<A, ConnectFailure, R>) =>
diff --git a/apps/server/src/cloud/relayTracing.test.ts b/apps/server/src/cloud/relayTracing.test.ts
new file mode 100644
index 00000000000..34fcaa74bc6
--- /dev/null
+++ b/apps/server/src/cloud/relayTracing.test.ts
@@ -0,0 +1,44 @@
+import * as NodeServices from "@effect/platform-node/NodeServices";
+import { assert, it } from "@effect/vitest";
+import type { ManagedPolicyDocument } from "@t3tools/contracts";
+import * as RelayTracing from "@t3tools/shared/relayTracing";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+import * as Option from "effect/Option";
+import { FetchHttpClient } from "effect/http";
+
+import * as ServerConfig from "../config.ts";
+import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
+import { relayLayer } from "./relayTracing.ts";
+
+const tracesTo = (policy?: ManagedPolicyDocument) =>
+ Effect.service(RelayTracing.RelayClientTracer).pipe(
+ Effect.provide(
+ relayLayer(
+ { serviceName: "t3code-server", runtime: "node", client: "environment-server" },
+ { tracesUrl: "https://traces.example.com", tracesDataset: "relay", tracesToken: "token" },
+ ).pipe(
+ Layer.provide(ManagedPolicy.layerTest(policy)),
+ Layer.provide(
+ ServerConfig.layerTest(process.cwd(), { prefix: "t3-relay-tracing-" }).pipe(
+ Layer.provide(NodeServices.layer),
+ ),
+ ),
+ Layer.provide(FetchHttpClient.layer),
+ ),
+ ),
+ Effect.map(Option.isSome),
+ );
+
+it.effect("a policy with telemetry off stops relay tracing to T3 Connect", () =>
+ Effect.gen(function* () {
+ assert.isTrue(yield* tracesTo());
+ assert.isFalse(
+ yield* tracesTo({
+ schemaVersion: 1,
+ organization: "Example Corp",
+ limits: { telemetry: false },
+ }),
+ );
+ }),
+);
diff --git a/apps/server/src/cloud/relayTracing.ts b/apps/server/src/cloud/relayTracing.ts
index 13a96db1320..c31c6b26911 100644
--- a/apps/server/src/cloud/relayTracing.ts
+++ b/apps/server/src/cloud/relayTracing.ts
@@ -7,18 +7,28 @@ import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as ServerConfig from "../config.ts";
+import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
import { resolveRelayClientTracingConfig } from "./publicConfig.ts";
const relayClientTracingConfig = resolveRelayClientTracingConfig();
-const relayLayer = (resource: Omit<RelayTracing.RelayClientTracingResource, "serviceInstanceId">) =>
+/** Relay traces leave the machine for T3 Connect, so a policy with `telemetry: false` stops them. */
+export const relayLayer = (
+ resource: Omit<RelayTracing.RelayClientTracingResource, "serviceInstanceId">,
+ tracingConfig = relayClientTracingConfig,
+) =>
Layer.unwrap(
- Effect.map(ServerConfig.ServerConfig, (config) =>
- RelayTracing.layer(relayClientTracingConfig, {
- ...resource,
- serviceInstanceId: processServiceInstanceId(config.otelEnvironment.resourceAttributes),
- }),
- ),
+ Effect.gen(function* () {
+ const config = yield* ServerConfig.ServerConfig;
+ const policy = yield* ManagedPolicy.ManagedPolicy;
+ return RelayTracing.layer(
+ ManagedPolicy.deniedBy(policy, "telemetry") === undefined ? tracingConfig : null,
+ {
+ ...resource,
+ serviceInstanceId: processServiceInstanceId(config.otelEnvironment.resourceAttributes),
+ },
+ );
+ }),
);
export const layerHeadlessRelayClient = relayLayer({
diff --git a/apps/server/src/cloud/selfUpdate.test.ts b/apps/server/src/cloud/selfUpdate.test.ts
index 1e3157adfff..8070ea2af73 100644
--- a/apps/server/src/cloud/selfUpdate.test.ts
+++ b/apps/server/src/cloud/selfUpdate.test.ts
@@ -1,10 +1,12 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
+import type { ManagedPolicyDocument } from "@t3tools/contracts";
import * as HostProcess from "@t3tools/shared/HostProcess";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Fiber from "effect/Fiber";
+import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Stream from "effect/Stream";
import * as TestClock from "effect/testing/TestClock";
@@ -14,6 +16,7 @@ import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
import packageJson from "../../package.json" with { type: "json" };
import * as ServerConfig from "../config.ts";
import * as DesktopAppUpdate from "../desktopUpdate/DesktopAppUpdate.ts";
+import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
import * as ProcessRunner from "../processRunner.ts";
import * as ServiceLauncherClient from "./serviceLauncherClient.ts";
import { SERVICE_LAUNCHER_PROTOCOL } from "./serviceProtocol.ts";
@@ -26,6 +29,7 @@ interface HarnessOptions {
readonly beforeDownload?: Effect.Effect<void>;
readonly requestUpdate?: ServiceLauncherClient.ServiceLauncherClient["Service"]["requestUpdate"];
readonly desktopAppUpdate?: DesktopAppUpdate.DesktopAppUpdate["Service"];
+ readonly policy?: ManagedPolicyDocument;
}
const archiveBytes = new TextEncoder().encode("not really a tarball");
@@ -122,7 +126,12 @@ const makeHarness = Effect.fn("test.make_self_update_harness")(function* (
Effect.provideService(HttpClient.HttpClient, releaseHttpClient(order, options.beforeDownload)),
Effect.provideService(HostProcess.Platform, "linux"),
Effect.provideService(HostProcess.Architecture, "x64"),
- Effect.provide(ServerConfig.layer({ ...config, mode: options.mode ?? "web" })),
+ Effect.provide(
+ Layer.merge(
+ ServerConfig.layer({ ...config, mode: options.mode ?? "web" }),
+ ManagedPolicy.layerTest(options.policy),
+ ),
+ ),
);
return { selfUpdate, order };
});
@@ -143,6 +152,50 @@ it.layer(NodeServices.layer)("server self update", (it) => {
}),
);
+ it.effect("refuses every update when the managed policy turns updates off", () =>
+ Effect.gen(function* () {
+ const policy: ManagedPolicyDocument = {
+ schemaVersion: 1,
+ organization: "Example Corp",
+ limits: { updates: { mode: "off" } },
+ };
+ const service = yield* makeHarness({ policy });
+ const desktop = yield* makeHarness({
+ mode: "desktop",
+ policy,
+ desktopAppUpdate: {
+ available: true,
+ run: () => Effect.die("unexpected desktop app update run"),
+ commit: () => Effect.never,
+ },
+ });
+ for (const harness of [service, desktop]) {
+ expect(
+ (yield* harness.selfUpdate.update({ targetVersion: "1.1.0" }).pipe(Effect.flip)).reason,
+ ).toBe("Example Corp manages T3 Code updates.");
+ }
+ expect([...service.order, ...desktop.order]).toEqual([]);
+ }),
+ );
+
+ it.effect("lets a user start an update, but only to stable without nightly", () =>
+ Effect.gen(function* () {
+ const { selfUpdate, order } = yield* makeHarness({
+ policy: {
+ schemaVersion: 1,
+ organization: "Example Corp",
+ limits: { updates: { mode: "auto", allowNightly: false } },
+ },
+ });
+ expect(
+ (yield* selfUpdate.update({ targetVersion: "1.2.0-nightly.20261028.1" }).pipe(Effect.flip))
+ .reason,
+ ).toBe("Example Corp manages T3 Code updates. Only stable releases can be installed.");
+ expect(order).toEqual([]);
+ expect((yield* selfUpdate.update({ targetVersion: "1.1.0" })).updateId).toBe("launcher-id");
+ }),
+ );
+
it.effect("delegates desktop-managed updates to the desktop app when available", () =>
Effect.gen(function* () {
const stages: string[] = [];
diff --git a/apps/server/src/cloud/selfUpdate.ts b/apps/server/src/cloud/selfUpdate.ts
index d72c5e9218d..67e3e1f9413 100644
--- a/apps/server/src/cloud/selfUpdate.ts
+++ b/apps/server/src/cloud/selfUpdate.ts
@@ -20,12 +20,18 @@ import * as Queue from "effect/Queue";
import * as Stream from "effect/Stream";
import { HttpClient } from "effect/http";
-import { CLI_RELEASE_BASE_URL_ENV, crossesReleaseTrack } from "@t3tools/shared/cliRelease";
+import {
+ CLI_RELEASE_BASE_URL_ENV,
+ cliReleaseChannelOf,
+ crossesReleaseTrack,
+} from "@t3tools/shared/cliRelease";
import packageJson from "../../package.json" with { type: "json" };
import * as ServerConfig from "../config.ts";
import * as DesktopAppUpdate from "../desktopUpdate/DesktopAppUpdate.ts";
import { databaseMigrationHead } from "../persistence/databaseMigrationHead.ts";
+import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
+import { managedUpdateRefusal } from "../policy/managedUpdates.ts";
import * as ProcessRunner from "../processRunner.ts";
import {
ensurePinnedRuntimeInstalled,
@@ -117,6 +123,7 @@ export function trackSwitchBlockReason(input: {
export const make = Effect.fn("cloud.server_self_update.make")(function* () {
const serverConfig = yield* ServerConfig.ServerConfig;
const desktopAppUpdate = yield* DesktopAppUpdate.DesktopAppUpdate;
+ const policy = yield* ManagedPolicy.ManagedPolicy;
const launcher = yield* ServiceLauncherClient.ServiceLauncherClient;
const runner = yield* ProcessRunner.ProcessRunner;
const fs = yield* FileSystem.FileSystem;
@@ -151,6 +158,13 @@ export const make = Effect.fn("cloud.server_self_update.make")(function* () {
const update: ServerSelfUpdate["Service"]["update"] = Effect.fn(
"cloud.server_self_update.update",
)(function* (input, reportProgress = () => Effect.void, onHandoffAccepted = () => Effect.void) {
+ const policyRefusal = managedUpdateRefusal(
+ policy.document,
+ capability === "boot-service" ? cliReleaseChannelOf(input.targetVersion.trim()) : undefined,
+ );
+ if (policyRefusal !== undefined) {
+ return yield* failWith(policyRefusal);
+ }
if (capability === "desktop-managed") {
const unsafeCrossing = input.channel === undefined ? null : crossesTrackUnsafely(input);
if (unsafeCrossing !== null) return yield* failWith(unsafeCrossing);
diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts
index e684316f48d..bcfc5c377ae 100644
--- a/apps/server/src/mcp/McpHttpServer.ts
+++ b/apps/server/src/mcp/McpHttpServer.ts
@@ -196,6 +196,7 @@ const makeMcpAuthMiddleware = Effect.gen(function* () {
const registry = yield* McpSessionRegistry.McpSessionRegistry;
const clients = yield* Effect.serviceOption(McpClientAuthenticator);
const serverSettings = yield* ServerSettings.ServerSettingsService;
+ const runtimeModeCeiling = serverSettings.managedPolicy?.limits?.maxRuntimeMode;
const linksEnabled = serverSettings.getSettings.pipe(
Effect.map((settings) => settings.linkedEnvironmentsEnabled),
Effect.orElseSucceed(() => false),
@@ -222,8 +223,9 @@ const makeMcpAuthMiddleware = Effect.gen(function* () {
offerOAuth: Option.isSome(clients) && !looksLikeProviderToken(token),
});
}
- const limited = withModeLimit(invocation, request);
- if (limited === undefined) return invalidModeLimit;
+ const asked = withModeLimit(invocation, request);
+ if (asked === undefined) return invalidModeLimit;
+ const limited = McpInvocationContext.withRuntimeModeCeiling(asked, runtimeModeCeiling);
const linkedEnvironments = yield* linksEnabled;
if (limited.client?.linked === true && !linkedEnvironments) return linkedEnvironmentsOff;
return yield* httpEffect.pipe(
diff --git a/apps/server/src/mcp/McpInvocationContext.test.ts b/apps/server/src/mcp/McpInvocationContext.test.ts
index 94059d4fd8c..96c71fcd773 100644
--- a/apps/server/src/mcp/McpInvocationContext.test.ts
+++ b/apps/server/src/mcp/McpInvocationContext.test.ts
@@ -63,3 +63,35 @@ it.effect("refuses thread-owned capabilities to a caller signed in from outside
expect(error.threadId).toBeUndefined();
});
});
+
+it("acts at an administrator's ceiling for a client approved above it", () => {
+ const scope = (
+ access: McpInvocationContext.McpClientCaller["access"],
+ narrowedTo?: McpInvocationContext.ClientModes,
+ ): McpInvocationContext.McpInvocationScope => ({
+ environmentId: EnvironmentId.make("environment-1"),
+ requestNamespace: "client:session-1",
+ thread: undefined,
+ client: { sessionId: "session-1", label: "Claude Code", access, narrowedTo },
+ capabilities: new Set(["orchestration"]),
+ issuedAt: 1,
+ });
+ const modes = (invocation: McpInvocationContext.McpInvocationScope, ceiling?: "auto") =>
+ McpInvocationContext.clientModeCeiling(
+ McpInvocationContext.withRuntimeModeCeiling(invocation, ceiling).client,
+ );
+
+ expect(modes(scope("full-access"), "auto")).toEqual({
+ runtimeMode: "auto",
+ interactionMode: "default",
+ });
+ // A narrower request and the approved mode still win below the ceiling.
+ expect(
+ modes(
+ scope("full-access", { runtimeMode: "approval-required", interactionMode: "plan" }),
+ "auto",
+ ),
+ ).toEqual({ runtimeMode: "approval-required", interactionMode: "plan" });
+ expect(modes(scope("auto-accept-edits"), "auto").runtimeMode).toBe("auto-accept-edits");
+ expect(modes(scope("full-access")).runtimeMode).toBe("full-access");
+});
diff --git a/apps/server/src/mcp/McpInvocationContext.ts b/apps/server/src/mcp/McpInvocationContext.ts
index 5ce9669bc4d..181ac3a9cfb 100644
--- a/apps/server/src/mcp/McpInvocationContext.ts
+++ b/apps/server/src/mcp/McpInvocationContext.ts
@@ -96,6 +96,31 @@ export const clientModeCeiling = (client: McpClientCaller | undefined): ClientMo
};
};
+/**
+ * A client approved above an administrator's runtime-mode ceiling acts as if it had narrowed
+ * itself to the ceiling, so what it starts and schedules is not refused for a mode it never chose.
+ */
+export const withRuntimeModeCeiling = (
+ scope: McpInvocationScope,
+ ceiling: RuntimeMode | undefined,
+): McpInvocationScope => {
+ if (ceiling === undefined || scope.client === undefined) return scope;
+ const asked = scope.client.narrowedTo;
+ return {
+ ...scope,
+ client: {
+ ...scope.client,
+ narrowedTo: {
+ runtimeMode:
+ asked !== undefined && runtimeModeRank[asked.runtimeMode] < runtimeModeRank[ceiling]
+ ? asked.runtimeMode
+ : ceiling,
+ interactionMode: asked?.interactionMode ?? "default",
+ },
+ },
+ };
+};
+
/** Thread callers default to their own thread; client callers need thread for tools that act as the caller. */
export interface McpInvocationScope {
readonly environmentId: EnvironmentId;
diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts
index b124a03ea2c..e9fc08dcaac 100644
--- a/apps/server/src/mcp/OrchestratorMcpService.ts
+++ b/apps/server/src/mcp/OrchestratorMcpService.ts
@@ -263,10 +263,13 @@ function scheduledTaskSummary(task: ScheduledTask, mayRun: boolean): Orchestrato
schedule: task.schedule,
nextRunAt: task.nextRunAt,
lastRunStatus: task.lastRunStatus,
- ...(task.webhook?.url == null || !mayRun ? {} : { webhookUrl: task.webhook.url }),
+ ...(task.webhook?.url == null || !mayRun || task.blockedByPolicy !== undefined
+ ? {}
+ : { webhookUrl: task.webhook.url }),
...(task.webhook === undefined
? {}
: { webhookSignature: task.webhook.hasSecret ? "set" : "none" }),
+ ...(task.blockedByPolicy === undefined ? {} : { blockedByPolicy: task.blockedByPolicy }),
};
}
diff --git a/apps/server/src/mcp/threadAccess.ts b/apps/server/src/mcp/threadAccess.ts
index ca8b373ba92..d3fa0feda0d 100644
--- a/apps/server/src/mcp/threadAccess.ts
+++ b/apps/server/src/mcp/threadAccess.ts
@@ -47,7 +47,8 @@ export const unavailable = () =>
export const dispatchFailure = (
error: OrchestratorV2Error | ThreadManagement.ThreadManagementProviderInstanceDisabledError,
) =>
- error._tag === "ThreadManagementProviderInstanceDisabledError"
+ error._tag === "ThreadManagementProviderInstanceDisabledError" ||
+ error._tag === "OrchestratorRuntimeModeAboveCeilingError"
? new OrchestratorMcpFailure({ code: "invalid_request", message: error.message })
: (error._tag === "OrchestratorDispatchError" ||
error._tag === "OrchestratorCommandRejectedError") &&
diff --git a/apps/server/src/mcp/toolkits/project/handlers.test.ts b/apps/server/src/mcp/toolkits/project/handlers.test.ts
index 748234387cf..4dd7a995a92 100644
--- a/apps/server/src/mcp/toolkits/project/handlers.test.ts
+++ b/apps/server/src/mcp/toolkits/project/handlers.test.ts
@@ -10,6 +10,7 @@ import {
type ModelSelection,
type RuntimeMode,
type OrchestrationV2ThreadShell,
+ ThreadId,
} from "@t3tools/contracts";
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import * as NodeServices from "@effect/platform-node/NodeServices";
@@ -23,6 +24,7 @@ import * as Option from "effect/Option";
import * as Stream from "effect/Stream";
import * as DocumentText from "../../../provider/DocumentText.ts";
+import { OrchestratorRuntimeModeAboveCeilingError } from "../../../orchestration-v2/Orchestrator.ts";
import * as ThreadLaunch from "../../../orchestration-v2/ThreadLaunchService.ts";
import * as ThreadManagement from "../../../orchestration-v2/ThreadManagementService.ts";
import * as ServerConfig from "../../../config.ts";
@@ -49,6 +51,8 @@ const clientLaunchHarness = (input: {
readonly workspaceRoot?: string;
readonly checkWorktreeBase?: ThreadLaunch.ThreadLaunchService["Service"]["checkWorktreeBase"];
readonly webOrigin?: string;
+ /** The orchestrator refuses the new thread's mode, as under a managed ceiling. */
+ readonly refusedByCeiling?: true;
}) => {
const projectId = ProjectId.make("project:client-target");
const modelSelection = {
@@ -111,6 +115,23 @@ const clientLaunchHarness = (input: {
checkWorktreeBase: input.checkWorktreeBase ?? (() => Effect.void),
launch: (launch) => {
input.launched.push(launch);
+ if (input.refusedByCeiling) {
+ return Effect.fail(
+ new ThreadLaunch.ThreadLaunchError({
+ operation: "create-thread",
+ commandId: launch.commandId,
+ projectId: launch.projectId,
+ cause: new OrchestratorRuntimeModeAboveCeilingError({
+ commandId: launch.commandId,
+ threadId: launch.threadId ?? ThreadId.make("thread:refused"),
+ refused: "mode",
+ runtimeMode: launch.runtimeMode,
+ maxRuntimeMode: "approval-required",
+ organization: "Example Corp",
+ }),
+ }),
+ );
+ }
return Effect.succeed({
threadId: launch.threadId,
projection: {
@@ -168,9 +189,10 @@ it.effect(
readonly targeted?: false;
readonly overrideModel?: ModelSelection;
readonly webOrigin?: string;
+ readonly refusedByCeiling?: true;
},
) {
- const { targeted, overrideModel, webOrigin, ...input } = params;
+ const { targeted, overrideModel, webOrigin, refusedByCeiling, ...input } = params;
const launched: Array<ThreadLaunch.ThreadLaunchInput> = [];
const { projectId, modelSelection, dependencies } = clientLaunchHarness({
runtimeModeCeiling,
@@ -178,6 +200,7 @@ it.effect(
launched,
...(overrideModel === undefined ? {} : { overrideModel }),
...(webOrigin === undefined ? {} : { webOrigin }),
+ ...(refusedByCeiling === undefined ? {} : { refusedByCeiling }),
});
const toolkit = yield* ProjectToolkit.pipe(
Effect.provide(
@@ -241,6 +264,16 @@ it.effect(
overrideModel,
});
expect(fromSettings.launched[0]?.modelSelection).toEqual(overrideModel);
+
+ // An administrator's ceiling the orchestrator enforces is named, not reported as unavailable.
+ const managed = yield* launchWith("full-access", "full-access", {
+ title: "Fix",
+ refusedByCeiling: true,
+ });
+ expect(managed.result).toMatchObject({
+ code: "invalid_request",
+ message: "Example Corp limits threads to Supervised.",
+ });
}),
);
diff --git a/apps/server/src/mcp/toolkits/project/handlers.ts b/apps/server/src/mcp/toolkits/project/handlers.ts
index 7253bcedb00..59399c7febd 100644
--- a/apps/server/src/mcp/toolkits/project/handlers.ts
+++ b/apps/server/src/mcp/toolkits/project/handlers.ts
@@ -10,6 +10,8 @@ import * as Effect from "effect/Effect";
import * as Hex from "effect/encoding/Hex";
import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
+import * as Schema from "effect/Schema";
+import { OrchestratorRuntimeModeAboveCeilingError } from "../../../orchestration-v2/Orchestrator.ts";
import * as ThreadLaunch from "../../../orchestration-v2/ThreadLaunchService.ts";
import * as ThreadMessageIntake from "../../../orchestration-v2/ThreadMessageIntake.ts";
import * as Claims from "../../../orchestration-v2/AttachmentClaims.ts";
@@ -30,6 +32,8 @@ import * as McpToolAccess from "../../McpToolAccess.ts";
import { newCommandId, readCaller, resolveProjectId, unavailable } from "../../threadAccess.ts";
import { ProjectToolkit } from "./tools.ts";
+const isAboveCeilingError = Schema.is(OrchestratorRuntimeModeAboveCeilingError);
+
function projectFailure(error: Project.ProjectServiceError) {
if (error._tag === "ProjectOperationError") return unavailable();
const message =
@@ -257,6 +261,13 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
message: error.message,
});
}
+ // The administrator's ceiling refuses the mode; say so rather than "unavailable".
+ if (error._tag === "ThreadLaunchError" && isAboveCeilingError(error.cause)) {
+ return new OrchestratorMcpFailure({
+ code: "invalid_request",
+ message: error.cause.message,
+ });
+ }
return unavailable();
}),
);
diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts
index fd5951a148b..01936cb122a 100644
--- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts
@@ -1037,3 +1037,70 @@ describe("AntigravityAdapterV2 subagent reads", () => {
}).pipe(Effect.provide(layerSession), Effect.scoped),
);
});
+
+describe("AntigravityAdapterV2 runtime mode ceiling", () => {
+ const modesSetFor = (pickedMode: string) =>
+ Effect.gen(function* () {
+ const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
+ const path = yield* Path.Path;
+ const crypto = yield* Crypto.Crypto;
+ const mockAgentPath = yield* path.fromFileUrl(
+ new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
+ );
+ type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"];
+ const modesSet: Array<string> = [];
+ const instanceId = ProviderInstanceId.make("antigravity-ceiling-test");
+ const adapter = yield* makeAntigravityAdapterV2({
+ instanceId,
+ selfInvocation: yield* resolveSelfInvocation(),
+ makeRuntime: (input) =>
+ makeAntigravityAcpRuntime({
+ ...input,
+ childProcessSpawner,
+ spawn: {
+ command: process.execPath,
+ args: [mockAgentPath],
+ cwd: input.cwd,
+ env: { T3_ACP_ANTIGRAVITY: "1" },
+ },
+ }).pipe(
+ Effect.provideService(Crypto.Crypto, crypto),
+ Effect.map((runtime): RuntimeService => ({
+ ...runtime,
+ setMode: (modeId) =>
+ Effect.sync(() => {
+ modesSet.push(modeId);
+ }).pipe(Effect.andThen(runtime.setMode(modeId))),
+ })),
+ ),
+ withProcess: (_stop, task) => task,
+ // @effect-diagnostics-next-line effectSucceedWithVoid:off - This optional result requires undefined, not the wider void type.
+ defaultModel: Effect.succeed(undefined),
+ });
+ const threadId = ThreadId.make("thread-antigravity-ceiling");
+ yield* adapter.openSession({
+ threadId,
+ providerSessionId: ProviderSessionId.make("provider-session-antigravity-ceiling"),
+ modelSelection: {
+ instanceId,
+ model: "gemini-test-low",
+ options: [{ id: "_t3/session-mode", value: pickedMode }],
+ },
+ runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
+ runtimeMode: "approval-required",
+ interactionMode: "default",
+ cwd: process.cwd(),
+ maxRuntimeMode: "auto-accept-edits",
+ }),
+ });
+ return modesSet;
+ }).pipe(Effect.provide(layerSession), Effect.scoped);
+
+ it.effect("does not apply a picked session mode above the policy ceiling", () =>
+ Effect.gen(function* () {
+ assert.deepEqual(yield* modesSetFor("yolo"), ["default"]);
+ // A mode under the ceiling is still the user's to pick.
+ assert.deepEqual(yield* modesSetFor("auto_edit"), ["default", "auto_edit"]);
+ }),
+ );
+});
diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts
index bc842d2ec97..9d29ef248b2 100644
--- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts
+++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts
@@ -20,6 +20,7 @@ import type { AntigravityAuth } from "../../provider/AntigravityAuth.ts";
import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
import {
antigravityPermissionMode,
+ antigravityRuntimeModeForSessionMode,
applyAntigravityAcpModelSelection,
buildAntigravityPrompt,
type AntigravityAcpRuntimeInput,
@@ -217,6 +218,7 @@ export function makeAntigravityAcpAdapterFlavor(
});
}),
sessionModeForPolicy: (policy) => antigravityPermissionMode(policy.runtimeMode),
+ runtimeModeForSessionMode: antigravityRuntimeModeForSessionMode,
clientFileSystem: {
readTextFile: (request, cwd) =>
readAntigravityClientTextFile({
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
index 8494c4cab78..356f4cbd1ef 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
@@ -831,6 +831,32 @@ describe("ClaudeAdapterV2 session permissions", () => {
destination: "session",
},
]);
+
+ // Under an administrator's ceiling a suggested mode switch is dropped; the rule stays.
+ const managed = ClaudeAdapterV2.permissionResultFromDecision({
+ toolName: "Edit",
+ decision: "acceptForSession",
+ toolInput: {},
+ toolUseID: "tool-2",
+ managedCeiling: true,
+ suggestions: [
+ { type: "setMode", mode: "acceptEdits", destination: "session" },
+ {
+ type: "addRules",
+ rules: [{ toolName: "Edit" }],
+ behavior: "allow",
+ destination: "session",
+ },
+ ],
+ });
+ assert.deepEqual(managed.behavior === "allow" ? managed.updatedPermissions : undefined, [
+ {
+ type: "addRules",
+ rules: [{ toolName: "Edit" }],
+ behavior: "allow",
+ destination: "session",
+ },
+ ]);
});
it("adds a whole-tool session rule when Claude offers no suggestion", () => {
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
index 48ed26517c2..06b645bb7c0 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
@@ -3421,6 +3421,8 @@ export function permissionResultFromDecision(input: {
readonly toolUseID: string;
readonly suggestions?: Parameters<CanUseTool>[2]["suggestions"];
readonly feedback?: string;
+ /** Under an administrator's ceiling, T3 Code's mode is the only one; Claude cannot switch it. */
+ readonly managedCeiling?: boolean;
}): PermissionResult {
if (input.decision === "accept" || input.decision === "acceptForSession") {
return {
@@ -3431,7 +3433,12 @@ export function permissionResultFromDecision(input: {
input.decision === "acceptForSession" ? "user_permanent" : "user_temporary",
...(input.decision === "acceptForSession"
? {
- updatedPermissions: toSessionPermissionUpdates(input.toolName, input.suggestions),
+ updatedPermissions: toSessionPermissionUpdates(
+ input.toolName,
+ input.managedCeiling === true
+ ? input.suggestions?.filter((suggestion) => suggestion.type !== "setMode")
+ : input.suggestions,
+ ),
}
: {}),
};
@@ -9854,6 +9861,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
...resolvedDecision,
toolInput,
toolUseID: callbackOptions.toolUseID,
+ managedCeiling: context.input.runtimePolicy.maxRuntimeMode !== undefined,
...(callbackOptions.suggestions === undefined
? {}
: { suggestions: callbackOptions.suggestions }),
diff --git a/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.test.ts
index d2c23e185ba..a6038be86cf 100644
--- a/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.test.ts
@@ -39,6 +39,7 @@ import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
import * as RuntimePolicy from "../RuntimePolicy.ts";
+import * as ServerSettings from "../../serverSettings.ts";
import { acpPermissionDisposition } from "@t3tools/provider-acp/server/clientPolicy";
import { acpCompletedTurnShouldTerminalizeTool } from "@t3tools/provider-acp/server/adapter";
import {
@@ -336,6 +337,7 @@ describe("Grok launch permission mode", () => {
}).pipe(
Effect.provide(
RuntimePolicy.layerFromProjectStore.pipe(
+ Layer.provide(ServerSettings.layerTest()),
Layer.provide(
Layer.mock(ProjectStore.ProjectStoreV2)({
get: () => Effect.die("the thread has a worktree"),
diff --git a/apps/server/src/orchestration-v2/CheckpointRollbackService.ts b/apps/server/src/orchestration-v2/CheckpointRollbackService.ts
index 385de626cfd..e0da0d9edeb 100644
--- a/apps/server/src/orchestration-v2/CheckpointRollbackService.ts
+++ b/apps/server/src/orchestration-v2/CheckpointRollbackService.ts
@@ -33,7 +33,7 @@ import { GIT_INDEX_LOCKED_DETAIL } from "../vcs/VcsProcess.ts";
import * as ProjectStore from "./ProjectStore.ts";
import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts";
-import { RuntimePolicyV2 } from "./RuntimePolicy.ts";
+import { RuntimePolicyAboveCeilingError, RuntimePolicyV2 } from "./RuntimePolicy.ts";
import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts";
export const ROLLBACK_FAILED_MESSAGE =
@@ -74,6 +74,7 @@ export class CheckpointRollbackExecutionError extends Schema.TaggedError<Checkpo
const isCheckpointRollbackExecutionError = Schema.is(CheckpointRollbackExecutionError);
const isVcsProcessExitError = Schema.is(VcsProcessExitError);
const isCheckpointRestoreError = Schema.is(CheckpointRestoreError);
+const isRuntimePolicyAboveCeilingError = Schema.is(RuntimePolicyAboveCeilingError);
/**
* The message clients see when a rollback fails. Only a held Git index lock
@@ -81,6 +82,7 @@ const isCheckpointRestoreError = Schema.is(CheckpointRestoreError);
* output, so they fall back to the generic message.
*/
export function rollbackFailureClientMessage(error: CheckpointRollbackExecutionError): string {
+ if (isRuntimePolicyAboveCeilingError(error.cause)) return error.cause.message;
const restoreCause = isCheckpointRestoreError(error.cause) ? error.cause.cause : undefined;
return isVcsProcessExitError(restoreCause) && restoreCause.detail === GIT_INDEX_LOCKED_DETAIL
? GIT_INDEX_LOCKED_DETAIL
diff --git a/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts b/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts
index bde3af2c2ae..2ac0b9d5a58 100644
--- a/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts
+++ b/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts
@@ -25,6 +25,7 @@ import * as Queue from "effect/Queue";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
+import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
import * as SecretRequests from "../secrets/SecretRequests.ts";
import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts";
import * as Scheduler from "../scheduling/Scheduler.ts";
@@ -331,6 +332,7 @@ it.effect.each(deliveries)(
}),
),
Layer.provide(Layer.mock(ThreadLaunchService.ThreadLaunchService)({})),
+ Layer.provide(ManagedPolicy.layerTest()),
Layer.provide(
Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({
namedProjectsRoot: "/projects",
diff --git a/apps/server/src/orchestration-v2/DispatchModeLimit.test.ts b/apps/server/src/orchestration-v2/DispatchModeLimit.test.ts
index ba371f10524..8d29240e0aa 100644
--- a/apps/server/src/orchestration-v2/DispatchModeLimit.test.ts
+++ b/apps/server/src/orchestration-v2/DispatchModeLimit.test.ts
@@ -1,16 +1,20 @@
import { assert, it } from "@effect/vitest";
import {
CommandId,
+ EventId,
+ MessageId,
ProjectId,
ProviderDriverKind,
ProviderInstanceId,
ThreadId,
} from "@t3tools/contracts";
+import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as SqlitePersistence from "../persistence/Sqlite.ts";
import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
import { DispatchModeLimit } from "./DispatchModeLimit.ts";
+import * as EventSink from "./EventSink.ts";
import * as Orchestrator from "./Orchestrator.ts";
import * as ProjectionStore from "./ProjectionStore.ts";
import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
@@ -136,3 +140,220 @@ it.layer(layerTest)("DispatchModeLimit", (it) => {
}),
);
});
+
+const layerPolicyDatabase = SqlitePersistence.layerMemory;
+const layerWithCeiling = Layer.mergeAll(
+ layerPolicyDatabase,
+ ProjectionStore.layer.pipe(Layer.provide(layerPolicyDatabase)),
+ ProviderReplayHarness.layerWithRegistry(
+ { name: "runtime-mode-ceiling" },
+ ProviderAdapterRegistry.layerFromAdapters([adapter]),
+ {
+ databaseLayer: layerPolicyDatabase,
+ runEffectWorker: false,
+ managedPolicy: {
+ schemaVersion: 1,
+ organization: "Example Corp",
+ limits: { maxRuntimeMode: "auto-accept-edits" },
+ },
+ },
+ ),
+);
+
+const sendMessage = (threadId: ThreadId, id: string) => ({
+ type: "message.dispatch" as const,
+ commandId: CommandId.make(`send:${id}`),
+ threadId,
+ messageId: MessageId.make(`message:${id}`),
+ text: id,
+ attachments: [],
+ dispatchMode: { type: "start_immediately" as const },
+ createdBy: "user" as const,
+ creationSource: "web" as const,
+});
+
+/** A thread that ran in full access before the policy arrived, as an import or an older build leaves it. */
+const raiseBehindPolicy = (threadId: ThreadId) =>
+ Effect.gen(function* () {
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
+ const sink = yield* EventSink.EventSinkV2;
+ yield* createThread(threadId);
+ const { thread } = yield* orchestrator.getThreadRecords(threadId, []);
+ yield* sink.write({
+ events: [
+ {
+ id: EventId.make(`event:raise-behind-policy:${threadId}`),
+ type: "thread.runtime-mode-updated",
+ threadId,
+ occurredAt: yield* DateTime.now,
+ payload: { ...thread, runtimeMode: "full-access" },
+ },
+ ],
+ });
+ });
+
+it.layer(layerWithCeiling)("runtime mode ceiling", (it) => {
+ it.effect("refuses the user's own thread and mode changes above the ceiling", () =>
+ Effect.gen(function* () {
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
+ const projections = yield* ProjectionStore.ProjectionStoreV2;
+ const threadId = ThreadId.make("thread:ceiling-user");
+ const create = {
+ type: "thread.create",
+ commandId: CommandId.make("create:ceiling-user:full"),
+ threadId,
+ projectId: ProjectId.make("project:dispatch-mode-limit"),
+ title: "Full",
+ modelSelection: { instanceId, model: "gpt-5" },
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: null,
+ createdBy: "user",
+ creationSource: "web",
+ } as const;
+ const refusedCreate = yield* orchestrator.dispatch(create).pipe(Effect.flip);
+ assert.ok(refusedCreate._tag === "OrchestratorRuntimeModeAboveCeilingError");
+ assert.equal(refusedCreate.refused, "mode");
+ assert.equal(refusedCreate.message, "Example Corp limits threads to Auto-accept edits.");
+ assert.isNull(yield* projections.getThreadShell(threadId));
+
+ yield* createThread(threadId);
+ const raise = yield* orchestrator
+ .dispatch({
+ type: "thread.runtime-mode.set",
+ commandId: CommandId.make("raise:ceiling-user"),
+ threadId,
+ runtimeMode: "auto",
+ })
+ .pipe(Effect.flip);
+ assert.equal(raise._tag, "OrchestratorRuntimeModeAboveCeilingError");
+ yield* orchestrator.dispatch({
+ type: "thread.runtime-mode.set",
+ commandId: CommandId.make("raise-to-ceiling:ceiling-user"),
+ threadId,
+ runtimeMode: "auto-accept-edits",
+ });
+ assert.equal((yield* projections.getThreadShell(threadId))?.runtimeMode, "auto-accept-edits");
+ }),
+ );
+
+ it.effect("narrows an MCP caller's limit to the ceiling inside the lock", () =>
+ Effect.gen(function* () {
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
+ const projections = yield* ProjectionStore.ProjectionStoreV2;
+ const threadId = ThreadId.make("thread:ceiling-mcp");
+ yield* createThread(threadId);
+ const fullAccessCaller = { runtimeMode: "full-access", interactionMode: "default" } as const;
+ const raise = yield* orchestrator
+ .dispatch({
+ type: "thread.runtime-mode.set",
+ commandId: CommandId.make("raise:ceiling-mcp"),
+ threadId,
+ runtimeMode: "full-access",
+ })
+ .pipe(Effect.provideService(DispatchModeLimit, fullAccessCaller), Effect.flip);
+ assert.equal(raise._tag, "OrchestratorRuntimeModeAboveCeilingError");
+
+ const raisedThreadId = ThreadId.make("thread:ceiling-mcp-raised");
+ yield* raiseBehindPolicy(raisedThreadId);
+ const rename = yield* orchestrator
+ .dispatch({
+ type: "thread.metadata.update",
+ commandId: CommandId.make("rename:ceiling-mcp"),
+ threadId: raisedThreadId,
+ title: "After",
+ })
+ .pipe(Effect.provideService(DispatchModeLimit, fullAccessCaller), Effect.flip);
+ assert.equal(rename._tag, "OrchestratorThreadAboveModeLimitError");
+ assert.equal((yield* projections.getThreadShell(raisedThreadId))?.title, "Before");
+ }),
+ );
+
+ it.effect("refuses turns on a thread above the ceiling until its mode is lowered", () =>
+ Effect.gen(function* () {
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
+ const projections = yield* ProjectionStore.ProjectionStoreV2;
+ const threadId = ThreadId.make("thread:ceiling-raised");
+ yield* raiseBehindPolicy(threadId);
+
+ const refused = yield* orchestrator
+ .dispatch(sendMessage(threadId, "first"))
+ .pipe(Effect.flip);
+ assert.ok(refused._tag === "OrchestratorRuntimeModeAboveCeilingError");
+ assert.equal(refused.refused, "turn");
+ assert.equal(
+ refused.message,
+ "Example Corp limits threads to Auto-accept edits. Switch this thread's mode to continue.",
+ );
+ assert.lengthOf((yield* orchestrator.getThreadRecords(threadId, ["runs"])).runs, 0);
+
+ // The user's own housekeeping and the way back down stay open.
+ yield* orchestrator.dispatch({
+ type: "thread.metadata.update",
+ commandId: CommandId.make("rename:ceiling-raised"),
+ threadId,
+ title: "After",
+ });
+ yield* orchestrator.dispatch({
+ type: "thread.runtime-mode.set",
+ commandId: CommandId.make("lower:ceiling-raised"),
+ threadId,
+ runtimeMode: "approval-required",
+ });
+ // Refusals record no receipt, so the same command goes through once the mode is lowered.
+ yield* orchestrator.dispatch(sendMessage(threadId, "first"));
+ assert.lengthOf((yield* orchestrator.getThreadRecords(threadId, ["runs"])).runs, 1);
+ assert.equal((yield* projections.getThreadShell(threadId))?.title, "After");
+ }),
+ );
+
+ it.effect("starts a queue that waited above the ceiling once the mode is lowered", () =>
+ Effect.gen(function* () {
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
+ const sink = yield* EventSink.EventSinkV2;
+ const threadId = ThreadId.make("thread:ceiling-queue");
+ yield* createThread(threadId);
+ yield* orchestrator.dispatch(sendMessage(threadId, "running"));
+ yield* orchestrator.dispatch({
+ ...sendMessage(threadId, "waiting"),
+ dispatchMode: { type: "queue_after_active" },
+ });
+ // The policy arrives with the thread above it and its first run ending.
+ const { thread, runs } = yield* orchestrator.getThreadRecords(threadId, ["runs"]);
+ const [running, waiting] = runs;
+ const occurredAt = yield* DateTime.now;
+ yield* sink.write({
+ events: [
+ {
+ id: EventId.make("event:ceiling-queue:raise"),
+ type: "thread.runtime-mode-updated",
+ threadId,
+ occurredAt,
+ payload: { ...thread, runtimeMode: "full-access" },
+ },
+ {
+ id: EventId.make("event:ceiling-queue:complete"),
+ type: "run.updated",
+ threadId,
+ runId: running!.id,
+ providerInstanceId: running!.providerInstanceId,
+ occurredAt,
+ payload: { ...running!, status: "completed" },
+ },
+ ],
+ });
+
+ yield* orchestrator.dispatch({
+ type: "thread.runtime-mode.set",
+ commandId: CommandId.make("lower:ceiling-queue"),
+ threadId,
+ runtimeMode: "approval-required",
+ });
+ const started = (yield* orchestrator.getThreadRecords(threadId, ["runs"])).runs.find(
+ (run) => run.id === waiting!.id,
+ );
+ assert.notEqual(started?.status, "queued");
+ }),
+ );
+});
diff --git a/apps/server/src/orchestration-v2/DispatchModeLimit.ts b/apps/server/src/orchestration-v2/DispatchModeLimit.ts
index 8d7c8797b6e..627806347c5 100644
--- a/apps/server/src/orchestration-v2/DispatchModeLimit.ts
+++ b/apps/server/src/orchestration-v2/DispatchModeLimit.ts
@@ -1,4 +1,10 @@
-import type { ProviderInteractionMode, RuntimeMode, ThreadId } from "@t3tools/contracts";
+import {
+ isRuntimeModeAbove,
+ type OrchestrationV2DomainEvent,
+ type ProviderInteractionMode,
+ type RuntimeMode,
+ type ThreadId,
+} from "@t3tools/contracts";
import * as Context from "effect/Context";
import type * as Ref from "effect/Ref";
@@ -22,20 +28,85 @@ export const DispatchModeLimit = Context.Reference<DispatchModeLimitValue | unde
{ defaultValue: () => undefined },
);
-const runtimeModeRank: Record<RuntimeMode, number> = {
- "approval-required": 0,
- "auto-accept-edits": 1,
- auto: 2,
- "full-access": 3,
-};
const interactionModeRank: Record<ProviderInteractionMode, number> = { plan: 0, default: 1 };
export const exceededDispatchModeLimit = (
limit: DispatchModes,
modes: DispatchModes,
): "runtime" | "interaction" | undefined =>
- runtimeModeRank[modes.runtimeMode] > runtimeModeRank[limit.runtimeMode]
+ isRuntimeModeAbove(modes.runtimeMode, limit.runtimeMode)
? "runtime"
: interactionModeRank[modes.interactionMode] > interactionModeRank[limit.interactionMode]
? "interaction"
: undefined;
+
+/** The administrator's `limits.maxRuntimeMode`, which applies to every caller, the user included. */
+export interface RuntimeModeCeiling {
+ readonly organization: string;
+ readonly maxRuntimeMode: RuntimeMode;
+}
+
+/** A caller's limit, lowered to the ceiling when the caller may otherwise go above it. */
+export const narrowToCeiling = <Limit extends DispatchModes>(
+ limit: Limit | undefined,
+ ceiling: RuntimeModeCeiling | undefined,
+): Limit | undefined =>
+ limit === undefined ||
+ ceiling === undefined ||
+ !isRuntimeModeAbove(limit.runtimeMode, ceiling.maxRuntimeMode)
+ ? limit
+ : { ...limit, runtimeMode: ceiling.maxRuntimeMode };
+
+export interface RuntimeModeCeilingRefusal {
+ readonly threadId: ThreadId;
+ readonly runtimeMode: RuntimeMode;
+ /** `mode`: a thread would be created in or switched to the mode. `turn`: a turn would run in it. */
+ readonly refused: "mode" | "turn";
+}
+
+/**
+ * What a planned command would do above the ceiling, judged by its events so every command that
+ * creates a thread, switches its mode, or starts or steers a turn is covered. `runtimeModes` holds
+ * the committed mode of each thread a planned run belongs to. Lowering a mode, and commands that
+ * start no work, stay open on a thread above the ceiling: they are how its user gets back under.
+ */
+export const runtimeModeCeilingRefusal = (
+ maxRuntimeMode: RuntimeMode,
+ events: ReadonlyArray<OrchestrationV2DomainEvent>,
+ runtimeModes: ReadonlyMap<ThreadId, RuntimeMode>,
+): RuntimeModeCeilingRefusal | undefined => {
+ const planned = new Map(runtimeModes);
+ for (const event of events) {
+ if (event.type === "thread.created" || event.type === "thread.runtime-mode-updated") {
+ const { runtimeMode } = event.payload;
+ planned.set(event.threadId, runtimeMode);
+ if (isRuntimeModeAbove(runtimeMode, maxRuntimeMode)) {
+ return { threadId: event.threadId, runtimeMode, refused: "mode" };
+ }
+ } else if (event.type === "run.created" || event.type === "run-attempt.created") {
+ const runtimeMode = planned.get(event.threadId);
+ if (runtimeMode !== undefined && isRuntimeModeAbove(runtimeMode, maxRuntimeMode)) {
+ return { threadId: event.threadId, runtimeMode, refused: "turn" };
+ }
+ }
+ }
+ return undefined;
+};
+
+/** Threads whose committed mode `runtimeModeCeilingRefusal` needs: those a planned run belongs to. */
+export const threadsStartingWork = (
+ events: ReadonlyArray<OrchestrationV2DomainEvent>,
+): ReadonlySet<ThreadId> => {
+ const created = new Set<ThreadId>();
+ const starting = new Set<ThreadId>();
+ for (const event of events) {
+ if (event.type === "thread.created") created.add(event.threadId);
+ else if (
+ (event.type === "run.created" || event.type === "run-attempt.created") &&
+ !created.has(event.threadId)
+ ) {
+ starting.add(event.threadId);
+ }
+ }
+ return starting;
+};
diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts
index 35e9a78c4cd..3734082d9f5 100644
--- a/apps/server/src/orchestration-v2/Orchestrator.ts
+++ b/apps/server/src/orchestration-v2/Orchestrator.ts
@@ -62,6 +62,7 @@ import {
orchestrationV2WorktreePending,
ProviderInstanceId,
ProviderInteractionMode,
+ isRuntimeModeAbove,
resolveProviderInstanceEnabled,
resolveProjectProviderInstanceEnabled,
type ProviderSessionId,
@@ -71,6 +72,7 @@ import {
ThreadId,
TurnItemId,
TrimmedNonEmptyString,
+ managedRuntimeModeCeilingMessage,
} from "@t3tools/contracts";
import { modelSelectionsEqual } from "@t3tools/shared/model";
import { recordThreadOpen } from "@t3tools/shared/paletteSearch";
@@ -138,7 +140,14 @@ import { withCommandMetrics } from "../observability/Metrics.ts";
import type { OrchestrationEffectRequestV2, PendingOrchestrationEffectV2 } from "./EffectOutbox.ts";
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts";
-import { DispatchModeLimit, exceededDispatchModeLimit } from "./DispatchModeLimit.ts";
+import {
+ DispatchModeLimit,
+ exceededDispatchModeLimit,
+ narrowToCeiling,
+ type RuntimeModeCeiling,
+ runtimeModeCeilingRefusal,
+ threadsStartingWork,
+} from "./DispatchModeLimit.ts";
import {
applyToProjection,
emptyProjection,
@@ -162,7 +171,7 @@ import * as RunExecutionService from "./RunExecutionService.ts";
import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts";
import { ProviderSwitchServiceV2 } from "./ProviderSwitchService.ts";
import { isAutomaticCompletionRun, queuedRunsInDeliveryOrder } from "./QueuedRunOrder.ts";
-import { RuntimePolicyV2 } from "./RuntimePolicy.ts";
+import { isRuntimePolicyAboveCeilingError, RuntimePolicyV2 } from "./RuntimePolicy.ts";
import {
endOrphanedNativeSubagent,
endRunlessRootTurns,
@@ -277,6 +286,32 @@ export class OrchestratorThreadAboveModeLimitError extends Schema.TaggedError<Or
}
}
+const isOrchestratorDispatchError = Schema.is(OrchestratorDispatchError);
+
+/** The ceiling refusal under however many dispatch errors wrapped it on the way out. */
+function runtimePolicyCeilingCause(error: unknown) {
+ let current = error;
+ while (isOrchestratorDispatchError(current)) current = current.cause;
+ return isRuntimePolicyAboveCeilingError(current) ? current : undefined;
+}
+
+export class OrchestratorRuntimeModeAboveCeilingError extends Schema.TaggedError<OrchestratorRuntimeModeAboveCeilingError>()(
+ "OrchestratorRuntimeModeAboveCeilingError",
+ {
+ commandId: CommandId,
+ threadId: ThreadId,
+ refused: Schema.Literals(["mode", "turn"]),
+ runtimeMode: RuntimeMode,
+ maxRuntimeMode: RuntimeMode,
+ organization: Schema.String,
+ },
+) {
+ override get message(): string {
+ const limit = managedRuntimeModeCeilingMessage(this.organization, this.maxRuntimeMode);
+ return this.refused === "turn" ? `${limit} Switch this thread's mode to continue.` : limit;
+ }
+}
+
export class OrchestratorCommandPreviouslyRejectedError extends Schema.TaggedError<OrchestratorCommandPreviouslyRejectedError>()(
"OrchestratorCommandPreviouslyRejectedError",
{
@@ -315,6 +350,7 @@ export const OrchestratorV2Error = Schema.Union([
OrchestratorCommandIdConflictError,
OrchestratorSubagentThreadReadOnlyError,
OrchestratorThreadAboveModeLimitError,
+ OrchestratorRuntimeModeAboveCeilingError,
]);
export type OrchestratorV2Error = typeof OrchestratorV2Error.Type;
@@ -1006,6 +1042,15 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
const runtimePolicy = yield* RuntimePolicyV2;
const threadForkService = yield* ThreadForkServiceV2;
const threadDispatch = yield* ThreadCommandExecutor.ThreadCommandExecutor;
+ // Read once: the policy is fixed for the server's life, and dispatch takes it as an input.
+ const { managedPolicy } = serverSettings;
+ const runtimeModeCeiling: RuntimeModeCeiling | undefined =
+ managedPolicy?.limits?.maxRuntimeMode === undefined
+ ? undefined
+ : {
+ organization: managedPolicy.organization,
+ maxRuntimeMode: managedPolicy.limits.maxRuntimeMode,
+ };
/** The driver when this provider runs `/goal` natively, else undefined. */
const goalDriverFor = Effect.fn("Orchestrator.goalDriverFor")(function* (
@@ -1573,6 +1618,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
if (usageLimitHoldsQueue(projection, queuedRun.providerInstanceId)) {
return;
}
+ // Waits without a hold: lowering the thread's mode starts the queue again.
+ if (isRuntimeModeAbove(projection.thread.runtimeMode, runtimeModeCeiling?.maxRuntimeMode)) {
+ return;
+ }
// Failed worktree creation would run queued work in the project checkout; wait for the user.
const failedRun = latestExecutedRun(projection.runs);
const failureClass =
@@ -4229,7 +4278,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
readonly interactionMode: ProviderInteractionMode;
},
) {
- const limit = yield* DispatchModeLimit;
+ const limit = narrowToCeiling(yield* DispatchModeLimit, runtimeModeCeiling);
const exceeded = limit === undefined ? undefined : exceededDispatchModeLimit(limit, modes);
if (limit === undefined || exceeded === undefined) return;
const refusal = {
@@ -4246,6 +4295,34 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
},
);
+ const refuseAboveRuntimeModeCeiling = Effect.fn(
+ "orchestrationV2.dispatch.refuseAboveRuntimeModeCeiling",
+ )(function* (
+ command: OrchestrationV2ServerCommand,
+ events: ReadonlyArray<OrchestrationV2DomainEvent>,
+ ) {
+ if (runtimeModeCeiling === undefined) return;
+ const runtimeModes = new Map<ThreadId, RuntimeMode>();
+ for (const threadId of threadsStartingWork(events)) {
+ const thread = yield* projectionStore.getThread(threadId).pipe(
+ Effect.catchTags({ ProjectionStoreThreadNotFoundError: () => Effect.succeed(null) }),
+ Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause })),
+ );
+ if (thread !== null) runtimeModes.set(threadId, thread.runtimeMode);
+ }
+ const refusal = runtimeModeCeilingRefusal(
+ runtimeModeCeiling.maxRuntimeMode,
+ events,
+ runtimeModes,
+ );
+ if (refusal === undefined) return;
+ return yield* new OrchestratorRuntimeModeAboveCeilingError({
+ commandId: command.commandId,
+ ...refusal,
+ ...runtimeModeCeiling,
+ });
+ });
+
const dispatchThreadFork = Effect.fn("orchestrationV2.dispatch.threadFork")(function* (
command: Extract<OrchestrationV2Command, { readonly type: "thread.fork" }>,
events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
@@ -13329,6 +13406,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
}
const plan = yield* dispatchOnce(command, sideChatIds).pipe(
+ Effect.tap((planned) => refuseAboveRuntimeModeCeiling(command, planned.events)),
Effect.filterOrFail(
(planned) =>
planned.events.length > 0 ||
@@ -13348,7 +13426,26 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
),
Effect.catch((cause) =>
Effect.gen(function* () {
- if (cause._tag === "OrchestratorThreadAboveModeLimitError") return yield* cause;
+ // Refusals depend on modes the user can change; a recorded rejection would block the retry.
+ if (
+ cause._tag === "OrchestratorThreadAboveModeLimitError" ||
+ cause._tag === "OrchestratorRuntimeModeAboveCeilingError"
+ ) {
+ return yield* cause;
+ }
+ // Resolving a turn's policy refuses the same way, from inside the decision.
+ const ceiling = runtimePolicyCeilingCause(cause);
+ if (ceiling !== undefined) {
+ const { threadId, runtimeMode, maxRuntimeMode, organization } = ceiling;
+ return yield* new OrchestratorRuntimeModeAboveCeilingError({
+ commandId: command.commandId,
+ threadId,
+ refused: "turn",
+ runtimeMode,
+ maxRuntimeMode,
+ organization,
+ });
+ }
const rejectedAt = yield* DateTime.now;
const receipt = yield* eventSink
.commitRejectedCommand({
@@ -13449,7 +13546,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
detail: committed.receipt.error ?? "Previously rejected.",
});
}
- if (command.type === "queue.resume" || command.type === "queued-run.start") {
+ if (
+ command.type === "queue.resume" ||
+ command.type === "queued-run.start" ||
+ (command.type === "thread.runtime-mode.set" && runtimeModeCeiling !== undefined)
+ ) {
yield* mapDispatchError(command)(
startNextQueuedRun(
command.threadId,
diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts
index 402b2eaf3e0..9a5ad6114e2 100644
--- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts
+++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts
@@ -690,15 +690,29 @@ export const layer: Layer.Layer<
const { isCurrentAttemptInStatus } = runControls;
// A side chat shares its parent's worktree; the turn that gets its context asks before acting.
- const resolvedRuntimePolicy = yield* runtimePolicy.resolve({
- thread:
- projection.thread.lineage.sideChat === true &&
- (sideChatHandoff !== undefined ||
- !projection.runs.some((previous) => previous.ordinal < run.ordinal))
- ? { ...projection.thread, runtimeMode: "approval-required" }
- : projection.thread,
- modelSelection: run.modelSelection,
- });
+ const resolvedPolicy = yield* runtimePolicy
+ .resolve({
+ thread:
+ projection.thread.lineage.sideChat === true &&
+ (sideChatHandoff !== undefined ||
+ !projection.runs.some((previous) => previous.ordinal < run.ordinal))
+ ? { ...projection.thread, runtimeMode: "approval-required" }
+ : projection.thread,
+ modelSelection: run.modelSelection,
+ })
+ .pipe(Effect.result);
+ if (resolvedPolicy._tag === "Failure") {
+ const error = resolvedPolicy.failure;
+ if (error._tag !== "RuntimePolicyAboveCeilingError") return yield* error;
+ yield* settleStartFailure({
+ signal: "runtime-mode-above-ceiling",
+ title: "Thread mode is above the policy limit",
+ error,
+ message: error.message,
+ });
+ return;
+ }
+ const resolvedRuntimePolicy = resolvedPolicy.success;
if (!(yield* isCurrentAttemptInStatus("starting"))) return;
const existingSessionProjection = projection.providerSessions.find(
(candidate) => candidate.id === providerSessionId,
diff --git a/apps/server/src/orchestration-v2/RestartContinuation.ts b/apps/server/src/orchestration-v2/RestartContinuation.ts
index 8741fb7bc59..20d110d335a 100644
--- a/apps/server/src/orchestration-v2/RestartContinuation.ts
+++ b/apps/server/src/orchestration-v2/RestartContinuation.ts
@@ -328,7 +328,8 @@ export const continueRestartedRun = Effect.fn("RestartContinuation.continueResta
restartContinuationOfRunId: input.sourceRunId,
})
.pipe(
- // Disabled instances cannot resume; still run success cleanup so delegated children recover without futile retries.
+ // Disabled instances, and threads above a policy ceiling, cannot resume; still run success
+ // cleanup so delegated children recover without futile retries.
Effect.catchTags({
ThreadManagementProviderInstanceDisabledError: (error) =>
Effect.logInfo("orchestration-v2.restart-continuation.instance-disabled", {
@@ -337,6 +338,11 @@ export const continueRestartedRun = Effect.fn("RestartContinuation.continueResta
projectId: error.projectId,
instanceId: error.instanceId,
}),
+ OrchestratorRuntimeModeAboveCeilingError: () =>
+ Effect.logInfo("orchestration-v2.restart-continuation.above-ceiling", {
+ threadId: input.threadId,
+ sourceRunId: input.sourceRunId,
+ }),
}),
);
},
diff --git a/apps/server/src/orchestration-v2/RuntimePolicy.test.ts b/apps/server/src/orchestration-v2/RuntimePolicy.test.ts
index d410be8ddf1..21647ef49bf 100644
--- a/apps/server/src/orchestration-v2/RuntimePolicy.test.ts
+++ b/apps/server/src/orchestration-v2/RuntimePolicy.test.ts
@@ -1,5 +1,6 @@
import { assert, it } from "@effect/vitest";
import {
+ type ManagedPolicySummary,
type ModelSelection,
type OrchestrationV2AppThread,
ProjectId,
@@ -14,6 +15,7 @@ import * as Layer from "effect/Layer";
import * as Stream from "effect/Stream";
import type { ProviderInstance } from "@t3tools/provider-core/server/driver";
+import * as ServerSettings from "../serverSettings.ts";
import * as ProviderInstanceRegistry from "../provider/ProviderInstanceRegistry.ts";
import * as ProjectStore from "./ProjectStore.ts";
import * as RuntimePolicy from "./RuntimePolicy.ts";
@@ -73,38 +75,42 @@ const providerInstanceFor = (instanceId: ProviderInstanceId) =>
},
}) as ProviderInstance;
-const layerTest = RuntimePolicy.layerFromProjectStore.pipe(
- Layer.provide(
- Layer.succeed(ProviderInstanceRegistry.ProviderInstanceRegistry, {
- getInstance: (instanceId) => Effect.succeed(providerInstanceFor(instanceId)),
- listInstances: Effect.succeed([]),
- listUnavailable: Effect.succeed([]),
- streamChanges: Stream.empty,
- subscribeChanges: Effect.never,
- }),
- ),
- Layer.provide(
- Layer.mock(ProjectStore.ProjectStoreV2)({
- get: () =>
- Effect.succeedSome({
- projectId,
- title: "Project",
- workspaceRoot: "/project-root",
- defaultModelSelection: null,
- defaultThreadEnvMode: null,
- autoPull: false,
- faviconPath: null,
- projectIcon: null,
- scripts: [],
- pinnedAt: null,
- archivedAt: null,
- createdAt: "2026-06-21T00:00:00.000Z",
- updatedAt: "2026-06-21T00:00:00.000Z",
- deletedAt: null,
- }),
- }),
- ),
-);
+const layerWithPolicy = (policy?: ManagedPolicySummary) =>
+ RuntimePolicy.layerFromProjectStore.pipe(
+ Layer.provide(ServerSettings.layerTest({}, policy)),
+ Layer.provide(
+ Layer.succeed(ProviderInstanceRegistry.ProviderInstanceRegistry, {
+ getInstance: (instanceId) => Effect.succeed(providerInstanceFor(instanceId)),
+ listInstances: Effect.succeed([]),
+ listUnavailable: Effect.succeed([]),
+ streamChanges: Stream.empty,
+ subscribeChanges: Effect.never,
+ }),
+ ),
+ Layer.provide(
+ Layer.mock(ProjectStore.ProjectStoreV2)({
+ get: () =>
+ Effect.succeedSome({
+ projectId,
+ title: "Project",
+ workspaceRoot: "/project-root",
+ defaultModelSelection: null,
+ defaultThreadEnvMode: null,
+ autoPull: false,
+ faviconPath: null,
+ projectIcon: null,
+ scripts: [],
+ pinnedAt: null,
+ archivedAt: null,
+ createdAt: "2026-06-21T00:00:00.000Z",
+ updatedAt: "2026-06-21T00:00:00.000Z",
+ deletedAt: null,
+ }),
+ }),
+ ),
+ );
+
+const layerTest = layerWithPolicy();
it.layer(layerTest)("RuntimePolicyV2", (it) => {
it.effect("runs a mode the provider does not offer in Supervised", () =>
@@ -126,3 +132,33 @@ it.layer(layerTest)("RuntimePolicyV2", (it) => {
}),
);
});
+
+it.layer(
+ layerWithPolicy({
+ organization: "Example Corp",
+ lockedSettings: [],
+ limits: { maxRuntimeMode: "auto-accept-edits" },
+ }),
+)("RuntimePolicyV2 under a runtime mode ceiling", (it) => {
+ it.effect("refuses to start a turn above the ceiling, such as one resumed after a restart", () =>
+ Effect.gen(function* () {
+ const policy = yield* RuntimePolicy.RuntimePolicyV2;
+ const now = yield* DateTime.now;
+ const resolve = (runtimeMode: RuntimeMode) =>
+ policy.resolve({
+ thread: makeThread({ now, worktreePath: "/work", runtimeMode }),
+ modelSelection,
+ });
+
+ const refused = yield* resolve("full-access").pipe(Effect.flip);
+ assert.equal(refused._tag, "RuntimePolicyAboveCeilingError");
+ assert.equal(
+ refused.message,
+ "Example Corp limits threads to Auto-accept edits. Switch this thread's mode to continue.",
+ );
+ const allowed = yield* resolve("auto-accept-edits");
+ assert.equal(allowed.runtimeMode, "auto-accept-edits");
+ assert.equal(allowed.maxRuntimeMode, "auto-accept-edits");
+ }),
+ );
+});
diff --git a/apps/server/src/orchestration-v2/RuntimePolicy.ts b/apps/server/src/orchestration-v2/RuntimePolicy.ts
index d5f73ebee0e..f0d0ae38577 100644
--- a/apps/server/src/orchestration-v2/RuntimePolicy.ts
+++ b/apps/server/src/orchestration-v2/RuntimePolicy.ts
@@ -1,9 +1,12 @@
import {
+ isRuntimeModeAbove,
+ managedRuntimeModeCeilingMessage,
ModelSelection,
OrchestrationV2AppThread,
ProjectId,
ProviderInstanceId,
- type RuntimeMode,
+ RuntimeMode,
+ ThreadId,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
@@ -13,6 +16,7 @@ import * as Schema from "effect/Schema";
import * as ProviderInstanceRegistry from "../provider/ProviderInstanceRegistry.ts";
import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
+import * as ServerSettings from "../serverSettings.ts";
import * as ProjectStore from "./ProjectStore.ts";
export class RuntimePolicyResolveError extends Schema.TaggedError<RuntimePolicyResolveError>()(
@@ -28,7 +32,31 @@ export class RuntimePolicyResolveError extends Schema.TaggedError<RuntimePolicyR
}
}
-export const RuntimePolicyV2Error = Schema.Union([RuntimePolicyResolveError]);
+/**
+ * A turn would start in a mode above the policy's ceiling. The orchestrator refuses those when
+ * they are dispatched; this catches the ones it never saw, such as a run resumed after a restart
+ * on a thread whose mode predates the policy.
+ */
+export class RuntimePolicyAboveCeilingError extends Schema.TaggedError<RuntimePolicyAboveCeilingError>()(
+ "RuntimePolicyAboveCeilingError",
+ {
+ threadId: ThreadId,
+ runtimeMode: RuntimeMode,
+ maxRuntimeMode: RuntimeMode,
+ organization: Schema.String,
+ },
+) {
+ override get message(): string {
+ return `${managedRuntimeModeCeilingMessage(this.organization, this.maxRuntimeMode)} Switch this thread's mode to continue.`;
+ }
+}
+
+export const isRuntimePolicyAboveCeilingError = Schema.is(RuntimePolicyAboveCeilingError);
+
+export const RuntimePolicyV2Error = Schema.Union([
+ RuntimePolicyResolveError,
+ RuntimePolicyAboveCeilingError,
+]);
export type RuntimePolicyV2Error = typeof RuntimePolicyV2Error.Type;
export const RuntimePolicyV2Override = Schema.Struct({
@@ -71,17 +99,61 @@ function providerRuntimeMode(
: "approval-required";
}
+const refuseAboveCeiling = (
+ managedPolicy: ServerSettings.ServerSettingsService["Service"]["managedPolicy"],
+ thread: OrchestrationV2AppThread,
+) => {
+ const maxRuntimeMode = managedPolicy?.limits?.maxRuntimeMode;
+ return managedPolicy !== undefined &&
+ maxRuntimeMode !== undefined &&
+ isRuntimeModeAbove(thread.runtimeMode, maxRuntimeMode)
+ ? Effect.fail(
+ new RuntimePolicyAboveCeilingError({
+ threadId: thread.id,
+ runtimeMode: thread.runtimeMode,
+ maxRuntimeMode,
+ organization: managedPolicy.organization,
+ }),
+ )
+ : Effect.void;
+};
+
+/** Lays the policy's ceiling over another runtime policy, as `layerFromProjectStore` does. */
+export const layerEnforcingCeiling: Layer.Layer<
+ RuntimePolicyV2,
+ never,
+ RuntimePolicyV2 | ServerSettings.ServerSettingsService
+> = Layer.effect(
+ RuntimePolicyV2,
+ Effect.gen(function* () {
+ const base = yield* RuntimePolicyV2;
+ const { managedPolicy } = yield* ServerSettings.ServerSettingsService;
+ return RuntimePolicyV2.of({
+ resolve: Effect.fn("RuntimePolicyV2.resolveWithinCeiling")(function* (input) {
+ yield* refuseAboveCeiling(managedPolicy, input.thread);
+ return yield* base.resolve(input);
+ }),
+ });
+ }),
+);
+
export const layerFromProjectStore: Layer.Layer<
RuntimePolicyV2,
never,
- ProjectStore.ProjectStoreV2 | ProviderInstanceRegistry.ProviderInstanceRegistry
+ | ProjectStore.ProjectStoreV2
+ | ProviderInstanceRegistry.ProviderInstanceRegistry
+ | ServerSettings.ServerSettingsService
> = Layer.effect(
RuntimePolicyV2,
Effect.gen(function* () {
const projects = yield* ProjectStore.ProjectStoreV2;
const providerInstances = yield* ProviderInstanceRegistry.ProviderInstanceRegistry;
+ // The same ceiling the orchestrator enforces, fixed for the server's life.
+ const { managedPolicy } = yield* ServerSettings.ServerSettingsService;
+ const maxRuntimeMode = managedPolicy?.limits?.maxRuntimeMode;
return RuntimePolicyV2.of({
resolve: Effect.fn("RuntimePolicyV2.resolve")(function* (input) {
+ yield* refuseAboveCeiling(managedPolicy, input.thread);
const instance = yield* providerInstances.getInstance(input.modelSelection.instanceId);
const supportedRuntimeModes =
instance === undefined
@@ -116,6 +188,7 @@ export const layerFromProjectStore: Layer.Layer<
runtimeMode: providerRuntimeMode(input.thread.runtimeMode, supportedRuntimeModes),
interactionMode: input.thread.interactionMode,
cwd,
+ ...(maxRuntimeMode === undefined ? {} : { maxRuntimeMode }),
});
}),
});
diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts
index d3c62a7e134..06438082acd 100644
--- a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts
+++ b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts
@@ -50,6 +50,7 @@ import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts";
import * as ProviderRegistryMock from "../provider/testUtils/providerRegistryMock.ts";
import * as ServerSettings from "../serverSettings.ts";
import * as ScheduledTasks from "../scheduledTasks/ScheduledTaskService.ts";
+import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
import * as SecretRequests from "../secrets/SecretRequests.ts";
import * as TextGeneration from "../textGeneration/TextGeneration.ts";
import { ClaudeProviderCapabilitiesV2 } from "./Adapters/ClaudeAdapterV2.ts";
@@ -327,6 +328,7 @@ it.effect.each(
NodeCrypto.layer,
Scheduler.layer,
Layer.mock(SecretRequests.SecretRequests)({}),
+ ManagedPolicy.layerTest(),
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
),
),
@@ -393,6 +395,7 @@ it.effect(
NodeCrypto.layer,
Scheduler.layer,
Layer.mock(SecretRequests.SecretRequests)({}),
+ ManagedPolicy.layerTest(),
),
),
);
@@ -430,6 +433,7 @@ it.effect("runs a thread-bound automation on the provider the thread uses now",
NodeCrypto.layer,
Scheduler.layer,
Layer.mock(SecretRequests.SecretRequests)({}),
+ ManagedPolicy.layerTest(),
),
),
);
@@ -893,6 +897,7 @@ function scratchHarness() {
NodeCrypto.layer,
Scheduler.layer,
Layer.mock(SecretRequests.SecretRequests)({}),
+ ManagedPolicy.layerTest(),
),
),
);
diff --git a/apps/server/src/orchestration-v2/ThreadMessageIntake.ts b/apps/server/src/orchestration-v2/ThreadMessageIntake.ts
index 987a1deb246..3e8922c3ba7 100644
--- a/apps/server/src/orchestration-v2/ThreadMessageIntake.ts
+++ b/apps/server/src/orchestration-v2/ThreadMessageIntake.ts
@@ -24,6 +24,7 @@ function dispatchWasNotAccepted(
case "OrchestratorCommandIdConflictError":
case "OrchestratorSubagentThreadReadOnlyError":
case "OrchestratorThreadAboveModeLimitError":
+ case "OrchestratorRuntimeModeAboveCeilingError":
case "ThreadManagementProviderInstanceDisabledError":
return true;
default:
diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts
index 8e1ca75fcac..d48afee71ec 100644
--- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts
+++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts
@@ -79,6 +79,7 @@ import * as ThreadManagementService from "./ThreadManagementService.ts";
import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts";
import * as ScratchThreadPromotion from "../project/ScratchThreadPromotion.ts";
import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
+import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
import * as Scheduler from "../scheduling/Scheduler.ts";
import * as SecretRequests from "../secrets/SecretRequests.ts";
import * as PreviewManager from "../preview/Manager.ts";
@@ -309,6 +310,7 @@ const layerLegacyImportTest = RuntimeLayer.layer.pipe(
const layerScheduledTasksTest = ScheduledTaskService.layer.pipe(
Layer.provide(
Layer.mergeAll(
+ ManagedPolicy.layerTest(),
Layer.mock(ThreadLaunchService.ThreadLaunchService)({}),
Layer.mock(ThreadManagementService.ThreadManagementService)({}),
Layer.mock(SecretRequests.SecretRequests)({}),
diff --git a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts
index afd11a9ab7e..f87b7ba6af8 100644
--- a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts
+++ b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts
@@ -1,7 +1,11 @@
import * as OtelEnvironment from "@t3tools/shared/otelEnvironment";
import { DEFAULT_SIGNAL_EXPORT } from "@t3tools/shared/observability";
import * as NodeServices from "@effect/platform-node/NodeServices";
-import type { ProviderDriverKind, ProviderReplayTranscript } from "@t3tools/contracts";
+import type {
+ ManagedPolicyDocument,
+ ProviderDriverKind,
+ ProviderReplayTranscript,
+} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
@@ -15,6 +19,7 @@ import * as CheckpointStore from "../../checkpointing/CheckpointStore.ts";
import * as ServerConfig from "../../config.ts";
import * as SqlitePersistence from "../../persistence/Sqlite.ts";
import * as ServerSettings from "../../serverSettings.ts";
+import * as ManagedPolicy from "../../policy/ManagedPolicy.ts";
import * as ThreadManagementService from "../ThreadManagementService.ts";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import * as McpSessionRegistryTestkit from "../../mcp/McpSessionRegistry.testkit.ts";
@@ -197,6 +202,7 @@ export function runOrchestratorV2ProviderReplayScenario<
readonly runContinuationWorker?: boolean;
readonly recoverOnStartup?: boolean;
readonly continueThreadsAfterServerUpdate?: boolean;
+ readonly managedPolicy?: ManagedPolicyDocument;
} = {},
): Effect.Effect<
OrchestratorV2ScenarioResult,
@@ -239,6 +245,7 @@ export function layerProviderReplay<Transcript extends ProviderReplayTranscript,
readonly runContinuationWorker?: boolean;
readonly recoverOnStartup?: boolean;
readonly continueThreadsAfterServerUpdate?: boolean;
+ readonly managedPolicy?: ManagedPolicyDocument;
readonly replayGate?: ProviderReplayGate;
} = {},
): Layer.Layer<
@@ -272,6 +279,7 @@ export function layerWithRegistry<Error>(
readonly runContinuationWorker?: boolean;
readonly recoverOnStartup?: boolean;
readonly continueThreadsAfterServerUpdate?: boolean;
+ readonly managedPolicy?: ManagedPolicyDocument;
} = {},
): Layer.Layer<
| Orchestrator.OrchestratorV2
@@ -285,7 +293,7 @@ export function layerWithRegistry<Error>(
ServerConfig.ServerConfig,
makeReplayServerConfig(scenario.name).pipe(Effect.orDie),
).pipe(Layer.provide(NodeServices.layer));
- const layerRuntime =
+ const layerRuntimeBase =
scenario.runtimePolicyOverride === undefined
? RuntimePolicy.layer
: RuntimePolicy.layerWithOverride(scenario.runtimePolicyOverride).pipe(
@@ -298,12 +306,19 @@ export function layerWithRegistry<Error>(
const layerProvidedRegistry = registryLayer.pipe(
Layer.provide(Layer.merge(layerContinuationRequests, McpProviderSessions.layer)),
);
- const layerServerSettings = ServerSettings.layerTest({
- responseStreamingMode: "turn",
- ...(options.continueThreadsAfterServerUpdate === undefined
- ? {}
- : { continueThreadsAfterServerUpdate: options.continueThreadsAfterServerUpdate }),
- }).pipe(Layer.orDie);
+ const layerServerSettings = Layer.unwrap(
+ Effect.map(ManagedPolicy.fromDocument("/test/policy.json", options.managedPolicy), (policy) =>
+ ServerSettings.layerTest(
+ {
+ responseStreamingMode: "turn",
+ ...(options.continueThreadsAfterServerUpdate === undefined
+ ? {}
+ : { continueThreadsAfterServerUpdate: options.continueThreadsAfterServerUpdate }),
+ },
+ policy.summary,
+ ),
+ ),
+ ).pipe(Layer.orDie);
const layerStores = Layer.mergeAll(
EventStore.layer,
ProjectionStore.layer,
@@ -315,6 +330,9 @@ export function layerWithRegistry<Error>(
const layerEventSinkProvided = EventSink.layerFromStores.pipe(
Layer.provide(Layer.mergeAll(layerStores, layerDatabase)),
);
+ const layerRuntime = RuntimePolicy.layerEnforcingCeiling.pipe(
+ Layer.provide(Layer.merge(layerRuntimeBase, layerServerSettings)),
+ );
const layerCommandReceiptStoreProvided = CommandReceiptStore.layer.pipe(
Layer.provide(layerDatabase),
);
diff --git a/apps/server/src/peer/PeerLinks.testkit.ts b/apps/server/src/peer/PeerLinks.testkit.ts
index 0f7e39355b9..9bdc47298d5 100644
--- a/apps/server/src/peer/PeerLinks.testkit.ts
+++ b/apps/server/src/peer/PeerLinks.testkit.ts
@@ -30,6 +30,7 @@ import * as Sqlite from "../persistence/Sqlite.ts";
import * as PeerLinks from "./PeerLinks.ts";
import * as ServerSettings from "../serverSettings.ts";
import * as PeerMcpClient from "./PeerMcpClient.ts";
+import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
class PeerTestApi extends HttpApi.make("environment")
.add(EnvironmentHttpApi.groups.metadata)
@@ -71,6 +72,7 @@ export const servePeer = <E, R>(
getDescriptor: Ref.get(descriptor),
});
const authContext = yield* EnvironmentAuth.layer.pipe(
+ Layer.provide(ManagedPolicy.layerTest()),
Layer.provideMerge(ServerSettings.layerTest({ linkedEnvironmentsEnabled: true })),
Layer.provide(Sqlite.layerMemory),
Layer.provideMerge(ServerSecretStore.layer),
diff --git a/apps/server/src/policy/ManagedPolicy.test.ts b/apps/server/src/policy/ManagedPolicy.test.ts
new file mode 100644
index 00000000000..9fbe4d2c427
--- /dev/null
+++ b/apps/server/src/policy/ManagedPolicy.test.ts
@@ -0,0 +1,446 @@
+import * as NodeServices from "@effect/platform-node/NodeServices";
+import { assert, it } from "@effect/vitest";
+import * as Effect from "effect/Effect";
+import * as FileSystem from "effect/FileSystem";
+import * as Path from "effect/Path";
+
+import {
+ DEFAULT_SERVER_SETTINGS,
+ ProviderDriverKind,
+ ProviderInstanceId,
+} from "@t3tools/contracts";
+import * as HostProcess from "@t3tools/shared/HostProcess";
+
+import * as ManagedPolicy from "./ManagedPolicy.ts";
+import { disallowedDriverReason, providerHostEnvironment } from "./managedProviders.ts";
+
+it.layer(NodeServices.layer)("ManagedPolicy.load", (it) => {
+ const loadFrom = (contents: string | undefined) =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-managed-policy-" });
+ const file = path.join(dir, "policy.json");
+ if (contents !== undefined) yield* fs.writeFileString(file, contents);
+ return yield* ManagedPolicy.load(file);
+ }).pipe(Effect.scoped);
+
+ it.effect("means no policy when the file is missing", () =>
+ Effect.gen(function* () {
+ const policy = yield* loadFrom(undefined);
+ assert.isUndefined(policy.summary);
+ }),
+ );
+
+ it.effect("summarizes locked settings for clients", () =>
+ Effect.gen(function* () {
+ const policy = yield* loadFrom(
+ JSON.stringify({
+ schemaVersion: 1,
+ organization: "Example Corp",
+ supportUrl: "https://it.example/t3",
+ settings: {
+ "storageCleanup.logsAfterDays": { value: 30, locked: true },
+ defaultRuntimeMode: { value: "approval-required", locked: false },
+ },
+ }),
+ );
+ assert.deepEqual(policy.summary, {
+ organization: "Example Corp",
+ supportUrl: "https://it.example/t3",
+ lockedSettings: ["storageCleanup.logsAfterDays"],
+ });
+ }),
+ );
+
+ it.effect("tells clients which capabilities the policy switches off", () =>
+ Effect.gen(function* () {
+ const policy = yield* loadFrom(
+ JSON.stringify({
+ schemaVersion: 1,
+ organization: "Example Corp",
+ limits: { webhookTasks: false, telemetry: true },
+ }),
+ );
+ assert.deepEqual(policy.summary?.limits, { webhookTasks: false, telemetry: true });
+ assert.equal(ManagedPolicy.deniedBy(policy, "webhookTasks"), "Example Corp");
+ assert.isUndefined(ManagedPolicy.deniedBy(policy, "telemetry"));
+ }),
+ );
+
+ it.effect("refuses files it cannot fully enforce", () =>
+ Effect.gen(function* () {
+ const base = { schemaVersion: 1, organization: "Example Corp" };
+ const reasons = yield* Effect.forEach(
+ [
+ "{ not json",
+ // An unknown key may be a restriction from a newer release.
+ JSON.stringify({ ...base, limits: { connect: false, futureLimit: true } }),
+ JSON.stringify({ ...base, settings: { notASetting: { value: 1, locked: true } } }),
+ JSON.stringify({
+ ...base,
+ settings: { "storageCleanup.logsAfterDayz": { value: 30, locked: true } },
+ }),
+ JSON.stringify({
+ ...base,
+ settings: { defaultRuntimeMode: { value: "yolo", locked: true } },
+ }),
+ JSON.stringify({
+ ...base,
+ settings: { projectSettingsOverrides: { value: {}, locked: true } },
+ }),
+ // The user could never remove a provider instance a default keeps adding back.
+ JSON.stringify({
+ ...base,
+ settings: {
+ "providerInstances.codex_work": {
+ value: { driver: "codex", enabled: true },
+ locked: false,
+ },
+ },
+ }),
+ JSON.stringify({
+ ...base,
+ settings: {
+ providerInstances: { value: { codex_work: { driver: "codex" } }, locked: false },
+ },
+ }),
+ // A user's stored null would leave the lock building half a model selection.
+ JSON.stringify({
+ ...base,
+ settings: { "defaultModelSelection.model": { value: "gpt-5.4", locked: true } },
+ }),
+ // The server derives it from idleCompaction on every write.
+ JSON.stringify({
+ ...base,
+ settings: { compactIdleThreads: { value: false, locked: true } },
+ }),
+ // It would look locked while worktreeCleanup, which overrides it, stays the user's.
+ JSON.stringify({
+ ...base,
+ settings: { "storageCleanup.worktreeAfterDays": { value: 7, locked: true } },
+ }),
+ // An instance's own variables, home paths, and setup mode would override the lock.
+ JSON.stringify({
+ ...base,
+ settings: {
+ "providerInstances.codex.driver": { value: "codex", locked: true },
+ "providerInstances.codex.config.launchArgs": {
+ value: "-c model_provider=corp",
+ locked: true,
+ },
+ },
+ }),
+ // The server would move it into the user's secret store, past the policy's removal.
+ JSON.stringify({
+ ...base,
+ settings: {
+ providerInstances: {
+ value: { gemini: { driver: "antigravity", config: { apiKey: "corp-key" } } },
+ locked: true,
+ },
+ },
+ }),
+ ],
+ (contents) =>
+ loadFrom(contents).pipe(
+ Effect.flip,
+ Effect.map((error) => error.reason),
+ ),
+ );
+ assert.lengthOf(reasons, 13);
+ assert.include(reasons[3], "storageCleanup.logsAfterDayz");
+ assert.include(reasons[6], "adds entries users could not remove");
+ assert.include(reasons[7], "adds entries users could not remove");
+ assert.include(reasons[8], 'manage "defaultModelSelection" as a whole');
+ assert.include(reasons[9], 'manage "idleCompaction" instead');
+ assert.include(reasons[10], 'lock "worktreeCleanup" too');
+ assert.include(reasons[11], 'lock "providerInstances.codex" as a whole');
+ assert.include(reasons[12], "holds a credential");
+ }),
+ );
+
+ it.effect("tells clients the runtime mode ceiling", () =>
+ Effect.gen(function* () {
+ const policy = yield* loadFrom(
+ JSON.stringify({
+ schemaVersion: 1,
+ organization: "Example Corp",
+ settings: { defaultRuntimeMode: { value: "approval-required", locked: true } },
+ limits: { maxRuntimeMode: "auto-accept-edits" },
+ }),
+ );
+ const { providers, ...limits } = policy.summary?.limits ?? {};
+ assert.deepEqual(limits, { maxRuntimeMode: "auto-accept-edits" });
+ // Under a ceiling, each driver's launch configuration is the administrator's.
+ assert.deepEqual(providers?.lockedInstanceFields?.[ProviderDriverKind.make("claudeAgent")], [
+ "config.binaryPath",
+ "config.launchArgs",
+ "config.homePath",
+ "environment",
+ ]);
+ assert.deepEqual(providers?.lockedInstanceFields?.[ProviderDriverKind.make("acpRegistry")], [
+ "config.commandPath",
+ "config.commandArgs",
+ "environment",
+ ]);
+ // The host variable that replaces Codex's launch arguments is ignored too.
+ const host = { PATH: "/usr/bin", T3CODE_CODEX_LAUNCH_ARGS: "-c mcp_servers.x.command=sh" };
+ assert.deepEqual(providerHostEnvironment(policy.summary, host), { PATH: "/usr/bin" });
+ assert.strictEqual(providerHostEnvironment(undefined, host), host);
+ }),
+ );
+
+ it.effect(
+ "locks a variable in every spelling on Windows only, and drops a Codex launch override",
+ () =>
+ Effect.gen(function* () {
+ const codex = ProviderDriverKind.make("codex");
+ const variable = (name: string, value: string) => ({ name, value, sensitive: false });
+ const settings = {
+ ...DEFAULT_SERVER_SETTINGS,
+ providerInstances: {
+ codex: {
+ driver: codex,
+ environment: [
+ variable("HTTPS_PROXY", "http://mine"),
+ variable("T3CODE_CODEX_LAUNCH_ARGS", "--dangerously-bypass-approvals-and-sandbox"),
+ ],
+ },
+ },
+ };
+ const policyOn = (platform: NodeJS.Platform) =>
+ ManagedPolicy.fromDocument("/test/policy.json", {
+ schemaVersion: 1,
+ organization: "Example Corp",
+ limits: {
+ providers: {
+ instances: {
+ [codex]: {
+ locked: true,
+ launchArgs: "--strict-config",
+ environment: [{ name: "Https_Proxy", value: "http://gateway" }],
+ },
+ },
+ },
+ },
+ }).pipe(Effect.provideService(HostProcess.Platform, platform));
+ const environmentOn = (platform: NodeJS.Platform) =>
+ Effect.map(
+ policyOn(platform),
+ (policy) =>
+ policy.providers.applyLimits(settings).providerInstances[
+ ProviderInstanceId.make("codex")
+ ]?.environment,
+ );
+ assert.deepEqual(yield* environmentOn("win32"), [
+ variable("Https_Proxy", "http://gateway"),
+ ]);
+ assert.deepEqual(yield* environmentOn("linux"), [
+ variable("HTTPS_PROXY", "http://mine"),
+ variable("Https_Proxy", "http://gateway"),
+ ]);
+ // Saving what the client was shown keeps the override it never saw.
+ const linux = yield* policyOn("linux");
+ const shown = linux.providers.applyLimits(settings);
+ const codexId = ProviderInstanceId.make("codex");
+ const saved = linux.providers.vetWrite(settings, {
+ ...shown,
+ providerInstances: {
+ ...shown.providerInstances,
+ [codexId]: { ...shown.providerInstances[codexId]!, displayName: "Codex (work)" },
+ },
+ });
+ assert.equal(saved._tag, "Allowed");
+ const savedEnvironment =
+ saved._tag === "Allowed"
+ ? (saved.settings.providerInstances[codexId]?.environment ?? [])
+ : [];
+ assert.isTrue(savedEnvironment.some((entry) => entry.name === "T3CODE_CODEX_LAUNCH_ARGS"));
+ // A home path setting would rewrite a locked home variable at launch, so the lock owns it.
+ const claude = ProviderDriverKind.make("claudeAgent");
+ const homeLocked = yield* ManagedPolicy.fromDocument("/test/policy.json", {
+ schemaVersion: 1,
+ organization: "Example Corp",
+ limits: {
+ providers: {
+ instances: {
+ [claude]: {
+ locked: true,
+ environment: [{ name: "CLAUDE_CONFIG_DIR", value: "/opt/claude-home" }],
+ },
+ },
+ },
+ },
+ });
+ const claudeId = ProviderInstanceId.make("claudeAgent");
+ const claudeConfig = homeLocked.providers.applyLimits({
+ ...DEFAULT_SERVER_SETTINGS,
+ providerInstances: {
+ [claudeId]: { driver: claude, config: { homePath: "/home/me/.other-claude" } },
+ },
+ }).providerInstances[claudeId]?.config;
+ assert.deepEqual(claudeConfig, {});
+ assert.include(
+ homeLocked.summary?.limits?.providers?.lockedInstanceFields?.[claude] ?? [],
+ "config.homePath",
+ );
+ // Codex has a second home setting, which a locked CODEX_HOME owns too.
+ const codexHome = yield* ManagedPolicy.fromDocument("/test/policy.json", {
+ schemaVersion: 1,
+ organization: "Example Corp",
+ limits: {
+ providers: {
+ instances: {
+ [codex]: {
+ locked: true,
+ environment: [{ name: "CODEX_HOME", value: "/opt/codex-home" }],
+ },
+ },
+ },
+ },
+ });
+ assert.includeMembers(
+ [...(codexHome.summary?.limits?.providers?.lockedInstanceFields?.[codex] ?? [])],
+ ["config.homePath", "config.shadowHomePath"],
+ );
+ // A server URL makes OpenCode skip the local launch a pin sets, so the pin owns it too.
+ const opencode = ProviderDriverKind.make("opencode");
+ const opencodePinned = yield* ManagedPolicy.fromDocument("/test/policy.json", {
+ schemaVersion: 1,
+ organization: "Example Corp",
+ limits: {
+ providers: { instances: { [opencode]: { locked: true, binaryPath: "/opt/opencode" } } },
+ },
+ });
+ assert.include(
+ opencodePinned.summary?.limits?.providers?.lockedInstanceFields?.[opencode] ?? [],
+ "config.serverUrl",
+ );
+ // The same override from the environment that starts the server is ignored too.
+ const host = { PATH: "/usr/bin", T3CODE_CODEX_LAUNCH_ARGS: "--yolo" };
+ assert.deepEqual(providerHostEnvironment((yield* policyOn("linux")).summary, host), {
+ PATH: "/usr/bin",
+ });
+ }),
+ );
+
+ it.effect("refuses a default runtime mode above its own ceiling", () =>
+ Effect.gen(function* () {
+ const reasons = yield* Effect.forEach([false, true], (locked) =>
+ loadFrom(
+ JSON.stringify({
+ schemaVersion: 1,
+ organization: "Example Corp",
+ settings: { defaultRuntimeMode: { value: "auto", locked } },
+ limits: { maxRuntimeMode: "auto-accept-edits" },
+ }),
+ ).pipe(
+ Effect.flip,
+ Effect.map((error) => error.reason),
+ ),
+ );
+ assert.deepEqual(reasons, [
+ '"defaultRuntimeMode" is above "limits.maxRuntimeMode"',
+ '"defaultRuntimeMode" is above "limits.maxRuntimeMode"',
+ ]);
+ }),
+ );
+
+ it.effect("tells clients which drivers run and which instance fields are locked", () =>
+ Effect.gen(function* () {
+ const policy = yield* loadFrom(
+ JSON.stringify({
+ schemaVersion: 1,
+ organization: "Example Corp",
+ limits: {
+ providers: {
+ allowedDrivers: ["claudeAgent", "codex"],
+ instances: {
+ claudeAgent: {
+ locked: true,
+ environment: [{ name: "CLAUDE_CODE_USE_BEDROCK", value: "1" }],
+ binaryPath: "/opt/claude/bin/claude",
+ },
+ codex: { locked: false, launchArgs: "-c model_provider=gateway" },
+ },
+ },
+ },
+ }),
+ );
+ assert.deepEqual<unknown>(policy.summary?.limits, {
+ providers: {
+ allowedDrivers: ["claudeAgent", "codex"],
+ lockedInstanceFields: {
+ claudeAgent: ["config.binaryPath", "environment.CLAUDE_CODE_USE_BEDROCK"],
+ },
+ },
+ });
+ assert.equal(
+ disallowedDriverReason(policy.summary, ProviderDriverKind.make("cursor")),
+ "Example Corp's policy does not allow the Cursor provider.",
+ );
+ assert.isUndefined(disallowedDriverReason(policy.summary, ProviderDriverKind.make("codex")));
+ }),
+ );
+
+ it.effect("refuses provider limits it cannot enforce", () =>
+ Effect.gen(function* () {
+ const withProviders = (providers: unknown) =>
+ JSON.stringify({
+ schemaVersion: 1,
+ organization: "Example Corp",
+ limits: { providers },
+ });
+ const reasons = yield* Effect.forEach(
+ [
+ withProviders({ allowedDrivers: ["claudeAgent", "notAProvider"] }),
+ withProviders({ instances: { notAProvider: { locked: true, binaryPath: "/x" } } }),
+ // Cursor has no launch arguments setting to pin.
+ withProviders({ instances: { cursor: { locked: true, launchArgs: "--x" } } }),
+ withProviders({ instances: { codex: { locked: true, homePath: "/x" } } }),
+ withProviders({
+ instances: { codex: { locked: true, environment: [{ name: "1BAD", value: "" }] } },
+ }),
+ // No provider could run at all.
+ withProviders({ allowedDrivers: [] }),
+ ],
+ (contents) =>
+ loadFrom(contents).pipe(
+ Effect.flip,
+ Effect.map((error) => error.reason),
+ ),
+ );
+ assert.lengthOf(reasons, 6);
+ assert.include(reasons[0], "notAProvider");
+ assert.include(reasons[1], "notAProvider");
+ assert.include(reasons[2], "launchArgs");
+ }),
+ );
+
+ it.effect(
+ "tells clients how updates are managed and refuses an update feed it cannot trust",
+ () =>
+ Effect.gen(function* () {
+ const base = { schemaVersion: 1, organization: "Example Corp" };
+ const updates = {
+ mode: "auto" as const,
+ feedUrl: "https://updates.example/t3",
+ allowNightly: false,
+ };
+ const policy = yield* loadFrom(JSON.stringify({ ...base, limits: { updates } }));
+ const { feedUrl: _feedUrl, ...clientUpdates } = updates;
+ assert.deepEqual(policy.summary?.limits, { updates: clientUpdates });
+ for (const invalid of [
+ { mode: "auto", feedUrl: "http://updates.example/t3" },
+ { mode: "manual" },
+ { mode: "sometimes" },
+ { mode: "auto", pinVersion: "1.2.3" },
+ ]) {
+ yield* loadFrom(JSON.stringify({ ...base, limits: { updates: invalid } })).pipe(
+ Effect.flip,
+ );
+ }
+ }),
+ );
+});
diff --git a/apps/server/src/policy/ManagedPolicy.ts b/apps/server/src/policy/ManagedPolicy.ts
new file mode 100644
index 00000000000..8b3f668ee6c
--- /dev/null
+++ b/apps/server/src/policy/ManagedPolicy.ts
@@ -0,0 +1,215 @@
+/**
+ * ManagedPolicy - the administrator's machine-wide policy file, read once at startup. A file this
+ * build cannot fully enforce stops the server instead of leaving it looking managed.
+ *
+ * @module ManagedPolicy
+ */
+import * as NodeModule from "node:module";
+
+import { ManagedPolicyDocument, type ManagedPolicySummary } from "@t3tools/contracts";
+import * as Config from "effect/Config";
+import * as Context from "effect/Context";
+import * as Crypto from "effect/Crypto";
+import * as Effect from "effect/Effect";
+import * as Hex from "effect/encoding/Hex";
+import * as Layer from "effect/Layer";
+import * as Option from "effect/Option";
+import * as Schema from "effect/Schema";
+
+import * as HostProcess from "@t3tools/shared/HostProcess";
+import {
+ ManagedPolicyFileError,
+ managedPolicyPath,
+ layerWindowsRegistry,
+ readManagedPolicy,
+ readManagedPolicyFile,
+} from "@t3tools/shared/managedPolicyFile";
+
+import { telemetryChannel } from "../config.ts";
+import * as ManagedLimits from "./managedLimits.ts";
+import * as ManagedProviders from "./managedProviders.ts";
+import * as ManagedSettings from "./managedSettings.ts";
+
+export class ManagedPolicy extends Context.Service<
+ ManagedPolicy,
+ {
+ /** Where the policy is read from, whether or not a file exists there. */
+ readonly path: string;
+ readonly document: ManagedPolicyDocument | undefined;
+ readonly settings: ManagedSettings.ManagedSettings;
+ readonly providers: ManagedProviders.ManagedProviders;
+ /** What clients are told; absent when no policy applies. */
+ readonly summary: ManagedPolicySummary | undefined;
+ }
+>()("t3/policy/ManagedPolicy") {}
+
+type LimitsSummary = NonNullable<ManagedPolicySummary["limits"]>;
+
+const encodeDocumentJson = Schema.encodeEffect(Schema.fromJsonString(ManagedPolicyDocument));
+
+/** What `t3 policy show` compares to tell whether a running server loaded the installed policy. */
+export const loadedPolicy = Effect.fn("ManagedPolicy.loadedPolicy")(function* (
+ policy: Pick<ManagedPolicy["Service"], "path" | "document">,
+) {
+ if (policy.document === undefined) return null;
+ const json = yield* encodeDocumentJson(policy.document).pipe(Effect.orDie);
+ const digest = yield* (yield* Crypto.Crypto)
+ .digest("SHA-256", new TextEncoder().encode(json))
+ .pipe(Effect.orDie);
+ return {
+ source: policy.path,
+ organization: policy.document.organization,
+ fingerprint: Hex.encode(digest).slice(0, 12),
+ };
+});
+
+/**
+ * The organization whose policy switches `capability` off, or undefined when it is allowed.
+ * Only an explicit `false` restricts.
+ */
+export function deniedBy(
+ policy: Pick<ManagedPolicy["Service"], "document">,
+ capability: "webhookTasks" | "telemetry",
+): string | undefined {
+ return policy.document?.limits?.[capability] === false ? policy.document.organization : undefined;
+}
+
+/** Build the service from a decoded document; fails when the document cannot be enforced. */
+export const fromDocument = Effect.fn("ManagedPolicy.fromDocument")(function* (
+ path: string,
+ document: ManagedPolicyDocument | undefined,
+) {
+ if (document === undefined) {
+ return ManagedPolicy.of({
+ path,
+ document: undefined,
+ settings: ManagedSettings.unmanagedSettings,
+ providers: ManagedProviders.unmanagedProviders,
+ summary: undefined,
+ });
+ }
+ const maxRuntimeMode = document.limits?.maxRuntimeMode;
+ const settings = ManagedSettings.makeManagedSettings(document.settings ?? {}, maxRuntimeMode);
+ if (settings._tag === "Invalid") {
+ return yield* new ManagedPolicyFileError({ path, reason: settings.reason });
+ }
+ // A ceiling alone also shapes providers: their launch configuration becomes the administrator's.
+ const providerLimits = document.limits?.providers;
+ const providers =
+ providerLimits === undefined && maxRuntimeMode === undefined
+ ? undefined
+ : ManagedProviders.makeManagedProviders(
+ providerLimits ?? {},
+ maxRuntimeMode,
+ yield* HostProcess.Platform,
+ );
+ if (providers?._tag === "Invalid") {
+ return yield* new ManagedPolicyFileError({ path, reason: providers.reason });
+ }
+ const lockedInstanceFields = providers?.providers.lockedInstanceFields ?? {};
+ return ManagedPolicy.of({
+ path,
+ document,
+ settings: settings.settings,
+ providers: providers?.providers ?? ManagedProviders.unmanagedProviders,
+ summary: {
+ organization: document.organization,
+ ...(document.supportUrl === undefined ? {} : { supportUrl: document.supportUrl }),
+ lockedSettings: settings.settings.lockedPaths,
+ ...(document.limits === undefined
+ ? {}
+ : { limits: summarizeLimits(document, lockedInstanceFields) }),
+ },
+ });
+});
+
+// Copies only what clients may see; other limits can carry values that stay on the server.
+function summarizeLimits(
+ document: ManagedPolicyDocument,
+ lockedInstanceFields: Readonly<Record<string, ReadonlyArray<string>>>,
+): LimitsSummary {
+ const {
+ maxRuntimeMode,
+ clients,
+ webhookTasks,
+ telemetry,
+ browserCookieImport,
+ providers,
+ updates,
+ } = document.limits ?? {};
+ const connect = ManagedLimits.allowsConnect({ document });
+ return {
+ ...(maxRuntimeMode === undefined ? {} : { maxRuntimeMode }),
+ ...(clients === undefined ? {} : { clients }),
+ ...(connect ? {} : { connect: false }),
+ ...(webhookTasks === undefined ? {} : { webhookTasks }),
+ ...(telemetry === undefined ? {} : { telemetry }),
+ ...(browserCookieImport === undefined ? {} : { browserCookieImport }),
+ ...(providers?.allowedDrivers === undefined && Object.keys(lockedInstanceFields).length === 0
+ ? {}
+ : {
+ providers: {
+ ...(providers?.allowedDrivers === undefined
+ ? {}
+ : { allowedDrivers: providers.allowedDrivers }),
+ ...(Object.keys(lockedInstanceFields).length === 0 ? {} : { lockedInstanceFields }),
+ },
+ }),
+ ...(updates === undefined
+ ? {}
+ : {
+ updates: {
+ mode: updates.mode,
+ ...(updates.allowNightly === undefined ? {} : { allowNightly: updates.allowNightly }),
+ },
+ }),
+ };
+}
+
+/** Read and validate the policy at `path`; a missing file means no policy. */
+export const load = Effect.fn("ManagedPolicy.load")(function* (path: string) {
+ return yield* fromDocument(path, yield* readManagedPolicyFile(path));
+});
+
+const make = Effect.gen(function* () {
+ // Source builds may read a policy from elsewhere so it can be tried without root. Release
+ // builds never do: any override a user can set is a way around the policy.
+ const devPath =
+ telemetryChannel === "dev"
+ ? yield* Config.option(Config.String("T3CODE_DEV_MANAGED_POLICY_PATH")).pipe(
+ Effect.orElseSucceed(() => Option.none<string>()),
+ )
+ : Option.none<string>();
+ const platform = yield* HostProcess.Platform;
+ const policy = yield* Option.match(devPath, {
+ onSome: load,
+ onNone: () =>
+ readManagedPolicy(platform).pipe(
+ Effect.flatMap((found) =>
+ fromDocument(found?.source ?? managedPolicyPath(platform), found?.document),
+ ),
+ ),
+ });
+ const path = policy.path;
+ if (policy.summary !== undefined) {
+ yield* Effect.logInfo("Managed policy applies.", {
+ path,
+ organization: policy.summary.organization,
+ lockedSettings: policy.summary.lockedSettings,
+ });
+ }
+ return policy;
+});
+
+// A single-executable server resolves packages on disk only through `require`.
+const requireForFfi = NodeModule.createRequire(import.meta.url);
+
+export const layer = Layer.effect(ManagedPolicy, make).pipe(
+ Layer.provide(
+ layerWindowsRegistry(async () => requireForFfi("ffi-rs") as typeof import("ffi-rs")),
+ ),
+);
+
+/** A policy for tests; `undefined` means unmanaged. */
+export const layerTest = (document?: ManagedPolicyDocument) =>
+ Layer.effect(ManagedPolicy, fromDocument("/test/policy.json", document));
diff --git a/apps/server/src/policy/managedLimits.test.ts b/apps/server/src/policy/managedLimits.test.ts
new file mode 100644
index 00000000000..a09f11909ab
--- /dev/null
+++ b/apps/server/src/policy/managedLimits.test.ts
@@ -0,0 +1,411 @@
+import type { ManagedPolicyDocument } from "@t3tools/contracts";
+import { assert, it } from "@effect/vitest";
+import * as Effect from "effect/Effect";
+import * as Fiber from "effect/Fiber";
+import * as PlatformError from "effect/PlatformError";
+import * as Sink from "effect/Sink";
+import * as Stream from "effect/Stream";
+import * as TestClock from "effect/testing/TestClock";
+import { ChildProcessSpawner } from "effect/process";
+
+import * as NetService from "@t3tools/shared/Net";
+
+import * as EnvironmentAuthPolicy from "../auth/EnvironmentAuthPolicy.ts";
+import * as ManagedLimits from "./managedLimits.ts";
+import * as ManagedPolicy from "./ManagedPolicy.ts";
+
+const policy = (limits?: ManagedPolicyDocument["limits"]) => ({
+ document: {
+ schemaVersion: 1 as const,
+ organization: "Example Corp",
+ ...(limits === undefined ? {} : { limits }),
+ },
+});
+
+const desktopAndLocal = policy({ clients: ["desktop", "local-browser"] });
+
+it.effect("refuses to listen on a non-loopback host when remote clients are not allowed", () =>
+ Effect.gen(function* () {
+ const error = yield* ManagedLimits.checkServerReachability(desktopAndLocal, {
+ authPolicy: "remote-reachable",
+ host: "0.0.0.0",
+ tailscaleServeEnabled: false,
+ }).pipe(Effect.flip);
+ assert.equal(
+ error.message,
+ "Example Corp's policy does not allow remote clients, so the server cannot listen on 0.0.0.0.",
+ );
+ }),
+);
+
+it.effect("binds only the loopback address it approved when remote clients are not allowed", () =>
+ Effect.gen(function* () {
+ const bind = (
+ host: string | undefined,
+ policy: { readonly document: ManagedPolicyDocument | undefined } = desktopAndLocal,
+ ) =>
+ ManagedLimits.checkServerReachability(policy, {
+ authPolicy: EnvironmentAuthPolicy.resolveServerAuthPolicy({ mode: "web", host }),
+ host,
+ tailscaleServeEnabled: false,
+ });
+ // Node listens on every interface for an empty host, and a name resolves through DNS.
+ for (const host of ["", "127.office.example", "127.0.0.1e0", "0.0.0.0"]) {
+ const error = yield* bind(host).pipe(Effect.flip);
+ assert.include(error.message, "does not allow remote clients", host);
+ }
+ for (const [host, address] of [
+ [undefined, "127.0.0.1"],
+ ["localhost", "127.0.0.1"],
+ ["127.0.0.2", "127.0.0.2"],
+ ["[::1]", "::1"],
+ ] as const) {
+ assert.equal(yield* bind(host), address);
+ }
+ const service = yield* ManagedLimits.checkServerReachability(desktopAndLocal, {
+ authPolicy: "remote-reachable",
+ host: "0.0.0.0",
+ tailscaleServeEnabled: false,
+ privateNetworkOnly: true,
+ }).pipe(Effect.flip);
+ assert.include(service.message, "set T3CODE_HOST=127.0.0.1 in its service.env");
+ assert.equal(yield* bind("localhost", { document: undefined }), "localhost");
+ assert.equal(yield* bind(undefined, { document: undefined }), "127.0.0.1");
+ }),
+);
+
+it.effect("refuses Tailscale Serve when remote clients are not allowed", () =>
+ Effect.gen(function* () {
+ const error = yield* ManagedLimits.checkServerReachability(desktopAndLocal, {
+ authPolicy: "loopback-browser",
+ host: undefined,
+ tailscaleServeEnabled: true,
+ }).pipe(Effect.flip);
+ assert.include(error.message, "Tailscale Serve");
+ }),
+);
+
+it.effect("refuses an auth policy the clients list leaves out", () =>
+ Effect.gen(function* () {
+ const error = yield* ManagedLimits.checkServerReachability(policy({ clients: ["desktop"] }), {
+ authPolicy: "loopback-browser",
+ host: undefined,
+ tailscaleServeEnabled: false,
+ }).pipe(Effect.flip);
+ assert.equal(error.message, "Example Corp's policy does not allow browsers on this machine.");
+ }),
+);
+
+it.effect("refuses unsafe-no-auth under any policy file, even one without limits", () =>
+ Effect.gen(function* () {
+ const error = yield* ManagedLimits.checkServerReachability(policy(), {
+ authPolicy: "unsafe-no-auth",
+ host: undefined,
+ tailscaleServeEnabled: false,
+ }).pipe(Effect.flip);
+ assert.include(error.message, "without authentication");
+ assert.isTrue(ManagedLimits.allowsAuthPolicy({ document: undefined }, "unsafe-no-auth"));
+ }),
+);
+
+it.effect("allows the clients the policy lists", () =>
+ ManagedLimits.checkServerReachability(policy({ clients: ["remote"] }), {
+ authPolicy: "remote-reachable",
+ host: "0.0.0.0",
+ tailscaleServeEnabled: true,
+ }),
+);
+
+it.effect("tells clients Connect is off when the policy leaves out remote clients", () =>
+ Effect.gen(function* () {
+ const managed = yield* ManagedPolicy.fromDocument("/test/policy.json", {
+ ...desktopAndLocal.document,
+ });
+ assert.deepEqual(managed.summary?.limits, {
+ clients: ["desktop", "local-browser"],
+ connect: false,
+ });
+ assert.isTrue(ManagedLimits.allowsConnect(policy({ clients: ["remote"] })));
+ assert.isFalse(ManagedLimits.allowsConnect(policy({ connect: false })));
+ }),
+);
+
+it.effect(
+ "turns off only the Tailscale Serve routes that forward here, and refuses to start if one stays",
+ () => {
+ type Web = Record<string, Record<string, string>>;
+ interface Answers {
+ /** Serve handlers by host:port, then mount, to proxy target. */
+ readonly web?: Web;
+ /** TCP forwards by port. */
+ readonly tcp?: Record<string, string>;
+ /** The name `off` acts on: the machine's current one. */
+ readonly currentName?: string;
+ readonly status?: {
+ readonly stdout: string;
+ readonly exitCode: number;
+ readonly stderr?: string;
+ };
+ readonly offExitCode?: number;
+ /** `serve status` never answers, as on a Mac where Tailscale was never set up. */
+ readonly statusHangs?: boolean;
+ /** `off` exits as told but leaves the config alone. */
+ readonly offIgnored?: boolean;
+ }
+ // Acts as the real CLI: `serve status --json` prints the config; `serve --https=<port> off`
+ // drops every handler on that port of the current name unless `--set-path` names one
+ // (serve_v2.go removeWebServe), and `serve --tcp=<port> off` drops that port's forward.
+ const close = (answers: Answers, offCalls: Array<ReadonlyArray<string>> = []) => {
+ const web: Web = answers.web ?? {
+ "box.tailnet.ts.net:443": { "/": "http://127.0.0.1:3773" },
+ };
+ const tcp = answers.tcp ?? {};
+ const currentName = answers.currentName ?? "box.tailnet.ts.net";
+ return ManagedLimits.closeTailscaleServeTo(desktopAndLocal, {
+ host: "127.0.0.1",
+ port: 3773,
+ }).pipe(
+ Effect.provideService(
+ ChildProcessSpawner.ChildProcessSpawner,
+ ChildProcessSpawner.make((command) => {
+ const { args } = command as unknown as { readonly args: ReadonlyArray<string> };
+ // `tailscale status --json` names the machine; `tailscale serve status --json` routes.
+ if (args[0] === "status") {
+ return Effect.succeed(
+ ChildProcessSpawner.makeHandle({
+ pid: ChildProcessSpawner.ProcessId(1),
+ exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
+ isRunning: Effect.succeed(false),
+ kill: () => Effect.void,
+ unref: Effect.succeed(Effect.void),
+ stdin: Sink.drain,
+ stdout: Stream.make(
+ new TextEncoder().encode(
+ JSON.stringify({ Self: { DNSName: `${currentName}.` } }),
+ ),
+ ),
+ stderr: Stream.empty,
+ all: Stream.empty,
+ getInputFd: () => Sink.drain,
+ getOutputFd: () => Stream.empty,
+ }),
+ );
+ }
+ const isStatus = args.includes("status");
+ if (!isStatus) {
+ offCalls.push(args);
+ const port = args.find((arg) => arg.startsWith("--https="))?.slice(8);
+ const tcpPort = args.find((arg) => arg.startsWith("--tcp="))?.slice(6);
+ const mount = args.find((arg) => arg.startsWith("--set-path="))?.slice(11);
+ const site = web[`${currentName}:${port}`];
+ if (answers.offIgnored !== true) {
+ if (tcpPort !== undefined) delete tcp[tcpPort];
+ for (const handler of Object.keys(site ?? {})) {
+ if (mount === undefined || mount === handler) delete site![handler];
+ }
+ }
+ }
+ const status = answers.status ?? {
+ stdout: JSON.stringify({
+ TCP: Object.fromEntries(
+ Object.entries(tcp).map(([port, forward]) => [port, { TCPForward: forward }]),
+ ),
+ Web: Object.fromEntries(
+ Object.entries(web).map(([hostPort, handlers]) => [
+ hostPort,
+ {
+ Handlers: Object.fromEntries(
+ Object.entries(handlers).map(([mount, proxy]) => [mount, { Proxy: proxy }]),
+ ),
+ },
+ ]),
+ ),
+ }),
+ exitCode: 0,
+ };
+ const text = (value: string | undefined) =>
+ value === undefined ? Stream.empty : Stream.make(new TextEncoder().encode(value));
+ return Effect.succeed(
+ ChildProcessSpawner.makeHandle({
+ pid: ChildProcessSpawner.ProcessId(1),
+ exitCode:
+ isStatus && answers.statusHangs === true
+ ? Effect.never
+ : Effect.succeed(
+ ChildProcessSpawner.ExitCode(
+ isStatus ? status.exitCode : (answers.offExitCode ?? 0),
+ ),
+ ),
+ isRunning: Effect.succeed(false),
+ kill: () => Effect.void,
+ unref: Effect.succeed(Effect.void),
+ stdin: Sink.drain,
+ stdout: isStatus ? text(status.stdout) : Stream.empty,
+ stderr: isStatus ? text(status.stderr) : Stream.empty,
+ all: Stream.empty,
+ getInputFd: () => Sink.drain,
+ getOutputFd: () => Stream.empty,
+ }),
+ );
+ }),
+ ),
+ );
+ };
+ const portFree = { ...NetService.make(), canListenOnHost: () => Effect.succeed(true) };
+ const portHeld = { ...portFree, canListenOnHost: () => Effect.succeed(false) };
+ return Effect.gen(function* () {
+ // A route that shares the port with this server's stays, as does one to another loopback
+ // address on the same port; a TCP forward here goes too.
+ for (const mount of ["/t3", "/"]) {
+ const web: Web = {
+ "box.tailnet.ts.net:443": {
+ [mount]: "http://127.0.0.1:3773",
+ "/dashboard": "http://127.0.0.1:9000",
+ "/other": "http://127.0.0.2:3773",
+ },
+ };
+ const tcp: Record<string, string> = { "7000": "127.0.0.1:3773" };
+ const offCalls: Array<ReadonlyArray<string>> = [];
+ yield* close({ web, tcp }, offCalls);
+ assert.deepEqual(web, {
+ "box.tailnet.ts.net:443": {
+ "/dashboard": "http://127.0.0.1:9000",
+ "/other": "http://127.0.0.2:3773",
+ },
+ });
+ assert.deepEqual(tcp, {});
+ assert.deepEqual(offCalls, [
+ ["serve", "--tcp=7000", "off"],
+ ["serve", "--https=443", `--set-path=${mount}`, "off"],
+ ]);
+ }
+ // `off` acts on the current name: a route under a former one is left, with how to clear it,
+ // while one under the current name goes even if a former name has routes too.
+ const renamed: Web = {
+ "old.tailnet.ts.net:443": { "/": "http://127.0.0.1:3773" },
+ "new.tailnet.ts.net:443": { "/": "http://127.0.0.1:9000" },
+ };
+ const renamedOffCalls: Array<ReadonlyArray<string>> = [];
+ const former = yield* close(
+ { web: renamed, currentName: "new.tailnet.ts.net" },
+ renamedOffCalls,
+ ).pipe(Effect.flip);
+ assert.deepEqual(renamedOffCalls, []);
+ assert.deepEqual(renamed["new.tailnet.ts.net:443"], { "/": "http://127.0.0.1:9000" });
+ assert.include(
+ former.message,
+ 'under old.tailnet.ts.net, a former name of this machine, which "tailscale serve ... off" cannot reach; run "tailscale serve reset"',
+ );
+ const current: Web = {
+ "old.tailnet.ts.net:443": { "/": "http://127.0.0.1:9000" },
+ "new.tailnet.ts.net:443": { "/": "http://127.0.0.1:3773" },
+ };
+ yield* close({ web: current, currentName: "new.tailnet.ts.net" });
+ assert.deepEqual(current, {
+ "old.tailnet.ts.net:443": { "/": "http://127.0.0.1:9000" },
+ "new.tailnet.ts.net:443": {},
+ });
+ // A `localhost` target might reach another service on the other loopback, so it stays.
+ const localhostOffCalls: Array<ReadonlyArray<string>> = [];
+ const localhost = yield* close(
+ { web: { "box.tailnet.ts.net:443": { "/": "http://localhost:3773" } } },
+ localhostOffCalls,
+ ).pipe(Effect.flip);
+ assert.deepEqual(localhostOffCalls, []);
+ assert.include(localhost.message, "its target localhost might be another service");
+ // Only a fresh read confirms the route is gone, whatever `off` exits with.
+ for (const answers of [{ offIgnored: true }, { offIgnored: true, offExitCode: 1 }]) {
+ const stuck = yield* close(answers).pipe(Effect.flip);
+ assert.include(
+ stuck.message,
+ 'Tailscale Serve forwards port 443 at / here; turn it off with "tailscale serve --https=443 --set-path=/ off"',
+ );
+ }
+ // Routes the server must not remove itself: a Service's, and a foreground command's.
+ const owners = {
+ stdout: JSON.stringify({
+ Foreground: {
+ session1: {
+ Web: { "box:443": { Handlers: { "/": { Proxy: "http://127.0.0.1:3773" } } } },
+ },
+ },
+ Services: {
+ "svc:t3": {
+ Web: { "t3:443": { Handlers: { "/t3": { Proxy: "http://127.0.0.1:3773" } } } },
+ },
+ },
+ }),
+ exitCode: 0,
+ };
+ const ownedOffCalls: Array<ReadonlyArray<string>> = [];
+ const owned = yield* close({ status: owners }, ownedOffCalls).pipe(Effect.flip);
+ assert.deepEqual(ownedOffCalls, []);
+ assert.include(owned.message, 'stop the "tailscale serve" command that runs it');
+ assert.include(
+ owned.message,
+ '"tailscale serve --service=svc:t3 --https=443 --set-path=/t3 off"',
+ );
+ // An answer that cannot be read might hide a mapping, so the server does not start.
+ const dialFailure = (reason: string) =>
+ `Failed to connect to local Tailscale daemon for /localapi/v0/serve-config; not running? Error: dial unix /var/run/tailscale/tailscaled.sock: connect: ${reason}`;
+ for (const status of [
+ { stdout: "", exitCode: 1, stderr: "something unexpected" },
+ { stdout: "not json", exitCode: 0 },
+ { stdout: "", exitCode: 1, stderr: "Access denied: serve config denied" },
+ { stdout: "", exitCode: 1, stderr: dialFailure("permission denied") },
+ ]) {
+ const unread = yield* close({ status }).pipe(Effect.flip);
+ assert.include(unread.message, "does not start until Tailscale Serve can be checked");
+ }
+ // A Tailscale that never answers is not read as nothing to close, and the refusal says why.
+ const hung = yield* close({ statusHangs: true }).pipe(Effect.flip, Effect.forkChild);
+ yield* TestClock.adjust("10 seconds");
+ assert.include((yield* Fiber.join(hung)).message, "Tailscale did not answer");
+ // Tailscale down, logged out, or not installed forwards nothing now.
+ for (const stderr of [
+ dialFailure("connection refused"),
+ "NeedsLogin: not logged in",
+ String.raw`Get "http://local-tailscaled.sock/localapi/v0/serve-config": open \\.\pipe\ProtectedPrefix\Administrators\Tailscale\tailscaled: The system cannot find the file specified.`,
+ ]) {
+ yield* close({ status: { stdout: "", exitCode: 1, stderr } });
+ }
+ const spawnFailing = (tag: "NotFound" | "PermissionDenied") =>
+ ManagedLimits.closeTailscaleServeTo(desktopAndLocal, {
+ host: "127.0.0.1",
+ port: 3773,
+ }).pipe(
+ Effect.provideService(
+ ChildProcessSpawner.ChildProcessSpawner,
+ ChildProcessSpawner.make(() =>
+ Effect.fail(
+ PlatformError.systemError({ _tag: tag, module: "ChildProcess", method: "spawn" }),
+ ),
+ ),
+ ),
+ );
+ yield* spawnFailing("NotFound");
+ // Node throws this instead when PATH ends in a file.
+ yield* ManagedLimits.closeTailscaleServeTo(desktopAndLocal, {
+ host: "127.0.0.1",
+ port: 3773,
+ }).pipe(
+ Effect.provideService(
+ ChildProcessSpawner.ChildProcessSpawner,
+ ChildProcessSpawner.make(() =>
+ Effect.die(Object.assign(new Error("spawn tailscale ENOTDIR"), { code: "ENOTDIR" })),
+ ),
+ ),
+ );
+ // A CLI that is there but will not run might still front a daemon with a mapping.
+ yield* spawnFailing("PermissionDenied").pipe(Effect.flip);
+ // Another app holds the port: its route is not ours, and it could let go before the bind.
+ const heldOffCalls: Array<ReadonlyArray<string>> = [];
+ const held = yield* close({}, heldOffCalls).pipe(
+ Effect.provideService(NetService.NetService, portHeld),
+ Effect.flip,
+ );
+ assert.deepEqual(heldOffCalls, []);
+ assert.include(held.message, "while it cannot bind 127.0.0.1:3773");
+ }).pipe(Effect.provideService(NetService.NetService, portFree));
+ },
+);
diff --git a/apps/server/src/policy/managedLimits.ts b/apps/server/src/policy/managedLimits.ts
new file mode 100644
index 00000000000..88df7d63c27
--- /dev/null
+++ b/apps/server/src/policy/managedLimits.ts
@@ -0,0 +1,239 @@
+/**
+ * managedLimits - what `limits.clients` and `limits.connect` in the managed policy allow, and the
+ * one error every refusal uses so each transport can show the administrator's organization.
+ *
+ * @module managedLimits
+ */
+import type {
+ ManagedPolicyClient,
+ ManagedPolicyDocument,
+ ServerAuthPolicy,
+} from "@t3tools/contracts";
+import {
+ disableTailscaleServe,
+ disableTailscaleServeTcp,
+ readTailscaleServeRoutesTo,
+ tailscaleServeOffArgs,
+ readTailscaleStatus,
+ type TailscaleServeRoute,
+ type TailscaleStderrDiagnostic,
+} from "@t3tools/tailscale";
+import * as Effect from "effect/Effect";
+import * as PlatformError from "effect/PlatformError";
+import * as Schema from "effect/Schema";
+
+import * as NetService from "@t3tools/shared/Net";
+
+import { loopbackBindAddress } from "../auth/utils.ts";
+
+type PolicyDocument = { readonly document: ManagedPolicyDocument | undefined };
+
+export class ManagedPolicyRefusedError extends Schema.TaggedError<ManagedPolicyRefusedError>()(
+ "ManagedPolicyRefusedError",
+ {
+ organization: Schema.String,
+ /** What the policy does not allow, for example "T3 Connect". */
+ action: Schema.String,
+ /** What that means for this request, for example "so the server cannot listen on 0.0.0.0". */
+ detail: Schema.optionalKey(Schema.String),
+ },
+) {
+ override get message(): string {
+ return `${this.organization}'s policy does not allow ${this.action}${
+ this.detail === undefined ? "" : `, ${this.detail}`
+ }.`;
+ }
+}
+
+const CLIENT_AUTH_POLICY: Record<ManagedPolicyClient, ServerAuthPolicy> = {
+ desktop: "desktop-managed-local",
+ "local-browser": "loopback-browser",
+ remote: "remote-reachable",
+};
+
+const AUTH_POLICY_ACTION: Record<ServerAuthPolicy, string> = {
+ "desktop-managed-local": "the desktop app",
+ "loopback-browser": "browsers on this machine",
+ "remote-reachable": "remote clients",
+ "unsafe-no-auth": "running without authentication",
+};
+
+/** Whether the server may run with `authPolicy`. Any policy file rules out `unsafe-no-auth`. */
+export function allowsAuthPolicy(policy: PolicyDocument, authPolicy: ServerAuthPolicy): boolean {
+ if (policy.document === undefined) return true;
+ if (authPolicy === "unsafe-no-auth") return false;
+ const clients = policy.document.limits?.clients;
+ return (
+ clients === undefined || clients.some((client) => CLIENT_AUTH_POLICY[client] === authPolicy)
+ );
+}
+
+/** Whether anything off this machine may pair, by LAN, Tailscale, or a minted link. */
+export const allowsRemoteClients = (policy: PolicyDocument) =>
+ allowsAuthPolicy(policy, "remote-reachable");
+
+/** T3 Connect is a way for remote clients in, so a policy without `remote` turns it off too. */
+export const allowsConnect = (policy: PolicyDocument) =>
+ policy.document?.limits?.connect !== false && allowsRemoteClients(policy);
+
+const refuse = (policy: PolicyDocument, action: string, detail?: string) =>
+ new ManagedPolicyRefusedError({
+ organization: policy.document?.organization ?? "Your organization",
+ action,
+ ...(detail === undefined ? {} : { detail }),
+ });
+
+export const refuseConnect = (policy: PolicyDocument) => refuse(policy, "T3 Connect");
+
+// Node throws ENOTDIR, outside the spawner's error mapping, when PATH ends in a file.
+const isMissingCli = (cause: unknown) =>
+ (PlatformError.isPlatformError(cause) && cause.reason._tag === "NotFound") ||
+ (cause instanceof Error && "code" in cause && cause.code === "ENOTDIR");
+
+const NOTHING_FORWARDED: ReadonlyArray<TailscaleServeRoute> = [];
+
+/** Tailscale answers that leave nothing forwarding here right now. */
+const NOTHING_TO_CLOSE: ReadonlySet<TailscaleStderrDiagnostic | undefined> = new Set([
+ "not-running",
+ "not-logged-in",
+]);
+
+/**
+ * Turns off the Tailscale Serve routes that forward to the server at `target`, such as one
+ * `t3 pair --tailscale` left from before the policy, and keeps every other route. Runs before the
+ * server binds, and fails unless a fresh read shows no route here, since `off` can exit 0 and
+ * leave it. Without the CLI, or with Tailscale down or logged out, nothing forwards.
+ */
+export const closeTailscaleServeTo = Effect.fn("managedLimits.closeTailscaleServeTo")(function* (
+ policy: PolicyDocument,
+ target: { readonly host: string; readonly port: number },
+) {
+ if (allowsRemoteClients(policy)) return;
+ // Another app holds the port, so its routes are not ours to remove. It could let go before the
+ // bind, which would then take over those routes, so the server does not start.
+ if (!(yield* (yield* NetService.NetService).canListenOnHost(target.port, target.host))) {
+ return yield* refuseRemoteClients(
+ policy,
+ `so the server does not start while it cannot bind ${target.host}:${target.port}; if another app holds that port, the server would take over its Tailscale Serve routes`,
+ );
+ }
+ const readRoutes = readTailscaleServeRoutesTo(target).pipe(
+ Effect.catchTags({
+ // Only a CLI that is not there; one that will not run might still front a daemon.
+ TailscaleCommandSpawnError: (error) =>
+ isMissingCli(error.cause) ? Effect.succeed(NOTHING_FORWARDED) : Effect.fail(error),
+ TailscaleCommandExitError: (error) =>
+ NOTHING_TO_CLOSE.has(error.stderrDiagnostic)
+ ? Effect.succeed(NOTHING_FORWARDED)
+ : Effect.fail(error),
+ }),
+ // Tailscale errors carry only labelled diagnostics, never raw stderr, so they are safe to log.
+ Effect.tapError((cause) =>
+ Effect.logWarning("Tailscale Serve could not be checked", { cause }),
+ ),
+ Effect.mapError((error) =>
+ refuseRemoteClients(
+ policy,
+ error._tag === "TailscaleCommandTimeoutError"
+ ? // Seen on a Mac where Tailscale is installed but was never set up.
+ "so the server does not start until Tailscale Serve can be checked, and Tailscale did not answer; open Tailscale and finish setting it up, or remove it"
+ : "so the server does not start until Tailscale Serve can be checked",
+ ),
+ ),
+ );
+ const found = yield* readRoutes;
+ if (found.length === 0) return;
+ // `off` acts on the machine's current name, so a web route under a former name stays.
+ const currentName = found.some((route) => route.mount !== undefined && route.owner === undefined)
+ ? yield* readTailscaleStatus.pipe(
+ Effect.map((status) => status.magicDnsName?.toLowerCase() ?? null),
+ Effect.orElseSucceed(() => null),
+ )
+ : null;
+ const formerName = (route: TailscaleServeRoute) =>
+ route.owner === undefined &&
+ route.host !== undefined &&
+ currentName !== null &&
+ route.host.toLowerCase() !== currentName;
+ // A Service is shared across the tailnet, and a foreground route lives as long as its command.
+ const removable = (route: TailscaleServeRoute) =>
+ route.owner === undefined &&
+ route.ambiguous === undefined &&
+ (route.mount === undefined || (currentName !== null && !formerName(route)));
+ for (const route of found.filter(removable)) {
+ yield* (
+ route.mount === undefined
+ ? disableTailscaleServeTcp(route.servePort)
+ : disableTailscaleServe(route)
+ ).pipe(
+ Effect.catch((cause) =>
+ Effect.logWarning("Tailscale Serve route could not be turned off", { ...route, cause }),
+ ),
+ );
+ }
+ const left = yield* readRoutes;
+ if (left.length > 0) {
+ const describe = (route: TailscaleServeRoute) => {
+ const where = `port ${route.servePort}${route.mount === undefined ? "" : ` at ${route.mount}`} here`;
+ const off = tailscaleServeOffArgs(route);
+ if (off === undefined) return `${where}; stop the "tailscale serve" command that runs it`;
+ if (formerName(route)) {
+ return `${where} under ${route.host}, a former name of this machine, which "tailscale serve ... off" cannot reach; run "tailscale serve reset" and set up your other routes again`;
+ }
+ const command = `"tailscale ${off.join(" ")}"`;
+ // Without the current name, `off` might act on another name's route at this path.
+ if (currentName === null && route.owner === undefined && route.host !== undefined) {
+ return `${where} under ${route.host}; if that is this machine's current name, turn it off with ${command}`;
+ }
+ return route.ambiguous !== undefined
+ ? `${where}, and its target ${route.ambiguous} might be another service on this port; check it, then turn it off with ${command}`
+ : `${where}; turn it off with ${command}`;
+ };
+ return yield* refuseRemoteClients(
+ policy,
+ `so the server does not start while Tailscale Serve forwards ${left.map(describe).join(", and ")}`,
+ );
+ }
+ yield* Effect.logInfo("Turned off Tailscale Serve the managed policy does not allow", {
+ routes: found,
+ });
+});
+
+export const refuseRemoteClients = (policy: PolicyDocument, detail?: string) =>
+ refuse(policy, AUTH_POLICY_ACTION["remote-reachable"], detail);
+
+/**
+ * Fails when the server would accept clients the policy leaves out; otherwise returns the address
+ * to bind. Runs before the server binds, so a refused configuration never listens, not even
+ * briefly. Without `remote` that address is the loopback literal the check approved, never a name.
+ */
+export const checkServerReachability = Effect.fn("managedLimits.checkServerReachability")(
+ function* (
+ policy: PolicyDocument,
+ input: {
+ readonly authPolicy: ServerAuthPolicy;
+ readonly host: string | undefined;
+ readonly tailscaleServeEnabled: boolean;
+ /** The background service chose `host` to reach private networks; the user did not. */
+ readonly privateNetworkOnly?: boolean | undefined;
+ },
+ ) {
+ const cannotListen = () =>
+ refuseRemoteClients(
+ policy,
+ input.privateNetworkOnly === true
+ ? "so the background service cannot listen on private networks; set T3CODE_HOST=127.0.0.1 in its service.env"
+ : `so the server cannot listen on ${input.host === "" ? "every interface" : (input.host ?? "this host")}`,
+ );
+ if (!allowsAuthPolicy(policy, input.authPolicy)) {
+ return yield* input.authPolicy === "remote-reachable"
+ ? cannotListen()
+ : refuse(policy, AUTH_POLICY_ACTION[input.authPolicy]);
+ }
+ if (allowsRemoteClients(policy)) return input.host ?? "127.0.0.1";
+ if (input.tailscaleServeEnabled) {
+ return yield* refuseRemoteClients(policy, "so Tailscale Serve cannot be turned on");
+ }
+ return loopbackBindAddress(input.host) ?? (yield* cannotListen());
+ },
+);
diff --git a/apps/server/src/policy/managedProviders.ts b/apps/server/src/policy/managedProviders.ts
new file mode 100644
index 00000000000..cbf0f0a1d9b
--- /dev/null
+++ b/apps/server/src/policy/managedProviders.ts
@@ -0,0 +1,598 @@
+import {
+ AntigravitySettings,
+ ClaudeSettings,
+ CodexSettings,
+ defaultInstanceIdForDriver,
+ disallowedProviderMessage,
+ type ManagedProviderInstance,
+ type ManagedProviderLimits,
+ type ManagedPolicySummary,
+ ProviderDriverKind,
+ type ProviderInstanceConfig,
+ type ProviderInstanceEnvironmentVariable,
+ type ProviderInstanceId,
+ resolveProviderInstanceEnabled,
+ type RuntimeMode,
+ type ServerSettings,
+} from "@t3tools/contracts";
+import { acpRegistryClient } from "@t3tools/provider-acp-registry/client";
+import { cursorClient } from "@t3tools/provider-cursor/client";
+import { fxClient } from "@t3tools/provider-fx/client";
+import { grokClient } from "@t3tools/provider-grok/client";
+import { museClient } from "@t3tools/provider-muse/client";
+import { openCodeClient } from "@t3tools/provider-opencode/client";
+import { piClient } from "@t3tools/provider-pi/client";
+import type { ProviderClientDefinition } from "@t3tools/provider-core/client";
+
+interface KnownDriver {
+ readonly label: string;
+ readonly configFields: ReadonlySet<string>;
+ readonly hasDefaultInstance: boolean;
+}
+
+const known = (
+ driverKind: string,
+ label: string,
+ settingsSchema: { readonly fields: object },
+ hasDefaultInstance = true,
+) =>
+ [
+ ProviderDriverKind.make(driverKind),
+ { label, configFields: new Set(Object.keys(settingsSchema.fields)), hasDefaultInstance },
+ ] as const;
+
+const PACKAGED_CLIENTS: ReadonlyArray<ProviderClientDefinition> = [
+ cursorClient,
+ grokClient,
+ fxClient,
+ museClient,
+ openCodeClient,
+ piClient,
+ acpRegistryClient,
+];
+
+/**
+ * Fields that make an instance launch without the settings a pin sets: managed Codex runs T3's own
+ * runtime against OpenAI, and a server URL points OpenCode at a server it does not start. A policy
+ * that owns a pin owns these too, holding each at the value given here, which clients still send
+ * when they add an instance.
+ */
+const PIN_BYPASS_FIELDS: ReadonlyMap<
+ ProviderDriverKind,
+ Readonly<Record<string, unknown>>
+> = new Map<ProviderDriverKind, Readonly<Record<string, unknown>>>([
+ [ProviderDriverKind.make("codex"), { setupMode: "existing" }],
+ [ProviderDriverKind.make("opencode"), { serverUrl: "" }],
+]);
+
+/** Drivers this build knows, by the names users see; a policy naming any other is refused. */
+const KNOWN_DRIVERS: ReadonlyMap<ProviderDriverKind, KnownDriver> = new Map([
+ known("codex", "Codex", CodexSettings),
+ known("claudeAgent", "Claude", ClaudeSettings),
+ known("antigravity", "Antigravity", AntigravitySettings),
+ ...PACKAGED_CLIENTS.map((client) =>
+ known(client.driverKind, client.label, client.settingsSchema, client.hasDefaultInstance),
+ ),
+]);
+
+const PINNED_CONFIG_FIELDS = ["binaryPath", "launchArgs"] as const;
+type PinnedConfigField = (typeof PINNED_CONFIG_FIELDS)[number];
+
+/**
+ * Fields that decide what a provider starts and reads on startup; a driver has those its schema
+ * has. Under a ceiling they are the administrator's: a wrapper binary, a skip-permissions flag, or
+ * a config directory with allow rules each outrank T3 Code's mode, and no flag filter stops a wrapper.
+ */
+const LAUNCH_CONFIG_FIELDS = [
+ "binaryPath",
+ "launchArgs",
+ "homePath",
+ "shadowHomePath",
+ "commandPath",
+ "commandArgs",
+ "serverUrl",
+] as const;
+
+export type ProviderWriteVerdict =
+ | { readonly _tag: "Allowed"; readonly settings: ServerSettings }
+ | { readonly _tag: "Locked"; readonly path: string }
+ | {
+ readonly _tag: "Disallowed";
+ readonly instanceId: ProviderInstanceId;
+ readonly label: string;
+ };
+
+/**
+ * How a policy's `limits.providers` shapes provider instances. Like settings locks, pinned
+ * fields are laid over instances on every read and never written to the user's settings file.
+ */
+export interface ManagedProviders {
+ readonly isDriverAllowed: (driver: ProviderDriverKind) => boolean;
+ /** Lay pinned fields over every instance of a pinned driver, its default instance included. */
+ readonly applyLimits: (settings: ServerSettings) => ServerSettings;
+ /**
+ * Vet a write from stored `current` to `next`. Refuses enabling a disallowed driver and moving
+ * a locked field off its pinned value. Pinned values a client sends back are dropped, so the
+ * user's own values return once the policy is gone.
+ */
+ readonly vetWrite: (current: ServerSettings, next: ServerSettings) => ProviderWriteVerdict;
+ /**
+ * Per driver, the instance fields users cannot change, for clients. `environment` alone means
+ * every variable.
+ */
+ readonly lockedInstanceFields: Readonly<Record<string, ReadonlyArray<string>>>;
+}
+
+export const unmanagedProviders: ManagedProviders = {
+ isDriverAllowed: () => true,
+ applyLimits: (settings) => settings,
+ vetWrite: (_current, next) => ({ _tag: "Allowed", settings: next }),
+ lockedInstanceFields: {},
+};
+
+const labelFor = (driver: ProviderDriverKind) => KNOWN_DRIVERS.get(driver)?.label ?? driver;
+
+/** Why the policy clients were told about keeps `driver` from running, or undefined when it may run. */
+export const disallowedDriverReason = (
+ summary: ManagedPolicySummary | undefined,
+ driver: ProviderDriverKind,
+): string | undefined => {
+ const allowed = summary?.limits?.providers?.allowedDrivers;
+ return allowed === undefined || allowed.includes(driver)
+ ? undefined
+ : disallowedProviderMessage(summary?.organization, labelFor(driver));
+};
+
+/**
+ * Variables that replace a provider's launch configuration. From the environment that starts the
+ * server they are ignored under any policy, which can lock launch arguments in more than one way;
+ * from an instance's own variables they are ignored when the policy locks launch arguments.
+ */
+const LAUNCH_OVERRIDE_VARIABLES = ["T3CODE_CODEX_LAUNCH_ARGS"] as const;
+
+/** The environment provider drivers launch from under the policy clients were told about. */
+export const providerHostEnvironment = (
+ summary: ManagedPolicySummary | undefined,
+ environment: NodeJS.ProcessEnv,
+): NodeJS.ProcessEnv => {
+ if (summary === undefined) return environment;
+ const next = { ...environment };
+ for (const name of Object.keys(next)) {
+ if (LAUNCH_OVERRIDE_VARIABLES.some((override) => override === name.toUpperCase())) {
+ delete next[name];
+ }
+ }
+ return next;
+};
+
+/** Each driver's home variable, and the settings that rewrite it at launch. */
+const HOME_VARIABLES: ReadonlyMap<
+ ProviderDriverKind,
+ { readonly variable: string; readonly fields: ReadonlyArray<string> }
+> = new Map([
+ [ProviderDriverKind.make("claudeAgent"), { variable: "CLAUDE_CONFIG_DIR", fields: ["homePath"] }],
+ [
+ ProviderDriverKind.make("codex"),
+ { variable: "CODEX_HOME", fields: ["homePath", "shadowHomePath"] },
+ ],
+]);
+
+const configRecord = (instance: ProviderInstanceConfig | undefined): Record<string, unknown> =>
+ instance?.config !== null &&
+ typeof instance?.config === "object" &&
+ !Array.isArray(instance.config)
+ ? (instance.config as Record<string, unknown>)
+ : {};
+
+/** Empty strings and empty lists are how clients clear a field, so they count as unset. */
+const configValue = (instance: ProviderInstanceConfig | undefined, field: string) => {
+ const value = configRecord(instance)[field];
+ return value === "" || (Array.isArray(value) && value.length === 0) ? undefined : value;
+};
+
+const sameValue = (left: unknown, right: unknown) =>
+ left === right || JSON.stringify(left) === JSON.stringify(right);
+
+const sameVariable = (
+ left: ProviderInstanceEnvironmentVariable | undefined,
+ right: ProviderInstanceEnvironmentVariable | undefined,
+) =>
+ left === right ||
+ (left !== undefined &&
+ right !== undefined &&
+ left.value === right.value &&
+ left.sensitive === right.sensitive);
+
+const pinnedFields = (pin: ManagedProviderInstance): ReadonlyArray<PinnedConfigField> =>
+ PINNED_CONFIG_FIELDS.filter((field) => pin[field] !== undefined);
+
+/**
+ * What the administrator owns on one driver's instances. `config` fields take the pin or the
+ * default, never the user's value; `fill` fields take the pin only where the user left them empty.
+ * `environment`: `all` runs with only pinned variables, `locked` lets them win, `fill` fills gaps.
+ */
+interface DriverRule {
+ readonly pin: ManagedProviderInstance | undefined;
+ readonly config: ReadonlyArray<string>;
+ readonly fill: ReadonlyArray<PinnedConfigField>;
+ readonly environment: "all" | "locked" | "fill";
+}
+
+const pinnedValue = (pin: ManagedProviderInstance | undefined, field: string): unknown =>
+ pin === undefined ? undefined : (pin as Record<string, unknown>)[field];
+
+const overlayInstance = (
+ instance: ProviderInstanceConfig,
+ rule: DriverRule,
+ variableKey: (name: string) => string,
+): ProviderInstanceConfig => {
+ const config = { ...configRecord(instance) };
+ for (const field of rule.config) {
+ const value = pinnedValue(rule.pin, field);
+ if (value === undefined) delete config[field];
+ else config[field] = value;
+ }
+ for (const field of rule.fill) {
+ if (configValue(instance, field) === undefined) config[field] = rule.pin?.[field];
+ }
+ const pinnedEnvironment = (rule.pin?.environment ?? []).map((variable) => ({
+ name: variable.name,
+ value: variable.value,
+ sensitive: false,
+ }));
+ const pinnedByName = new Map(
+ pinnedEnvironment.map((variable) => [variableKey(variable.name), variable]),
+ );
+ const environment: Array<NonNullable<ProviderInstanceConfig["environment"]>[number]> =
+ rule.environment === "all" ? pinnedEnvironment : [];
+ if (rule.environment !== "all") {
+ const seen = new Set<string>();
+ // A user's override would replace launch arguments the administrator locked.
+ const overrides = rule.config.includes("launchArgs")
+ ? new Set(LAUNCH_OVERRIDE_VARIABLES.map(variableKey))
+ : new Set<string>();
+ // The last entry for a name wins at launch, so a lock replaces every entry with that name.
+ for (const variable of instance.environment ?? []) {
+ const key = variableKey(variable.name);
+ if (overrides.has(key)) continue;
+ const pinned = rule.environment === "locked" ? pinnedByName.get(key) : undefined;
+ if (pinned === undefined) environment.push(variable);
+ else if (!seen.has(key)) environment.push(pinned);
+ seen.add(key);
+ }
+ for (const pinned of pinnedEnvironment) {
+ if (!seen.has(variableKey(pinned.name))) environment.push(pinned);
+ }
+ }
+ const { config: _config, environment: _environment, ...envelope } = instance;
+ return {
+ ...envelope,
+ ...(instance.config === undefined && Object.keys(config).length === 0 ? {} : { config }),
+ ...(environment.length === 0 ? {} : { environment }),
+ };
+};
+
+/**
+ * Build the overlay for `limits.providers` and `limits.maxRuntimeMode`, or say why it cannot be
+ * enforced. A ceiling takes each driver's launch fields and its whole `environment`, which can
+ * carry `CLAUDE_CONFIG_DIR`, `PATH`, or `NODE_OPTIONS`; a deny list would miss the next one.
+ */
+export function makeManagedProviders(
+ limits: ManagedProviderLimits,
+ maxRuntimeMode: RuntimeMode | undefined,
+ platform: NodeJS.Platform,
+):
+ | { readonly _tag: "Valid"; readonly providers: ManagedProviders }
+ | { readonly _tag: "Invalid"; readonly reason: string } {
+ // Windows reads a variable name without regard to case, so there a lock covers every spelling.
+ const variableKey = (name: string) => (platform === "win32" ? name.toUpperCase() : name);
+ for (const driver of limits.allowedDrivers ?? []) {
+ if (!KNOWN_DRIVERS.has(driver)) {
+ return { _tag: "Invalid", reason: `"${driver}" in allowedDrivers is not a known provider` };
+ }
+ }
+ const pins = new Map<ProviderDriverKind, ManagedProviderInstance>();
+ for (const [rawDriver, pin] of Object.entries(limits.instances ?? {})) {
+ const driver = ProviderDriverKind.make(rawDriver);
+ const known = KNOWN_DRIVERS.get(driver);
+ if (known === undefined) {
+ return { _tag: "Invalid", reason: `"${driver}" in instances is not a known provider` };
+ }
+ const unsupported = pinnedFields(pin).find((field) => !known.configFields.has(field));
+ if (unsupported !== undefined) {
+ return {
+ _tag: "Invalid",
+ reason: `the ${known.label} provider has no ${unsupported} setting`,
+ };
+ }
+ const names = (pin.environment ?? []).map((variable) => variableKey(variable.name));
+ if (new Set(names).size !== names.length) {
+ return { _tag: "Invalid", reason: `instances.${driver}.environment repeats a variable` };
+ }
+ pins.set(driver, pin);
+ }
+
+ const rules = new Map<ProviderDriverKind, DriverRule>();
+ for (const [driver, known] of KNOWN_DRIVERS) {
+ const pin = pins.get(driver);
+ const bypasses = pin === undefined ? [] : Object.keys(PIN_BYPASS_FIELDS.get(driver) ?? {});
+ if (maxRuntimeMode !== undefined) {
+ rules.set(driver, {
+ pin,
+ config: [
+ ...LAUNCH_CONFIG_FIELDS.filter((field) => known.configFields.has(field)),
+ ...bypasses,
+ ],
+ fill: [],
+ environment: "all",
+ });
+ } else if (pin !== undefined) {
+ // A home path setting rewrites the provider's home variable at launch, so a lock on that
+ // variable owns the setting too.
+ const home = HOME_VARIABLES.get(driver);
+ const homeLocked =
+ home !== undefined &&
+ (pin.environment ?? []).some(
+ (variable) => variableKey(variable.name) === variableKey(home.variable),
+ );
+ rules.set(driver, {
+ pin,
+ config: pin.locked
+ ? [...pinnedFields(pin), ...bypasses, ...(homeLocked ? home.fields : [])]
+ : [],
+ fill: pin.locked ? [] : pinnedFields(pin),
+ environment: pin.locked ? "locked" : "fill",
+ });
+ }
+ }
+
+ const allowed =
+ limits.allowedDrivers === undefined ? undefined : new Set<string>(limits.allowedDrivers);
+ const isDriverAllowed = (driver: ProviderDriverKind) => allowed?.has(driver) ?? true;
+ const allowedSelection = (
+ settings: ServerSettings,
+ selection: { readonly instanceId: ProviderInstanceId } | null | undefined,
+ ) =>
+ selection == null ||
+ isDriverAllowed(
+ settings.providerInstances[selection.instanceId]?.driver ??
+ ProviderDriverKind.make(selection.instanceId),
+ );
+
+ const cache = new WeakMap<ServerSettings, ServerSettings>();
+ const applyLimits = (settings: ServerSettings): ServerSettings => {
+ const cached = cache.get(settings);
+ if (cached !== undefined) return cached;
+ const providerInstances: Record<string, ProviderInstanceConfig> = {
+ ...settings.providerInstances,
+ };
+ // Default instances exist without a settings entry until the user edits one; pin them too.
+ for (const driver of pins.keys()) {
+ const instanceId = defaultInstanceIdForDriver(driver);
+ if (KNOWN_DRIVERS.get(driver)?.hasDefaultInstance === false) continue;
+ if (providerInstances[instanceId] === undefined) providerInstances[instanceId] = { driver };
+ }
+ for (const [instanceId, instance] of Object.entries(providerInstances)) {
+ const rule = rules.get(instance.driver);
+ if (rule !== undefined) {
+ providerInstances[instanceId] = overlayInstance(instance, rule, variableKey);
+ }
+ }
+ // A cleared selection falls back to the text generation model, which is resolved afterwards.
+ const result: ServerSettings = {
+ ...settings,
+ providerInstances: providerInstances as ServerSettings["providerInstances"],
+ sourceControlWriterModelSelection: allowedSelection(
+ settings,
+ settings.sourceControlWriterModelSelection,
+ )
+ ? settings.sourceControlWriterModelSelection
+ : null,
+ reviewGuideModelSelection: allowedSelection(settings, settings.reviewGuideModelSelection)
+ ? settings.reviewGuideModelSelection
+ : null,
+ };
+ cache.set(settings, result);
+ return result;
+ };
+
+ type Locked = { readonly _tag: "Locked"; readonly path: string };
+
+ /**
+ * Vet the environment a client sent. Pinned values it echoes back are dropped; anything else
+ * the administrator owns must match what is stored. Returns the environment to store.
+ */
+ const vetEnvironment = (
+ instanceId: string,
+ stored: ProviderInstanceConfig | undefined,
+ next: ProviderInstanceConfig,
+ rule: DriverRule,
+ ):
+ | Locked
+ | {
+ readonly _tag: "Kept";
+ readonly environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>;
+ } => {
+ const pinned = rule.pin?.environment ?? [];
+ const storedVariable = (name: string) =>
+ stored?.environment?.find((existing) => variableKey(existing.name) === variableKey(name));
+ const storedUnchanged = (variable: ProviderInstanceEnvironmentVariable) =>
+ (stored?.environment ?? []).some((existing) => sameVariable(variable, existing));
+ const echoed = (variable: ProviderInstanceEnvironmentVariable) =>
+ !variable.sensitive &&
+ pinned.some((pin) => pin.name === variable.name && pin.value === variable.value);
+ if (rule.environment === "all") {
+ // Only the pinned variables were shown, so the user's own stay as stored.
+ for (const variable of next.environment ?? []) {
+ if (echoed(variable) || storedUnchanged(variable)) continue;
+ return { _tag: "Locked", path: `providerInstances.${instanceId}.environment` };
+ }
+ return { _tag: "Kept", environment: stored?.environment ?? [] };
+ }
+ let environment: ReadonlyArray<ProviderInstanceEnvironmentVariable> = next.environment ?? [];
+ for (const variable of pinned) {
+ const sent = environment.find(
+ (existing) => variableKey(existing.name) === variableKey(variable.name),
+ );
+ const kept = storedVariable(variable.name);
+ if ((sent !== undefined && echoed(sent)) || sameVariable(sent, kept)) {
+ // Put the user's own entries back where it was sent, or drop the echoed policy value.
+ const storedEntries = (stored?.environment ?? []).filter(
+ (existing) => variableKey(existing.name) === variableKey(variable.name),
+ );
+ let restored = false;
+ environment = environment.flatMap((existing) => {
+ if (variableKey(existing.name) !== variableKey(variable.name)) return [existing];
+ if (restored) return [];
+ restored = true;
+ return storedEntries;
+ });
+ } else if (rule.environment === "locked") {
+ return {
+ _tag: "Locked",
+ path: `providerInstances.${instanceId}.environment.${variable.name}`,
+ };
+ }
+ }
+ // The client never saw a launch override the lock hides, so keep the stored one.
+ if (rule.config.includes("launchArgs")) {
+ const overrides = new Set(LAUNCH_OVERRIDE_VARIABLES.map(variableKey));
+ environment = [
+ ...environment.filter((variable) => !overrides.has(variableKey(variable.name))),
+ ...(stored?.environment ?? []).filter((variable) =>
+ overrides.has(variableKey(variable.name)),
+ ),
+ ];
+ }
+ return { _tag: "Kept", environment };
+ };
+
+ const vetInstance = (
+ instanceId: string,
+ stored: ProviderInstanceConfig | undefined,
+ next: ProviderInstanceConfig,
+ rule: DriverRule,
+ ): Locked | { readonly _tag: "Kept"; readonly instance: ProviderInstanceConfig | undefined } => {
+ const config = { ...configRecord(next) };
+ const harmless = PIN_BYPASS_FIELDS.get(next.driver) ?? {};
+ for (const field of [...rule.config, ...rule.fill]) {
+ const value = configValue(next, field);
+ const storedValue = configValue(stored, field);
+ if (
+ sameValue(value, pinnedValue(rule.pin, field)) ||
+ sameValue(value, storedValue) ||
+ (field in harmless && sameValue(value, harmless[field]))
+ ) {
+ if (storedValue === undefined) delete config[field];
+ else config[field] = configRecord(stored)[field];
+ } else if (rule.config.includes(field)) {
+ return { _tag: "Locked", path: `providerInstances.${instanceId}.config.${field}` };
+ }
+ }
+ const vettedEnvironment = vetEnvironment(instanceId, stored, next, rule);
+ if (vettedEnvironment._tag === "Locked") return vettedEnvironment;
+ const { environment } = vettedEnvironment;
+ const { config: _config, environment: _environment, ...envelope } = next;
+ const kept: ProviderInstanceConfig = {
+ ...envelope,
+ ...(Object.keys(config).length === 0 && stored?.config === undefined ? {} : { config }),
+ ...(environment.length === 0 ? {} : { environment }),
+ };
+ // A default instance the client echoed back with only pinned values stays implicit.
+ const echoedDefault =
+ stored === undefined &&
+ instanceId === defaultInstanceIdForDriver(next.driver) &&
+ Object.keys(kept).length === 1;
+ return { _tag: "Kept", instance: echoedDefault ? undefined : kept };
+ };
+
+ const vetWrite = (current: ServerSettings, next: ServerSettings): ProviderWriteVerdict => {
+ const providerInstances: Record<string, ProviderInstanceConfig> = {};
+ for (const [instanceId, instance] of Object.entries(next.providerInstances)) {
+ const stored = current.providerInstances[instanceId as ProviderInstanceId];
+ // Clients echo instances with policy fields laid over them, so compare only whether it runs.
+ // A driver's default instance runs before it is configured.
+ const wasEnabled =
+ stored !== undefined
+ ? stored.driver === instance.driver && resolveProviderInstanceEnabled(stored)
+ : instanceId === defaultInstanceIdForDriver(instance.driver);
+ if (
+ !isDriverAllowed(instance.driver) &&
+ resolveProviderInstanceEnabled(instance) &&
+ !wasEnabled
+ ) {
+ return {
+ _tag: "Disallowed",
+ instanceId: instanceId as ProviderInstanceId,
+ label: labelFor(instance.driver),
+ };
+ }
+ const rule = rules.get(instance.driver);
+ if (rule === undefined) {
+ providerInstances[instanceId] = instance;
+ continue;
+ }
+ const vetted = vetInstance(
+ instanceId,
+ stored?.driver === instance.driver ? stored : undefined,
+ instance,
+ rule,
+ );
+ if (vetted._tag === "Locked") return vetted;
+ if (vetted.instance !== undefined) providerInstances[instanceId] = vetted.instance;
+ }
+ // A project can switch an instance on for itself; that is enabling it too.
+ for (const [projectId, overrides] of Object.entries(next.projectSettingsOverrides)) {
+ const storedOverrides =
+ current.projectSettingsOverrides[projectId as keyof typeof current.projectSettingsOverrides]
+ ?.providerInstances;
+ for (const [instanceId, override] of Object.entries(overrides.providerInstances ?? {})) {
+ const driver =
+ next.providerInstances[instanceId as ProviderInstanceId]?.driver ??
+ ProviderDriverKind.make(instanceId);
+ if (
+ override.enabled === true &&
+ storedOverrides?.[instanceId as ProviderInstanceId]?.enabled !== true &&
+ !isDriverAllowed(driver)
+ ) {
+ return {
+ _tag: "Disallowed",
+ instanceId: instanceId as ProviderInstanceId,
+ label: labelFor(driver),
+ };
+ }
+ }
+ }
+ return {
+ _tag: "Allowed",
+ settings: {
+ ...next,
+ providerInstances: providerInstances as ServerSettings["providerInstances"],
+ },
+ };
+ };
+
+ const lockedInstanceFields = Object.fromEntries(
+ [...rules].flatMap(([driver, rule]) => {
+ const fields = [
+ ...rule.config.map((field) => `config.${field}`),
+ ...(rule.environment === "all"
+ ? ["environment"]
+ : rule.environment === "locked"
+ ? (rule.pin?.environment ?? []).map((variable) => `environment.${variable.name}`)
+ : []),
+ ];
+ return fields.length === 0 ? [] : [[driver, fields] as const];
+ }),
+ );
+
+ return {
+ _tag: "Valid",
+ providers: {
+ isDriverAllowed,
+ applyLimits,
+ vetWrite,
+ lockedInstanceFields,
+ },
+ };
+}
diff --git a/apps/server/src/policy/managedSettings.ts b/apps/server/src/policy/managedSettings.ts
new file mode 100644
index 00000000000..7ae0cf6aa2b
--- /dev/null
+++ b/apps/server/src/policy/managedSettings.ts
@@ -0,0 +1,502 @@
+import {
+ DEFAULT_SERVER_SETTINGS,
+ isRuntimeModeAbove,
+ type ManagedPolicySetting,
+ ProjectSettingsOverrides,
+ type RuntimeMode,
+ ServerSettings,
+ withIdleCompaction,
+} from "@t3tools/contracts";
+import * as Exit from "effect/Exit";
+import * as Schema from "effect/Schema";
+
+import { mapSettingsSecrets } from "../settingsSecrets.ts";
+
+const encodeSettings = Schema.encodeSync(ServerSettings);
+const decodeSettings = Schema.decodeUnknownSync(ServerSettings);
+const decodeSettingsExit = Schema.decodeUnknownExit(ServerSettings);
+
+/** Project overrides mirror these top-level keys, so a lock on one applies inside each project. */
+const PROJECT_OVERRIDE_KEYS: ReadonlySet<string> = new Set(
+ Object.keys(ProjectSettingsOverrides.fields),
+);
+/** Per-project stores; admins lock the top-level key and the lock reaches every project. */
+const UNMANAGEABLE_KEYS: ReadonlySet<string> = new Set([
+ "projectSettingsOverrides",
+ "projectAgentBrowserAccessOverrides",
+ "projectAutoPullOverrides",
+ "projectScriptOverrides",
+]);
+
+/** Legacy settings the server derives from another on every write; manage that one instead. */
+const DERIVED_FROM: ReadonlyMap<string, string> = new Map([
+ ["compactIdleThreads", "idleCompaction"],
+]);
+
+/**
+ * Settings another one overrides when it is set: `worktreeCleanup`, also per project, wins over
+ * the worktree rules in `storageCleanup`. A lock on the first alone would look enforced without
+ * being, so the second must be locked too.
+ */
+const OVERRIDDEN_BY: ReadonlyArray<readonly [overridden: string, by: string]> = [
+ ["storageCleanup.worktree", "worktreeCleanup"],
+];
+
+type Segments = ReadonlyArray<string>;
+
+/**
+ * The server derives the legacy switch from `idleCompaction` on every write, and shipped clients
+ * still read it, so values the policy sets carry the matching switch.
+ */
+const syncIdleCompaction = (settings: ServerSettings): ServerSettings =>
+ settings.idleCompaction === undefined
+ ? settings
+ : withIdleCompaction(settings, settings.idleCompaction);
+
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ value !== null && typeof value === "object" && !Array.isArray(value);
+
+const getPath = (tree: unknown, segments: Segments): unknown => {
+ let current = tree;
+ for (const segment of segments) {
+ if (!isRecord(current)) return undefined;
+ current = current[segment];
+ }
+ return current;
+};
+
+const setPath = (tree: unknown, segments: Segments, value: unknown): unknown => {
+ const [head, ...rest] = segments;
+ if (head === undefined) return value;
+ const record = isRecord(tree) ? tree : {};
+ if (value === undefined && rest.length === 0) {
+ const { [head]: _removed, ...remaining } = record;
+ return remaining;
+ }
+ return { ...record, [head]: setPath(record[head], rest, value) };
+};
+
+/** Fills keys `target` lacks from `defaults`, recursing into objects both sides hold. */
+const fillMissing = (target: unknown, defaults: unknown): unknown => {
+ if (!isRecord(target) || !isRecord(defaults)) return target;
+ const next: Record<string, unknown> = { ...target };
+ for (const [key, value] of Object.entries(defaults)) {
+ next[key] = key in target ? fillMissing(target[key], value) : value;
+ }
+ return next;
+};
+
+const jsonEqual = (left: unknown, right: unknown): boolean => {
+ if (Object.is(left, right)) return true;
+ if (Array.isArray(left) && Array.isArray(right)) {
+ return (
+ left.length === right.length && left.every((item, index) => jsonEqual(item, right[index]))
+ );
+ }
+ if (!isRecord(left) || !isRecord(right)) return false;
+ const leftKeys = Object.keys(left).filter((key) => left[key] !== undefined);
+ const rightKeys = Object.keys(right).filter((key) => right[key] !== undefined);
+ return (
+ leftKeys.length === rightKeys.length &&
+ leftKeys.every((key) => jsonEqual(left[key], right[key]))
+ );
+};
+
+/**
+ * Whether `value` agrees with a lock on every key it holds. Patches and project overrides carry
+ * only some of a locked object's keys, such as `{ enabled }` for a provider instance.
+ */
+const matchesLock = (value: unknown, lock: unknown): boolean =>
+ isRecord(value) && isRecord(lock)
+ ? Object.entries(value).every(
+ ([key, child]) => child === undefined || matchesLock(child, lock[key]),
+ )
+ : jsonEqual(value, lock);
+
+/** Whether `value` holds a key `existing` does not, at any depth. */
+const addsKeys = (existing: unknown, value: unknown): boolean =>
+ isRecord(existing) &&
+ isRecord(value) &&
+ Object.entries(value).some(([key, child]) =>
+ key in existing ? addsKeys(existing[key], child) : true,
+ );
+
+/**
+ * How a policy's `settings` shape the server's settings. Policy values are never written to
+ * the user's settings file: defaults fill keys the file leaves out, and locks are laid over the
+ * result on every read, so removing the policy brings the user's own settings back.
+ */
+export interface ManagedSettings {
+ /** Fill policy defaults into a parsed settings file before it is decoded. */
+ readonly withDefaults: (persisted: unknown) => unknown;
+ /** Built-in defaults with the policy's defaults applied; the settings file omits values equal to these. */
+ readonly defaults: ServerSettings;
+ /**
+ * Lay locked values over settings, including inside each project's overrides, and lower
+ * default runtime modes above the policy's ceiling to it.
+ */
+ readonly applyLocks: (settings: ServerSettings) => ServerSettings;
+ /**
+ * Vet a write from `current` to `next`. It is refused when it tries to move a locked path off
+ * its locked value, whether set in `patch` or changed by another route such as a legacy patch
+ * key. An allowed write keeps the user's stored values at locked paths, so a client re-sending
+ * the locked value does not overwrite what applies once the policy is gone.
+ */
+ readonly vetWrite: (
+ current: ServerSettings,
+ next: ServerSettings,
+ patch: unknown,
+ ) =>
+ | { readonly _tag: "Allowed"; readonly settings: ServerSettings }
+ | { readonly _tag: "Locked"; readonly path: string };
+ readonly lockedPaths: ReadonlyArray<string>;
+ /**
+ * Put back into a stripped settings file the values `stored`, the file before this write, held
+ * at or under paths the policy defaults: equal to the policy's default, they are still the
+ * user's choice. A key `isAtomic` names comes back whole or not at all. Undefined without
+ * policy defaults, so writers can skip reading the file.
+ */
+ readonly keepStored:
+ | ((
+ stripped: unknown,
+ settings: ServerSettings,
+ stored: unknown,
+ isAtomic: (key: string) => boolean,
+ ) => unknown)
+ | undefined;
+}
+
+export const unmanagedSettings: ManagedSettings = {
+ keepStored: undefined,
+ withDefaults: (persisted) => persisted,
+ defaults: DEFAULT_SERVER_SETTINGS,
+ applyLocks: (settings) => settings,
+ vetWrite: (_current, next) => ({ _tag: "Allowed", settings: next }),
+ lockedPaths: [],
+};
+
+interface Entry {
+ readonly path: string;
+ readonly segments: Segments;
+ /** As written in the policy, the encoded form. */
+ readonly value: unknown;
+}
+
+interface Lock extends Entry {
+ /** The decoded form, which is what patches carry. */
+ readonly decodedValue: unknown;
+}
+
+/** Locked paths as stored in the top level and in each project's overrides of `encoded`. */
+const lockTargets = (encoded: unknown, entry: Entry): ReadonlyArray<Segments> => {
+ const [head] = entry.segments;
+ if (head === undefined || !PROJECT_OVERRIDE_KEYS.has(head)) return [entry.segments];
+ const projects = getPath(encoded, ["projectSettingsOverrides"]);
+ const projectTargets = isRecord(projects)
+ ? Object.entries(projects)
+ .filter(([, overrides]) => isRecord(overrides) && overrides[head] !== undefined)
+ .map(([projectId]) => ["projectSettingsOverrides", projectId, ...entry.segments])
+ : [];
+ return [entry.segments, ...projectTargets];
+};
+
+/**
+ * A user's stored default runtime mode can sit above a ceiling deployed after it was chosen, and
+ * the built-in default is the broadest mode. Every new thread would then be refused, so the
+ * effective default is the ceiling instead. The stored value is untouched and returns with the
+ * policy's removal; existing threads keep their modes and are refused turns instead.
+ */
+const clampDefaultRuntimeModes = (
+ settings: ServerSettings,
+ ceiling: RuntimeMode,
+): ServerSettings => {
+ const projectsAbove = Object.entries(settings.projectSettingsOverrides).filter(
+ ([, overrides]) =>
+ overrides.defaultRuntimeMode !== undefined &&
+ isRuntimeModeAbove(overrides.defaultRuntimeMode, ceiling),
+ );
+ if (!isRuntimeModeAbove(settings.defaultRuntimeMode, ceiling) && projectsAbove.length === 0) {
+ return settings;
+ }
+ return {
+ ...settings,
+ defaultRuntimeMode: isRuntimeModeAbove(settings.defaultRuntimeMode, ceiling)
+ ? ceiling
+ : settings.defaultRuntimeMode,
+ projectSettingsOverrides: {
+ ...settings.projectSettingsOverrides,
+ ...Object.fromEntries(
+ projectsAbove.map(([projectId, overrides]) => [
+ projectId,
+ { ...overrides, defaultRuntimeMode: ceiling },
+ ]),
+ ),
+ },
+ };
+};
+
+/** Build the overlay for a policy's settings, or describe the first entry this build cannot apply. */
+export function makeManagedSettings(
+ settings: Readonly<Record<string, ManagedPolicySetting>>,
+ maxRuntimeMode?: RuntimeMode,
+):
+ | { readonly _tag: "Valid"; readonly settings: ManagedSettings }
+ | { readonly _tag: "Invalid"; readonly reason: string } {
+ const defaults: Entry[] = [];
+ const locks: Entry[] = [];
+ for (const [path, setting] of Object.entries(settings)) {
+ const segments = path.split(".");
+ const [head] = segments;
+ if (head === undefined || segments.some((segment) => segment.length === 0)) {
+ return { _tag: "Invalid", reason: `"${path}" is not a settings path` };
+ }
+ if (!(head in ServerSettings.fields) || UNMANAGEABLE_KEYS.has(head)) {
+ return { _tag: "Invalid", reason: `"${path}" is not a setting this version can manage` };
+ }
+ const source = DERIVED_FROM.get(head);
+ if (source !== undefined) {
+ return {
+ _tag: "Invalid",
+ reason: `"${head}" follows "${source}"; manage "${source}" instead`,
+ };
+ }
+ (setting.locked ? locks : defaults).push({ path, segments, value: setting.value });
+ }
+
+ for (const lock of locks) {
+ const unheld = OVERRIDDEN_BY.find(
+ ([overridden, by]) =>
+ (lock.path.startsWith(overridden) || overridden.startsWith(`${lock.path}.`)) &&
+ !locks.some((other) => other.path === by),
+ );
+ if (unheld !== undefined) {
+ return {
+ _tag: "Invalid",
+ reason: `"${lock.path}" can be overridden by "${unheld[1]}"; lock "${unheld[1]}" too`,
+ };
+ }
+ // An instance's fields override each other: a variable replaces launch arguments, a home
+ // path rewrites a home variable, and a setup mode brings its own runtime.
+ const [head, instanceId] = lock.segments;
+ if (head === "providerInstances" && instanceId !== undefined && lock.segments.length > 2) {
+ return {
+ _tag: "Invalid",
+ reason: `"${lock.path}" is one field of a provider instance whose fields override each other; lock "providerInstances.${instanceId}" as a whole, or pin fields with limits.providers.instances`,
+ };
+ }
+ }
+
+ // Apply every entry to the built-in defaults at once, and read each value back: a typo in a
+ // nested key or a value of the wrong type does not survive the round trip.
+ const builtIn = encodeSettings(DEFAULT_SERVER_SETTINGS);
+ const all = [...defaults, ...locks];
+ // A user's stored null would leave a nested lock building a partial object, so lock the whole
+ // setting instead.
+ const insideNullable = all.find((entry) =>
+ entry.segments
+ .slice(0, -1)
+ .some((_, index) =>
+ Exit.isSuccess(
+ decodeSettingsExit(setPath(builtIn, entry.segments.slice(0, index + 1), null)),
+ ),
+ ),
+ );
+ if (insideNullable !== undefined) {
+ return {
+ _tag: "Invalid",
+ reason: `"${insideNullable.path}" is inside a setting that can be empty; manage "${insideNullable.segments[0]}" as a whole`,
+ };
+ }
+ const applied = all.reduce<unknown>(
+ (tree, entry) => setPath(tree, entry.segments, entry.value),
+ builtIn,
+ );
+ const decoded = decodeSettingsExit(applied);
+ if (Exit.isFailure(decoded)) {
+ return { _tag: "Invalid", reason: "a managed setting has a value of the wrong type" };
+ }
+ const roundTrip = encodeSettings(decoded.value);
+ const lost = all.find((entry) => !jsonEqual(getPath(roundTrip, entry.segments), entry.value));
+ if (lost !== undefined) {
+ return {
+ _tag: "Invalid",
+ reason: `"${lost.path}" is not a setting this version can manage, or its value is invalid`,
+ };
+ }
+ // The server moves a credential it finds in settings into the user's secret store, where a
+ // policy's would outlive the policy. Built-in defaults hold none, so any found is the policy's.
+ let holdsCredential = false;
+ mapSettingsSecrets(decoded.value, (secret) => {
+ if (secret.sensitive && !secret.redacted && secret.value.length > 0) holdsCredential = true;
+ return secret;
+ });
+ if (holdsCredential) {
+ return {
+ _tag: "Invalid",
+ reason:
+ "a managed setting holds a credential, which every user can read in the policy; deploy credentials another way",
+ };
+ }
+ // Defaults fill in what the file leaves out, so an entry a default adds to a record such as
+ // `providerInstances` would come back each time the user removed it.
+ const addsEntry = defaults.find((entry) => {
+ const existing = getPath(builtIn, entry.segments);
+ return existing === undefined ? entry.segments.length > 1 : addsKeys(existing, entry.value);
+ });
+ if (addsEntry !== undefined) {
+ return {
+ _tag: "Invalid",
+ reason: `"${addsEntry.path}" adds entries users could not remove; lock it instead`,
+ };
+ }
+ // A managed default above the ceiling would start every thread in a mode the policy refuses.
+ if (
+ all.some((entry) => entry.path === "defaultRuntimeMode") &&
+ isRuntimeModeAbove(decoded.value.defaultRuntimeMode, maxRuntimeMode)
+ ) {
+ return {
+ _tag: "Invalid",
+ reason: `"defaultRuntimeMode" is above "limits.maxRuntimeMode"`,
+ };
+ }
+
+ const defaultsTree = defaults.reduce<unknown>(
+ (tree, entry) => setPath(tree, entry.segments, entry.value),
+ {},
+ );
+ const lockEntries: ReadonlyArray<Lock> = locks.map((entry) => ({
+ ...entry,
+ decodedValue: getPath(decoded.value, entry.segments),
+ }));
+ const lockedPaths = locks.map((entry) => entry.path);
+ const idleCompactionLocked = lockedPaths.includes("idleCompaction");
+ const lockCache = new WeakMap<ServerSettings, ServerSettings>();
+
+ const applyLocks = (current: ServerSettings): ServerSettings => {
+ if (locks.length === 0 && maxRuntimeMode === undefined) return current;
+ const cached = lockCache.get(current);
+ if (cached !== undefined) return cached;
+ const locked =
+ locks.length === 0
+ ? current
+ : // Validated against the built-in defaults above, so a failure here is a bug, not bad input.
+ decodeSettings(
+ locks.reduce<unknown>(
+ (tree, entry) =>
+ lockTargets(tree, entry).reduce<unknown>(
+ (next, target) => setPath(next, target, entry.value),
+ tree,
+ ),
+ encodeSettings(current),
+ ),
+ );
+ const derived = idleCompactionLocked ? syncIdleCompaction(locked) : locked;
+ const result =
+ maxRuntimeMode === undefined ? derived : clampDefaultRuntimeModes(derived, maxRuntimeMode);
+ lockCache.set(current, result);
+ return result;
+ };
+
+ const vetWrite: ManagedSettings["vetWrite"] = (current, next, patch) => {
+ if (locks.length === 0) return { _tag: "Allowed", settings: next };
+ const before = encodeSettings(current);
+ const after = encodeSettings(next);
+ const changed = lockEntries.find(
+ (entry) =>
+ // Re-sending a stored value the lock overrides changes nothing on disk, but it is still
+ // an attempt to change what the user sees.
+ lockTargets(patch, entry).some((target) => {
+ const value = getPath(patch, target);
+ return value !== undefined && !matchesLock(value, entry.decodedValue);
+ }) ||
+ lockTargets(after, entry).some((target) => {
+ const value = getPath(after, target);
+ // Removing a project's override of a locked key is harmless; the lock applies either way.
+ return (
+ value !== undefined &&
+ !jsonEqual(value, getPath(before, target)) &&
+ !matchesLock(value, entry.value)
+ );
+ }),
+ );
+ if (changed !== undefined) return { _tag: "Locked", path: changed.path };
+ const kept = locks.reduce<unknown>(
+ (tree, entry) =>
+ lockTargets(tree, entry).reduce<unknown>((result, target) => {
+ // A parent the write adds holds the locked value already; removing only the locked key
+ // inside it would leave a partial object.
+ const added = target
+ .slice(0, -1)
+ .some((_, index) => getPath(before, target.slice(0, index + 1)) === undefined);
+ return added ? result : setPath(result, target, getPath(before, target));
+ }, tree),
+ after,
+ );
+ return { _tag: "Allowed", settings: decodeSettings(kept) };
+ };
+
+ // A file from before a setting replaced its legacy key holds the user's choice in that key, which
+ // a default for the new setting would otherwise override.
+ const withoutLegacyChoices = (persisted: unknown): unknown => {
+ if (!isRecord(persisted) || !isRecord(defaultsTree)) return defaultsTree;
+ const kept = { ...defaultsTree };
+ for (const [legacy, source] of DERIVED_FROM) {
+ if (persisted[legacy] !== undefined && persisted[source] === undefined) delete kept[source];
+ }
+ return kept;
+ };
+
+ // The paths keepStored puts back: each default, cut at an atomic setting, and the legacy key a
+ // defaulted setting replaced, which an older file holds the user's choice in.
+ const restoredPaths = (isAtomic: (key: string) => boolean): ReadonlyArray<Segments> => [
+ ...defaults.map((entry) => {
+ const atomicAt = entry.segments.findIndex(isAtomic);
+ return atomicAt === -1 ? entry.segments : entry.segments.slice(0, atomicAt + 1);
+ }),
+ ...[...DERIVED_FROM]
+ .filter(([, source]) => defaults.some((entry) => entry.path === source))
+ .map(([legacy]) => [legacy]),
+ ];
+
+ const keepStored: ManagedSettings["keepStored"] =
+ defaults.length === 0
+ ? undefined
+ : (stripped, settings, stored, isAtomic) => {
+ const encoded = encodeSettings(settings);
+ const restore = (tree: unknown, segments: Segments): unknown => {
+ const previous = getPath(stored, segments);
+ if (previous === undefined) return tree;
+ if (isRecord(previous) && !isAtomic(segments.at(-1) ?? "")) {
+ return Object.keys(previous).reduce<unknown>(
+ (next, key) => restore(next, [...segments, key]),
+ tree,
+ );
+ }
+ return getPath(tree, segments) === undefined &&
+ jsonEqual(previous, getPath(encoded, segments))
+ ? setPath(tree, segments, getPath(settings, segments))
+ : tree;
+ };
+ // A default inside an atomic setting restores that whole setting, never part of it.
+ return restoredPaths(isAtomic).reduce<unknown>(restore, stripped);
+ };
+
+ return {
+ _tag: "Valid",
+ settings: {
+ keepStored,
+ withDefaults: (persisted) => fillMissing(persisted, withoutLegacyChoices(persisted)),
+ defaults: syncIdleCompaction(
+ decodeSettings(
+ defaults.reduce<unknown>(
+ (tree, entry) => setPath(tree, entry.segments, entry.value),
+ builtIn,
+ ),
+ ),
+ ),
+ applyLocks,
+ vetWrite,
+ lockedPaths,
+ },
+ };
+}
diff --git a/apps/server/src/policy/managedUpdates.ts b/apps/server/src/policy/managedUpdates.ts
new file mode 100644
index 00000000000..32adc6e4f38
--- /dev/null
+++ b/apps/server/src/policy/managedUpdates.ts
@@ -0,0 +1,24 @@
+import {
+ managedNightlyDeniedMessage,
+ managedUpdatesMessage,
+ type ManagedPolicyDocument,
+} from "@t3tools/contracts";
+import type { CliReleaseChannel } from "@t3tools/shared/cliRelease";
+
+/**
+ * Why the managed policy refuses an update a user or maintainer asked for, or `undefined` when it
+ * allows it. The server never updates on its own, so `auto` allows every explicit request.
+ * Pass `targetChannel` when the caller picks the release; the desktop app gates its own channel.
+ */
+export function managedUpdateRefusal(
+ document: ManagedPolicyDocument | undefined,
+ targetChannel?: CliReleaseChannel,
+): string | undefined {
+ const updates = document?.limits?.updates;
+ if (document === undefined || updates === undefined) return undefined;
+ if (updates.mode === "off") return managedUpdatesMessage(document.organization);
+ if (updates.allowNightly === false && targetChannel !== undefined && targetChannel !== "stable") {
+ return managedNightlyDeniedMessage(document.organization);
+ }
+ return undefined;
+}
diff --git a/apps/server/src/project/AgentSessionImporter.test.ts b/apps/server/src/project/AgentSessionImporter.test.ts
index 0e3a3c67a76..140dff31486 100644
--- a/apps/server/src/project/AgentSessionImporter.test.ts
+++ b/apps/server/src/project/AgentSessionImporter.test.ts
@@ -1,6 +1,7 @@
import { expect, it } from "@effect/vitest";
import {
type AgentSessionSource,
+ type ServerSettingsError,
EventId,
ProjectId,
ProviderDriverKind,
@@ -31,6 +32,7 @@ import {
} from "../orchestration-v2/testkit/fixtures/shared.ts";
import * as ProviderSessionRuntime from "../persistence/ProviderSessionRuntime.ts";
import * as SqlitePersistence from "../persistence/Sqlite.ts";
+import * as ServerSettings from "../serverSettings.ts";
import * as AgentSessionImporter from "./AgentSessionImporter.ts";
import * as AgentSessionScanner from "./AgentSessionScanner.ts";
import * as ProjectService from "./ProjectService.ts";
@@ -170,6 +172,10 @@ const seedOwner = Effect.fn(function* (
const makeImporter = Effect.fn(function* (
candidates: ReadonlyArray<ReturnType<typeof candidate>>,
beforeTransaction: Effect.Effect<void> = Effect.void,
+ settings: Layer.Layer<
+ ServerSettings.ServerSettingsService,
+ ServerSettingsError
+ > = ServerSettings.layerTest(),
) {
const sql = yield* SqlClient.SqlClient;
const events = yield* EventStore.EventStoreV2;
@@ -205,6 +211,7 @@ const makeImporter = Effect.fn(function* (
Layer.provide(
Layer.mergeAll(
sinkLayer,
+ settings,
Layer.succeed(IdAllocator.IdAllocatorV2, yield* IdAllocator.IdAllocatorV2),
Layer.succeed(
ProviderSessionRuntime.ProviderSessionRuntimeRepository,
@@ -416,3 +423,29 @@ it.effect(
});
}).pipe(Effect.scoped, Effect.provide(persistence)),
);
+
+it.effect("imports under a policy ceiling in the project's default, kept under the ceiling", () =>
+ Effect.gen(function* () {
+ const projections = yield* ProjectionStore.ProjectionStoreV2;
+ const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
+ const source = candidate(CODEX_MODEL_SELECTION, "ceiling");
+ const threadId = importId(source);
+ const importer = yield* makeImporter(
+ [source],
+ Effect.void,
+ ServerSettings.layerTest(
+ { defaultRuntimeMode: "full-access" },
+ {
+ organization: "Example Corp",
+ lockedSettings: [],
+ limits: { maxRuntimeMode: "auto-accept-edits" },
+ },
+ ),
+ );
+ expect(yield* importer.run).toEqual({ importedCount: 1, skippedCount: 0 });
+ expect((yield* projections.getThread(threadId)).runtimeMode).toBe("auto-accept-edits");
+ expect(Option.getOrThrow(yield* runtimes.getByThreadId({ threadId })).runtimeMode).toBe(
+ "auto-accept-edits",
+ );
+ }).pipe(Effect.scoped, Effect.provide(persistence)),
+);
diff --git a/apps/server/src/project/AgentSessionImporter.ts b/apps/server/src/project/AgentSessionImporter.ts
index a3f587c1c6d..211ad06fc26 100644
--- a/apps/server/src/project/AgentSessionImporter.ts
+++ b/apps/server/src/project/AgentSessionImporter.ts
@@ -3,6 +3,7 @@ import {
DEFAULT_MODEL_BY_PROVIDER,
DEFAULT_PROVIDER_INTERACTION_MODE,
DEFAULT_RUNTIME_MODE,
+ isRuntimeModeAbove,
AgentSessionImportProjectChangedError,
AgentSessionImportProjectNotFoundError,
AgentSessionImportSource,
@@ -23,6 +24,7 @@ import {
type OrchestrationV2TurnItem,
} from "@t3tools/contracts";
import { normalizeProjectPathForComparison } from "@t3tools/shared/path";
+import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
@@ -35,6 +37,7 @@ import * as EventSink from "../orchestration-v2/EventSink.ts";
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
import * as ProviderSessionRuntime from "../persistence/ProviderSessionRuntime.ts";
+import * as ServerSettings from "../serverSettings.ts";
import * as AgentSessionScanner from "./AgentSessionScanner.ts";
import * as ProjectService from "./ProjectService.ts";
@@ -172,6 +175,8 @@ const make = Effect.gen(function* () {
const eventSink = yield* EventSink.EventSinkV2;
const idAllocator = yield* IdAllocator.IdAllocatorV2;
const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
+ const settingsService = yield* ServerSettings.ServerSettingsService;
+ const ceiling = settingsService.managedPolicy?.limits?.maxRuntimeMode;
const importRecentAgentThreads = Effect.fn("importRecentAgentThreadsV2")(function* (
input: AgentSessionImportInput,
) {
@@ -192,6 +197,21 @@ const make = Effect.gen(function* () {
) {
return yield* new AgentSessionImportProjectChangedError({ projectId: input.projectId });
}
+ // Imports run in full access, except under a policy ceiling: then in the project's default,
+ // which the policy keeps under it, so imported threads never sit above the ceiling.
+ const runtimeMode =
+ ceiling === undefined
+ ? DEFAULT_RUNTIME_MODE
+ : yield* settingsService.getSettings.pipe(
+ Effect.mapError(
+ (cause) => new AgentSessionScanError({ operation: "read-settings", cause }),
+ ),
+ Effect.map((settings) => {
+ const mode = resolveProjectSettings(settings, input.projectId, project).settings
+ .defaultRuntimeMode;
+ return isRuntimeModeAbove(mode, ceiling) ? ceiling : mode;
+ }),
+ );
const runtimeRows = yield* runtimes
.list()
.pipe(
@@ -259,7 +279,7 @@ const make = Effect.gen(function* () {
providerName: driver,
providerInstanceId: thread.providerInstanceId,
adapterKey: driver,
- runtimeMode: DEFAULT_RUNTIME_MODE,
+ runtimeMode,
status: "stopped",
lastSeenAt: thread.updatedAt,
resumeCursor:
@@ -303,7 +323,7 @@ const make = Effect.gen(function* () {
title: thread.title.trim() === "" ? "Untitled thread" : thread.title,
providerInstanceId: thread.providerInstanceId,
modelSelection: { instanceId: thread.providerInstanceId, model },
- runtimeMode: DEFAULT_RUNTIME_MODE,
+ runtimeMode,
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
branch: null,
worktreePath: null,
diff --git a/apps/server/src/provider/Drivers/CodexDriver.ts b/apps/server/src/provider/Drivers/CodexDriver.ts
index 97ec4954ed8..14cb4b6d25a 100644
--- a/apps/server/src/provider/Drivers/CodexDriver.ts
+++ b/apps/server/src/provider/Drivers/CodexDriver.ts
@@ -150,7 +150,10 @@ export const CodexDriver: ProviderDriver<
const installation = yield* CodexInstallation.CodexInstallation;
const modelCatalog = yield* ModelCatalog.ModelCatalog;
const currentCatalog = modelCatalog.current(DRIVER_KIND);
- const processEnv = yield* mergeProviderInstanceEnvironment(environment);
+ const processEnv = yield* mergeProviderInstanceEnvironment(
+ environment,
+ yield* HostProcess.Environment,
+ );
const homeLayout = yield* resolveCodexHomeLayout(config);
const continuationIdentity = codexContinuationIdentity(homeLayout);
const stampIdentity = withInstanceIdentity({
diff --git a/apps/server/src/provider/ProviderInstanceRegistry.test.ts b/apps/server/src/provider/ProviderInstanceRegistry.test.ts
index af3359ea7f2..cf9a6c4f8e1 100644
--- a/apps/server/src/provider/ProviderInstanceRegistry.test.ts
+++ b/apps/server/src/provider/ProviderInstanceRegistry.test.ts
@@ -360,6 +360,24 @@ describe("ProviderInstanceRegistry — multi-instance codex slice", () => {
}).pipe(Effect.provide(layerTest)),
);
+ it.live("lists a blocked driver's instances as unavailable without running them", () =>
+ Effect.gen(function* () {
+ const instanceId = ProviderInstanceId.make("codex");
+ const reason = "Example Corp's policy does not allow the Codex provider.";
+ const { registry } = yield* makeProviderInstanceRegistry({
+ drivers: [CodexDriver],
+ configMap: { [instanceId]: { driver: ProviderDriverKind.make("codex") } },
+ blockedReason: (driver) => (driver === "codex" ? reason : undefined),
+ });
+
+ expect(yield* registry.getInstance(instanceId)).toBeUndefined();
+ const [unavailable] = yield* registry.listUnavailable;
+ expect(unavailable?.instanceId).toBe(instanceId);
+ expect(unavailable?.availability).toBe("unavailable");
+ expect(unavailable?.unavailableReason).toBe(reason);
+ }).pipe(Effect.provide(layerTest)),
+ );
+
it.live("runs Codex and Claude readiness probes from configured tilde paths", () =>
Effect.gen(function* () {
if (yield* HostProcess.isWindows) return;
diff --git a/apps/server/src/provider/ProviderInstanceRegistry.ts b/apps/server/src/provider/ProviderInstanceRegistry.ts
index a944f751a1d..57a218a0daf 100644
--- a/apps/server/src/provider/ProviderInstanceRegistry.ts
+++ b/apps/server/src/provider/ProviderInstanceRegistry.ts
@@ -129,6 +129,8 @@ const resolveEntryEnabled = (entry: ProviderInstanceConfig, typedConfig: unknown
return entry.enabled ?? providerInstanceConfigEnabledFlag(typedConfig) ?? true;
};
+type BlockedReason = (driver: ProviderDriverKind) => string | undefined;
+
// The enabled state `buildEntry` decodes, so a disabled instance never reads its secrets.
const isEntryEnabled = Effect.fn("ProviderInstanceRegistry.isEntryEnabled")(function* <R>(
driversById: ReadonlyMap<ProviderDriverKind, AnyProviderDriver<R>>,
@@ -143,6 +145,7 @@ const isEntryEnabled = Effect.fn("ProviderInstanceRegistry.isEntryEnabled")(func
const buildEntry = Effect.fn("ProviderInstanceRegistry.buildEntry")(function* <R>(input: {
readonly driversById: ReadonlyMap<ProviderDriverKind, AnyProviderDriver<R>>;
+ readonly blockedReason: BlockedReason;
readonly parentScope: Scope.Scope;
readonly instanceId: ProviderInstanceId;
readonly rawInstanceId: string;
@@ -155,6 +158,19 @@ const buildEntry = Effect.fn("ProviderInstanceRegistry.buildEntry")(function* <R
R | SecretResolver.SecretResolver
> {
const { driversById, parentScope, instanceId, rawInstanceId, entry, deferSecrets } = input;
+ const blocked = input.blockedReason(entry.driver);
+ if (blocked !== undefined) {
+ return {
+ kind: "unavailable" as const,
+ snapshot: yield* buildUnavailableProviderSnapshot({
+ driverKind: entry.driver,
+ instanceId,
+ displayName: entry.displayName,
+ accentColor: entry.accentColor,
+ reason: blocked,
+ }),
+ };
+ }
const driver = driversById.get(entry.driver);
if (!driver) {
return {
@@ -274,13 +290,14 @@ const buildEntry = Effect.fn("ProviderInstanceRegistry.buildEntry")(function* <R
const makeReconcile = <R>(input: {
readonly state: RegistryState;
readonly driversById: ReadonlyMap<ProviderDriverKind, AnyProviderDriver<R>>;
+ readonly blockedReason: BlockedReason;
readonly parentScope: Scope.Scope;
}): ((
configMap: ProviderInstanceConfigMap,
rebuild?: ReadonlySet<ProviderInstanceId>,
deferSecrets?: boolean,
) => Effect.Effect<void, never, R | SecretResolver.SecretResolver>) => {
- const { state, driversById, parentScope } = input;
+ const { state, driversById, blockedReason, parentScope } = input;
return (configMap, rebuild = new Set(), deferSecrets = false) =>
Effect.gen(function* () {
const previousEntries = yield* Ref.get(state.entries);
@@ -351,6 +368,7 @@ const makeReconcile = <R>(input: {
const result = yield* buildEntry({
driversById,
+ blockedReason,
parentScope,
instanceId,
rawInstanceId,
@@ -402,6 +420,8 @@ export const makeProviderInstanceRegistry = Effect.fn(
)(function* <R>(input: {
readonly drivers: ReadonlyArray<AnyProviderDriver<R>>;
readonly configMap: ProviderInstanceConfigMap;
+ /** A reason to show instead of running a driver, such as an administrator's policy. */
+ readonly blockedReason?: BlockedReason | undefined;
}): Effect.fn.Return<
{
readonly registry: ProviderInstanceRegistry["Service"];
@@ -428,7 +448,12 @@ export const makeProviderInstanceRegistry = Effect.fn(
yield* Effect.addFinalizer(() => PubSub.shutdown(changes));
const state: RegistryState = { entries, unavailable, changes };
- const reconcileWithR = makeReconcile({ state, driversById, parentScope });
+ const reconcileWithR = makeReconcile({
+ state,
+ driversById,
+ blockedReason: input.blockedReason ?? (() => undefined),
+ parentScope,
+ });
const configMapRef = yield* Ref.make(input.configMap);
const semaphore = yield* Semaphore.make(1);
const reconcile: ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutatorShape["reconcile"] =
@@ -535,6 +560,7 @@ export const makeProviderInstanceRegistry = Effect.fn(
export const layer = <R>(input: {
readonly drivers: ReadonlyArray<AnyProviderDriver<R>>;
readonly configMap: ProviderInstanceConfigMap;
+ readonly blockedReason?: BlockedReason | undefined;
}): Layer.Layer<
ProviderInstanceRegistry | ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutator,
never,
diff --git a/apps/server/src/provider/ProviderInstanceRegistryHydration.ts b/apps/server/src/provider/ProviderInstanceRegistryHydration.ts
index c8f2fb9b33e..9dd93bd3f58 100644
--- a/apps/server/src/provider/ProviderInstanceRegistryHydration.ts
+++ b/apps/server/src/provider/ProviderInstanceRegistryHydration.ts
@@ -16,6 +16,7 @@ import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Stream from "effect/Stream";
+import * as ManagedProviders from "../policy/managedProviders.ts";
import * as Settings from "../serverSettings.ts";
import * as SecretResolver from "../secrets/SecretResolver.ts";
import { BUILT_IN_DRIVERS, type BuiltInDriversEnv } from "./builtInDrivers.ts";
@@ -165,13 +166,23 @@ export const layer: Layer.Layer<
? ({} as ProviderInstanceConfigMap)
: deriveProviderInstanceConfigMap(initialSettings);
+ // Drivers launch from the host environment, minus launch overrides a policy ignores.
+ const hostEnvironment = ManagedProviders.providerHostEnvironment(
+ serverSettings.managedPolicy,
+ yield* HostProcess.Environment,
+ );
+ // Instances of drivers the policy leaves out stay listed, as unavailable, so their threads
+ // explain why instead of losing their provider.
const layerMutable = ProviderInstanceRegistry.layer({
drivers: BUILT_IN_DRIVERS,
configMap: initialConfigMap,
+ blockedReason: (driver) =>
+ ManagedProviders.disallowedDriverReason(serverSettings.managedPolicy, driver),
}).pipe(
Layer.provide(ProviderOrchestrationAdapterInfrastructure.layer),
Layer.provide(AcpRegistrySupport.layerFromHost),
Layer.provide(ProviderHostLive.layer),
+ Layer.provide(Layer.succeed(HostProcess.Environment, hostEnvironment)),
Layer.provide(SecretResolver.layer),
);
diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.ts
index a57fc08f9b7..ed8fff03795 100644
--- a/apps/server/src/provider/acp/AntigravityAcpSupport.ts
+++ b/apps/server/src/provider/acp/AntigravityAcpSupport.ts
@@ -92,6 +92,20 @@ export function antigravityPermissionMode(runtimeMode: RuntimeMode): string {
}
}
+/** The runtime mode an Antigravity session mode grants; the inverse of `antigravityPermissionMode`. */
+export function antigravityRuntimeModeForSessionMode(modeId: string): RuntimeMode | undefined {
+ switch (modeId) {
+ case "yolo":
+ return "full-access";
+ case "auto_edit":
+ return "auto-accept-edits";
+ case "default":
+ return "approval-required";
+ default:
+ return undefined;
+ }
+}
+
export function antigravityModelOptions(
configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption>,
) {
diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.interval.test.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.interval.test.ts
index c2cc1f382b6..ecc761d1d0b 100644
--- a/apps/server/src/scheduledTasks/ScheduledTaskService.interval.test.ts
+++ b/apps/server/src/scheduledTasks/ScheduledTaskService.interval.test.ts
@@ -16,12 +16,14 @@ import * as Scheduler from "../scheduling/Scheduler.ts";
import * as SecretRequests from "../secrets/SecretRequests.ts";
import { ServerActivation } from "../serverActivation.ts";
import * as ScheduledTaskService from "./ScheduledTaskService.ts";
+import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
afterEach(() => vi.unstubAllEnvs());
const dependencies = Layer.mergeAll(
NodeCrypto.layer,
Scheduler.layer,
+ ManagedPolicy.layerTest(),
Layer.mock(ThreadLaunchService.ThreadLaunchService)({
launch: () => Effect.die("synthetic dispatch failure"),
}),
diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.schedule.test.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.schedule.test.ts
index 1070b49a0dc..a6adcdaba91 100644
--- a/apps/server/src/scheduledTasks/ScheduledTaskService.schedule.test.ts
+++ b/apps/server/src/scheduledTasks/ScheduledTaskService.schedule.test.ts
@@ -15,6 +15,7 @@ import * as SecretRequests from "../secrets/SecretRequests.ts";
import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts";
import * as SqlitePersistence from "../persistence/Sqlite.ts";
import * as ScheduledTaskService from "./ScheduledTaskService.ts";
+import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
const decodeUpsertInput = Schema.decodeUnknownEffect(ScheduledTaskUpsertInput);
@@ -23,6 +24,7 @@ it.effect("rejects a stale form save after deletion while preserving explicit-id
const layerDependencies = Layer.mergeAll(
NodeCrypto.layer,
Scheduler.layer,
+ ManagedPolicy.layerTest(),
Layer.mock(ThreadLaunchService.ThreadLaunchService)({}),
Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({
namedProjectsRoot: "/projects",
@@ -70,6 +72,7 @@ it.effect("preserves a due run when a save only pads the scheduled hour", () =>
const layerDependencies = Layer.mergeAll(
NodeCrypto.layer,
Scheduler.layer,
+ ManagedPolicy.layerTest(),
Layer.mock(ThreadLaunchService.ThreadLaunchService)({}),
Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({
namedProjectsRoot: "/projects",
@@ -124,6 +127,7 @@ it.effect("keeps the task list order when a toggle or edit rewrites updated_at",
const layerDependencies = Layer.mergeAll(
NodeCrypto.layer,
Scheduler.layer,
+ ManagedPolicy.layerTest(),
Layer.mock(ThreadLaunchService.ThreadLaunchService)({}),
Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({
namedProjectsRoot: "/projects",
@@ -178,6 +182,7 @@ it.effect(
const layerDependencies = Layer.mergeAll(
NodeCrypto.layer,
Scheduler.layer,
+ ManagedPolicy.layerTest(),
Layer.mock(ThreadLaunchService.ThreadLaunchService)({
launch: (input) =>
Deferred.succeed(launched, input.title).pipe(
diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.test.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.test.ts
index 75650b55354..b37932dc1c9 100644
--- a/apps/server/src/scheduledTasks/ScheduledTaskService.test.ts
+++ b/apps/server/src/scheduledTasks/ScheduledTaskService.test.ts
@@ -30,6 +30,7 @@ import * as SecretRequests from "../secrets/SecretRequests.ts";
import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts";
import * as SqlitePersistence from "../persistence/Sqlite.ts";
import * as ScheduledTaskService from "./ScheduledTaskService.ts";
+import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
const isScheduledTaskError = Schema.is(ScheduledTaskError);
@@ -190,6 +191,7 @@ it.effect(
Layer.provideMerge(
ScheduledTaskService.layer,
Layer.mergeAll(
+ ManagedPolicy.layerTest(),
Layer.mock(ThreadLaunchService.ThreadLaunchService)({
launch: () =>
Ref.updateAndGet(dispatched, (n) => n + 1).pipe(
@@ -283,6 +285,7 @@ it.effect(
Layer.provideMerge(
ScheduledTaskService.layer,
Layer.mergeAll(
+ ManagedPolicy.layerTest(),
Layer.mock(ThreadLaunchService.ThreadLaunchService)({
launch: () =>
Ref.updateAndGet(dispatched, (n) => n + 1).pipe(
@@ -347,6 +350,7 @@ it.effect("thread cleanup notifies subscribers and a finishing run cannot recrea
const layer = ScheduledTaskService.layer.pipe(
Layer.provide(
Layer.mergeAll(
+ ManagedPolicy.layerTest(),
Layer.mock(ThreadLaunchService.ThreadLaunchService)({}),
Layer.mock(ThreadManagementService.ThreadManagementService)({
sendToThread: () =>
@@ -414,6 +418,7 @@ it.effect("a bound run follows its thread when promotion moves it mid-send", ()
const layer = ScheduledTaskService.layer.pipe(
Layer.provide(
Layer.mergeAll(
+ ManagedPolicy.layerTest(),
Layer.mock(ThreadLaunchService.ThreadLaunchService)({}),
Layer.mock(ThreadManagementService.ThreadManagementService)({
sendToThread: (input) =>
@@ -478,12 +483,79 @@ it.effect("a bound run follows its thread when promotion moves it mid-send", ()
}).pipe(Effect.provide(SqlitePersistence.layerMemory)),
);
+it.effect("refuses saving an enabled task above the policy ceiling", () =>
+ Effect.gen(function* () {
+ const layer = ScheduledTaskService.layer.pipe(
+ Layer.provide(
+ Layer.mergeAll(
+ ManagedPolicy.layerTest({
+ schemaVersion: 1,
+ organization: "Example Corp",
+ limits: { maxRuntimeMode: "auto-accept-edits" },
+ }),
+ Layer.mock(ThreadLaunchService.ThreadLaunchService)({}),
+ Layer.mock(ThreadManagementService.ThreadManagementService)({}),
+ Layer.mock(SecretRequests.SecretRequests)({}),
+ Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({
+ namedProjectsRoot: "/projects",
+ isScratchProject: () => Effect.succeed(false),
+ }),
+ NodeCrypto.layer,
+ Scheduler.layer,
+ ),
+ ),
+ );
+ yield* Effect.gen(function* () {
+ const service = yield* ScheduledTaskService.ScheduledTaskService;
+ const save = (enabled: boolean) =>
+ service.upsert({
+ id: ScheduledTaskId.make("task:above-ceiling"),
+ title: "Nightly",
+ prompt: "Check progress",
+ enabled,
+ schedule: { type: "interval", everyMs: 60_000 },
+ projectId: ProjectId.make("project:test"),
+ workspaceStrategy: { type: "root" },
+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ });
+ const refused = yield* save(true).pipe(Effect.flip);
+ assert.equal(refused.message, "Example Corp limits threads to Auto-accept edits.");
+ assert.lengthOf((yield* service.list()).tasks, 0);
+ // A disabled task does not run, so it can still be saved.
+ yield* save(false);
+ assert.lengthOf((yield* service.list()).tasks, 1);
+ // Nor can it be switched back on while its mode is above the ceiling.
+ const reenabled = yield* service
+ .setEnabled({ id: ScheduledTaskId.make("task:above-ceiling"), enabled: true })
+ .pipe(Effect.flip);
+ assert.equal(reenabled.message, "Example Corp limits threads to Auto-accept edits.");
+ // A task bound to a thread runs in that thread's mode, so its own is not checked.
+ yield* service.upsert({
+ id: ScheduledTaskId.make("task:bound"),
+ title: "Follow up",
+ prompt: "Check progress",
+ enabled: true,
+ schedule: { type: "interval", everyMs: 60_000 },
+ projectId: ProjectId.make("project:test"),
+ threadId: ThreadId.make("thread:bound"),
+ workspaceStrategy: { type: "root" },
+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ });
+ }).pipe(Effect.provide(layer));
+ }).pipe(Effect.provide(SqlitePersistence.layerMemory)),
+);
+
it.effect("a run interrupted right after it reserves the task does not block the next run", () =>
Effect.gen(function* () {
const launches = yield* Ref.make(0);
const layer = ScheduledTaskService.layer.pipe(
Layer.provide(
Layer.mergeAll(
+ ManagedPolicy.layerTest(),
Layer.mock(ThreadLaunchService.ThreadLaunchService)({
launch: () =>
Ref.update(launches, (n) => n + 1).pipe(
diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.ts
index d69254009b0..3d91ffa623a 100644
--- a/apps/server/src/scheduledTasks/ScheduledTaskService.ts
+++ b/apps/server/src/scheduledTasks/ScheduledTaskService.ts
@@ -23,6 +23,8 @@ import {
type ScheduledTaskRunNowResult,
type ScheduledTaskSetEnabledInput,
type ScheduledTaskUpsertInput,
+ managedPolicyDeniedMessage,
+ managedRuntimeModeDenial,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
@@ -49,6 +51,7 @@ import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts";
import * as Metrics from "../observability/Metrics.ts";
import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
import * as SecretRequests from "../secrets/SecretRequests.ts";
+import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
import * as DueHint from "../scheduling/DueHint.ts";
import * as Scheduler from "../scheduling/Scheduler.ts";
import { isMissedFixedTimeRun, isSameSchedule, nextScheduledRunAt } from "./Schedule.ts";
@@ -145,6 +148,7 @@ export type WebhookDeliveryOutcome =
| "expired"
| "filtered"
| "not_found"
+ | "blocked_by_policy"
| "error";
export type WebhookTriggerResult =
@@ -156,6 +160,7 @@ export type WebhookTriggerResult =
| { readonly _tag: "not_found" }
| { readonly _tag: "rejected_signature" }
| { readonly _tag: "disabled" }
+ | { readonly _tag: "blocked_by_policy" }
| {
readonly _tag: "rate_limited";
readonly outcome: "rate_limited" | "queue_full";
@@ -437,6 +442,17 @@ export const layer = Layer.effect(
const secretRequests = yield* SecretRequests.SecretRequests;
const scheduler = yield* Scheduler.Scheduler;
const readWebhookOrigin = yield* ScheduledTaskWebhookOrigin;
+ const managedPolicy = yield* ManagedPolicy.ManagedPolicy;
+ const webhookPolicyOrganization = ManagedPolicy.deniedBy(managedPolicy, "webhookTasks");
+ // Existing webhook tasks stay stored but report why they do not run.
+ const webhookPolicyBlock =
+ webhookPolicyOrganization === undefined
+ ? undefined
+ : managedPolicyDeniedMessage(webhookPolicyOrganization, "webhook tasks");
+ const withPolicy = (task: ScheduledTask): ScheduledTask =>
+ webhookPolicyBlock !== undefined && task.schedule.type === "webhook"
+ ? { ...task, blockedByPolicy: webhookPolicyBlock }
+ : task;
const webhookPermits = yield* Ref.make<ReadonlyMap<ScheduledTaskId, Semaphore.Semaphore>>(
new Map(),
);
@@ -498,7 +514,11 @@ export const layer = Layer.effect(
const listRows = Effect.fn("ScheduledTaskService.listRows")(function* () {
const rows = yield* selectAllRows();
const origin = yield* readWebhookOrigin;
- return yield* Effect.forEach(rows, (row) => decodeRow(row, origin), { concurrency: 1 });
+ return yield* Effect.forEach(
+ rows,
+ (row) => decodeRow(row, origin).pipe(Effect.map(withPolicy)),
+ { concurrency: 1 },
+ );
});
const getRows = (id: ScheduledTaskId) =>
@@ -538,7 +558,7 @@ export const layer = Layer.effect(
);
const row = rows[0];
if (row === undefined) return null;
- return yield* decodeRow(row, yield* readWebhookOrigin);
+ return withPolicy(yield* decodeRow(row, yield* readWebhookOrigin));
});
const findWebhookCredentials = (id: ScheduledTaskId) =>
@@ -828,9 +848,11 @@ export const layer = Layer.effect(
? "The task was replaced before this delivery ran."
: active.schedule.type !== "webhook"
? "The task's trigger changed before this delivery ran."
- : !active.enabled
- ? "The task was paused before this delivery ran."
- : null;
+ : webhookPolicyBlock !== undefined
+ ? webhookPolicyBlock
+ : !active.enabled
+ ? "The task was paused before this delivery ran."
+ : null;
if (reason !== null) return yield* new WebhookDeliverySkipped({ reason });
}
@@ -1177,6 +1199,23 @@ export const layer = Layer.effect(
const upsert: ScheduledTaskService["Service"]["upsert"] = Effect.fn(
"ScheduledTaskService.upsert",
)(function* (input) {
+ // A webhook task the policy blocks can still be edited while it is off.
+ if (input.enabled && input.schedule.type === "webhook" && webhookPolicyBlock !== undefined) {
+ return yield* taskError(
+ webhookPolicyBlock,
+ input.id === undefined ? {} : { taskId: input.id },
+ );
+ }
+ // Refused on save rather than at run time; a disabled task can still be saved, so one
+ // stored above the ceiling can be turned off before its mode is lowered. A task bound to a
+ // thread runs in that thread's mode, which the orchestrator checks instead.
+ const modeDenial =
+ input.enabled && input.threadId == null
+ ? managedRuntimeModeDenial(managedPolicy.summary, input.runtimeMode)
+ : undefined;
+ if (modeDenial !== undefined) {
+ return yield* taskError(modeDenial, input.id === undefined ? {} : { taskId: input.id });
+ }
const now = yield* localNow;
const uuid =
input.commandId === undefined
@@ -1317,6 +1356,20 @@ export const layer = Layer.effect(
)(function* (input) {
const existing = yield* loadTask(input.id);
if (existing.enabled === input.enabled) return { task: existing };
+ if (
+ input.enabled &&
+ existing.schedule.type === "webhook" &&
+ webhookPolicyBlock !== undefined
+ ) {
+ return yield* taskError(webhookPolicyBlock, { taskId: input.id });
+ }
+ const modeDenial =
+ input.enabled && existing.threadId === null
+ ? managedRuntimeModeDenial(managedPolicy.summary, existing.runtimeMode)
+ : undefined;
+ if (modeDenial !== undefined) {
+ return yield* taskError(modeDenial, { taskId: input.id });
+ }
const now = yield* localNow;
yield* requireFutureOnce(
{ enabled: input.enabled, schedule: existing.schedule },
@@ -1851,6 +1904,12 @@ export const layer = Layer.effect(
// triggerWebhook owns the operation span and its task-id annotation.
const triggerWebhookUnobserved = Effect.fnUntraced(function* (request: WebhookTriggerRequest) {
+ // Refused before any lookup or log, so a blocked hook neither runs nor records a delivery.
+ if (webhookPolicyBlock !== undefined) {
+ return yield* observeDelivery(request, "blocked_by_policy", undefined, undefined).pipe(
+ Effect.as({ _tag: "blocked_by_policy" as const }),
+ );
+ }
const taskId = decodeTaskId(request.hookId);
const notFound = observeDelivery(request, "not_found", undefined, undefined).pipe(
Effect.as({ _tag: "not_found" as const }),
diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts
index aaeb374bd0d..6fb5de1ff88 100644
--- a/apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts
+++ b/apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts
@@ -4,6 +4,7 @@ import * as NodeCrypto from "node:crypto";
import * as NodePlatformCrypto from "@effect/platform-node/NodeCrypto";
import { assert, it } from "@effect/vitest";
import {
+ type ManagedPolicyDocument,
ScheduledTaskUpsertInput,
ScheduledTaskWebhookDeliveryId,
SecretRequestError,
@@ -23,6 +24,7 @@ import * as TestClock from "effect/testing/TestClock";
import * as Tracer from "effect/Tracer";
import * as ThreadLaunchService from "../orchestration-v2/ThreadLaunchService.ts";
+import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
import * as SecretRequests from "../secrets/SecretRequests.ts";
import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts";
@@ -173,6 +175,7 @@ const withService = <A, E>(
readonly relayHookBaseUrl?: string;
readonly sql?: SqlClient.SqlClient;
readonly workers?: Map<string, Effect.Effect<void>>;
+ readonly policy?: ManagedPolicyDocument;
} = {},
) =>
Effect.gen(function* () {
@@ -249,6 +252,7 @@ const withService = <A, E>(
ScheduledTaskService.ScheduledTaskWebhookOrigin,
Effect.succeed({ relayHookBaseUrl: options.relayHookBaseUrl ?? null }),
),
+ ManagedPolicy.layerTest(options.policy),
);
return yield* Effect.gen(function* () {
const service = yield* ScheduledTaskService.ScheduledTaskService;
@@ -427,6 +431,62 @@ it.effect("checks the configured signature and keeps the secret write-only", ()
),
);
+it.effect("a policy without webhook tasks keeps existing ones but refuses saves and requests", () =>
+ withService(({ service, sql }) =>
+ Effect.gen(function* () {
+ const { task } = yield* service.upsert(yield* webhookTaskInput());
+ const timer = yield* webhookTaskInput({
+ id: "scheduled-task:timer",
+ schedule: { type: "interval", everyMs: 3_600_000 },
+ });
+ yield* withService(
+ ({ service, launches }) =>
+ Effect.gen(function* () {
+ const blocked = "Example Corp's policy does not allow webhook tasks.";
+ const listed = (yield* service.list()).tasks.find(({ id }) => id === task.id);
+ assert.equal(listed?.blockedByPolicy, blocked);
+ assert.isTrue(listed?.enabled);
+
+ const refused = yield* service.upsert(yield* webhookTaskInput()).pipe(Effect.flip);
+ assert.equal(refused.message, blocked);
+ const created = yield* service
+ .upsert(yield* webhookTaskInput({ id: "scheduled-task:new-hook" }))
+ .pipe(Effect.flip);
+ assert.equal(created.message, blocked);
+
+ // Turned off, it can still be edited, but not turned back on.
+ yield* service.setEnabled({ id: task.id, enabled: false });
+ yield* service.upsert(yield* webhookTaskInput({ enabled: false }));
+ const reenabled = yield* service
+ .setEnabled({ id: task.id, enabled: true })
+ .pipe(Effect.flip);
+ assert.equal(reenabled.message, blocked);
+
+ const result = yield* service.triggerWebhook(requestFor(task));
+ assert.equal(result._tag, "blocked_by_policy");
+ assert.equal(yield* Queue.size(launches), 0);
+ assert.equal((yield* sql`SELECT * FROM scheduled_task_webhook_deliveries`).length, 0);
+
+ // Timer tasks are unaffected, including a webhook task switched to a timer.
+ assert.isUndefined((yield* service.upsert(timer)).task.blockedByPolicy);
+ const switched = yield* service.upsert(
+ yield* webhookTaskInput({ schedule: { type: "interval", everyMs: 3_600_000 } }),
+ );
+ assert.isUndefined(switched.task.blockedByPolicy);
+ }),
+ {
+ sql,
+ policy: {
+ schemaVersion: 1,
+ organization: "Example Corp",
+ limits: { webhookTasks: false },
+ },
+ },
+ );
+ }),
+ ),
+);
+
it.effect("logs but does not run deliveries to a disabled task, and refuses run now", () =>
withService(({ service, launches }) =>
Effect.gen(function* () {
diff --git a/apps/server/src/scheduledTasks/webhookRoute.test.ts b/apps/server/src/scheduledTasks/webhookRoute.test.ts
index 95ff46c2a75..d920840c700 100644
--- a/apps/server/src/scheduledTasks/webhookRoute.test.ts
+++ b/apps/server/src/scheduledTasks/webhookRoute.test.ts
@@ -197,6 +197,7 @@ describe("webhook route", () => {
[{ _tag: "not_found" }, 404, "not_found"],
[{ _tag: "rejected_signature" }, 401, "rejected_signature"],
[{ _tag: "disabled" }, 409, "disabled"],
+ [{ _tag: "blocked_by_policy" }, 403, "blocked_by_policy"],
[{ _tag: "rate_limited", outcome: "rate_limited" }, 429, "rate_limited"],
[{ _tag: "rate_limited", outcome: "queue_full" }, 429, "queue_full"],
[{ _tag: "expired" }, 410, "expired"],
diff --git a/apps/server/src/scheduledTasks/webhookRoute.ts b/apps/server/src/scheduledTasks/webhookRoute.ts
index dc6ce74bfa3..a7e0c512cbe 100644
--- a/apps/server/src/scheduledTasks/webhookRoute.ts
+++ b/apps/server/src/scheduledTasks/webhookRoute.ts
@@ -131,6 +131,8 @@ export const layer = HttpApiBuilder.group(
return json(401, { error: "invalid_signature" }, "rejected_signature");
case "disabled":
return json(409, { error: "hook_disabled" }, "disabled");
+ case "blocked_by_policy":
+ return json(403, { error: "blocked_by_policy" }, "blocked_by_policy");
case "rate_limited":
return json(429, { error: result.outcome }, result.outcome);
case "expired":
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index 452addfb4a6..d0d51a0b241 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -94,6 +94,8 @@ import * as ServerOwnership from "./serverOwnership.ts";
import * as AgentAwarenessRelay from "./relay/AgentAwarenessRelay.ts";
import { hasCloudPublicConfig } from "./cloud/publicConfig.ts";
import * as ServerSettings from "./serverSettings.ts";
+import * as ManagedLimits from "./policy/managedLimits.ts";
+import * as ManagedPolicy from "./policy/ManagedPolicy.ts";
import * as ProjectEnrichmentService from "./project/ProjectEnrichmentService.ts";
import * as NativeAppIconResolver from "./assets/NativeAppIconResolver.ts";
import * as AntigravityInstallation from "./provider/AntigravityInstallation.ts";
@@ -149,6 +151,7 @@ import {
RELAY_URL_SECRET,
} from "./cloud/config.ts";
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
+import * as EnvironmentAuthPolicy from "./auth/EnvironmentAuthPolicy.ts";
import * as CloudHttp from "./cloud/http.ts";
import * as GuestHttp from "./guest/http.ts";
import * as CloudLink from "./cloud/CloudLink.ts";
@@ -202,7 +205,12 @@ import * as OrchestrationHttp from "./orchestration-v2/http.ts";
import * as ProjectHttp from "./project/http.ts";
import * as NetService from "@t3tools/shared/Net";
import * as RelayClient from "@t3tools/shared/relayClient";
-import { disableTailscaleServe, ensureTailscaleServe } from "@t3tools/tailscale";
+import {
+ disableTailscaleServe,
+ ensureTailscaleServe,
+ readTailscaleServeRoutesTo,
+ readTailscaleStatus,
+} from "@t3tools/tailscale";
import * as ServerActivation from "./serverActivation.ts";
// Escaped MCP handoff provenance can exceed find-my-way's 100-character segment default.
@@ -244,6 +252,7 @@ const layerPtyAdapter = NodePtyAdapter.layer;
const layerServerSettings = ServerSettings.layer.pipe(
Layer.provide(ServerSecretStore.layer),
+ Layer.provideMerge(ManagedPolicy.layer),
Layer.provideMerge(SqlitePersistence.layerConfig),
);
@@ -298,13 +307,42 @@ const layerResourceDiagnostics = Layer.mergeAll(
const layerRelayClient = Layer.unwrap(
Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
- return RelayClient.layerCloudflared({ baseDir: config.baseDir });
+ const policy = yield* ManagedPolicy.ManagedPolicy;
+ const layerCloudflared = RelayClient.layerCloudflared({ baseDir: config.baseDir });
+ if (ManagedLimits.allowsConnect(policy)) return layerCloudflared;
+ // The connector only carries T3 Connect, so a policy without Connect never installs one.
+ const refused = Effect.fn("RelayClient.installRefusedByPolicy")(function* () {
+ return yield* new RelayClient.RelayClientInstallError({
+ reason: "managed_by_policy",
+ message: ManagedLimits.refuseConnect(policy).message,
+ });
+ });
+ return Layer.effect(
+ RelayClient.RelayClient,
+ Effect.gen(function* () {
+ const relayClient = yield* RelayClient.RelayClient;
+ return RelayClient.RelayClient.of({
+ ...relayClient,
+ install: refused(),
+ installWithProgress: refused,
+ });
+ }),
+ ).pipe(Layer.provide(layerCloudflared));
}),
-);
+).pipe(Layer.provide(ManagedPolicy.layer));
const layerHttpServer = Layer.unwrap(
Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
+ // Before binding: a host the policy does not allow must never listen, not even briefly.
+ const policy = yield* ManagedPolicy.ManagedPolicy;
+ const bindHost = yield* ManagedLimits.checkServerReachability(policy, {
+ authPolicy: EnvironmentAuthPolicy.resolveServerAuthPolicy(config),
+ host: config.host,
+ tailscaleServeEnabled: config.tailscaleServeEnabled,
+ privateNetworkOnly: config.privateNetworkOnly,
+ });
+ yield* ManagedLimits.closeTailscaleServeTo(policy, { host: bindHost, port: config.port });
return NodeHttpServer.layer(
() => {
const server = rejectRequestsUntilServing(
@@ -320,7 +358,7 @@ const layerHttpServer = Layer.unwrap(
return server;
},
{
- host: config.host ?? "127.0.0.1",
+ host: bindHost,
port: config.port,
gracefulShutdownTimeout: HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS,
// Context takeover stays enabled (ws default) so the compression
@@ -331,7 +369,7 @@ const layerHttpServer = Layer.unwrap(
},
);
}),
-);
+).pipe(Layer.provide(ManagedPolicy.layer));
const layerPlatformServices = DocumentText.layer.pipe(Layer.provideMerge(NodeServices.layer));
@@ -701,7 +739,8 @@ const layerRuntimeDependencies = layerRuntimeCoreDependencies.pipe(
Layer.provideMerge(layerResourceDiagnostics),
Layer.provideMerge(TraceDiagnostics.layer),
Layer.provideMerge(TriageService.layer.pipe(Layer.provide(GitVcsDriver.layer))),
- Layer.provideMerge(AnalyticsService.layer),
+ // Layers memoize by reference, so this is the same policy the settings layer reads.
+ Layer.provideMerge(AnalyticsService.layer.pipe(Layer.provide(ManagedPolicy.layer))),
Layer.provideMerge(ExternalLauncher.layer),
Layer.provideMerge(RemoteOpenTargets.layer),
Layer.provideMerge(DirectEndpoints.layer),
@@ -816,6 +855,7 @@ const layerMakeServer = Layer.unwrap(
config,
port: address.port,
serviceManaged: launcher.managed,
+ managedPolicy: yield* ManagedPolicy.loadedPolicy(yield* ManagedPolicy.ManagedPolicy),
});
yield* ownership
.publish(state)
@@ -839,12 +879,17 @@ const layerMakeServer = Layer.unwrap(
}
const localPort = address.port;
+ const localHost = loopbackUrlHostForAddress(address);
return yield* ensureTailscaleServe({
localPort,
servePort: config.tailscaleServePort,
- localHost: loopbackUrlHostForAddress(address),
+ localHost,
}).pipe(
- Effect.as({ localPort, servePort: config.tailscaleServePort }),
+ Effect.as({
+ localPort,
+ localHost: localHost.replace(/^\[|\]$/gu, ""),
+ servePort: config.tailscaleServePort,
+ }),
Effect.tap(() =>
Effect.logInfo("Tailscale Serve configured", {
localPort,
@@ -862,11 +907,44 @@ const layerMakeServer = Layer.unwrap(
}),
(configured) =>
configured
- ? disableTailscaleServe({ servePort: configured.servePort }).pipe(
- Effect.tap(() =>
- Effect.logInfo("Tailscale Serve disabled", {
- servePort: configured.servePort,
+ ? Effect.all(
+ [
+ readTailscaleServeRoutesTo({
+ host: configured.localHost,
+ port: configured.localPort,
}),
+ readTailscaleStatus,
+ ],
+ { concurrency: 2 },
+ ).pipe(
+ // Another service may hold the root route by now, or it may sit under a
+ // former name, where `off` would act on the current one; only ours goes.
+ Effect.map(([routes, status]) =>
+ routes.some(
+ (route) =>
+ route.servePort === configured.servePort &&
+ route.mount === "/" &&
+ route.owner === undefined &&
+ route.ambiguous === undefined &&
+ route.host?.toLowerCase() === status.magicDnsName?.toLowerCase(),
+ ),
+ ),
+ Effect.orElseSucceed(() => false),
+ Effect.flatMap((ours) =>
+ ours
+ ? disableTailscaleServe({ servePort: configured.servePort }).pipe(
+ Effect.tap(() =>
+ Effect.logInfo("Tailscale Serve disabled", {
+ servePort: configured.servePort,
+ }),
+ ),
+ )
+ : Effect.logInfo(
+ "Tailscale Serve left on; its root route is not known to be ours",
+ {
+ servePort: configured.servePort,
+ },
+ ),
),
Effect.catch((cause) =>
Effect.logWarning("Failed to disable Tailscale Serve", {
@@ -882,6 +960,11 @@ const layerMakeServer = Layer.unwrap(
const layerCloudDesiredLinkReconcile = Layer.effectDiscard(
Effect.gen(function* () {
const cloudLink = yield* CloudLink.CloudLink;
+ // CloudLink unlinks on startup when the policy turns Connect off; nothing to restore.
+ if (!ManagedLimits.allowsConnect(yield* ManagedPolicy.ManagedPolicy)) {
+ yield* Deferred.succeed(cloudLinkParked, undefined).pipe(Effect.orDie);
+ return;
+ }
const releaseManagedTunnel = cloudLink.releaseManagedTunnelOnShutdown().pipe(
Effect.timeout("10 seconds"),
Effect.tap((released) =>
@@ -1099,7 +1182,9 @@ const layerMakeServer = Layer.unwrap(
),
),
Layer.provide(layerActivation),
- Layer.provideMerge(RelayTracing.layerServerRelayBroker),
+ Layer.provideMerge(
+ RelayTracing.layerServerRelayBroker.pipe(Layer.provide(ManagedPolicy.layer)),
+ ),
Layer.provideMerge(layerHttpServer),
Layer.provide(layerApplicationObservability),
Layer.provideMerge(FetchHttpClient.layer),
diff --git a/apps/server/src/serverRuntimeState.ts b/apps/server/src/serverRuntimeState.ts
index aca62ebb01e..49d9a48f991 100644
--- a/apps/server/src/serverRuntimeState.ts
+++ b/apps/server/src/serverRuntimeState.ts
@@ -22,6 +22,16 @@ export const PersistedServerRuntimeState = Schema.Struct({
startedAt: Schema.String,
serviceManaged: Schema.optional(Schema.Boolean),
serverVersion: Schema.optional(Schema.String),
+ // The managed policy this server loaded at startup, null for none; absent from older servers.
+ managedPolicy: Schema.optional(
+ Schema.NullOr(
+ Schema.Struct({
+ source: Schema.String,
+ organization: Schema.String,
+ fingerprint: Schema.String,
+ }),
+ ),
+ ),
});
export type PersistedServerRuntimeState = typeof PersistedServerRuntimeState.Type;
@@ -58,6 +68,7 @@ export const makePersistedServerRuntimeState = (input: {
>;
readonly port: number;
readonly serviceManaged?: boolean;
+ readonly managedPolicy?: PersistedServerRuntimeState["managedPolicy"];
}): Effect.Effect<PersistedServerRuntimeState> =>
Effect.map(DateTime.now, (now) => ({
version: 1,
@@ -70,6 +81,7 @@ export const makePersistedServerRuntimeState = (input: {
startedAt: DateTime.formatIso(now),
...(input.serviceManaged ? { serviceManaged: true } : {}),
serverVersion: packageJson.version,
+ ...(input.managedPolicy === undefined ? {} : { managedPolicy: input.managedPolicy }),
}));
export const persistServerRuntimeState = (input: {
diff --git a/apps/server/src/serverSettings.test.ts b/apps/server/src/serverSettings.test.ts
index ef8b4d6afae..281bab5e422 100644
--- a/apps/server/src/serverSettings.test.ts
+++ b/apps/server/src/serverSettings.test.ts
@@ -1,6 +1,8 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import {
DEFAULT_SERVER_SETTINGS,
+ globalIdleCompaction,
+ type ManagedPolicyDocument,
ModelSelection,
ProjectId,
ProjectScript,
@@ -31,15 +33,17 @@ import * as ServerConfig from "./config.ts";
import * as SqlitePersistence from "./persistence/Sqlite.ts";
import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";
import * as ServerSettingsModule from "./serverSettings.ts";
+import * as ManagedPolicy from "./policy/ManagedPolicy.ts";
import { resolveProviderInstanceTerminalEnvironment } from "./terminal/Manager.ts";
const decodeServerSettings = Schema.decodeUnknownEffect(ServerSettings);
const decodeServerSettingsJson = Schema.decodeUnknownEffect(Schema.fromJsonString(ServerSettings));
const decodeServerSettingsPatch = Schema.decodeUnknownEffect(ServerSettingsPatch);
-const layerServerSettings = () =>
+const layerServerSettings = (policy?: ManagedPolicyDocument) =>
ServerSettingsModule.layer.pipe(
Layer.provide(ServerSecretStore.layer),
+ Layer.provide(ManagedPolicy.layerTest(policy)),
Layer.provideMerge(Layer.fresh(SqlitePersistence.layerMemory)),
Layer.provideMerge(
Layer.fresh(
@@ -53,6 +57,7 @@ const layerServerSettings = () =>
const layerServerSettingsWithSecrets = () =>
ServerSettingsModule.layer.pipe(
Layer.provideMerge(ServerSecretStore.layer),
+ Layer.provide(ManagedPolicy.layerTest()),
Layer.provideMerge(Layer.fresh(SqlitePersistence.layerMemory)),
Layer.provideMerge(
Layer.fresh(
@@ -1084,6 +1089,7 @@ it.layer(NodeServices.layer)("server settings", (it) => {
).pipe(Layer.provide(ServerSecretStore.layer));
const layerSettings = ServerSettingsModule.layer.pipe(
Layer.provide(layerSecret),
+ Layer.provide(ManagedPolicy.layerTest()),
Layer.provideMerge(Layer.fresh(SqlitePersistence.layerMemory)),
Layer.provideMerge(
Layer.fresh(
@@ -1130,6 +1136,7 @@ it.layer(NodeServices.layer)("server settings", (it) => {
})),
).pipe(Layer.provide(ServerSecretStore.layer));
const layerSettings = ServerSettingsModule.layer.pipe(
+ Layer.provide(ManagedPolicy.layerTest()),
Layer.provide(layerSecret),
Layer.provideMerge(Layer.fresh(SqlitePersistence.layerMemory)),
Layer.provideMerge(
@@ -1232,7 +1239,9 @@ it.layer(NodeServices.layer)("server settings", (it) => {
return yield* fresh.getSettings;
}).pipe(
Effect.provide(
- Layer.fresh(ServerSettingsModule.layer).pipe(Layer.provide(ServerSecretStore.layer)),
+ Layer.fresh(ServerSettingsModule.layer).pipe(
+ Layer.provide(Layer.merge(ServerSecretStore.layer, ManagedPolicy.layerTest())),
+ ),
),
);
assert.equal(reloaded.providerInstances[instanceId]?.environment?.[0]?.value, expected);
@@ -1567,6 +1576,7 @@ it.layer(NodeServices.layer)("server settings", (it) => {
}),
});
const layerSettings = ServerSettingsModule.layer.pipe(
+ Layer.provide(ManagedPolicy.layerTest()),
Layer.provide(layerFailingSecretStore(cause)),
Layer.provideMerge(Layer.fresh(SqlitePersistence.layerMemory)),
Layer.provideMerge(
@@ -1823,6 +1833,8 @@ it.layer(NodeServices.layer)("server settings", (it) => {
}),
);
const layerSettings = ServerSettingsModule.layer.pipe(
+ Layer.provide(ManagedPolicy.layerTest()),
+ Layer.provide(ManagedPolicy.layerTest()),
Layer.provideMerge(Layer.fresh(SqlitePersistence.layerMemory)),
Layer.provide(layerSecretStore),
Layer.provideMerge(
@@ -1984,3 +1996,644 @@ it.layer(NodeServices.layer)("server settings", (it) => {
}).pipe(Effect.provide(layerServerSettings())),
);
});
+
+it.layer(NodeServices.layer)("server settings under a managed policy", (it) => {
+ const policy: ManagedPolicyDocument = {
+ schemaVersion: 1,
+ organization: "Example Corp",
+ settings: {
+ defaultRuntimeMode: { value: "approval-required", locked: false },
+ enableAgentDeviceAccess: { value: false, locked: true },
+ },
+ };
+
+ it.effect("uses policy defaults until the user picks something else", () =>
+ Effect.gen(function* () {
+ const service = yield* ServerSettingsModule.ServerSettingsService;
+ const config = yield* ServerConfig.ServerConfig;
+ const fs = yield* FileSystem.FileSystem;
+
+ assert.equal((yield* service.getSettings).defaultRuntimeMode, "approval-required");
+
+ // The built-in default differs from the policy's, so choosing it must persist.
+ yield* service.updateSettings({ defaultRuntimeMode: "full-access" });
+ assert.equal((yield* service.getSettings).defaultRuntimeMode, "full-access");
+ assert.include(yield* fs.readFileString(config.settingsPath), '"full-access"');
+
+ // Choosing the policy's value leaves nothing in the file to outlive the policy.
+ yield* service.updateSettings({ defaultRuntimeMode: "approval-required" });
+ assert.notInclude(yield* fs.readFileString(config.settingsPath), "defaultRuntimeMode");
+ }).pipe(Effect.provide(layerServerSettings(policy))),
+ );
+
+ it.effect("keeps a stored value that equals a policy default through unrelated writes", () =>
+ Effect.gen(function* () {
+ const service = yield* ServerSettingsModule.ServerSettingsService;
+ const config = yield* ServerConfig.ServerConfig;
+ const fs = yield* FileSystem.FileSystem;
+ yield* fs.writeFileString(
+ config.settingsPath,
+ JSON.stringify({ defaultRuntimeMode: "approval-required" }),
+ );
+
+ yield* service.updateSettings({ defaultAutoPull: true });
+ assert.include(yield* fs.readFileString(config.settingsPath), '"approval-required"');
+ }).pipe(Effect.provide(layerServerSettings(policy))),
+ );
+
+ it.effect("keeps stored values under whole-object policy defaults, and only the user's", () =>
+ Effect.gen(function* () {
+ const service = yield* ServerSettingsModule.ServerSettingsService;
+ const config = yield* ServerConfig.ServerConfig;
+ const fs = yield* FileSystem.FileSystem;
+ const selection = {
+ ...DEFAULT_SERVER_SETTINGS.textGenerationModelSelection,
+ model: "managed",
+ };
+ const chosenModel = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-mini" };
+ yield* fs.writeFileString(
+ config.settingsPath,
+ JSON.stringify({
+ storageCleanup: { logsAfterDays: 30, browserArtifactsAfterDays: 7 },
+ textGenerationModelSelection: selection,
+ }),
+ );
+
+ // Picking another model on the policy's instance differs from the policy in one field only.
+ yield* service.updateSettings({ defaultAutoPull: true, defaultModelSelection: chosenModel });
+ const stored = JSON.parse(yield* fs.readFileString(config.settingsPath));
+ assert.deepEqual(stored.storageCleanup, { logsAfterDays: 30, browserArtifactsAfterDays: 7 });
+ // Model selections are saved whole, never as the fields that differ from the policy's.
+ assert.deepEqual(stored.textGenerationModelSelection, selection);
+ assert.deepEqual(stored.defaultModelSelection, chosenModel);
+ // The switch the server derives from the policy's idle compaction stays out of the file.
+ assert.notProperty(stored, "compactIdleThreads");
+ }).pipe(
+ Effect.provide(
+ layerServerSettings({
+ schemaVersion: 1,
+ organization: "Example Corp",
+ settings: {
+ storageCleanup: {
+ value: { ...DEFAULT_SERVER_SETTINGS.storageCleanup, logsAfterDays: 30 },
+ locked: false,
+ },
+ "textGenerationModelSelection.model": { value: "managed", locked: false },
+ defaultModelSelection: {
+ value: { instanceId: "codex", model: "gpt-managed" },
+ locked: false,
+ },
+ idleCompaction: { value: "beforeCacheExpires", locked: false },
+ },
+ }),
+ ),
+ ),
+ );
+
+ it.effect(
+ "keeps an idle compaction choice saved before idleCompaction over a policy default",
+ () =>
+ // The file holds only the legacy switch: off differs from the policy's default, on matches it.
+ Effect.forEach([false, true], (compactIdleThreads) =>
+ Effect.gen(function* () {
+ const service = yield* ServerSettingsModule.ServerSettingsService;
+ const config = yield* ServerConfig.ServerConfig;
+ const fs = yield* FileSystem.FileSystem;
+ const chosen = compactIdleThreads ? "beforeCacheExpires" : "onReturn";
+ yield* fs.writeFileString(config.settingsPath, JSON.stringify({ compactIdleThreads }));
+
+ assert.equal((yield* service.getSettings).idleCompaction, chosen);
+ yield* service.updateSettings({ defaultAutoPull: true });
+ // What applies once the policy is gone is still the user's choice.
+ const stored = JSON.parse(yield* fs.readFileString(config.settingsPath));
+ assert.equal(globalIdleCompaction(stored), chosen);
+ }).pipe(
+ Effect.provide(
+ layerServerSettings({
+ schemaVersion: 1,
+ organization: "Example Corp",
+ settings: { idleCompaction: { value: "beforeCacheExpires", locked: false } },
+ }),
+ ),
+ ),
+ ),
+ );
+
+ it.effect("lays locks over the user's own and per-project values without persisting them", () =>
+ Effect.gen(function* () {
+ const service = yield* ServerSettingsModule.ServerSettingsService;
+ const config = yield* ServerConfig.ServerConfig;
+ const fs = yield* FileSystem.FileSystem;
+ const projectId = ProjectId.make("project-locked");
+ yield* fs.writeFileString(
+ config.settingsPath,
+ JSON.stringify({
+ enableAgentDeviceAccess: true,
+ projectSettingsOverrides: { [projectId]: { enableAgentDeviceAccess: true } },
+ }),
+ );
+
+ const settings = yield* service.getSettings;
+ assert.isFalse(settings.enableAgentDeviceAccess);
+ assert.isFalse(settings.projectSettingsOverrides[projectId]?.enableAgentDeviceAccess);
+ assert.deepEqual(service.managedPolicy, {
+ organization: "Example Corp",
+ lockedSettings: ["enableAgentDeviceAccess"],
+ });
+
+ const rejected = yield* service
+ .updateSettings({ enableAgentDeviceAccess: true, defaultAutoPull: true })
+ .pipe(Effect.flip);
+ assert.equal(rejected.operation, "write-managed-setting");
+ assert.equal(rejected.managedSetting, "enableAgentDeviceAccess");
+ assert.equal(
+ rejected.message,
+ "enableAgentDeviceAccess is managed by Example Corp and cannot be changed.",
+ );
+ assert.isFalse((yield* service.getSettings).defaultAutoPull);
+
+ const projectRejected = yield* service
+ .updateSettings({
+ projectSettingsOverrides: { [projectId]: { enableAgentDeviceAccess: true } },
+ })
+ .pipe(Effect.flip);
+ assert.equal(projectRejected.managedSetting, "enableAgentDeviceAccess");
+
+ // Unrelated writes, and writes that keep the locked value, go through.
+ yield* service.updateSettings({ enableAgentDeviceAccess: false, defaultAutoPull: true });
+ assert.isTrue((yield* service.getSettings).defaultAutoPull);
+
+ // The user's own value stays on disk, ready for when the policy is removed.
+ const stored = JSON.parse(yield* fs.readFileString(config.settingsPath));
+ assert.isTrue(stored.enableAgentDeviceAccess);
+ }).pipe(Effect.provide(layerServerSettings(policy))),
+ );
+ it.effect("accepts a project override that brings the locked value inside a new setting", () =>
+ Effect.gen(function* () {
+ const service = yield* ServerSettingsModule.ServerSettingsService;
+ const projectId = ProjectId.make("project-text-generation");
+ const selection = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-locked" };
+
+ yield* service.updateSettings({
+ projectSettingsOverrides: { [projectId]: { textGenerationModelSelection: selection } },
+ });
+
+ const project = (yield* service.getSettings).projectSettingsOverrides[projectId];
+ assert.equal(project?.textGenerationModelSelection?.model, "gpt-locked");
+ }).pipe(
+ Effect.provide(
+ layerServerSettings({
+ schemaVersion: 1,
+ organization: "Example Corp",
+ settings: { "textGenerationModelSelection.model": { value: "gpt-locked", locked: true } },
+ }),
+ ),
+ ),
+ );
+
+ it.effect("compares a project's partial override with a locked entry by the keys it holds", () =>
+ Effect.gen(function* () {
+ const service = yield* ServerSettingsModule.ServerSettingsService;
+ const codexId = ProviderInstanceId.make("codex");
+ const projectWith = (enabled: boolean) => ({
+ projectSettingsOverrides: {
+ [ProjectId.make("project-codex")]: { providerInstances: { [codexId]: { enabled } } },
+ },
+ });
+
+ yield* service.updateSettings(projectWith(true));
+ const refused = yield* service.updateSettings(projectWith(false)).pipe(Effect.flip);
+ assert.equal(refused.managedSetting, "providerInstances.codex");
+ }).pipe(
+ Effect.provide(
+ layerServerSettings({
+ schemaVersion: 1,
+ organization: "Example Corp",
+ settings: {
+ "providerInstances.codex": { value: { driver: "codex", enabled: true }, locked: true },
+ },
+ }),
+ ),
+ ),
+ );
+
+ it.effect("lowers default runtime modes above the ceiling without rewriting them", () =>
+ Effect.gen(function* () {
+ const service = yield* ServerSettingsModule.ServerSettingsService;
+ const config = yield* ServerConfig.ServerConfig;
+ const fs = yield* FileSystem.FileSystem;
+ const raised = ProjectId.make("project-raised");
+ const supervised = ProjectId.make("project-supervised");
+ yield* fs.writeFileString(
+ config.settingsPath,
+ JSON.stringify({
+ defaultRuntimeMode: "auto",
+ projectSettingsOverrides: {
+ [raised]: { defaultRuntimeMode: "full-access" },
+ [supervised]: { defaultRuntimeMode: "approval-required" },
+ },
+ }),
+ );
+
+ const settings = yield* service.getSettings;
+ assert.equal(settings.defaultRuntimeMode, "auto-accept-edits");
+ assert.equal(
+ settings.projectSettingsOverrides[raised]?.defaultRuntimeMode,
+ "auto-accept-edits",
+ );
+ assert.equal(
+ settings.projectSettingsOverrides[supervised]?.defaultRuntimeMode,
+ "approval-required",
+ );
+
+ yield* service.updateSettings({ defaultAutoPull: true });
+ const stored = JSON.parse(yield* fs.readFileString(config.settingsPath));
+ assert.equal(stored.defaultRuntimeMode, "auto");
+ assert.equal(stored.projectSettingsOverrides[raised].defaultRuntimeMode, "full-access");
+ }).pipe(
+ Effect.provide(
+ layerServerSettings({
+ schemaVersion: 1,
+ organization: "Example Corp",
+ limits: { maxRuntimeMode: "auto-accept-edits" },
+ }),
+ ),
+ ),
+ );
+});
+
+it.layer(NodeServices.layer)("server settings under a provider policy", (it) => {
+ const claude = ProviderDriverKind.make("claudeAgent");
+ const codex = ProviderDriverKind.make("codex");
+ const cursor = ProviderDriverKind.make("cursor");
+ const bedrock = { name: "CLAUDE_CODE_USE_BEDROCK", value: "1", sensitive: false };
+ const policy: ManagedPolicyDocument = {
+ schemaVersion: 1,
+ organization: "Example Corp",
+ limits: {
+ providers: {
+ allowedDrivers: [claude, codex],
+ instances: {
+ [claude]: {
+ locked: true,
+ environment: [{ name: bedrock.name, value: bedrock.value }],
+ binaryPath: "/opt/claude/bin/claude",
+ },
+ [codex]: { locked: false, launchArgs: "-c model_provider=gateway" },
+ },
+ },
+ },
+ };
+
+ it.effect("refuses enabling a driver the policy leaves out, and keeps existing ones", () =>
+ Effect.gen(function* () {
+ const service = yield* ServerSettingsModule.ServerSettingsService;
+ const config = yield* ServerConfig.ServerConfig;
+ const fs = yield* FileSystem.FileSystem;
+ const cursorId = ProviderInstanceId.make("cursor_work");
+ yield* fs.writeFileString(
+ config.settingsPath,
+ JSON.stringify({
+ providerInstances: {
+ [cursorId]: { driver: cursor, enabled: true },
+ // A default instance id is no proof of its driver.
+ codex: { driver: cursor, enabled: true },
+ },
+ textGenerationModelSelection: { instanceId: cursorId, model: "auto" },
+ }),
+ );
+
+ const settings = yield* service.getSettings;
+ // Never deleted: the instance stays for its threads, and the registry shows it unavailable.
+ assert.equal(settings.providerInstances[cursorId]?.driver, cursor);
+ // Built-in text generation does not fall back onto a disallowed driver either.
+ assert.equal(settings.textGenerationModelSelection.instanceId, "claudeAgent");
+
+ const rejected = yield* service
+ .updateProviderInstance({
+ operation: "create",
+ instanceId: ProviderInstanceId.make("cursor_new"),
+ instance: { driver: cursor, enabled: true },
+ })
+ .pipe(Effect.flip);
+ assert.equal(rejected.operation, "use-disallowed-provider");
+ assert.equal(rejected.message, "Example Corp's policy does not allow the Cursor provider.");
+ // Switching it on for one project is enabling it too.
+ const perProject = yield* service
+ .updateSettings({
+ projectSettingsOverrides: {
+ [ProjectId.make("project-a")]: { providerInstances: { [cursorId]: { enabled: true } } },
+ },
+ })
+ .pipe(Effect.flip);
+ assert.equal(perProject.operation, "use-disallowed-provider");
+
+ // The client echoes a default instance that was running before it was configured.
+ yield* service.updateProviderInstance({
+ operation: "upsert",
+ instanceId: ProviderInstanceId.make("cursor"),
+ instance: { driver: cursor, enabled: true },
+ });
+
+ // Turning it off, or removing it, is still the user's call.
+ yield* service.updateProviderInstance({
+ operation: "upsert",
+ instanceId: cursorId,
+ instance: { driver: cursor, enabled: false },
+ });
+ yield* service.updateProviderInstance({ operation: "remove", instanceId: cursorId });
+ assert.isUndefined((yield* service.getSettings).providerInstances[cursorId]);
+ }).pipe(Effect.provide(layerServerSettings(policy))),
+ );
+
+ it.effect("keeps a locked Codex pin from being bypassed by managed setup", () =>
+ Effect.gen(function* () {
+ const service = yield* ServerSettingsModule.ServerSettingsService;
+ const config = yield* ServerConfig.ServerConfig;
+ const fs = yield* FileSystem.FileSystem;
+ const codexId = ProviderInstanceId.make("codex_chatgpt");
+ yield* fs.writeFileString(
+ config.settingsPath,
+ JSON.stringify({
+ providerInstances: { [codexId]: { driver: codex, config: { setupMode: "managed" } } },
+ }),
+ );
+
+ const effective = (yield* service.getSettings).providerInstances[codexId];
+ assert.deepEqual(effective?.config, { binaryPath: "/opt/gateway/codex" });
+ // A stored value stays for when the policy is gone; a new one is refused.
+ const refused = yield* service
+ .updateProviderInstance({
+ operation: "upsert",
+ instanceId: ProviderInstanceId.make("codex_new"),
+ instance: { driver: codex, config: { setupMode: "managed" } },
+ })
+ .pipe(Effect.flip);
+ assert.equal(refused.managedSetting, "providerInstances.codex_new.config.setupMode");
+ // Adding a Codex instance sends the default setup, which leaves the pin in charge.
+ yield* service.updateProviderInstance({
+ operation: "upsert",
+ instanceId: ProviderInstanceId.make("codex_cli"),
+ instance: { driver: codex, config: { setupMode: "existing" } },
+ });
+ }).pipe(
+ Effect.provide(
+ layerServerSettings({
+ schemaVersion: 1,
+ organization: "Example Corp",
+ limits: {
+ providers: {
+ instances: { [codex]: { locked: true, binaryPath: "/opt/gateway/codex" } },
+ },
+ },
+ }),
+ ),
+ ),
+ );
+
+ it.effect("pins instance fields at read time and refuses edits to locked ones", () =>
+ Effect.gen(function* () {
+ const service = yield* ServerSettingsModule.ServerSettingsService;
+ const config = yield* ServerConfig.ServerConfig;
+ const fs = yield* FileSystem.FileSystem;
+ const claudeId = ProviderInstanceId.make("claudeAgent");
+ const codexId = ProviderInstanceId.make("codex");
+ const userVariable = { name: "MY_FLAG", value: "on", sensitive: false };
+ yield* fs.writeFileString(
+ config.settingsPath,
+ JSON.stringify({
+ providerInstances: {
+ [claudeId]: {
+ driver: claude,
+ environment: [{ ...bedrock, value: "0" }, userVariable, { ...bedrock, value: "2" }],
+ config: { binaryPath: "/usr/local/bin/claude" },
+ },
+ },
+ }),
+ );
+
+ const effective = yield* service.getSettings;
+ const claudeInstance = effective.providerInstances[claudeId];
+ assert.deepEqual(claudeInstance?.environment, [bedrock, userVariable]);
+ assert.deepEqual(claudeInstance?.config, { binaryPath: "/opt/claude/bin/claude" });
+ // The implicit default Codex instance gets the unlocked default too.
+ assert.deepEqual(effective.providerInstances[codexId]?.config, {
+ launchArgs: "-c model_provider=gateway",
+ });
+
+ const lockedBinary = yield* service
+ .updateProviderInstance({
+ operation: "upsert",
+ instanceId: claudeId,
+ instance: { ...claudeInstance!, config: { binaryPath: "/tmp/claude" } },
+ })
+ .pipe(Effect.flip);
+ assert.equal(lockedBinary.operation, "write-managed-setting");
+ assert.equal(lockedBinary.managedSetting, "providerInstances.claudeAgent.config.binaryPath");
+ const lockedVariable = yield* service
+ .updateProviderInstance({
+ operation: "upsert",
+ instanceId: claudeId,
+ instance: { ...claudeInstance!, environment: [userVariable] },
+ })
+ .pipe(Effect.flip);
+ assert.equal(
+ lockedVariable.managedSetting,
+ "providerInstances.claudeAgent.environment.CLAUDE_CODE_USE_BEDROCK",
+ );
+
+ // Saving what the client was shown, plus an unrelated edit, goes through without baking
+ // the policy into the file: the user's own values come back once the policy is removed.
+ yield* service.updateProviderInstance({
+ operation: "upsert",
+ instanceId: claudeId,
+ instance: { ...claudeInstance!, displayName: "Claude (work)" },
+ });
+ yield* service.updateProviderInstance({
+ operation: "upsert",
+ instanceId: codexId,
+ instance: effective.providerInstances[codexId]!,
+ });
+ const stored = JSON.parse(yield* fs.readFileString(config.settingsPath));
+ assert.deepEqual(stored.providerInstances[claudeId], {
+ driver: claude,
+ displayName: "Claude (work)",
+ environment: [{ ...bedrock, value: "0" }, { ...bedrock, value: "2" }, userVariable],
+ config: { binaryPath: "/usr/local/bin/claude" },
+ });
+ assert.isUndefined(stored.providerInstances[codexId]);
+
+ // Unlocked fields are the user's to override.
+ yield* service.updateProviderInstance({
+ operation: "upsert",
+ instanceId: codexId,
+ instance: { driver: codex, config: { launchArgs: "--mine" } },
+ });
+ assert.deepEqual((yield* service.getSettings).providerInstances[codexId]?.config, {
+ launchArgs: "--mine",
+ });
+ }).pipe(Effect.provide(layerServerSettings(policy))),
+ );
+});
+
+it.layer(NodeServices.layer)("server settings under a runtime mode ceiling", (it) => {
+ const claude = ProviderDriverKind.make("claudeAgent");
+ const acpRegistry = ProviderDriverKind.make("acpRegistry");
+ const policy: ManagedPolicyDocument = {
+ schemaVersion: 1,
+ organization: "Example Corp",
+ limits: {
+ maxRuntimeMode: "auto-accept-edits",
+ providers: {
+ instances: {
+ [claude]: {
+ locked: false,
+ environment: [{ name: "CLAUDE_CODE_USE_BEDROCK", value: "1" }],
+ binaryPath: "/opt/claude/bin/claude",
+ },
+ },
+ },
+ },
+ };
+
+ it.effect("keeps the secret of a variable it hides when the instance is saved", () => {
+ const shared = ServerSecretStore.layer.pipe(
+ Layer.provideMerge(Layer.fresh(SqlitePersistence.layerMemory)),
+ Layer.provideMerge(
+ Layer.fresh(ServerConfig.layerTest(process.cwd(), { prefix: "t3code-hidden-secret-" })),
+ ),
+ );
+ const withPolicy = <A, E>(
+ document: ManagedPolicyDocument | undefined,
+ use: (service: ServerSettingsModule.ServerSettingsService["Service"]) => Effect.Effect<A, E>,
+ ) =>
+ ServerSettingsModule.ServerSettingsService.pipe(
+ Effect.flatMap(use),
+ Effect.provide(
+ ServerSettingsModule.layer.pipe(Layer.provide(ManagedPolicy.layerTest(document))),
+ ),
+ );
+ const claudeId = ProviderInstanceId.make("claudeAgent");
+ const token = { name: "ANTHROPIC_API_KEY", value: "sk-kept", sensitive: true };
+ return Effect.gen(function* () {
+ yield* withPolicy(undefined, (service) =>
+ service.updateProviderInstance({
+ operation: "upsert",
+ instanceId: claudeId,
+ instance: { driver: claude, environment: [token] },
+ }),
+ );
+ // The ceiling shows only pinned variables, so the client saves without the token.
+ yield* withPolicy(policy, (service) =>
+ service.getSettings.pipe(
+ Effect.flatMap((settings) =>
+ service.updateProviderInstance({
+ operation: "upsert",
+ instanceId: claudeId,
+ instance: { ...settings.providerInstances[claudeId]!, displayName: "Claude (work)" },
+ }),
+ ),
+ ),
+ );
+ const restored = yield* withPolicy(undefined, (service) => service.getSettings);
+ assert.equal(restored.providerInstances[claudeId]?.environment?.[0]?.value, token.value);
+ }).pipe(Effect.provide(shared));
+ });
+
+ it.effect("ignores stored launch configuration and refuses new values", () =>
+ Effect.gen(function* () {
+ const service = yield* ServerSettingsModule.ServerSettingsService;
+ const config = yield* ServerConfig.ServerConfig;
+ const fs = yield* FileSystem.FileSystem;
+ const claudeId = ProviderInstanceId.make("claudeAgent");
+ const registryId = ProviderInstanceId.make("acp_devin");
+ const userVariable = { name: "CLAUDE_CONFIG_DIR", value: "/tmp/allow-all", sensitive: false };
+ const storedClaude = {
+ driver: claude,
+ environment: [userVariable, { ...userVariable, value: "/tmp/later-wins" }],
+ config: {
+ binaryPath: "/tmp/wrapper",
+ launchArgs: "--dangerously-skip-permissions",
+ homePath: "/tmp/allow-all",
+ autoCompactWindow: "300000",
+ },
+ };
+ yield* fs.writeFileString(
+ config.settingsPath,
+ JSON.stringify({
+ providerInstances: {
+ [claudeId]: storedClaude,
+ [registryId]: {
+ driver: acpRegistry,
+ config: { agentId: "devin", commandPath: "/tmp/agent", commandArgs: ["--yolo"] },
+ },
+ },
+ }),
+ );
+
+ // Even an unlocked pin wins, and the user's launch values and variables are not used.
+ const effective = yield* service.getSettings;
+ const claudeInstance = effective.providerInstances[claudeId]!;
+ assert.deepEqual(claudeInstance.config, {
+ binaryPath: "/opt/claude/bin/claude",
+ autoCompactWindow: "300000",
+ });
+ assert.deepEqual(claudeInstance.environment, [
+ { name: "CLAUDE_CODE_USE_BEDROCK", value: "1", sensitive: false },
+ ]);
+ assert.deepEqual(effective.providerInstances[registryId]?.config, { agentId: "devin" });
+
+ const refused = (instance: typeof claudeInstance) =>
+ service
+ .updateProviderInstance({ operation: "upsert", instanceId: claudeId, instance })
+ .pipe(Effect.flip);
+ const launchArgs = yield* refused({
+ ...claudeInstance,
+ config: { ...claudeInstance.config!, launchArgs: "--permission-mode bypassPermissions" },
+ });
+ assert.equal(launchArgs.operation, "write-managed-setting");
+ assert.equal(launchArgs.managedSetting, "providerInstances.claudeAgent.config.launchArgs");
+ const binary = yield* refused({
+ ...claudeInstance,
+ config: { ...claudeInstance.config!, binaryPath: "/tmp/other-wrapper" },
+ });
+ assert.equal(binary.managedSetting, "providerInstances.claudeAgent.config.binaryPath");
+ const environment = yield* refused({
+ ...claudeInstance,
+ environment: [{ name: "NODE_OPTIONS", value: "--require /tmp/x.js", sensitive: false }],
+ });
+ assert.equal(environment.managedSetting, "providerInstances.claudeAgent.environment");
+ const commandArgs = yield* service
+ .updateProviderInstance({
+ operation: "upsert",
+ instanceId: registryId,
+ instance: {
+ driver: acpRegistry,
+ config: { agentId: "devin", commandArgs: ["--dangerously-skip-permissions"] },
+ },
+ })
+ .pipe(Effect.flip);
+ assert.equal(commandArgs.managedSetting, "providerInstances.acp_devin.config.commandArgs");
+
+ // Unrelated writes carry the stored instance through unchanged, duplicates included.
+ yield* service.updateSettings({ defaultAutoPull: true });
+
+ // What the client was shown saves, with user-owned edits, and the stored values survive.
+ yield* service.updateProviderInstance({
+ operation: "upsert",
+ instanceId: claudeId,
+ instance: {
+ ...claudeInstance,
+ displayName: "Claude (work)",
+ config: { ...claudeInstance.config!, autoCompactWindow: "400000" },
+ },
+ });
+ const stored = JSON.parse(yield* fs.readFileString(config.settingsPath));
+ assert.deepEqual(stored.providerInstances[claudeId], {
+ ...storedClaude,
+ displayName: "Claude (work)",
+ config: { ...storedClaude.config, autoCompactWindow: "400000" },
+ });
+ }).pipe(Effect.provide(layerServerSettings(policy))),
+ );
+});
diff --git a/apps/server/src/serverSettings.ts b/apps/server/src/serverSettings.ts
index 67a1c3c3414..1ead9e27bfc 100644
--- a/apps/server/src/serverSettings.ts
+++ b/apps/server/src/serverSettings.ts
@@ -16,6 +16,7 @@ import {
ServerSettings,
ServerSettingsError,
type ServerSettingsPatch,
+ type ManagedPolicySummary,
globalIdleCompaction,
withIdleCompaction,
} from "@t3tools/contracts";
@@ -52,6 +53,7 @@ import {
isModelSelectionProviderEnabled,
} from "@t3tools/shared/serverSettings";
import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
+import * as ManagedPolicy from "./policy/ManagedPolicy.ts";
import { secretProviderDefinitions } from "./secrets/secretProviderDefinitions.ts";
import {
readSecretFieldValues,
@@ -225,6 +227,9 @@ export class ServerSettingsService extends Context.Service<
readonly ready: Effect.Effect<void, ServerSettingsError>;
+ /** The administrator's policy as clients see it; absent when unmanaged. */
+ readonly managedPolicy?: ManagedPolicySummary | undefined;
+
readonly getSettings: Effect.Effect<ServerSettings, ServerSettingsError>;
readonly updateSettings: (
@@ -246,11 +251,15 @@ export class ServerSettingsService extends Context.Service<
readonly subscribeChanges: Effect.Effect<Stream.Stream<ServerSettings>, never, Scope.Scope>;
}
>()("t3/serverSettings/ServerSettingsService") {
- static readonly layerTest = (overrides: DeepPartial<ServerSettings> = {}) => layerTest(overrides);
+ static readonly layerTest = (
+ overrides: DeepPartial<ServerSettings> = {},
+ managedPolicy?: ManagedPolicySummary,
+ ) => layerTest(overrides, managedPolicy);
}
const makeTest = Effect.fn("serverSettings.makeTest")(function* (
overrides: DeepPartial<ServerSettings> = {},
+ managedPolicy?: ManagedPolicySummary,
) {
const { automaticGitFetchInterval, providerHealthRefreshInterval, ...overridesForMerge } =
overrides;
@@ -281,6 +290,7 @@ const makeTest = Effect.fn("serverSettings.makeTest")(function* (
);
return {
+ managedPolicy,
start: Effect.void,
ready: Effect.void,
getSettings,
@@ -303,8 +313,11 @@ const makeTest = Effect.fn("serverSettings.makeTest")(function* (
} satisfies ServerSettingsService["Service"];
});
-export const layerTest = (overrides: DeepPartial<ServerSettings> = {}) =>
- Layer.effect(ServerSettingsService, makeTest(overrides));
+/** Test settings; `managedPolicy` only tells consumers a policy applies, it does not lock values. */
+export const layerTest = (
+ overrides: DeepPartial<ServerSettings> = {},
+ managedPolicy?: ManagedPolicySummary,
+) => Layer.effect(ServerSettingsService, makeTest(overrides, managedPolicy));
// Accept retired token delivery only on load so one old value cannot reset all settings.
const PersistedResponseStreamingMode = Schema.Union([
@@ -319,24 +332,24 @@ const PersistedResponseStreamingMode = Schema.Union([
}),
),
);
-const ServerSettingsJson = fromLenientJson(
- Schema.Struct({
- ...ServerSettings.fields,
- responseStreamingMode: PersistedResponseStreamingMode.pipe(
- Schema.withDecodingDefault(Effect.succeed("paragraph" as const)),
+const PersistedServerSettings = Schema.Struct({
+ ...ServerSettings.fields,
+ responseStreamingMode: PersistedResponseStreamingMode.pipe(
+ Schema.withDecodingDefault(Effect.succeed("paragraph" as const)),
+ ),
+ projectSettingsOverrides: Schema.Record(
+ ProjectId,
+ keepUnknownOverrideKeys(
+ Schema.Struct({
+ ...ProjectSettingsOverrides.fields,
+ responseStreamingMode: Schema.optionalKey(PersistedResponseStreamingMode),
+ }),
),
- projectSettingsOverrides: Schema.Record(
- ProjectId,
- keepUnknownOverrideKeys(
- Schema.Struct({
- ...ProjectSettingsOverrides.fields,
- responseStreamingMode: Schema.optionalKey(PersistedResponseStreamingMode),
- }),
- ),
- ).pipe(Schema.withDecodingDefault(Effect.succeed({}))),
- }),
-);
-const decodeServerSettingsJsonExit = Schema.decodeUnknownExit(ServerSettingsJson);
+ ).pipe(Schema.withDecodingDefault(Effect.succeed({}))),
+});
+// Parse first and decode second, so a managed policy can fill its defaults in between.
+const decodeSettingsFileJsonExit = Schema.decodeUnknownExit(fromLenientJson(Schema.Unknown));
+const decodePersistedServerSettingsExit = Schema.decodeUnknownExit(PersistedServerSettings);
const LegacyProviderSettingsJson = fromLenientJson(
Schema.Struct({
providers: Schema.optionalKey(Schema.Record(Schema.String, Schema.Unknown)),
@@ -461,17 +474,33 @@ function selectionSupportsTextGeneration(
return settings.providerInstances[selection.instanceId]?.driver !== ACP_REGISTRY_DRIVER;
}
-function resolveTextGenerationProvider(settings: ServerSettings): ServerSettings {
- return isModelSelectionProviderEnabled(settings, settings.textGenerationModelSelection) &&
- selectionSupportsTextGeneration(settings, settings.textGenerationModelSelection)
+type DriverAllowed = (driver: ProviderDriverKind) => boolean;
+const anyDriver: DriverAllowed = () => true;
+
+function resolveTextGenerationProvider(
+ settings: ServerSettings,
+ isDriverAllowed: DriverAllowed = anyDriver,
+): ServerSettings {
+ const selection = settings.textGenerationModelSelection;
+ return isModelSelectionProviderEnabled(settings, selection) &&
+ selectionSupportsTextGeneration(settings, selection) &&
+ isDriverAllowed(
+ settings.providerInstances[selection.instanceId]?.driver ??
+ ProviderDriverKind.make(selection.instanceId),
+ )
? settings
- : fallbackTextGenerationProvider(settings);
+ : fallbackTextGenerationProvider(settings, isDriverAllowed);
}
-function fallbackTextGenerationProvider(settings: ServerSettings): ServerSettings {
+function fallbackTextGenerationProvider(
+ settings: ServerSettings,
+ isDriverAllowed: DriverAllowed,
+): ServerSettings {
const fallback = fallbackTextGenerationModelSelection(
settings.providerInstances,
(instanceId, driver) =>
+ // A default instance id can be configured with another driver.
+ isDriverAllowed(settings.providerInstances[instanceId]?.driver ?? driver) &&
resolveProviderInstanceEnabled(
settings.providerInstances[instanceId] ?? { driver, config: {} },
),
@@ -489,6 +518,10 @@ const ATOMIC_SETTINGS_KEYS: ReadonlySet<string> = new Set([
"textGenerationModelSelection",
"fallbackModelSelection",
"pullRequestMergeMethod",
+ // Empty by default, these hold one whole value, which a managed policy can default.
+ ...Object.entries(DEFAULT_SERVER_SETTINGS).flatMap(([key, value]) =>
+ value === null ? [key] : [],
+ ),
]);
function stripDefaultServerSettings(current: unknown, defaults: unknown): unknown | undefined {
@@ -610,6 +643,17 @@ const make = Effect.gen(function* () {
const pathService = yield* Path.Path;
const secretStore = yield* ServerSecretStore.ServerSecretStore;
const sql = yield* SqlClient.SqlClient;
+ const {
+ settings: managed,
+ providers: managedProviders,
+ summary: managedPolicy,
+ } = yield* ManagedPolicy.ManagedPolicy;
+ // Locks are laid over every settings value that leaves this service, never persisted.
+ const toEffective = (settings: ServerSettings) =>
+ resolveTextGenerationProvider(
+ managedProviders.applyLimits(managed.applyLocks(settings)),
+ managedProviders.isDriverAllowed,
+ );
const writeSemaphore = yield* Semaphore.make(1);
const cacheKey = "settings" as const;
const changesPubSub = yield* PubSub.unbounded<ServerSettings>();
@@ -643,10 +687,22 @@ const make = Effect.gen(function* () {
),
);
+ // The file before this write, parsed; only read when policy defaults need it.
+ const readStoredSettings = Effect.gen(function* () {
+ if (!(yield* readConfigExists)) return undefined;
+ const parsed = decodeSettingsFileJsonExit(yield* readRawConfig);
+ return Exit.isSuccess(parsed) ? parsed.value : undefined;
+ });
+
const writeSettingsAtomically = Effect.fnUntraced(
function* (settings: ServerSettings) {
+ const stripped = stripDefaultServerSettings(settings, managed.defaults) ?? {};
const sparseSettingsJson = yield* encodeServerSettingsJson(
- stripDefaultServerSettings(settings, DEFAULT_SERVER_SETTINGS) ?? {},
+ managed.keepStored === undefined
+ ? stripped
+ : managed.keepStored(stripped, settings, yield* readStoredSettings, (key) =>
+ ATOMIC_SETTINGS_KEYS.has(key),
+ ),
);
return yield* writeFileStringAtomically({
@@ -698,14 +754,17 @@ const make = Effect.gen(function* () {
);
const loadSettingsFromDisk = Effect.gen(function* () {
- let settings = DEFAULT_SERVER_SETTINGS;
+ let settings = managed.defaults;
let legacyProviders: Readonly<Record<string, unknown>> | undefined;
let legacySourceControl: Parameters<typeof migrateLegacySourceControlSettings>[1] = {};
let parseFailure = Option.none<unknown>();
if (yield* readConfigExists) {
const raw = yield* readRawConfig;
- const decoded = decodeServerSettingsJsonExit(raw);
+ const parsed = decodeSettingsFileJsonExit(raw);
+ const decoded = Exit.isFailure(parsed)
+ ? parsed
+ : decodePersistedServerSettingsExit(managed.withDefaults(parsed.value));
const legacySettings = decodeLegacyProviderSettingsJsonExit(raw);
if (legacySettings._tag === "Success") {
legacyProviders = legacySettings.value.providers;
@@ -717,7 +776,7 @@ const make = Effect.gen(function* () {
if (decoded._tag === "Failure" || legacySettings._tag === "Failure") {
const failure = decoded._tag === "Failure" ? decoded : legacySettings;
// The file may hold an opt-out we can no longer read; never resume threads on a guess.
- settings = { ...DEFAULT_SERVER_SETTINGS, continueThreadsAfterServerUpdate: false };
+ settings = { ...managed.defaults, continueThreadsAfterServerUpdate: false };
if (failure._tag === "Failure") {
parseFailure = Option.some(Cause.squash(failure.cause));
yield* Effect.logWarning("failed to parse settings.json, using defaults", {
@@ -900,7 +959,7 @@ const make = Effect.gen(function* () {
if (materialized?.source === source) return Effect.succeed(materialized.value);
const generation = secretWriteGeneration;
return materializeSettingsSecrets(source).pipe(
- Effect.map(resolveTextGenerationProvider),
+ Effect.map(toEffective),
Effect.tap((value) =>
Effect.sync(() => {
if (generation === secretWriteGeneration) materialized = { source, value };
@@ -924,7 +983,7 @@ const make = Effect.gen(function* () {
),
),
),
- Stream.map(resolveTextGenerationProvider),
+ Stream.map(toEffective),
);
type SecretChange = {
@@ -1070,6 +1129,7 @@ const make = Effect.gen(function* () {
};
const updateAndPersistSettings = (
+ patch: ServerSettingsPatch,
update: (current: ServerSettings) => Effect.Effect<ServerSettings, ServerSettingsError>,
): Effect.Effect<ServerSettings, ServerSettingsError> =>
writeSemaphore.withPermits(1)(
@@ -1083,7 +1143,35 @@ const make = Effect.gen(function* () {
});
}
const updated = yield* update(current);
- const persisted = yield* persistSettingsSecrets(current, updated);
+ // Vet before secrets: a variable the policy hides from clients is not one they removed.
+ const vetted = managed.vetWrite(current, yield* normalizeServerSettings(updated), patch);
+ if (vetted._tag === "Locked") {
+ return yield* new ServerSettingsError({
+ settingsPath,
+ operation: "write-managed-setting",
+ managedSetting: vetted.path,
+ managedBy: managedPolicy?.organization,
+ });
+ }
+ const vettedProviders = managedProviders.vetWrite(current, vetted.settings);
+ if (vettedProviders._tag === "Locked") {
+ return yield* new ServerSettingsError({
+ settingsPath,
+ operation: "write-managed-setting",
+ managedSetting: vettedProviders.path,
+ managedBy: managedPolicy?.organization,
+ });
+ }
+ if (vettedProviders._tag === "Disallowed") {
+ return yield* new ServerSettingsError({
+ settingsPath,
+ operation: "use-disallowed-provider",
+ providerInstanceId: vettedProviders.instanceId,
+ providerLabel: vettedProviders.label,
+ managedBy: managedPolicy?.organization,
+ });
+ }
+ const persisted = yield* persistSettingsSecrets(current, vettedProviders.settings);
const next = yield* normalizeServerSettings(persisted.settings);
const materializedNext = yield* Effect.uninterruptibleMask(() =>
Effect.gen(function* () {
@@ -1103,7 +1191,7 @@ const make = Effect.gen(function* () {
}).pipe(Effect.ensuring(invalidateMaterialized)),
);
yield* Cache.set(settingsCache, cacheKey, { settings: next, parseFailure: Option.none() });
- const resolved = resolveTextGenerationProvider(materializedNext);
+ const resolved = toEffective(materializedNext);
materialized = { source: next, value: resolved };
yield* emitChange(next);
return resolved;
@@ -1214,17 +1302,18 @@ const make = Effect.gen(function* () {
});
return {
+ managedPolicy,
start,
ready: Deferred.await(startedDeferred),
getSettings: getMaterializedSettings,
updateSettings: (patch) =>
- updateAndPersistSettings((current) =>
+ updateAndPersistSettings(patch, (current) =>
ensureSecretProviderWritesAllowed(patch, settingsPath).pipe(
Effect.as(applyServerSettingsPatch(current, patch)),
),
),
updateProviderInstance: (mutation, patch = {}) =>
- updateAndPersistSettings((current) =>
+ updateAndPersistSettings(patch, (current) =>
Effect.gen(function* () {
yield* ensureSecretProviderWritesAllowed(patch, settingsPath);
yield* ensureProviderInstanceMutationAllowed(current, mutation, settingsPath);
diff --git a/apps/server/src/telemetry/AnalyticsService.test.ts b/apps/server/src/telemetry/AnalyticsService.test.ts
index eb5858c4ba4..1cc30e74e50 100644
--- a/apps/server/src/telemetry/AnalyticsService.test.ts
+++ b/apps/server/src/telemetry/AnalyticsService.test.ts
@@ -16,7 +16,10 @@ import * as HttpServerRequest from "effect/http/HttpServerRequest";
import * as HttpServerResponse from "effect/http/HttpServerResponse";
import * as HostProcess from "@t3tools/shared/HostProcess";
+import type { ManagedPolicyDocument } from "@t3tools/contracts";
+
import * as ServerConfig from "../config.ts";
+import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
import { getTelemetryIdentity } from "./Identify.ts";
import * as AnalyticsService from "./AnalyticsService.ts";
@@ -119,6 +122,7 @@ const sendFor = (
never,
AnalyticsService.AnalyticsService | Effect.Services<typeof getTelemetryIdentity>
> = recordTwentyEvents,
+ policy?: ManagedPolicyDocument,
) =>
Effect.gen(function* () {
const batches: Array<ReadonlyArray<SentEvent>> = [];
@@ -151,6 +155,7 @@ const sendFor = (
Layer.succeed(HostProcess.Platform, "win32"),
Layer.succeed(HostProcess.Architecture, "x64"),
Layer.succeed(HttpClient.HttpClient, client),
+ ManagedPolicy.layerTest(policy),
),
),
);
@@ -240,6 +245,24 @@ it.layer(NodeServices.layer)("AnalyticsService test", (it) => {
}),
);
+ it.effect(
+ "sends nothing when a managed policy turns telemetry off, despite the environment",
+ () =>
+ Effect.gen(function* () {
+ const policy = { schemaVersion: 1, organization: "Example Corp" } as const;
+ const allowed = yield* sendFor(1, respondWithStatus(204), recordTwentyEvents, {
+ ...policy,
+ limits: { telemetry: true },
+ });
+ assert.equal(allowed.length, 1);
+ const denied = yield* sendFor(1, respondWithStatus(204), recordTwentyEvents, {
+ ...policy,
+ limits: { telemetry: false },
+ });
+ assert.deepEqual(denied, []);
+ }),
+ );
+
it.effect("drops a batch the endpoint rejects without sending it again", () =>
Effect.gen(function* () {
const batches = yield* sendFor(10, respondWithStatus(400));
@@ -286,6 +309,7 @@ it.layer(NodeServices.layer)("AnalyticsService test", (it) => {
Layer.mergeAll(
Layer.succeed(HostProcess.Platform, "linux"),
Layer.succeed(HostProcess.Architecture, "arm64"),
+ ManagedPolicy.layerTest(),
),
),
Layer.provideMerge(NodeHttpServer.layerTest),
@@ -376,6 +400,7 @@ it.layer(NodeServices.layer)("AnalyticsService test", (it) => {
Layer.mergeAll(
Layer.succeed(HostProcess.Platform, "linux"),
Layer.succeed(HostProcess.Architecture, "arm64"),
+ ManagedPolicy.layerTest(),
),
),
Layer.provideMerge(NodeHttpServer.layerTest),
diff --git a/apps/server/src/telemetry/AnalyticsService.ts b/apps/server/src/telemetry/AnalyticsService.ts
index 07b6f604e08..05d82c7aa5c 100644
--- a/apps/server/src/telemetry/AnalyticsService.ts
+++ b/apps/server/src/telemetry/AnalyticsService.ts
@@ -21,6 +21,7 @@ import * as HttpClientResponse from "effect/http/HttpClientResponse";
import packageJson from "../../package.json" with { type: "json" };
import * as ServerConfig from "../config.ts";
+import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
import { getTelemetryIdentity, type TelemetryOwner } from "./Identify.ts";
interface BufferedAnalyticsEvent {
@@ -119,9 +120,12 @@ export const make = Effect.gen(function* () {
const telemetryConfig = yield* TelemetryEnvConfig;
const hostEnvironment = yield* HostProcess.Environment;
const awaitingShellConsent = hostEnvironment.T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING === "1";
+ // A managed policy can switch analytics off over the environment, never on.
+ const policyAllows =
+ ManagedPolicy.deniedBy(yield* ManagedPolicy.ManagedPolicy, "telemetry") === undefined;
// A cached PATH does not establish consent from the current login shell.
const telemetryEnabled = Effect.suspend(() => {
- if (!telemetryConfig.enabled) return Effect.succeed(false);
+ if (!telemetryConfig.enabled || !policyAllows) return Effect.succeed(false);
if (!awaitingShellConsent) return Effect.succeed(true);
if (hostEnvironment.T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING === "1")
return Effect.succeed(false);
diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts
index ca899d4ef04..09db12ea35b 100644
--- a/apps/server/src/ws.test.ts
+++ b/apps/server/src/ws.test.ts
@@ -111,6 +111,7 @@ import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
import * as ServerConfigModule from "./config.ts";
import * as Keybindings from "./keybindings.ts";
import * as ServerSettings from "./serverSettings.ts";
+import * as ManagedPolicy from "./policy/ManagedPolicy.ts";
import * as EventStore from "./orchestration-v2/EventStore.ts";
import * as ProjectionMaintenance from "./orchestration-v2/ProjectionMaintenance.ts";
@@ -602,7 +603,9 @@ const layerUnusedConfigRpcServices = Layer.mergeAll(
const layerConfigSources = Layer.mergeAll(
Keybindings.layer,
- ServerSettings.layer.pipe(Layer.provide(ServerSecretStore.layer)),
+ ServerSettings.layer.pipe(
+ Layer.provide(Layer.merge(ServerSecretStore.layer, ManagedPolicy.layerTest())),
+ ),
).pipe(
Layer.provideMerge(Layer.fresh(SqlitePersistence.layerMemory)),
Layer.provideMerge(
diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts
index abc7c71f4b8..12436650b07 100644
--- a/apps/server/src/ws.ts
+++ b/apps/server/src/ws.ts
@@ -1831,6 +1831,9 @@ export const layerWsRpc = (
otlpLogsEnabled: config.otlpLogsUrl !== undefined,
},
settings,
+ ...(serverSettings.managedPolicy === undefined
+ ? {}
+ : { managedPolicy: serverSettings.managedPolicy }),
shellResumeCompletionMarker: true,
shellThreadFamilies: true,
shellOlderSettled: true,
diff --git a/apps/web/src/components/ManagedPolicy.tsx b/apps/web/src/components/ManagedPolicy.tsx
new file mode 100644
index 00000000000..cce0689563e
--- /dev/null
+++ b/apps/web/src/components/ManagedPolicy.tsx
@@ -0,0 +1,71 @@
+import type { ManagedPolicySummary } from "@t3tools/contracts";
+import { BuildingIcon } from "lucide-react";
+import type { ReactNode } from "react";
+
+import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
+
+/**
+ * A control an administrator's policy turns off: shown inert, with the policy's reason on hover
+ * and focus. Without a reason it renders the control untouched.
+ */
+export function ManagedControl({
+ reason,
+ children,
+}: {
+ reason: string | undefined;
+ children: ReactNode;
+}) {
+ if (reason === undefined) return children;
+ return (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <span
+ tabIndex={0}
+ role="group"
+ aria-disabled="true"
+ aria-label={reason}
+ className="inline-flex rounded-md outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"
+ />
+ }
+ >
+ <span inert className="inline-flex opacity-50">
+ {children}
+ </span>
+ </TooltipTrigger>
+ <TooltipPopup side="top">{reason}</TooltipPopup>
+ </Tooltip>
+ );
+}
+
+/** One line of policy text with the building mark, for places a whole feature is managed. */
+export function ManagedNotice({ children }: { children: ReactNode }) {
+ return (
+ <p className="flex items-start gap-2 text-muted-foreground text-xs leading-relaxed">
+ <BuildingIcon aria-hidden="true" className="mt-0.5 size-3.5 shrink-0" />
+ <span>{children}</span>
+ </p>
+ );
+}
+
+/** "This environment is managed by <organization>", linking the support page when there is one. */
+export function ManagedByOrganization({ policy }: { policy: ManagedPolicySummary }) {
+ return (
+ <ManagedNotice>
+ This environment is managed by {policy.organization}.
+ {policy.supportUrl ? (
+ <>
+ {" "}
+ <a
+ href={policy.supportUrl}
+ target="_blank"
+ rel="noreferrer"
+ className="text-foreground underline underline-offset-2"
+ >
+ Get help
+ </a>
+ </>
+ ) : null}
+ </ManagedNotice>
+ );
+}
diff --git a/apps/web/src/components/ServerUpdateAction.tsx b/apps/web/src/components/ServerUpdateAction.tsx
index 141f139aefd..1d82a7628a2 100644
--- a/apps/web/src/components/ServerUpdateAction.tsx
+++ b/apps/web/src/components/ServerUpdateAction.tsx
@@ -2,6 +2,7 @@ import { useAtomValue } from "@effect/atom-react";
import {
AuthEnvironmentMaintainScope,
type AuthSessionState,
+ managedUpdatesDenial,
sessionGrantsScope,
} from "@t3tools/contracts";
import type { AsyncResult } from "effect/reactivity";
@@ -26,8 +27,11 @@ import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
import { serverEnvironment, updateOutdatedServer } from "~/state/server";
import { appAtomRegistry } from "~/rpc/atomRegistry";
import { useAtomCommand } from "~/state/use-atom-command";
-import { manualServerUpdateCommand } from "~/versionSkew";
import { useServerConfigs } from "~/state/entities";
+import { useManagedPolicy } from "~/state/managedPolicy";
+import { environmentPresentations } from "~/state/presentation";
+import { ManagedControl } from "./ManagedPolicy";
+import { manualServerUpdateCommand } from "~/versionSkew";
import { crossesReleaseTrack } from "@t3tools/shared/cliRelease";
import { Button } from "./ui/button";
import { toastManager } from "./ui/toast";
@@ -44,6 +48,14 @@ export function serverUpdateStageLabel(stage: ServerUpdateStage): string {
return UPDATE_STAGE_LABELS[stage];
}
+/** Why the environment's policy refuses server updates, read outside render. */
+function readUpdatesDenial(environmentId: EnvironmentId): string | undefined {
+ return managedUpdatesDenial(
+ appAtomRegistry.get(environmentPresentations.serverConfigsAtom).get(environmentId)
+ ?.managedPolicy,
+ );
+}
+
const CROSS_TRACK_NOTE = "Switch tracks in About → Update track";
/** Hosts refuse a Stable/Nightly crossing outside a track switch, which checks the database first. */
@@ -103,6 +115,17 @@ export function useServerUpdate() {
{ quiet = false }: { readonly quiet?: boolean } = {},
): Promise<ServerUpdateOutcome> => {
const { environmentId, serverLabel, selfUpdate, targetVersion } = target;
+ const denial = readUpdatesDenial(environmentId);
+ if (denial !== undefined) {
+ if (!quiet) {
+ toastManager.add({
+ type: "error",
+ title: `${serverLabel} not updated`,
+ description: denial,
+ });
+ }
+ return { status: "failed", message: denial };
+ }
if (
!canUpdateServer(appAtomRegistry.get(environmentSession.sessionStateAtom(environmentId))) ||
pendingUpdateEnvironmentIds.has(environmentId)
@@ -163,6 +186,7 @@ export function ServerUpdatesAction({
(target) =>
target.selfUpdate !== null &&
(target.selfUpdate !== "desktop-managed" || target.desktopAppUpdate) &&
+ managedUpdatesDenial(serverConfigs.get(target.environmentId)?.managedPolicy) === undefined &&
!refusedCrossing(target, serverConfigs.get(target.environmentId)?.environment.serverVersion),
);
const handleUpdate = async () => {
@@ -249,6 +273,7 @@ export function ServerUpdateAction({
const serverVersion = useServerConfigs().get(environmentId)?.environment.serverVersion;
const sessionStateAtom = environmentSession.sessionStateAtom(environmentId);
const canUpdate = canUpdateServer(useAtomValue(sessionStateAtom));
+ const updatesDenial = managedUpdatesDenial(useManagedPolicy(environmentId));
const update = useServerUpdate();
const { copyToClipboard } = useCopyToClipboard<{ command: string }>({
target: installation?.kind === "npm-global" ? "update command" : "relaunch command",
@@ -298,6 +323,18 @@ export function ServerUpdateAction({
});
};
+ if (updatesDenial !== undefined) {
+ return appearance === "icon" ? (
+ <ManagedControl reason={updatesDenial}>
+ <Button size="icon-xs" variant="ghost-muted" aria-label={updatesDenial} disabled>
+ <CircleArrowUpIcon className="size-3.5" />
+ </Button>
+ </ManagedControl>
+ ) : (
+ <span className="text-muted-foreground text-xs">{updatesDenial}</span>
+ );
+ }
+
if (selfUpdate === "desktop-managed" && !desktopAppUpdate) {
return (
<span className="text-muted-foreground text-xs">
diff --git a/apps/web/src/components/auth/ConnectAgentSurface.tsx b/apps/web/src/components/auth/ConnectAgentSurface.tsx
index fab38ccefad..f741b550681 100644
--- a/apps/web/src/components/auth/ConnectAgentSurface.tsx
+++ b/apps/web/src/components/auth/ConnectAgentSurface.tsx
@@ -4,6 +4,8 @@ import {
AuthMcpApprovalError,
AuthMcpClientAccess,
AuthMcpAuthorizationRequest,
+ isRuntimeModeAbove,
+ managedRuntimeModeCeilingMessage,
} from "@t3tools/contracts";
import { Radio as RadioPrimitive } from "@base-ui/react/radio";
import { isLoopbackHost } from "@t3tools/shared/preview";
@@ -209,7 +211,12 @@ export function ConnectAgentSurface() {
onValueChange={(value) => setAccess(value as AuthMcpClientAccess)}
>
{AuthMcpClientAccess.literals.map((option) => (
- <AccessOption key={option} access={option} selected={option === access} />
+ <AccessOption
+ key={option}
+ access={option}
+ selected={option === access}
+ managedReason={ceilingReason(details, option)}
+ />
))}
</RadioGroup>
<p className="text-xs text-muted-foreground">
@@ -276,17 +283,30 @@ function ConnectAgentHeading({
return <StandalonePageHeader context="Agent sign-in" title={title} description={description} />;
}
+/** Why a managed policy keeps `access` from being granted, or undefined when it may be. */
+function ceilingReason(details: AuthMcpApprovalDetails, access: AuthMcpClientAccess) {
+ const ceiling = details.runtimeModeCeiling;
+ return ceiling === undefined ||
+ access === "read-only" ||
+ !isRuntimeModeAbove(access, ceiling.maxRuntimeMode)
+ ? undefined
+ : managedRuntimeModeCeilingMessage(ceiling.organization, ceiling.maxRuntimeMode);
+}
+
function AccessOption({
access,
selected,
+ managedReason,
}: {
readonly access: AuthMcpClientAccess;
readonly selected: boolean;
+ readonly managedReason: string | undefined;
}) {
const { label, description, icon: Icon } = accessConfig[access];
return (
<RadioPrimitive.Root
value={access}
+ disabled={managedReason !== undefined}
className={cn(
"flex cursor-pointer items-start gap-3 rounded-lg border px-3 py-2.5 text-left outline-none transition-[background-color,border-color,box-shadow]",
"focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",
@@ -304,7 +324,7 @@ function AccessOption({
/>
<span className="min-w-0">
<span className="block text-sm font-medium text-foreground">{label}</span>
- <span className="block text-xs text-muted-foreground">{description}</span>
+ <span className="block text-xs text-muted-foreground">{managedReason ?? description}</span>
</span>
</RadioPrimitive.Root>
);
diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx
index 82b6b9617c1..7d1f0ade710 100644
--- a/apps/web/src/components/chat/ChatComposer.tsx
+++ b/apps/web/src/components/chat/ChatComposer.tsx
@@ -38,6 +38,8 @@ import type {
import {
EnvironmentRequestInvalidError,
AuthOrchestrationOperateScope,
+ clampManagedRuntimeMode,
+ managedRuntimeModeDenial,
ProviderDriverKind,
ProviderInstanceId,
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
@@ -230,7 +232,9 @@ import { observeResize } from "~/lib/observeResize";
const isEnvironmentRequestInvalidError = Schema.is(EnvironmentRequestInvalidError);
import { toastManager } from "../ui/toast";
-import { PlayIcon } from "lucide-react";
+import { BuildingIcon, PlayIcon } from "lucide-react";
+import { Button } from "../ui/button";
+import { useManagedPolicy } from "../../state/managedPolicy";
import { proposedPlanTitle } from "@t3tools/shared/proposedPlanText";
import { hasProviderSetup } from "./ProviderStatusBanner";
import { type AppModelOption, getAppModelOptionsForInstance } from "../../modelSelection";
@@ -910,9 +914,20 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
runtimeMode,
selectedProviderEntry?.snapshot.supportedRuntimeModes,
);
- const compatibleRuntimeModeOptions = runtimeModeOptions.filter((option) =>
- compatibleRuntimeModes.includes(option.mode),
- );
+ // Modes above an administrator's ceiling stay listed, disabled with the reason.
+ const managedPolicy = useManagedPolicy(environmentId);
+ const compatibleRuntimeModeOptions = runtimeModeOptions
+ .filter((option) => compatibleRuntimeModes.includes(option.mode))
+ .map((option) => {
+ const disabledReason = managedRuntimeModeDenial(managedPolicy, option.mode);
+ return disabledReason === undefined ? option : { ...option, disabledReason };
+ });
+ // A thread or draft already above the ceiling would be refused; offer the broadest mode left.
+ const runtimeModeCeilingDenial = managedRuntimeModeDenial(managedPolicy, compatibleRuntimeMode);
+ const runtimeModeCeilingFallback =
+ runtimeModeCeilingDenial === undefined
+ ? undefined
+ : clampManagedRuntimeMode(managedPolicy, compatibleRuntimeMode, compatibleRuntimeModes);
const providerSendBlockReason = getAntigravitySendBlockReason(
selectedProviderEntry?.snapshot,
@@ -924,6 +939,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
(activePendingProgress
? attachmentBlockReason
: (attachmentBlockReason ??
+ runtimeModeCeilingDenial ??
(multipleModelSelections === null ? providerSendBlockReason : null)));
const isSendDisabled = sendDisabledReason !== null;
const selectedProviderStatus = selectedProviderEntry?.snapshot ?? null;
@@ -2349,12 +2365,37 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
);
// An open question owns the space above the composer. Only a machine problem,
// which is why an answer could not go through, stays beside it.
+ const bannerItems: readonly ComposerBannerStackItem[] =
+ runtimeModeCeilingDenial === undefined || activePendingProgress
+ ? props.bannerItems
+ : [
+ ...props.bannerItems,
+ {
+ id: "managed-runtime-mode",
+ variant: "warning",
+ icon: <BuildingIcon />,
+ title: runtimeModeCeilingDenial,
+ ...(runtimeModeCeilingFallback === undefined
+ ? {}
+ : {
+ actions: (
+ <Button
+ size="xs"
+ variant="ghost"
+ onClick={() => handleRuntimeModeChange(runtimeModeCeilingFallback)}
+ >
+ Switch to {runtimeModeConfig[runtimeModeCeilingFallback].label}
+ </Button>
+ ),
+ }),
+ },
+ ];
const shelfItems = hasBlockingComposerTopDrawer
- ? props.bannerItems.filter(
+ ? bannerItems.filter(
(item) =>
item.group === "environment" && (item.variant === "error" || item.variant === "warning"),
)
- : props.bannerItems;
+ : bannerItems;
const insertComposerText = (
text: string,
diff --git a/apps/web/src/components/chat/ComposerFooterControls.tsx b/apps/web/src/components/chat/ComposerFooterControls.tsx
index 31c5889db9b..cb5e78c1e8c 100644
--- a/apps/web/src/components/chat/ComposerFooterControls.tsx
+++ b/apps/web/src/components/chat/ComposerFooterControls.tsx
@@ -21,8 +21,11 @@ import { ProviderModelPicker } from "./ProviderModelPicker";
import { runtimeModeConfig } from "./runtimeModeConfig";
import { useComposerMenuState } from "./useComposerMenuState";
-export type RuntimeModeOption = { mode: RuntimeMode } & (typeof runtimeModeConfig)[RuntimeMode];
-const supervisedRuntimeModeOption = {
+export type RuntimeModeOption = {
+ mode: RuntimeMode;
+ disabledReason?: string;
+} & (typeof runtimeModeConfig)[RuntimeMode];
+const supervisedRuntimeModeOption: RuntimeModeOption = {
mode: "approval-required" as const,
...runtimeModeConfig["approval-required"],
};
@@ -161,9 +164,7 @@ export const ComposerFooterModeControls = memo(function ComposerFooterModeContro
*/
export function ComposerPermissionsSection(props: {
runtimeMode: RuntimeMode;
- runtimeModeOptions: ReadonlyArray<
- { mode: RuntimeMode } & (typeof runtimeModeConfig)[RuntimeMode]
- >;
+ runtimeModeOptions: ReadonlyArray<RuntimeModeOption>;
onRuntimeModeChange: (mode: RuntimeMode) => void;
}) {
// Hover or keyboard focus previews a mode's name and description before a pick.
@@ -203,6 +204,7 @@ export function ComposerPermissionsSection(props: {
<MenuPrimitive.RadioItem
key={option.mode}
value={option.mode}
+ disabled={option.disabledReason !== undefined}
label={option.label}
aria-label={option.label}
aria-describedby={`${descriptionId}-${option.mode}`}
@@ -211,7 +213,7 @@ export function ComposerPermissionsSection(props: {
onPointerLeave={() => setPreviewMode(null)}
onFocus={() => setPreviewMode(option.mode)}
onBlur={() => setPreviewMode(null)}
- className="flex h-6 flex-1 cursor-pointer items-center justify-center text-muted-foreground outline-none first:rounded-l-md last:rounded-r-md data-checked:bg-input/72 data-checked:text-foreground data-highlighted:text-foreground not-data-checked:data-highlighted:bg-accent focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset"
+ className="flex h-6 flex-1 cursor-pointer items-center justify-center text-muted-foreground outline-none first:rounded-l-md last:rounded-r-md data-disabled:cursor-not-allowed data-disabled:opacity-40 data-checked:bg-input/72 data-checked:text-foreground data-highlighted:text-foreground not-data-checked:data-highlighted:bg-accent focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset"
>
<OptionIcon aria-hidden="true" className="size-3.5" />
</MenuPrimitive.RadioItem>
@@ -221,7 +223,7 @@ export function ComposerPermissionsSection(props: {
{/* Static per-mode descriptions for screen readers; the preview below is visual only. */}
{props.runtimeModeOptions.map((option) => (
<span key={option.mode} id={`${descriptionId}-${option.mode}`} className="sr-only">
- {option.description}
+ {option.disabledReason ?? option.description}
</span>
))}
<div className="grid gap-0.5" aria-hidden="true">
@@ -235,7 +237,9 @@ export function ComposerPermissionsSection(props: {
{shown.label}
</span>
{/* Two lines reserved so the menu does not shift while you preview modes. */}
- <span className="min-h-8 text-muted-foreground text-xs leading-4">{shown.description}</span>
+ <span className="min-h-8 text-muted-foreground text-xs leading-4">
+ {shown.disabledReason ?? shown.description}
+ </span>
</div>
</div>
);
diff --git a/apps/web/src/components/chat/ModelPickerSidebar.tsx b/apps/web/src/components/chat/ModelPickerSidebar.tsx
index 1c792cf4cec..c07b1f33c5f 100644
--- a/apps/web/src/components/chat/ModelPickerSidebar.tsx
+++ b/apps/web/src/components/chat/ModelPickerSidebar.tsx
@@ -13,7 +13,8 @@ import {
function describeUnavailableInstance(entry: ProviderInstanceEntry): string {
const label = entry.displayName;
- if (!entry.enabled || entry.status === "disabled") {
+ // An unavailable instance (a driver this build lacks or the policy leaves out) says why instead.
+ if ((!entry.enabled && entry.isAvailable) || entry.status === "disabled") {
return `${label}: Disabled in settings.`;
}
if (entry.status === "ready" && entry.isAvailable) {
diff --git a/apps/web/src/components/chat/ThreadAutomationsPanel.tsx b/apps/web/src/components/chat/ThreadAutomationsPanel.tsx
index ca2497bd20e..30eade3d813 100644
--- a/apps/web/src/components/chat/ThreadAutomationsPanel.tsx
+++ b/apps/web/src/components/chat/ThreadAutomationsPanel.tsx
@@ -41,7 +41,9 @@ function taskScheduleLine(task: ScheduledTask) {
return (
<>
{scheduleLabel(task.schedule)}
- {task.enabled && task.nextRunAt !== null ? (
+ {task.blockedByPolicy !== undefined ? (
+ ` · ${task.blockedByPolicy}`
+ ) : task.enabled && task.nextRunAt !== null ? (
<>
{" · next "}
<ScheduledRelativeLabel value={task.nextRunAt} />
diff --git a/apps/web/src/components/chat/guestShareAvailability.ts b/apps/web/src/components/chat/guestShareAvailability.ts
index e49d2e57e02..4e5c8a77916 100644
--- a/apps/web/src/components/chat/guestShareAvailability.ts
+++ b/apps/web/src/components/chat/guestShareAvailability.ts
@@ -1,4 +1,4 @@
-import type { EnvironmentId } from "@t3tools/contracts";
+import { type EnvironmentId, managedCapabilityDenial } from "@t3tools/contracts";
import { Atom } from "effect/reactivity";
import { environmentPresentations } from "~/state/presentation";
@@ -7,12 +7,15 @@ import { serverEnvironment } from "~/state/server";
/**
* Whether this environment offers "Share with guest": the user may create links there, and its
* Guest links beta is on (Settings > Labs). The server refuses links while the beta is off.
+ * Guests arrive through T3 Connect, so a policy that turns Connect off hides sharing too.
*/
export const canShareWithGuestAtom = Atom.family((environmentId: EnvironmentId) =>
- Atom.make(
- (get) =>
+ Atom.make((get) => {
+ const serverConfig = get(environmentPresentations.serverConfigsAtom).get(environmentId);
+ return (
get(serverEnvironment.createGuestShare.permissionAtom(environmentId)) &&
- get(environmentPresentations.serverConfigsAtom).get(environmentId)?.settings
- .guestSharingEnabled === true,
- ).pipe(Atom.withLabel(`guest-share:available:${environmentId}`)),
+ serverConfig?.settings.guestSharingEnabled === true &&
+ managedCapabilityDenial(serverConfig.managedPolicy, "connect") === undefined
+ );
+ }).pipe(Atom.withLabel(`guest-share:available:${environmentId}`)),
);
diff --git a/apps/web/src/components/cloud/ConnectOnboardingDialog.tsx b/apps/web/src/components/cloud/ConnectOnboardingDialog.tsx
index 2e6bb927d69..70c4f6e8579 100644
--- a/apps/web/src/components/cloud/ConnectOnboardingDialog.tsx
+++ b/apps/web/src/components/cloud/ConnectOnboardingDialog.tsx
@@ -1,6 +1,11 @@
import { useAuth } from "@clerk/react";
import { useAtomValue } from "@effect/atom-react";
-import { AuthRelayReadScope, AuthRelayWriteScope, type AuthSessionState } from "@t3tools/contracts";
+import {
+ AuthRelayReadScope,
+ AuthRelayWriteScope,
+ type AuthSessionState,
+ managedCapabilityDenial,
+} from "@t3tools/contracts";
import { AsyncResult, Atom } from "effect/reactivity";
import { useState } from "react";
@@ -19,6 +24,7 @@ import {
usePrimaryEnvironment,
usePrimaryEnvironmentId,
} from "~/state/environments";
+import { usePrimaryManagedPolicy } from "~/state/managedPolicy";
import { environmentSession, readEnvironmentScope, useEnvironmentScope } from "~/state/session";
import {
type T3ConnectAccountPageUrl,
@@ -64,7 +70,10 @@ function ConfiguredConnectOnboardingDialog() {
);
const canReadRelay = useEnvironmentScope(primaryEnvironmentId, AuthRelayReadScope);
const canWriteRelay = useEnvironmentScope(primaryEnvironmentId, AuthRelayWriteScope);
- const canManageRelay = canReadRelay && canWriteRelay;
+ // A policy that turns Connect off leaves nothing to publish; reaching other devices still works.
+ const connectAllowed =
+ managedCapabilityDenial(usePrimaryManagedPolicy(), "connect") === undefined;
+ const canManageRelay = canReadRelay && canWriteRelay && connectAllowed;
const sessionScopesKnown =
primaryEnvironmentId === null ? environmentsReady : primarySessionState._tag !== "Initial";
diff --git a/apps/web/src/components/desktopUpdate.logic.ts b/apps/web/src/components/desktopUpdate.logic.ts
index 5277747ee63..51b2b92b0a8 100644
--- a/apps/web/src/components/desktopUpdate.logic.ts
+++ b/apps/web/src/components/desktopUpdate.logic.ts
@@ -145,17 +145,21 @@ export function canCheckForUpdate(state: DesktopUpdateState | null): boolean {
);
}
+/** `managedDenial` is this machine's policy refusing updates (`managedUpdatesDenial`); it wins. */
export function getDesktopUpdateDisabledReason(
state: Pick<DesktopUpdateState, "enabled" | "status" | "message"> | null,
+ managedDenial?: string,
): string | null {
+ if (managedDenial !== undefined) return managedDenial;
if (!state || (state.enabled && state.status !== "disabled")) return null;
return state.message?.trim() || "Automatic updates are not available in this build.";
}
export function getDesktopUpdateIdleTooltip(
state: Pick<DesktopUpdateState, "enabled" | "status" | "message"> | null,
+ managedDenial?: string,
) {
- const disabledReason = getDesktopUpdateDisabledReason(state);
+ const disabledReason = getDesktopUpdateDisabledReason(state, managedDenial);
return disabledReason
? { title: "Updates unavailable", detail: disabledReason }
: { title: "Check for updates", detail: null };
diff --git a/apps/web/src/components/onboarding/WelcomeWizard.tsx b/apps/web/src/components/onboarding/WelcomeWizard.tsx
index cc41156b0b6..5dc5f0e28e0 100644
--- a/apps/web/src/components/onboarding/WelcomeWizard.tsx
+++ b/apps/web/src/components/onboarding/WelcomeWizard.tsx
@@ -20,6 +20,7 @@ import {
CommandId,
defaultInstanceIdForDriver,
AuthOrchestrationOperateScope,
+ isManagedDriverAllowed,
ProviderDriverKind,
ThreadId,
} from "@t3tools/contracts";
@@ -60,6 +61,11 @@ import { newProjectId, randomUUID } from "../../lib/utils";
import { agentSessionImport } from "../../state/agentSessions";
import { readProjects, waitForProject } from "../../state/entities";
import { useEnvironments, usePrimaryEnvironment } from "../../state/environments";
+import {
+ managedInstanceLocks,
+ managedTelemetryOffMessage,
+ usePrimaryManagedPolicy,
+} from "../../state/managedPolicy";
import {
isOnboardingRelayEnvironment,
resolveOnboardingSetup,
@@ -310,6 +316,7 @@ function ConnectionStep({
readonly onPaired: (environmentId: EnvironmentId) => void;
}) {
const { environments } = useEnvironments();
+ const telemetryOff = managedTelemetryOffMessage(usePrimaryManagedPolicy());
const cloudEnabled = hasCloudPublicConfig();
const directEnvironments = environments.filter(
(environment) => !cloudEnabled || !isOnboardingRelayEnvironment(environment),
@@ -434,8 +441,9 @@ function ConnectionStep({
) : null}
<div className="mt-6 flex flex-col-reverse gap-4 sm:flex-row sm:items-center sm:justify-between sm:gap-6">
<p className="min-w-0 text-xs leading-relaxed text-muted-foreground">
- T3 Code collects anonymous usage data to help us improve it. To read more about how your
- data is used and how to opt out, see our{" "}
+ {telemetryOff ?? "T3 Code collects anonymous usage data to help us improve it."} To read
+ more about how your data is used{telemetryOff === undefined ? " and how to opt out" : ""},
+ see our{" "}
<a
className="underline underline-offset-2 hover:text-foreground"
href={PRIVACY_POLICY_URL}
@@ -728,8 +736,16 @@ function ConnectedAgentsStep({
}, [environmentId, refreshProviders]);
const byDriver = selectOnboardingProvidersByDriver(providers);
+ const managedPolicy = serverConfig?.managedPolicy;
+ // A policy that owns Codex's launch settings also rules out ChatGPT's own runtime.
+ const chatGptAllowed =
+ managedInstanceLocks(managedPolicy, ProviderDriverKind.make("codex"))?.configKeys.has(
+ "setupMode",
+ ) !== true;
- const primaryAgents = PRIMARY_AGENT_DRIVERS.flatMap((driver) => {
+ const primaryAgents = PRIMARY_AGENT_DRIVERS.filter((driver) =>
+ isManagedDriverAllowed(managedPolicy, ProviderDriverKind.make(driver)),
+ ).flatMap((driver) => {
const instances =
driver === "codex" ? providers?.filter((provider) => provider.driver === driver) : undefined;
return instances?.length
@@ -831,7 +847,8 @@ function ConnectedAgentsStep({
),
)}
</div>
- {providers?.some(
+ {chatGptAllowed &&
+ providers?.some(
(provider) =>
provider.driver === "codex" && getOnboardingProviderState(provider) === "ready",
) ? (
diff --git a/apps/web/src/components/settings/AddProviderInstanceDialog.tsx b/apps/web/src/components/settings/AddProviderInstanceDialog.tsx
index 0c9eee9386c..31e298beec2 100644
--- a/apps/web/src/components/settings/AddProviderInstanceDialog.tsx
+++ b/apps/web/src/components/settings/AddProviderInstanceDialog.tsx
@@ -13,6 +13,7 @@ import {
type EnvironmentId,
type ProviderInstanceConfig,
type ProviderInstanceEnvironmentVariable,
+ isManagedDriverAllowed,
} from "@t3tools/contracts";
import {
@@ -22,6 +23,7 @@ import {
import { cn } from "../../lib/utils";
import { normalizeProviderAccentColor } from "../../providerInstances";
+import { managedInstanceLocks, useManagedPolicy } from "../../state/managedPolicy";
import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";
import { Button } from "../ui/button";
import { ChatGptConnectionButton } from "./ChatGptConnectionButton";
@@ -167,7 +169,20 @@ export function AddProviderInstanceDialog({
const [wizardStep, setWizardStep] = useState(0);
const [addingChatGptAccount, setAddingChatGptAccount] = useState(false);
- const [driver, setDriver] = useState<ProviderDriverKind>(DEFAULT_DRIVER_KIND);
+ // Drivers the administrator's policy leaves out are not offered at all.
+ const managedPolicy = useManagedPolicy(environmentId);
+ const featuredDriverOptions = FEATURED_DRIVER_OPTIONS.filter((option) =>
+ isManagedDriverAllowed(managedPolicy, option.driverKind),
+ );
+ const moreDriverOptions = MORE_DRIVER_OPTIONS.filter((option) =>
+ isManagedDriverAllowed(managedPolicy, option.driverKind),
+ );
+ const acpRegistryAllowed = isManagedDriverAllowed(managedPolicy, ACP_REGISTRY_DRIVER_KIND);
+ const [driver, setDriver] = useState<ProviderDriverKind>(
+ () =>
+ (featuredDriverOptions[0] ?? moreDriverOptions[0])?.driverKind ??
+ (acpRegistryAllowed ? ACP_REGISTRY_DRIVER_KIND : DEFAULT_DRIVER_KIND),
+ );
const [identityByDriver, setIdentityByDriver] = useState<Record<string, ProviderIdentityDraft>>(
{},
);
@@ -361,6 +376,9 @@ export function AddProviderInstanceDialog({
setHasAttemptedSubmit(false);
};
+ // A policy that owns this driver's launch settings also rules out ChatGPT's own runtime.
+ const driverLocks = managedInstanceLocks(managedPolicy, driver);
+
const handleSave = async () => {
if (!readEnvironmentScope(environmentId, AuthProvidersManageScope)) return;
if (isSaving || createdInstanceId) return;
@@ -467,7 +485,7 @@ export function AddProviderInstanceDialog({
Provider
</div>
<ProviderOptionGrid
- options={FEATURED_DRIVER_OPTIONS}
+ options={featuredDriverOptions}
value={driver}
disabled={isPreparingRegistryAgent}
onValueChange={selectDriver}
@@ -476,7 +494,7 @@ export function AddProviderInstanceDialog({
<MultipleAccountsNote environmentId={environmentId} driver={driver} />
</div>
- {wizardStep === 0 ? (
+ {wizardStep === 0 && (moreDriverOptions.length > 0 || acpRegistryAllowed) ? (
<Collapsible open={showMoreProviders} onOpenChange={setShowMoreProviders}>
<div className="flex pt-2">
<CollapsibleTrigger render={<Button variant="ghost-muted" size="xs" />}>
@@ -491,18 +509,20 @@ export function AddProviderInstanceDialog({
<CollapsiblePanel animate={false}>
<div className="space-y-4 pt-4">
<ProviderOptionGrid
- options={MORE_DRIVER_OPTIONS}
+ options={moreDriverOptions}
value={driver}
disabled={isPreparingRegistryAgent}
onValueChange={selectDriver}
aria-label="More providers"
/>
- <div className="flex items-center gap-3 text-xs text-muted-foreground">
- <div aria-hidden className="flex-1 border-t border-border/70" />
- <span>Or choose from ACP Registry</span>
- <div aria-hidden className="flex-1 border-t border-border/70" />
- </div>
- {isAcpRegistry && isManualAcpConfiguration ? (
+ {!acpRegistryAllowed ? null : (
+ <div className="flex items-center gap-3 text-xs text-muted-foreground">
+ <div aria-hidden className="flex-1 border-t border-border/70" />
+ <span>Or choose from ACP Registry</span>
+ <div aria-hidden className="flex-1 border-t border-border/70" />
+ </div>
+ )}
+ {!acpRegistryAllowed ? null : isAcpRegistry && isManualAcpConfiguration ? (
<div className="grid gap-4">
<div className="flex items-start justify-between gap-3">
<div>
@@ -684,6 +704,9 @@ export function AddProviderInstanceDialog({
idPrefix={`add-provider-${driver}`}
variant="settings"
onChange={setConfigDraft}
+ managed={
+ driverLocks && { keys: driverLocks.configKeys, reason: driverLocks.reason }
+ }
environmentId={environmentId}
/>
</SettingsGroup>
@@ -716,10 +739,12 @@ export function AddProviderInstanceDialog({
<Button variant="outline" size="sm" onClick={() => navigateToStep(1)}>
Configure manually
</Button>
- <ChatGptConnectionButton
- size="sm"
- onClick={() => setAddingChatGptAccount(true)}
- />
+ {driverLocks?.configKeys.has("setupMode") ? null : (
+ <ChatGptConnectionButton
+ size="sm"
+ onClick={() => setAddingChatGptAccount(true)}
+ />
+ )}
</>
) : wizardStep < (isAcpRegistry ? 1 : 2) ? (
<Button
diff --git a/apps/web/src/components/settings/AuthorizedClientsSettings.tsx b/apps/web/src/components/settings/AuthorizedClientsSettings.tsx
index b11e1835c4b..c63c163592c 100644
--- a/apps/web/src/components/settings/AuthorizedClientsSettings.tsx
+++ b/apps/web/src/components/settings/AuthorizedClientsSettings.tsx
@@ -8,6 +8,7 @@ import {
AuthFilesystemReadScope,
AuthStandardClientScopes,
AuthTerminalReadScope,
+ managedCapabilityDenial,
type AuthEnvironmentScope,
type AuthGrantScope,
type AuthPairingCredentialResult,
@@ -53,6 +54,8 @@ import {
} from "~/environments/primary";
import { readEnvironmentScope } from "~/state/session";
import { usePrimaryEnvironmentId } from "~/state/environments";
+import { usePrimaryManagedPolicy } from "~/state/managedPolicy";
+import { ManagedControl } from "../ManagedPolicy";
import { ConnectionStatusDot } from "../ConnectionStatusDot";
import { ITEM_ROW_CLASSNAME, ITEM_ROW_INNER_CLASSNAME } from "./itemRows";
import {
@@ -577,6 +580,7 @@ export const AuthorizedClientsHeaderAction = memo(function AuthorizedClientsHead
delegatableScopes,
}: AuthorizedClientsHeaderActionProps) {
const primaryEnvironmentId = usePrimaryEnvironmentId();
+ const pairingDenial = managedCapabilityDenial(usePrimaryManagedPolicy(), "remoteClients");
const [dialogOpen, setDialogOpen] = useState(false);
const [pairingLabel, setPairingLabel] = useState("");
const [pairingScopes, setPairingScopes] = useState<ReadonlyArray<AuthGrantScope>>([
@@ -634,8 +638,16 @@ export const AuthorizedClientsHeaderAction = memo(function AuthorizedClientsHead
>
{isRevokingOtherClients ? "Revoking…" : "Revoke others"}
</Button>
+ {pairingDenial !== undefined ? (
+ <ManagedControl reason={pairingDenial}>
+ <Button size="xs" variant="default" disabled>
+ <PlusIcon className="size-3" />
+ Create link
+ </Button>
+ </ManagedControl>
+ ) : null}
<Dialog
- open={dialogOpen}
+ open={dialogOpen && pairingDenial === undefined}
onOpenChange={(open) => {
setDialogOpen(open);
if (!open) {
@@ -646,14 +658,16 @@ export const AuthorizedClientsHeaderAction = memo(function AuthorizedClientsHead
}
}}
>
- <DialogTrigger
- render={
- <Button size="xs" variant="default">
- <PlusIcon className="size-3" />
- Create link
- </Button>
- }
- />
+ {pairingDenial === undefined ? (
+ <DialogTrigger
+ render={
+ <Button size="xs" variant="default">
+ <PlusIcon className="size-3" />
+ Create link
+ </Button>
+ }
+ />
+ ) : null}
<DialogPopup className="max-w-md">
<DialogHeader>
<DialogTitle>Create pairing link</DialogTitle>
@@ -856,6 +870,7 @@ export const AdvertisedEndpointListRow = memo(function AdvertisedEndpointListRow
const canDisableTailscaleServe =
isTailscaleHttpsEndpoint(endpoint) && endpoint.status === "available";
const shouldShowEndpointUrl = !needsTailscaleSetup;
+ const remoteDenial = managedCapabilityDenial(usePrimaryManagedPolicy(), "remoteClients");
return (
<div className={endpointRowClassName(isAvailable)}>
{isDefault ? (
@@ -891,14 +906,16 @@ export const AdvertisedEndpointListRow = memo(function AdvertisedEndpointListRow
</span>
) : null}
{needsTailscaleSetup ? (
- <Button
- size="xs"
- variant="outline"
- onClick={() => onSetupTailscaleServe(endpoint)}
- disabled={isUpdatingTailscaleServe}
- >
- {isUpdatingTailscaleServe ? "Restarting…" : "Setup"}
- </Button>
+ <ManagedControl reason={remoteDenial}>
+ <Button
+ size="xs"
+ variant="outline"
+ onClick={() => onSetupTailscaleServe(endpoint)}
+ disabled={isUpdatingTailscaleServe || remoteDenial !== undefined}
+ >
+ {isUpdatingTailscaleServe ? "Restarting…" : "Setup"}
+ </Button>
+ </ManagedControl>
) : null}
{canDisableTailscaleServe ? (
<Button
diff --git a/apps/web/src/components/settings/BrowserImportWizard.tsx b/apps/web/src/components/settings/BrowserImportWizard.tsx
index 2cbce23e94e..b12696ce89e 100644
--- a/apps/web/src/components/settings/BrowserImportWizard.tsx
+++ b/apps/web/src/components/settings/BrowserImportWizard.tsx
@@ -151,8 +151,11 @@ export function BrowserImportWizard({
<BlockedStep
source={source}
reason={step.reason}
+ message={step.message}
onClose={onClose}
- onRetry={isRetryableReason(step.reason) ? runImport : undefined}
+ onRetry={
+ step.message === undefined && isRetryableReason(step.reason) ? runImport : undefined
+ }
/>
) : (
<ConfigureStep
@@ -552,11 +555,13 @@ function DoneStep({
function BlockedStep({
source,
reason,
+ message,
onClose,
onRetry,
}: {
readonly source: BrowserImportSource;
readonly reason: keyof typeof BROWSER_IMPORT_FAILURE_COPY;
+ readonly message: string | undefined;
readonly onClose: () => void;
readonly onRetry: (() => void) | undefined;
}) {
@@ -564,7 +569,7 @@ function BlockedStep({
<>
<DialogHeader>
<DialogTitle>Couldn&rsquo;t import from {source.name}</DialogTitle>
- <DialogDescription>{BROWSER_IMPORT_FAILURE_COPY[reason]}</DialogDescription>
+ <DialogDescription>{message ?? BROWSER_IMPORT_FAILURE_COPY[reason]}</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button variant="outline" onClick={onClose}>
diff --git a/apps/web/src/components/settings/CodexSetupSection.tsx b/apps/web/src/components/settings/CodexSetupSection.tsx
index e7ef1c9a204..0dfd68dcdc3 100644
--- a/apps/web/src/components/settings/CodexSetupSection.tsx
+++ b/apps/web/src/components/settings/CodexSetupSection.tsx
@@ -1,4 +1,4 @@
-import { AuthProvidersManageScope } from "@t3tools/contracts";
+import { AuthProvidersManageScope, ProviderDriverKind } from "@t3tools/contracts";
import { readPreparedConnection, useEnvironmentScope } from "../../state/session";
import {
isAtomCommandInterrupted,
@@ -27,6 +27,8 @@ import {
} from "react";
import { ensureLocalApi } from "../../localApi";
+import { managedInstanceLocks, useManagedPolicy } from "../../state/managedPolicy";
+import { ManagedControl } from "../ManagedPolicy";
import { useEnvironmentHttpBaseUrl } from "../../state/environments";
import { environmentPresentations } from "../../state/presentation";
import { primaryEnvironmentIdAtom } from "../../state/primaryEnvironment";
@@ -102,6 +104,12 @@ interface CodexSetupSectionProps {
export function CodexSetupSection(props: CodexSetupSectionProps) {
const [requested, setRequested] = useState(false);
+ // A policy that owns Codex's launch settings also rules out ChatGPT's own runtime.
+ const codexLocks = managedInstanceLocks(
+ useManagedPolicy(props.environmentId),
+ ProviderDriverKind.make("codex"),
+ );
+ const chatGptDenial = codexLocks?.configKeys.has("setupMode") ? codexLocks.reason : undefined;
const existingState = getOnboardingProviderState(props.provider);
const existingReady = props.enabled && existingState === "ready";
const existingAuthenticated = props.provider?.auth.status === "authenticated";
@@ -147,16 +155,18 @@ export function CodexSetupSection(props: CodexSetupSectionProps) {
) : existingAuthenticated ? (
<span className="text-xs text-muted-foreground">{existingSummary.headline}</span>
) : (
- <ChatGptConnectionButton
- size="sm"
- disabled={props.readOnly}
- onClick={() => {
- setRequested(true);
- props.onModeChange("managed");
- }}
- >
- Continue with ChatGPT
- </ChatGptConnectionButton>
+ <ManagedControl reason={chatGptDenial}>
+ <ChatGptConnectionButton
+ size="sm"
+ disabled={props.readOnly}
+ onClick={() => {
+ setRequested(true);
+ props.onModeChange("managed");
+ }}
+ >
+ Continue with ChatGPT
+ </ChatGptConnectionButton>
+ </ManagedControl>
)
}
secondaryControl={
diff --git a/apps/web/src/components/settings/ConnectionsSettings.tsx b/apps/web/src/components/settings/ConnectionsSettings.tsx
index a0ebd148453..8df75864623 100644
--- a/apps/web/src/components/settings/ConnectionsSettings.tsx
+++ b/apps/web/src/components/settings/ConnectionsSettings.tsx
@@ -15,6 +15,7 @@ import {
type DesktopServerExposureState,
type DesktopWslState,
type EnvironmentId,
+ managedCapabilityDenial,
resolveEnvironmentMachineKind,
} from "@t3tools/contracts";
import {
@@ -33,6 +34,7 @@ import {
resolveTailscaleServeBaseUrl,
} from "./ConnectionsSettings.logic";
import { SettingsPageContainer, SettingsRow, SettingsSection } from "./settingsLayout";
+import { ManagedByOrganization } from "../ManagedPolicy";
import { LocalEnvironmentSetting } from "./LocalEnvironmentSetting";
import { searchableSetting } from "./settingsSearch";
import { EnvironmentIconMenu } from "./EnvironmentIconPicker";
@@ -268,6 +270,9 @@ export function ConnectionsSettings({ view }: { readonly view: "environments" |
DesktopServerExposureState["mode"] | null
>(null);
const primaryServerConfig = primaryEnvironment?.serverConfig ?? null;
+ const primaryManagedPolicy = primaryServerConfig?.managedPolicy;
+ // Turning remote access off stays possible; only the way in is managed.
+ const remoteClientsDenial = managedCapabilityDenial(primaryManagedPolicy, "remoteClients");
const primaryVersionMismatch = resolveServerConfigVersionMismatch(primaryServerConfig);
const primaryServerUpdateState = useAtomValue(
serverEnvironment.updateStateAtom(primaryEnvironmentId),
@@ -920,6 +925,7 @@ export function ConnectionsSettings({ view }: { readonly view: "environments" |
/>
) : null
}
+ managed={tailscaleHttpsEndpoint?.status === "available" ? undefined : remoteClientsDenial}
/>
);
const renderAuthorizedClients = () => (
@@ -975,6 +981,7 @@ export function ConnectionsSettings({ view }: { readonly view: "environments" |
) : null
}
control={renderNetworkAccessToggle()}
+ managed={isLocalBackendNetworkAccessible ? undefined : remoteClientsDenial}
/>
);
const renderDisabledNetworkAccessRow = () => (
@@ -1059,6 +1066,11 @@ export function ConnectionsSettings({ view }: { readonly view: "environments" |
) : null
}
>
+ {primaryManagedPolicy ? (
+ <div className="px-3 py-2 sm:px-4">
+ <ManagedByOrganization policy={primaryManagedPolicy} />
+ </div>
+ ) : null}
{canManageLocalBackend ? (
<SettingsRow
title="Version"
diff --git a/apps/web/src/components/settings/IntegrationsSettings.logic.test.ts b/apps/web/src/components/settings/IntegrationsSettings.logic.test.ts
index d25089f723b..0b74a9493ad 100644
--- a/apps/web/src/components/settings/IntegrationsSettings.logic.test.ts
+++ b/apps/web/src/components/settings/IntegrationsSettings.logic.test.ts
@@ -1,7 +1,11 @@
import { describe, expect, it, vi } from "vite-plus/test";
-import type { EnvironmentId } from "@t3tools/contracts";
+import { type EnvironmentId, managedPolicyDeniedMessage } from "@t3tools/contracts";
-import { clearBrowserProfileData, importFailureReason } from "./IntegrationsSettings";
+import {
+ clearBrowserProfileData,
+ importFailureReason,
+ importPolicyRefusal,
+} from "./IntegrationsSettings";
const environmentId = "environment-a" as EnvironmentId;
const secondEnvironmentId = "environment-b" as EnvironmentId;
@@ -62,3 +66,21 @@ describe("importFailureReason", () => {
expect(importFailureReason(failure("profileLimitReached"))).toBe("profileLimitReached");
});
});
+
+describe("importPolicyRefusal", () => {
+ it("recovers a managed policy's refusal from the IPC-wrapped message", () => {
+ const denied = managedPolicyDeniedMessage("Example Corp", "importing browser cookies");
+ expect(
+ importPolicyRefusal({
+ message: `Error invoking remote method 'desktop:preview-import-cookies': BrowserImportPolicyError: ${denied}`,
+ }),
+ ).toBe(denied);
+ const unreadable =
+ "The managed policy at C:\\Program Files\\T3Code\\policy.json could not be read, so importing browser cookies is not allowed.";
+ expect(importPolicyRefusal({ message: `Error: ${unreadable}` })).toBe(unreadable);
+ });
+
+ it("leaves other failures to their reason token", () => {
+ expect(importPolicyRefusal(failure("readFailed"))).toBeUndefined();
+ });
+});
diff --git a/apps/web/src/components/settings/IntegrationsSettings.tsx b/apps/web/src/components/settings/IntegrationsSettings.tsx
index 5239f57bfdc..b64e35db951 100644
--- a/apps/web/src/components/settings/IntegrationsSettings.tsx
+++ b/apps/web/src/components/settings/IntegrationsSettings.tsx
@@ -34,7 +34,9 @@ import {
type BrowserImportSource,
type PreviewAppearancePreference,
type PreviewViewportSetting,
+ managedCapabilityDenial,
} from "@t3tools/contracts";
+import { usePrimaryManagedPolicy } from "~/state/managedPolicy";
import { isValidSearchUrlTemplate } from "@t3tools/shared/preview";
import { PREVIEW_VIEWPORT_PRESETS } from "@t3tools/shared/previewViewport";
import { MoreVertical, Plus as PlusIcon } from "lucide-react";
@@ -187,6 +189,18 @@ export const importFailureReason = (cause: unknown): BrowserImportFailureReason
);
};
+/**
+ * The desktop's refusal when the machine's managed policy forbids cookie import. IPC wraps the
+ * message in its own prefixes, so the sentence is matched on the contract's wording.
+ */
+export const importPolicyRefusal = (cause: unknown): string | undefined => {
+ const message = String((cause as { message?: unknown } | undefined)?.message ?? "");
+ return (
+ /The managed policy at .* importing browser cookies is not allowed\./u.exec(message)?.[0] ??
+ /(?:^|: )([^:]*'s policy does not allow importing browser cookies\.)/u.exec(message)?.[1]
+ );
+};
+
async function importBrowserCookiesIntoTarget(
bridge: NonNullable<typeof previewBridge>,
source: BrowserImportSource,
@@ -261,7 +275,10 @@ async function importBrowserCookiesIntoTarget(
targetName,
};
} catch (cause) {
- return { kind: "blocked", reason: importFailureReason(cause) };
+ const policyRefusal = importPolicyRefusal(cause);
+ return policyRefusal !== undefined
+ ? { kind: "blocked", reason: "readFailed", message: policyRefusal }
+ : { kind: "blocked", reason: importFailureReason(cause) };
}
}
@@ -1091,6 +1108,11 @@ function BrowserProfilesSetting({ disabled }: { readonly disabled: boolean }) {
const updateSettings = useUpdatePrimarySettings();
const { environments, isReady: environmentsReady } = useEnvironments();
const primaryEnvironment = usePrimaryEnvironment();
+ // Cookie import runs on this desktop, whose policy the primary environment reports.
+ const cookieImportDenial = managedCapabilityDenial(
+ usePrimaryManagedPolicy(),
+ "browserCookieImport",
+ );
const [sources, setSources] = useState<ReadonlyArray<BrowserImportSource> | null>(null);
const [importSession, setImportSession] = useState<{
readonly source: BrowserImportSource;
@@ -1298,7 +1320,9 @@ function BrowserProfilesSetting({ disabled }: { readonly disabled: boolean }) {
<MenuSeparator />
<MenuGroup>
<MenuGroupLabel>Import from</MenuGroupLabel>
- {sources === null ? (
+ {cookieImportDenial !== undefined ? (
+ <MenuItem disabled>{cookieImportDenial}</MenuItem>
+ ) : sources === null ? (
<MenuItem disabled>Looking for browsers…</MenuItem>
) : importableSources.length === 0 ? (
<MenuItem disabled>No supported browsers found</MenuItem>
diff --git a/apps/web/src/components/settings/LabsSettingsPanel.tsx b/apps/web/src/components/settings/LabsSettingsPanel.tsx
index ce3f68eac49..36c289b8335 100644
--- a/apps/web/src/components/settings/LabsSettingsPanel.tsx
+++ b/apps/web/src/components/settings/LabsSettingsPanel.tsx
@@ -1,5 +1,6 @@
import { useAuth } from "@clerk/react";
import { Link } from "@tanstack/react-router";
+import { managedCapabilityDenial } from "@t3tools/contracts";
import { hasCloudPublicConfig } from "~/cloud/publicConfig";
import { useT3ConnectAuthPrompt } from "../clerk/useT3ConnectAuthPrompt";
@@ -10,6 +11,8 @@ import { SettingsPageContainer, SettingsRow, SettingsSection } from "./settingsL
import { searchableSetting } from "./settingsSearch";
import { LegacyFeaturesSection } from "./SettingsPanels";
import { useScopedSettings, useUpdateScopedSettings } from "./useScopedSettings";
+import { useOptionalSettingsScope } from "./SettingsScopeContext";
+import { firstManagedDenial, usePrimaryManagedPolicy } from "~/state/managedPolicy";
/** Features still settling in, and legacy behavior kept for people who rely on it. */
export function LabsSettingsPanel() {
@@ -91,11 +94,22 @@ function GuestLinksRowWithSignIn() {
function GuestLinksRow() {
const settings = useScopedSettings();
const updateSettings = useUpdateScopedSettings();
+ const scope = useOptionalSettingsScope();
+ const primaryPolicy = usePrimaryManagedPolicy();
+ // Guests arrive through T3 Connect, so a policy that turns Connect off turns this off too.
+ const connectDenial = firstManagedDenial(
+ scope
+ ? scope.connectedEnvironments.map((environment) => environment.serverConfig?.managedPolicy)
+ : [primaryPolicy],
+ (policy) => managedCapabilityDenial(policy, "connect"),
+ );
return (
<SettingsRow
serverScoped
{...searchableSetting("guest-links")}
settingKeys={["guestSharingEnabled"]}
+ // Turning guest links off still works without T3 Connect.
+ managed={settings.guestSharingEnabled ? undefined : connectDenial}
description={
<>
Share a thread with a guest who watches it live in their browser and sends messages you
diff --git a/apps/web/src/components/settings/ProjectDefaultsSettings.tsx b/apps/web/src/components/settings/ProjectDefaultsSettings.tsx
index 3d6ad58d1d9..d81b7ad1120 100644
--- a/apps/web/src/components/settings/ProjectDefaultsSettings.tsx
+++ b/apps/web/src/components/settings/ProjectDefaultsSettings.tsx
@@ -2,6 +2,7 @@ import {
DEFAULT_SERVER_SETTINGS,
type ModelSelection,
type WorktreeSubmodules,
+ managedRuntimeModeDenial,
} from "@t3tools/contracts";
import { createModelSelection } from "@t3tools/shared/model";
import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
@@ -19,6 +20,7 @@ import {
resolveProjectDefaultProviderModelSelection,
} from "../../providerInstances";
import { useEnvironmentProviders, useEnvironments } from "../../state/environments";
+import { firstManagedDenial } from "../../state/managedPolicy";
import { EMPTY_SERVER_PROVIDERS } from "../../state/server";
import { resolveEnvModeLabel, WORKTREE_SUBMODULES_LABELS } from "../BranchToolbar.logic";
import { ProviderModelPicker } from "../chat/ProviderModelPicker";
@@ -380,15 +382,26 @@ export function ProjectDefaultsSettings({ category }: { category: ProjectSetting
{runtimeModeOptions.map((mode) => {
const option = runtimeModeConfig[mode];
const Icon = option.icon;
+ const managedReason = firstManagedDenial(
+ connectedEnvironments.map(
+ (environment) => environment.serverConfig?.managedPolicy,
+ ),
+ (policy) => managedRuntimeModeDenial(policy, mode),
+ );
return (
- <SelectItem key={mode} value={mode} className="min-w-64">
+ <SelectItem
+ key={mode}
+ value={mode}
+ disabled={managedReason !== undefined}
+ className="min-w-64"
+ >
<div className="grid gap-0.5">
<span className="inline-flex items-center gap-1.5 font-medium">
<Icon className="size-3.5 shrink-0 text-muted-foreground" />
{option.label}
</span>
<span className="text-xs leading-4 text-muted-foreground">
- {option.description}
+ {managedReason ?? option.description}
</span>
</div>
</SelectItem>
diff --git a/apps/web/src/components/settings/ProviderInstanceCard.tsx b/apps/web/src/components/settings/ProviderInstanceCard.tsx
index 21fe0fad2d0..ca9db4b968d 100644
--- a/apps/web/src/components/settings/ProviderInstanceCard.tsx
+++ b/apps/web/src/components/settings/ProviderInstanceCard.tsx
@@ -47,6 +47,9 @@ import { DraftInput } from "../ui/draft-input";
import { SecretSourceInput, type SecretSource } from "./SecretSourceInput";
import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
import { Switch } from "../ui/switch";
+import { ManagedControl, ManagedNotice } from "../ManagedPolicy";
+import { managedInstanceLocks, useManagedPolicy } from "../../state/managedPolicy";
+import { disallowedProviderMessage, isManagedDriverAllowed } from "@t3tools/contracts";
import { stackedThreadToast, toastManager } from "../ui/toast";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import type {
@@ -277,6 +280,7 @@ function ProviderEnvironmentFieldRow(props: {
secret: SecretReference | undefined,
) => void;
readonly onRemove: (field: ProviderEnvironmentField) => void;
+ readonly managedReason?: string | undefined;
readonly secretSources: ReadonlyArray<SecretSource>;
}) {
const inputId = `${props.idPrefix}-environment-${props.field.name}`;
@@ -286,6 +290,7 @@ function ProviderEnvironmentFieldRow(props: {
<SettingsRow
title={<label htmlFor={inputId}>{props.field.label}</label>}
description={props.field.description}
+ managed={props.managedReason}
control={
<div className="flex w-full min-w-0 items-center gap-2 @min-[32rem]/settings-row:w-56">
{props.field.sensitive === false ? (
@@ -334,6 +339,8 @@ function ProviderEnvironmentFieldRow(props: {
export function ProviderEnvironmentSection(props: {
readonly environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>;
readonly onChange: (environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>) => void;
+ /** Variables an administrator's policy pins: listed by name, never editable or removable. */
+ readonly managed?: { readonly names: ReadonlySet<string>; readonly reason: string } | undefined;
readonly secretSources?: ReadonlyArray<SecretSource>;
}) {
const [storedDraft, setDraft] = useState(() =>
@@ -373,6 +380,8 @@ export function ProviderEnvironmentSection(props: {
};
const updateVariable = (id: string, patch: Partial<Omit<EnvironmentDraftRow, "id">>) => {
+ // A row named like a pinned variable renders as the policy's, with no way to edit or remove it.
+ if (patch.name !== undefined && props.managed?.names.has(patch.name)) return;
const nextRows = rows.map((row) =>
row.id === id
? {
@@ -427,6 +436,16 @@ export function ProviderEnvironmentSection(props: {
{rows.length > 0 ? (
<div className="mt-3 min-w-0 space-y-2 pb-2">
{rows.map((variable, index) => {
+ if (props.managed?.names.has(variable.name)) {
+ return (
+ <div key={variable.id} className="flex min-w-0 flex-wrap items-center gap-1.5">
+ <code className="min-w-0 truncate text-xs sm:w-44 sm:shrink-0">
+ {variable.name}
+ </code>
+ <span className="text-xs text-muted-foreground">{props.managed.reason}</span>
+ </div>
+ );
+ }
const nameInput = (
<DraftInput
size="sm"
@@ -746,6 +765,14 @@ export function ProviderInstanceCard({
const displayName =
instance.displayName?.trim() || driverOption?.label || String(instance.driver);
const accentColor = normalizeProviderAccentColor(instance.accentColor);
+ const managedPolicy = useManagedPolicy(environmentId);
+ const instanceLocks = managedInstanceLocks(managedPolicy, instance.driver);
+ const managedDriverReason = isManagedDriverAllowed(managedPolicy, instance.driver)
+ ? undefined
+ : disallowedProviderMessage(
+ managedPolicy?.organization,
+ driverOption?.label ?? String(instance.driver),
+ );
const { copyToClipboard } = useCopyToClipboard<{ providerName: string }>({
onCopy: ({ providerName }) => {
toastManager.add({
@@ -1109,12 +1136,15 @@ export function ProviderInstanceCard({
/>
</span>
) : null}
- <Switch
- checked={enabled}
- disabled={readOnly || (projectOverride !== undefined && !canWriteSettings)}
- onCheckedChange={(checked) => updateEnabled(Boolean(checked))}
- aria-label={`Enable ${displayName}`}
- />
+ {/* The policy refuses switching it on; switching it off stays the user's call. */}
+ <ManagedControl reason={enabled ? undefined : managedDriverReason}>
+ <Switch
+ checked={enabled}
+ disabled={readOnly || (projectOverride !== undefined && !canWriteSettings)}
+ onCheckedChange={(checked) => updateEnabled(Boolean(checked))}
+ aria-label={`Enable ${displayName}`}
+ />
+ </ManagedControl>
</span>
</div>
);
@@ -1196,6 +1226,7 @@ export function ProviderInstanceCard({
idPrefix={`provider-instance-${instanceId}`}
variant="settings"
onChange={updateConfig}
+ managed={instanceLocks && { keys: instanceLocks.configKeys, reason: instanceLocks.reason }}
environmentId={environmentId}
/>
) : (
@@ -1263,6 +1294,12 @@ export function ProviderInstanceCard({
onCommit={updateEnvironmentField}
onSecretChange={updateEnvironmentFieldSecret}
onRemove={removeEnvironmentField}
+ managedReason={
+ instanceLocks?.wholeEnvironment ||
+ instanceLocks?.environmentNames.has(field.name)
+ ? instanceLocks.reason
+ : undefined
+ }
secretSources={secretSources}
/>
))}
@@ -1299,15 +1336,26 @@ export function ProviderInstanceCard({
<SettingsSection
title="Environment"
- inert={readOnly}
- aria-disabled={readOnly || undefined}
+ inert={readOnly || instanceLocks?.wholeEnvironment}
+ aria-disabled={readOnly || instanceLocks?.wholeEnvironment || undefined}
className={readOnly ? "opacity-50 select-none" : undefined}
>
- <ProviderEnvironmentSection
- environment={genericEnvironment}
- onChange={updateGenericEnvironment}
- secretSources={secretSources}
- />
+ {instanceLocks?.wholeEnvironment ? (
+ <ManagedNotice>{instanceLocks.reason}</ManagedNotice>
+ ) : null}
+ <div className={instanceLocks?.wholeEnvironment ? "opacity-50" : undefined}>
+ <ProviderEnvironmentSection
+ environment={genericEnvironment}
+ onChange={updateGenericEnvironment}
+ secretSources={secretSources}
+ managed={
+ instanceLocks && {
+ names: instanceLocks.environmentNames,
+ reason: instanceLocks.reason,
+ }
+ }
+ />
+ </div>
</SettingsSection>
{environmentId !== undefined && liveProvider?.driver === "acpRegistry" ? (
<AcpSessionManagementSection
diff --git a/apps/web/src/components/settings/ProviderSettingsForm.tsx b/apps/web/src/components/settings/ProviderSettingsForm.tsx
index fbb1ac1503e..646dfd80edc 100644
--- a/apps/web/src/components/settings/ProviderSettingsForm.tsx
+++ b/apps/web/src/components/settings/ProviderSettingsForm.tsx
@@ -206,7 +206,10 @@ function configuredCommandArgs(value: ProviderSettingsFormProps["value"]) {
function ProviderCommandArguments({
value,
onChange,
-}: Pick<ProviderSettingsFormProps, "value" | "onChange">) {
+ managedReason,
+}: Pick<ProviderSettingsFormProps, "value" | "onChange"> & {
+ readonly managedReason: string | undefined;
+}) {
const args = configuredCommandArgs(value);
const [storedDraft, setDraft] = useState(() => seedRowsDraft(args, toCommandArgumentRows));
const draft = reconcileRowsDraft(storedDraft, args, commandArgumentsEqual, toCommandArgumentRows);
@@ -225,6 +228,7 @@ function ProviderCommandArguments({
<SettingsRow
title="Arguments"
description="One literal argument per row, in launch order."
+ managed={managedReason}
control={
<Button
type="button"
@@ -239,35 +243,41 @@ function ProviderCommandArguments({
>
{rows.length > 0 ? (
<div className="mt-3 min-w-0 space-y-2 pb-2">
- {rows.map((argument, index) => (
- <div key={argument.id} className="flex min-w-0 items-center gap-1.5">
- <DraftInput
- size="sm"
- font="mono"
- value={argument.value}
- onCommit={(next) =>
- updateArguments(
- rows.map((current) =>
- current.id === argument.id ? { ...current, value: next } : current,
- ),
- )
- }
- aria-label={`Argument ${index + 1}`}
- spellCheck={false}
- />
- <Button
- type="button"
- size="icon-micro"
- variant="ghost-destructive"
- onClick={() =>
- updateArguments(rows.filter((current) => current.id !== argument.id))
- }
- aria-label={`Remove argument ${index + 1}`}
- >
- <XIcon />
- </Button>
- </div>
- ))}
+ {rows.map((argument, index) =>
+ managedReason !== undefined ? (
+ <code key={argument.id} className="block min-w-0 truncate text-xs">
+ {argument.value}
+ </code>
+ ) : (
+ <div key={argument.id} className="flex min-w-0 items-center gap-1.5">
+ <DraftInput
+ size="sm"
+ font="mono"
+ value={argument.value}
+ onCommit={(next) =>
+ updateArguments(
+ rows.map((current) =>
+ current.id === argument.id ? { ...current, value: next } : current,
+ ),
+ )
+ }
+ aria-label={`Argument ${index + 1}`}
+ spellCheck={false}
+ />
+ <Button
+ type="button"
+ size="icon-micro"
+ variant="ghost-destructive"
+ onClick={() =>
+ updateArguments(rows.filter((current) => current.id !== argument.id))
+ }
+ aria-label={`Remove argument ${index + 1}`}
+ >
+ <XIcon />
+ </Button>
+ </div>
+ ),
+ )}
</div>
) : null}
</SettingsRow>
@@ -324,6 +334,8 @@ interface ProviderSettingsFormProps {
readonly idPrefix: string;
readonly variant: "card" | "dialog" | "settings";
readonly onChange: (nextConfig: Record<string, unknown> | undefined) => void;
+ /** Config keys an administrator's policy pins, shown inert with the reason. */
+ readonly managed?: { readonly keys: ReadonlySet<string>; readonly reason: string } | undefined;
/** Where the secret providers offered for `SettingsSecretValue` fields are configured. */
readonly environmentId?: EnvironmentId | undefined;
}
@@ -438,6 +450,7 @@ interface ProviderSettingsFieldRowProps {
readonly idPrefix: string;
readonly variant: ProviderSettingsFormProps["variant"];
readonly onChange: ProviderSettingsFormProps["onChange"];
+ readonly managedReason?: string | undefined;
readonly environmentId: EnvironmentId | undefined;
}
@@ -447,6 +460,7 @@ function ProviderSettingsFieldRow({
idPrefix,
variant,
onChange,
+ managedReason,
environmentId,
}: ProviderSettingsFieldRowProps) {
const inputId = `${idPrefix}-${field.key}`;
@@ -552,6 +566,7 @@ function ProviderSettingsFieldRow({
field.description ? <span id={descriptionId}>{field.description}</span> : undefined
}
control={control}
+ managed={managedReason}
/>
);
}
@@ -660,6 +675,7 @@ export function ProviderSettingsForm({
idPrefix,
variant,
onChange,
+ managed,
environmentId,
}: ProviderSettingsFormProps) {
const fields = deriveProviderSettingsFields(definition, value);
@@ -681,10 +697,17 @@ export function ProviderSettingsForm({
idPrefix={idPrefix}
variant={variant}
onChange={onChange}
+ managedReason={managed?.keys.has(field.key) ? managed.reason : undefined}
environmentId={environmentId}
/>
))}
- {isLocalAcp ? <ProviderCommandArguments value={value} onChange={onChange} /> : null}
+ {isLocalAcp ? (
+ <ProviderCommandArguments
+ value={value}
+ onChange={onChange}
+ managedReason={managed?.keys.has("commandArgs") ? managed.reason : undefined}
+ />
+ ) : null}
</>
);
}
diff --git a/apps/web/src/components/settings/ProviderSettingsPanel.tsx b/apps/web/src/components/settings/ProviderSettingsPanel.tsx
index b5fb648ff97..e0cdea54321 100644
--- a/apps/web/src/components/settings/ProviderSettingsPanel.tsx
+++ b/apps/web/src/components/settings/ProviderSettingsPanel.tsx
@@ -96,6 +96,7 @@ import { Toggle, ToggleGroup } from "../ui/toggle-group";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import { stackedThreadToast, toastManager } from "../ui/toast";
import { AddProviderInstanceDialog } from "./AddProviderInstanceDialog";
+import { useManagedPolicy } from "~/state/managedPolicy";
import { ExpandableText } from "./ExpandableText";
import { ProviderInstanceCard } from "./ProviderInstanceCard";
import { useSecretSources } from "./SecretSourceInput";
@@ -548,6 +549,10 @@ export function EnvironmentProviderSettings({
readonly readOnly?: boolean;
}) {
const settings = useEnvironmentSettings(environmentId);
+ const managedPolicy = useManagedPolicy(environmentId);
+ // A policy that allows no provider leaves nothing to add.
+ const canAddProvider =
+ !readOnly && managedPolicy?.limits?.providers?.allowedDrivers?.length !== 0;
const canWriteSettings = useEnvironmentScope(environmentId, AuthSettingsWriteScope);
const canRefreshProviders = useEnvironmentScope(environmentId, AuthOrchestrationReadScope);
const updateSettings = useUpdateEnvironmentSettings(environmentId);
@@ -962,7 +967,7 @@ export function EnvironmentProviderSettings({
{...searchableSetting("providers")}
variant="plain"
titleAction={
- !readOnly ? (
+ canAddProvider ? (
<Tooltip>
<TooltipTrigger
render={
@@ -1037,7 +1042,7 @@ export function EnvironmentProviderSettings({
>
<div className="divide-y divide-border/50">
{rows.map((row) => renderProviderInstance(row, "list"))}
- {!readOnly ? (
+ {canAddProvider ? (
<button
type="button"
className="flex w-full cursor-pointer items-center gap-3 px-3 py-3 text-left text-sm text-muted-foreground transition-colors outline-none hover:bg-muted/25 hover:text-foreground focus-visible:bg-muted/25 focus-visible:text-foreground sm:px-4"
diff --git a/apps/web/src/components/settings/SavedEnvironmentRows.tsx b/apps/web/src/components/settings/SavedEnvironmentRows.tsx
index fee5b9857a6..ec888267c78 100644
--- a/apps/web/src/components/settings/SavedEnvironmentRows.tsx
+++ b/apps/web/src/components/settings/SavedEnvironmentRows.tsx
@@ -12,6 +12,7 @@ import {
type EnvironmentId,
connectReachabilityHelpUrl,
formatConnectReachable,
+ managedCapabilityDenial,
resolveEnvironmentMachineKind,
} from "@t3tools/contracts";
import {
@@ -60,6 +61,7 @@ import {
usePrimaryEnvironmentId,
} from "~/state/environments";
import { APP_VERSION } from "~/branding";
+import { usePrimaryManagedPolicy } from "~/state/managedPolicy";
import { useAtomCommand } from "../../state/use-atom-command";
import { serverEnvironment } from "~/state/server";
import {
@@ -531,6 +533,8 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: b
reconcileCloudState,
} = useCloudLinkController();
const { openAuthPrompt } = useT3ConnectAuthPrompt();
+ // The server unlinks and refuses relay changes under such a policy; unlinking stays possible.
+ const connectDenial = managedCapabilityDenial(usePrimaryManagedPolicy(), "connect");
const [isUpdating, setIsUpdating] = useState(false);
const [isUpdatingPreference, setIsUpdatingPreference] = useState(false);
@@ -652,21 +656,24 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: b
<SettingsRow
title={searchableSetting("t3-connect").title}
description={
- signedOut
- ? "Sign in to make this environment available to your other devices through T3 Connect."
- : linkRevoked
- ? "This environment was removed from T3 Connect. Turn it on to link it again."
- : managedTunnelActive
- ? reachability?.status === "unreachable"
- ? "T3 Connect is on, but other devices cannot reach this environment."
- : reachability?.status === "reachable"
- ? "This environment is available to your other devices through T3 Connect."
- : "T3 Connect is on. Reachability has not been checked yet."
- : managedTunnelOutOfSync
- ? "T3 Connect is out of sync. This environment is linked only to publish agent activity, so other devices cannot connect. Turn T3 Connect on to repair it."
- : "Make this environment available to your other devices through T3 Connect."
+ connectDenial !== undefined && !managedTunnelActive
+ ? connectDenial
+ : signedOut
+ ? "Sign in to make this environment available to your other devices through T3 Connect."
+ : linkRevoked
+ ? "This environment was removed from T3 Connect. Turn it on to link it again."
+ : managedTunnelActive
+ ? reachability?.status === "unreachable"
+ ? "T3 Connect is on, but other devices cannot reach this environment."
+ : reachability?.status === "reachable"
+ ? "This environment is available to your other devices through T3 Connect."
+ : "T3 Connect is on. Reachability has not been checked yet."
+ : managedTunnelOutOfSync
+ ? "T3 Connect is out of sync. This environment is linked only to publish agent activity, so other devices cannot connect. Turn T3 Connect on to repair it."
+ : "Make this environment available to your other devices through T3 Connect."
}
status={operationError ?? primaryCloudLinkState.error ?? reachabilityStatus}
+ managed={managedTunnelActive ? undefined : connectDenial}
control={
signedOut ? (
signInButton
@@ -680,7 +687,9 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: b
)
}
>
- {signedOut ? null : <T3ConnectTunnelUsage tunnelLimit={tunnelLimit} />}
+ {signedOut || connectDenial !== undefined ? null : (
+ <T3ConnectTunnelUsage tunnelLimit={tunnelLimit} />
+ )}
</SettingsRow>
) : linkRevoked ? (
<SettingsRow
@@ -696,6 +705,7 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: b
? "Sign in to send activity to mobile notifications and Live Activities."
: "Send activity to mobile notifications and Live Activities without T3 Connect."
}
+ managed={connectDenial}
control={
signedOut ? (
signInButton
@@ -715,6 +725,7 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: b
<SettingsRow
title={searchableSetting("hold-webhooks-while-offline").title}
description="Keep webhook requests for up to 24 hours while this environment is offline, then deliver them. Off: T3 Connect only forwards requests and stores nothing."
+ managed={connectDenial}
control={
<CloudLinkSwitch
ariaLabel="Hold webhook requests while this environment is offline"
diff --git a/apps/web/src/components/settings/ScheduledTasksSettings.tsx b/apps/web/src/components/settings/ScheduledTasksSettings.tsx
index 9489e4162cb..3715a092be3 100644
--- a/apps/web/src/components/settings/ScheduledTasksSettings.tsx
+++ b/apps/web/src/components/settings/ScheduledTasksSettings.tsx
@@ -69,7 +69,13 @@ import { useAtomCommand } from "../../state/use-atom-command";
import { WorktreeBaseBranchPicker } from "../WorktreeBaseBranchPicker";
import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon";
import { ConnectionStatusDot, connectionPhaseDotClassName } from "../ConnectionStatusDot";
-import { AuthOrchestrationOperateScope } from "@t3tools/contracts";
+import {
+ AuthOrchestrationOperateScope,
+ clampManagedRuntimeMode,
+ managedCapabilityDenial,
+} from "@t3tools/contracts";
+import { useManagedPolicy } from "~/state/managedPolicy";
+import { ManagedNotice } from "../ManagedPolicy";
import { readEnvironmentScope } from "~/state/session";
import { useSettingsScope } from "./SettingsScopeContext";
import { EnvironmentRow, useEnvironmentTransportLabel } from "./EnvironmentRow";
@@ -761,7 +767,9 @@ function ScheduledTaskRow({
<div className="flex flex-wrap items-center gap-2">
<span>
{scheduleLabel(task.schedule)} ·{" "}
- {!task.enabled ? (
+ {task.blockedByPolicy !== undefined ? (
+ task.blockedByPolicy
+ ) : !task.enabled ? (
"Paused"
) : isWebhook ? (
"Listening"
@@ -1204,6 +1212,7 @@ function ScheduledTaskEditorForm({
const upsertTask = useAtomCommand(serverEnvironment.upsertScheduledTask, {
label: "scheduled task upsert",
});
+ const webhookDenial = managedCapabilityDenial(useManagedPolicy(environmentId), "webhookTasks");
const [draft, setDraft] = useState<DraftState>(() =>
task
? taskToDraft(task)
@@ -1348,7 +1357,10 @@ function ScheduledTaskEditorForm({
threadId: draft.threadId ? (draft.threadId as ThreadId) : null,
workspaceStrategy,
modelSelection,
- runtimeMode: draft.runtimeMode,
+ // Tasks have no mode picker; a mode above the administrator's ceiling would fail every run.
+ runtimeMode:
+ clampManagedRuntimeMode(environment?.serverConfig?.managedPolicy, draft.runtimeMode) ??
+ draft.runtimeMode,
interactionMode: draft.interactionMode,
creationSource: "web",
};
@@ -1635,11 +1647,26 @@ function ScheduledTaskEditorForm({
<Toggle value="once">Once</Toggle>
) : null}
<Toggle value="interval">Every interval</Toggle>
- <Toggle value="webhook">On webhook</Toggle>
+ <Toggle
+ value="webhook"
+ disabled={webhookDenial !== undefined && draft.scheduleMode !== "webhook"}
+ >
+ On webhook
+ </Toggle>
</ToggleGroup>
</div>
- {draft.scheduleMode === "webhook" ? (
+ {webhookDenial !== undefined ? (
+ <ManagedNotice>
+ {draft.scheduleMode === "webhook"
+ ? `${webhookDenial} Switch this task to a time or an interval, or turn it off, to save it.`
+ : webhookDenial}
+ </ManagedNotice>
+ ) : null}
+ {/* A disabled task still saves, so keep its fields reachable for fixing. */}
+ {draft.scheduleMode === "webhook" &&
+ webhookDenial !== undefined &&
+ draft.enabled ? null : draft.scheduleMode === "webhook" ? (
<div className="space-y-4">
<WebhookEndpointField environmentId={environmentId} task={liveTask} />
<p className="text-xs text-muted-foreground">
@@ -1905,7 +1932,14 @@ function ScheduledTaskEditorForm({
</DialogClose>
<Button
size="sm"
- disabled={!canOperate || saving || editingTaskMissing || !connected || !tasksQuery.data}
+ disabled={
+ !canOperate ||
+ saving ||
+ editingTaskMissing ||
+ !connected ||
+ !tasksQuery.data ||
+ (draft.enabled && draft.scheduleMode === "webhook" && webhookDenial !== undefined)
+ }
onClick={() => void submit()}
>
{draft.editingId ? "Save task" : "Create task"}
diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx
index 91cb8d6613c..8c31910d7d2 100644
--- a/apps/web/src/components/settings/SettingsPanels.tsx
+++ b/apps/web/src/components/settings/SettingsPanels.tsx
@@ -8,6 +8,8 @@ import {
type DesktopUpdateChannel,
IDLE_COMPACTION_MODES,
globalIdleCompaction,
+ managedUpdatesDenial,
+ managedUpdatesMessage,
ProviderDriverKind,
type ProviderInstanceId,
type SidebarProjectGroupingMode,
@@ -59,6 +61,7 @@ import { ProjectDefaultsSettings } from "./ProjectDefaultsSettings";
import { ThreadTitleInstructionsSettings } from "./ThreadTitleInstructionsSettings";
import { SnoozePresetsRow } from "./SnoozePresetsSettings";
import { useDesktopUpdateState } from "../../state/desktopUpdate";
+import { managedTelemetryOffMessage, usePrimaryManagedPolicy } from "../../state/managedPolicy";
import {
getCustomModelOptionsByInstance,
resolveAppModelSelectionState,
@@ -156,6 +159,13 @@ function AboutVersionSection() {
const hasDesktopBridge = typeof window !== "undefined" && Boolean(window.desktopBridge);
const selectedUpdateChannel = updateState?.channel ?? "latest";
+ // The desktop updates this machine, whose policy the primary environment reports.
+ const primaryPolicy = usePrimaryManagedPolicy();
+ const updatesDenial = hasDesktopBridge ? managedUpdatesDenial(primaryPolicy) : undefined;
+ const nightlyDeniedBy =
+ hasDesktopBridge && primaryPolicy?.limits?.updates?.allowNightly === false
+ ? primaryPolicy.organization
+ : undefined;
const selectedHostedAppChannel = hasDesktopBridge ? null : HOSTED_APP_CHANNEL;
// A switch that failed part way leaves this app or a server on the other track.
// With its updater off, a switch cannot move this app, so it is not counted.
@@ -245,7 +255,9 @@ function AboutVersionSection() {
type: "error",
title: "Could not check for updates",
description:
- result.state.message ?? "Automatic updates are not available in this build.",
+ updatesDenial ??
+ result.state.message ??
+ "Automatic updates are not available in this build.",
}),
);
}
@@ -280,7 +292,8 @@ function AboutVersionSection() {
const description =
action === "download" || action === "install"
? "Update available."
- : (getDesktopUpdateDisabledReason(updateState) ?? "Current version of the application.");
+ : (getDesktopUpdateDisabledReason(updateState, updatesDenial) ??
+ "Current version of the application.");
return (
<>
@@ -288,6 +301,7 @@ function AboutVersionSection() {
id={searchableSetting("app-version").id}
title={<AboutVersionTitle />}
description={description}
+ managed={updatesDenial}
control={
<Tooltip>
<TooltipTrigger
@@ -310,7 +324,13 @@ function AboutVersionSection() {
<SettingsRow
{...searchableSetting("update-track")}
description={
- unswitchedMachines > 0 ? (
+ nightlyDeniedBy !== undefined ? (
+ `${managedUpdatesMessage(nightlyDeniedBy)} Nightly builds are not available${
+ selectedUpdateChannel === "nightly"
+ ? "; switch to Stable to keep getting updates."
+ : "."
+ }`
+ ) : unswitchedMachines > 0 ? (
<>
{unswitchedMachines === 1
? "1 machine still runs"
@@ -330,6 +350,7 @@ function AboutVersionSection() {
"Switches this app and every connected machine whose database the target release supports."
)
}
+ managed={updatesDenial}
control={
<Select
value={selectedUpdateChannel}
@@ -351,7 +372,11 @@ function AboutVersionSection() {
<SelectItem hideIndicator value="latest">
Stable
</SelectItem>
- <SelectItem hideIndicator value="nightly">
+ <SelectItem
+ hideIndicator
+ value="nightly"
+ disabled={nightlyDeniedBy !== undefined && selectedUpdateChannel !== "nightly"}
+ >
Nightly
</SelectItem>
</SelectPopup>
@@ -1977,9 +2002,30 @@ export function MaintenanceSettingsPanel() {
}
export function AboutSettingsPanel() {
+ const primaryPolicy = usePrimaryManagedPolicy();
+ const telemetryOff = managedTelemetryOffMessage(primaryPolicy);
return (
<SettingsPageContainer>
<SettingsSection id="about" title="App">
+ {primaryPolicy ? (
+ <SettingsRow
+ title="Organization"
+ description={`This environment is managed by ${primaryPolicy.organization}. Some settings and features follow its policy.`}
+ control={
+ primaryPolicy.supportUrl ? (
+ <Button
+ render={
+ <a href={primaryPolicy.supportUrl} target="_blank" rel="noreferrer noopener" />
+ }
+ size="sm"
+ variant="outline"
+ >
+ Get help
+ </Button>
+ ) : null
+ }
+ />
+ ) : null}
{isElectron || HOSTED_APP_CHANNEL ? (
<AboutVersionSection />
) : (
@@ -1997,7 +2043,11 @@ export function AboutSettingsPanel() {
<SettingsSection id="legal" title="Legal">
<SettingsRow
{...searchableSetting("privacy-policy")}
- description="How we handle your data, including the anonymous usage data T3 Code collects."
+ description={
+ telemetryOff === undefined
+ ? "How we handle your data, including the anonymous usage data T3 Code collects."
+ : `How we handle your data. ${telemetryOff}`
+ }
control={
<Button
render={<a href={PRIVACY_POLICY_URL} target="_blank" rel="noreferrer noopener" />}
diff --git a/apps/web/src/components/settings/StorageSettings.tsx b/apps/web/src/components/settings/StorageSettings.tsx
index 8be558dca60..81d03ab752c 100644
--- a/apps/web/src/components/settings/StorageSettings.tsx
+++ b/apps/web/src/components/settings/StorageSettings.tsx
@@ -476,6 +476,9 @@ export function WorktreeCleanupSection() {
)
? "Mixed across selected machines"
: undefined;
+ // A policy locks these through worktreeCleanup, which also reaches each project's own rules.
+ const lockablePath = (key: keyof WorktreeCleanupRules) =>
+ isProjectScope ? ["worktreeCleanup"] : ["worktreeCleanup", `storageCleanup.${key}`];
const update = (patch: Partial<StorageCleanupSettings>) =>
updateSettings({ storageCleanup: patch });
const updateWorktree = (patch: Partial<WorktreeCleanupRules>) =>
@@ -557,6 +560,7 @@ export function WorktreeCleanupSection() {
<SettingsRow
title="Delete worktrees with deleted threads"
status={ruleStatus("worktreeOnDelete")}
+ managedPaths={lockablePath("worktreeOnDelete")}
description="Remove unused worktrees when active or archived threads are deleted. Worktrees with local changes are kept."
serverScoped={!isProjectScope}
control={
@@ -570,6 +574,7 @@ export function WorktreeCleanupSection() {
<SettingsRow
title="Delete merged worktrees"
status={ruleStatus("worktreeOnMerge")}
+ managedPaths={lockablePath("worktreeOnMerge")}
description="Remove worktrees whose pull request is merged and whose commits are included in the default branch."
serverScoped={!isProjectScope}
control={
@@ -583,6 +588,7 @@ export function WorktreeCleanupSection() {
<SettingsRow
title="Delete inactive worktrees"
status={ruleStatus("worktreeAfterDays")}
+ managedPaths={lockablePath("worktreeAfterDays")}
description="Remove worktrees after their threads have been inactive for this many days. Branches and thread history are kept."
serverScoped={!isProjectScope}
control={
@@ -605,6 +611,7 @@ export function WorktreeCleanupSection() {
) && (
<SettingsRow
title="Delete settled worktrees"
+ managedPaths={lockablePath("worktreeSettledAfterDays")}
status={[
ruleStatus("worktreeSettledAfterDays"),
environments.length > connectedEnvironments.length
@@ -630,6 +637,7 @@ export function WorktreeCleanupSection() {
<SettingsRow
title="Delete unchanged worktrees"
status={ruleStatus("worktreeUnchanged")}
+ managedPaths={lockablePath("worktreeUnchanged")}
description="Remove worktrees with no commits beyond the default branch."
serverScoped={!isProjectScope}
control={
@@ -647,6 +655,7 @@ export function WorktreeCleanupSection() {
<SettingsRow
{...searchableSetting("storage-worktree-keep-when")}
status={ruleStatus("worktreeKeepWhen")}
+ managedPaths={lockablePath("worktreeKeepWhen")}
description={
settings.worktreeKeepWhen === "any-local-files"
? "Includes ignored files, except node_modules."
@@ -750,6 +759,7 @@ export function StorageCleanupSections() {
<SettingsRow
title="Delete old browser artifacts"
status={artifactsStatus}
+ managedPaths={["storageCleanup.browserArtifactsAfterDays"]}
description="Delete saved browser captures after this many days. Older capture links will no longer open."
serverScoped
control={
@@ -765,6 +775,7 @@ export function StorageCleanupSections() {
<SettingsRow
title="Delete old rotated logs"
status={logsStatus}
+ managedPaths={["storageCleanup.logsAfterDays"]}
description="Delete inactive rotated log files after this many days. Current logs are kept."
serverScoped
control={
diff --git a/apps/web/src/components/settings/UpdateTrackSwitchDialog.tsx b/apps/web/src/components/settings/UpdateTrackSwitchDialog.tsx
index 83547b8712f..f5db42c452c 100644
--- a/apps/web/src/components/settings/UpdateTrackSwitchDialog.tsx
+++ b/apps/web/src/components/settings/UpdateTrackSwitchDialog.tsx
@@ -18,7 +18,7 @@ import {
type ChannelSwitchRelease,
} from "../sidebar/updateEverything.logic";
import { isHostedByThisApp, useUpdateEverything } from "../sidebar/useUpdateEverything";
-import { prepareLocalTrackSwitch } from "./updateTrackSwitch.logic";
+import { localUpdaterStaysPut, prepareLocalTrackSwitch } from "./updateTrackSwitch.logic";
import {
AlertDialog,
AlertDialogClose,
@@ -76,8 +76,7 @@ function SwitchPlan({
const updateState = useDesktopUpdateState();
const { environments } = useEnvironments();
const crossesLocal = desktopUpdateChannelOf(APP_VERSION) !== release.channel;
- // With its updater off (a .deb install, or no feed) this app stays put and only remotes move.
- const updatesOff = updateState?.enabled === false;
+ const updatesOff = localUpdaterStaysPut(updateState, release.channel);
// After a partial switch this app may already be on the track; then only remotes move.
const switchesLocal = crossesLocal && !updatesOff;
const [checking, setChecking] = useState(false);
diff --git a/apps/web/src/components/settings/browserImportWizard.logic.ts b/apps/web/src/components/settings/browserImportWizard.logic.ts
index d36d90aed46..ed96f128d27 100644
--- a/apps/web/src/components/settings/browserImportWizard.logic.ts
+++ b/apps/web/src/components/settings/browserImportWizard.logic.ts
@@ -45,7 +45,12 @@ export type ImportOutcome =
readonly skippedDomains: ReadonlyArray<string>;
readonly targetName: string;
}
- | { readonly kind: "blocked"; readonly reason: BrowserImportFailureReason };
+ | {
+ readonly kind: "blocked";
+ readonly reason: BrowserImportFailureReason;
+ /** Shown instead of the reason's copy, such as a managed policy's refusal. */
+ readonly message?: string;
+ };
export type WizardStep =
| { readonly step: "quit" }
@@ -64,7 +69,11 @@ export type WizardStep =
readonly skippedDomains: ReadonlyArray<string>;
readonly targetName: string;
}
- | { readonly step: "blocked"; readonly reason: BrowserImportFailureReason };
+ | {
+ readonly step: "blocked";
+ readonly reason: BrowserImportFailureReason;
+ readonly message?: string;
+ };
export function canCloseWizard(step: WizardStep): boolean {
return step.step !== "importing";
@@ -94,7 +103,9 @@ export function outcomeToStep(outcome: ImportOutcome): WizardStep {
if (outcome.reason === "needsFullDiskAccess") {
return { step: "fullDiskAccess", resume: "import", checked: true };
}
- return { step: "blocked", reason: outcome.reason };
+ return outcome.message === undefined
+ ? { step: "blocked", reason: outcome.reason }
+ : { step: "blocked", reason: outcome.reason, message: outcome.message };
}
export function refreshedSourceStep(source: BrowserImportSource | undefined): WizardStep {
diff --git a/apps/web/src/components/settings/settingsLayout.tsx b/apps/web/src/components/settings/settingsLayout.tsx
index 816e0e48763..cf2aae4cf53 100644
--- a/apps/web/src/components/settings/settingsLayout.tsx
+++ b/apps/web/src/components/settings/settingsLayout.tsx
@@ -2,8 +2,13 @@ import { SettingsGroup } from "./SettingsGroup";
import { AuthSettingsWriteScope } from "@t3tools/contracts";
import { usePrimaryEnvironmentId, usePrimaryEnvironment } from "../../state/environments";
import { useEnvironmentScope, useEnvironmentsWithScope } from "../../state/session";
+import { useServerConfigs } from "../../state/entities";
import { InfoIcon, Undo2Icon } from "lucide-react";
-import { DEFAULT_SERVER_SETTINGS, type ServerSettings } from "@t3tools/contracts";
+import {
+ DEFAULT_SERVER_SETTINGS,
+ isManagedSettingPath,
+ type ServerSettings,
+} from "@t3tools/contracts";
import * as Equal from "effect/Equal";
import { useLocation, useNavigate } from "@tanstack/react-router";
import { createContext, type ComponentPropsWithoutRef, type ReactNode, useContext } from "react";
@@ -33,6 +38,7 @@ import {
} from "./SettingInheritance";
const EMPTY_SETTING_KEYS: readonly (keyof ServerSettings)[] = [];
+const EMPTY_MANAGED_PATHS: readonly string[] = [];
declare module "@tanstack/react-router" {
interface HistoryState {
@@ -303,7 +309,9 @@ export function SettingsRow({
control,
serverScoped = false,
settingKeys = EMPTY_SETTING_KEYS,
+ managedPaths = EMPTY_MANAGED_PATHS,
mixed: mixedOverride,
+ managed,
children,
className,
...rowProps
@@ -316,7 +324,11 @@ export function SettingsRow({
control?: ReactNode;
serverScoped?: boolean;
settingKeys?: readonly (keyof ServerSettings)[];
+ /** Dot paths inside a setting, such as `storageCleanup.logsAfterDays`, an administrator can lock. */
+ managedPaths?: readonly string[];
mixed?: boolean;
+ /** Why an administrator's policy turns this row's control off, from the contract's denial helpers. */
+ managed?: string | undefined;
children?: ReactNode;
}) {
const targetRef = useSettingsSearchTarget<HTMLDivElement>(rowProps.id);
@@ -333,6 +345,22 @@ export function SettingsRow({
? context.connectedEnvironments.length > 0 &&
context.connectedEnvironments.every((target) => writableIds.has(target.environmentId))
: primaryCanWrite;
+ const serverConfigs = useServerConfigs();
+ // An administrator's lock on any target wins over every other reason a control is inert.
+ const lockablePaths = [...settingKeys, ...managedPaths];
+ const managedBy =
+ lockablePaths.length === 0
+ ? undefined
+ : (context
+ ? context.connectedEnvironments.map((environment) => environment.serverConfig)
+ : [primaryEnvironmentId === null ? undefined : serverConfigs.get(primaryEnvironmentId)]
+ )
+ .map((config) => config?.managedPolicy)
+ .find(
+ (policy) =>
+ policy !== undefined &&
+ lockablePaths.some((path) => isManagedSettingPath(policy, path)),
+ )?.organization;
const clearOverrides = useClearScopedSettings();
const clearProjectOverrides = useClearProjectOverrides();
const isProjectScope =
@@ -361,17 +389,19 @@ export function SettingsRow({
),
);
const overridingProjects = isProjectScope ? [] : projectOverrides(context, scopedKeys);
- const renderedReset = unavailable ? null : isProjectScope && scopedKeys.length > 0 ? (
- source === "project" || source === "mixed" ? (
- <SettingResetButton
- label={typeof title === "string" ? title : "override"}
- tooltip="Reset to inherited value"
- onClick={() => (onResetOverride ? onResetOverride() : clearOverrides(scopedKeys))}
- />
- ) : null
- ) : (
- resetAction
- );
+ const renderedReset =
+ unavailable || managedBy !== undefined || managed !== undefined ? null : isProjectScope &&
+ scopedKeys.length > 0 ? (
+ source === "project" || source === "mixed" ? (
+ <SettingResetButton
+ label={typeof title === "string" ? title : "override"}
+ tooltip="Reset to inherited value"
+ onClick={() => (onResetOverride ? onResetOverride() : clearOverrides(scopedKeys))}
+ />
+ ) : null
+ ) : (
+ resetAction
+ );
const inertControl = (message: string) => (
<Tooltip>
<TooltipTrigger
@@ -393,24 +423,28 @@ export function SettingsRow({
</Tooltip>
);
const renderedControl =
- unavailable && control
- ? inertControl(
- !canWriteSettings
- ? `This connection lacks permission to change settings on ${
- context
- ? context.connectedEnvironments
- .filter((target) => !writableIds.has(target.environmentId))
- .map((target) => target.label)
- .join(", ") || "the selected environment"
- : (primaryEnvironment?.label ?? "the primary environment")
- }.`
- : context
- ? "Reconnect the selected environment to change this setting."
- : PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE,
- )
- : environmentWide && control
- ? inertControl("Environment-wide setting. Select an environment to change it.")
- : control;
+ managed !== undefined && control
+ ? inertControl(managed)
+ : managedBy !== undefined && control
+ ? inertControl(`Managed by ${managedBy}.`)
+ : unavailable && control
+ ? inertControl(
+ !canWriteSettings
+ ? `This connection lacks permission to change settings on ${
+ context
+ ? context.connectedEnvironments
+ .filter((target) => !writableIds.has(target.environmentId))
+ .map((target) => target.label)
+ .join(", ") || "the selected environment"
+ : (primaryEnvironment?.label ?? "the primary environment")
+ }.`
+ : context
+ ? "Reconnect the selected environment to change this setting."
+ : PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE,
+ )
+ : environmentWide && control
+ ? inertControl("Environment-wide setting. Select an environment to change it.")
+ : control;
const customized =
context !== null &&
settingKeys.some((key) =>
diff --git a/apps/web/src/components/settings/updateTrackSwitch.logic.test.ts b/apps/web/src/components/settings/updateTrackSwitch.logic.test.ts
index 63c4422f28a..abc27d1f525 100644
--- a/apps/web/src/components/settings/updateTrackSwitch.logic.test.ts
+++ b/apps/web/src/components/settings/updateTrackSwitch.logic.test.ts
@@ -1,7 +1,7 @@
import type { DesktopUpdateChannel, DesktopUpdateState } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
-import { prepareLocalTrackSwitch } from "./updateTrackSwitch.logic";
+import { localUpdaterStaysPut, prepareLocalTrackSwitch } from "./updateTrackSwitch.logic";
const STABLE = "0.1.3";
@@ -74,3 +74,14 @@ describe("prepareLocalTrackSwitch", () => {
expect(undo.saved).toEqual(["latest"]);
});
});
+
+describe("localUpdaterStaysPut", () => {
+ it("moves an app whose updater is off only because its policy rules out nightly", () => {
+ const blocked = { enabled: false, channelBlockedByPolicy: true as const };
+ expect(localUpdaterStaysPut(blocked, "latest")).toBe(false);
+ expect(localUpdaterStaysPut(blocked, "nightly")).toBe(true);
+ // Off for another reason too, such as T3CODE_DISABLE_AUTO_UPDATE or a .deb install.
+ expect(localUpdaterStaysPut({ enabled: false }, "latest")).toBe(true);
+ expect(localUpdaterStaysPut({ enabled: true }, "nightly")).toBe(false);
+ });
+});
diff --git a/apps/web/src/components/settings/updateTrackSwitch.logic.ts b/apps/web/src/components/settings/updateTrackSwitch.logic.ts
index 6e7e49898df..41d478e050d 100644
--- a/apps/web/src/components/settings/updateTrackSwitch.logic.ts
+++ b/apps/web/src/components/settings/updateTrackSwitch.logic.ts
@@ -48,3 +48,16 @@ export async function prepareLocalTrackSwitch(
: (local.message ?? `This app found no build of ${input.version} to install.`),
};
}
+
+/**
+ * Whether this app stays put while connected machines move: its updater is off, as for a .deb
+ * install or without a feed. Off only because a policy rules out its nightly channel, it moves.
+ */
+export function localUpdaterStaysPut(
+ state: Pick<DesktopUpdateState, "enabled" | "channelBlockedByPolicy"> | null | undefined,
+ target: DesktopUpdateChannel,
+): boolean {
+ return (
+ state?.enabled === false && !(target === "latest" && state.channelBlockedByPolicy === true)
+ );
+}
diff --git a/apps/web/src/components/sidebar/SidebarUpdatePill.tsx b/apps/web/src/components/sidebar/SidebarUpdatePill.tsx
index 7e0ee498cec..420a4127f80 100644
--- a/apps/web/src/components/sidebar/SidebarUpdatePill.tsx
+++ b/apps/web/src/components/sidebar/SidebarUpdatePill.tsx
@@ -1,4 +1,8 @@
-import type { DesktopBridge, DesktopUpdateState } from "@t3tools/contracts";
+import {
+ type DesktopBridge,
+ type DesktopUpdateState,
+ managedUpdatesDenial,
+} from "@t3tools/contracts";
import { TriangleAlertIcon } from "lucide-react";
import { type ComponentProps, useId, useRef, useState } from "react";
import { flushSync } from "react-dom";
@@ -8,6 +12,7 @@ import { useMediaQuery } from "../../hooks/useMediaQuery";
import { cn } from "../../lib/utils";
import { ensureLocalApi } from "../../localApi";
import { useDesktopUpdateState } from "../../state/desktopUpdate";
+import { usePrimaryManagedPolicy } from "../../state/managedPolicy";
import { stackedThreadToast, toastManager } from "../ui/toast";
import {
canCheckForUpdate,
@@ -192,6 +197,8 @@ export function SidebarUpdatePill() {
function SidebarUpdateControl() {
const state = useDesktopUpdateState();
+ // The desktop updates this machine, whose policy the primary environment reports.
+ const updatesDenial = managedUpdatesDenial(usePrimaryManagedPolicy());
const [isActionPending, setIsActionPending] = useState(false);
const [isConfirmingEverything, setIsConfirmingEverything] = useState(false);
const [checkAnimationKey, setCheckAnimationKey] = useState(0);
@@ -239,7 +246,7 @@ function SidebarUpdateControl() {
showCheckIcon,
});
const idleTooltip =
- !showUpdateDetails && !showCheckIcon ? getDesktopUpdateIdleTooltip(state) : null;
+ !showUpdateDetails && !showCheckIcon ? getDesktopUpdateIdleTooltip(state, updatesDenial) : null;
const tooltip = runsEverything
? everything.summary
: showUpdateDetails
@@ -327,7 +334,9 @@ function SidebarUpdateControl() {
type: "error",
title: "Could not check for updates",
description:
- result.state.message ?? "Automatic updates are not available in this build.",
+ updatesDenial ??
+ result.state.message ??
+ "Automatic updates are not available in this build.",
}),
);
})
diff --git a/apps/web/src/components/sidebar/updateEverything.logic.test.ts b/apps/web/src/components/sidebar/updateEverything.logic.test.ts
index 4c09823d405..58328dbc1ee 100644
--- a/apps/web/src/components/sidebar/updateEverything.logic.test.ts
+++ b/apps/web/src/components/sidebar/updateEverything.logic.test.ts
@@ -84,6 +84,48 @@ describe("collectServerUpdateTargets", () => {
["manual", "needs a manual update"],
]);
});
+
+ it("skips servers whose policy refuses the update, with the policy's message", () => {
+ const managed = (
+ id: string,
+ updates: { mode: "off" } | { mode: "auto"; allowNightly: false },
+ selfUpdate: "boot-service" | "desktop-managed" = "boot-service",
+ ) => {
+ const base = machine(id, "0.0.40", selfUpdate);
+ return {
+ ...base,
+ serverConfig: {
+ ...base.serverConfig!,
+ managedPolicy: { organization: "Example Corp", lockedSettings: [], limits: { updates } },
+ },
+ };
+ };
+ const machines = [
+ managed("off", { mode: "off" }),
+ managed("no-nightly", { mode: "auto", allowNightly: false }),
+ // A desktop app updates from its own feed, whatever track this app is on.
+ managed("desktop-no-nightly", { mode: "auto", allowNightly: false }, "desktop-managed"),
+ ];
+
+ expect(
+ collectServerUpdateTargets(machines, "0.0.50").skipped.map((entry) => [
+ entry.label,
+ entry.reason,
+ ]),
+ ).toEqual([["off", "Example Corp manages T3 Code updates."]]);
+ expect(
+ collectServerUpdateTargets(
+ machines.map((entry) => ({
+ ...entry,
+ serverConfig: {
+ ...entry.serverConfig,
+ environment: { ...entry.serverConfig.environment, serverVersion: "0.0.49-nightly.1" },
+ },
+ })),
+ "0.0.50-nightly.20261028.1",
+ ).skipped.map((entry) => entry.label),
+ ).toEqual(["off", "no-nightly"]);
+ });
});
describe("collectChannelSwitchTargets", () => {
@@ -154,6 +196,18 @@ describe("collectChannelSwitchTargets", () => {
]);
});
+ const managedHost = (base: UpdateEverythingMachine): UpdateEverythingMachine => ({
+ ...base,
+ serverConfig: {
+ ...base.serverConfig!,
+ managedPolicy: {
+ organization: "Example Corp",
+ lockedSettings: [],
+ limits: { updates: { mode: "auto", allowNightly: false } },
+ },
+ },
+ });
+
it("moves stable hosts to nightly only when nightly knows their database", () => {
const nightly = { channel: "nightly" as const, version: NIGHTLY, databaseMigration: 72 };
const { targets, skipped } = collectChannelSwitchTargets(
@@ -171,6 +225,8 @@ describe("collectChannelSwitchTargets", () => {
},
}),
machine("current", NIGHTLY, "boot-service"),
+ // The server refuses a track its policy rules out, so the dialog skips it up front.
+ managedHost(host(machine("no-nightly", "0.1.2", "boot-service"), 70)),
],
nightly,
);
@@ -184,6 +240,10 @@ describe("collectChannelSwitchTargets", () => {
`its database has changes ${NIGHTLY} does not support yet; stay on Stable until Nightly has them`,
],
["old-desktop", "needs a newer desktop app"],
+ [
+ "no-nightly",
+ "Example Corp manages T3 Code updates. Only stable releases can be installed.",
+ ],
]);
});
});
diff --git a/apps/web/src/components/sidebar/updateEverything.logic.ts b/apps/web/src/components/sidebar/updateEverything.logic.ts
index cfeecfd5e31..cbbd3baa7c7 100644
--- a/apps/web/src/components/sidebar/updateEverything.logic.ts
+++ b/apps/web/src/components/sidebar/updateEverything.logic.ts
@@ -1,9 +1,11 @@
import type { ServerUpdateState } from "@t3tools/client-runtime/state/server";
-import type {
- DesktopUpdateChannel,
- EnvironmentId,
- ServerConfig,
- ServerSelfUpdateCapability,
+import {
+ type DesktopUpdateChannel,
+ type EnvironmentId,
+ managedNightlyDeniedMessage,
+ managedUpdatesDenial,
+ type ServerConfig,
+ type ServerSelfUpdateCapability,
} from "@t3tools/contracts";
import { cliReleaseChannelOf, desktopUpdateChannelOf } from "@t3tools/shared/cliRelease";
import { compareSemverVersions } from "@t3tools/shared/semver";
@@ -21,6 +23,7 @@ export interface UpdateEverythingMachine {
readonly serverConfig: {
readonly environment: ServerConfig["environment"];
readonly settings: Pick<ServerConfig["settings"], "continueThreadsAfterServerUpdate">;
+ readonly managedPolicy?: ServerConfig["managedPolicy"];
} | null;
readonly connected: boolean;
readonly hostedByThisApp: boolean;
@@ -92,6 +95,14 @@ export function collectServerUpdateTargets(
continue;
}
const selfUpdate = resolveServerSelfUpdateCapability(config);
+ const managedDenial = managedMachineUpdateDenial(
+ config,
+ selfUpdate === "desktop-managed" ? undefined : targetVersion,
+ );
+ if (managedDenial !== undefined) {
+ skip(managedDenial);
+ continue;
+ }
const desktopAppUpdate = supportsDesktopAppUpdate(config);
if (selfUpdate === null) {
skip("needs a manual update");
@@ -190,6 +201,26 @@ export function localSwitchBlockReason(
);
}
+/**
+ * The server refuses these with the same message; say so before the run instead of after.
+ * `targetVersion` is undefined when the server picks its own version, as desktop apps do.
+ */
+function managedMachineUpdateDenial(
+ config: NonNullable<UpdateEverythingMachine["serverConfig"]>,
+ targetVersion: string | undefined,
+): string | undefined {
+ const policy = config.managedPolicy;
+ return (
+ managedUpdatesDenial(policy) ??
+ (policy !== undefined &&
+ policy.limits?.updates?.allowNightly === false &&
+ targetVersion !== undefined &&
+ cliReleaseChannelOf(targetVersion) !== "stable"
+ ? managedNightlyDeniedMessage(policy.organization)
+ : undefined)
+ );
+}
+
/** Servers move to the release; desktop-managed hosts reinstall their app on its track. A desktop
* host already current gets a track-only request, since its saved track may still differ. */
export function collectChannelSwitchTargets(
@@ -229,7 +260,8 @@ export function collectChannelSwitchTargets(
if (
!("skip" in move) &&
move.selfUpdate === "desktop-managed" &&
- unavailableReason(machine) === null
+ unavailableReason(machine) === null &&
+ managedMachineUpdateDenial(config, release.version) === undefined
) {
targets.push({ ...target(move.selfUpdate, serverVersion), trackOnly: true });
}
@@ -240,6 +272,11 @@ export function collectChannelSwitchTargets(
skip(unavailable ?? "not connected");
continue;
}
+ const managedDenial = managedMachineUpdateDenial(config, release.version);
+ if (managedDenial !== undefined) {
+ skip(managedDenial);
+ continue;
+ }
const move = trackSwitchMove(config, sameTrack);
if ("skip" in move) {
skip(move.skip);
diff --git a/apps/web/src/state/managedPolicy.test.ts b/apps/web/src/state/managedPolicy.test.ts
new file mode 100644
index 00000000000..2fde6442a93
--- /dev/null
+++ b/apps/web/src/state/managedPolicy.test.ts
@@ -0,0 +1,45 @@
+import { ProviderDriverKind, type ManagedPolicySummary } from "@t3tools/contracts";
+import { describe, expect, it } from "vite-plus/test";
+
+import { managedInstanceLocks } from "./managedPolicy";
+
+const codex = ProviderDriverKind.make("codex");
+const claude = ProviderDriverKind.make("claudeAgent");
+
+const policy: ManagedPolicySummary = {
+ organization: "Example Corp",
+ lockedSettings: [],
+ limits: {
+ providers: {
+ lockedInstanceFields: {
+ [codex]: ["config.binaryPath", "environment.OPENAI_BASE_URL", "environment.HTTPS_PROXY"],
+ },
+ },
+ },
+};
+
+describe("managedInstanceLocks", () => {
+ it("splits locked instance paths into config keys and environment names", () => {
+ const locks = managedInstanceLocks(policy, codex);
+ expect(locks && [...locks.configKeys]).toEqual(["binaryPath"]);
+ expect(locks && [...locks.environmentNames]).toEqual(["OPENAI_BASE_URL", "HTTPS_PROXY"]);
+ expect(locks?.reason).toBe("Managed by Example Corp.");
+ });
+
+ it("treats a bare environment path as every variable", () => {
+ const ceilingPolicy = {
+ ...policy,
+ limits: {
+ providers: { lockedInstanceFields: { [codex]: ["config.binaryPath", "environment"] } },
+ },
+ };
+ const locks = managedInstanceLocks(ceilingPolicy, codex);
+ expect(locks?.wholeEnvironment).toBe(true);
+ expect(managedInstanceLocks(policy, codex)?.wholeEnvironment).toBe(false);
+ });
+
+ it("locks nothing for drivers the policy does not pin, or without a policy", () => {
+ expect(managedInstanceLocks(policy, claude)).toBeUndefined();
+ expect(managedInstanceLocks(undefined, codex)).toBeUndefined();
+ });
+});
diff --git a/apps/web/src/state/managedPolicy.ts b/apps/web/src/state/managedPolicy.ts
new file mode 100644
index 00000000000..4e588b37960
--- /dev/null
+++ b/apps/web/src/state/managedPolicy.ts
@@ -0,0 +1,67 @@
+import type { EnvironmentId, ManagedPolicySummary, ProviderDriverKind } from "@t3tools/contracts";
+
+import { useServerConfigs } from "./entities";
+import { usePrimaryEnvironmentId } from "./environments";
+
+/** The policy an environment's administrator applies, or undefined when it is unmanaged. */
+export function useManagedPolicy(
+ environmentId: EnvironmentId | null | undefined,
+): ManagedPolicySummary | undefined {
+ const serverConfigs = useServerConfigs();
+ return environmentId == null ? undefined : serverConfigs.get(environmentId)?.managedPolicy;
+}
+
+export function usePrimaryManagedPolicy(): ManagedPolicySummary | undefined {
+ return useManagedPolicy(usePrimaryEnvironmentId());
+}
+
+/**
+ * Why a control acting on several environments is unavailable: the first denial any target's
+ * policy gives, since one refusing target refuses the whole action.
+ */
+export function firstManagedDenial(
+ policies: Iterable<ManagedPolicySummary | undefined>,
+ deny: (policy: ManagedPolicySummary | undefined) => string | undefined,
+): string | undefined {
+ for (const policy of policies) {
+ const denial = deny(policy);
+ if (denial !== undefined) return denial;
+ }
+ return undefined;
+}
+
+/** What usage-data notices say when the policy turns product analytics off. */
+export function managedTelemetryOffMessage(
+ policy: ManagedPolicySummary | undefined,
+): string | undefined {
+ return policy?.limits?.telemetry === false
+ ? `${policy.organization} turned off anonymous usage data.`
+ : undefined;
+}
+
+export interface ManagedInstanceLocks {
+ /** Keys inside the instance's `config` users cannot change. */
+ readonly configKeys: ReadonlySet<string>;
+ /** Environment variables users cannot edit, rename, or remove. */
+ readonly environmentNames: ReadonlySet<string>;
+ /** Under a runtime-mode ceiling every variable is the administrator's, not only named ones. */
+ readonly wholeEnvironment: boolean;
+ readonly reason: string;
+}
+
+/** What the policy pins on instances of `driver`, or undefined when nothing is. */
+export function managedInstanceLocks(
+ policy: ManagedPolicySummary | undefined,
+ driver: ProviderDriverKind,
+): ManagedInstanceLocks | undefined {
+ const paths = policy?.limits?.providers?.lockedInstanceFields?.[driver];
+ if (policy === undefined || paths === undefined || paths.length === 0) return undefined;
+ const fieldsUnder = (prefix: string) =>
+ new Set(paths.flatMap((path) => (path.startsWith(prefix) ? [path.slice(prefix.length)] : [])));
+ return {
+ configKeys: fieldsUnder("config."),
+ environmentNames: fieldsUnder("environment."),
+ wholeEnvironment: paths.includes("environment"),
+ reason: `Managed by ${policy.organization}.`,
+ };
+}
diff --git a/docs/user/install.md b/docs/user/install.md
index 6f3f63330e0..eb01607a917 100644
--- a/docs/user/install.md
+++ b/docs/user/install.md
@@ -208,3 +208,4 @@ For provider-specific setup and accounts, see [Codex](./providers-codex.md),
- [Remote access](./remote-access.md): connect from another device.
- [Running in the background](./background-service.md): keep a Linux or macOS host available.
- [Updating T3 Code](./updating.md): update the app and connected servers.
+- [Managed policy](./managed-policy.md): configure T3 Code for everyone on a machine.
diff --git a/docs/user/managed-policy.md b/docs/user/managed-policy.md
new file mode 100644
index 00000000000..e1ba501e6fa
--- /dev/null
+++ b/docs/user/managed-policy.md
@@ -0,0 +1,274 @@
+# Managed policy
+
+A managed policy lets an administrator configure T3 Code for every user on a machine. It sets
+defaults and locks for settings, and limits such as the broadest permission mode or which
+providers may run. The T3 Code server on the machine enforces it for every app that connects:
+the desktop app, a browser, or the mobile app.
+
+## Roll out a policy
+
+1. Write the policy as JSON, starting from the [example](#write-a-policy).
+2. Run `t3 policy check policy.json`. It prints what the policy will do, or what is wrong with it.
+3. Deploy the policy to each machine with your device management tool, in
+ [one of the supported places](#where-the-policy-goes).
+4. Restart T3 Code on the machine. The server reads the policy only when it starts.
+5. Run `t3 policy show` on the machine to
+ [check what the server loaded](#check-what-the-server-loaded).
+
+The desktop app includes the `t3` command; see [The `t3` command](./install.md#the-t3-command).
+
+## Write a policy
+
+```json
+{
+ "schemaVersion": 1,
+ "organization": "Example Corp",
+ "supportUrl": "https://it.example.com/t3",
+ "settings": {
+ "defaultRuntimeMode": { "value": "approval-required", "locked": false },
+ "enableAgentBrowserAccess": { "value": false, "locked": true }
+ },
+ "limits": {
+ "maxRuntimeMode": "auto-accept-edits",
+ "clients": ["desktop", "local-browser"],
+ "telemetry": false
+ }
+}
+```
+
+`schemaVersion` and `organization` are required. Users see the organization's name in Settings
+and beside each control the policy locks, with a link to `supportUrl` if you set one. [`settings`](#settings)
+sets defaults and locks, and [`limits`](#limits) restricts what T3 Code may do.
+
+Every user on the machine can read the policy, so do not put credentials in it.
+
+## Where the policy goes
+
+Use one of these per machine:
+
+| OS | Native policy | Policy file |
+| ------- | ------------------------------------------------------------------- | ------------------------------------------------- |
+| macOS | Configuration profile for `com.t3tools.t3code` | `/Library/Application Support/T3Code/policy.json` |
+| Windows | `Policy` string value under `HKLM\SOFTWARE\Policies\T3Tools\T3Code` | `C:\Program Files\T3Code\policy.json` |
+| Linux | | `/etc/t3code/policy.json` |
+
+T3 Code does not merge sources. If a machine has both a native policy and a policy file, T3 Code
+refuses to start until you remove one.
+
+**Policy file.** Copy the JSON to the path for the OS. Make it and its folder writable only by
+administrators.
+
+**macOS configuration profile.** Add a custom settings payload for the preference domain
+`com.t3tools.t3code`. The payload's keys are the policy's top-level keys (`schemaVersion`,
+`organization`, `supportUrl`, `settings`, `limits`); JSON objects become dictionaries and lists
+become arrays. To make the payload from a policy file you checked, run
+`plutil -convert xml1 -o com.t3tools.t3code.plist policy.json` and upload the result. Install it as
+a device profile, since T3 Code ignores user profiles, and deploy only one profile for this domain.
+A profile cannot hold `null`, so use a policy file if a setting's value must be `null`.
+
+**Windows registry.** Set the `Policy` value (`REG_SZ`) to the whole policy as one line of JSON,
+from Group Policy Preferences or an Intune script. T3 Code reads it through the Windows registry
+API, so it works where registry tools such as `reg.exe` are blocked for users. In PowerShell, as an
+administrator:
+
+```powershell
+$json = (Get-Content -Raw -Encoding UTF8 policy.json) -replace '\r?\n\s*', ''
+New-Item -Path HKLM:\SOFTWARE\Policies\T3Tools\T3Code -Force | Out-Null
+Set-ItemProperty -Path HKLM:\SOFTWARE\Policies\T3Tools\T3Code -Name Policy -Value $json -Type String
+```
+
+## Check what the server loaded
+
+Run `t3 policy show` as the user who runs T3 Code. It prints the installed policy and its
+fingerprint, then says whether the running server loaded that policy or an older one. The server
+reads the policy only when it starts, so "Restart T3 Code to apply the installed policy" means it
+still enforces the old one. In Settings, users see that your organization manages the environment,
+and each locked control shows **Managed by**.
+
+## Change or remove a policy
+
+After you deploy, change, or remove a policy, restart the T3 Code server on the machine: quit and
+reopen the desktop app, or run `t3 service restart` for the
+[background service](./background-service.md). Reconnecting a phone or browser does not reload the
+policy.
+
+To remove a policy, delete the file, remove the profile, or delete the registry value, then restart
+the server. Users get back the settings they had chosen, since T3 Code never writes policy values
+into them.
+
+## When T3 Code refuses to start
+
+T3 Code refuses to start rather than run with a policy it cannot fully enforce. That includes a
+policy it cannot read or parse, a setting it does not know, a value of the wrong type, a key this
+version does not support, or a machine with both a native policy and a file. The error names where
+the policy came from and what is wrong.
+
+`t3 policy check` catches the same problems in a JSON file. For a profile or registry value, check
+the JSON before you convert it. A policy written for a newer version can use keys an older one
+cannot enforce, so upgrade T3 Code before you deploy a policy that uses them.
+
+## Settings
+
+Each key under `settings` is a setting's path in the server's `settings.json`, such as
+`storageCleanup.logsAfterDays`. To find a path, change the setting in T3 Code and look in
+`settings.json` under `~/.t3/userdata`.
+
+- `"locked": false` sets a default. It applies wherever the user has not chosen a value of their
+ own, and users can change it.
+- `"locked": true` sets the value. Users and agents cannot change it, in Settings or in a project's
+ settings, and Settings shows the control as managed by your organization. Removing the policy
+ brings back the user's own value.
+
+A few settings need care:
+
+- A default cannot add an entry, such as a provider instance, because users could never remove it.
+ Lock the entry instead, or set provider fields with [`providers.instances`](#providers).
+- A setting that can be empty, such as `defaultModelSelection`, is managed as a whole. You cannot
+ manage one field inside it.
+- `defaultRuntimeMode` cannot be broader than [`maxRuntimeMode`](#permission-modes).
+- `worktreeCleanup`, which projects can also set, overrides the `worktree` rules in
+ `storageCleanup`. Lock it along with those rules; T3 Code refuses a policy that locks only the
+ rules.
+- Manage `idleCompaction`, not the older `compactIdleThreads`. A Claude instance's own idle
+ compaction choice still wins over `idleCompaction`.
+- A provider instance's fields override each other, so lock `providerInstances.<id>` as a whole,
+ or pin single fields with [`providers.instances`](#providers). T3 Code refuses a lock on one
+ field inside an instance. A whole-instance lock covers only that instance; to cover every
+ instance of a provider, use `providers.instances`.
+
+## Limits
+
+`limits` restricts what T3 Code may do. Leave a key out to keep T3 Code's normal behavior.
+
+```json
+{
+ "schemaVersion": 1,
+ "organization": "Example Corp",
+ "limits": {
+ "maxRuntimeMode": "auto-accept-edits",
+ "clients": ["desktop"],
+ "connect": false,
+ "webhookTasks": false,
+ "browserCookieImport": false,
+ "telemetry": false,
+ "providers": {
+ "allowedDrivers": ["claudeAgent", "codex"],
+ "instances": {
+ "claudeAgent": {
+ "locked": true,
+ "environment": [{ "name": "CLAUDE_CODE_USE_BEDROCK", "value": "1" }]
+ }
+ }
+ },
+ "updates": { "mode": "auto", "feedUrl": "https://updates.example.com/t3code/" }
+ }
+}
+```
+
+### Permission modes
+
+`maxRuntimeMode` is the broadest [permission mode](./permission-modes.md) any thread may use:
+`approval-required` (Supervised), `auto-accept-edits`, `auto`, or `full-access`. It covers threads
+that users start, agents start, and scheduled tasks start. A thread already above the limit cannot
+run another turn until someone lowers its mode; its queued messages send once that happens. New
+threads start at the limit when the user's default is above it.
+
+With `maxRuntimeMode` set, you own each provider's launch settings: binary path, launch arguments,
+config home, and the environment variables set on each provider. They come from
+[`providers.instances`](#providers) or T3 Code's defaults, and users cannot change them, because a
+wrapper script, a launch flag, or a variable such as `NODE_OPTIONS` could otherwise turn off the
+provider's approvals. Pin the variables your users need, such as a gateway URL, in
+`providers.instances`. Variables in the environment that starts T3 Code itself still reach
+providers.
+
+ACP agents' own mode menus have no effect under `maxRuntimeMode`, except Antigravity's, whose modes
+T3 Code can place under the limit. Users still choose which ACP Registry agent runs; leave
+`acpRegistry` out of `allowedDrivers` to stop that.
+
+The limit decides which modes T3 Code asks the provider for. It is not a sandbox; see
+[What a policy does not cover](#what-a-policy-does-not-cover).
+
+### Clients and T3 Connect
+
+`clients` lists how the server may run:
+
+- `desktop`: as the desktop app's own server.
+- `local-browser`: as a server only browsers on this machine reach, such as `npx t3`.
+- `remote`: reachable from phones, other computers, and app.t3.codes over the network.
+
+`remote` is the line that matters. A server reachable from the network also accepts browsers on
+this machine, and the two local kinds differ only in how T3 Code was started. On machines with the
+desktop app, keep `desktop` in the list, or the app cannot start.
+
+Without `remote`, the server listens only on a loopback address, creates no pairing links, and
+signs out devices that paired earlier. It does not start with a host other than a loopback
+address or `localhost`. The [background service](./background-service.md) listens on private
+networks by default, so set `T3CODE_HOST=127.0.0.1` in its `service.env`. The desktop app starts
+with network access and Tailscale Serve off, whatever the user chose. That also turns off
+T3 Connect. To keep other remote access but turn off T3 Connect alone, set `"connect": false`.
+
+When it starts, the server also turns off each Tailscale Serve route, HTTPS or TCP, that forwards
+to it, such as one `t3 pair --tailscale` set up, and leaves other routes alone. It does not start
+while such a route stays on, or while Tailscale's answer cannot be read; the error names the
+command that turns the route off. A route whose target is a name, such as `localhost` or another
+machine on the same port, also stops it, since a name can resolve to this server; change the route
+or T3 Code's port. If Tailscale is installed but does not answer, as on a Mac where it was never set up, the
+server does not start until Tailscale is set up or removed. It does start when Tailscale is not
+installed, not running, or
+logged out, since nothing forwards then; a route Tailscale kept returns when Tailscale runs again,
+so restart T3 Code after that.
+
+### Other capabilities
+
+- `webhookTasks: false`: scheduled tasks cannot use webhook triggers. Existing webhook tasks stay
+ but do not run, and cannot be turned back on. Users can still edit or delete them.
+- `browserCookieImport: false`: users cannot import cookies from another browser into T3 Code's
+ browser.
+- `telemetry: false`: the server and desktop app send no [product usage data](./telemetry.md) or
+ relay connection traces. A policy cannot turn them on. A browser that opens the server, such as
+ app.t3.codes, still sends its own relay traces.
+
+### Providers
+
+`providers.allowedDrivers` lists the providers that may run, by ID: `codex` (Codex),
+`claudeAgent` (Claude), `cursor` (Cursor), `grok` (Grok), `opencode` (OpenCode), `antigravity`
+(Antigravity), `fx` (fx), `pi` (Pi), `muse` (Muse Code), and `acpRegistry` (ACP Registry).
+`t3 policy check` rejects an ID this version does not know. Threads on other providers stay,
+marked unavailable, and users can still turn those providers off.
+
+`providers.instances` sets fields on every instance of a provider, such as an environment variable
+that routes Claude through Amazon Bedrock or a base URL for a company gateway. `binaryPath` and
+`launchArgs` work only for providers that have those settings. With `"locked": true`, users cannot
+change the fields you set. With `"locked": false`, the fields fill in only what the user left
+empty. A `codex` entry that is locked, or any `codex` entry under `maxRuntimeMode`, also rules out
+[Connect with ChatGPT](./providers-codex.md#connect-with-chatgpt), since that runtime would skip
+your fields. In the same way, an `opencode` entry like that rules out a server URL, so OpenCode
+starts the binary you set.
+
+### Updates
+
+- `mode`: `auto` keeps the normal update flow. `off` stops T3 Code from checking for updates, for
+ machines that get T3 Code through device management.
+- `feedUrl`: the desktop app updates from your own mirror of the release feed instead of GitHub.
+ Publish only the versions you have approved. The `t3` command-line server updates through npm,
+ so pin it with your package tooling.
+- `allowNightly: false`: the nightly channel is unavailable.
+
+## What a policy does not cover
+
+The policy controls what T3 Code does. Agents run through each provider's own CLI, which reads its
+own configuration, such as `~/.claude`, and which a user can also run outside T3 Code. To restrict
+those CLIs, use their own managed configuration, such as Claude Code's managed settings.
+
+On a managed Windows machine, the desktop app does not run a WSL environment. A T3 Code server a
+user starts inside WSL reads `/etc/t3code/policy.json` in that distro, not the Windows policy.
+Deploy the policy file there too if your users run T3 Code in WSL.
+
+Without `remote`, T3 Code does not expose the server, but a user can still forward its local port
+with other tools.
+
+A user with administrator rights on the machine can edit or remove the policy. T3 Code enforces
+the policy in its own processes, which run as the user, so it stops users from changing managed
+settings in T3 Code but does not stop a user who modifies or replaces T3 Code itself. A version
+from before managed policy ignores it too. To control which builds can run, use your device
+management tool's application controls.
diff --git a/docs/user/permission-modes.md b/docs/user/permission-modes.md
index 3c330bc6bae..5ec8dc48fa4 100644
--- a/docs/user/permission-modes.md
+++ b/docs/user/permission-modes.md
@@ -17,6 +17,9 @@ and modes you choose in a draft keep their permissions.
| **Auto** | Uses the provider's automatic review to approve routine actions and ask about others. |
| **Full access** | Allows commands and edits without approval prompts. |
+An administrator can cap the modes available on a machine with a
+[managed policy](./managed-policy.md#permission-modes); modes above the cap show who manages them.
+
Approve or reject requests in the conversation to let the agent continue. Permission modes do
not prevent the agent from asking questions about the task. Subagent approval requests appear in
the parent conversation with the subagent's name, so you can respond without switching threads.
diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md
index c7e69989e04..259f58c00e5 100644
--- a/docs/user/remote-access.md
+++ b/docs/user/remote-access.md
@@ -189,7 +189,7 @@ The mapping created by `pair --tailscale` persists across restarts. Remove its
default-port mapping with:
```bash
-tailscale serve --https=443 off
+tailscale serve --https=443 --set-path=/ off
```
If that port is already in use, choose another with
diff --git a/docs/user/telemetry.md b/docs/user/telemetry.md
index aeec380e8dd..9e70561332e 100644
--- a/docs/user/telemetry.md
+++ b/docs/user/telemetry.md
@@ -18,6 +18,9 @@ environment before starting it. Relay tracing also stops when `T3CODE_OTEL_SDK_D
`OTEL_SDK_DISABLED` turns OpenTelemetry export off. The web app in a browser, including one the
`t3` CLI opens, does not read these variables.
+An administrator can turn product events and relay tracing off for every user on a machine with
+a [managed policy](./managed-policy.md#other-capabilities).
+
The desktop app reads `T3CODE_TELEMETRY_ENABLED` from your shell profile (for example `~/.zshrc`) on macOS and
Linux, so export it there and restart the app. On Windows, set it as a user environment variable.
diff --git a/knip.jsonc b/knip.jsonc
index 615581793fb..e7289c39147 100644
--- a/knip.jsonc
+++ b/knip.jsonc
@@ -62,7 +62,12 @@
// The Vite+ web build prerequisite.
// Native and disk-loaded provider packages stay external to the bundle; the
// CLI archive and desktop sidecar stage them from this manifest.
- "ignoreDependencies": ["@effect/platform-node-shared", "@t3tools/web", "@napi-rs/keyring"],
+ "ignoreDependencies": [
+ "@effect/platform-node-shared",
+ "@t3tools/web",
+ "@napi-rs/keyring",
+ "ffi-rs",
+ ],
},
"apps/desktop": {
// Electron loads these bundles by filename rather than importing them.
diff --git a/packages/contracts/src/auth.ts b/packages/contracts/src/auth.ts
index 4037e6cc128..555fa7e90b2 100644
--- a/packages/contracts/src/auth.ts
+++ b/packages/contracts/src/auth.ts
@@ -8,6 +8,7 @@ import {
ClientWebDeployment,
TrimmedNonEmptyString,
} from "./baseSchemas.ts";
+import { RuntimeMode } from "./providerPolicy.ts";
export const ServerAuthPolicy = Schema.Literals([
"desktop-managed-local",
@@ -504,6 +505,10 @@ export const AuthMcpApprovalDetails = Schema.Struct({
csrfToken: Schema.optionalKey(Schema.String),
/** Only scopes held by this session qualify; others need a pairing code. Absent with `csrfToken`. */
oneClickAccess: Schema.optionalKey(Schema.Array(AuthMcpClientAccess)),
+ /** A managed policy's runtime-mode ceiling; the page loads without the server's config. */
+ runtimeModeCeiling: Schema.optionalKey(
+ Schema.Struct({ organization: Schema.String, maxRuntimeMode: RuntimeMode }),
+ ),
});
export type AuthMcpApprovalDetails = typeof AuthMcpApprovalDetails.Type;
diff --git a/packages/contracts/src/environmentHttp.ts b/packages/contracts/src/environmentHttp.ts
index 30c33deebd5..160b8266488 100644
--- a/packages/contracts/src/environmentHttp.ts
+++ b/packages/contracts/src/environmentHttp.ts
@@ -345,6 +345,8 @@ const EnvironmentScopedOperationErrors = [
] as const;
const EnvironmentPairingCredentialErrors = [
EnvironmentRequestInvalidError,
+ // The managed policy does not allow remote clients.
+ EnvironmentHttpForbiddenError,
...EnvironmentScopedOperationErrors,
] as const;
const EnvironmentSessionRevokeErrors = [
diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts
index f00976d243b..f2d88e96470 100644
--- a/packages/contracts/src/index.ts
+++ b/packages/contracts/src/index.ts
@@ -28,6 +28,7 @@ export * from "./model.ts";
export * from "./keybindings.ts";
export * from "./server.ts";
export * from "./settings.ts";
+export * from "./managedPolicy.ts";
export * from "./git.ts";
export * from "./vcs.ts";
export * from "./sourceControl.ts";
diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts
index 0466f245844..59f8fd12c3f 100644
--- a/packages/contracts/src/ipc.ts
+++ b/packages/contracts/src/ipc.ts
@@ -282,6 +282,8 @@ export interface DesktopUpdateState {
errorContext: "check" | "download" | "install" | null;
canRetry: boolean;
notAppliedVersion?: string;
+ /** Off only because a managed policy rules out this channel; switching channels turns it on. */
+ channelBlockedByPolicy?: true;
}
export interface DesktopUpdateReleaseNote {
diff --git a/packages/contracts/src/managedPolicy.ts b/packages/contracts/src/managedPolicy.ts
new file mode 100644
index 00000000000..7d1c7ed8b8a
--- /dev/null
+++ b/packages/contracts/src/managedPolicy.ts
@@ -0,0 +1,244 @@
+import * as Schema from "effect/Schema";
+import * as Struct from "effect/Struct";
+
+import { TrimmedNonEmptyString } from "./baseSchemas.ts";
+import { ProviderDriverKind, ProviderInstanceEnvironmentVariableName } from "./providerInstance.ts";
+import { isRuntimeModeAbove, RuntimeMode } from "./providerPolicy.ts";
+
+/**
+ * One server setting an administrator manages, keyed in the policy by its dot path in the
+ * encoded `ServerSettings` (for example `storageCleanup.logsAfterDays`). `locked: false`
+ * replaces the built-in default; `locked: true` also stops users and agents from changing it.
+ */
+export const ManagedPolicySetting = Schema.Struct({
+ value: Schema.Unknown,
+ locked: Schema.Boolean,
+});
+export type ManagedPolicySetting = typeof ManagedPolicySetting.Type;
+
+/**
+ * Fields an administrator pins on every instance of one driver, merged over the user's instance
+ * when settings are read. `binaryPath` and `launchArgs` land in the driver's `config`, so a driver
+ * without that config field rejects the policy. `locked: false` fills only what the user left empty.
+ */
+export const ManagedProviderInstance = Schema.Struct({
+ locked: Schema.Boolean,
+ environment: Schema.optionalKey(
+ Schema.Array(
+ Schema.Struct({ name: ProviderInstanceEnvironmentVariableName, value: Schema.String }),
+ ),
+ ),
+ binaryPath: Schema.optionalKey(TrimmedNonEmptyString),
+ launchArgs: Schema.optionalKey(TrimmedNonEmptyString),
+});
+export type ManagedProviderInstance = typeof ManagedProviderInstance.Type;
+
+export const ManagedProviderLimits = Schema.Struct({
+ /** Only these drivers run; instances of any other driver show as unavailable. */
+ allowedDrivers: Schema.optionalKey(Schema.NonEmptyArray(ProviderDriverKind)),
+ instances: Schema.optionalKey(Schema.Record(ProviderDriverKind, ManagedProviderInstance)),
+});
+export type ManagedProviderLimits = typeof ManagedProviderLimits.Type;
+
+/**
+ * How T3 Code updates itself. `auto` is the default: it checks, and installs only when a user
+ * asks. `off` never checks, for machines that get T3 Code through MDM.
+ */
+export const ManagedUpdatesMode = Schema.Literals(["auto", "off"]);
+export type ManagedUpdatesMode = typeof ManagedUpdatesMode.Type;
+
+const HttpsUrl = TrimmedNonEmptyString.check(
+ Schema.makeFilter((value: string) => /^https:\/\/[^\s/]+/i.test(value.trim()), {
+ expected: "an https URL",
+ }),
+);
+
+export const ManagedUpdatesPolicy = Schema.Struct({
+ mode: ManagedUpdatesMode,
+ /** A generic electron-updater feed the desktop app updates from instead of GitHub. */
+ feedUrl: Schema.optionalKey(HttpsUrl),
+ /** `false` makes the nightly channel unavailable. */
+ allowNightly: Schema.optionalKey(Schema.Boolean),
+});
+export type ManagedUpdatesPolicy = typeof ManagedUpdatesPolicy.Type;
+
+/** A kind of client the server may accept, mapped onto `ServerAuthPolicy`. */
+export const ManagedPolicyClient = Schema.Literals(["desktop", "local-browser", "remote"]);
+export type ManagedPolicyClient = typeof ManagedPolicyClient.Type;
+
+/**
+ * Restrictions that are not settings: users cannot opt out of them anywhere. For the boolean
+ * capabilities, omitted means allowed and only `false` restricts.
+ */
+export const ManagedPolicyLimits = Schema.Struct({
+ /** The broadest runtime mode any thread may be created in, switched to, or run turns in. */
+ maxRuntimeMode: Schema.optionalKey(RuntimeMode),
+ /** Clients the server accepts. Without `remote`, nothing off this machine can pair. */
+ clients: Schema.optionalKey(Schema.NonEmptyArray(ManagedPolicyClient)),
+ /** `false` turns T3 Connect off and unlinks this machine. */
+ connect: Schema.optionalKey(Schema.Boolean),
+ webhookTasks: Schema.optionalKey(Schema.Boolean),
+ /** Can only turn product analytics off, never force it on. */
+ telemetry: Schema.optionalKey(Schema.Boolean),
+ browserCookieImport: Schema.optionalKey(Schema.Boolean),
+ providers: Schema.optionalKey(ManagedProviderLimits),
+ updates: Schema.optionalKey(ManagedUpdatesPolicy),
+});
+export type ManagedPolicyLimits = typeof ManagedPolicyLimits.Type;
+
+/** The limits clients see: what the server enforces, which can be broader than the file says. */
+export const ManagedPolicySummaryLimits = Schema.Struct({
+ maxRuntimeMode: Schema.optionalKey(RuntimeMode),
+ clients: Schema.optionalKey(Schema.NonEmptyArray(ManagedPolicyClient)),
+ /** `false` also when `clients` leaves out `remote`, since Connect is remote access. */
+ connect: Schema.optionalKey(Schema.Boolean),
+ webhookTasks: Schema.optionalKey(Schema.Boolean),
+ telemetry: Schema.optionalKey(Schema.Boolean),
+ browserCookieImport: Schema.optionalKey(Schema.Boolean),
+ providers: Schema.optionalKey(
+ Schema.Struct({
+ /** Absent means every driver is allowed. */
+ allowedDrivers: Schema.optionalKey(Schema.NonEmptyArray(ProviderDriverKind)),
+ /**
+ * Per driver, the instance fields users cannot change, as dot paths into the instance
+ * envelope: `config.binaryPath`, `config.launchArgs`, `environment.<NAME>`. A bare
+ * `environment` means every variable, as under `maxRuntimeMode`, where each driver's
+ * launch configuration belongs to the administrator.
+ */
+ lockedInstanceFields: Schema.optionalKey(
+ Schema.Record(ProviderDriverKind, Schema.Array(Schema.String)),
+ ),
+ }),
+ ),
+ /** No `feedUrl`: it can carry a token, and only the desktop app, which reads the file, uses it. */
+ updates: Schema.optionalKey(ManagedUpdatesPolicy.mapFields(Struct.omit(["feedUrl"]))),
+});
+export type ManagedPolicySummaryLimits = typeof ManagedPolicySummaryLimits.Type;
+
+/**
+ * The machine-wide policy file an administrator deploys. Decoded with excess properties
+ * rejected: a key this build does not know might be a restriction it cannot enforce, and
+ * starting anyway would look managed without being managed.
+ */
+export const ManagedPolicyDocument = Schema.Struct({
+ schemaVersion: Schema.Literal(1),
+ /** Shown to users as "Managed by <organization>". */
+ organization: TrimmedNonEmptyString,
+ supportUrl: Schema.optionalKey(TrimmedNonEmptyString),
+ settings: Schema.optionalKey(Schema.Record(Schema.String, ManagedPolicySetting)),
+ limits: Schema.optionalKey(ManagedPolicyLimits),
+});
+export type ManagedPolicyDocument = typeof ManagedPolicyDocument.Type;
+
+/** What clients learn about the policy: enough to explain a locked control, no values. */
+export const ManagedPolicySummary = Schema.Struct({
+ organization: TrimmedNonEmptyString,
+ supportUrl: Schema.optionalKey(TrimmedNonEmptyString),
+ /** Dot paths into `ServerSettings` that users cannot change. */
+ lockedSettings: Schema.Array(Schema.String),
+ /** What the server enforces; a missing key means no limit. */
+ limits: Schema.optionalKey(ManagedPolicySummaryLimits),
+});
+export type ManagedPolicySummary = typeof ManagedPolicySummary.Type;
+
+/** The message every surface shows when the policy stops an update. */
+export function managedUpdatesMessage(organization: string): string {
+ return `${organization} manages T3 Code updates.`;
+}
+
+/** The message when the policy allows only stable releases. */
+export function managedNightlyDeniedMessage(organization: string): string {
+ return `${managedUpdatesMessage(organization)} Only stable releases can be installed.`;
+}
+
+/** Whether `path` is locked itself, sits inside a locked setting, or contains one. */
+export function isManagedSettingPath(
+ summary: Pick<ManagedPolicySummary, "lockedSettings"> | undefined,
+ path: string,
+): boolean {
+ if (summary === undefined) return false;
+ return summary.lockedSettings.some(
+ (locked) => locked === path || locked.startsWith(`${path}.`) || path.startsWith(`${locked}.`),
+ );
+}
+
+/** The one shape users see when policy refuses something: "Example Corp's policy does not allow webhook tasks." */
+export function managedPolicyDeniedMessage(organization: string, capability: string): string {
+ return `${organization}'s policy does not allow ${capability}.`;
+}
+
+const RUNTIME_MODE_LABELS: Record<RuntimeMode, string> = {
+ "approval-required": "Supervised",
+ "auto-accept-edits": "Auto-accept edits",
+ auto: "Auto",
+ "full-access": "Full access",
+};
+
+/** "Example Corp limits threads to Auto-accept edits." */
+export function managedRuntimeModeCeilingMessage(organization: string, ceiling: RuntimeMode) {
+ return `${organization} limits threads to ${RUNTIME_MODE_LABELS[ceiling]}.`;
+}
+
+/** Why `mode` is unavailable on an environment with `summary`, or undefined when it is allowed. */
+export function managedRuntimeModeDenial(
+ summary: ManagedPolicySummary | undefined,
+ mode: RuntimeMode,
+): string | undefined {
+ const ceiling = summary?.limits?.maxRuntimeMode;
+ return summary !== undefined && ceiling !== undefined && isRuntimeModeAbove(mode, ceiling)
+ ? managedRuntimeModeCeilingMessage(summary.organization, ceiling)
+ : undefined;
+}
+
+/**
+ * `mode` when the policy allows it, else the broadest of `modes` (narrowest first) that it does:
+ * where a thread or task above the ceiling switches down to. Undefined when none is allowed.
+ */
+export function clampManagedRuntimeMode(
+ summary: ManagedPolicySummary | undefined,
+ mode: RuntimeMode,
+ modes: ReadonlyArray<RuntimeMode> = RuntimeMode.literals,
+): RuntimeMode | undefined {
+ const ceiling = summary?.limits?.maxRuntimeMode;
+ if (!isRuntimeModeAbove(mode, ceiling)) return mode;
+ return modes.findLast((candidate) => !isRuntimeModeAbove(candidate, ceiling));
+}
+
+const CAPABILITY_LABELS = {
+ remoteClients: "connecting from other devices",
+ connect: "T3 Connect",
+ webhookTasks: "webhook tasks",
+ browserCookieImport: "importing browser cookies",
+} as const;
+
+/** Why a capability is unavailable on an environment with `summary`, or undefined when allowed. */
+export function managedCapabilityDenial(
+ summary: ManagedPolicySummary | undefined,
+ capability: keyof typeof CAPABILITY_LABELS,
+): string | undefined {
+ const limits = summary?.limits;
+ if (summary === undefined || limits === undefined) return undefined;
+ const denied =
+ capability === "remoteClients"
+ ? limits.clients !== undefined && !limits.clients.includes("remote")
+ : limits[capability] === false;
+ return denied
+ ? managedPolicyDeniedMessage(summary.organization, CAPABILITY_LABELS[capability])
+ : undefined;
+}
+
+/** Whether the policy lets `driver` run; clients name it with their own provider label. */
+export function isManagedDriverAllowed(
+ summary: ManagedPolicySummary | undefined,
+ driver: ProviderDriverKind,
+): boolean {
+ const allowed = summary?.limits?.providers?.allowedDrivers;
+ return allowed === undefined || allowed.includes(driver);
+}
+
+/** Why updates are unavailable on an environment with `summary`, or undefined when allowed. */
+export function managedUpdatesDenial(summary: ManagedPolicySummary | undefined) {
+ return summary?.limits?.updates?.mode === "off"
+ ? managedUpdatesMessage(summary.organization)
+ : undefined;
+}
diff --git a/packages/contracts/src/orchestratorMcp.ts b/packages/contracts/src/orchestratorMcp.ts
index 438a3fe2def..1d6d7f3d679 100644
--- a/packages/contracts/src/orchestratorMcp.ts
+++ b/packages/contracts/src/orchestratorMcp.ts
@@ -690,6 +690,9 @@ export const OrchestratorMcpScheduledTask = Schema.Struct({
"Public URL for the sender. Absent: no T3 Connect tunnel. The user must enable T3 Connect remote access.",
}),
webhookSignature: Schema.optional(Schema.Literals(["none", "set"])),
+ blockedByPolicy: Schema.optional(Schema.String).annotate({
+ description: "Present when an administrator's policy stops this task from running.",
+ }),
});
export type OrchestratorMcpScheduledTask = typeof OrchestratorMcpScheduledTask.Type;
diff --git a/packages/contracts/src/providerPolicy.ts b/packages/contracts/src/providerPolicy.ts
index b7607fec3e8..1b94f43aabd 100644
--- a/packages/contracts/src/providerPolicy.ts
+++ b/packages/contracts/src/providerPolicy.ts
@@ -31,6 +31,17 @@ export const RuntimeMode = Schema.Literals([
export type RuntimeMode = typeof RuntimeMode.Type;
export const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
+const RUNTIME_MODE_RANK: Record<RuntimeMode, number> = {
+ "approval-required": 0,
+ "auto-accept-edits": 1,
+ auto: 2,
+ "full-access": 3,
+};
+
+/** Whether `mode` grants the agent more than `ceiling`; no ceiling allows every mode. */
+export const isRuntimeModeAbove = (mode: RuntimeMode, ceiling: RuntimeMode | undefined): boolean =>
+ ceiling !== undefined && RUNTIME_MODE_RANK[mode] > RUNTIME_MODE_RANK[ceiling];
+
export const ProviderInteractionMode = Schema.Literals(["default", "plan"]);
export type ProviderInteractionMode = typeof ProviderInteractionMode.Type;
export const DEFAULT_PROVIDER_INTERACTION_MODE: ProviderInteractionMode = "default";
diff --git a/packages/contracts/src/relayClient.ts b/packages/contracts/src/relayClient.ts
index 0f8762cf06d..c28f56ce80d 100644
--- a/packages/contracts/src/relayClient.ts
+++ b/packages/contracts/src/relayClient.ts
@@ -47,6 +47,7 @@ export const RelayClientInstallFailureReasonSchema = Schema.Literals([
"download_failed",
"invalid_checksum",
"install_locked",
+ "managed_by_policy",
"override_missing",
"unsupported_platform",
"validation_failed",
diff --git a/packages/contracts/src/scheduledTask.ts b/packages/contracts/src/scheduledTask.ts
index 5fbbc48301d..6d80c962a1f 100644
--- a/packages/contracts/src/scheduledTask.ts
+++ b/packages/contracts/src/scheduledTask.ts
@@ -246,6 +246,8 @@ export const ScheduledTask = Schema.Struct({
lastRunError: Schema.NullOr(Schema.String),
runCount: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
webhook: Schema.optional(ScheduledTaskWebhookEndpoint),
+ /** Why the task cannot run regardless of `enabled`, such as a managed policy refusing webhooks. */
+ blockedByPolicy: Schema.optionalKey(Schema.String),
});
export type ScheduledTask = typeof ScheduledTask.Type;
diff --git a/packages/contracts/src/server.ts b/packages/contracts/src/server.ts
index c36f724b823..e027930c116 100644
--- a/packages/contracts/src/server.ts
+++ b/packages/contracts/src/server.ts
@@ -23,6 +23,7 @@ import {
ResolvedKeybindingsConfig,
} from "./keybindings.ts";
import { EditorId, FileManagerRevealKind, RemoteOpenTarget } from "./editor.ts";
+import { ManagedPolicySummary } from "./managedPolicy.ts";
import { ModelCapabilities, ProviderOptionDescriptor } from "./model.ts";
import { RuntimeMode } from "./providerPolicy.ts";
import { ProviderDriverKind, ProviderInstanceId } from "./providerInstance.ts";
@@ -620,6 +621,8 @@ export const ServerConfig = Schema.Struct({
directEndpoints: Schema.optionalKey(ForwardCompatibleArray(ServerDirectEndpoint)),
observability: ServerObservability,
settings: ServerSettings,
+ /** Present when an administrator's policy file manages this environment. */
+ managedPolicy: Schema.optionalKey(ManagedPolicySummary),
shellResumeCompletionMarker: Schema.optionalKey(Schema.Boolean),
/**
* The shell can leave idle subagent children out of snapshots (`omitIdleSubagents`), and
diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts
index fff25149b2e..e90b977fae3 100644
--- a/packages/contracts/src/settings.ts
+++ b/packages/contracts/src/settings.ts
@@ -1482,9 +1482,15 @@ export const ServerSettingsOperation = Schema.Literals([
"write-secret-provider",
"write-file",
"prepare-directory",
+ "write-managed-setting",
+ "use-disallowed-provider",
]);
export type ServerSettingsOperation = typeof ServerSettingsOperation.Type;
+/** Why a provider the administrator's policy leaves out cannot be used. */
+export const disallowedProviderMessage = (organization: string | undefined, label: string) =>
+ `${organization === undefined ? "Your organization" : `${organization}'s`} policy does not allow the ${label} provider.`;
+
export class ServerSettingsError extends Schema.TaggedError<ServerSettingsError>()(
"ServerSettingsError",
{
@@ -1492,10 +1498,24 @@ export class ServerSettingsError extends Schema.TaggedError<ServerSettingsError>
operation: ServerSettingsOperation,
providerInstanceId: Schema.optional(Schema.String),
environmentVariable: Schema.optional(Schema.String),
+ /** For `write-managed-setting`: the locked dot path and who manages it. */
+ managedSetting: Schema.optional(Schema.String),
+ managedBy: Schema.optional(Schema.String),
+ /** For `use-disallowed-provider`: the provider's name as users know it. */
+ providerLabel: Schema.optional(Schema.String),
cause: Schema.optional(Schema.Defect()),
},
) {
override get message(): string {
+ if (this.operation === "write-managed-setting") {
+ return `${this.managedSetting ?? "This setting"} is managed by ${this.managedBy ?? "your organization"} and cannot be changed.`;
+ }
+ if (this.operation === "use-disallowed-provider") {
+ return disallowedProviderMessage(
+ this.managedBy,
+ this.providerLabel ?? this.providerInstanceId ?? "this",
+ );
+ }
const provider =
this.providerInstanceId === undefined ? "" : ` for provider ${this.providerInstanceId}`;
const variable =
diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts
index bc34b9fd65f..7b24d9ef09a 100644
--- a/packages/provider-acp/src/server/adapter.ts
+++ b/packages/provider-acp/src/server/adapter.ts
@@ -27,9 +27,11 @@ import {
type ProviderRequestKind,
type ProviderThreadId,
type ProviderUserInputAnswers,
+ type RuntimeMode,
type RuntimeRequestId,
type ThreadTokenUsageSnapshot,
type ThreadId,
+ isRuntimeModeAbove,
type TurnTokenUsage,
} from "@t3tools/contracts";
import { AgentScope, AgentScopeThreadId } from "@t3tools/shared/AgentScope";
@@ -329,6 +331,11 @@ export interface AcpAdapterV2Flavor {
readonly sessionModeForPolicy?: (
policy: ProviderAdapter.ProviderAdapterV2RuntimePolicy,
) => string | undefined;
+ /**
+ * The runtime mode a native session mode grants, for flavors whose modes are permission levels.
+ * Under a policy ceiling, a mode the user picks that this does not place under it is not applied.
+ */
+ readonly runtimeModeForSessionMode?: (modeId: string) => RuntimeMode | undefined;
readonly clientFileSystem?: {
readonly readTextFile: (
request: EffectAcpSchema.ReadTextFileRequest,
@@ -6876,10 +6883,33 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
};
});
}
- const optionSelections = (modelSelection.options ?? []).map((selection) =>
- selection.value === ACP_EMPTY_OPTION_VALUE ? { ...selection, value: "" } : selection,
- );
const configOptions = yield* runtime.getConfigOptions;
+ // Under a policy ceiling, a mode the user picks applies only when the flavor can place
+ // it under the ceiling; an unknown mode could be the agent's own skip-approval mode.
+ const ceiling = runtimePolicy.maxRuntimeMode;
+ const isModeChoice = (id: string) =>
+ id === ACP_SESSION_MODE_OPTION_ID ||
+ configOptions.some(
+ (option) =>
+ option.id === id &&
+ (option.category === "mode" || option.category === "collaboration_mode"),
+ );
+ const withinCeiling = (selection: { readonly id: string; readonly value: unknown }) => {
+ if (ceiling === undefined || ceiling === "full-access" || !isModeChoice(selection.id)) {
+ return true;
+ }
+ const granted =
+ typeof selection.value === "string"
+ ? flavor.runtimeModeForSessionMode?.(selection.value)
+ : undefined;
+ return granted !== undefined && !isRuntimeModeAbove(granted, ceiling);
+ };
+ const optionSelections = (modelSelection.options ?? []).flatMap((selection) => {
+ if (!withinCeiling(selection)) return [];
+ return [
+ selection.value === ACP_EMPTY_OPTION_VALUE ? { ...selection, value: "" } : selection,
+ ];
+ });
const availableConfigIds = new Set(configOptions.map((option) => option.id));
const hasNativeConfigWithSyntheticModeId = availableConfigIds.has(
ACP_SESSION_MODE_OPTION_ID,
diff --git a/packages/provider-core/src/server/ProviderAdapter.ts b/packages/provider-core/src/server/ProviderAdapter.ts
index cadf4173a60..b83ea279734 100644
--- a/packages/provider-core/src/server/ProviderAdapter.ts
+++ b/packages/provider-core/src/server/ProviderAdapter.ts
@@ -51,6 +51,11 @@ export const ProviderAdapterV2RuntimePolicy = Schema.Struct({
cwd: Schema.NullOr(Schema.String),
approvalPolicy: Schema.optional(Schema.Unknown),
sandboxPolicy: Schema.optional(Schema.Unknown),
+ /**
+ * The administrator's ceiling, when a managed policy sets one. `runtimeMode` is already under
+ * it; adapters use it to refuse native mode choices a user makes beside T3 Code's own.
+ */
+ maxRuntimeMode: Schema.optional(RuntimeMode),
});
export type ProviderAdapterV2RuntimePolicy = typeof ProviderAdapterV2RuntimePolicy.Type;
diff --git a/packages/provider-core/src/server/instanceEnvironment.test.ts b/packages/provider-core/src/server/instanceEnvironment.test.ts
index 7f70cdddad5..114905d3f21 100644
--- a/packages/provider-core/src/server/instanceEnvironment.test.ts
+++ b/packages/provider-core/src/server/instanceEnvironment.test.ts
@@ -81,4 +81,31 @@ describe("mergeProviderInstanceEnvironment", () => {
});
}),
);
+
+ it.effect("replaces every inherited spelling of a name on Windows, and only there", () =>
+ Effect.gen(function* () {
+ const merge = (platform: NodeJS.Platform) =>
+ mergeProviderInstanceEnvironment(
+ [{ name: "Https_Proxy", value: "http://gateway", sensitive: false }],
+ { HTTPS_PROXY: "http://mine", PATH: "/bin" },
+ ).pipe(Effect.provideService(HostProcess.Platform, platform));
+ // A home variable in another spelling is still expanded.
+ expect(
+ yield* mergeProviderInstanceEnvironment(
+ [{ name: "Codex_Home", value: "~/corp", sensitive: false }],
+ {},
+ ).pipe(
+ Effect.provideService(HostProcess.Platform, "win32"),
+ Effect.provideService(HostProcess.HomeDirectory, "/home/ada"),
+ ),
+ ).toEqual({ CODEX_HOME: "/home/ada/corp" });
+ // Upper case sorts first, so it also wins where a spawn merges the parent environment back.
+ expect(yield* merge("win32")).toEqual({ HTTPS_PROXY: "http://gateway", PATH: "/bin" });
+ expect(yield* merge("linux")).toEqual({
+ HTTPS_PROXY: "http://mine",
+ Https_Proxy: "http://gateway",
+ PATH: "/bin",
+ });
+ }),
+ );
});
diff --git a/packages/provider-core/src/server/instanceEnvironment.ts b/packages/provider-core/src/server/instanceEnvironment.ts
index 4a73f678da0..470f7e70dc6 100644
--- a/packages/provider-core/src/server/instanceEnvironment.ts
+++ b/packages/provider-core/src/server/instanceEnvironment.ts
@@ -13,12 +13,22 @@ export const mergeProviderInstanceEnvironment = Effect.fn(function* (
}
const home = yield* HostProcess.HomeDirectory;
+ const windows = (yield* HostProcess.Platform) === "win32";
const next: NodeJS.ProcessEnv = { ...baseEnv };
for (const variable of environment) {
// An unresolved secret reference carries no value; the registry resolves it for the provider.
if (typeof variable.value !== "string") continue;
- next[variable.name] =
- variable.name === "CODEX_HOME" || variable.name === "CLAUDE_CONFIG_DIR"
+ // Windows reads names without regard to case, and a child gets the first spelling in sort
+ // order. Upper case sorts first, so the configured value wins even where a spawn merges the
+ // parent environment back in.
+ const name = windows ? variable.name.toUpperCase() : variable.name;
+ if (windows) {
+ for (const inherited of Object.keys(next)) {
+ if (inherited.toUpperCase() === name) delete next[inherited];
+ }
+ }
+ next[name] =
+ name === "CODEX_HOME" || name === "CLAUDE_CONFIG_DIR"
? expandHomePath(variable.value, home)
: variable.value;
}
diff --git a/packages/shared/package.json b/packages/shared/package.json
index f17f48f1c9e..19542c44590 100644
--- a/packages/shared/package.json
+++ b/packages/shared/package.json
@@ -335,6 +335,10 @@
"types": "./src/AgentScope.ts",
"import": "./src/AgentScope.ts"
},
+ "./managedPolicyFile": {
+ "types": "./src/managedPolicyFile.ts",
+ "import": "./src/managedPolicyFile.ts"
+ },
"./HostProcess": {
"types": "./src/HostProcess.ts",
"import": "./src/HostProcess.ts"
@@ -529,6 +533,7 @@
"@noble/hashes": "catalog:",
"@t3tools/contracts": "workspace:*",
"effect": "catalog:",
+ "ffi-rs": "1.3.2",
"jose": "catalog:",
"mdast-util-directive": "catalog:",
"mdast-util-to-hast": "^13.2.1",
diff --git a/packages/shared/src/managedPolicyFile.test.ts b/packages/shared/src/managedPolicyFile.test.ts
new file mode 100644
index 00000000000..f6cf7ef8c2c
--- /dev/null
+++ b/packages/shared/src/managedPolicyFile.test.ts
@@ -0,0 +1,190 @@
+import { assert, describe, it } from "@effect/vitest";
+import * as Effect from "effect/Effect";
+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 { ChildProcessSpawner } from "effect/process";
+
+import * as HostProcess from "./HostProcess.ts";
+
+import {
+ MACOS_MANAGED_PREFERENCES_PATH,
+ managedPolicyPath,
+ readManagedPolicy,
+ WINDOWS_POLICY_KEY,
+ layerWindowsRegistry,
+ WindowsRegistry,
+ WindowsRegistryError,
+} from "./managedPolicyFile.ts";
+
+const policy = JSON.stringify({ schemaVersion: 1, organization: "Example Corp" });
+
+/** What a command prints and exits with. */
+type Result = { readonly stdout: string; readonly exitCode: number };
+
+/** The registry's `Policy` value: its text, absent, or the Win32 error reading it fails with. */
+type RegistryAnswer = string | undefined | { readonly code?: number };
+
+/** Files that exist, what a command prints and exits with by command name, and the registry. */
+const machine = (
+ files: Readonly<Record<string, string>>,
+ commands: Readonly<Record<string, Result>>,
+ registry: RegistryAnswer,
+) =>
+ Layer.mergeAll(
+ Layer.succeed(
+ WindowsRegistry,
+ WindowsRegistry.of({
+ readMachineString: () =>
+ typeof registry === "object"
+ ? Effect.fail(new WindowsRegistryError(registry))
+ : Effect.succeed(registry),
+ }),
+ ),
+ FileSystem.layerNoop({
+ exists: (path) => Effect.succeed(path in files),
+ readFileString: (path) => Effect.succeed(files[path] ?? ""),
+ }),
+ Layer.succeed(
+ ChildProcessSpawner.ChildProcessSpawner,
+ ChildProcessSpawner.make((command) => {
+ const { command: name } = command as unknown as { readonly command: string };
+ const result = commands[name] ?? { stdout: "", exitCode: 127 };
+ return Effect.succeed(
+ ChildProcessSpawner.makeHandle({
+ pid: ChildProcessSpawner.ProcessId(1),
+ exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(result.exitCode)),
+ isRunning: Effect.succeed(false),
+ kill: () => Effect.void,
+ unref: Effect.succeed(Effect.void),
+ stdin: Sink.drain,
+ stdout: Stream.make(new TextEncoder().encode(result.stdout)),
+ stderr: Stream.empty,
+ all: Stream.empty,
+ getInputFd: () => Sink.drain,
+ getOutputFd: () => Stream.empty,
+ }),
+ );
+ }),
+ ),
+ );
+
+const read = (
+ platform: NodeJS.Platform,
+ files: Readonly<Record<string, string>>,
+ commands: Parameters<typeof machine>[1] = {},
+ registry: RegistryAnswer = undefined,
+) =>
+ readManagedPolicy(platform).pipe(
+ Effect.map((found) => found?.source),
+ Effect.catchTags({
+ ManagedPolicyFileError: (error) => Effect.succeed(`error: ${error.reason}`),
+ }),
+ Effect.provide(machine(files, commands, registry)),
+ );
+
+describe("readManagedPolicy", () => {
+ it.effect("reads a macOS configuration profile, and refuses one beside a policy file", () =>
+ Effect.gen(function* () {
+ const plutil = { "/usr/bin/plutil": { stdout: policy, exitCode: 0 } };
+ const profile = { [MACOS_MANAGED_PREFERENCES_PATH]: "<binary plist>" };
+ const file = { [managedPolicyPath("darwin")]: policy };
+
+ assert.equal(yield* read("darwin", profile, plutil), MACOS_MANAGED_PREFERENCES_PATH);
+ const plist = (contents: object) => ({
+ "/usr/bin/plutil": { stdout: JSON.stringify(contents), exitCode: 0 },
+ });
+ const settings = JSON.parse(policy);
+ // What macOS 27 writes for a manually installed profile.
+ assert.equal(
+ yield* read(
+ "darwin",
+ profile,
+ plist({ ...settings, PayloadUUID: "e8c7f49b", _manualProfile: true }),
+ ),
+ MACOS_MANAGED_PREFERENCES_PATH,
+ );
+ assert.equal(
+ yield* read("darwin", profile, plist({ Forced: [{ mcx_preference_settings: settings }] })),
+ MACOS_MANAGED_PREFERENCES_PATH,
+ );
+ // Keys beside the wrapper, or a second entry, are refused rather than dropped or merged.
+ for (const ambiguous of [
+ { Forced: [{ mcx_preference_settings: settings }], limits: { telemetry: false } },
+ { Forced: [{ mcx_preference_settings: settings }, { mcx_preference_settings: settings }] },
+ ]) {
+ assert.include(
+ yield* read("darwin", profile, plist(ambiguous)),
+ "does not match the policy schema",
+ );
+ }
+ assert.equal(yield* read("darwin", file), managedPolicyPath("darwin"));
+ const typo = JSON.stringify({ ...settings, limits: { maxRuntimeMod: "auto" } });
+ assert.include(
+ yield* read("darwin", { [managedPolicyPath("darwin")]: typo }),
+ '["limits"]["maxRuntimeMod"]',
+ );
+ assert.isUndefined(yield* read("darwin", {}));
+ assert.include(
+ yield* read("darwin", { ...profile, ...file }, plutil),
+ "deploy the policy one way",
+ );
+ // A profile plutil cannot convert fails closed rather than reading as no policy.
+ assert.include(
+ yield* read("darwin", profile, { "/usr/bin/plutil": { stdout: "", exitCode: 1 } }),
+ "cannot be read",
+ );
+ }),
+ );
+
+ it.effect(
+ "reads the Windows Policies registry value, and treats only an absent one as none",
+ () =>
+ Effect.gen(function* () {
+ const file = { [managedPolicyPath("win32")]: policy };
+ const win32 = (files: Readonly<Record<string, string>>, registry: RegistryAnswer) =>
+ read("win32", files, {}, registry);
+
+ assert.equal(yield* win32({}, policy), WINDOWS_POLICY_KEY);
+ assert.isUndefined(yield* win32({}, undefined));
+ assert.equal(yield* win32(file, undefined), managedPolicyPath("win32"));
+ assert.include(yield* win32(file, policy), "deploy the policy one way");
+ // A read that fails, here access denied, is not read as no policy, file or not.
+ for (const files of [{}, file]) {
+ assert.include(
+ yield* win32(files, { code: 5 }),
+ "the registry cannot be read (Windows error 5)",
+ );
+ }
+ assert.include(yield* win32({}, {}), "cannot load its registry reader; reinstall T3 Code");
+ assert.include(
+ yield* win32({}, { code: 1630 }),
+ "its Policy value is not a string (REG_SZ)",
+ );
+ assert.include(yield* win32({}, "{ not json"), "does not match the policy schema");
+ }),
+ );
+
+ it.effect.runIf(HostProcess.Platform.defaultValue() === "win32")(
+ "reads REG_SZ values through the Win32 API, and refuses other types",
+ () =>
+ Effect.gen(function* () {
+ const registry = yield* WindowsRegistry;
+ const version = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion";
+ assert.match((yield* registry.readMachineString(version, "ProductName")) ?? "", /Windows/);
+ assert.isUndefined(yield* registry.readMachineString(version, "T3CodeNoSuchValue"));
+ assert.isUndefined(
+ yield* registry.readMachineString("SOFTWARE\\T3CodeNoSuchKey", "Policy"),
+ );
+ // REG_DWORD, and REG_EXPAND_SZ, which would otherwise expand the user's variables.
+ for (const [key, value] of [
+ [version, "CurrentMajorVersionNumber"],
+ ["SOFTWARE\\Microsoft\\Windows\\CurrentVersion", "ProgramFilesPath"],
+ ] as const) {
+ const error = yield* registry.readMachineString(key, value).pipe(Effect.flip);
+ assert.equal(error.code, 1630);
+ }
+ }).pipe(Effect.provide(layerWindowsRegistry(() => import("ffi-rs")))),
+ );
+});
diff --git a/packages/shared/src/managedPolicyFile.ts b/packages/shared/src/managedPolicyFile.ts
new file mode 100644
index 00000000000..e7e44608d83
--- /dev/null
+++ b/packages/shared/src/managedPolicyFile.ts
@@ -0,0 +1,330 @@
+import { ManagedPolicyDocument } from "@t3tools/contracts";
+import * as Cause from "effect/Cause";
+import * as Context from "effect/Context";
+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 Schema from "effect/Schema";
+import * as Stream from "effect/Stream";
+import { ChildProcess, ChildProcessSpawner } from "effect/process";
+
+import * as HostProcess from "./HostProcess.ts";
+
+export class ManagedPolicyFileError extends Schema.TaggedError<ManagedPolicyFileError>()(
+ "ManagedPolicyFileError",
+ {
+ path: Schema.String,
+ reason: Schema.String,
+ cause: Schema.optional(Schema.Defect()),
+ },
+) {
+ override get message(): string {
+ return `T3 Code cannot use the managed policy at ${this.path}: ${this.reason}. It will not start until an administrator fixes this.`;
+ }
+}
+
+/** The system path an administrator deploys the policy to on `platform`. */
+export function managedPolicyPath(platform: NodeJS.Platform): string {
+ switch (platform) {
+ case "darwin":
+ return "/Library/Application Support/T3Code/policy.json";
+ case "win32":
+ // Not ProgramData, where a user can create the folder first and own it; and not
+ // %ProgramFiles%, which a user can point somewhere they write.
+ return "C:\\Program Files\\T3Code\\policy.json";
+ default:
+ return "/etc/t3code/policy.json";
+ }
+}
+
+// Unknown keys may be restrictions from a newer release; refusing them keeps a file this
+// build cannot fully enforce from looking enforced.
+const decodeDocumentJsonExit = Schema.decodeUnknownExit(
+ Schema.fromJsonString(ManagedPolicyDocument),
+ { onExcessProperty: "error" },
+);
+const decodeDocumentExit = Schema.decodeUnknownExit(ManagedPolicyDocument, {
+ onExcessProperty: "error",
+});
+
+/** Decode a policy from JSON text, or from a value a profile already parsed. */
+const decodeDocument = (path: string, raw: unknown) => {
+ const decoded = typeof raw === "string" ? decodeDocumentJsonExit(raw) : decodeDocumentExit(raw);
+ if (Exit.isSuccess(decoded)) return Effect.succeed(decoded.value);
+ const error = Cause.squash(decoded.cause);
+ // The schema message names the offending key, e.g. `Expected no excess property at ["limits"]`.
+ const detail = Schema.isSchemaError(error) ? ` (${error.message.replace(/\s*\n\s*/g, " ")})` : "";
+ return Effect.fail(
+ new ManagedPolicyFileError({
+ path,
+ reason: `it is not valid JSON or does not match the policy schema${detail}`,
+ cause: decoded.cause,
+ }),
+ );
+};
+
+/** Read the policy document at `path`; a missing file means no policy. */
+export const readManagedPolicyFile = Effect.fn("readManagedPolicyFile")(function* (path: string) {
+ const fs = yield* FileSystem.FileSystem;
+ const exists = yield* fs
+ .exists(path)
+ .pipe(
+ Effect.mapError(
+ (cause) =>
+ new ManagedPolicyFileError({ path, reason: "the file cannot be checked", cause }),
+ ),
+ );
+ if (!exists) return undefined;
+ const raw = yield* fs
+ .readFileString(path)
+ .pipe(
+ Effect.mapError(
+ (cause) => new ManagedPolicyFileError({ path, reason: "the file cannot be read", cause }),
+ ),
+ );
+ return yield* decodeDocument(path, raw);
+});
+
+/** Where a configuration profile's managed preferences land on macOS. */
+export const MACOS_MANAGED_PREFERENCES_PATH =
+ "/Library/Managed Preferences/com.t3tools.t3code.plist";
+const WINDOWS_POLICY_SUBKEY = "SOFTWARE\\Policies\\T3Tools\\T3Code";
+/** The registry key Group Policy and Intune write to on Windows; `Policy` holds the JSON. */
+export const WINDOWS_POLICY_KEY = `HKLM\\${WINDOWS_POLICY_SUBKEY}`;
+// An absolute path: an earlier PATH entry could otherwise answer that there is no policy.
+const PLUTIL = "/usr/bin/plutil";
+
+export class WindowsRegistryError extends Schema.TaggedError<WindowsRegistryError>()(
+ "WindowsRegistryError",
+ {
+ /** The Win32 error, such as 5 for access denied; absent when the registry API cannot load. */
+ code: Schema.optional(Schema.Number),
+ cause: Schema.optional(Schema.Defect()),
+ },
+) {
+ override get message(): string {
+ return this.code === undefined ? "the registry API cannot load" : `Windows error ${this.code}`;
+ }
+}
+
+/**
+ * Reads the registry through the Win32 API in this process. A missing value and a failed read
+ * come back apart, and blocked registry tools such as reg.exe do not matter.
+ */
+export class WindowsRegistry extends Context.Service<
+ WindowsRegistry,
+ {
+ /** The REG_SZ `value` of HKLM\\`subkey` in the 64-bit view; undefined when either is absent. */
+ readonly readMachineString: (
+ subkey: string,
+ value: string,
+ ) => Effect.Effect<string | undefined, WindowsRegistryError>;
+ }
+>()("@t3tools/shared/managedPolicyFile/WindowsRegistry") {}
+
+// (HKEY)(LONG)0x80000002, sign-extended to 64 bits.
+const HKEY_LOCAL_MACHINE = -0x7ffffffen;
+const RRF_RT_REG_SZ = 0x2;
+const RRF_SUBKEY_WOW6464KEY = 0x10000;
+// Without it a REG_EXPAND_SZ value passes as REG_SZ, with the user's variables filled in.
+const RRF_NOEXPAND = 0x10000000;
+const ERROR_FILE_NOT_FOUND = 2;
+const ERROR_MORE_DATA = 234;
+const ERROR_UNSUPPORTED_TYPE = 1630;
+
+/**
+ * Each app passes how it loads ffi-rs: a server single-executable resolves packages on disk only
+ * through `require`, and the desktop's CommonJS bundle loads them with `import()`.
+ */
+export const layerWindowsRegistry = (loadFfi: () => Promise<typeof import("ffi-rs")>) =>
+ Layer.effect(
+ WindowsRegistry,
+ Effect.gen(function* () {
+ const architecture = yield* HostProcess.Architecture;
+ const loadGetValue = yield* Effect.cached(
+ Effect.tryPromise({
+ try: async () => {
+ // HKEY_LOCAL_MACHINE and the pointer arguments below are 64-bit.
+ if (architecture !== "x64" && architecture !== "arm64") {
+ throw new Error(`no registry access on ${architecture}`);
+ }
+ const { DataType, load, open } = await loadFfi();
+ open({ library: "t3-advapi32", path: "advapi32.dll" });
+ return (subkey: string, value: string, data: Buffer, size: Buffer): number =>
+ load({
+ library: "t3-advapi32",
+ funcName: "RegGetValueW",
+ retType: DataType.I32,
+ paramsType: [
+ DataType.BigInt,
+ DataType.WString,
+ DataType.WString,
+ DataType.U32,
+ DataType.BigInt,
+ DataType.U8Array,
+ DataType.U8Array,
+ ],
+ paramsValue: [
+ HKEY_LOCAL_MACHINE,
+ subkey,
+ value,
+ RRF_RT_REG_SZ | RRF_SUBKEY_WOW6464KEY | RRF_NOEXPAND,
+ 0n,
+ data,
+ size,
+ ],
+ });
+ },
+ catch: (cause) => new WindowsRegistryError({ cause }),
+ }),
+ );
+ return WindowsRegistry.of({
+ readMachineString: Effect.fn("WindowsRegistry.readMachineString")(
+ function* (subkey, value) {
+ const getValue = yield* loadGetValue;
+ const attempt = (bytes: number) =>
+ Effect.try({
+ try: () => {
+ const data = Buffer.alloc(bytes);
+ const size = Buffer.alloc(4);
+ size.writeUInt32LE(bytes);
+ const code = getValue(subkey, value, data, size);
+ return { code, data, bytes: size.readUInt32LE() };
+ },
+ catch: (cause) => new WindowsRegistryError({ cause }),
+ });
+ let result = yield* attempt(64 * 1024);
+ // The value grew past the buffer; the API reported the size it needs.
+ if (result.code === ERROR_MORE_DATA) result = yield* attempt(result.bytes);
+ if (result.code === ERROR_FILE_NOT_FOUND) return undefined;
+ if (result.code !== 0) return yield* new WindowsRegistryError({ code: result.code });
+ // The size counts the terminating null RegGetValueW adds.
+ return result.data.subarray(0, result.bytes).toString("utf16le").replace(/\0+$/, "");
+ },
+ ),
+ });
+ }),
+ );
+
+// A hung query must not hang startup; a timeout reads as a failed query.
+const run = Effect.fnUntraced(
+ function* (command: string, args: ReadonlyArray<string>) {
+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
+ const handle = yield* spawner.spawn(
+ ChildProcess.make(command, args, { stdin: "ignore", stderr: "ignore" }),
+ );
+ const [stdout, exitCode] = yield* Effect.all(
+ [handle.stdout.pipe(Stream.decodeText(), Stream.mkString), handle.exitCode],
+ { concurrency: 2 },
+ );
+ return { stdout, exitCode: Number(exitCode) };
+ },
+ Effect.scoped,
+ Effect.timeout(Duration.seconds(10)),
+);
+
+const decodeJsonExit = Schema.decodeUnknownExit(Schema.fromJsonString(Schema.Unknown));
+// Strict: keys beside the wrapper, or more than one entry, decode as a plain document and fail.
+const decodeForcedExit = Schema.decodeUnknownExit(
+ Schema.Struct({
+ Forced: Schema.Tuple([Schema.Struct({ mcx_preference_settings: Schema.Unknown })]),
+ }),
+ { onExcessProperty: "error" },
+);
+
+// macOS writes `PayloadUUID` and `_manualProfile` beside the profile's own keys; no policy key
+// starts with `Payload` or `_`, so dropping them cannot hide a restriction.
+const withoutProfileKeys = (value: unknown) =>
+ value === null || typeof value !== "object" || Array.isArray(value)
+ ? value
+ : Object.fromEntries(
+ Object.entries(value).filter(([key]) => !key.startsWith("Payload") && !key.startsWith("_")),
+ );
+
+/**
+ * Installed managed preferences hold the profile's keys directly, but MCX-style profiles keep
+ * them under `Forced[0].mcx_preference_settings`; read either rather than refuse a valid profile.
+ */
+function unwrapForced(json: string): unknown {
+ const parsed = decodeJsonExit(json);
+ if (Exit.isFailure(parsed)) return json;
+ const preferences = withoutProfileKeys(parsed.value);
+ const forced = decodeForcedExit(preferences);
+ return Exit.isSuccess(forced)
+ ? withoutProfileKeys(forced.value.Forced[0].mcx_preference_settings)
+ : preferences;
+}
+
+/** Read the policy a configuration profile or Group Policy set; absent means no such policy. */
+const readPlatformPolicy = Effect.fnUntraced(function* (platform: NodeJS.Platform) {
+ if (platform === "darwin") {
+ const path = MACOS_MANAGED_PREFERENCES_PATH;
+ const exists = yield* (yield* FileSystem.FileSystem)
+ .exists(path)
+ .pipe(
+ Effect.mapError(
+ (cause) =>
+ new ManagedPolicyFileError({ path, reason: "the profile cannot be checked", cause }),
+ ),
+ );
+ if (!exists) return undefined;
+ const converted = yield* run(PLUTIL, ["-convert", "json", "-o", "-", path]).pipe(
+ Effect.mapError(
+ (cause) =>
+ new ManagedPolicyFileError({ path, reason: "the profile cannot be read", cause }),
+ ),
+ );
+ if (converted.exitCode !== 0) {
+ return yield* new ManagedPolicyFileError({ path, reason: "the profile cannot be read" });
+ }
+ return { source: path, document: yield* decodeDocument(path, unwrapForced(converted.stdout)) };
+ }
+ if (platform === "win32") {
+ const path = WINDOWS_POLICY_KEY;
+ const raw = yield* (yield* WindowsRegistry)
+ .readMachineString(WINDOWS_POLICY_SUBKEY, "Policy")
+ .pipe(
+ Effect.mapError(
+ (cause) =>
+ new ManagedPolicyFileError({
+ path,
+ reason:
+ cause.code === ERROR_UNSUPPORTED_TYPE
+ ? "its Policy value is not a string (REG_SZ)"
+ : cause.code === undefined
+ ? "this T3 Code install cannot load its registry reader; reinstall T3 Code"
+ : `the registry cannot be read (${cause.message})`,
+ cause,
+ }),
+ ),
+ );
+ return raw === undefined
+ ? undefined
+ : { source: path, document: yield* decodeDocument(path, raw) };
+ }
+ return undefined;
+});
+
+/**
+ * Read the machine's policy from wherever an administrator put it: a configuration profile on
+ * macOS, the Policies registry key on Windows, or the policy file. Two sources are refused rather
+ * than merged, so what applies is never a mix nobody wrote.
+ */
+export const readManagedPolicy = Effect.fn("readManagedPolicy")(function* (
+ platform: NodeJS.Platform,
+) {
+ const filePath = managedPolicyPath(platform);
+ const [platformPolicy, file] = yield* Effect.all([
+ readPlatformPolicy(platform),
+ readManagedPolicyFile(filePath),
+ ]);
+ if (platformPolicy !== undefined && file !== undefined) {
+ return yield* new ManagedPolicyFileError({
+ path: platformPolicy.source,
+ reason: `a policy file at ${filePath} also exists; deploy the policy one way`,
+ });
+ }
+ return platformPolicy ?? (file === undefined ? undefined : { source: filePath, document: file });
+});
diff --git a/packages/shared/src/relayClient.ts b/packages/shared/src/relayClient.ts
index e56ef42ee1a..4b277a1196e 100644
--- a/packages/shared/src/relayClient.ts
+++ b/packages/shared/src/relayClient.ts
@@ -60,6 +60,7 @@ export class RelayClientInstallError extends Data.TaggedError("RelayClientInstal
| "download_failed"
| "invalid_checksum"
| "install_locked"
+ | "managed_by_policy"
| "override_missing"
| "unsupported_platform"
| "validation_failed"
diff --git a/packages/tailscale/src/tailscale.test.ts b/packages/tailscale/src/tailscale.test.ts
index 0b83cb3008d..d1b90208443 100644
--- a/packages/tailscale/src/tailscale.test.ts
+++ b/packages/tailscale/src/tailscale.test.ts
@@ -10,6 +10,7 @@ import * as HostProcess from "@t3tools/shared/HostProcess";
import {
ensureTailscaleServe,
parseTailscaleExitNode,
+ parseTailscaleServeRoutesTo,
parseTailscaleSshEnabled,
parseTailscaleStatus,
readTailscaleSshEnabled,
@@ -94,6 +95,101 @@ function layerMockSpawner(
}
describe("tailscale", () => {
+ it("finds the Serve routes that forward to the bound address, and only those", () => {
+ const status = JSON.stringify({
+ TCP: {
+ "443": { HTTPS: true },
+ "7000": { TCPForward: "127.0.0.1:3773" },
+ "7001": { TCPForward: "127.0.0.2:3773" },
+ "80": { TCPForward: "unix:/run/app.sock" },
+ },
+ Web: {
+ "box.tailnet.ts.net:443": {
+ Handlers: {
+ "/t3": { Proxy: "http://127.0.0.1:3773" },
+ "/dashboard": { Proxy: "http://127.0.0.1:9000" },
+ },
+ },
+ "box.tailnet.ts.net:8443": { Handlers: { "/": { Proxy: "http://127.0.0.1:5173" } } },
+ "box.tailnet.ts.net:10000": {
+ Handlers: {
+ // Another service on another loopback address, and one on the other family.
+ "/a": { Proxy: "http://127.0.0.2:3773" },
+ "/b": { Proxy: "http://[::1]:3773" },
+ "/c": { Proxy: "http://192.168.1.5:3773" },
+ "/d": { Proxy: "http://0.0.0.0:3773" },
+ "/e": { Proxy: "http://[::ffff:127.0.0.1]:3773" },
+ "/f": { Proxy: "http://localhost:3773" },
+ // Shorthand Tailscale expands when it proxies.
+ "/g": { Proxy: "3773" },
+ "/h": { Proxy: "localhost:3773" },
+ "/i": { Proxy: "http://[::]:3773" },
+ // A name can resolve to any address, the bound one included.
+ "/j": { Proxy: "http://ip6-localhost:3773" },
+ // Go resolves these as names; a WHATWG URL rejects the first and rewrites the second.
+ "/k": { Proxy: "http://box.1:3773" },
+ "/l": { Proxy: "http://127.1:3773" },
+ "/m": { Proxy: "unix:/run/app.sock" },
+ // Credentials before the host, and IPv6 written out in full, still dial here.
+ "/n": { Proxy: "http://user:[email protected]:3773" },
+ "/o": { Proxy: "http://[0:0:0:0:0:ffff:7f00:1]:3773" },
+ "/p": { Proxy: "http://127.0.0.1:03773" },
+ },
+ },
+ },
+ Services: {
+ "svc:t3": {
+ Web: {
+ "t3.tailnet.ts.net:443": { Handlers: { "/": { Proxy: "http://127.0.0.1:3773" } } },
+ },
+ },
+ },
+ Foreground: {
+ session1: { TCP: { "9000": { TCPForward: "localhost:3773" } } },
+ },
+ });
+ assert.deepEqual(parseTailscaleServeRoutesTo(status, { host: "127.0.0.1", port: 3773 }), [
+ { servePort: 7000 },
+ { servePort: 443, mount: "/t3", host: "box.tailnet.ts.net" },
+ // `localhost` and `[::]` can dial either loopback, so they might be another service's.
+ ...(
+ [
+ ["/d", undefined],
+ ["/e", undefined],
+ ["/f", "localhost"],
+ ["/g", undefined],
+ ["/h", "localhost"],
+ ["/i", "[::]"],
+ ["/j", "ip6-localhost"],
+ ["/k", "box.1"],
+ ["/l", "127.1"],
+ ["/n", undefined],
+ ["/o", undefined],
+ ["/p", undefined],
+ ] as const
+ ).map(([mount, ambiguous]) => ({
+ servePort: 10000,
+ mount,
+ host: "box.tailnet.ts.net",
+ ...(ambiguous === undefined ? {} : { ambiguous }),
+ })),
+ { servePort: 443, mount: "/", host: "t3.tailnet.ts.net", owner: "svc:t3" },
+ { servePort: 9000, ambiguous: "localhost", owner: "foreground" },
+ ]);
+ assert.deepEqual(
+ parseTailscaleServeRoutesTo(
+ JSON.stringify({
+ Web: { "box:443": { Handlers: { "/": { Proxy: "http://127.0.0.1" } } } },
+ }),
+ { host: "127.0.0.1", port: 80 },
+ ),
+ [{ servePort: 443, mount: "/", host: "box" }],
+ );
+ assert.deepEqual(parseTailscaleServeRoutesTo("{}", { host: "127.0.0.1", port: 3773 }), []);
+ assert.deepEqual(parseTailscaleServeRoutesTo("null", { host: "127.0.0.1", port: 3773 }), []);
+ assert.isUndefined(parseTailscaleServeRoutesTo("not json", { host: "127.0.0.1", port: 3773 }));
+ });
+
it.effect("parses status facts", () =>
Effect.gen(function* () {
const status = yield* parseTailscaleStatus(tailscaleStatusJson);
diff --git a/packages/tailscale/src/tailscale.ts b/packages/tailscale/src/tailscale.ts
index 1c803b27f1e..cb5748d21e7 100644
--- a/packages/tailscale/src/tailscale.ts
+++ b/packages/tailscale/src/tailscale.ts
@@ -1,4 +1,5 @@
import * as HostProcess from "@t3tools/shared/HostProcess";
+import { normalizeHostname } from "@t3tools/shared/hostClassification";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
@@ -42,6 +43,7 @@ const TailscaleCommandContext = {
export const TailscaleStderrDiagnostic = Schema.Literals([
"no-existing-handler",
"not-logged-in",
+ "not-running",
"permission-denied",
"unknown",
]);
@@ -52,6 +54,12 @@ const STDERR_DIAGNOSTIC_PATTERNS: ReadonlyArray<
> = [
[/handler does not exist/i, "no-existing-handler"],
[/not logged in|logged out|needs? login/i, "not-logged-in"],
+ // Only answers that confirm no daemon; a dial can also fail for want of permission. Windows
+ // reports a missing service as its pipe not being found, without the usual prefix.
+ [
+ /doesn't appear to be running|tailscaled\.service not running|tailscale is stopped|tailscaled: the system cannot find the file specified|failed to connect to local tailscale[\s\S]*(connection refused|no such file or directory|cannot find the file)/i,
+ "not-running",
+ ],
[/permission denied|access denied|must be root|operation not permitted/i, "permission-denied"],
];
@@ -222,7 +230,7 @@ export const parseTailscaleStatus = (
);
const readTailscaleOutput = Effect.fn("tailscale.readTailscaleOutput")(function* (
- subcommand: "status" | "debug",
+ subcommand: "status" | "serve" | "debug",
args: readonly string[],
) {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
@@ -438,18 +446,208 @@ export const ensureTailscaleServe = (input: {
return runTailscaleCommand(args, TAILSCALE_SERVE_TIMEOUT);
};
+/** A Serve route: a web handler at `mount` on `servePort`, or a TCP forward without one. */
+export interface TailscaleServeRoute {
+ readonly servePort: number;
+ readonly mount?: string;
+ /** The machine name a web route serves under. */
+ readonly host?: string;
+ /** A target, such as a name, that may dial this server or another service on the same port. */
+ readonly ambiguous?: string;
+ /** The Tailscale Service it belongs to, or `foreground` for a `tailscale serve` still running. */
+ readonly owner?: string;
+}
+
+/**
+ * The `tailscale` arguments that turn `route` off; a foreground route has none, since it ends with
+ * its command. A web route names its path: without one the CLI removes every handler on the port,
+ * and answers its own confirmation prompt with yes when nobody is there to answer.
+ */
+export const tailscaleServeOffArgs = (
+ route: TailscaleServeRoute,
+): ReadonlyArray<string> | undefined =>
+ route.owner === "foreground"
+ ? undefined
+ : [
+ "serve",
+ ...(route.owner === undefined ? [] : [`--service=${route.owner}`]),
+ ...(route.mount === undefined
+ ? [`--tcp=${route.servePort}`]
+ : [`--https=${route.servePort}`, `--set-path=${route.mount}`]),
+ "off",
+ ];
+
+/** Removes the web handler at `mount` on `servePort`, the root one `ensureTailscaleServe` adds by default. */
export const disableTailscaleServe = Effect.fn("tailscale.disableTailscaleServe")(function* (
input: {
readonly servePort?: number;
+ readonly mount?: string;
} = {},
): Effect.fn.Return<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> {
- const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;
return yield* runTailscaleCommand(
- ["serve", `--https=${servePort}`, "off"],
+ tailscaleServeOffArgs({
+ servePort: input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT,
+ mount: input.mount ?? "/",
+ })!,
TAILSCALE_SERVE_TIMEOUT,
);
});
+/** Removes a TCP forward on `servePort`; one port holds one forward, so nothing else goes. */
+export const disableTailscaleServeTcp = (servePort: number) =>
+ runTailscaleCommand(tailscaleServeOffArgs({ servePort })!, TAILSCALE_SERVE_TIMEOUT);
+
+const TailscaleServeConfigJson = Schema.Struct({
+ TCP: Schema.optional(
+ Schema.Record(Schema.String, Schema.Struct({ TCPForward: Schema.optional(Schema.String) })),
+ ),
+ Web: Schema.optional(
+ Schema.Record(
+ Schema.String,
+ Schema.Struct({
+ Handlers: Schema.optional(
+ Schema.Record(Schema.String, Schema.Struct({ Proxy: Schema.optional(Schema.String) })),
+ ),
+ }),
+ ),
+ ),
+});
+const TailscaleServeStatusJson = Schema.Struct({
+ ...TailscaleServeConfigJson.fields,
+ // A Tailscale Service's routes, and those of each `tailscale serve` still running in the foreground.
+ Services: Schema.optional(Schema.Record(Schema.String, TailscaleServeConfigJson)),
+ Foreground: Schema.optional(Schema.Record(Schema.String, TailscaleServeConfigJson)),
+});
+// A node without any Serve configuration prints `null`.
+const decodeTailscaleServeStatusJson = Schema.decodeUnknownOption(
+ Schema.fromJsonString(Schema.NullOr(TailscaleServeStatusJson)),
+);
+
+/**
+ * Whether a proxy to `hostname` dials `bindHost`. `0.0.0.0` reaches 127.0.0.1. `[::]` may reach
+ * either loopback, since Go dials `::` and then 0.0.0.0 (golang/go#18806), and a name such as
+ * `localhost` may resolve to whatever the server binds.
+ */
+const reaches = (hostname: string, bindHost: string): "exact" | "either" | undefined => {
+ let address = normalizeHostname(hostname);
+ // Compare IPv6 by value: 0:0:0:0:0:ffff:7f00:1 is ::ffff:7f00:1.
+ if (address.includes(":") && URL.canParse(`http://[${address}]`)) {
+ address = normalizeHostname(new URL(`http://[${address}]`).hostname);
+ }
+ // An IPv4-mapped address can be written as hex, such as ::ffff:7f00:1 for 127.0.0.1.
+ const mapped = /^::ffff:([\da-f]{1,4}):([\da-f]{1,4})$/u.exec(address);
+ if (mapped !== null) {
+ const high = Number.parseInt(mapped[1]!, 16);
+ const low = Number.parseInt(mapped[2]!, 16);
+ address = [high >>> 8, high & 0xff, low >>> 8, low & 0xff].join(".");
+ } else if (address.startsWith("::ffff:")) {
+ address = address.slice("::ffff:".length);
+ }
+ // Strict, as Go's ParseIP is; anything else, such as `127.1` or `box.1`, goes to the resolver.
+ const literal =
+ address.includes(":") ||
+ /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?!$)|$)){4}$/u.test(address);
+ if (!literal) return "either";
+ if (address === "::")
+ return bindHost === "127.0.0.1" || bindHost === "::1" ? "either" : undefined;
+ return (address === "0.0.0.0" ? "127.0.0.1" : address) === bindHost ? "exact" : undefined;
+};
+
+/** The URL Tailscale's proxy dials for a handler's `Proxy`, expanded as its `expandProxyArg` does. */
+const expandProxy = (proxy: string) =>
+ /^\d+$/u.test(proxy)
+ ? `http://127.0.0.1:${proxy}`
+ : proxy.startsWith("https+insecure://")
+ ? `https://${proxy.slice("https+insecure://".length)}`
+ : /^(?:https?:\/\/|unix:)/u.test(proxy)
+ ? proxy
+ : `http://${proxy}`;
+
+/**
+ * The host and port a proxy target dials, read as Go's url.Parse reads it rather than as a WHATWG
+ * URL, which rejects `box.1` and rewrites `127.1`; none for a Unix socket.
+ */
+const dialedHostPort = (url: string) => {
+ const match = /^(https?|tcp):\/\/(?:[^@/?#]*@)?(\[[^\]]*\]|[^/?#:]*)(?::(\d*))?/iu.exec(url);
+ if (match === null) return undefined;
+ const [, scheme = "", host = "", port] = match;
+ return { host, port: port || (scheme.toLowerCase() === "https" ? "443" : "80") };
+};
+
+const reachesTarget = (url: string, target: { readonly host: string; readonly port: number }) => {
+ const dialed = dialedHostPort(url);
+ // Go reads the port as a decimal number, so 03773 is 3773.
+ if (dialed === undefined || Number(dialed.port) !== target.port) return undefined;
+ const reach = reaches(dialed.host, target.host);
+ return reach === undefined ? undefined : { reach, hostname: dialed.host };
+};
+
+/**
+ * The Serve routes that forward to the server bound at `target`, or undefined when the status
+ * cannot be read.
+ */
+export const parseTailscaleServeRoutesTo = (
+ rawServeStatusJson: string,
+ target: { readonly host: string; readonly port: number },
+): ReadonlyArray<TailscaleServeRoute> | undefined => {
+ const status = decodeTailscaleServeStatusJson(rawServeStatusJson);
+ if (Option.isNone(status)) return undefined;
+ const routesIn = (
+ config: typeof TailscaleServeConfigJson.Type | undefined,
+ owner?: string,
+ ): ReadonlyArray<TailscaleServeRoute> => {
+ const scope = owner === undefined ? {} : { owner };
+ const reached = (url: string) => {
+ const found = reachesTarget(url, target);
+ if (found === undefined) return undefined;
+ return found.reach === "either" ? { ambiguous: found.hostname } : {};
+ };
+ const tcp = Object.entries(config?.TCP ?? {}).flatMap(([port, handler]) => {
+ const reach =
+ handler.TCPForward === undefined || handler.TCPForward.startsWith("unix:")
+ ? undefined
+ : reached(`tcp://${handler.TCPForward}`);
+ return reach !== undefined && Number.isInteger(Number(port))
+ ? [{ servePort: Number(port), ...reach, ...scope }]
+ : [];
+ });
+ const web = Object.entries(config?.Web ?? {}).flatMap(([hostPort, site]) => {
+ const separator = hostPort.lastIndexOf(":");
+ const servePort = Number(hostPort.slice(separator + 1));
+ if (!Number.isInteger(servePort)) return [];
+ const host = hostPort.slice(0, separator);
+ return Object.entries(site.Handlers ?? {}).flatMap(([mount, handler]) => {
+ const reach = handler.Proxy === undefined ? undefined : reached(expandProxy(handler.Proxy));
+ return reach === undefined ? [] : [{ servePort, mount, host, ...reach, ...scope }];
+ });
+ });
+ return [...tcp, ...web];
+ };
+ return [
+ ...routesIn(status.value ?? undefined),
+ ...Object.entries(status.value?.Services ?? {}).flatMap(([name, service]) =>
+ routesIn(service, name),
+ ),
+ ...Object.values(status.value?.Foreground ?? {}).flatMap((session) =>
+ routesIn(session, "foreground"),
+ ),
+ ];
+};
+
+/** The Serve routes that forward to the server bound at `target` on this machine. */
+export const readTailscaleServeRoutesTo = (target: {
+ readonly host: string;
+ readonly port: number;
+}) =>
+ readTailscaleOutput("serve", ["serve", "status", "--json"]).pipe(
+ Effect.flatMap((status) => {
+ const routes = parseTailscaleServeRoutesTo(status, target);
+ return routes === undefined
+ ? Effect.fail(new TailscaleStatusParseError({ cause: "unreadable serve status" }))
+ : Effect.succeed(routes);
+ }),
+ );
+
export const probeTailscaleHttpsEndpoint = Effect.fn("tailscale.probeTailscaleHttpsEndpoint")(
function* (input: { readonly baseUrl: string; readonly timeout?: Duration.Input }) {
const client = yield* HttpClient.HttpClient;
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 93fc3a9060c..d690b2b4a36 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -910,6 +910,9 @@ importers:
effect:
specifier: 4.0.5
version: 4.0.5
+ ffi-rs:
+ specifier: 1.3.2
+ version: 1.3.2
jose:
specifier: 'catalog:'
version: 6.2.2
@@ -2012,6 +2015,9 @@ importers:
effect:
specifier: 4.0.5
version: 4.0.5
+ ffi-rs:
+ specifier: 1.3.2
+ version: 1.3.2
jose:
specifier: 'catalog:'
version: 6.2.2
diff --git a/scripts/dev-runner.ts b/scripts/dev-runner.ts
index 5903cb7686e..9cd8e598acf 100644
--- a/scripts/dev-runner.ts
+++ b/scripts/dev-runner.ts
@@ -806,7 +806,7 @@ export const runDevRunnerWithInput = Effect.fn("dev-runner.runDevRunnerWithInput
: Effect.logWarning(
`[dev-runner] could not remove the tailnet mapping for port ${String(sharedWebPort)}${
result.explanation ? `: ${result.explanation}` : ""
- }. Remove it with \`tailscale serve --https=${String(sharedWebPort)} off\`.`,
+ }. Remove it with \`tailscale serve --https=${String(sharedWebPort)} --set-path=/ off\`.`,
),
),
),
diff --git a/scripts/lib/dev-share.ts b/scripts/lib/dev-share.ts
index 9f4ac5212e2..78144321459 100644
--- a/scripts/lib/dev-share.ts
+++ b/scripts/lib/dev-share.ts
@@ -16,6 +16,7 @@ import type { ChildProcessSpawner } from "effect/process";
const DIAGNOSTIC_EXPLANATIONS: Record<TailscaleStderrDiagnostic, string | undefined> = {
"no-existing-handler": "no mapping existed for that port",
"not-logged-in": "this machine is not logged into a tailnet — run `tailscale up`",
+ "not-running": "Tailscale is not running; start it and try again",
"permission-denied": "permission denied — `tailscale serve` may need elevated privileges",
unknown: undefined,
};
@@ -64,7 +65,7 @@ export class DevServeFailedError extends Schema.TaggedError<DevServeFailedError>
const port = String(this.webPort);
const base =
this.stage === "clear-existing"
- ? `could not clear the existing mapping for port ${port}. Run \`tailscale serve --https=${port} off\` and retry`
+ ? `could not clear the existing mapping for port ${port}. Run \`tailscale serve --https=${port} --set-path=/ off\` and retry`
: `could not serve port ${port} on the tailnet (it is no longer served; any previous mapping for it was cleared before this attempt)`;
return this.explanation ? `${base}: ${this.explanation}` : base;
}