Open History to see the last commit
1import {
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";
18import { acpRegistryClient } from "@t3tools/provider-acp-registry/client";
19import { cursorClient } from "@t3tools/provider-cursor/client";
20import { fxClient } from "@t3tools/provider-fx/client";
21import { kiroClient } from "@t3tools/provider-kiro/client";
22import { museClient } from "@t3tools/provider-muse/client";
23import { openCodeClient } from "@t3tools/provider-opencode/client";
24import { piClient } from "@t3tools/provider-pi/client";
25import type { ProviderClientDefinition } from "@t3tools/provider-core/client";
26
27interface KnownDriver {
28 readonly label: string;
29 readonly configFields: ReadonlySet<string>;
30 readonly hasDefaultInstance: boolean;
31}
32
33const 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
44const PACKAGED_CLIENTS: ReadonlyArray<ProviderClientDefinition> = [
45 cursorClient,
46 fxClient,
47 kiroClient,
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 */
60const 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. */
69const 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/** Each driver a policy may name, with the label users see. */
79export const knownDriverLabels = () =>
80 Array.from(KNOWN_DRIVERS, ([driver, { label }]) => ({ driver, label }));
81
82const PINNED_CONFIG_FIELDS = ["binaryPath", "launchArgs"] as const;
83type PinnedConfigField = (typeof PINNED_CONFIG_FIELDS)[number];
84
85/**
86 * Fields that decide what a provider starts and reads on startup; a driver has those its schema
87 * has. Under a ceiling they are the administrator's: a wrapper binary, a skip-permissions flag, or
88 * a config directory with allow rules each outrank T3 Code's mode, and no flag filter stops a wrapper.
89 */
90const LAUNCH_CONFIG_FIELDS = [
91 "binaryPath",
92 "launchArgs",
93 "homePath",
94 "shadowHomePath",
95 "commandPath",
96 "commandArgs",
97 "serverUrl",
98] as const;
99
100export type ProviderWriteVerdict =
101 | { readonly _tag: "Allowed"; readonly settings: ServerSettings }
102 | { readonly _tag: "Locked"; readonly path: string }
103 | {
104 readonly _tag: "Disallowed";
105 readonly instanceId: ProviderInstanceId;
106 readonly label: string;
107 };
108
109/**
110 * How a policy's `limits.providers` shapes provider instances. Like settings locks, pinned
111 * fields are laid over instances on every read and never written to the user's settings file.
112 */
113export interface ManagedProviders {
114 readonly isDriverAllowed: (driver: ProviderDriverKind) => boolean;
115 /** Lay pinned fields over every instance of a pinned driver, its default instance included. */
116 readonly applyLimits: (settings: ServerSettings) => ServerSettings;
117 /**
118 * Vet a write from stored `current` to `next`. Refuses enabling a disallowed driver and moving
119 * a locked field off its pinned value. Pinned values a client sends back are dropped, so the
120 * user's own values return once the policy is gone.
121 */
122 readonly vetWrite: (current: ServerSettings, next: ServerSettings) => ProviderWriteVerdict;
123 /**
124 * Per driver, the instance fields users cannot change, for clients. `environment` alone means
125 * every variable.
126 */
127 readonly lockedInstanceFields: Readonly<Record<string, ReadonlyArray<string>>>;
128}
129
130export const unmanagedProviders: ManagedProviders = {
131 isDriverAllowed: () => true,
132 applyLimits: (settings) => settings,
133 vetWrite: (_current, next) => ({ _tag: "Allowed", settings: next }),
134 lockedInstanceFields: {},
135};
136
137const labelFor = (driver: ProviderDriverKind) => KNOWN_DRIVERS.get(driver)?.label ?? driver;
138
139/** Why the policy clients were told about keeps `driver` from running, or undefined when it may run. */
140export const disallowedDriverReason = (
141 summary: ManagedPolicySummary | undefined,
142 driver: ProviderDriverKind,
143): string | undefined => {
144 const allowed = summary?.limits?.providers?.allowedDrivers;
145 return allowed === undefined || allowed.includes(driver)
146 ? undefined
147 : disallowedProviderMessage(summary?.organization, labelFor(driver));
148};
149
150/**
151 * Variables that replace a provider's launch configuration. From the environment that starts the
152 * server they are ignored under any policy, which can lock launch arguments in more than one way;
153 * from an instance's own variables they are ignored when the policy locks launch arguments.
154 */
155const LAUNCH_OVERRIDE_VARIABLES = ["T3CODE_CODEX_LAUNCH_ARGS"] as const;
156
157/** The environment provider drivers launch from under the policy clients were told about. */
158export const providerHostEnvironment = (
159 summary: ManagedPolicySummary | undefined,
160 environment: NodeJS.ProcessEnv,
161): NodeJS.ProcessEnv => {
162 if (summary === undefined) return environment;
163 const next = { ...environment };
164 for (const name of Object.keys(next)) {
165 if (LAUNCH_OVERRIDE_VARIABLES.some((override) => override === name.toUpperCase())) {
166 delete next[name];
167 }
168 }
169 // Drivers keep this object, so PATH reads through to the host for a refresh after launch to reach them.
170 const pathKeys = Object.keys(next).filter((name) => name.toUpperCase() === "PATH");
171 if (pathKeys.length > 0) {
172 for (const name of pathKeys) delete next[name];
173 Object.defineProperty(next, "PATH", {
174 enumerable: true,
175 configurable: true,
176 get: () => environment.PATH ?? environment.Path ?? environment.path,
177 set: (value) =>
178 Object.defineProperty(next, "PATH", {
179 value,
180 enumerable: true,
181 writable: true,
182 configurable: true,
183 }),
184 });
185 }
186 return next;
187};
188
189/** Each driver's home variable, and the settings that rewrite it at launch. */
190const HOME_VARIABLES: ReadonlyMap<
191 ProviderDriverKind,
192 { readonly variable: string; readonly fields: ReadonlyArray<string> }
193> = new Map([
194 [ProviderDriverKind.make("claudeAgent"), { variable: "CLAUDE_CONFIG_DIR", fields: ["homePath"] }],
195 [
196 ProviderDriverKind.make("codex"),
197 { variable: "CODEX_HOME", fields: ["homePath", "shadowHomePath"] },
198 ],
199]);
200
201const configRecord = (instance: ProviderInstanceConfig | undefined): Record<string, unknown> =>
202 instance?.config !== null &&
203 typeof instance?.config === "object" &&
204 !Array.isArray(instance.config)
205 ? (instance.config as Record<string, unknown>)
206 : {};
207
208/** Empty strings and empty lists are how clients clear a field, so they count as unset. */
209const configValue = (instance: ProviderInstanceConfig | undefined, field: string) => {
210 const value = configRecord(instance)[field];
211 return value === "" || (Array.isArray(value) && value.length === 0) ? undefined : value;
212};
213
214const sameValue = (left: unknown, right: unknown) =>
215 left === right || JSON.stringify(left) === JSON.stringify(right);
216
217const sameVariable = (
218 left: ProviderInstanceEnvironmentVariable | undefined,
219 right: ProviderInstanceEnvironmentVariable | undefined,
220) =>
221 left === right ||
222 (left !== undefined &&
223 right !== undefined &&
224 // A secret reference is an object, and a decoded copy is never the stored one.
225 sameValue(left.value, right.value) &&
226 left.sensitive === right.sensitive);
227
228const pinnedFields = (pin: ManagedProviderInstance): ReadonlyArray<PinnedConfigField> =>
229 PINNED_CONFIG_FIELDS.filter((field) => pin[field] !== undefined);
230
231/**
232 * What the administrator owns on one driver's instances. `config` fields take the pin or the
233 * default, never the user's value; `fill` fields take the pin only where the user left them empty.
234 * `environment`: `all` runs with only pinned variables, `locked` lets them win, `fill` fills gaps.
235 */
236interface DriverRule {
237 readonly pin: ManagedProviderInstance | undefined;
238 readonly config: ReadonlyArray<string>;
239 readonly fill: ReadonlyArray<PinnedConfigField>;
240 readonly environment: "all" | "locked" | "fill";
241}
242
243const pinnedValue = (pin: ManagedProviderInstance | undefined, field: string): unknown =>
244 pin === undefined ? undefined : (pin as Record<string, unknown>)[field];
245
246const overlayInstance = (
247 instance: ProviderInstanceConfig,
248 rule: DriverRule,
249 variableKey: (name: string) => string,
250): ProviderInstanceConfig => {
251 const config = { ...configRecord(instance) };
252 for (const field of rule.config) {
253 const value = pinnedValue(rule.pin, field);
254 if (value === undefined) delete config[field];
255 else config[field] = value;
256 }
257 for (const field of rule.fill) {
258 if (configValue(instance, field) === undefined) config[field] = rule.pin?.[field];
259 }
260 const pinnedEnvironment = (rule.pin?.environment ?? []).map((variable) => ({
261 name: variable.name,
262 value: variable.value,
263 sensitive: false,
264 }));
265 const pinnedByName = new Map(
266 pinnedEnvironment.map((variable) => [variableKey(variable.name), variable]),
267 );
268 const environment: Array<NonNullable<ProviderInstanceConfig["environment"]>[number]> =
269 rule.environment === "all" ? pinnedEnvironment : [];
270 if (rule.environment !== "all") {
271 const seen = new Set<string>();
272 // A user's override would replace launch arguments the administrator locked.
273 const overrides = rule.config.includes("launchArgs")
274 ? new Set(LAUNCH_OVERRIDE_VARIABLES.map(variableKey))
275 : new Set<string>();
276 // The last entry for a name wins at launch, so a lock replaces every entry with that name.
277 for (const variable of instance.environment ?? []) {
278 const key = variableKey(variable.name);
279 if (overrides.has(key)) continue;
280 const pinned = rule.environment === "locked" ? pinnedByName.get(key) : undefined;
281 if (pinned === undefined) environment.push(variable);
282 else if (!seen.has(key)) environment.push(pinned);
283 seen.add(key);
284 }
285 for (const pinned of pinnedEnvironment) {
286 if (!seen.has(variableKey(pinned.name))) environment.push(pinned);
287 }
288 }
289 const { config: _config, environment: _environment, ...envelope } = instance;
290 return {
291 ...envelope,
292 ...(instance.config === undefined && Object.keys(config).length === 0 ? {} : { config }),
293 ...(environment.length === 0 ? {} : { environment }),
294 };
295};
296
297/**
298 * Build the overlay for `limits.providers` and `limits.maxRuntimeMode`, or say why it cannot be
299 * enforced. A ceiling takes each driver's launch fields and its whole `environment`, which can
300 * carry `CLAUDE_CONFIG_DIR`, `PATH`, or `NODE_OPTIONS`; a deny list would miss the next one.
301 */
302export function makeManagedProviders(
303 limits: ManagedProviderLimits,
304 maxRuntimeMode: RuntimeMode | undefined,
305 platform: NodeJS.Platform,
306):
307 | { readonly _tag: "Valid"; readonly providers: ManagedProviders }
308 | { readonly _tag: "Invalid"; readonly reason: string } {
309 // Windows reads a variable name without regard to case, so there a lock covers every spelling.
310 const variableKey = (name: string) => (platform === "win32" ? name.toUpperCase() : name);
311 for (const driver of limits.allowedDrivers ?? []) {
312 if (driver !== "grok" && !KNOWN_DRIVERS.has(driver)) {
313 return { _tag: "Invalid", reason: `"${driver}" in allowedDrivers is not a known provider` };
314 }
315 }
316 const pins = new Map<ProviderDriverKind, ManagedProviderInstance>();
317 for (const [rawDriver, pin] of Object.entries(limits.instances ?? {})) {
318 // A policy from before the ACP driver was retired must still enforce its allowlist.
319 if (rawDriver === "grok") continue;
320 const driver = ProviderDriverKind.make(rawDriver);
321 const known = KNOWN_DRIVERS.get(driver);
322 if (known === undefined) {
323 return { _tag: "Invalid", reason: `"${driver}" in instances is not a known provider` };
324 }
325 const unsupported = pinnedFields(pin).find((field) => !known.configFields.has(field));
326 if (unsupported !== undefined) {
327 return {
328 _tag: "Invalid",
329 reason: `the ${known.label} provider has no ${unsupported} setting`,
330 };
331 }
332 const names = (pin.environment ?? []).map((variable) => variableKey(variable.name));
333 if (new Set(names).size !== names.length) {
334 return { _tag: "Invalid", reason: `instances.${driver}.environment repeats a variable` };
335 }
336 pins.set(driver, pin);
337 }
338
339 const rules = new Map<ProviderDriverKind, DriverRule>();
340 for (const [driver, known] of KNOWN_DRIVERS) {
341 const pin = pins.get(driver);
342 const bypasses = pin === undefined ? [] : Object.keys(PIN_BYPASS_FIELDS.get(driver) ?? {});
343 if (maxRuntimeMode !== undefined) {
344 rules.set(driver, {
345 pin,
346 config: [
347 ...LAUNCH_CONFIG_FIELDS.filter((field) => known.configFields.has(field)),
348 ...bypasses,
349 ],
350 fill: [],
351 environment: "all",
352 });
353 } else if (pin !== undefined) {
354 // A home path setting rewrites the provider's home variable at launch, so a lock on that
355 // variable owns the setting too.
356 const home = HOME_VARIABLES.get(driver);
357 const homeLocked =
358 home !== undefined &&
359 (pin.environment ?? []).some(
360 (variable) => variableKey(variable.name) === variableKey(home.variable),
361 );
362 rules.set(driver, {
363 pin,
364 config: pin.locked
365 ? [...pinnedFields(pin), ...bypasses, ...(homeLocked ? home.fields : [])]
366 : [],
367 fill: pin.locked ? [] : pinnedFields(pin),
368 environment: pin.locked ? "locked" : "fill",
369 });
370 }
371 }
372
373 const allowed =
374 limits.allowedDrivers === undefined ? undefined : new Set<string>(limits.allowedDrivers);
375 const isDriverAllowed = (driver: ProviderDriverKind) => allowed?.has(driver) ?? true;
376 const allowedSelection = (
377 settings: ServerSettings,
378 selection: { readonly instanceId: ProviderInstanceId } | null | undefined,
379 ) =>
380 selection == null ||
381 isDriverAllowed(
382 settings.providerInstances[selection.instanceId]?.driver ??
383 ProviderDriverKind.make(selection.instanceId),
384 );
385
386 const cache = new WeakMap<ServerSettings, ServerSettings>();
387 const applyLimits = (settings: ServerSettings): ServerSettings => {
388 const cached = cache.get(settings);
389 if (cached !== undefined) return cached;
390 const providerInstances: Record<string, ProviderInstanceConfig> = {
391 ...settings.providerInstances,
392 };
393 // Default instances exist without a settings entry until the user edits one; pin them too.
394 for (const driver of pins.keys()) {
395 const instanceId = defaultInstanceIdForDriver(driver);
396 if (KNOWN_DRIVERS.get(driver)?.hasDefaultInstance === false) continue;
397 if (providerInstances[instanceId] === undefined) providerInstances[instanceId] = { driver };
398 }
399 for (const [instanceId, instance] of Object.entries(providerInstances)) {
400 const rule = rules.get(instance.driver);
401 if (rule !== undefined) {
402 providerInstances[instanceId] = overlayInstance(instance, rule, variableKey);
403 }
404 }
405 // A cleared selection falls back to the text generation model, which is resolved afterwards.
406 const result: ServerSettings = {
407 ...settings,
408 providerInstances: providerInstances as ServerSettings["providerInstances"],
409 // An allow-list names agent drivers; text generators would send code to any other API.
410 ...(allowed === undefined ? {} : { textGenerators: {} }),
411 sourceControlWriterModelSelection: allowedSelection(
412 settings,
413 settings.sourceControlWriterModelSelection,
414 )
415 ? settings.sourceControlWriterModelSelection
416 : null,
417 reviewGuideModelSelection: allowedSelection(settings, settings.reviewGuideModelSelection)
418 ? settings.reviewGuideModelSelection
419 : null,
420 };
421 cache.set(settings, result);
422 return result;
423 };
424
425 type Locked = { readonly _tag: "Locked"; readonly path: string };
426
427 /**
428 * Vet the environment a client sent. Pinned values it echoes back are dropped; anything else
429 * the administrator owns must match what is stored. Returns the environment to store.
430 */
431 const vetEnvironment = (
432 instanceId: string,
433 stored: ProviderInstanceConfig | undefined,
434 next: ProviderInstanceConfig,
435 rule: DriverRule,
436 ):
437 | Locked
438 | {
439 readonly _tag: "Kept";
440 readonly environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>;
441 } => {
442 const pinned = rule.pin?.environment ?? [];
443 const storedVariable = (name: string) =>
444 stored?.environment?.find((existing) => variableKey(existing.name) === variableKey(name));
445 const storedUnchanged = (variable: ProviderInstanceEnvironmentVariable) =>
446 (stored?.environment ?? []).some((existing) => sameVariable(variable, existing));
447 const echoed = (variable: ProviderInstanceEnvironmentVariable) =>
448 !variable.sensitive &&
449 pinned.some((pin) => pin.name === variable.name && pin.value === variable.value);
450 if (rule.environment === "all") {
451 // Only the pinned variables were shown, so the user's own stay as stored.
452 for (const variable of next.environment ?? []) {
453 if (echoed(variable) || storedUnchanged(variable)) continue;
454 return { _tag: "Locked", path: `providerInstances.${instanceId}.environment` };
455 }
456 return { _tag: "Kept", environment: stored?.environment ?? [] };
457 }
458 let environment: ReadonlyArray<ProviderInstanceEnvironmentVariable> = next.environment ?? [];
459 for (const variable of pinned) {
460 const sent = environment.find(
461 (existing) => variableKey(existing.name) === variableKey(variable.name),
462 );
463 const kept = storedVariable(variable.name);
464 if ((sent !== undefined && echoed(sent)) || sameVariable(sent, kept)) {
465 // Put the user's own entries back where it was sent, or drop the echoed policy value.
466 const storedEntries = (stored?.environment ?? []).filter(
467 (existing) => variableKey(existing.name) === variableKey(variable.name),
468 );
469 let restored = false;
470 environment = environment.flatMap((existing) => {
471 if (variableKey(existing.name) !== variableKey(variable.name)) return [existing];
472 if (restored) return [];
473 restored = true;
474 return storedEntries;
475 });
476 } else if (rule.environment === "locked") {
477 return {
478 _tag: "Locked",
479 path: `providerInstances.${instanceId}.environment.${variable.name}`,
480 };
481 }
482 }
483 // The client never saw a launch override the lock hides, so keep the stored one.
484 if (rule.config.includes("launchArgs")) {
485 const overrides = new Set(LAUNCH_OVERRIDE_VARIABLES.map(variableKey));
486 environment = [
487 ...environment.filter((variable) => !overrides.has(variableKey(variable.name))),
488 ...(stored?.environment ?? []).filter((variable) =>
489 overrides.has(variableKey(variable.name)),
490 ),
491 ];
492 }
493 return { _tag: "Kept", environment };
494 };
495
496 const vetInstance = (
497 instanceId: string,
498 stored: ProviderInstanceConfig | undefined,
499 next: ProviderInstanceConfig,
500 rule: DriverRule,
501 ): Locked | { readonly _tag: "Kept"; readonly instance: ProviderInstanceConfig | undefined } => {
502 const config = { ...configRecord(next) };
503 const harmless = PIN_BYPASS_FIELDS.get(next.driver) ?? {};
504 for (const field of [...rule.config, ...rule.fill]) {
505 const value = configValue(next, field);
506 const storedValue = configValue(stored, field);
507 if (
508 sameValue(value, pinnedValue(rule.pin, field)) ||
509 sameValue(value, storedValue) ||
510 (field in harmless && sameValue(value, harmless[field]))
511 ) {
512 if (storedValue === undefined) delete config[field];
513 else config[field] = configRecord(stored)[field];
514 } else if (rule.config.includes(field)) {
515 return { _tag: "Locked", path: `providerInstances.${instanceId}.config.${field}` };
516 }
517 }
518 const vettedEnvironment = vetEnvironment(instanceId, stored, next, rule);
519 if (vettedEnvironment._tag === "Locked") return vettedEnvironment;
520 const { environment } = vettedEnvironment;
521 const { config: _config, environment: _environment, ...envelope } = next;
522 const kept: ProviderInstanceConfig = {
523 ...envelope,
524 ...(Object.keys(config).length === 0 && stored?.config === undefined ? {} : { config }),
525 ...(environment.length === 0 ? {} : { environment }),
526 };
527 // A default instance the client echoed back with only pinned values stays implicit.
528 const echoedDefault =
529 stored === undefined &&
530 instanceId === defaultInstanceIdForDriver(next.driver) &&
531 Object.keys(kept).length === 1;
532 return { _tag: "Kept", instance: echoedDefault ? undefined : kept };
533 };
534
535 const vetWrite = (current: ServerSettings, next: ServerSettings): ProviderWriteVerdict => {
536 const providerInstances: Record<string, ProviderInstanceConfig> = {};
537 for (const [instanceId, instance] of Object.entries(next.providerInstances)) {
538 const stored = current.providerInstances[instanceId as ProviderInstanceId];
539 // Clients echo instances with policy fields laid over them, so compare only whether it runs.
540 // A driver's default instance runs before it is configured.
541 const wasEnabled =
542 stored !== undefined
543 ? stored.driver === instance.driver && resolveProviderInstanceEnabled(stored)
544 : instanceId === defaultInstanceIdForDriver(instance.driver);
545 if (
546 !isDriverAllowed(instance.driver) &&
547 resolveProviderInstanceEnabled(instance) &&
548 !wasEnabled
549 ) {
550 return {
551 _tag: "Disallowed",
552 instanceId: instanceId as ProviderInstanceId,
553 label: labelFor(instance.driver),
554 };
555 }
556 const rule = rules.get(instance.driver);
557 if (rule === undefined) {
558 providerInstances[instanceId] = instance;
559 continue;
560 }
561 const vetted = vetInstance(
562 instanceId,
563 stored?.driver === instance.driver ? stored : undefined,
564 instance,
565 rule,
566 );
567 if (vetted._tag === "Locked") return vetted;
568 if (vetted.instance !== undefined) providerInstances[instanceId] = vetted.instance;
569 }
570 // A project can switch an instance on for itself; that is enabling it too.
571 for (const [projectId, overrides] of Object.entries(next.projectSettingsOverrides)) {
572 const storedOverrides =
573 current.projectSettingsOverrides[projectId as keyof typeof current.projectSettingsOverrides]
574 ?.providerInstances;
575 for (const [instanceId, override] of Object.entries(overrides.providerInstances ?? {})) {
576 const driver =
577 next.providerInstances[instanceId as ProviderInstanceId]?.driver ??
578 ProviderDriverKind.make(instanceId);
579 if (
580 override.enabled === true &&
581 storedOverrides?.[instanceId as ProviderInstanceId]?.enabled !== true &&
582 !isDriverAllowed(driver)
583 ) {
584 return {
585 _tag: "Disallowed",
586 instanceId: instanceId as ProviderInstanceId,
587 label: labelFor(driver),
588 };
589 }
590 }
591 }
592 return {
593 _tag: "Allowed",
594 settings: {
595 ...next,
596 providerInstances: providerInstances as ServerSettings["providerInstances"],
597 },
598 };
599 };
600
601 const lockedInstanceFields = Object.fromEntries(
602 [...rules].flatMap(([driver, rule]) => {
603 const fields = [
604 ...rule.config.map((field) => `config.${field}`),
605 ...(rule.environment === "all"
606 ? ["environment"]
607 : rule.environment === "locked"
608 ? (rule.pin?.environment ?? []).map((variable) => `environment.${variable.name}`)
609 : []),
610 ];
611 return fields.length === 0 ? [] : [[driver, fields] as const];
612 }),
613 );
614
615 return {
616 _tag: "Valid",
617 providers: {
618 isDriverAllowed,
619 applyLimits,
620 vetWrite,
621 lockedInstanceFields,
622 },
623 };
624}