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 21, 04:45 UTC
| 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 { kiroClient } from "@t3tools/provider-kiro/client"; |
| 23 | import { museClient } from "@t3tools/provider-muse/client"; |
| 24 | import { openCodeClient } from "@t3tools/provider-opencode/client"; |
| 25 | import { piClient } from "@t3tools/provider-pi/client"; |
| 26 | import type { ProviderClientDefinition } from "@t3tools/provider-core/client"; |
| 27 | |
| 28 | interface KnownDriver { |
| 29 | readonly label: string; |
| 30 | readonly configFields: ReadonlySet<string>; |
| 31 | readonly hasDefaultInstance: boolean; |
| 32 | } |
| 33 | |
| 34 | const known = ( |
| 35 | driverKind: string, |
| 36 | label: string, |
| 37 | settingsSchema: { readonly fields: object }, |
| 38 | hasDefaultInstance = true, |
| 39 | ) => |
| 40 | [ |
| 41 | ProviderDriverKind.make(driverKind), |
| 42 | { label, configFields: new Set(Object.keys(settingsSchema.fields)), hasDefaultInstance }, |
| 43 | ] as const; |
| 44 | |
| 45 | const PACKAGED_CLIENTS: ReadonlyArray<ProviderClientDefinition> = [ |
| 46 | cursorClient, |
| 47 | grokClient, |
| 48 | fxClient, |
| 49 | kiroClient, |
| 50 | museClient, |
| 51 | openCodeClient, |
| 52 | piClient, |
| 53 | acpRegistryClient, |
| 54 | ]; |
| 55 | |
| 56 | /** |
| 57 | * Fields that make an instance launch without the settings a pin sets: managed Codex runs T3's own |
| 58 | * runtime against OpenAI, and a server URL points OpenCode at a server it does not start. A policy |
| 59 | * that owns a pin owns these too, holding each at the value given here, which clients still send |
| 60 | * when they add an instance. |
| 61 | */ |
| 62 | const PIN_BYPASS_FIELDS: ReadonlyMap< |
| 63 | ProviderDriverKind, |
| 64 | Readonly<Record<string, unknown>> |
| 65 | > = new Map<ProviderDriverKind, Readonly<Record<string, unknown>>>([ |
| 66 | [ProviderDriverKind.make("codex"), { setupMode: "existing" }], |
| 67 | [ProviderDriverKind.make("opencode"), { serverUrl: "" }], |
| 68 | ]); |
| 69 | |
| 70 | /** Drivers this build knows, by the names users see; a policy naming any other is refused. */ |
| 71 | const KNOWN_DRIVERS: ReadonlyMap<ProviderDriverKind, KnownDriver> = new Map([ |
| 72 | known("codex", "Codex", CodexSettings), |
| 73 | known("claudeAgent", "Claude", ClaudeSettings), |
| 74 | known("antigravity", "Antigravity", AntigravitySettings), |
| 75 | ...PACKAGED_CLIENTS.map((client) => |
| 76 | known(client.driverKind, client.label, client.settingsSchema, client.hasDefaultInstance), |
| 77 | ), |
| 78 | ]); |
| 79 | |
| 80 | /** Each driver a policy may name, with the label users see. */ |
| 81 | export const knownDriverLabels = () => |
| 82 | Array.from(KNOWN_DRIVERS, ([driver, { label }]) => ({ driver, label })); |
| 83 | |
| 84 | const PINNED_CONFIG_FIELDS = ["binaryPath", "launchArgs"] as const; |
| 85 | type PinnedConfigField = (typeof PINNED_CONFIG_FIELDS)[number]; |
| 86 | |
| 87 | /** |
| 88 | * Fields that decide what a provider starts and reads on startup; a driver has those its schema |
| 89 | * has. Under a ceiling they are the administrator's: a wrapper binary, a skip-permissions flag, or |
| 90 | * a config directory with allow rules each outrank T3 Code's mode, and no flag filter stops a wrapper. |
| 91 | */ |
| 92 | const LAUNCH_CONFIG_FIELDS = [ |
| 93 | "binaryPath", |
| 94 | "launchArgs", |
| 95 | "homePath", |
| 96 | "shadowHomePath", |
| 97 | "commandPath", |
| 98 | "commandArgs", |
| 99 | "serverUrl", |
| 100 | ] as const; |
| 101 | |
| 102 | export type ProviderWriteVerdict = |
| 103 | | { readonly _tag: "Allowed"; readonly settings: ServerSettings } |
| 104 | | { readonly _tag: "Locked"; readonly path: string } |
| 105 | | { |
| 106 | readonly _tag: "Disallowed"; |
| 107 | readonly instanceId: ProviderInstanceId; |
| 108 | readonly label: string; |
| 109 | }; |
| 110 | |
| 111 | /** |
| 112 | * How a policy's `limits.providers` shapes provider instances. Like settings locks, pinned |
| 113 | * fields are laid over instances on every read and never written to the user's settings file. |
| 114 | */ |
| 115 | export interface ManagedProviders { |
| 116 | readonly isDriverAllowed: (driver: ProviderDriverKind) => boolean; |
| 117 | /** Lay pinned fields over every instance of a pinned driver, its default instance included. */ |
| 118 | readonly applyLimits: (settings: ServerSettings) => ServerSettings; |
| 119 | /** |
| 120 | * Vet a write from stored `current` to `next`. Refuses enabling a disallowed driver and moving |
| 121 | * a locked field off its pinned value. Pinned values a client sends back are dropped, so the |
| 122 | * user's own values return once the policy is gone. |
| 123 | */ |
| 124 | readonly vetWrite: (current: ServerSettings, next: ServerSettings) => ProviderWriteVerdict; |
| 125 | /** |
| 126 | * Per driver, the instance fields users cannot change, for clients. `environment` alone means |
| 127 | * every variable. |
| 128 | */ |
| 129 | readonly lockedInstanceFields: Readonly<Record<string, ReadonlyArray<string>>>; |
| 130 | } |
| 131 | |
| 132 | export const unmanagedProviders: ManagedProviders = { |
| 133 | isDriverAllowed: () => true, |
| 134 | applyLimits: (settings) => settings, |
| 135 | vetWrite: (_current, next) => ({ _tag: "Allowed", settings: next }), |
| 136 | lockedInstanceFields: {}, |
| 137 | }; |
| 138 | |
| 139 | const labelFor = (driver: ProviderDriverKind) => KNOWN_DRIVERS.get(driver)?.label ?? driver; |
| 140 | |
| 141 | /** Why the policy clients were told about keeps `driver` from running, or undefined when it may run. */ |
| 142 | export const disallowedDriverReason = ( |
| 143 | summary: ManagedPolicySummary | undefined, |
| 144 | driver: ProviderDriverKind, |
| 145 | ): string | undefined => { |
| 146 | const allowed = summary?.limits?.providers?.allowedDrivers; |
| 147 | return allowed === undefined || allowed.includes(driver) |
| 148 | ? undefined |
| 149 | : disallowedProviderMessage(summary?.organization, labelFor(driver)); |
| 150 | }; |
| 151 | |
| 152 | /** |
| 153 | * Variables that replace a provider's launch configuration. From the environment that starts the |
| 154 | * server they are ignored under any policy, which can lock launch arguments in more than one way; |
| 155 | * from an instance's own variables they are ignored when the policy locks launch arguments. |
| 156 | */ |
| 157 | const LAUNCH_OVERRIDE_VARIABLES = ["T3CODE_CODEX_LAUNCH_ARGS"] as const; |
| 158 | |
| 159 | /** The environment provider drivers launch from under the policy clients were told about. */ |
| 160 | export const providerHostEnvironment = ( |
| 161 | summary: ManagedPolicySummary | undefined, |
| 162 | environment: NodeJS.ProcessEnv, |
| 163 | ): NodeJS.ProcessEnv => { |
| 164 | if (summary === undefined) return environment; |
| 165 | const next = { ...environment }; |
| 166 | for (const name of Object.keys(next)) { |
| 167 | if (LAUNCH_OVERRIDE_VARIABLES.some((override) => override === name.toUpperCase())) { |
| 168 | delete next[name]; |
| 169 | } |
| 170 | } |
| 171 | // Drivers keep this object, so PATH reads through to the host for a refresh after launch to reach them. |
| 172 | const pathKeys = Object.keys(next).filter((name) => name.toUpperCase() === "PATH"); |
| 173 | if (pathKeys.length > 0) { |
| 174 | for (const name of pathKeys) delete next[name]; |
| 175 | Object.defineProperty(next, "PATH", { |
| 176 | enumerable: true, |
| 177 | configurable: true, |
| 178 | get: () => environment.PATH ?? environment.Path ?? environment.path, |
| 179 | set: (value) => |
| 180 | Object.defineProperty(next, "PATH", { |
| 181 | value, |
| 182 | enumerable: true, |
| 183 | writable: true, |
| 184 | configurable: true, |
| 185 | }), |
| 186 | }); |
| 187 | } |
| 188 | return next; |
| 189 | }; |
| 190 | |
| 191 | /** Each driver's home variable, and the settings that rewrite it at launch. */ |
| 192 | const HOME_VARIABLES: ReadonlyMap< |
| 193 | ProviderDriverKind, |
| 194 | { readonly variable: string; readonly fields: ReadonlyArray<string> } |
| 195 | > = new Map([ |
| 196 | [ProviderDriverKind.make("claudeAgent"), { variable: "CLAUDE_CONFIG_DIR", fields: ["homePath"] }], |
| 197 | [ |
| 198 | ProviderDriverKind.make("codex"), |
| 199 | { variable: "CODEX_HOME", fields: ["homePath", "shadowHomePath"] }, |
| 200 | ], |
| 201 | ]); |
| 202 | |
| 203 | const configRecord = (instance: ProviderInstanceConfig | undefined): Record<string, unknown> => |
| 204 | instance?.config !== null && |
| 205 | typeof instance?.config === "object" && |
| 206 | !Array.isArray(instance.config) |
| 207 | ? (instance.config as Record<string, unknown>) |
| 208 | : {}; |
| 209 | |
| 210 | /** Empty strings and empty lists are how clients clear a field, so they count as unset. */ |
| 211 | const configValue = (instance: ProviderInstanceConfig | undefined, field: string) => { |
| 212 | const value = configRecord(instance)[field]; |
| 213 | return value === "" || (Array.isArray(value) && value.length === 0) ? undefined : value; |
| 214 | }; |
| 215 | |
| 216 | const sameValue = (left: unknown, right: unknown) => |
| 217 | left === right || JSON.stringify(left) === JSON.stringify(right); |
| 218 | |
| 219 | const sameVariable = ( |
| 220 | left: ProviderInstanceEnvironmentVariable | undefined, |
| 221 | right: ProviderInstanceEnvironmentVariable | undefined, |
| 222 | ) => |
| 223 | left === right || |
| 224 | (left !== undefined && |
| 225 | right !== undefined && |
| 226 | // A secret reference is an object, and a decoded copy is never the stored one. |
| 227 | sameValue(left.value, right.value) && |
| 228 | left.sensitive === right.sensitive); |
| 229 | |
| 230 | const pinnedFields = (pin: ManagedProviderInstance): ReadonlyArray<PinnedConfigField> => |
| 231 | PINNED_CONFIG_FIELDS.filter((field) => pin[field] !== undefined); |
| 232 | |
| 233 | /** |
| 234 | * What the administrator owns on one driver's instances. `config` fields take the pin or the |
| 235 | * default, never the user's value; `fill` fields take the pin only where the user left them empty. |
| 236 | * `environment`: `all` runs with only pinned variables, `locked` lets them win, `fill` fills gaps. |
| 237 | */ |
| 238 | interface DriverRule { |
| 239 | readonly pin: ManagedProviderInstance | undefined; |
| 240 | readonly config: ReadonlyArray<string>; |
| 241 | readonly fill: ReadonlyArray<PinnedConfigField>; |
| 242 | readonly environment: "all" | "locked" | "fill"; |
| 243 | } |
| 244 | |
| 245 | const pinnedValue = (pin: ManagedProviderInstance | undefined, field: string): unknown => |
| 246 | pin === undefined ? undefined : (pin as Record<string, unknown>)[field]; |
| 247 | |
| 248 | const overlayInstance = ( |
| 249 | instance: ProviderInstanceConfig, |
| 250 | rule: DriverRule, |
| 251 | variableKey: (name: string) => string, |
| 252 | ): ProviderInstanceConfig => { |
| 253 | const config = { ...configRecord(instance) }; |
| 254 | for (const field of rule.config) { |
| 255 | const value = pinnedValue(rule.pin, field); |
| 256 | if (value === undefined) delete config[field]; |
| 257 | else config[field] = value; |
| 258 | } |
| 259 | for (const field of rule.fill) { |
| 260 | if (configValue(instance, field) === undefined) config[field] = rule.pin?.[field]; |
| 261 | } |
| 262 | const pinnedEnvironment = (rule.pin?.environment ?? []).map((variable) => ({ |
| 263 | name: variable.name, |
| 264 | value: variable.value, |
| 265 | sensitive: false, |
| 266 | })); |
| 267 | const pinnedByName = new Map( |
| 268 | pinnedEnvironment.map((variable) => [variableKey(variable.name), variable]), |
| 269 | ); |
| 270 | const environment: Array<NonNullable<ProviderInstanceConfig["environment"]>[number]> = |
| 271 | rule.environment === "all" ? pinnedEnvironment : []; |
| 272 | if (rule.environment !== "all") { |
| 273 | const seen = new Set<string>(); |
| 274 | // A user's override would replace launch arguments the administrator locked. |
| 275 | const overrides = rule.config.includes("launchArgs") |
| 276 | ? new Set(LAUNCH_OVERRIDE_VARIABLES.map(variableKey)) |
| 277 | : new Set<string>(); |
| 278 | // The last entry for a name wins at launch, so a lock replaces every entry with that name. |
| 279 | for (const variable of instance.environment ?? []) { |
| 280 | const key = variableKey(variable.name); |
| 281 | if (overrides.has(key)) continue; |
| 282 | const pinned = rule.environment === "locked" ? pinnedByName.get(key) : undefined; |
| 283 | if (pinned === undefined) environment.push(variable); |
| 284 | else if (!seen.has(key)) environment.push(pinned); |
| 285 | seen.add(key); |
| 286 | } |
| 287 | for (const pinned of pinnedEnvironment) { |
| 288 | if (!seen.has(variableKey(pinned.name))) environment.push(pinned); |
| 289 | } |
| 290 | } |
| 291 | const { config: _config, environment: _environment, ...envelope } = instance; |
| 292 | return { |
| 293 | ...envelope, |
| 294 | ...(instance.config === undefined && Object.keys(config).length === 0 ? {} : { config }), |
| 295 | ...(environment.length === 0 ? {} : { environment }), |
| 296 | }; |
| 297 | }; |
| 298 | |
| 299 | /** |
| 300 | * Build the overlay for `limits.providers` and `limits.maxRuntimeMode`, or say why it cannot be |
| 301 | * enforced. A ceiling takes each driver's launch fields and its whole `environment`, which can |
| 302 | * carry `CLAUDE_CONFIG_DIR`, `PATH`, or `NODE_OPTIONS`; a deny list would miss the next one. |
| 303 | */ |
| 304 | export function makeManagedProviders( |
| 305 | limits: ManagedProviderLimits, |
| 306 | maxRuntimeMode: RuntimeMode | undefined, |
| 307 | platform: NodeJS.Platform, |
| 308 | ): |
| 309 | | { readonly _tag: "Valid"; readonly providers: ManagedProviders } |
| 310 | | { readonly _tag: "Invalid"; readonly reason: string } { |
| 311 | // Windows reads a variable name without regard to case, so there a lock covers every spelling. |
| 312 | const variableKey = (name: string) => (platform === "win32" ? name.toUpperCase() : name); |
| 313 | for (const driver of limits.allowedDrivers ?? []) { |
| 314 | if (!KNOWN_DRIVERS.has(driver)) { |
| 315 | return { _tag: "Invalid", reason: `"${driver}" in allowedDrivers is not a known provider` }; |
| 316 | } |
| 317 | } |
| 318 | const pins = new Map<ProviderDriverKind, ManagedProviderInstance>(); |
| 319 | for (const [rawDriver, pin] of Object.entries(limits.instances ?? {})) { |
| 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 | } |