@devries-cameron20 / t3code Mirror · read-only / commits / d897d3f3f0
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 08:15 UTC

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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Matthew Feroz <136640686+MatthewFeroz@users.noreply.github.com> Co-authored-by: Theo Browne <me@t3.gg> Co-authored-by: Adamulek123 <adam.bogucki2018@gmail.com> Co-authored-by: maria-rcks <maria@kuuro.net>

Julius Marminge committed Nov 1, 2026 at 12:10 UTC d897d3f3f00f2cb534c813e637154d39c8d1cff6
193 files changed +9048 -543
apps/desktop/src/app/DesktopManagedPolicy.ts new
+65
@@ -0,0 +1,65 @@
1 +/**
2 + * DesktopManagedPolicy - the administrator's managed policy as the desktop app reads it, at most
3 + * once: every desktop check needs the same answer.
4 + *
5 + * @module DesktopManagedPolicy
6 + */
7 +import type { ManagedPolicyDocument } from "@t3tools/contracts";
8 +import {
9 + layerWindowsRegistry,
10 + ManagedPolicyFileError,
11 + readManagedPolicy,
12 + WindowsRegistry,
13 +} from "@t3tools/shared/managedPolicyFile";
14 +import * as Context from "effect/Context";
15 +import * as Effect from "effect/Effect";
16 +import * as FileSystem from "effect/FileSystem";
17 +import * as Layer from "effect/Layer";
18 +import * as Schema from "effect/Schema";
19 +import { ChildProcessSpawner } from "effect/process";
20 +
21 +import * as DesktopEnvironment from "./DesktopEnvironment.ts";
22 +
23 +type FoundPolicy = Effect.Success<ReturnType<typeof readManagedPolicy>>;
24 +const isManagedPolicyFileError = Schema.is(ManagedPolicyFileError);
25 +
26 +export class DesktopManagedPolicy extends Context.Service<
27 + DesktopManagedPolicy,
28 + {
29 + /** The policy on this machine, undefined without one; fails when it cannot be used. */
30 + readonly read: Effect.Effect<FoundPolicy, ManagedPolicyFileError>;
31 + }
32 +>()("@t3tools/desktop/app/DesktopManagedPolicy") {}
33 +
34 +export const layer = Layer.effect(
35 + DesktopManagedPolicy,
36 + Effect.gen(function* () {
37 + const { platform } = yield* DesktopEnvironment.DesktopEnvironment;
38 + const read = yield* Effect.cached(
39 + readManagedPolicy(platform).pipe(
40 + Effect.provideService(FileSystem.FileSystem, yield* FileSystem.FileSystem),
41 + Effect.provideService(
42 + ChildProcessSpawner.ChildProcessSpawner,
43 + yield* ChildProcessSpawner.ChildProcessSpawner,
44 + ),
45 + Effect.provideService(WindowsRegistry, yield* WindowsRegistry),
46 + ),
47 + );
48 + return DesktopManagedPolicy.of({ read });
49 + }),
50 +).pipe(Layer.provide(layerWindowsRegistry(() => import("ffi-rs"))));
51 +
52 +/** A machine with `policy` deployed, one whose policy cannot be used, or none. */
53 +export const layerTest = (policy?: ManagedPolicyDocument | ManagedPolicyFileError) =>
54 + Layer.succeed(
55 + DesktopManagedPolicy,
56 + DesktopManagedPolicy.of({
57 + read:
58 + policy === undefined
59 + ? // @effect-diagnostics-next-line effectSucceedWithVoid:off - No policy is undefined, not void.
60 + Effect.succeed(undefined)
61 + : isManagedPolicyFileError(policy)
62 + ? Effect.fail(policy)
63 + : Effect.succeed({ source: "/test/policy.json", document: policy }),
64 + }),
65 + );
apps/desktop/src/backend/DesktopBackendConfiguration.test.ts
+2
@@ -12,6 +12,7 @@ import * as Stream from "effect/Stream";
12 import { ChildProcessSpawner } from "effect/process";
13
14 import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
15 +import * as DesktopManagedPolicy from "../app/DesktopManagedPolicy.ts";
16 import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
17 import * as DesktopShellEnvironment from "../shell/DesktopShellEnvironment.ts";
18 import * as DesktopConfig from "../app/DesktopConfig.ts";
@@ -972,6 +973,7 @@ describe("DesktopBackendConfiguration", () => {
973 Layer.provideMerge(DesktopAppSettings.layerTest()),
974 Layer.provideMerge(DesktopWslServerTree.layerTest()),
975 Layer.provideMerge(DesktopWslEnvironment.layer),
976 + Layer.provideMerge(DesktopManagedPolicy.layerTest()),
977 Layer.provideMerge(
978 Layer.succeed(
979 ChildProcessSpawner.ChildProcessSpawner,
apps/desktop/src/backend/DesktopServerExposure.test.ts
+41
@@ -7,12 +7,14 @@ import * as Effect from "effect/Effect";
7 import * as Fiber from "effect/Fiber";
8 import * as FileSystem from "effect/FileSystem";
9 import * as Layer from "effect/Layer";
10 +import * as Option from "effect/Option";
11 import * as Sink from "effect/Sink";
12 import * as Stream from "effect/Stream";
13 import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
14
15 import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
16 import * as DesktopConfig from "../app/DesktopConfig.ts";
17 +import * as DesktopManagedPolicy from "../app/DesktopManagedPolicy.ts";
18 import * as DesktopNetworkInterfaces from "./DesktopNetworkInterfaces.ts";
19 import * as DesktopServerExposure from "./DesktopServerExposure.ts";
20 import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
@@ -90,6 +92,7 @@ function layer(input: {
92 readonly env?: Record<string, string | undefined>;
93 readonly spawnerLayer?: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>;
94 readonly desktopSettingsLayer?: Layer.Layer<DesktopAppSettings.DesktopAppSettings>;
95 + readonly managedPolicyLayer?: Layer.Layer<DesktopManagedPolicy.DesktopManagedPolicy>;
96 }) {
97 const env = { T3CODE_HOME: input.baseDir, ...input.env };
98 const layerEnvironment = layerEnvironmentFor(input.baseDir, env);
@@ -99,6 +102,7 @@ function layer(input: {
102
103 return DesktopServerExposure.layer.pipe(
104 Layer.provideMerge(input.desktopSettingsLayer ?? DesktopAppSettings.layer),
105 + Layer.provideMerge(input.managedPolicyLayer ?? DesktopManagedPolicy.layerTest()),
106 Layer.provideMerge(NodeFileSystem.layer),
107 Layer.provideMerge(NodeHttpClient.layerUndici),
108 Layer.provideMerge(input.spawnerLayer ?? layerMockSpawner()),
@@ -122,6 +126,7 @@ const withHarness = <A, E, R>(
126 env: Record<string, string | undefined> = {},
127 spawnerLayer?: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>,
128 desktopSettingsLayer?: Layer.Layer<DesktopAppSettings.DesktopAppSettings>,
129 + managedPolicyLayer?: Layer.Layer<DesktopManagedPolicy.DesktopManagedPolicy>,
130 ) =>
131 Effect.gen(function* () {
132 const fileSystem = yield* FileSystem.FileSystem;
@@ -136,6 +141,7 @@ const withHarness = <A, E, R>(
141 env,
142 ...(spawnerLayer ? { spawnerLayer } : {}),
143 ...(desktopSettingsLayer ? { desktopSettingsLayer } : {}),
144 + ...(managedPolicyLayer ? { managedPolicyLayer } : {}),
145 }),
146 ),
147 );
@@ -191,6 +197,41 @@ describe("DesktopServerExposure", () => {
197 ),
198 );
199
200 + it.effect("starts local-only, Serve off, when a managed policy keeps clients local", () =>
201 + withHarness(
202 + lanNetworkInterfaces,
203 + Effect.gen(function* () {
204 + const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
205 + const settings = yield* DesktopAppSettings.DesktopAppSettings;
206 + yield* settings.setServerExposureMode("network-accessible");
207 + yield* settings.setTailscaleServe({ enabled: true, port: Option.none() });
208 +
209 + const state = yield* serverExposure.configureFromSettings({ port: 4173 });
210 + assert.equal(state.mode, "local-only");
211 + const backendConfig = yield* serverExposure.backendConfig;
212 + assert.equal(backendConfig.bindHost, "127.0.0.1");
213 + assert.isFalse(backendConfig.tailscaleServeEnabled);
214 + // Choosing them again while the policy applies does not widen the backend either.
215 + yield* serverExposure.setMode("network-accessible");
216 + yield* serverExposure.setTailscaleServeEnabled({ enabled: true });
217 + assert.equal((yield* serverExposure.backendConfig).bindHost, "127.0.0.1");
218 + assert.isFalse((yield* serverExposure.backendConfig).tailscaleServeEnabled);
219 + // The saved choice returns once the policy allows it.
220 + const saved = yield* settings.get;
221 + assert.equal(saved.serverExposureMode, "network-accessible");
222 + assert.isTrue(saved.tailscaleServeEnabled);
223 + }),
224 + {},
225 + undefined,
226 + undefined,
227 + DesktopManagedPolicy.layerTest({
228 + schemaVersion: 1,
229 + organization: "Example Corp",
230 + limits: { clients: ["desktop"] },
231 + }),
232 + ),
233 + );
234 +
235 it.effect("persists network-accessible mode and updates backend binding state", () =>
236 withHarness(
237 lanNetworkInterfaces,
apps/desktop/src/backend/DesktopServerExposure.ts
+18 -5
@@ -22,6 +22,7 @@ import * as Semaphore from "effect/Semaphore";
22 import * as HttpClient from "effect/http/HttpClient";
23 import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
24
25 +import * as DesktopManagedPolicy from "../app/DesktopManagedPolicy.ts";
26 import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
27 import * as DesktopConfig from "../app/DesktopConfig.ts";
28 import * as DesktopNetworkInterfaces from "./DesktopNetworkInterfaces.ts";
@@ -482,6 +483,18 @@ export const make = Effect.gen(function* () {
483
484 const readNetworkInterfaces = networkInterfaces.read;
485
486 + // The server refuses to bind wider than the policy's clients allow, so network access or Serve
487 + // saved before the policy would keep the backend from starting. The backend runs without them;
488 + // the saved choice stays for when the policy allows it.
489 + const remoteAllowed = yield* (yield* DesktopManagedPolicy.DesktopManagedPolicy).read.pipe(
490 + Effect.map((found) => found?.document.limits?.clients?.includes("remote") ?? true),
491 + Effect.orElseSucceed(() => false),
492 + );
493 + const withinPolicy = (settings: DesktopAppSettings.DesktopSettings) =>
494 + remoteAllowed
495 + ? settings
496 + : { ...settings, serverExposureMode: "local-only" as const, tailscaleServeEnabled: false };
497 +
498 const readCurrentState = (currentNetworkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces) =>
499 Ref.get(stateRef).pipe(
500 Effect.map((state) =>
@@ -501,8 +514,8 @@ export const make = Effect.gen(function* () {
514 const settings = yield* desktopSettings.get;
515 const currentNetworkInterfaces = yield* readNetworkInterfaces;
516 const resolved = resolveRuntimeState({
504 - requestedMode: settings.serverExposureMode,
505 - settings,
517 + requestedMode: withinPolicy(settings).serverExposureMode,
518 + settings: withinPolicy(settings),
519 port,
520 networkInterfaces: currentNetworkInterfaces,
521 advertisedHostOverride: config.desktopLanHostOverride,
@@ -524,8 +537,8 @@ export const make = Effect.gen(function* () {
537 };
538 const currentNetworkInterfaces = yield* readNetworkInterfaces;
539 const resolved = resolveRuntimeState({
527 - requestedMode: mode,
528 - settings: nextSettings,
540 + requestedMode: withinPolicy(nextSettings).serverExposureMode,
541 + settings: withinPolicy(nextSettings),
542 port: previous.port,
543 networkInterfaces: currentNetworkInterfaces,
544 advertisedHostOverride: config.desktopLanHostOverride,
@@ -576,7 +589,7 @@ export const make = Effect.gen(function* () {
589
590 const nextState = yield* Ref.updateAndGet(stateRef, (current) => ({
591 ...current,
579 - tailscaleServeEnabled: result.settings.tailscaleServeEnabled,
592 + tailscaleServeEnabled: withinPolicy(result.settings).tailscaleServeEnabled,
593 tailscaleServePort: result.settings.tailscaleServePort,
594 }));
595
apps/desktop/src/ipc/DesktopIpcHandlers.ts
+2 -2
@@ -36,7 +36,7 @@ import {
36 getAppBranding,
37 getLocalEnvironmentBootstraps,
38 getLocalEnvironmentBearerToken,
39 - getRelayTelemetryEnabled,
39 + installRelayTelemetryEnabled,
40 getSystemLocale,
41 getWindowFullscreenState,
42 openExternal,
@@ -91,7 +91,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
91 yield* ipc.handleSync(takeLegacyLocalStorage);
92 yield* ipc.handle(completeLegacyLocalStorage);
93 yield* ipc.handleSync(getAppBranding);
94 - yield* ipc.handleSync(getRelayTelemetryEnabled);
94 + yield* installRelayTelemetryEnabled();
95 yield* ipc.handleSync(getSystemLocale);
96 yield* ipc.handleSync(getWindowFullscreenState);
97 yield* ipc.handleSync(getLocalEnvironmentBootstraps);
apps/desktop/src/ipc/methods/window.test.ts
+49 -11
@@ -1,6 +1,8 @@
1 import { assert, describe, it } from "@effect/vitest";
2 import * as NodeServices from "@effect/platform-node/NodeServices";
3 +import type { ManagedPolicyLimits } from "@t3tools/contracts";
4 import * as HostProcess from "@t3tools/shared/HostProcess";
5 +import { ManagedPolicyFileError } from "@t3tools/shared/managedPolicyFile";
6 import * as FileSystem from "effect/FileSystem";
7 import * as Path from "effect/Path";
8 import * as Effect from "effect/Effect";
@@ -21,11 +23,14 @@ import * as DesktopBackendConfiguration from "../../backend/DesktopBackendConfig
23 import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts";
24 import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts";
25 import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts";
26 +import * as DesktopManagedPolicy from "../../app/DesktopManagedPolicy.ts";
27 import * as ElectronDialog from "../../electron/ElectronDialog.ts";
28 import * as ElectronWindow from "../../electron/ElectronWindow.ts";
29 +import * as IpcChannels from "../channels.ts";
30 +import * as DesktopIpc from "../DesktopIpc.ts";
31 import {
32 getLocalEnvironmentBootstraps,
28 - getRelayTelemetryEnabled,
33 + installRelayTelemetryEnabled,
34 pickProjectFavicon,
35 probeRemoteEditors,
36 } from "./window.ts";
@@ -177,21 +182,54 @@ describe("getLocalEnvironmentBootstraps", () => {
182 });
183 });
184
180 -describe("getRelayTelemetryEnabled", () => {
185 +describe("installRelayTelemetryEnabled", () => {
186 + // The renderer reads this over sync IPC, so the answer must not wait on the filesystem.
187 + const relayTelemetryEnabled = (
188 + env: NodeJS.ProcessEnv,
189 + policy?: Parameters<typeof DesktopManagedPolicy.layerTest>[0],
190 + ) =>
191 + Effect.gen(function* () {
192 + const listeners = new Map<string, DesktopIpc.DesktopIpcSyncListener>();
193 + const ipcMain: DesktopIpc.DesktopIpcMain = {
194 + removeHandler: () => undefined,
195 + handle: () => undefined,
196 + removeAllListeners: (channel) => void listeners.delete(channel),
197 + on: (channel, listener) => void listeners.set(channel, listener),
198 + };
199 + yield* installRelayTelemetryEnabled().pipe(
200 + Effect.provideService(HostProcess.Environment, env),
201 + Effect.provide(
202 + Layer.mergeAll(DesktopIpc.layer(ipcMain), DesktopManagedPolicy.layerTest(policy)),
203 + ),
204 + );
205 + const event = { returnValue: undefined as unknown };
206 + listeners.get(IpcChannels.GET_RELAY_TELEMETRY_ENABLED_CHANNEL)?.(event as never);
207 + return event.returnValue;
208 + }).pipe(Effect.scoped);
209 +
210 it.effect("reads the desktop host opt-out before returning the renderer policy", () =>
211 Effect.gen(function* () {
212 + assert.isFalse(yield* relayTelemetryEnabled({ T3CODE_TELEMETRY_ENABLED: "false" }));
213 + assert.isTrue(yield* relayTelemetryEnabled({}));
214 + }),
215 + );
216 +
217 + it.effect("turns relay tracing off when the managed policy turns telemetry off", () =>
218 + Effect.gen(function* () {
219 + const policy = (limits: ManagedPolicyLimits) => ({
220 + schemaVersion: 1 as const,
221 + organization: "Example Corp",
222 + limits,
223 + });
224 + assert.isFalse(yield* relayTelemetryEnabled({}, policy({ telemetry: false })));
225 + assert.isTrue(yield* relayTelemetryEnabled({}, policy({ webhookTasks: false })));
226 + // A policy that cannot be read fails closed.
227 assert.isFalse(
184 - yield* getRelayTelemetryEnabled.handler().pipe(
185 - Effect.provideService(HostProcess.Environment, {
186 - T3CODE_TELEMETRY_ENABLED: "false",
187 - }),
228 + yield* relayTelemetryEnabled(
229 + {},
230 + new ManagedPolicyFileError({ path: "/test", reason: "bad JSON" }),
231 ),
232 );
190 - assert.isTrue(
191 - yield* getRelayTelemetryEnabled
192 - .handler()
193 - .pipe(Effect.provideService(HostProcess.Environment, {})),
194 - );
233 }),
234 );
235 });
apps/desktop/src/ipc/methods/window.ts
+23 -7
@@ -27,6 +27,7 @@ import * as DesktopBackendConfiguration from "../../backend/DesktopBackendConfig
27 import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts";
28 import * as DesktopLocalEnvironmentAuth from "../../backend/DesktopLocalEnvironmentAuth.ts";
29 import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts";
30 +import * as DesktopManagedPolicy from "../../app/DesktopManagedPolicy.ts";
31 import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts";
32 import * as DesktopWslBackend from "../../wsl/DesktopWslBackend.ts";
33 import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts";
@@ -72,13 +73,28 @@ export const getAppBranding = DesktopIpc.makeSyncIpcMethod({
73 }),
74 });
75
75 -export const getRelayTelemetryEnabled = DesktopIpc.makeSyncIpcMethod({
76 - channel: IpcChannels.GET_RELAY_TELEMETRY_ENABLED_CHANNEL,
77 - result: Schema.Boolean,
78 - handler: Effect.fn("desktop.ipc.window.getRelayTelemetryEnabled")(function* () {
79 - return isRelayTracingEnabled(yield* HostProcess.Environment);
80 - }),
81 -});
76 +/**
77 + * Relay traces leave the machine, so a policy with `telemetry: false`, or one that cannot be read,
78 + * stops them. Read once here: a sync IPC handler cannot wait on the filesystem.
79 + */
80 +export const installRelayTelemetryEnabled = Effect.fn("desktop.ipc.window.installRelayTelemetry")(
81 + function* () {
82 + const ipc = yield* DesktopIpc.DesktopIpc;
83 + const enabled =
84 + isRelayTracingEnabled(yield* HostProcess.Environment) &&
85 + (yield* (yield* DesktopManagedPolicy.DesktopManagedPolicy).read.pipe(
86 + Effect.map((found) => found?.document.limits?.telemetry !== false),
87 + Effect.orElseSucceed(() => false),
88 + ));
89 + yield* ipc.handleSync(
90 + DesktopIpc.makeSyncIpcMethod({
91 + channel: IpcChannels.GET_RELAY_TELEMETRY_ENABLED_CHANNEL,
92 + result: Schema.Boolean,
93 + handler: () => Effect.succeed(enabled),
94 + }),
95 + );
96 + },
97 +);
98
99 export const getSystemLocale = DesktopIpc.makeSyncIpcMethod({
100 channel: IpcChannels.GET_SYSTEM_LOCALE_CHANNEL,
apps/desktop/src/main.ts
+10 -1
@@ -47,6 +47,7 @@ import * as DesktopBackendPool from "./backend/DesktopBackendPool.ts";
47 import * as DesktopLocalEnvironmentAuth from "./backend/DesktopLocalEnvironmentAuth.ts";
48 import * as DesktopNetworkInterfaces from "./backend/DesktopNetworkInterfaces.ts";
49 import * as DesktopEnvironment from "./app/DesktopEnvironment.ts";
50 +import * as DesktopManagedPolicy from "./app/DesktopManagedPolicy.ts";
51 import * as DesktopLifecycle from "./app/DesktopLifecycle.ts";
52 import * as DesktopLinuxUrlHandler from "./app/DesktopLinuxUrlHandler.ts";
53 import * as DesktopShutdown from "./app/DesktopShutdown.ts";
@@ -65,6 +66,7 @@ import * as DesktopState from "./app/DesktopState.ts";
66 import * as DesktopLegacyLocalStorage from "./app/DesktopLegacyLocalStorage.ts";
67 import * as DesktopTelemetryPublisher from "./telemetry/DesktopTelemetryPublisher.ts";
68 import * as DesktopRendererHistory from "./telemetry/DesktopRendererHistory.ts";
69 +import * as DesktopUpdatePolicy from "./updates/DesktopUpdatePolicy.ts";
70 import * as DesktopUpdates from "./updates/DesktopUpdates.ts";
71 import * as BrowserImport from "./preview/BrowserImport/BrowserImport.ts";
72 import * as LinuxBrowserSecret from "./preview/BrowserImport/LinuxBrowserSecret.ts";
@@ -141,6 +143,7 @@ const layerElectron = Layer.mergeAll(
143
144 const layerDesktopFoundation = Layer.mergeAll(
145 MacPermissions.layer,
146 + DesktopManagedPolicy.layer,
147 DesktopState.layer,
148 DesktopShutdown.layer,
149 DesktopLegacyLocalStorage.layer,
@@ -211,7 +214,13 @@ const layerDesktopApplication = Layer.mergeAll(
214 layerDesktopSsh,
215 ).pipe(
216 Layer.provideMerge(layerDesktopSnapShot),
214 - Layer.provideMerge(DesktopUpdates.layer),
217 + Layer.provideMerge(
218 + DesktopUpdates.layer.pipe(
219 + Layer.provide(DesktopUpdatePolicy.layer),
220 + // The same layer as the foundation's, so the policy is still read once.
221 + Layer.provide(DesktopManagedPolicy.layer),
222 + ),
223 + ),
224 Layer.provideMerge(layerDesktopWslBackend),
225 Layer.provideMerge(layerDesktopLocalEnvironmentAuth),
226 );
apps/desktop/src/preview/BrowserImport/BrowserImport.test.ts
+38
@@ -6,6 +6,8 @@ import * as FileSystem from "effect/FileSystem";
6 import * as Layer from "effect/Layer";
7
8 import * as BrowserSession from "../BrowserSession.ts";
9 +import { readManagedPolicyFile } from "@t3tools/shared/managedPolicyFile";
10 +import * as DesktopManagedPolicy from "../../app/DesktopManagedPolicy.ts";
11 import * as BrowserImport from "./BrowserImport.ts";
12 import { BROWSER_IMPORT_SOURCES, sourcePathContext } from "./Sources.ts";
13 import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
@@ -52,6 +54,7 @@ const withImporter = Effect.fnUntraced(function* () {
54 Effect.provide(
55 BrowserImport.layer.pipe(
56 Layer.provide(layerRejectedBeforeSession),
57 + Layer.provide(DesktopManagedPolicy.layerTest()),
58 Layer.provide(layerEnvironment),
59 Layer.provide(Layer.succeed(HostProcess.Platform, "darwin")),
60 Layer.provide(Layer.succeed(HostProcess.ExecutablePath, "/Applications/T3 Code.app")),
@@ -108,11 +111,46 @@ describe("BrowserImport.importCookies", () => {
111 })
112 .pipe(Effect.flip);
113
114 + assert.instanceOf(error, BrowserImport.BrowserImportFailedError);
115 assert.equal(error.reason, "browserRunning");
116 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
117 );
118 });
119
120 +describe("BrowserImport.checkBrowserImportPolicy", () => {
121 + it.effect("allows imports unless a readable policy turns them off, and fails closed", () =>
122 + Effect.gen(function* () {
123 + const fileSystem = yield* FileSystem.FileSystem;
124 + const dir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-import-policy-" });
125 + const outcome = (contents: string | undefined) =>
126 + Effect.gen(function* () {
127 + const policyPath = `${dir}/policy.json`;
128 + yield* fileSystem.remove(policyPath, { force: true });
129 + if (contents !== undefined) yield* fileSystem.writeFileString(policyPath, contents);
130 + const readPolicy = readManagedPolicyFile(policyPath).pipe(
131 + Effect.map((document) => document && { source: policyPath, document }),
132 + );
133 + return yield* BrowserImport.checkBrowserImportPolicy(readPolicy).pipe(
134 + Effect.match({ onFailure: (error) => error.message, onSuccess: () => "allowed" }),
135 + );
136 + });
137 + const policy = (limits?: object) =>
138 + JSON.stringify({ schemaVersion: 1, organization: "Example Corp", limits });
139 +
140 + assert.equal(yield* outcome(undefined), "allowed");
141 + assert.equal(yield* outcome(policy()), "allowed");
142 + assert.equal(yield* outcome(policy({ browserCookieImport: true })), "allowed");
143 + assert.equal(
144 + yield* outcome(policy({ browserCookieImport: false })),
145 + "Example Corp's policy does not allow importing browser cookies.",
146 + );
147 + for (const unreadable of ["{ not json", policy({ notALimit: false })]) {
148 + assert.include(yield* outcome(unreadable), "could not be read");
149 + }
150 + }).pipe(Effect.provide(NodeServices.layer)),
151 + );
152 +});
153 +
154 describe("BrowserImport.writeCookies", () => {
155 it.effect("flushes the store after writing, and reports success if the flush fails", () =>
156 Effect.gen(function* () {
apps/desktop/src/preview/BrowserImport/BrowserImport.ts
+49 -2
@@ -4,7 +4,11 @@ import type {
4 BrowserImportSource,
5 BrowserImportUnavailableReason,
6 } from "@t3tools/contracts";
7 -import { BrowserImportFailureReason } from "@t3tools/contracts";
7 +import {
8 + BrowserImportFailureReason,
9 + type ManagedPolicyDocument,
10 + managedPolicyDeniedMessage,
11 +} from "@t3tools/contracts";
12 import * as Context from "effect/Context";
13 import type { Session } from "electron";
14 import * as Effect from "effect/Effect";
@@ -16,7 +20,9 @@ import * as Scope from "effect/Scope";
20 import { ChildProcessSpawner } from "effect/process";
21
22 import * as HostProcess from "@t3tools/shared/HostProcess";
23 +import type { ManagedPolicyFileError } from "@t3tools/shared/managedPolicyFile";
24
25 +import * as DesktopManagedPolicy from "../../app/DesktopManagedPolicy.ts";
26 import * as BrowserSession from "../BrowserSession.ts";
27 import { ChromiumCookieReadError, readChromiumCookies } from "./ChromiumCookies.ts";
28 import type { CookieReadResult } from "./CookieDatabase.ts";
@@ -47,6 +53,45 @@ export class BrowserImportFailedError extends Schema.TaggedError<BrowserImportFa
53 }
54 }
55
56 +/** An administrator's policy forbids the import, or the policy file could not be checked. */
57 +export class BrowserImportPolicyError extends Schema.TaggedError<BrowserImportPolicyError>()(
58 + "BrowserImportPolicyError",
59 + {
60 + policyPath: Schema.String,
61 + /** Absent when the policy could not be read or decoded. */
62 + organization: Schema.optional(Schema.String),
63 + cause: Schema.optional(Schema.Defect()),
64 + },
65 +) {
66 + override get message(): string {
67 + return this.organization === undefined
68 + ? `The managed policy at ${this.policyPath} could not be read, so importing browser cookies is not allowed.`
69 + : managedPolicyDeniedMessage(this.organization, "importing browser cookies");
70 + }
71 +}
72 +
73 +/**
74 + * A policy that cannot be read or decoded denies the import: cookies are credentials, and the
75 + * server refuses to start on the same policy anyway.
76 + */
77 +export const checkBrowserImportPolicy = Effect.fn("BrowserImport.checkPolicy")(function* <R>(
78 + readPolicy: Effect.Effect<
79 + { readonly source: string; readonly document: ManagedPolicyDocument } | undefined,
80 + ManagedPolicyFileError,
81 + R
82 + >,
83 +) {
84 + const policy = yield* readPolicy.pipe(
85 + Effect.mapError((cause) => new BrowserImportPolicyError({ policyPath: cause.path, cause })),
86 + );
87 + if (policy?.document.limits?.browserCookieImport === false) {
88 + return yield* new BrowserImportPolicyError({
89 + policyPath: policy.source,
90 + organization: policy.document.organization,
91 + });
92 + }
93 +});
94 +
95 export class BrowserCookieWriteError extends Schema.TaggedError<BrowserCookieWriteError>()(
96 "BrowserCookieWriteError",
97 {
@@ -69,7 +114,7 @@ export class BrowserImport extends Context.Service<
114 readonly scope: string;
115 readonly persistent: boolean;
116 readonly namespace?: BrowserSession.BrowserSessionPartitionNamespace;
72 - }) => Effect.Effect<BrowserImportResult, BrowserImportFailedError>;
117 + }) => Effect.Effect<BrowserImportResult, BrowserImportFailedError | BrowserImportPolicyError>;
118 }
119 >()("@t3tools/desktop/preview/BrowserImport/BrowserImport") {}
120
@@ -150,6 +195,7 @@ export const writeCookies = Effect.fn("BrowserImport.writeCookies")(function* (
195 /** @public */
196 export const make = Effect.gen(function* BrowserImportMake() {
197 const browserSession = yield* BrowserSession.BrowserSession;
198 + const managedPolicy = yield* DesktopManagedPolicy.DesktopManagedPolicy;
199 const platform = yield* HostProcess.Platform;
200 const executablePath = yield* HostProcess.ExecutablePath;
201 const platformServices = yield* Effect.context<
@@ -177,6 +223,7 @@ export const make = Effect.gen(function* BrowserImportMake() {
223 readonly persistent: boolean;
224 readonly namespace?: BrowserSession.BrowserSessionPartitionNamespace;
225 }) {
226 + yield* checkBrowserImportPolicy(managedPolicy.read);
227 const definition = BROWSER_IMPORT_SOURCES.find(
228 (candidate) => candidate.id === input.input.sourceId,
229 );
apps/desktop/src/updates/DesktopUpdatePolicy.ts new
+89
@@ -0,0 +1,89 @@
1 +/**
2 + * DesktopUpdatePolicy - what the administrator's managed policy allows the desktop updater to do.
3 + * The desktop reads the policy file itself, before any backend runs, and fails closed: a policy it
4 + * cannot read turns updates off.
5 + *
6 + * @module DesktopUpdatePolicy
7 + */
8 +import {
9 + managedUpdatesMessage,
10 + type ManagedPolicyDocument,
11 + type ManagedUpdatesMode,
12 +} from "@t3tools/contracts";
13 +import * as Context from "effect/Context";
14 +import * as Effect from "effect/Effect";
15 +import * as Layer from "effect/Layer";
16 +
17 +import * as DesktopManagedPolicy from "../app/DesktopManagedPolicy.ts";
18 +import * as DesktopObservability from "../app/DesktopObservability.ts";
19 +
20 +export interface UpdatePolicy {
21 + readonly mode: ManagedUpdatesMode;
22 + readonly feedUrl: string | undefined;
23 + readonly allowNightly: boolean;
24 + /** Why the updater is restricted, shown in place of update actions; `null` when unmanaged. */
25 + readonly message: string | null;
26 +}
27 +
28 +export class DesktopUpdatePolicy extends Context.Service<DesktopUpdatePolicy, UpdatePolicy>()(
29 + "@t3tools/desktop/updates/DesktopUpdatePolicy",
30 +) {}
31 +
32 +export const unmanagedUpdatePolicy: UpdatePolicy = {
33 + mode: "auto",
34 + feedUrl: undefined,
35 + allowNightly: true,
36 + message: null,
37 +};
38 +
39 +function resolveUpdatePolicy(document: ManagedPolicyDocument | undefined): UpdatePolicy {
40 + const updates = document?.limits?.updates;
41 + if (document === undefined || updates === undefined) return unmanagedUpdatePolicy;
42 + return {
43 + mode: updates.mode,
44 + feedUrl: updates.feedUrl,
45 + allowNightly: updates.allowNightly ?? true,
46 + message: managedUpdatesMessage(document.organization),
47 + };
48 +}
49 +
50 +const { logInfo, logError } = DesktopObservability.makeComponentLogger("desktop-update-policy");
51 +
52 +const make = Effect.gen(function* () {
53 + return yield* (yield* DesktopManagedPolicy.DesktopManagedPolicy).read.pipe(
54 + Effect.map((found) => ({
55 + source: found?.source,
56 + policy: resolveUpdatePolicy(found?.document),
57 + })),
58 + Effect.tap(({ source, policy }) =>
59 + policy.message === null
60 + ? Effect.void
61 + : logInfo("managed policy restricts updates", {
62 + source,
63 + mode: policy.mode,
64 + customFeed: policy.feedUrl !== undefined,
65 + allowNightly: policy.allowNightly,
66 + }),
67 + ),
68 + Effect.map(({ policy }) => policy),
69 + Effect.catchTags({
70 + ManagedPolicyFileError: (error) =>
71 + logError("updates are off because the managed policy cannot be used", {
72 + path: error.path,
73 + reason: error.reason,
74 + }).pipe(
75 + Effect.as<UpdatePolicy>({
76 + mode: "off",
77 + feedUrl: undefined,
78 + allowNightly: false,
79 + message: `Updates are off because T3 Code cannot use the managed policy at ${error.path}. Contact your administrator.`,
80 + }),
81 + ),
82 + }),
83 + );
84 +});
85 +
86 +export const layer = Layer.effect(DesktopUpdatePolicy, make);
87 +
88 +export const layerTest = (policy: UpdatePolicy = unmanagedUpdatePolicy) =>
89 + Layer.succeed(DesktopUpdatePolicy, policy);
apps/desktop/src/updates/DesktopUpdates.test.ts
+113
@@ -18,6 +18,7 @@ import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
18 import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
19 import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
20 import * as DesktopState from "../app/DesktopState.ts";
21 +import * as DesktopUpdatePolicy from "./DesktopUpdatePolicy.ts";
22 import * as DesktopUpdates from "./DesktopUpdates.ts";
23 import { flushCallbacks, makeHarness } from "./updatesTestHarness.ts";
24
@@ -963,3 +964,115 @@ describe("describeUpdateErrorCause", () => {
964 assert.equal(DesktopUpdates.describeUpdateErrorCause(unreadable), "UnknownError");
965 });
966 });
967 +
968 +describe("DesktopUpdates under a managed policy", () => {
969 + const message = "Example Corp manages T3 Code updates.";
970 + const managed = (
971 + policy: Partial<DesktopUpdatePolicy.UpdatePolicy>,
972 + ): DesktopUpdatePolicy.UpdatePolicy => ({
973 + ...DesktopUpdatePolicy.unmanagedUpdatePolicy,
974 + message,
975 + ...policy,
976 + });
977 +
978 + it.effect("never checks when updates are off", () => {
979 + const harness = makeHarness({ policy: managed({ mode: "off" }) });
980 +
981 + return Effect.scoped(
982 + Effect.gen(function* () {
983 + const updates = yield* DesktopUpdates.DesktopUpdates;
984 + yield* updates.configure;
985 + yield* TestClock.adjust("10 minutes");
986 +
987 + const state = yield* updates.getState;
988 + assert.equal(state.status, "disabled");
989 + assert.equal(state.message, message);
990 + assert.isFalse((yield* updates.check("menu")).checked);
991 + assert.deepEqual(yield* updates.disabledReason, Option.some(message));
992 + assert.equal(harness.checkCount(), 0);
993 + assert.equal(harness.listenerCount(), 0);
994 + }),
995 + ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
996 + });
997 +
998 + it.effect("updates from the administrator's feed", () => {
999 + const harness = makeHarness({
1000 + // Any user can set the mock flag; it must not redirect a managed feed.
1001 + env: { T3CODE_DESKTOP_MOCK_UPDATES: "true" },
1002 + policy: managed({ feedUrl: "https://updates.example.com/t3code" }),
1003 + });
1004 +
1005 + return Effect.scoped(
1006 + Effect.gen(function* () {
1007 + const updates = yield* DesktopUpdates.DesktopUpdates;
1008 + yield* updates.configure;
1009 + assert.equal((yield* updates.getState).status, "idle");
1010 + assert.deepEqual(harness.feedUrls(), [
1011 + { provider: "generic", url: "https://updates.example.com/t3code" },
1012 + ]);
1013 + }),
1014 + ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
1015 + });
1016 +
1017 + it.effect("refuses the nightly channel without nightly", () => {
1018 + const harness = makeHarness({ policy: managed({ allowNightly: false }) });
1019 +
1020 + return Effect.scoped(
1021 + Effect.gen(function* () {
1022 + const updates = yield* DesktopUpdates.DesktopUpdates;
1023 + yield* updates.configure;
1024 + const error = yield* updates.setChannel("nightly").pipe(Effect.flip);
1025 + assert.equal(error._tag, "DesktopUpdateChannelManagedError");
1026 + assert.equal((yield* updates.getState).channel, "latest");
1027 + }),
1028 + ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
1029 + });
1030 +
1031 + it.effect("does not report the channel as the only block when updates are off anyway", () => {
1032 + const harness = makeHarness({
1033 + appVersion: "1.2.3-nightly.20261028.1",
1034 + env: { T3CODE_DISABLE_AUTO_UPDATE: "true" },
1035 + policy: managed({ allowNightly: false, feedUrl: "https://updates.example.com/t3code" }),
1036 + });
1037 +
1038 + return Effect.scoped(
1039 + Effect.gen(function* () {
1040 + const updates = yield* DesktopUpdates.DesktopUpdates;
1041 + yield* updates.configure;
1042 + const state = yield* updates.getState;
1043 + assert.isFalse(state.enabled);
1044 + assert.isUndefined(state.channelBlockedByPolicy);
1045 + }),
1046 + ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
1047 + });
1048 +
1049 + it.effect("holds a nightly install until its user switches to stable", () => {
1050 + const harness = makeHarness({
1051 + appVersion: "1.2.3-nightly.20261028.1",
1052 + // A managed app ignores the mock feed, so give it a real one.
1053 + policy: managed({ allowNightly: false, feedUrl: "https://updates.example.com/t3code" }),
1054 + });
1055 +
1056 + return Effect.scoped(
1057 + Effect.gen(function* () {
1058 + const updates = yield* DesktopUpdates.DesktopUpdates;
1059 + yield* updates.configure;
1060 + yield* TestClock.adjust("10 minutes");
1061 +
1062 + const held = yield* updates.getState;
1063 + assert.equal(held.channel, "nightly");
1064 + assert.equal(held.status, "disabled");
1065 + assert.include(held.message ?? "", message);
1066 + assert.isTrue(held.channelBlockedByPolicy);
1067 + assert.isFalse((yield* updates.check("menu")).checked);
1068 + assert.equal(harness.checkCount(), 0);
1069 +
1070 + const stable = yield* updates.setChannel("latest");
1071 + assert.equal(stable.channel, "latest");
1072 + assert.isTrue(stable.enabled);
1073 + assert.isUndefined(stable.channelBlockedByPolicy);
1074 + assert.equal(harness.checkCount(), 1);
1075 + }),
1076 + ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
1077 + });
1078 +});
apps/desktop/src/updates/DesktopUpdates.ts
+67 -4
@@ -34,6 +34,7 @@ import * as ElectronUpdater from "../electron/ElectronUpdater.ts";
34 import * as ElectronWindow from "../electron/ElectronWindow.ts";
35 import * as IpcChannels from "../ipc/channels.ts";
36 import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
37 +import * as DesktopUpdatePolicy from "./DesktopUpdatePolicy.ts";
38 import { normalizeDesktopUpdateReleaseNotes } from "./releaseNotes.ts";
39 import { desktopUpdateChannelOf } from "@t3tools/shared/cliRelease";
40 import { compareSemverVersions } from "@t3tools/shared/semver";
@@ -161,9 +162,22 @@ export class DesktopUpdateUnexpectedActionError extends Schema.TaggedError<Deskt
162 }
163 }
164
165 +export class DesktopUpdateChannelManagedError extends Schema.TaggedError<DesktopUpdateChannelManagedError>()(
166 + "DesktopUpdateChannelManagedError",
167 + {
168 + channel: DesktopUpdateChannelSchema,
169 + policyMessage: Schema.String,
170 + },
171 +) {
172 + override get message(): string {
173 + return `${this.policyMessage} The ${this.channel} channel is not available.`;
174 + }
175 +}
176 +
177 export const DesktopUpdateSetChannelError = Schema.Union([
178 DesktopUpdateActionInProgressError,
179 DesktopUpdateChannelPersistenceError,
180 + DesktopUpdateChannelManagedError,
181 ]);
182 export type DesktopUpdateSetChannelError = typeof DesktopUpdateSetChannelError.Type;
183
@@ -315,6 +329,7 @@ function shouldBroadcastDownloadProgress(
329 }
330
331 function getAutoUpdateDisabledReason(args: {
332 + policy: DesktopUpdatePolicy.UpdatePolicy;
333 isDevelopment: boolean;
334 isPackaged: boolean;
335 platform: NodeJS.Platform;
@@ -323,6 +338,9 @@ function getAutoUpdateDisabledReason(args: {
338 disabledByEnv: boolean;
339 hasUpdateFeedConfig: boolean;
340 }): string | null {
341 + if (args.policy.mode === "off") {
342 + return args.policy.message ?? "Updates are turned off on this machine.";
343 + }
344 if (!args.hasUpdateFeedConfig) {
345 return "Automatic updates are not available because no update feed is configured.";
346 }
@@ -352,6 +370,9 @@ export const make = Effect.gen(function* () {
370 const environment = yield* DesktopEnvironment.DesktopEnvironment;
371 const fileSystem = yield* FileSystem.FileSystem;
372 const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
373 + const policy = yield* DesktopUpdatePolicy.DesktopUpdatePolicy;
374 + // Any user can set the mock flag, so it never replaces an administrator's update source.
375 + const mockUpdates = config.mockUpdates && policy.message === null;
376
377 const appUpdateYmlConfigRef = yield* Ref.make<Option.Option<AppUpdateYmlConfig>>(Option.none());
378 const activeUpdateActionRef = yield* Ref.make<Option.Option<UpdateAction>>(Option.none());
@@ -431,13 +452,17 @@ export const make = Effect.gen(function* () {
452 : false;
453
454 const hasUpdateFeedConfig = Ref.get(appUpdateYmlConfigRef).pipe(
434 - Effect.map((appUpdateYmlConfig) => Option.isSome(appUpdateYmlConfig) || config.mockUpdates),
455 + Effect.map(
456 + (appUpdateYmlConfig) =>
457 + Option.isSome(appUpdateYmlConfig) || mockUpdates || policy.feedUrl !== undefined,
458 + ),
459 );
460
461 const resolveDisabledReason = Effect.gen(function* () {
462 const hasFeedConfig = yield* hasUpdateFeedConfig;
463 return Option.fromNullishOr(
464 getAutoUpdateDisabledReason({
465 + policy,
466 isDevelopment: environment.isDevelopment,
467 isPackaged: environment.isPackaged,
468 platform: environment.platform,
@@ -449,6 +474,18 @@ export const make = Effect.gen(function* () {
474 );
475 });
476
477 + // Without nightly, an install on that channel stays put until its user picks stable: moving it
478 + // silently would be a downgrade nobody asked for, and checking nightly would break the policy.
479 + const channelBlockedReason = (channel: DesktopUpdateChannel): Option.Option<string> =>
480 + channel === "nightly" && !policy.allowNightly
481 + ? Option.some(
482 + `${policy.message ?? "Nightly updates are turned off on this machine."} Switch to the stable channel to keep getting updates.`,
483 + )
484 + : Option.none();
485 +
486 + const resolveStateDisabledReason = (channel: DesktopUpdateChannel) =>
487 + resolveDisabledReason.pipe(Effect.map(Option.orElse(() => channelBlockedReason(channel))));
488 +
489 const activeUpdateAction = Ref.get(activeUpdateActionRef);
490
491 const tryStartUpdateAction = (action: UpdateAction): Effect.Effect<boolean> =>
@@ -500,6 +537,8 @@ export const make = Effect.gen(function* () {
537 if (!(yield* Ref.get(updaterConfiguredRef))) return false;
538
539 const state = yield* Ref.get(updateStateRef);
540 + // A configured updater is disabled only by a channel the managed policy blocks.
541 + if (state.status === "disabled") return false;
542 if (state.status === "downloading") {
543 yield* logUpdaterInfo("skipping update check while update is active", {
544 reason,
@@ -659,6 +698,11 @@ export const make = Effect.gen(function* () {
698 Ref.get(notAppliedVersionRef).pipe(
699 Effect.map((notAppliedVersion) => ({
700 ...createBaseUpdateState(channel, disabledReason, environment),
701 + // Callers fall back to the channel's reason only when nothing else turns updates off.
702 + ...(Option.isSome(disabledReason) &&
703 + disabledReason.value === Option.getOrUndefined(channelBlockedReason(channel))
704 + ? { channelBlockedByPolicy: true as const }
705 + : {}),
706 ...Option.match(notAppliedVersion, {
707 onNone: () => ({}),
708 onSome: (version) => ({ notAppliedVersion: version }),
@@ -1064,7 +1108,9 @@ export const make = Effect.gen(function* () {
1108 }),
1109 ),
1110 emitState,
1067 - disabledReason: resolveDisabledReason,
1111 + disabledReason: Ref.get(updateStateRef).pipe(
1112 + Effect.flatMap((state) => resolveStateDisabledReason(state.channel)),
1113 + ),
1114 configure: Effect.gen(function* () {
1115 const context = yield* Effect.context<never>();
1116 const runEffect = (effect: Effect.Effect<void>) => {
@@ -1083,16 +1129,27 @@ export const make = Effect.gen(function* () {
1129 });
1130 }
1131
1086 - if (config.mockUpdates) {
1132 + if (mockUpdates) {
1133 yield* electronUpdater.setFeedURL({
1134 provider: "generic",
1135 url: `http://localhost:${config.mockUpdateServerPort}`,
1136 } as ElectronUpdater.ElectronUpdaterFeedUrl);
1137 + } else if (policy.feedUrl !== undefined) {
1138 + // The administrator's mirror replaces the GitHub feed baked into app-update.yml.
1139 + yield* electronUpdater.setFeedURL({
1140 + provider: "generic",
1141 + url: policy.feedUrl,
1142 + } as ElectronUpdater.ElectronUpdaterFeedUrl);
1143 }
1144
1145 const settings = yield* desktopSettings.get;
1146 const disabledReason = yield* resolveDisabledReason;
1095 - yield* setState(yield* baseUpdateState(settings.updateChannel, disabledReason));
1147 + yield* setState(
1148 + yield* baseUpdateState(
1149 + settings.updateChannel,
1150 + Option.orElse(disabledReason, () => channelBlockedReason(settings.updateChannel)),
1151 + ),
1152 + );
1153 if (Option.isSome(disabledReason)) {
1154 return;
1155 }
@@ -1141,6 +1198,12 @@ export const make = Effect.gen(function* () {
1198 options?: { readonly minimumVersion?: string | undefined },
1199 ) {
1200 yield* Effect.annotateCurrentSpan({ channel: nextChannel });
1201 + if (Option.isSome(channelBlockedReason(nextChannel))) {
1202 + return yield* new DesktopUpdateChannelManagedError({
1203 + channel: nextChannel,
1204 + policyMessage: policy.message ?? "Your administrator manages T3 Code updates.",
1205 + });
1206 + }
1207 // A background check holds the updater only briefly, so wait it out instead of refusing.
1208 const activeAction = yield* tryStartChannelChange.pipe(
1209 Effect.repeat({
apps/desktop/src/updates/updatesTestHarness.ts
+3
@@ -13,6 +13,7 @@ import * as ElectronUpdater from "../electron/ElectronUpdater.ts";
13 import * as ElectronWindow from "../electron/ElectronWindow.ts";
14 import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
15 import * as DesktopState from "../app/DesktopState.ts";
16 +import * as DesktopUpdatePolicy from "./DesktopUpdatePolicy.ts";
17 import * as DesktopUpdates from "./DesktopUpdates.ts";
18
19 export const flushCallbacks = Effect.yieldNow;
@@ -35,6 +36,7 @@ export interface UpdatesHarnessOptions {
36 readonly platform?: NodeJS.Platform;
37 readonly packageType?: string | undefined;
38 readonly installRecord?: string | undefined;
39 + readonly policy?: DesktopUpdatePolicy.UpdatePolicy;
40 readonly appVersion?: string;
41 /** Starts from in-memory settings with this track saved, as after a restart. */
42 readonly savedChannel?: DesktopAppSettings.DesktopSettings["updateChannel"];
@@ -271,6 +273,7 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) {
273
274 const layer = DesktopUpdates.layer.pipe(
275 Layer.provide(layerFileSystem),
276 + Layer.provide(DesktopUpdatePolicy.layerTest(options.policy)),
277 Layer.provideMerge(layerUpdater),
278 Layer.provideMerge(layerWindow),
279 Layer.provideMerge(layerBackend),
apps/desktop/src/wsl/DesktopWslEnvironment.test.ts
+35 -1
@@ -1,10 +1,18 @@
1 // @effect-diagnostics nodeBuiltinImport:off - the executed suite runs the generated install script through a real POSIX shell.
2 -import { describe, it } from "@effect/vitest";
2 +import { assert, describe, it } from "@effect/vitest";
3 +import * as Effect from "effect/Effect";
4 +import * as FileSystem from "effect/FileSystem";
5 +import * as Layer from "effect/Layer";
6 +import * as Path from "effect/Path";
7 import { afterAll, expect } from "vite-plus/test";
8 import * as NodeChildProcess from "node:child_process";
9
10 +import { ManagedPolicyFileError } from "@t3tools/shared/managedPolicyFile";
11 +
12 +import * as DesktopManagedPolicy from "../app/DesktopManagedPolicy.ts";
13 import {
14 buildWslRuntimeInstallScript,
15 + makeIsAvailable,
16 buildWslRuntimeInvalidateScript,
17 buildWslRuntimePruneScript,
18 buildWslRuntimeProbeScript,
@@ -425,3 +433,29 @@ describe("parseResolvedPath", () => {
433 );
434 });
435 });
436 +
437 +// Path.layer joins with POSIX separators here, so the test windir is a POSIX path.
438 +const WSL_EXE = "/windows/System32/wsl.exe";
439 +
440 +const isAvailable = (policy?: Parameters<typeof DesktopManagedPolicy.layerTest>[0]) =>
441 + makeIsAvailable("win32", "/windows").pipe(
442 + Effect.provide(
443 + Layer.mergeAll(
444 + FileSystem.layerNoop({ exists: (path) => Effect.succeed(path === WSL_EXE) }),
445 + Path.layer,
446 + DesktopManagedPolicy.layerTest(policy),
447 + ),
448 + ),
449 + );
450 +
451 +describe("makeIsAvailable", () => {
452 + it.effect("turns WSL off on a machine with a managed policy, even an invalid one", () =>
453 + Effect.gen(function* () {
454 + assert.isTrue(yield* isAvailable());
455 + assert.isFalse(yield* isAvailable({ schemaVersion: 1, organization: "Example Corp" }));
456 + assert.isFalse(
457 + yield* isAvailable(new ManagedPolicyFileError({ path: "/test", reason: "bad JSON" })),
458 + );
459 + }),
460 + );
461 +});
apps/desktop/src/wsl/DesktopWslEnvironment.ts
+19 -3
@@ -13,6 +13,7 @@ import { buildRemoteNodeEnvScript } from "@t3tools/ssh/tunnel";
13 import { satisfiesSemverRange } from "@t3tools/shared/semver";
14
15 import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
16 +import * as DesktopManagedPolicy from "../app/DesktopManagedPolicy.ts";
17 import { parseWslDistroList, type WslDistro } from "./wslPathParsing.ts";
18
19 const PROCESS_TERMINATE_GRACE = Duration.seconds(1);
@@ -1027,15 +1028,26 @@ const getUserHomeImpl = (
1028 Effect.orElseSucceed(() => Option.none<string>()),
1029 );
1030
1030 -const makeIsAvailable = Effect.fn("DesktopWslEnvironment.makeIsAvailable")(function* (
1031 +export const makeIsAvailable = Effect.fn("DesktopWslEnvironment.makeIsAvailable")(function* (
1032 platform: NodeJS.Platform,
1033 windir: string,
1033 -): Effect.fn.Return<boolean, never, FileSystem.FileSystem | Path.Path> {
1034 +): Effect.fn.Return<
1035 + boolean,
1036 + never,
1037 + FileSystem.FileSystem | Path.Path | DesktopManagedPolicy.DesktopManagedPolicy
1038 +> {
1039 if (platform !== "win32") return false;
1040 const path = yield* Path.Path;
1041 const fileSystem = yield* FileSystem.FileSystem;
1042 const wslExePath = path.join(windir, "System32", "wsl.exe");
1038 - return yield* fileSystem.exists(wslExePath).pipe(Effect.orElseSucceed(() => false));
1043 + if (!(yield* fileSystem.exists(wslExePath).pipe(Effect.orElseSucceed(() => false)))) {
1044 + return false;
1045 + }
1046 + // A server in WSL reads Linux's policy, never this machine's, so a managed machine runs none.
1047 + return yield* (yield* DesktopManagedPolicy.DesktopManagedPolicy).read.pipe(
1048 + Effect.map((found) => found === undefined),
1049 + Effect.orElseSucceed(() => false),
1050 + );
1051 });
1052
1053 export interface DesktopWslEnvironmentTestStub {
@@ -1140,6 +1152,10 @@ export const layer = Layer.effect(
1152 const wslAvailable = yield* makeIsAvailable(environment.platform, windir).pipe(
1153 Effect.provideService(FileSystem.FileSystem, fileSystem),
1154 Effect.provideService(Path.Path, environment.path),
1155 + Effect.provideService(
1156 + DesktopManagedPolicy.DesktopManagedPolicy,
1157 + yield* DesktopManagedPolicy.DesktopManagedPolicy,
1158 + ),
1159 Effect.withSpan("desktop.wsl.isAvailable"),
1160 );
1161 const isAvailable = Effect.succeed(wslAvailable);
apps/mobile/src/features/settings/SettingsEnvironmentDetailRouteScreen.tsx
+41 -17
@@ -4,6 +4,7 @@ import { useNavigation, type StaticScreenProps } from "@react-navigation/native"
4 import {
5 AuthProvidersManageScope,
6 AuthOrchestrationReadScope,
7 + managedUpdatesDenial,
8 type EnvironmentId,
9 type ServerProvider,
10 } from "@t3tools/contracts";
@@ -13,7 +14,7 @@ import * as Cause from "effect/Cause";
14 import * as Exit from "effect/Exit";
15 import { AsyncResult } from "effect/reactivity";
16 import { useRef, useState } from "react";
16 -import { View } from "react-native";
17 +import { Linking, View } from "react-native";
18 import { useSafeAreaInsets } from "react-native-safe-area-context";
19
20 import { AppText as Text } from "../../components/ui/AppText";
@@ -94,6 +95,10 @@ function EnvironmentDetail({ environmentId }: { readonly environmentId: Environm
95 const version = config?.environment.serverVersion;
96 const checkedRelease = release?.fromVersion === version ? release : null;
97 const capabilities = config?.environment.capabilities;
98 + const managedPolicy = config?.managedPolicy;
99 + const supportUrl = managedPolicy?.supportUrl;
100 + // The server refuses checks and installs; say so instead of offering them.
101 + const updatesDenial = managedUpdatesDenial(managedPolicy);
102
103 async function run(label: string, action: () => Promise<void>) {
104 if (pendingRef.current) return;
@@ -230,6 +235,14 @@ function EnvironmentDetail({ environmentId }: { readonly environmentId: Environm
235 <SettingsSection title="T3 Code">
236 <View className="gap-1 p-4">
237 <Text className="text-base text-foreground">Version {version}</Text>
238 + {managedPolicy ? (
239 + <Text className="text-sm text-foreground-muted">
240 + Managed by {managedPolicy.organization}
241 + </Text>
242 + ) : null}
243 + {updatesDenial ? (
244 + <Text className="text-sm text-foreground-muted">{updatesDenial}</Text>
245 + ) : null}
246 {running ? (
247 <Text className="text-sm text-foreground-muted">
248 {updateState.stage === "resuming"
@@ -241,7 +254,7 @@ function EnvironmentDetail({ environmentId }: { readonly environmentId: Environm
254 {updateState.message}
255 </Text>
256 ) : null}
244 - {checkedRelease ? (
257 + {checkedRelease && !updatesDenial ? (
258 <Text className="text-sm text-foreground-muted">
259 {checkedRelease.targetVersion
260 ? `Version ${checkedRelease.targetVersion} is available.`
@@ -249,6 +262,7 @@ function EnvironmentDetail({ environmentId }: { readonly environmentId: Environm
262 </Text>
263 ) : null}
264 {checkedRelease?.targetVersion &&
265 + !updatesDenial &&
266 !supportsEnvironmentUpdate(config.environment.capabilities) ? (
267 <Text className="text-sm text-foreground-muted">
268 {capabilities?.serverSelfUpdate === "desktop-managed"
@@ -257,22 +271,32 @@ function EnvironmentDetail({ environmentId }: { readonly environmentId: Environm
271 </Text>
272 ) : null}
273 </View>
260 - <SettingsActionRow
261 - icon="arrow.clockwise"
262 - label="Check for updates"
263 - disabled={disabled}
264 - loading={pending === "check"}
265 - onPress={() => {
266 - if (disabled) return;
267 - const fromVersion = config.environment.serverVersion;
268 - void run("check", async () => {
269 - const exit = await checkRelease(async () => fromVersion);
270 - // `run` owns the error message, so a failed lookup rethrows to it.
271 - if (Exit.isFailure(exit)) throw Cause.squash(exit.cause);
272 - });
273 - }}
274 - />
274 + {supportUrl ? (
275 + <SettingsActionRow
276 + icon="questionmark.bubble"
277 + label={`Get help from ${managedPolicy.organization}`}
278 + onPress={() => void Linking.openURL(supportUrl).catch(() => undefined)}
279 + />
280 + ) : null}
281 + {updatesDenial ? null : (
282 + <SettingsActionRow
283 + icon="arrow.clockwise"
284 + label="Check for updates"
285 + disabled={disabled}
286 + loading={pending === "check"}
287 + onPress={() => {
288 + if (disabled) return;
289 + const fromVersion = config.environment.serverVersion;
290 + void run("check", async () => {
291 + const exit = await checkRelease(async () => fromVersion);
292 + // `run` owns the error message, so a failed lookup rethrows to it.
293 + if (Exit.isFailure(exit)) throw Cause.squash(exit.cause);
294 + });
295 + }}
296 + />
297 + )}
298 {checkedRelease?.targetVersion &&
299 + !updatesDenial &&
300 supportsEnvironmentUpdate(config.environment.capabilities) ? (
301 <SettingsActionRow
302 icon="arrow.up.circle"
apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx
+23 -5
@@ -1,6 +1,12 @@
1 import * as Dialog from "../../components/ui/Dialog";
2 -import { AuthRelayWriteScope } from "@t3tools/contracts";
2 +import {
3 + AuthRelayWriteScope,
4 + managedCapabilityDenial,
5 + type EnvironmentId,
6 +} from "@t3tools/contracts";
7 import { readEnvironmentScope } from "../../state/session";
8 +import { appAtomRegistry } from "../../state/atom-registry";
9 +import { serverEnvironment } from "../../state/server";
10 import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView";
11 import { useAuth } from "@clerk/expo";
12 import { useAtomSet, useAtomValue } from "@effect/atom-react";
@@ -44,6 +50,20 @@ import { SettingsSwitchRow } from "./components/SettingsSwitchRow";
50 import { SettingsScreen } from "./components/SettingsScreen";
51 import { resolveAgentAwarenessPlatformPresentation } from "./SettingsRouteScreen.logic";
52
53 +/**
54 + * A policy that turns Connect off refuses relay links and preferences, which would fail the
55 + * whole batch, so those environments are skipped like ones this session cannot configure.
56 + */
57 +function canLinkEnvironmentToConnect(environmentId: EnvironmentId) {
58 + const policy = appAtomRegistry.get(
59 + serverEnvironment.configValueAtom(environmentId),
60 + )?.managedPolicy;
61 + return (
62 + readEnvironmentScope(environmentId, AuthRelayWriteScope) &&
63 + managedCapabilityDenial(policy, "connect") === undefined
64 + );
65 +}
66 +
67 type NotificationStatus = "checking" | "enabled" | "disabled" | "unsupported";
68 type LiveActivityStatus = "checking" | "enabled" | "disabled" | "signed-out" | "linking";
69
@@ -272,8 +292,7 @@ function ConfiguredSettingsNotificationsRouteScreen() {
292 const updateResult = await settleAsyncResult(() =>
293 runtime.runPromiseExit(
294 setLiveActivityUpdatesEnabled({
275 - canConfigureEnvironment: (environmentId) =>
276 - readEnvironmentScope(environmentId, AuthRelayWriteScope),
295 + canConfigureEnvironment: canLinkEnvironmentToConnect,
296 enabled: true,
297 previousEnabled: liveActivitiesPreferenceEnabled,
298 clerkToken: tokenResult.value,
@@ -351,8 +370,7 @@ function ConfiguredSettingsNotificationsRouteScreen() {
370 const updateResult = await settleAsyncResult(() =>
371 runtime.runPromiseExit(
372 setLiveActivityUpdatesEnabled({
354 - canConfigureEnvironment: (environmentId) =>
355 - readEnvironmentScope(environmentId, AuthRelayWriteScope),
373 + canConfigureEnvironment: canLinkEnvironmentToConnect,
374 enabled: false,
375 previousEnabled: liveActivitiesPreferenceEnabled,
376 clerkToken: token,
apps/mobile/src/features/settings/SettingsProviderAccountsRouteScreen.tsx
+13 -2
@@ -6,6 +6,7 @@ import {
6 } from "@t3tools/client-runtime/state/runtime";
7 import {
8 AuthProvidersManageScope,
9 + isManagedDriverAllowed,
10 type ProviderAuthResponse,
11 type ServerProvider,
12 } from "@t3tools/contracts";
@@ -64,7 +65,7 @@ export function SettingsProviderAccountsRouteScreen() {
65 </View>
66 ) : (
67 <>
67 - {(providersByEnvironment.get(environment.environmentId) ?? [])
68 + {managedProviders(environment, providersByEnvironment)
69 .filter(canManageProvider)
70 .map((provider, index) => (
71 <ProviderAccount
@@ -74,7 +75,7 @@ export function SettingsProviderAccountsRouteScreen() {
75 divider={index > 0}
76 />
77 ))}
77 - {!(providersByEnvironment.get(environment.environmentId) ?? []).some(
78 + {!managedProviders(environment, providersByEnvironment).some(
79 canManageProvider,
80 ) ? (
81 <Text className="p-4 text-foreground-muted">
@@ -92,6 +93,16 @@ export function SettingsProviderAccountsRouteScreen() {
93 );
94 }
95
96 +/** Providers the environment's managed policy allows; the rest cannot run or sign in. */
97 +function managedProviders(
98 + environment: SettingsTarget,
99 + providersByEnvironment: ReadonlyMap<string, ReadonlyArray<ServerProvider>>,
100 +) {
101 + return (providersByEnvironment.get(environment.environmentId) ?? []).filter((provider) =>
102 + isManagedDriverAllowed(environment.serverConfig.managedPolicy, provider.driver),
103 + );
104 +}
105 +
106 function canManageProvider(provider: ServerProvider) {
107 return Boolean(
108 provider.setup?.canAuthenticate || (provider.driver === "acpRegistry" && provider.installed),
apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx
+27 -3
@@ -2,6 +2,8 @@ import * as Dialog from "../../components/ui/Dialog";
2 import { useAtomValue } from "@effect/atom-react";
3 import {
4 AuthOrchestrationOperateScope,
5 + clampManagedRuntimeMode,
6 + managedCapabilityDenial,
7 resolveProjectProviderInstanceEnabled,
8 } from "@t3tools/contracts";
9 import { readEnvironmentScope } from "../../state/session";
@@ -690,6 +692,8 @@ function TaskForm({
692 .sort((left, right) => Number(right.pinnedAt != null) - Number(left.pinnedAt != null));
693 const config = useEnvironmentServerConfig(environmentId);
694 const modelOptions = buildModelOptions(config, null, undefined, draft.projectId);
695 + // Existing webhook tasks keep the option so they can still switch to a timer.
696 + const webhookDenial = managedCapabilityDenial(config?.managedPolicy, "webhookTasks");
697 const canOperate = useAtomValue(
698 serverEnvironment.upsertScheduledTask.permissionAtom(environmentId),
699 );
@@ -800,7 +804,9 @@ function TaskForm({
804 baseRef: draft.baseRef.trim() || "main",
805 startFromOrigin: draft.startFromOrigin,
806 },
803 - runtimeMode: draft.runtimeMode,
807 + // Tasks have no mode picker; a mode above the administrator's ceiling is refused.
808 + runtimeMode:
809 + clampManagedRuntimeMode(config?.managedPolicy, draft.runtimeMode) ?? draft.runtimeMode,
810 interactionMode: draft.task?.interactionMode ?? "default",
811 creationSource: draft.task?.creationSource ?? "mobile",
812 };
@@ -992,7 +998,9 @@ function TaskForm({
998 ? [{ value: "once" as const, label: "Once" }]
999 : []),
1000 { value: "interval", label: "Interval" },
995 - { value: "webhook", label: "On webhook" },
1001 + ...(webhookDenial === undefined || draft.schedule.mode === "webhook"
1002 + ? [{ value: "webhook" as const, label: "On webhook" }]
1003 + : []),
1004 ]}
1005 selected={draft.schedule.mode}
1006 onSelect={(mode) => {
@@ -1093,6 +1101,10 @@ function TaskForm({
1101 }}
1102 />
1103 </>
1104 + ) : draft.schedule.mode === "webhook" && webhookDenial !== undefined && draft.enabled ? (
1105 + <Text className="border-t border-border-subtle px-4 py-3 text-sm text-foreground-muted">
1106 + {`${webhookDenial} Switch the task to a timer, or turn it off, to save it.`}
1107 + </Text>
1108 ) : draft.schedule.mode === "once" ? (
1109 (["date", "time"] as const).map((field) => {
1110 const runAt = new Date(draft.schedule.runAt);
@@ -1256,7 +1268,14 @@ function TaskForm({
1268 tone="primary"
1269 fullWidth
1270 loading={saving}
1259 - disabled={!canOperate || dictationPending || taskMissing || environmentUnavailable}
1271 + disabled={
1272 + !canOperate ||
1273 + dictationPending ||
1274 + taskMissing ||
1275 + environmentUnavailable ||
1276 + // The server refuses an enabled webhook task under this policy.
1277 + (draft.enabled && draft.schedule.mode === "webhook" && webhookDenial !== undefined)
1278 + }
1279 onPress={() => void save()}
1280 label={saving ? "Saving…" : draft.task ? "Save changes" : "Create task"}
1281 />
@@ -1452,6 +1471,11 @@ function EnvironmentTasks({
1471 ? ` · ${formatNextScheduledTaskRun(task.nextRunAt, now)}`
1472 : ""}
1473 </Text>
1474 + {task.blockedByPolicy ? (
1475 + <Text className="text-sm text-foreground-muted" numberOfLines={2}>
1476 + {task.blockedByPolicy}
1477 + </Text>
1478 + ) : null}
1479 {task.lastRunError ? (
1480 <Text className="text-sm text-danger-foreground" numberOfLines={2}>
1481 Last run failed: {task.lastRunError}
apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.test.tsx
+4 -1
@@ -64,7 +64,10 @@ vi.mock("../../state/environments", () => ({ useEnvironments: () => ({ environme
64 vi.mock("../../state/use-atom-command", () => ({
65 useAtomCommand: () => mocks.updateSettings,
66 }));
67 -vi.mock("../threads/thread-settings-options", () => ({ RUNTIME_MODE_CHOICES: [] }));
67 +vi.mock("../threads/thread-settings-options", () => ({
68 + RUNTIME_MODE_CHOICES: [],
69 + withManagedRuntimeModeLimits: (choices: readonly unknown[]) => choices,
70 +}));
71 vi.mock("../../components/ui/ScreenScrollView", () => ({ ScreenScrollView: Children }));
72 vi.mock("../../components/ui/AppText", () => ({ AppText: Children }));
73 vi.mock("../../components/ui/Button", () => ({
apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx
+75 -13
@@ -17,7 +17,10 @@ import { useRef, useState } from "react";
17 import { View } from "react-native";
18 import { useSafeAreaInsets } from "react-native-safe-area-context";
19
20 -import { RUNTIME_MODE_CHOICES } from "../threads/thread-settings-options";
20 +import {
21 + RUNTIME_MODE_CHOICES,
22 + withManagedRuntimeModeLimits,
23 +} from "../threads/thread-settings-options";
24 import { SettingsScreen } from "./components/SettingsScreen";
25 import {
26 AndroidSettingsEnvironmentFilter,
@@ -33,6 +36,7 @@ import { SettingsProjectOverridesSection } from "./components/SettingsProjectOve
36 import { useSettingsEnvironmentFilter } from "./settings-environment-filter";
37 import { useSettingsWriter } from "./useSettingsWriter";
38 import {
39 + managedSettingReason,
40 planMobileScopedSettingsClear,
41 planMobileScopedSettingsPatch,
42 resolveMobileSettingsTargets,
@@ -260,8 +264,19 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
264 });
265 };
266 const disabled = !canWriteSettings || pendingWrites > 0 || !hasConnectedSelection;
267 + const managed = (...keys: string[]) => managedSettingReason(targets, ...keys);
268 + // A locked row keeps its explanation and says who manages it.
269 + const managedSubtitle = (key: string, subtitle: string) => {
270 + const reason = managed(key);
271 + return reason === undefined ? subtitle : `${subtitle} ${reason}`;
272 + };
273 + const runtimeModeChoices = withManagedRuntimeModeLimits(
274 + RUNTIME_MODE_CHOICES,
275 + targets.map((target) => target.environment.serverConfig.managedPolicy),
276 + );
277 const disabledFor = (key: string) =>
278 disabled ||
279 + managed(key) !== undefined ||
280 (projectSelected &&
281 !PROJECT_SCOPED_SERVER_SETTING_KEYS.includes(
282 key as (typeof PROJECT_SCOPED_SERVER_SETTING_KEYS)[number],
@@ -289,6 +304,7 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
304 </Text>
305 ) : (
306 <>
307 + <ManagedPolicyNotice targets={targets} />
308 {projectSelected ? (
309 <SettingsProjectOverridesSection
310 projectLabel={selectedProject?.label ?? "Unavailable project"}
@@ -304,6 +320,7 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
320 <>
321 <SettingsSection
322 title="Default workspace"
323 + footer={managed("defaultThreadEnvMode")}
324 trailing={
325 pendingWrites === 0 && isMixed("defaultThreadEnvMode") ? (
326 <MixedValuesLabel projectSelected={projectSelected} />
@@ -329,26 +346,30 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
346 </SettingsSection>
347 <SettingsSection
348 title="Default permissions"
349 + footer={managed("defaultRuntimeMode")}
350 trailing={
351 pendingWrites === 0 && uniform("defaultRuntimeMode") === null ? (
352 <MixedValuesLabel projectSelected={projectSelected} />
353 ) : null
354 }
355 >
338 - {RUNTIME_MODE_CHOICES.map((choice, index) => (
356 + {runtimeModeChoices.map((choice, index) => (
357 <SettingsChoiceRow
358 key={choice.mode}
359 label={choice.label}
342 - description={choice.description}
360 + description={choice.disabledReason ?? choice.description}
361 selected={uniform("defaultRuntimeMode") === choice.mode}
362 separated={index > 0}
345 - disabled={disabledFor("defaultRuntimeMode")}
363 + disabled={
364 + disabledFor("defaultRuntimeMode") || choice.disabledReason !== undefined
365 + }
366 onPress={() => write({ defaultRuntimeMode: choice.mode })}
367 />
368 ))}
369 </SettingsSection>
370 <SettingsSection
371 title="Response streaming"
372 + footer={managed("responseStreamingMode")}
373 trailing={
374 pendingWrites === 0 && uniform("responseStreamingMode") === null ? (
375 <MixedValuesLabel projectSelected={projectSelected} />
@@ -371,7 +392,10 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
392 <SettingsSwitchRow
393 icon="globe"
394 label="Agent browser access"
374 - subtitle="Allow agents to use the in-app preview browser."
395 + subtitle={managedSubtitle(
396 + "enableAgentBrowserAccess",
397 + "Allow agents to use the in-app preview browser.",
398 + )}
399 value={uniform("enableAgentBrowserAccess")}
400 disabled={disabledFor("enableAgentBrowserAccess")}
401 onValueChange={(value) => write({ enableAgentBrowserAccess: value })}
@@ -393,7 +417,10 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
417 <SettingsSwitchRow
418 icon={PullRequestGlyph.merged}
419 label="Remove agent credits when merging"
396 - 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."
420 + subtitle={managedSubtitle(
421 + "removeAgentCreditsOnMerge",
422 + "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.",
423 + )}
424 value={uniform("removeAgentCreditsOnMerge")}
425 disabled={disabledFor("removeAgentCreditsOnMerge")}
426 onValueChange={(value) => write({ removeAgentCreditsOnMerge: value })}
@@ -403,7 +430,10 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
430 <SettingsSwitchRow
431 icon="arrow.down.circle"
432 label="Automatically pull"
406 - subtitle="Keep the default branch current when there are no local changes."
433 + subtitle={managedSubtitle(
434 + "defaultAutoPull",
435 + "Keep the default branch current when there are no local changes.",
436 + )}
437 value={uniform("defaultAutoPull")}
438 disabled={disabledFor("defaultAutoPull")}
439 onValueChange={(value) => write({ defaultAutoPull: value })}
@@ -418,7 +448,10 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
448 <SettingsSwitchRow
449 icon="arrow.triangle.branch"
450 label="Start from remote"
421 - 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."
451 + subtitle={managedSubtitle(
452 + "newWorktreesStartFromOrigin",
453 + "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.",
454 + )}
455 value={uniform("newWorktreesStartFromOrigin")}
456 disabled={disabledFor("newWorktreesStartFromOrigin")}
457 onValueChange={(value) => write({ newWorktreesStartFromOrigin: value })}
@@ -426,6 +459,7 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
459 </SettingsSection>
460 <SettingsSection
461 title="Worktree submodules"
462 + footer={managed("worktreeSubmodules")}
463 trailing={
464 pendingWrites === 0 && isMixed("worktreeSubmodules") ? (
465 <MixedValuesLabel projectSelected={projectSelected} />
@@ -454,7 +488,11 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
488 mode={uniform("branchNamingMode")}
489 prefix={uniform("branchNamePrefix")}
490 instructions={uniform("branchNameInstructions")}
457 - disabled={disabledFor("branchNamingMode")}
491 + disabled={{
492 + mode: disabledFor("branchNamingMode"),
493 + prefix: disabledFor("branchNamePrefix"),
494 + instructions: disabledFor("branchNameInstructions"),
495 + }}
496 onChange={write}
497 />
498 </>
@@ -491,11 +529,12 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
529 <SettingsSwitchRow
530 icon="arrow.clockwise"
531 label="Check provider updates"
494 - subtitle={
532 + subtitle={managedSubtitle(
533 + "enableProviderUpdateChecks",
534 projectSelected
535 ? "Environment-wide setting. Select All projects to change it."
497 - : "Check installed provider CLIs for newer versions and fetch model catalog updates. When off, new models may not appear."
498 - }
536 + : "Check installed provider CLIs for newer versions and fetch model catalog updates. When off, new models may not appear.",
537 + )}
538 value={uniform("enableProviderUpdateChecks")}
539 disabled={disabledFor("enableProviderUpdateChecks")}
540 onValueChange={(value) => write({ enableProviderUpdateChecks: value })}
@@ -504,7 +543,10 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
543 <SettingsSwitchRow
544 icon="arrow.uturn.forward"
545 label="Continue after restart"
507 - subtitle="Resume interrupted threads after an update or restart."
546 + subtitle={managedSubtitle(
547 + "continueThreadsAfterServerUpdate",
548 + "Resume interrupted threads after an update or restart.",
549 + )}
550 value={uniform("continueThreadsAfterServerUpdate")}
551 disabled={disabledFor("continueThreadsAfterServerUpdate")}
552 onValueChange={(value) =>
@@ -537,3 +579,23 @@ function MixedValuesLabel(props: { readonly projectSelected: boolean }) {
579 </Text>
580 );
581 }
582 +
583 +/** Locked settings are refused when saved; say so before the user tries. */
584 +function ManagedPolicyNotice(props: { readonly targets: readonly ScopedMobileSettingsTarget[] }) {
585 + const organizations = [
586 + ...new Set(
587 + props.targets.flatMap((target) => {
588 + const policy = target.environment.serverConfig.managedPolicy;
589 + return policy !== undefined && policy.lockedSettings.length > 0
590 + ? [policy.organization]
591 + : [];
592 + }),
593 + ),
594 + ];
595 + if (organizations.length === 0) return null;
596 + return (
597 + <Text className="px-2 text-sm text-foreground-muted android:px-4">
598 + Some settings are managed by {organizations.join(", ")} and cannot be changed here.
599 + </Text>
600 + );
601 +}
apps/mobile/src/features/settings/ThreadSettingsSections.tsx
+38 -23
@@ -1,5 +1,9 @@
1 import { Button } from "../../components/ui/Button";
2 -import { AuthSettingsWriteScope, type ServerSettingsPatch } from "@t3tools/contracts";
2 +import {
3 + AuthSettingsWriteScope,
4 + isManagedSettingPath,
5 + type ServerSettingsPatch,
6 +} from "@t3tools/contracts";
7 import { useEnvironmentsWithScope } from "../../state/session";
8 import { AutoSettleDaysField } from "./components/AutoSettleDaysField";
9 import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView";
@@ -20,7 +24,11 @@ import { SettingsSwitchRow } from "./components/SettingsSwitchRow";
24 import { SettingsScreen } from "./components/SettingsScreen";
25 import { planAutoSettleSettingsSync, type AutoSettleSettings } from "./autoSettleSettingsSync";
26 import { useSettingsEnvironmentFilter } from "./settings-environment-filter";
23 -import { resolveMobileSettingsTargets, uniformMobileSetting } from "./settings-scoped-server";
27 +import {
28 + managedSettingReason,
29 + resolveMobileSettingsTargets,
30 + uniformMobileSetting,
31 +} from "./settings-scoped-server";
32
33 export function SettingsLabsRouteScreen() {
34 const insets = useSafeAreaInsets();
@@ -98,6 +106,8 @@ export function AutoSettleSettingsRows(props: {
106 );
107
108 const disabled = !canWriteSettings || props.pending;
109 + const disabledFor = (...keys: string[]) =>
110 + disabled || managedSettingReason(displayTargets, ...keys) !== undefined;
111 const afterDays = referenceSettings.sidebarAutoSettleAfterDays;
112
113 return (
@@ -109,7 +119,7 @@ export function AutoSettleSettingsRows(props: {
119 label="Resume after usage limits"
120 subtitle="Automatically resume threads when their usage limits reset. You can cancel auto-resume in each thread."
121 value={uniformMobileSetting(displayTargets, "autoResumeLimitedThreads")}
112 - disabled={disabled}
122 + disabled={disabledFor("autoResumeLimitedThreads")}
123 onValueChange={(value) => writeToAll({ autoResumeLimitedThreads: value })}
124 />
125 <SettingsSwitchRow
@@ -117,7 +127,7 @@ export function AutoSettleSettingsRows(props: {
127 label="Snooze until limits reset"
128 subtitle="Snooze threads until their usage limits reset. Enable auto-resume to continue the agent after the reset."
129 value={uniformMobileSetting(displayTargets, "snoozeLimitedThreads")}
120 - disabled={disabled}
130 + disabled={disabledFor("snoozeLimitedThreads")}
131 onValueChange={(value) => writeToAll({ snoozeLimitedThreads: value })}
132 />
133 </SettingsSection>
@@ -127,14 +137,14 @@ export function AutoSettleSettingsRows(props: {
137 icon="arrow.triangle.branch"
138 label="Auto-settle merged threads"
139 value={referenceSettings.sidebarAutoSettleOnMerge}
130 - disabled={disabled}
140 + disabled={disabledFor("sidebarAutoSettleOnMerge")}
141 onValueChange={(value) => writeToAll({ sidebarAutoSettleOnMerge: value })}
142 />
143 <SettingsSwitchRow
144 icon="clock"
145 label="Auto-settle inactive threads"
146 value={afterDays !== null}
137 - disabled={disabled}
147 + disabled={disabledFor("sidebarAutoSettleAfterDays")}
148 onValueChange={(value) =>
149 writeToAll({ sidebarAutoSettleAfterDays: value ? AUTO_SETTLE_DEFAULT_DAYS : null })
150 }
@@ -145,7 +155,7 @@ export function AutoSettleSettingsRows(props: {
155 <Text className="flex-1 text-foreground text-lg android:text-base">Inactive days</Text>
156 <AutoSettleDaysField
157 value={afterDays}
148 - disabled={disabled}
158 + disabled={disabledFor("sidebarAutoSettleAfterDays")}
159 onValueChange={(value) => writeToAll({ sidebarAutoSettleAfterDays: value })}
160 />
161 </View>
@@ -161,7 +171,7 @@ export function AutoSettleSettingsRows(props: {
171 <Button
172 label="Apply auto-settle defaults"
173 tone="secondary"
164 - disabled={disabled}
174 + disabled={disabledFor("sidebarAutoSettleOnMerge", "sidebarAutoSettleAfterDays")}
175 onPress={() => writeToAll(autoSettlePatch)}
176 />
177 </View>
@@ -232,21 +242,26 @@ function BetaSettingsSection() {
242 return (
243 <View className="gap-3">
244 <SettingsSection title="Beta: Linked environments">
235 - {supported.map((environment) => (
236 - <SettingsSwitchRow
237 - key={environment.environmentId}
238 - icon="link"
239 - label={environment.label}
240 - value={environment.serverConfig?.settings.linkedEnvironmentsEnabled === true}
241 - disabled={!writable.has(environment.environmentId)}
242 - onValueChange={(value) =>
243 - void updateSettings({
244 - environmentId: environment.environmentId,
245 - input: { patch: { linkedEnvironmentsEnabled: value } },
246 - })
247 - }
248 - />
249 - ))}
245 + {supported.map((environment) => {
246 + const policy = environment.serverConfig?.managedPolicy;
247 + const managed = isManagedSettingPath(policy, "linkedEnvironmentsEnabled");
248 + return (
249 + <SettingsSwitchRow
250 + key={environment.environmentId}
251 + icon="link"
252 + label={environment.label}
253 + {...(managed ? { subtitle: `Managed by ${policy?.organization}.` } : {})}
254 + value={environment.serverConfig?.settings.linkedEnvironmentsEnabled === true}
255 + disabled={managed || !writable.has(environment.environmentId)}
256 + onValueChange={(value) =>
257 + void updateSettings({
258 + environmentId: environment.environmentId,
259 + input: { patch: { linkedEnvironmentsEnabled: value } },
260 + })
261 + }
262 + />
263 + );
264 + })}
265 </SettingsSection>
266 <Text className="px-2 text-sm text-foreground-muted">
267 Let agents on a machine work on your other machines, and theirs on it. Turn it on for each
apps/mobile/src/features/settings/components/BranchNamingSettings.test.tsx
+1 -1
@@ -47,7 +47,7 @@ function render(
47 mode={mode}
48 prefix={saved.prefix ?? "t3"}
49 instructions={saved.instructions ?? "Use issue IDs."}
50 - disabled={disabled}
50 + disabled={{ mode: disabled, prefix: disabled, instructions: disabled }}
51 onChange={onChange}
52 />,
53 ),
apps/mobile/src/features/settings/components/BranchNamingSettings.tsx
+5 -4
@@ -22,7 +22,8 @@ export function BranchNamingSettings(props: {
22 mode: BranchNamingMode | null;
23 prefix: string | null;
24 instructions: string | null;
25 - disabled: boolean;
25 + /** Per setting, since a policy can lock one and leave the others to the user. */
26 + disabled: Readonly<Record<"mode" | "prefix" | "instructions", boolean>>;
27 onChange: (patch: ServerSettingsPatch) => void;
28 }) {
29 // Save on exit too: Android Back hides the keyboard without ending editing.
@@ -66,7 +67,7 @@ export function BranchNamingSettings(props: {
67 description={MODES[mode].description}
68 selected={props.mode === mode}
69 separated={index > 0}
69 - disabled={props.disabled}
70 + disabled={props.disabled.mode}
71 onPress={() => props.onChange({ branchNamingMode: mode })}
72 />
73 ))}
@@ -81,7 +82,7 @@ export function BranchNamingSettings(props: {
82 onChangeText={(text) => edit("branchNamePrefix", text)}
83 defaultValue={props.prefix ?? ""}
84 placeholder={props.prefix === null ? "Mixed" : "No prefix"}
84 - editable={!props.disabled}
85 + editable={!props.disabled.prefix}
86 autoCapitalize="none"
87 autoCorrect={false}
88 className="min-h-10 rounded-xl px-3 py-2 text-base text-foreground"
@@ -104,7 +105,7 @@ export function BranchNamingSettings(props: {
105 ? "Mixed. Enter instructions for all selected targets."
106 : "Use julius/ followed by the issue ID and a short description."
107 }
107 - editable={!props.disabled}
108 + editable={!props.disabled.instructions}
109 multiline
110 autoCapitalize="sentences"
111 className="min-h-24 rounded-xl px-3 py-2 text-base text-foreground"
apps/mobile/src/features/settings/settings-scoped-server.test.ts
+26
@@ -8,6 +8,7 @@ import { describe, expect, it } from "vite-plus/test";
8
9 import type { SettingsTarget } from "./settings-environment-filter";
10 import {
11 + managedSettingReason,
12 planMobileScopedSettingsClear,
13 planMobileScopedSettingsPatch,
14 resolveMobileSettingsTargets,
@@ -162,3 +163,28 @@ describe("mobile project settings scope", () => {
163 ).toEqual([]);
164 });
165 });
166 +
167 +describe("managed settings across environments", () => {
168 + it("names the manager when any selected environment locks the setting", () => {
169 + const managed = {
170 + ...environment(secondId, DEFAULT_SERVER_SETTINGS),
171 + serverConfig: {
172 + ...environment(secondId, DEFAULT_SERVER_SETTINGS).serverConfig,
173 + managedPolicy: { organization: "Example Corp", lockedSettings: ["storageCleanup"] },
174 + },
175 + } as SettingsTarget;
176 + const targets = resolveMobileSettingsTargets(
177 + [environment(firstId, DEFAULT_SERVER_SETTINGS), managed],
178 + null,
179 + );
180 +
181 + expect(managedSettingReason(targets, "storageCleanup.logsAfterDays")).toBe(
182 + "Managed by Example Corp.",
183 + );
184 + expect(managedSettingReason(targets, "defaultAutoPull", "storageCleanup")).toBe(
185 + "Managed by Example Corp.",
186 + );
187 + expect(managedSettingReason(targets, "defaultAutoPull")).toBeUndefined();
188 + expect(managedSettingReason(targets.slice(0, 1), "storageCleanup")).toBeUndefined();
189 + });
190 +});
apps/mobile/src/features/settings/settings-scoped-server.ts
+15
@@ -1,4 +1,5 @@
1 import {
2 + isManagedSettingPath,
3 isNullableProjectSettingsOverride,
4 PROJECT_SCOPED_SERVER_SETTING_KEYS,
5 type EnvironmentId,
@@ -21,6 +22,20 @@ export interface ScopedMobileSettingsTarget {
22 readonly sources: ReturnType<typeof resolveProjectSettings>["sources"];
23 }
24
25 +/**
26 + * "Managed by <organization>." when any target's policy locks `path`: the server refuses the
27 + * whole write then, so the control is managed for the selection.
28 + */
29 +export function managedSettingReason(
30 + targets: readonly ScopedMobileSettingsTarget[],
31 + ...paths: readonly string[]
32 +): string | undefined {
33 + const policy = targets
34 + .map((target) => target.environment.serverConfig.managedPolicy)
35 + .find((candidate) => paths.some((path) => isManagedSettingPath(candidate, path)));
36 + return policy === undefined ? undefined : `Managed by ${policy.organization}.`;
37 +}
38 +
39 export function resolveMobileSettingsTargets(
40 environments: readonly SettingsTarget[],
41 members: readonly { readonly environmentId: EnvironmentId; readonly id: ProjectId }[] | null,
apps/mobile/src/features/threads/ManagedRuntimeModeNotice.tsx new
+51
@@ -0,0 +1,51 @@
1 +import {
2 + clampManagedRuntimeMode,
3 + managedRuntimeModeDenial,
4 + type ManagedPolicySummary,
5 + type RuntimeMode,
6 +} from "@t3tools/contracts";
7 +import { View } from "react-native";
8 +
9 +import { AppText } from "../../components/ui/AppText";
10 +import { Button } from "../../components/ui/Button";
11 +import {
12 + updateComposerDraftSettings,
13 + useComposerDraftSettings,
14 +} from "../../state/use-composer-drafts";
15 +import { runtimeModeChoicesForSupportedModes } from "./thread-settings-options";
16 +
17 +/**
18 + * Shown while a thread's mode is above its environment's managed ceiling, where the server
19 + * refuses every turn. Switching sets the draft's mode, which the next send applies first.
20 + */
21 +export function ManagedRuntimeModeNotice(props: {
22 + readonly threadKey: string;
23 + readonly threadRuntimeMode: RuntimeMode;
24 + readonly supportedRuntimeModes: ReadonlyArray<RuntimeMode> | undefined;
25 + readonly policy: ManagedPolicySummary | undefined;
26 +}) {
27 + const draftSettings = useComposerDraftSettings(props.threadKey);
28 + const runtimeMode = draftSettings.runtimeMode ?? props.threadRuntimeMode;
29 + const denial = managedRuntimeModeDenial(props.policy, runtimeMode);
30 + if (denial === undefined) return null;
31 + const choices = runtimeModeChoicesForSupportedModes(props.supportedRuntimeModes);
32 + const target = clampManagedRuntimeMode(
33 + props.policy,
34 + runtimeMode,
35 + choices.map((choice) => choice.mode),
36 + );
37 + const targetLabel = choices.find((choice) => choice.mode === target)?.label;
38 + return (
39 + <View className="gap-2 px-4 pb-3">
40 + <AppText textRole="footnote" className="text-foreground-muted">
41 + {`${denial} Switch this thread's mode to continue.`}
42 + </AppText>
43 + {target === undefined || targetLabel === undefined ? null : (
44 + <Button
45 + label={`Switch to ${targetLabel}`}
46 + onPress={() => updateComposerDraftSettings(props.threadKey, { runtimeMode: target })}
47 + />
48 + )}
49 + </View>
50 + );
51 +}
apps/mobile/src/features/threads/ThreadDetailScreen.tsx
+15
@@ -170,6 +170,7 @@ import type {
170 } from "../../lib/threadActivity";
171 import { PendingApprovalCard } from "./PendingApprovalCard";
172 import { ComposerErrorNotice } from "./ComposerErrorNotice";
173 +import { ManagedRuntimeModeNotice } from "./ManagedRuntimeModeNotice";
174 import { ComposerFeedback } from "./ComposerFeedback";
175 import { ComposerUsageLimits } from "./ComposerUsageLimits";
176 import { PendingUserInputCard } from "./PendingUserInputCard";
@@ -1562,6 +1563,20 @@ function ThreadDetailBody(props: ThreadDetailScreenProps) {
1563 onDismiss={() => props.onDismissFeedback(submission.id)}
1564 />
1565 ))}
1566 + {props.canOperateThread ? (
1567 + <ManagedRuntimeModeNotice
1568 + threadKey={selectedThreadKey}
1569 + threadRuntimeMode={props.selectedThread.runtimeMode}
1570 + supportedRuntimeModes={
1571 + props.serverConfig?.providers.find(
1572 + (provider) =>
1573 + provider.instanceId ===
1574 + props.selectedThread.modelSelection.instanceId,
1575 + )?.supportedRuntimeModes
1576 + }
1577 + policy={props.serverConfig?.managedPolicy}
1578 + />
1579 + ) : null}
1580 {composerError !== null ? (
1581 <Animated.View
1582 className="shrink-0"
apps/mobile/src/features/threads/ThreadSettingsRows.shared.tsx
+4 -2
@@ -22,6 +22,7 @@ export type ChoiceRowProps = {
22 readonly label: string;
23 readonly description?: string;
24 readonly selected: boolean;
25 + readonly disabled?: boolean;
26 readonly onPress: () => void;
27 readonly isLast: boolean;
28 };
@@ -140,7 +141,8 @@ export function ChoiceRowContent(props: ChoiceRowProps & RowSelectionProps) {
141 <Pressable
142 accessibilityLabel={props.description ? `${props.label}. ${props.description}` : props.label}
143 accessibilityRole="radio"
143 - accessibilityState={{ checked: props.selected }}
144 + accessibilityState={{ checked: props.selected, disabled: props.disabled === true }}
145 + disabled={props.disabled}
146 onPress={props.onPress}
147 style={props.minimumHeight === undefined ? undefined : { minHeight: props.minimumHeight }}
148 className={cn(
@@ -149,7 +151,7 @@ export function ChoiceRowContent(props: ChoiceRowProps & RowSelectionProps) {
151 )}
152 >
153 {props.leadingSelection}
152 - <View className="min-w-0 flex-1 gap-0.5">
154 + <View className={cn("min-w-0 flex-1 gap-0.5", props.disabled && "opacity-50")}>
155 <Text className="text-base font-t3-medium text-foreground">{props.label}</Text>
156 {props.description ? (
157 <Text className="text-sm leading-5 text-foreground-muted">{props.description}</Text>
apps/mobile/src/features/threads/ThreadSettingsSheet.tsx
+10 -4
@@ -116,6 +116,8 @@ import { ModelRow, ChoiceRow } from "./ThreadSettingsRows";
116 import {
117 compatibleRuntimeModeForChoices,
118 runtimeModeChoicesForSupportedModes,
119 + withManagedRuntimeModeLimits,
120 + type RuntimeModeChoice,
121 selectableChoices,
122 } from "./thread-settings-options";
123 import {
@@ -304,7 +306,7 @@ type ThreadSettingsSessionValue = {
306 readonly manageHidden: boolean;
307 readonly setManageHidden: (value: boolean) => void;
308 readonly runtimeMode: RuntimeMode;
307 - readonly runtimeModeChoices: ReturnType<typeof runtimeModeChoicesForSupportedModes>;
309 + readonly runtimeModeChoices: ReadonlyArray<RuntimeModeChoice>;
310 readonly onUpdateRuntimeMode: (mode: RuntimeMode) => void;
311 readonly displayedDescriptors: ReadonlyArray<ProviderOptionDescriptor>;
312 readonly promptTraits: ReturnType<typeof getPromptControlledTraits>;
@@ -511,8 +513,9 @@ function ThreadSettingsSessionProvider(
513 pendingModel ??
514 props.providerGroups.flatMap((group) => group.models).find((option) => isApplied(option)) ??
515 null;
514 - const runtimeModeChoices = runtimeModeChoicesForSupportedModes(
515 - displayedModel?.supportedRuntimeModes,
516 + const runtimeModeChoices = withManagedRuntimeModeLimits(
517 + runtimeModeChoicesForSupportedModes(displayedModel?.supportedRuntimeModes),
518 + [config?.managedPolicy],
519 );
520 const compatibleRuntimeMode = compatibleRuntimeModeForChoices(
521 props.runtimeMode,
@@ -1100,7 +1103,8 @@ function ThreadSettingsChoiceContent(props: {
1103 rows: session.runtimeModeChoices.map((choice) => ({
1104 id: choice.mode,
1105 label: choice.label,
1103 - description: choice.description,
1106 + description: choice.disabledReason ?? choice.description,
1107 + disabled: choice.disabledReason !== undefined,
1108 selected: choice.mode === session.runtimeMode,
1109 onPress: () => {
1110 void Haptics.selectionAsync();
@@ -1115,6 +1119,7 @@ function ThreadSettingsChoiceContent(props: {
1119 id: choice.id,
1120 label: choice.label,
1121 description: choice.description,
1122 + disabled: false,
1123 selected:
1124 choice.id ===
1125 (session.promptTraits.ultrathinkPromptControlled &&
@@ -1172,6 +1177,7 @@ function ThreadSettingsChoiceContent(props: {
1177 isLast={index === submenuContent.rows.length - 1}
1178 label={row.label}
1179 selected={row.selected}
1180 + disabled={row.disabled}
1181 onPress={row.onPress}
1182 />
1183 ))}
apps/mobile/src/features/threads/new-task-flow-provider.tsx
+12 -2
@@ -95,6 +95,7 @@ import {
95 } from "./new-task-context-presentation";
96 import { resolveEnvironmentProjectMatch } from "./new-task-project-selection";
97 import { useNewTaskProjectDefaults } from "./use-new-task-project-defaults";
98 +import { resolveNewThreadRuntimeMode } from "./thread-settings-options";
99 import { resolveProjectThreadCreationBranch } from "./projectThreadCreationValidation";
100 import {
101 INACTIVE_FLOW_KEY,
@@ -417,7 +418,12 @@ export function NewTaskFlowProvider(
418 const startFromOrigin =
419 isGitRepo && (draftStartFromOrigin ?? projectSettings.settings.newWorktreesStartFromOrigin);
420 const defaultRuntimeMode = projectSettings.settings.defaultRuntimeMode;
420 - const runtimeMode = selectedProjectDraft.runtimeMode ?? defaultRuntimeMode;
421 + const managedPolicy = selectedEnvironmentServerConfig?.managedPolicy;
422 + const runtimeMode = resolveNewThreadRuntimeMode(
423 + selectedProjectDraft.runtimeMode,
424 + defaultRuntimeMode,
425 + managedPolicy,
426 + );
427
428 // Antigravity keeps unavailable selections so sign-out or a catalog change
429 // cannot switch the user's model.
@@ -750,7 +756,11 @@ export function NewTaskFlowProvider(
756 attachments: draft.attachments,
757 context: draft.context,
758 modelSelection: draftModelSelection,
753 - runtimeMode: draft.runtimeMode ?? defaultRuntimeMode,
759 + runtimeMode: resolveNewThreadRuntimeMode(
760 + draft.runtimeMode,
761 + defaultRuntimeMode,
762 + managedPolicy,
763 + ),
764 interactionMode: resolvePendingTaskInteractionMode({
765 planModeEnabled: legacyPlanModeEnabled,
766 draftInteractionMode: draft.interactionMode,
apps/mobile/src/features/threads/thread-settings-options.test.ts
+44 -2
@@ -2,10 +2,52 @@ import {
2 getPromptControlledTraits,
3 getTraitSelectChange,
4 } from "@t3tools/client-runtime/model-traits";
5 -import type { ProviderOptionDescriptor } from "@t3tools/contracts";
5 +import type {
6 + ManagedPolicySummary,
7 + ProviderOptionDescriptor,
8 + RuntimeMode,
9 +} from "@t3tools/contracts";
10 import { describe, expect, it } from "vite-plus/test";
11
8 -import { selectableChoices } from "./thread-settings-options";
12 +import {
13 + RUNTIME_MODE_CHOICES,
14 + resolveNewThreadRuntimeMode,
15 + selectableChoices,
16 + withManagedRuntimeModeLimits,
17 +} from "./thread-settings-options";
18 +
19 +const policy = (organization: string, maxRuntimeMode?: RuntimeMode): ManagedPolicySummary => ({
20 + organization,
21 + lockedSettings: [],
22 + ...(maxRuntimeMode === undefined ? {} : { limits: { maxRuntimeMode } }),
23 +});
24 +
25 +describe("managed runtime mode limits", () => {
26 + it("disables modes above the strictest target's ceiling with that target's reason", () => {
27 + const choices = withManagedRuntimeModeLimits(RUNTIME_MODE_CHOICES, [
28 + policy("Wide Corp", "auto"),
29 + undefined,
30 + policy("Narrow Corp", "auto-accept-edits"),
31 + ]);
32 +
33 + expect(choices.map((choice) => [choice.mode, choice.disabledReason])).toEqual([
34 + ["approval-required", undefined],
35 + ["auto-accept-edits", undefined],
36 + ["auto", "Narrow Corp limits threads to Auto-accept edits."],
37 + ["full-access", "Wide Corp limits threads to Auto."],
38 + ]);
39 + });
40 +
41 + it("drops a new thread's draft mode above the ceiling for the default", () => {
42 + const capped = policy("Corp", "auto");
43 + expect(resolveNewThreadRuntimeMode("full-access", "auto", capped)).toBe("auto");
44 + expect(resolveNewThreadRuntimeMode("approval-required", "auto", capped)).toBe(
45 + "approval-required",
46 + );
47 + expect(resolveNewThreadRuntimeMode(undefined, "auto", capped)).toBe("auto");
48 + expect(resolveNewThreadRuntimeMode("full-access", "auto", undefined)).toBe("full-access");
49 + });
50 +});
51
52 const effortDescriptor: Extract<ProviderOptionDescriptor, { type: "select" }> = {
53 id: "effort",
apps/mobile/src/features/threads/thread-settings-options.ts
+40 -1
@@ -1,4 +1,8 @@
1 -import type { RuntimeMode } from "@t3tools/contracts";
1 +import {
2 + managedRuntimeModeDenial,
3 + type ManagedPolicySummary,
4 + type RuntimeMode,
5 +} from "@t3tools/contracts";
6
7 export const RUNTIME_MODE_CHOICES: ReadonlyArray<{
8 readonly mode: RuntimeMode;
@@ -35,6 +39,41 @@ export function runtimeModeChoicesForSupportedModes(
39 : RUNTIME_MODE_CHOICES;
40 }
41
42 +export type RuntimeModeChoice = (typeof RUNTIME_MODE_CHOICES)[number] & {
43 + /** Set when a target environment's managed policy caps runtime modes below this one. */
44 + readonly disabledReason?: string;
45 +};
46 +
47 +/**
48 + * Marks modes above a managed runtime ceiling. A control acting on several environments is
49 + * managed when any of them is, so the first target that refuses a mode supplies its reason.
50 + */
51 +export function withManagedRuntimeModeLimits(
52 + choices: ReadonlyArray<RuntimeModeChoice>,
53 + policies: ReadonlyArray<ManagedPolicySummary | undefined>,
54 +): ReadonlyArray<RuntimeModeChoice> {
55 + return choices.map((choice) => {
56 + const reason = policies
57 + .map((policy) => managedRuntimeModeDenial(policy, choice.mode))
58 + .find((denial) => denial !== undefined);
59 + return reason === undefined ? choice : { ...choice, disabledReason: reason };
60 + });
61 +}
62 +
63 +/**
64 + * A new thread's mode: the draft's choice unless the managed ceiling refuses it, then the
65 + * default, which the server already reads back at or below the ceiling.
66 + */
67 +export function resolveNewThreadRuntimeMode(
68 + draftMode: RuntimeMode | undefined,
69 + defaultMode: RuntimeMode,
70 + policy: ManagedPolicySummary | undefined,
71 +): RuntimeMode {
72 + return draftMode !== undefined && managedRuntimeModeDenial(policy, draftMode) === undefined
73 + ? draftMode
74 + : defaultMode;
75 +}
76 +
77 export function compatibleRuntimeModeForChoices(
78 runtimeMode: RuntimeMode,
79 choices: ReadonlyArray<{ readonly mode: RuntimeMode }>,
apps/mobile/src/lib/modelOptions.test.ts
+53
@@ -802,4 +802,57 @@ describe("synchronized mobile model visibility", () => {
802 buildModelOptions(cleared, null, provider, null).map((option) => option.selection.model),
803 ).toEqual(["hidden", "first", "second", "custom"]);
804 });
805 +
806 + describe("managed provider policy", () => {
807 + const config = {
808 + providers: [
809 + {
810 + instanceId: "codex",
811 + driver: "codex",
812 + enabled: true,
813 + installed: true,
814 + auth: { status: "authenticated" },
815 + models: [{ slug: "gpt-5.6-sol", name: "GPT", isCustom: false, capabilities: null }],
816 + },
817 + {
818 + instanceId: "claudeAgent",
819 + driver: "claudeAgent",
820 + enabled: true,
821 + installed: true,
822 + auth: { status: "authenticated" },
823 + models: [
824 + { slug: "claude-sonnet-5", name: "Sonnet", isCustom: false, capabilities: null },
825 + ],
826 + },
827 + ],
828 + managedPolicy: {
829 + organization: "Example Corp",
830 + lockedSettings: [],
831 + limits: { providers: { allowedDrivers: [ProviderDriverKind.make("codex")] } },
832 + },
833 + } as unknown as ServerConfig;
834 + const disallowed = {
835 + instanceId: ProviderInstanceId.make("claudeAgent"),
836 + model: "claude-sonnet-5",
837 + };
838 +
839 + it("leaves drivers the policy does not allow out of the picker", () => {
840 + expect(
841 + buildModelOptions(config, null, undefined, null).map((option) => option.providerKey),
842 + ).toEqual(["codex"]);
843 + });
844 +
845 + it("marks a thread's selection on a disallowed driver unavailable with the policy reason", () => {
846 + expect(
847 + buildModelOptions(config, disallowed, undefined, null).find(
848 + (option) => option.providerKey === "claudeAgent",
849 + )?.isUnavailable,
850 + ).toBe(true);
851 + expect(isModelSelectionUnavailable(config, disallowed, null)).toBe(true);
852 + expect(describeUnavailableModelSelection(config, disallowed, null)).toEqual({
853 + title: "Provider not allowed",
854 + detail: "Example Corp's policy does not allow the Claude provider. Choose another model.",
855 + });
856 + });
857 + });
858 });
apps/mobile/src/lib/modelOptions.ts
+43 -1
@@ -11,7 +11,12 @@ import type {
11 RuntimeMode,
12 ServerConfig as T3ServerConfig,
13 } from "@t3tools/contracts";
14 -import { isProviderDriverKind, resolveProjectProviderInstanceEnabled } from "@t3tools/contracts";
14 +import {
15 + disallowedProviderMessage,
16 + isManagedDriverAllowed,
17 + isProviderDriverKind,
18 + resolveProjectProviderInstanceEnabled,
19 +} from "@t3tools/contracts";
20 import {
21 buildExplicitProviderOptionSelectionsFromDescriptors,
22 getProviderOptionDescriptors,
@@ -110,6 +115,25 @@ function isDisabledForProject(
115 return provider !== undefined && !isProviderEnabledForProject(config, provider, projectId);
116 }
117
118 +function selectionDriver(
119 + config: T3ServerConfig | null | undefined,
120 + instanceId: ModelSelection["instanceId"],
121 +): string | undefined {
122 + return (
123 + config?.providers.find((candidate) => candidate.instanceId === instanceId)?.driver ??
124 + config?.settings?.providerInstances[instanceId]?.driver
125 + );
126 +}
127 +
128 +/** Whether the environment's managed policy leaves this driver out; the server refuses its turns. */
129 +function isDriverDisallowed(config: T3ServerConfig | null | undefined, driver: string | undefined) {
130 + return (
131 + driver !== undefined &&
132 + isProviderDriverKind(driver) &&
133 + !isManagedDriverAllowed(config?.managedPolicy, driver)
134 + );
135 +}
136 +
137 function normalizeSelectionOptions(
138 selection: ModelSelection,
139 capabilities: ModelCapabilities | null,
@@ -152,6 +176,9 @@ export function isModelSelectionUnavailable(
176 }
177 const driver =
178 provider?.driver ?? config.settings?.providerInstances[selection.instanceId]?.driver;
179 + if (isDriverDisallowed(config, driver)) {
180 + return true;
181 + }
182 return (
183 driver === "antigravity" &&
184 (!provider ||
@@ -170,6 +197,20 @@ export function describeUnavailableModelSelection(
197 const provider = config?.providers.find(
198 (candidate) => candidate.instanceId === selection.instanceId,
199 );
200 + const driver = selectionDriver(config, selection.instanceId);
201 + if (isDriverDisallowed(config, driver)) {
202 + const label = providerDisplayLabel({
203 + driver: driver ?? selection.instanceId,
204 + displayName:
205 + provider?.displayName ??
206 + config?.settings?.providerInstances[selection.instanceId]?.displayName,
207 + instanceId: selection.instanceId,
208 + });
209 + return {
210 + title: "Provider not allowed",
211 + detail: `${disallowedProviderMessage(config?.managedPolicy?.organization, label)} Choose another model.`,
212 + };
213 + }
214 return isDisabledForProject(config, provider, selection.instanceId, projectId)
215 ? {
216 title: "Model turned off for this project",
@@ -298,6 +339,7 @@ export function buildModelOptions(
339 for (const provider of config?.providers ?? []) {
340 if (
341 !matchesLockedProvider(provider) ||
342 + isDriverDisallowed(config, provider.driver) ||
343 !isProviderEnabledForProject(config, provider, projectId) ||
344 !provider.installed ||
345 provider.auth.status === "unauthenticated" ||
apps/mobile/src/state/threadOutboxDelivery.ts
+16
@@ -16,6 +16,7 @@ import {
16 CommandId,
17 DEFAULT_PROVIDER_INTERACTION_MODE,
18 DEFAULT_RUNTIME_MODE,
19 + managedRuntimeModeDenial,
20 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
21 type EnvironmentId,
22 type MessageId,
@@ -782,6 +783,14 @@ export function createThreadOutboxDelivery(): {
783 );
784 return restoreQueuedMessage(queuedMessage, `${title}. ${detail}`);
785 }
786 + // The server would refuse this mode in settings sync, which retries forever; stop first.
787 + const runtimeModeDenial = managedRuntimeModeDenial(
788 + serverConfig.managedPolicy,
789 + settings.runtimeMode,
790 + );
791 + if (runtimeModeDenial !== undefined) {
792 + return restoreQueuedMessage(queuedMessage, runtimeModeDenial);
793 + }
794
795 if (settings.runtimeMode !== thread.runtimeMode) {
796 if (!hasAccess()) return true;
@@ -949,6 +958,13 @@ export function createThreadOutboxDelivery(): {
958 );
959 return restoreQueuedMessage(queuedMessage, `${title}. ${detail}`);
960 }
961 + const runtimeModeDenial = managedRuntimeModeDenial(
962 + serverConfig.managedPolicy,
963 + settings.runtimeMode,
964 + );
965 + if (runtimeModeDenial !== undefined) {
966 + return restoreQueuedMessage(queuedMessage, runtimeModeDenial);
967 + }
968 let prepared: PreparedTurnAttachments;
969 let persistedMessage: QueuedThreadMessage;
970 let deliveryRevision: number;
apps/server/package.json
+1
@@ -60,6 +60,7 @@
60 "character-entities": "2.0.2",
61 "diff": "8.0.3",
62 "effect": "catalog:",
63 + "ffi-rs": "1.3.2",
64 "jose": "catalog:",
65 "node-pty": "^1.2.0-beta.15",
66 "playwright-core": "1.60.0",
apps/server/src/auth/EnvironmentAuth.test.ts
+2
@@ -21,6 +21,7 @@ import * as EnvironmentAuth from "./EnvironmentAuth.ts";
21
22 import * as ServerSecretStore from "./ServerSecretStore.ts";
23 import * as SessionStore from "./SessionStore.ts";
24 +import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
25
26 const TEST_SERVER_PORT = 13_773;
27
@@ -39,6 +40,7 @@ const layerServerConfig = (overrides?: Partial<ServerConfig.ServerConfig["Servic
40
41 const layerEnvironmentAuth = (overrides?: Partial<ServerConfig.ServerConfig["Service"]>) =>
42 EnvironmentAuth.layer.pipe(
43 + Layer.provide(ManagedPolicy.layerTest()),
44 Layer.provideMerge(SqlitePersistence.layerMemory),
45 Layer.provide(ServerSecretStore.layer),
46 Layer.provide(ServerEnvironment.layerIdentity),
apps/server/src/auth/EnvironmentAuth.ts
+92 -32
@@ -23,6 +23,7 @@ import {
23 type DpopFailureReason as DpopFailureReasonType,
24 mcpClientScopes,
25 } from "@t3tools/contracts";
26 +import { isLocalLoopbackHost } from "@t3tools/shared/hostClassification";
27 import { encodeOAuthScope } from "@t3tools/shared/oauthScope";
28 import * as Context from "effect/Context";
29 import * as Crypto from "effect/Crypto";
@@ -45,6 +46,8 @@ import { REUSABLE_DEV_SESSION_EXPIRES_AT, resolveReusableDevAuth } from "./Reusa
46 import { verifyRequestDpopProof } from "./dpop.ts";
47 import { DESKTOP_RENDERER_ORIGINS } from "../httpCors.ts";
48 import * as SqlitePersistence from "../persistence/Sqlite.ts";
49 +import * as ManagedLimits from "../policy/managedLimits.ts";
50 +import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
51
52 const DEFAULT_SESSION_SUBJECT = "cli-issued-session";
53 export const INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT = "administrative-bootstrap";
@@ -484,10 +487,16 @@ export class EnvironmentAuth extends Context.Service<
487 readonly subject?: string;
488 readonly proofKeyThumbprint?: string;
489 readonly purpose?: "startup";
487 - }) => Effect.Effect<IssuedPairingLink, ServerAuthInternalError>;
490 + }) => Effect.Effect<
491 + IssuedPairingLink,
492 + ServerAuthInternalError | ManagedLimits.ManagedPolicyRefusedError
493 + >;
494 readonly issuePairingCredential: (
495 input?: AuthCreatePairingCredentialInput,
490 - ) => Effect.Effect<AuthPairingCredentialResult, ServerAuthInternalError>;
496 + ) => Effect.Effect<
497 + AuthPairingCredentialResult,
498 + ServerAuthInternalError | ManagedLimits.ManagedPolicyRefusedError
499 + >;
500 readonly issueStartupPairingCredential: () => Effect.Effect<
501 AuthPairingCredentialResult,
502 ServerAuthInternalError
@@ -707,6 +716,7 @@ export const make = Effect.gen(function* () {
716 const crypto = yield* Crypto.Crypto;
717 const descriptor = yield* policy.getDescriptor();
718 const config = yield* ServerConfig.ServerConfig;
719 + const managedPolicy = yield* ManagedPolicy.ManagedPolicy;
720 const devAuth = resolveReusableDevAuth(config);
721
722 const authenticateToken = (
@@ -1004,33 +1014,15 @@ export const make = Effect.gen(function* () {
1014 );
1015 };
1016
1007 - const issuePairingCredentialForSubject = (input: {
1008 - readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
1009 - readonly subject: string;
1010 - readonly label?: string;
1011 - readonly purpose?: "startup";
1012 - }) =>
1013 - createPairingLink({
1014 - scopes: input.scopes,
1015 - subject: input.subject,
1016 - ...(input.label ? { label: input.label } : {}),
1017 - ...(input.purpose ? { purpose: input.purpose } : {}),
1018 - }).pipe(
1019 - Effect.map(
1020 - (issued) =>
1021 - ({
1022 - id: issued.id,
1023 - credential: issued.credential,
1024 - ...(issued.label ? { label: issued.label } : {}),
1025 - expiresAt: issued.expiresAt,
1026 - }) satisfies AuthPairingCredentialResult,
1027 - ),
1028 - );
1017 + const toPairingCredential = (issued: IssuedPairingLink): AuthPairingCredentialResult => ({
1018 + id: issued.id,
1019 + credential: issued.credential,
1020 + ...(issued.label ? { label: issued.label } : {}),
1021 + expiresAt: issued.expiresAt,
1022 + });
1023
1030 - const createPairingLink: EnvironmentAuth["Service"]["createPairingLink"] = Effect.fn(
1031 - "EnvironmentAuth.createPairingLink",
1032 - )(
1033 - function* (input) {
1024 + const issuePairingLink = Effect.fn("EnvironmentAuth.issuePairingLink")(
1025 + function* (input: Parameters<EnvironmentAuth["Service"]["createPairingLink"]>[0]) {
1026 const createdAt = yield* DateTime.now;
1027 const issued = yield* bootstrapCredentials.issueOneTimeToken({
1028 scopes: input?.scopes ?? AuthStandardClientScopes,
@@ -1053,6 +1045,19 @@ export const make = Effect.gen(function* () {
1045 Effect.mapError((cause) => new ServerAuthPairingLinkCreationError({ cause })),
1046 );
1047
1048 + const createPairingLink: EnvironmentAuth["Service"]["createPairingLink"] = Effect.fn(
1049 + "EnvironmentAuth.createPairingLink",
1050 + )(function* (input) {
1051 + // The startup link is for a browser on this machine; every other link lets a device pair.
1052 + if (input?.purpose !== "startup" && !ManagedLimits.allowsRemoteClients(managedPolicy)) {
1053 + return yield* ManagedLimits.refuseRemoteClients(
1054 + managedPolicy,
1055 + "so this server cannot create pairing links",
1056 + );
1057 + }
1058 + return yield* issuePairingLink(input);
1059 + });
1060 +
1061 const listPairingLinks: EnvironmentAuth["Service"]["listPairingLinks"] = (input) =>
1062 bootstrapCredentials.listActive().pipe(
1063 Effect.map((pairingLinks) => {
@@ -1125,19 +1130,23 @@ export const make = Effect.gen(function* () {
1130 );
1131
1132 const issuePairingCredential: EnvironmentAuth["Service"]["issuePairingCredential"] = (input) =>
1128 - issuePairingCredentialForSubject({
1133 + createPairingLink({
1134 scopes: input?.scopes ?? AuthStandardClientScopes,
1135 subject: "one-time-token",
1136 ...(input?.label ? { label: input.label } : {}),
1132 - }).pipe(Effect.withSpan("EnvironmentAuth.issuePairingCredential"));
1137 + }).pipe(
1138 + Effect.map(toPairingCredential),
1139 + Effect.withSpan("EnvironmentAuth.issuePairingCredential"),
1140 + );
1141
1142 const issueStartupPairingCredential: EnvironmentAuth["Service"]["issueStartupPairingCredential"] =
1143 () => {
1136 - const fallback = issuePairingCredentialForSubject({
1144 + // Unguarded: startup already refused auth policies the managed policy leaves out.
1145 + const fallback = issuePairingLink({
1146 scopes: AuthStandardClientScopes,
1147 subject: INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT,
1148 purpose: "startup",
1140 - });
1149 + }).pipe(Effect.map(toPairingCredential));
1150 if (!devAuth) {
1151 return fallback.pipe(Effect.withSpan("EnvironmentAuth.issueStartupPairingCredential"));
1152 }
@@ -1366,6 +1375,11 @@ export const make = Effect.gen(function* () {
1375 Effect.withSpan("EnvironmentAuth.consumeMcpApprovalCode"),
1376 );
1377
1378 + yield* revokePairedClientsThePolicyDisallows(managedPolicy, {
1379 + sessions,
1380 + pairingLinks: bootstrapCredentials,
1381 + });
1382 +
1383 return EnvironmentAuth.of({
1384 getDescriptor: Effect.fn("EnvironmentAuth.getDescriptor")(function () {
1385 return Effect.succeed(descriptor);
@@ -1395,6 +1409,51 @@ export const make = Effect.gen(function* () {
1409 });
1410 });
1411
1412 +/** Subjects of sessions and links a pairing link created, keyed by how the client paired. */
1413 +const LINK_PAIRED_SUBJECTS = { link: "one-time-token", connect: "cloud-connect" } as const;
1414 +
1415 +/**
1416 + * Revokes sessions and unused links from pairing the policy no longer allows, so a policy rolled
1417 + * out to a machine that already had phones paired takes effect on the next start.
1418 + */
1419 +const revokePairedClientsThePolicyDisallows = Effect.fn(
1420 + "EnvironmentAuth.revokePairedClientsThePolicyDisallows",
1421 +)(function* (
1422 + policy: ManagedPolicy.ManagedPolicy["Service"],
1423 + stores: {
1424 + readonly sessions: SessionStore.SessionStore["Service"];
1425 + readonly pairingLinks: PairingGrantStore.PairingGrantStore["Service"];
1426 + },
1427 +) {
1428 + const remoteAllowed = ManagedLimits.allowsRemoteClients(policy);
1429 + const disallowed = new Set<string>();
1430 + if (!remoteAllowed) disallowed.add(LINK_PAIRED_SUBJECTS.link);
1431 + if (!ManagedLimits.allowsConnect(policy)) disallowed.add(LINK_PAIRED_SUBJECTS.connect);
1432 + if (disallowed.size === 0) return;
1433 + const sessions = (yield* stores.sessions.listActive()).filter(
1434 + (session) =>
1435 + disallowed.has(session.subject) ||
1436 + // The startup link also pairs browsers on this machine; only a device elsewhere goes.
1437 + (!remoteAllowed &&
1438 + session.subject === INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT &&
1439 + session.client.ipAddress !== undefined &&
1440 + !isLocalLoopbackHost(session.client.ipAddress)),
1441 + );
1442 + const links = (yield* stores.pairingLinks.listActive()).filter((link) =>
1443 + disallowed.has(link.subject),
1444 + );
1445 + yield* Effect.forEach(sessions, (session) => stores.sessions.revoke(session.sessionId), {
1446 + discard: true,
1447 + });
1448 + yield* Effect.forEach(links, (link) => stores.pairingLinks.revoke(link.id), { discard: true });
1449 + if (sessions.length > 0 || links.length > 0) {
1450 + yield* Effect.logInfo("Revoked clients the managed policy does not allow.", {
1451 + sessions: sessions.length,
1452 + pairingLinks: links.length,
1453 + });
1454 + }
1455 +});
1456 +
1457 export const layer = Layer.effect(EnvironmentAuth, make).pipe(
1458 Layer.provideMerge(PairingGrantStore.layer),
1459 Layer.provideMerge(SessionStore.layer),
@@ -1404,6 +1463,7 @@ export const layer = Layer.effect(EnvironmentAuth, make).pipe(
1463 const layerStorage = Layer.mergeAll(ServerSecretStore.layer, SqlitePersistence.layerConfig);
1464
1465 export const layerRuntime = layer.pipe(
1466 + Layer.provideMerge(ManagedPolicy.layer),
1467 Layer.provideMerge(layerStorage),
1468 Layer.provideMerge(ServerEnvironment.layerIdentity),
1469 );
apps/server/src/auth/EnvironmentAuthAdmin.test.ts
+83 -2
@@ -1,6 +1,6 @@
1 -import { AuthStandardClientScopes } from "@t3tools/contracts";
1 +import { AuthStandardClientScopes, type ManagedPolicyDocument } from "@t3tools/contracts";
2 import * as NodeServices from "@effect/platform-node/NodeServices";
3 -import { expect, it } from "@effect/vitest";
3 +import { assert, expect, it } from "@effect/vitest";
4 import * as Effect from "effect/Effect";
5 import * as Layer from "effect/Layer";
6
@@ -10,6 +10,8 @@ import * as SqlitePersistence from "../persistence/Sqlite.ts";
10 import * as EnvironmentAuth from "./EnvironmentAuth.ts";
11 import * as ServerSecretStore from "./ServerSecretStore.ts";
12 import * as SessionStore from "./SessionStore.ts";
13 +import * as PairingGrantStore from "./PairingGrantStore.ts";
14 +import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
15
16 const layerServerConfig = (
17 overrides?: Partial<Pick<ServerConfig.ServerConfig["Service"], "desktopBootstrapToken">>,
@@ -33,15 +35,94 @@ const layerServerConfig = (
35
36 const layerEnvironmentAuth = (
37 overrides?: Partial<Pick<ServerConfig.ServerConfig["Service"], "desktopBootstrapToken">>,
38 + policy?: ManagedPolicyDocument,
39 ) =>
40 EnvironmentAuth.layer.pipe(
41 + Layer.provide(ManagedPolicy.layerTest(policy)),
42 Layer.provideMerge(ServerSecretStore.layer),
43 Layer.provideMerge(SqlitePersistence.layerMemory),
44 Layer.provide(ServerEnvironment.layerIdentity),
45 Layer.provide(layerServerConfig(overrides)),
46 );
47
48 +const desktopAndLocalOnly: ManagedPolicyDocument = {
49 + schemaVersion: 1,
50 + organization: "Example Corp",
51 + limits: { clients: ["desktop", "local-browser"] },
52 +};
53 +
54 it.layer(NodeServices.layer)("EnvironmentAuth administrative operations", (it) => {
55 + it.effect("refuses pairing links when the policy does not allow remote clients", () =>
56 + Effect.gen(function* () {
57 + const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
58 +
59 + const error = yield* environmentAuth.issuePairingCredential().pipe(Effect.flip);
60 + const startup = yield* environmentAuth.issueStartupPairingCredential();
61 +
62 + assert.equal(
63 + error.message,
64 + "Example Corp's policy does not allow remote clients, so this server cannot create pairing links.",
65 + );
66 + assert.isAbove(startup.credential.length, 0);
67 + }).pipe(Effect.provide(layerEnvironmentAuth(undefined, desktopAndLocalOnly))),
68 + );
69 +
70 + it.effect("revokes link-paired clients on startup under a policy without remote clients", () =>
71 + Effect.gen(function* () {
72 + const sessions = yield* SessionStore.SessionStore;
73 + const pairingLinks = yield* PairingGrantStore.PairingGrantStore;
74 + const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
75 + const phone = yield* sessions.issue({ subject: "one-time-token" });
76 + const bot = yield* sessions.issue({ subject: "cli-issued-session" });
77 + const startup = (ipAddress: string) =>
78 + sessions.issue({
79 + subject: EnvironmentAuth.INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT,
80 + client: { deviceType: "unknown", ipAddress },
81 + });
82 + const startupPhone = yield* startup("192.168.1.20");
83 + const startupBrowser = yield* startup("127.0.0.1");
84 + yield* environmentAuth.createPairingLink({ subject: "one-time-token" });
85 +
86 + yield* EnvironmentAuth.make.pipe(
87 + Effect.provide(
88 + Layer.merge(ManagedPolicy.layerTest(desktopAndLocalOnly), layerServerConfig()),
89 + ),
90 + );
91 +
92 + const remaining = (yield* sessions.listActive()).map((session) => session.sessionId);
93 + assert.notInclude(remaining, phone.sessionId);
94 + assert.notInclude(remaining, startupPhone.sessionId);
95 + assert.include(remaining, startupBrowser.sessionId);
96 + assert.include(remaining, bot.sessionId);
97 + assert.lengthOf(yield* pairingLinks.listActive(), 0);
98 + }).pipe(Effect.provide(layerEnvironmentAuth())),
99 + );
100 +
101 + it.effect("revokes only T3 Connect clients when the policy keeps remote clients", () =>
102 + Effect.gen(function* () {
103 + const sessions = yield* SessionStore.SessionStore;
104 + const phone = yield* sessions.issue({ subject: "one-time-token" });
105 + const connect = yield* sessions.issue({ subject: "cloud-connect" });
106 +
107 + yield* EnvironmentAuth.make.pipe(
108 + Effect.provide(
109 + Layer.merge(
110 + ManagedPolicy.layerTest({
111 + schemaVersion: 1,
112 + organization: "Example Corp",
113 + limits: { connect: false },
114 + }),
115 + layerServerConfig(),
116 + ),
117 + ),
118 + );
119 +
120 + const remaining = (yield* sessions.listActive()).map((session) => session.sessionId);
121 + assert.include(remaining, phone.sessionId);
122 + assert.notInclude(remaining, connect.sessionId);
123 + }).pipe(Effect.provide(layerEnvironmentAuth())),
124 + );
125 +
126 it.effect("creates, lists, and revokes client pairing links", () =>
127 Effect.gen(function* () {
128 const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
apps/server/src/auth/EnvironmentAuthPolicy.ts
+14 -11
@@ -1,4 +1,8 @@
1 -import { AuthEnvironmentMaintainScope, type ServerAuthDescriptor } from "@t3tools/contracts";
1 +import {
2 + AuthEnvironmentMaintainScope,
3 + type ServerAuthDescriptor,
4 + type ServerAuthPolicy,
5 +} from "@t3tools/contracts";
6 import * as Context from "effect/Context";
7 import * as Effect from "effect/Effect";
8 import * as Layer from "effect/Layer";
@@ -14,20 +18,19 @@ export class EnvironmentAuthPolicy extends Context.Service<
18 }
19 >()("t3/auth/EnvironmentAuthPolicy") {}
20
21 +/** The auth policy a server started with `config` runs under. */
22 +export function resolveServerAuthPolicy(
23 + config: Pick<ServerConfig.ServerConfig["Service"], "mode" | "host">,
24 +): ServerAuthPolicy {
25 + if (isRemoteReachableHost(config.host)) return "remote-reachable";
26 + return config.mode === "desktop" ? "desktop-managed-local" : "loopback-browser";
27 +}
28 +
29 /** @public */
30 export const make = Effect.gen(function* () {
31 const config = yield* ServerConfig.ServerConfig;
32 const serverEnvironment = yield* ServerEnvironment.ServerEnvironmentIdentity;
21 - const isRemoteReachable = isRemoteReachableHost(config.host);
22 -
23 - const policy =
24 - config.mode === "desktop"
25 - ? isRemoteReachable
26 - ? "remote-reachable"
27 - : "desktop-managed-local"
28 - : isRemoteReachable
29 - ? "remote-reachable"
30 - : "loopback-browser";
33 + const policy = resolveServerAuthPolicy(config);
34
35 const bootstrapMethods: ServerAuthDescriptor["bootstrapMethods"] =
36 policy === "desktop-managed-local"
apps/server/src/auth/McpOAuth.test.ts
+2
@@ -28,6 +28,7 @@ import * as McpOAuth from "./McpOAuth.ts";
28 import * as McpOAuthHttp from "./mcpOAuthHttp.ts";
29 import * as ServerSecretStore from "./ServerSecretStore.ts";
30 import * as AuthHttp from "./http.ts";
31 +import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
32
33 class AuthTestApi extends HttpApi.make("environment")
34 .add(EnvironmentHttpApi.groups.auth)
@@ -35,6 +36,7 @@ class AuthTestApi extends HttpApi.make("environment")
36
37 const layerConfig = ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-oauth-test-" });
38 const layerEnvironmentAuth = EnvironmentAuth.layer.pipe(
39 + Layer.provide(ManagedPolicy.layerTest()),
40 Layer.provide(Sqlite.layerMemory),
41 Layer.provideMerge(ServerSecretStore.layer),
42 Layer.provideMerge(ServerEnvironment.layerIdentity),
apps/server/src/auth/McpOAuth.ts
+11
@@ -15,6 +15,7 @@ import {
15 AuthOrchestrationReadScope,
16 MCP_PEER_LINK_SOFTWARE_ID,
17 mcpClientScopes,
18 + type RuntimeMode,
19 } from "@t3tools/contracts";
20 import { encodeOAuthScope } from "@t3tools/shared/oauthScope";
21 import * as Clock from "effect/Clock";
@@ -213,6 +214,10 @@ export class McpOAuth extends Context.Service<
214 readonly decision: ApprovalDecision;
215 }) => Effect.Effect<string, EnvironmentAuth.ServerAuthMcpApprovalCodeError | McpOAuthPageError>;
216 readonly deny: (authorization: AuthorizationRequest) => string;
217 + /** A managed policy's runtime-mode ceiling, shown on the approval page. */
218 + readonly runtimeModeCeiling:
219 + | { readonly organization: string; readonly maxRuntimeMode: RuntimeMode }
220 + | undefined;
221 readonly exchangeCode: (input: {
222 readonly request: HttpServerRequest.HttpServerRequest;
223 readonly urls: McpOAuthUrls;
@@ -547,7 +552,13 @@ const make = Effect.gen(function* () {
552 },
553 );
554
555 + const managedPolicy = serverSettings.managedPolicy;
556 + const maxRuntimeMode = managedPolicy?.limits?.maxRuntimeMode;
557 return McpOAuth.of({
558 + runtimeModeCeiling:
559 + managedPolicy === undefined || maxRuntimeMode === undefined
560 + ? undefined
561 + : { organization: managedPolicy.organization, maxRuntimeMode },
562 register,
563 validateAuthorization,
564 approvingBrowserSession,
apps/server/src/auth/http.test.ts
+2
@@ -24,6 +24,7 @@ import * as SqlitePersistence from "../persistence/Sqlite.ts";
24 import * as EnvironmentAuth from "./EnvironmentAuth.ts";
25 import * as ServerSecretStore from "./ServerSecretStore.ts";
26 import * as AuthHttp from "./http.ts";
27 +import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
28
29 const DEV_TOKEN = "reusable-dev-auth-token-that-is-long-enough";
30 class AuthTestApi extends HttpApi.make("environment").add(EnvironmentHttpApi.groups.auth) {}
@@ -42,6 +43,7 @@ const layerConfig = Layer.effect(
43 ).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-http-test-" })));
44
45 const layerEnvironmentAuth = EnvironmentAuth.layer.pipe(
46 + Layer.provide(ManagedPolicy.layerTest()),
47 Layer.provide(SqlitePersistence.layerMemory),
48 Layer.provide(ServerSecretStore.layer),
49 Layer.provide(ServerEnvironment.layerIdentity),
apps/server/src/auth/http.ts
+5
@@ -6,6 +6,7 @@ import {
6 EnvironmentAuthInvalidError,
7 type EnvironmentAuthInvalidReason,
8 EnvironmentHttpApi,
9 + EnvironmentHttpForbiddenError,
10 EnvironmentInternalError,
11 type EnvironmentInternalErrorReason,
12 EnvironmentOperationForbiddenError,
@@ -461,6 +462,10 @@ export const layer = HttpApiBuilder.group(
462 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
463 failEnvironmentInternal("pairing_credential_issuance_failed", error),
464 ),
465 + Effect.catchTags({
466 + ManagedPolicyRefusedError: (error) =>
467 + Effect.fail(new EnvironmentHttpForbiddenError({ message: error.message })),
468 + }),
469 ),
470 )
471 .handle(
apps/server/src/auth/mcpOAuthHttp.ts
+3
@@ -121,6 +121,9 @@ export const layer = HttpApiBuilder.group(
121 clientName: resolved.client.name,
122 redirectHost: new URL(resolved.redirectUri).host,
123 environmentHost: new URL(urls.issuer).host,
124 + ...(oauth.runtimeModeCeiling === undefined
125 + ? {}
126 + : { runtimeModeCeiling: oauth.runtimeModeCeiling }),
127 ...(session === undefined
128 ? {}
129 : {
apps/server/src/auth/utils.ts
+17 -14
@@ -6,6 +6,8 @@ import type {
6 import type * as HttpServerRequest from "effect/http/HttpServerRequest";
7 // @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no createHmac or timingSafeEqual.
8 import * as NodeCrypto from "node:crypto";
9 +import * as NodeNet from "node:net";
10 +import { normalizeHostname } from "@t3tools/shared/hostClassification";
11 import * as Base64Url from "effect/encoding/Base64Url";
12 import * as Result from "effect/Result";
13
@@ -50,22 +52,23 @@ export function resolveLegacySessionCookieName(input: {
52 : undefined;
53 }
54
53 -export function isRemoteReachableHost(host: string | undefined): boolean {
54 - if (host === "0.0.0.0" || host === "::" || host === "[::]") {
55 - return true;
56 - }
57 - if (!host || host.length === 0) {
58 - return false;
59 - }
60 - return !(
61 - host === "localhost" ||
62 - host === "127.0.0.1" ||
63 - host === "::1" ||
64 - host === "[::1]" ||
65 - host.startsWith("127.")
66 - );
55 +/**
56 + * The loopback address a server given `host` listens on, or undefined when it may listen beyond
57 + * this machine. Unset means 127.0.0.1. Only a loopback literal or `localhost` counts: Node listens
58 + * on every interface for an empty host, and any other name resolves through DNS.
59 + */
60 +export function loopbackBindAddress(host: string | undefined): string | undefined {
61 + if (host === undefined) return "127.0.0.1";
62 + const address = normalizeHostname(host);
63 + if (address === "localhost") return "127.0.0.1";
64 + return (NodeNet.isIPv4(address) && address.startsWith("127.")) || address === "::1"
65 + ? address
66 + : undefined;
67 }
68
69 +export const isRemoteReachableHost = (host: string | undefined): boolean =>
70 + loopbackBindAddress(host) === undefined;
71 +
72 export function base64UrlEncode(input: string | Uint8Array): string {
73 return typeof input === "string"
74 ? Base64Url.encode(new TextEncoder().encode(input))
apps/server/src/binCli.ts
+2
@@ -1,4 +1,5 @@
1 import { doctorCommand } from "./cli/doctor.ts";
2 +import { policyCommand } from "./cli/policy.ts";
3 import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
4 import * as NodeServices from "@effect/platform-node/NodeServices";
5 import * as Effect from "effect/Effect";
@@ -95,6 +96,7 @@ export const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) =>
96 themeCommand,
97 traceCommand,
98 doctorCommand,
99 + policyCommand,
100 triageCommand,
101 cloudEnabled ? connectCommand : connectUnavailableCommand,
102 ]),
apps/server/src/cli/connect.ts
+15 -1
@@ -30,6 +30,8 @@ import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } fr
30 import * as HttpApiClient from "effect/http-api/HttpApiClient";
31
32 import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
33 +import * as ManagedLimits from "../policy/managedLimits.ts";
34 +import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
35 import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
36 import * as BootService from "../cloud/bootService.ts";
37 import * as CliState from "../cloud/CliState.ts";
@@ -523,6 +525,7 @@ export const runCloudCommand = Effect.fn("cloud.cli.run_cloud_command")(function
525 | Prompt.Environment
526 | ServerConfig.ServerConfig
527 | ServerEnvironment.ServerEnvironmentIdentity
528 + | ManagedPolicy.ManagedPolicy
529 >,
530 options?: {
531 readonly quietLogs?: boolean;
@@ -540,7 +543,7 @@ export const runCloudCommand = Effect.fn("cloud.cli.run_cloud_command")(function
543 RelayClient.layerCloudflared({ baseDir: config.baseDir }),
544 EnvironmentAuth.layerRuntime,
545 CliService.layer(config),
543 - RelayTracing.layerHeadlessRelayClient,
546 + RelayTracing.layerHeadlessRelayClient.pipe(Layer.provide(ManagedPolicy.layer)),
547 ).pipe(
548 Layer.provideMerge(FetchHttpClient.layer),
549 Layer.provideMerge(ServerConfig.layer(config)),
@@ -549,6 +552,14 @@ export const runCloudCommand = Effect.fn("cloud.cli.run_cloud_command")(function
552 return yield* run.pipe(Effect.provide(layerRuntime));
553 });
554
555 +/** Status, unlink, and logout stay available so a machine can leave Connect the policy turned off. */
556 +export const requireConnectAllowed = Effect.gen(function* () {
557 + const policy = yield* ManagedPolicy.ManagedPolicy;
558 + if (!ManagedLimits.allowsConnect(policy)) {
559 + return yield* ManagedLimits.refuseConnect(policy);
560 + }
561 +});
562 +
563 const connectedAs = (identity: string | null): string => (identity ? ` as ${identity}` : "");
564
565 function formatRelayClientReady(version: string): string {
@@ -605,6 +616,7 @@ const connectLoginCommand = Command.make("login", {
616 runCloudCommand(
617 flags,
618 Effect.gen(function* () {
619 + yield* requireConnectAllowed;
620 yield* Console.log("T3 Connect\n");
621 const identity = yield* authorizeCli(flags);
622 yield* Console.log(`✓ Signed in${connectedAs(identity)}`);
@@ -628,6 +640,7 @@ const connectLinkCommand = Command.make("link", {
640 runCloudCommand(
641 flags,
642 Effect.gen(function* () {
643 + yield* requireConnectAllowed;
644 yield* Console.log("T3 Connect\n");
645 const linked = yield* linkEnvironmentForConnect(flags);
646 if (linked) {
@@ -722,6 +735,7 @@ const connectPublishCommand = Command.make("publish", {
735 const secrets = yield* ServerSecretStore.ServerSecretStore;
736 const tokens = yield* CliTokenManager.CloudCliTokenManager;
737 const enabled = !flags.disable;
738 + if (enabled) yield* requireConnectAllowed;
739 yield* secrets.set(
740 PUBLISH_AGENT_ACTIVITY_SECRET,
741 stringToBytes(enabled ? "true" : "false"),
apps/server/src/cli/environment.ts
+8 -1
@@ -16,6 +16,7 @@ import * as ServerConfig from "../config.ts";
16 import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
17 import * as PeerLinks from "../peer/PeerLinks.ts";
18 import * as ServerSettings from "../serverSettings.ts";
19 +import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
20 import * as SqlitePersistence from "../persistence/Sqlite.ts";
21 import { authLocationFlags, type CliAuthLocationFlags, resolveCliAuthConfig } from "./config.ts";
22
@@ -44,7 +45,13 @@ const runWithPeerLinks = Effect.fn("environment.runWithPeerLinks")(function* <A,
45 Layer.provide(ServerEnvironment.layer.pipe(Layer.provide(ServerSecretStore.layer))),
46 Layer.provide(
47 ServerSettings.layer.pipe(
47 - Layer.provide(Layer.mergeAll(ServerSecretStore.layer, SqlitePersistence.layerConfig)),
48 + Layer.provide(
49 + Layer.mergeAll(
50 + ServerSecretStore.layer,
51 + SqlitePersistence.layerConfig,
52 + ManagedPolicy.layer,
53 + ),
54 + ),
55 ),
56 ),
57 Layer.provide(ServerConfig.layer(config)),
apps/server/src/cli/pair.test.ts
+44
@@ -267,6 +267,50 @@ describe("t3 pair", () => {
267 ).pipe(Effect.provide(NodeServices.layer)),
268 );
269
270 + it.effect("refuses --tailscale before turning on Serve when the policy keeps clients local", () =>
271 + withDescriptorServer((origin) =>
272 + Effect.gen(function* () {
273 + const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-policy-test-"));
274 + const policyPath = NodePath.join(baseDir, "policy.json");
275 + NodeFS.writeFileSync(
276 + policyPath,
277 + JSON.stringify({
278 + schemaVersion: 1,
279 + organization: "Example Corp",
280 + limits: { clients: ["desktop", "local-browser"] },
281 + }),
282 + );
283 + yield* persistServerRuntimeState({
284 + path: NodePath.join(baseDir, "userdata", "server-runtime.json"),
285 + state: yield* makePersistedServerRuntimeState({
286 + config: { host: "127.0.0.1", devUrl: undefined },
287 + port: Number(new URL(origin).port),
288 + }),
289 + });
290 +
291 + const error = yield* provideCliTestLayers(
292 + runCli(["pair", "--base-dir", baseDir, "--tailscale"]).pipe(
293 + Effect.provideService(
294 + ChildProcessSpawner.ChildProcessSpawner,
295 + ChildProcessSpawner.make(() => Effect.die("tailscale must not run")),
296 + ),
297 + Effect.provide(
298 + ConfigProvider.layer(
299 + ConfigProvider.fromEnv({ env: { T3CODE_DEV_MANAGED_POLICY_PATH: policyPath } }),
300 + ),
301 + ),
302 + Effect.flip,
303 + ),
304 + );
305 +
306 + assert.include(
307 + String(error),
308 + "Example Corp's policy does not allow remote clients, so Tailscale Serve cannot be turned on.",
309 + );
310 + }),
311 + ).pipe(Effect.provide(NodeServices.layer)),
312 + );
313 +
314 it.effect("ignores runtime state whose recorded pid is no longer alive", () =>
315 withDescriptorServer((origin) =>
316 Effect.gen(function* () {
apps/server/src/cli/pair.ts
+11 -1
@@ -30,6 +30,8 @@ import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } fr
30
31 import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
32 import * as ServerConfig from "../config.ts";
33 +import * as ManagedLimits from "../policy/managedLimits.ts";
34 +import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
35 import { resolveBaseDir } from "../os-jank.ts";
36 import {
37 type PersistedServerRuntimeState,
@@ -404,7 +406,7 @@ const resolveTailscalePairingBase = Effect.fn("pair.resolveTailscalePairingBase"
406 ),
407 );
408 notes.push(
407 - `Tailscale Serve now maps ${baseUrl} to this server and persists across restarts. Remove it with \`tailscale serve --https=${String(input.servePort)} off\`.`,
409 + `Tailscale Serve now maps ${baseUrl} to this server and persists across restarts. Remove it with \`tailscale serve --https=${String(input.servePort)} --set-path=/ off\`.`,
410 );
411
412 const probed = yield* awaitEnvironmentDescriptor(baseUrl);
@@ -502,6 +504,14 @@ export const pairCommand = Command.make("pair", {
504 const notes: Array<string> = [];
505 let pairingBaseUrl: string;
506 if (flags.tailscale) {
507 + // Serve stays on after this command exits, so refuse before turning it on.
508 + const policy = yield* ManagedPolicy.ManagedPolicy.pipe(Effect.provide(ManagedPolicy.layer));
509 + if (!ManagedLimits.allowsRemoteClients(policy)) {
510 + return yield* ManagedLimits.refuseRemoteClients(
511 + policy,
512 + "so Tailscale Serve cannot be turned on",
513 + );
514 + }
515 const resolved = yield* resolveTailscalePairingBase({
516 target,
517 servePort: flags.tailscaleServePort,
apps/server/src/cli/policy.test.ts new
+55
@@ -0,0 +1,55 @@
1 +import * as NodeServices from "@effect/platform-node/NodeServices";
2 +import { assert, it } from "@effect/vitest";
3 +import * as Effect from "effect/Effect";
4 +import * as FileSystem from "effect/FileSystem";
5 +import * as Path from "effect/Path";
6 +import * as Schema from "effect/Schema";
7 +
8 +import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
9 +import {
10 + makePersistedServerRuntimeState,
11 + PersistedServerRuntimeState,
12 +} from "../serverRuntimeState.ts";
13 +import { describeRunningServer } from "./policy.ts";
14 +
15 +const encodeState = Schema.encodeEffect(Schema.fromJsonString(PersistedServerRuntimeState));
16 +
17 +it.layer(NodeServices.layer)((it) =>
18 + it.effect("tells whether the running server loaded the installed policy", () =>
19 + Effect.gen(function* () {
20 + const fs = yield* FileSystem.FileSystem;
21 + const statePath = (yield* Path.Path).join(
22 + yield* fs.makeTempDirectoryScoped({ prefix: "t3-policy-show-" }),
23 + "server-runtime.json",
24 + );
25 + const loaded = (organization: string) =>
26 + ManagedPolicy.loadedPolicy({
27 + path: "/etc/t3code/policy.json",
28 + document: { schemaVersion: 1, organization },
29 + });
30 + const installed = yield* loaded("Example Corp");
31 + // A live server (this process) that loaded `managedPolicy`; undefined is an older server.
32 + const running = (managedPolicy: typeof installed | undefined, current = installed) =>
33 + Effect.gen(function* () {
34 + const state = yield* makePersistedServerRuntimeState({
35 + config: { host: undefined, devUrl: undefined },
36 + port: 3773,
37 + ...(managedPolicy === undefined ? {} : { managedPolicy }),
38 + });
39 + yield* fs.writeFileString(statePath, yield* encodeState(state));
40 + return yield* describeRunningServer(statePath, current);
41 + });
42 +
43 + assert.include(yield* describeRunningServer(statePath, installed), "No T3 Code server");
44 + assert.include(yield* running(installed), "loaded this policy.");
45 + assert.include(
46 + yield* running(yield* loaded("Other Corp")),
47 + "loaded Other Corp's policy from /etc/t3code/policy.json",
48 + );
49 + assert.include(yield* running(null), "loaded no policy. Restart T3 Code");
50 + assert.include(yield* running(installed, null), "Restart T3 Code to apply");
51 + assert.include(yield* running(null, null), "runs without a policy, as installed");
52 + assert.include(yield* running(undefined), "does not report which policy it loaded");
53 + }),
54 + ),
55 +);
apps/server/src/cli/policy.ts new
+109
@@ -0,0 +1,109 @@
1 +import * as Console from "effect/Console";
2 +import * as Effect from "effect/Effect";
3 +import * as FileSystem from "effect/FileSystem";
4 +import * as Layer from "effect/Layer";
5 +import * as Option from "effect/Option";
6 +import * as References from "effect/References";
7 +import { Argument, Command, GlobalFlag } from "effect/cli";
8 +import * as CliError from "effect/cli/CliError";
9 +
10 +import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
11 +import { isProcessAlive, readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
12 +import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
13 +
14 +const describePolicy = (
15 + policy: ManagedPolicy.ManagedPolicy["Service"],
16 + loaded: Effect.Success<ReturnType<typeof ManagedPolicy.loadedPolicy>>,
17 +) => {
18 + const { document } = policy;
19 + if (document === undefined || loaded === null) {
20 + return "No managed policy on this machine. Every setting belongs to the user.\n";
21 + }
22 + const settings = Object.entries(document.settings ?? {});
23 + const lines = [
24 + `Managed by ${document.organization} (${policy.path}, fingerprint ${loaded.fingerprint}).`,
25 + ...(document.supportUrl === undefined ? [] : [`Support: ${document.supportUrl}`]),
26 + "",
27 + settings.length === 0 ? "No managed settings." : "Settings:",
28 + ...settings.map(
29 + ([path, setting]) =>
30 + ` ${path} = ${JSON.stringify(setting.value)} (${setting.locked ? "locked" : "default"})`,
31 + ),
32 + ];
33 + if (document.limits !== undefined) {
34 + lines.push("", "Limits:", JSON.stringify(document.limits, null, 2));
35 + }
36 + return `${lines.join("\n")}\n`;
37 +};
38 +
39 +/** Whether the server running from this T3 home loaded the installed policy, which waits for a restart. */
40 +export const describeRunningServer = Effect.fn("cli.policy.describeRunningServer")(function* (
41 + statePath: string,
42 + installed: Effect.Success<ReturnType<typeof ManagedPolicy.loadedPolicy>>,
43 +) {
44 + const state = yield* readPersistedServerRuntimeState(statePath);
45 + if (Option.isNone(state) || !isProcessAlive(state.value.pid)) {
46 + return "No T3 Code server is running from this T3 home. The installed policy applies when one starts.";
47 + }
48 + const { pid, startedAt, managedPolicy: loaded } = state.value;
49 + const server = `The running server (pid ${pid}, started ${startedAt})`;
50 + if (loaded === undefined) {
51 + return `${server} does not report which policy it loaded. Restart it to apply the installed policy.`;
52 + }
53 + if ((loaded?.fingerprint ?? null) === (installed?.fingerprint ?? null)) {
54 + return loaded === null
55 + ? `${server} runs without a policy, as installed.`
56 + : `${server} loaded this policy.`;
57 + }
58 + const what =
59 + loaded === null
60 + ? "no policy"
61 + : `${loaded.organization}'s policy from ${loaded.source} (fingerprint ${loaded.fingerprint})`;
62 + return `${server} loaded ${what}. Restart T3 Code to apply the installed policy.`;
63 +});
64 +
65 +const showCommand = Command.make("show", projectLocationFlags).pipe(
66 + Command.withDescription(
67 + "Show the policy installed on this machine, and whether the running server loaded it.",
68 + ),
69 + Command.withHandler(
70 + Effect.fn("cli.policy.show")(function* (flags) {
71 + // The command prints the policy itself; the server's startup log line would repeat it.
72 + const policy = yield* ManagedPolicy.ManagedPolicy.pipe(
73 + Effect.provide(
74 + ManagedPolicy.layer.pipe(
75 + Layer.provide(Layer.succeed(References.MinimumLogLevel, "Warn")),
76 + ),
77 + ),
78 + );
79 + const installed = yield* ManagedPolicy.loadedPolicy(policy);
80 + yield* Console.log(describePolicy(policy, installed));
81 + const config = yield* resolveCliAuthConfig(flags, yield* GlobalFlag.LogLevel);
82 + yield* Console.log(yield* describeRunningServer(config.serverRuntimeStatePath, installed));
83 + }),
84 + ),
85 +);
86 +
87 +const checkCommand = Command.make("check", {
88 + file: Argument.String("file").pipe(Argument.withDescription("Policy file to validate.")),
89 +}).pipe(
90 + Command.withDescription("Validate a policy file before deploying it."),
91 + Command.withHandler(
92 + Effect.fn("cli.policy.check")(function* ({ file }) {
93 + // Startup treats a missing file as no policy; a draft that is not there checks nothing.
94 + if (!(yield* (yield* FileSystem.FileSystem).exists(file))) {
95 + return yield* new CliError.UserError({
96 + cause: file,
97 + userMessage: `No policy file at ${file}.`,
98 + });
99 + }
100 + const policy = yield* ManagedPolicy.load(file);
101 + yield* Console.log(describePolicy(policy, yield* ManagedPolicy.loadedPolicy(policy)));
102 + }),
103 + ),
104 +);
105 +
106 +export const policyCommand = Command.make("policy").pipe(
107 + Command.withDescription("Inspect the administrator's managed policy."),
108 + Command.withSubcommands([showCommand, checkCommand]),
109 +);
apps/server/src/cli/project.test.ts
+6 -1
@@ -45,6 +45,7 @@ import {
45 persistServerRuntimeState,
46 } from "../serverRuntimeState.ts";
47 import * as ServerSettings from "../serverSettings.ts";
48 +import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
49 import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
50
51 const layerCliRuntime = Layer.mergeAll(NodeServices.layer, NetService.layer);
@@ -96,7 +97,11 @@ const readProjects = (baseDir: string) =>
97 Layer.provideMerge(ProjectFaviconResolver.layer),
98 Layer.provideMerge(T3ProjectFileLoader.layer),
99 Layer.provideMerge(WorkspacePaths.layer),
99 - Layer.provideMerge(ServerSettings.layer.pipe(Layer.provide(ServerSecretStore.layer))),
100 + Layer.provideMerge(
101 + ServerSettings.layer.pipe(
102 + Layer.provide(Layer.merge(ServerSecretStore.layer, ManagedPolicy.layerTest())),
103 + ),
104 + ),
105 Layer.provideMerge(SqlitePersistence.layerConfig),
106 Layer.provideMerge(NodeServices.layer),
107 Layer.provide(ServerConfig.layer(config)),
apps/server/src/cli/project.ts
+6 -1
@@ -36,6 +36,7 @@ import * as ProjectService from "../project/ProjectService.ts";
36 import { projectMutationOperation } from "../project/ProjectMutation.ts";
37 import * as T3ProjectFileLoader from "../project/T3ProjectFileLoader.ts";
38 import * as ServerSettings from "../serverSettings.ts";
39 +import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
40 import {
41 clearPersistedServerRuntimeState,
42 readPersistedServerRuntimeState,
@@ -210,7 +211,11 @@ const layerProjectCliRuntime = RuntimeLayer.layerProjectService.pipe(
211 ),
212 ),
213 Layer.provideMerge(WorkspacePaths.layer),
213 - Layer.provideMerge(ServerSettings.layer.pipe(Layer.provide(ServerSecretStore.layer))),
214 + Layer.provideMerge(
215 + ServerSettings.layer.pipe(
216 + Layer.provide(Layer.merge(ServerSecretStore.layer, ManagedPolicy.layer)),
217 + ),
218 + ),
219 Layer.provideMerge(SqlitePersistence.layerConfig),
220 );
221
apps/server/src/cli/up.ts
+10
@@ -16,12 +16,15 @@ import { CLOUD_ENDPOINT_RUNTIME_CONFIG, CLOUD_LINK_REVOKED } from "../cloud/conf
16 import { hasCloudPublicConfig } from "../cloud/publicConfig.ts";
17 import { compareExactServiceVersions } from "../cloud/serviceProtocol.ts";
18 import * as ServerConfig from "../config.ts";
19 +import * as ManagedLimits from "../policy/managedLimits.ts";
20 +import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
21 import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
22 import {
23 connectSubcommands,
24 disconnectCloud,
25 headlessFlag,
26 linkEnvironmentForConnect,
27 + requireConnectAllowed,
28 runCloudCommand,
29 waitForReachability,
30 } from "./connect.ts";
@@ -236,6 +239,13 @@ const setUp = Effect.fn("cli.up")(function* (flags: {
239 }, or use --yes for the default. See \`t3 up --help\`.`,
240 });
241 }
242 + if (routes.connect && !current.connect) yield* requireConnectAllowed;
243 + if (routes.lan && !current.lan) {
244 + const policy = yield* ManagedPolicy.ManagedPolicy;
245 + if (!ManagedLimits.allowsRemoteClients(policy)) {
246 + return yield* ManagedLimits.refuseRemoteClients(policy);
247 + }
248 + }
249 // Nothing to run in the background, but a route left on still gets turned off.
250 if (!before.service.installed && !routes.connect && !routes.lan) {
251 if (current.connect || before.connectRevoked) {
apps/server/src/cli/update.test.ts
+65 -1
@@ -1,10 +1,12 @@
1 import * as NodeServices from "@effect/platform-node/NodeServices";
2 import { assert, it } from "@effect/vitest";
3 +import type { ManagedUpdatesPolicy } from "@t3tools/contracts";
4 import * as HostProcess from "@t3tools/shared/HostProcess";
5 import * as Duration from "effect/Duration";
6 import * as Effect from "effect/Effect";
7 import * as Exit from "effect/Exit";
8 import * as FileSystem from "effect/FileSystem";
9 +import * as Layer from "effect/Layer";
10 import * as Option from "effect/Option";
11 import * as Path from "effect/Path";
12 import * as TestClock from "effect/testing/TestClock";
@@ -12,9 +14,11 @@ import { HttpClient, HttpClientResponse } from "effect/http";
14 import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
15 import { afterEach, vi } from "vite-plus/test";
16
17 +import * as BootService from "../cloud/bootService.ts";
18 import { prunePinnedRuntimes } from "../cloud/pinnedRuntime.ts";
19 +import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
20 import * as ProcessRunner from "../processRunner.ts";
17 -import { repointLauncher, resolveLauncherPath, resolveNewestVersion } from "./update.ts";
21 +import { repointLauncher, resolveLauncherPath, resolveNewestVersion, runUpdate } from "./update.ts";
22
23 // lsof listing one process, so prune sees a process list in which no runtime is running.
24 const unrelatedLsof = ProcessRunner.ProcessRunner.of({
@@ -56,6 +60,66 @@ it.effect("authenticates each release page until the requested channel is found"
60 }),
61 );
62
63 +it.layer(NodeServices.layer)("t3 update under a managed policy", (it) => {
64 + const runWithPolicy = (
65 + updates: ManagedUpdatesPolicy,
66 + input: { readonly channel?: "stable" | "nightly"; readonly requestedVersion?: string } = {},
67 + ) =>
68 + runUpdate({
69 + baseDir: "/unused",
70 + logsDir: "/unused",
71 + serverRuntimeStatePath: "/unused",
72 + channel: input.channel,
73 + requestedVersion: input.requestedVersion,
74 + allowDowngrade: false,
75 + assumeYes: true,
76 + }).pipe(
77 + Effect.flip,
78 + Effect.provide(
79 + Layer.mergeAll(
80 + ManagedPolicy.layerTest({
81 + schemaVersion: 1,
82 + organization: "Example Corp",
83 + limits: { updates },
84 + }),
85 + // Refusals happen before the update touches the network, the service, or a process.
86 + Layer.mock(BootService.BootService, {}),
87 + Layer.mock(ProcessRunner.ProcessRunner, {}),
88 + Layer.succeed(
89 + HttpClient.HttpClient,
90 + HttpClient.make(() => Effect.die("unexpected release lookup")),
91 + ),
92 + ),
93 + ),
94 + );
95 +
96 + it.effect("refuses to update when updates are off", () =>
97 + Effect.gen(function* () {
98 + const error = yield* runWithPolicy({ mode: "off" });
99 + assert.equal(error.message, "Example Corp manages T3 Code updates.");
100 + }),
101 + );
102 +
103 + it.effect("refuses nightly releases when the policy disallows them", () =>
104 + Effect.gen(function* () {
105 + const byChannel = yield* runWithPolicy(
106 + { mode: "auto", allowNightly: false },
107 + { channel: "nightly" },
108 + );
109 + const byVersion = yield* runWithPolicy(
110 + { mode: "auto", allowNightly: false },
111 + { channel: "stable", requestedVersion: "1.2.0-nightly.20261028.1" },
112 + );
113 + for (const error of [byChannel, byVersion]) {
114 + assert.equal(
115 + error.message,
116 + "Example Corp manages T3 Code updates. Only stable releases can be installed.",
117 + );
118 + }
119 + }),
120 + );
121 +});
122 +
123 it.layer(NodeServices.layer)("t3 update launcher", (it) => {
124 it.effect("repoints a symlink that lives in a runtime versions tree", () =>
125 Effect.gen(function* () {
apps/server/src/cli/update.ts
+17 -2
@@ -32,6 +32,8 @@ import {
32 windowsShimTarget,
33 } from "../cloud/pinnedRuntime.ts";
34 import { compareExactServiceVersions, isExactServiceVersion } from "../cloud/serviceProtocol.ts";
35 +import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
36 +import { managedUpdateRefusal } from "../policy/managedUpdates.ts";
37 import * as ProcessRunner from "../processRunner.ts";
38 import { isProcessAlive, readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
39 import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
@@ -245,7 +247,12 @@ export const updateCommand = Command.make("update", {
247 assumeYes: flags.yes,
248 }).pipe(
249 Effect.provide(
248 - Layer.mergeAll(CliService.layer(config), ProcessRunner.layer, FetchHttpClient.layer),
250 + Layer.mergeAll(
251 + CliService.layer(config),
252 + ProcessRunner.layer,
253 + FetchHttpClient.layer,
254 + ManagedPolicy.layer,
255 + ),
256 ),
257 );
258 }),
@@ -295,7 +302,7 @@ const belongsToBootService = Effect.fn("cli.update.belongs_to_boot_service")(fun
302 return false;
303 });
304
298 -const runUpdate = Effect.fn("cli.update.run")(function* (input: {
305 +export const runUpdate = Effect.fn("cli.update.run")(function* (input: {
306 readonly baseDir: string;
307 readonly logsDir: string;
308 readonly serverRuntimeStatePath: string;
@@ -312,9 +319,17 @@ const runUpdate = Effect.fn("cli.update.run")(function* (input: {
319 const environment = yield* HostProcess.Environment;
320 const httpClient = yield* HttpClient.HttpClient;
321 const service = yield* BootService.BootService;
322 + const policy = yield* ManagedPolicy.ManagedPolicy;
323
324 const currentVersion = packageJson.version;
325 const channel = input.channel ?? cliReleaseChannelOf(currentVersion);
326 + const refusal = managedUpdateRefusal(
327 + policy.document,
328 + input.requestedVersion === undefined ? channel : cliReleaseChannelOf(input.requestedVersion),
329 + );
330 + if (refusal !== undefined) {
331 + return yield* new CliUpdateError({ reason: refusal });
332 + }
333 if (input.requestedVersion !== undefined && !isExactServiceVersion(input.requestedVersion)) {
334 return yield* new CliUpdateError({
335 reason: `'${input.requestedVersion}' is not an exact t3 version.`,
apps/server/src/cloud/CloudLink.lifecycle.test.ts
+2 -1
@@ -43,6 +43,7 @@ import { consumeCloudReplayGuards } from "./CloudLink.ts";
43 import { pendingServiceUpdateExists } from "./updateHandoff.ts";
44 import { managedTunnelStartupAction } from "./managedTunnelStartup.ts";
45 import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
46 +import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
47
48 const storeFailure = (tag: "AlreadyExists" | "PermissionDenied") =>
49 new ServerSecretStore.SecretStorePersistError({
@@ -158,7 +159,7 @@ describe("releaseManagedTunnelOnShutdown", () => {
159 (harness: ReleaseHarness) =>
160 <A, E, R>(effect: Effect.Effect<A, E, R>) =>
161 effect.pipe(
161 - Effect.provide(CloudLink.layer),
162 + Effect.provide(CloudLink.layer.pipe(Layer.provide(ManagedPolicy.layerTest()))),
163 Effect.provideService(
164 ConnectReachability.ConnectReachability,
165 ConnectReachability.ConnectReachability.of({
apps/server/src/cloud/CloudLink.test.ts
+57
@@ -19,11 +19,13 @@ import * as CloudLink from "./CloudLink.ts";
19 import * as ConnectReachability from "./ConnectReachability.ts";
20 import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
21 import {
22 + CLOUD_LINKED_USER_ID,
23 HOLD_WEBHOOKS_WHILE_OFFLINE_SECRET,
24 PUBLISH_AGENT_ACTIVITY_SECRET,
25 RELAY_ENVIRONMENT_CREDENTIAL_SECRET,
26 RELAY_URL_SECRET,
27 } from "./config.ts";
28 +import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
29
30 const encode = (value: string) => new TextEncoder().encode(value);
31
@@ -95,6 +97,7 @@ const withService = <A, E>(
97 }),
98 Layer.mock(AgentAwarenessRelay.AgentAwarenessRelay)({ requestCatchUp: () => Effect.void }),
99 Layer.mock(ManagedEndpointRuntime.CloudManagedEndpointRuntime)({}),
100 + ManagedPolicy.layerTest(),
101 Layer.mock(ConnectReachability.ConnectReachability)({
102 latest: Effect.succeedNone,
103 }),
@@ -244,3 +247,57 @@ it.effect("an update the client walks away from still finishes", () => {
247 }),
248 );
249 });
250 +
251 +it.effect("unlinks on startup and refuses to link when the policy turns Connect off", () =>
252 + Effect.gen(function* () {
253 + const stored = new Map<string, Uint8Array>([
254 + [CLOUD_LINKED_USER_ID, encode("user-1")],
255 + [RELAY_URL_SECRET, encode("https://relay.test")],
256 + ]);
257 + const appliedConfigs: Array<unknown> = [];
258 + const layerDependencies = Layer.mergeAll(
259 + Layer.mock(ServerSecretStore.ServerSecretStore)({
260 + get: (name) => Effect.succeed(Option.fromNullishOr(stored.get(name))),
261 + set: (name, value) => Effect.sync(() => void stored.set(name, value)),
262 + remove: (name) => Effect.sync(() => void stored.delete(name)),
263 + }),
264 + Layer.mock(ServerEnvironment.ServerEnvironment)({}),
265 + Layer.mock(AgentAwarenessRelay.AgentAwarenessRelay)({}),
266 + Layer.mock(ManagedEndpointRuntime.CloudManagedEndpointRuntime)({
267 + withLinkStateLock: (effect) => effect,
268 + applyConfig: (config) =>
269 + Effect.sync(() => {
270 + appliedConfigs.push(config);
271 + return { status: "disabled" as const };
272 + }),
273 + }),
274 + ManagedPolicy.layerTest({
275 + schemaVersion: 1,
276 + organization: "Example Corp",
277 + limits: { connect: false },
278 + }),
279 + Layer.mock(ConnectReachability.ConnectReachability)({}),
280 + Layer.mock(EnvironmentAuth.EnvironmentAuth)({}),
281 + Layer.mock(CliTokenManager.CloudCliTokenManager)({}),
282 + Layer.mock(HttpServer.HttpServer)({
283 + address: NetAddress.inetAddressFromIpStringUnsafe("127.0.0.1", 3773),
284 + }),
285 + Layer.mock(ServerConfig.ServerConfig)({} as ServerConfig.ServerConfig["Service"]),
286 + Layer.succeed(
287 + HttpClient.HttpClient,
288 + HttpClient.make(() => Effect.die("unused")),
289 + ),
290 + NodeServices.layer,
291 + );
292 + yield* Effect.gen(function* () {
293 + const link = yield* CloudLink.CloudLink;
294 + assert.isFalse(stored.has(CLOUD_LINKED_USER_ID));
295 + assert.deepEqual(appliedConfigs, [null]);
296 +
297 + const applyError = yield* link.applyRelayConfig({} as never).pipe(Effect.flip);
298 + const mintError = yield* link.mintCredential({} as never).pipe(Effect.flip);
299 + assert.equal(applyError.message, "Example Corp's policy does not allow T3 Connect.");
300 + assert.equal(mintError._tag, "ManagedPolicyRefusedError");
301 + }).pipe(Effect.provide(CloudLink.layer.pipe(Layer.provide(layerDependencies))));
302 + }),
303 +);
apps/server/src/cloud/CloudLink.ts
+41 -2
@@ -98,6 +98,8 @@ import {
98 import { getOrCreateEnvironmentKeyPairFromSecretStore } from "./environmentKeys.ts";
99 import * as ConnectReachability from "./ConnectReachability.ts";
100 import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
101 +import * as ManagedLimits from "../policy/managedLimits.ts";
102 +import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
103 import { relayUrlConfig } from "./publicConfig.ts";
104 import {
105 filterRelayResponse,
@@ -432,7 +434,8 @@ export class CloudLink extends Context.Service<
434 RelayEnvironmentLinkProof,
435 | CloudLinkOriginInvalidError
436 | CloudLinkInternalError
435 - | EnvironmentAuth.ServerAuthInternalError,
437 + | EnvironmentAuth.ServerAuthInternalError
438 + | ManagedLimits.ManagedPolicyRefusedError,
439 EnvironmentAuthenticatedPrincipal
440 >;
441 readonly applyRelayConfig: (
@@ -446,6 +449,7 @@ export class CloudLink extends Context.Service<
449 | CloudLinkRelayConfigInvalidError
450 | CloudLinkTunnelSupersededError
451 | EnvironmentAuth.ServerAuthInternalError
452 + | ManagedLimits.ManagedPolicyRefusedError
453 | RelayRequestError
454 >;
455 readonly linkState: () => Effect.Effect<
@@ -457,7 +461,7 @@ export class CloudLink extends Context.Service<
461 input: EnvironmentCloudPreferencesRequest,
462 ) => Effect.Effect<
463 EnvironmentCloudLinkStateResult,
460 - CloudLinkNotLinkedError | CloudLinkInternalError
464 + CloudLinkNotLinkedError | CloudLinkInternalError | ManagedLimits.ManagedPolicyRefusedError
465 >;
466 readonly answerHealthRequest: (
467 request: RelayCloudEnvironmentHealthRequest,
@@ -467,6 +471,7 @@ export class CloudLink extends Context.Service<
471 | CloudLinkProofReplayedError
472 | CloudLinkInternalError
473 | EnvironmentAuth.ServerAuthInternalError
474 + | ManagedLimits.ManagedPolicyRefusedError
475 >;
476 readonly mintCredential: (
477 request: RelayCloudMintCredentialRequest,
@@ -476,6 +481,7 @@ export class CloudLink extends Context.Service<
481 | CloudLinkProofReplayedError
482 | CloudLinkInternalError
483 | EnvironmentAuth.ServerAuthInternalError
484 + | ManagedLimits.ManagedPolicyRefusedError
485 >;
486 readonly reconcileDesiredLinkIfStillDesired: (
487 localOrigin: string,
@@ -529,6 +535,7 @@ const make = Effect.gen(function* () {
535 const config = yield* ServerConfig.ServerConfig;
536 const fileSystem = yield* FileSystem.FileSystem;
537 const path = yield* Path.Path;
538 + const managedPolicy = yield* ManagedPolicy.ManagedPolicy;
539
540 const withSecrets = Effect.provideService(ServerSecretStore.ServerSecretStore, secrets);
541 const withRuntimeFiles = <A, E>(
@@ -1618,6 +1625,38 @@ const make = Effect.gen(function* () {
1625 Effect.catchTags({ PlatformError: internalError("issue-credential") }),
1626 );
1627
1628 + if (!ManagedLimits.allowsConnect(managedPolicy)) {
1629 + // Reading state and unlinking stay available so clients can show and leave the old link.
1630 + yield* unlink().pipe(
1631 + Effect.tap(() => Effect.logInfo("T3 Connect is off by managed policy; unlinked.")),
1632 + Effect.catch((cause) =>
1633 + Effect.logWarning("Failed to unlink T3 Connect turned off by managed policy", { cause }),
1634 + ),
1635 + );
1636 + const refused = Effect.fn("CloudLink.refusedByPolicy")(function* () {
1637 + return yield* ManagedLimits.refuseConnect(managedPolicy);
1638 + });
1639 + const notLinked = Effect.fn("CloudLink.notLinkedByPolicy")(() =>
1640 + Effect.succeed({ status: "not_linked" as const }),
1641 + );
1642 + const notDesired = Effect.fn("CloudLink.notDesiredByPolicy")(() => Effect.succeed(null));
1643 + const notStarted = Effect.fn("CloudLink.notStartedByPolicy")(() => Effect.succeed(false));
1644 + return CloudLink.of({
1645 + linkProof: refused,
1646 + applyRelayConfig: refused,
1647 + linkState,
1648 + unlink,
1649 + updatePreferences: refused,
1650 + answerHealthRequest: refused,
1651 + mintCredential: refused,
1652 + reconcileDesiredLinkIfStillDesired: notDesired,
1653 + registerManagedTunnelRecovery: notLinked,
1654 + recoverManagedTunnel: notStarted,
1655 + startManagedTunnelIfOriginConfirmed: notStarted,
1656 + releaseManagedTunnelOnShutdown,
1657 + });
1658 + }
1659 +
1660 return CloudLink.of({
1661 linkProof,
1662 applyRelayConfig,
apps/server/src/cloud/ManagedEndpointRuntime.test.ts
+2
@@ -23,6 +23,7 @@ import * as RelayClient from "@t3tools/shared/relayClient";
23 import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
24 import * as ServerConfig from "../config.ts";
25 import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
26 +import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
27
28 const layerRelayClientAvailable = Layer.succeed(
29 RelayClient.RelayClient,
@@ -53,6 +54,7 @@ const runtimeDependencies = (
54 secretStoreLayer = emptySecretStoreLayer,
55 ) =>
56 Layer.mergeAll(
57 + ManagedPolicy.layerTest(),
58 Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
59 Layer.succeed(HttpClient.HttpClient, httpClient),
60 relayClientLayer,
apps/server/src/cloud/ManagedEndpointRuntime.ts
+6 -1
@@ -20,6 +20,8 @@ import * as ChildProcess from "effect/process/ChildProcess";
20 import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
21
22 import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
23 +import * as ManagedLimits from "../policy/managedLimits.ts";
24 +import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
25
26 export type CloudManagedEndpointRuntimeStatus =
27 | {
@@ -192,6 +194,8 @@ export const make = Effect.gen(function* () {
194 const relayClient = yield* RelayClient.RelayClient;
195 const secrets = yield* ServerSecretStore.ServerSecretStore;
196 const httpClient = HttpClient.withScope(yield* HttpClient.HttpClient);
197 + // Without T3 Connect no connector ever runs, whoever asks for one.
198 + const connectAllowed = ManagedLimits.allowsConnect(yield* ManagedPolicy.ManagedPolicy);
199 const activeRef = yield* Ref.make<ActiveConnector | null>(null);
200 const desiredConfigRef = yield* Ref.make<RelayManagedEndpointRuntimeConfig | null>(null);
201 const recoveryRequests = yield* Queue.sliding<RelayManagedEndpointRuntimeConfig>(1);
@@ -739,9 +743,10 @@ export const make = Effect.gen(function* () {
743 });
744
745 const applyConfig = Effect.fn("CloudManagedEndpointRuntime.applyConfig")(
742 - (config: RelayManagedEndpointRuntimeConfig | null) =>
746 + (requested: RelayManagedEndpointRuntimeConfig | null) =>
747 reconcileSemaphore.withPermits(1)(
748 Effect.gen(function* () {
749 + const config = connectAllowed ? requested : null;
750 // Keep backoff when recovery returns the same tunnel/token, or every recovery respawns a crash loop.
751 const desired = yield* Ref.get(desiredConfigRef);
752 const unchanged =
apps/server/src/cloud/http.test.ts
+2
@@ -36,6 +36,7 @@ import * as CloudLink from "./CloudLink.ts";
36 import * as ConnectHttp from "./http.ts";
37 import * as ConnectReachability from "./ConnectReachability.ts";
38 import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
39 +import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
40
41 const DESKTOP_BOOTSTRAP_TOKEN = "test-desktop-bootstrap-token";
42 const NON_LOOPBACK_ORIGIN = "http://172.24.162.233:3773";
@@ -81,6 +82,7 @@ const layerLinkProofRoutes = HttpApiBuilder.layer(LinkProofTestApi).pipe(
82 ),
83 Layer.provide(EnvironmentAuth.layer),
84 Layer.provide([
85 + ManagedPolicy.layerTest(),
86 SqlitePersistence.layerMemory,
87 ServerEnvironment.layerIdentity,
88 Layer.mock(ServerEnvironment.ServerEnvironment)({
apps/server/src/cloud/http.ts
+4
@@ -16,6 +16,7 @@ import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
16
17 import { requireEnvironmentScope } from "../auth/http.ts";
18 import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
19 +import * as ManagedLimits from "../policy/managedLimits.ts";
20 import * as CloudLink from "./CloudLink.ts";
21 import * as ConnectReachability from "./ConnectReachability.ts";
22 import type { RelayRequestError } from "./relayResponse.ts";
@@ -66,6 +67,8 @@ const connectErrorCases = {
67 CloudLinkProofRejectedError: unauthorized,
68 CloudLinkProofReplayedError: conflict,
69 CloudLinkTunnelSupersededError: conflict,
70 + ManagedPolicyRefusedError: (error: ManagedLimits.ManagedPolicyRefusedError) =>
71 + Effect.fail(new EnvironmentHttpForbiddenError({ message: error.message })),
72 CloudLinkInternalError: (error: CloudLink.CloudLinkInternalError) =>
73 internalServerError(error, error.cause),
74 RelayRequestError: relayFailure,
@@ -74,6 +77,7 @@ const connectErrorCases = {
77 type ConnectFailure =
78 | Exclude<CloudLink.CloudLinkError, CloudLink.CloudLinkEndpointUnavailableError>
79 | EnvironmentAuth.ServerAuthInternalError
80 + | ManagedLimits.ManagedPolicyRefusedError
81 | RelayRequestError;
82
83 const toHttpError = <A, R>(effect: Effect.Effect<A, ConnectFailure, R>) =>
apps/server/src/cloud/relayTracing.test.ts new
+44
@@ -0,0 +1,44 @@
1 +import * as NodeServices from "@effect/platform-node/NodeServices";
2 +import { assert, it } from "@effect/vitest";
3 +import type { ManagedPolicyDocument } from "@t3tools/contracts";
4 +import * as RelayTracing from "@t3tools/shared/relayTracing";
5 +import * as Effect from "effect/Effect";
6 +import * as Layer from "effect/Layer";
7 +import * as Option from "effect/Option";
8 +import { FetchHttpClient } from "effect/http";
9 +
10 +import * as ServerConfig from "../config.ts";
11 +import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
12 +import { relayLayer } from "./relayTracing.ts";
13 +
14 +const tracesTo = (policy?: ManagedPolicyDocument) =>
15 + Effect.service(RelayTracing.RelayClientTracer).pipe(
16 + Effect.provide(
17 + relayLayer(
18 + { serviceName: "t3code-server", runtime: "node", client: "environment-server" },
19 + { tracesUrl: "https://traces.example.com", tracesDataset: "relay", tracesToken: "token" },
20 + ).pipe(
21 + Layer.provide(ManagedPolicy.layerTest(policy)),
22 + Layer.provide(
23 + ServerConfig.layerTest(process.cwd(), { prefix: "t3-relay-tracing-" }).pipe(
24 + Layer.provide(NodeServices.layer),
25 + ),
26 + ),
27 + Layer.provide(FetchHttpClient.layer),
28 + ),
29 + ),
30 + Effect.map(Option.isSome),
31 + );
32 +
33 +it.effect("a policy with telemetry off stops relay tracing to T3 Connect", () =>
34 + Effect.gen(function* () {
35 + assert.isTrue(yield* tracesTo());
36 + assert.isFalse(
37 + yield* tracesTo({
38 + schemaVersion: 1,
39 + organization: "Example Corp",
40 + limits: { telemetry: false },
41 + }),
42 + );
43 + }),
44 +);
apps/server/src/cloud/relayTracing.ts
+17 -7
@@ -7,18 +7,28 @@ import * as Effect from "effect/Effect";
7 import * as Layer from "effect/Layer";
8
9 import * as ServerConfig from "../config.ts";
10 +import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
11 import { resolveRelayClientTracingConfig } from "./publicConfig.ts";
12
13 const relayClientTracingConfig = resolveRelayClientTracingConfig();
14
14 -const relayLayer = (resource: Omit<RelayTracing.RelayClientTracingResource, "serviceInstanceId">) =>
15 +/** Relay traces leave the machine for T3 Connect, so a policy with `telemetry: false` stops them. */
16 +export const relayLayer = (
17 + resource: Omit<RelayTracing.RelayClientTracingResource, "serviceInstanceId">,
18 + tracingConfig = relayClientTracingConfig,
19 +) =>
20 Layer.unwrap(
16 - Effect.map(ServerConfig.ServerConfig, (config) =>
17 - RelayTracing.layer(relayClientTracingConfig, {
18 - ...resource,
19 - serviceInstanceId: processServiceInstanceId(config.otelEnvironment.resourceAttributes),
20 - }),
21 - ),
21 + Effect.gen(function* () {
22 + const config = yield* ServerConfig.ServerConfig;
23 + const policy = yield* ManagedPolicy.ManagedPolicy;
24 + return RelayTracing.layer(
25 + ManagedPolicy.deniedBy(policy, "telemetry") === undefined ? tracingConfig : null,
26 + {
27 + ...resource,
28 + serviceInstanceId: processServiceInstanceId(config.otelEnvironment.resourceAttributes),
29 + },
30 + );
31 + }),
32 );
33
34 export const layerHeadlessRelayClient = relayLayer({
apps/server/src/cloud/selfUpdate.test.ts
+54 -1
@@ -1,10 +1,12 @@
1 import * as NodeServices from "@effect/platform-node/NodeServices";
2 import { expect, it } from "@effect/vitest";
3 +import type { ManagedPolicyDocument } from "@t3tools/contracts";
4 import * as HostProcess from "@t3tools/shared/HostProcess";
5 import * as Deferred from "effect/Deferred";
6 import * as Effect from "effect/Effect";
7 import * as FileSystem from "effect/FileSystem";
8 import * as Fiber from "effect/Fiber";
9 +import * as Layer from "effect/Layer";
10 import * as Path from "effect/Path";
11 import * as Stream from "effect/Stream";
12 import * as TestClock from "effect/testing/TestClock";
@@ -14,6 +16,7 @@ import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
16 import packageJson from "../../package.json" with { type: "json" };
17 import * as ServerConfig from "../config.ts";
18 import * as DesktopAppUpdate from "../desktopUpdate/DesktopAppUpdate.ts";
19 +import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
20 import * as ProcessRunner from "../processRunner.ts";
21 import * as ServiceLauncherClient from "./serviceLauncherClient.ts";
22 import { SERVICE_LAUNCHER_PROTOCOL } from "./serviceProtocol.ts";
@@ -26,6 +29,7 @@ interface HarnessOptions {
29 readonly beforeDownload?: Effect.Effect<void>;
30 readonly requestUpdate?: ServiceLauncherClient.ServiceLauncherClient["Service"]["requestUpdate"];
31 readonly desktopAppUpdate?: DesktopAppUpdate.DesktopAppUpdate["Service"];
32 + readonly policy?: ManagedPolicyDocument;
33 }
34
35 const archiveBytes = new TextEncoder().encode("not really a tarball");
@@ -122,7 +126,12 @@ const makeHarness = Effect.fn("test.make_self_update_harness")(function* (
126 Effect.provideService(HttpClient.HttpClient, releaseHttpClient(order, options.beforeDownload)),
127 Effect.provideService(HostProcess.Platform, "linux"),
128 Effect.provideService(HostProcess.Architecture, "x64"),
125 - Effect.provide(ServerConfig.layer({ ...config, mode: options.mode ?? "web" })),
129 + Effect.provide(
130 + Layer.merge(
131 + ServerConfig.layer({ ...config, mode: options.mode ?? "web" }),
132 + ManagedPolicy.layerTest(options.policy),
133 + ),
134 + ),
135 );
136 return { selfUpdate, order };
137 });
@@ -143,6 +152,50 @@ it.layer(NodeServices.layer)("server self update", (it) => {
152 }),
153 );
154
155 + it.effect("refuses every update when the managed policy turns updates off", () =>
156 + Effect.gen(function* () {
157 + const policy: ManagedPolicyDocument = {
158 + schemaVersion: 1,
159 + organization: "Example Corp",
160 + limits: { updates: { mode: "off" } },
161 + };
162 + const service = yield* makeHarness({ policy });
163 + const desktop = yield* makeHarness({
164 + mode: "desktop",
165 + policy,
166 + desktopAppUpdate: {
167 + available: true,
168 + run: () => Effect.die("unexpected desktop app update run"),
169 + commit: () => Effect.never,
170 + },
171 + });
172 + for (const harness of [service, desktop]) {
173 + expect(
174 + (yield* harness.selfUpdate.update({ targetVersion: "1.1.0" }).pipe(Effect.flip)).reason,
175 + ).toBe("Example Corp manages T3 Code updates.");
176 + }
177 + expect([...service.order, ...desktop.order]).toEqual([]);
178 + }),
179 + );
180 +
181 + it.effect("lets a user start an update, but only to stable without nightly", () =>
182 + Effect.gen(function* () {
183 + const { selfUpdate, order } = yield* makeHarness({
184 + policy: {
185 + schemaVersion: 1,
186 + organization: "Example Corp",
187 + limits: { updates: { mode: "auto", allowNightly: false } },
188 + },
189 + });
190 + expect(
191 + (yield* selfUpdate.update({ targetVersion: "1.2.0-nightly.20261028.1" }).pipe(Effect.flip))
192 + .reason,
193 + ).toBe("Example Corp manages T3 Code updates. Only stable releases can be installed.");
194 + expect(order).toEqual([]);
195 + expect((yield* selfUpdate.update({ targetVersion: "1.1.0" })).updateId).toBe("launcher-id");
196 + }),
197 + );
198 +
199 it.effect("delegates desktop-managed updates to the desktop app when available", () =>
200 Effect.gen(function* () {
201 const stages: string[] = [];
apps/server/src/cloud/selfUpdate.ts
+15 -1
@@ -20,12 +20,18 @@ import * as Queue from "effect/Queue";
20 import * as Stream from "effect/Stream";
21 import { HttpClient } from "effect/http";
22
23 -import { CLI_RELEASE_BASE_URL_ENV, crossesReleaseTrack } from "@t3tools/shared/cliRelease";
23 +import {
24 + CLI_RELEASE_BASE_URL_ENV,
25 + cliReleaseChannelOf,
26 + crossesReleaseTrack,
27 +} from "@t3tools/shared/cliRelease";
28
29 import packageJson from "../../package.json" with { type: "json" };
30 import * as ServerConfig from "../config.ts";
31 import * as DesktopAppUpdate from "../desktopUpdate/DesktopAppUpdate.ts";
32 import { databaseMigrationHead } from "../persistence/databaseMigrationHead.ts";
33 +import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
34 +import { managedUpdateRefusal } from "../policy/managedUpdates.ts";
35 import * as ProcessRunner from "../processRunner.ts";
36 import {
37 ensurePinnedRuntimeInstalled,
@@ -117,6 +123,7 @@ export function trackSwitchBlockReason(input: {
123 export const make = Effect.fn("cloud.server_self_update.make")(function* () {
124 const serverConfig = yield* ServerConfig.ServerConfig;
125 const desktopAppUpdate = yield* DesktopAppUpdate.DesktopAppUpdate;
126 + const policy = yield* ManagedPolicy.ManagedPolicy;
127 const launcher = yield* ServiceLauncherClient.ServiceLauncherClient;
128 const runner = yield* ProcessRunner.ProcessRunner;
129 const fs = yield* FileSystem.FileSystem;
@@ -151,6 +158,13 @@ export const make = Effect.fn("cloud.server_self_update.make")(function* () {
158 const update: ServerSelfUpdate["Service"]["update"] = Effect.fn(
159 "cloud.server_self_update.update",
160 )(function* (input, reportProgress = () => Effect.void, onHandoffAccepted = () => Effect.void) {
161 + const policyRefusal = managedUpdateRefusal(
162 + policy.document,
163 + capability === "boot-service" ? cliReleaseChannelOf(input.targetVersion.trim()) : undefined,
164 + );
165 + if (policyRefusal !== undefined) {
166 + return yield* failWith(policyRefusal);
167 + }
168 if (capability === "desktop-managed") {
169 const unsafeCrossing = input.channel === undefined ? null : crossesTrackUnsafely(input);
170 if (unsafeCrossing !== null) return yield* failWith(unsafeCrossing);
apps/server/src/mcp/McpHttpServer.ts
+4 -2
@@ -196,6 +196,7 @@ const makeMcpAuthMiddleware = Effect.gen(function* () {
196 const registry = yield* McpSessionRegistry.McpSessionRegistry;
197 const clients = yield* Effect.serviceOption(McpClientAuthenticator);
198 const serverSettings = yield* ServerSettings.ServerSettingsService;
199 + const runtimeModeCeiling = serverSettings.managedPolicy?.limits?.maxRuntimeMode;
200 const linksEnabled = serverSettings.getSettings.pipe(
201 Effect.map((settings) => settings.linkedEnvironmentsEnabled),
202 Effect.orElseSucceed(() => false),
@@ -222,8 +223,9 @@ const makeMcpAuthMiddleware = Effect.gen(function* () {
223 offerOAuth: Option.isSome(clients) && !looksLikeProviderToken(token),
224 });
225 }
225 - const limited = withModeLimit(invocation, request);
226 - if (limited === undefined) return invalidModeLimit;
226 + const asked = withModeLimit(invocation, request);
227 + if (asked === undefined) return invalidModeLimit;
228 + const limited = McpInvocationContext.withRuntimeModeCeiling(asked, runtimeModeCeiling);
229 const linkedEnvironments = yield* linksEnabled;
230 if (limited.client?.linked === true && !linkedEnvironments) return linkedEnvironmentsOff;
231 return yield* httpEffect.pipe(
apps/server/src/mcp/McpInvocationContext.test.ts
+32
@@ -63,3 +63,35 @@ it.effect("refuses thread-owned capabilities to a caller signed in from outside
63 expect(error.threadId).toBeUndefined();
64 });
65 });
66 +
67 +it("acts at an administrator's ceiling for a client approved above it", () => {
68 + const scope = (
69 + access: McpInvocationContext.McpClientCaller["access"],
70 + narrowedTo?: McpInvocationContext.ClientModes,
71 + ): McpInvocationContext.McpInvocationScope => ({
72 + environmentId: EnvironmentId.make("environment-1"),
73 + requestNamespace: "client:session-1",
74 + thread: undefined,
75 + client: { sessionId: "session-1", label: "Claude Code", access, narrowedTo },
76 + capabilities: new Set(["orchestration"]),
77 + issuedAt: 1,
78 + });
79 + const modes = (invocation: McpInvocationContext.McpInvocationScope, ceiling?: "auto") =>
80 + McpInvocationContext.clientModeCeiling(
81 + McpInvocationContext.withRuntimeModeCeiling(invocation, ceiling).client,
82 + );
83 +
84 + expect(modes(scope("full-access"), "auto")).toEqual({
85 + runtimeMode: "auto",
86 + interactionMode: "default",
87 + });
88 + // A narrower request and the approved mode still win below the ceiling.
89 + expect(
90 + modes(
91 + scope("full-access", { runtimeMode: "approval-required", interactionMode: "plan" }),
92 + "auto",
93 + ),
94 + ).toEqual({ runtimeMode: "approval-required", interactionMode: "plan" });
95 + expect(modes(scope("auto-accept-edits"), "auto").runtimeMode).toBe("auto-accept-edits");
96 + expect(modes(scope("full-access")).runtimeMode).toBe("full-access");
97 +});
apps/server/src/mcp/McpInvocationContext.ts
+25
@@ -96,6 +96,31 @@ export const clientModeCeiling = (client: McpClientCaller | undefined): ClientMo
96 };
97 };
98
99 +/**
100 + * A client approved above an administrator's runtime-mode ceiling acts as if it had narrowed
101 + * itself to the ceiling, so what it starts and schedules is not refused for a mode it never chose.
102 + */
103 +export const withRuntimeModeCeiling = (
104 + scope: McpInvocationScope,
105 + ceiling: RuntimeMode | undefined,
106 +): McpInvocationScope => {
107 + if (ceiling === undefined || scope.client === undefined) return scope;
108 + const asked = scope.client.narrowedTo;
109 + return {
110 + ...scope,
111 + client: {
112 + ...scope.client,
113 + narrowedTo: {
114 + runtimeMode:
115 + asked !== undefined && runtimeModeRank[asked.runtimeMode] < runtimeModeRank[ceiling]
116 + ? asked.runtimeMode
117 + : ceiling,
118 + interactionMode: asked?.interactionMode ?? "default",
119 + },
120 + },
121 + };
122 +};
123 +
124 /** Thread callers default to their own thread; client callers need thread for tools that act as the caller. */
125 export interface McpInvocationScope {
126 readonly environmentId: EnvironmentId;
apps/server/src/mcp/OrchestratorMcpService.ts
+4 -1
@@ -263,10 +263,13 @@ function scheduledTaskSummary(task: ScheduledTask, mayRun: boolean): Orchestrato
263 schedule: task.schedule,
264 nextRunAt: task.nextRunAt,
265 lastRunStatus: task.lastRunStatus,
266 - ...(task.webhook?.url == null || !mayRun ? {} : { webhookUrl: task.webhook.url }),
266 + ...(task.webhook?.url == null || !mayRun || task.blockedByPolicy !== undefined
267 + ? {}
268 + : { webhookUrl: task.webhook.url }),
269 ...(task.webhook === undefined
270 ? {}
271 : { webhookSignature: task.webhook.hasSecret ? "set" : "none" }),
272 + ...(task.blockedByPolicy === undefined ? {} : { blockedByPolicy: task.blockedByPolicy }),
273 };
274 }
275
apps/server/src/mcp/threadAccess.ts
+2 -1
@@ -47,7 +47,8 @@ export const unavailable = () =>
47 export const dispatchFailure = (
48 error: OrchestratorV2Error | ThreadManagement.ThreadManagementProviderInstanceDisabledError,
49 ) =>
50 - error._tag === "ThreadManagementProviderInstanceDisabledError"
50 + error._tag === "ThreadManagementProviderInstanceDisabledError" ||
51 + error._tag === "OrchestratorRuntimeModeAboveCeilingError"
52 ? new OrchestratorMcpFailure({ code: "invalid_request", message: error.message })
53 : (error._tag === "OrchestratorDispatchError" ||
54 error._tag === "OrchestratorCommandRejectedError") &&
apps/server/src/mcp/toolkits/project/handlers.test.ts
+34 -1
@@ -10,6 +10,7 @@ import {
10 type ModelSelection,
11 type RuntimeMode,
12 type OrchestrationV2ThreadShell,
13 + ThreadId,
14 } from "@t3tools/contracts";
15 import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
16 import * as NodeServices from "@effect/platform-node/NodeServices";
@@ -23,6 +24,7 @@ import * as Option from "effect/Option";
24 import * as Stream from "effect/Stream";
25
26 import * as DocumentText from "../../../provider/DocumentText.ts";
27 +import { OrchestratorRuntimeModeAboveCeilingError } from "../../../orchestration-v2/Orchestrator.ts";
28 import * as ThreadLaunch from "../../../orchestration-v2/ThreadLaunchService.ts";
29 import * as ThreadManagement from "../../../orchestration-v2/ThreadManagementService.ts";
30 import * as ServerConfig from "../../../config.ts";
@@ -49,6 +51,8 @@ const clientLaunchHarness = (input: {
51 readonly workspaceRoot?: string;
52 readonly checkWorktreeBase?: ThreadLaunch.ThreadLaunchService["Service"]["checkWorktreeBase"];
53 readonly webOrigin?: string;
54 + /** The orchestrator refuses the new thread's mode, as under a managed ceiling. */
55 + readonly refusedByCeiling?: true;
56 }) => {
57 const projectId = ProjectId.make("project:client-target");
58 const modelSelection = {
@@ -111,6 +115,23 @@ const clientLaunchHarness = (input: {
115 checkWorktreeBase: input.checkWorktreeBase ?? (() => Effect.void),
116 launch: (launch) => {
117 input.launched.push(launch);
118 + if (input.refusedByCeiling) {
119 + return Effect.fail(
120 + new ThreadLaunch.ThreadLaunchError({
121 + operation: "create-thread",
122 + commandId: launch.commandId,
123 + projectId: launch.projectId,
124 + cause: new OrchestratorRuntimeModeAboveCeilingError({
125 + commandId: launch.commandId,
126 + threadId: launch.threadId ?? ThreadId.make("thread:refused"),
127 + refused: "mode",
128 + runtimeMode: launch.runtimeMode,
129 + maxRuntimeMode: "approval-required",
130 + organization: "Example Corp",
131 + }),
132 + }),
133 + );
134 + }
135 return Effect.succeed({
136 threadId: launch.threadId,
137 projection: {
@@ -168,9 +189,10 @@ it.effect(
189 readonly targeted?: false;
190 readonly overrideModel?: ModelSelection;
191 readonly webOrigin?: string;
192 + readonly refusedByCeiling?: true;
193 },
194 ) {
173 - const { targeted, overrideModel, webOrigin, ...input } = params;
195 + const { targeted, overrideModel, webOrigin, refusedByCeiling, ...input } = params;
196 const launched: Array<ThreadLaunch.ThreadLaunchInput> = [];
197 const { projectId, modelSelection, dependencies } = clientLaunchHarness({
198 runtimeModeCeiling,
@@ -178,6 +200,7 @@ it.effect(
200 launched,
201 ...(overrideModel === undefined ? {} : { overrideModel }),
202 ...(webOrigin === undefined ? {} : { webOrigin }),
203 + ...(refusedByCeiling === undefined ? {} : { refusedByCeiling }),
204 });
205 const toolkit = yield* ProjectToolkit.pipe(
206 Effect.provide(
@@ -241,6 +264,16 @@ it.effect(
264 overrideModel,
265 });
266 expect(fromSettings.launched[0]?.modelSelection).toEqual(overrideModel);
267 +
268 + // An administrator's ceiling the orchestrator enforces is named, not reported as unavailable.
269 + const managed = yield* launchWith("full-access", "full-access", {
270 + title: "Fix",
271 + refusedByCeiling: true,
272 + });
273 + expect(managed.result).toMatchObject({
274 + code: "invalid_request",
275 + message: "Example Corp limits threads to Supervised.",
276 + });
277 }),
278 );
279
apps/server/src/mcp/toolkits/project/handlers.ts
+11
@@ -10,6 +10,8 @@ import * as Effect from "effect/Effect";
10 import * as Hex from "effect/encoding/Hex";
11 import * as FileSystem from "effect/FileSystem";
12 import * as Option from "effect/Option";
13 +import * as Schema from "effect/Schema";
14 +import { OrchestratorRuntimeModeAboveCeilingError } from "../../../orchestration-v2/Orchestrator.ts";
15 import * as ThreadLaunch from "../../../orchestration-v2/ThreadLaunchService.ts";
16 import * as ThreadMessageIntake from "../../../orchestration-v2/ThreadMessageIntake.ts";
17 import * as Claims from "../../../orchestration-v2/AttachmentClaims.ts";
@@ -30,6 +32,8 @@ import * as McpToolAccess from "../../McpToolAccess.ts";
32 import { newCommandId, readCaller, resolveProjectId, unavailable } from "../../threadAccess.ts";
33 import { ProjectToolkit } from "./tools.ts";
34
35 +const isAboveCeilingError = Schema.is(OrchestratorRuntimeModeAboveCeilingError);
36 +
37 function projectFailure(error: Project.ProjectServiceError) {
38 if (error._tag === "ProjectOperationError") return unavailable();
39 const message =
@@ -257,6 +261,13 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
261 message: error.message,
262 });
263 }
264 + // The administrator's ceiling refuses the mode; say so rather than "unavailable".
265 + if (error._tag === "ThreadLaunchError" && isAboveCeilingError(error.cause)) {
266 + return new OrchestratorMcpFailure({
267 + code: "invalid_request",
268 + message: error.cause.message,
269 + });
270 + }
271 return unavailable();
272 }),
273 );
apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts
+67
@@ -1037,3 +1037,70 @@ describe("AntigravityAdapterV2 subagent reads", () => {
1037 }).pipe(Effect.provide(layerSession), Effect.scoped),
1038 );
1039 });
1040 +
1041 +describe("AntigravityAdapterV2 runtime mode ceiling", () => {
1042 + const modesSetFor = (pickedMode: string) =>
1043 + Effect.gen(function* () {
1044 + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
1045 + const path = yield* Path.Path;
1046 + const crypto = yield* Crypto.Crypto;
1047 + const mockAgentPath = yield* path.fromFileUrl(
1048 + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
1049 + );
1050 + type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"];
1051 + const modesSet: Array<string> = [];
1052 + const instanceId = ProviderInstanceId.make("antigravity-ceiling-test");
1053 + const adapter = yield* makeAntigravityAdapterV2({
1054 + instanceId,
1055 + selfInvocation: yield* resolveSelfInvocation(),
1056 + makeRuntime: (input) =>
1057 + makeAntigravityAcpRuntime({
1058 + ...input,
1059 + childProcessSpawner,
1060 + spawn: {
1061 + command: process.execPath,
1062 + args: [mockAgentPath],
1063 + cwd: input.cwd,
1064 + env: { T3_ACP_ANTIGRAVITY: "1" },
1065 + },
1066 + }).pipe(
1067 + Effect.provideService(Crypto.Crypto, crypto),
1068 + Effect.map((runtime): RuntimeService => ({
1069 + ...runtime,
1070 + setMode: (modeId) =>
1071 + Effect.sync(() => {
1072 + modesSet.push(modeId);
1073 + }).pipe(Effect.andThen(runtime.setMode(modeId))),
1074 + })),
1075 + ),
1076 + withProcess: (_stop, task) => task,
1077 + // @effect-diagnostics-next-line effectSucceedWithVoid:off - This optional result requires undefined, not the wider void type.
1078 + defaultModel: Effect.succeed(undefined),
1079 + });
1080 + const threadId = ThreadId.make("thread-antigravity-ceiling");
1081 + yield* adapter.openSession({
1082 + threadId,
1083 + providerSessionId: ProviderSessionId.make("provider-session-antigravity-ceiling"),
1084 + modelSelection: {
1085 + instanceId,
1086 + model: "gemini-test-low",
1087 + options: [{ id: "_t3/session-mode", value: pickedMode }],
1088 + },
1089 + runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
1090 + runtimeMode: "approval-required",
1091 + interactionMode: "default",
1092 + cwd: process.cwd(),
1093 + maxRuntimeMode: "auto-accept-edits",
1094 + }),
1095 + });
1096 + return modesSet;
1097 + }).pipe(Effect.provide(layerSession), Effect.scoped);
1098 +
1099 + it.effect("does not apply a picked session mode above the policy ceiling", () =>
1100 + Effect.gen(function* () {
1101 + assert.deepEqual(yield* modesSetFor("yolo"), ["default"]);
1102 + // A mode under the ceiling is still the user's to pick.
1103 + assert.deepEqual(yield* modesSetFor("auto_edit"), ["default", "auto_edit"]);
1104 + }),
1105 + );
1106 +});
apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts
+2
@@ -20,6 +20,7 @@ import type { AntigravityAuth } from "../../provider/AntigravityAuth.ts";
20 import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
21 import {
22 antigravityPermissionMode,
23 + antigravityRuntimeModeForSessionMode,
24 applyAntigravityAcpModelSelection,
25 buildAntigravityPrompt,
26 type AntigravityAcpRuntimeInput,
@@ -217,6 +218,7 @@ export function makeAntigravityAcpAdapterFlavor(
218 });
219 }),
220 sessionModeForPolicy: (policy) => antigravityPermissionMode(policy.runtimeMode),
221 + runtimeModeForSessionMode: antigravityRuntimeModeForSessionMode,
222 clientFileSystem: {
223 readTextFile: (request, cwd) =>
224 readAntigravityClientTextFile({
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+26
@@ -831,6 +831,32 @@ describe("ClaudeAdapterV2 session permissions", () => {
831 destination: "session",
832 },
833 ]);
834 +
835 + // Under an administrator's ceiling a suggested mode switch is dropped; the rule stays.
836 + const managed = ClaudeAdapterV2.permissionResultFromDecision({
837 + toolName: "Edit",
838 + decision: "acceptForSession",
839 + toolInput: {},
840 + toolUseID: "tool-2",
841 + managedCeiling: true,
842 + suggestions: [
843 + { type: "setMode", mode: "acceptEdits", destination: "session" },
844 + {
845 + type: "addRules",
846 + rules: [{ toolName: "Edit" }],
847 + behavior: "allow",
848 + destination: "session",
849 + },
850 + ],
851 + });
852 + assert.deepEqual(managed.behavior === "allow" ? managed.updatedPermissions : undefined, [
853 + {
854 + type: "addRules",
855 + rules: [{ toolName: "Edit" }],
856 + behavior: "allow",
857 + destination: "session",
858 + },
859 + ]);
860 });
861
862 it("adds a whole-tool session rule when Claude offers no suggestion", () => {
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+9 -1
@@ -3421,6 +3421,8 @@ export function permissionResultFromDecision(input: {
3421 readonly toolUseID: string;
3422 readonly suggestions?: Parameters<CanUseTool>[2]["suggestions"];
3423 readonly feedback?: string;
3424 + /** Under an administrator's ceiling, T3 Code's mode is the only one; Claude cannot switch it. */
3425 + readonly managedCeiling?: boolean;
3426 }): PermissionResult {
3427 if (input.decision === "accept" || input.decision === "acceptForSession") {
3428 return {
@@ -3431,7 +3433,12 @@ export function permissionResultFromDecision(input: {
3433 input.decision === "acceptForSession" ? "user_permanent" : "user_temporary",
3434 ...(input.decision === "acceptForSession"
3435 ? {
3434 - updatedPermissions: toSessionPermissionUpdates(input.toolName, input.suggestions),
3436 + updatedPermissions: toSessionPermissionUpdates(
3437 + input.toolName,
3438 + input.managedCeiling === true
3439 + ? input.suggestions?.filter((suggestion) => suggestion.type !== "setMode")
3440 + : input.suggestions,
3441 + ),
3442 }
3443 : {}),
3444 };
@@ -9854,6 +9861,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
9861 ...resolvedDecision,
9862 toolInput,
9863 toolUseID: callbackOptions.toolUseID,
9864 + managedCeiling: context.input.runtimePolicy.maxRuntimeMode !== undefined,
9865 ...(callbackOptions.suggestions === undefined
9866 ? {}
9867 : { suggestions: callbackOptions.suggestions }),
apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.test.ts
+2
@@ -39,6 +39,7 @@ import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
39 import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
40 import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
41 import * as RuntimePolicy from "../RuntimePolicy.ts";
42 +import * as ServerSettings from "../../serverSettings.ts";
43 import { acpPermissionDisposition } from "@t3tools/provider-acp/server/clientPolicy";
44 import { acpCompletedTurnShouldTerminalizeTool } from "@t3tools/provider-acp/server/adapter";
45 import {
@@ -336,6 +337,7 @@ describe("Grok launch permission mode", () => {
337 }).pipe(
338 Effect.provide(
339 RuntimePolicy.layerFromProjectStore.pipe(
340 + Layer.provide(ServerSettings.layerTest()),
341 Layer.provide(
342 Layer.mock(ProjectStore.ProjectStoreV2)({
343 get: () => Effect.die("the thread has a worktree"),
apps/server/src/orchestration-v2/CheckpointRollbackService.ts
+3 -1
@@ -33,7 +33,7 @@ import { GIT_INDEX_LOCKED_DETAIL } from "../vcs/VcsProcess.ts";
33 import * as ProjectStore from "./ProjectStore.ts";
34 import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
35 import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts";
36 -import { RuntimePolicyV2 } from "./RuntimePolicy.ts";
36 +import { RuntimePolicyAboveCeilingError, RuntimePolicyV2 } from "./RuntimePolicy.ts";
37 import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts";
38
39 export const ROLLBACK_FAILED_MESSAGE =
@@ -74,6 +74,7 @@ export class CheckpointRollbackExecutionError extends Schema.TaggedError<Checkpo
74 const isCheckpointRollbackExecutionError = Schema.is(CheckpointRollbackExecutionError);
75 const isVcsProcessExitError = Schema.is(VcsProcessExitError);
76 const isCheckpointRestoreError = Schema.is(CheckpointRestoreError);
77 +const isRuntimePolicyAboveCeilingError = Schema.is(RuntimePolicyAboveCeilingError);
78
79 /**
80 * The message clients see when a rollback fails. Only a held Git index lock
@@ -81,6 +82,7 @@ const isCheckpointRestoreError = Schema.is(CheckpointRestoreError);
82 * output, so they fall back to the generic message.
83 */
84 export function rollbackFailureClientMessage(error: CheckpointRollbackExecutionError): string {
85 + if (isRuntimePolicyAboveCeilingError(error.cause)) return error.cause.message;
86 const restoreCause = isCheckpointRestoreError(error.cause) ? error.cause.cause : undefined;
87 return isVcsProcessExitError(restoreCause) && restoreCause.detail === GIT_INDEX_LOCKED_DETAIL
88 ? GIT_INDEX_LOCKED_DETAIL
apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts
+2
@@ -25,6 +25,7 @@ import * as Queue from "effect/Queue";
25 import * as Schema from "effect/Schema";
26 import * as Stream from "effect/Stream";
27 import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
28 +import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
29 import * as SecretRequests from "../secrets/SecretRequests.ts";
30 import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts";
31 import * as Scheduler from "../scheduling/Scheduler.ts";
@@ -331,6 +332,7 @@ it.effect.each(deliveries)(
332 }),
333 ),
334 Layer.provide(Layer.mock(ThreadLaunchService.ThreadLaunchService)({})),
335 + Layer.provide(ManagedPolicy.layerTest()),
336 Layer.provide(
337 Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({
338 namedProjectsRoot: "/projects",
apps/server/src/orchestration-v2/DispatchModeLimit.test.ts
+221
@@ -1,16 +1,20 @@
1 import { assert, it } from "@effect/vitest";
2 import {
3 CommandId,
4 + EventId,
5 + MessageId,
6 ProjectId,
7 ProviderDriverKind,
8 ProviderInstanceId,
9 ThreadId,
10 } from "@t3tools/contracts";
11 +import * as DateTime from "effect/DateTime";
12 import * as Effect from "effect/Effect";
13 import * as Layer from "effect/Layer";
14 import * as SqlitePersistence from "../persistence/Sqlite.ts";
15 import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
16 import { DispatchModeLimit } from "./DispatchModeLimit.ts";
17 +import * as EventSink from "./EventSink.ts";
18 import * as Orchestrator from "./Orchestrator.ts";
19 import * as ProjectionStore from "./ProjectionStore.ts";
20 import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
@@ -136,3 +140,220 @@ it.layer(layerTest)("DispatchModeLimit", (it) => {
140 }),
141 );
142 });
143 +
144 +const layerPolicyDatabase = SqlitePersistence.layerMemory;
145 +const layerWithCeiling = Layer.mergeAll(
146 + layerPolicyDatabase,
147 + ProjectionStore.layer.pipe(Layer.provide(layerPolicyDatabase)),
148 + ProviderReplayHarness.layerWithRegistry(
149 + { name: "runtime-mode-ceiling" },
150 + ProviderAdapterRegistry.layerFromAdapters([adapter]),
151 + {
152 + databaseLayer: layerPolicyDatabase,
153 + runEffectWorker: false,
154 + managedPolicy: {
155 + schemaVersion: 1,
156 + organization: "Example Corp",
157 + limits: { maxRuntimeMode: "auto-accept-edits" },
158 + },
159 + },
160 + ),
161 +);
162 +
163 +const sendMessage = (threadId: ThreadId, id: string) => ({
164 + type: "message.dispatch" as const,
165 + commandId: CommandId.make(`send:${id}`),
166 + threadId,
167 + messageId: MessageId.make(`message:${id}`),
168 + text: id,
169 + attachments: [],
170 + dispatchMode: { type: "start_immediately" as const },
171 + createdBy: "user" as const,
172 + creationSource: "web" as const,
173 +});
174 +
175 +/** A thread that ran in full access before the policy arrived, as an import or an older build leaves it. */
176 +const raiseBehindPolicy = (threadId: ThreadId) =>
177 + Effect.gen(function* () {
178 + const orchestrator = yield* Orchestrator.OrchestratorV2;
179 + const sink = yield* EventSink.EventSinkV2;
180 + yield* createThread(threadId);
181 + const { thread } = yield* orchestrator.getThreadRecords(threadId, []);
182 + yield* sink.write({
183 + events: [
184 + {
185 + id: EventId.make(`event:raise-behind-policy:${threadId}`),
186 + type: "thread.runtime-mode-updated",
187 + threadId,
188 + occurredAt: yield* DateTime.now,
189 + payload: { ...thread, runtimeMode: "full-access" },
190 + },
191 + ],
192 + });
193 + });
194 +
195 +it.layer(layerWithCeiling)("runtime mode ceiling", (it) => {
196 + it.effect("refuses the user's own thread and mode changes above the ceiling", () =>
197 + Effect.gen(function* () {
198 + const orchestrator = yield* Orchestrator.OrchestratorV2;
199 + const projections = yield* ProjectionStore.ProjectionStoreV2;
200 + const threadId = ThreadId.make("thread:ceiling-user");
201 + const create = {
202 + type: "thread.create",
203 + commandId: CommandId.make("create:ceiling-user:full"),
204 + threadId,
205 + projectId: ProjectId.make("project:dispatch-mode-limit"),
206 + title: "Full",
207 + modelSelection: { instanceId, model: "gpt-5" },
208 + runtimeMode: "full-access",
209 + interactionMode: "default",
210 + branch: null,
211 + worktreePath: null,
212 + createdBy: "user",
213 + creationSource: "web",
214 + } as const;
215 + const refusedCreate = yield* orchestrator.dispatch(create).pipe(Effect.flip);
216 + assert.ok(refusedCreate._tag === "OrchestratorRuntimeModeAboveCeilingError");
217 + assert.equal(refusedCreate.refused, "mode");
218 + assert.equal(refusedCreate.message, "Example Corp limits threads to Auto-accept edits.");
219 + assert.isNull(yield* projections.getThreadShell(threadId));
220 +
221 + yield* createThread(threadId);
222 + const raise = yield* orchestrator
223 + .dispatch({
224 + type: "thread.runtime-mode.set",
225 + commandId: CommandId.make("raise:ceiling-user"),
226 + threadId,
227 + runtimeMode: "auto",
228 + })
229 + .pipe(Effect.flip);
230 + assert.equal(raise._tag, "OrchestratorRuntimeModeAboveCeilingError");
231 + yield* orchestrator.dispatch({
232 + type: "thread.runtime-mode.set",
233 + commandId: CommandId.make("raise-to-ceiling:ceiling-user"),
234 + threadId,
235 + runtimeMode: "auto-accept-edits",
236 + });
237 + assert.equal((yield* projections.getThreadShell(threadId))?.runtimeMode, "auto-accept-edits");
238 + }),
239 + );
240 +
241 + it.effect("narrows an MCP caller's limit to the ceiling inside the lock", () =>
242 + Effect.gen(function* () {
243 + const orchestrator = yield* Orchestrator.OrchestratorV2;
244 + const projections = yield* ProjectionStore.ProjectionStoreV2;
245 + const threadId = ThreadId.make("thread:ceiling-mcp");
246 + yield* createThread(threadId);
247 + const fullAccessCaller = { runtimeMode: "full-access", interactionMode: "default" } as const;
248 + const raise = yield* orchestrator
249 + .dispatch({
250 + type: "thread.runtime-mode.set",
251 + commandId: CommandId.make("raise:ceiling-mcp"),
252 + threadId,
253 + runtimeMode: "full-access",
254 + })
255 + .pipe(Effect.provideService(DispatchModeLimit, fullAccessCaller), Effect.flip);
256 + assert.equal(raise._tag, "OrchestratorRuntimeModeAboveCeilingError");
257 +
258 + const raisedThreadId = ThreadId.make("thread:ceiling-mcp-raised");
259 + yield* raiseBehindPolicy(raisedThreadId);
260 + const rename = yield* orchestrator
261 + .dispatch({
262 + type: "thread.metadata.update",
263 + commandId: CommandId.make("rename:ceiling-mcp"),
264 + threadId: raisedThreadId,
265 + title: "After",
266 + })
267 + .pipe(Effect.provideService(DispatchModeLimit, fullAccessCaller), Effect.flip);
268 + assert.equal(rename._tag, "OrchestratorThreadAboveModeLimitError");
269 + assert.equal((yield* projections.getThreadShell(raisedThreadId))?.title, "Before");
270 + }),
271 + );
272 +
273 + it.effect("refuses turns on a thread above the ceiling until its mode is lowered", () =>
274 + Effect.gen(function* () {
275 + const orchestrator = yield* Orchestrator.OrchestratorV2;
276 + const projections = yield* ProjectionStore.ProjectionStoreV2;
277 + const threadId = ThreadId.make("thread:ceiling-raised");
278 + yield* raiseBehindPolicy(threadId);
279 +
280 + const refused = yield* orchestrator
281 + .dispatch(sendMessage(threadId, "first"))
282 + .pipe(Effect.flip);
283 + assert.ok(refused._tag === "OrchestratorRuntimeModeAboveCeilingError");
284 + assert.equal(refused.refused, "turn");
285 + assert.equal(
286 + refused.message,
287 + "Example Corp limits threads to Auto-accept edits. Switch this thread's mode to continue.",
288 + );
289 + assert.lengthOf((yield* orchestrator.getThreadRecords(threadId, ["runs"])).runs, 0);
290 +
291 + // The user's own housekeeping and the way back down stay open.
292 + yield* orchestrator.dispatch({
293 + type: "thread.metadata.update",
294 + commandId: CommandId.make("rename:ceiling-raised"),
295 + threadId,
296 + title: "After",
297 + });
298 + yield* orchestrator.dispatch({
299 + type: "thread.runtime-mode.set",
300 + commandId: CommandId.make("lower:ceiling-raised"),
301 + threadId,
302 + runtimeMode: "approval-required",
303 + });
304 + // Refusals record no receipt, so the same command goes through once the mode is lowered.
305 + yield* orchestrator.dispatch(sendMessage(threadId, "first"));
306 + assert.lengthOf((yield* orchestrator.getThreadRecords(threadId, ["runs"])).runs, 1);
307 + assert.equal((yield* projections.getThreadShell(threadId))?.title, "After");
308 + }),
309 + );
310 +
311 + it.effect("starts a queue that waited above the ceiling once the mode is lowered", () =>
312 + Effect.gen(function* () {
313 + const orchestrator = yield* Orchestrator.OrchestratorV2;
314 + const sink = yield* EventSink.EventSinkV2;
315 + const threadId = ThreadId.make("thread:ceiling-queue");
316 + yield* createThread(threadId);
317 + yield* orchestrator.dispatch(sendMessage(threadId, "running"));
318 + yield* orchestrator.dispatch({
319 + ...sendMessage(threadId, "waiting"),
320 + dispatchMode: { type: "queue_after_active" },
321 + });
322 + // The policy arrives with the thread above it and its first run ending.
323 + const { thread, runs } = yield* orchestrator.getThreadRecords(threadId, ["runs"]);
324 + const [running, waiting] = runs;
325 + const occurredAt = yield* DateTime.now;
326 + yield* sink.write({
327 + events: [
328 + {
329 + id: EventId.make("event:ceiling-queue:raise"),
330 + type: "thread.runtime-mode-updated",
331 + threadId,
332 + occurredAt,
333 + payload: { ...thread, runtimeMode: "full-access" },
334 + },
335 + {
336 + id: EventId.make("event:ceiling-queue:complete"),
337 + type: "run.updated",
338 + threadId,
339 + runId: running!.id,
340 + providerInstanceId: running!.providerInstanceId,
341 + occurredAt,
342 + payload: { ...running!, status: "completed" },
343 + },
344 + ],
345 + });
346 +
347 + yield* orchestrator.dispatch({
348 + type: "thread.runtime-mode.set",
349 + commandId: CommandId.make("lower:ceiling-queue"),
350 + threadId,
351 + runtimeMode: "approval-required",
352 + });
353 + const started = (yield* orchestrator.getThreadRecords(threadId, ["runs"])).runs.find(
354 + (run) => run.id === waiting!.id,
355 + );
356 + assert.notEqual(started?.status, "queued");
357 + }),
358 + );
359 +});
apps/server/src/orchestration-v2/DispatchModeLimit.ts
+79 -8
@@ -1,4 +1,10 @@
1 -import type { ProviderInteractionMode, RuntimeMode, ThreadId } from "@t3tools/contracts";
1 +import {
2 + isRuntimeModeAbove,
3 + type OrchestrationV2DomainEvent,
4 + type ProviderInteractionMode,
5 + type RuntimeMode,
6 + type ThreadId,
7 +} from "@t3tools/contracts";
8 import * as Context from "effect/Context";
9 import type * as Ref from "effect/Ref";
10
@@ -22,20 +28,85 @@ export const DispatchModeLimit = Context.Reference<DispatchModeLimitValue | unde
28 { defaultValue: () => undefined },
29 );
30
25 -const runtimeModeRank: Record<RuntimeMode, number> = {
26 - "approval-required": 0,
27 - "auto-accept-edits": 1,
28 - auto: 2,
29 - "full-access": 3,
30 -};
31 const interactionModeRank: Record<ProviderInteractionMode, number> = { plan: 0, default: 1 };
32
33 export const exceededDispatchModeLimit = (
34 limit: DispatchModes,
35 modes: DispatchModes,
36 ): "runtime" | "interaction" | undefined =>
37 - runtimeModeRank[modes.runtimeMode] > runtimeModeRank[limit.runtimeMode]
37 + isRuntimeModeAbove(modes.runtimeMode, limit.runtimeMode)
38 ? "runtime"
39 : interactionModeRank[modes.interactionMode] > interactionModeRank[limit.interactionMode]
40 ? "interaction"
41 : undefined;
42 +
43 +/** The administrator's `limits.maxRuntimeMode`, which applies to every caller, the user included. */
44 +export interface RuntimeModeCeiling {
45 + readonly organization: string;
46 + readonly maxRuntimeMode: RuntimeMode;
47 +}
48 +
49 +/** A caller's limit, lowered to the ceiling when the caller may otherwise go above it. */
50 +export const narrowToCeiling = <Limit extends DispatchModes>(
51 + limit: Limit | undefined,
52 + ceiling: RuntimeModeCeiling | undefined,
53 +): Limit | undefined =>
54 + limit === undefined ||
55 + ceiling === undefined ||
56 + !isRuntimeModeAbove(limit.runtimeMode, ceiling.maxRuntimeMode)
57 + ? limit
58 + : { ...limit, runtimeMode: ceiling.maxRuntimeMode };
59 +
60 +export interface RuntimeModeCeilingRefusal {
61 + readonly threadId: ThreadId;
62 + readonly runtimeMode: RuntimeMode;
63 + /** `mode`: a thread would be created in or switched to the mode. `turn`: a turn would run in it. */
64 + readonly refused: "mode" | "turn";
65 +}
66 +
67 +/**
68 + * What a planned command would do above the ceiling, judged by its events so every command that
69 + * creates a thread, switches its mode, or starts or steers a turn is covered. `runtimeModes` holds
70 + * the committed mode of each thread a planned run belongs to. Lowering a mode, and commands that
71 + * start no work, stay open on a thread above the ceiling: they are how its user gets back under.
72 + */
73 +export const runtimeModeCeilingRefusal = (
74 + maxRuntimeMode: RuntimeMode,
75 + events: ReadonlyArray<OrchestrationV2DomainEvent>,
76 + runtimeModes: ReadonlyMap<ThreadId, RuntimeMode>,
77 +): RuntimeModeCeilingRefusal | undefined => {
78 + const planned = new Map(runtimeModes);
79 + for (const event of events) {
80 + if (event.type === "thread.created" || event.type === "thread.runtime-mode-updated") {
81 + const { runtimeMode } = event.payload;
82 + planned.set(event.threadId, runtimeMode);
83 + if (isRuntimeModeAbove(runtimeMode, maxRuntimeMode)) {
84 + return { threadId: event.threadId, runtimeMode, refused: "mode" };
85 + }
86 + } else if (event.type === "run.created" || event.type === "run-attempt.created") {
87 + const runtimeMode = planned.get(event.threadId);
88 + if (runtimeMode !== undefined && isRuntimeModeAbove(runtimeMode, maxRuntimeMode)) {
89 + return { threadId: event.threadId, runtimeMode, refused: "turn" };
90 + }
91 + }
92 + }
93 + return undefined;
94 +};
95 +
96 +/** Threads whose committed mode `runtimeModeCeilingRefusal` needs: those a planned run belongs to. */
97 +export const threadsStartingWork = (
98 + events: ReadonlyArray<OrchestrationV2DomainEvent>,
99 +): ReadonlySet<ThreadId> => {
100 + const created = new Set<ThreadId>();
101 + const starting = new Set<ThreadId>();
102 + for (const event of events) {
103 + if (event.type === "thread.created") created.add(event.threadId);
104 + else if (
105 + (event.type === "run.created" || event.type === "run-attempt.created") &&
106 + !created.has(event.threadId)
107 + ) {
108 + starting.add(event.threadId);
109 + }
110 + }
111 + return starting;
112 +};
apps/server/src/orchestration-v2/Orchestrator.ts
+106 -5
@@ -62,6 +62,7 @@ import {
62 orchestrationV2WorktreePending,
63 ProviderInstanceId,
64 ProviderInteractionMode,
65 + isRuntimeModeAbove,
66 resolveProviderInstanceEnabled,
67 resolveProjectProviderInstanceEnabled,
68 type ProviderSessionId,
@@ -71,6 +72,7 @@ import {
72 ThreadId,
73 TurnItemId,
74 TrimmedNonEmptyString,
75 + managedRuntimeModeCeilingMessage,
76 } from "@t3tools/contracts";
77 import { modelSelectionsEqual } from "@t3tools/shared/model";
78 import { recordThreadOpen } from "@t3tools/shared/paletteSearch";
@@ -138,7 +140,14 @@ import { withCommandMetrics } from "../observability/Metrics.ts";
140 import type { OrchestrationEffectRequestV2, PendingOrchestrationEffectV2 } from "./EffectOutbox.ts";
141 import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
142 import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts";
141 -import { DispatchModeLimit, exceededDispatchModeLimit } from "./DispatchModeLimit.ts";
143 +import {
144 + DispatchModeLimit,
145 + exceededDispatchModeLimit,
146 + narrowToCeiling,
147 + type RuntimeModeCeiling,
148 + runtimeModeCeilingRefusal,
149 + threadsStartingWork,
150 +} from "./DispatchModeLimit.ts";
151 import {
152 applyToProjection,
153 emptyProjection,
@@ -162,7 +171,7 @@ import * as RunExecutionService from "./RunExecutionService.ts";
171 import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts";
172 import { ProviderSwitchServiceV2 } from "./ProviderSwitchService.ts";
173 import { isAutomaticCompletionRun, queuedRunsInDeliveryOrder } from "./QueuedRunOrder.ts";
165 -import { RuntimePolicyV2 } from "./RuntimePolicy.ts";
174 +import { isRuntimePolicyAboveCeilingError, RuntimePolicyV2 } from "./RuntimePolicy.ts";
175 import {
176 endOrphanedNativeSubagent,
177 endRunlessRootTurns,
@@ -277,6 +286,32 @@ export class OrchestratorThreadAboveModeLimitError extends Schema.TaggedError<Or
286 }
287 }
288
289 +const isOrchestratorDispatchError = Schema.is(OrchestratorDispatchError);
290 +
291 +/** The ceiling refusal under however many dispatch errors wrapped it on the way out. */
292 +function runtimePolicyCeilingCause(error: unknown) {
293 + let current = error;
294 + while (isOrchestratorDispatchError(current)) current = current.cause;
295 + return isRuntimePolicyAboveCeilingError(current) ? current : undefined;
296 +}
297 +
298 +export class OrchestratorRuntimeModeAboveCeilingError extends Schema.TaggedError<OrchestratorRuntimeModeAboveCeilingError>()(
299 + "OrchestratorRuntimeModeAboveCeilingError",
300 + {
301 + commandId: CommandId,
302 + threadId: ThreadId,
303 + refused: Schema.Literals(["mode", "turn"]),
304 + runtimeMode: RuntimeMode,
305 + maxRuntimeMode: RuntimeMode,
306 + organization: Schema.String,
307 + },
308 +) {
309 + override get message(): string {
310 + const limit = managedRuntimeModeCeilingMessage(this.organization, this.maxRuntimeMode);
311 + return this.refused === "turn" ? `${limit} Switch this thread's mode to continue.` : limit;
312 + }
313 +}
314 +
315 export class OrchestratorCommandPreviouslyRejectedError extends Schema.TaggedError<OrchestratorCommandPreviouslyRejectedError>()(
316 "OrchestratorCommandPreviouslyRejectedError",
317 {
@@ -315,6 +350,7 @@ export const OrchestratorV2Error = Schema.Union([
350 OrchestratorCommandIdConflictError,
351 OrchestratorSubagentThreadReadOnlyError,
352 OrchestratorThreadAboveModeLimitError,
353 + OrchestratorRuntimeModeAboveCeilingError,
354 ]);
355 export type OrchestratorV2Error = typeof OrchestratorV2Error.Type;
356
@@ -1006,6 +1042,15 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
1042 const runtimePolicy = yield* RuntimePolicyV2;
1043 const threadForkService = yield* ThreadForkServiceV2;
1044 const threadDispatch = yield* ThreadCommandExecutor.ThreadCommandExecutor;
1045 + // Read once: the policy is fixed for the server's life, and dispatch takes it as an input.
1046 + const { managedPolicy } = serverSettings;
1047 + const runtimeModeCeiling: RuntimeModeCeiling | undefined =
1048 + managedPolicy?.limits?.maxRuntimeMode === undefined
1049 + ? undefined
1050 + : {
1051 + organization: managedPolicy.organization,
1052 + maxRuntimeMode: managedPolicy.limits.maxRuntimeMode,
1053 + };
1054
1055 /** The driver when this provider runs `/goal` natively, else undefined. */
1056 const goalDriverFor = Effect.fn("Orchestrator.goalDriverFor")(function* (
@@ -1573,6 +1618,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
1618 if (usageLimitHoldsQueue(projection, queuedRun.providerInstanceId)) {
1619 return;
1620 }
1621 + // Waits without a hold: lowering the thread's mode starts the queue again.
1622 + if (isRuntimeModeAbove(projection.thread.runtimeMode, runtimeModeCeiling?.maxRuntimeMode)) {
1623 + return;
1624 + }
1625 // Failed worktree creation would run queued work in the project checkout; wait for the user.
1626 const failedRun = latestExecutedRun(projection.runs);
1627 const failureClass =
@@ -4229,7 +4278,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
4278 readonly interactionMode: ProviderInteractionMode;
4279 },
4280 ) {
4232 - const limit = yield* DispatchModeLimit;
4281 + const limit = narrowToCeiling(yield* DispatchModeLimit, runtimeModeCeiling);
4282 const exceeded = limit === undefined ? undefined : exceededDispatchModeLimit(limit, modes);
4283 if (limit === undefined || exceeded === undefined) return;
4284 const refusal = {
@@ -4246,6 +4295,34 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
4295 },
4296 );
4297
4298 + const refuseAboveRuntimeModeCeiling = Effect.fn(
4299 + "orchestrationV2.dispatch.refuseAboveRuntimeModeCeiling",
4300 + )(function* (
4301 + command: OrchestrationV2ServerCommand,
4302 + events: ReadonlyArray<OrchestrationV2DomainEvent>,
4303 + ) {
4304 + if (runtimeModeCeiling === undefined) return;
4305 + const runtimeModes = new Map<ThreadId, RuntimeMode>();
4306 + for (const threadId of threadsStartingWork(events)) {
4307 + const thread = yield* projectionStore.getThread(threadId).pipe(
4308 + Effect.catchTags({ ProjectionStoreThreadNotFoundError: () => Effect.succeed(null) }),
4309 + Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause })),
4310 + );
4311 + if (thread !== null) runtimeModes.set(threadId, thread.runtimeMode);
4312 + }
4313 + const refusal = runtimeModeCeilingRefusal(
4314 + runtimeModeCeiling.maxRuntimeMode,
4315 + events,
4316 + runtimeModes,
4317 + );
4318 + if (refusal === undefined) return;
4319 + return yield* new OrchestratorRuntimeModeAboveCeilingError({
4320 + commandId: command.commandId,
4321 + ...refusal,
4322 + ...runtimeModeCeiling,
4323 + });
4324 + });
4325 +
4326 const dispatchThreadFork = Effect.fn("orchestrationV2.dispatch.threadFork")(function* (
4327 command: Extract<OrchestrationV2Command, { readonly type: "thread.fork" }>,
4328 events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
@@ -13329,6 +13406,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
13406 }
13407
13408 const plan = yield* dispatchOnce(command, sideChatIds).pipe(
13409 + Effect.tap((planned) => refuseAboveRuntimeModeCeiling(command, planned.events)),
13410 Effect.filterOrFail(
13411 (planned) =>
13412 planned.events.length > 0 ||
@@ -13348,7 +13426,26 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
13426 ),
13427 Effect.catch((cause) =>
13428 Effect.gen(function* () {
13351 - if (cause._tag === "OrchestratorThreadAboveModeLimitError") return yield* cause;
13429 + // Refusals depend on modes the user can change; a recorded rejection would block the retry.
13430 + if (
13431 + cause._tag === "OrchestratorThreadAboveModeLimitError" ||
13432 + cause._tag === "OrchestratorRuntimeModeAboveCeilingError"
13433 + ) {
13434 + return yield* cause;
13435 + }
13436 + // Resolving a turn's policy refuses the same way, from inside the decision.
13437 + const ceiling = runtimePolicyCeilingCause(cause);
13438 + if (ceiling !== undefined) {
13439 + const { threadId, runtimeMode, maxRuntimeMode, organization } = ceiling;
13440 + return yield* new OrchestratorRuntimeModeAboveCeilingError({
13441 + commandId: command.commandId,
13442 + threadId,
13443 + refused: "turn",
13444 + runtimeMode,
13445 + maxRuntimeMode,
13446 + organization,
13447 + });
13448 + }
13449 const rejectedAt = yield* DateTime.now;
13450 const receipt = yield* eventSink
13451 .commitRejectedCommand({
@@ -13449,7 +13546,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
13546 detail: committed.receipt.error ?? "Previously rejected.",
13547 });
13548 }
13452 - if (command.type === "queue.resume" || command.type === "queued-run.start") {
13549 + if (
13550 + command.type === "queue.resume" ||
13551 + command.type === "queued-run.start" ||
13552 + (command.type === "thread.runtime-mode.set" && runtimeModeCeiling !== undefined)
13553 + ) {
13554 yield* mapDispatchError(command)(
13555 startNextQueuedRun(
13556 command.threadId,
apps/server/src/orchestration-v2/ProviderTurnStartService.ts
+23 -9
@@ -690,15 +690,29 @@ export const layer: Layer.Layer<
690 const { isCurrentAttemptInStatus } = runControls;
691
692 // A side chat shares its parent's worktree; the turn that gets its context asks before acting.
693 - const resolvedRuntimePolicy = yield* runtimePolicy.resolve({
694 - thread:
695 - projection.thread.lineage.sideChat === true &&
696 - (sideChatHandoff !== undefined ||
697 - !projection.runs.some((previous) => previous.ordinal < run.ordinal))
698 - ? { ...projection.thread, runtimeMode: "approval-required" }
699 - : projection.thread,
700 - modelSelection: run.modelSelection,
701 - });
693 + const resolvedPolicy = yield* runtimePolicy
694 + .resolve({
695 + thread:
696 + projection.thread.lineage.sideChat === true &&
697 + (sideChatHandoff !== undefined ||
698 + !projection.runs.some((previous) => previous.ordinal < run.ordinal))
699 + ? { ...projection.thread, runtimeMode: "approval-required" }
700 + : projection.thread,
701 + modelSelection: run.modelSelection,
702 + })
703 + .pipe(Effect.result);
704 + if (resolvedPolicy._tag === "Failure") {
705 + const error = resolvedPolicy.failure;
706 + if (error._tag !== "RuntimePolicyAboveCeilingError") return yield* error;
707 + yield* settleStartFailure({
708 + signal: "runtime-mode-above-ceiling",
709 + title: "Thread mode is above the policy limit",
710 + error,
711 + message: error.message,
712 + });
713 + return;
714 + }
715 + const resolvedRuntimePolicy = resolvedPolicy.success;
716 if (!(yield* isCurrentAttemptInStatus("starting"))) return;
717 const existingSessionProjection = projection.providerSessions.find(
718 (candidate) => candidate.id === providerSessionId,
apps/server/src/orchestration-v2/RestartContinuation.ts
+7 -1
@@ -328,7 +328,8 @@ export const continueRestartedRun = Effect.fn("RestartContinuation.continueResta
328 restartContinuationOfRunId: input.sourceRunId,
329 })
330 .pipe(
331 - // Disabled instances cannot resume; still run success cleanup so delegated children recover without futile retries.
331 + // Disabled instances, and threads above a policy ceiling, cannot resume; still run success
332 + // cleanup so delegated children recover without futile retries.
333 Effect.catchTags({
334 ThreadManagementProviderInstanceDisabledError: (error) =>
335 Effect.logInfo("orchestration-v2.restart-continuation.instance-disabled", {
@@ -337,6 +338,11 @@ export const continueRestartedRun = Effect.fn("RestartContinuation.continueResta
338 projectId: error.projectId,
339 instanceId: error.instanceId,
340 }),
341 + OrchestratorRuntimeModeAboveCeilingError: () =>
342 + Effect.logInfo("orchestration-v2.restart-continuation.above-ceiling", {
343 + threadId: input.threadId,
344 + sourceRunId: input.sourceRunId,
345 + }),
346 }),
347 );
348 },
apps/server/src/orchestration-v2/RuntimePolicy.test.ts
+68 -32
@@ -1,5 +1,6 @@
1 import { assert, it } from "@effect/vitest";
2 import {
3 + type ManagedPolicySummary,
4 type ModelSelection,
5 type OrchestrationV2AppThread,
6 ProjectId,
@@ -14,6 +15,7 @@ import * as Layer from "effect/Layer";
15 import * as Stream from "effect/Stream";
16
17 import type { ProviderInstance } from "@t3tools/provider-core/server/driver";
18 +import * as ServerSettings from "../serverSettings.ts";
19 import * as ProviderInstanceRegistry from "../provider/ProviderInstanceRegistry.ts";
20 import * as ProjectStore from "./ProjectStore.ts";
21 import * as RuntimePolicy from "./RuntimePolicy.ts";
@@ -73,38 +75,42 @@ const providerInstanceFor = (instanceId: ProviderInstanceId) =>
75 },
76 }) as ProviderInstance;
77
76 -const layerTest = RuntimePolicy.layerFromProjectStore.pipe(
77 - Layer.provide(
78 - Layer.succeed(ProviderInstanceRegistry.ProviderInstanceRegistry, {
79 - getInstance: (instanceId) => Effect.succeed(providerInstanceFor(instanceId)),
80 - listInstances: Effect.succeed([]),
81 - listUnavailable: Effect.succeed([]),
82 - streamChanges: Stream.empty,
83 - subscribeChanges: Effect.never,
84 - }),
85 - ),
86 - Layer.provide(
87 - Layer.mock(ProjectStore.ProjectStoreV2)({
88 - get: () =>
89 - Effect.succeedSome({
90 - projectId,
91 - title: "Project",
92 - workspaceRoot: "/project-root",
93 - defaultModelSelection: null,
94 - defaultThreadEnvMode: null,
95 - autoPull: false,
96 - faviconPath: null,
97 - projectIcon: null,
98 - scripts: [],
99 - pinnedAt: null,
100 - archivedAt: null,
101 - createdAt: "2026-06-21T00:00:00.000Z",
102 - updatedAt: "2026-06-21T00:00:00.000Z",
103 - deletedAt: null,
104 - }),
105 - }),
106 - ),
107 -);
78 +const layerWithPolicy = (policy?: ManagedPolicySummary) =>
79 + RuntimePolicy.layerFromProjectStore.pipe(
80 + Layer.provide(ServerSettings.layerTest({}, policy)),
81 + Layer.provide(
82 + Layer.succeed(ProviderInstanceRegistry.ProviderInstanceRegistry, {
83 + getInstance: (instanceId) => Effect.succeed(providerInstanceFor(instanceId)),
84 + listInstances: Effect.succeed([]),
85 + listUnavailable: Effect.succeed([]),
86 + streamChanges: Stream.empty,
87 + subscribeChanges: Effect.never,
88 + }),
89 + ),
90 + Layer.provide(
91 + Layer.mock(ProjectStore.ProjectStoreV2)({
92 + get: () =>
93 + Effect.succeedSome({
94 + projectId,
95 + title: "Project",
96 + workspaceRoot: "/project-root",
97 + defaultModelSelection: null,
98 + defaultThreadEnvMode: null,
99 + autoPull: false,
100 + faviconPath: null,
101 + projectIcon: null,
102 + scripts: [],
103 + pinnedAt: null,
104 + archivedAt: null,
105 + createdAt: "2026-06-21T00:00:00.000Z",
106 + updatedAt: "2026-06-21T00:00:00.000Z",
107 + deletedAt: null,
108 + }),
109 + }),
110 + ),
111 + );
112 +
113 +const layerTest = layerWithPolicy();
114
115 it.layer(layerTest)("RuntimePolicyV2", (it) => {
116 it.effect("runs a mode the provider does not offer in Supervised", () =>
@@ -126,3 +132,33 @@ it.layer(layerTest)("RuntimePolicyV2", (it) => {
132 }),
133 );
134 });
135 +
136 +it.layer(
137 + layerWithPolicy({
138 + organization: "Example Corp",
139 + lockedSettings: [],
140 + limits: { maxRuntimeMode: "auto-accept-edits" },
141 + }),
142 +)("RuntimePolicyV2 under a runtime mode ceiling", (it) => {
143 + it.effect("refuses to start a turn above the ceiling, such as one resumed after a restart", () =>
144 + Effect.gen(function* () {
145 + const policy = yield* RuntimePolicy.RuntimePolicyV2;
146 + const now = yield* DateTime.now;
147 + const resolve = (runtimeMode: RuntimeMode) =>
148 + policy.resolve({
149 + thread: makeThread({ now, worktreePath: "/work", runtimeMode }),
150 + modelSelection,
151 + });
152 +
153 + const refused = yield* resolve("full-access").pipe(Effect.flip);
154 + assert.equal(refused._tag, "RuntimePolicyAboveCeilingError");
155 + assert.equal(
156 + refused.message,
157 + "Example Corp limits threads to Auto-accept edits. Switch this thread's mode to continue.",
158 + );
159 + const allowed = yield* resolve("auto-accept-edits");
160 + assert.equal(allowed.runtimeMode, "auto-accept-edits");
161 + assert.equal(allowed.maxRuntimeMode, "auto-accept-edits");
162 + }),
163 + );
164 +});
apps/server/src/orchestration-v2/RuntimePolicy.ts
+76 -3
@@ -1,9 +1,12 @@
1 import {
2 + isRuntimeModeAbove,
3 + managedRuntimeModeCeilingMessage,
4 ModelSelection,
5 OrchestrationV2AppThread,
6 ProjectId,
7 ProviderInstanceId,
6 - type RuntimeMode,
8 + RuntimeMode,
9 + ThreadId,
10 } from "@t3tools/contracts";
11 import * as Context from "effect/Context";
12 import * as Effect from "effect/Effect";
@@ -13,6 +16,7 @@ import * as Schema from "effect/Schema";
16
17 import * as ProviderInstanceRegistry from "../provider/ProviderInstanceRegistry.ts";
18 import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
19 +import * as ServerSettings from "../serverSettings.ts";
20 import * as ProjectStore from "./ProjectStore.ts";
21
22 export class RuntimePolicyResolveError extends Schema.TaggedError<RuntimePolicyResolveError>()(
@@ -28,7 +32,31 @@ export class RuntimePolicyResolveError extends Schema.TaggedError<RuntimePolicyR
32 }
33 }
34
31 -export const RuntimePolicyV2Error = Schema.Union([RuntimePolicyResolveError]);
35 +/**
36 + * A turn would start in a mode above the policy's ceiling. The orchestrator refuses those when
37 + * they are dispatched; this catches the ones it never saw, such as a run resumed after a restart
38 + * on a thread whose mode predates the policy.
39 + */
40 +export class RuntimePolicyAboveCeilingError extends Schema.TaggedError<RuntimePolicyAboveCeilingError>()(
41 + "RuntimePolicyAboveCeilingError",
42 + {
43 + threadId: ThreadId,
44 + runtimeMode: RuntimeMode,
45 + maxRuntimeMode: RuntimeMode,
46 + organization: Schema.String,
47 + },
48 +) {
49 + override get message(): string {
50 + return `${managedRuntimeModeCeilingMessage(this.organization, this.maxRuntimeMode)} Switch this thread's mode to continue.`;
51 + }
52 +}
53 +
54 +export const isRuntimePolicyAboveCeilingError = Schema.is(RuntimePolicyAboveCeilingError);
55 +
56 +export const RuntimePolicyV2Error = Schema.Union([
57 + RuntimePolicyResolveError,
58 + RuntimePolicyAboveCeilingError,
59 +]);
60 export type RuntimePolicyV2Error = typeof RuntimePolicyV2Error.Type;
61
62 export const RuntimePolicyV2Override = Schema.Struct({
@@ -71,17 +99,61 @@ function providerRuntimeMode(
99 : "approval-required";
100 }
101
102 +const refuseAboveCeiling = (
103 + managedPolicy: ServerSettings.ServerSettingsService["Service"]["managedPolicy"],
104 + thread: OrchestrationV2AppThread,
105 +) => {
106 + const maxRuntimeMode = managedPolicy?.limits?.maxRuntimeMode;
107 + return managedPolicy !== undefined &&
108 + maxRuntimeMode !== undefined &&
109 + isRuntimeModeAbove(thread.runtimeMode, maxRuntimeMode)
110 + ? Effect.fail(
111 + new RuntimePolicyAboveCeilingError({
112 + threadId: thread.id,
113 + runtimeMode: thread.runtimeMode,
114 + maxRuntimeMode,
115 + organization: managedPolicy.organization,
116 + }),
117 + )
118 + : Effect.void;
119 +};
120 +
121 +/** Lays the policy's ceiling over another runtime policy, as `layerFromProjectStore` does. */
122 +export const layerEnforcingCeiling: Layer.Layer<
123 + RuntimePolicyV2,
124 + never,
125 + RuntimePolicyV2 | ServerSettings.ServerSettingsService
126 +> = Layer.effect(
127 + RuntimePolicyV2,
128 + Effect.gen(function* () {
129 + const base = yield* RuntimePolicyV2;
130 + const { managedPolicy } = yield* ServerSettings.ServerSettingsService;
131 + return RuntimePolicyV2.of({
132 + resolve: Effect.fn("RuntimePolicyV2.resolveWithinCeiling")(function* (input) {
133 + yield* refuseAboveCeiling(managedPolicy, input.thread);
134 + return yield* base.resolve(input);
135 + }),
136 + });
137 + }),
138 +);
139 +
140 export const layerFromProjectStore: Layer.Layer<
141 RuntimePolicyV2,
142 never,
77 - ProjectStore.ProjectStoreV2 | ProviderInstanceRegistry.ProviderInstanceRegistry
143 + | ProjectStore.ProjectStoreV2
144 + | ProviderInstanceRegistry.ProviderInstanceRegistry
145 + | ServerSettings.ServerSettingsService
146 > = Layer.effect(
147 RuntimePolicyV2,
148 Effect.gen(function* () {
149 const projects = yield* ProjectStore.ProjectStoreV2;
150 const providerInstances = yield* ProviderInstanceRegistry.ProviderInstanceRegistry;
151 + // The same ceiling the orchestrator enforces, fixed for the server's life.
152 + const { managedPolicy } = yield* ServerSettings.ServerSettingsService;
153 + const maxRuntimeMode = managedPolicy?.limits?.maxRuntimeMode;
154 return RuntimePolicyV2.of({
155 resolve: Effect.fn("RuntimePolicyV2.resolve")(function* (input) {
156 + yield* refuseAboveCeiling(managedPolicy, input.thread);
157 const instance = yield* providerInstances.getInstance(input.modelSelection.instanceId);
158 const supportedRuntimeModes =
159 instance === undefined
@@ -116,6 +188,7 @@ export const layerFromProjectStore: Layer.Layer<
188 runtimeMode: providerRuntimeMode(input.thread.runtimeMode, supportedRuntimeModes),
189 interactionMode: input.thread.interactionMode,
190 cwd,
191 + ...(maxRuntimeMode === undefined ? {} : { maxRuntimeMode }),
192 });
193 }),
194 });
apps/server/src/orchestration-v2/ThreadLaunchService.test.ts
+5
@@ -50,6 +50,7 @@ import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts";
50 import * as ProviderRegistryMock from "../provider/testUtils/providerRegistryMock.ts";
51 import * as ServerSettings from "../serverSettings.ts";
52 import * as ScheduledTasks from "../scheduledTasks/ScheduledTaskService.ts";
53 +import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
54 import * as SecretRequests from "../secrets/SecretRequests.ts";
55 import * as TextGeneration from "../textGeneration/TextGeneration.ts";
56 import { ClaudeProviderCapabilitiesV2 } from "./Adapters/ClaudeAdapterV2.ts";
@@ -327,6 +328,7 @@ it.effect.each(
328 NodeCrypto.layer,
329 Scheduler.layer,
330 Layer.mock(SecretRequests.SecretRequests)({}),
331 + ManagedPolicy.layerTest(),
332 Layer.mock(RemoteDelegation.RemoteDelegation)({}),
333 ),
334 ),
@@ -393,6 +395,7 @@ it.effect(
395 NodeCrypto.layer,
396 Scheduler.layer,
397 Layer.mock(SecretRequests.SecretRequests)({}),
398 + ManagedPolicy.layerTest(),
399 ),
400 ),
401 );
@@ -430,6 +433,7 @@ it.effect("runs a thread-bound automation on the provider the thread uses now",
433 NodeCrypto.layer,
434 Scheduler.layer,
435 Layer.mock(SecretRequests.SecretRequests)({}),
436 + ManagedPolicy.layerTest(),
437 ),
438 ),
439 );
@@ -893,6 +897,7 @@ function scratchHarness() {
897 NodeCrypto.layer,
898 Scheduler.layer,
899 Layer.mock(SecretRequests.SecretRequests)({}),
900 + ManagedPolicy.layerTest(),
901 ),
902 ),
903 );
apps/server/src/orchestration-v2/ThreadMessageIntake.ts
+1
@@ -24,6 +24,7 @@ function dispatchWasNotAccepted(
24 case "OrchestratorCommandIdConflictError":
25 case "OrchestratorSubagentThreadReadOnlyError":
26 case "OrchestratorThreadAboveModeLimitError":
27 + case "OrchestratorRuntimeModeAboveCeilingError":
28 case "ThreadManagementProviderInstanceDisabledError":
29 return true;
30 default:
apps/server/src/orchestration-v2/runtimeLayer.test.ts
+2
@@ -79,6 +79,7 @@ import * as ThreadManagementService from "./ThreadManagementService.ts";
79 import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts";
80 import * as ScratchThreadPromotion from "../project/ScratchThreadPromotion.ts";
81 import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
82 +import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
83 import * as Scheduler from "../scheduling/Scheduler.ts";
84 import * as SecretRequests from "../secrets/SecretRequests.ts";
85 import * as PreviewManager from "../preview/Manager.ts";
@@ -309,6 +310,7 @@ const layerLegacyImportTest = RuntimeLayer.layer.pipe(
310 const layerScheduledTasksTest = ScheduledTaskService.layer.pipe(
311 Layer.provide(
312 Layer.mergeAll(
313 + ManagedPolicy.layerTest(),
314 Layer.mock(ThreadLaunchService.ThreadLaunchService)({}),
315 Layer.mock(ThreadManagementService.ThreadManagementService)({}),
316 Layer.mock(SecretRequests.SecretRequests)({}),
apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts
+26 -8
@@ -1,7 +1,11 @@
1 import * as OtelEnvironment from "@t3tools/shared/otelEnvironment";
2 import { DEFAULT_SIGNAL_EXPORT } from "@t3tools/shared/observability";
3 import * as NodeServices from "@effect/platform-node/NodeServices";
4 -import type { ProviderDriverKind, ProviderReplayTranscript } from "@t3tools/contracts";
4 +import type {
5 + ManagedPolicyDocument,
6 + ProviderDriverKind,
7 + ProviderReplayTranscript,
8 +} from "@t3tools/contracts";
9 import * as Effect from "effect/Effect";
10 import * as FileSystem from "effect/FileSystem";
11 import * as Layer from "effect/Layer";
@@ -15,6 +19,7 @@ import * as CheckpointStore from "../../checkpointing/CheckpointStore.ts";
19 import * as ServerConfig from "../../config.ts";
20 import * as SqlitePersistence from "../../persistence/Sqlite.ts";
21 import * as ServerSettings from "../../serverSettings.ts";
22 +import * as ManagedPolicy from "../../policy/ManagedPolicy.ts";
23 import * as ThreadManagementService from "../ThreadManagementService.ts";
24 import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
25 import * as McpSessionRegistryTestkit from "../../mcp/McpSessionRegistry.testkit.ts";
@@ -197,6 +202,7 @@ export function runOrchestratorV2ProviderReplayScenario<
202 readonly runContinuationWorker?: boolean;
203 readonly recoverOnStartup?: boolean;
204 readonly continueThreadsAfterServerUpdate?: boolean;
205 + readonly managedPolicy?: ManagedPolicyDocument;
206 } = {},
207 ): Effect.Effect<
208 OrchestratorV2ScenarioResult,
@@ -239,6 +245,7 @@ export function layerProviderReplay<Transcript extends ProviderReplayTranscript,
245 readonly runContinuationWorker?: boolean;
246 readonly recoverOnStartup?: boolean;
247 readonly continueThreadsAfterServerUpdate?: boolean;
248 + readonly managedPolicy?: ManagedPolicyDocument;
249 readonly replayGate?: ProviderReplayGate;
250 } = {},
251 ): Layer.Layer<
@@ -272,6 +279,7 @@ export function layerWithRegistry<Error>(
279 readonly runContinuationWorker?: boolean;
280 readonly recoverOnStartup?: boolean;
281 readonly continueThreadsAfterServerUpdate?: boolean;
282 + readonly managedPolicy?: ManagedPolicyDocument;
283 } = {},
284 ): Layer.Layer<
285 | Orchestrator.OrchestratorV2
@@ -285,7 +293,7 @@ export function layerWithRegistry<Error>(
293 ServerConfig.ServerConfig,
294 makeReplayServerConfig(scenario.name).pipe(Effect.orDie),
295 ).pipe(Layer.provide(NodeServices.layer));
288 - const layerRuntime =
296 + const layerRuntimeBase =
297 scenario.runtimePolicyOverride === undefined
298 ? RuntimePolicy.layer
299 : RuntimePolicy.layerWithOverride(scenario.runtimePolicyOverride).pipe(
@@ -298,12 +306,19 @@ export function layerWithRegistry<Error>(
306 const layerProvidedRegistry = registryLayer.pipe(
307 Layer.provide(Layer.merge(layerContinuationRequests, McpProviderSessions.layer)),
308 );
301 - const layerServerSettings = ServerSettings.layerTest({
302 - responseStreamingMode: "turn",
303 - ...(options.continueThreadsAfterServerUpdate === undefined
304 - ? {}
305 - : { continueThreadsAfterServerUpdate: options.continueThreadsAfterServerUpdate }),
306 - }).pipe(Layer.orDie);
309 + const layerServerSettings = Layer.unwrap(
310 + Effect.map(ManagedPolicy.fromDocument("/test/policy.json", options.managedPolicy), (policy) =>
311 + ServerSettings.layerTest(
312 + {
313 + responseStreamingMode: "turn",
314 + ...(options.continueThreadsAfterServerUpdate === undefined
315 + ? {}
316 + : { continueThreadsAfterServerUpdate: options.continueThreadsAfterServerUpdate }),
317 + },
318 + policy.summary,
319 + ),
320 + ),
321 + ).pipe(Layer.orDie);
322 const layerStores = Layer.mergeAll(
323 EventStore.layer,
324 ProjectionStore.layer,
@@ -315,6 +330,9 @@ export function layerWithRegistry<Error>(
330 const layerEventSinkProvided = EventSink.layerFromStores.pipe(
331 Layer.provide(Layer.mergeAll(layerStores, layerDatabase)),
332 );
333 + const layerRuntime = RuntimePolicy.layerEnforcingCeiling.pipe(
334 + Layer.provide(Layer.merge(layerRuntimeBase, layerServerSettings)),
335 + );
336 const layerCommandReceiptStoreProvided = CommandReceiptStore.layer.pipe(
337 Layer.provide(layerDatabase),
338 );
apps/server/src/peer/PeerLinks.testkit.ts
+2
@@ -30,6 +30,7 @@ import * as Sqlite from "../persistence/Sqlite.ts";
30 import * as PeerLinks from "./PeerLinks.ts";
31 import * as ServerSettings from "../serverSettings.ts";
32 import * as PeerMcpClient from "./PeerMcpClient.ts";
33 +import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
34
35 class PeerTestApi extends HttpApi.make("environment")
36 .add(EnvironmentHttpApi.groups.metadata)
@@ -71,6 +72,7 @@ export const servePeer = <E, R>(
72 getDescriptor: Ref.get(descriptor),
73 });
74 const authContext = yield* EnvironmentAuth.layer.pipe(
75 + Layer.provide(ManagedPolicy.layerTest()),
76 Layer.provideMerge(ServerSettings.layerTest({ linkedEnvironmentsEnabled: true })),
77 Layer.provide(Sqlite.layerMemory),
78 Layer.provideMerge(ServerSecretStore.layer),
apps/server/src/policy/ManagedPolicy.test.ts new
+446
@@ -0,0 +1,446 @@
1 +import * as NodeServices from "@effect/platform-node/NodeServices";
2 +import { assert, it } from "@effect/vitest";
3 +import * as Effect from "effect/Effect";
4 +import * as FileSystem from "effect/FileSystem";
5 +import * as Path from "effect/Path";
6 +
7 +import {
8 + DEFAULT_SERVER_SETTINGS,
9 + ProviderDriverKind,
10 + ProviderInstanceId,
11 +} from "@t3tools/contracts";
12 +import * as HostProcess from "@t3tools/shared/HostProcess";
13 +
14 +import * as ManagedPolicy from "./ManagedPolicy.ts";
15 +import { disallowedDriverReason, providerHostEnvironment } from "./managedProviders.ts";
16 +
17 +it.layer(NodeServices.layer)("ManagedPolicy.load", (it) => {
18 + const loadFrom = (contents: string | undefined) =>
19 + Effect.gen(function* () {
20 + const fs = yield* FileSystem.FileSystem;
21 + const path = yield* Path.Path;
22 + const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-managed-policy-" });
23 + const file = path.join(dir, "policy.json");
24 + if (contents !== undefined) yield* fs.writeFileString(file, contents);
25 + return yield* ManagedPolicy.load(file);
26 + }).pipe(Effect.scoped);
27 +
28 + it.effect("means no policy when the file is missing", () =>
29 + Effect.gen(function* () {
30 + const policy = yield* loadFrom(undefined);
31 + assert.isUndefined(policy.summary);
32 + }),
33 + );
34 +
35 + it.effect("summarizes locked settings for clients", () =>
36 + Effect.gen(function* () {
37 + const policy = yield* loadFrom(
38 + JSON.stringify({
39 + schemaVersion: 1,
40 + organization: "Example Corp",
41 + supportUrl: "https://it.example/t3",
42 + settings: {
43 + "storageCleanup.logsAfterDays": { value: 30, locked: true },
44 + defaultRuntimeMode: { value: "approval-required", locked: false },
45 + },
46 + }),
47 + );
48 + assert.deepEqual(policy.summary, {
49 + organization: "Example Corp",
50 + supportUrl: "https://it.example/t3",
51 + lockedSettings: ["storageCleanup.logsAfterDays"],
52 + });
53 + }),
54 + );
55 +
56 + it.effect("tells clients which capabilities the policy switches off", () =>
57 + Effect.gen(function* () {
58 + const policy = yield* loadFrom(
59 + JSON.stringify({
60 + schemaVersion: 1,
61 + organization: "Example Corp",
62 + limits: { webhookTasks: false, telemetry: true },
63 + }),
64 + );
65 + assert.deepEqual(policy.summary?.limits, { webhookTasks: false, telemetry: true });
66 + assert.equal(ManagedPolicy.deniedBy(policy, "webhookTasks"), "Example Corp");
67 + assert.isUndefined(ManagedPolicy.deniedBy(policy, "telemetry"));
68 + }),
69 + );
70 +
71 + it.effect("refuses files it cannot fully enforce", () =>
72 + Effect.gen(function* () {
73 + const base = { schemaVersion: 1, organization: "Example Corp" };
74 + const reasons = yield* Effect.forEach(
75 + [
76 + "{ not json",
77 + // An unknown key may be a restriction from a newer release.
78 + JSON.stringify({ ...base, limits: { connect: false, futureLimit: true } }),
79 + JSON.stringify({ ...base, settings: { notASetting: { value: 1, locked: true } } }),
80 + JSON.stringify({
81 + ...base,
82 + settings: { "storageCleanup.logsAfterDayz": { value: 30, locked: true } },
83 + }),
84 + JSON.stringify({
85 + ...base,
86 + settings: { defaultRuntimeMode: { value: "yolo", locked: true } },
87 + }),
88 + JSON.stringify({
89 + ...base,
90 + settings: { projectSettingsOverrides: { value: {}, locked: true } },
91 + }),
92 + // The user could never remove a provider instance a default keeps adding back.
93 + JSON.stringify({
94 + ...base,
95 + settings: {
96 + "providerInstances.codex_work": {
97 + value: { driver: "codex", enabled: true },
98 + locked: false,
99 + },
100 + },
101 + }),
102 + JSON.stringify({
103 + ...base,
104 + settings: {
105 + providerInstances: { value: { codex_work: { driver: "codex" } }, locked: false },
106 + },
107 + }),
108 + // A user's stored null would leave the lock building half a model selection.
109 + JSON.stringify({
110 + ...base,
111 + settings: { "defaultModelSelection.model": { value: "gpt-5.4", locked: true } },
112 + }),
113 + // The server derives it from idleCompaction on every write.
114 + JSON.stringify({
115 + ...base,
116 + settings: { compactIdleThreads: { value: false, locked: true } },
117 + }),
118 + // It would look locked while worktreeCleanup, which overrides it, stays the user's.
119 + JSON.stringify({
120 + ...base,
121 + settings: { "storageCleanup.worktreeAfterDays": { value: 7, locked: true } },
122 + }),
123 + // An instance's own variables, home paths, and setup mode would override the lock.
124 + JSON.stringify({
125 + ...base,
126 + settings: {
127 + "providerInstances.codex.driver": { value: "codex", locked: true },
128 + "providerInstances.codex.config.launchArgs": {
129 + value: "-c model_provider=corp",
130 + locked: true,
131 + },
132 + },
133 + }),
134 + // The server would move it into the user's secret store, past the policy's removal.
135 + JSON.stringify({
136 + ...base,
137 + settings: {
138 + providerInstances: {
139 + value: { gemini: { driver: "antigravity", config: { apiKey: "corp-key" } } },
140 + locked: true,
141 + },
142 + },
143 + }),
144 + ],
145 + (contents) =>
146 + loadFrom(contents).pipe(
147 + Effect.flip,
148 + Effect.map((error) => error.reason),
149 + ),
150 + );
151 + assert.lengthOf(reasons, 13);
152 + assert.include(reasons[3], "storageCleanup.logsAfterDayz");
153 + assert.include(reasons[6], "adds entries users could not remove");
154 + assert.include(reasons[7], "adds entries users could not remove");
155 + assert.include(reasons[8], 'manage "defaultModelSelection" as a whole');
156 + assert.include(reasons[9], 'manage "idleCompaction" instead');
157 + assert.include(reasons[10], 'lock "worktreeCleanup" too');
158 + assert.include(reasons[11], 'lock "providerInstances.codex" as a whole');
159 + assert.include(reasons[12], "holds a credential");
160 + }),
161 + );
162 +
163 + it.effect("tells clients the runtime mode ceiling", () =>
164 + Effect.gen(function* () {
165 + const policy = yield* loadFrom(
166 + JSON.stringify({
167 + schemaVersion: 1,
168 + organization: "Example Corp",
169 + settings: { defaultRuntimeMode: { value: "approval-required", locked: true } },
170 + limits: { maxRuntimeMode: "auto-accept-edits" },
171 + }),
172 + );
173 + const { providers, ...limits } = policy.summary?.limits ?? {};
174 + assert.deepEqual(limits, { maxRuntimeMode: "auto-accept-edits" });
175 + // Under a ceiling, each driver's launch configuration is the administrator's.
176 + assert.deepEqual(providers?.lockedInstanceFields?.[ProviderDriverKind.make("claudeAgent")], [
177 + "config.binaryPath",
178 + "config.launchArgs",
179 + "config.homePath",
180 + "environment",
181 + ]);
182 + assert.deepEqual(providers?.lockedInstanceFields?.[ProviderDriverKind.make("acpRegistry")], [
183 + "config.commandPath",
184 + "config.commandArgs",
185 + "environment",
186 + ]);
187 + // The host variable that replaces Codex's launch arguments is ignored too.
188 + const host = { PATH: "/usr/bin", T3CODE_CODEX_LAUNCH_ARGS: "-c mcp_servers.x.command=sh" };
189 + assert.deepEqual(providerHostEnvironment(policy.summary, host), { PATH: "/usr/bin" });
190 + assert.strictEqual(providerHostEnvironment(undefined, host), host);
191 + }),
192 + );
193 +
194 + it.effect(
195 + "locks a variable in every spelling on Windows only, and drops a Codex launch override",
196 + () =>
197 + Effect.gen(function* () {
198 + const codex = ProviderDriverKind.make("codex");
199 + const variable = (name: string, value: string) => ({ name, value, sensitive: false });
200 + const settings = {
201 + ...DEFAULT_SERVER_SETTINGS,
202 + providerInstances: {
203 + codex: {
204 + driver: codex,
205 + environment: [
206 + variable("HTTPS_PROXY", "http://mine"),
207 + variable("T3CODE_CODEX_LAUNCH_ARGS", "--dangerously-bypass-approvals-and-sandbox"),
208 + ],
209 + },
210 + },
211 + };
212 + const policyOn = (platform: NodeJS.Platform) =>
213 + ManagedPolicy.fromDocument("/test/policy.json", {
214 + schemaVersion: 1,
215 + organization: "Example Corp",
216 + limits: {
217 + providers: {
218 + instances: {
219 + [codex]: {
220 + locked: true,
221 + launchArgs: "--strict-config",
222 + environment: [{ name: "Https_Proxy", value: "http://gateway" }],
223 + },
224 + },
225 + },
226 + },
227 + }).pipe(Effect.provideService(HostProcess.Platform, platform));
228 + const environmentOn = (platform: NodeJS.Platform) =>
229 + Effect.map(
230 + policyOn(platform),
231 + (policy) =>
232 + policy.providers.applyLimits(settings).providerInstances[
233 + ProviderInstanceId.make("codex")
234 + ]?.environment,
235 + );
236 + assert.deepEqual(yield* environmentOn("win32"), [
237 + variable("Https_Proxy", "http://gateway"),
238 + ]);
239 + assert.deepEqual(yield* environmentOn("linux"), [
240 + variable("HTTPS_PROXY", "http://mine"),
241 + variable("Https_Proxy", "http://gateway"),
242 + ]);
243 + // Saving what the client was shown keeps the override it never saw.
244 + const linux = yield* policyOn("linux");
245 + const shown = linux.providers.applyLimits(settings);
246 + const codexId = ProviderInstanceId.make("codex");
247 + const saved = linux.providers.vetWrite(settings, {
248 + ...shown,
249 + providerInstances: {
250 + ...shown.providerInstances,
251 + [codexId]: { ...shown.providerInstances[codexId]!, displayName: "Codex (work)" },
252 + },
253 + });
254 + assert.equal(saved._tag, "Allowed");
255 + const savedEnvironment =
256 + saved._tag === "Allowed"
257 + ? (saved.settings.providerInstances[codexId]?.environment ?? [])
258 + : [];
259 + assert.isTrue(savedEnvironment.some((entry) => entry.name === "T3CODE_CODEX_LAUNCH_ARGS"));
260 + // A home path setting would rewrite a locked home variable at launch, so the lock owns it.
261 + const claude = ProviderDriverKind.make("claudeAgent");
262 + const homeLocked = yield* ManagedPolicy.fromDocument("/test/policy.json", {
263 + schemaVersion: 1,
264 + organization: "Example Corp",
265 + limits: {
266 + providers: {
267 + instances: {
268 + [claude]: {
269 + locked: true,
270 + environment: [{ name: "CLAUDE_CONFIG_DIR", value: "/opt/claude-home" }],
271 + },
272 + },
273 + },
274 + },
275 + });
276 + const claudeId = ProviderInstanceId.make("claudeAgent");
277 + const claudeConfig = homeLocked.providers.applyLimits({
278 + ...DEFAULT_SERVER_SETTINGS,
279 + providerInstances: {
280 + [claudeId]: { driver: claude, config: { homePath: "/home/me/.other-claude" } },
281 + },
282 + }).providerInstances[claudeId]?.config;
283 + assert.deepEqual(claudeConfig, {});
284 + assert.include(
285 + homeLocked.summary?.limits?.providers?.lockedInstanceFields?.[claude] ?? [],
286 + "config.homePath",
287 + );
288 + // Codex has a second home setting, which a locked CODEX_HOME owns too.
289 + const codexHome = yield* ManagedPolicy.fromDocument("/test/policy.json", {
290 + schemaVersion: 1,
291 + organization: "Example Corp",
292 + limits: {
293 + providers: {
294 + instances: {
295 + [codex]: {
296 + locked: true,
297 + environment: [{ name: "CODEX_HOME", value: "/opt/codex-home" }],
298 + },
299 + },
300 + },
301 + },
302 + });
303 + assert.includeMembers(
304 + [...(codexHome.summary?.limits?.providers?.lockedInstanceFields?.[codex] ?? [])],
305 + ["config.homePath", "config.shadowHomePath"],
306 + );
307 + // A server URL makes OpenCode skip the local launch a pin sets, so the pin owns it too.
308 + const opencode = ProviderDriverKind.make("opencode");
309 + const opencodePinned = yield* ManagedPolicy.fromDocument("/test/policy.json", {
310 + schemaVersion: 1,
311 + organization: "Example Corp",
312 + limits: {
313 + providers: { instances: { [opencode]: { locked: true, binaryPath: "/opt/opencode" } } },
314 + },
315 + });
316 + assert.include(
317 + opencodePinned.summary?.limits?.providers?.lockedInstanceFields?.[opencode] ?? [],
318 + "config.serverUrl",
319 + );
320 + // The same override from the environment that starts the server is ignored too.
321 + const host = { PATH: "/usr/bin", T3CODE_CODEX_LAUNCH_ARGS: "--yolo" };
322 + assert.deepEqual(providerHostEnvironment((yield* policyOn("linux")).summary, host), {
323 + PATH: "/usr/bin",
324 + });
325 + }),
326 + );
327 +
328 + it.effect("refuses a default runtime mode above its own ceiling", () =>
329 + Effect.gen(function* () {
330 + const reasons = yield* Effect.forEach([false, true], (locked) =>
331 + loadFrom(
332 + JSON.stringify({
333 + schemaVersion: 1,
334 + organization: "Example Corp",
335 + settings: { defaultRuntimeMode: { value: "auto", locked } },
336 + limits: { maxRuntimeMode: "auto-accept-edits" },
337 + }),
338 + ).pipe(
339 + Effect.flip,
340 + Effect.map((error) => error.reason),
341 + ),
342 + );
343 + assert.deepEqual(reasons, [
344 + '"defaultRuntimeMode" is above "limits.maxRuntimeMode"',
345 + '"defaultRuntimeMode" is above "limits.maxRuntimeMode"',
346 + ]);
347 + }),
348 + );
349 +
350 + it.effect("tells clients which drivers run and which instance fields are locked", () =>
351 + Effect.gen(function* () {
352 + const policy = yield* loadFrom(
353 + JSON.stringify({
354 + schemaVersion: 1,
355 + organization: "Example Corp",
356 + limits: {
357 + providers: {
358 + allowedDrivers: ["claudeAgent", "codex"],
359 + instances: {
360 + claudeAgent: {
361 + locked: true,
362 + environment: [{ name: "CLAUDE_CODE_USE_BEDROCK", value: "1" }],
363 + binaryPath: "/opt/claude/bin/claude",
364 + },
365 + codex: { locked: false, launchArgs: "-c model_provider=gateway" },
366 + },
367 + },
368 + },
369 + }),
370 + );
371 + assert.deepEqual<unknown>(policy.summary?.limits, {
372 + providers: {
373 + allowedDrivers: ["claudeAgent", "codex"],
374 + lockedInstanceFields: {
375 + claudeAgent: ["config.binaryPath", "environment.CLAUDE_CODE_USE_BEDROCK"],
376 + },
377 + },
378 + });
379 + assert.equal(
380 + disallowedDriverReason(policy.summary, ProviderDriverKind.make("cursor")),
381 + "Example Corp's policy does not allow the Cursor provider.",
382 + );
383 + assert.isUndefined(disallowedDriverReason(policy.summary, ProviderDriverKind.make("codex")));
384 + }),
385 + );
386 +
387 + it.effect("refuses provider limits it cannot enforce", () =>
388 + Effect.gen(function* () {
389 + const withProviders = (providers: unknown) =>
390 + JSON.stringify({
391 + schemaVersion: 1,
392 + organization: "Example Corp",
393 + limits: { providers },
394 + });
395 + const reasons = yield* Effect.forEach(
396 + [
397 + withProviders({ allowedDrivers: ["claudeAgent", "notAProvider"] }),
398 + withProviders({ instances: { notAProvider: { locked: true, binaryPath: "/x" } } }),
399 + // Cursor has no launch arguments setting to pin.
400 + withProviders({ instances: { cursor: { locked: true, launchArgs: "--x" } } }),
401 + withProviders({ instances: { codex: { locked: true, homePath: "/x" } } }),
402 + withProviders({
403 + instances: { codex: { locked: true, environment: [{ name: "1BAD", value: "" }] } },
404 + }),
405 + // No provider could run at all.
406 + withProviders({ allowedDrivers: [] }),
407 + ],
408 + (contents) =>
409 + loadFrom(contents).pipe(
410 + Effect.flip,
411 + Effect.map((error) => error.reason),
412 + ),
413 + );
414 + assert.lengthOf(reasons, 6);
415 + assert.include(reasons[0], "notAProvider");
416 + assert.include(reasons[1], "notAProvider");
417 + assert.include(reasons[2], "launchArgs");
418 + }),
419 + );
420 +
421 + it.effect(
422 + "tells clients how updates are managed and refuses an update feed it cannot trust",
423 + () =>
424 + Effect.gen(function* () {
425 + const base = { schemaVersion: 1, organization: "Example Corp" };
426 + const updates = {
427 + mode: "auto" as const,
428 + feedUrl: "https://updates.example/t3",
429 + allowNightly: false,
430 + };
431 + const policy = yield* loadFrom(JSON.stringify({ ...base, limits: { updates } }));
432 + const { feedUrl: _feedUrl, ...clientUpdates } = updates;
433 + assert.deepEqual(policy.summary?.limits, { updates: clientUpdates });
434 + for (const invalid of [
435 + { mode: "auto", feedUrl: "http://updates.example/t3" },
436 + { mode: "manual" },
437 + { mode: "sometimes" },
438 + { mode: "auto", pinVersion: "1.2.3" },
439 + ]) {
440 + yield* loadFrom(JSON.stringify({ ...base, limits: { updates: invalid } })).pipe(
441 + Effect.flip,
442 + );
443 + }
444 + }),
445 + );
446 +});
apps/server/src/policy/ManagedPolicy.ts new
+215
@@ -0,0 +1,215 @@
1 +/**
2 + * ManagedPolicy - the administrator's machine-wide policy file, read once at startup. A file this
3 + * build cannot fully enforce stops the server instead of leaving it looking managed.
4 + *
5 + * @module ManagedPolicy
6 + */
7 +import * as NodeModule from "node:module";
8 +
9 +import { ManagedPolicyDocument, type ManagedPolicySummary } from "@t3tools/contracts";
10 +import * as Config from "effect/Config";
11 +import * as Context from "effect/Context";
12 +import * as Crypto from "effect/Crypto";
13 +import * as Effect from "effect/Effect";
14 +import * as Hex from "effect/encoding/Hex";
15 +import * as Layer from "effect/Layer";
16 +import * as Option from "effect/Option";
17 +import * as Schema from "effect/Schema";
18 +
19 +import * as HostProcess from "@t3tools/shared/HostProcess";
20 +import {
21 + ManagedPolicyFileError,
22 + managedPolicyPath,
23 + layerWindowsRegistry,
24 + readManagedPolicy,
25 + readManagedPolicyFile,
26 +} from "@t3tools/shared/managedPolicyFile";
27 +
28 +import { telemetryChannel } from "../config.ts";
29 +import * as ManagedLimits from "./managedLimits.ts";
30 +import * as ManagedProviders from "./managedProviders.ts";
31 +import * as ManagedSettings from "./managedSettings.ts";
32 +
33 +export class ManagedPolicy extends Context.Service<
34 + ManagedPolicy,
35 + {
36 + /** Where the policy is read from, whether or not a file exists there. */
37 + readonly path: string;
38 + readonly document: ManagedPolicyDocument | undefined;
39 + readonly settings: ManagedSettings.ManagedSettings;
40 + readonly providers: ManagedProviders.ManagedProviders;
41 + /** What clients are told; absent when no policy applies. */
42 + readonly summary: ManagedPolicySummary | undefined;
43 + }
44 +>()("t3/policy/ManagedPolicy") {}
45 +
46 +type LimitsSummary = NonNullable<ManagedPolicySummary["limits"]>;
47 +
48 +const encodeDocumentJson = Schema.encodeEffect(Schema.fromJsonString(ManagedPolicyDocument));
49 +
50 +/** What `t3 policy show` compares to tell whether a running server loaded the installed policy. */
51 +export const loadedPolicy = Effect.fn("ManagedPolicy.loadedPolicy")(function* (
52 + policy: Pick<ManagedPolicy["Service"], "path" | "document">,
53 +) {
54 + if (policy.document === undefined) return null;
55 + const json = yield* encodeDocumentJson(policy.document).pipe(Effect.orDie);
56 + const digest = yield* (yield* Crypto.Crypto)
57 + .digest("SHA-256", new TextEncoder().encode(json))
58 + .pipe(Effect.orDie);
59 + return {
60 + source: policy.path,
61 + organization: policy.document.organization,
62 + fingerprint: Hex.encode(digest).slice(0, 12),
63 + };
64 +});
65 +
66 +/**
67 + * The organization whose policy switches `capability` off, or undefined when it is allowed.
68 + * Only an explicit `false` restricts.
69 + */
70 +export function deniedBy(
71 + policy: Pick<ManagedPolicy["Service"], "document">,
72 + capability: "webhookTasks" | "telemetry",
73 +): string | undefined {
74 + return policy.document?.limits?.[capability] === false ? policy.document.organization : undefined;
75 +}
76 +
77 +/** Build the service from a decoded document; fails when the document cannot be enforced. */
78 +export const fromDocument = Effect.fn("ManagedPolicy.fromDocument")(function* (
79 + path: string,
80 + document: ManagedPolicyDocument | undefined,
81 +) {
82 + if (document === undefined) {
83 + return ManagedPolicy.of({
84 + path,
85 + document: undefined,
86 + settings: ManagedSettings.unmanagedSettings,
87 + providers: ManagedProviders.unmanagedProviders,
88 + summary: undefined,
89 + });
90 + }
91 + const maxRuntimeMode = document.limits?.maxRuntimeMode;
92 + const settings = ManagedSettings.makeManagedSettings(document.settings ?? {}, maxRuntimeMode);
93 + if (settings._tag === "Invalid") {
94 + return yield* new ManagedPolicyFileError({ path, reason: settings.reason });
95 + }
96 + // A ceiling alone also shapes providers: their launch configuration becomes the administrator's.
97 + const providerLimits = document.limits?.providers;
98 + const providers =
99 + providerLimits === undefined && maxRuntimeMode === undefined
100 + ? undefined
101 + : ManagedProviders.makeManagedProviders(
102 + providerLimits ?? {},
103 + maxRuntimeMode,
104 + yield* HostProcess.Platform,
105 + );
106 + if (providers?._tag === "Invalid") {
107 + return yield* new ManagedPolicyFileError({ path, reason: providers.reason });
108 + }
109 + const lockedInstanceFields = providers?.providers.lockedInstanceFields ?? {};
110 + return ManagedPolicy.of({
111 + path,
112 + document,
113 + settings: settings.settings,
114 + providers: providers?.providers ?? ManagedProviders.unmanagedProviders,
115 + summary: {
116 + organization: document.organization,
117 + ...(document.supportUrl === undefined ? {} : { supportUrl: document.supportUrl }),
118 + lockedSettings: settings.settings.lockedPaths,
119 + ...(document.limits === undefined
120 + ? {}
121 + : { limits: summarizeLimits(document, lockedInstanceFields) }),
122 + },
123 + });
124 +});
125 +
126 +// Copies only what clients may see; other limits can carry values that stay on the server.
127 +function summarizeLimits(
128 + document: ManagedPolicyDocument,
129 + lockedInstanceFields: Readonly<Record<string, ReadonlyArray<string>>>,
130 +): LimitsSummary {
131 + const {
132 + maxRuntimeMode,
133 + clients,
134 + webhookTasks,
135 + telemetry,
136 + browserCookieImport,
137 + providers,
138 + updates,
139 + } = document.limits ?? {};
140 + const connect = ManagedLimits.allowsConnect({ document });
141 + return {
142 + ...(maxRuntimeMode === undefined ? {} : { maxRuntimeMode }),
143 + ...(clients === undefined ? {} : { clients }),
144 + ...(connect ? {} : { connect: false }),
145 + ...(webhookTasks === undefined ? {} : { webhookTasks }),
146 + ...(telemetry === undefined ? {} : { telemetry }),
147 + ...(browserCookieImport === undefined ? {} : { browserCookieImport }),
148 + ...(providers?.allowedDrivers === undefined && Object.keys(lockedInstanceFields).length === 0
149 + ? {}
150 + : {
151 + providers: {
152 + ...(providers?.allowedDrivers === undefined
153 + ? {}
154 + : { allowedDrivers: providers.allowedDrivers }),
155 + ...(Object.keys(lockedInstanceFields).length === 0 ? {} : { lockedInstanceFields }),
156 + },
157 + }),
158 + ...(updates === undefined
159 + ? {}
160 + : {
161 + updates: {
162 + mode: updates.mode,
163 + ...(updates.allowNightly === undefined ? {} : { allowNightly: updates.allowNightly }),
164 + },
165 + }),
166 + };
167 +}
168 +
169 +/** Read and validate the policy at `path`; a missing file means no policy. */
170 +export const load = Effect.fn("ManagedPolicy.load")(function* (path: string) {
171 + return yield* fromDocument(path, yield* readManagedPolicyFile(path));
172 +});
173 +
174 +const make = Effect.gen(function* () {
175 + // Source builds may read a policy from elsewhere so it can be tried without root. Release
176 + // builds never do: any override a user can set is a way around the policy.
177 + const devPath =
178 + telemetryChannel === "dev"
179 + ? yield* Config.option(Config.String("T3CODE_DEV_MANAGED_POLICY_PATH")).pipe(
180 + Effect.orElseSucceed(() => Option.none<string>()),
181 + )
182 + : Option.none<string>();
183 + const platform = yield* HostProcess.Platform;
184 + const policy = yield* Option.match(devPath, {
185 + onSome: load,
186 + onNone: () =>
187 + readManagedPolicy(platform).pipe(
188 + Effect.flatMap((found) =>
189 + fromDocument(found?.source ?? managedPolicyPath(platform), found?.document),
190 + ),
191 + ),
192 + });
193 + const path = policy.path;
194 + if (policy.summary !== undefined) {
195 + yield* Effect.logInfo("Managed policy applies.", {
196 + path,
197 + organization: policy.summary.organization,
198 + lockedSettings: policy.summary.lockedSettings,
199 + });
200 + }
201 + return policy;
202 +});
203 +
204 +// A single-executable server resolves packages on disk only through `require`.
205 +const requireForFfi = NodeModule.createRequire(import.meta.url);
206 +
207 +export const layer = Layer.effect(ManagedPolicy, make).pipe(
208 + Layer.provide(
209 + layerWindowsRegistry(async () => requireForFfi("ffi-rs") as typeof import("ffi-rs")),
210 + ),
211 +);
212 +
213 +/** A policy for tests; `undefined` means unmanaged. */
214 +export const layerTest = (document?: ManagedPolicyDocument) =>
215 + Layer.effect(ManagedPolicy, fromDocument("/test/policy.json", document));
apps/server/src/policy/managedLimits.test.ts new
+411
@@ -0,0 +1,411 @@
1 +import type { ManagedPolicyDocument } from "@t3tools/contracts";
2 +import { assert, it } from "@effect/vitest";
3 +import * as Effect from "effect/Effect";
4 +import * as Fiber from "effect/Fiber";
5 +import * as PlatformError from "effect/PlatformError";
6 +import * as Sink from "effect/Sink";
7 +import * as Stream from "effect/Stream";
8 +import * as TestClock from "effect/testing/TestClock";
9 +import { ChildProcessSpawner } from "effect/process";
10 +
11 +import * as NetService from "@t3tools/shared/Net";
12 +
13 +import * as EnvironmentAuthPolicy from "../auth/EnvironmentAuthPolicy.ts";
14 +import * as ManagedLimits from "./managedLimits.ts";
15 +import * as ManagedPolicy from "./ManagedPolicy.ts";
16 +
17 +const policy = (limits?: ManagedPolicyDocument["limits"]) => ({
18 + document: {
19 + schemaVersion: 1 as const,
20 + organization: "Example Corp",
21 + ...(limits === undefined ? {} : { limits }),
22 + },
23 +});
24 +
25 +const desktopAndLocal = policy({ clients: ["desktop", "local-browser"] });
26 +
27 +it.effect("refuses to listen on a non-loopback host when remote clients are not allowed", () =>
28 + Effect.gen(function* () {
29 + const error = yield* ManagedLimits.checkServerReachability(desktopAndLocal, {
30 + authPolicy: "remote-reachable",
31 + host: "0.0.0.0",
32 + tailscaleServeEnabled: false,
33 + }).pipe(Effect.flip);
34 + assert.equal(
35 + error.message,
36 + "Example Corp's policy does not allow remote clients, so the server cannot listen on 0.0.0.0.",
37 + );
38 + }),
39 +);
40 +
41 +it.effect("binds only the loopback address it approved when remote clients are not allowed", () =>
42 + Effect.gen(function* () {
43 + const bind = (
44 + host: string | undefined,
45 + policy: { readonly document: ManagedPolicyDocument | undefined } = desktopAndLocal,
46 + ) =>
47 + ManagedLimits.checkServerReachability(policy, {
48 + authPolicy: EnvironmentAuthPolicy.resolveServerAuthPolicy({ mode: "web", host }),
49 + host,
50 + tailscaleServeEnabled: false,
51 + });
52 + // Node listens on every interface for an empty host, and a name resolves through DNS.
53 + for (const host of ["", "127.office.example", "127.0.0.1e0", "0.0.0.0"]) {
54 + const error = yield* bind(host).pipe(Effect.flip);
55 + assert.include(error.message, "does not allow remote clients", host);
56 + }
57 + for (const [host, address] of [
58 + [undefined, "127.0.0.1"],
59 + ["localhost", "127.0.0.1"],
60 + ["127.0.0.2", "127.0.0.2"],
61 + ["[::1]", "::1"],
62 + ] as const) {
63 + assert.equal(yield* bind(host), address);
64 + }
65 + const service = yield* ManagedLimits.checkServerReachability(desktopAndLocal, {
66 + authPolicy: "remote-reachable",
67 + host: "0.0.0.0",
68 + tailscaleServeEnabled: false,
69 + privateNetworkOnly: true,
70 + }).pipe(Effect.flip);
71 + assert.include(service.message, "set T3CODE_HOST=127.0.0.1 in its service.env");
72 + assert.equal(yield* bind("localhost", { document: undefined }), "localhost");
73 + assert.equal(yield* bind(undefined, { document: undefined }), "127.0.0.1");
74 + }),
75 +);
76 +
77 +it.effect("refuses Tailscale Serve when remote clients are not allowed", () =>
78 + Effect.gen(function* () {
79 + const error = yield* ManagedLimits.checkServerReachability(desktopAndLocal, {
80 + authPolicy: "loopback-browser",
81 + host: undefined,
82 + tailscaleServeEnabled: true,
83 + }).pipe(Effect.flip);
84 + assert.include(error.message, "Tailscale Serve");
85 + }),
86 +);
87 +
88 +it.effect("refuses an auth policy the clients list leaves out", () =>
89 + Effect.gen(function* () {
90 + const error = yield* ManagedLimits.checkServerReachability(policy({ clients: ["desktop"] }), {
91 + authPolicy: "loopback-browser",
92 + host: undefined,
93 + tailscaleServeEnabled: false,
94 + }).pipe(Effect.flip);
95 + assert.equal(error.message, "Example Corp's policy does not allow browsers on this machine.");
96 + }),
97 +);
98 +
99 +it.effect("refuses unsafe-no-auth under any policy file, even one without limits", () =>
100 + Effect.gen(function* () {
101 + const error = yield* ManagedLimits.checkServerReachability(policy(), {
102 + authPolicy: "unsafe-no-auth",
103 + host: undefined,
104 + tailscaleServeEnabled: false,
105 + }).pipe(Effect.flip);
106 + assert.include(error.message, "without authentication");
107 + assert.isTrue(ManagedLimits.allowsAuthPolicy({ document: undefined }, "unsafe-no-auth"));
108 + }),
109 +);
110 +
111 +it.effect("allows the clients the policy lists", () =>
112 + ManagedLimits.checkServerReachability(policy({ clients: ["remote"] }), {
113 + authPolicy: "remote-reachable",
114 + host: "0.0.0.0",
115 + tailscaleServeEnabled: true,
116 + }),
117 +);
118 +
119 +it.effect("tells clients Connect is off when the policy leaves out remote clients", () =>
120 + Effect.gen(function* () {
121 + const managed = yield* ManagedPolicy.fromDocument("/test/policy.json", {
122 + ...desktopAndLocal.document,
123 + });
124 + assert.deepEqual(managed.summary?.limits, {
125 + clients: ["desktop", "local-browser"],
126 + connect: false,
127 + });
128 + assert.isTrue(ManagedLimits.allowsConnect(policy({ clients: ["remote"] })));
129 + assert.isFalse(ManagedLimits.allowsConnect(policy({ connect: false })));
130 + }),
131 +);
132 +
133 +it.effect(
134 + "turns off only the Tailscale Serve routes that forward here, and refuses to start if one stays",
135 + () => {
136 + type Web = Record<string, Record<string, string>>;
137 + interface Answers {
138 + /** Serve handlers by host:port, then mount, to proxy target. */
139 + readonly web?: Web;
140 + /** TCP forwards by port. */
141 + readonly tcp?: Record<string, string>;
142 + /** The name `off` acts on: the machine's current one. */
143 + readonly currentName?: string;
144 + readonly status?: {
145 + readonly stdout: string;
146 + readonly exitCode: number;
147 + readonly stderr?: string;
148 + };
149 + readonly offExitCode?: number;
150 + /** `serve status` never answers, as on a Mac where Tailscale was never set up. */
151 + readonly statusHangs?: boolean;
152 + /** `off` exits as told but leaves the config alone. */
153 + readonly offIgnored?: boolean;
154 + }
155 + // Acts as the real CLI: `serve status --json` prints the config; `serve --https=<port> off`
156 + // drops every handler on that port of the current name unless `--set-path` names one
157 + // (serve_v2.go removeWebServe), and `serve --tcp=<port> off` drops that port's forward.
158 + const close = (answers: Answers, offCalls: Array<ReadonlyArray<string>> = []) => {
159 + const web: Web = answers.web ?? {
160 + "box.tailnet.ts.net:443": { "/": "http://127.0.0.1:3773" },
161 + };
162 + const tcp = answers.tcp ?? {};
163 + const currentName = answers.currentName ?? "box.tailnet.ts.net";
164 + return ManagedLimits.closeTailscaleServeTo(desktopAndLocal, {
165 + host: "127.0.0.1",
166 + port: 3773,
167 + }).pipe(
168 + Effect.provideService(
169 + ChildProcessSpawner.ChildProcessSpawner,
170 + ChildProcessSpawner.make((command) => {
171 + const { args } = command as unknown as { readonly args: ReadonlyArray<string> };
172 + // `tailscale status --json` names the machine; `tailscale serve status --json` routes.
173 + if (args[0] === "status") {
174 + return Effect.succeed(
175 + ChildProcessSpawner.makeHandle({
176 + pid: ChildProcessSpawner.ProcessId(1),
177 + exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
178 + isRunning: Effect.succeed(false),
179 + kill: () => Effect.void,
180 + unref: Effect.succeed(Effect.void),
181 + stdin: Sink.drain,
182 + stdout: Stream.make(
183 + new TextEncoder().encode(
184 + JSON.stringify({ Self: { DNSName: `${currentName}.` } }),
185 + ),
186 + ),
187 + stderr: Stream.empty,
188 + all: Stream.empty,
189 + getInputFd: () => Sink.drain,
190 + getOutputFd: () => Stream.empty,
191 + }),
192 + );
193 + }
194 + const isStatus = args.includes("status");
195 + if (!isStatus) {
196 + offCalls.push(args);
197 + const port = args.find((arg) => arg.startsWith("--https="))?.slice(8);
198 + const tcpPort = args.find((arg) => arg.startsWith("--tcp="))?.slice(6);
199 + const mount = args.find((arg) => arg.startsWith("--set-path="))?.slice(11);
200 + const site = web[`${currentName}:${port}`];
201 + if (answers.offIgnored !== true) {
202 + if (tcpPort !== undefined) delete tcp[tcpPort];
203 + for (const handler of Object.keys(site ?? {})) {
204 + if (mount === undefined || mount === handler) delete site![handler];
205 + }
206 + }
207 + }
208 + const status = answers.status ?? {
209 + stdout: JSON.stringify({
210 + TCP: Object.fromEntries(
211 + Object.entries(tcp).map(([port, forward]) => [port, { TCPForward: forward }]),
212 + ),
213 + Web: Object.fromEntries(
214 + Object.entries(web).map(([hostPort, handlers]) => [
215 + hostPort,
216 + {
217 + Handlers: Object.fromEntries(
218 + Object.entries(handlers).map(([mount, proxy]) => [mount, { Proxy: proxy }]),
219 + ),
220 + },
221 + ]),
222 + ),
223 + }),
224 + exitCode: 0,
225 + };
226 + const text = (value: string | undefined) =>
227 + value === undefined ? Stream.empty : Stream.make(new TextEncoder().encode(value));
228 + return Effect.succeed(
229 + ChildProcessSpawner.makeHandle({
230 + pid: ChildProcessSpawner.ProcessId(1),
231 + exitCode:
232 + isStatus && answers.statusHangs === true
233 + ? Effect.never
234 + : Effect.succeed(
235 + ChildProcessSpawner.ExitCode(
236 + isStatus ? status.exitCode : (answers.offExitCode ?? 0),
237 + ),
238 + ),
239 + isRunning: Effect.succeed(false),
240 + kill: () => Effect.void,
241 + unref: Effect.succeed(Effect.void),
242 + stdin: Sink.drain,
243 + stdout: isStatus ? text(status.stdout) : Stream.empty,
244 + stderr: isStatus ? text(status.stderr) : Stream.empty,
245 + all: Stream.empty,
246 + getInputFd: () => Sink.drain,
247 + getOutputFd: () => Stream.empty,
248 + }),
249 + );
250 + }),
251 + ),
252 + );
253 + };
254 + const portFree = { ...NetService.make(), canListenOnHost: () => Effect.succeed(true) };
255 + const portHeld = { ...portFree, canListenOnHost: () => Effect.succeed(false) };
256 + return Effect.gen(function* () {
257 + // A route that shares the port with this server's stays, as does one to another loopback
258 + // address on the same port; a TCP forward here goes too.
259 + for (const mount of ["/t3", "/"]) {
260 + const web: Web = {
261 + "box.tailnet.ts.net:443": {
262 + [mount]: "http://127.0.0.1:3773",
263 + "/dashboard": "http://127.0.0.1:9000",
264 + "/other": "http://127.0.0.2:3773",
265 + },
266 + };
267 + const tcp: Record<string, string> = { "7000": "127.0.0.1:3773" };
268 + const offCalls: Array<ReadonlyArray<string>> = [];
269 + yield* close({ web, tcp }, offCalls);
270 + assert.deepEqual(web, {
271 + "box.tailnet.ts.net:443": {
272 + "/dashboard": "http://127.0.0.1:9000",
273 + "/other": "http://127.0.0.2:3773",
274 + },
275 + });
276 + assert.deepEqual(tcp, {});
277 + assert.deepEqual(offCalls, [
278 + ["serve", "--tcp=7000", "off"],
279 + ["serve", "--https=443", `--set-path=${mount}`, "off"],
280 + ]);
281 + }
282 + // `off` acts on the current name: a route under a former one is left, with how to clear it,
283 + // while one under the current name goes even if a former name has routes too.
284 + const renamed: Web = {
285 + "old.tailnet.ts.net:443": { "/": "http://127.0.0.1:3773" },
286 + "new.tailnet.ts.net:443": { "/": "http://127.0.0.1:9000" },
287 + };
288 + const renamedOffCalls: Array<ReadonlyArray<string>> = [];
289 + const former = yield* close(
290 + { web: renamed, currentName: "new.tailnet.ts.net" },
291 + renamedOffCalls,
292 + ).pipe(Effect.flip);
293 + assert.deepEqual(renamedOffCalls, []);
294 + assert.deepEqual(renamed["new.tailnet.ts.net:443"], { "/": "http://127.0.0.1:9000" });
295 + assert.include(
296 + former.message,
297 + 'under old.tailnet.ts.net, a former name of this machine, which "tailscale serve ... off" cannot reach; run "tailscale serve reset"',
298 + );
299 + const current: Web = {
300 + "old.tailnet.ts.net:443": { "/": "http://127.0.0.1:9000" },
301 + "new.tailnet.ts.net:443": { "/": "http://127.0.0.1:3773" },
302 + };
303 + yield* close({ web: current, currentName: "new.tailnet.ts.net" });
304 + assert.deepEqual(current, {
305 + "old.tailnet.ts.net:443": { "/": "http://127.0.0.1:9000" },
306 + "new.tailnet.ts.net:443": {},
307 + });
308 + // A `localhost` target might reach another service on the other loopback, so it stays.
309 + const localhostOffCalls: Array<ReadonlyArray<string>> = [];
310 + const localhost = yield* close(
311 + { web: { "box.tailnet.ts.net:443": { "/": "http://localhost:3773" } } },
312 + localhostOffCalls,
313 + ).pipe(Effect.flip);
314 + assert.deepEqual(localhostOffCalls, []);
315 + assert.include(localhost.message, "its target localhost might be another service");
316 + // Only a fresh read confirms the route is gone, whatever `off` exits with.
317 + for (const answers of [{ offIgnored: true }, { offIgnored: true, offExitCode: 1 }]) {
318 + const stuck = yield* close(answers).pipe(Effect.flip);
319 + assert.include(
320 + stuck.message,
321 + 'Tailscale Serve forwards port 443 at / here; turn it off with "tailscale serve --https=443 --set-path=/ off"',
322 + );
323 + }
324 + // Routes the server must not remove itself: a Service's, and a foreground command's.
325 + const owners = {
326 + stdout: JSON.stringify({
327 + Foreground: {
328 + session1: {
329 + Web: { "box:443": { Handlers: { "/": { Proxy: "http://127.0.0.1:3773" } } } },
330 + },
331 + },
332 + Services: {
333 + "svc:t3": {
334 + Web: { "t3:443": { Handlers: { "/t3": { Proxy: "http://127.0.0.1:3773" } } } },
335 + },
336 + },
337 + }),
338 + exitCode: 0,
339 + };
340 + const ownedOffCalls: Array<ReadonlyArray<string>> = [];
341 + const owned = yield* close({ status: owners }, ownedOffCalls).pipe(Effect.flip);
342 + assert.deepEqual(ownedOffCalls, []);
343 + assert.include(owned.message, 'stop the "tailscale serve" command that runs it');
344 + assert.include(
345 + owned.message,
346 + '"tailscale serve --service=svc:t3 --https=443 --set-path=/t3 off"',
347 + );
348 + // An answer that cannot be read might hide a mapping, so the server does not start.
349 + const dialFailure = (reason: string) =>
350 + `Failed to connect to local Tailscale daemon for /localapi/v0/serve-config; not running? Error: dial unix /var/run/tailscale/tailscaled.sock: connect: ${reason}`;
351 + for (const status of [
352 + { stdout: "", exitCode: 1, stderr: "something unexpected" },
353 + { stdout: "not json", exitCode: 0 },
354 + { stdout: "", exitCode: 1, stderr: "Access denied: serve config denied" },
355 + { stdout: "", exitCode: 1, stderr: dialFailure("permission denied") },
356 + ]) {
357 + const unread = yield* close({ status }).pipe(Effect.flip);
358 + assert.include(unread.message, "does not start until Tailscale Serve can be checked");
359 + }
360 + // A Tailscale that never answers is not read as nothing to close, and the refusal says why.
361 + const hung = yield* close({ statusHangs: true }).pipe(Effect.flip, Effect.forkChild);
362 + yield* TestClock.adjust("10 seconds");
363 + assert.include((yield* Fiber.join(hung)).message, "Tailscale did not answer");
364 + // Tailscale down, logged out, or not installed forwards nothing now.
365 + for (const stderr of [
366 + dialFailure("connection refused"),
367 + "NeedsLogin: not logged in",
368 + String.raw`Get "http://local-tailscaled.sock/localapi/v0/serve-config": open \\.\pipe\ProtectedPrefix\Administrators\Tailscale\tailscaled: The system cannot find the file specified.`,
369 + ]) {
370 + yield* close({ status: { stdout: "", exitCode: 1, stderr } });
371 + }
372 + const spawnFailing = (tag: "NotFound" | "PermissionDenied") =>
373 + ManagedLimits.closeTailscaleServeTo(desktopAndLocal, {
374 + host: "127.0.0.1",
375 + port: 3773,
376 + }).pipe(
377 + Effect.provideService(
378 + ChildProcessSpawner.ChildProcessSpawner,
379 + ChildProcessSpawner.make(() =>
380 + Effect.fail(
381 + PlatformError.systemError({ _tag: tag, module: "ChildProcess", method: "spawn" }),
382 + ),
383 + ),
384 + ),
385 + );
386 + yield* spawnFailing("NotFound");
387 + // Node throws this instead when PATH ends in a file.
388 + yield* ManagedLimits.closeTailscaleServeTo(desktopAndLocal, {
389 + host: "127.0.0.1",
390 + port: 3773,
391 + }).pipe(
392 + Effect.provideService(
393 + ChildProcessSpawner.ChildProcessSpawner,
394 + ChildProcessSpawner.make(() =>
395 + Effect.die(Object.assign(new Error("spawn tailscale ENOTDIR"), { code: "ENOTDIR" })),
396 + ),
397 + ),
398 + );
399 + // A CLI that is there but will not run might still front a daemon with a mapping.
400 + yield* spawnFailing("PermissionDenied").pipe(Effect.flip);
401 + // Another app holds the port: its route is not ours, and it could let go before the bind.
402 + const heldOffCalls: Array<ReadonlyArray<string>> = [];
403 + const held = yield* close({}, heldOffCalls).pipe(
404 + Effect.provideService(NetService.NetService, portHeld),
405 + Effect.flip,
406 + );
407 + assert.deepEqual(heldOffCalls, []);
408 + assert.include(held.message, "while it cannot bind 127.0.0.1:3773");
409 + }).pipe(Effect.provideService(NetService.NetService, portFree));
410 + },
411 +);
apps/server/src/policy/managedLimits.ts new
+239
@@ -0,0 +1,239 @@
1 +/**
2 + * managedLimits - what `limits.clients` and `limits.connect` in the managed policy allow, and the
3 + * one error every refusal uses so each transport can show the administrator's organization.
4 + *
5 + * @module managedLimits
6 + */
7 +import type {
8 + ManagedPolicyClient,
9 + ManagedPolicyDocument,
10 + ServerAuthPolicy,
11 +} from "@t3tools/contracts";
12 +import {
13 + disableTailscaleServe,
14 + disableTailscaleServeTcp,
15 + readTailscaleServeRoutesTo,
16 + tailscaleServeOffArgs,
17 + readTailscaleStatus,
18 + type TailscaleServeRoute,
19 + type TailscaleStderrDiagnostic,
20 +} from "@t3tools/tailscale";
21 +import * as Effect from "effect/Effect";
22 +import * as PlatformError from "effect/PlatformError";
23 +import * as Schema from "effect/Schema";
24 +
25 +import * as NetService from "@t3tools/shared/Net";
26 +
27 +import { loopbackBindAddress } from "../auth/utils.ts";
28 +
29 +type PolicyDocument = { readonly document: ManagedPolicyDocument | undefined };
30 +
31 +export class ManagedPolicyRefusedError extends Schema.TaggedError<ManagedPolicyRefusedError>()(
32 + "ManagedPolicyRefusedError",
33 + {
34 + organization: Schema.String,
35 + /** What the policy does not allow, for example "T3 Connect". */
36 + action: Schema.String,
37 + /** What that means for this request, for example "so the server cannot listen on 0.0.0.0". */
38 + detail: Schema.optionalKey(Schema.String),
39 + },
40 +) {
41 + override get message(): string {
42 + return `${this.organization}'s policy does not allow ${this.action}${
43 + this.detail === undefined ? "" : `, ${this.detail}`
44 + }.`;
45 + }
46 +}
47 +
48 +const CLIENT_AUTH_POLICY: Record<ManagedPolicyClient, ServerAuthPolicy> = {
49 + desktop: "desktop-managed-local",
50 + "local-browser": "loopback-browser",
51 + remote: "remote-reachable",
52 +};
53 +
54 +const AUTH_POLICY_ACTION: Record<ServerAuthPolicy, string> = {
55 + "desktop-managed-local": "the desktop app",
56 + "loopback-browser": "browsers on this machine",
57 + "remote-reachable": "remote clients",
58 + "unsafe-no-auth": "running without authentication",
59 +};
60 +
61 +/** Whether the server may run with `authPolicy`. Any policy file rules out `unsafe-no-auth`. */
62 +export function allowsAuthPolicy(policy: PolicyDocument, authPolicy: ServerAuthPolicy): boolean {
63 + if (policy.document === undefined) return true;
64 + if (authPolicy === "unsafe-no-auth") return false;
65 + const clients = policy.document.limits?.clients;
66 + return (
67 + clients === undefined || clients.some((client) => CLIENT_AUTH_POLICY[client] === authPolicy)
68 + );
69 +}
70 +
71 +/** Whether anything off this machine may pair, by LAN, Tailscale, or a minted link. */
72 +export const allowsRemoteClients = (policy: PolicyDocument) =>
73 + allowsAuthPolicy(policy, "remote-reachable");
74 +
75 +/** T3 Connect is a way for remote clients in, so a policy without `remote` turns it off too. */
76 +export const allowsConnect = (policy: PolicyDocument) =>
77 + policy.document?.limits?.connect !== false && allowsRemoteClients(policy);
78 +
79 +const refuse = (policy: PolicyDocument, action: string, detail?: string) =>
80 + new ManagedPolicyRefusedError({
81 + organization: policy.document?.organization ?? "Your organization",
82 + action,
83 + ...(detail === undefined ? {} : { detail }),
84 + });
85 +
86 +export const refuseConnect = (policy: PolicyDocument) => refuse(policy, "T3 Connect");
87 +
88 +// Node throws ENOTDIR, outside the spawner's error mapping, when PATH ends in a file.
89 +const isMissingCli = (cause: unknown) =>
90 + (PlatformError.isPlatformError(cause) && cause.reason._tag === "NotFound") ||
91 + (cause instanceof Error && "code" in cause && cause.code === "ENOTDIR");
92 +
93 +const NOTHING_FORWARDED: ReadonlyArray<TailscaleServeRoute> = [];
94 +
95 +/** Tailscale answers that leave nothing forwarding here right now. */
96 +const NOTHING_TO_CLOSE: ReadonlySet<TailscaleStderrDiagnostic | undefined> = new Set([
97 + "not-running",
98 + "not-logged-in",
99 +]);
100 +
101 +/**
102 + * Turns off the Tailscale Serve routes that forward to the server at `target`, such as one
103 + * `t3 pair --tailscale` left from before the policy, and keeps every other route. Runs before the
104 + * server binds, and fails unless a fresh read shows no route here, since `off` can exit 0 and
105 + * leave it. Without the CLI, or with Tailscale down or logged out, nothing forwards.
106 + */
107 +export const closeTailscaleServeTo = Effect.fn("managedLimits.closeTailscaleServeTo")(function* (
108 + policy: PolicyDocument,
109 + target: { readonly host: string; readonly port: number },
110 +) {
111 + if (allowsRemoteClients(policy)) return;
112 + // Another app holds the port, so its routes are not ours to remove. It could let go before the
113 + // bind, which would then take over those routes, so the server does not start.
114 + if (!(yield* (yield* NetService.NetService).canListenOnHost(target.port, target.host))) {
115 + return yield* refuseRemoteClients(
116 + policy,
117 + `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`,
118 + );
119 + }
120 + const readRoutes = readTailscaleServeRoutesTo(target).pipe(
121 + Effect.catchTags({
122 + // Only a CLI that is not there; one that will not run might still front a daemon.
123 + TailscaleCommandSpawnError: (error) =>
124 + isMissingCli(error.cause) ? Effect.succeed(NOTHING_FORWARDED) : Effect.fail(error),
125 + TailscaleCommandExitError: (error) =>
126 + NOTHING_TO_CLOSE.has(error.stderrDiagnostic)
127 + ? Effect.succeed(NOTHING_FORWARDED)
128 + : Effect.fail(error),
129 + }),
130 + // Tailscale errors carry only labelled diagnostics, never raw stderr, so they are safe to log.
131 + Effect.tapError((cause) =>
132 + Effect.logWarning("Tailscale Serve could not be checked", { cause }),
133 + ),
134 + Effect.mapError((error) =>
135 + refuseRemoteClients(
136 + policy,
137 + error._tag === "TailscaleCommandTimeoutError"
138 + ? // Seen on a Mac where Tailscale is installed but was never set up.
139 + "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"
140 + : "so the server does not start until Tailscale Serve can be checked",
141 + ),
142 + ),
143 + );
144 + const found = yield* readRoutes;
145 + if (found.length === 0) return;
146 + // `off` acts on the machine's current name, so a web route under a former name stays.
147 + const currentName = found.some((route) => route.mount !== undefined && route.owner === undefined)
148 + ? yield* readTailscaleStatus.pipe(
149 + Effect.map((status) => status.magicDnsName?.toLowerCase() ?? null),
150 + Effect.orElseSucceed(() => null),
151 + )
152 + : null;
153 + const formerName = (route: TailscaleServeRoute) =>
154 + route.owner === undefined &&
155 + route.host !== undefined &&
156 + currentName !== null &&
157 + route.host.toLowerCase() !== currentName;
158 + // A Service is shared across the tailnet, and a foreground route lives as long as its command.
159 + const removable = (route: TailscaleServeRoute) =>
160 + route.owner === undefined &&
161 + route.ambiguous === undefined &&
162 + (route.mount === undefined || (currentName !== null && !formerName(route)));
163 + for (const route of found.filter(removable)) {
164 + yield* (
165 + route.mount === undefined
166 + ? disableTailscaleServeTcp(route.servePort)
167 + : disableTailscaleServe(route)
168 + ).pipe(
169 + Effect.catch((cause) =>
170 + Effect.logWarning("Tailscale Serve route could not be turned off", { ...route, cause }),
171 + ),
172 + );
173 + }
174 + const left = yield* readRoutes;
175 + if (left.length > 0) {
176 + const describe = (route: TailscaleServeRoute) => {
177 + const where = `port ${route.servePort}${route.mount === undefined ? "" : ` at ${route.mount}`} here`;
178 + const off = tailscaleServeOffArgs(route);
179 + if (off === undefined) return `${where}; stop the "tailscale serve" command that runs it`;
180 + if (formerName(route)) {
181 + 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`;
182 + }
183 + const command = `"tailscale ${off.join(" ")}"`;
184 + // Without the current name, `off` might act on another name's route at this path.
185 + if (currentName === null && route.owner === undefined && route.host !== undefined) {
186 + return `${where} under ${route.host}; if that is this machine's current name, turn it off with ${command}`;
187 + }
188 + return route.ambiguous !== undefined
189 + ? `${where}, and its target ${route.ambiguous} might be another service on this port; check it, then turn it off with ${command}`
190 + : `${where}; turn it off with ${command}`;
191 + };
192 + return yield* refuseRemoteClients(
193 + policy,
194 + `so the server does not start while Tailscale Serve forwards ${left.map(describe).join(", and ")}`,
195 + );
196 + }
197 + yield* Effect.logInfo("Turned off Tailscale Serve the managed policy does not allow", {
198 + routes: found,
199 + });
200 +});
201 +
202 +export const refuseRemoteClients = (policy: PolicyDocument, detail?: string) =>
203 + refuse(policy, AUTH_POLICY_ACTION["remote-reachable"], detail);
204 +
205 +/**
206 + * Fails when the server would accept clients the policy leaves out; otherwise returns the address
207 + * to bind. Runs before the server binds, so a refused configuration never listens, not even
208 + * briefly. Without `remote` that address is the loopback literal the check approved, never a name.
209 + */
210 +export const checkServerReachability = Effect.fn("managedLimits.checkServerReachability")(
211 + function* (
212 + policy: PolicyDocument,
213 + input: {
214 + readonly authPolicy: ServerAuthPolicy;
215 + readonly host: string | undefined;
216 + readonly tailscaleServeEnabled: boolean;
217 + /** The background service chose `host` to reach private networks; the user did not. */
218 + readonly privateNetworkOnly?: boolean | undefined;
219 + },
220 + ) {
221 + const cannotListen = () =>
222 + refuseRemoteClients(
223 + policy,
224 + input.privateNetworkOnly === true
225 + ? "so the background service cannot listen on private networks; set T3CODE_HOST=127.0.0.1 in its service.env"
226 + : `so the server cannot listen on ${input.host === "" ? "every interface" : (input.host ?? "this host")}`,
227 + );
228 + if (!allowsAuthPolicy(policy, input.authPolicy)) {
229 + return yield* input.authPolicy === "remote-reachable"
230 + ? cannotListen()
231 + : refuse(policy, AUTH_POLICY_ACTION[input.authPolicy]);
232 + }
233 + if (allowsRemoteClients(policy)) return input.host ?? "127.0.0.1";
234 + if (input.tailscaleServeEnabled) {
235 + return yield* refuseRemoteClients(policy, "so Tailscale Serve cannot be turned on");
236 + }
237 + return loopbackBindAddress(input.host) ?? (yield* cannotListen());
238 + },
239 +);
apps/server/src/policy/managedProviders.ts new
+598
@@ -0,0 +1,598 @@
1 +import {
2 + AntigravitySettings,
3 + ClaudeSettings,
4 + CodexSettings,
5 + defaultInstanceIdForDriver,
6 + disallowedProviderMessage,
7 + type ManagedProviderInstance,
8 + type ManagedProviderLimits,
9 + type ManagedPolicySummary,
10 + ProviderDriverKind,
11 + type ProviderInstanceConfig,
12 + type ProviderInstanceEnvironmentVariable,
13 + type ProviderInstanceId,
14 + resolveProviderInstanceEnabled,
15 + type RuntimeMode,
16 + type ServerSettings,
17 +} from "@t3tools/contracts";
18 +import { acpRegistryClient } from "@t3tools/provider-acp-registry/client";
19 +import { cursorClient } from "@t3tools/provider-cursor/client";
20 +import { fxClient } from "@t3tools/provider-fx/client";
21 +import { grokClient } from "@t3tools/provider-grok/client";
22 +import { museClient } from "@t3tools/provider-muse/client";
23 +import { openCodeClient } from "@t3tools/provider-opencode/client";
24 +import { piClient } from "@t3tools/provider-pi/client";
25 +import type { ProviderClientDefinition } from "@t3tools/provider-core/client";
26 +
27 +interface KnownDriver {
28 + readonly label: string;
29 + readonly configFields: ReadonlySet<string>;
30 + readonly hasDefaultInstance: boolean;
31 +}
32 +
33 +const known = (
34 + driverKind: string,
35 + label: string,
36 + settingsSchema: { readonly fields: object },
37 + hasDefaultInstance = true,
38 +) =>
39 + [
40 + ProviderDriverKind.make(driverKind),
41 + { label, configFields: new Set(Object.keys(settingsSchema.fields)), hasDefaultInstance },
42 + ] as const;
43 +
44 +const PACKAGED_CLIENTS: ReadonlyArray<ProviderClientDefinition> = [
45 + cursorClient,
46 + grokClient,
47 + fxClient,
48 + museClient,
49 + openCodeClient,
50 + piClient,
51 + acpRegistryClient,
52 +];
53 +
54 +/**
55 + * Fields that make an instance launch without the settings a pin sets: managed Codex runs T3's own
56 + * runtime against OpenAI, and a server URL points OpenCode at a server it does not start. A policy
57 + * that owns a pin owns these too, holding each at the value given here, which clients still send
58 + * when they add an instance.
59 + */
60 +const PIN_BYPASS_FIELDS: ReadonlyMap<
61 + ProviderDriverKind,
62 + Readonly<Record<string, unknown>>
63 +> = new Map<ProviderDriverKind, Readonly<Record<string, unknown>>>([
64 + [ProviderDriverKind.make("codex"), { setupMode: "existing" }],
65 + [ProviderDriverKind.make("opencode"), { serverUrl: "" }],
66 +]);
67 +
68 +/** Drivers this build knows, by the names users see; a policy naming any other is refused. */
69 +const KNOWN_DRIVERS: ReadonlyMap<ProviderDriverKind, KnownDriver> = new Map([
70 + known("codex", "Codex", CodexSettings),
71 + known("claudeAgent", "Claude", ClaudeSettings),
72 + known("antigravity", "Antigravity", AntigravitySettings),
73 + ...PACKAGED_CLIENTS.map((client) =>
74 + known(client.driverKind, client.label, client.settingsSchema, client.hasDefaultInstance),
75 + ),
76 +]);
77 +
78 +const PINNED_CONFIG_FIELDS = ["binaryPath", "launchArgs"] as const;
79 +type PinnedConfigField = (typeof PINNED_CONFIG_FIELDS)[number];
80 +
81 +/**
82 + * Fields that decide what a provider starts and reads on startup; a driver has those its schema
83 + * has. Under a ceiling they are the administrator's: a wrapper binary, a skip-permissions flag, or
84 + * a config directory with allow rules each outrank T3 Code's mode, and no flag filter stops a wrapper.
85 + */
86 +const LAUNCH_CONFIG_FIELDS = [
87 + "binaryPath",
88 + "launchArgs",
89 + "homePath",
90 + "shadowHomePath",
91 + "commandPath",
92 + "commandArgs",
93 + "serverUrl",
94 +] as const;
95 +
96 +export type ProviderWriteVerdict =
97 + | { readonly _tag: "Allowed"; readonly settings: ServerSettings }
98 + | { readonly _tag: "Locked"; readonly path: string }
99 + | {
100 + readonly _tag: "Disallowed";
101 + readonly instanceId: ProviderInstanceId;
102 + readonly label: string;
103 + };
104 +
105 +/**
106 + * How a policy's `limits.providers` shapes provider instances. Like settings locks, pinned
107 + * fields are laid over instances on every read and never written to the user's settings file.
108 + */
109 +export interface ManagedProviders {
110 + readonly isDriverAllowed: (driver: ProviderDriverKind) => boolean;
111 + /** Lay pinned fields over every instance of a pinned driver, its default instance included. */
112 + readonly applyLimits: (settings: ServerSettings) => ServerSettings;
113 + /**
114 + * Vet a write from stored `current` to `next`. Refuses enabling a disallowed driver and moving
115 + * a locked field off its pinned value. Pinned values a client sends back are dropped, so the
116 + * user's own values return once the policy is gone.
117 + */
118 + readonly vetWrite: (current: ServerSettings, next: ServerSettings) => ProviderWriteVerdict;
119 + /**
120 + * Per driver, the instance fields users cannot change, for clients. `environment` alone means
121 + * every variable.
122 + */
123 + readonly lockedInstanceFields: Readonly<Record<string, ReadonlyArray<string>>>;
124 +}
125 +
126 +export const unmanagedProviders: ManagedProviders = {
127 + isDriverAllowed: () => true,
128 + applyLimits: (settings) => settings,
129 + vetWrite: (_current, next) => ({ _tag: "Allowed", settings: next }),
130 + lockedInstanceFields: {},
131 +};
132 +
133 +const labelFor = (driver: ProviderDriverKind) => KNOWN_DRIVERS.get(driver)?.label ?? driver;
134 +
135 +/** Why the policy clients were told about keeps `driver` from running, or undefined when it may run. */
136 +export const disallowedDriverReason = (
137 + summary: ManagedPolicySummary | undefined,
138 + driver: ProviderDriverKind,
139 +): string | undefined => {
140 + const allowed = summary?.limits?.providers?.allowedDrivers;
141 + return allowed === undefined || allowed.includes(driver)
142 + ? undefined
143 + : disallowedProviderMessage(summary?.organization, labelFor(driver));
144 +};
145 +
146 +/**
147 + * Variables that replace a provider's launch configuration. From the environment that starts the
148 + * server they are ignored under any policy, which can lock launch arguments in more than one way;
149 + * from an instance's own variables they are ignored when the policy locks launch arguments.
150 + */
151 +const LAUNCH_OVERRIDE_VARIABLES = ["T3CODE_CODEX_LAUNCH_ARGS"] as const;
152 +
153 +/** The environment provider drivers launch from under the policy clients were told about. */
154 +export const providerHostEnvironment = (
155 + summary: ManagedPolicySummary | undefined,
156 + environment: NodeJS.ProcessEnv,
157 +): NodeJS.ProcessEnv => {
158 + if (summary === undefined) return environment;
159 + const next = { ...environment };
160 + for (const name of Object.keys(next)) {
161 + if (LAUNCH_OVERRIDE_VARIABLES.some((override) => override === name.toUpperCase())) {
162 + delete next[name];
163 + }
164 + }
165 + return next;
166 +};
167 +
168 +/** Each driver's home variable, and the settings that rewrite it at launch. */
169 +const HOME_VARIABLES: ReadonlyMap<
170 + ProviderDriverKind,
171 + { readonly variable: string; readonly fields: ReadonlyArray<string> }
172 +> = new Map([
173 + [ProviderDriverKind.make("claudeAgent"), { variable: "CLAUDE_CONFIG_DIR", fields: ["homePath"] }],
174 + [
175 + ProviderDriverKind.make("codex"),
176 + { variable: "CODEX_HOME", fields: ["homePath", "shadowHomePath"] },
177 + ],
178 +]);
179 +
180 +const configRecord = (instance: ProviderInstanceConfig | undefined): Record<string, unknown> =>
181 + instance?.config !== null &&
182 + typeof instance?.config === "object" &&
183 + !Array.isArray(instance.config)
184 + ? (instance.config as Record<string, unknown>)
185 + : {};
186 +
187 +/** Empty strings and empty lists are how clients clear a field, so they count as unset. */
188 +const configValue = (instance: ProviderInstanceConfig | undefined, field: string) => {
189 + const value = configRecord(instance)[field];
190 + return value === "" || (Array.isArray(value) && value.length === 0) ? undefined : value;
191 +};
192 +
193 +const sameValue = (left: unknown, right: unknown) =>
194 + left === right || JSON.stringify(left) === JSON.stringify(right);
195 +
196 +const sameVariable = (
197 + left: ProviderInstanceEnvironmentVariable | undefined,
198 + right: ProviderInstanceEnvironmentVariable | undefined,
199 +) =>
200 + left === right ||
201 + (left !== undefined &&
202 + right !== undefined &&
203 + left.value === right.value &&
204 + left.sensitive === right.sensitive);
205 +
206 +const pinnedFields = (pin: ManagedProviderInstance): ReadonlyArray<PinnedConfigField> =>
207 + PINNED_CONFIG_FIELDS.filter((field) => pin[field] !== undefined);
208 +
209 +/**
210 + * What the administrator owns on one driver's instances. `config` fields take the pin or the
211 + * default, never the user's value; `fill` fields take the pin only where the user left them empty.
212 + * `environment`: `all` runs with only pinned variables, `locked` lets them win, `fill` fills gaps.
213 + */
214 +interface DriverRule {
215 + readonly pin: ManagedProviderInstance | undefined;
216 + readonly config: ReadonlyArray<string>;
217 + readonly fill: ReadonlyArray<PinnedConfigField>;
218 + readonly environment: "all" | "locked" | "fill";
219 +}
220 +
221 +const pinnedValue = (pin: ManagedProviderInstance | undefined, field: string): unknown =>
222 + pin === undefined ? undefined : (pin as Record<string, unknown>)[field];
223 +
224 +const overlayInstance = (
225 + instance: ProviderInstanceConfig,
226 + rule: DriverRule,
227 + variableKey: (name: string) => string,
228 +): ProviderInstanceConfig => {
229 + const config = { ...configRecord(instance) };
230 + for (const field of rule.config) {
231 + const value = pinnedValue(rule.pin, field);
232 + if (value === undefined) delete config[field];
233 + else config[field] = value;
234 + }
235 + for (const field of rule.fill) {
236 + if (configValue(instance, field) === undefined) config[field] = rule.pin?.[field];
237 + }
238 + const pinnedEnvironment = (rule.pin?.environment ?? []).map((variable) => ({
239 + name: variable.name,
240 + value: variable.value,
241 + sensitive: false,
242 + }));
243 + const pinnedByName = new Map(
244 + pinnedEnvironment.map((variable) => [variableKey(variable.name), variable]),
245 + );
246 + const environment: Array<NonNullable<ProviderInstanceConfig["environment"]>[number]> =
247 + rule.environment === "all" ? pinnedEnvironment : [];
248 + if (rule.environment !== "all") {
249 + const seen = new Set<string>();
250 + // A user's override would replace launch arguments the administrator locked.
251 + const overrides = rule.config.includes("launchArgs")
252 + ? new Set(LAUNCH_OVERRIDE_VARIABLES.map(variableKey))
253 + : new Set<string>();
254 + // The last entry for a name wins at launch, so a lock replaces every entry with that name.
255 + for (const variable of instance.environment ?? []) {
256 + const key = variableKey(variable.name);
257 + if (overrides.has(key)) continue;
258 + const pinned = rule.environment === "locked" ? pinnedByName.get(key) : undefined;
259 + if (pinned === undefined) environment.push(variable);
260 + else if (!seen.has(key)) environment.push(pinned);
261 + seen.add(key);
262 + }
263 + for (const pinned of pinnedEnvironment) {
264 + if (!seen.has(variableKey(pinned.name))) environment.push(pinned);
265 + }
266 + }
267 + const { config: _config, environment: _environment, ...envelope } = instance;
268 + return {
269 + ...envelope,
270 + ...(instance.config === undefined && Object.keys(config).length === 0 ? {} : { config }),
271 + ...(environment.length === 0 ? {} : { environment }),
272 + };
273 +};
274 +
275 +/**
276 + * Build the overlay for `limits.providers` and `limits.maxRuntimeMode`, or say why it cannot be
277 + * enforced. A ceiling takes each driver's launch fields and its whole `environment`, which can
278 + * carry `CLAUDE_CONFIG_DIR`, `PATH`, or `NODE_OPTIONS`; a deny list would miss the next one.
279 + */
280 +export function makeManagedProviders(
281 + limits: ManagedProviderLimits,
282 + maxRuntimeMode: RuntimeMode | undefined,
283 + platform: NodeJS.Platform,
284 +):
285 + | { readonly _tag: "Valid"; readonly providers: ManagedProviders }
286 + | { readonly _tag: "Invalid"; readonly reason: string } {
287 + // Windows reads a variable name without regard to case, so there a lock covers every spelling.
288 + const variableKey = (name: string) => (platform === "win32" ? name.toUpperCase() : name);
289 + for (const driver of limits.allowedDrivers ?? []) {
290 + if (!KNOWN_DRIVERS.has(driver)) {
291 + return { _tag: "Invalid", reason: `"${driver}" in allowedDrivers is not a known provider` };
292 + }
293 + }
294 + const pins = new Map<ProviderDriverKind, ManagedProviderInstance>();
295 + for (const [rawDriver, pin] of Object.entries(limits.instances ?? {})) {
296 + const driver = ProviderDriverKind.make(rawDriver);
297 + const known = KNOWN_DRIVERS.get(driver);
298 + if (known === undefined) {
299 + return { _tag: "Invalid", reason: `"${driver}" in instances is not a known provider` };
300 + }
301 + const unsupported = pinnedFields(pin).find((field) => !known.configFields.has(field));
302 + if (unsupported !== undefined) {
303 + return {
304 + _tag: "Invalid",
305 + reason: `the ${known.label} provider has no ${unsupported} setting`,
306 + };
307 + }
308 + const names = (pin.environment ?? []).map((variable) => variableKey(variable.name));
309 + if (new Set(names).size !== names.length) {
310 + return { _tag: "Invalid", reason: `instances.${driver}.environment repeats a variable` };
311 + }
312 + pins.set(driver, pin);
313 + }
314 +
315 + const rules = new Map<ProviderDriverKind, DriverRule>();
316 + for (const [driver, known] of KNOWN_DRIVERS) {
317 + const pin = pins.get(driver);
318 + const bypasses = pin === undefined ? [] : Object.keys(PIN_BYPASS_FIELDS.get(driver) ?? {});
319 + if (maxRuntimeMode !== undefined) {
320 + rules.set(driver, {
321 + pin,
322 + config: [
323 + ...LAUNCH_CONFIG_FIELDS.filter((field) => known.configFields.has(field)),
324 + ...bypasses,
325 + ],
326 + fill: [],
327 + environment: "all",
328 + });
329 + } else if (pin !== undefined) {
330 + // A home path setting rewrites the provider's home variable at launch, so a lock on that
331 + // variable owns the setting too.
332 + const home = HOME_VARIABLES.get(driver);
333 + const homeLocked =
334 + home !== undefined &&
335 + (pin.environment ?? []).some(
336 + (variable) => variableKey(variable.name) === variableKey(home.variable),
337 + );
338 + rules.set(driver, {
339 + pin,
340 + config: pin.locked
341 + ? [...pinnedFields(pin), ...bypasses, ...(homeLocked ? home.fields : [])]
342 + : [],
343 + fill: pin.locked ? [] : pinnedFields(pin),
344 + environment: pin.locked ? "locked" : "fill",
345 + });
346 + }
347 + }
348 +
349 + const allowed =
350 + limits.allowedDrivers === undefined ? undefined : new Set<string>(limits.allowedDrivers);
351 + const isDriverAllowed = (driver: ProviderDriverKind) => allowed?.has(driver) ?? true;
352 + const allowedSelection = (
353 + settings: ServerSettings,
354 + selection: { readonly instanceId: ProviderInstanceId } | null | undefined,
355 + ) =>
356 + selection == null ||
357 + isDriverAllowed(
358 + settings.providerInstances[selection.instanceId]?.driver ??
359 + ProviderDriverKind.make(selection.instanceId),
360 + );
361 +
362 + const cache = new WeakMap<ServerSettings, ServerSettings>();
363 + const applyLimits = (settings: ServerSettings): ServerSettings => {
364 + const cached = cache.get(settings);
365 + if (cached !== undefined) return cached;
366 + const providerInstances: Record<string, ProviderInstanceConfig> = {
367 + ...settings.providerInstances,
368 + };
369 + // Default instances exist without a settings entry until the user edits one; pin them too.
370 + for (const driver of pins.keys()) {
371 + const instanceId = defaultInstanceIdForDriver(driver);
372 + if (KNOWN_DRIVERS.get(driver)?.hasDefaultInstance === false) continue;
373 + if (providerInstances[instanceId] === undefined) providerInstances[instanceId] = { driver };
374 + }
375 + for (const [instanceId, instance] of Object.entries(providerInstances)) {
376 + const rule = rules.get(instance.driver);
377 + if (rule !== undefined) {
378 + providerInstances[instanceId] = overlayInstance(instance, rule, variableKey);
379 + }
380 + }
381 + // A cleared selection falls back to the text generation model, which is resolved afterwards.
382 + const result: ServerSettings = {
383 + ...settings,
384 + providerInstances: providerInstances as ServerSettings["providerInstances"],
385 + sourceControlWriterModelSelection: allowedSelection(
386 + settings,
387 + settings.sourceControlWriterModelSelection,
388 + )
389 + ? settings.sourceControlWriterModelSelection
390 + : null,
391 + reviewGuideModelSelection: allowedSelection(settings, settings.reviewGuideModelSelection)
392 + ? settings.reviewGuideModelSelection
393 + : null,
394 + };
395 + cache.set(settings, result);
396 + return result;
397 + };
398 +
399 + type Locked = { readonly _tag: "Locked"; readonly path: string };
400 +
401 + /**
402 + * Vet the environment a client sent. Pinned values it echoes back are dropped; anything else
403 + * the administrator owns must match what is stored. Returns the environment to store.
404 + */
405 + const vetEnvironment = (
406 + instanceId: string,
407 + stored: ProviderInstanceConfig | undefined,
408 + next: ProviderInstanceConfig,
409 + rule: DriverRule,
410 + ):
411 + | Locked
412 + | {
413 + readonly _tag: "Kept";
414 + readonly environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>;
415 + } => {
416 + const pinned = rule.pin?.environment ?? [];
417 + const storedVariable = (name: string) =>
418 + stored?.environment?.find((existing) => variableKey(existing.name) === variableKey(name));
419 + const storedUnchanged = (variable: ProviderInstanceEnvironmentVariable) =>
420 + (stored?.environment ?? []).some((existing) => sameVariable(variable, existing));
421 + const echoed = (variable: ProviderInstanceEnvironmentVariable) =>
422 + !variable.sensitive &&
423 + pinned.some((pin) => pin.name === variable.name && pin.value === variable.value);
424 + if (rule.environment === "all") {
425 + // Only the pinned variables were shown, so the user's own stay as stored.
426 + for (const variable of next.environment ?? []) {
427 + if (echoed(variable) || storedUnchanged(variable)) continue;
428 + return { _tag: "Locked", path: `providerInstances.${instanceId}.environment` };
429 + }
430 + return { _tag: "Kept", environment: stored?.environment ?? [] };
431 + }
432 + let environment: ReadonlyArray<ProviderInstanceEnvironmentVariable> = next.environment ?? [];
433 + for (const variable of pinned) {
434 + const sent = environment.find(
435 + (existing) => variableKey(existing.name) === variableKey(variable.name),
436 + );
437 + const kept = storedVariable(variable.name);
438 + if ((sent !== undefined && echoed(sent)) || sameVariable(sent, kept)) {
439 + // Put the user's own entries back where it was sent, or drop the echoed policy value.
440 + const storedEntries = (stored?.environment ?? []).filter(
441 + (existing) => variableKey(existing.name) === variableKey(variable.name),
442 + );
443 + let restored = false;
444 + environment = environment.flatMap((existing) => {
445 + if (variableKey(existing.name) !== variableKey(variable.name)) return [existing];
446 + if (restored) return [];
447 + restored = true;
448 + return storedEntries;
449 + });
450 + } else if (rule.environment === "locked") {
451 + return {
452 + _tag: "Locked",
453 + path: `providerInstances.${instanceId}.environment.${variable.name}`,
454 + };
455 + }
456 + }
457 + // The client never saw a launch override the lock hides, so keep the stored one.
458 + if (rule.config.includes("launchArgs")) {
459 + const overrides = new Set(LAUNCH_OVERRIDE_VARIABLES.map(variableKey));
460 + environment = [
461 + ...environment.filter((variable) => !overrides.has(variableKey(variable.name))),
462 + ...(stored?.environment ?? []).filter((variable) =>
463 + overrides.has(variableKey(variable.name)),
464 + ),
465 + ];
466 + }
467 + return { _tag: "Kept", environment };
468 + };
469 +
470 + const vetInstance = (
471 + instanceId: string,
472 + stored: ProviderInstanceConfig | undefined,
473 + next: ProviderInstanceConfig,
474 + rule: DriverRule,
475 + ): Locked | { readonly _tag: "Kept"; readonly instance: ProviderInstanceConfig | undefined } => {
476 + const config = { ...configRecord(next) };
477 + const harmless = PIN_BYPASS_FIELDS.get(next.driver) ?? {};
478 + for (const field of [...rule.config, ...rule.fill]) {
479 + const value = configValue(next, field);
480 + const storedValue = configValue(stored, field);
481 + if (
482 + sameValue(value, pinnedValue(rule.pin, field)) ||
483 + sameValue(value, storedValue) ||
484 + (field in harmless && sameValue(value, harmless[field]))
485 + ) {
486 + if (storedValue === undefined) delete config[field];
487 + else config[field] = configRecord(stored)[field];
488 + } else if (rule.config.includes(field)) {
489 + return { _tag: "Locked", path: `providerInstances.${instanceId}.config.${field}` };
490 + }
491 + }
492 + const vettedEnvironment = vetEnvironment(instanceId, stored, next, rule);
493 + if (vettedEnvironment._tag === "Locked") return vettedEnvironment;
494 + const { environment } = vettedEnvironment;
495 + const { config: _config, environment: _environment, ...envelope } = next;
496 + const kept: ProviderInstanceConfig = {
497 + ...envelope,
498 + ...(Object.keys(config).length === 0 && stored?.config === undefined ? {} : { config }),
499 + ...(environment.length === 0 ? {} : { environment }),
500 + };
501 + // A default instance the client echoed back with only pinned values stays implicit.
502 + const echoedDefault =
503 + stored === undefined &&
504 + instanceId === defaultInstanceIdForDriver(next.driver) &&
505 + Object.keys(kept).length === 1;
506 + return { _tag: "Kept", instance: echoedDefault ? undefined : kept };
507 + };
508 +
509 + const vetWrite = (current: ServerSettings, next: ServerSettings): ProviderWriteVerdict => {
510 + const providerInstances: Record<string, ProviderInstanceConfig> = {};
511 + for (const [instanceId, instance] of Object.entries(next.providerInstances)) {
512 + const stored = current.providerInstances[instanceId as ProviderInstanceId];
513 + // Clients echo instances with policy fields laid over them, so compare only whether it runs.
514 + // A driver's default instance runs before it is configured.
515 + const wasEnabled =
516 + stored !== undefined
517 + ? stored.driver === instance.driver && resolveProviderInstanceEnabled(stored)
518 + : instanceId === defaultInstanceIdForDriver(instance.driver);
519 + if (
520 + !isDriverAllowed(instance.driver) &&
521 + resolveProviderInstanceEnabled(instance) &&
522 + !wasEnabled
523 + ) {
524 + return {
525 + _tag: "Disallowed",
526 + instanceId: instanceId as ProviderInstanceId,
527 + label: labelFor(instance.driver),
528 + };
529 + }
530 + const rule = rules.get(instance.driver);
531 + if (rule === undefined) {
532 + providerInstances[instanceId] = instance;
533 + continue;
534 + }
535 + const vetted = vetInstance(
536 + instanceId,
537 + stored?.driver === instance.driver ? stored : undefined,
538 + instance,
539 + rule,
540 + );
541 + if (vetted._tag === "Locked") return vetted;
542 + if (vetted.instance !== undefined) providerInstances[instanceId] = vetted.instance;
543 + }
544 + // A project can switch an instance on for itself; that is enabling it too.
545 + for (const [projectId, overrides] of Object.entries(next.projectSettingsOverrides)) {
546 + const storedOverrides =
547 + current.projectSettingsOverrides[projectId as keyof typeof current.projectSettingsOverrides]
548 + ?.providerInstances;
549 + for (const [instanceId, override] of Object.entries(overrides.providerInstances ?? {})) {
550 + const driver =
551 + next.providerInstances[instanceId as ProviderInstanceId]?.driver ??
552 + ProviderDriverKind.make(instanceId);
553 + if (
554 + override.enabled === true &&
555 + storedOverrides?.[instanceId as ProviderInstanceId]?.enabled !== true &&
556 + !isDriverAllowed(driver)
557 + ) {
558 + return {
559 + _tag: "Disallowed",
560 + instanceId: instanceId as ProviderInstanceId,
561 + label: labelFor(driver),
562 + };
563 + }
564 + }
565 + }
566 + return {
567 + _tag: "Allowed",
568 + settings: {
569 + ...next,
570 + providerInstances: providerInstances as ServerSettings["providerInstances"],
571 + },
572 + };
573 + };
574 +
575 + const lockedInstanceFields = Object.fromEntries(
576 + [...rules].flatMap(([driver, rule]) => {
577 + const fields = [
578 + ...rule.config.map((field) => `config.${field}`),
579 + ...(rule.environment === "all"
580 + ? ["environment"]
581 + : rule.environment === "locked"
582 + ? (rule.pin?.environment ?? []).map((variable) => `environment.${variable.name}`)
583 + : []),
584 + ];
585 + return fields.length === 0 ? [] : [[driver, fields] as const];
586 + }),
587 + );
588 +
589 + return {
590 + _tag: "Valid",
591 + providers: {
592 + isDriverAllowed,
593 + applyLimits,
594 + vetWrite,
595 + lockedInstanceFields,
596 + },
597 + };
598 +}
apps/server/src/policy/managedSettings.ts new
+502
@@ -0,0 +1,502 @@
1 +import {
2 + DEFAULT_SERVER_SETTINGS,
3 + isRuntimeModeAbove,
4 + type ManagedPolicySetting,
5 + ProjectSettingsOverrides,
6 + type RuntimeMode,
7 + ServerSettings,
8 + withIdleCompaction,
9 +} from "@t3tools/contracts";
10 +import * as Exit from "effect/Exit";
11 +import * as Schema from "effect/Schema";
12 +
13 +import { mapSettingsSecrets } from "../settingsSecrets.ts";
14 +
15 +const encodeSettings = Schema.encodeSync(ServerSettings);
16 +const decodeSettings = Schema.decodeUnknownSync(ServerSettings);
17 +const decodeSettingsExit = Schema.decodeUnknownExit(ServerSettings);
18 +
19 +/** Project overrides mirror these top-level keys, so a lock on one applies inside each project. */
20 +const PROJECT_OVERRIDE_KEYS: ReadonlySet<string> = new Set(
21 + Object.keys(ProjectSettingsOverrides.fields),
22 +);
23 +/** Per-project stores; admins lock the top-level key and the lock reaches every project. */
24 +const UNMANAGEABLE_KEYS: ReadonlySet<string> = new Set([
25 + "projectSettingsOverrides",
26 + "projectAgentBrowserAccessOverrides",
27 + "projectAutoPullOverrides",
28 + "projectScriptOverrides",
29 +]);
30 +
31 +/** Legacy settings the server derives from another on every write; manage that one instead. */
32 +const DERIVED_FROM: ReadonlyMap<string, string> = new Map([
33 + ["compactIdleThreads", "idleCompaction"],
34 +]);
35 +
36 +/**
37 + * Settings another one overrides when it is set: `worktreeCleanup`, also per project, wins over
38 + * the worktree rules in `storageCleanup`. A lock on the first alone would look enforced without
39 + * being, so the second must be locked too.
40 + */
41 +const OVERRIDDEN_BY: ReadonlyArray<readonly [overridden: string, by: string]> = [
42 + ["storageCleanup.worktree", "worktreeCleanup"],
43 +];
44 +
45 +type Segments = ReadonlyArray<string>;
46 +
47 +/**
48 + * The server derives the legacy switch from `idleCompaction` on every write, and shipped clients
49 + * still read it, so values the policy sets carry the matching switch.
50 + */
51 +const syncIdleCompaction = (settings: ServerSettings): ServerSettings =>
52 + settings.idleCompaction === undefined
53 + ? settings
54 + : withIdleCompaction(settings, settings.idleCompaction);
55 +
56 +const isRecord = (value: unknown): value is Record<string, unknown> =>
57 + value !== null && typeof value === "object" && !Array.isArray(value);
58 +
59 +const getPath = (tree: unknown, segments: Segments): unknown => {
60 + let current = tree;
61 + for (const segment of segments) {
62 + if (!isRecord(current)) return undefined;
63 + current = current[segment];
64 + }
65 + return current;
66 +};
67 +
68 +const setPath = (tree: unknown, segments: Segments, value: unknown): unknown => {
69 + const [head, ...rest] = segments;
70 + if (head === undefined) return value;
71 + const record = isRecord(tree) ? tree : {};
72 + if (value === undefined && rest.length === 0) {
73 + const { [head]: _removed, ...remaining } = record;
74 + return remaining;
75 + }
76 + return { ...record, [head]: setPath(record[head], rest, value) };
77 +};
78 +
79 +/** Fills keys `target` lacks from `defaults`, recursing into objects both sides hold. */
80 +const fillMissing = (target: unknown, defaults: unknown): unknown => {
81 + if (!isRecord(target) || !isRecord(defaults)) return target;
82 + const next: Record<string, unknown> = { ...target };
83 + for (const [key, value] of Object.entries(defaults)) {
84 + next[key] = key in target ? fillMissing(target[key], value) : value;
85 + }
86 + return next;
87 +};
88 +
89 +const jsonEqual = (left: unknown, right: unknown): boolean => {
90 + if (Object.is(left, right)) return true;
91 + if (Array.isArray(left) && Array.isArray(right)) {
92 + return (
93 + left.length === right.length && left.every((item, index) => jsonEqual(item, right[index]))
94 + );
95 + }
96 + if (!isRecord(left) || !isRecord(right)) return false;
97 + const leftKeys = Object.keys(left).filter((key) => left[key] !== undefined);
98 + const rightKeys = Object.keys(right).filter((key) => right[key] !== undefined);
99 + return (
100 + leftKeys.length === rightKeys.length &&
101 + leftKeys.every((key) => jsonEqual(left[key], right[key]))
102 + );
103 +};
104 +
105 +/**
106 + * Whether `value` agrees with a lock on every key it holds. Patches and project overrides carry
107 + * only some of a locked object's keys, such as `{ enabled }` for a provider instance.
108 + */
109 +const matchesLock = (value: unknown, lock: unknown): boolean =>
110 + isRecord(value) && isRecord(lock)
111 + ? Object.entries(value).every(
112 + ([key, child]) => child === undefined || matchesLock(child, lock[key]),
113 + )
114 + : jsonEqual(value, lock);
115 +
116 +/** Whether `value` holds a key `existing` does not, at any depth. */
117 +const addsKeys = (existing: unknown, value: unknown): boolean =>
118 + isRecord(existing) &&
119 + isRecord(value) &&
120 + Object.entries(value).some(([key, child]) =>
121 + key in existing ? addsKeys(existing[key], child) : true,
122 + );
123 +
124 +/**
125 + * How a policy's `settings` shape the server's settings. Policy values are never written to
126 + * the user's settings file: defaults fill keys the file leaves out, and locks are laid over the
127 + * result on every read, so removing the policy brings the user's own settings back.
128 + */
129 +export interface ManagedSettings {
130 + /** Fill policy defaults into a parsed settings file before it is decoded. */
131 + readonly withDefaults: (persisted: unknown) => unknown;
132 + /** Built-in defaults with the policy's defaults applied; the settings file omits values equal to these. */
133 + readonly defaults: ServerSettings;
134 + /**
135 + * Lay locked values over settings, including inside each project's overrides, and lower
136 + * default runtime modes above the policy's ceiling to it.
137 + */
138 + readonly applyLocks: (settings: ServerSettings) => ServerSettings;
139 + /**
140 + * Vet a write from `current` to `next`. It is refused when it tries to move a locked path off
141 + * its locked value, whether set in `patch` or changed by another route such as a legacy patch
142 + * key. An allowed write keeps the user's stored values at locked paths, so a client re-sending
143 + * the locked value does not overwrite what applies once the policy is gone.
144 + */
145 + readonly vetWrite: (
146 + current: ServerSettings,
147 + next: ServerSettings,
148 + patch: unknown,
149 + ) =>
150 + | { readonly _tag: "Allowed"; readonly settings: ServerSettings }
151 + | { readonly _tag: "Locked"; readonly path: string };
152 + readonly lockedPaths: ReadonlyArray<string>;
153 + /**
154 + * Put back into a stripped settings file the values `stored`, the file before this write, held
155 + * at or under paths the policy defaults: equal to the policy's default, they are still the
156 + * user's choice. A key `isAtomic` names comes back whole or not at all. Undefined without
157 + * policy defaults, so writers can skip reading the file.
158 + */
159 + readonly keepStored:
160 + | ((
161 + stripped: unknown,
162 + settings: ServerSettings,
163 + stored: unknown,
164 + isAtomic: (key: string) => boolean,
165 + ) => unknown)
166 + | undefined;
167 +}
168 +
169 +export const unmanagedSettings: ManagedSettings = {
170 + keepStored: undefined,
171 + withDefaults: (persisted) => persisted,
172 + defaults: DEFAULT_SERVER_SETTINGS,
173 + applyLocks: (settings) => settings,
174 + vetWrite: (_current, next) => ({ _tag: "Allowed", settings: next }),
175 + lockedPaths: [],
176 +};
177 +
178 +interface Entry {
179 + readonly path: string;
180 + readonly segments: Segments;
181 + /** As written in the policy, the encoded form. */
182 + readonly value: unknown;
183 +}
184 +
185 +interface Lock extends Entry {
186 + /** The decoded form, which is what patches carry. */
187 + readonly decodedValue: unknown;
188 +}
189 +
190 +/** Locked paths as stored in the top level and in each project's overrides of `encoded`. */
191 +const lockTargets = (encoded: unknown, entry: Entry): ReadonlyArray<Segments> => {
192 + const [head] = entry.segments;
193 + if (head === undefined || !PROJECT_OVERRIDE_KEYS.has(head)) return [entry.segments];
194 + const projects = getPath(encoded, ["projectSettingsOverrides"]);
195 + const projectTargets = isRecord(projects)
196 + ? Object.entries(projects)
197 + .filter(([, overrides]) => isRecord(overrides) && overrides[head] !== undefined)
198 + .map(([projectId]) => ["projectSettingsOverrides", projectId, ...entry.segments])
199 + : [];
200 + return [entry.segments, ...projectTargets];
201 +};
202 +
203 +/**
204 + * A user's stored default runtime mode can sit above a ceiling deployed after it was chosen, and
205 + * the built-in default is the broadest mode. Every new thread would then be refused, so the
206 + * effective default is the ceiling instead. The stored value is untouched and returns with the
207 + * policy's removal; existing threads keep their modes and are refused turns instead.
208 + */
209 +const clampDefaultRuntimeModes = (
210 + settings: ServerSettings,
211 + ceiling: RuntimeMode,
212 +): ServerSettings => {
213 + const projectsAbove = Object.entries(settings.projectSettingsOverrides).filter(
214 + ([, overrides]) =>
215 + overrides.defaultRuntimeMode !== undefined &&
216 + isRuntimeModeAbove(overrides.defaultRuntimeMode, ceiling),
217 + );
218 + if (!isRuntimeModeAbove(settings.defaultRuntimeMode, ceiling) && projectsAbove.length === 0) {
219 + return settings;
220 + }
221 + return {
222 + ...settings,
223 + defaultRuntimeMode: isRuntimeModeAbove(settings.defaultRuntimeMode, ceiling)
224 + ? ceiling
225 + : settings.defaultRuntimeMode,
226 + projectSettingsOverrides: {
227 + ...settings.projectSettingsOverrides,
228 + ...Object.fromEntries(
229 + projectsAbove.map(([projectId, overrides]) => [
230 + projectId,
231 + { ...overrides, defaultRuntimeMode: ceiling },
232 + ]),
233 + ),
234 + },
235 + };
236 +};
237 +
238 +/** Build the overlay for a policy's settings, or describe the first entry this build cannot apply. */
239 +export function makeManagedSettings(
240 + settings: Readonly<Record<string, ManagedPolicySetting>>,
241 + maxRuntimeMode?: RuntimeMode,
242 +):
243 + | { readonly _tag: "Valid"; readonly settings: ManagedSettings }
244 + | { readonly _tag: "Invalid"; readonly reason: string } {
245 + const defaults: Entry[] = [];
246 + const locks: Entry[] = [];
247 + for (const [path, setting] of Object.entries(settings)) {
248 + const segments = path.split(".");
249 + const [head] = segments;
250 + if (head === undefined || segments.some((segment) => segment.length === 0)) {
251 + return { _tag: "Invalid", reason: `"${path}" is not a settings path` };
252 + }
253 + if (!(head in ServerSettings.fields) || UNMANAGEABLE_KEYS.has(head)) {
254 + return { _tag: "Invalid", reason: `"${path}" is not a setting this version can manage` };
255 + }
256 + const source = DERIVED_FROM.get(head);
257 + if (source !== undefined) {
258 + return {
259 + _tag: "Invalid",
260 + reason: `"${head}" follows "${source}"; manage "${source}" instead`,
261 + };
262 + }
263 + (setting.locked ? locks : defaults).push({ path, segments, value: setting.value });
264 + }
265 +
266 + for (const lock of locks) {
267 + const unheld = OVERRIDDEN_BY.find(
268 + ([overridden, by]) =>
269 + (lock.path.startsWith(overridden) || overridden.startsWith(`${lock.path}.`)) &&
270 + !locks.some((other) => other.path === by),
271 + );
272 + if (unheld !== undefined) {
273 + return {
274 + _tag: "Invalid",
275 + reason: `"${lock.path}" can be overridden by "${unheld[1]}"; lock "${unheld[1]}" too`,
276 + };
277 + }
278 + // An instance's fields override each other: a variable replaces launch arguments, a home
279 + // path rewrites a home variable, and a setup mode brings its own runtime.
280 + const [head, instanceId] = lock.segments;
281 + if (head === "providerInstances" && instanceId !== undefined && lock.segments.length > 2) {
282 + return {
283 + _tag: "Invalid",
284 + 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`,
285 + };
286 + }
287 + }
288 +
289 + // Apply every entry to the built-in defaults at once, and read each value back: a typo in a
290 + // nested key or a value of the wrong type does not survive the round trip.
291 + const builtIn = encodeSettings(DEFAULT_SERVER_SETTINGS);
292 + const all = [...defaults, ...locks];
293 + // A user's stored null would leave a nested lock building a partial object, so lock the whole
294 + // setting instead.
295 + const insideNullable = all.find((entry) =>
296 + entry.segments
297 + .slice(0, -1)
298 + .some((_, index) =>
299 + Exit.isSuccess(
300 + decodeSettingsExit(setPath(builtIn, entry.segments.slice(0, index + 1), null)),
301 + ),
302 + ),
303 + );
304 + if (insideNullable !== undefined) {
305 + return {
306 + _tag: "Invalid",
307 + reason: `"${insideNullable.path}" is inside a setting that can be empty; manage "${insideNullable.segments[0]}" as a whole`,
308 + };
309 + }
310 + const applied = all.reduce<unknown>(
311 + (tree, entry) => setPath(tree, entry.segments, entry.value),
312 + builtIn,
313 + );
314 + const decoded = decodeSettingsExit(applied);
315 + if (Exit.isFailure(decoded)) {
316 + return { _tag: "Invalid", reason: "a managed setting has a value of the wrong type" };
317 + }
318 + const roundTrip = encodeSettings(decoded.value);
319 + const lost = all.find((entry) => !jsonEqual(getPath(roundTrip, entry.segments), entry.value));
320 + if (lost !== undefined) {
321 + return {
322 + _tag: "Invalid",
323 + reason: `"${lost.path}" is not a setting this version can manage, or its value is invalid`,
324 + };
325 + }
326 + // The server moves a credential it finds in settings into the user's secret store, where a
327 + // policy's would outlive the policy. Built-in defaults hold none, so any found is the policy's.
328 + let holdsCredential = false;
329 + mapSettingsSecrets(decoded.value, (secret) => {
330 + if (secret.sensitive && !secret.redacted && secret.value.length > 0) holdsCredential = true;
331 + return secret;
332 + });
333 + if (holdsCredential) {
334 + return {
335 + _tag: "Invalid",
336 + reason:
337 + "a managed setting holds a credential, which every user can read in the policy; deploy credentials another way",
338 + };
339 + }
340 + // Defaults fill in what the file leaves out, so an entry a default adds to a record such as
341 + // `providerInstances` would come back each time the user removed it.
342 + const addsEntry = defaults.find((entry) => {
343 + const existing = getPath(builtIn, entry.segments);
344 + return existing === undefined ? entry.segments.length > 1 : addsKeys(existing, entry.value);
345 + });
346 + if (addsEntry !== undefined) {
347 + return {
348 + _tag: "Invalid",
349 + reason: `"${addsEntry.path}" adds entries users could not remove; lock it instead`,
350 + };
351 + }
352 + // A managed default above the ceiling would start every thread in a mode the policy refuses.
353 + if (
354 + all.some((entry) => entry.path === "defaultRuntimeMode") &&
355 + isRuntimeModeAbove(decoded.value.defaultRuntimeMode, maxRuntimeMode)
356 + ) {
357 + return {
358 + _tag: "Invalid",
359 + reason: `"defaultRuntimeMode" is above "limits.maxRuntimeMode"`,
360 + };
361 + }
362 +
363 + const defaultsTree = defaults.reduce<unknown>(
364 + (tree, entry) => setPath(tree, entry.segments, entry.value),
365 + {},
366 + );
367 + const lockEntries: ReadonlyArray<Lock> = locks.map((entry) => ({
368 + ...entry,
369 + decodedValue: getPath(decoded.value, entry.segments),
370 + }));
371 + const lockedPaths = locks.map((entry) => entry.path);
372 + const idleCompactionLocked = lockedPaths.includes("idleCompaction");
373 + const lockCache = new WeakMap<ServerSettings, ServerSettings>();
374 +
375 + const applyLocks = (current: ServerSettings): ServerSettings => {
376 + if (locks.length === 0 && maxRuntimeMode === undefined) return current;
377 + const cached = lockCache.get(current);
378 + if (cached !== undefined) return cached;
379 + const locked =
380 + locks.length === 0
381 + ? current
382 + : // Validated against the built-in defaults above, so a failure here is a bug, not bad input.
383 + decodeSettings(
384 + locks.reduce<unknown>(
385 + (tree, entry) =>
386 + lockTargets(tree, entry).reduce<unknown>(
387 + (next, target) => setPath(next, target, entry.value),
388 + tree,
389 + ),
390 + encodeSettings(current),
391 + ),
392 + );
393 + const derived = idleCompactionLocked ? syncIdleCompaction(locked) : locked;
394 + const result =
395 + maxRuntimeMode === undefined ? derived : clampDefaultRuntimeModes(derived, maxRuntimeMode);
396 + lockCache.set(current, result);
397 + return result;
398 + };
399 +
400 + const vetWrite: ManagedSettings["vetWrite"] = (current, next, patch) => {
401 + if (locks.length === 0) return { _tag: "Allowed", settings: next };
402 + const before = encodeSettings(current);
403 + const after = encodeSettings(next);
404 + const changed = lockEntries.find(
405 + (entry) =>
406 + // Re-sending a stored value the lock overrides changes nothing on disk, but it is still
407 + // an attempt to change what the user sees.
408 + lockTargets(patch, entry).some((target) => {
409 + const value = getPath(patch, target);
410 + return value !== undefined && !matchesLock(value, entry.decodedValue);
411 + }) ||
412 + lockTargets(after, entry).some((target) => {
413 + const value = getPath(after, target);
414 + // Removing a project's override of a locked key is harmless; the lock applies either way.
415 + return (
416 + value !== undefined &&
417 + !jsonEqual(value, getPath(before, target)) &&
418 + !matchesLock(value, entry.value)
419 + );
420 + }),
421 + );
422 + if (changed !== undefined) return { _tag: "Locked", path: changed.path };
423 + const kept = locks.reduce<unknown>(
424 + (tree, entry) =>
425 + lockTargets(tree, entry).reduce<unknown>((result, target) => {
426 + // A parent the write adds holds the locked value already; removing only the locked key
427 + // inside it would leave a partial object.
428 + const added = target
429 + .slice(0, -1)
430 + .some((_, index) => getPath(before, target.slice(0, index + 1)) === undefined);
431 + return added ? result : setPath(result, target, getPath(before, target));
432 + }, tree),
433 + after,
434 + );
435 + return { _tag: "Allowed", settings: decodeSettings(kept) };
436 + };
437 +
438 + // A file from before a setting replaced its legacy key holds the user's choice in that key, which
439 + // a default for the new setting would otherwise override.
440 + const withoutLegacyChoices = (persisted: unknown): unknown => {
441 + if (!isRecord(persisted) || !isRecord(defaultsTree)) return defaultsTree;
442 + const kept = { ...defaultsTree };
443 + for (const [legacy, source] of DERIVED_FROM) {
444 + if (persisted[legacy] !== undefined && persisted[source] === undefined) delete kept[source];
445 + }
446 + return kept;
447 + };
448 +
449 + // The paths keepStored puts back: each default, cut at an atomic setting, and the legacy key a
450 + // defaulted setting replaced, which an older file holds the user's choice in.
451 + const restoredPaths = (isAtomic: (key: string) => boolean): ReadonlyArray<Segments> => [
452 + ...defaults.map((entry) => {
453 + const atomicAt = entry.segments.findIndex(isAtomic);
454 + return atomicAt === -1 ? entry.segments : entry.segments.slice(0, atomicAt + 1);
455 + }),
456 + ...[...DERIVED_FROM]
457 + .filter(([, source]) => defaults.some((entry) => entry.path === source))
458 + .map(([legacy]) => [legacy]),
459 + ];
460 +
461 + const keepStored: ManagedSettings["keepStored"] =
462 + defaults.length === 0
463 + ? undefined
464 + : (stripped, settings, stored, isAtomic) => {
465 + const encoded = encodeSettings(settings);
466 + const restore = (tree: unknown, segments: Segments): unknown => {
467 + const previous = getPath(stored, segments);
468 + if (previous === undefined) return tree;
469 + if (isRecord(previous) && !isAtomic(segments.at(-1) ?? "")) {
470 + return Object.keys(previous).reduce<unknown>(
471 + (next, key) => restore(next, [...segments, key]),
472 + tree,
473 + );
474 + }
475 + return getPath(tree, segments) === undefined &&
476 + jsonEqual(previous, getPath(encoded, segments))
477 + ? setPath(tree, segments, getPath(settings, segments))
478 + : tree;
479 + };
480 + // A default inside an atomic setting restores that whole setting, never part of it.
481 + return restoredPaths(isAtomic).reduce<unknown>(restore, stripped);
482 + };
483 +
484 + return {
485 + _tag: "Valid",
486 + settings: {
487 + keepStored,
488 + withDefaults: (persisted) => fillMissing(persisted, withoutLegacyChoices(persisted)),
489 + defaults: syncIdleCompaction(
490 + decodeSettings(
491 + defaults.reduce<unknown>(
492 + (tree, entry) => setPath(tree, entry.segments, entry.value),
493 + builtIn,
494 + ),
495 + ),
496 + ),
497 + applyLocks,
498 + vetWrite,
499 + lockedPaths,
500 + },
501 + };
502 +}
apps/server/src/policy/managedUpdates.ts new
+24
@@ -0,0 +1,24 @@
1 +import {
2 + managedNightlyDeniedMessage,
3 + managedUpdatesMessage,
4 + type ManagedPolicyDocument,
5 +} from "@t3tools/contracts";
6 +import type { CliReleaseChannel } from "@t3tools/shared/cliRelease";
7 +
8 +/**
9 + * Why the managed policy refuses an update a user or maintainer asked for, or `undefined` when it
10 + * allows it. The server never updates on its own, so `auto` allows every explicit request.
11 + * Pass `targetChannel` when the caller picks the release; the desktop app gates its own channel.
12 + */
13 +export function managedUpdateRefusal(
14 + document: ManagedPolicyDocument | undefined,
15 + targetChannel?: CliReleaseChannel,
16 +): string | undefined {
17 + const updates = document?.limits?.updates;
18 + if (document === undefined || updates === undefined) return undefined;
19 + if (updates.mode === "off") return managedUpdatesMessage(document.organization);
20 + if (updates.allowNightly === false && targetChannel !== undefined && targetChannel !== "stable") {
21 + return managedNightlyDeniedMessage(document.organization);
22 + }
23 + return undefined;
24 +}
apps/server/src/project/AgentSessionImporter.test.ts
+33
@@ -1,6 +1,7 @@
1 import { expect, it } from "@effect/vitest";
2 import {
3 type AgentSessionSource,
4 + type ServerSettingsError,
5 EventId,
6 ProjectId,
7 ProviderDriverKind,
@@ -31,6 +32,7 @@ import {
32 } from "../orchestration-v2/testkit/fixtures/shared.ts";
33 import * as ProviderSessionRuntime from "../persistence/ProviderSessionRuntime.ts";
34 import * as SqlitePersistence from "../persistence/Sqlite.ts";
35 +import * as ServerSettings from "../serverSettings.ts";
36 import * as AgentSessionImporter from "./AgentSessionImporter.ts";
37 import * as AgentSessionScanner from "./AgentSessionScanner.ts";
38 import * as ProjectService from "./ProjectService.ts";
@@ -170,6 +172,10 @@ const seedOwner = Effect.fn(function* (
172 const makeImporter = Effect.fn(function* (
173 candidates: ReadonlyArray<ReturnType<typeof candidate>>,
174 beforeTransaction: Effect.Effect<void> = Effect.void,
175 + settings: Layer.Layer<
176 + ServerSettings.ServerSettingsService,
177 + ServerSettingsError
178 + > = ServerSettings.layerTest(),
179 ) {
180 const sql = yield* SqlClient.SqlClient;
181 const events = yield* EventStore.EventStoreV2;
@@ -205,6 +211,7 @@ const makeImporter = Effect.fn(function* (
211 Layer.provide(
212 Layer.mergeAll(
213 sinkLayer,
214 + settings,
215 Layer.succeed(IdAllocator.IdAllocatorV2, yield* IdAllocator.IdAllocatorV2),
216 Layer.succeed(
217 ProviderSessionRuntime.ProviderSessionRuntimeRepository,
@@ -416,3 +423,29 @@ it.effect(
423 });
424 }).pipe(Effect.scoped, Effect.provide(persistence)),
425 );
426 +
427 +it.effect("imports under a policy ceiling in the project's default, kept under the ceiling", () =>
428 + Effect.gen(function* () {
429 + const projections = yield* ProjectionStore.ProjectionStoreV2;
430 + const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
431 + const source = candidate(CODEX_MODEL_SELECTION, "ceiling");
432 + const threadId = importId(source);
433 + const importer = yield* makeImporter(
434 + [source],
435 + Effect.void,
436 + ServerSettings.layerTest(
437 + { defaultRuntimeMode: "full-access" },
438 + {
439 + organization: "Example Corp",
440 + lockedSettings: [],
441 + limits: { maxRuntimeMode: "auto-accept-edits" },
442 + },
443 + ),
444 + );
445 + expect(yield* importer.run).toEqual({ importedCount: 1, skippedCount: 0 });
446 + expect((yield* projections.getThread(threadId)).runtimeMode).toBe("auto-accept-edits");
447 + expect(Option.getOrThrow(yield* runtimes.getByThreadId({ threadId })).runtimeMode).toBe(
448 + "auto-accept-edits",
449 + );
450 + }).pipe(Effect.scoped, Effect.provide(persistence)),
451 +);
apps/server/src/project/AgentSessionImporter.ts
+22 -2
@@ -3,6 +3,7 @@ import {
3 DEFAULT_MODEL_BY_PROVIDER,
4 DEFAULT_PROVIDER_INTERACTION_MODE,
5 DEFAULT_RUNTIME_MODE,
6 + isRuntimeModeAbove,
7 AgentSessionImportProjectChangedError,
8 AgentSessionImportProjectNotFoundError,
9 AgentSessionImportSource,
@@ -23,6 +24,7 @@ import {
24 type OrchestrationV2TurnItem,
25 } from "@t3tools/contracts";
26 import { normalizeProjectPathForComparison } from "@t3tools/shared/path";
27 +import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
28 import * as Context from "effect/Context";
29 import * as DateTime from "effect/DateTime";
30 import * as Effect from "effect/Effect";
@@ -35,6 +37,7 @@ import * as EventSink from "../orchestration-v2/EventSink.ts";
37 import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
38 import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
39 import * as ProviderSessionRuntime from "../persistence/ProviderSessionRuntime.ts";
40 +import * as ServerSettings from "../serverSettings.ts";
41 import * as AgentSessionScanner from "./AgentSessionScanner.ts";
42 import * as ProjectService from "./ProjectService.ts";
43
@@ -172,6 +175,8 @@ const make = Effect.gen(function* () {
175 const eventSink = yield* EventSink.EventSinkV2;
176 const idAllocator = yield* IdAllocator.IdAllocatorV2;
177 const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
178 + const settingsService = yield* ServerSettings.ServerSettingsService;
179 + const ceiling = settingsService.managedPolicy?.limits?.maxRuntimeMode;
180 const importRecentAgentThreads = Effect.fn("importRecentAgentThreadsV2")(function* (
181 input: AgentSessionImportInput,
182 ) {
@@ -192,6 +197,21 @@ const make = Effect.gen(function* () {
197 ) {
198 return yield* new AgentSessionImportProjectChangedError({ projectId: input.projectId });
199 }
200 + // Imports run in full access, except under a policy ceiling: then in the project's default,
201 + // which the policy keeps under it, so imported threads never sit above the ceiling.
202 + const runtimeMode =
203 + ceiling === undefined
204 + ? DEFAULT_RUNTIME_MODE
205 + : yield* settingsService.getSettings.pipe(
206 + Effect.mapError(
207 + (cause) => new AgentSessionScanError({ operation: "read-settings", cause }),
208 + ),
209 + Effect.map((settings) => {
210 + const mode = resolveProjectSettings(settings, input.projectId, project).settings
211 + .defaultRuntimeMode;
212 + return isRuntimeModeAbove(mode, ceiling) ? ceiling : mode;
213 + }),
214 + );
215 const runtimeRows = yield* runtimes
216 .list()
217 .pipe(
@@ -259,7 +279,7 @@ const make = Effect.gen(function* () {
279 providerName: driver,
280 providerInstanceId: thread.providerInstanceId,
281 adapterKey: driver,
262 - runtimeMode: DEFAULT_RUNTIME_MODE,
282 + runtimeMode,
283 status: "stopped",
284 lastSeenAt: thread.updatedAt,
285 resumeCursor:
@@ -303,7 +323,7 @@ const make = Effect.gen(function* () {
323 title: thread.title.trim() === "" ? "Untitled thread" : thread.title,
324 providerInstanceId: thread.providerInstanceId,
325 modelSelection: { instanceId: thread.providerInstanceId, model },
306 - runtimeMode: DEFAULT_RUNTIME_MODE,
326 + runtimeMode,
327 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
328 branch: null,
329 worktreePath: null,
apps/server/src/provider/Drivers/CodexDriver.ts
+4 -1
@@ -150,7 +150,10 @@ export const CodexDriver: ProviderDriver<
150 const installation = yield* CodexInstallation.CodexInstallation;
151 const modelCatalog = yield* ModelCatalog.ModelCatalog;
152 const currentCatalog = modelCatalog.current(DRIVER_KIND);
153 - const processEnv = yield* mergeProviderInstanceEnvironment(environment);
153 + const processEnv = yield* mergeProviderInstanceEnvironment(
154 + environment,
155 + yield* HostProcess.Environment,
156 + );
157 const homeLayout = yield* resolveCodexHomeLayout(config);
158 const continuationIdentity = codexContinuationIdentity(homeLayout);
159 const stampIdentity = withInstanceIdentity({
apps/server/src/provider/ProviderInstanceRegistry.test.ts
+18
@@ -360,6 +360,24 @@ describe("ProviderInstanceRegistry — multi-instance codex slice", () => {
360 }).pipe(Effect.provide(layerTest)),
361 );
362
363 + it.live("lists a blocked driver's instances as unavailable without running them", () =>
364 + Effect.gen(function* () {
365 + const instanceId = ProviderInstanceId.make("codex");
366 + const reason = "Example Corp's policy does not allow the Codex provider.";
367 + const { registry } = yield* makeProviderInstanceRegistry({
368 + drivers: [CodexDriver],
369 + configMap: { [instanceId]: { driver: ProviderDriverKind.make("codex") } },
370 + blockedReason: (driver) => (driver === "codex" ? reason : undefined),
371 + });
372 +
373 + expect(yield* registry.getInstance(instanceId)).toBeUndefined();
374 + const [unavailable] = yield* registry.listUnavailable;
375 + expect(unavailable?.instanceId).toBe(instanceId);
376 + expect(unavailable?.availability).toBe("unavailable");
377 + expect(unavailable?.unavailableReason).toBe(reason);
378 + }).pipe(Effect.provide(layerTest)),
379 + );
380 +
381 it.live("runs Codex and Claude readiness probes from configured tilde paths", () =>
382 Effect.gen(function* () {
383 if (yield* HostProcess.isWindows) return;
apps/server/src/provider/ProviderInstanceRegistry.ts
+28 -2
@@ -129,6 +129,8 @@ const resolveEntryEnabled = (entry: ProviderInstanceConfig, typedConfig: unknown
129 return entry.enabled ?? providerInstanceConfigEnabledFlag(typedConfig) ?? true;
130 };
131
132 +type BlockedReason = (driver: ProviderDriverKind) => string | undefined;
133 +
134 // The enabled state `buildEntry` decodes, so a disabled instance never reads its secrets.
135 const isEntryEnabled = Effect.fn("ProviderInstanceRegistry.isEntryEnabled")(function* <R>(
136 driversById: ReadonlyMap<ProviderDriverKind, AnyProviderDriver<R>>,
@@ -143,6 +145,7 @@ const isEntryEnabled = Effect.fn("ProviderInstanceRegistry.isEntryEnabled")(func
145
146 const buildEntry = Effect.fn("ProviderInstanceRegistry.buildEntry")(function* <R>(input: {
147 readonly driversById: ReadonlyMap<ProviderDriverKind, AnyProviderDriver<R>>;
148 + readonly blockedReason: BlockedReason;
149 readonly parentScope: Scope.Scope;
150 readonly instanceId: ProviderInstanceId;
151 readonly rawInstanceId: string;
@@ -155,6 +158,19 @@ const buildEntry = Effect.fn("ProviderInstanceRegistry.buildEntry")(function* <R
158 R | SecretResolver.SecretResolver
159 > {
160 const { driversById, parentScope, instanceId, rawInstanceId, entry, deferSecrets } = input;
161 + const blocked = input.blockedReason(entry.driver);
162 + if (blocked !== undefined) {
163 + return {
164 + kind: "unavailable" as const,
165 + snapshot: yield* buildUnavailableProviderSnapshot({
166 + driverKind: entry.driver,
167 + instanceId,
168 + displayName: entry.displayName,
169 + accentColor: entry.accentColor,
170 + reason: blocked,
171 + }),
172 + };
173 + }
174 const driver = driversById.get(entry.driver);
175 if (!driver) {
176 return {
@@ -274,13 +290,14 @@ const buildEntry = Effect.fn("ProviderInstanceRegistry.buildEntry")(function* <R
290 const makeReconcile = <R>(input: {
291 readonly state: RegistryState;
292 readonly driversById: ReadonlyMap<ProviderDriverKind, AnyProviderDriver<R>>;
293 + readonly blockedReason: BlockedReason;
294 readonly parentScope: Scope.Scope;
295 }): ((
296 configMap: ProviderInstanceConfigMap,
297 rebuild?: ReadonlySet<ProviderInstanceId>,
298 deferSecrets?: boolean,
299 ) => Effect.Effect<void, never, R | SecretResolver.SecretResolver>) => {
283 - const { state, driversById, parentScope } = input;
300 + const { state, driversById, blockedReason, parentScope } = input;
301 return (configMap, rebuild = new Set(), deferSecrets = false) =>
302 Effect.gen(function* () {
303 const previousEntries = yield* Ref.get(state.entries);
@@ -351,6 +368,7 @@ const makeReconcile = <R>(input: {
368
369 const result = yield* buildEntry({
370 driversById,
371 + blockedReason,
372 parentScope,
373 instanceId,
374 rawInstanceId,
@@ -402,6 +420,8 @@ export const makeProviderInstanceRegistry = Effect.fn(
420 )(function* <R>(input: {
421 readonly drivers: ReadonlyArray<AnyProviderDriver<R>>;
422 readonly configMap: ProviderInstanceConfigMap;
423 + /** A reason to show instead of running a driver, such as an administrator's policy. */
424 + readonly blockedReason?: BlockedReason | undefined;
425 }): Effect.fn.Return<
426 {
427 readonly registry: ProviderInstanceRegistry["Service"];
@@ -428,7 +448,12 @@ export const makeProviderInstanceRegistry = Effect.fn(
448 yield* Effect.addFinalizer(() => PubSub.shutdown(changes));
449
450 const state: RegistryState = { entries, unavailable, changes };
431 - const reconcileWithR = makeReconcile({ state, driversById, parentScope });
451 + const reconcileWithR = makeReconcile({
452 + state,
453 + driversById,
454 + blockedReason: input.blockedReason ?? (() => undefined),
455 + parentScope,
456 + });
457 const configMapRef = yield* Ref.make(input.configMap);
458 const semaphore = yield* Semaphore.make(1);
459 const reconcile: ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutatorShape["reconcile"] =
@@ -535,6 +560,7 @@ export const makeProviderInstanceRegistry = Effect.fn(
560 export const layer = <R>(input: {
561 readonly drivers: ReadonlyArray<AnyProviderDriver<R>>;
562 readonly configMap: ProviderInstanceConfigMap;
563 + readonly blockedReason?: BlockedReason | undefined;
564 }): Layer.Layer<
565 ProviderInstanceRegistry | ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutator,
566 never,
apps/server/src/provider/ProviderInstanceRegistryHydration.ts
+11
@@ -16,6 +16,7 @@ import * as Layer from "effect/Layer";
16 import * as Path from "effect/Path";
17 import * as Stream from "effect/Stream";
18
19 +import * as ManagedProviders from "../policy/managedProviders.ts";
20 import * as Settings from "../serverSettings.ts";
21 import * as SecretResolver from "../secrets/SecretResolver.ts";
22 import { BUILT_IN_DRIVERS, type BuiltInDriversEnv } from "./builtInDrivers.ts";
@@ -165,13 +166,23 @@ export const layer: Layer.Layer<
166 ? ({} as ProviderInstanceConfigMap)
167 : deriveProviderInstanceConfigMap(initialSettings);
168
169 + // Drivers launch from the host environment, minus launch overrides a policy ignores.
170 + const hostEnvironment = ManagedProviders.providerHostEnvironment(
171 + serverSettings.managedPolicy,
172 + yield* HostProcess.Environment,
173 + );
174 + // Instances of drivers the policy leaves out stay listed, as unavailable, so their threads
175 + // explain why instead of losing their provider.
176 const layerMutable = ProviderInstanceRegistry.layer({
177 drivers: BUILT_IN_DRIVERS,
178 configMap: initialConfigMap,
179 + blockedReason: (driver) =>
180 + ManagedProviders.disallowedDriverReason(serverSettings.managedPolicy, driver),
181 }).pipe(
182 Layer.provide(ProviderOrchestrationAdapterInfrastructure.layer),
183 Layer.provide(AcpRegistrySupport.layerFromHost),
184 Layer.provide(ProviderHostLive.layer),
185 + Layer.provide(Layer.succeed(HostProcess.Environment, hostEnvironment)),
186 Layer.provide(SecretResolver.layer),
187 );
188
apps/server/src/provider/acp/AntigravityAcpSupport.ts
+14
@@ -92,6 +92,20 @@ export function antigravityPermissionMode(runtimeMode: RuntimeMode): string {
92 }
93 }
94
95 +/** The runtime mode an Antigravity session mode grants; the inverse of `antigravityPermissionMode`. */
96 +export function antigravityRuntimeModeForSessionMode(modeId: string): RuntimeMode | undefined {
97 + switch (modeId) {
98 + case "yolo":
99 + return "full-access";
100 + case "auto_edit":
101 + return "auto-accept-edits";
102 + case "default":
103 + return "approval-required";
104 + default:
105 + return undefined;
106 + }
107 +}
108 +
109 export function antigravityModelOptions(
110 configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption>,
111 ) {
apps/server/src/scheduledTasks/ScheduledTaskService.interval.test.ts
+2
@@ -16,12 +16,14 @@ import * as Scheduler from "../scheduling/Scheduler.ts";
16 import * as SecretRequests from "../secrets/SecretRequests.ts";
17 import { ServerActivation } from "../serverActivation.ts";
18 import * as ScheduledTaskService from "./ScheduledTaskService.ts";
19 +import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
20
21 afterEach(() => vi.unstubAllEnvs());
22
23 const dependencies = Layer.mergeAll(
24 NodeCrypto.layer,
25 Scheduler.layer,
26 + ManagedPolicy.layerTest(),
27 Layer.mock(ThreadLaunchService.ThreadLaunchService)({
28 launch: () => Effect.die("synthetic dispatch failure"),
29 }),
apps/server/src/scheduledTasks/ScheduledTaskService.schedule.test.ts
+5
@@ -15,6 +15,7 @@ import * as SecretRequests from "../secrets/SecretRequests.ts";
15 import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts";
16 import * as SqlitePersistence from "../persistence/Sqlite.ts";
17 import * as ScheduledTaskService from "./ScheduledTaskService.ts";
18 +import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
19
20 const decodeUpsertInput = Schema.decodeUnknownEffect(ScheduledTaskUpsertInput);
21
@@ -23,6 +24,7 @@ it.effect("rejects a stale form save after deletion while preserving explicit-id
24 const layerDependencies = Layer.mergeAll(
25 NodeCrypto.layer,
26 Scheduler.layer,
27 + ManagedPolicy.layerTest(),
28 Layer.mock(ThreadLaunchService.ThreadLaunchService)({}),
29 Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({
30 namedProjectsRoot: "/projects",
@@ -70,6 +72,7 @@ it.effect("preserves a due run when a save only pads the scheduled hour", () =>
72 const layerDependencies = Layer.mergeAll(
73 NodeCrypto.layer,
74 Scheduler.layer,
75 + ManagedPolicy.layerTest(),
76 Layer.mock(ThreadLaunchService.ThreadLaunchService)({}),
77 Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({
78 namedProjectsRoot: "/projects",
@@ -124,6 +127,7 @@ it.effect("keeps the task list order when a toggle or edit rewrites updated_at",
127 const layerDependencies = Layer.mergeAll(
128 NodeCrypto.layer,
129 Scheduler.layer,
130 + ManagedPolicy.layerTest(),
131 Layer.mock(ThreadLaunchService.ThreadLaunchService)({}),
132 Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({
133 namedProjectsRoot: "/projects",
@@ -178,6 +182,7 @@ it.effect(
182 const layerDependencies = Layer.mergeAll(
183 NodeCrypto.layer,
184 Scheduler.layer,
185 + ManagedPolicy.layerTest(),
186 Layer.mock(ThreadLaunchService.ThreadLaunchService)({
187 launch: (input) =>
188 Deferred.succeed(launched, input.title).pipe(
apps/server/src/scheduledTasks/ScheduledTaskService.test.ts
+72
@@ -30,6 +30,7 @@ import * as SecretRequests from "../secrets/SecretRequests.ts";
30 import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts";
31 import * as SqlitePersistence from "../persistence/Sqlite.ts";
32 import * as ScheduledTaskService from "./ScheduledTaskService.ts";
33 +import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
34
35 const isScheduledTaskError = Schema.is(ScheduledTaskError);
36
@@ -190,6 +191,7 @@ it.effect(
191 Layer.provideMerge(
192 ScheduledTaskService.layer,
193 Layer.mergeAll(
194 + ManagedPolicy.layerTest(),
195 Layer.mock(ThreadLaunchService.ThreadLaunchService)({
196 launch: () =>
197 Ref.updateAndGet(dispatched, (n) => n + 1).pipe(
@@ -283,6 +285,7 @@ it.effect(
285 Layer.provideMerge(
286 ScheduledTaskService.layer,
287 Layer.mergeAll(
288 + ManagedPolicy.layerTest(),
289 Layer.mock(ThreadLaunchService.ThreadLaunchService)({
290 launch: () =>
291 Ref.updateAndGet(dispatched, (n) => n + 1).pipe(
@@ -347,6 +350,7 @@ it.effect("thread cleanup notifies subscribers and a finishing run cannot recrea
350 const layer = ScheduledTaskService.layer.pipe(
351 Layer.provide(
352 Layer.mergeAll(
353 + ManagedPolicy.layerTest(),
354 Layer.mock(ThreadLaunchService.ThreadLaunchService)({}),
355 Layer.mock(ThreadManagementService.ThreadManagementService)({
356 sendToThread: () =>
@@ -414,6 +418,7 @@ it.effect("a bound run follows its thread when promotion moves it mid-send", ()
418 const layer = ScheduledTaskService.layer.pipe(
419 Layer.provide(
420 Layer.mergeAll(
421 + ManagedPolicy.layerTest(),
422 Layer.mock(ThreadLaunchService.ThreadLaunchService)({}),
423 Layer.mock(ThreadManagementService.ThreadManagementService)({
424 sendToThread: (input) =>
@@ -478,12 +483,79 @@ it.effect("a bound run follows its thread when promotion moves it mid-send", ()
483 }).pipe(Effect.provide(SqlitePersistence.layerMemory)),
484 );
485
486 +it.effect("refuses saving an enabled task above the policy ceiling", () =>
487 + Effect.gen(function* () {
488 + const layer = ScheduledTaskService.layer.pipe(
489 + Layer.provide(
490 + Layer.mergeAll(
491 + ManagedPolicy.layerTest({
492 + schemaVersion: 1,
493 + organization: "Example Corp",
494 + limits: { maxRuntimeMode: "auto-accept-edits" },
495 + }),
496 + Layer.mock(ThreadLaunchService.ThreadLaunchService)({}),
497 + Layer.mock(ThreadManagementService.ThreadManagementService)({}),
498 + Layer.mock(SecretRequests.SecretRequests)({}),
499 + Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({
500 + namedProjectsRoot: "/projects",
501 + isScratchProject: () => Effect.succeed(false),
502 + }),
503 + NodeCrypto.layer,
504 + Scheduler.layer,
505 + ),
506 + ),
507 + );
508 + yield* Effect.gen(function* () {
509 + const service = yield* ScheduledTaskService.ScheduledTaskService;
510 + const save = (enabled: boolean) =>
511 + service.upsert({
512 + id: ScheduledTaskId.make("task:above-ceiling"),
513 + title: "Nightly",
514 + prompt: "Check progress",
515 + enabled,
516 + schedule: { type: "interval", everyMs: 60_000 },
517 + projectId: ProjectId.make("project:test"),
518 + workspaceStrategy: { type: "root" },
519 + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
520 + runtimeMode: "full-access",
521 + interactionMode: "default",
522 + });
523 + const refused = yield* save(true).pipe(Effect.flip);
524 + assert.equal(refused.message, "Example Corp limits threads to Auto-accept edits.");
525 + assert.lengthOf((yield* service.list()).tasks, 0);
526 + // A disabled task does not run, so it can still be saved.
527 + yield* save(false);
528 + assert.lengthOf((yield* service.list()).tasks, 1);
529 + // Nor can it be switched back on while its mode is above the ceiling.
530 + const reenabled = yield* service
531 + .setEnabled({ id: ScheduledTaskId.make("task:above-ceiling"), enabled: true })
532 + .pipe(Effect.flip);
533 + assert.equal(reenabled.message, "Example Corp limits threads to Auto-accept edits.");
534 + // A task bound to a thread runs in that thread's mode, so its own is not checked.
535 + yield* service.upsert({
536 + id: ScheduledTaskId.make("task:bound"),
537 + title: "Follow up",
538 + prompt: "Check progress",
539 + enabled: true,
540 + schedule: { type: "interval", everyMs: 60_000 },
541 + projectId: ProjectId.make("project:test"),
542 + threadId: ThreadId.make("thread:bound"),
543 + workspaceStrategy: { type: "root" },
544 + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
545 + runtimeMode: "full-access",
546 + interactionMode: "default",
547 + });
548 + }).pipe(Effect.provide(layer));
549 + }).pipe(Effect.provide(SqlitePersistence.layerMemory)),
550 +);
551 +
552 it.effect("a run interrupted right after it reserves the task does not block the next run", () =>
553 Effect.gen(function* () {
554 const launches = yield* Ref.make(0);
555 const layer = ScheduledTaskService.layer.pipe(
556 Layer.provide(
557 Layer.mergeAll(
558 + ManagedPolicy.layerTest(),
559 Layer.mock(ThreadLaunchService.ThreadLaunchService)({
560 launch: () =>
561 Ref.update(launches, (n) => n + 1).pipe(
apps/server/src/scheduledTasks/ScheduledTaskService.ts
+64 -5
@@ -23,6 +23,8 @@ import {
23 type ScheduledTaskRunNowResult,
24 type ScheduledTaskSetEnabledInput,
25 type ScheduledTaskUpsertInput,
26 + managedPolicyDeniedMessage,
27 + managedRuntimeModeDenial,
28 } from "@t3tools/contracts";
29 import * as Cause from "effect/Cause";
30 import * as Context from "effect/Context";
@@ -49,6 +51,7 @@ import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts";
51 import * as Metrics from "../observability/Metrics.ts";
52 import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
53 import * as SecretRequests from "../secrets/SecretRequests.ts";
54 +import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
55 import * as DueHint from "../scheduling/DueHint.ts";
56 import * as Scheduler from "../scheduling/Scheduler.ts";
57 import { isMissedFixedTimeRun, isSameSchedule, nextScheduledRunAt } from "./Schedule.ts";
@@ -145,6 +148,7 @@ export type WebhookDeliveryOutcome =
148 | "expired"
149 | "filtered"
150 | "not_found"
151 + | "blocked_by_policy"
152 | "error";
153
154 export type WebhookTriggerResult =
@@ -156,6 +160,7 @@ export type WebhookTriggerResult =
160 | { readonly _tag: "not_found" }
161 | { readonly _tag: "rejected_signature" }
162 | { readonly _tag: "disabled" }
163 + | { readonly _tag: "blocked_by_policy" }
164 | {
165 readonly _tag: "rate_limited";
166 readonly outcome: "rate_limited" | "queue_full";
@@ -437,6 +442,17 @@ export const layer = Layer.effect(
442 const secretRequests = yield* SecretRequests.SecretRequests;
443 const scheduler = yield* Scheduler.Scheduler;
444 const readWebhookOrigin = yield* ScheduledTaskWebhookOrigin;
445 + const managedPolicy = yield* ManagedPolicy.ManagedPolicy;
446 + const webhookPolicyOrganization = ManagedPolicy.deniedBy(managedPolicy, "webhookTasks");
447 + // Existing webhook tasks stay stored but report why they do not run.
448 + const webhookPolicyBlock =
449 + webhookPolicyOrganization === undefined
450 + ? undefined
451 + : managedPolicyDeniedMessage(webhookPolicyOrganization, "webhook tasks");
452 + const withPolicy = (task: ScheduledTask): ScheduledTask =>
453 + webhookPolicyBlock !== undefined && task.schedule.type === "webhook"
454 + ? { ...task, blockedByPolicy: webhookPolicyBlock }
455 + : task;
456 const webhookPermits = yield* Ref.make<ReadonlyMap<ScheduledTaskId, Semaphore.Semaphore>>(
457 new Map(),
458 );
@@ -498,7 +514,11 @@ export const layer = Layer.effect(
514 const listRows = Effect.fn("ScheduledTaskService.listRows")(function* () {
515 const rows = yield* selectAllRows();
516 const origin = yield* readWebhookOrigin;
501 - return yield* Effect.forEach(rows, (row) => decodeRow(row, origin), { concurrency: 1 });
517 + return yield* Effect.forEach(
518 + rows,
519 + (row) => decodeRow(row, origin).pipe(Effect.map(withPolicy)),
520 + { concurrency: 1 },
521 + );
522 });
523
524 const getRows = (id: ScheduledTaskId) =>
@@ -538,7 +558,7 @@ export const layer = Layer.effect(
558 );
559 const row = rows[0];
560 if (row === undefined) return null;
541 - return yield* decodeRow(row, yield* readWebhookOrigin);
561 + return withPolicy(yield* decodeRow(row, yield* readWebhookOrigin));
562 });
563
564 const findWebhookCredentials = (id: ScheduledTaskId) =>
@@ -828,9 +848,11 @@ export const layer = Layer.effect(
848 ? "The task was replaced before this delivery ran."
849 : active.schedule.type !== "webhook"
850 ? "The task's trigger changed before this delivery ran."
831 - : !active.enabled
832 - ? "The task was paused before this delivery ran."
833 - : null;
851 + : webhookPolicyBlock !== undefined
852 + ? webhookPolicyBlock
853 + : !active.enabled
854 + ? "The task was paused before this delivery ran."
855 + : null;
856 if (reason !== null) return yield* new WebhookDeliverySkipped({ reason });
857 }
858
@@ -1177,6 +1199,23 @@ export const layer = Layer.effect(
1199 const upsert: ScheduledTaskService["Service"]["upsert"] = Effect.fn(
1200 "ScheduledTaskService.upsert",
1201 )(function* (input) {
1202 + // A webhook task the policy blocks can still be edited while it is off.
1203 + if (input.enabled && input.schedule.type === "webhook" && webhookPolicyBlock !== undefined) {
1204 + return yield* taskError(
1205 + webhookPolicyBlock,
1206 + input.id === undefined ? {} : { taskId: input.id },
1207 + );
1208 + }
1209 + // Refused on save rather than at run time; a disabled task can still be saved, so one
1210 + // stored above the ceiling can be turned off before its mode is lowered. A task bound to a
1211 + // thread runs in that thread's mode, which the orchestrator checks instead.
1212 + const modeDenial =
1213 + input.enabled && input.threadId == null
1214 + ? managedRuntimeModeDenial(managedPolicy.summary, input.runtimeMode)
1215 + : undefined;
1216 + if (modeDenial !== undefined) {
1217 + return yield* taskError(modeDenial, input.id === undefined ? {} : { taskId: input.id });
1218 + }
1219 const now = yield* localNow;
1220 const uuid =
1221 input.commandId === undefined
@@ -1317,6 +1356,20 @@ export const layer = Layer.effect(
1356 )(function* (input) {
1357 const existing = yield* loadTask(input.id);
1358 if (existing.enabled === input.enabled) return { task: existing };
1359 + if (
1360 + input.enabled &&
1361 + existing.schedule.type === "webhook" &&
1362 + webhookPolicyBlock !== undefined
1363 + ) {
1364 + return yield* taskError(webhookPolicyBlock, { taskId: input.id });
1365 + }
1366 + const modeDenial =
1367 + input.enabled && existing.threadId === null
1368 + ? managedRuntimeModeDenial(managedPolicy.summary, existing.runtimeMode)
1369 + : undefined;
1370 + if (modeDenial !== undefined) {
1371 + return yield* taskError(modeDenial, { taskId: input.id });
1372 + }
1373 const now = yield* localNow;
1374 yield* requireFutureOnce(
1375 { enabled: input.enabled, schedule: existing.schedule },
@@ -1851,6 +1904,12 @@ export const layer = Layer.effect(
1904
1905 // triggerWebhook owns the operation span and its task-id annotation.
1906 const triggerWebhookUnobserved = Effect.fnUntraced(function* (request: WebhookTriggerRequest) {
1907 + // Refused before any lookup or log, so a blocked hook neither runs nor records a delivery.
1908 + if (webhookPolicyBlock !== undefined) {
1909 + return yield* observeDelivery(request, "blocked_by_policy", undefined, undefined).pipe(
1910 + Effect.as({ _tag: "blocked_by_policy" as const }),
1911 + );
1912 + }
1913 const taskId = decodeTaskId(request.hookId);
1914 const notFound = observeDelivery(request, "not_found", undefined, undefined).pipe(
1915 Effect.as({ _tag: "not_found" as const }),
apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts
+60
@@ -4,6 +4,7 @@ import * as NodeCrypto from "node:crypto";
4 import * as NodePlatformCrypto from "@effect/platform-node/NodeCrypto";
5 import { assert, it } from "@effect/vitest";
6 import {
7 + type ManagedPolicyDocument,
8 ScheduledTaskUpsertInput,
9 ScheduledTaskWebhookDeliveryId,
10 SecretRequestError,
@@ -23,6 +24,7 @@ import * as TestClock from "effect/testing/TestClock";
24 import * as Tracer from "effect/Tracer";
25
26 import * as ThreadLaunchService from "../orchestration-v2/ThreadLaunchService.ts";
27 +import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
28 import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
29 import * as SecretRequests from "../secrets/SecretRequests.ts";
30 import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts";
@@ -173,6 +175,7 @@ const withService = <A, E>(
175 readonly relayHookBaseUrl?: string;
176 readonly sql?: SqlClient.SqlClient;
177 readonly workers?: Map<string, Effect.Effect<void>>;
178 + readonly policy?: ManagedPolicyDocument;
179 } = {},
180 ) =>
181 Effect.gen(function* () {
@@ -249,6 +252,7 @@ const withService = <A, E>(
252 ScheduledTaskService.ScheduledTaskWebhookOrigin,
253 Effect.succeed({ relayHookBaseUrl: options.relayHookBaseUrl ?? null }),
254 ),
255 + ManagedPolicy.layerTest(options.policy),
256 );
257 return yield* Effect.gen(function* () {
258 const service = yield* ScheduledTaskService.ScheduledTaskService;
@@ -427,6 +431,62 @@ it.effect("checks the configured signature and keeps the secret write-only", ()
431 ),
432 );
433
434 +it.effect("a policy without webhook tasks keeps existing ones but refuses saves and requests", () =>
435 + withService(({ service, sql }) =>
436 + Effect.gen(function* () {
437 + const { task } = yield* service.upsert(yield* webhookTaskInput());
438 + const timer = yield* webhookTaskInput({
439 + id: "scheduled-task:timer",
440 + schedule: { type: "interval", everyMs: 3_600_000 },
441 + });
442 + yield* withService(
443 + ({ service, launches }) =>
444 + Effect.gen(function* () {
445 + const blocked = "Example Corp's policy does not allow webhook tasks.";
446 + const listed = (yield* service.list()).tasks.find(({ id }) => id === task.id);
447 + assert.equal(listed?.blockedByPolicy, blocked);
448 + assert.isTrue(listed?.enabled);
449 +
450 + const refused = yield* service.upsert(yield* webhookTaskInput()).pipe(Effect.flip);
451 + assert.equal(refused.message, blocked);
452 + const created = yield* service
453 + .upsert(yield* webhookTaskInput({ id: "scheduled-task:new-hook" }))
454 + .pipe(Effect.flip);
455 + assert.equal(created.message, blocked);
456 +
457 + // Turned off, it can still be edited, but not turned back on.
458 + yield* service.setEnabled({ id: task.id, enabled: false });
459 + yield* service.upsert(yield* webhookTaskInput({ enabled: false }));
460 + const reenabled = yield* service
461 + .setEnabled({ id: task.id, enabled: true })
462 + .pipe(Effect.flip);
463 + assert.equal(reenabled.message, blocked);
464 +
465 + const result = yield* service.triggerWebhook(requestFor(task));
466 + assert.equal(result._tag, "blocked_by_policy");
467 + assert.equal(yield* Queue.size(launches), 0);
468 + assert.equal((yield* sql`SELECT * FROM scheduled_task_webhook_deliveries`).length, 0);
469 +
470 + // Timer tasks are unaffected, including a webhook task switched to a timer.
471 + assert.isUndefined((yield* service.upsert(timer)).task.blockedByPolicy);
472 + const switched = yield* service.upsert(
473 + yield* webhookTaskInput({ schedule: { type: "interval", everyMs: 3_600_000 } }),
474 + );
475 + assert.isUndefined(switched.task.blockedByPolicy);
476 + }),
477 + {
478 + sql,
479 + policy: {
480 + schemaVersion: 1,
481 + organization: "Example Corp",
482 + limits: { webhookTasks: false },
483 + },
484 + },
485 + );
486 + }),
487 + ),
488 +);
489 +
490 it.effect("logs but does not run deliveries to a disabled task, and refuses run now", () =>
491 withService(({ service, launches }) =>
492 Effect.gen(function* () {
apps/server/src/scheduledTasks/webhookRoute.test.ts
+1
@@ -197,6 +197,7 @@ describe("webhook route", () => {
197 [{ _tag: "not_found" }, 404, "not_found"],
198 [{ _tag: "rejected_signature" }, 401, "rejected_signature"],
199 [{ _tag: "disabled" }, 409, "disabled"],
200 + [{ _tag: "blocked_by_policy" }, 403, "blocked_by_policy"],
201 [{ _tag: "rate_limited", outcome: "rate_limited" }, 429, "rate_limited"],
202 [{ _tag: "rate_limited", outcome: "queue_full" }, 429, "queue_full"],
203 [{ _tag: "expired" }, 410, "expired"],
apps/server/src/scheduledTasks/webhookRoute.ts
+2
@@ -131,6 +131,8 @@ export const layer = HttpApiBuilder.group(
131 return json(401, { error: "invalid_signature" }, "rejected_signature");
132 case "disabled":
133 return json(409, { error: "hook_disabled" }, "disabled");
134 + case "blocked_by_policy":
135 + return json(403, { error: "blocked_by_policy" }, "blocked_by_policy");
136 case "rate_limited":
137 return json(429, { error: result.outcome }, result.outcome);
138 case "expired":
apps/server/src/server.ts
+98 -13
@@ -94,6 +94,8 @@ import * as ServerOwnership from "./serverOwnership.ts";
94 import * as AgentAwarenessRelay from "./relay/AgentAwarenessRelay.ts";
95 import { hasCloudPublicConfig } from "./cloud/publicConfig.ts";
96 import * as ServerSettings from "./serverSettings.ts";
97 +import * as ManagedLimits from "./policy/managedLimits.ts";
98 +import * as ManagedPolicy from "./policy/ManagedPolicy.ts";
99 import * as ProjectEnrichmentService from "./project/ProjectEnrichmentService.ts";
100 import * as NativeAppIconResolver from "./assets/NativeAppIconResolver.ts";
101 import * as AntigravityInstallation from "./provider/AntigravityInstallation.ts";
@@ -149,6 +151,7 @@ import {
151 RELAY_URL_SECRET,
152 } from "./cloud/config.ts";
153 import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
154 +import * as EnvironmentAuthPolicy from "./auth/EnvironmentAuthPolicy.ts";
155 import * as CloudHttp from "./cloud/http.ts";
156 import * as GuestHttp from "./guest/http.ts";
157 import * as CloudLink from "./cloud/CloudLink.ts";
@@ -202,7 +205,12 @@ import * as OrchestrationHttp from "./orchestration-v2/http.ts";
205 import * as ProjectHttp from "./project/http.ts";
206 import * as NetService from "@t3tools/shared/Net";
207 import * as RelayClient from "@t3tools/shared/relayClient";
205 -import { disableTailscaleServe, ensureTailscaleServe } from "@t3tools/tailscale";
208 +import {
209 + disableTailscaleServe,
210 + ensureTailscaleServe,
211 + readTailscaleServeRoutesTo,
212 + readTailscaleStatus,
213 +} from "@t3tools/tailscale";
214 import * as ServerActivation from "./serverActivation.ts";
215
216 // Escaped MCP handoff provenance can exceed find-my-way's 100-character segment default.
@@ -244,6 +252,7 @@ const layerPtyAdapter = NodePtyAdapter.layer;
252
253 const layerServerSettings = ServerSettings.layer.pipe(
254 Layer.provide(ServerSecretStore.layer),
255 + Layer.provideMerge(ManagedPolicy.layer),
256 Layer.provideMerge(SqlitePersistence.layerConfig),
257 );
258
@@ -298,13 +307,42 @@ const layerResourceDiagnostics = Layer.mergeAll(
307 const layerRelayClient = Layer.unwrap(
308 Effect.gen(function* () {
309 const config = yield* ServerConfig.ServerConfig;
301 - return RelayClient.layerCloudflared({ baseDir: config.baseDir });
310 + const policy = yield* ManagedPolicy.ManagedPolicy;
311 + const layerCloudflared = RelayClient.layerCloudflared({ baseDir: config.baseDir });
312 + if (ManagedLimits.allowsConnect(policy)) return layerCloudflared;
313 + // The connector only carries T3 Connect, so a policy without Connect never installs one.
314 + const refused = Effect.fn("RelayClient.installRefusedByPolicy")(function* () {
315 + return yield* new RelayClient.RelayClientInstallError({
316 + reason: "managed_by_policy",
317 + message: ManagedLimits.refuseConnect(policy).message,
318 + });
319 + });
320 + return Layer.effect(
321 + RelayClient.RelayClient,
322 + Effect.gen(function* () {
323 + const relayClient = yield* RelayClient.RelayClient;
324 + return RelayClient.RelayClient.of({
325 + ...relayClient,
326 + install: refused(),
327 + installWithProgress: refused,
328 + });
329 + }),
330 + ).pipe(Layer.provide(layerCloudflared));
331 }),
303 -);
332 +).pipe(Layer.provide(ManagedPolicy.layer));
333
334 const layerHttpServer = Layer.unwrap(
335 Effect.gen(function* () {
336 const config = yield* ServerConfig.ServerConfig;
337 + // Before binding: a host the policy does not allow must never listen, not even briefly.
338 + const policy = yield* ManagedPolicy.ManagedPolicy;
339 + const bindHost = yield* ManagedLimits.checkServerReachability(policy, {
340 + authPolicy: EnvironmentAuthPolicy.resolveServerAuthPolicy(config),
341 + host: config.host,
342 + tailscaleServeEnabled: config.tailscaleServeEnabled,
343 + privateNetworkOnly: config.privateNetworkOnly,
344 + });
345 + yield* ManagedLimits.closeTailscaleServeTo(policy, { host: bindHost, port: config.port });
346 return NodeHttpServer.layer(
347 () => {
348 const server = rejectRequestsUntilServing(
@@ -320,7 +358,7 @@ const layerHttpServer = Layer.unwrap(
358 return server;
359 },
360 {
323 - host: config.host ?? "127.0.0.1",
361 + host: bindHost,
362 port: config.port,
363 gracefulShutdownTimeout: HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS,
364 // Context takeover stays enabled (ws default) so the compression
@@ -331,7 +369,7 @@ const layerHttpServer = Layer.unwrap(
369 },
370 );
371 }),
334 -);
372 +).pipe(Layer.provide(ManagedPolicy.layer));
373
374 const layerPlatformServices = DocumentText.layer.pipe(Layer.provideMerge(NodeServices.layer));
375
@@ -701,7 +739,8 @@ const layerRuntimeDependencies = layerRuntimeCoreDependencies.pipe(
739 Layer.provideMerge(layerResourceDiagnostics),
740 Layer.provideMerge(TraceDiagnostics.layer),
741 Layer.provideMerge(TriageService.layer.pipe(Layer.provide(GitVcsDriver.layer))),
704 - Layer.provideMerge(AnalyticsService.layer),
742 + // Layers memoize by reference, so this is the same policy the settings layer reads.
743 + Layer.provideMerge(AnalyticsService.layer.pipe(Layer.provide(ManagedPolicy.layer))),
744 Layer.provideMerge(ExternalLauncher.layer),
745 Layer.provideMerge(RemoteOpenTargets.layer),
746 Layer.provideMerge(DirectEndpoints.layer),
@@ -816,6 +855,7 @@ const layerMakeServer = Layer.unwrap(
855 config,
856 port: address.port,
857 serviceManaged: launcher.managed,
858 + managedPolicy: yield* ManagedPolicy.loadedPolicy(yield* ManagedPolicy.ManagedPolicy),
859 });
860 yield* ownership
861 .publish(state)
@@ -839,12 +879,17 @@ const layerMakeServer = Layer.unwrap(
879 }
880
881 const localPort = address.port;
882 + const localHost = loopbackUrlHostForAddress(address);
883 return yield* ensureTailscaleServe({
884 localPort,
885 servePort: config.tailscaleServePort,
845 - localHost: loopbackUrlHostForAddress(address),
886 + localHost,
887 }).pipe(
847 - Effect.as({ localPort, servePort: config.tailscaleServePort }),
888 + Effect.as({
889 + localPort,
890 + localHost: localHost.replace(/^\[|\]$/gu, ""),
891 + servePort: config.tailscaleServePort,
892 + }),
893 Effect.tap(() =>
894 Effect.logInfo("Tailscale Serve configured", {
895 localPort,
@@ -862,11 +907,44 @@ const layerMakeServer = Layer.unwrap(
907 }),
908 (configured) =>
909 configured
865 - ? disableTailscaleServe({ servePort: configured.servePort }).pipe(
866 - Effect.tap(() =>
867 - Effect.logInfo("Tailscale Serve disabled", {
868 - servePort: configured.servePort,
910 + ? Effect.all(
911 + [
912 + readTailscaleServeRoutesTo({
913 + host: configured.localHost,
914 + port: configured.localPort,
915 }),
916 + readTailscaleStatus,
917 + ],
918 + { concurrency: 2 },
919 + ).pipe(
920 + // Another service may hold the root route by now, or it may sit under a
921 + // former name, where `off` would act on the current one; only ours goes.
922 + Effect.map(([routes, status]) =>
923 + routes.some(
924 + (route) =>
925 + route.servePort === configured.servePort &&
926 + route.mount === "/" &&
927 + route.owner === undefined &&
928 + route.ambiguous === undefined &&
929 + route.host?.toLowerCase() === status.magicDnsName?.toLowerCase(),
930 + ),
931 + ),
932 + Effect.orElseSucceed(() => false),
933 + Effect.flatMap((ours) =>
934 + ours
935 + ? disableTailscaleServe({ servePort: configured.servePort }).pipe(
936 + Effect.tap(() =>
937 + Effect.logInfo("Tailscale Serve disabled", {
938 + servePort: configured.servePort,
939 + }),
940 + ),
941 + )
942 + : Effect.logInfo(
943 + "Tailscale Serve left on; its root route is not known to be ours",
944 + {
945 + servePort: configured.servePort,
946 + },
947 + ),
948 ),
949 Effect.catch((cause) =>
950 Effect.logWarning("Failed to disable Tailscale Serve", {
@@ -882,6 +960,11 @@ const layerMakeServer = Layer.unwrap(
960 const layerCloudDesiredLinkReconcile = Layer.effectDiscard(
961 Effect.gen(function* () {
962 const cloudLink = yield* CloudLink.CloudLink;
963 + // CloudLink unlinks on startup when the policy turns Connect off; nothing to restore.
964 + if (!ManagedLimits.allowsConnect(yield* ManagedPolicy.ManagedPolicy)) {
965 + yield* Deferred.succeed(cloudLinkParked, undefined).pipe(Effect.orDie);
966 + return;
967 + }
968 const releaseManagedTunnel = cloudLink.releaseManagedTunnelOnShutdown().pipe(
969 Effect.timeout("10 seconds"),
970 Effect.tap((released) =>
@@ -1099,7 +1182,9 @@ const layerMakeServer = Layer.unwrap(
1182 ),
1183 ),
1184 Layer.provide(layerActivation),
1102 - Layer.provideMerge(RelayTracing.layerServerRelayBroker),
1185 + Layer.provideMerge(
1186 + RelayTracing.layerServerRelayBroker.pipe(Layer.provide(ManagedPolicy.layer)),
1187 + ),
1188 Layer.provideMerge(layerHttpServer),
1189 Layer.provide(layerApplicationObservability),
1190 Layer.provideMerge(FetchHttpClient.layer),
apps/server/src/serverRuntimeState.ts
+12
@@ -22,6 +22,16 @@ export const PersistedServerRuntimeState = Schema.Struct({
22 startedAt: Schema.String,
23 serviceManaged: Schema.optional(Schema.Boolean),
24 serverVersion: Schema.optional(Schema.String),
25 + // The managed policy this server loaded at startup, null for none; absent from older servers.
26 + managedPolicy: Schema.optional(
27 + Schema.NullOr(
28 + Schema.Struct({
29 + source: Schema.String,
30 + organization: Schema.String,
31 + fingerprint: Schema.String,
32 + }),
33 + ),
34 + ),
35 });
36 export type PersistedServerRuntimeState = typeof PersistedServerRuntimeState.Type;
37
@@ -58,6 +68,7 @@ export const makePersistedServerRuntimeState = (input: {
68 >;
69 readonly port: number;
70 readonly serviceManaged?: boolean;
71 + readonly managedPolicy?: PersistedServerRuntimeState["managedPolicy"];
72 }): Effect.Effect<PersistedServerRuntimeState> =>
73 Effect.map(DateTime.now, (now) => ({
74 version: 1,
@@ -70,6 +81,7 @@ export const makePersistedServerRuntimeState = (input: {
81 startedAt: DateTime.formatIso(now),
82 ...(input.serviceManaged ? { serviceManaged: true } : {}),
83 serverVersion: packageJson.version,
84 + ...(input.managedPolicy === undefined ? {} : { managedPolicy: input.managedPolicy }),
85 }));
86
87 export const persistServerRuntimeState = (input: {
apps/server/src/serverSettings.test.ts
+655 -2
@@ -1,6 +1,8 @@
1 import * as NodeServices from "@effect/platform-node/NodeServices";
2 import {
3 DEFAULT_SERVER_SETTINGS,
4 + globalIdleCompaction,
5 + type ManagedPolicyDocument,
6 ModelSelection,
7 ProjectId,
8 ProjectScript,
@@ -31,15 +33,17 @@ import * as ServerConfig from "./config.ts";
33 import * as SqlitePersistence from "./persistence/Sqlite.ts";
34 import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";
35 import * as ServerSettingsModule from "./serverSettings.ts";
36 +import * as ManagedPolicy from "./policy/ManagedPolicy.ts";
37 import { resolveProviderInstanceTerminalEnvironment } from "./terminal/Manager.ts";
38
39 const decodeServerSettings = Schema.decodeUnknownEffect(ServerSettings);
40 const decodeServerSettingsJson = Schema.decodeUnknownEffect(Schema.fromJsonString(ServerSettings));
41 const decodeServerSettingsPatch = Schema.decodeUnknownEffect(ServerSettingsPatch);
42
40 -const layerServerSettings = () =>
43 +const layerServerSettings = (policy?: ManagedPolicyDocument) =>
44 ServerSettingsModule.layer.pipe(
45 Layer.provide(ServerSecretStore.layer),
46 + Layer.provide(ManagedPolicy.layerTest(policy)),
47 Layer.provideMerge(Layer.fresh(SqlitePersistence.layerMemory)),
48 Layer.provideMerge(
49 Layer.fresh(
@@ -53,6 +57,7 @@ const layerServerSettings = () =>
57 const layerServerSettingsWithSecrets = () =>
58 ServerSettingsModule.layer.pipe(
59 Layer.provideMerge(ServerSecretStore.layer),
60 + Layer.provide(ManagedPolicy.layerTest()),
61 Layer.provideMerge(Layer.fresh(SqlitePersistence.layerMemory)),
62 Layer.provideMerge(
63 Layer.fresh(
@@ -1084,6 +1089,7 @@ it.layer(NodeServices.layer)("server settings", (it) => {
1089 ).pipe(Layer.provide(ServerSecretStore.layer));
1090 const layerSettings = ServerSettingsModule.layer.pipe(
1091 Layer.provide(layerSecret),
1092 + Layer.provide(ManagedPolicy.layerTest()),
1093 Layer.provideMerge(Layer.fresh(SqlitePersistence.layerMemory)),
1094 Layer.provideMerge(
1095 Layer.fresh(
@@ -1130,6 +1136,7 @@ it.layer(NodeServices.layer)("server settings", (it) => {
1136 })),
1137 ).pipe(Layer.provide(ServerSecretStore.layer));
1138 const layerSettings = ServerSettingsModule.layer.pipe(
1139 + Layer.provide(ManagedPolicy.layerTest()),
1140 Layer.provide(layerSecret),
1141 Layer.provideMerge(Layer.fresh(SqlitePersistence.layerMemory)),
1142 Layer.provideMerge(
@@ -1232,7 +1239,9 @@ it.layer(NodeServices.layer)("server settings", (it) => {
1239 return yield* fresh.getSettings;
1240 }).pipe(
1241 Effect.provide(
1235 - Layer.fresh(ServerSettingsModule.layer).pipe(Layer.provide(ServerSecretStore.layer)),
1242 + Layer.fresh(ServerSettingsModule.layer).pipe(
1243 + Layer.provide(Layer.merge(ServerSecretStore.layer, ManagedPolicy.layerTest())),
1244 + ),
1245 ),
1246 );
1247 assert.equal(reloaded.providerInstances[instanceId]?.environment?.[0]?.value, expected);
@@ -1567,6 +1576,7 @@ it.layer(NodeServices.layer)("server settings", (it) => {
1576 }),
1577 });
1578 const layerSettings = ServerSettingsModule.layer.pipe(
1579 + Layer.provide(ManagedPolicy.layerTest()),
1580 Layer.provide(layerFailingSecretStore(cause)),
1581 Layer.provideMerge(Layer.fresh(SqlitePersistence.layerMemory)),
1582 Layer.provideMerge(
@@ -1823,6 +1833,8 @@ it.layer(NodeServices.layer)("server settings", (it) => {
1833 }),
1834 );
1835 const layerSettings = ServerSettingsModule.layer.pipe(
1836 + Layer.provide(ManagedPolicy.layerTest()),
1837 + Layer.provide(ManagedPolicy.layerTest()),
1838 Layer.provideMerge(Layer.fresh(SqlitePersistence.layerMemory)),
1839 Layer.provide(layerSecretStore),
1840 Layer.provideMerge(
@@ -1984,3 +1996,644 @@ it.layer(NodeServices.layer)("server settings", (it) => {
1996 }).pipe(Effect.provide(layerServerSettings())),
1997 );
1998 });
1999 +
2000 +it.layer(NodeServices.layer)("server settings under a managed policy", (it) => {
2001 + const policy: ManagedPolicyDocument = {
2002 + schemaVersion: 1,
2003 + organization: "Example Corp",
2004 + settings: {
2005 + defaultRuntimeMode: { value: "approval-required", locked: false },
2006 + enableAgentDeviceAccess: { value: false, locked: true },
2007 + },
2008 + };
2009 +
2010 + it.effect("uses policy defaults until the user picks something else", () =>
2011 + Effect.gen(function* () {
2012 + const service = yield* ServerSettingsModule.ServerSettingsService;
2013 + const config = yield* ServerConfig.ServerConfig;
2014 + const fs = yield* FileSystem.FileSystem;
2015 +
2016 + assert.equal((yield* service.getSettings).defaultRuntimeMode, "approval-required");
2017 +
2018 + // The built-in default differs from the policy's, so choosing it must persist.
2019 + yield* service.updateSettings({ defaultRuntimeMode: "full-access" });
2020 + assert.equal((yield* service.getSettings).defaultRuntimeMode, "full-access");
2021 + assert.include(yield* fs.readFileString(config.settingsPath), '"full-access"');
2022 +
2023 + // Choosing the policy's value leaves nothing in the file to outlive the policy.
2024 + yield* service.updateSettings({ defaultRuntimeMode: "approval-required" });
2025 + assert.notInclude(yield* fs.readFileString(config.settingsPath), "defaultRuntimeMode");
2026 + }).pipe(Effect.provide(layerServerSettings(policy))),
2027 + );
2028 +
2029 + it.effect("keeps a stored value that equals a policy default through unrelated writes", () =>
2030 + Effect.gen(function* () {
2031 + const service = yield* ServerSettingsModule.ServerSettingsService;
2032 + const config = yield* ServerConfig.ServerConfig;
2033 + const fs = yield* FileSystem.FileSystem;
2034 + yield* fs.writeFileString(
2035 + config.settingsPath,
2036 + JSON.stringify({ defaultRuntimeMode: "approval-required" }),
2037 + );
2038 +
2039 + yield* service.updateSettings({ defaultAutoPull: true });
2040 + assert.include(yield* fs.readFileString(config.settingsPath), '"approval-required"');
2041 + }).pipe(Effect.provide(layerServerSettings(policy))),
2042 + );
2043 +
2044 + it.effect("keeps stored values under whole-object policy defaults, and only the user's", () =>
2045 + Effect.gen(function* () {
2046 + const service = yield* ServerSettingsModule.ServerSettingsService;
2047 + const config = yield* ServerConfig.ServerConfig;
2048 + const fs = yield* FileSystem.FileSystem;
2049 + const selection = {
2050 + ...DEFAULT_SERVER_SETTINGS.textGenerationModelSelection,
2051 + model: "managed",
2052 + };
2053 + const chosenModel = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-mini" };
2054 + yield* fs.writeFileString(
2055 + config.settingsPath,
2056 + JSON.stringify({
2057 + storageCleanup: { logsAfterDays: 30, browserArtifactsAfterDays: 7 },
2058 + textGenerationModelSelection: selection,
2059 + }),
2060 + );
2061 +
2062 + // Picking another model on the policy's instance differs from the policy in one field only.
2063 + yield* service.updateSettings({ defaultAutoPull: true, defaultModelSelection: chosenModel });
2064 + const stored = JSON.parse(yield* fs.readFileString(config.settingsPath));
2065 + assert.deepEqual(stored.storageCleanup, { logsAfterDays: 30, browserArtifactsAfterDays: 7 });
2066 + // Model selections are saved whole, never as the fields that differ from the policy's.
2067 + assert.deepEqual(stored.textGenerationModelSelection, selection);
2068 + assert.deepEqual(stored.defaultModelSelection, chosenModel);
2069 + // The switch the server derives from the policy's idle compaction stays out of the file.
2070 + assert.notProperty(stored, "compactIdleThreads");
2071 + }).pipe(
2072 + Effect.provide(
2073 + layerServerSettings({
2074 + schemaVersion: 1,
2075 + organization: "Example Corp",
2076 + settings: {
2077 + storageCleanup: {
2078 + value: { ...DEFAULT_SERVER_SETTINGS.storageCleanup, logsAfterDays: 30 },
2079 + locked: false,
2080 + },
2081 + "textGenerationModelSelection.model": { value: "managed", locked: false },
2082 + defaultModelSelection: {
2083 + value: { instanceId: "codex", model: "gpt-managed" },
2084 + locked: false,
2085 + },
2086 + idleCompaction: { value: "beforeCacheExpires", locked: false },
2087 + },
2088 + }),
2089 + ),
2090 + ),
2091 + );
2092 +
2093 + it.effect(
2094 + "keeps an idle compaction choice saved before idleCompaction over a policy default",
2095 + () =>
2096 + // The file holds only the legacy switch: off differs from the policy's default, on matches it.
2097 + Effect.forEach([false, true], (compactIdleThreads) =>
2098 + Effect.gen(function* () {
2099 + const service = yield* ServerSettingsModule.ServerSettingsService;
2100 + const config = yield* ServerConfig.ServerConfig;
2101 + const fs = yield* FileSystem.FileSystem;
2102 + const chosen = compactIdleThreads ? "beforeCacheExpires" : "onReturn";
2103 + yield* fs.writeFileString(config.settingsPath, JSON.stringify({ compactIdleThreads }));
2104 +
2105 + assert.equal((yield* service.getSettings).idleCompaction, chosen);
2106 + yield* service.updateSettings({ defaultAutoPull: true });
2107 + // What applies once the policy is gone is still the user's choice.
2108 + const stored = JSON.parse(yield* fs.readFileString(config.settingsPath));
2109 + assert.equal(globalIdleCompaction(stored), chosen);
2110 + }).pipe(
2111 + Effect.provide(
2112 + layerServerSettings({
2113 + schemaVersion: 1,
2114 + organization: "Example Corp",
2115 + settings: { idleCompaction: { value: "beforeCacheExpires", locked: false } },
2116 + }),
2117 + ),
2118 + ),
2119 + ),
2120 + );
2121 +
2122 + it.effect("lays locks over the user's own and per-project values without persisting them", () =>
2123 + Effect.gen(function* () {
2124 + const service = yield* ServerSettingsModule.ServerSettingsService;
2125 + const config = yield* ServerConfig.ServerConfig;
2126 + const fs = yield* FileSystem.FileSystem;
2127 + const projectId = ProjectId.make("project-locked");
2128 + yield* fs.writeFileString(
2129 + config.settingsPath,
2130 + JSON.stringify({
2131 + enableAgentDeviceAccess: true,
2132 + projectSettingsOverrides: { [projectId]: { enableAgentDeviceAccess: true } },
2133 + }),
2134 + );
2135 +
2136 + const settings = yield* service.getSettings;
2137 + assert.isFalse(settings.enableAgentDeviceAccess);
2138 + assert.isFalse(settings.projectSettingsOverrides[projectId]?.enableAgentDeviceAccess);
2139 + assert.deepEqual(service.managedPolicy, {
2140 + organization: "Example Corp",
2141 + lockedSettings: ["enableAgentDeviceAccess"],
2142 + });
2143 +
2144 + const rejected = yield* service
2145 + .updateSettings({ enableAgentDeviceAccess: true, defaultAutoPull: true })
2146 + .pipe(Effect.flip);
2147 + assert.equal(rejected.operation, "write-managed-setting");
2148 + assert.equal(rejected.managedSetting, "enableAgentDeviceAccess");
2149 + assert.equal(
2150 + rejected.message,
2151 + "enableAgentDeviceAccess is managed by Example Corp and cannot be changed.",
2152 + );
2153 + assert.isFalse((yield* service.getSettings).defaultAutoPull);
2154 +
2155 + const projectRejected = yield* service
2156 + .updateSettings({
2157 + projectSettingsOverrides: { [projectId]: { enableAgentDeviceAccess: true } },
2158 + })
2159 + .pipe(Effect.flip);
2160 + assert.equal(projectRejected.managedSetting, "enableAgentDeviceAccess");
2161 +
2162 + // Unrelated writes, and writes that keep the locked value, go through.
2163 + yield* service.updateSettings({ enableAgentDeviceAccess: false, defaultAutoPull: true });
2164 + assert.isTrue((yield* service.getSettings).defaultAutoPull);
2165 +
2166 + // The user's own value stays on disk, ready for when the policy is removed.
2167 + const stored = JSON.parse(yield* fs.readFileString(config.settingsPath));
2168 + assert.isTrue(stored.enableAgentDeviceAccess);
2169 + }).pipe(Effect.provide(layerServerSettings(policy))),
2170 + );
2171 + it.effect("accepts a project override that brings the locked value inside a new setting", () =>
2172 + Effect.gen(function* () {
2173 + const service = yield* ServerSettingsModule.ServerSettingsService;
2174 + const projectId = ProjectId.make("project-text-generation");
2175 + const selection = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-locked" };
2176 +
2177 + yield* service.updateSettings({
2178 + projectSettingsOverrides: { [projectId]: { textGenerationModelSelection: selection } },
2179 + });
2180 +
2181 + const project = (yield* service.getSettings).projectSettingsOverrides[projectId];
2182 + assert.equal(project?.textGenerationModelSelection?.model, "gpt-locked");
2183 + }).pipe(
2184 + Effect.provide(
2185 + layerServerSettings({
2186 + schemaVersion: 1,
2187 + organization: "Example Corp",
2188 + settings: { "textGenerationModelSelection.model": { value: "gpt-locked", locked: true } },
2189 + }),
2190 + ),
2191 + ),
2192 + );
2193 +
2194 + it.effect("compares a project's partial override with a locked entry by the keys it holds", () =>
2195 + Effect.gen(function* () {
2196 + const service = yield* ServerSettingsModule.ServerSettingsService;
2197 + const codexId = ProviderInstanceId.make("codex");
2198 + const projectWith = (enabled: boolean) => ({
2199 + projectSettingsOverrides: {
2200 + [ProjectId.make("project-codex")]: { providerInstances: { [codexId]: { enabled } } },
2201 + },
2202 + });
2203 +
2204 + yield* service.updateSettings(projectWith(true));
2205 + const refused = yield* service.updateSettings(projectWith(false)).pipe(Effect.flip);
2206 + assert.equal(refused.managedSetting, "providerInstances.codex");
2207 + }).pipe(
2208 + Effect.provide(
2209 + layerServerSettings({
2210 + schemaVersion: 1,
2211 + organization: "Example Corp",
2212 + settings: {
2213 + "providerInstances.codex": { value: { driver: "codex", enabled: true }, locked: true },
2214 + },
2215 + }),
2216 + ),
2217 + ),
2218 + );
2219 +
2220 + it.effect("lowers default runtime modes above the ceiling without rewriting them", () =>
2221 + Effect.gen(function* () {
2222 + const service = yield* ServerSettingsModule.ServerSettingsService;
2223 + const config = yield* ServerConfig.ServerConfig;
2224 + const fs = yield* FileSystem.FileSystem;
2225 + const raised = ProjectId.make("project-raised");
2226 + const supervised = ProjectId.make("project-supervised");
2227 + yield* fs.writeFileString(
2228 + config.settingsPath,
2229 + JSON.stringify({
2230 + defaultRuntimeMode: "auto",
2231 + projectSettingsOverrides: {
2232 + [raised]: { defaultRuntimeMode: "full-access" },
2233 + [supervised]: { defaultRuntimeMode: "approval-required" },
2234 + },
2235 + }),
2236 + );
2237 +
2238 + const settings = yield* service.getSettings;
2239 + assert.equal(settings.defaultRuntimeMode, "auto-accept-edits");
2240 + assert.equal(
2241 + settings.projectSettingsOverrides[raised]?.defaultRuntimeMode,
2242 + "auto-accept-edits",
2243 + );
2244 + assert.equal(
2245 + settings.projectSettingsOverrides[supervised]?.defaultRuntimeMode,
2246 + "approval-required",
2247 + );
2248 +
2249 + yield* service.updateSettings({ defaultAutoPull: true });
2250 + const stored = JSON.parse(yield* fs.readFileString(config.settingsPath));
2251 + assert.equal(stored.defaultRuntimeMode, "auto");
2252 + assert.equal(stored.projectSettingsOverrides[raised].defaultRuntimeMode, "full-access");
2253 + }).pipe(
2254 + Effect.provide(
2255 + layerServerSettings({
2256 + schemaVersion: 1,
2257 + organization: "Example Corp",
2258 + limits: { maxRuntimeMode: "auto-accept-edits" },
2259 + }),
2260 + ),
2261 + ),
2262 + );
2263 +});
2264 +
2265 +it.layer(NodeServices.layer)("server settings under a provider policy", (it) => {
2266 + const claude = ProviderDriverKind.make("claudeAgent");
2267 + const codex = ProviderDriverKind.make("codex");
2268 + const cursor = ProviderDriverKind.make("cursor");
2269 + const bedrock = { name: "CLAUDE_CODE_USE_BEDROCK", value: "1", sensitive: false };
2270 + const policy: ManagedPolicyDocument = {
2271 + schemaVersion: 1,
2272 + organization: "Example Corp",
2273 + limits: {
2274 + providers: {
2275 + allowedDrivers: [claude, codex],
2276 + instances: {
2277 + [claude]: {
2278 + locked: true,
2279 + environment: [{ name: bedrock.name, value: bedrock.value }],
2280 + binaryPath: "/opt/claude/bin/claude",
2281 + },
2282 + [codex]: { locked: false, launchArgs: "-c model_provider=gateway" },
2283 + },
2284 + },
2285 + },
2286 + };
2287 +
2288 + it.effect("refuses enabling a driver the policy leaves out, and keeps existing ones", () =>
2289 + Effect.gen(function* () {
2290 + const service = yield* ServerSettingsModule.ServerSettingsService;
2291 + const config = yield* ServerConfig.ServerConfig;
2292 + const fs = yield* FileSystem.FileSystem;
2293 + const cursorId = ProviderInstanceId.make("cursor_work");
2294 + yield* fs.writeFileString(
2295 + config.settingsPath,
2296 + JSON.stringify({
2297 + providerInstances: {
2298 + [cursorId]: { driver: cursor, enabled: true },
2299 + // A default instance id is no proof of its driver.
2300 + codex: { driver: cursor, enabled: true },
2301 + },
2302 + textGenerationModelSelection: { instanceId: cursorId, model: "auto" },
2303 + }),
2304 + );
2305 +
2306 + const settings = yield* service.getSettings;
2307 + // Never deleted: the instance stays for its threads, and the registry shows it unavailable.
2308 + assert.equal(settings.providerInstances[cursorId]?.driver, cursor);
2309 + // Built-in text generation does not fall back onto a disallowed driver either.
2310 + assert.equal(settings.textGenerationModelSelection.instanceId, "claudeAgent");
2311 +
2312 + const rejected = yield* service
2313 + .updateProviderInstance({
2314 + operation: "create",
2315 + instanceId: ProviderInstanceId.make("cursor_new"),
2316 + instance: { driver: cursor, enabled: true },
2317 + })
2318 + .pipe(Effect.flip);
2319 + assert.equal(rejected.operation, "use-disallowed-provider");
2320 + assert.equal(rejected.message, "Example Corp's policy does not allow the Cursor provider.");
2321 + // Switching it on for one project is enabling it too.
2322 + const perProject = yield* service
2323 + .updateSettings({
2324 + projectSettingsOverrides: {
2325 + [ProjectId.make("project-a")]: { providerInstances: { [cursorId]: { enabled: true } } },
2326 + },
2327 + })
2328 + .pipe(Effect.flip);
2329 + assert.equal(perProject.operation, "use-disallowed-provider");
2330 +
2331 + // The client echoes a default instance that was running before it was configured.
2332 + yield* service.updateProviderInstance({
2333 + operation: "upsert",
2334 + instanceId: ProviderInstanceId.make("cursor"),
2335 + instance: { driver: cursor, enabled: true },
2336 + });
2337 +
2338 + // Turning it off, or removing it, is still the user's call.
2339 + yield* service.updateProviderInstance({
2340 + operation: "upsert",
2341 + instanceId: cursorId,
2342 + instance: { driver: cursor, enabled: false },
2343 + });
2344 + yield* service.updateProviderInstance({ operation: "remove", instanceId: cursorId });
2345 + assert.isUndefined((yield* service.getSettings).providerInstances[cursorId]);
2346 + }).pipe(Effect.provide(layerServerSettings(policy))),
2347 + );
2348 +
2349 + it.effect("keeps a locked Codex pin from being bypassed by managed setup", () =>
2350 + Effect.gen(function* () {
2351 + const service = yield* ServerSettingsModule.ServerSettingsService;
2352 + const config = yield* ServerConfig.ServerConfig;
2353 + const fs = yield* FileSystem.FileSystem;
2354 + const codexId = ProviderInstanceId.make("codex_chatgpt");
2355 + yield* fs.writeFileString(
2356 + config.settingsPath,
2357 + JSON.stringify({
2358 + providerInstances: { [codexId]: { driver: codex, config: { setupMode: "managed" } } },
2359 + }),
2360 + );
2361 +
2362 + const effective = (yield* service.getSettings).providerInstances[codexId];
2363 + assert.deepEqual(effective?.config, { binaryPath: "/opt/gateway/codex" });
2364 + // A stored value stays for when the policy is gone; a new one is refused.
2365 + const refused = yield* service
2366 + .updateProviderInstance({
2367 + operation: "upsert",
2368 + instanceId: ProviderInstanceId.make("codex_new"),
2369 + instance: { driver: codex, config: { setupMode: "managed" } },
2370 + })
2371 + .pipe(Effect.flip);
2372 + assert.equal(refused.managedSetting, "providerInstances.codex_new.config.setupMode");
2373 + // Adding a Codex instance sends the default setup, which leaves the pin in charge.
2374 + yield* service.updateProviderInstance({
2375 + operation: "upsert",
2376 + instanceId: ProviderInstanceId.make("codex_cli"),
2377 + instance: { driver: codex, config: { setupMode: "existing" } },
2378 + });
2379 + }).pipe(
2380 + Effect.provide(
2381 + layerServerSettings({
2382 + schemaVersion: 1,
2383 + organization: "Example Corp",
2384 + limits: {
2385 + providers: {
2386 + instances: { [codex]: { locked: true, binaryPath: "/opt/gateway/codex" } },
2387 + },
2388 + },
2389 + }),
2390 + ),
2391 + ),
2392 + );
2393 +
2394 + it.effect("pins instance fields at read time and refuses edits to locked ones", () =>
2395 + Effect.gen(function* () {
2396 + const service = yield* ServerSettingsModule.ServerSettingsService;
2397 + const config = yield* ServerConfig.ServerConfig;
2398 + const fs = yield* FileSystem.FileSystem;
2399 + const claudeId = ProviderInstanceId.make("claudeAgent");
2400 + const codexId = ProviderInstanceId.make("codex");
2401 + const userVariable = { name: "MY_FLAG", value: "on", sensitive: false };
2402 + yield* fs.writeFileString(
2403 + config.settingsPath,
2404 + JSON.stringify({
2405 + providerInstances: {
2406 + [claudeId]: {
2407 + driver: claude,
2408 + environment: [{ ...bedrock, value: "0" }, userVariable, { ...bedrock, value: "2" }],
2409 + config: { binaryPath: "/usr/local/bin/claude" },
2410 + },
2411 + },
2412 + }),
2413 + );
2414 +
2415 + const effective = yield* service.getSettings;
2416 + const claudeInstance = effective.providerInstances[claudeId];
2417 + assert.deepEqual(claudeInstance?.environment, [bedrock, userVariable]);
2418 + assert.deepEqual(claudeInstance?.config, { binaryPath: "/opt/claude/bin/claude" });
2419 + // The implicit default Codex instance gets the unlocked default too.
2420 + assert.deepEqual(effective.providerInstances[codexId]?.config, {
2421 + launchArgs: "-c model_provider=gateway",
2422 + });
2423 +
2424 + const lockedBinary = yield* service
2425 + .updateProviderInstance({
2426 + operation: "upsert",
2427 + instanceId: claudeId,
2428 + instance: { ...claudeInstance!, config: { binaryPath: "/tmp/claude" } },
2429 + })
2430 + .pipe(Effect.flip);
2431 + assert.equal(lockedBinary.operation, "write-managed-setting");
2432 + assert.equal(lockedBinary.managedSetting, "providerInstances.claudeAgent.config.binaryPath");
2433 + const lockedVariable = yield* service
2434 + .updateProviderInstance({
2435 + operation: "upsert",
2436 + instanceId: claudeId,
2437 + instance: { ...claudeInstance!, environment: [userVariable] },
2438 + })
2439 + .pipe(Effect.flip);
2440 + assert.equal(
2441 + lockedVariable.managedSetting,
2442 + "providerInstances.claudeAgent.environment.CLAUDE_CODE_USE_BEDROCK",
2443 + );
2444 +
2445 + // Saving what the client was shown, plus an unrelated edit, goes through without baking
2446 + // the policy into the file: the user's own values come back once the policy is removed.
2447 + yield* service.updateProviderInstance({
2448 + operation: "upsert",
2449 + instanceId: claudeId,
2450 + instance: { ...claudeInstance!, displayName: "Claude (work)" },
2451 + });
2452 + yield* service.updateProviderInstance({
2453 + operation: "upsert",
2454 + instanceId: codexId,
2455 + instance: effective.providerInstances[codexId]!,
2456 + });
2457 + const stored = JSON.parse(yield* fs.readFileString(config.settingsPath));
2458 + assert.deepEqual(stored.providerInstances[claudeId], {
2459 + driver: claude,
2460 + displayName: "Claude (work)",
2461 + environment: [{ ...bedrock, value: "0" }, { ...bedrock, value: "2" }, userVariable],
2462 + config: { binaryPath: "/usr/local/bin/claude" },
2463 + });
2464 + assert.isUndefined(stored.providerInstances[codexId]);
2465 +
2466 + // Unlocked fields are the user's to override.
2467 + yield* service.updateProviderInstance({
2468 + operation: "upsert",
2469 + instanceId: codexId,
2470 + instance: { driver: codex, config: { launchArgs: "--mine" } },
2471 + });
2472 + assert.deepEqual((yield* service.getSettings).providerInstances[codexId]?.config, {
2473 + launchArgs: "--mine",
2474 + });
2475 + }).pipe(Effect.provide(layerServerSettings(policy))),
2476 + );
2477 +});
2478 +
2479 +it.layer(NodeServices.layer)("server settings under a runtime mode ceiling", (it) => {
2480 + const claude = ProviderDriverKind.make("claudeAgent");
2481 + const acpRegistry = ProviderDriverKind.make("acpRegistry");
2482 + const policy: ManagedPolicyDocument = {
2483 + schemaVersion: 1,
2484 + organization: "Example Corp",
2485 + limits: {
2486 + maxRuntimeMode: "auto-accept-edits",
2487 + providers: {
2488 + instances: {
2489 + [claude]: {
2490 + locked: false,
2491 + environment: [{ name: "CLAUDE_CODE_USE_BEDROCK", value: "1" }],
2492 + binaryPath: "/opt/claude/bin/claude",
2493 + },
2494 + },
2495 + },
2496 + },
2497 + };
2498 +
2499 + it.effect("keeps the secret of a variable it hides when the instance is saved", () => {
2500 + const shared = ServerSecretStore.layer.pipe(
2501 + Layer.provideMerge(Layer.fresh(SqlitePersistence.layerMemory)),
2502 + Layer.provideMerge(
2503 + Layer.fresh(ServerConfig.layerTest(process.cwd(), { prefix: "t3code-hidden-secret-" })),
2504 + ),
2505 + );
2506 + const withPolicy = <A, E>(
2507 + document: ManagedPolicyDocument | undefined,
2508 + use: (service: ServerSettingsModule.ServerSettingsService["Service"]) => Effect.Effect<A, E>,
2509 + ) =>
2510 + ServerSettingsModule.ServerSettingsService.pipe(
2511 + Effect.flatMap(use),
2512 + Effect.provide(
2513 + ServerSettingsModule.layer.pipe(Layer.provide(ManagedPolicy.layerTest(document))),
2514 + ),
2515 + );
2516 + const claudeId = ProviderInstanceId.make("claudeAgent");
2517 + const token = { name: "ANTHROPIC_API_KEY", value: "sk-kept", sensitive: true };
2518 + return Effect.gen(function* () {
2519 + yield* withPolicy(undefined, (service) =>
2520 + service.updateProviderInstance({
2521 + operation: "upsert",
2522 + instanceId: claudeId,
2523 + instance: { driver: claude, environment: [token] },
2524 + }),
2525 + );
2526 + // The ceiling shows only pinned variables, so the client saves without the token.
2527 + yield* withPolicy(policy, (service) =>
2528 + service.getSettings.pipe(
2529 + Effect.flatMap((settings) =>
2530 + service.updateProviderInstance({
2531 + operation: "upsert",
2532 + instanceId: claudeId,
2533 + instance: { ...settings.providerInstances[claudeId]!, displayName: "Claude (work)" },
2534 + }),
2535 + ),
2536 + ),
2537 + );
2538 + const restored = yield* withPolicy(undefined, (service) => service.getSettings);
2539 + assert.equal(restored.providerInstances[claudeId]?.environment?.[0]?.value, token.value);
2540 + }).pipe(Effect.provide(shared));
2541 + });
2542 +
2543 + it.effect("ignores stored launch configuration and refuses new values", () =>
2544 + Effect.gen(function* () {
2545 + const service = yield* ServerSettingsModule.ServerSettingsService;
2546 + const config = yield* ServerConfig.ServerConfig;
2547 + const fs = yield* FileSystem.FileSystem;
2548 + const claudeId = ProviderInstanceId.make("claudeAgent");
2549 + const registryId = ProviderInstanceId.make("acp_devin");
2550 + const userVariable = { name: "CLAUDE_CONFIG_DIR", value: "/tmp/allow-all", sensitive: false };
2551 + const storedClaude = {
2552 + driver: claude,
2553 + environment: [userVariable, { ...userVariable, value: "/tmp/later-wins" }],
2554 + config: {
2555 + binaryPath: "/tmp/wrapper",
2556 + launchArgs: "--dangerously-skip-permissions",
2557 + homePath: "/tmp/allow-all",
2558 + autoCompactWindow: "300000",
2559 + },
2560 + };
2561 + yield* fs.writeFileString(
2562 + config.settingsPath,
2563 + JSON.stringify({
2564 + providerInstances: {
2565 + [claudeId]: storedClaude,
2566 + [registryId]: {
2567 + driver: acpRegistry,
2568 + config: { agentId: "devin", commandPath: "/tmp/agent", commandArgs: ["--yolo"] },
2569 + },
2570 + },
2571 + }),
2572 + );
2573 +
2574 + // Even an unlocked pin wins, and the user's launch values and variables are not used.
2575 + const effective = yield* service.getSettings;
2576 + const claudeInstance = effective.providerInstances[claudeId]!;
2577 + assert.deepEqual(claudeInstance.config, {
2578 + binaryPath: "/opt/claude/bin/claude",
2579 + autoCompactWindow: "300000",
2580 + });
2581 + assert.deepEqual(claudeInstance.environment, [
2582 + { name: "CLAUDE_CODE_USE_BEDROCK", value: "1", sensitive: false },
2583 + ]);
2584 + assert.deepEqual(effective.providerInstances[registryId]?.config, { agentId: "devin" });
2585 +
2586 + const refused = (instance: typeof claudeInstance) =>
2587 + service
2588 + .updateProviderInstance({ operation: "upsert", instanceId: claudeId, instance })
2589 + .pipe(Effect.flip);
2590 + const launchArgs = yield* refused({
2591 + ...claudeInstance,
2592 + config: { ...claudeInstance.config!, launchArgs: "--permission-mode bypassPermissions" },
2593 + });
2594 + assert.equal(launchArgs.operation, "write-managed-setting");
2595 + assert.equal(launchArgs.managedSetting, "providerInstances.claudeAgent.config.launchArgs");
2596 + const binary = yield* refused({
2597 + ...claudeInstance,
2598 + config: { ...claudeInstance.config!, binaryPath: "/tmp/other-wrapper" },
2599 + });
2600 + assert.equal(binary.managedSetting, "providerInstances.claudeAgent.config.binaryPath");
2601 + const environment = yield* refused({
2602 + ...claudeInstance,
2603 + environment: [{ name: "NODE_OPTIONS", value: "--require /tmp/x.js", sensitive: false }],
2604 + });
2605 + assert.equal(environment.managedSetting, "providerInstances.claudeAgent.environment");
2606 + const commandArgs = yield* service
2607 + .updateProviderInstance({
2608 + operation: "upsert",
2609 + instanceId: registryId,
2610 + instance: {
2611 + driver: acpRegistry,
2612 + config: { agentId: "devin", commandArgs: ["--dangerously-skip-permissions"] },
2613 + },
2614 + })
2615 + .pipe(Effect.flip);
2616 + assert.equal(commandArgs.managedSetting, "providerInstances.acp_devin.config.commandArgs");
2617 +
2618 + // Unrelated writes carry the stored instance through unchanged, duplicates included.
2619 + yield* service.updateSettings({ defaultAutoPull: true });
2620 +
2621 + // What the client was shown saves, with user-owned edits, and the stored values survive.
2622 + yield* service.updateProviderInstance({
2623 + operation: "upsert",
2624 + instanceId: claudeId,
2625 + instance: {
2626 + ...claudeInstance,
2627 + displayName: "Claude (work)",
2628 + config: { ...claudeInstance.config!, autoCompactWindow: "400000" },
2629 + },
2630 + });
2631 + const stored = JSON.parse(yield* fs.readFileString(config.settingsPath));
2632 + assert.deepEqual(stored.providerInstances[claudeId], {
2633 + ...storedClaude,
2634 + displayName: "Claude (work)",
2635 + config: { ...storedClaude.config, autoCompactWindow: "400000" },
2636 + });
2637 + }).pipe(Effect.provide(layerServerSettings(policy))),
2638 + );
2639 +});
apps/server/src/serverSettings.ts
+124 -35
@@ -16,6 +16,7 @@ import {
16 ServerSettings,
17 ServerSettingsError,
18 type ServerSettingsPatch,
19 + type ManagedPolicySummary,
20 globalIdleCompaction,
21 withIdleCompaction,
22 } from "@t3tools/contracts";
@@ -52,6 +53,7 @@ import {
53 isModelSelectionProviderEnabled,
54 } from "@t3tools/shared/serverSettings";
55 import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
56 +import * as ManagedPolicy from "./policy/ManagedPolicy.ts";
57 import { secretProviderDefinitions } from "./secrets/secretProviderDefinitions.ts";
58 import {
59 readSecretFieldValues,
@@ -225,6 +227,9 @@ export class ServerSettingsService extends Context.Service<
227
228 readonly ready: Effect.Effect<void, ServerSettingsError>;
229
230 + /** The administrator's policy as clients see it; absent when unmanaged. */
231 + readonly managedPolicy?: ManagedPolicySummary | undefined;
232 +
233 readonly getSettings: Effect.Effect<ServerSettings, ServerSettingsError>;
234
235 readonly updateSettings: (
@@ -246,11 +251,15 @@ export class ServerSettingsService extends Context.Service<
251 readonly subscribeChanges: Effect.Effect<Stream.Stream<ServerSettings>, never, Scope.Scope>;
252 }
253 >()("t3/serverSettings/ServerSettingsService") {
249 - static readonly layerTest = (overrides: DeepPartial<ServerSettings> = {}) => layerTest(overrides);
254 + static readonly layerTest = (
255 + overrides: DeepPartial<ServerSettings> = {},
256 + managedPolicy?: ManagedPolicySummary,
257 + ) => layerTest(overrides, managedPolicy);
258 }
259
260 const makeTest = Effect.fn("serverSettings.makeTest")(function* (
261 overrides: DeepPartial<ServerSettings> = {},
262 + managedPolicy?: ManagedPolicySummary,
263 ) {
264 const { automaticGitFetchInterval, providerHealthRefreshInterval, ...overridesForMerge } =
265 overrides;
@@ -281,6 +290,7 @@ const makeTest = Effect.fn("serverSettings.makeTest")(function* (
290 );
291
292 return {
293 + managedPolicy,
294 start: Effect.void,
295 ready: Effect.void,
296 getSettings,
@@ -303,8 +313,11 @@ const makeTest = Effect.fn("serverSettings.makeTest")(function* (
313 } satisfies ServerSettingsService["Service"];
314 });
315
306 -export const layerTest = (overrides: DeepPartial<ServerSettings> = {}) =>
307 - Layer.effect(ServerSettingsService, makeTest(overrides));
316 +/** Test settings; `managedPolicy` only tells consumers a policy applies, it does not lock values. */
317 +export const layerTest = (
318 + overrides: DeepPartial<ServerSettings> = {},
319 + managedPolicy?: ManagedPolicySummary,
320 +) => Layer.effect(ServerSettingsService, makeTest(overrides, managedPolicy));
321
322 // Accept retired token delivery only on load so one old value cannot reset all settings.
323 const PersistedResponseStreamingMode = Schema.Union([
@@ -319,24 +332,24 @@ const PersistedResponseStreamingMode = Schema.Union([
332 }),
333 ),
334 );
322 -const ServerSettingsJson = fromLenientJson(
323 - Schema.Struct({
324 - ...ServerSettings.fields,
325 - responseStreamingMode: PersistedResponseStreamingMode.pipe(
326 - Schema.withDecodingDefault(Effect.succeed("paragraph" as const)),
335 +const PersistedServerSettings = Schema.Struct({
336 + ...ServerSettings.fields,
337 + responseStreamingMode: PersistedResponseStreamingMode.pipe(
338 + Schema.withDecodingDefault(Effect.succeed("paragraph" as const)),
339 + ),
340 + projectSettingsOverrides: Schema.Record(
341 + ProjectId,
342 + keepUnknownOverrideKeys(
343 + Schema.Struct({
344 + ...ProjectSettingsOverrides.fields,
345 + responseStreamingMode: Schema.optionalKey(PersistedResponseStreamingMode),
346 + }),
347 ),
328 - projectSettingsOverrides: Schema.Record(
329 - ProjectId,
330 - keepUnknownOverrideKeys(
331 - Schema.Struct({
332 - ...ProjectSettingsOverrides.fields,
333 - responseStreamingMode: Schema.optionalKey(PersistedResponseStreamingMode),
334 - }),
335 - ),
336 - ).pipe(Schema.withDecodingDefault(Effect.succeed({}))),
337 - }),
338 -);
339 -const decodeServerSettingsJsonExit = Schema.decodeUnknownExit(ServerSettingsJson);
348 + ).pipe(Schema.withDecodingDefault(Effect.succeed({}))),
349 +});
350 +// Parse first and decode second, so a managed policy can fill its defaults in between.
351 +const decodeSettingsFileJsonExit = Schema.decodeUnknownExit(fromLenientJson(Schema.Unknown));
352 +const decodePersistedServerSettingsExit = Schema.decodeUnknownExit(PersistedServerSettings);
353 const LegacyProviderSettingsJson = fromLenientJson(
354 Schema.Struct({
355 providers: Schema.optionalKey(Schema.Record(Schema.String, Schema.Unknown)),
@@ -461,17 +474,33 @@ function selectionSupportsTextGeneration(
474 return settings.providerInstances[selection.instanceId]?.driver !== ACP_REGISTRY_DRIVER;
475 }
476
464 -function resolveTextGenerationProvider(settings: ServerSettings): ServerSettings {
465 - return isModelSelectionProviderEnabled(settings, settings.textGenerationModelSelection) &&
466 - selectionSupportsTextGeneration(settings, settings.textGenerationModelSelection)
477 +type DriverAllowed = (driver: ProviderDriverKind) => boolean;
478 +const anyDriver: DriverAllowed = () => true;
479 +
480 +function resolveTextGenerationProvider(
481 + settings: ServerSettings,
482 + isDriverAllowed: DriverAllowed = anyDriver,
483 +): ServerSettings {
484 + const selection = settings.textGenerationModelSelection;
485 + return isModelSelectionProviderEnabled(settings, selection) &&
486 + selectionSupportsTextGeneration(settings, selection) &&
487 + isDriverAllowed(
488 + settings.providerInstances[selection.instanceId]?.driver ??
489 + ProviderDriverKind.make(selection.instanceId),
490 + )
491 ? settings
468 - : fallbackTextGenerationProvider(settings);
492 + : fallbackTextGenerationProvider(settings, isDriverAllowed);
493 }
494
471 -function fallbackTextGenerationProvider(settings: ServerSettings): ServerSettings {
495 +function fallbackTextGenerationProvider(
496 + settings: ServerSettings,
497 + isDriverAllowed: DriverAllowed,
498 +): ServerSettings {
499 const fallback = fallbackTextGenerationModelSelection(
500 settings.providerInstances,
501 (instanceId, driver) =>
502 + // A default instance id can be configured with another driver.
503 + isDriverAllowed(settings.providerInstances[instanceId]?.driver ?? driver) &&
504 resolveProviderInstanceEnabled(
505 settings.providerInstances[instanceId] ?? { driver, config: {} },
506 ),
@@ -489,6 +518,10 @@ const ATOMIC_SETTINGS_KEYS: ReadonlySet<string> = new Set([
518 "textGenerationModelSelection",
519 "fallbackModelSelection",
520 "pullRequestMergeMethod",
521 + // Empty by default, these hold one whole value, which a managed policy can default.
522 + ...Object.entries(DEFAULT_SERVER_SETTINGS).flatMap(([key, value]) =>
523 + value === null ? [key] : [],
524 + ),
525 ]);
526
527 function stripDefaultServerSettings(current: unknown, defaults: unknown): unknown | undefined {
@@ -610,6 +643,17 @@ const make = Effect.gen(function* () {
643 const pathService = yield* Path.Path;
644 const secretStore = yield* ServerSecretStore.ServerSecretStore;
645 const sql = yield* SqlClient.SqlClient;
646 + const {
647 + settings: managed,
648 + providers: managedProviders,
649 + summary: managedPolicy,
650 + } = yield* ManagedPolicy.ManagedPolicy;
651 + // Locks are laid over every settings value that leaves this service, never persisted.
652 + const toEffective = (settings: ServerSettings) =>
653 + resolveTextGenerationProvider(
654 + managedProviders.applyLimits(managed.applyLocks(settings)),
655 + managedProviders.isDriverAllowed,
656 + );
657 const writeSemaphore = yield* Semaphore.make(1);
658 const cacheKey = "settings" as const;
659 const changesPubSub = yield* PubSub.unbounded<ServerSettings>();
@@ -643,10 +687,22 @@ const make = Effect.gen(function* () {
687 ),
688 );
689
690 + // The file before this write, parsed; only read when policy defaults need it.
691 + const readStoredSettings = Effect.gen(function* () {
692 + if (!(yield* readConfigExists)) return undefined;
693 + const parsed = decodeSettingsFileJsonExit(yield* readRawConfig);
694 + return Exit.isSuccess(parsed) ? parsed.value : undefined;
695 + });
696 +
697 const writeSettingsAtomically = Effect.fnUntraced(
698 function* (settings: ServerSettings) {
699 + const stripped = stripDefaultServerSettings(settings, managed.defaults) ?? {};
700 const sparseSettingsJson = yield* encodeServerSettingsJson(
649 - stripDefaultServerSettings(settings, DEFAULT_SERVER_SETTINGS) ?? {},
701 + managed.keepStored === undefined
702 + ? stripped
703 + : managed.keepStored(stripped, settings, yield* readStoredSettings, (key) =>
704 + ATOMIC_SETTINGS_KEYS.has(key),
705 + ),
706 );
707
708 return yield* writeFileStringAtomically({
@@ -698,14 +754,17 @@ const make = Effect.gen(function* () {
754 );
755
756 const loadSettingsFromDisk = Effect.gen(function* () {
701 - let settings = DEFAULT_SERVER_SETTINGS;
757 + let settings = managed.defaults;
758 let legacyProviders: Readonly<Record<string, unknown>> | undefined;
759 let legacySourceControl: Parameters<typeof migrateLegacySourceControlSettings>[1] = {};
760 let parseFailure = Option.none<unknown>();
761
762 if (yield* readConfigExists) {
763 const raw = yield* readRawConfig;
708 - const decoded = decodeServerSettingsJsonExit(raw);
764 + const parsed = decodeSettingsFileJsonExit(raw);
765 + const decoded = Exit.isFailure(parsed)
766 + ? parsed
767 + : decodePersistedServerSettingsExit(managed.withDefaults(parsed.value));
768 const legacySettings = decodeLegacyProviderSettingsJsonExit(raw);
769 if (legacySettings._tag === "Success") {
770 legacyProviders = legacySettings.value.providers;
@@ -717,7 +776,7 @@ const make = Effect.gen(function* () {
776 if (decoded._tag === "Failure" || legacySettings._tag === "Failure") {
777 const failure = decoded._tag === "Failure" ? decoded : legacySettings;
778 // The file may hold an opt-out we can no longer read; never resume threads on a guess.
720 - settings = { ...DEFAULT_SERVER_SETTINGS, continueThreadsAfterServerUpdate: false };
779 + settings = { ...managed.defaults, continueThreadsAfterServerUpdate: false };
780 if (failure._tag === "Failure") {
781 parseFailure = Option.some(Cause.squash(failure.cause));
782 yield* Effect.logWarning("failed to parse settings.json, using defaults", {
@@ -900,7 +959,7 @@ const make = Effect.gen(function* () {
959 if (materialized?.source === source) return Effect.succeed(materialized.value);
960 const generation = secretWriteGeneration;
961 return materializeSettingsSecrets(source).pipe(
903 - Effect.map(resolveTextGenerationProvider),
962 + Effect.map(toEffective),
963 Effect.tap((value) =>
964 Effect.sync(() => {
965 if (generation === secretWriteGeneration) materialized = { source, value };
@@ -924,7 +983,7 @@ const make = Effect.gen(function* () {
983 ),
984 ),
985 ),
927 - Stream.map(resolveTextGenerationProvider),
986 + Stream.map(toEffective),
987 );
988
989 type SecretChange = {
@@ -1070,6 +1129,7 @@ const make = Effect.gen(function* () {
1129 };
1130
1131 const updateAndPersistSettings = (
1132 + patch: ServerSettingsPatch,
1133 update: (current: ServerSettings) => Effect.Effect<ServerSettings, ServerSettingsError>,
1134 ): Effect.Effect<ServerSettings, ServerSettingsError> =>
1135 writeSemaphore.withPermits(1)(
@@ -1083,7 +1143,35 @@ const make = Effect.gen(function* () {
1143 });
1144 }
1145 const updated = yield* update(current);
1086 - const persisted = yield* persistSettingsSecrets(current, updated);
1146 + // Vet before secrets: a variable the policy hides from clients is not one they removed.
1147 + const vetted = managed.vetWrite(current, yield* normalizeServerSettings(updated), patch);
1148 + if (vetted._tag === "Locked") {
1149 + return yield* new ServerSettingsError({
1150 + settingsPath,
1151 + operation: "write-managed-setting",
1152 + managedSetting: vetted.path,
1153 + managedBy: managedPolicy?.organization,
1154 + });
1155 + }
1156 + const vettedProviders = managedProviders.vetWrite(current, vetted.settings);
1157 + if (vettedProviders._tag === "Locked") {
1158 + return yield* new ServerSettingsError({
1159 + settingsPath,
1160 + operation: "write-managed-setting",
1161 + managedSetting: vettedProviders.path,
1162 + managedBy: managedPolicy?.organization,
1163 + });
1164 + }
1165 + if (vettedProviders._tag === "Disallowed") {
1166 + return yield* new ServerSettingsError({
1167 + settingsPath,
1168 + operation: "use-disallowed-provider",
1169 + providerInstanceId: vettedProviders.instanceId,
1170 + providerLabel: vettedProviders.label,
1171 + managedBy: managedPolicy?.organization,
1172 + });
1173 + }
1174 + const persisted = yield* persistSettingsSecrets(current, vettedProviders.settings);
1175 const next = yield* normalizeServerSettings(persisted.settings);
1176 const materializedNext = yield* Effect.uninterruptibleMask(() =>
1177 Effect.gen(function* () {
@@ -1103,7 +1191,7 @@ const make = Effect.gen(function* () {
1191 }).pipe(Effect.ensuring(invalidateMaterialized)),
1192 );
1193 yield* Cache.set(settingsCache, cacheKey, { settings: next, parseFailure: Option.none() });
1106 - const resolved = resolveTextGenerationProvider(materializedNext);
1194 + const resolved = toEffective(materializedNext);
1195 materialized = { source: next, value: resolved };
1196 yield* emitChange(next);
1197 return resolved;
@@ -1214,17 +1302,18 @@ const make = Effect.gen(function* () {
1302 });
1303
1304 return {
1305 + managedPolicy,
1306 start,
1307 ready: Deferred.await(startedDeferred),
1308 getSettings: getMaterializedSettings,
1309 updateSettings: (patch) =>
1221 - updateAndPersistSettings((current) =>
1310 + updateAndPersistSettings(patch, (current) =>
1311 ensureSecretProviderWritesAllowed(patch, settingsPath).pipe(
1312 Effect.as(applyServerSettingsPatch(current, patch)),
1313 ),
1314 ),
1315 updateProviderInstance: (mutation, patch = {}) =>
1227 - updateAndPersistSettings((current) =>
1316 + updateAndPersistSettings(patch, (current) =>
1317 Effect.gen(function* () {
1318 yield* ensureSecretProviderWritesAllowed(patch, settingsPath);
1319 yield* ensureProviderInstanceMutationAllowed(current, mutation, settingsPath);
apps/server/src/telemetry/AnalyticsService.test.ts
+25
@@ -16,7 +16,10 @@ import * as HttpServerRequest from "effect/http/HttpServerRequest";
16 import * as HttpServerResponse from "effect/http/HttpServerResponse";
17 import * as HostProcess from "@t3tools/shared/HostProcess";
18
19 +import type { ManagedPolicyDocument } from "@t3tools/contracts";
20 +
21 import * as ServerConfig from "../config.ts";
22 +import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
23 import { getTelemetryIdentity } from "./Identify.ts";
24 import * as AnalyticsService from "./AnalyticsService.ts";
25
@@ -119,6 +122,7 @@ const sendFor = (
122 never,
123 AnalyticsService.AnalyticsService | Effect.Services<typeof getTelemetryIdentity>
124 > = recordTwentyEvents,
125 + policy?: ManagedPolicyDocument,
126 ) =>
127 Effect.gen(function* () {
128 const batches: Array<ReadonlyArray<SentEvent>> = [];
@@ -151,6 +155,7 @@ const sendFor = (
155 Layer.succeed(HostProcess.Platform, "win32"),
156 Layer.succeed(HostProcess.Architecture, "x64"),
157 Layer.succeed(HttpClient.HttpClient, client),
158 + ManagedPolicy.layerTest(policy),
159 ),
160 ),
161 );
@@ -240,6 +245,24 @@ it.layer(NodeServices.layer)("AnalyticsService test", (it) => {
245 }),
246 );
247
248 + it.effect(
249 + "sends nothing when a managed policy turns telemetry off, despite the environment",
250 + () =>
251 + Effect.gen(function* () {
252 + const policy = { schemaVersion: 1, organization: "Example Corp" } as const;
253 + const allowed = yield* sendFor(1, respondWithStatus(204), recordTwentyEvents, {
254 + ...policy,
255 + limits: { telemetry: true },
256 + });
257 + assert.equal(allowed.length, 1);
258 + const denied = yield* sendFor(1, respondWithStatus(204), recordTwentyEvents, {
259 + ...policy,
260 + limits: { telemetry: false },
261 + });
262 + assert.deepEqual(denied, []);
263 + }),
264 + );
265 +
266 it.effect("drops a batch the endpoint rejects without sending it again", () =>
267 Effect.gen(function* () {
268 const batches = yield* sendFor(10, respondWithStatus(400));
@@ -286,6 +309,7 @@ it.layer(NodeServices.layer)("AnalyticsService test", (it) => {
309 Layer.mergeAll(
310 Layer.succeed(HostProcess.Platform, "linux"),
311 Layer.succeed(HostProcess.Architecture, "arm64"),
312 + ManagedPolicy.layerTest(),
313 ),
314 ),
315 Layer.provideMerge(NodeHttpServer.layerTest),
@@ -376,6 +400,7 @@ it.layer(NodeServices.layer)("AnalyticsService test", (it) => {
400 Layer.mergeAll(
401 Layer.succeed(HostProcess.Platform, "linux"),
402 Layer.succeed(HostProcess.Architecture, "arm64"),
403 + ManagedPolicy.layerTest(),
404 ),
405 ),
406 Layer.provideMerge(NodeHttpServer.layerTest),
apps/server/src/telemetry/AnalyticsService.ts
+5 -1
@@ -21,6 +21,7 @@ import * as HttpClientResponse from "effect/http/HttpClientResponse";
21
22 import packageJson from "../../package.json" with { type: "json" };
23 import * as ServerConfig from "../config.ts";
24 +import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
25 import { getTelemetryIdentity, type TelemetryOwner } from "./Identify.ts";
26
27 interface BufferedAnalyticsEvent {
@@ -119,9 +120,12 @@ export const make = Effect.gen(function* () {
120 const telemetryConfig = yield* TelemetryEnvConfig;
121 const hostEnvironment = yield* HostProcess.Environment;
122 const awaitingShellConsent = hostEnvironment.T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING === "1";
123 + // A managed policy can switch analytics off over the environment, never on.
124 + const policyAllows =
125 + ManagedPolicy.deniedBy(yield* ManagedPolicy.ManagedPolicy, "telemetry") === undefined;
126 // A cached PATH does not establish consent from the current login shell.
127 const telemetryEnabled = Effect.suspend(() => {
124 - if (!telemetryConfig.enabled) return Effect.succeed(false);
128 + if (!telemetryConfig.enabled || !policyAllows) return Effect.succeed(false);
129 if (!awaitingShellConsent) return Effect.succeed(true);
130 if (hostEnvironment.T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING === "1")
131 return Effect.succeed(false);
apps/server/src/ws.test.ts
+4 -1
@@ -111,6 +111,7 @@ import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
111 import * as ServerConfigModule from "./config.ts";
112 import * as Keybindings from "./keybindings.ts";
113 import * as ServerSettings from "./serverSettings.ts";
114 +import * as ManagedPolicy from "./policy/ManagedPolicy.ts";
115
116 import * as EventStore from "./orchestration-v2/EventStore.ts";
117 import * as ProjectionMaintenance from "./orchestration-v2/ProjectionMaintenance.ts";
@@ -602,7 +603,9 @@ const layerUnusedConfigRpcServices = Layer.mergeAll(
603
604 const layerConfigSources = Layer.mergeAll(
605 Keybindings.layer,
605 - ServerSettings.layer.pipe(Layer.provide(ServerSecretStore.layer)),
606 + ServerSettings.layer.pipe(
607 + Layer.provide(Layer.merge(ServerSecretStore.layer, ManagedPolicy.layerTest())),
608 + ),
609 ).pipe(
610 Layer.provideMerge(Layer.fresh(SqlitePersistence.layerMemory)),
611 Layer.provideMerge(
apps/server/src/ws.ts
+3
@@ -1831,6 +1831,9 @@ export const layerWsRpc = (
1831 otlpLogsEnabled: config.otlpLogsUrl !== undefined,
1832 },
1833 settings,
1834 + ...(serverSettings.managedPolicy === undefined
1835 + ? {}
1836 + : { managedPolicy: serverSettings.managedPolicy }),
1837 shellResumeCompletionMarker: true,
1838 shellThreadFamilies: true,
1839 shellOlderSettled: true,
apps/web/src/components/ManagedPolicy.tsx new
+71
@@ -0,0 +1,71 @@
1 +import type { ManagedPolicySummary } from "@t3tools/contracts";
2 +import { BuildingIcon } from "lucide-react";
3 +import type { ReactNode } from "react";
4 +
5 +import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
6 +
7 +/**
8 + * A control an administrator's policy turns off: shown inert, with the policy's reason on hover
9 + * and focus. Without a reason it renders the control untouched.
10 + */
11 +export function ManagedControl({
12 + reason,
13 + children,
14 +}: {
15 + reason: string | undefined;
16 + children: ReactNode;
17 +}) {
18 + if (reason === undefined) return children;
19 + return (
20 + <Tooltip>
21 + <TooltipTrigger
22 + render={
23 + <span
24 + tabIndex={0}
25 + role="group"
26 + aria-disabled="true"
27 + aria-label={reason}
28 + className="inline-flex rounded-md outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"
29 + />
30 + }
31 + >
32 + <span inert className="inline-flex opacity-50">
33 + {children}
34 + </span>
35 + </TooltipTrigger>
36 + <TooltipPopup side="top">{reason}</TooltipPopup>
37 + </Tooltip>
38 + );
39 +}
40 +
41 +/** One line of policy text with the building mark, for places a whole feature is managed. */
42 +export function ManagedNotice({ children }: { children: ReactNode }) {
43 + return (
44 + <p className="flex items-start gap-2 text-muted-foreground text-xs leading-relaxed">
45 + <BuildingIcon aria-hidden="true" className="mt-0.5 size-3.5 shrink-0" />
46 + <span>{children}</span>
47 + </p>
48 + );
49 +}
50 +
51 +/** "This environment is managed by <organization>", linking the support page when there is one. */
52 +export function ManagedByOrganization({ policy }: { policy: ManagedPolicySummary }) {
53 + return (
54 + <ManagedNotice>
55 + This environment is managed by {policy.organization}.
56 + {policy.supportUrl ? (
57 + <>
58 + {" "}
59 + <a
60 + href={policy.supportUrl}
61 + target="_blank"
62 + rel="noreferrer"
63 + className="text-foreground underline underline-offset-2"
64 + >
65 + Get help
66 + </a>
67 + </>
68 + ) : null}
69 + </ManagedNotice>
70 + );
71 +}
apps/web/src/components/ServerUpdateAction.tsx
+38 -1
@@ -2,6 +2,7 @@ import { useAtomValue } from "@effect/atom-react";
2 import {
3 AuthEnvironmentMaintainScope,
4 type AuthSessionState,
5 + managedUpdatesDenial,
6 sessionGrantsScope,
7 } from "@t3tools/contracts";
8 import type { AsyncResult } from "effect/reactivity";
@@ -26,8 +27,11 @@ import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
27 import { serverEnvironment, updateOutdatedServer } from "~/state/server";
28 import { appAtomRegistry } from "~/rpc/atomRegistry";
29 import { useAtomCommand } from "~/state/use-atom-command";
29 -import { manualServerUpdateCommand } from "~/versionSkew";
30 import { useServerConfigs } from "~/state/entities";
31 +import { useManagedPolicy } from "~/state/managedPolicy";
32 +import { environmentPresentations } from "~/state/presentation";
33 +import { ManagedControl } from "./ManagedPolicy";
34 +import { manualServerUpdateCommand } from "~/versionSkew";
35 import { crossesReleaseTrack } from "@t3tools/shared/cliRelease";
36 import { Button } from "./ui/button";
37 import { toastManager } from "./ui/toast";
@@ -44,6 +48,14 @@ export function serverUpdateStageLabel(stage: ServerUpdateStage): string {
48 return UPDATE_STAGE_LABELS[stage];
49 }
50
51 +/** Why the environment's policy refuses server updates, read outside render. */
52 +function readUpdatesDenial(environmentId: EnvironmentId): string | undefined {
53 + return managedUpdatesDenial(
54 + appAtomRegistry.get(environmentPresentations.serverConfigsAtom).get(environmentId)
55 + ?.managedPolicy,
56 + );
57 +}
58 +
59 const CROSS_TRACK_NOTE = "Switch tracks in About → Update track";
60
61 /** Hosts refuse a Stable/Nightly crossing outside a track switch, which checks the database first. */
@@ -103,6 +115,17 @@ export function useServerUpdate() {
115 { quiet = false }: { readonly quiet?: boolean } = {},
116 ): Promise<ServerUpdateOutcome> => {
117 const { environmentId, serverLabel, selfUpdate, targetVersion } = target;
118 + const denial = readUpdatesDenial(environmentId);
119 + if (denial !== undefined) {
120 + if (!quiet) {
121 + toastManager.add({
122 + type: "error",
123 + title: `${serverLabel} not updated`,
124 + description: denial,
125 + });
126 + }
127 + return { status: "failed", message: denial };
128 + }
129 if (
130 !canUpdateServer(appAtomRegistry.get(environmentSession.sessionStateAtom(environmentId))) ||
131 pendingUpdateEnvironmentIds.has(environmentId)
@@ -163,6 +186,7 @@ export function ServerUpdatesAction({
186 (target) =>
187 target.selfUpdate !== null &&
188 (target.selfUpdate !== "desktop-managed" || target.desktopAppUpdate) &&
189 + managedUpdatesDenial(serverConfigs.get(target.environmentId)?.managedPolicy) === undefined &&
190 !refusedCrossing(target, serverConfigs.get(target.environmentId)?.environment.serverVersion),
191 );
192 const handleUpdate = async () => {
@@ -249,6 +273,7 @@ export function ServerUpdateAction({
273 const serverVersion = useServerConfigs().get(environmentId)?.environment.serverVersion;
274 const sessionStateAtom = environmentSession.sessionStateAtom(environmentId);
275 const canUpdate = canUpdateServer(useAtomValue(sessionStateAtom));
276 + const updatesDenial = managedUpdatesDenial(useManagedPolicy(environmentId));
277 const update = useServerUpdate();
278 const { copyToClipboard } = useCopyToClipboard<{ command: string }>({
279 target: installation?.kind === "npm-global" ? "update command" : "relaunch command",
@@ -298,6 +323,18 @@ export function ServerUpdateAction({
323 });
324 };
325
326 + if (updatesDenial !== undefined) {
327 + return appearance === "icon" ? (
328 + <ManagedControl reason={updatesDenial}>
329 + <Button size="icon-xs" variant="ghost-muted" aria-label={updatesDenial} disabled>
330 + <CircleArrowUpIcon className="size-3.5" />
331 + </Button>
332 + </ManagedControl>
333 + ) : (
334 + <span className="text-muted-foreground text-xs">{updatesDenial}</span>
335 + );
336 + }
337 +
338 if (selfUpdate === "desktop-managed" && !desktopAppUpdate) {
339 return (
340 <span className="text-muted-foreground text-xs">
apps/web/src/components/auth/ConnectAgentSurface.tsx
+22 -2
@@ -4,6 +4,8 @@ import {
4 AuthMcpApprovalError,
5 AuthMcpClientAccess,
6 AuthMcpAuthorizationRequest,
7 + isRuntimeModeAbove,
8 + managedRuntimeModeCeilingMessage,
9 } from "@t3tools/contracts";
10 import { Radio as RadioPrimitive } from "@base-ui/react/radio";
11 import { isLoopbackHost } from "@t3tools/shared/preview";
@@ -209,7 +211,12 @@ export function ConnectAgentSurface() {
211 onValueChange={(value) => setAccess(value as AuthMcpClientAccess)}
212 >
213 {AuthMcpClientAccess.literals.map((option) => (
212 - <AccessOption key={option} access={option} selected={option === access} />
214 + <AccessOption
215 + key={option}
216 + access={option}
217 + selected={option === access}
218 + managedReason={ceilingReason(details, option)}
219 + />
220 ))}
221 </RadioGroup>
222 <p className="text-xs text-muted-foreground">
@@ -276,17 +283,30 @@ function ConnectAgentHeading({
283 return <StandalonePageHeader context="Agent sign-in" title={title} description={description} />;
284 }
285
286 +/** Why a managed policy keeps `access` from being granted, or undefined when it may be. */
287 +function ceilingReason(details: AuthMcpApprovalDetails, access: AuthMcpClientAccess) {
288 + const ceiling = details.runtimeModeCeiling;
289 + return ceiling === undefined ||
290 + access === "read-only" ||
291 + !isRuntimeModeAbove(access, ceiling.maxRuntimeMode)
292 + ? undefined
293 + : managedRuntimeModeCeilingMessage(ceiling.organization, ceiling.maxRuntimeMode);
294 +}
295 +
296 function AccessOption({
297 access,
298 selected,
299 + managedReason,
300 }: {
301 readonly access: AuthMcpClientAccess;
302 readonly selected: boolean;
303 + readonly managedReason: string | undefined;
304 }) {
305 const { label, description, icon: Icon } = accessConfig[access];
306 return (
307 <RadioPrimitive.Root
308 value={access}
309 + disabled={managedReason !== undefined}
310 className={cn(
311 "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]",
312 "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({
324 />
325 <span className="min-w-0">
326 <span className="block text-sm font-medium text-foreground">{label}</span>
307 - <span className="block text-xs text-muted-foreground">{description}</span>
327 + <span className="block text-xs text-muted-foreground">{managedReason ?? description}</span>
328 </span>
329 </RadioPrimitive.Root>
330 );
apps/web/src/components/chat/ChatComposer.tsx
+47 -6
@@ -38,6 +38,8 @@ import type {
38 import {
39 EnvironmentRequestInvalidError,
40 AuthOrchestrationOperateScope,
41 + clampManagedRuntimeMode,
42 + managedRuntimeModeDenial,
43 ProviderDriverKind,
44 ProviderInstanceId,
45 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
@@ -230,7 +232,9 @@ import { observeResize } from "~/lib/observeResize";
232
233 const isEnvironmentRequestInvalidError = Schema.is(EnvironmentRequestInvalidError);
234 import { toastManager } from "../ui/toast";
233 -import { PlayIcon } from "lucide-react";
235 +import { BuildingIcon, PlayIcon } from "lucide-react";
236 +import { Button } from "../ui/button";
237 +import { useManagedPolicy } from "../../state/managedPolicy";
238 import { proposedPlanTitle } from "@t3tools/shared/proposedPlanText";
239 import { hasProviderSetup } from "./ProviderStatusBanner";
240 import { type AppModelOption, getAppModelOptionsForInstance } from "../../modelSelection";
@@ -910,9 +914,20 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
914 runtimeMode,
915 selectedProviderEntry?.snapshot.supportedRuntimeModes,
916 );
913 - const compatibleRuntimeModeOptions = runtimeModeOptions.filter((option) =>
914 - compatibleRuntimeModes.includes(option.mode),
915 - );
917 + // Modes above an administrator's ceiling stay listed, disabled with the reason.
918 + const managedPolicy = useManagedPolicy(environmentId);
919 + const compatibleRuntimeModeOptions = runtimeModeOptions
920 + .filter((option) => compatibleRuntimeModes.includes(option.mode))
921 + .map((option) => {
922 + const disabledReason = managedRuntimeModeDenial(managedPolicy, option.mode);
923 + return disabledReason === undefined ? option : { ...option, disabledReason };
924 + });
925 + // A thread or draft already above the ceiling would be refused; offer the broadest mode left.
926 + const runtimeModeCeilingDenial = managedRuntimeModeDenial(managedPolicy, compatibleRuntimeMode);
927 + const runtimeModeCeilingFallback =
928 + runtimeModeCeilingDenial === undefined
929 + ? undefined
930 + : clampManagedRuntimeMode(managedPolicy, compatibleRuntimeMode, compatibleRuntimeModes);
931
932 const providerSendBlockReason = getAntigravitySendBlockReason(
933 selectedProviderEntry?.snapshot,
@@ -924,6 +939,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
939 (activePendingProgress
940 ? attachmentBlockReason
941 : (attachmentBlockReason ??
942 + runtimeModeCeilingDenial ??
943 (multipleModelSelections === null ? providerSendBlockReason : null)));
944 const isSendDisabled = sendDisabledReason !== null;
945 const selectedProviderStatus = selectedProviderEntry?.snapshot ?? null;
@@ -2349,12 +2365,37 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
2365 );
2366 // An open question owns the space above the composer. Only a machine problem,
2367 // which is why an answer could not go through, stays beside it.
2368 + const bannerItems: readonly ComposerBannerStackItem[] =
2369 + runtimeModeCeilingDenial === undefined || activePendingProgress
2370 + ? props.bannerItems
2371 + : [
2372 + ...props.bannerItems,
2373 + {
2374 + id: "managed-runtime-mode",
2375 + variant: "warning",
2376 + icon: <BuildingIcon />,
2377 + title: runtimeModeCeilingDenial,
2378 + ...(runtimeModeCeilingFallback === undefined
2379 + ? {}
2380 + : {
2381 + actions: (
2382 + <Button
2383 + size="xs"
2384 + variant="ghost"
2385 + onClick={() => handleRuntimeModeChange(runtimeModeCeilingFallback)}
2386 + >
2387 + Switch to {runtimeModeConfig[runtimeModeCeilingFallback].label}
2388 + </Button>
2389 + ),
2390 + }),
2391 + },
2392 + ];
2393 const shelfItems = hasBlockingComposerTopDrawer
2353 - ? props.bannerItems.filter(
2394 + ? bannerItems.filter(
2395 (item) =>
2396 item.group === "environment" && (item.variant === "error" || item.variant === "warning"),
2397 )
2357 - : props.bannerItems;
2398 + : bannerItems;
2399
2400 const insertComposerText = (
2401 text: string,
apps/web/src/components/chat/ComposerFooterControls.tsx
+12 -8
@@ -21,8 +21,11 @@ import { ProviderModelPicker } from "./ProviderModelPicker";
21 import { runtimeModeConfig } from "./runtimeModeConfig";
22 import { useComposerMenuState } from "./useComposerMenuState";
23
24 -export type RuntimeModeOption = { mode: RuntimeMode } & (typeof runtimeModeConfig)[RuntimeMode];
25 -const supervisedRuntimeModeOption = {
24 +export type RuntimeModeOption = {
25 + mode: RuntimeMode;
26 + disabledReason?: string;
27 +} & (typeof runtimeModeConfig)[RuntimeMode];
28 +const supervisedRuntimeModeOption: RuntimeModeOption = {
29 mode: "approval-required" as const,
30 ...runtimeModeConfig["approval-required"],
31 };
@@ -161,9 +164,7 @@ export const ComposerFooterModeControls = memo(function ComposerFooterModeContro
164 */
165 export function ComposerPermissionsSection(props: {
166 runtimeMode: RuntimeMode;
164 - runtimeModeOptions: ReadonlyArray<
165 - { mode: RuntimeMode } & (typeof runtimeModeConfig)[RuntimeMode]
166 - >;
167 + runtimeModeOptions: ReadonlyArray<RuntimeModeOption>;
168 onRuntimeModeChange: (mode: RuntimeMode) => void;
169 }) {
170 // Hover or keyboard focus previews a mode's name and description before a pick.
@@ -203,6 +204,7 @@ export function ComposerPermissionsSection(props: {
204 <MenuPrimitive.RadioItem
205 key={option.mode}
206 value={option.mode}
207 + disabled={option.disabledReason !== undefined}
208 label={option.label}
209 aria-label={option.label}
210 aria-describedby={`${descriptionId}-${option.mode}`}
@@ -211,7 +213,7 @@ export function ComposerPermissionsSection(props: {
213 onPointerLeave={() => setPreviewMode(null)}
214 onFocus={() => setPreviewMode(option.mode)}
215 onBlur={() => setPreviewMode(null)}
214 - 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"
216 + 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"
217 >
218 <OptionIcon aria-hidden="true" className="size-3.5" />
219 </MenuPrimitive.RadioItem>
@@ -221,7 +223,7 @@ export function ComposerPermissionsSection(props: {
223 {/* Static per-mode descriptions for screen readers; the preview below is visual only. */}
224 {props.runtimeModeOptions.map((option) => (
225 <span key={option.mode} id={`${descriptionId}-${option.mode}`} className="sr-only">
224 - {option.description}
226 + {option.disabledReason ?? option.description}
227 </span>
228 ))}
229 <div className="grid gap-0.5" aria-hidden="true">
@@ -235,7 +237,9 @@ export function ComposerPermissionsSection(props: {
237 {shown.label}
238 </span>
239 {/* Two lines reserved so the menu does not shift while you preview modes. */}
238 - <span className="min-h-8 text-muted-foreground text-xs leading-4">{shown.description}</span>
240 + <span className="min-h-8 text-muted-foreground text-xs leading-4">
241 + {shown.disabledReason ?? shown.description}
242 + </span>
243 </div>
244 </div>
245 );
apps/web/src/components/chat/ModelPickerSidebar.tsx
+2 -1
@@ -13,7 +13,8 @@ import {
13
14 function describeUnavailableInstance(entry: ProviderInstanceEntry): string {
15 const label = entry.displayName;
16 - if (!entry.enabled || entry.status === "disabled") {
16 + // An unavailable instance (a driver this build lacks or the policy leaves out) says why instead.
17 + if ((!entry.enabled && entry.isAvailable) || entry.status === "disabled") {
18 return `${label}: Disabled in settings.`;
19 }
20 if (entry.status === "ready" && entry.isAvailable) {
apps/web/src/components/chat/ThreadAutomationsPanel.tsx
+3 -1
@@ -41,7 +41,9 @@ function taskScheduleLine(task: ScheduledTask) {
41 return (
42 <>
43 {scheduleLabel(task.schedule)}
44 - {task.enabled && task.nextRunAt !== null ? (
44 + {task.blockedByPolicy !== undefined ? (
45 + ` · ${task.blockedByPolicy}`
46 + ) : task.enabled && task.nextRunAt !== null ? (
47 <>
48 {" · next "}
49 <ScheduledRelativeLabel value={task.nextRunAt} />
apps/web/src/components/chat/guestShareAvailability.ts
+9 -6
@@ -1,4 +1,4 @@
1 -import type { EnvironmentId } from "@t3tools/contracts";
1 +import { type EnvironmentId, managedCapabilityDenial } from "@t3tools/contracts";
2 import { Atom } from "effect/reactivity";
3
4 import { environmentPresentations } from "~/state/presentation";
@@ -7,12 +7,15 @@ import { serverEnvironment } from "~/state/server";
7 /**
8 * Whether this environment offers "Share with guest": the user may create links there, and its
9 * Guest links beta is on (Settings > Labs). The server refuses links while the beta is off.
10 + * Guests arrive through T3 Connect, so a policy that turns Connect off hides sharing too.
11 */
12 export const canShareWithGuestAtom = Atom.family((environmentId: EnvironmentId) =>
12 - Atom.make(
13 - (get) =>
13 + Atom.make((get) => {
14 + const serverConfig = get(environmentPresentations.serverConfigsAtom).get(environmentId);
15 + return (
16 get(serverEnvironment.createGuestShare.permissionAtom(environmentId)) &&
15 - get(environmentPresentations.serverConfigsAtom).get(environmentId)?.settings
16 - .guestSharingEnabled === true,
17 - ).pipe(Atom.withLabel(`guest-share:available:${environmentId}`)),
17 + serverConfig?.settings.guestSharingEnabled === true &&
18 + managedCapabilityDenial(serverConfig.managedPolicy, "connect") === undefined
19 + );
20 + }).pipe(Atom.withLabel(`guest-share:available:${environmentId}`)),
21 );
apps/web/src/components/cloud/ConnectOnboardingDialog.tsx
+11 -2
@@ -1,6 +1,11 @@
1 import { useAuth } from "@clerk/react";
2 import { useAtomValue } from "@effect/atom-react";
3 -import { AuthRelayReadScope, AuthRelayWriteScope, type AuthSessionState } from "@t3tools/contracts";
3 +import {
4 + AuthRelayReadScope,
5 + AuthRelayWriteScope,
6 + type AuthSessionState,
7 + managedCapabilityDenial,
8 +} from "@t3tools/contracts";
9 import { AsyncResult, Atom } from "effect/reactivity";
10 import { useState } from "react";
11
@@ -19,6 +24,7 @@ import {
24 usePrimaryEnvironment,
25 usePrimaryEnvironmentId,
26 } from "~/state/environments";
27 +import { usePrimaryManagedPolicy } from "~/state/managedPolicy";
28 import { environmentSession, readEnvironmentScope, useEnvironmentScope } from "~/state/session";
29 import {
30 type T3ConnectAccountPageUrl,
@@ -64,7 +70,10 @@ function ConfiguredConnectOnboardingDialog() {
70 );
71 const canReadRelay = useEnvironmentScope(primaryEnvironmentId, AuthRelayReadScope);
72 const canWriteRelay = useEnvironmentScope(primaryEnvironmentId, AuthRelayWriteScope);
67 - const canManageRelay = canReadRelay && canWriteRelay;
73 + // A policy that turns Connect off leaves nothing to publish; reaching other devices still works.
74 + const connectAllowed =
75 + managedCapabilityDenial(usePrimaryManagedPolicy(), "connect") === undefined;
76 + const canManageRelay = canReadRelay && canWriteRelay && connectAllowed;
77 const sessionScopesKnown =
78 primaryEnvironmentId === null ? environmentsReady : primarySessionState._tag !== "Initial";
79
apps/web/src/components/desktopUpdate.logic.ts
+5 -1
@@ -145,17 +145,21 @@ export function canCheckForUpdate(state: DesktopUpdateState | null): boolean {
145 );
146 }
147
148 +/** `managedDenial` is this machine's policy refusing updates (`managedUpdatesDenial`); it wins. */
149 export function getDesktopUpdateDisabledReason(
150 state: Pick<DesktopUpdateState, "enabled" | "status" | "message"> | null,
151 + managedDenial?: string,
152 ): string | null {
153 + if (managedDenial !== undefined) return managedDenial;
154 if (!state || (state.enabled && state.status !== "disabled")) return null;
155 return state.message?.trim() || "Automatic updates are not available in this build.";
156 }
157
158 export function getDesktopUpdateIdleTooltip(
159 state: Pick<DesktopUpdateState, "enabled" | "status" | "message"> | null,
160 + managedDenial?: string,
161 ) {
158 - const disabledReason = getDesktopUpdateDisabledReason(state);
162 + const disabledReason = getDesktopUpdateDisabledReason(state, managedDenial);
163 return disabledReason
164 ? { title: "Updates unavailable", detail: disabledReason }
165 : { title: "Check for updates", detail: null };
apps/web/src/components/onboarding/WelcomeWizard.tsx
+21 -4
@@ -20,6 +20,7 @@ import {
20 CommandId,
21 defaultInstanceIdForDriver,
22 AuthOrchestrationOperateScope,
23 + isManagedDriverAllowed,
24 ProviderDriverKind,
25 ThreadId,
26 } from "@t3tools/contracts";
@@ -60,6 +61,11 @@ import { newProjectId, randomUUID } from "../../lib/utils";
61 import { agentSessionImport } from "../../state/agentSessions";
62 import { readProjects, waitForProject } from "../../state/entities";
63 import { useEnvironments, usePrimaryEnvironment } from "../../state/environments";
64 +import {
65 + managedInstanceLocks,
66 + managedTelemetryOffMessage,
67 + usePrimaryManagedPolicy,
68 +} from "../../state/managedPolicy";
69 import {
70 isOnboardingRelayEnvironment,
71 resolveOnboardingSetup,
@@ -310,6 +316,7 @@ function ConnectionStep({
316 readonly onPaired: (environmentId: EnvironmentId) => void;
317 }) {
318 const { environments } = useEnvironments();
319 + const telemetryOff = managedTelemetryOffMessage(usePrimaryManagedPolicy());
320 const cloudEnabled = hasCloudPublicConfig();
321 const directEnvironments = environments.filter(
322 (environment) => !cloudEnabled || !isOnboardingRelayEnvironment(environment),
@@ -434,8 +441,9 @@ function ConnectionStep({
441 ) : null}
442 <div className="mt-6 flex flex-col-reverse gap-4 sm:flex-row sm:items-center sm:justify-between sm:gap-6">
443 <p className="min-w-0 text-xs leading-relaxed text-muted-foreground">
437 - T3 Code collects anonymous usage data to help us improve it. To read more about how your
438 - data is used and how to opt out, see our{" "}
444 + {telemetryOff ?? "T3 Code collects anonymous usage data to help us improve it."} To read
445 + more about how your data is used{telemetryOff === undefined ? " and how to opt out" : ""},
446 + see our{" "}
447 <a
448 className="underline underline-offset-2 hover:text-foreground"
449 href={PRIVACY_POLICY_URL}
@@ -728,8 +736,16 @@ function ConnectedAgentsStep({
736 }, [environmentId, refreshProviders]);
737
738 const byDriver = selectOnboardingProvidersByDriver(providers);
739 + const managedPolicy = serverConfig?.managedPolicy;
740 + // A policy that owns Codex's launch settings also rules out ChatGPT's own runtime.
741 + const chatGptAllowed =
742 + managedInstanceLocks(managedPolicy, ProviderDriverKind.make("codex"))?.configKeys.has(
743 + "setupMode",
744 + ) !== true;
745
732 - const primaryAgents = PRIMARY_AGENT_DRIVERS.flatMap((driver) => {
746 + const primaryAgents = PRIMARY_AGENT_DRIVERS.filter((driver) =>
747 + isManagedDriverAllowed(managedPolicy, ProviderDriverKind.make(driver)),
748 + ).flatMap((driver) => {
749 const instances =
750 driver === "codex" ? providers?.filter((provider) => provider.driver === driver) : undefined;
751 return instances?.length
@@ -831,7 +847,8 @@ function ConnectedAgentsStep({
847 ),
848 )}
849 </div>
834 - {providers?.some(
850 + {chatGptAllowed &&
851 + providers?.some(
852 (provider) =>
853 provider.driver === "codex" && getOnboardingProviderState(provider) === "ready",
854 ) ? (
apps/web/src/components/settings/AddProviderInstanceDialog.tsx
+39 -14
@@ -13,6 +13,7 @@ import {
13 type EnvironmentId,
14 type ProviderInstanceConfig,
15 type ProviderInstanceEnvironmentVariable,
16 + isManagedDriverAllowed,
17 } from "@t3tools/contracts";
18
19 import {
@@ -22,6 +23,7 @@ import {
23
24 import { cn } from "../../lib/utils";
25 import { normalizeProviderAccentColor } from "../../providerInstances";
26 +import { managedInstanceLocks, useManagedPolicy } from "../../state/managedPolicy";
27 import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";
28 import { Button } from "../ui/button";
29 import { ChatGptConnectionButton } from "./ChatGptConnectionButton";
@@ -167,7 +169,20 @@ export function AddProviderInstanceDialog({
169
170 const [wizardStep, setWizardStep] = useState(0);
171 const [addingChatGptAccount, setAddingChatGptAccount] = useState(false);
170 - const [driver, setDriver] = useState<ProviderDriverKind>(DEFAULT_DRIVER_KIND);
172 + // Drivers the administrator's policy leaves out are not offered at all.
173 + const managedPolicy = useManagedPolicy(environmentId);
174 + const featuredDriverOptions = FEATURED_DRIVER_OPTIONS.filter((option) =>
175 + isManagedDriverAllowed(managedPolicy, option.driverKind),
176 + );
177 + const moreDriverOptions = MORE_DRIVER_OPTIONS.filter((option) =>
178 + isManagedDriverAllowed(managedPolicy, option.driverKind),
179 + );
180 + const acpRegistryAllowed = isManagedDriverAllowed(managedPolicy, ACP_REGISTRY_DRIVER_KIND);
181 + const [driver, setDriver] = useState<ProviderDriverKind>(
182 + () =>
183 + (featuredDriverOptions[0] ?? moreDriverOptions[0])?.driverKind ??
184 + (acpRegistryAllowed ? ACP_REGISTRY_DRIVER_KIND : DEFAULT_DRIVER_KIND),
185 + );
186 const [identityByDriver, setIdentityByDriver] = useState<Record<string, ProviderIdentityDraft>>(
187 {},
188 );
@@ -361,6 +376,9 @@ export function AddProviderInstanceDialog({
376 setHasAttemptedSubmit(false);
377 };
378
379 + // A policy that owns this driver's launch settings also rules out ChatGPT's own runtime.
380 + const driverLocks = managedInstanceLocks(managedPolicy, driver);
381 +
382 const handleSave = async () => {
383 if (!readEnvironmentScope(environmentId, AuthProvidersManageScope)) return;
384 if (isSaving || createdInstanceId) return;
@@ -467,7 +485,7 @@ export function AddProviderInstanceDialog({
485 Provider
486 </div>
487 <ProviderOptionGrid
470 - options={FEATURED_DRIVER_OPTIONS}
488 + options={featuredDriverOptions}
489 value={driver}
490 disabled={isPreparingRegistryAgent}
491 onValueChange={selectDriver}
@@ -476,7 +494,7 @@ export function AddProviderInstanceDialog({
494 <MultipleAccountsNote environmentId={environmentId} driver={driver} />
495 </div>
496
479 - {wizardStep === 0 ? (
497 + {wizardStep === 0 && (moreDriverOptions.length > 0 || acpRegistryAllowed) ? (
498 <Collapsible open={showMoreProviders} onOpenChange={setShowMoreProviders}>
499 <div className="flex pt-2">
500 <CollapsibleTrigger render={<Button variant="ghost-muted" size="xs" />}>
@@ -491,18 +509,20 @@ export function AddProviderInstanceDialog({
509 <CollapsiblePanel animate={false}>
510 <div className="space-y-4 pt-4">
511 <ProviderOptionGrid
494 - options={MORE_DRIVER_OPTIONS}
512 + options={moreDriverOptions}
513 value={driver}
514 disabled={isPreparingRegistryAgent}
515 onValueChange={selectDriver}
516 aria-label="More providers"
517 />
500 - <div className="flex items-center gap-3 text-xs text-muted-foreground">
501 - <div aria-hidden className="flex-1 border-t border-border/70" />
502 - <span>Or choose from ACP Registry</span>
503 - <div aria-hidden className="flex-1 border-t border-border/70" />
504 - </div>
505 - {isAcpRegistry && isManualAcpConfiguration ? (
518 + {!acpRegistryAllowed ? null : (
519 + <div className="flex items-center gap-3 text-xs text-muted-foreground">
520 + <div aria-hidden className="flex-1 border-t border-border/70" />
521 + <span>Or choose from ACP Registry</span>
522 + <div aria-hidden className="flex-1 border-t border-border/70" />
523 + </div>
524 + )}
525 + {!acpRegistryAllowed ? null : isAcpRegistry && isManualAcpConfiguration ? (
526 <div className="grid gap-4">
527 <div className="flex items-start justify-between gap-3">
528 <div>
@@ -684,6 +704,9 @@ export function AddProviderInstanceDialog({
704 idPrefix={`add-provider-${driver}`}
705 variant="settings"
706 onChange={setConfigDraft}
707 + managed={
708 + driverLocks && { keys: driverLocks.configKeys, reason: driverLocks.reason }
709 + }
710 environmentId={environmentId}
711 />
712 </SettingsGroup>
@@ -716,10 +739,12 @@ export function AddProviderInstanceDialog({
739 <Button variant="outline" size="sm" onClick={() => navigateToStep(1)}>
740 Configure manually
741 </Button>
719 - <ChatGptConnectionButton
720 - size="sm"
721 - onClick={() => setAddingChatGptAccount(true)}
722 - />
742 + {driverLocks?.configKeys.has("setupMode") ? null : (
743 + <ChatGptConnectionButton
744 + size="sm"
745 + onClick={() => setAddingChatGptAccount(true)}
746 + />
747 + )}
748 </>
749 ) : wizardStep < (isAcpRegistry ? 1 : 2) ? (
750 <Button
apps/web/src/components/settings/AuthorizedClientsSettings.tsx
+34 -17
@@ -8,6 +8,7 @@ import {
8 AuthFilesystemReadScope,
9 AuthStandardClientScopes,
10 AuthTerminalReadScope,
11 + managedCapabilityDenial,
12 type AuthEnvironmentScope,
13 type AuthGrantScope,
14 type AuthPairingCredentialResult,
@@ -53,6 +54,8 @@ import {
54 } from "~/environments/primary";
55 import { readEnvironmentScope } from "~/state/session";
56 import { usePrimaryEnvironmentId } from "~/state/environments";
57 +import { usePrimaryManagedPolicy } from "~/state/managedPolicy";
58 +import { ManagedControl } from "../ManagedPolicy";
59 import { ConnectionStatusDot } from "../ConnectionStatusDot";
60 import { ITEM_ROW_CLASSNAME, ITEM_ROW_INNER_CLASSNAME } from "./itemRows";
61 import {
@@ -577,6 +580,7 @@ export const AuthorizedClientsHeaderAction = memo(function AuthorizedClientsHead
580 delegatableScopes,
581 }: AuthorizedClientsHeaderActionProps) {
582 const primaryEnvironmentId = usePrimaryEnvironmentId();
583 + const pairingDenial = managedCapabilityDenial(usePrimaryManagedPolicy(), "remoteClients");
584 const [dialogOpen, setDialogOpen] = useState(false);
585 const [pairingLabel, setPairingLabel] = useState("");
586 const [pairingScopes, setPairingScopes] = useState<ReadonlyArray<AuthGrantScope>>([
@@ -634,8 +638,16 @@ export const AuthorizedClientsHeaderAction = memo(function AuthorizedClientsHead
638 >
639 {isRevokingOtherClients ? "Revoking…" : "Revoke others"}
640 </Button>
641 + {pairingDenial !== undefined ? (
642 + <ManagedControl reason={pairingDenial}>
643 + <Button size="xs" variant="default" disabled>
644 + <PlusIcon className="size-3" />
645 + Create link
646 + </Button>
647 + </ManagedControl>
648 + ) : null}
649 <Dialog
638 - open={dialogOpen}
650 + open={dialogOpen && pairingDenial === undefined}
651 onOpenChange={(open) => {
652 setDialogOpen(open);
653 if (!open) {
@@ -646,14 +658,16 @@ export const AuthorizedClientsHeaderAction = memo(function AuthorizedClientsHead
658 }
659 }}
660 >
649 - <DialogTrigger
650 - render={
651 - <Button size="xs" variant="default">
652 - <PlusIcon className="size-3" />
653 - Create link
654 - </Button>
655 - }
656 - />
661 + {pairingDenial === undefined ? (
662 + <DialogTrigger
663 + render={
664 + <Button size="xs" variant="default">
665 + <PlusIcon className="size-3" />
666 + Create link
667 + </Button>
668 + }
669 + />
670 + ) : null}
671 <DialogPopup className="max-w-md">
672 <DialogHeader>
673 <DialogTitle>Create pairing link</DialogTitle>
@@ -856,6 +870,7 @@ export const AdvertisedEndpointListRow = memo(function AdvertisedEndpointListRow
870 const canDisableTailscaleServe =
871 isTailscaleHttpsEndpoint(endpoint) && endpoint.status === "available";
872 const shouldShowEndpointUrl = !needsTailscaleSetup;
873 + const remoteDenial = managedCapabilityDenial(usePrimaryManagedPolicy(), "remoteClients");
874 return (
875 <div className={endpointRowClassName(isAvailable)}>
876 {isDefault ? (
@@ -891,14 +906,16 @@ export const AdvertisedEndpointListRow = memo(function AdvertisedEndpointListRow
906 </span>
907 ) : null}
908 {needsTailscaleSetup ? (
894 - <Button
895 - size="xs"
896 - variant="outline"
897 - onClick={() => onSetupTailscaleServe(endpoint)}
898 - disabled={isUpdatingTailscaleServe}
899 - >
900 - {isUpdatingTailscaleServe ? "Restarting…" : "Setup"}
901 - </Button>
909 + <ManagedControl reason={remoteDenial}>
910 + <Button
911 + size="xs"
912 + variant="outline"
913 + onClick={() => onSetupTailscaleServe(endpoint)}
914 + disabled={isUpdatingTailscaleServe || remoteDenial !== undefined}
915 + >
916 + {isUpdatingTailscaleServe ? "Restarting…" : "Setup"}
917 + </Button>
918 + </ManagedControl>
919 ) : null}
920 {canDisableTailscaleServe ? (
921 <Button
apps/web/src/components/settings/BrowserImportWizard.tsx
+7 -2
@@ -151,8 +151,11 @@ export function BrowserImportWizard({
151 <BlockedStep
152 source={source}
153 reason={step.reason}
154 + message={step.message}
155 onClose={onClose}
155 - onRetry={isRetryableReason(step.reason) ? runImport : undefined}
156 + onRetry={
157 + step.message === undefined && isRetryableReason(step.reason) ? runImport : undefined
158 + }
159 />
160 ) : (
161 <ConfigureStep
@@ -552,11 +555,13 @@ function DoneStep({
555 function BlockedStep({
556 source,
557 reason,
558 + message,
559 onClose,
560 onRetry,
561 }: {
562 readonly source: BrowserImportSource;
563 readonly reason: keyof typeof BROWSER_IMPORT_FAILURE_COPY;
564 + readonly message: string | undefined;
565 readonly onClose: () => void;
566 readonly onRetry: (() => void) | undefined;
567 }) {
@@ -564,7 +569,7 @@ function BlockedStep({
569 <>
570 <DialogHeader>
571 <DialogTitle>Couldn&rsquo;t import from {source.name}</DialogTitle>
567 - <DialogDescription>{BROWSER_IMPORT_FAILURE_COPY[reason]}</DialogDescription>
572 + <DialogDescription>{message ?? BROWSER_IMPORT_FAILURE_COPY[reason]}</DialogDescription>
573 </DialogHeader>
574 <DialogFooter>
575 <Button variant="outline" onClick={onClose}>
apps/web/src/components/settings/CodexSetupSection.tsx
+21 -11
@@ -1,4 +1,4 @@
1 -import { AuthProvidersManageScope } from "@t3tools/contracts";
1 +import { AuthProvidersManageScope, ProviderDriverKind } from "@t3tools/contracts";
2 import { readPreparedConnection, useEnvironmentScope } from "../../state/session";
3 import {
4 isAtomCommandInterrupted,
@@ -27,6 +27,8 @@ import {
27 } from "react";
28
29 import { ensureLocalApi } from "../../localApi";
30 +import { managedInstanceLocks, useManagedPolicy } from "../../state/managedPolicy";
31 +import { ManagedControl } from "../ManagedPolicy";
32 import { useEnvironmentHttpBaseUrl } from "../../state/environments";
33 import { environmentPresentations } from "../../state/presentation";
34 import { primaryEnvironmentIdAtom } from "../../state/primaryEnvironment";
@@ -102,6 +104,12 @@ interface CodexSetupSectionProps {
104
105 export function CodexSetupSection(props: CodexSetupSectionProps) {
106 const [requested, setRequested] = useState(false);
107 + // A policy that owns Codex's launch settings also rules out ChatGPT's own runtime.
108 + const codexLocks = managedInstanceLocks(
109 + useManagedPolicy(props.environmentId),
110 + ProviderDriverKind.make("codex"),
111 + );
112 + const chatGptDenial = codexLocks?.configKeys.has("setupMode") ? codexLocks.reason : undefined;
113 const existingState = getOnboardingProviderState(props.provider);
114 const existingReady = props.enabled && existingState === "ready";
115 const existingAuthenticated = props.provider?.auth.status === "authenticated";
@@ -147,16 +155,18 @@ export function CodexSetupSection(props: CodexSetupSectionProps) {
155 ) : existingAuthenticated ? (
156 <span className="text-xs text-muted-foreground">{existingSummary.headline}</span>
157 ) : (
150 - <ChatGptConnectionButton
151 - size="sm"
152 - disabled={props.readOnly}
153 - onClick={() => {
154 - setRequested(true);
155 - props.onModeChange("managed");
156 - }}
157 - >
158 - Continue with ChatGPT
159 - </ChatGptConnectionButton>
158 + <ManagedControl reason={chatGptDenial}>
159 + <ChatGptConnectionButton
160 + size="sm"
161 + disabled={props.readOnly}
162 + onClick={() => {
163 + setRequested(true);
164 + props.onModeChange("managed");
165 + }}
166 + >
167 + Continue with ChatGPT
168 + </ChatGptConnectionButton>
169 + </ManagedControl>
170 )
171 }
172 secondaryControl={
apps/web/src/components/settings/ConnectionsSettings.tsx
+12
@@ -15,6 +15,7 @@ import {
15 type DesktopServerExposureState,
16 type DesktopWslState,
17 type EnvironmentId,
18 + managedCapabilityDenial,
19 resolveEnvironmentMachineKind,
20 } from "@t3tools/contracts";
21 import {
@@ -33,6 +34,7 @@ import {
34 resolveTailscaleServeBaseUrl,
35 } from "./ConnectionsSettings.logic";
36 import { SettingsPageContainer, SettingsRow, SettingsSection } from "./settingsLayout";
37 +import { ManagedByOrganization } from "../ManagedPolicy";
38 import { LocalEnvironmentSetting } from "./LocalEnvironmentSetting";
39 import { searchableSetting } from "./settingsSearch";
40 import { EnvironmentIconMenu } from "./EnvironmentIconPicker";
@@ -268,6 +270,9 @@ export function ConnectionsSettings({ view }: { readonly view: "environments" |
270 DesktopServerExposureState["mode"] | null
271 >(null);
272 const primaryServerConfig = primaryEnvironment?.serverConfig ?? null;
273 + const primaryManagedPolicy = primaryServerConfig?.managedPolicy;
274 + // Turning remote access off stays possible; only the way in is managed.
275 + const remoteClientsDenial = managedCapabilityDenial(primaryManagedPolicy, "remoteClients");
276 const primaryVersionMismatch = resolveServerConfigVersionMismatch(primaryServerConfig);
277 const primaryServerUpdateState = useAtomValue(
278 serverEnvironment.updateStateAtom(primaryEnvironmentId),
@@ -920,6 +925,7 @@ export function ConnectionsSettings({ view }: { readonly view: "environments" |
925 />
926 ) : null
927 }
928 + managed={tailscaleHttpsEndpoint?.status === "available" ? undefined : remoteClientsDenial}
929 />
930 );
931 const renderAuthorizedClients = () => (
@@ -975,6 +981,7 @@ export function ConnectionsSettings({ view }: { readonly view: "environments" |
981 ) : null
982 }
983 control={renderNetworkAccessToggle()}
984 + managed={isLocalBackendNetworkAccessible ? undefined : remoteClientsDenial}
985 />
986 );
987 const renderDisabledNetworkAccessRow = () => (
@@ -1059,6 +1066,11 @@ export function ConnectionsSettings({ view }: { readonly view: "environments" |
1066 ) : null
1067 }
1068 >
1069 + {primaryManagedPolicy ? (
1070 + <div className="px-3 py-2 sm:px-4">
1071 + <ManagedByOrganization policy={primaryManagedPolicy} />
1072 + </div>
1073 + ) : null}
1074 {canManageLocalBackend ? (
1075 <SettingsRow
1076 title="Version"
apps/web/src/components/settings/IntegrationsSettings.logic.test.ts
+24 -2
@@ -1,7 +1,11 @@
1 import { describe, expect, it, vi } from "vite-plus/test";
2 -import type { EnvironmentId } from "@t3tools/contracts";
2 +import { type EnvironmentId, managedPolicyDeniedMessage } from "@t3tools/contracts";
3
4 -import { clearBrowserProfileData, importFailureReason } from "./IntegrationsSettings";
4 +import {
5 + clearBrowserProfileData,
6 + importFailureReason,
7 + importPolicyRefusal,
8 +} from "./IntegrationsSettings";
9
10 const environmentId = "environment-a" as EnvironmentId;
11 const secondEnvironmentId = "environment-b" as EnvironmentId;
@@ -62,3 +66,21 @@ describe("importFailureReason", () => {
66 expect(importFailureReason(failure("profileLimitReached"))).toBe("profileLimitReached");
67 });
68 });
69 +
70 +describe("importPolicyRefusal", () => {
71 + it("recovers a managed policy's refusal from the IPC-wrapped message", () => {
72 + const denied = managedPolicyDeniedMessage("Example Corp", "importing browser cookies");
73 + expect(
74 + importPolicyRefusal({
75 + message: `Error invoking remote method 'desktop:preview-import-cookies': BrowserImportPolicyError: ${denied}`,
76 + }),
77 + ).toBe(denied);
78 + const unreadable =
79 + "The managed policy at C:\\Program Files\\T3Code\\policy.json could not be read, so importing browser cookies is not allowed.";
80 + expect(importPolicyRefusal({ message: `Error: ${unreadable}` })).toBe(unreadable);
81 + });
82 +
83 + it("leaves other failures to their reason token", () => {
84 + expect(importPolicyRefusal(failure("readFailed"))).toBeUndefined();
85 + });
86 +});
apps/web/src/components/settings/IntegrationsSettings.tsx
+26 -2
@@ -34,7 +34,9 @@ import {
34 type BrowserImportSource,
35 type PreviewAppearancePreference,
36 type PreviewViewportSetting,
37 + managedCapabilityDenial,
38 } from "@t3tools/contracts";
39 +import { usePrimaryManagedPolicy } from "~/state/managedPolicy";
40 import { isValidSearchUrlTemplate } from "@t3tools/shared/preview";
41 import { PREVIEW_VIEWPORT_PRESETS } from "@t3tools/shared/previewViewport";
42 import { MoreVertical, Plus as PlusIcon } from "lucide-react";
@@ -187,6 +189,18 @@ export const importFailureReason = (cause: unknown): BrowserImportFailureReason
189 );
190 };
191
192 +/**
193 + * The desktop's refusal when the machine's managed policy forbids cookie import. IPC wraps the
194 + * message in its own prefixes, so the sentence is matched on the contract's wording.
195 + */
196 +export const importPolicyRefusal = (cause: unknown): string | undefined => {
197 + const message = String((cause as { message?: unknown } | undefined)?.message ?? "");
198 + return (
199 + /The managed policy at .* importing browser cookies is not allowed\./u.exec(message)?.[0] ??
200 + /(?:^|: )([^:]*'s policy does not allow importing browser cookies\.)/u.exec(message)?.[1]
201 + );
202 +};
203 +
204 async function importBrowserCookiesIntoTarget(
205 bridge: NonNullable<typeof previewBridge>,
206 source: BrowserImportSource,
@@ -261,7 +275,10 @@ async function importBrowserCookiesIntoTarget(
275 targetName,
276 };
277 } catch (cause) {
264 - return { kind: "blocked", reason: importFailureReason(cause) };
278 + const policyRefusal = importPolicyRefusal(cause);
279 + return policyRefusal !== undefined
280 + ? { kind: "blocked", reason: "readFailed", message: policyRefusal }
281 + : { kind: "blocked", reason: importFailureReason(cause) };
282 }
283 }
284
@@ -1091,6 +1108,11 @@ function BrowserProfilesSetting({ disabled }: { readonly disabled: boolean }) {
1108 const updateSettings = useUpdatePrimarySettings();
1109 const { environments, isReady: environmentsReady } = useEnvironments();
1110 const primaryEnvironment = usePrimaryEnvironment();
1111 + // Cookie import runs on this desktop, whose policy the primary environment reports.
1112 + const cookieImportDenial = managedCapabilityDenial(
1113 + usePrimaryManagedPolicy(),
1114 + "browserCookieImport",
1115 + );
1116 const [sources, setSources] = useState<ReadonlyArray<BrowserImportSource> | null>(null);
1117 const [importSession, setImportSession] = useState<{
1118 readonly source: BrowserImportSource;
@@ -1298,7 +1320,9 @@ function BrowserProfilesSetting({ disabled }: { readonly disabled: boolean }) {
1320 <MenuSeparator />
1321 <MenuGroup>
1322 <MenuGroupLabel>Import from</MenuGroupLabel>
1301 - {sources === null ? (
1323 + {cookieImportDenial !== undefined ? (
1324 + <MenuItem disabled>{cookieImportDenial}</MenuItem>
1325 + ) : sources === null ? (
1326 <MenuItem disabled>Looking for browsers…</MenuItem>
1327 ) : importableSources.length === 0 ? (
1328 <MenuItem disabled>No supported browsers found</MenuItem>
apps/web/src/components/settings/LabsSettingsPanel.tsx
+14
@@ -1,5 +1,6 @@
1 import { useAuth } from "@clerk/react";
2 import { Link } from "@tanstack/react-router";
3 +import { managedCapabilityDenial } from "@t3tools/contracts";
4
5 import { hasCloudPublicConfig } from "~/cloud/publicConfig";
6 import { useT3ConnectAuthPrompt } from "../clerk/useT3ConnectAuthPrompt";
@@ -10,6 +11,8 @@ import { SettingsPageContainer, SettingsRow, SettingsSection } from "./settingsL
11 import { searchableSetting } from "./settingsSearch";
12 import { LegacyFeaturesSection } from "./SettingsPanels";
13 import { useScopedSettings, useUpdateScopedSettings } from "./useScopedSettings";
14 +import { useOptionalSettingsScope } from "./SettingsScopeContext";
15 +import { firstManagedDenial, usePrimaryManagedPolicy } from "~/state/managedPolicy";
16
17 /** Features still settling in, and legacy behavior kept for people who rely on it. */
18 export function LabsSettingsPanel() {
@@ -91,11 +94,22 @@ function GuestLinksRowWithSignIn() {
94 function GuestLinksRow() {
95 const settings = useScopedSettings();
96 const updateSettings = useUpdateScopedSettings();
97 + const scope = useOptionalSettingsScope();
98 + const primaryPolicy = usePrimaryManagedPolicy();
99 + // Guests arrive through T3 Connect, so a policy that turns Connect off turns this off too.
100 + const connectDenial = firstManagedDenial(
101 + scope
102 + ? scope.connectedEnvironments.map((environment) => environment.serverConfig?.managedPolicy)
103 + : [primaryPolicy],
104 + (policy) => managedCapabilityDenial(policy, "connect"),
105 + );
106 return (
107 <SettingsRow
108 serverScoped
109 {...searchableSetting("guest-links")}
110 settingKeys={["guestSharingEnabled"]}
111 + // Turning guest links off still works without T3 Connect.
112 + managed={settings.guestSharingEnabled ? undefined : connectDenial}
113 description={
114 <>
115 Share a thread with a guest who watches it live in their browser and sends messages you
apps/web/src/components/settings/ProjectDefaultsSettings.tsx
+15 -2
@@ -2,6 +2,7 @@ import {
2 DEFAULT_SERVER_SETTINGS,
3 type ModelSelection,
4 type WorktreeSubmodules,
5 + managedRuntimeModeDenial,
6 } from "@t3tools/contracts";
7 import { createModelSelection } from "@t3tools/shared/model";
8 import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
@@ -19,6 +20,7 @@ import {
20 resolveProjectDefaultProviderModelSelection,
21 } from "../../providerInstances";
22 import { useEnvironmentProviders, useEnvironments } from "../../state/environments";
23 +import { firstManagedDenial } from "../../state/managedPolicy";
24 import { EMPTY_SERVER_PROVIDERS } from "../../state/server";
25 import { resolveEnvModeLabel, WORKTREE_SUBMODULES_LABELS } from "../BranchToolbar.logic";
26 import { ProviderModelPicker } from "../chat/ProviderModelPicker";
@@ -380,15 +382,26 @@ export function ProjectDefaultsSettings({ category }: { category: ProjectSetting
382 {runtimeModeOptions.map((mode) => {
383 const option = runtimeModeConfig[mode];
384 const Icon = option.icon;
385 + const managedReason = firstManagedDenial(
386 + connectedEnvironments.map(
387 + (environment) => environment.serverConfig?.managedPolicy,
388 + ),
389 + (policy) => managedRuntimeModeDenial(policy, mode),
390 + );
391 return (
384 - <SelectItem key={mode} value={mode} className="min-w-64">
392 + <SelectItem
393 + key={mode}
394 + value={mode}
395 + disabled={managedReason !== undefined}
396 + className="min-w-64"
397 + >
398 <div className="grid gap-0.5">
399 <span className="inline-flex items-center gap-1.5 font-medium">
400 <Icon className="size-3.5 shrink-0 text-muted-foreground" />
401 {option.label}
402 </span>
403 <span className="text-xs leading-4 text-muted-foreground">
391 - {option.description}
404 + {managedReason ?? option.description}
405 </span>
406 </div>
407 </SelectItem>
apps/web/src/components/settings/ProviderInstanceCard.tsx
+61 -13
@@ -47,6 +47,9 @@ import { DraftInput } from "../ui/draft-input";
47 import { SecretSourceInput, type SecretSource } from "./SecretSourceInput";
48 import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
49 import { Switch } from "../ui/switch";
50 +import { ManagedControl, ManagedNotice } from "../ManagedPolicy";
51 +import { managedInstanceLocks, useManagedPolicy } from "../../state/managedPolicy";
52 +import { disallowedProviderMessage, isManagedDriverAllowed } from "@t3tools/contracts";
53 import { stackedThreadToast, toastManager } from "../ui/toast";
54 import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
55 import type {
@@ -277,6 +280,7 @@ function ProviderEnvironmentFieldRow(props: {
280 secret: SecretReference | undefined,
281 ) => void;
282 readonly onRemove: (field: ProviderEnvironmentField) => void;
283 + readonly managedReason?: string | undefined;
284 readonly secretSources: ReadonlyArray<SecretSource>;
285 }) {
286 const inputId = `${props.idPrefix}-environment-${props.field.name}`;
@@ -286,6 +290,7 @@ function ProviderEnvironmentFieldRow(props: {
290 <SettingsRow
291 title={<label htmlFor={inputId}>{props.field.label}</label>}
292 description={props.field.description}
293 + managed={props.managedReason}
294 control={
295 <div className="flex w-full min-w-0 items-center gap-2 @min-[32rem]/settings-row:w-56">
296 {props.field.sensitive === false ? (
@@ -334,6 +339,8 @@ function ProviderEnvironmentFieldRow(props: {
339 export function ProviderEnvironmentSection(props: {
340 readonly environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>;
341 readonly onChange: (environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>) => void;
342 + /** Variables an administrator's policy pins: listed by name, never editable or removable. */
343 + readonly managed?: { readonly names: ReadonlySet<string>; readonly reason: string } | undefined;
344 readonly secretSources?: ReadonlyArray<SecretSource>;
345 }) {
346 const [storedDraft, setDraft] = useState(() =>
@@ -373,6 +380,8 @@ export function ProviderEnvironmentSection(props: {
380 };
381
382 const updateVariable = (id: string, patch: Partial<Omit<EnvironmentDraftRow, "id">>) => {
383 + // A row named like a pinned variable renders as the policy's, with no way to edit or remove it.
384 + if (patch.name !== undefined && props.managed?.names.has(patch.name)) return;
385 const nextRows = rows.map((row) =>
386 row.id === id
387 ? {
@@ -427,6 +436,16 @@ export function ProviderEnvironmentSection(props: {
436 {rows.length > 0 ? (
437 <div className="mt-3 min-w-0 space-y-2 pb-2">
438 {rows.map((variable, index) => {
439 + if (props.managed?.names.has(variable.name)) {
440 + return (
441 + <div key={variable.id} className="flex min-w-0 flex-wrap items-center gap-1.5">
442 + <code className="min-w-0 truncate text-xs sm:w-44 sm:shrink-0">
443 + {variable.name}
444 + </code>
445 + <span className="text-xs text-muted-foreground">{props.managed.reason}</span>
446 + </div>
447 + );
448 + }
449 const nameInput = (
450 <DraftInput
451 size="sm"
@@ -746,6 +765,14 @@ export function ProviderInstanceCard({
765 const displayName =
766 instance.displayName?.trim() || driverOption?.label || String(instance.driver);
767 const accentColor = normalizeProviderAccentColor(instance.accentColor);
768 + const managedPolicy = useManagedPolicy(environmentId);
769 + const instanceLocks = managedInstanceLocks(managedPolicy, instance.driver);
770 + const managedDriverReason = isManagedDriverAllowed(managedPolicy, instance.driver)
771 + ? undefined
772 + : disallowedProviderMessage(
773 + managedPolicy?.organization,
774 + driverOption?.label ?? String(instance.driver),
775 + );
776 const { copyToClipboard } = useCopyToClipboard<{ providerName: string }>({
777 onCopy: ({ providerName }) => {
778 toastManager.add({
@@ -1109,12 +1136,15 @@ export function ProviderInstanceCard({
1136 />
1137 </span>
1138 ) : null}
1112 - <Switch
1113 - checked={enabled}
1114 - disabled={readOnly || (projectOverride !== undefined && !canWriteSettings)}
1115 - onCheckedChange={(checked) => updateEnabled(Boolean(checked))}
1116 - aria-label={`Enable ${displayName}`}
1117 - />
1139 + {/* The policy refuses switching it on; switching it off stays the user's call. */}
1140 + <ManagedControl reason={enabled ? undefined : managedDriverReason}>
1141 + <Switch
1142 + checked={enabled}
1143 + disabled={readOnly || (projectOverride !== undefined && !canWriteSettings)}
1144 + onCheckedChange={(checked) => updateEnabled(Boolean(checked))}
1145 + aria-label={`Enable ${displayName}`}
1146 + />
1147 + </ManagedControl>
1148 </span>
1149 </div>
1150 );
@@ -1196,6 +1226,7 @@ export function ProviderInstanceCard({
1226 idPrefix={`provider-instance-${instanceId}`}
1227 variant="settings"
1228 onChange={updateConfig}
1229 + managed={instanceLocks && { keys: instanceLocks.configKeys, reason: instanceLocks.reason }}
1230 environmentId={environmentId}
1231 />
1232 ) : (
@@ -1263,6 +1294,12 @@ export function ProviderInstanceCard({
1294 onCommit={updateEnvironmentField}
1295 onSecretChange={updateEnvironmentFieldSecret}
1296 onRemove={removeEnvironmentField}
1297 + managedReason={
1298 + instanceLocks?.wholeEnvironment ||
1299 + instanceLocks?.environmentNames.has(field.name)
1300 + ? instanceLocks.reason
1301 + : undefined
1302 + }
1303 secretSources={secretSources}
1304 />
1305 ))}
@@ -1299,15 +1336,26 @@ export function ProviderInstanceCard({
1336
1337 <SettingsSection
1338 title="Environment"
1302 - inert={readOnly}
1303 - aria-disabled={readOnly || undefined}
1339 + inert={readOnly || instanceLocks?.wholeEnvironment}
1340 + aria-disabled={readOnly || instanceLocks?.wholeEnvironment || undefined}
1341 className={readOnly ? "opacity-50 select-none" : undefined}
1342 >
1306 - <ProviderEnvironmentSection
1307 - environment={genericEnvironment}
1308 - onChange={updateGenericEnvironment}
1309 - secretSources={secretSources}
1310 - />
1343 + {instanceLocks?.wholeEnvironment ? (
1344 + <ManagedNotice>{instanceLocks.reason}</ManagedNotice>
1345 + ) : null}
1346 + <div className={instanceLocks?.wholeEnvironment ? "opacity-50" : undefined}>
1347 + <ProviderEnvironmentSection
1348 + environment={genericEnvironment}
1349 + onChange={updateGenericEnvironment}
1350 + secretSources={secretSources}
1351 + managed={
1352 + instanceLocks && {
1353 + names: instanceLocks.environmentNames,
1354 + reason: instanceLocks.reason,
1355 + }
1356 + }
1357 + />
1358 + </div>
1359 </SettingsSection>
1360 {environmentId !== undefined && liveProvider?.driver === "acpRegistry" ? (
1361 <AcpSessionManagementSection
apps/web/src/components/settings/ProviderSettingsForm.tsx
+54 -31
@@ -206,7 +206,10 @@ function configuredCommandArgs(value: ProviderSettingsFormProps["value"]) {
206 function ProviderCommandArguments({
207 value,
208 onChange,
209 -}: Pick<ProviderSettingsFormProps, "value" | "onChange">) {
209 + managedReason,
210 +}: Pick<ProviderSettingsFormProps, "value" | "onChange"> & {
211 + readonly managedReason: string | undefined;
212 +}) {
213 const args = configuredCommandArgs(value);
214 const [storedDraft, setDraft] = useState(() => seedRowsDraft(args, toCommandArgumentRows));
215 const draft = reconcileRowsDraft(storedDraft, args, commandArgumentsEqual, toCommandArgumentRows);
@@ -225,6 +228,7 @@ function ProviderCommandArguments({
228 <SettingsRow
229 title="Arguments"
230 description="One literal argument per row, in launch order."
231 + managed={managedReason}
232 control={
233 <Button
234 type="button"
@@ -239,35 +243,41 @@ function ProviderCommandArguments({
243 >
244 {rows.length > 0 ? (
245 <div className="mt-3 min-w-0 space-y-2 pb-2">
242 - {rows.map((argument, index) => (
243 - <div key={argument.id} className="flex min-w-0 items-center gap-1.5">
244 - <DraftInput
245 - size="sm"
246 - font="mono"
247 - value={argument.value}
248 - onCommit={(next) =>
249 - updateArguments(
250 - rows.map((current) =>
251 - current.id === argument.id ? { ...current, value: next } : current,
252 - ),
253 - )
254 - }
255 - aria-label={`Argument ${index + 1}`}
256 - spellCheck={false}
257 - />
258 - <Button
259 - type="button"
260 - size="icon-micro"
261 - variant="ghost-destructive"
262 - onClick={() =>
263 - updateArguments(rows.filter((current) => current.id !== argument.id))
264 - }
265 - aria-label={`Remove argument ${index + 1}`}
266 - >
267 - <XIcon />
268 - </Button>
269 - </div>
270 - ))}
246 + {rows.map((argument, index) =>
247 + managedReason !== undefined ? (
248 + <code key={argument.id} className="block min-w-0 truncate text-xs">
249 + {argument.value}
250 + </code>
251 + ) : (
252 + <div key={argument.id} className="flex min-w-0 items-center gap-1.5">
253 + <DraftInput
254 + size="sm"
255 + font="mono"
256 + value={argument.value}
257 + onCommit={(next) =>
258 + updateArguments(
259 + rows.map((current) =>
260 + current.id === argument.id ? { ...current, value: next } : current,
261 + ),
262 + )
263 + }
264 + aria-label={`Argument ${index + 1}`}
265 + spellCheck={false}
266 + />
267 + <Button
268 + type="button"
269 + size="icon-micro"
270 + variant="ghost-destructive"
271 + onClick={() =>
272 + updateArguments(rows.filter((current) => current.id !== argument.id))
273 + }
274 + aria-label={`Remove argument ${index + 1}`}
275 + >
276 + <XIcon />
277 + </Button>
278 + </div>
279 + ),
280 + )}
281 </div>
282 ) : null}
283 </SettingsRow>
@@ -324,6 +334,8 @@ interface ProviderSettingsFormProps {
334 readonly idPrefix: string;
335 readonly variant: "card" | "dialog" | "settings";
336 readonly onChange: (nextConfig: Record<string, unknown> | undefined) => void;
337 + /** Config keys an administrator's policy pins, shown inert with the reason. */
338 + readonly managed?: { readonly keys: ReadonlySet<string>; readonly reason: string } | undefined;
339 /** Where the secret providers offered for `SettingsSecretValue` fields are configured. */
340 readonly environmentId?: EnvironmentId | undefined;
341 }
@@ -438,6 +450,7 @@ interface ProviderSettingsFieldRowProps {
450 readonly idPrefix: string;
451 readonly variant: ProviderSettingsFormProps["variant"];
452 readonly onChange: ProviderSettingsFormProps["onChange"];
453 + readonly managedReason?: string | undefined;
454 readonly environmentId: EnvironmentId | undefined;
455 }
456
@@ -447,6 +460,7 @@ function ProviderSettingsFieldRow({
460 idPrefix,
461 variant,
462 onChange,
463 + managedReason,
464 environmentId,
465 }: ProviderSettingsFieldRowProps) {
466 const inputId = `${idPrefix}-${field.key}`;
@@ -552,6 +566,7 @@ function ProviderSettingsFieldRow({
566 field.description ? <span id={descriptionId}>{field.description}</span> : undefined
567 }
568 control={control}
569 + managed={managedReason}
570 />
571 );
572 }
@@ -660,6 +675,7 @@ export function ProviderSettingsForm({
675 idPrefix,
676 variant,
677 onChange,
678 + managed,
679 environmentId,
680 }: ProviderSettingsFormProps) {
681 const fields = deriveProviderSettingsFields(definition, value);
@@ -681,10 +697,17 @@ export function ProviderSettingsForm({
697 idPrefix={idPrefix}
698 variant={variant}
699 onChange={onChange}
700 + managedReason={managed?.keys.has(field.key) ? managed.reason : undefined}
701 environmentId={environmentId}
702 />
703 ))}
687 - {isLocalAcp ? <ProviderCommandArguments value={value} onChange={onChange} /> : null}
704 + {isLocalAcp ? (
705 + <ProviderCommandArguments
706 + value={value}
707 + onChange={onChange}
708 + managedReason={managed?.keys.has("commandArgs") ? managed.reason : undefined}
709 + />
710 + ) : null}
711 </>
712 );
713 }
apps/web/src/components/settings/ProviderSettingsPanel.tsx
+7 -2
@@ -96,6 +96,7 @@ import { Toggle, ToggleGroup } from "../ui/toggle-group";
96 import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
97 import { stackedThreadToast, toastManager } from "../ui/toast";
98 import { AddProviderInstanceDialog } from "./AddProviderInstanceDialog";
99 +import { useManagedPolicy } from "~/state/managedPolicy";
100 import { ExpandableText } from "./ExpandableText";
101 import { ProviderInstanceCard } from "./ProviderInstanceCard";
102 import { useSecretSources } from "./SecretSourceInput";
@@ -548,6 +549,10 @@ export function EnvironmentProviderSettings({
549 readonly readOnly?: boolean;
550 }) {
551 const settings = useEnvironmentSettings(environmentId);
552 + const managedPolicy = useManagedPolicy(environmentId);
553 + // A policy that allows no provider leaves nothing to add.
554 + const canAddProvider =
555 + !readOnly && managedPolicy?.limits?.providers?.allowedDrivers?.length !== 0;
556 const canWriteSettings = useEnvironmentScope(environmentId, AuthSettingsWriteScope);
557 const canRefreshProviders = useEnvironmentScope(environmentId, AuthOrchestrationReadScope);
558 const updateSettings = useUpdateEnvironmentSettings(environmentId);
@@ -962,7 +967,7 @@ export function EnvironmentProviderSettings({
967 {...searchableSetting("providers")}
968 variant="plain"
969 titleAction={
965 - !readOnly ? (
970 + canAddProvider ? (
971 <Tooltip>
972 <TooltipTrigger
973 render={
@@ -1037,7 +1042,7 @@ export function EnvironmentProviderSettings({
1042 >
1043 <div className="divide-y divide-border/50">
1044 {rows.map((row) => renderProviderInstance(row, "list"))}
1040 - {!readOnly ? (
1045 + {canAddProvider ? (
1046 <button
1047 type="button"
1048 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"
apps/web/src/components/settings/SavedEnvironmentRows.tsx
+25 -14
@@ -12,6 +12,7 @@ import {
12 type EnvironmentId,
13 connectReachabilityHelpUrl,
14 formatConnectReachable,
15 + managedCapabilityDenial,
16 resolveEnvironmentMachineKind,
17 } from "@t3tools/contracts";
18 import {
@@ -60,6 +61,7 @@ import {
61 usePrimaryEnvironmentId,
62 } from "~/state/environments";
63 import { APP_VERSION } from "~/branding";
64 +import { usePrimaryManagedPolicy } from "~/state/managedPolicy";
65 import { useAtomCommand } from "../../state/use-atom-command";
66 import { serverEnvironment } from "~/state/server";
67 import {
@@ -531,6 +533,8 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: b
533 reconcileCloudState,
534 } = useCloudLinkController();
535 const { openAuthPrompt } = useT3ConnectAuthPrompt();
536 + // The server unlinks and refuses relay changes under such a policy; unlinking stays possible.
537 + const connectDenial = managedCapabilityDenial(usePrimaryManagedPolicy(), "connect");
538 const [isUpdating, setIsUpdating] = useState(false);
539 const [isUpdatingPreference, setIsUpdatingPreference] = useState(false);
540
@@ -652,21 +656,24 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: b
656 <SettingsRow
657 title={searchableSetting("t3-connect").title}
658 description={
655 - signedOut
656 - ? "Sign in to make this environment available to your other devices through T3 Connect."
657 - : linkRevoked
658 - ? "This environment was removed from T3 Connect. Turn it on to link it again."
659 - : managedTunnelActive
660 - ? reachability?.status === "unreachable"
661 - ? "T3 Connect is on, but other devices cannot reach this environment."
662 - : reachability?.status === "reachable"
663 - ? "This environment is available to your other devices through T3 Connect."
664 - : "T3 Connect is on. Reachability has not been checked yet."
665 - : managedTunnelOutOfSync
666 - ? "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."
667 - : "Make this environment available to your other devices through T3 Connect."
659 + connectDenial !== undefined && !managedTunnelActive
660 + ? connectDenial
661 + : signedOut
662 + ? "Sign in to make this environment available to your other devices through T3 Connect."
663 + : linkRevoked
664 + ? "This environment was removed from T3 Connect. Turn it on to link it again."
665 + : managedTunnelActive
666 + ? reachability?.status === "unreachable"
667 + ? "T3 Connect is on, but other devices cannot reach this environment."
668 + : reachability?.status === "reachable"
669 + ? "This environment is available to your other devices through T3 Connect."
670 + : "T3 Connect is on. Reachability has not been checked yet."
671 + : managedTunnelOutOfSync
672 + ? "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."
673 + : "Make this environment available to your other devices through T3 Connect."
674 }
675 status={operationError ?? primaryCloudLinkState.error ?? reachabilityStatus}
676 + managed={managedTunnelActive ? undefined : connectDenial}
677 control={
678 signedOut ? (
679 signInButton
@@ -680,7 +687,9 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: b
687 )
688 }
689 >
683 - {signedOut ? null : <T3ConnectTunnelUsage tunnelLimit={tunnelLimit} />}
690 + {signedOut || connectDenial !== undefined ? null : (
691 + <T3ConnectTunnelUsage tunnelLimit={tunnelLimit} />
692 + )}
693 </SettingsRow>
694 ) : linkRevoked ? (
695 <SettingsRow
@@ -696,6 +705,7 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: b
705 ? "Sign in to send activity to mobile notifications and Live Activities."
706 : "Send activity to mobile notifications and Live Activities without T3 Connect."
707 }
708 + managed={connectDenial}
709 control={
710 signedOut ? (
711 signInButton
@@ -715,6 +725,7 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: b
725 <SettingsRow
726 title={searchableSetting("hold-webhooks-while-offline").title}
727 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."
728 + managed={connectDenial}
729 control={
730 <CloudLinkSwitch
731 ariaLabel="Hold webhook requests while this environment is offline"
apps/web/src/components/settings/ScheduledTasksSettings.tsx
+40 -6
@@ -69,7 +69,13 @@ import { useAtomCommand } from "../../state/use-atom-command";
69 import { WorktreeBaseBranchPicker } from "../WorktreeBaseBranchPicker";
70 import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon";
71 import { ConnectionStatusDot, connectionPhaseDotClassName } from "../ConnectionStatusDot";
72 -import { AuthOrchestrationOperateScope } from "@t3tools/contracts";
72 +import {
73 + AuthOrchestrationOperateScope,
74 + clampManagedRuntimeMode,
75 + managedCapabilityDenial,
76 +} from "@t3tools/contracts";
77 +import { useManagedPolicy } from "~/state/managedPolicy";
78 +import { ManagedNotice } from "../ManagedPolicy";
79 import { readEnvironmentScope } from "~/state/session";
80 import { useSettingsScope } from "./SettingsScopeContext";
81 import { EnvironmentRow, useEnvironmentTransportLabel } from "./EnvironmentRow";
@@ -761,7 +767,9 @@ function ScheduledTaskRow({
767 <div className="flex flex-wrap items-center gap-2">
768 <span>
769 {scheduleLabel(task.schedule)} ·{" "}
764 - {!task.enabled ? (
770 + {task.blockedByPolicy !== undefined ? (
771 + task.blockedByPolicy
772 + ) : !task.enabled ? (
773 "Paused"
774 ) : isWebhook ? (
775 "Listening"
@@ -1204,6 +1212,7 @@ function ScheduledTaskEditorForm({
1212 const upsertTask = useAtomCommand(serverEnvironment.upsertScheduledTask, {
1213 label: "scheduled task upsert",
1214 });
1215 + const webhookDenial = managedCapabilityDenial(useManagedPolicy(environmentId), "webhookTasks");
1216 const [draft, setDraft] = useState<DraftState>(() =>
1217 task
1218 ? taskToDraft(task)
@@ -1348,7 +1357,10 @@ function ScheduledTaskEditorForm({
1357 threadId: draft.threadId ? (draft.threadId as ThreadId) : null,
1358 workspaceStrategy,
1359 modelSelection,
1351 - runtimeMode: draft.runtimeMode,
1360 + // Tasks have no mode picker; a mode above the administrator's ceiling would fail every run.
1361 + runtimeMode:
1362 + clampManagedRuntimeMode(environment?.serverConfig?.managedPolicy, draft.runtimeMode) ??
1363 + draft.runtimeMode,
1364 interactionMode: draft.interactionMode,
1365 creationSource: "web",
1366 };
@@ -1635,11 +1647,26 @@ function ScheduledTaskEditorForm({
1647 <Toggle value="once">Once</Toggle>
1648 ) : null}
1649 <Toggle value="interval">Every interval</Toggle>
1638 - <Toggle value="webhook">On webhook</Toggle>
1650 + <Toggle
1651 + value="webhook"
1652 + disabled={webhookDenial !== undefined && draft.scheduleMode !== "webhook"}
1653 + >
1654 + On webhook
1655 + </Toggle>
1656 </ToggleGroup>
1657 </div>
1658
1642 - {draft.scheduleMode === "webhook" ? (
1659 + {webhookDenial !== undefined ? (
1660 + <ManagedNotice>
1661 + {draft.scheduleMode === "webhook"
1662 + ? `${webhookDenial} Switch this task to a time or an interval, or turn it off, to save it.`
1663 + : webhookDenial}
1664 + </ManagedNotice>
1665 + ) : null}
1666 + {/* A disabled task still saves, so keep its fields reachable for fixing. */}
1667 + {draft.scheduleMode === "webhook" &&
1668 + webhookDenial !== undefined &&
1669 + draft.enabled ? null : draft.scheduleMode === "webhook" ? (
1670 <div className="space-y-4">
1671 <WebhookEndpointField environmentId={environmentId} task={liveTask} />
1672 <p className="text-xs text-muted-foreground">
@@ -1905,7 +1932,14 @@ function ScheduledTaskEditorForm({
1932 </DialogClose>
1933 <Button
1934 size="sm"
1908 - disabled={!canOperate || saving || editingTaskMissing || !connected || !tasksQuery.data}
1935 + disabled={
1936 + !canOperate ||
1937 + saving ||
1938 + editingTaskMissing ||
1939 + !connected ||
1940 + !tasksQuery.data ||
1941 + (draft.enabled && draft.scheduleMode === "webhook" && webhookDenial !== undefined)
1942 + }
1943 onClick={() => void submit()}
1944 >
1945 {draft.editingId ? "Save task" : "Create task"}
apps/web/src/components/settings/SettingsPanels.tsx
+55 -5
@@ -8,6 +8,8 @@ import {
8 type DesktopUpdateChannel,
9 IDLE_COMPACTION_MODES,
10 globalIdleCompaction,
11 + managedUpdatesDenial,
12 + managedUpdatesMessage,
13 ProviderDriverKind,
14 type ProviderInstanceId,
15 type SidebarProjectGroupingMode,
@@ -59,6 +61,7 @@ import { ProjectDefaultsSettings } from "./ProjectDefaultsSettings";
61 import { ThreadTitleInstructionsSettings } from "./ThreadTitleInstructionsSettings";
62 import { SnoozePresetsRow } from "./SnoozePresetsSettings";
63 import { useDesktopUpdateState } from "../../state/desktopUpdate";
64 +import { managedTelemetryOffMessage, usePrimaryManagedPolicy } from "../../state/managedPolicy";
65 import {
66 getCustomModelOptionsByInstance,
67 resolveAppModelSelectionState,
@@ -156,6 +159,13 @@ function AboutVersionSection() {
159
160 const hasDesktopBridge = typeof window !== "undefined" && Boolean(window.desktopBridge);
161 const selectedUpdateChannel = updateState?.channel ?? "latest";
162 + // The desktop updates this machine, whose policy the primary environment reports.
163 + const primaryPolicy = usePrimaryManagedPolicy();
164 + const updatesDenial = hasDesktopBridge ? managedUpdatesDenial(primaryPolicy) : undefined;
165 + const nightlyDeniedBy =
166 + hasDesktopBridge && primaryPolicy?.limits?.updates?.allowNightly === false
167 + ? primaryPolicy.organization
168 + : undefined;
169 const selectedHostedAppChannel = hasDesktopBridge ? null : HOSTED_APP_CHANNEL;
170 // A switch that failed part way leaves this app or a server on the other track.
171 // With its updater off, a switch cannot move this app, so it is not counted.
@@ -245,7 +255,9 @@ function AboutVersionSection() {
255 type: "error",
256 title: "Could not check for updates",
257 description:
248 - result.state.message ?? "Automatic updates are not available in this build.",
258 + updatesDenial ??
259 + result.state.message ??
260 + "Automatic updates are not available in this build.",
261 }),
262 );
263 }
@@ -280,7 +292,8 @@ function AboutVersionSection() {
292 const description =
293 action === "download" || action === "install"
294 ? "Update available."
283 - : (getDesktopUpdateDisabledReason(updateState) ?? "Current version of the application.");
295 + : (getDesktopUpdateDisabledReason(updateState, updatesDenial) ??
296 + "Current version of the application.");
297
298 return (
299 <>
@@ -288,6 +301,7 @@ function AboutVersionSection() {
301 id={searchableSetting("app-version").id}
302 title={<AboutVersionTitle />}
303 description={description}
304 + managed={updatesDenial}
305 control={
306 <Tooltip>
307 <TooltipTrigger
@@ -310,7 +324,13 @@ function AboutVersionSection() {
324 <SettingsRow
325 {...searchableSetting("update-track")}
326 description={
313 - unswitchedMachines > 0 ? (
327 + nightlyDeniedBy !== undefined ? (
328 + `${managedUpdatesMessage(nightlyDeniedBy)} Nightly builds are not available${
329 + selectedUpdateChannel === "nightly"
330 + ? "; switch to Stable to keep getting updates."
331 + : "."
332 + }`
333 + ) : unswitchedMachines > 0 ? (
334 <>
335 {unswitchedMachines === 1
336 ? "1 machine still runs"
@@ -330,6 +350,7 @@ function AboutVersionSection() {
350 "Switches this app and every connected machine whose database the target release supports."
351 )
352 }
353 + managed={updatesDenial}
354 control={
355 <Select
356 value={selectedUpdateChannel}
@@ -351,7 +372,11 @@ function AboutVersionSection() {
372 <SelectItem hideIndicator value="latest">
373 Stable
374 </SelectItem>
354 - <SelectItem hideIndicator value="nightly">
375 + <SelectItem
376 + hideIndicator
377 + value="nightly"
378 + disabled={nightlyDeniedBy !== undefined && selectedUpdateChannel !== "nightly"}
379 + >
380 Nightly
381 </SelectItem>
382 </SelectPopup>
@@ -1977,9 +2002,30 @@ export function MaintenanceSettingsPanel() {
2002 }
2003
2004 export function AboutSettingsPanel() {
2005 + const primaryPolicy = usePrimaryManagedPolicy();
2006 + const telemetryOff = managedTelemetryOffMessage(primaryPolicy);
2007 return (
2008 <SettingsPageContainer>
2009 <SettingsSection id="about" title="App">
2010 + {primaryPolicy ? (
2011 + <SettingsRow
2012 + title="Organization"
2013 + description={`This environment is managed by ${primaryPolicy.organization}. Some settings and features follow its policy.`}
2014 + control={
2015 + primaryPolicy.supportUrl ? (
2016 + <Button
2017 + render={
2018 + <a href={primaryPolicy.supportUrl} target="_blank" rel="noreferrer noopener" />
2019 + }
2020 + size="sm"
2021 + variant="outline"
2022 + >
2023 + Get help
2024 + </Button>
2025 + ) : null
2026 + }
2027 + />
2028 + ) : null}
2029 {isElectron || HOSTED_APP_CHANNEL ? (
2030 <AboutVersionSection />
2031 ) : (
@@ -1997,7 +2043,11 @@ export function AboutSettingsPanel() {
2043 <SettingsSection id="legal" title="Legal">
2044 <SettingsRow
2045 {...searchableSetting("privacy-policy")}
2000 - description="How we handle your data, including the anonymous usage data T3 Code collects."
2046 + description={
2047 + telemetryOff === undefined
2048 + ? "How we handle your data, including the anonymous usage data T3 Code collects."
2049 + : `How we handle your data. ${telemetryOff}`
2050 + }
2051 control={
2052 <Button
2053 render={<a href={PRIVACY_POLICY_URL} target="_blank" rel="noreferrer noopener" />}
apps/web/src/components/settings/StorageSettings.tsx
+11
@@ -476,6 +476,9 @@ export function WorktreeCleanupSection() {
476 )
477 ? "Mixed across selected machines"
478 : undefined;
479 + // A policy locks these through worktreeCleanup, which also reaches each project's own rules.
480 + const lockablePath = (key: keyof WorktreeCleanupRules) =>
481 + isProjectScope ? ["worktreeCleanup"] : ["worktreeCleanup", `storageCleanup.${key}`];
482 const update = (patch: Partial<StorageCleanupSettings>) =>
483 updateSettings({ storageCleanup: patch });
484 const updateWorktree = (patch: Partial<WorktreeCleanupRules>) =>
@@ -557,6 +560,7 @@ export function WorktreeCleanupSection() {
560 <SettingsRow
561 title="Delete worktrees with deleted threads"
562 status={ruleStatus("worktreeOnDelete")}
563 + managedPaths={lockablePath("worktreeOnDelete")}
564 description="Remove unused worktrees when active or archived threads are deleted. Worktrees with local changes are kept."
565 serverScoped={!isProjectScope}
566 control={
@@ -570,6 +574,7 @@ export function WorktreeCleanupSection() {
574 <SettingsRow
575 title="Delete merged worktrees"
576 status={ruleStatus("worktreeOnMerge")}
577 + managedPaths={lockablePath("worktreeOnMerge")}
578 description="Remove worktrees whose pull request is merged and whose commits are included in the default branch."
579 serverScoped={!isProjectScope}
580 control={
@@ -583,6 +588,7 @@ export function WorktreeCleanupSection() {
588 <SettingsRow
589 title="Delete inactive worktrees"
590 status={ruleStatus("worktreeAfterDays")}
591 + managedPaths={lockablePath("worktreeAfterDays")}
592 description="Remove worktrees after their threads have been inactive for this many days. Branches and thread history are kept."
593 serverScoped={!isProjectScope}
594 control={
@@ -605,6 +611,7 @@ export function WorktreeCleanupSection() {
611 ) && (
612 <SettingsRow
613 title="Delete settled worktrees"
614 + managedPaths={lockablePath("worktreeSettledAfterDays")}
615 status={[
616 ruleStatus("worktreeSettledAfterDays"),
617 environments.length > connectedEnvironments.length
@@ -630,6 +637,7 @@ export function WorktreeCleanupSection() {
637 <SettingsRow
638 title="Delete unchanged worktrees"
639 status={ruleStatus("worktreeUnchanged")}
640 + managedPaths={lockablePath("worktreeUnchanged")}
641 description="Remove worktrees with no commits beyond the default branch."
642 serverScoped={!isProjectScope}
643 control={
@@ -647,6 +655,7 @@ export function WorktreeCleanupSection() {
655 <SettingsRow
656 {...searchableSetting("storage-worktree-keep-when")}
657 status={ruleStatus("worktreeKeepWhen")}
658 + managedPaths={lockablePath("worktreeKeepWhen")}
659 description={
660 settings.worktreeKeepWhen === "any-local-files"
661 ? "Includes ignored files, except node_modules."
@@ -750,6 +759,7 @@ export function StorageCleanupSections() {
759 <SettingsRow
760 title="Delete old browser artifacts"
761 status={artifactsStatus}
762 + managedPaths={["storageCleanup.browserArtifactsAfterDays"]}
763 description="Delete saved browser captures after this many days. Older capture links will no longer open."
764 serverScoped
765 control={
@@ -765,6 +775,7 @@ export function StorageCleanupSections() {
775 <SettingsRow
776 title="Delete old rotated logs"
777 status={logsStatus}
778 + managedPaths={["storageCleanup.logsAfterDays"]}
779 description="Delete inactive rotated log files after this many days. Current logs are kept."
780 serverScoped
781 control={
apps/web/src/components/settings/UpdateTrackSwitchDialog.tsx
+2 -3
@@ -18,7 +18,7 @@ import {
18 type ChannelSwitchRelease,
19 } from "../sidebar/updateEverything.logic";
20 import { isHostedByThisApp, useUpdateEverything } from "../sidebar/useUpdateEverything";
21 -import { prepareLocalTrackSwitch } from "./updateTrackSwitch.logic";
21 +import { localUpdaterStaysPut, prepareLocalTrackSwitch } from "./updateTrackSwitch.logic";
22 import {
23 AlertDialog,
24 AlertDialogClose,
@@ -76,8 +76,7 @@ function SwitchPlan({
76 const updateState = useDesktopUpdateState();
77 const { environments } = useEnvironments();
78 const crossesLocal = desktopUpdateChannelOf(APP_VERSION) !== release.channel;
79 - // With its updater off (a .deb install, or no feed) this app stays put and only remotes move.
80 - const updatesOff = updateState?.enabled === false;
79 + const updatesOff = localUpdaterStaysPut(updateState, release.channel);
80 // After a partial switch this app may already be on the track; then only remotes move.
81 const switchesLocal = crossesLocal && !updatesOff;
82 const [checking, setChecking] = useState(false);
apps/web/src/components/settings/browserImportWizard.logic.ts
+14 -3
@@ -45,7 +45,12 @@ export type ImportOutcome =
45 readonly skippedDomains: ReadonlyArray<string>;
46 readonly targetName: string;
47 }
48 - | { readonly kind: "blocked"; readonly reason: BrowserImportFailureReason };
48 + | {
49 + readonly kind: "blocked";
50 + readonly reason: BrowserImportFailureReason;
51 + /** Shown instead of the reason's copy, such as a managed policy's refusal. */
52 + readonly message?: string;
53 + };
54
55 export type WizardStep =
56 | { readonly step: "quit" }
@@ -64,7 +69,11 @@ export type WizardStep =
69 readonly skippedDomains: ReadonlyArray<string>;
70 readonly targetName: string;
71 }
67 - | { readonly step: "blocked"; readonly reason: BrowserImportFailureReason };
72 + | {
73 + readonly step: "blocked";
74 + readonly reason: BrowserImportFailureReason;
75 + readonly message?: string;
76 + };
77
78 export function canCloseWizard(step: WizardStep): boolean {
79 return step.step !== "importing";
@@ -94,7 +103,9 @@ export function outcomeToStep(outcome: ImportOutcome): WizardStep {
103 if (outcome.reason === "needsFullDiskAccess") {
104 return { step: "fullDiskAccess", resume: "import", checked: true };
105 }
97 - return { step: "blocked", reason: outcome.reason };
106 + return outcome.message === undefined
107 + ? { step: "blocked", reason: outcome.reason }
108 + : { step: "blocked", reason: outcome.reason, message: outcome.message };
109 }
110
111 export function refreshedSourceStep(source: BrowserImportSource | undefined): WizardStep {
apps/web/src/components/settings/settingsLayout.tsx
+64 -30
@@ -2,8 +2,13 @@ import { SettingsGroup } from "./SettingsGroup";
2 import { AuthSettingsWriteScope } from "@t3tools/contracts";
3 import { usePrimaryEnvironmentId, usePrimaryEnvironment } from "../../state/environments";
4 import { useEnvironmentScope, useEnvironmentsWithScope } from "../../state/session";
5 +import { useServerConfigs } from "../../state/entities";
6 import { InfoIcon, Undo2Icon } from "lucide-react";
6 -import { DEFAULT_SERVER_SETTINGS, type ServerSettings } from "@t3tools/contracts";
7 +import {
8 + DEFAULT_SERVER_SETTINGS,
9 + isManagedSettingPath,
10 + type ServerSettings,
11 +} from "@t3tools/contracts";
12 import * as Equal from "effect/Equal";
13 import { useLocation, useNavigate } from "@tanstack/react-router";
14 import { createContext, type ComponentPropsWithoutRef, type ReactNode, useContext } from "react";
@@ -33,6 +38,7 @@ import {
38 } from "./SettingInheritance";
39
40 const EMPTY_SETTING_KEYS: readonly (keyof ServerSettings)[] = [];
41 +const EMPTY_MANAGED_PATHS: readonly string[] = [];
42
43 declare module "@tanstack/react-router" {
44 interface HistoryState {
@@ -303,7 +309,9 @@ export function SettingsRow({
309 control,
310 serverScoped = false,
311 settingKeys = EMPTY_SETTING_KEYS,
312 + managedPaths = EMPTY_MANAGED_PATHS,
313 mixed: mixedOverride,
314 + managed,
315 children,
316 className,
317 ...rowProps
@@ -316,7 +324,11 @@ export function SettingsRow({
324 control?: ReactNode;
325 serverScoped?: boolean;
326 settingKeys?: readonly (keyof ServerSettings)[];
327 + /** Dot paths inside a setting, such as `storageCleanup.logsAfterDays`, an administrator can lock. */
328 + managedPaths?: readonly string[];
329 mixed?: boolean;
330 + /** Why an administrator's policy turns this row's control off, from the contract's denial helpers. */
331 + managed?: string | undefined;
332 children?: ReactNode;
333 }) {
334 const targetRef = useSettingsSearchTarget<HTMLDivElement>(rowProps.id);
@@ -333,6 +345,22 @@ export function SettingsRow({
345 ? context.connectedEnvironments.length > 0 &&
346 context.connectedEnvironments.every((target) => writableIds.has(target.environmentId))
347 : primaryCanWrite;
348 + const serverConfigs = useServerConfigs();
349 + // An administrator's lock on any target wins over every other reason a control is inert.
350 + const lockablePaths = [...settingKeys, ...managedPaths];
351 + const managedBy =
352 + lockablePaths.length === 0
353 + ? undefined
354 + : (context
355 + ? context.connectedEnvironments.map((environment) => environment.serverConfig)
356 + : [primaryEnvironmentId === null ? undefined : serverConfigs.get(primaryEnvironmentId)]
357 + )
358 + .map((config) => config?.managedPolicy)
359 + .find(
360 + (policy) =>
361 + policy !== undefined &&
362 + lockablePaths.some((path) => isManagedSettingPath(policy, path)),
363 + )?.organization;
364 const clearOverrides = useClearScopedSettings();
365 const clearProjectOverrides = useClearProjectOverrides();
366 const isProjectScope =
@@ -361,17 +389,19 @@ export function SettingsRow({
389 ),
390 );
391 const overridingProjects = isProjectScope ? [] : projectOverrides(context, scopedKeys);
364 - const renderedReset = unavailable ? null : isProjectScope && scopedKeys.length > 0 ? (
365 - source === "project" || source === "mixed" ? (
366 - <SettingResetButton
367 - label={typeof title === "string" ? title : "override"}
368 - tooltip="Reset to inherited value"
369 - onClick={() => (onResetOverride ? onResetOverride() : clearOverrides(scopedKeys))}
370 - />
371 - ) : null
372 - ) : (
373 - resetAction
374 - );
392 + const renderedReset =
393 + unavailable || managedBy !== undefined || managed !== undefined ? null : isProjectScope &&
394 + scopedKeys.length > 0 ? (
395 + source === "project" || source === "mixed" ? (
396 + <SettingResetButton
397 + label={typeof title === "string" ? title : "override"}
398 + tooltip="Reset to inherited value"
399 + onClick={() => (onResetOverride ? onResetOverride() : clearOverrides(scopedKeys))}
400 + />
401 + ) : null
402 + ) : (
403 + resetAction
404 + );
405 const inertControl = (message: string) => (
406 <Tooltip>
407 <TooltipTrigger
@@ -393,24 +423,28 @@ export function SettingsRow({
423 </Tooltip>
424 );
425 const renderedControl =
396 - unavailable && control
397 - ? inertControl(
398 - !canWriteSettings
399 - ? `This connection lacks permission to change settings on ${
400 - context
401 - ? context.connectedEnvironments
402 - .filter((target) => !writableIds.has(target.environmentId))
403 - .map((target) => target.label)
404 - .join(", ") || "the selected environment"
405 - : (primaryEnvironment?.label ?? "the primary environment")
406 - }.`
407 - : context
408 - ? "Reconnect the selected environment to change this setting."
409 - : PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE,
410 - )
411 - : environmentWide && control
412 - ? inertControl("Environment-wide setting. Select an environment to change it.")
413 - : control;
426 + managed !== undefined && control
427 + ? inertControl(managed)
428 + : managedBy !== undefined && control
429 + ? inertControl(`Managed by ${managedBy}.`)
430 + : unavailable && control
431 + ? inertControl(
432 + !canWriteSettings
433 + ? `This connection lacks permission to change settings on ${
434 + context
435 + ? context.connectedEnvironments
436 + .filter((target) => !writableIds.has(target.environmentId))
437 + .map((target) => target.label)
438 + .join(", ") || "the selected environment"
439 + : (primaryEnvironment?.label ?? "the primary environment")
440 + }.`
441 + : context
442 + ? "Reconnect the selected environment to change this setting."
443 + : PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE,
444 + )
445 + : environmentWide && control
446 + ? inertControl("Environment-wide setting. Select an environment to change it.")
447 + : control;
448 const customized =
449 context !== null &&
450 settingKeys.some((key) =>
apps/web/src/components/settings/updateTrackSwitch.logic.test.ts
+12 -1
@@ -1,7 +1,7 @@
1 import type { DesktopUpdateChannel, DesktopUpdateState } from "@t3tools/contracts";
2 import { describe, expect, it } from "vite-plus/test";
3
4 -import { prepareLocalTrackSwitch } from "./updateTrackSwitch.logic";
4 +import { localUpdaterStaysPut, prepareLocalTrackSwitch } from "./updateTrackSwitch.logic";
5
6 const STABLE = "0.1.3";
7
@@ -74,3 +74,14 @@ describe("prepareLocalTrackSwitch", () => {
74 expect(undo.saved).toEqual(["latest"]);
75 });
76 });
77 +
78 +describe("localUpdaterStaysPut", () => {
79 + it("moves an app whose updater is off only because its policy rules out nightly", () => {
80 + const blocked = { enabled: false, channelBlockedByPolicy: true as const };
81 + expect(localUpdaterStaysPut(blocked, "latest")).toBe(false);
82 + expect(localUpdaterStaysPut(blocked, "nightly")).toBe(true);
83 + // Off for another reason too, such as T3CODE_DISABLE_AUTO_UPDATE or a .deb install.
84 + expect(localUpdaterStaysPut({ enabled: false }, "latest")).toBe(true);
85 + expect(localUpdaterStaysPut({ enabled: true }, "nightly")).toBe(false);
86 + });
87 +});
apps/web/src/components/settings/updateTrackSwitch.logic.ts
+13
@@ -48,3 +48,16 @@ export async function prepareLocalTrackSwitch(
48 : (local.message ?? `This app found no build of ${input.version} to install.`),
49 };
50 }
51 +
52 +/**
53 + * Whether this app stays put while connected machines move: its updater is off, as for a .deb
54 + * install or without a feed. Off only because a policy rules out its nightly channel, it moves.
55 + */
56 +export function localUpdaterStaysPut(
57 + state: Pick<DesktopUpdateState, "enabled" | "channelBlockedByPolicy"> | null | undefined,
58 + target: DesktopUpdateChannel,
59 +): boolean {
60 + return (
61 + state?.enabled === false && !(target === "latest" && state.channelBlockedByPolicy === true)
62 + );
63 +}
apps/web/src/components/sidebar/SidebarUpdatePill.tsx
+12 -3
@@ -1,4 +1,8 @@
1 -import type { DesktopBridge, DesktopUpdateState } from "@t3tools/contracts";
1 +import {
2 + type DesktopBridge,
3 + type DesktopUpdateState,
4 + managedUpdatesDenial,
5 +} from "@t3tools/contracts";
6 import { TriangleAlertIcon } from "lucide-react";
7 import { type ComponentProps, useId, useRef, useState } from "react";
8 import { flushSync } from "react-dom";
@@ -8,6 +12,7 @@ import { useMediaQuery } from "../../hooks/useMediaQuery";
12 import { cn } from "../../lib/utils";
13 import { ensureLocalApi } from "../../localApi";
14 import { useDesktopUpdateState } from "../../state/desktopUpdate";
15 +import { usePrimaryManagedPolicy } from "../../state/managedPolicy";
16 import { stackedThreadToast, toastManager } from "../ui/toast";
17 import {
18 canCheckForUpdate,
@@ -192,6 +197,8 @@ export function SidebarUpdatePill() {
197
198 function SidebarUpdateControl() {
199 const state = useDesktopUpdateState();
200 + // The desktop updates this machine, whose policy the primary environment reports.
201 + const updatesDenial = managedUpdatesDenial(usePrimaryManagedPolicy());
202 const [isActionPending, setIsActionPending] = useState(false);
203 const [isConfirmingEverything, setIsConfirmingEverything] = useState(false);
204 const [checkAnimationKey, setCheckAnimationKey] = useState(0);
@@ -239,7 +246,7 @@ function SidebarUpdateControl() {
246 showCheckIcon,
247 });
248 const idleTooltip =
242 - !showUpdateDetails && !showCheckIcon ? getDesktopUpdateIdleTooltip(state) : null;
249 + !showUpdateDetails && !showCheckIcon ? getDesktopUpdateIdleTooltip(state, updatesDenial) : null;
250 const tooltip = runsEverything
251 ? everything.summary
252 : showUpdateDetails
@@ -327,7 +334,9 @@ function SidebarUpdateControl() {
334 type: "error",
335 title: "Could not check for updates",
336 description:
330 - result.state.message ?? "Automatic updates are not available in this build.",
337 + updatesDenial ??
338 + result.state.message ??
339 + "Automatic updates are not available in this build.",
340 }),
341 );
342 })
apps/web/src/components/sidebar/updateEverything.logic.test.ts
+60
@@ -84,6 +84,48 @@ describe("collectServerUpdateTargets", () => {
84 ["manual", "needs a manual update"],
85 ]);
86 });
87 +
88 + it("skips servers whose policy refuses the update, with the policy's message", () => {
89 + const managed = (
90 + id: string,
91 + updates: { mode: "off" } | { mode: "auto"; allowNightly: false },
92 + selfUpdate: "boot-service" | "desktop-managed" = "boot-service",
93 + ) => {
94 + const base = machine(id, "0.0.40", selfUpdate);
95 + return {
96 + ...base,
97 + serverConfig: {
98 + ...base.serverConfig!,
99 + managedPolicy: { organization: "Example Corp", lockedSettings: [], limits: { updates } },
100 + },
101 + };
102 + };
103 + const machines = [
104 + managed("off", { mode: "off" }),
105 + managed("no-nightly", { mode: "auto", allowNightly: false }),
106 + // A desktop app updates from its own feed, whatever track this app is on.
107 + managed("desktop-no-nightly", { mode: "auto", allowNightly: false }, "desktop-managed"),
108 + ];
109 +
110 + expect(
111 + collectServerUpdateTargets(machines, "0.0.50").skipped.map((entry) => [
112 + entry.label,
113 + entry.reason,
114 + ]),
115 + ).toEqual([["off", "Example Corp manages T3 Code updates."]]);
116 + expect(
117 + collectServerUpdateTargets(
118 + machines.map((entry) => ({
119 + ...entry,
120 + serverConfig: {
121 + ...entry.serverConfig,
122 + environment: { ...entry.serverConfig.environment, serverVersion: "0.0.49-nightly.1" },
123 + },
124 + })),
125 + "0.0.50-nightly.20261028.1",
126 + ).skipped.map((entry) => entry.label),
127 + ).toEqual(["off", "no-nightly"]);
128 + });
129 });
130
131 describe("collectChannelSwitchTargets", () => {
@@ -154,6 +196,18 @@ describe("collectChannelSwitchTargets", () => {
196 ]);
197 });
198
199 + const managedHost = (base: UpdateEverythingMachine): UpdateEverythingMachine => ({
200 + ...base,
201 + serverConfig: {
202 + ...base.serverConfig!,
203 + managedPolicy: {
204 + organization: "Example Corp",
205 + lockedSettings: [],
206 + limits: { updates: { mode: "auto", allowNightly: false } },
207 + },
208 + },
209 + });
210 +
211 it("moves stable hosts to nightly only when nightly knows their database", () => {
212 const nightly = { channel: "nightly" as const, version: NIGHTLY, databaseMigration: 72 };
213 const { targets, skipped } = collectChannelSwitchTargets(
@@ -171,6 +225,8 @@ describe("collectChannelSwitchTargets", () => {
225 },
226 }),
227 machine("current", NIGHTLY, "boot-service"),
228 + // The server refuses a track its policy rules out, so the dialog skips it up front.
229 + managedHost(host(machine("no-nightly", "0.1.2", "boot-service"), 70)),
230 ],
231 nightly,
232 );
@@ -184,6 +240,10 @@ describe("collectChannelSwitchTargets", () => {
240 `its database has changes ${NIGHTLY} does not support yet; stay on Stable until Nightly has them`,
241 ],
242 ["old-desktop", "needs a newer desktop app"],
243 + [
244 + "no-nightly",
245 + "Example Corp manages T3 Code updates. Only stable releases can be installed.",
246 + ],
247 ]);
248 });
249 });
apps/web/src/components/sidebar/updateEverything.logic.ts
+43 -6
@@ -1,9 +1,11 @@
1 import type { ServerUpdateState } from "@t3tools/client-runtime/state/server";
2 -import type {
3 - DesktopUpdateChannel,
4 - EnvironmentId,
5 - ServerConfig,
6 - ServerSelfUpdateCapability,
2 +import {
3 + type DesktopUpdateChannel,
4 + type EnvironmentId,
5 + managedNightlyDeniedMessage,
6 + managedUpdatesDenial,
7 + type ServerConfig,
8 + type ServerSelfUpdateCapability,
9 } from "@t3tools/contracts";
10 import { cliReleaseChannelOf, desktopUpdateChannelOf } from "@t3tools/shared/cliRelease";
11 import { compareSemverVersions } from "@t3tools/shared/semver";
@@ -21,6 +23,7 @@ export interface UpdateEverythingMachine {
23 readonly serverConfig: {
24 readonly environment: ServerConfig["environment"];
25 readonly settings: Pick<ServerConfig["settings"], "continueThreadsAfterServerUpdate">;
26 + readonly managedPolicy?: ServerConfig["managedPolicy"];
27 } | null;
28 readonly connected: boolean;
29 readonly hostedByThisApp: boolean;
@@ -92,6 +95,14 @@ export function collectServerUpdateTargets(
95 continue;
96 }
97 const selfUpdate = resolveServerSelfUpdateCapability(config);
98 + const managedDenial = managedMachineUpdateDenial(
99 + config,
100 + selfUpdate === "desktop-managed" ? undefined : targetVersion,
101 + );
102 + if (managedDenial !== undefined) {
103 + skip(managedDenial);
104 + continue;
105 + }
106 const desktopAppUpdate = supportsDesktopAppUpdate(config);
107 if (selfUpdate === null) {
108 skip("needs a manual update");
@@ -190,6 +201,26 @@ export function localSwitchBlockReason(
201 );
202 }
203
204 +/**
205 + * The server refuses these with the same message; say so before the run instead of after.
206 + * `targetVersion` is undefined when the server picks its own version, as desktop apps do.
207 + */
208 +function managedMachineUpdateDenial(
209 + config: NonNullable<UpdateEverythingMachine["serverConfig"]>,
210 + targetVersion: string | undefined,
211 +): string | undefined {
212 + const policy = config.managedPolicy;
213 + return (
214 + managedUpdatesDenial(policy) ??
215 + (policy !== undefined &&
216 + policy.limits?.updates?.allowNightly === false &&
217 + targetVersion !== undefined &&
218 + cliReleaseChannelOf(targetVersion) !== "stable"
219 + ? managedNightlyDeniedMessage(policy.organization)
220 + : undefined)
221 + );
222 +}
223 +
224 /** Servers move to the release; desktop-managed hosts reinstall their app on its track. A desktop
225 * host already current gets a track-only request, since its saved track may still differ. */
226 export function collectChannelSwitchTargets(
@@ -229,7 +260,8 @@ export function collectChannelSwitchTargets(
260 if (
261 !("skip" in move) &&
262 move.selfUpdate === "desktop-managed" &&
232 - unavailableReason(machine) === null
263 + unavailableReason(machine) === null &&
264 + managedMachineUpdateDenial(config, release.version) === undefined
265 ) {
266 targets.push({ ...target(move.selfUpdate, serverVersion), trackOnly: true });
267 }
@@ -240,6 +272,11 @@ export function collectChannelSwitchTargets(
272 skip(unavailable ?? "not connected");
273 continue;
274 }
275 + const managedDenial = managedMachineUpdateDenial(config, release.version);
276 + if (managedDenial !== undefined) {
277 + skip(managedDenial);
278 + continue;
279 + }
280 const move = trackSwitchMove(config, sameTrack);
281 if ("skip" in move) {
282 skip(move.skip);
apps/web/src/state/managedPolicy.test.ts new
+45
@@ -0,0 +1,45 @@
1 +import { ProviderDriverKind, type ManagedPolicySummary } from "@t3tools/contracts";
2 +import { describe, expect, it } from "vite-plus/test";
3 +
4 +import { managedInstanceLocks } from "./managedPolicy";
5 +
6 +const codex = ProviderDriverKind.make("codex");
7 +const claude = ProviderDriverKind.make("claudeAgent");
8 +
9 +const policy: ManagedPolicySummary = {
10 + organization: "Example Corp",
11 + lockedSettings: [],
12 + limits: {
13 + providers: {
14 + lockedInstanceFields: {
15 + [codex]: ["config.binaryPath", "environment.OPENAI_BASE_URL", "environment.HTTPS_PROXY"],
16 + },
17 + },
18 + },
19 +};
20 +
21 +describe("managedInstanceLocks", () => {
22 + it("splits locked instance paths into config keys and environment names", () => {
23 + const locks = managedInstanceLocks(policy, codex);
24 + expect(locks && [...locks.configKeys]).toEqual(["binaryPath"]);
25 + expect(locks && [...locks.environmentNames]).toEqual(["OPENAI_BASE_URL", "HTTPS_PROXY"]);
26 + expect(locks?.reason).toBe("Managed by Example Corp.");
27 + });
28 +
29 + it("treats a bare environment path as every variable", () => {
30 + const ceilingPolicy = {
31 + ...policy,
32 + limits: {
33 + providers: { lockedInstanceFields: { [codex]: ["config.binaryPath", "environment"] } },
34 + },
35 + };
36 + const locks = managedInstanceLocks(ceilingPolicy, codex);
37 + expect(locks?.wholeEnvironment).toBe(true);
38 + expect(managedInstanceLocks(policy, codex)?.wholeEnvironment).toBe(false);
39 + });
40 +
41 + it("locks nothing for drivers the policy does not pin, or without a policy", () => {
42 + expect(managedInstanceLocks(policy, claude)).toBeUndefined();
43 + expect(managedInstanceLocks(undefined, codex)).toBeUndefined();
44 + });
45 +});
apps/web/src/state/managedPolicy.ts new
+67
@@ -0,0 +1,67 @@
1 +import type { EnvironmentId, ManagedPolicySummary, ProviderDriverKind } from "@t3tools/contracts";
2 +
3 +import { useServerConfigs } from "./entities";
4 +import { usePrimaryEnvironmentId } from "./environments";
5 +
6 +/** The policy an environment's administrator applies, or undefined when it is unmanaged. */
7 +export function useManagedPolicy(
8 + environmentId: EnvironmentId | null | undefined,
9 +): ManagedPolicySummary | undefined {
10 + const serverConfigs = useServerConfigs();
11 + return environmentId == null ? undefined : serverConfigs.get(environmentId)?.managedPolicy;
12 +}
13 +
14 +export function usePrimaryManagedPolicy(): ManagedPolicySummary | undefined {
15 + return useManagedPolicy(usePrimaryEnvironmentId());
16 +}
17 +
18 +/**
19 + * Why a control acting on several environments is unavailable: the first denial any target's
20 + * policy gives, since one refusing target refuses the whole action.
21 + */
22 +export function firstManagedDenial(
23 + policies: Iterable<ManagedPolicySummary | undefined>,
24 + deny: (policy: ManagedPolicySummary | undefined) => string | undefined,
25 +): string | undefined {
26 + for (const policy of policies) {
27 + const denial = deny(policy);
28 + if (denial !== undefined) return denial;
29 + }
30 + return undefined;
31 +}
32 +
33 +/** What usage-data notices say when the policy turns product analytics off. */
34 +export function managedTelemetryOffMessage(
35 + policy: ManagedPolicySummary | undefined,
36 +): string | undefined {
37 + return policy?.limits?.telemetry === false
38 + ? `${policy.organization} turned off anonymous usage data.`
39 + : undefined;
40 +}
41 +
42 +export interface ManagedInstanceLocks {
43 + /** Keys inside the instance's `config` users cannot change. */
44 + readonly configKeys: ReadonlySet<string>;
45 + /** Environment variables users cannot edit, rename, or remove. */
46 + readonly environmentNames: ReadonlySet<string>;
47 + /** Under a runtime-mode ceiling every variable is the administrator's, not only named ones. */
48 + readonly wholeEnvironment: boolean;
49 + readonly reason: string;
50 +}
51 +
52 +/** What the policy pins on instances of `driver`, or undefined when nothing is. */
53 +export function managedInstanceLocks(
54 + policy: ManagedPolicySummary | undefined,
55 + driver: ProviderDriverKind,
56 +): ManagedInstanceLocks | undefined {
57 + const paths = policy?.limits?.providers?.lockedInstanceFields?.[driver];
58 + if (policy === undefined || paths === undefined || paths.length === 0) return undefined;
59 + const fieldsUnder = (prefix: string) =>
60 + new Set(paths.flatMap((path) => (path.startsWith(prefix) ? [path.slice(prefix.length)] : [])));
61 + return {
62 + configKeys: fieldsUnder("config."),
63 + environmentNames: fieldsUnder("environment."),
64 + wholeEnvironment: paths.includes("environment"),
65 + reason: `Managed by ${policy.organization}.`,
66 + };
67 +}
docs/user/install.md
+1
@@ -208,3 +208,4 @@ For provider-specific setup and accounts, see [Codex](./providers-codex.md),
208 - [Remote access](./remote-access.md): connect from another device.
209 - [Running in the background](./background-service.md): keep a Linux or macOS host available.
210 - [Updating T3 Code](./updating.md): update the app and connected servers.
211 +- [Managed policy](./managed-policy.md): configure T3 Code for everyone on a machine.
docs/user/managed-policy.md new
+274
@@ -0,0 +1,274 @@
1 +# Managed policy
2 +
3 +A managed policy lets an administrator configure T3 Code for every user on a machine. It sets
4 +defaults and locks for settings, and limits such as the broadest permission mode or which
5 +providers may run. The T3 Code server on the machine enforces it for every app that connects:
6 +the desktop app, a browser, or the mobile app.
7 +
8 +## Roll out a policy
9 +
10 +1. Write the policy as JSON, starting from the [example](#write-a-policy).
11 +2. Run `t3 policy check policy.json`. It prints what the policy will do, or what is wrong with it.
12 +3. Deploy the policy to each machine with your device management tool, in
13 + [one of the supported places](#where-the-policy-goes).
14 +4. Restart T3 Code on the machine. The server reads the policy only when it starts.
15 +5. Run `t3 policy show` on the machine to
16 + [check what the server loaded](#check-what-the-server-loaded).
17 +
18 +The desktop app includes the `t3` command; see [The `t3` command](./install.md#the-t3-command).
19 +
20 +## Write a policy
21 +
22 +```json
23 +{
24 + "schemaVersion": 1,
25 + "organization": "Example Corp",
26 + "supportUrl": "https://it.example.com/t3",
27 + "settings": {
28 + "defaultRuntimeMode": { "value": "approval-required", "locked": false },
29 + "enableAgentBrowserAccess": { "value": false, "locked": true }
30 + },
31 + "limits": {
32 + "maxRuntimeMode": "auto-accept-edits",
33 + "clients": ["desktop", "local-browser"],
34 + "telemetry": false
35 + }
36 +}
37 +```
38 +
39 +`schemaVersion` and `organization` are required. Users see the organization's name in Settings
40 +and beside each control the policy locks, with a link to `supportUrl` if you set one. [`settings`](#settings)
41 +sets defaults and locks, and [`limits`](#limits) restricts what T3 Code may do.
42 +
43 +Every user on the machine can read the policy, so do not put credentials in it.
44 +
45 +## Where the policy goes
46 +
47 +Use one of these per machine:
48 +
49 +| OS | Native policy | Policy file |
50 +| ------- | ------------------------------------------------------------------- | ------------------------------------------------- |
51 +| macOS | Configuration profile for `com.t3tools.t3code` | `/Library/Application Support/T3Code/policy.json` |
52 +| Windows | `Policy` string value under `HKLM\SOFTWARE\Policies\T3Tools\T3Code` | `C:\Program Files\T3Code\policy.json` |
53 +| Linux | | `/etc/t3code/policy.json` |
54 +
55 +T3 Code does not merge sources. If a machine has both a native policy and a policy file, T3 Code
56 +refuses to start until you remove one.
57 +
58 +**Policy file.** Copy the JSON to the path for the OS. Make it and its folder writable only by
59 +administrators.
60 +
61 +**macOS configuration profile.** Add a custom settings payload for the preference domain
62 +`com.t3tools.t3code`. The payload's keys are the policy's top-level keys (`schemaVersion`,
63 +`organization`, `supportUrl`, `settings`, `limits`); JSON objects become dictionaries and lists
64 +become arrays. To make the payload from a policy file you checked, run
65 +`plutil -convert xml1 -o com.t3tools.t3code.plist policy.json` and upload the result. Install it as
66 +a device profile, since T3 Code ignores user profiles, and deploy only one profile for this domain.
67 +A profile cannot hold `null`, so use a policy file if a setting's value must be `null`.
68 +
69 +**Windows registry.** Set the `Policy` value (`REG_SZ`) to the whole policy as one line of JSON,
70 +from Group Policy Preferences or an Intune script. T3 Code reads it through the Windows registry
71 +API, so it works where registry tools such as `reg.exe` are blocked for users. In PowerShell, as an
72 +administrator:
73 +
74 +```powershell
75 +$json = (Get-Content -Raw -Encoding UTF8 policy.json) -replace '\r?\n\s*', ''
76 +New-Item -Path HKLM:\SOFTWARE\Policies\T3Tools\T3Code -Force | Out-Null
77 +Set-ItemProperty -Path HKLM:\SOFTWARE\Policies\T3Tools\T3Code -Name Policy -Value $json -Type String
78 +```
79 +
80 +## Check what the server loaded
81 +
82 +Run `t3 policy show` as the user who runs T3 Code. It prints the installed policy and its
83 +fingerprint, then says whether the running server loaded that policy or an older one. The server
84 +reads the policy only when it starts, so "Restart T3 Code to apply the installed policy" means it
85 +still enforces the old one. In Settings, users see that your organization manages the environment,
86 +and each locked control shows **Managed by**.
87 +
88 +## Change or remove a policy
89 +
90 +After you deploy, change, or remove a policy, restart the T3 Code server on the machine: quit and
91 +reopen the desktop app, or run `t3 service restart` for the
92 +[background service](./background-service.md). Reconnecting a phone or browser does not reload the
93 +policy.
94 +
95 +To remove a policy, delete the file, remove the profile, or delete the registry value, then restart
96 +the server. Users get back the settings they had chosen, since T3 Code never writes policy values
97 +into them.
98 +
99 +## When T3 Code refuses to start
100 +
101 +T3 Code refuses to start rather than run with a policy it cannot fully enforce. That includes a
102 +policy it cannot read or parse, a setting it does not know, a value of the wrong type, a key this
103 +version does not support, or a machine with both a native policy and a file. The error names where
104 +the policy came from and what is wrong.
105 +
106 +`t3 policy check` catches the same problems in a JSON file. For a profile or registry value, check
107 +the JSON before you convert it. A policy written for a newer version can use keys an older one
108 +cannot enforce, so upgrade T3 Code before you deploy a policy that uses them.
109 +
110 +## Settings
111 +
112 +Each key under `settings` is a setting's path in the server's `settings.json`, such as
113 +`storageCleanup.logsAfterDays`. To find a path, change the setting in T3 Code and look in
114 +`settings.json` under `~/.t3/userdata`.
115 +
116 +- `"locked": false` sets a default. It applies wherever the user has not chosen a value of their
117 + own, and users can change it.
118 +- `"locked": true` sets the value. Users and agents cannot change it, in Settings or in a project's
119 + settings, and Settings shows the control as managed by your organization. Removing the policy
120 + brings back the user's own value.
121 +
122 +A few settings need care:
123 +
124 +- A default cannot add an entry, such as a provider instance, because users could never remove it.
125 + Lock the entry instead, or set provider fields with [`providers.instances`](#providers).
126 +- A setting that can be empty, such as `defaultModelSelection`, is managed as a whole. You cannot
127 + manage one field inside it.
128 +- `defaultRuntimeMode` cannot be broader than [`maxRuntimeMode`](#permission-modes).
129 +- `worktreeCleanup`, which projects can also set, overrides the `worktree` rules in
130 + `storageCleanup`. Lock it along with those rules; T3 Code refuses a policy that locks only the
131 + rules.
132 +- Manage `idleCompaction`, not the older `compactIdleThreads`. A Claude instance's own idle
133 + compaction choice still wins over `idleCompaction`.
134 +- A provider instance's fields override each other, so lock `providerInstances.<id>` as a whole,
135 + or pin single fields with [`providers.instances`](#providers). T3 Code refuses a lock on one
136 + field inside an instance. A whole-instance lock covers only that instance; to cover every
137 + instance of a provider, use `providers.instances`.
138 +
139 +## Limits
140 +
141 +`limits` restricts what T3 Code may do. Leave a key out to keep T3 Code's normal behavior.
142 +
143 +```json
144 +{
145 + "schemaVersion": 1,
146 + "organization": "Example Corp",
147 + "limits": {
148 + "maxRuntimeMode": "auto-accept-edits",
149 + "clients": ["desktop"],
150 + "connect": false,
151 + "webhookTasks": false,
152 + "browserCookieImport": false,
153 + "telemetry": false,
154 + "providers": {
155 + "allowedDrivers": ["claudeAgent", "codex"],
156 + "instances": {
157 + "claudeAgent": {
158 + "locked": true,
159 + "environment": [{ "name": "CLAUDE_CODE_USE_BEDROCK", "value": "1" }]
160 + }
161 + }
162 + },
163 + "updates": { "mode": "auto", "feedUrl": "https://updates.example.com/t3code/" }
164 + }
165 +}
166 +```
167 +
168 +### Permission modes
169 +
170 +`maxRuntimeMode` is the broadest [permission mode](./permission-modes.md) any thread may use:
171 +`approval-required` (Supervised), `auto-accept-edits`, `auto`, or `full-access`. It covers threads
172 +that users start, agents start, and scheduled tasks start. A thread already above the limit cannot
173 +run another turn until someone lowers its mode; its queued messages send once that happens. New
174 +threads start at the limit when the user's default is above it.
175 +
176 +With `maxRuntimeMode` set, you own each provider's launch settings: binary path, launch arguments,
177 +config home, and the environment variables set on each provider. They come from
178 +[`providers.instances`](#providers) or T3 Code's defaults, and users cannot change them, because a
179 +wrapper script, a launch flag, or a variable such as `NODE_OPTIONS` could otherwise turn off the
180 +provider's approvals. Pin the variables your users need, such as a gateway URL, in
181 +`providers.instances`. Variables in the environment that starts T3 Code itself still reach
182 +providers.
183 +
184 +ACP agents' own mode menus have no effect under `maxRuntimeMode`, except Antigravity's, whose modes
185 +T3 Code can place under the limit. Users still choose which ACP Registry agent runs; leave
186 +`acpRegistry` out of `allowedDrivers` to stop that.
187 +
188 +The limit decides which modes T3 Code asks the provider for. It is not a sandbox; see
189 +[What a policy does not cover](#what-a-policy-does-not-cover).
190 +
191 +### Clients and T3 Connect
192 +
193 +`clients` lists how the server may run:
194 +
195 +- `desktop`: as the desktop app's own server.
196 +- `local-browser`: as a server only browsers on this machine reach, such as `npx t3`.
197 +- `remote`: reachable from phones, other computers, and app.t3.codes over the network.
198 +
199 +`remote` is the line that matters. A server reachable from the network also accepts browsers on
200 +this machine, and the two local kinds differ only in how T3 Code was started. On machines with the
201 +desktop app, keep `desktop` in the list, or the app cannot start.
202 +
203 +Without `remote`, the server listens only on a loopback address, creates no pairing links, and
204 +signs out devices that paired earlier. It does not start with a host other than a loopback
205 +address or `localhost`. The [background service](./background-service.md) listens on private
206 +networks by default, so set `T3CODE_HOST=127.0.0.1` in its `service.env`. The desktop app starts
207 +with network access and Tailscale Serve off, whatever the user chose. That also turns off
208 +T3 Connect. To keep other remote access but turn off T3 Connect alone, set `"connect": false`.
209 +
210 +When it starts, the server also turns off each Tailscale Serve route, HTTPS or TCP, that forwards
211 +to it, such as one `t3 pair --tailscale` set up, and leaves other routes alone. It does not start
212 +while such a route stays on, or while Tailscale's answer cannot be read; the error names the
213 +command that turns the route off. A route whose target is a name, such as `localhost` or another
214 +machine on the same port, also stops it, since a name can resolve to this server; change the route
215 +or T3 Code's port. If Tailscale is installed but does not answer, as on a Mac where it was never set up, the
216 +server does not start until Tailscale is set up or removed. It does start when Tailscale is not
217 +installed, not running, or
218 +logged out, since nothing forwards then; a route Tailscale kept returns when Tailscale runs again,
219 +so restart T3 Code after that.
220 +
221 +### Other capabilities
222 +
223 +- `webhookTasks: false`: scheduled tasks cannot use webhook triggers. Existing webhook tasks stay
224 + but do not run, and cannot be turned back on. Users can still edit or delete them.
225 +- `browserCookieImport: false`: users cannot import cookies from another browser into T3 Code's
226 + browser.
227 +- `telemetry: false`: the server and desktop app send no [product usage data](./telemetry.md) or
228 + relay connection traces. A policy cannot turn them on. A browser that opens the server, such as
229 + app.t3.codes, still sends its own relay traces.
230 +
231 +### Providers
232 +
233 +`providers.allowedDrivers` lists the providers that may run, by ID: `codex` (Codex),
234 +`claudeAgent` (Claude), `cursor` (Cursor), `grok` (Grok), `opencode` (OpenCode), `antigravity`
235 +(Antigravity), `fx` (fx), `pi` (Pi), `muse` (Muse Code), and `acpRegistry` (ACP Registry).
236 +`t3 policy check` rejects an ID this version does not know. Threads on other providers stay,
237 +marked unavailable, and users can still turn those providers off.
238 +
239 +`providers.instances` sets fields on every instance of a provider, such as an environment variable
240 +that routes Claude through Amazon Bedrock or a base URL for a company gateway. `binaryPath` and
241 +`launchArgs` work only for providers that have those settings. With `"locked": true`, users cannot
242 +change the fields you set. With `"locked": false`, the fields fill in only what the user left
243 +empty. A `codex` entry that is locked, or any `codex` entry under `maxRuntimeMode`, also rules out
244 +[Connect with ChatGPT](./providers-codex.md#connect-with-chatgpt), since that runtime would skip
245 +your fields. In the same way, an `opencode` entry like that rules out a server URL, so OpenCode
246 +starts the binary you set.
247 +
248 +### Updates
249 +
250 +- `mode`: `auto` keeps the normal update flow. `off` stops T3 Code from checking for updates, for
251 + machines that get T3 Code through device management.
252 +- `feedUrl`: the desktop app updates from your own mirror of the release feed instead of GitHub.
253 + Publish only the versions you have approved. The `t3` command-line server updates through npm,
254 + so pin it with your package tooling.
255 +- `allowNightly: false`: the nightly channel is unavailable.
256 +
257 +## What a policy does not cover
258 +
259 +The policy controls what T3 Code does. Agents run through each provider's own CLI, which reads its
260 +own configuration, such as `~/.claude`, and which a user can also run outside T3 Code. To restrict
261 +those CLIs, use their own managed configuration, such as Claude Code's managed settings.
262 +
263 +On a managed Windows machine, the desktop app does not run a WSL environment. A T3 Code server a
264 +user starts inside WSL reads `/etc/t3code/policy.json` in that distro, not the Windows policy.
265 +Deploy the policy file there too if your users run T3 Code in WSL.
266 +
267 +Without `remote`, T3 Code does not expose the server, but a user can still forward its local port
268 +with other tools.
269 +
270 +A user with administrator rights on the machine can edit or remove the policy. T3 Code enforces
271 +the policy in its own processes, which run as the user, so it stops users from changing managed
272 +settings in T3 Code but does not stop a user who modifies or replaces T3 Code itself. A version
273 +from before managed policy ignores it too. To control which builds can run, use your device
274 +management tool's application controls.
docs/user/permission-modes.md
+3
@@ -17,6 +17,9 @@ and modes you choose in a draft keep their permissions.
17 | **Auto** | Uses the provider's automatic review to approve routine actions and ask about others. |
18 | **Full access** | Allows commands and edits without approval prompts. |
19
20 +An administrator can cap the modes available on a machine with a
21 +[managed policy](./managed-policy.md#permission-modes); modes above the cap show who manages them.
22 +
23 Approve or reject requests in the conversation to let the agent continue. Permission modes do
24 not prevent the agent from asking questions about the task. Subagent approval requests appear in
25 the parent conversation with the subagent's name, so you can respond without switching threads.
docs/user/remote-access.md
+1 -1
@@ -189,7 +189,7 @@ The mapping created by `pair --tailscale` persists across restarts. Remove its
189 default-port mapping with:
190
191 ```bash
192 -tailscale serve --https=443 off
192 +tailscale serve --https=443 --set-path=/ off
193 ```
194
195 If that port is already in use, choose another with
docs/user/telemetry.md
+3
@@ -18,6 +18,9 @@ environment before starting it. Relay tracing also stops when `T3CODE_OTEL_SDK_D
18 `OTEL_SDK_DISABLED` turns OpenTelemetry export off. The web app in a browser, including one the
19 `t3` CLI opens, does not read these variables.
20
21 +An administrator can turn product events and relay tracing off for every user on a machine with
22 +a [managed policy](./managed-policy.md#other-capabilities).
23 +
24 The desktop app reads `T3CODE_TELEMETRY_ENABLED` from your shell profile (for example `~/.zshrc`) on macOS and
25 Linux, so export it there and restart the app. On Windows, set it as a user environment variable.
26
knip.jsonc
+6 -1
@@ -62,7 +62,12 @@
62 // The Vite+ web build prerequisite.
63 // Native and disk-loaded provider packages stay external to the bundle; the
64 // CLI archive and desktop sidecar stage them from this manifest.
65 - "ignoreDependencies": ["@effect/platform-node-shared", "@t3tools/web", "@napi-rs/keyring"],
65 + "ignoreDependencies": [
66 + "@effect/platform-node-shared",
67 + "@t3tools/web",
68 + "@napi-rs/keyring",
69 + "ffi-rs",
70 + ],
71 },
72 "apps/desktop": {
73 // Electron loads these bundles by filename rather than importing them.
packages/contracts/src/auth.ts
+5
@@ -8,6 +8,7 @@ import {
8 ClientWebDeployment,
9 TrimmedNonEmptyString,
10 } from "./baseSchemas.ts";
11 +import { RuntimeMode } from "./providerPolicy.ts";
12
13 export const ServerAuthPolicy = Schema.Literals([
14 "desktop-managed-local",
@@ -504,6 +505,10 @@ export const AuthMcpApprovalDetails = Schema.Struct({
505 csrfToken: Schema.optionalKey(Schema.String),
506 /** Only scopes held by this session qualify; others need a pairing code. Absent with `csrfToken`. */
507 oneClickAccess: Schema.optionalKey(Schema.Array(AuthMcpClientAccess)),
508 + /** A managed policy's runtime-mode ceiling; the page loads without the server's config. */
509 + runtimeModeCeiling: Schema.optionalKey(
510 + Schema.Struct({ organization: Schema.String, maxRuntimeMode: RuntimeMode }),
511 + ),
512 });
513 export type AuthMcpApprovalDetails = typeof AuthMcpApprovalDetails.Type;
514
packages/contracts/src/environmentHttp.ts
+2
@@ -345,6 +345,8 @@ const EnvironmentScopedOperationErrors = [
345 ] as const;
346 const EnvironmentPairingCredentialErrors = [
347 EnvironmentRequestInvalidError,
348 + // The managed policy does not allow remote clients.
349 + EnvironmentHttpForbiddenError,
350 ...EnvironmentScopedOperationErrors,
351 ] as const;
352 const EnvironmentSessionRevokeErrors = [
packages/contracts/src/index.ts
+1
@@ -28,6 +28,7 @@ export * from "./model.ts";
28 export * from "./keybindings.ts";
29 export * from "./server.ts";
30 export * from "./settings.ts";
31 +export * from "./managedPolicy.ts";
32 export * from "./git.ts";
33 export * from "./vcs.ts";
34 export * from "./sourceControl.ts";
packages/contracts/src/ipc.ts
+2
@@ -282,6 +282,8 @@ export interface DesktopUpdateState {
282 errorContext: "check" | "download" | "install" | null;
283 canRetry: boolean;
284 notAppliedVersion?: string;
285 + /** Off only because a managed policy rules out this channel; switching channels turns it on. */
286 + channelBlockedByPolicy?: true;
287 }
288
289 export interface DesktopUpdateReleaseNote {
packages/contracts/src/managedPolicy.ts new
+244
@@ -0,0 +1,244 @@
1 +import * as Schema from "effect/Schema";
2 +import * as Struct from "effect/Struct";
3 +
4 +import { TrimmedNonEmptyString } from "./baseSchemas.ts";
5 +import { ProviderDriverKind, ProviderInstanceEnvironmentVariableName } from "./providerInstance.ts";
6 +import { isRuntimeModeAbove, RuntimeMode } from "./providerPolicy.ts";
7 +
8 +/**
9 + * One server setting an administrator manages, keyed in the policy by its dot path in the
10 + * encoded `ServerSettings` (for example `storageCleanup.logsAfterDays`). `locked: false`
11 + * replaces the built-in default; `locked: true` also stops users and agents from changing it.
12 + */
13 +export const ManagedPolicySetting = Schema.Struct({
14 + value: Schema.Unknown,
15 + locked: Schema.Boolean,
16 +});
17 +export type ManagedPolicySetting = typeof ManagedPolicySetting.Type;
18 +
19 +/**
20 + * Fields an administrator pins on every instance of one driver, merged over the user's instance
21 + * when settings are read. `binaryPath` and `launchArgs` land in the driver's `config`, so a driver
22 + * without that config field rejects the policy. `locked: false` fills only what the user left empty.
23 + */
24 +export const ManagedProviderInstance = Schema.Struct({
25 + locked: Schema.Boolean,
26 + environment: Schema.optionalKey(
27 + Schema.Array(
28 + Schema.Struct({ name: ProviderInstanceEnvironmentVariableName, value: Schema.String }),
29 + ),
30 + ),
31 + binaryPath: Schema.optionalKey(TrimmedNonEmptyString),
32 + launchArgs: Schema.optionalKey(TrimmedNonEmptyString),
33 +});
34 +export type ManagedProviderInstance = typeof ManagedProviderInstance.Type;
35 +
36 +export const ManagedProviderLimits = Schema.Struct({
37 + /** Only these drivers run; instances of any other driver show as unavailable. */
38 + allowedDrivers: Schema.optionalKey(Schema.NonEmptyArray(ProviderDriverKind)),
39 + instances: Schema.optionalKey(Schema.Record(ProviderDriverKind, ManagedProviderInstance)),
40 +});
41 +export type ManagedProviderLimits = typeof ManagedProviderLimits.Type;
42 +
43 +/**
44 + * How T3 Code updates itself. `auto` is the default: it checks, and installs only when a user
45 + * asks. `off` never checks, for machines that get T3 Code through MDM.
46 + */
47 +export const ManagedUpdatesMode = Schema.Literals(["auto", "off"]);
48 +export type ManagedUpdatesMode = typeof ManagedUpdatesMode.Type;
49 +
50 +const HttpsUrl = TrimmedNonEmptyString.check(
51 + Schema.makeFilter((value: string) => /^https:\/\/[^\s/]+/i.test(value.trim()), {
52 + expected: "an https URL",
53 + }),
54 +);
55 +
56 +export const ManagedUpdatesPolicy = Schema.Struct({
57 + mode: ManagedUpdatesMode,
58 + /** A generic electron-updater feed the desktop app updates from instead of GitHub. */
59 + feedUrl: Schema.optionalKey(HttpsUrl),
60 + /** `false` makes the nightly channel unavailable. */
61 + allowNightly: Schema.optionalKey(Schema.Boolean),
62 +});
63 +export type ManagedUpdatesPolicy = typeof ManagedUpdatesPolicy.Type;
64 +
65 +/** A kind of client the server may accept, mapped onto `ServerAuthPolicy`. */
66 +export const ManagedPolicyClient = Schema.Literals(["desktop", "local-browser", "remote"]);
67 +export type ManagedPolicyClient = typeof ManagedPolicyClient.Type;
68 +
69 +/**
70 + * Restrictions that are not settings: users cannot opt out of them anywhere. For the boolean
71 + * capabilities, omitted means allowed and only `false` restricts.
72 + */
73 +export const ManagedPolicyLimits = Schema.Struct({
74 + /** The broadest runtime mode any thread may be created in, switched to, or run turns in. */
75 + maxRuntimeMode: Schema.optionalKey(RuntimeMode),
76 + /** Clients the server accepts. Without `remote`, nothing off this machine can pair. */
77 + clients: Schema.optionalKey(Schema.NonEmptyArray(ManagedPolicyClient)),
78 + /** `false` turns T3 Connect off and unlinks this machine. */
79 + connect: Schema.optionalKey(Schema.Boolean),
80 + webhookTasks: Schema.optionalKey(Schema.Boolean),
81 + /** Can only turn product analytics off, never force it on. */
82 + telemetry: Schema.optionalKey(Schema.Boolean),
83 + browserCookieImport: Schema.optionalKey(Schema.Boolean),
84 + providers: Schema.optionalKey(ManagedProviderLimits),
85 + updates: Schema.optionalKey(ManagedUpdatesPolicy),
86 +});
87 +export type ManagedPolicyLimits = typeof ManagedPolicyLimits.Type;
88 +
89 +/** The limits clients see: what the server enforces, which can be broader than the file says. */
90 +export const ManagedPolicySummaryLimits = Schema.Struct({
91 + maxRuntimeMode: Schema.optionalKey(RuntimeMode),
92 + clients: Schema.optionalKey(Schema.NonEmptyArray(ManagedPolicyClient)),
93 + /** `false` also when `clients` leaves out `remote`, since Connect is remote access. */
94 + connect: Schema.optionalKey(Schema.Boolean),
95 + webhookTasks: Schema.optionalKey(Schema.Boolean),
96 + telemetry: Schema.optionalKey(Schema.Boolean),
97 + browserCookieImport: Schema.optionalKey(Schema.Boolean),
98 + providers: Schema.optionalKey(
99 + Schema.Struct({
100 + /** Absent means every driver is allowed. */
101 + allowedDrivers: Schema.optionalKey(Schema.NonEmptyArray(ProviderDriverKind)),
102 + /**
103 + * Per driver, the instance fields users cannot change, as dot paths into the instance
104 + * envelope: `config.binaryPath`, `config.launchArgs`, `environment.<NAME>`. A bare
105 + * `environment` means every variable, as under `maxRuntimeMode`, where each driver's
106 + * launch configuration belongs to the administrator.
107 + */
108 + lockedInstanceFields: Schema.optionalKey(
109 + Schema.Record(ProviderDriverKind, Schema.Array(Schema.String)),
110 + ),
111 + }),
112 + ),
113 + /** No `feedUrl`: it can carry a token, and only the desktop app, which reads the file, uses it. */
114 + updates: Schema.optionalKey(ManagedUpdatesPolicy.mapFields(Struct.omit(["feedUrl"]))),
115 +});
116 +export type ManagedPolicySummaryLimits = typeof ManagedPolicySummaryLimits.Type;
117 +
118 +/**
119 + * The machine-wide policy file an administrator deploys. Decoded with excess properties
120 + * rejected: a key this build does not know might be a restriction it cannot enforce, and
121 + * starting anyway would look managed without being managed.
122 + */
123 +export const ManagedPolicyDocument = Schema.Struct({
124 + schemaVersion: Schema.Literal(1),
125 + /** Shown to users as "Managed by <organization>". */
126 + organization: TrimmedNonEmptyString,
127 + supportUrl: Schema.optionalKey(TrimmedNonEmptyString),
128 + settings: Schema.optionalKey(Schema.Record(Schema.String, ManagedPolicySetting)),
129 + limits: Schema.optionalKey(ManagedPolicyLimits),
130 +});
131 +export type ManagedPolicyDocument = typeof ManagedPolicyDocument.Type;
132 +
133 +/** What clients learn about the policy: enough to explain a locked control, no values. */
134 +export const ManagedPolicySummary = Schema.Struct({
135 + organization: TrimmedNonEmptyString,
136 + supportUrl: Schema.optionalKey(TrimmedNonEmptyString),
137 + /** Dot paths into `ServerSettings` that users cannot change. */
138 + lockedSettings: Schema.Array(Schema.String),
139 + /** What the server enforces; a missing key means no limit. */
140 + limits: Schema.optionalKey(ManagedPolicySummaryLimits),
141 +});
142 +export type ManagedPolicySummary = typeof ManagedPolicySummary.Type;
143 +
144 +/** The message every surface shows when the policy stops an update. */
145 +export function managedUpdatesMessage(organization: string): string {
146 + return `${organization} manages T3 Code updates.`;
147 +}
148 +
149 +/** The message when the policy allows only stable releases. */
150 +export function managedNightlyDeniedMessage(organization: string): string {
151 + return `${managedUpdatesMessage(organization)} Only stable releases can be installed.`;
152 +}
153 +
154 +/** Whether `path` is locked itself, sits inside a locked setting, or contains one. */
155 +export function isManagedSettingPath(
156 + summary: Pick<ManagedPolicySummary, "lockedSettings"> | undefined,
157 + path: string,
158 +): boolean {
159 + if (summary === undefined) return false;
160 + return summary.lockedSettings.some(
161 + (locked) => locked === path || locked.startsWith(`${path}.`) || path.startsWith(`${locked}.`),
162 + );
163 +}
164 +
165 +/** The one shape users see when policy refuses something: "Example Corp's policy does not allow webhook tasks." */
166 +export function managedPolicyDeniedMessage(organization: string, capability: string): string {
167 + return `${organization}'s policy does not allow ${capability}.`;
168 +}
169 +
170 +const RUNTIME_MODE_LABELS: Record<RuntimeMode, string> = {
171 + "approval-required": "Supervised",
172 + "auto-accept-edits": "Auto-accept edits",
173 + auto: "Auto",
174 + "full-access": "Full access",
175 +};
176 +
177 +/** "Example Corp limits threads to Auto-accept edits." */
178 +export function managedRuntimeModeCeilingMessage(organization: string, ceiling: RuntimeMode) {
179 + return `${organization} limits threads to ${RUNTIME_MODE_LABELS[ceiling]}.`;
180 +}
181 +
182 +/** Why `mode` is unavailable on an environment with `summary`, or undefined when it is allowed. */
183 +export function managedRuntimeModeDenial(
184 + summary: ManagedPolicySummary | undefined,
185 + mode: RuntimeMode,
186 +): string | undefined {
187 + const ceiling = summary?.limits?.maxRuntimeMode;
188 + return summary !== undefined && ceiling !== undefined && isRuntimeModeAbove(mode, ceiling)
189 + ? managedRuntimeModeCeilingMessage(summary.organization, ceiling)
190 + : undefined;
191 +}
192 +
193 +/**
194 + * `mode` when the policy allows it, else the broadest of `modes` (narrowest first) that it does:
195 + * where a thread or task above the ceiling switches down to. Undefined when none is allowed.
196 + */
197 +export function clampManagedRuntimeMode(
198 + summary: ManagedPolicySummary | undefined,
199 + mode: RuntimeMode,
200 + modes: ReadonlyArray<RuntimeMode> = RuntimeMode.literals,
201 +): RuntimeMode | undefined {
202 + const ceiling = summary?.limits?.maxRuntimeMode;
203 + if (!isRuntimeModeAbove(mode, ceiling)) return mode;
204 + return modes.findLast((candidate) => !isRuntimeModeAbove(candidate, ceiling));
205 +}
206 +
207 +const CAPABILITY_LABELS = {
208 + remoteClients: "connecting from other devices",
209 + connect: "T3 Connect",
210 + webhookTasks: "webhook tasks",
211 + browserCookieImport: "importing browser cookies",
212 +} as const;
213 +
214 +/** Why a capability is unavailable on an environment with `summary`, or undefined when allowed. */
215 +export function managedCapabilityDenial(
216 + summary: ManagedPolicySummary | undefined,
217 + capability: keyof typeof CAPABILITY_LABELS,
218 +): string | undefined {
219 + const limits = summary?.limits;
220 + if (summary === undefined || limits === undefined) return undefined;
221 + const denied =
222 + capability === "remoteClients"
223 + ? limits.clients !== undefined && !limits.clients.includes("remote")
224 + : limits[capability] === false;
225 + return denied
226 + ? managedPolicyDeniedMessage(summary.organization, CAPABILITY_LABELS[capability])
227 + : undefined;
228 +}
229 +
230 +/** Whether the policy lets `driver` run; clients name it with their own provider label. */
231 +export function isManagedDriverAllowed(
232 + summary: ManagedPolicySummary | undefined,
233 + driver: ProviderDriverKind,
234 +): boolean {
235 + const allowed = summary?.limits?.providers?.allowedDrivers;
236 + return allowed === undefined || allowed.includes(driver);
237 +}
238 +
239 +/** Why updates are unavailable on an environment with `summary`, or undefined when allowed. */
240 +export function managedUpdatesDenial(summary: ManagedPolicySummary | undefined) {
241 + return summary?.limits?.updates?.mode === "off"
242 + ? managedUpdatesMessage(summary.organization)
243 + : undefined;
244 +}
packages/contracts/src/orchestratorMcp.ts
+3
@@ -690,6 +690,9 @@ export const OrchestratorMcpScheduledTask = Schema.Struct({
690 "Public URL for the sender. Absent: no T3 Connect tunnel. The user must enable T3 Connect remote access.",
691 }),
692 webhookSignature: Schema.optional(Schema.Literals(["none", "set"])),
693 + blockedByPolicy: Schema.optional(Schema.String).annotate({
694 + description: "Present when an administrator's policy stops this task from running.",
695 + }),
696 });
697 export type OrchestratorMcpScheduledTask = typeof OrchestratorMcpScheduledTask.Type;
698
packages/contracts/src/providerPolicy.ts
+11
@@ -31,6 +31,17 @@ export const RuntimeMode = Schema.Literals([
31 export type RuntimeMode = typeof RuntimeMode.Type;
32 export const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
33
34 +const RUNTIME_MODE_RANK: Record<RuntimeMode, number> = {
35 + "approval-required": 0,
36 + "auto-accept-edits": 1,
37 + auto: 2,
38 + "full-access": 3,
39 +};
40 +
41 +/** Whether `mode` grants the agent more than `ceiling`; no ceiling allows every mode. */
42 +export const isRuntimeModeAbove = (mode: RuntimeMode, ceiling: RuntimeMode | undefined): boolean =>
43 + ceiling !== undefined && RUNTIME_MODE_RANK[mode] > RUNTIME_MODE_RANK[ceiling];
44 +
45 export const ProviderInteractionMode = Schema.Literals(["default", "plan"]);
46 export type ProviderInteractionMode = typeof ProviderInteractionMode.Type;
47 export const DEFAULT_PROVIDER_INTERACTION_MODE: ProviderInteractionMode = "default";
packages/contracts/src/relayClient.ts
+1
@@ -47,6 +47,7 @@ export const RelayClientInstallFailureReasonSchema = Schema.Literals([
47 "download_failed",
48 "invalid_checksum",
49 "install_locked",
50 + "managed_by_policy",
51 "override_missing",
52 "unsupported_platform",
53 "validation_failed",
packages/contracts/src/scheduledTask.ts
+2
@@ -246,6 +246,8 @@ export const ScheduledTask = Schema.Struct({
246 lastRunError: Schema.NullOr(Schema.String),
247 runCount: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
248 webhook: Schema.optional(ScheduledTaskWebhookEndpoint),
249 + /** Why the task cannot run regardless of `enabled`, such as a managed policy refusing webhooks. */
250 + blockedByPolicy: Schema.optionalKey(Schema.String),
251 });
252 export type ScheduledTask = typeof ScheduledTask.Type;
253
packages/contracts/src/server.ts
+3
@@ -23,6 +23,7 @@ import {
23 ResolvedKeybindingsConfig,
24 } from "./keybindings.ts";
25 import { EditorId, FileManagerRevealKind, RemoteOpenTarget } from "./editor.ts";
26 +import { ManagedPolicySummary } from "./managedPolicy.ts";
27 import { ModelCapabilities, ProviderOptionDescriptor } from "./model.ts";
28 import { RuntimeMode } from "./providerPolicy.ts";
29 import { ProviderDriverKind, ProviderInstanceId } from "./providerInstance.ts";
@@ -620,6 +621,8 @@ export const ServerConfig = Schema.Struct({
621 directEndpoints: Schema.optionalKey(ForwardCompatibleArray(ServerDirectEndpoint)),
622 observability: ServerObservability,
623 settings: ServerSettings,
624 + /** Present when an administrator's policy file manages this environment. */
625 + managedPolicy: Schema.optionalKey(ManagedPolicySummary),
626 shellResumeCompletionMarker: Schema.optionalKey(Schema.Boolean),
627 /**
628 * The shell can leave idle subagent children out of snapshots (`omitIdleSubagents`), and
packages/contracts/src/settings.ts
+20
@@ -1482,9 +1482,15 @@ export const ServerSettingsOperation = Schema.Literals([
1482 "write-secret-provider",
1483 "write-file",
1484 "prepare-directory",
1485 + "write-managed-setting",
1486 + "use-disallowed-provider",
1487 ]);
1488 export type ServerSettingsOperation = typeof ServerSettingsOperation.Type;
1489
1490 +/** Why a provider the administrator's policy leaves out cannot be used. */
1491 +export const disallowedProviderMessage = (organization: string | undefined, label: string) =>
1492 + `${organization === undefined ? "Your organization" : `${organization}'s`} policy does not allow the ${label} provider.`;
1493 +
1494 export class ServerSettingsError extends Schema.TaggedError<ServerSettingsError>()(
1495 "ServerSettingsError",
1496 {
@@ -1492,10 +1498,24 @@ export class ServerSettingsError extends Schema.TaggedError<ServerSettingsError>
1498 operation: ServerSettingsOperation,
1499 providerInstanceId: Schema.optional(Schema.String),
1500 environmentVariable: Schema.optional(Schema.String),
1501 + /** For `write-managed-setting`: the locked dot path and who manages it. */
1502 + managedSetting: Schema.optional(Schema.String),
1503 + managedBy: Schema.optional(Schema.String),
1504 + /** For `use-disallowed-provider`: the provider's name as users know it. */
1505 + providerLabel: Schema.optional(Schema.String),
1506 cause: Schema.optional(Schema.Defect()),
1507 },
1508 ) {
1509 override get message(): string {
1510 + if (this.operation === "write-managed-setting") {
1511 + return `${this.managedSetting ?? "This setting"} is managed by ${this.managedBy ?? "your organization"} and cannot be changed.`;
1512 + }
1513 + if (this.operation === "use-disallowed-provider") {
1514 + return disallowedProviderMessage(
1515 + this.managedBy,
1516 + this.providerLabel ?? this.providerInstanceId ?? "this",
1517 + );
1518 + }
1519 const provider =
1520 this.providerInstanceId === undefined ? "" : ` for provider ${this.providerInstanceId}`;
1521 const variable =
packages/provider-acp/src/server/adapter.ts
+33 -3
@@ -27,9 +27,11 @@ import {
27 type ProviderRequestKind,
28 type ProviderThreadId,
29 type ProviderUserInputAnswers,
30 + type RuntimeMode,
31 type RuntimeRequestId,
32 type ThreadTokenUsageSnapshot,
33 type ThreadId,
34 + isRuntimeModeAbove,
35 type TurnTokenUsage,
36 } from "@t3tools/contracts";
37 import { AgentScope, AgentScopeThreadId } from "@t3tools/shared/AgentScope";
@@ -329,6 +331,11 @@ export interface AcpAdapterV2Flavor {
331 readonly sessionModeForPolicy?: (
332 policy: ProviderAdapter.ProviderAdapterV2RuntimePolicy,
333 ) => string | undefined;
334 + /**
335 + * The runtime mode a native session mode grants, for flavors whose modes are permission levels.
336 + * Under a policy ceiling, a mode the user picks that this does not place under it is not applied.
337 + */
338 + readonly runtimeModeForSessionMode?: (modeId: string) => RuntimeMode | undefined;
339 readonly clientFileSystem?: {
340 readonly readTextFile: (
341 request: EffectAcpSchema.ReadTextFileRequest,
@@ -6876,10 +6883,33 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
6883 };
6884 });
6885 }
6879 - const optionSelections = (modelSelection.options ?? []).map((selection) =>
6880 - selection.value === ACP_EMPTY_OPTION_VALUE ? { ...selection, value: "" } : selection,
6881 - );
6886 const configOptions = yield* runtime.getConfigOptions;
6887 + // Under a policy ceiling, a mode the user picks applies only when the flavor can place
6888 + // it under the ceiling; an unknown mode could be the agent's own skip-approval mode.
6889 + const ceiling = runtimePolicy.maxRuntimeMode;
6890 + const isModeChoice = (id: string) =>
6891 + id === ACP_SESSION_MODE_OPTION_ID ||
6892 + configOptions.some(
6893 + (option) =>
6894 + option.id === id &&
6895 + (option.category === "mode" || option.category === "collaboration_mode"),
6896 + );
6897 + const withinCeiling = (selection: { readonly id: string; readonly value: unknown }) => {
6898 + if (ceiling === undefined || ceiling === "full-access" || !isModeChoice(selection.id)) {
6899 + return true;
6900 + }
6901 + const granted =
6902 + typeof selection.value === "string"
6903 + ? flavor.runtimeModeForSessionMode?.(selection.value)
6904 + : undefined;
6905 + return granted !== undefined && !isRuntimeModeAbove(granted, ceiling);
6906 + };
6907 + const optionSelections = (modelSelection.options ?? []).flatMap((selection) => {
6908 + if (!withinCeiling(selection)) return [];
6909 + return [
6910 + selection.value === ACP_EMPTY_OPTION_VALUE ? { ...selection, value: "" } : selection,
6911 + ];
6912 + });
6913 const availableConfigIds = new Set(configOptions.map((option) => option.id));
6914 const hasNativeConfigWithSyntheticModeId = availableConfigIds.has(
6915 ACP_SESSION_MODE_OPTION_ID,
packages/provider-core/src/server/ProviderAdapter.ts
+5
@@ -51,6 +51,11 @@ export const ProviderAdapterV2RuntimePolicy = Schema.Struct({
51 cwd: Schema.NullOr(Schema.String),
52 approvalPolicy: Schema.optional(Schema.Unknown),
53 sandboxPolicy: Schema.optional(Schema.Unknown),
54 + /**
55 + * The administrator's ceiling, when a managed policy sets one. `runtimeMode` is already under
56 + * it; adapters use it to refuse native mode choices a user makes beside T3 Code's own.
57 + */
58 + maxRuntimeMode: Schema.optional(RuntimeMode),
59 });
60 export type ProviderAdapterV2RuntimePolicy = typeof ProviderAdapterV2RuntimePolicy.Type;
61
packages/provider-core/src/server/instanceEnvironment.test.ts
+27
@@ -81,4 +81,31 @@ describe("mergeProviderInstanceEnvironment", () => {
81 });
82 }),
83 );
84 +
85 + it.effect("replaces every inherited spelling of a name on Windows, and only there", () =>
86 + Effect.gen(function* () {
87 + const merge = (platform: NodeJS.Platform) =>
88 + mergeProviderInstanceEnvironment(
89 + [{ name: "Https_Proxy", value: "http://gateway", sensitive: false }],
90 + { HTTPS_PROXY: "http://mine", PATH: "/bin" },
91 + ).pipe(Effect.provideService(HostProcess.Platform, platform));
92 + // A home variable in another spelling is still expanded.
93 + expect(
94 + yield* mergeProviderInstanceEnvironment(
95 + [{ name: "Codex_Home", value: "~/corp", sensitive: false }],
96 + {},
97 + ).pipe(
98 + Effect.provideService(HostProcess.Platform, "win32"),
99 + Effect.provideService(HostProcess.HomeDirectory, "/home/ada"),
100 + ),
101 + ).toEqual({ CODEX_HOME: "/home/ada/corp" });
102 + // Upper case sorts first, so it also wins where a spawn merges the parent environment back.
103 + expect(yield* merge("win32")).toEqual({ HTTPS_PROXY: "http://gateway", PATH: "/bin" });
104 + expect(yield* merge("linux")).toEqual({
105 + HTTPS_PROXY: "http://mine",
106 + Https_Proxy: "http://gateway",
107 + PATH: "/bin",
108 + });
109 + }),
110 + );
111 });
packages/provider-core/src/server/instanceEnvironment.ts
+12 -2
@@ -13,12 +13,22 @@ export const mergeProviderInstanceEnvironment = Effect.fn(function* (
13 }
14
15 const home = yield* HostProcess.HomeDirectory;
16 + const windows = (yield* HostProcess.Platform) === "win32";
17 const next: NodeJS.ProcessEnv = { ...baseEnv };
18 for (const variable of environment) {
19 // An unresolved secret reference carries no value; the registry resolves it for the provider.
20 if (typeof variable.value !== "string") continue;
20 - next[variable.name] =
21 - variable.name === "CODEX_HOME" || variable.name === "CLAUDE_CONFIG_DIR"
21 + // Windows reads names without regard to case, and a child gets the first spelling in sort
22 + // order. Upper case sorts first, so the configured value wins even where a spawn merges the
23 + // parent environment back in.
24 + const name = windows ? variable.name.toUpperCase() : variable.name;
25 + if (windows) {
26 + for (const inherited of Object.keys(next)) {
27 + if (inherited.toUpperCase() === name) delete next[inherited];
28 + }
29 + }
30 + next[name] =
31 + name === "CODEX_HOME" || name === "CLAUDE_CONFIG_DIR"
32 ? expandHomePath(variable.value, home)
33 : variable.value;
34 }
packages/shared/package.json
+5
@@ -335,6 +335,10 @@
335 "types": "./src/AgentScope.ts",
336 "import": "./src/AgentScope.ts"
337 },
338 + "./managedPolicyFile": {
339 + "types": "./src/managedPolicyFile.ts",
340 + "import": "./src/managedPolicyFile.ts"
341 + },
342 "./HostProcess": {
343 "types": "./src/HostProcess.ts",
344 "import": "./src/HostProcess.ts"
@@ -529,6 +533,7 @@
533 "@noble/hashes": "catalog:",
534 "@t3tools/contracts": "workspace:*",
535 "effect": "catalog:",
536 + "ffi-rs": "1.3.2",
537 "jose": "catalog:",
538 "mdast-util-directive": "catalog:",
539 "mdast-util-to-hast": "^13.2.1",
packages/shared/src/managedPolicyFile.test.ts new
+190
@@ -0,0 +1,190 @@
1 +import { assert, describe, it } from "@effect/vitest";
2 +import * as Effect from "effect/Effect";
3 +import * as FileSystem from "effect/FileSystem";
4 +import * as Layer from "effect/Layer";
5 +import * as Sink from "effect/Sink";
6 +import * as Stream from "effect/Stream";
7 +import { ChildProcessSpawner } from "effect/process";
8 +
9 +import * as HostProcess from "./HostProcess.ts";
10 +
11 +import {
12 + MACOS_MANAGED_PREFERENCES_PATH,
13 + managedPolicyPath,
14 + readManagedPolicy,
15 + WINDOWS_POLICY_KEY,
16 + layerWindowsRegistry,
17 + WindowsRegistry,
18 + WindowsRegistryError,
19 +} from "./managedPolicyFile.ts";
20 +
21 +const policy = JSON.stringify({ schemaVersion: 1, organization: "Example Corp" });
22 +
23 +/** What a command prints and exits with. */
24 +type Result = { readonly stdout: string; readonly exitCode: number };
25 +
26 +/** The registry's `Policy` value: its text, absent, or the Win32 error reading it fails with. */
27 +type RegistryAnswer = string | undefined | { readonly code?: number };
28 +
29 +/** Files that exist, what a command prints and exits with by command name, and the registry. */
30 +const machine = (
31 + files: Readonly<Record<string, string>>,
32 + commands: Readonly<Record<string, Result>>,
33 + registry: RegistryAnswer,
34 +) =>
35 + Layer.mergeAll(
36 + Layer.succeed(
37 + WindowsRegistry,
38 + WindowsRegistry.of({
39 + readMachineString: () =>
40 + typeof registry === "object"
41 + ? Effect.fail(new WindowsRegistryError(registry))
42 + : Effect.succeed(registry),
43 + }),
44 + ),
45 + FileSystem.layerNoop({
46 + exists: (path) => Effect.succeed(path in files),
47 + readFileString: (path) => Effect.succeed(files[path] ?? ""),
48 + }),
49 + Layer.succeed(
50 + ChildProcessSpawner.ChildProcessSpawner,
51 + ChildProcessSpawner.make((command) => {
52 + const { command: name } = command as unknown as { readonly command: string };
53 + const result = commands[name] ?? { stdout: "", exitCode: 127 };
54 + return Effect.succeed(
55 + ChildProcessSpawner.makeHandle({
56 + pid: ChildProcessSpawner.ProcessId(1),
57 + exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(result.exitCode)),
58 + isRunning: Effect.succeed(false),
59 + kill: () => Effect.void,
60 + unref: Effect.succeed(Effect.void),
61 + stdin: Sink.drain,
62 + stdout: Stream.make(new TextEncoder().encode(result.stdout)),
63 + stderr: Stream.empty,
64 + all: Stream.empty,
65 + getInputFd: () => Sink.drain,
66 + getOutputFd: () => Stream.empty,
67 + }),
68 + );
69 + }),
70 + ),
71 + );
72 +
73 +const read = (
74 + platform: NodeJS.Platform,
75 + files: Readonly<Record<string, string>>,
76 + commands: Parameters<typeof machine>[1] = {},
77 + registry: RegistryAnswer = undefined,
78 +) =>
79 + readManagedPolicy(platform).pipe(
80 + Effect.map((found) => found?.source),
81 + Effect.catchTags({
82 + ManagedPolicyFileError: (error) => Effect.succeed(`error: ${error.reason}`),
83 + }),
84 + Effect.provide(machine(files, commands, registry)),
85 + );
86 +
87 +describe("readManagedPolicy", () => {
88 + it.effect("reads a macOS configuration profile, and refuses one beside a policy file", () =>
89 + Effect.gen(function* () {
90 + const plutil = { "/usr/bin/plutil": { stdout: policy, exitCode: 0 } };
91 + const profile = { [MACOS_MANAGED_PREFERENCES_PATH]: "<binary plist>" };
92 + const file = { [managedPolicyPath("darwin")]: policy };
93 +
94 + assert.equal(yield* read("darwin", profile, plutil), MACOS_MANAGED_PREFERENCES_PATH);
95 + const plist = (contents: object) => ({
96 + "/usr/bin/plutil": { stdout: JSON.stringify(contents), exitCode: 0 },
97 + });
98 + const settings = JSON.parse(policy);
99 + // What macOS 27 writes for a manually installed profile.
100 + assert.equal(
101 + yield* read(
102 + "darwin",
103 + profile,
104 + plist({ ...settings, PayloadUUID: "e8c7f49b", _manualProfile: true }),
105 + ),
106 + MACOS_MANAGED_PREFERENCES_PATH,
107 + );
108 + assert.equal(
109 + yield* read("darwin", profile, plist({ Forced: [{ mcx_preference_settings: settings }] })),
110 + MACOS_MANAGED_PREFERENCES_PATH,
111 + );
112 + // Keys beside the wrapper, or a second entry, are refused rather than dropped or merged.
113 + for (const ambiguous of [
114 + { Forced: [{ mcx_preference_settings: settings }], limits: { telemetry: false } },
115 + { Forced: [{ mcx_preference_settings: settings }, { mcx_preference_settings: settings }] },
116 + ]) {
117 + assert.include(
118 + yield* read("darwin", profile, plist(ambiguous)),
119 + "does not match the policy schema",
120 + );
121 + }
122 + assert.equal(yield* read("darwin", file), managedPolicyPath("darwin"));
123 + const typo = JSON.stringify({ ...settings, limits: { maxRuntimeMod: "auto" } });
124 + assert.include(
125 + yield* read("darwin", { [managedPolicyPath("darwin")]: typo }),
126 + '["limits"]["maxRuntimeMod"]',
127 + );
128 + assert.isUndefined(yield* read("darwin", {}));
129 + assert.include(
130 + yield* read("darwin", { ...profile, ...file }, plutil),
131 + "deploy the policy one way",
132 + );
133 + // A profile plutil cannot convert fails closed rather than reading as no policy.
134 + assert.include(
135 + yield* read("darwin", profile, { "/usr/bin/plutil": { stdout: "", exitCode: 1 } }),
136 + "cannot be read",
137 + );
138 + }),
139 + );
140 +
141 + it.effect(
142 + "reads the Windows Policies registry value, and treats only an absent one as none",
143 + () =>
144 + Effect.gen(function* () {
145 + const file = { [managedPolicyPath("win32")]: policy };
146 + const win32 = (files: Readonly<Record<string, string>>, registry: RegistryAnswer) =>
147 + read("win32", files, {}, registry);
148 +
149 + assert.equal(yield* win32({}, policy), WINDOWS_POLICY_KEY);
150 + assert.isUndefined(yield* win32({}, undefined));
151 + assert.equal(yield* win32(file, undefined), managedPolicyPath("win32"));
152 + assert.include(yield* win32(file, policy), "deploy the policy one way");
153 + // A read that fails, here access denied, is not read as no policy, file or not.
154 + for (const files of [{}, file]) {
155 + assert.include(
156 + yield* win32(files, { code: 5 }),
157 + "the registry cannot be read (Windows error 5)",
158 + );
159 + }
160 + assert.include(yield* win32({}, {}), "cannot load its registry reader; reinstall T3 Code");
161 + assert.include(
162 + yield* win32({}, { code: 1630 }),
163 + "its Policy value is not a string (REG_SZ)",
164 + );
165 + assert.include(yield* win32({}, "{ not json"), "does not match the policy schema");
166 + }),
167 + );
168 +
169 + it.effect.runIf(HostProcess.Platform.defaultValue() === "win32")(
170 + "reads REG_SZ values through the Win32 API, and refuses other types",
171 + () =>
172 + Effect.gen(function* () {
173 + const registry = yield* WindowsRegistry;
174 + const version = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion";
175 + assert.match((yield* registry.readMachineString(version, "ProductName")) ?? "", /Windows/);
176 + assert.isUndefined(yield* registry.readMachineString(version, "T3CodeNoSuchValue"));
177 + assert.isUndefined(
178 + yield* registry.readMachineString("SOFTWARE\\T3CodeNoSuchKey", "Policy"),
179 + );
180 + // REG_DWORD, and REG_EXPAND_SZ, which would otherwise expand the user's variables.
181 + for (const [key, value] of [
182 + [version, "CurrentMajorVersionNumber"],
183 + ["SOFTWARE\\Microsoft\\Windows\\CurrentVersion", "ProgramFilesPath"],
184 + ] as const) {
185 + const error = yield* registry.readMachineString(key, value).pipe(Effect.flip);
186 + assert.equal(error.code, 1630);
187 + }
188 + }).pipe(Effect.provide(layerWindowsRegistry(() => import("ffi-rs")))),
189 + );
190 +});
packages/shared/src/managedPolicyFile.ts new
+330
@@ -0,0 +1,330 @@
1 +import { ManagedPolicyDocument } from "@t3tools/contracts";
2 +import * as Cause from "effect/Cause";
3 +import * as Context from "effect/Context";
4 +import * as Duration from "effect/Duration";
5 +import * as Effect from "effect/Effect";
6 +import * as Exit from "effect/Exit";
7 +import * as FileSystem from "effect/FileSystem";
8 +import * as Layer from "effect/Layer";
9 +import * as Schema from "effect/Schema";
10 +import * as Stream from "effect/Stream";
11 +import { ChildProcess, ChildProcessSpawner } from "effect/process";
12 +
13 +import * as HostProcess from "./HostProcess.ts";
14 +
15 +export class ManagedPolicyFileError extends Schema.TaggedError<ManagedPolicyFileError>()(
16 + "ManagedPolicyFileError",
17 + {
18 + path: Schema.String,
19 + reason: Schema.String,
20 + cause: Schema.optional(Schema.Defect()),
21 + },
22 +) {
23 + override get message(): string {
24 + return `T3 Code cannot use the managed policy at ${this.path}: ${this.reason}. It will not start until an administrator fixes this.`;
25 + }
26 +}
27 +
28 +/** The system path an administrator deploys the policy to on `platform`. */
29 +export function managedPolicyPath(platform: NodeJS.Platform): string {
30 + switch (platform) {
31 + case "darwin":
32 + return "/Library/Application Support/T3Code/policy.json";
33 + case "win32":
34 + // Not ProgramData, where a user can create the folder first and own it; and not
35 + // %ProgramFiles%, which a user can point somewhere they write.
36 + return "C:\\Program Files\\T3Code\\policy.json";
37 + default:
38 + return "/etc/t3code/policy.json";
39 + }
40 +}
41 +
42 +// Unknown keys may be restrictions from a newer release; refusing them keeps a file this
43 +// build cannot fully enforce from looking enforced.
44 +const decodeDocumentJsonExit = Schema.decodeUnknownExit(
45 + Schema.fromJsonString(ManagedPolicyDocument),
46 + { onExcessProperty: "error" },
47 +);
48 +const decodeDocumentExit = Schema.decodeUnknownExit(ManagedPolicyDocument, {
49 + onExcessProperty: "error",
50 +});
51 +
52 +/** Decode a policy from JSON text, or from a value a profile already parsed. */
53 +const decodeDocument = (path: string, raw: unknown) => {
54 + const decoded = typeof raw === "string" ? decodeDocumentJsonExit(raw) : decodeDocumentExit(raw);
55 + if (Exit.isSuccess(decoded)) return Effect.succeed(decoded.value);
56 + const error = Cause.squash(decoded.cause);
57 + // The schema message names the offending key, e.g. `Expected no excess property at ["limits"]`.
58 + const detail = Schema.isSchemaError(error) ? ` (${error.message.replace(/\s*\n\s*/g, " ")})` : "";
59 + return Effect.fail(
60 + new ManagedPolicyFileError({
61 + path,
62 + reason: `it is not valid JSON or does not match the policy schema${detail}`,
63 + cause: decoded.cause,
64 + }),
65 + );
66 +};
67 +
68 +/** Read the policy document at `path`; a missing file means no policy. */
69 +export const readManagedPolicyFile = Effect.fn("readManagedPolicyFile")(function* (path: string) {
70 + const fs = yield* FileSystem.FileSystem;
71 + const exists = yield* fs
72 + .exists(path)
73 + .pipe(
74 + Effect.mapError(
75 + (cause) =>
76 + new ManagedPolicyFileError({ path, reason: "the file cannot be checked", cause }),
77 + ),
78 + );
79 + if (!exists) return undefined;
80 + const raw = yield* fs
81 + .readFileString(path)
82 + .pipe(
83 + Effect.mapError(
84 + (cause) => new ManagedPolicyFileError({ path, reason: "the file cannot be read", cause }),
85 + ),
86 + );
87 + return yield* decodeDocument(path, raw);
88 +});
89 +
90 +/** Where a configuration profile's managed preferences land on macOS. */
91 +export const MACOS_MANAGED_PREFERENCES_PATH =
92 + "/Library/Managed Preferences/com.t3tools.t3code.plist";
93 +const WINDOWS_POLICY_SUBKEY = "SOFTWARE\\Policies\\T3Tools\\T3Code";
94 +/** The registry key Group Policy and Intune write to on Windows; `Policy` holds the JSON. */
95 +export const WINDOWS_POLICY_KEY = `HKLM\\${WINDOWS_POLICY_SUBKEY}`;
96 +// An absolute path: an earlier PATH entry could otherwise answer that there is no policy.
97 +const PLUTIL = "/usr/bin/plutil";
98 +
99 +export class WindowsRegistryError extends Schema.TaggedError<WindowsRegistryError>()(
100 + "WindowsRegistryError",
101 + {
102 + /** The Win32 error, such as 5 for access denied; absent when the registry API cannot load. */
103 + code: Schema.optional(Schema.Number),
104 + cause: Schema.optional(Schema.Defect()),
105 + },
106 +) {
107 + override get message(): string {
108 + return this.code === undefined ? "the registry API cannot load" : `Windows error ${this.code}`;
109 + }
110 +}
111 +
112 +/**
113 + * Reads the registry through the Win32 API in this process. A missing value and a failed read
114 + * come back apart, and blocked registry tools such as reg.exe do not matter.
115 + */
116 +export class WindowsRegistry extends Context.Service<
117 + WindowsRegistry,
118 + {
119 + /** The REG_SZ `value` of HKLM\\`subkey` in the 64-bit view; undefined when either is absent. */
120 + readonly readMachineString: (
121 + subkey: string,
122 + value: string,
123 + ) => Effect.Effect<string | undefined, WindowsRegistryError>;
124 + }
125 +>()("@t3tools/shared/managedPolicyFile/WindowsRegistry") {}
126 +
127 +// (HKEY)(LONG)0x80000002, sign-extended to 64 bits.
128 +const HKEY_LOCAL_MACHINE = -0x7ffffffen;
129 +const RRF_RT_REG_SZ = 0x2;
130 +const RRF_SUBKEY_WOW6464KEY = 0x10000;
131 +// Without it a REG_EXPAND_SZ value passes as REG_SZ, with the user's variables filled in.
132 +const RRF_NOEXPAND = 0x10000000;
133 +const ERROR_FILE_NOT_FOUND = 2;
134 +const ERROR_MORE_DATA = 234;
135 +const ERROR_UNSUPPORTED_TYPE = 1630;
136 +
137 +/**
138 + * Each app passes how it loads ffi-rs: a server single-executable resolves packages on disk only
139 + * through `require`, and the desktop's CommonJS bundle loads them with `import()`.
140 + */
141 +export const layerWindowsRegistry = (loadFfi: () => Promise<typeof import("ffi-rs")>) =>
142 + Layer.effect(
143 + WindowsRegistry,
144 + Effect.gen(function* () {
145 + const architecture = yield* HostProcess.Architecture;
146 + const loadGetValue = yield* Effect.cached(
147 + Effect.tryPromise({
148 + try: async () => {
149 + // HKEY_LOCAL_MACHINE and the pointer arguments below are 64-bit.
150 + if (architecture !== "x64" && architecture !== "arm64") {
151 + throw new Error(`no registry access on ${architecture}`);
152 + }
153 + const { DataType, load, open } = await loadFfi();
154 + open({ library: "t3-advapi32", path: "advapi32.dll" });
155 + return (subkey: string, value: string, data: Buffer, size: Buffer): number =>
156 + load({
157 + library: "t3-advapi32",
158 + funcName: "RegGetValueW",
159 + retType: DataType.I32,
160 + paramsType: [
161 + DataType.BigInt,
162 + DataType.WString,
163 + DataType.WString,
164 + DataType.U32,
165 + DataType.BigInt,
166 + DataType.U8Array,
167 + DataType.U8Array,
168 + ],
169 + paramsValue: [
170 + HKEY_LOCAL_MACHINE,
171 + subkey,
172 + value,
173 + RRF_RT_REG_SZ | RRF_SUBKEY_WOW6464KEY | RRF_NOEXPAND,
174 + 0n,
175 + data,
176 + size,
177 + ],
178 + });
179 + },
180 + catch: (cause) => new WindowsRegistryError({ cause }),
181 + }),
182 + );
183 + return WindowsRegistry.of({
184 + readMachineString: Effect.fn("WindowsRegistry.readMachineString")(
185 + function* (subkey, value) {
186 + const getValue = yield* loadGetValue;
187 + const attempt = (bytes: number) =>
188 + Effect.try({
189 + try: () => {
190 + const data = Buffer.alloc(bytes);
191 + const size = Buffer.alloc(4);
192 + size.writeUInt32LE(bytes);
193 + const code = getValue(subkey, value, data, size);
194 + return { code, data, bytes: size.readUInt32LE() };
195 + },
196 + catch: (cause) => new WindowsRegistryError({ cause }),
197 + });
198 + let result = yield* attempt(64 * 1024);
199 + // The value grew past the buffer; the API reported the size it needs.
200 + if (result.code === ERROR_MORE_DATA) result = yield* attempt(result.bytes);
201 + if (result.code === ERROR_FILE_NOT_FOUND) return undefined;
202 + if (result.code !== 0) return yield* new WindowsRegistryError({ code: result.code });
203 + // The size counts the terminating null RegGetValueW adds.
204 + return result.data.subarray(0, result.bytes).toString("utf16le").replace(/\0+$/, "");
205 + },
206 + ),
207 + });
208 + }),
209 + );
210 +
211 +// A hung query must not hang startup; a timeout reads as a failed query.
212 +const run = Effect.fnUntraced(
213 + function* (command: string, args: ReadonlyArray<string>) {
214 + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
215 + const handle = yield* spawner.spawn(
216 + ChildProcess.make(command, args, { stdin: "ignore", stderr: "ignore" }),
217 + );
218 + const [stdout, exitCode] = yield* Effect.all(
219 + [handle.stdout.pipe(Stream.decodeText(), Stream.mkString), handle.exitCode],
220 + { concurrency: 2 },
221 + );
222 + return { stdout, exitCode: Number(exitCode) };
223 + },
224 + Effect.scoped,
225 + Effect.timeout(Duration.seconds(10)),
226 +);
227 +
228 +const decodeJsonExit = Schema.decodeUnknownExit(Schema.fromJsonString(Schema.Unknown));
229 +// Strict: keys beside the wrapper, or more than one entry, decode as a plain document and fail.
230 +const decodeForcedExit = Schema.decodeUnknownExit(
231 + Schema.Struct({
232 + Forced: Schema.Tuple([Schema.Struct({ mcx_preference_settings: Schema.Unknown })]),
233 + }),
234 + { onExcessProperty: "error" },
235 +);
236 +
237 +// macOS writes `PayloadUUID` and `_manualProfile` beside the profile's own keys; no policy key
238 +// starts with `Payload` or `_`, so dropping them cannot hide a restriction.
239 +const withoutProfileKeys = (value: unknown) =>
240 + value === null || typeof value !== "object" || Array.isArray(value)
241 + ? value
242 + : Object.fromEntries(
243 + Object.entries(value).filter(([key]) => !key.startsWith("Payload") && !key.startsWith("_")),
244 + );
245 +
246 +/**
247 + * Installed managed preferences hold the profile's keys directly, but MCX-style profiles keep
248 + * them under `Forced[0].mcx_preference_settings`; read either rather than refuse a valid profile.
249 + */
250 +function unwrapForced(json: string): unknown {
251 + const parsed = decodeJsonExit(json);
252 + if (Exit.isFailure(parsed)) return json;
253 + const preferences = withoutProfileKeys(parsed.value);
254 + const forced = decodeForcedExit(preferences);
255 + return Exit.isSuccess(forced)
256 + ? withoutProfileKeys(forced.value.Forced[0].mcx_preference_settings)
257 + : preferences;
258 +}
259 +
260 +/** Read the policy a configuration profile or Group Policy set; absent means no such policy. */
261 +const readPlatformPolicy = Effect.fnUntraced(function* (platform: NodeJS.Platform) {
262 + if (platform === "darwin") {
263 + const path = MACOS_MANAGED_PREFERENCES_PATH;
264 + const exists = yield* (yield* FileSystem.FileSystem)
265 + .exists(path)
266 + .pipe(
267 + Effect.mapError(
268 + (cause) =>
269 + new ManagedPolicyFileError({ path, reason: "the profile cannot be checked", cause }),
270 + ),
271 + );
272 + if (!exists) return undefined;
273 + const converted = yield* run(PLUTIL, ["-convert", "json", "-o", "-", path]).pipe(
274 + Effect.mapError(
275 + (cause) =>
276 + new ManagedPolicyFileError({ path, reason: "the profile cannot be read", cause }),
277 + ),
278 + );
279 + if (converted.exitCode !== 0) {
280 + return yield* new ManagedPolicyFileError({ path, reason: "the profile cannot be read" });
281 + }
282 + return { source: path, document: yield* decodeDocument(path, unwrapForced(converted.stdout)) };
283 + }
284 + if (platform === "win32") {
285 + const path = WINDOWS_POLICY_KEY;
286 + const raw = yield* (yield* WindowsRegistry)
287 + .readMachineString(WINDOWS_POLICY_SUBKEY, "Policy")
288 + .pipe(
289 + Effect.mapError(
290 + (cause) =>
291 + new ManagedPolicyFileError({
292 + path,
293 + reason:
294 + cause.code === ERROR_UNSUPPORTED_TYPE
295 + ? "its Policy value is not a string (REG_SZ)"
296 + : cause.code === undefined
297 + ? "this T3 Code install cannot load its registry reader; reinstall T3 Code"
298 + : `the registry cannot be read (${cause.message})`,
299 + cause,
300 + }),
301 + ),
302 + );
303 + return raw === undefined
304 + ? undefined
305 + : { source: path, document: yield* decodeDocument(path, raw) };
306 + }
307 + return undefined;
308 +});
309 +
310 +/**
311 + * Read the machine's policy from wherever an administrator put it: a configuration profile on
312 + * macOS, the Policies registry key on Windows, or the policy file. Two sources are refused rather
313 + * than merged, so what applies is never a mix nobody wrote.
314 + */
315 +export const readManagedPolicy = Effect.fn("readManagedPolicy")(function* (
316 + platform: NodeJS.Platform,
317 +) {
318 + const filePath = managedPolicyPath(platform);
319 + const [platformPolicy, file] = yield* Effect.all([
320 + readPlatformPolicy(platform),
321 + readManagedPolicyFile(filePath),
322 + ]);
323 + if (platformPolicy !== undefined && file !== undefined) {
324 + return yield* new ManagedPolicyFileError({
325 + path: platformPolicy.source,
326 + reason: `a policy file at ${filePath} also exists; deploy the policy one way`,
327 + });
328 + }
329 + return platformPolicy ?? (file === undefined ? undefined : { source: filePath, document: file });
330 +});
packages/shared/src/relayClient.ts
+1
@@ -60,6 +60,7 @@ export class RelayClientInstallError extends Data.TaggedError("RelayClientInstal
60 | "download_failed"
61 | "invalid_checksum"
62 | "install_locked"
63 + | "managed_by_policy"
64 | "override_missing"
65 | "unsupported_platform"
66 | "validation_failed"
packages/tailscale/src/tailscale.test.ts
+96
@@ -10,6 +10,7 @@ import * as HostProcess from "@t3tools/shared/HostProcess";
10 import {
11 ensureTailscaleServe,
12 parseTailscaleExitNode,
13 + parseTailscaleServeRoutesTo,
14 parseTailscaleSshEnabled,
15 parseTailscaleStatus,
16 readTailscaleSshEnabled,
@@ -94,6 +95,101 @@ function layerMockSpawner(
95 }
96
97 describe("tailscale", () => {
98 + it("finds the Serve routes that forward to the bound address, and only those", () => {
99 + const status = JSON.stringify({
100 + TCP: {
101 + "443": { HTTPS: true },
102 + "7000": { TCPForward: "127.0.0.1:3773" },
103 + "7001": { TCPForward: "127.0.0.2:3773" },
104 + "80": { TCPForward: "unix:/run/app.sock" },
105 + },
106 + Web: {
107 + "box.tailnet.ts.net:443": {
108 + Handlers: {
109 + "/t3": { Proxy: "http://127.0.0.1:3773" },
110 + "/dashboard": { Proxy: "http://127.0.0.1:9000" },
111 + },
112 + },
113 + "box.tailnet.ts.net:8443": { Handlers: { "/": { Proxy: "http://127.0.0.1:5173" } } },
114 + "box.tailnet.ts.net:10000": {
115 + Handlers: {
116 + // Another service on another loopback address, and one on the other family.
117 + "/a": { Proxy: "http://127.0.0.2:3773" },
118 + "/b": { Proxy: "http://[::1]:3773" },
119 + "/c": { Proxy: "http://192.168.1.5:3773" },
120 + "/d": { Proxy: "http://0.0.0.0:3773" },
121 + "/e": { Proxy: "http://[::ffff:127.0.0.1]:3773" },
122 + "/f": { Proxy: "http://localhost:3773" },
123 + // Shorthand Tailscale expands when it proxies.
124 + "/g": { Proxy: "3773" },
125 + "/h": { Proxy: "localhost:3773" },
126 + "/i": { Proxy: "http://[::]:3773" },
127 + // A name can resolve to any address, the bound one included.
128 + "/j": { Proxy: "http://ip6-localhost:3773" },
129 + // Go resolves these as names; a WHATWG URL rejects the first and rewrites the second.
130 + "/k": { Proxy: "http://box.1:3773" },
131 + "/l": { Proxy: "http://127.1:3773" },
132 + "/m": { Proxy: "unix:/run/app.sock" },
133 + // Credentials before the host, and IPv6 written out in full, still dial here.
134 + "/n": { Proxy: "http://user:pass@127.0.0.1:3773" },
135 + "/o": { Proxy: "http://[0:0:0:0:0:ffff:7f00:1]:3773" },
136 + "/p": { Proxy: "http://127.0.0.1:03773" },
137 + },
138 + },
139 + },
140 + Services: {
141 + "svc:t3": {
142 + Web: {
143 + "t3.tailnet.ts.net:443": { Handlers: { "/": { Proxy: "http://127.0.0.1:3773" } } },
144 + },
145 + },
146 + },
147 + Foreground: {
148 + session1: { TCP: { "9000": { TCPForward: "localhost:3773" } } },
149 + },
150 + });
151 + assert.deepEqual(parseTailscaleServeRoutesTo(status, { host: "127.0.0.1", port: 3773 }), [
152 + { servePort: 7000 },
153 + { servePort: 443, mount: "/t3", host: "box.tailnet.ts.net" },
154 + // `localhost` and `[::]` can dial either loopback, so they might be another service's.
155 + ...(
156 + [
157 + ["/d", undefined],
158 + ["/e", undefined],
159 + ["/f", "localhost"],
160 + ["/g", undefined],
161 + ["/h", "localhost"],
162 + ["/i", "[::]"],
163 + ["/j", "ip6-localhost"],
164 + ["/k", "box.1"],
165 + ["/l", "127.1"],
166 + ["/n", undefined],
167 + ["/o", undefined],
168 + ["/p", undefined],
169 + ] as const
170 + ).map(([mount, ambiguous]) => ({
171 + servePort: 10000,
172 + mount,
173 + host: "box.tailnet.ts.net",
174 + ...(ambiguous === undefined ? {} : { ambiguous }),
175 + })),
176 + { servePort: 443, mount: "/", host: "t3.tailnet.ts.net", owner: "svc:t3" },
177 + { servePort: 9000, ambiguous: "localhost", owner: "foreground" },
178 + ]);
179 + assert.deepEqual(
180 + parseTailscaleServeRoutesTo(
181 + JSON.stringify({
182 + Web: { "box:443": { Handlers: { "/": { Proxy: "http://127.0.0.1" } } } },
183 + }),
184 + { host: "127.0.0.1", port: 80 },
185 + ),
186 + [{ servePort: 443, mount: "/", host: "box" }],
187 + );
188 + assert.deepEqual(parseTailscaleServeRoutesTo("{}", { host: "127.0.0.1", port: 3773 }), []);
189 + assert.deepEqual(parseTailscaleServeRoutesTo("null", { host: "127.0.0.1", port: 3773 }), []);
190 + assert.isUndefined(parseTailscaleServeRoutesTo("not json", { host: "127.0.0.1", port: 3773 }));
191 + });
192 +
193 it.effect("parses status facts", () =>
194 Effect.gen(function* () {
195 const status = yield* parseTailscaleStatus(tailscaleStatusJson);
packages/tailscale/src/tailscale.ts
+201 -3
@@ -1,4 +1,5 @@
1 import * as HostProcess from "@t3tools/shared/HostProcess";
2 +import { normalizeHostname } from "@t3tools/shared/hostClassification";
3 import * as Duration from "effect/Duration";
4 import * as Effect from "effect/Effect";
5 import * as Option from "effect/Option";
@@ -42,6 +43,7 @@ const TailscaleCommandContext = {
43 export const TailscaleStderrDiagnostic = Schema.Literals([
44 "no-existing-handler",
45 "not-logged-in",
46 + "not-running",
47 "permission-denied",
48 "unknown",
49 ]);
@@ -52,6 +54,12 @@ const STDERR_DIAGNOSTIC_PATTERNS: ReadonlyArray<
54 > = [
55 [/handler does not exist/i, "no-existing-handler"],
56 [/not logged in|logged out|needs? login/i, "not-logged-in"],
57 + // Only answers that confirm no daemon; a dial can also fail for want of permission. Windows
58 + // reports a missing service as its pipe not being found, without the usual prefix.
59 + [
60 + /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,
61 + "not-running",
62 + ],
63 [/permission denied|access denied|must be root|operation not permitted/i, "permission-denied"],
64 ];
65
@@ -222,7 +230,7 @@ export const parseTailscaleStatus = (
230 );
231
232 const readTailscaleOutput = Effect.fn("tailscale.readTailscaleOutput")(function* (
225 - subcommand: "status" | "debug",
233 + subcommand: "status" | "serve" | "debug",
234 args: readonly string[],
235 ) {
236 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
@@ -438,18 +446,208 @@ export const ensureTailscaleServe = (input: {
446 return runTailscaleCommand(args, TAILSCALE_SERVE_TIMEOUT);
447 };
448
449 +/** A Serve route: a web handler at `mount` on `servePort`, or a TCP forward without one. */
450 +export interface TailscaleServeRoute {
451 + readonly servePort: number;
452 + readonly mount?: string;
453 + /** The machine name a web route serves under. */
454 + readonly host?: string;
455 + /** A target, such as a name, that may dial this server or another service on the same port. */
456 + readonly ambiguous?: string;
457 + /** The Tailscale Service it belongs to, or `foreground` for a `tailscale serve` still running. */
458 + readonly owner?: string;
459 +}
460 +
461 +/**
462 + * The `tailscale` arguments that turn `route` off; a foreground route has none, since it ends with
463 + * its command. A web route names its path: without one the CLI removes every handler on the port,
464 + * and answers its own confirmation prompt with yes when nobody is there to answer.
465 + */
466 +export const tailscaleServeOffArgs = (
467 + route: TailscaleServeRoute,
468 +): ReadonlyArray<string> | undefined =>
469 + route.owner === "foreground"
470 + ? undefined
471 + : [
472 + "serve",
473 + ...(route.owner === undefined ? [] : [`--service=${route.owner}`]),
474 + ...(route.mount === undefined
475 + ? [`--tcp=${route.servePort}`]
476 + : [`--https=${route.servePort}`, `--set-path=${route.mount}`]),
477 + "off",
478 + ];
479 +
480 +/** Removes the web handler at `mount` on `servePort`, the root one `ensureTailscaleServe` adds by default. */
481 export const disableTailscaleServe = Effect.fn("tailscale.disableTailscaleServe")(function* (
482 input: {
483 readonly servePort?: number;
484 + readonly mount?: string;
485 } = {},
486 ): Effect.fn.Return<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> {
446 - const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;
487 return yield* runTailscaleCommand(
448 - ["serve", `--https=${servePort}`, "off"],
488 + tailscaleServeOffArgs({
489 + servePort: input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT,
490 + mount: input.mount ?? "/",
491 + })!,
492 TAILSCALE_SERVE_TIMEOUT,
493 );
494 });
495
496 +/** Removes a TCP forward on `servePort`; one port holds one forward, so nothing else goes. */
497 +export const disableTailscaleServeTcp = (servePort: number) =>
498 + runTailscaleCommand(tailscaleServeOffArgs({ servePort })!, TAILSCALE_SERVE_TIMEOUT);
499 +
500 +const TailscaleServeConfigJson = Schema.Struct({
501 + TCP: Schema.optional(
502 + Schema.Record(Schema.String, Schema.Struct({ TCPForward: Schema.optional(Schema.String) })),
503 + ),
504 + Web: Schema.optional(
505 + Schema.Record(
506 + Schema.String,
507 + Schema.Struct({
508 + Handlers: Schema.optional(
509 + Schema.Record(Schema.String, Schema.Struct({ Proxy: Schema.optional(Schema.String) })),
510 + ),
511 + }),
512 + ),
513 + ),
514 +});
515 +const TailscaleServeStatusJson = Schema.Struct({
516 + ...TailscaleServeConfigJson.fields,
517 + // A Tailscale Service's routes, and those of each `tailscale serve` still running in the foreground.
518 + Services: Schema.optional(Schema.Record(Schema.String, TailscaleServeConfigJson)),
519 + Foreground: Schema.optional(Schema.Record(Schema.String, TailscaleServeConfigJson)),
520 +});
521 +// A node without any Serve configuration prints `null`.
522 +const decodeTailscaleServeStatusJson = Schema.decodeUnknownOption(
523 + Schema.fromJsonString(Schema.NullOr(TailscaleServeStatusJson)),
524 +);
525 +
526 +/**
527 + * Whether a proxy to `hostname` dials `bindHost`. `0.0.0.0` reaches 127.0.0.1. `[::]` may reach
528 + * either loopback, since Go dials `::` and then 0.0.0.0 (golang/go#18806), and a name such as
529 + * `localhost` may resolve to whatever the server binds.
530 + */
531 +const reaches = (hostname: string, bindHost: string): "exact" | "either" | undefined => {
532 + let address = normalizeHostname(hostname);
533 + // Compare IPv6 by value: 0:0:0:0:0:ffff:7f00:1 is ::ffff:7f00:1.
534 + if (address.includes(":") && URL.canParse(`http://[${address}]`)) {
535 + address = normalizeHostname(new URL(`http://[${address}]`).hostname);
536 + }
537 + // An IPv4-mapped address can be written as hex, such as ::ffff:7f00:1 for 127.0.0.1.
538 + const mapped = /^::ffff:([\da-f]{1,4}):([\da-f]{1,4})$/u.exec(address);
539 + if (mapped !== null) {
540 + const high = Number.parseInt(mapped[1]!, 16);
541 + const low = Number.parseInt(mapped[2]!, 16);
542 + address = [high >>> 8, high & 0xff, low >>> 8, low & 0xff].join(".");
543 + } else if (address.startsWith("::ffff:")) {
544 + address = address.slice("::ffff:".length);
545 + }
546 + // Strict, as Go's ParseIP is; anything else, such as `127.1` or `box.1`, goes to the resolver.
547 + const literal =
548 + address.includes(":") ||
549 + /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?!$)|$)){4}$/u.test(address);
550 + if (!literal) return "either";
551 + if (address === "::")
552 + return bindHost === "127.0.0.1" || bindHost === "::1" ? "either" : undefined;
553 + return (address === "0.0.0.0" ? "127.0.0.1" : address) === bindHost ? "exact" : undefined;
554 +};
555 +
556 +/** The URL Tailscale's proxy dials for a handler's `Proxy`, expanded as its `expandProxyArg` does. */
557 +const expandProxy = (proxy: string) =>
558 + /^\d+$/u.test(proxy)
559 + ? `http://127.0.0.1:${proxy}`
560 + : proxy.startsWith("https+insecure://")
561 + ? `https://${proxy.slice("https+insecure://".length)}`
562 + : /^(?:https?:\/\/|unix:)/u.test(proxy)
563 + ? proxy
564 + : `http://${proxy}`;
565 +
566 +/**
567 + * The host and port a proxy target dials, read as Go's url.Parse reads it rather than as a WHATWG
568 + * URL, which rejects `box.1` and rewrites `127.1`; none for a Unix socket.
569 + */
570 +const dialedHostPort = (url: string) => {
571 + const match = /^(https?|tcp):\/\/(?:[^@/?#]*@)?(\[[^\]]*\]|[^/?#:]*)(?::(\d*))?/iu.exec(url);
572 + if (match === null) return undefined;
573 + const [, scheme = "", host = "", port] = match;
574 + return { host, port: port || (scheme.toLowerCase() === "https" ? "443" : "80") };
575 +};
576 +
577 +const reachesTarget = (url: string, target: { readonly host: string; readonly port: number }) => {
578 + const dialed = dialedHostPort(url);
579 + // Go reads the port as a decimal number, so 03773 is 3773.
580 + if (dialed === undefined || Number(dialed.port) !== target.port) return undefined;
581 + const reach = reaches(dialed.host, target.host);
582 + return reach === undefined ? undefined : { reach, hostname: dialed.host };
583 +};
584 +
585 +/**
586 + * The Serve routes that forward to the server bound at `target`, or undefined when the status
587 + * cannot be read.
588 + */
589 +export const parseTailscaleServeRoutesTo = (
590 + rawServeStatusJson: string,
591 + target: { readonly host: string; readonly port: number },
592 +): ReadonlyArray<TailscaleServeRoute> | undefined => {
593 + const status = decodeTailscaleServeStatusJson(rawServeStatusJson);
594 + if (Option.isNone(status)) return undefined;
595 + const routesIn = (
596 + config: typeof TailscaleServeConfigJson.Type | undefined,
597 + owner?: string,
598 + ): ReadonlyArray<TailscaleServeRoute> => {
599 + const scope = owner === undefined ? {} : { owner };
600 + const reached = (url: string) => {
601 + const found = reachesTarget(url, target);
602 + if (found === undefined) return undefined;
603 + return found.reach === "either" ? { ambiguous: found.hostname } : {};
604 + };
605 + const tcp = Object.entries(config?.TCP ?? {}).flatMap(([port, handler]) => {
606 + const reach =
607 + handler.TCPForward === undefined || handler.TCPForward.startsWith("unix:")
608 + ? undefined
609 + : reached(`tcp://${handler.TCPForward}`);
610 + return reach !== undefined && Number.isInteger(Number(port))
611 + ? [{ servePort: Number(port), ...reach, ...scope }]
612 + : [];
613 + });
614 + const web = Object.entries(config?.Web ?? {}).flatMap(([hostPort, site]) => {
615 + const separator = hostPort.lastIndexOf(":");
616 + const servePort = Number(hostPort.slice(separator + 1));
617 + if (!Number.isInteger(servePort)) return [];
618 + const host = hostPort.slice(0, separator);
619 + return Object.entries(site.Handlers ?? {}).flatMap(([mount, handler]) => {
620 + const reach = handler.Proxy === undefined ? undefined : reached(expandProxy(handler.Proxy));
621 + return reach === undefined ? [] : [{ servePort, mount, host, ...reach, ...scope }];
622 + });
623 + });
624 + return [...tcp, ...web];
625 + };
626 + return [
627 + ...routesIn(status.value ?? undefined),
628 + ...Object.entries(status.value?.Services ?? {}).flatMap(([name, service]) =>
629 + routesIn(service, name),
630 + ),
631 + ...Object.values(status.value?.Foreground ?? {}).flatMap((session) =>
632 + routesIn(session, "foreground"),
633 + ),
634 + ];
635 +};
636 +
637 +/** The Serve routes that forward to the server bound at `target` on this machine. */
638 +export const readTailscaleServeRoutesTo = (target: {
639 + readonly host: string;
640 + readonly port: number;
641 +}) =>
642 + readTailscaleOutput("serve", ["serve", "status", "--json"]).pipe(
643 + Effect.flatMap((status) => {
644 + const routes = parseTailscaleServeRoutesTo(status, target);
645 + return routes === undefined
646 + ? Effect.fail(new TailscaleStatusParseError({ cause: "unreadable serve status" }))
647 + : Effect.succeed(routes);
648 + }),
649 + );
650 +
651 export const probeTailscaleHttpsEndpoint = Effect.fn("tailscale.probeTailscaleHttpsEndpoint")(
652 function* (input: { readonly baseUrl: string; readonly timeout?: Duration.Input }) {
653 const client = yield* HttpClient.HttpClient;
pnpm-lock.yaml
+6
@@ -910,6 +910,9 @@ importers:
910 effect:
911 specifier: 4.0.5
912 version: 4.0.5
913 + ffi-rs:
914 + specifier: 1.3.2
915 + version: 1.3.2
916 jose:
917 specifier: 'catalog:'
918 version: 6.2.2
@@ -2012,6 +2015,9 @@ importers:
2015 effect:
2016 specifier: 4.0.5
2017 version: 4.0.5
2018 + ffi-rs:
2019 + specifier: 1.3.2
2020 + version: 1.3.2
2021 jose:
2022 specifier: 'catalog:'
2023 version: 6.2.2
scripts/dev-runner.ts
+1 -1
@@ -806,7 +806,7 @@ export const runDevRunnerWithInput = Effect.fn("dev-runner.runDevRunnerWithInput
806 : Effect.logWarning(
807 `[dev-runner] could not remove the tailnet mapping for port ${String(sharedWebPort)}${
808 result.explanation ? `: ${result.explanation}` : ""
809 - }. Remove it with \`tailscale serve --https=${String(sharedWebPort)} off\`.`,
809 + }. Remove it with \`tailscale serve --https=${String(sharedWebPort)} --set-path=/ off\`.`,
810 ),
811 ),
812 ),
scripts/lib/dev-share.ts
+2 -1
@@ -16,6 +16,7 @@ import type { ChildProcessSpawner } from "effect/process";
16 const DIAGNOSTIC_EXPLANATIONS: Record<TailscaleStderrDiagnostic, string | undefined> = {
17 "no-existing-handler": "no mapping existed for that port",
18 "not-logged-in": "this machine is not logged into a tailnet — run `tailscale up`",
19 + "not-running": "Tailscale is not running; start it and try again",
20 "permission-denied": "permission denied — `tailscale serve` may need elevated privileges",
21 unknown: undefined,
22 };
@@ -64,7 +65,7 @@ export class DevServeFailedError extends Schema.TaggedError<DevServeFailedError>
65 const port = String(this.webPort);
66 const base =
67 this.stage === "clear-existing"
67 - ? `could not clear the existing mapping for port ${port}. Run \`tailscale serve --https=${port} off\` and retry`
68 + ? `could not clear the existing mapping for port ${port}. Run \`tailscale serve --https=${port} --set-path=/ off\` and retry`
69 : `could not serve port ${port} on the tailnet (it is no longer served; any previous mapping for it was cleared before this attempt)`;
70 return this.explanation ? `${base}: ${this.explanation}` : base;
71 }