fix(server): only run provider updates through the installer that owns the binary (#9325)
Co-authored-by: Claude Code <[email protected]>
This commit is contained in:
1 parent
94cc8152ff
commit
2fb99a7a66
23 files changed
+1642
-954
No files matched your search
@@ -48,6 +48,7 @@ import { withInstanceIdentity } from "./instanceIdentity.ts";
|
||||
import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
|
||||
import {
|
||||
enrichProviderSnapshotWithVersionAdvisory,
|
||||
makeCachedProviderMaintenanceResolution,
|
||||
makePackageManagedProviderMaintenanceResolver,
|
||||
normalizeCommandPath,
|
||||
resolveProviderMaintenanceCapabilitiesEffect,
|
||||
@@ -76,11 +77,8 @@ function isClaudeNativeCommandPath(commandPath: string): boolean {
|
||||
const UPDATE = makePackageManagedProviderMaintenanceResolver({
|
||||
provider: DRIVER_KIND,
|
||||
npmPackageName: "@anthropic-ai/claude-code",
|
||||
homebrewFormula: "claude-code",
|
||||
nativeUpdate: {
|
||||
executable: "claude",
|
||||
args: ["update"],
|
||||
lockKey: "claude-native",
|
||||
isCommandPath: isClaudeNativeCommandPath,
|
||||
},
|
||||
});
|
||||
@@ -122,10 +120,16 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
|
||||
instanceId,
|
||||
});
|
||||
const effectiveConfig = { ...config, enabled } satisfies ClaudeSettings;
|
||||
const maintenanceCapabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
|
||||
binaryPath: effectiveConfig.binaryPath,
|
||||
env: processEnv,
|
||||
});
|
||||
const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution(
|
||||
resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
|
||||
binaryPath: effectiveConfig.binaryPath,
|
||||
env: processEnv,
|
||||
}).pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(Path.Path, path),
|
||||
),
|
||||
);
|
||||
const continuationGroupKey = yield* makeClaudeContinuationGroupKey(effectiveConfig);
|
||||
const stampIdentity = withInstanceIdentity({
|
||||
instanceId,
|
||||
@@ -189,7 +193,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
|
||||
|
||||
const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);
|
||||
const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<ClaudeSettings>>({
|
||||
maintenanceCapabilities,
|
||||
resolveMaintenance,
|
||||
getSettings: snapshotSettings.getSettings,
|
||||
streamSettings: snapshotSettings.streamSettings,
|
||||
haveSettingsChanged: haveProviderSnapshotSettingsChanged,
|
||||
@@ -202,9 +206,12 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
|
||||
),
|
||||
checkProvider,
|
||||
enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>
|
||||
enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {
|
||||
enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
|
||||
}).pipe(
|
||||
resolveMaintenance().pipe(
|
||||
Effect.flatMap((maintenanceCapabilities) =>
|
||||
enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {
|
||||
enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
|
||||
}),
|
||||
),
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
|
||||
),
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as NodeOS from "node:os";
|
||||
import * as NodePath from "node:path";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import { ProviderInstanceId } from "@t3tools/contracts";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
|
||||
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { layerTest as codexResetCreditLayerTest } from "../Layers/codexResetCredit.ts";
|
||||
import { NoOpProviderEventLoggers, ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
|
||||
import * as ModelManifest from "../ModelManifest.ts";
|
||||
import { CodexDriver } from "./CodexDriver.ts";
|
||||
|
||||
const testLayer = ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-codex-driver-maintenance-",
|
||||
}).pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(ModelManifest.layerTest),
|
||||
Layer.provideMerge(codexResetCreditLayerTest),
|
||||
Layer.provideMerge(
|
||||
Layer.mock(BackgroundPolicy.BackgroundPolicy)({
|
||||
shouldRunScopeWork: () => Effect.succeed(false),
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(
|
||||
HttpClient.HttpClient,
|
||||
HttpClient.make(() => Effect.die("Disabled Codex must not make an HTTP request")),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
// The `#!/bin/sh` stub below cannot be resolved as an executable on Windows.
|
||||
const windowsHost = HostProcessPlatform.defaultValue() === "win32";
|
||||
|
||||
const noSpawn = ChildProcessSpawner.make(() =>
|
||||
Effect.die("Disabled Codex must not spawn a process"),
|
||||
);
|
||||
|
||||
it.layer(testLayer)("CodexDriver", (it) => {
|
||||
it.effect.skipIf(windowsHost)(
|
||||
"runs the standalone updater against the shared home, not the shadow home",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-codex-driver-" });
|
||||
const sharedHome = NodePath.join(tempDir, "codex-home");
|
||||
const shadowHome = NodePath.join(tempDir, "codex-shadow");
|
||||
const binaryPath = NodePath.join(sharedHome, "packages", "standalone", "bin", "codex");
|
||||
yield* fs.makeDirectory(NodePath.dirname(binaryPath), { recursive: true });
|
||||
yield* fs.writeFileString(binaryPath, "#!/bin/sh\n");
|
||||
yield* fs.chmod(binaryPath, 0o755);
|
||||
|
||||
const instance = yield* CodexDriver.create({
|
||||
instanceId: ProviderInstanceId.make("codex-shadow"),
|
||||
displayName: "Codex test",
|
||||
enabled: false,
|
||||
environment: [],
|
||||
config: {
|
||||
...CodexDriver.defaultConfig(),
|
||||
binaryPath,
|
||||
homePath: sharedHome,
|
||||
shadowHomePath: shadowHome,
|
||||
},
|
||||
});
|
||||
|
||||
const capabilities = yield* instance.snapshot.resolveMaintenance();
|
||||
expect(capabilities.update).toMatchObject({
|
||||
executable: binaryPath,
|
||||
args: ["update"],
|
||||
lockKey: "codex-native",
|
||||
env: { CODEX_HOME: sharedHome },
|
||||
});
|
||||
}).pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn),
|
||||
Effect.scoped,
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("stays manual-only when the configured executable does not exist", () =>
|
||||
Effect.gen(function* () {
|
||||
const instance = yield* CodexDriver.create({
|
||||
instanceId: ProviderInstanceId.make("codex-missing"),
|
||||
displayName: "Codex test",
|
||||
enabled: false,
|
||||
environment: [],
|
||||
config: {
|
||||
...CodexDriver.defaultConfig(),
|
||||
binaryPath: NodePath.join(NodeOS.tmpdir(), "t3-codex-missing", "codex"),
|
||||
},
|
||||
});
|
||||
expect((yield* instance.snapshot.resolveMaintenance()).update).toBeNull();
|
||||
}).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn), Effect.scoped),
|
||||
);
|
||||
});
|
||||
@@ -55,7 +55,9 @@ import { withInstanceIdentity } from "./instanceIdentity.ts";
|
||||
import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
|
||||
import {
|
||||
enrichProviderSnapshotWithVersionAdvisory,
|
||||
makeCachedProviderMaintenanceResolution,
|
||||
makePackageManagedProviderMaintenanceResolver,
|
||||
normalizeCommandPath,
|
||||
resolveProviderMaintenanceCapabilitiesEffect,
|
||||
} from "../providerMaintenance.ts";
|
||||
import {
|
||||
@@ -71,12 +73,29 @@ import {
|
||||
const decodeCodexSettings = Schema.decodeSync(CodexSettings);
|
||||
|
||||
const DRIVER_KIND = ProviderDriverKind.make("codex");
|
||||
const UPDATE = makePackageManagedProviderMaintenanceResolver({
|
||||
provider: DRIVER_KIND,
|
||||
npmPackageName: "@openai/codex",
|
||||
homebrewFormula: "codex",
|
||||
nativeUpdate: null,
|
||||
});
|
||||
// The standalone installer lays out `<CODEX_HOME>/packages/standalone/…`;
|
||||
// CODEX_HOME is not always `~/.codex`.
|
||||
function isCodexStandaloneCommandPath(commandPath: string): boolean {
|
||||
return normalizeCommandPath(commandPath).includes("/packages/standalone/");
|
||||
}
|
||||
|
||||
/**
|
||||
* `codex update` replaces the standalone tree under `CODEX_HOME`. That tree
|
||||
* lives in the shared home even when an auth-overlay shadow home is in use
|
||||
* (the overlay only carries auth and a few local entries), so the updater
|
||||
* runs against `sharedHomePath` rather than the instance's effective home.
|
||||
*/
|
||||
function makeCodexMaintenanceResolver(sharedHomePath: string) {
|
||||
return makePackageManagedProviderMaintenanceResolver({
|
||||
provider: DRIVER_KIND,
|
||||
npmPackageName: "@openai/codex",
|
||||
nativeUpdate: {
|
||||
args: ["update"],
|
||||
isCommandPath: isCodexStandaloneCommandPath,
|
||||
env: { CODEX_HOME: sharedHomePath },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Services the driver needs to materialize an instance. Surfaced as the
|
||||
@@ -108,6 +127,8 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const resetCreditCoordinator = yield* CodexResetCreditCoordinator;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const pathService = yield* Path.Path;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const eventLoggers = yield* ProviderEventLoggers;
|
||||
@@ -138,10 +159,19 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
|
||||
enabled,
|
||||
homePath: homeLayout.effectiveHomePath ?? "",
|
||||
} satisfies CodexSettings;
|
||||
const maintenanceCapabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
|
||||
binaryPath: effectiveConfig.binaryPath,
|
||||
env: processEnv,
|
||||
});
|
||||
const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution(
|
||||
resolveProviderMaintenanceCapabilitiesEffect(
|
||||
makeCodexMaintenanceResolver(homeLayout.sharedHomePath),
|
||||
{
|
||||
binaryPath: effectiveConfig.binaryPath,
|
||||
env: processEnv,
|
||||
},
|
||||
).pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(Path.Path, pathService),
|
||||
),
|
||||
);
|
||||
|
||||
// `makeCodexAdapter` and `makeCodexTextGeneration` have `never` error
|
||||
// channels at construction time — their failure modes are all on the
|
||||
@@ -177,7 +207,7 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
|
||||
);
|
||||
const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);
|
||||
const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<CodexSettings>>({
|
||||
maintenanceCapabilities,
|
||||
resolveMaintenance,
|
||||
getSettings: snapshotSettings.getSettings,
|
||||
streamSettings: snapshotSettings.streamSettings,
|
||||
haveSettingsChanged: haveProviderSnapshotSettingsChanged,
|
||||
@@ -190,9 +220,12 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {
|
||||
),
|
||||
checkProvider,
|
||||
enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>
|
||||
enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {
|
||||
enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
|
||||
}).pipe(
|
||||
resolveMaintenance().pipe(
|
||||
Effect.flatMap((maintenanceCapabilities) =>
|
||||
enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {
|
||||
enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
|
||||
}),
|
||||
),
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
|
||||
),
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as NodeOS from "node:os";
|
||||
import * as NodePath from "node:path";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import { ProviderInstanceId } from "@t3tools/contracts";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
@@ -32,26 +36,59 @@ const testLayer = ServerConfig.layerTest(process.cwd(), {
|
||||
),
|
||||
);
|
||||
|
||||
// The `#!/bin/sh` stub below cannot be resolved as an executable on Windows.
|
||||
const windowsHost = HostProcessPlatform.defaultValue() === "win32";
|
||||
|
||||
it.layer(testLayer)("CursorDriver", (it) => {
|
||||
it.effect("formats a copied update command for the injected Windows environment", () =>
|
||||
it.effect.skipIf(windowsHost)(
|
||||
"quotes a configured executable path in the copyable update command",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cursor-driver-" });
|
||||
const binaryPath = NodePath.join(tempDir, "Cursor Tools", "bin", "cursor-agent");
|
||||
yield* fs.makeDirectory(NodePath.dirname(binaryPath), { recursive: true });
|
||||
yield* fs.writeFileString(binaryPath, "#!/bin/sh\n");
|
||||
yield* fs.chmod(binaryPath, 0o755);
|
||||
|
||||
const instance = yield* CursorDriver.create({
|
||||
instanceId: ProviderInstanceId.make("cursor-copy-command"),
|
||||
displayName: "Cursor test",
|
||||
enabled: false,
|
||||
environment: [],
|
||||
config: { ...CursorDriver.defaultConfig(), binaryPath },
|
||||
});
|
||||
|
||||
const capabilities = yield* instance.snapshot.resolveMaintenance();
|
||||
expect(capabilities.update).toMatchObject({
|
||||
command: `'${binaryPath}' update`,
|
||||
executable: binaryPath,
|
||||
args: ["update"],
|
||||
});
|
||||
expect((yield* instance.snapshot.refresh).status).toBe("disabled");
|
||||
}).pipe(
|
||||
Effect.provideService(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() => Effect.die("Disabled Cursor must not spawn a process")),
|
||||
),
|
||||
Effect.scoped,
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("stays manual-only when the configured executable does not exist", () =>
|
||||
Effect.gen(function* () {
|
||||
const binaryPath = "C:\\Users\\Example User\\.local\\bin\\cursor-agent.exe";
|
||||
const instance = yield* CursorDriver.create({
|
||||
instanceId: ProviderInstanceId.make("cursor-copy-command"),
|
||||
instanceId: ProviderInstanceId.make("cursor-missing"),
|
||||
displayName: "Cursor test",
|
||||
enabled: false,
|
||||
environment: [],
|
||||
config: { ...CursorDriver.defaultConfig(), binaryPath },
|
||||
config: {
|
||||
...CursorDriver.defaultConfig(),
|
||||
binaryPath: NodePath.join(NodeOS.tmpdir(), "t3-cursor-missing", "cursor-agent"),
|
||||
},
|
||||
});
|
||||
|
||||
expect(instance.snapshot.maintenanceCapabilities.update).toMatchObject({
|
||||
command: `& '${binaryPath}' update`,
|
||||
executable: binaryPath,
|
||||
args: ["update"],
|
||||
});
|
||||
expect((yield* instance.snapshot.refresh).status).toBe("disabled");
|
||||
expect((yield* instance.snapshot.resolveMaintenance()).update).toBeNull();
|
||||
}).pipe(
|
||||
Effect.provideService(HostProcessPlatform, "win32"),
|
||||
Effect.provideService(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() => Effect.die("Disabled Cursor must not spawn a process")),
|
||||
|
||||
@@ -41,6 +41,8 @@ import {
|
||||
import { withInstanceIdentity } from "./instanceIdentity.ts";
|
||||
import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
|
||||
import {
|
||||
makeCachedProviderMaintenanceResolution,
|
||||
makeManualOnlyProviderMaintenanceCapabilities,
|
||||
makeProviderMaintenanceCapabilities,
|
||||
type ProviderMaintenanceCapabilitiesResolver,
|
||||
resolveProviderMaintenanceCapabilitiesEffect,
|
||||
@@ -54,16 +56,25 @@ import { probeCursorSkills } from "./CursorSkills.ts";
|
||||
const decodeCursorSettings = Schema.decodeSync(CursorSettings);
|
||||
|
||||
const DRIVER_KIND = ProviderDriverKind.make("cursor");
|
||||
// cursor-agent updates itself, so the resolved executable is its own updater.
|
||||
// No executable means nothing to update, not "whatever is on PATH".
|
||||
const UPDATE: ProviderMaintenanceCapabilitiesResolver = {
|
||||
resolve: (options) =>
|
||||
makeProviderMaintenanceCapabilities({
|
||||
provider: DRIVER_KIND,
|
||||
packageName: null,
|
||||
updateExecutable: options?.binaryPath?.trim() || "cursor-agent",
|
||||
updateArgs: ["update"],
|
||||
updateLockKey: "cursor-agent",
|
||||
...(options?.platform ? { platform: options.platform } : {}),
|
||||
}),
|
||||
resolve: (context) =>
|
||||
Effect.succeed(
|
||||
context
|
||||
? makeProviderMaintenanceCapabilities({
|
||||
provider: DRIVER_KIND,
|
||||
packageName: null,
|
||||
updateExecutable: context.resolvedCommandPath,
|
||||
updateArgs: ["update"],
|
||||
updateLockKey: "cursor-agent",
|
||||
platform: context.platform,
|
||||
})
|
||||
: makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: DRIVER_KIND,
|
||||
packageName: null,
|
||||
}),
|
||||
),
|
||||
};
|
||||
|
||||
export type CursorDriverEnv =
|
||||
@@ -107,10 +118,16 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
|
||||
continuationGroupKey: continuationIdentity.continuationKey,
|
||||
});
|
||||
const effectiveConfig = { ...config, enabled } satisfies CursorSettings;
|
||||
const maintenanceCapabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
|
||||
binaryPath: effectiveConfig.binaryPath,
|
||||
env: processEnv,
|
||||
});
|
||||
const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution(
|
||||
resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
|
||||
binaryPath: effectiveConfig.binaryPath,
|
||||
env: processEnv,
|
||||
}).pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(Path.Path, path),
|
||||
),
|
||||
);
|
||||
|
||||
const adapter = yield* makeCursorAdapter(effectiveConfig, {
|
||||
environment: processEnv,
|
||||
@@ -129,7 +146,7 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
|
||||
|
||||
const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);
|
||||
const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<CursorSettings>>({
|
||||
maintenanceCapabilities,
|
||||
resolveMaintenance,
|
||||
getSettings: snapshotSettings.getSettings,
|
||||
streamSettings: snapshotSettings.streamSettings,
|
||||
haveSettingsChanged: haveProviderSnapshotSettingsChanged,
|
||||
@@ -139,15 +156,20 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
|
||||
// Model catalog and capabilities come exclusively from Cursor's
|
||||
// list_available_models extension method during provider checks.
|
||||
enrichSnapshot: ({ settings, snapshot: currentSnapshot, publishSnapshot }) =>
|
||||
enrichCursorSnapshot({
|
||||
settings: settings.provider,
|
||||
snapshot: currentSnapshot,
|
||||
maintenanceCapabilities,
|
||||
enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
|
||||
publishSnapshot,
|
||||
stampIdentity,
|
||||
httpClient,
|
||||
}).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner)),
|
||||
resolveMaintenance().pipe(
|
||||
Effect.flatMap((maintenanceCapabilities) =>
|
||||
enrichCursorSnapshot({
|
||||
settings: settings.provider,
|
||||
snapshot: currentSnapshot,
|
||||
maintenanceCapabilities,
|
||||
enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
|
||||
publishSnapshot,
|
||||
stampIdentity,
|
||||
httpClient,
|
||||
}),
|
||||
),
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
),
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
|
||||
@@ -28,11 +28,7 @@ import {
|
||||
import { withInstanceIdentity } from "./instanceIdentity.ts";
|
||||
import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
|
||||
import { discoverGrokSkills } from "./GrokSkills.ts";
|
||||
import {
|
||||
makeManualOnlyProviderMaintenanceCapabilities,
|
||||
makeStaticProviderMaintenanceResolver,
|
||||
resolveProviderMaintenanceCapabilitiesEffect,
|
||||
} from "../providerMaintenance.ts";
|
||||
import { makeManualOnlyProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
|
||||
import {
|
||||
haveProviderSnapshotSettingsChanged,
|
||||
makeProviderSnapshotSettingsSource,
|
||||
@@ -41,12 +37,10 @@ import {
|
||||
const decodeGrokSettings = Schema.decodeSync(GrokSettings);
|
||||
|
||||
const DRIVER_KIND = ProviderDriverKind.make("grok");
|
||||
const UPDATE = makeStaticProviderMaintenanceResolver(
|
||||
makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: DRIVER_KIND,
|
||||
packageName: null,
|
||||
}),
|
||||
);
|
||||
const MAINTENANCE_CAPABILITIES = makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: DRIVER_KIND,
|
||||
packageName: null,
|
||||
});
|
||||
|
||||
export type GrokDriverEnv =
|
||||
| BackgroundPolicy.BackgroundPolicy
|
||||
@@ -88,11 +82,6 @@ export const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv> = {
|
||||
continuationGroupKey: continuationIdentity.continuationKey,
|
||||
});
|
||||
const effectiveConfig = { ...config, enabled } satisfies GrokSettings;
|
||||
const maintenanceCapabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
|
||||
binaryPath: effectiveConfig.binaryPath,
|
||||
env: processEnv,
|
||||
});
|
||||
|
||||
const adapter = yield* makeGrokAdapter(effectiveConfig, {
|
||||
environment: processEnv,
|
||||
...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),
|
||||
@@ -108,7 +97,7 @@ export const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv> = {
|
||||
|
||||
const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);
|
||||
const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<GrokSettings>>({
|
||||
maintenanceCapabilities,
|
||||
resolveMaintenance: () => Effect.succeed(MAINTENANCE_CAPABILITIES),
|
||||
getSettings: snapshotSettings.getSettings,
|
||||
streamSettings: snapshotSettings.streamSettings,
|
||||
haveSettingsChanged: haveProviderSnapshotSettingsChanged,
|
||||
@@ -118,7 +107,7 @@ export const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv> = {
|
||||
enrichSnapshot: ({ settings, snapshot: currentSnapshot, publishSnapshot }) =>
|
||||
enrichGrokSnapshot({
|
||||
snapshot: currentSnapshot,
|
||||
maintenanceCapabilities,
|
||||
maintenanceCapabilities: MAINTENANCE_CAPABILITIES,
|
||||
enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
|
||||
publishSnapshot,
|
||||
httpClient,
|
||||
|
||||
@@ -45,6 +45,7 @@ import { withInstanceIdentity } from "./instanceIdentity.ts";
|
||||
import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
|
||||
import {
|
||||
enrichProviderSnapshotWithVersionAdvisory,
|
||||
makeCachedProviderMaintenanceResolution,
|
||||
makePackageManagedProviderMaintenanceResolver,
|
||||
normalizeCommandPath,
|
||||
resolveProviderMaintenanceCapabilitiesEffect,
|
||||
@@ -69,11 +70,8 @@ function isOpenCodeNativeCommandPath(commandPath: string): boolean {
|
||||
const UPDATE = makePackageManagedProviderMaintenanceResolver({
|
||||
provider: DRIVER_KIND,
|
||||
npmPackageName: "opencode-ai",
|
||||
homebrewFormula: "anomalyco/tap/opencode",
|
||||
nativeUpdate: {
|
||||
executable: "opencode",
|
||||
args: ["upgrade"],
|
||||
lockKey: "opencode-native",
|
||||
isCommandPath: isOpenCodeNativeCommandPath,
|
||||
},
|
||||
});
|
||||
@@ -100,6 +98,9 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
|
||||
defaultConfig: (): OpenCodeSettings => decodeOpenCodeSettings({}),
|
||||
create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const pathService = yield* Path.Path;
|
||||
const openCodeRuntime = yield* OpenCodeRuntime;
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
@@ -118,10 +119,16 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
|
||||
continuationGroupKey: continuationIdentity.continuationKey,
|
||||
});
|
||||
const effectiveConfig = { ...config, enabled } satisfies OpenCodeSettings;
|
||||
const maintenanceCapabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
|
||||
binaryPath: effectiveConfig.binaryPath,
|
||||
env: processEnv,
|
||||
});
|
||||
const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution(
|
||||
resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
|
||||
binaryPath: effectiveConfig.binaryPath,
|
||||
env: processEnv,
|
||||
}).pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(Path.Path, pathService),
|
||||
),
|
||||
);
|
||||
|
||||
const adapter = yield* makeOpenCodeAdapter(effectiveConfig, {
|
||||
instanceId,
|
||||
@@ -195,7 +202,7 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
|
||||
const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);
|
||||
const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<OpenCodeSettings>>(
|
||||
{
|
||||
maintenanceCapabilities,
|
||||
resolveMaintenance,
|
||||
getSettings: snapshotSettings.getSettings,
|
||||
streamSettings: snapshotSettings.streamSettings,
|
||||
haveSettingsChanged: haveProviderSnapshotSettingsChanged,
|
||||
@@ -205,9 +212,12 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
|
||||
makePendingOpenCodeProvider(settings.provider).pipe(Effect.map(stampIdentity)),
|
||||
checkProvider,
|
||||
enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>
|
||||
enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {
|
||||
enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
|
||||
}).pipe(
|
||||
resolveMaintenance().pipe(
|
||||
Effect.flatMap((maintenanceCapabilities) =>
|
||||
enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {
|
||||
enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
|
||||
}),
|
||||
),
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
|
||||
),
|
||||
|
||||
@@ -232,13 +232,14 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func
|
||||
return yield* options.stampIdentity(next.draft);
|
||||
});
|
||||
|
||||
const maintenanceCapabilities =
|
||||
options.maintenanceCapabilities ??
|
||||
makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: ProviderDriverKind.make("antigravity"),
|
||||
packageName: null,
|
||||
});
|
||||
const managed = yield* makeManagedServerProvider({
|
||||
maintenanceCapabilities:
|
||||
options.maintenanceCapabilities ??
|
||||
makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: ProviderDriverKind.make("antigravity"),
|
||||
packageName: null,
|
||||
}),
|
||||
resolveMaintenance: () => Effect.succeed(maintenanceCapabilities),
|
||||
getSettings: Effect.succeed(settings),
|
||||
streamSettings: Stream.empty,
|
||||
haveSettingsChanged: () => false,
|
||||
|
||||
@@ -111,10 +111,13 @@ const makeFakeInstance = (
|
||||
displayName: undefined,
|
||||
enabled: true,
|
||||
snapshot: {
|
||||
maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: driverKind,
|
||||
packageName: null,
|
||||
}),
|
||||
resolveMaintenance: () =>
|
||||
Effect.succeed(
|
||||
makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: driverKind,
|
||||
packageName: null,
|
||||
}),
|
||||
),
|
||||
getSnapshot: Effect.succeed({} as unknown as ServerProvider),
|
||||
refresh: Effect.succeed({} as unknown as ServerProvider),
|
||||
streamChanges: Stream.empty,
|
||||
|
||||
@@ -1033,10 +1033,13 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
displayName: undefined,
|
||||
enabled: true,
|
||||
snapshot: {
|
||||
maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: cachedProvider.driver,
|
||||
packageName: null,
|
||||
}),
|
||||
resolveMaintenance: () =>
|
||||
Effect.succeed(
|
||||
makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: cachedProvider.driver,
|
||||
packageName: null,
|
||||
}),
|
||||
),
|
||||
getSnapshot: Effect.succeed(pendingProvider),
|
||||
refresh: Ref.get(nextProvider),
|
||||
streamChanges: Stream.empty,
|
||||
@@ -1288,10 +1291,13 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
displayName: undefined,
|
||||
enabled: true,
|
||||
snapshot: {
|
||||
maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: codexDriver,
|
||||
packageName: null,
|
||||
}),
|
||||
resolveMaintenance: () =>
|
||||
Effect.succeed(
|
||||
makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: codexDriver,
|
||||
packageName: null,
|
||||
}),
|
||||
),
|
||||
getSnapshot: Effect.succeed(initialProvider),
|
||||
refresh: Ref.update(refreshCalls, (count) => count + 1).pipe(
|
||||
Effect.andThen(Effect.never),
|
||||
@@ -1380,10 +1386,13 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
displayName: undefined,
|
||||
enabled: true,
|
||||
snapshot: {
|
||||
maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: driver,
|
||||
packageName: null,
|
||||
}),
|
||||
resolveMaintenance: () =>
|
||||
Effect.succeed(
|
||||
makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: driver,
|
||||
packageName: null,
|
||||
}),
|
||||
),
|
||||
getSnapshot: Effect.succeed(provider),
|
||||
refresh: Effect.succeed(provider),
|
||||
streamChanges: Stream.empty,
|
||||
@@ -1569,10 +1578,13 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
displayName: undefined,
|
||||
enabled: true,
|
||||
snapshot: {
|
||||
maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: codexDriver,
|
||||
packageName: null,
|
||||
}),
|
||||
resolveMaintenance: () =>
|
||||
Effect.succeed(
|
||||
makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: codexDriver,
|
||||
packageName: null,
|
||||
}),
|
||||
),
|
||||
getSnapshot: Effect.succeed(codexProvider),
|
||||
refresh: Ref.update(codexRefreshCalls, (count) => count + 1).pipe(
|
||||
Effect.as(codexProvider),
|
||||
@@ -1593,10 +1605,13 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
displayName: undefined,
|
||||
enabled: true,
|
||||
snapshot: {
|
||||
maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: openCodeDriver,
|
||||
packageName: null,
|
||||
}),
|
||||
resolveMaintenance: () =>
|
||||
Effect.succeed(
|
||||
makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: openCodeDriver,
|
||||
packageName: null,
|
||||
}),
|
||||
),
|
||||
getSnapshot: Effect.succeed(failedOpenCodeProvider),
|
||||
refresh: Ref.update(openCodeRefreshCalls, (count) => count + 1).pipe(
|
||||
Effect.andThen(Ref.get(catalogSnapshot)),
|
||||
@@ -1717,10 +1732,13 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
displayName: undefined,
|
||||
enabled: true,
|
||||
snapshot: {
|
||||
maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: cursorDriver,
|
||||
packageName: null,
|
||||
}),
|
||||
resolveMaintenance: () =>
|
||||
Effect.succeed(
|
||||
makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: cursorDriver,
|
||||
packageName: null,
|
||||
}),
|
||||
),
|
||||
getSnapshot: Effect.succeed(initialProvider),
|
||||
refresh: Effect.succeed(refreshedProvider),
|
||||
streamChanges: Stream.fromPubSub(changes),
|
||||
@@ -1839,10 +1857,13 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
displayName: undefined,
|
||||
enabled: true,
|
||||
snapshot: {
|
||||
maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: openCodeDriver,
|
||||
packageName: null,
|
||||
}),
|
||||
resolveMaintenance: () =>
|
||||
Effect.succeed(
|
||||
makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: openCodeDriver,
|
||||
packageName: null,
|
||||
}),
|
||||
),
|
||||
getSnapshot: Effect.succeed(initialProvider),
|
||||
refresh: Effect.succeed(authoritativeProvider),
|
||||
streamChanges: Stream.fromPubSub(changes),
|
||||
@@ -1939,10 +1960,13 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
displayName: undefined,
|
||||
enabled: true,
|
||||
snapshot: {
|
||||
maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: codexDriver,
|
||||
packageName: null,
|
||||
}),
|
||||
resolveMaintenance: () =>
|
||||
Effect.succeed(
|
||||
makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: codexDriver,
|
||||
packageName: null,
|
||||
}),
|
||||
),
|
||||
getSnapshot: Effect.succeed(cachedProvider),
|
||||
refresh: Effect.die(new Error("simulated refresh failure")),
|
||||
streamChanges: Stream.empty,
|
||||
@@ -2033,10 +2057,13 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
displayName: undefined,
|
||||
enabled: true,
|
||||
snapshot: {
|
||||
maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: provider.driver,
|
||||
packageName: null,
|
||||
}),
|
||||
resolveMaintenance: () =>
|
||||
Effect.succeed(
|
||||
makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: provider.driver,
|
||||
packageName: null,
|
||||
}),
|
||||
),
|
||||
getSnapshot: Effect.succeed(provider),
|
||||
refresh: Effect.succeed(provider),
|
||||
streamChanges: Stream.empty,
|
||||
|
||||
@@ -532,14 +532,19 @@ export const ProviderRegistryLive = Layer.effect(
|
||||
|
||||
const getProviderMaintenanceCapabilitiesForInstance = Effect.fn(
|
||||
"getProviderMaintenanceCapabilitiesForInstance",
|
||||
)(function* (instanceId: ProviderInstanceId, provider: ProviderDriverKind) {
|
||||
const instance = Array.from((yield* Ref.get(liveSubsRef)).values()).find(
|
||||
(candidate) => candidate.instanceId === instanceId,
|
||||
);
|
||||
return (
|
||||
instance?.snapshot.maintenanceCapabilities ??
|
||||
makeManualProviderMaintenanceCapabilities(provider)
|
||||
);
|
||||
)(function* (
|
||||
instanceId: ProviderInstanceId,
|
||||
provider: ProviderDriverKind,
|
||||
options?: { readonly fresh?: boolean },
|
||||
) {
|
||||
// Read the instance registry, not `liveSubsRef`: the latter trails
|
||||
// reconciliation, and an update must never run a retired instance's
|
||||
// command against a freshly configured executable.
|
||||
const instance = yield* instanceRegistry.getInstance(instanceId);
|
||||
if (!instance || instance.driverKind !== provider) {
|
||||
return makeManualProviderMaintenanceCapabilities(provider);
|
||||
}
|
||||
return yield* instance.snapshot.resolveMaintenance(options);
|
||||
});
|
||||
|
||||
/**
|
||||
|
||||
@@ -56,10 +56,12 @@ export interface ProviderRegistryShape {
|
||||
/**
|
||||
* Resolve the maintenance capabilities owned by one live provider instance.
|
||||
* Falls back to manual-only capabilities when the instance is not live.
|
||||
* `fresh` re-derives ownership from the executable instead of the cache.
|
||||
*/
|
||||
readonly getProviderMaintenanceCapabilitiesForInstance: (
|
||||
instanceId: ProviderInstanceId,
|
||||
provider: ProviderDriverKind,
|
||||
options?: { readonly fresh?: boolean },
|
||||
) => Effect.Effect<ProviderMaintenanceCapabilities>;
|
||||
|
||||
/**
|
||||
|
||||
@@ -4,7 +4,14 @@ import type * as Stream from "effect/Stream";
|
||||
import type { ProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
|
||||
|
||||
export interface ServerProviderShape {
|
||||
readonly maintenanceCapabilities: ProviderMaintenanceCapabilities;
|
||||
/**
|
||||
* Ownership-derived update capabilities. Cached between reads; pass
|
||||
* `{ fresh: true }` before executing an update so it never trusts a
|
||||
* resolution older than the click.
|
||||
*/
|
||||
readonly resolveMaintenance: (options?: {
|
||||
readonly fresh?: boolean;
|
||||
}) => Effect.Effect<ProviderMaintenanceCapabilities>;
|
||||
readonly getSnapshot: Effect.Effect<ServerProvider>;
|
||||
readonly refresh: Effect.Effect<ServerProvider>;
|
||||
readonly streamChanges: Stream.Stream<ServerProvider>;
|
||||
|
||||
@@ -158,7 +158,7 @@ describe("makeManagedServerProvider", () => {
|
||||
const checkCalls = yield* Ref.make(0);
|
||||
const releaseCheck = yield* Deferred.make<void>();
|
||||
const provider = yield* makeManagedServerProvider<TestSettings>({
|
||||
maintenanceCapabilities,
|
||||
resolveMaintenance: () => Effect.succeed(maintenanceCapabilities),
|
||||
getSettings: Effect.succeed({ enabled: true }),
|
||||
streamSettings: Stream.empty,
|
||||
haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,
|
||||
@@ -198,7 +198,7 @@ describe("makeManagedServerProvider", () => {
|
||||
const checkCalls = yield* Ref.make(0);
|
||||
const initialCheckDone = yield* Deferred.make<void>();
|
||||
yield* makeManagedServerProvider<TestSettings>({
|
||||
maintenanceCapabilities,
|
||||
resolveMaintenance: () => Effect.succeed(maintenanceCapabilities),
|
||||
getSettings: Effect.succeed({ enabled: true }),
|
||||
streamSettings: Stream.empty,
|
||||
haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,
|
||||
@@ -229,7 +229,7 @@ describe("makeManagedServerProvider", () => {
|
||||
const checkCalls = yield* Ref.make(0);
|
||||
const initialCheckDone = yield* Deferred.make<void>();
|
||||
yield* makeManagedServerProvider<TestSettings>({
|
||||
maintenanceCapabilities,
|
||||
resolveMaintenance: () => Effect.succeed(maintenanceCapabilities),
|
||||
getSettings: Effect.succeed({ enabled: true }),
|
||||
streamSettings: Stream.empty,
|
||||
haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,
|
||||
@@ -256,7 +256,7 @@ describe("makeManagedServerProvider", () => {
|
||||
const checkCalls = yield* Ref.make(0);
|
||||
const initialCheckDone = yield* Deferred.make<void>();
|
||||
const provider = yield* makeManagedServerProvider<TestSettings>({
|
||||
maintenanceCapabilities,
|
||||
resolveMaintenance: () => Effect.succeed(maintenanceCapabilities),
|
||||
getSettings: Effect.succeed({ enabled: true }),
|
||||
streamSettings: Stream.empty,
|
||||
haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,
|
||||
@@ -311,7 +311,7 @@ describe("makeManagedServerProvider", () => {
|
||||
const periodicCheckDone = yield* Deferred.make<void>();
|
||||
|
||||
yield* makeManagedServerProvider<TestSettings>({
|
||||
maintenanceCapabilities,
|
||||
resolveMaintenance: () => Effect.succeed(maintenanceCapabilities),
|
||||
getSettings: Effect.succeed({ enabled: true }),
|
||||
streamSettings: Stream.empty,
|
||||
haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,
|
||||
@@ -353,7 +353,7 @@ describe("makeManagedServerProvider", () => {
|
||||
const releaseInitialCheck = yield* Deferred.make<void>();
|
||||
const releaseSettingsCheck = yield* Deferred.make<void>();
|
||||
const provider = yield* makeManagedServerProvider<TestSettings>({
|
||||
maintenanceCapabilities,
|
||||
resolveMaintenance: () => Effect.succeed(maintenanceCapabilities),
|
||||
getSettings: Ref.get(settingsRef),
|
||||
streamSettings: Stream.fromPubSub(settingsChanges),
|
||||
haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,
|
||||
@@ -397,7 +397,7 @@ describe("makeManagedServerProvider", () => {
|
||||
const initialCheckDone = yield* Deferred.make<void>();
|
||||
const enrichmentCalls = yield* Ref.make(0);
|
||||
yield* makeManagedServerProvider<TestSettings>({
|
||||
maintenanceCapabilities,
|
||||
resolveMaintenance: () => Effect.succeed(maintenanceCapabilities),
|
||||
getSettings: Effect.succeed({ enabled: true }),
|
||||
streamSettings: Stream.fromPubSub(settingsChanges),
|
||||
haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,
|
||||
@@ -430,7 +430,7 @@ describe("makeManagedServerProvider", () => {
|
||||
const releaseEnrichment = yield* Deferred.make<void>();
|
||||
const releaseCheck = yield* Deferred.make<void>();
|
||||
const provider = yield* makeManagedServerProvider<TestSettings>({
|
||||
maintenanceCapabilities,
|
||||
resolveMaintenance: () => Effect.succeed(maintenanceCapabilities),
|
||||
getSettings: Effect.succeed({ enabled: true }),
|
||||
streamSettings: Stream.empty,
|
||||
haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,
|
||||
@@ -471,7 +471,7 @@ describe("makeManagedServerProvider", () => {
|
||||
const secondCallbackReady = yield* Deferred.make<void>();
|
||||
const allowFirstRefresh = yield* Deferred.make<void>();
|
||||
const provider = yield* makeManagedServerProvider<TestSettings>({
|
||||
maintenanceCapabilities,
|
||||
resolveMaintenance: () => Effect.succeed(maintenanceCapabilities),
|
||||
getSettings: Effect.succeed({ enabled: true }),
|
||||
streamSettings: Stream.empty,
|
||||
haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,
|
||||
@@ -527,7 +527,7 @@ describe("makeManagedServerProvider", () => {
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* makeManagedServerProvider<TestSettings>({
|
||||
maintenanceCapabilities,
|
||||
resolveMaintenance: () => Effect.succeed(maintenanceCapabilities),
|
||||
getSettings: Effect.succeed({ enabled: true }),
|
||||
streamSettings: Stream.empty,
|
||||
haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,
|
||||
@@ -595,7 +595,7 @@ describe("makeManagedServerProvider", () => {
|
||||
windows: [{ id: "primary", kind: "session", label: "Session", usedPercent: 10 }],
|
||||
} as const;
|
||||
const provider = yield* makeManagedServerProvider<TestSettings>({
|
||||
maintenanceCapabilities,
|
||||
resolveMaintenance: () => Effect.succeed(maintenanceCapabilities),
|
||||
getSettings: Effect.succeed({ enabled: true }),
|
||||
streamSettings: Stream.empty,
|
||||
haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,
|
||||
|
||||
@@ -39,7 +39,7 @@ function withUsageLimits(
|
||||
export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(function* <
|
||||
Settings,
|
||||
>(input: {
|
||||
readonly maintenanceCapabilities: ServerProviderShape["maintenanceCapabilities"];
|
||||
readonly resolveMaintenance: ServerProviderShape["resolveMaintenance"];
|
||||
readonly getSettings: Effect.Effect<Settings, ServerSettingsError>;
|
||||
readonly streamSettings: Stream.Stream<Settings>;
|
||||
readonly haveSettingsChanged: (previous: Settings, next: Settings) => boolean;
|
||||
@@ -283,7 +283,7 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
|
||||
);
|
||||
|
||||
return {
|
||||
maintenanceCapabilities: input.maintenanceCapabilities,
|
||||
resolveMaintenance: input.resolveMaintenance,
|
||||
getSnapshot: Ref.get(snapshotStateRef).pipe(Effect.map((state) => state.snapshot)),
|
||||
refresh: refreshSnapshot().pipe(Effect.tapError(Effect.logError), Effect.orDie),
|
||||
applyUsageLimits,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -4,21 +4,37 @@ import {
|
||||
type ServerProviderVersionAdvisory,
|
||||
} from "@t3tools/contracts";
|
||||
import { compareSemverVersions } from "@t3tools/shared/semver";
|
||||
import { resolveCommandPath } from "@t3tools/shared/shell";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import { causeErrorTag } from "@t3tools/shared/observability";
|
||||
import { resolveCommandPath } from "@t3tools/shared/shell";
|
||||
import * as Config from "effect/Config";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { HttpClient, HttpClientRequest } from "effect/unstable/http";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
|
||||
|
||||
const LATEST_VERSION_CACHE_TTL_MS = 60 * 60 * 1_000;
|
||||
const LATEST_VERSION_TIMEOUT_MS = 4_000;
|
||||
const HOMEBREW_INFO_TIMEOUT_MS = 10_000;
|
||||
const HOMEBREW_INFO_MAX_BYTES = 256 * 1_024;
|
||||
const PROVIDER_UPDATE_ACTION_TOAST_MESSAGE = "Install the update now or review provider settings.";
|
||||
|
||||
/**
|
||||
* Ownership is re-derived from the executable this often. Installs do not
|
||||
* move on their own, so this mostly bounds how stale a Homebrew "latest" can
|
||||
* get; the npm registry check keeps its own cache.
|
||||
*/
|
||||
export const MAINTENANCE_CAPABILITIES_CACHE_TTL = Duration.hours(1);
|
||||
|
||||
const compactEnv = (input: Record<string, Option.Option<string>>): NodeJS.ProcessEnv =>
|
||||
Object.fromEntries(
|
||||
Object.entries(input).flatMap(([key, value]) =>
|
||||
@@ -42,6 +58,13 @@ export interface ProviderMaintenanceCapabilities {
|
||||
readonly provider: ProviderDriverKind;
|
||||
readonly packageName: string | null;
|
||||
readonly update: ProviderMaintenanceCommandAction | null;
|
||||
/**
|
||||
* Latest version reported by the installer that owns the executable.
|
||||
* `undefined` means the installer has no channel of its own and the npm
|
||||
* registry entry for `packageName` is authoritative; `null` means the
|
||||
* installer was asked and did not know.
|
||||
*/
|
||||
readonly latestVersion?: string | null;
|
||||
}
|
||||
|
||||
export interface ProviderMaintenanceCommandAction {
|
||||
@@ -49,31 +72,44 @@ export interface ProviderMaintenanceCommandAction {
|
||||
readonly executable: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly lockKey: string;
|
||||
/**
|
||||
* Extra environment for the spawned updater, on top of the server's own.
|
||||
* A native updater finds its install through the same variables the
|
||||
* provider runs with (e.g. `CODEX_HOME`), so an instance with a custom home
|
||||
* must update that home and not the default one.
|
||||
*/
|
||||
readonly env?: NodeJS.ProcessEnv;
|
||||
}
|
||||
|
||||
export interface ProviderMaintenanceCapabilityResolutionOptions {
|
||||
readonly binaryPath?: string | null;
|
||||
readonly platform?: NodeJS.Platform;
|
||||
readonly env?: NodeJS.ProcessEnv;
|
||||
readonly resolvedCommandPath?: string | null;
|
||||
readonly realCommandPath?: string | null;
|
||||
/** Where the provider executable was found; every path is absolute. */
|
||||
export interface ProviderMaintenanceResolutionContext {
|
||||
readonly binaryPath: string;
|
||||
readonly resolvedCommandPath: string;
|
||||
readonly realCommandPath: string;
|
||||
readonly env: NodeJS.ProcessEnv;
|
||||
/** Host platform; decides how the copyable command quotes the executable. */
|
||||
readonly platform: NodeJS.Platform;
|
||||
}
|
||||
|
||||
export type ProviderMaintenanceResolverServices =
|
||||
| FileSystem.FileSystem
|
||||
| Path.Path
|
||||
| ChildProcessSpawner.ChildProcessSpawner;
|
||||
|
||||
export interface ProviderMaintenanceCapabilitiesResolver {
|
||||
readonly resolve: (
|
||||
options?: ProviderMaintenanceCapabilityResolutionOptions,
|
||||
) => ProviderMaintenanceCapabilities;
|
||||
context: ProviderMaintenanceResolutionContext | null,
|
||||
) => Effect.Effect<ProviderMaintenanceCapabilities, never, ProviderMaintenanceResolverServices>;
|
||||
}
|
||||
|
||||
export interface PackageManagedProviderMaintenanceDefinition {
|
||||
readonly provider: ProviderDriverKind;
|
||||
readonly npmPackageName: string;
|
||||
readonly homebrewFormula: string | null;
|
||||
readonly nativeUpdate: {
|
||||
readonly executable: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly lockKey: string;
|
||||
readonly isCommandPath: (commandPath: string) => boolean;
|
||||
/** Environment the native updater needs to target this instance's install. */
|
||||
readonly env?: NodeJS.ProcessEnv;
|
||||
} | null;
|
||||
}
|
||||
|
||||
@@ -96,13 +132,22 @@ function nonEmptyString(value: unknown): string | null {
|
||||
return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
|
||||
}
|
||||
|
||||
function quoteUpdateExecutable(executable: string, platform: NodeJS.Platform): string {
|
||||
const safePath = platform === "win32" ? /^[\w./:\\-]+$/ : /^[\w./:-]+$/;
|
||||
if (safePath.test(executable)) return executable;
|
||||
// Windows terminals default to PowerShell, where a quoted executable needs &.
|
||||
/**
|
||||
* The copyable command must paste into a shell as-is, so an executable path
|
||||
* with spaces or quotes is quoted for the host's default shell.
|
||||
*/
|
||||
function quoteShellWord(word: string, platform: NodeJS.Platform): string {
|
||||
const safeWord = platform === "win32" ? /^[\w./:\\@=-]+$/ : /^[\w./:@=-]+$/;
|
||||
if (safeWord.test(word)) return word;
|
||||
return platform === "win32"
|
||||
? `& '${executable.replace(/['\u2018\u2019]/g, "$&$&")}'`
|
||||
: `'${executable.replaceAll("'", "'\\''")}'`;
|
||||
? `'${word.replace(/['\u2018\u2019]/g, "$&$&")}'`
|
||||
: `'${word.replaceAll("'", "'\\''")}'`;
|
||||
}
|
||||
|
||||
function quoteUpdateExecutable(executable: string, platform: NodeJS.Platform): string {
|
||||
const quoted = quoteShellWord(executable, platform);
|
||||
// Windows terminals default to PowerShell, where a quoted executable needs &.
|
||||
return platform === "win32" && quoted !== executable ? `& ${quoted}` : quoted;
|
||||
}
|
||||
|
||||
export function makeProviderMaintenanceCapabilities(input: {
|
||||
@@ -111,27 +156,33 @@ export function makeProviderMaintenanceCapabilities(input: {
|
||||
readonly updateExecutable: string | null;
|
||||
readonly updateArgs: ReadonlyArray<string>;
|
||||
readonly updateLockKey: string | null;
|
||||
/** Shown to the user instead of `<executable> <args>`; use for a bare tool name like `brew`. */
|
||||
readonly updateCommand?: string;
|
||||
readonly platform?: NodeJS.Platform;
|
||||
readonly env?: NodeJS.ProcessEnv;
|
||||
readonly latestVersion?: string | null;
|
||||
}): ProviderMaintenanceCapabilities {
|
||||
const platform = input.platform ?? HostProcessPlatform.defaultValue();
|
||||
const update =
|
||||
input.updateExecutable === null || input.updateLockKey === null
|
||||
? null
|
||||
: {
|
||||
command: [
|
||||
quoteUpdateExecutable(
|
||||
input.updateExecutable,
|
||||
input.platform ?? HostProcessPlatform.defaultValue(),
|
||||
),
|
||||
...input.updateArgs,
|
||||
].join(" "),
|
||||
command:
|
||||
input.updateCommand ??
|
||||
[
|
||||
quoteUpdateExecutable(input.updateExecutable, platform),
|
||||
...input.updateArgs.map((arg) => quoteShellWord(arg, platform)),
|
||||
].join(" "),
|
||||
executable: input.updateExecutable,
|
||||
args: input.updateArgs,
|
||||
lockKey: input.updateLockKey,
|
||||
...(input.env ? { env: input.env } : {}),
|
||||
};
|
||||
return {
|
||||
provider: input.provider,
|
||||
packageName: input.packageName,
|
||||
update,
|
||||
...("latestVersion" in input ? { latestVersion: input.latestVersion } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -148,118 +199,18 @@ export function makeManualOnlyProviderMaintenanceCapabilities(input: {
|
||||
});
|
||||
}
|
||||
|
||||
function makeNpmGlobalProviderMaintenanceCapabilities(
|
||||
definition: PackageManagedProviderMaintenanceDefinition,
|
||||
): ProviderMaintenanceCapabilities {
|
||||
return makeProviderMaintenanceCapabilities({
|
||||
provider: definition.provider,
|
||||
packageName: definition.npmPackageName,
|
||||
updateExecutable: "npm",
|
||||
// npm 12 blocks install scripts by default (empty allow-scripts allowlist)
|
||||
// and still exits 0, so a package whose postinstall finishes the install
|
||||
// (claude copies its native binary over a placeholder stub) is left broken
|
||||
// while the update reports success. Allow this one package's scripts.
|
||||
// Older npm warns about the unknown config and continues.
|
||||
updateArgs: [
|
||||
"install",
|
||||
"-g",
|
||||
`--allow-scripts=${definition.npmPackageName}`,
|
||||
`${definition.npmPackageName}@latest`,
|
||||
],
|
||||
updateLockKey: "npm-global",
|
||||
});
|
||||
}
|
||||
|
||||
function makeBunGlobalProviderMaintenanceCapabilities(
|
||||
definition: PackageManagedProviderMaintenanceDefinition,
|
||||
): ProviderMaintenanceCapabilities {
|
||||
return makeProviderMaintenanceCapabilities({
|
||||
provider: definition.provider,
|
||||
packageName: definition.npmPackageName,
|
||||
updateExecutable: "bun",
|
||||
updateArgs: ["i", "-g", `${definition.npmPackageName}@latest`],
|
||||
updateLockKey: "bun-global",
|
||||
});
|
||||
}
|
||||
|
||||
function makePnpmGlobalProviderMaintenanceCapabilities(
|
||||
definition: PackageManagedProviderMaintenanceDefinition,
|
||||
): ProviderMaintenanceCapabilities {
|
||||
return makeProviderMaintenanceCapabilities({
|
||||
provider: definition.provider,
|
||||
packageName: definition.npmPackageName,
|
||||
updateExecutable: "pnpm",
|
||||
updateArgs: ["add", "-g", `${definition.npmPackageName}@latest`],
|
||||
updateLockKey: "pnpm-global",
|
||||
});
|
||||
}
|
||||
|
||||
function makeVitePlusGlobalProviderMaintenanceCapabilities(
|
||||
definition: PackageManagedProviderMaintenanceDefinition,
|
||||
): ProviderMaintenanceCapabilities {
|
||||
return makeProviderMaintenanceCapabilities({
|
||||
provider: definition.provider,
|
||||
packageName: definition.npmPackageName,
|
||||
updateExecutable: "vp",
|
||||
updateArgs: ["i", "-g", definition.npmPackageName],
|
||||
updateLockKey: "vite-plus-global",
|
||||
});
|
||||
}
|
||||
|
||||
function makeHomebrewProviderMaintenanceCapabilities(
|
||||
definition: PackageManagedProviderMaintenanceDefinition,
|
||||
): ProviderMaintenanceCapabilities {
|
||||
if (!definition.homebrewFormula) {
|
||||
return makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: definition.provider,
|
||||
packageName: definition.npmPackageName,
|
||||
});
|
||||
}
|
||||
|
||||
return makeProviderMaintenanceCapabilities({
|
||||
provider: definition.provider,
|
||||
packageName: definition.npmPackageName,
|
||||
updateExecutable: "brew",
|
||||
updateArgs: ["upgrade", definition.homebrewFormula],
|
||||
updateLockKey: "homebrew",
|
||||
});
|
||||
}
|
||||
|
||||
function makeNativeProviderMaintenanceCapabilities(
|
||||
definition: PackageManagedProviderMaintenanceDefinition,
|
||||
commandPath: string,
|
||||
platform: NodeJS.Platform,
|
||||
): ProviderMaintenanceCapabilities | null {
|
||||
if (!definition.nativeUpdate) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return makeProviderMaintenanceCapabilities({
|
||||
provider: definition.provider,
|
||||
packageName: definition.npmPackageName,
|
||||
updateExecutable: commandPath,
|
||||
updateArgs: definition.nativeUpdate.args,
|
||||
updateLockKey: definition.nativeUpdate.lockKey,
|
||||
platform,
|
||||
});
|
||||
}
|
||||
|
||||
export function hasPathSeparator(value: string): boolean {
|
||||
return value.includes("/") || value.includes("\\");
|
||||
}
|
||||
|
||||
export function normalizeCommandPath(commandPath: string): string {
|
||||
return commandPath.replaceAll("\\", "/").toLowerCase();
|
||||
}
|
||||
|
||||
function isBunGlobalCommandPath(commandPath: string): boolean {
|
||||
return normalizeCommandPath(commandPath).includes("/.bun/bin/");
|
||||
}
|
||||
|
||||
function isVitePlusGlobalCommandPath(commandPath: string): boolean {
|
||||
return normalizeCommandPath(commandPath).includes("/.vite-plus/bin/");
|
||||
}
|
||||
|
||||
function isBunGlobalCommandPath(commandPath: string): boolean {
|
||||
return normalizeCommandPath(commandPath).includes("/.bun/bin/");
|
||||
}
|
||||
|
||||
function isPnpmGlobalCommandPath(commandPath: string): boolean {
|
||||
const normalized = normalizeCommandPath(commandPath);
|
||||
return (
|
||||
@@ -271,100 +222,287 @@ function isPnpmGlobalCommandPath(commandPath: string): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
function isNpmGlobalCommandPath(commandPath: string): boolean {
|
||||
const normalized = normalizeCommandPath(commandPath);
|
||||
return (
|
||||
normalized.includes("/node_modules/.bin/") ||
|
||||
normalized.includes("/lib/node_modules/") ||
|
||||
normalized.includes("/npm/node_modules/")
|
||||
);
|
||||
/**
|
||||
* The npm global prefix that owns a package, derived from the real path of
|
||||
* its entry point: `<prefix>/lib/node_modules/<pkg>/…`. Windows global
|
||||
* installs have no `lib` segment and are proven by the shim instead (see
|
||||
* `resolveNpmGlobalPrefix`). A project-local `node_modules` is not a global
|
||||
* install and yields null.
|
||||
*/
|
||||
export function npmGlobalPrefixFromCommandPath(
|
||||
realCommandPath: string,
|
||||
packageName: string,
|
||||
): string | null {
|
||||
const slashPath = realCommandPath.replaceAll("\\", "/");
|
||||
const normalized = slashPath.toLowerCase();
|
||||
const packageSegment = `/lib/node_modules/${packageName.toLowerCase()}/`;
|
||||
const packageIndex = normalized.lastIndexOf(packageSegment);
|
||||
if (packageIndex < 0 || normalized.slice(0, packageIndex).includes("/node_modules/")) {
|
||||
return null;
|
||||
}
|
||||
return packageIndex === 0 ? "/" : slashPath.slice(0, packageIndex);
|
||||
}
|
||||
|
||||
function isHomebrewCommandPath(commandPath: string): boolean {
|
||||
const normalized = normalizeCommandPath(commandPath);
|
||||
return (
|
||||
normalized.includes("/opt/homebrew/cellar/") ||
|
||||
normalized.includes("/usr/local/cellar/") ||
|
||||
normalized.includes("/homebrew/cellar/") ||
|
||||
normalized.includes("/opt/homebrew/caskroom/") ||
|
||||
normalized.includes("/usr/local/caskroom/") ||
|
||||
normalized.includes("/homebrew/caskroom/") ||
|
||||
normalized.startsWith("/opt/homebrew/bin/") ||
|
||||
normalized.startsWith("/usr/local/bin/")
|
||||
);
|
||||
// `<prefix>/Cellar/<name>/<version>/…` or `<prefix>/Caskroom/<name>/<version>/…`.
|
||||
// Homebrew always nests a version directory under the keg.
|
||||
const HOMEBREW_KEG_PATTERN = /^(.*)\/(cellar|caskroom)\/([^/]+)\/[^/]+\//i;
|
||||
|
||||
export interface HomebrewOwnership {
|
||||
readonly kind: "formula" | "cask";
|
||||
readonly name: string;
|
||||
/** The Homebrew prefix the keg sits under; must match `brew --prefix`. */
|
||||
readonly prefix: string;
|
||||
}
|
||||
|
||||
export function resolvePackageManagedProviderMaintenance(
|
||||
/**
|
||||
* Homebrew looks like the owner when the real path runs through a versioned
|
||||
* keg or cask. It is only proven once the prefix matches the `brew` that will
|
||||
* run the upgrade (see `resolvePackageManagedProviderMaintenance`).
|
||||
*/
|
||||
export function homebrewOwnershipFromCommandPath(
|
||||
realCommandPath: string,
|
||||
): HomebrewOwnership | null {
|
||||
const match = HOMEBREW_KEG_PATTERN.exec(realCommandPath.replaceAll("\\", "/"));
|
||||
if (!match) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
kind: match[2]!.toLowerCase() === "cellar" ? "formula" : "cask",
|
||||
name: match[3]!,
|
||||
prefix: match[1]!,
|
||||
};
|
||||
}
|
||||
|
||||
const HomebrewInfoResponse = Schema.Struct({
|
||||
formulae: Schema.optional(
|
||||
Schema.Array(
|
||||
Schema.Struct({
|
||||
versions: Schema.optional(Schema.Struct({ stable: Schema.optional(Schema.String) })),
|
||||
}),
|
||||
),
|
||||
),
|
||||
casks: Schema.optional(Schema.Array(Schema.Struct({ version: Schema.optional(Schema.String) }))),
|
||||
});
|
||||
|
||||
const decodeHomebrewInfo = Schema.decodeUnknownOption(Schema.fromJsonString(HomebrewInfoResponse));
|
||||
|
||||
/** Cask versions may carry a build suffix after a comma (`1.2.3,456`). */
|
||||
export function parseHomebrewLatestVersion(
|
||||
infoJson: string,
|
||||
ownership: HomebrewOwnership,
|
||||
): string | null {
|
||||
const decoded = decodeHomebrewInfo(infoJson);
|
||||
if (Option.isNone(decoded)) {
|
||||
return null;
|
||||
}
|
||||
const raw =
|
||||
ownership.kind === "formula"
|
||||
? decoded.value.formulae?.[0]?.versions?.stable
|
||||
: decoded.value.casks?.[0]?.version?.split(",", 1)[0];
|
||||
return nonEmptyString(raw);
|
||||
}
|
||||
|
||||
/** Run `brew <args>` and return stdout, or null on failure, timeout, or oversized output. */
|
||||
const runHomebrew = Effect.fn("runHomebrew")(function* (
|
||||
brewPath: string,
|
||||
args: ReadonlyArray<string>,
|
||||
env: NodeJS.ProcessEnv,
|
||||
) {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const collect = Effect.gen(function* () {
|
||||
const child = yield* spawner.spawn(ChildProcess.make(brewPath, args, { env, extendEnv: true }));
|
||||
yield* Effect.addFinalizer(() => child.kill().pipe(Effect.ignore));
|
||||
// stderr is drained so a chatty brew cannot block on a full pipe.
|
||||
const [stdout, exitCode] = yield* Effect.all(
|
||||
[
|
||||
collectUint8StreamText({ stream: child.stdout, maxBytes: HOMEBREW_INFO_MAX_BYTES }),
|
||||
child.exitCode,
|
||||
Stream.runDrain(child.stderr),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
return Number(exitCode) !== 0 || stdout.truncated ? null : stdout.text;
|
||||
});
|
||||
return yield* collect.pipe(
|
||||
Effect.scoped,
|
||||
Effect.timeoutOption(Duration.millis(HOMEBREW_INFO_TIMEOUT_MS)),
|
||||
Effect.map(Option.getOrNull),
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("Homebrew probe failed", {
|
||||
subcommand: args[0],
|
||||
errorTag: causeErrorTag(cause),
|
||||
}).pipe(Effect.as(null)),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* Derive update capabilities from where the executable actually lives. Every
|
||||
* branch that yields a one-click command has evidence that the named tool
|
||||
* owns that path; anything unproven stays manual-only so T3 Code never runs
|
||||
* a package manager against an install it did not create.
|
||||
*/
|
||||
export const resolvePackageManagedProviderMaintenance = Effect.fn(
|
||||
"resolvePackageManagedProviderMaintenance",
|
||||
)(function* (
|
||||
definition: PackageManagedProviderMaintenanceDefinition,
|
||||
options?: ProviderMaintenanceCapabilityResolutionOptions,
|
||||
): ProviderMaintenanceCapabilities {
|
||||
const binaryPath = nonEmptyString(options?.binaryPath);
|
||||
if (!binaryPath) {
|
||||
return makeNpmGlobalProviderMaintenanceCapabilities(definition);
|
||||
}
|
||||
|
||||
const resolvedCommandPath =
|
||||
options?.resolvedCommandPath ?? (hasPathSeparator(binaryPath) ? binaryPath : null);
|
||||
|
||||
if (resolvedCommandPath) {
|
||||
const commandPaths = [
|
||||
resolvedCommandPath,
|
||||
...(options?.realCommandPath ? [options.realCommandPath] : []),
|
||||
];
|
||||
|
||||
const nativeUpdate = definition.nativeUpdate;
|
||||
if (
|
||||
nativeUpdate &&
|
||||
commandPaths.some((commandPath) => nativeUpdate.isCommandPath(commandPath))
|
||||
) {
|
||||
return (
|
||||
makeNativeProviderMaintenanceCapabilities(
|
||||
definition,
|
||||
resolvedCommandPath,
|
||||
options?.platform ?? HostProcessPlatform.defaultValue(),
|
||||
) ?? makeNpmGlobalProviderMaintenanceCapabilities(definition)
|
||||
);
|
||||
}
|
||||
if (commandPaths.some(isVitePlusGlobalCommandPath)) {
|
||||
return makeVitePlusGlobalProviderMaintenanceCapabilities(definition);
|
||||
}
|
||||
if (commandPaths.some(isBunGlobalCommandPath)) {
|
||||
return makeBunGlobalProviderMaintenanceCapabilities(definition);
|
||||
}
|
||||
if (commandPaths.some(isPnpmGlobalCommandPath)) {
|
||||
return makePnpmGlobalProviderMaintenanceCapabilities(definition);
|
||||
}
|
||||
if (commandPaths.some(isNpmGlobalCommandPath)) {
|
||||
return makeNpmGlobalProviderMaintenanceCapabilities(definition);
|
||||
}
|
||||
if (commandPaths.some(isHomebrewCommandPath)) {
|
||||
return makeHomebrewProviderMaintenanceCapabilities(definition);
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasPathSeparator(binaryPath)) {
|
||||
return makeNpmGlobalProviderMaintenanceCapabilities(definition);
|
||||
}
|
||||
|
||||
return makeManualOnlyProviderMaintenanceCapabilities({
|
||||
context: ProviderMaintenanceResolutionContext | null,
|
||||
) {
|
||||
const manual = makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: definition.provider,
|
||||
packageName: definition.npmPackageName,
|
||||
});
|
||||
}
|
||||
if (!context) {
|
||||
return manual;
|
||||
}
|
||||
const commandPaths = [context.resolvedCommandPath, context.realCommandPath];
|
||||
const packageName = definition.npmPackageName;
|
||||
|
||||
const nativeUpdate = definition.nativeUpdate;
|
||||
if (nativeUpdate && commandPaths.some((commandPath) => nativeUpdate.isCommandPath(commandPath))) {
|
||||
return makeProviderMaintenanceCapabilities({
|
||||
provider: definition.provider,
|
||||
packageName,
|
||||
updateExecutable: context.resolvedCommandPath,
|
||||
updateArgs: nativeUpdate.args,
|
||||
updateLockKey: `${definition.provider}-native`,
|
||||
platform: context.platform,
|
||||
...(nativeUpdate.env ? { env: nativeUpdate.env } : {}),
|
||||
});
|
||||
}
|
||||
if (commandPaths.some(isVitePlusGlobalCommandPath)) {
|
||||
return makeProviderMaintenanceCapabilities({
|
||||
provider: definition.provider,
|
||||
packageName,
|
||||
updateExecutable: "vp",
|
||||
updateArgs: ["i", "-g", packageName],
|
||||
updateLockKey: "vite-plus-global",
|
||||
});
|
||||
}
|
||||
if (commandPaths.some(isBunGlobalCommandPath)) {
|
||||
return makeProviderMaintenanceCapabilities({
|
||||
provider: definition.provider,
|
||||
packageName,
|
||||
updateExecutable: "bun",
|
||||
updateArgs: ["i", "-g", `${packageName}@latest`],
|
||||
updateLockKey: "bun-global",
|
||||
});
|
||||
}
|
||||
if (commandPaths.some(isPnpmGlobalCommandPath)) {
|
||||
return makeProviderMaintenanceCapabilities({
|
||||
provider: definition.provider,
|
||||
packageName,
|
||||
updateExecutable: "pnpm",
|
||||
updateArgs: ["add", "-g", `${packageName}@latest`],
|
||||
updateLockKey: "pnpm-global",
|
||||
});
|
||||
}
|
||||
|
||||
// npm proof names the package, so it outranks a keg the path merely passes
|
||||
// through: a Homebrew-installed Node keeps its globals under
|
||||
// `Cellar/node/<ver>/lib/node_modules/`, and that is npm's install, not brew's.
|
||||
const npmPrefix = yield* resolveNpmGlobalPrefix(context, packageName);
|
||||
if (npmPrefix) {
|
||||
// npm 12 blocks install scripts by default (empty allow-scripts allowlist)
|
||||
// and still exits 0, so a package whose postinstall finishes the install
|
||||
// (claude copies its native binary over a placeholder stub) is left broken
|
||||
// while the update reports success. Allow this one package's scripts.
|
||||
// Older npm warns about the unknown config and continues.
|
||||
return makeProviderMaintenanceCapabilities({
|
||||
provider: definition.provider,
|
||||
packageName,
|
||||
updateExecutable: "npm",
|
||||
updateArgs: [
|
||||
"install",
|
||||
"-g",
|
||||
"--prefix",
|
||||
npmPrefix,
|
||||
`--allow-scripts=${packageName}`,
|
||||
`${packageName}@latest`,
|
||||
],
|
||||
updateLockKey: `npm-global:${normalizeCommandPath(npmPrefix)}`,
|
||||
});
|
||||
}
|
||||
|
||||
const homebrew = homebrewOwnershipFromCommandPath(context.realCommandPath);
|
||||
if (homebrew) {
|
||||
const brewPath = yield* resolveCommandPath("brew", { env: context.env }).pipe(
|
||||
Effect.catchTags({ CommandResolutionError: () => Effect.succeed(null) }),
|
||||
);
|
||||
if (!brewPath) {
|
||||
return manual;
|
||||
}
|
||||
// A keg-shaped path is only Homebrew's if it sits under the prefix of the
|
||||
// `brew` that would upgrade it; `brew --prefix` is a cheap shell script.
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const brewPrefix = nonEmptyString(yield* runHomebrew(brewPath, ["--prefix"], context.env));
|
||||
const realBrewPrefix = brewPrefix
|
||||
? yield* fileSystem.realPath(brewPrefix).pipe(Effect.orElseSucceed(() => brewPrefix))
|
||||
: null;
|
||||
if (
|
||||
!realBrewPrefix ||
|
||||
normalizeCommandPath(realBrewPrefix) !== normalizeCommandPath(homebrew.prefix)
|
||||
) {
|
||||
return manual;
|
||||
}
|
||||
const args =
|
||||
homebrew.kind === "cask" ? ["upgrade", "--cask", homebrew.name] : ["upgrade", homebrew.name];
|
||||
// Homebrew lags npm by hours on every release, so compare against what
|
||||
// `brew upgrade` can actually deliver.
|
||||
const info = yield* runHomebrew(brewPath, ["info", "--json=v2", homebrew.name], context.env);
|
||||
return makeProviderMaintenanceCapabilities({
|
||||
provider: definition.provider,
|
||||
packageName,
|
||||
updateExecutable: brewPath,
|
||||
updateArgs: args,
|
||||
updateLockKey: "homebrew",
|
||||
updateCommand: ["brew", ...args].join(" "),
|
||||
latestVersion: info ? parseHomebrewLatestVersion(info, homebrew) : null,
|
||||
});
|
||||
}
|
||||
|
||||
return manual;
|
||||
});
|
||||
|
||||
/**
|
||||
* POSIX npm links `<prefix>/bin/<cmd>` into the package, so the real path is
|
||||
* proof. Windows npm writes `.cmd` shims beside `node_modules`, so the proof
|
||||
* is the package manifest next to the shim.
|
||||
*/
|
||||
const resolveNpmGlobalPrefix = Effect.fn("resolveNpmGlobalPrefix")(function* (
|
||||
context: ProviderMaintenanceResolutionContext,
|
||||
packageName: string,
|
||||
) {
|
||||
const fromRealPath = npmGlobalPrefixFromCommandPath(context.realCommandPath, packageName);
|
||||
if (fromRealPath) {
|
||||
return fromRealPath;
|
||||
}
|
||||
if ((yield* HostProcessPlatform) !== "win32") {
|
||||
return null;
|
||||
}
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const shimDir = path.dirname(context.resolvedCommandPath);
|
||||
const manifestPath = path.join(
|
||||
shimDir,
|
||||
"node_modules",
|
||||
...packageName.split("/"),
|
||||
"package.json",
|
||||
);
|
||||
// npm writes both `<cmd>.cmd` and an extensionless sh script into the
|
||||
// Windows prefix; either one sits directly beside `node_modules`. A POSIX
|
||||
// project checkout has the same shape, which is why this is Windows-only.
|
||||
const hasManifest = yield* fileSystem
|
||||
.exists(manifestPath)
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
return hasManifest ? shimDir : null;
|
||||
});
|
||||
|
||||
export function makePackageManagedProviderMaintenanceResolver(
|
||||
definition: PackageManagedProviderMaintenanceDefinition,
|
||||
): ProviderMaintenanceCapabilitiesResolver {
|
||||
return {
|
||||
resolve: (options) => resolvePackageManagedProviderMaintenance(definition, options),
|
||||
};
|
||||
}
|
||||
|
||||
export function makeStaticProviderMaintenanceResolver(
|
||||
capabilities: ProviderMaintenanceCapabilities,
|
||||
): ProviderMaintenanceCapabilitiesResolver {
|
||||
return {
|
||||
resolve: () => capabilities,
|
||||
resolve: (context) => resolvePackageManagedProviderMaintenance(definition, context),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -377,40 +515,68 @@ function makeManualProviderMaintenanceCapabilities(
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Locate the configured provider executable, follow symlinks, and hand the
|
||||
* result to the resolver. A binary that cannot be found yields the resolver's
|
||||
* no-context answer.
|
||||
*/
|
||||
export const resolveProviderMaintenanceCapabilitiesEffect = Effect.fn(
|
||||
"resolveProviderMaintenanceCapabilitiesEffect",
|
||||
)(function* (
|
||||
resolver: ProviderMaintenanceCapabilitiesResolver,
|
||||
options?: Omit<ProviderMaintenanceCapabilityResolutionOptions, "realCommandPath">,
|
||||
options?: {
|
||||
readonly binaryPath?: string | null;
|
||||
readonly env?: NodeJS.ProcessEnv;
|
||||
},
|
||||
) {
|
||||
const binaryPath = nonEmptyString(options?.binaryPath);
|
||||
const platform = options?.platform ?? (yield* HostProcessPlatform);
|
||||
if (!binaryPath) {
|
||||
return resolver.resolve({ ...options, platform });
|
||||
return yield* resolver.resolve(null);
|
||||
}
|
||||
|
||||
const env = options?.env ?? (yield* readCommandLookupEnv);
|
||||
const resolvedCommandPath =
|
||||
(yield* resolveCommandPath(binaryPath, { env }).pipe(
|
||||
Effect.catchTag("CommandResolutionError", () => Effect.succeed(null)),
|
||||
)) ?? (hasPathSeparator(binaryPath) ? binaryPath : null);
|
||||
// resolveCommandPath checks explicit paths for existence too, so a missing
|
||||
// binary always lands in the no-context branch and never gets an update
|
||||
// command it cannot run.
|
||||
const resolvedCommandPath = yield* resolveCommandPath(binaryPath, { env }).pipe(
|
||||
Effect.catchTags({ CommandResolutionError: () => Effect.succeed(null) }),
|
||||
);
|
||||
if (!resolvedCommandPath) {
|
||||
return resolver.resolve({ ...options, platform });
|
||||
return yield* resolver.resolve(null);
|
||||
}
|
||||
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const realCommandPath = yield* fileSystem
|
||||
.realPath(resolvedCommandPath)
|
||||
.pipe(Effect.orElseSucceed(() => resolvedCommandPath));
|
||||
return resolver.resolve({
|
||||
...options,
|
||||
platform,
|
||||
env,
|
||||
.pipe(Effect.orElseSucceed(() => null));
|
||||
if (!realCommandPath) {
|
||||
return yield* resolver.resolve(null);
|
||||
}
|
||||
return yield* resolver.resolve({
|
||||
binaryPath,
|
||||
resolvedCommandPath,
|
||||
realCommandPath,
|
||||
env,
|
||||
platform: yield* HostProcessPlatform,
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Turn a one-shot resolution into the shape drivers expose: a cached read for
|
||||
* advisories and a `fresh` read that update execution uses so it never trusts
|
||||
* ownership derived before the user clicked.
|
||||
*/
|
||||
export const makeCachedProviderMaintenanceResolution = Effect.fn(
|
||||
"makeCachedProviderMaintenanceResolution",
|
||||
)(function* (resolve: Effect.Effect<ProviderMaintenanceCapabilities>) {
|
||||
const [cached, invalidate] = yield* Effect.cachedInvalidateWithTTL(
|
||||
resolve,
|
||||
MAINTENANCE_CAPABILITIES_CACHE_TTL,
|
||||
);
|
||||
return (options?: { readonly fresh?: boolean }) =>
|
||||
options?.fresh ? invalidate.pipe(Effect.andThen(cached)) : cached;
|
||||
});
|
||||
|
||||
function deriveVersionAdvisory(input: {
|
||||
readonly currentVersion: string | null;
|
||||
readonly latestVersion: string | null;
|
||||
@@ -482,6 +648,9 @@ const fetchNpmLatestVersion = Effect.fn("fetchNpmLatestVersion")(function* (pack
|
||||
export const resolveLatestProviderVersion = Effect.fn("resolveLatestProviderVersion")(function* (
|
||||
maintenanceCapabilities: ProviderMaintenanceCapabilities,
|
||||
) {
|
||||
if (maintenanceCapabilities.latestVersion !== undefined) {
|
||||
return maintenanceCapabilities.latestVersion;
|
||||
}
|
||||
const packageName = maintenanceCapabilities.packageName;
|
||||
if (!packageName) {
|
||||
return null;
|
||||
|
||||
@@ -70,7 +70,7 @@ const baseProvider: ServerProvider = {
|
||||
driver: CODEX_DRIVER,
|
||||
enabled: true,
|
||||
installed: true,
|
||||
version: null,
|
||||
version: "0.0.0",
|
||||
status: "ready",
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: "2026-04-10T00:00:00.000Z",
|
||||
@@ -129,6 +129,7 @@ function mockSpawnerLayer(
|
||||
handler: (
|
||||
command: string,
|
||||
args: ReadonlyArray<string>,
|
||||
options: { readonly env?: NodeJS.ProcessEnv | undefined },
|
||||
) => {
|
||||
readonly stdout?: string;
|
||||
readonly stderr?: string;
|
||||
@@ -142,8 +143,11 @@ function mockSpawnerLayer(
|
||||
const childProcess = command as unknown as {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly options: { readonly env?: NodeJS.ProcessEnv | undefined };
|
||||
};
|
||||
return Effect.succeed(mockHandle(handler(childProcess.command, childProcess.args)));
|
||||
return Effect.succeed(
|
||||
mockHandle(handler(childProcess.command, childProcess.args, childProcess.options)),
|
||||
);
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -198,6 +202,7 @@ function makeRegistry(
|
||||
|
||||
return {
|
||||
registry,
|
||||
providersRef,
|
||||
updateStatesRef,
|
||||
};
|
||||
});
|
||||
@@ -210,7 +215,8 @@ const makeTestRunner = (registry: ProviderRegistryShape) =>
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
Layer.succeed(ProviderRegistry, registry),
|
||||
Layer.succeed(ProviderVersionCache, new Map()),
|
||||
// Fresh per runner so a version cached by one test cannot leak into another.
|
||||
Layer.sync(ProviderVersionCache, () => new Map()),
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -250,6 +256,182 @@ describe("providerMaintenanceRunner", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("reports unchanged when the updater exits 0 but the provider is gone", () => {
|
||||
return Effect.gen(function* () {
|
||||
const { registry, providersRef } = yield* makeRegistry(baseProvider);
|
||||
// After the update, the refreshed snapshot no longer sees an install.
|
||||
const updater = yield* makeTestRunner({
|
||||
...registry,
|
||||
refreshInstance: () =>
|
||||
Ref.updateAndGet(providersRef, (providers) =>
|
||||
providers.map((provider) => ({ ...provider, installed: false, version: null })),
|
||||
),
|
||||
});
|
||||
|
||||
const result = yield* updater.updateProvider(CODEX_DRIVER);
|
||||
assert.strictEqual(result.providers[0]?.updateState?.status, "unchanged");
|
||||
assert.match(result.providers[0]?.updateState?.message ?? "", /could not verify/);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
NonWindowsPlatform,
|
||||
latestVersionHttpClient("0.0.0"),
|
||||
mockSpawnerLayer(() => ({ stdout: "updated" })),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"keeps a successful update when the binary is present but its version is unreadable",
|
||||
() => {
|
||||
return Effect.gen(function* () {
|
||||
const { registry, providersRef } = yield* makeRegistry(baseCursorProvider);
|
||||
// Cursor's `agent about` probe can fail right after an update while the
|
||||
// new binary is perfectly fine.
|
||||
const updater = yield* makeTestRunner({
|
||||
...registry,
|
||||
refreshInstance: () =>
|
||||
Ref.updateAndGet(providersRef, (providers) =>
|
||||
providers.map((provider) => ({ ...provider, installed: true, version: null })),
|
||||
),
|
||||
});
|
||||
|
||||
const result = yield* updater.updateProvider(CURSOR_DRIVER);
|
||||
assert.strictEqual(result.providers[0]?.updateState?.status, "succeeded");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
NonWindowsPlatform,
|
||||
latestVersionHttpClient("0.0.0"),
|
||||
mockSpawnerLayer(() => ({ stdout: "updated" })),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it.effect("spawns the updater with the environment its capabilities declare", () => {
|
||||
const seen: Array<NodeJS.ProcessEnv | undefined> = [];
|
||||
return Effect.gen(function* () {
|
||||
const { registry } = yield* makeRegistry(baseProvider);
|
||||
const updater = yield* makeTestRunner({
|
||||
...registry,
|
||||
getProviderMaintenanceCapabilitiesForInstance: (_instanceId, provider) =>
|
||||
Effect.succeed({
|
||||
...lifecycleFor(provider),
|
||||
update: {
|
||||
command: "codex update",
|
||||
executable: "/work/codex-home/packages/standalone/bin/codex",
|
||||
args: ["update"],
|
||||
lockKey: "codex-native",
|
||||
env: { CODEX_HOME: "/work/codex-home" },
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
yield* updater.updateProvider(CODEX_DRIVER);
|
||||
assert.deepStrictEqual(seen, [{ CODEX_HOME: "/work/codex-home" }]);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
NonWindowsPlatform,
|
||||
latestVersionHttpClient("0.0.0"),
|
||||
mockSpawnerLayer((_command, _args, options) => {
|
||||
seen.push(options.env);
|
||||
return { stdout: "updated" };
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("re-resolves ownership before running and executes the fresh command", () => {
|
||||
const calls: Array<{ command: string; args: ReadonlyArray<string> }> = [];
|
||||
const fresh: Array<boolean> = [];
|
||||
return Effect.gen(function* () {
|
||||
const { registry } = yield* makeRegistry(baseProvider);
|
||||
const updater = yield* makeTestRunner({
|
||||
...registry,
|
||||
getProviderMaintenanceCapabilitiesForInstance: (_instanceId, provider, options) => {
|
||||
fresh.push(options?.fresh === true);
|
||||
return Effect.succeed(
|
||||
makeProviderMaintenanceCapabilities({
|
||||
provider,
|
||||
packageName: "@openai/codex",
|
||||
updateExecutable: options?.fresh ? "/opt/homebrew/bin/brew" : "brew",
|
||||
updateArgs: ["upgrade", "--cask", "codex"],
|
||||
updateLockKey: "homebrew",
|
||||
}),
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
yield* updater.updateProvider(CODEX_DRIVER);
|
||||
// Cached read picks the lock; the two fresh reads bracket the command.
|
||||
assert.deepStrictEqual(fresh, [false, true, true]);
|
||||
assert.deepStrictEqual(calls, [
|
||||
{ command: "/opt/homebrew/bin/brew", args: ["upgrade", "--cask", "codex"] },
|
||||
]);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
NonWindowsPlatform,
|
||||
latestVersionHttpClient("0.0.0"),
|
||||
mockSpawnerLayer((command, args) => {
|
||||
calls.push({ command, args });
|
||||
return { stdout: "updated" };
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("aborts without running when the installation changed since the advisory", () => {
|
||||
const calls: Array<string> = [];
|
||||
return Effect.gen(function* () {
|
||||
const { registry, updateStatesRef } = yield* makeRegistry(baseProvider);
|
||||
const updater = yield* makeTestRunner({
|
||||
...registry,
|
||||
getProviderMaintenanceCapabilitiesForInstance: (_instanceId, provider, options) =>
|
||||
Effect.succeed(
|
||||
options?.fresh
|
||||
? makeProviderMaintenanceCapabilities({
|
||||
provider,
|
||||
packageName: "@openai/codex",
|
||||
updateExecutable: null,
|
||||
updateArgs: [],
|
||||
updateLockKey: null,
|
||||
})
|
||||
: lifecycleFor(provider),
|
||||
),
|
||||
});
|
||||
|
||||
const result = yield* updater.updateProvider(CODEX_DRIVER);
|
||||
assert.deepStrictEqual(calls, []);
|
||||
assert.strictEqual(result.providers[0]?.updateState?.status, "failed");
|
||||
assert.strictEqual(
|
||||
result.providers[0]?.updateState?.message,
|
||||
"Provider installation changed. Refresh and try again.",
|
||||
);
|
||||
assert.deepStrictEqual(
|
||||
(yield* Ref.get(updateStatesRef)).map((state) => state.status),
|
||||
["queued", "running", "failed"],
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
NonWindowsPlatform,
|
||||
latestVersionHttpClient("0.0.0"),
|
||||
mockSpawnerLayer((command) => {
|
||||
calls.push(command);
|
||||
return { stdout: "updated" };
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("uses the resolved provider capabilities when choosing the update executable", () => {
|
||||
const calls: Array<{ command: string; args: ReadonlyArray<string> }> = [];
|
||||
return Effect.gen(function* () {
|
||||
|
||||
@@ -23,7 +23,11 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { ProviderRegistry } from "./Services/ProviderRegistry.ts";
|
||||
import { makeProviderMaintenanceCommandCoordinator } from "./providerMaintenanceCommandCoordinator.ts";
|
||||
import { enrichProviderSnapshotWithVersionAdvisory } from "./providerMaintenance.ts";
|
||||
import {
|
||||
enrichProviderSnapshotWithVersionAdvisory,
|
||||
type ProviderMaintenanceCommandAction,
|
||||
ProviderVersionCache,
|
||||
} from "./providerMaintenance.ts";
|
||||
import type { ProviderMaintenanceCapabilities } from "./providerMaintenance.ts";
|
||||
import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
|
||||
const isServerProviderUpdateError = Schema.is(ServerProviderUpdateError);
|
||||
@@ -73,6 +77,7 @@ const runProviderMaintenanceCommandWithSpawner = Effect.fn("ProviderMaintenanceR
|
||||
readonly spawner: ChildProcessSpawner.ChildProcessSpawner["Service"];
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly env?: NodeJS.ProcessEnv;
|
||||
}) {
|
||||
const collectCommandResult = Effect.fn("ProviderMaintenanceRunner.collectCommandResult")(
|
||||
function* () {
|
||||
@@ -83,7 +88,12 @@ const runProviderMaintenanceCommandWithSpawner = Effect.fn("ProviderMaintenanceR
|
||||
// shell. On Linux/macOS (incl. the WSL backend) this is a no-op.
|
||||
const resolved = yield* resolveSpawnCommand(input.command, input.args);
|
||||
const child = yield* input.spawner
|
||||
.spawn(ChildProcess.make(resolved.command, resolved.args, { shell: resolved.shell }))
|
||||
.spawn(
|
||||
ChildProcess.make(resolved.command, resolved.args, {
|
||||
shell: resolved.shell,
|
||||
...(input.env ? { env: input.env, extendEnv: true } : {}),
|
||||
}),
|
||||
)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
@@ -181,6 +191,10 @@ function isOutdatedProvider(provider: ServerProvider | undefined): boolean {
|
||||
return provider?.versionAdvisory?.status === "behind_latest";
|
||||
}
|
||||
|
||||
function isStillInstalled(provider: ServerProvider): boolean {
|
||||
return provider.installed;
|
||||
}
|
||||
|
||||
function makeUpdateState(input: {
|
||||
readonly status: ServerProviderUpdateState["status"];
|
||||
readonly startedAt: string | null;
|
||||
@@ -201,11 +215,13 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () {
|
||||
const providerRegistry = yield* ProviderRegistry;
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const runMaintenanceCommand = (command: string, args: ReadonlyArray<string>) =>
|
||||
const versionCache = yield* ProviderVersionCache;
|
||||
const runMaintenanceCommand = (update: ProviderMaintenanceCommandAction) =>
|
||||
runProviderMaintenanceCommandWithSpawner({
|
||||
spawner,
|
||||
command,
|
||||
args,
|
||||
command: update.executable,
|
||||
args: update.args,
|
||||
...(update.env ? { env: update.env } : {}),
|
||||
});
|
||||
const commandCoordinator = yield* makeProviderMaintenanceCommandCoordinator({
|
||||
makeAlreadyRunningError: () =>
|
||||
@@ -258,7 +274,10 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () {
|
||||
enrichProviderSnapshotWithVersionAdvisory(
|
||||
refreshedProvider,
|
||||
maintenanceCapabilities,
|
||||
).pipe(Effect.provideService(HttpClient.HttpClient, httpClient)),
|
||||
).pipe(
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
Effect.provideService(ProviderVersionCache, versionCache),
|
||||
),
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
},
|
||||
@@ -337,7 +356,26 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () {
|
||||
}),
|
||||
);
|
||||
|
||||
const result = yield* runMaintenanceCommand(update.executable, update.args);
|
||||
// The cached capabilities chose the lock; re-derive ownership
|
||||
// now so the command that runs matches the executable as it is
|
||||
// at click time, not as it was at the last health refresh.
|
||||
const fresh = yield* providerRegistry.getProviderMaintenanceCapabilitiesForInstance(
|
||||
instanceId,
|
||||
provider,
|
||||
{ fresh: true },
|
||||
);
|
||||
if (!fresh.update || fresh.update.lockKey !== update.lockKey) {
|
||||
return yield* finish(
|
||||
makeUpdateState({
|
||||
status: "failed",
|
||||
startedAt,
|
||||
finishedAt: yield* nowIso,
|
||||
message: "Provider installation changed. Refresh and try again.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const result = yield* runMaintenanceCommand(fresh.update);
|
||||
const finishedAt = yield* nowIso;
|
||||
if (result.timedOut || result.exitCode !== 0) {
|
||||
return yield* finish(
|
||||
@@ -351,18 +389,30 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () {
|
||||
);
|
||||
}
|
||||
|
||||
// Homebrew's "latest" moves once the upgrade lands; read it again.
|
||||
const verified = yield* providerRegistry.getProviderMaintenanceCapabilitiesForInstance(
|
||||
instanceId,
|
||||
provider,
|
||||
{ fresh: true },
|
||||
);
|
||||
const { verifiedProviders } = yield* verifyRefreshedProvider(
|
||||
provider,
|
||||
capabilities,
|
||||
verified,
|
||||
instanceId,
|
||||
);
|
||||
const couldNotVerify = verifiedProviders.length === 0;
|
||||
const stillOutdated =
|
||||
couldNotVerify ||
|
||||
verifiedProviders.some((verifiedProvider) => isOutdatedProvider(verifiedProvider));
|
||||
// "Succeeded" needs the provider to still be installed: an
|
||||
// installer that exits 0 and leaves the binary missing is not a
|
||||
// success. A missing version alone is not held against it, since
|
||||
// Cursor's `about` probe can fail transiently on a healthy binary.
|
||||
const couldNotVerify =
|
||||
verifiedProviders.length === 0 ||
|
||||
verifiedProviders.some((verifiedProvider) => !isStillInstalled(verifiedProvider));
|
||||
const stillOutdated = verifiedProviders.some((verifiedProvider) =>
|
||||
isOutdatedProvider(verifiedProvider),
|
||||
);
|
||||
return yield* finish(
|
||||
makeUpdateState({
|
||||
status: stillOutdated ? "unchanged" : "succeeded",
|
||||
status: couldNotVerify || stillOutdated ? "unchanged" : "succeeded",
|
||||
startedAt,
|
||||
finishedAt,
|
||||
message: couldNotVerify
|
||||
|
||||
@@ -19,6 +19,13 @@ export type ProviderUpdateCandidate = ServerProvider & {
|
||||
};
|
||||
};
|
||||
|
||||
export type ProviderSettingsUpdateCandidate = ServerProvider & {
|
||||
readonly versionAdvisory: NonNullable<ServerProvider["versionAdvisory"]> & {
|
||||
readonly canUpdate: true;
|
||||
readonly updateCommand: string;
|
||||
};
|
||||
};
|
||||
|
||||
export type ProviderUpdateToastType = "warning" | "loading" | "error" | "success";
|
||||
export type ProviderUpdateToastPhase = "initial" | "running" | "failed" | "unchanged" | "succeeded";
|
||||
|
||||
@@ -149,6 +156,17 @@ export function collectProviderUpdateCandidates(
|
||||
return dedupeProvidersByDriver(providers.filter(isProviderUpdateCandidate));
|
||||
}
|
||||
|
||||
export function isProviderSettingsUpdateCandidate(
|
||||
provider: ServerProvider,
|
||||
): provider is ProviderSettingsUpdateCandidate {
|
||||
return (
|
||||
provider.enabled &&
|
||||
provider.versionAdvisory?.status === "behind_latest" &&
|
||||
provider.versionAdvisory.canUpdate === true &&
|
||||
provider.versionAdvisory.updateCommand !== null
|
||||
);
|
||||
}
|
||||
|
||||
export function hasOneClickUpdateProviderCandidate(
|
||||
candidate: ProviderUpdateCandidate,
|
||||
providers: ReadonlyArray<ServerProvider>,
|
||||
|
||||
@@ -49,11 +49,9 @@ import {
|
||||
connectionPhasePingClassName,
|
||||
} from "../ConnectionStatusDot";
|
||||
import {
|
||||
canOneClickUpdateProviderCandidate,
|
||||
collectProviderUpdateCandidates,
|
||||
hasOneClickUpdateProviderCandidate,
|
||||
isProviderSettingsUpdateCandidate,
|
||||
isProviderUpdateActive,
|
||||
type ProviderUpdateCandidate,
|
||||
type ProviderSettingsUpdateCandidate,
|
||||
} from "../ProviderUpdateLaunchNotification.logic";
|
||||
import { Button } from "../ui/button";
|
||||
import {
|
||||
@@ -574,19 +572,20 @@ export function EnvironmentProviderSettings({
|
||||
const [selectedInstanceId, setSelectedInstanceId] = useState<ProviderInstanceId | null>(
|
||||
targetInstanceId ?? null,
|
||||
);
|
||||
const [updatingProviderDrivers, setUpdatingProviderDrivers] = useState<
|
||||
ReadonlySet<ProviderDriverKind>
|
||||
const [updatingProviderInstanceIds, setUpdatingProviderInstanceIds] = useState<
|
||||
ReadonlySet<ProviderInstanceId>
|
||||
>(() => new Set());
|
||||
const refreshingRef = useRef(false);
|
||||
const updatingDriversRef = useRef<Set<ProviderDriverKind>>(new Set());
|
||||
const updatingInstanceIdsRef = useRef<Set<ProviderInstanceId>>(new Set());
|
||||
|
||||
const providerUpdateCandidates = useMemo(
|
||||
() => collectProviderUpdateCandidates(serverProviders),
|
||||
[serverProviders],
|
||||
);
|
||||
const providerUpdateCandidateByInstanceId = useMemo(
|
||||
() => new Map(providerUpdateCandidates.map((candidate) => [candidate.instanceId, candidate])),
|
||||
[providerUpdateCandidates],
|
||||
() =>
|
||||
new Map(
|
||||
serverProviders
|
||||
.filter(isProviderSettingsUpdateCandidate)
|
||||
.map((candidate) => [candidate.instanceId, candidate]),
|
||||
),
|
||||
[serverProviders],
|
||||
);
|
||||
const visibleProviderSettings = PROVIDER_SETTINGS.filter(
|
||||
(providerSettings) =>
|
||||
@@ -636,14 +635,14 @@ export function EnvironmentProviderSettings({
|
||||
}, [environmentId, refreshServerProviders]);
|
||||
|
||||
const runProviderUpdate = useCallback(
|
||||
async (candidate: ProviderUpdateCandidate) => {
|
||||
async (candidate: ProviderSettingsUpdateCandidate) => {
|
||||
// Ref-based re-entry guard, mirroring refreshProviders: a state updater
|
||||
// may run after this function returns, so it cannot gate the dispatch.
|
||||
if (updatingDriversRef.current.has(candidate.driver)) {
|
||||
if (updatingInstanceIdsRef.current.has(candidate.instanceId)) {
|
||||
return;
|
||||
}
|
||||
updatingDriversRef.current.add(candidate.driver);
|
||||
setUpdatingProviderDrivers((previous) => new Set(previous).add(candidate.driver));
|
||||
updatingInstanceIdsRef.current.add(candidate.instanceId);
|
||||
setUpdatingProviderInstanceIds((previous) => new Set(previous).add(candidate.instanceId));
|
||||
|
||||
const result = await updateProvider({
|
||||
environmentId,
|
||||
@@ -665,13 +664,13 @@ export function EnvironmentProviderSettings({
|
||||
}),
|
||||
);
|
||||
}
|
||||
updatingDriversRef.current.delete(candidate.driver);
|
||||
setUpdatingProviderDrivers((previous) => {
|
||||
if (!previous.has(candidate.driver)) {
|
||||
updatingInstanceIdsRef.current.delete(candidate.instanceId);
|
||||
setUpdatingProviderInstanceIds((previous) => {
|
||||
if (!previous.has(candidate.instanceId)) {
|
||||
return previous;
|
||||
}
|
||||
const next = new Set(previous);
|
||||
next.delete(candidate.driver);
|
||||
next.delete(candidate.instanceId);
|
||||
return next;
|
||||
});
|
||||
},
|
||||
@@ -872,23 +871,13 @@ export function EnvironmentProviderSettings({
|
||||
const liveProvider = serverProviders.find(
|
||||
(candidate) => candidate.instanceId === row.instanceId,
|
||||
);
|
||||
const updateCandidate = liveProvider
|
||||
? providerUpdateCandidateByInstanceId.get(liveProvider.instanceId)
|
||||
: undefined;
|
||||
const isDriverUpdateRunning =
|
||||
const updateCandidate = providerUpdateCandidateByInstanceId.get(row.instanceId);
|
||||
const isInstanceUpdateRunning =
|
||||
updateCandidate !== undefined &&
|
||||
(updatingProviderDrivers.has(updateCandidate.driver) ||
|
||||
serverProviders.some(
|
||||
(provider) =>
|
||||
provider.driver === updateCandidate.driver && isProviderUpdateActive(provider),
|
||||
));
|
||||
const showInlineUpdateButton =
|
||||
updateCandidate !== undefined &&
|
||||
hasOneClickUpdateProviderCandidate(updateCandidate, serverProviders);
|
||||
const canRunInlineUpdate =
|
||||
updateCandidate !== undefined &&
|
||||
canOneClickUpdateProviderCandidate(updateCandidate, serverProviders) &&
|
||||
!updatingProviderDrivers.has(updateCandidate.driver);
|
||||
(updatingProviderInstanceIds.has(updateCandidate.instanceId) ||
|
||||
isProviderUpdateActive(updateCandidate));
|
||||
const showInlineUpdateButton = updateCandidate !== undefined;
|
||||
const canRunInlineUpdate = updateCandidate !== undefined && !isInstanceUpdateRunning;
|
||||
const modelPreferences = settings.providerModelPreferences?.[row.instanceId] ?? {
|
||||
hiddenModels: [],
|
||||
modelOrder: [],
|
||||
@@ -975,7 +964,9 @@ export function EnvironmentProviderSettings({
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
isUpdating={mode === "editor" && showInlineUpdateButton ? isDriverUpdateRunning : undefined}
|
||||
isUpdating={
|
||||
mode === "editor" && showInlineUpdateButton ? isInstanceUpdateRunning : undefined
|
||||
}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -55,6 +55,25 @@ run before the prompt. They reject profiles with such configuration before launc
|
||||
instructions and tool denial do not create a native sandbox.
|
||||
See [helper constraints](../../apps/server/src/textGeneration/AntigravityTextGeneration.ts).
|
||||
|
||||
## Provider updates run only through the owning installer
|
||||
|
||||
A one-click update is offered only when the resolved executable's path proves which installer owns
|
||||
it. Homebrew and npm are proven by the real path (symlinks followed): a versioned keg or cask under
|
||||
`brew --prefix`, or `<prefix>/lib/node_modules/<pkg>/` (Windows: the shim beside `node_modules`).
|
||||
Native installer layouts and the global bin directories of pnpm, Bun, and Vite+ may match on either
|
||||
the resolved path or its real target, since those installers place real files or their own symlinks
|
||||
there. Anything unproven stays manual-only but still reports the version gap. npm updates pin
|
||||
`--prefix` because the `npm` on `PATH` can belong to a different Node than the one that owns the
|
||||
provider. Homebrew
|
||||
compares against `brew info` since casks trail npm by hours; native installs share npm's version
|
||||
train, so the registry stays authoritative for them.
|
||||
See the [resolver](../../apps/server/src/provider/providerMaintenance.ts).
|
||||
|
||||
Ownership is cached per instance and re-read immediately before an update runs. The
|
||||
[runner](../../apps/server/src/provider/providerMaintenanceRunner.ts) refuses when the lock key
|
||||
changed since the advisory, and reports success only when the refreshed provider is still installed
|
||||
with a readable, current version.
|
||||
|
||||
## Protocol traps
|
||||
|
||||
Codex async questions arrive as notifications and are answered with a new user message. There is
|
||||
|
||||
@@ -81,6 +81,13 @@ Provider CLIs must be on the server's `PATH`. If T3 Code cannot find one, set it
|
||||
Cursor's executable is `cursor-agent`, although its login command is
|
||||
`agent login`. Antigravity can use its managed runtime without a `PATH` entry.
|
||||
|
||||
When a provider CLI is behind its latest release, its provider card shows the
|
||||
available version. **Update now** appears only when T3 Code can tell which
|
||||
installer owns the CLI (its own update command, Homebrew, or a global npm, pnpm,
|
||||
bun, or Vite+ install) and runs that installer. Otherwise update the CLI the same
|
||||
way you installed it. Homebrew installs compare against the version Homebrew
|
||||
offers, which can trail the npm release by a few hours.
|
||||
|
||||
Add another provider instance for a separate account or configuration. Each
|
||||
instance can have its own environment variables, such as API keys or a custom
|
||||
base URL. Mark secret values as sensitive; after saving, T3 Code does not display
|
||||
|
||||
Reference in new issue
Block a user