Open History to see the last commit
1import * as Schema from "effect/Schema";
2import * as Struct from "effect/Struct";
3
4import { TrimmedNonEmptyString } from "./baseSchemas.ts";
5import { ProviderDriverKind, ProviderInstanceEnvironmentVariableName } from "./providerInstance.ts";
6import { 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 */
13export const ManagedPolicySetting = Schema.Struct({
14 value: Schema.Unknown,
15 locked: Schema.Boolean,
16});
17export 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 */
24export 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});
34export type ManagedProviderInstance = typeof ManagedProviderInstance.Type;
35
36export 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});
41export 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 */
47export const ManagedUpdatesMode = Schema.Literals(["auto", "off"]);
48export type ManagedUpdatesMode = typeof ManagedUpdatesMode.Type;
49
50const HttpsUrl = TrimmedNonEmptyString.check(
51 Schema.makeFilter((value: string) => /^https:\/\/[^\s/]+/i.test(value.trim()), {
52 expected: "an https URL",
53 }),
54);
55
56export 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});
63export type ManagedUpdatesPolicy = typeof ManagedUpdatesPolicy.Type;
64
65/** A kind of client the server may accept, mapped onto `ServerAuthPolicy`. */
66export const ManagedPolicyClient = Schema.Literals(["desktop", "local-browser", "remote"]);
67export 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 */
73export 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 /** `false` turns the preview tunnel off: no client reaches this machine's loopback ports. */
85 previewTunnel: Schema.optionalKey(Schema.Boolean),
86 /** `false` turns a project's `worktreeLayout` commands off: none runs, approved or not. */
87 worktreeLayoutCommands: Schema.optionalKey(Schema.Boolean),
88 providers: Schema.optionalKey(ManagedProviderLimits),
89 updates: Schema.optionalKey(ManagedUpdatesPolicy),
90});
91export type ManagedPolicyLimits = typeof ManagedPolicyLimits.Type;
92
93/** The limits clients see: what the server enforces, which can be broader than the file says. */
94export const ManagedPolicySummaryLimits = Schema.Struct({
95 maxRuntimeMode: Schema.optionalKey(RuntimeMode),
96 clients: Schema.optionalKey(Schema.NonEmptyArray(ManagedPolicyClient)),
97 /** `false` also when `clients` leaves out `remote`, since Connect is remote access. */
98 connect: Schema.optionalKey(Schema.Boolean),
99 webhookTasks: Schema.optionalKey(Schema.Boolean),
100 telemetry: Schema.optionalKey(Schema.Boolean),
101 browserCookieImport: Schema.optionalKey(Schema.Boolean),
102 previewTunnel: Schema.optionalKey(Schema.Boolean),
103 worktreeLayoutCommands: Schema.optionalKey(Schema.Boolean),
104 providers: Schema.optionalKey(
105 Schema.Struct({
106 /** Absent means every driver is allowed. */
107 allowedDrivers: Schema.optionalKey(Schema.NonEmptyArray(ProviderDriverKind)),
108 /**
109 * Per driver, the instance fields users cannot change, as dot paths into the instance
110 * envelope: `config.binaryPath`, `config.launchArgs`, `environment.<NAME>`. A bare
111 * `environment` means every variable, as under `maxRuntimeMode`, where each driver's
112 * launch configuration belongs to the administrator.
113 */
114 lockedInstanceFields: Schema.optionalKey(
115 Schema.Record(ProviderDriverKind, Schema.Array(Schema.String)),
116 ),
117 }),
118 ),
119 /** No `feedUrl`: it can carry a token, and only the desktop app, which reads the file, uses it. */
120 updates: Schema.optionalKey(ManagedUpdatesPolicy.mapFields(Struct.omit(["feedUrl"]))),
121});
122export type ManagedPolicySummaryLimits = typeof ManagedPolicySummaryLimits.Type;
123
124/**
125 * The machine-wide policy file an administrator deploys. Decoded with excess properties
126 * rejected: a key this build does not know might be a restriction it cannot enforce, and
127 * starting anyway would look managed without being managed.
128 */
129export const ManagedPolicyDocument = Schema.Struct({
130 schemaVersion: Schema.Literal(1),
131 /** Shown to users as "Managed by <organization>". */
132 organization: TrimmedNonEmptyString,
133 supportUrl: Schema.optionalKey(TrimmedNonEmptyString),
134 settings: Schema.optionalKey(Schema.Record(Schema.String, ManagedPolicySetting)),
135 limits: Schema.optionalKey(ManagedPolicyLimits),
136});
137export type ManagedPolicyDocument = typeof ManagedPolicyDocument.Type;
138
139/** What clients learn about the policy: enough to explain a locked control, no values. */
140export const ManagedPolicySummary = Schema.Struct({
141 organization: TrimmedNonEmptyString,
142 supportUrl: Schema.optionalKey(TrimmedNonEmptyString),
143 /** Dot paths into `ServerSettings` that users cannot change. */
144 lockedSettings: Schema.Array(Schema.String),
145 /** What the server enforces; a missing key means no limit. */
146 limits: Schema.optionalKey(ManagedPolicySummaryLimits),
147});
148export type ManagedPolicySummary = typeof ManagedPolicySummary.Type;
149
150/** The message every surface shows when the policy stops an update. */
151export function managedUpdatesMessage(organization: string): string {
152 return `${organization} manages T3 Code updates.`;
153}
154
155/** The message when the policy allows only stable releases. */
156export function managedNightlyDeniedMessage(organization: string): string {
157 return `${managedUpdatesMessage(organization)} Only stable releases can be installed.`;
158}
159
160/** Whether `path` is locked itself, sits inside a locked setting, or contains one. */
161export function isManagedSettingPath(
162 summary: Pick<ManagedPolicySummary, "lockedSettings"> | undefined,
163 path: string,
164): boolean {
165 if (summary === undefined) return false;
166 return summary.lockedSettings.some(
167 (locked) => locked === path || locked.startsWith(`${path}.`) || path.startsWith(`${locked}.`),
168 );
169}
170
171/** The one shape users see when policy refuses something: "Example Corp's policy does not allow webhook tasks." */
172export function managedPolicyDeniedMessage(organization: string, capability: string): string {
173 return `${organization}'s policy does not allow ${capability}.`;
174}
175
176const RUNTIME_MODE_LABELS: Record<RuntimeMode, string> = {
177 "approval-required": "Supervised",
178 "auto-accept-edits": "Auto-accept edits",
179 auto: "Auto",
180 "full-access": "Full access",
181};
182
183/** "Example Corp limits threads to Auto-accept edits." */
184export function managedRuntimeModeCeilingMessage(organization: string, ceiling: RuntimeMode) {
185 return `${organization} limits threads to ${RUNTIME_MODE_LABELS[ceiling]}.`;
186}
187
188/** Why `mode` is unavailable on an environment with `summary`, or undefined when it is allowed. */
189export function managedRuntimeModeDenial(
190 summary: ManagedPolicySummary | undefined,
191 mode: RuntimeMode,
192): string | undefined {
193 const ceiling = summary?.limits?.maxRuntimeMode;
194 return summary !== undefined && ceiling !== undefined && isRuntimeModeAbove(mode, ceiling)
195 ? managedRuntimeModeCeilingMessage(summary.organization, ceiling)
196 : undefined;
197}
198
199/**
200 * `mode` when the policy allows it, else the broadest of `modes` (narrowest first) that it does:
201 * where a thread or task above the ceiling switches down to. Undefined when none is allowed.
202 */
203export function clampManagedRuntimeMode(
204 summary: ManagedPolicySummary | undefined,
205 mode: RuntimeMode,
206 modes: ReadonlyArray<RuntimeMode> = RuntimeMode.literals,
207): RuntimeMode | undefined {
208 const ceiling = summary?.limits?.maxRuntimeMode;
209 if (!isRuntimeModeAbove(mode, ceiling)) return mode;
210 return modes.findLast((candidate) => !isRuntimeModeAbove(candidate, ceiling));
211}
212
213const CAPABILITY_LABELS = {
214 remoteClients: "connecting from other devices",
215 connect: "T3 Connect",
216 webhookTasks: "webhook tasks",
217 browserCookieImport: "importing browser cookies",
218 previewTunnel: "opening this machine's local servers on other devices",
219 worktreeLayoutCommands: "project worktree layout commands",
220} as const;
221
222/** Why a capability is unavailable on an environment with `summary`, or undefined when allowed. */
223export function managedCapabilityDenial(
224 summary: ManagedPolicySummary | undefined,
225 capability: keyof typeof CAPABILITY_LABELS,
226): string | undefined {
227 const limits = summary?.limits;
228 if (summary === undefined || limits === undefined) return undefined;
229 const denied =
230 capability === "remoteClients"
231 ? limits.clients !== undefined && !limits.clients.includes("remote")
232 : limits[capability] === false;
233 return denied
234 ? managedPolicyDeniedMessage(summary.organization, CAPABILITY_LABELS[capability])
235 : undefined;
236}
237
238/** Whether the preview tunnel serves: the setting is on and no policy switches it off. */
239export function allowsPreviewTunnel(config: {
240 readonly settings: { readonly enablePreviewTunnel: boolean };
241 readonly managedPolicy?: ManagedPolicySummary | undefined;
242}): boolean {
243 return (
244 config.settings.enablePreviewTunnel && config.managedPolicy?.limits?.previewTunnel !== false
245 );
246}
247
248/** Whether the policy lets `driver` run; clients name it with their own provider label. */
249export function isManagedDriverAllowed(
250 summary: ManagedPolicySummary | undefined,
251 driver: ProviderDriverKind,
252): boolean {
253 const allowed = summary?.limits?.providers?.allowedDrivers;
254 return allowed === undefined || allowed.includes(driver);
255}
256
257/** Why updates are unavailable on an environment with `summary`, or undefined when allowed. */
258export function managedUpdatesDenial(summary: ManagedPolicySummary | undefined) {
259 return summary?.limits?.updates?.mode === "off"
260 ? managedUpdatesMessage(summary.organization)
261 : undefined;
262}