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