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

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