TypeScript
refactor(provider): trace provider runtime operations (#21991)
Julius Marminge0878d3f4d463
diff --git a/packages/effect-codex-app-server/src/protocol.ts b/packages/effect-codex-app-server/src/protocol.tsindex 4a32973a988..c1f6cb1f1b6 100644--- a/packages/effect-codex-app-server/src/protocol.ts+++ b/packages/effect-codex-app-server/src/protocol.ts@@ -217,8 +217,9 @@ export const makeCodexAppServerPatchedProtocol = Effect.fn("makeCodexAppServerPa] as const;}).pipe(Effect.flatten);- const offerOutgoing = (message: Record<string, unknown>) =>- Effect.gen(function* () {+ const offerOutgoing =+ /* Every protocol write reaches this helper; request spans cover the operation. */+ Effect.fnUntraced(function* (message: Record<string, unknown>) {const failure = yield* Ref.get(terminationFailure);if (Option.isSome(failure)) return yield* failure.value;@@ -447,25 +448,27 @@ export const makeCodexAppServerPatchedProtocol = Effect.fn("makeCodexAppServerPayield* Stream.fromQueue(outgoing).pipe(Stream.run(options.stdio.stdout()), Effect.forkScoped);- const request = (method: string, payload?: unknown) =>- Effect.gen(function* () {- const requestId = yield* Ref.modify(- nextRequestId,- (current) => [current, current + 1] as const,- );- const deferred = yield* Deferred.make<unknown, CodexError.CodexAppServerError>();- yield* Ref.update(pending, (current) =>- new Map(current).set(String(requestId), { deferred, method }),- );- yield* offerOutgoing({- id: requestId,- method,- ...(payload !== undefined ? { params: payload } : {}),- }).pipe(Effect.tapError(() => removePending(String(requestId))));- return yield* Deferred.await(deferred).pipe(- Effect.onInterrupt(() => removePending(String(requestId))),- );- });+ const request = Effect.fn("CodexAppServerProtocol.request")(function* (+ method: string,+ payload?: unknown,+ ) {+ const requestId = yield* Ref.modify(+ nextRequestId,+ (current) => [current, current + 1] as const,+ );+ const deferred = yield* Deferred.make<unknown, CodexError.CodexAppServerError>();+ yield* Ref.update(pending, (current) =>+ new Map(current).set(String(requestId), { deferred, method }),+ );+ yield* offerOutgoing({+ id: requestId,+ method,+ ...(payload !== undefined ? { params: payload } : {}),+ }).pipe(Effect.tapError(() => removePending(String(requestId))));+ return yield* Deferred.await(deferred).pipe(+ Effect.onInterrupt(() => removePending(String(requestId))),+ );+ });const notify = (method: string, payload?: unknown) =>offerOutgoing({diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.tsindex 519c4f45df8..28e05da3f55 100644--- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts+++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts@@ -1589,8 +1589,8 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(functreturn distribution;});- const search: AcpRegistryCatalog["Service"]["search"] = (input) =>- Effect.gen(function* () {+ const search: AcpRegistryCatalog["Service"]["search"] = Effect.fn("AcpRegistryCatalog.search")(+ function* (input) {const registry = yield* refreshRegistry();const ranked = registry.agents.flatMap((agent) => {const distribution = resolveAcpRegistryDistribution({@@ -1632,10 +1632,11 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct: "registry",})),} satisfies AcpRegistrySearchResult;- });+ },+ );- const prepare: AcpRegistryCatalog["Service"]["prepare"] = (input) =>- Effect.gen(function* () {+ const prepare: AcpRegistryCatalog["Service"]["prepare"] = Effect.fn("AcpRegistryCatalog.prepare")(+ function* (input) {const registry = yield* refreshRegistry();const agent = yield* findAgent(registry, input.agentId);const distribution = yield* compatibleDistribution(agent, "auto");@@ -1658,7 +1659,8 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(functdistribution: distribution.kind,prepared: true,} satisfies AcpRegistryPrepareResult;- });+ },+ );const validateLocalExecutable = (command: string) =>platform === "win32" && /\.(?:cmd|bat)$/iu.test(command)@@ -1671,8 +1673,8 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct): Effect.void;- const inspect: AcpRegistryCatalog["Service"]["inspect"] = (settings, environment) =>- Effect.gen(function* () {+ const inspect: AcpRegistryCatalog["Service"]["inspect"] = Effect.fn("AcpRegistryCatalog.inspect")(+ function* (settings, environment) {if (settings.source === "local") {const command = settings.commandPath.trim();if (!command) return { status: "unconfigured" } as const;@@ -1782,10 +1784,11 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(functdistribution: distribution.kind,runner,} as const);- });+ },+ );- const resolve: AcpRegistryCatalog["Service"]["resolve"] = (settings, cwd, environment) =>- Effect.gen(function* () {+ const resolve: AcpRegistryCatalog["Service"]["resolve"] = Effect.fn("AcpRegistryCatalog.resolve")(+ function* (settings, cwd, environment) {if (settings.source === "local") {const executable = settings.commandPath.trim();if (!executable) {@@ -1875,7 +1878,8 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(functenv: spawnEnvironment,},} satisfies ResolvedAcpRegistryAgent;- });+ },+ );const uninstallManagedBinary: AcpRegistryCatalog["Service"]["uninstallManagedBinary"] = (input) =>hostSettingsdiff --git a/packages/provider-acp-registry/src/server/auth.ts b/packages/provider-acp-registry/src/server/auth.tsindex ac87bfc1b0c..af82212d3ee 100644--- a/packages/provider-acp-registry/src/server/auth.ts+++ b/packages/provider-acp-registry/src/server/auth.ts@@ -227,109 +227,104 @@ export const makeAcpRegistryAuth = Effect.fn("makeAcpRegistryAuth")(function* (oreturn yield* failure("start", "The provider login command did not finish successfully.");});- const authenticate = (methodId: string, context: ProviderAuthFlow.ProviderAuthFlowContext) =>- Effect.gen(function* () {- if (!options.settings.enabled)- return yield* failure("start", "Enable this provider before signing in.");- const login = Effect.scoped(- Effect.gen(function* () {- const resolved = yield* resolve;- const runtimeScope = yield* Scope.make();- yield* Effect.addFinalizer(() => Scope.close(runtimeScope, Exit.void));- const runtime = yield* makeRuntime(resolved.spawn).pipe(- Effect.provideService(Scope.Scope, runtimeScope),- );- yield* runtime.handleElicitation((request) =>- Effect.gen(function* () {- if (- request.mode !== "url" ||- !("url" in request) ||- !("elicitationId" in request) ||- typeof request.url !== "string" ||- typeof request.elicitationId !== "string"- )- return { action: "decline" } as const;- const url = normalizeAcpRegistryWebUrl(request.url);- const id = request.elicitationId.trim();- if (!url || !id || id.length > 128) return { action: "decline" } as const;- const consent = yield* Deferred.make<boolean>();- yield* context.setInteraction(- { type: "browser", id, url, requiresConsent: true },- (response) =>- response.type === "browser"- ? Deferred.succeed(consent, response.action === "accept").pipe(Effect.asVoid)- : Effect.void,- );- return (yield* Deferred.await(consent))- ? ({ action: "accept" } as const)- : ({ action: "decline" } as const);- }),+ const authenticate = Effect.fn("AcpRegistryAuth.authenticate")(function* (+ methodId: string,+ context: ProviderAuthFlow.ProviderAuthFlowContext,+ ) {+ if (!options.settings.enabled)+ return yield* failure("start", "Enable this provider before signing in.");+ const login = Effect.scoped(+ Effect.gen(function* () {+ const resolved = yield* resolve;+ const runtimeScope = yield* Scope.make();+ yield* Effect.addFinalizer(() => Scope.close(runtimeScope, Exit.void));+ const runtime = yield* makeRuntime(resolved.spawn).pipe(+ Effect.provideService(Scope.Scope, runtimeScope),+ );+ yield* runtime.handleElicitation((request) =>+ Effect.gen(function* () {+ if (+ request.mode !== "url" ||+ !("url" in request) ||+ !("elicitationId" in request) ||+ typeof request.url !== "string" ||+ typeof request.elicitationId !== "string"+ )+ return { action: "decline" } as const;+ const url = normalizeAcpRegistryWebUrl(request.url);+ const id = request.elicitationId.trim();+ if (!url || !id || id.length > 128) return { action: "decline" } as const;+ const consent = yield* Deferred.make<boolean>();+ yield* context.setInteraction(+ { type: "browser", id, url, requiresConsent: true },+ (response) =>+ response.type === "browser"+ ? Deferred.succeed(consent, response.action === "accept").pipe(Effect.asVoid)+ : Effect.void,+ );+ return (yield* Deferred.await(consent))+ ? ({ action: "accept" } as const)+ : ({ action: "decline" } as const);+ }),+ );+ const initialized = yield* runtime+ .initialize()+ .pipe(+ Effect.mapError((cause) =>+ failure("start", "Could not initialize the selected ACP agent.", cause),+ ),);- const initialized = yield* runtime- .initialize()+ const method = initialized.authMethods?.find((method) => method.id === methodId);+ if (!method)+ return yield* failure("start", "The agent no longer advertises this sign-in method.");+ if (method.type === "terminal") {+ yield* Scope.close(runtimeScope, Exit.void);+ yield* runTerminal(resolved, method, context).pipe(Effect.scoped);+ // Terminal login is a separate invocation. Reconnect after it exits so+ // the ACP process reads the credentials its login command persisted.+ const verifiedRuntime = yield* makeRuntime(resolved.spawn);+ yield* context.verifying;+ yield* verifiedRuntime+ .start().pipe(Effect.mapError((cause) =>- failure("start", "Could not initialize the selected ACP agent.", cause),+ failure(+ "verify",+ "The provider could not create a session after terminal sign-in.",+ cause,+ ),),);- const method = initialized.authMethods?.find((method) => method.id === methodId);- if (!method)- return yield* failure("start", "The agent no longer advertises this sign-in method.");- if (method.type === "terminal") {- yield* Scope.close(runtimeScope, Exit.void);- yield* runTerminal(resolved, method, context).pipe(Effect.scoped);- // Terminal login is a separate invocation. Reconnect after it exits so- // the ACP process reads the credentials its login command persisted.- const verifiedRuntime = yield* makeRuntime(resolved.spawn);- yield* context.verifying;- yield* verifiedRuntime- .start()- .pipe(- Effect.mapError((cause) =>- failure(- "verify",- "The provider could not create a session after terminal sign-in.",- cause,- ),- ),- );- } else {- if (method.type === undefined || method.type === "agent") {- if (!runtime.authenticate)- return yield* failure(- "start",- "This runtime does not support explicit ACP sign-in.",- );- yield* runtime- .authenticate(methodId)- .pipe(- Effect.mapError((cause) =>- failure("start", "The ACP agent could not complete sign-in.", cause),- ),- );- }- // Legacy env_var methods use the secret-backed environment fields in- // provider settings. Never send their ID to authenticate.- yield* context.verifying;+ } else {+ if (method.type === undefined || method.type === "agent") {+ if (!runtime.authenticate)+ return yield* failure("start", "This runtime does not support explicit ACP sign-in.");yield* runtime- .start()+ .authenticate(methodId).pipe(Effect.mapError((cause) =>- failure(- "verify",- "The provider could not create a session after sign-in.",- cause,- ),+ failure("start", "The ACP agent could not complete sign-in.", cause),),);}- }),- );- yield* Option.isSome(coordinator)- ? coordinator.value.withForegroundStartup(agentKey, login)- : login;- yield* options.onChanged(true);- });+ // Legacy env_var methods use the secret-backed environment fields in+ // provider settings. Never send their ID to authenticate.+ yield* context.verifying;+ yield* runtime+ .start()+ .pipe(+ Effect.mapError((cause) =>+ failure("verify", "The provider could not create a session after sign-in.", cause),+ ),+ );+ }+ }),+ );+ yield* Option.isSome(coordinator)+ ? coordinator.value.withForegroundStartup(agentKey, login)+ : login;+ yield* options.onChanged(true);+ });const logout = Effect.scoped(Effect.gen(function* () {const resolved = yield* resolve;diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.tsindex dce555f0c5d..1f0f7401e20 100644--- a/packages/provider-acp-registry/src/server/driver.ts+++ b/packages/provider-acp-registry/src/server/driver.ts@@ -464,438 +464,439 @@ export const AcpRegistryDriver: ProviderDriver<AcpRegistrySettings, AcpRegistryD},configSchema: AcpRegistrySettings,defaultConfig: () => decodeSettings({}),- create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>- Effect.gen(function* () {- const catalog = yield* AcpRegistrySupport.AcpRegistryCatalog;- const runtimeCoordinator = yield* Effect.serviceOption(- AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator,- );- if (Option.isSome(runtimeCoordinator)) {- yield* runtimeCoordinator.value.clearAvailableCommands(instanceId);- yield* runtimeCoordinator.value.clearLiveConfiguration(instanceId);- yield* Effect.addFinalizer(() =>- runtimeCoordinator.value- .clearAvailableCommands(instanceId)- .pipe(Effect.andThen(runtimeCoordinator.value.clearLiveConfiguration(instanceId))),- );- }- const crypto = yield* Crypto.Crypto;- const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;- const hostEnvironment = yield* HostProcess.Environment;- const host = yield* ProviderHost.ProviderHost;- const continuationIdentity = defaultProviderContinuationIdentity({- driverKind: DRIVER_KIND,- instanceId,- });- const identity = {- instanceId,- displayName,- accentColor,- continuationKey: continuationIdentity.continuationKey,- };- const effectiveConfig = { ...config, enabled } satisfies AcpRegistrySettings;- const processEnvironment = yield* mergeProviderInstanceEnvironment(- environment,- hostEnvironment,+ create: Effect.fn("AcpRegistryDriver.create")(function* ({+ instanceId,+ displayName,+ accentColor,+ environment,+ enabled,+ config,+ }) {+ const catalog = yield* AcpRegistrySupport.AcpRegistryCatalog;+ const runtimeCoordinator = yield* Effect.serviceOption(+ AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator,+ );+ if (Option.isSome(runtimeCoordinator)) {+ yield* runtimeCoordinator.value.clearAvailableCommands(instanceId);+ yield* runtimeCoordinator.value.clearLiveConfiguration(instanceId);+ yield* Effect.addFinalizer(() =>+ runtimeCoordinator.value+ .clearAvailableCommands(instanceId)+ .pipe(Effect.andThen(runtimeCoordinator.value.clearLiveConfiguration(instanceId))),);- const orchestrationAdapter = yield* AcpRegistryAdapterV2Driver.create({+ }+ const crypto = yield* Crypto.Crypto;+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;+ const hostEnvironment = yield* HostProcess.Environment;+ const host = yield* ProviderHost.ProviderHost;+ const continuationIdentity = defaultProviderContinuationIdentity({+ driverKind: DRIVER_KIND,+ instanceId,+ });+ const identity = {+ instanceId,+ displayName,+ accentColor,+ continuationKey: continuationIdentity.continuationKey,+ };+ const effectiveConfig = { ...config, enabled } satisfies AcpRegistrySettings;+ const processEnvironment = yield* mergeProviderInstanceEnvironment(+ environment,+ hostEnvironment,+ );+ const orchestrationAdapter = yield* AcpRegistryAdapterV2Driver.create({+ instanceId,+ displayName,+ accentColor,+ environment,+ enabled,+ config,+ }).pipe(+ Effect.mapError(+ (cause) =>+ new ProviderDriverError({+ driver: DRIVER_KIND,+ instanceId,+ detail: "Failed to build ACP Registry orchestration adapter.",+ cause,+ }),+ ),+ );+ const readinessInput = {+ ...identity,+ settings: effectiveConfig,+ environment: processEnvironment,+ };+ const confirmedAuthentication =+ yield* AcpRegistryAuthenticationState.makeAcpRegistryAuthenticationState({+ cacheDir: host.paths.providerStatusCacheDir,instanceId,- displayName,- accentColor,+ settings: effectiveConfig,environment,- enabled,- config,- }).pipe(- Effect.mapError(- (cause) =>- new ProviderDriverError({- driver: DRIVER_KIND,- instanceId,- detail: "Failed to build ACP Registry orchestration adapter.",- cause,+ processEnvironment,+ });+ const withLiveRuntimeState = Effect.fn("AcpRegistryDriver.withLiveRuntimeState")(function* (+ input: ServerProvider,+ ) {+ if (input.auth.status === "unauthenticated") yield* confirmedAuthentication.set(false);+ const provider =+ input.enabled &&+ input.installed &&+ input.auth.status === "unknown" &&+ (yield* confirmedAuthentication.get)+ ? { ...input, auth: { ...input.auth, status: "authenticated" as const } }+ : input;+ return yield* Option.isNone(runtimeCoordinator)+ ? Effect.succeed(provider)+ : Effect.all({+ commands: runtimeCoordinator.value.getAvailableCommands(instanceId),+ configuration: runtimeCoordinator.value.getLiveConfiguration(instanceId),+ authAction: runtimeCoordinator.value.getUrlAuthAction(instanceId),+ }).pipe(+ Effect.map(({ commands, configuration, authAction }) => {+ const withCommands = applyAcpRegistryAvailableCommands(provider, commands);+ const withConfiguration = Option.match(configuration, {+ onNone: () => withCommands,+ onSome: (liveConfiguration) =>+ applyAcpRegistryLiveConfiguration(+ withCommands,+ liveConfiguration,+ effectiveConfig.customModels,+ ),+ });+ return applyAcpRegistryUrlAuthAction(withConfiguration, authAction);}),- ),- );- const readinessInput = {- ...identity,- settings: effectiveConfig,- environment: processEnvironment,- };- const confirmedAuthentication =- yield* AcpRegistryAuthenticationState.makeAcpRegistryAuthenticationState({- cacheDir: host.paths.providerStatusCacheDir,- instanceId,- settings: effectiveConfig,- environment,- processEnvironment,- });- const withLiveRuntimeState = (input: ServerProvider) =>- Effect.gen(function* () {- if (input.auth.status === "unauthenticated") yield* confirmedAuthentication.set(false);- const provider =- input.enabled &&- input.installed &&- input.auth.status === "unknown" &&- (yield* confirmedAuthentication.get)- ? { ...input, auth: { ...input.auth, status: "authenticated" as const } }- : input;- return yield* Option.isNone(runtimeCoordinator)- ? Effect.succeed(provider)- : Effect.all({- commands: runtimeCoordinator.value.getAvailableCommands(instanceId),- configuration: runtimeCoordinator.value.getLiveConfiguration(instanceId),- authAction: runtimeCoordinator.value.getUrlAuthAction(instanceId),- }).pipe(- Effect.map(({ commands, configuration, authAction }) => {- const withCommands = applyAcpRegistryAvailableCommands(provider, commands);- const withConfiguration = Option.match(configuration, {- onNone: () => withCommands,- onSome: (liveConfiguration) =>- applyAcpRegistryLiveConfiguration(- withCommands,- liveConfiguration,- effectiveConfig.customModels,- ),- });- return applyAcpRegistryUrlAuthAction(withConfiguration, authAction);- }),- );- });- const checkProvider = checkAcpRegistryProviderReadiness(readinessInput).pipe(- Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog),- Effect.flatMap(withLiveRuntimeState),- );- const enrichProvider = checkAcpRegistryProviderStatus(- {- ...readinessInput,- cwd: host.paths.cwd,- },- probeAcpRegistryConfiguration,- ).pipe(- Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog),- Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),- Effect.provideService(Crypto.Crypto, crypto),- );- const enrichmentCache = yield* Ref.make<{- readonly generation: number;- readonly entry: {- readonly provider: ServerProvider;- readonly expiresAt: number;- } | null;- }>({ generation: 0, entry: null });- const liveSnapshotSemaphore = yield* Semaphore.make(1);- const invalidateEnrichmentCache = Ref.update(enrichmentCache, (current) => ({- generation: current.generation + 1,- entry: null,- }));- const enrichProviderCached = (baseSnapshot: ServerProvider) =>- Effect.gen(function* () {- const now = yield* Clock.currentTimeMillis;- const cacheState = yield* Ref.get(enrichmentCache);- const cached = cacheState.entry;- if (- cached !== null &&- cached.expiresAt > now &&- cached.provider.version === baseSnapshot.version- ) {- return {- provider: { ...cached.provider, checkedAt: baseSnapshot.checkedAt },- generation: cacheState.generation,- };- }- const enriched = yield* enrichProvider;- if (enriched.status === "ready") {- yield* Ref.update(enrichmentCache, (current) =>- current.generation === cacheState.generation- ? {- ...current,- entry: {- provider: enriched,- expiresAt: now + PROBE_SUCCESS_TTL_MS,- },- }- : current,- );- }- return { provider: enriched, generation: cacheState.generation };- });- const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);- const snapshot = yield* makeManagedServerProvider<- ProviderSnapshotSettings<AcpRegistrySettings>- >({- resolveMaintenance: () => Effect.succeed(MAINTENANCE),- getSettings: snapshotSettings.getSettings,- streamSettings: snapshotSettings.streamSettings,- haveSettingsChanged: haveProviderSnapshotSettingsChanged,- initialSnapshot: () => checkProvider,- checkProvider,- enrichSnapshot: ({ snapshot, getSnapshot, publishSnapshot }) => {- if (!snapshot.installed) return Effect.void;- const publishEnrichment = (- Option.isSome(runtimeCoordinator)- ? runtimeCoordinator.value.runBackgroundProbe(- effectiveConfig.source === "local"- ? `local:${instanceId}`- : effectiveConfig.agentId,- enrichProviderCached(snapshot),- )- : enrichProviderCached(snapshot).pipe(Effect.map(Option.some))- ).pipe(- Effect.flatMap(- Option.match({- onNone: () => Effect.void,- onSome: ({ provider, generation }) =>- liveSnapshotSemaphore.withPermit(- Ref.get(enrichmentCache).pipe(- Effect.flatMap((current) =>- current.generation === generation- ? withLiveRuntimeState(provider).pipe(Effect.flatMap(publishSnapshot))- : Effect.void,- ),+ );+ });+ const checkProvider = checkAcpRegistryProviderReadiness(readinessInput).pipe(+ Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog),+ Effect.flatMap(withLiveRuntimeState),+ );+ const enrichProvider = checkAcpRegistryProviderStatus(+ {+ ...readinessInput,+ cwd: host.paths.cwd,+ },+ probeAcpRegistryConfiguration,+ ).pipe(+ Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog),+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),+ Effect.provideService(Crypto.Crypto, crypto),+ );+ const enrichmentCache = yield* Ref.make<{+ readonly generation: number;+ readonly entry: {+ readonly provider: ServerProvider;+ readonly expiresAt: number;+ } | null;+ }>({ generation: 0, entry: null });+ const liveSnapshotSemaphore = yield* Semaphore.make(1);+ const invalidateEnrichmentCache = Ref.update(enrichmentCache, (current) => ({+ generation: current.generation + 1,+ entry: null,+ }));+ const enrichProviderCached = Effect.fn("AcpRegistryDriver.enrichProviderCached")(function* (+ baseSnapshot: ServerProvider,+ ) {+ const now = yield* Clock.currentTimeMillis;+ const cacheState = yield* Ref.get(enrichmentCache);+ const cached = cacheState.entry;+ if (+ cached !== null &&+ cached.expiresAt > now &&+ cached.provider.version === baseSnapshot.version+ ) {+ return {+ provider: { ...cached.provider, checkedAt: baseSnapshot.checkedAt },+ generation: cacheState.generation,+ };+ }+ const enriched = yield* enrichProvider;+ if (enriched.status === "ready") {+ yield* Ref.update(enrichmentCache, (current) =>+ current.generation === cacheState.generation+ ? {+ ...current,+ entry: {+ provider: enriched,+ expiresAt: now + PROBE_SUCCESS_TTL_MS,+ },+ }+ : current,+ );+ }+ return { provider: enriched, generation: cacheState.generation };+ });+ const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);+ const snapshot = yield* makeManagedServerProvider<+ ProviderSnapshotSettings<AcpRegistrySettings>+ >({+ resolveMaintenance: () => Effect.succeed(MAINTENANCE),+ getSettings: snapshotSettings.getSettings,+ streamSettings: snapshotSettings.streamSettings,+ haveSettingsChanged: haveProviderSnapshotSettingsChanged,+ initialSnapshot: () => checkProvider,+ checkProvider,+ enrichSnapshot: ({ snapshot, getSnapshot, publishSnapshot }) => {+ if (!snapshot.installed) return Effect.void;+ const publishEnrichment = (+ Option.isSome(runtimeCoordinator)+ ? runtimeCoordinator.value.runBackgroundProbe(+ effectiveConfig.source === "local"+ ? `local:${instanceId}`+ : effectiveConfig.agentId,+ enrichProviderCached(snapshot),+ )+ : enrichProviderCached(snapshot).pipe(Effect.map(Option.some))+ ).pipe(+ Effect.flatMap(+ Option.match({+ onNone: () => Effect.void,+ onSome: ({ provider, generation }) =>+ liveSnapshotSemaphore.withPermit(+ Ref.get(enrichmentCache).pipe(+ Effect.flatMap((current) =>+ current.generation === generation+ ? withLiveRuntimeState(provider).pipe(Effect.flatMap(publishSnapshot))+ : Effect.void,),),- }),- ),- );- if (Option.isNone(runtimeCoordinator)) return publishEnrichment;+ ),+ }),+ ),+ );+ if (Option.isNone(runtimeCoordinator)) return publishEnrichment;- const publishLiveCommands = runtimeCoordinator.value.watchAvailableCommands(- instanceId,- ({ slashCommands, skills }) =>- liveSnapshotSemaphore.withPermit(- getSnapshot.pipe(- Effect.flatMap((current) =>- publishSnapshot({- ...current,- slashCommands,- skills,- }),- ),+ const publishLiveCommands = runtimeCoordinator.value.watchAvailableCommands(+ instanceId,+ ({ slashCommands, skills }) =>+ liveSnapshotSemaphore.withPermit(+ getSnapshot.pipe(+ Effect.flatMap((current) =>+ publishSnapshot({+ ...current,+ slashCommands,+ skills,+ }),),),- );- const publishLiveConfiguration = runtimeCoordinator.value.watchLiveConfiguration(- instanceId,- (configuration) =>- liveSnapshotSemaphore.withPermit(- getSnapshot.pipe(- Effect.flatMap((current) =>- publishSnapshot(- applyAcpRegistryLiveConfiguration(- current,- configuration,- effectiveConfig.customModels,- ),+ ),+ );+ const publishLiveConfiguration = runtimeCoordinator.value.watchLiveConfiguration(+ instanceId,+ (configuration) =>+ liveSnapshotSemaphore.withPermit(+ getSnapshot.pipe(+ Effect.flatMap((current) =>+ publishSnapshot(+ applyAcpRegistryLiveConfiguration(+ current,+ configuration,+ effectiveConfig.customModels,),),),),- );- const publishUrlAuthAction = runtimeCoordinator.value.watchUrlAuthAction(- instanceId,- (action) =>- liveSnapshotSemaphore.withPermit(- getSnapshot.pipe(- Effect.flatMap((current) =>- publishSnapshot(- applyAcpRegistryUrlAuthAction(current, Option.fromNullishOr(action)),- ),+ ),+ );+ const publishUrlAuthAction = runtimeCoordinator.value.watchUrlAuthAction(+ instanceId,+ (action) =>+ liveSnapshotSemaphore.withPermit(+ getSnapshot.pipe(+ Effect.flatMap((current) =>+ publishSnapshot(+ applyAcpRegistryUrlAuthAction(current, Option.fromNullishOr(action)),),),),- );- return Effect.all(- [- publishEnrichment,- publishLiveCommands,- publishLiveConfiguration,- publishUrlAuthAction,- ],- {- concurrency: "unbounded",- discard: true,- },- );- },- }).pipe(- Effect.mapError(- (cause) =>- new ProviderDriverError({- driver: DRIVER_KIND,- instanceId,- detail: "Failed to build the ACP Registry provider snapshot.",- cause,- }),- ),- );-- const provideAcpManagementServices = <A, E>(- effect: Effect.Effect<- A,- E,- | AcpRegistrySupport.AcpRegistryCatalog- | ChildProcessSpawner.ChildProcessSpawner- | Crypto.Crypto- >,- ): Effect.Effect<A, E> => {- const provided = effect.pipe(- Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog),- Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),- Effect.provideService(Crypto.Crypto, crypto),+ ),);- return Option.isSome(runtimeCoordinator)- ? provided.pipe(- Effect.provideService(- AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator,- runtimeCoordinator.value,- ),- )- : provided;- };+ return Effect.all(+ [publishEnrichment, publishLiveCommands, publishLiveConfiguration, publishUrlAuthAction],+ {+ concurrency: "unbounded",+ discard: true,+ },+ );+ },+ }).pipe(+ Effect.mapError(+ (cause) =>+ new ProviderDriverError({+ driver: DRIVER_KIND,+ instanceId,+ detail: "Failed to build the ACP Registry provider snapshot.",+ cause,+ }),+ ),+ );- const clearLiveState = Option.isSome(runtimeCoordinator)- ? runtimeCoordinator.value- .clearLiveConfiguration(instanceId)- .pipe(Effect.andThen(runtimeCoordinator.value.clearAvailableCommands(instanceId)))- : Effect.void;- const controller = yield* AcpRegistryAuth.makeAcpRegistryAuth({- instanceId,- settings: effectiveConfig,- cwd: host.paths.cwd,- environment: processEnvironment,- onChanged: (authenticated) =>- confirmedAuthentication- .set(authenticated)- .pipe(- Effect.andThen(authenticated ? Effect.void : clearLiveState),- Effect.andThen(liveSnapshotSemaphore.withPermit(invalidateEnrichmentCache)),- Effect.andThen(snapshot.refresh),- Effect.asVoid,- ),- }).pipe(+ const provideAcpManagementServices = <A, E>(+ effect: Effect.Effect<+ A,+ E,+ | AcpRegistrySupport.AcpRegistryCatalog+ | ChildProcessSpawner.ChildProcessSpawner+ | Crypto.Crypto+ >,+ ): Effect.Effect<A, E> => {+ const provided = effect.pipe(Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog),Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),Effect.provideService(Crypto.Crypto, crypto),);- const auth = {- ...controller,- invalidate: (controller.invalidate ?? Effect.void).pipe(- Effect.andThen(confirmedAuthentication.set(false)),- Effect.andThen(clearLiveState),- Effect.andThen(liveSnapshotSemaphore.withPermit(invalidateEnrichmentCache)),- Effect.andThen(snapshot.refresh),- Effect.asVoid,- ),- };+ return Option.isSome(runtimeCoordinator)+ ? provided.pipe(+ Effect.provideService(+ AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator,+ runtimeCoordinator.value,+ ),+ )+ : provided;+ };- return {- instanceId,- driverKind: DRIVER_KIND,- continuationIdentity,- displayName,- accentColor,- enabled,- auth,- snapshot: {- ...snapshot,- refresh: snapshot.refresh.pipe(- Effect.tap(() => controller.refreshMethods ?? Effect.void),+ const clearLiveState = Option.isSome(runtimeCoordinator)+ ? runtimeCoordinator.value+ .clearLiveConfiguration(instanceId)+ .pipe(Effect.andThen(runtimeCoordinator.value.clearAvailableCommands(instanceId)))+ : Effect.void;+ const controller = yield* AcpRegistryAuth.makeAcpRegistryAuth({+ instanceId,+ settings: effectiveConfig,+ cwd: host.paths.cwd,+ environment: processEnvironment,+ onChanged: (authenticated) =>+ confirmedAuthentication+ .set(authenticated)+ .pipe(+ Effect.andThen(authenticated ? Effect.void : clearLiveState),+ Effect.andThen(liveSnapshotSemaphore.withPermit(invalidateEnrichmentCache)),+ Effect.andThen(snapshot.refresh),+ Effect.asVoid,),- },- orchestrationAdapter,- textGeneration: makeUnsupportedTextGeneration(),- acpSessionManagement: {- listSessions: ({ cwd, cursor }) =>- provideAcpManagementServices(- listAcpRegistrySessions({- instanceId,- settings: effectiveConfig,- cwd,- environment: processEnvironment,- ...(cursor === undefined ? {} : { cursor }),- }),- ),- deleteSession: ({ cwd, sessionId }) =>- provideAcpManagementServices(- deleteAcpRegistrySession({- instanceId,- settings: effectiveConfig,- cwd,- environment: processEnvironment,- sessionId,- }),- ),- listProviders: (cwd) =>- provideAcpManagementServices(- listAcpRegistryProviders({- instanceId,- settings: effectiveConfig,- cwd,- environment: processEnvironment,- }),- ),- setProvider: ({ cwd, providerId, apiType, baseUrl, headers }) =>- provideAcpManagementServices(- setAcpRegistryProvider({- instanceId,- settings: effectiveConfig,- cwd,- environment: processEnvironment,- providerId,- apiType,- baseUrl,- ...(headers === undefined ? {} : { headers }),- }),- ).pipe(Effect.tap(() => liveSnapshotSemaphore.withPermit(invalidateEnrichmentCache))),- disableProvider: ({ cwd, providerId }) =>- provideAcpManagementServices(- disableAcpRegistryProvider({- instanceId,- settings: effectiveConfig,- cwd,- environment: processEnvironment,- providerId,- }),- ).pipe(Effect.tap(() => liveSnapshotSemaphore.withPermit(invalidateEnrichmentCache))),- logout: (cwd) => {- const logout = logoutAcpRegistry({+ }).pipe(+ Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog),+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),+ Effect.provideService(Crypto.Crypto, crypto),+ );+ const auth = {+ ...controller,+ invalidate: (controller.invalidate ?? Effect.void).pipe(+ Effect.andThen(confirmedAuthentication.set(false)),+ Effect.andThen(clearLiveState),+ Effect.andThen(liveSnapshotSemaphore.withPermit(invalidateEnrichmentCache)),+ Effect.andThen(snapshot.refresh),+ Effect.asVoid,+ ),+ };++ return {+ instanceId,+ driverKind: DRIVER_KIND,+ continuationIdentity,+ displayName,+ accentColor,+ enabled,+ auth,+ snapshot: {+ ...snapshot,+ refresh: snapshot.refresh.pipe(Effect.tap(() => controller.refreshMethods ?? Effect.void)),+ },+ orchestrationAdapter,+ textGeneration: makeUnsupportedTextGeneration(),+ acpSessionManagement: {+ listSessions: ({ cwd, cursor }) =>+ provideAcpManagementServices(+ listAcpRegistrySessions({instanceId,settings: effectiveConfig,cwd,environment: processEnvironment,- }).pipe(- Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog),- Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),- Effect.provideService(Crypto.Crypto, crypto),- Effect.tap(() => confirmedAuthentication.set(false)),- Effect.tap(() =>- liveSnapshotSemaphore.withPermit(- invalidateEnrichmentCache.pipe(- Effect.andThen(- Option.isSome(runtimeCoordinator)- ? Effect.all(- [- runtimeCoordinator.value.clearAvailableCommands(instanceId),- runtimeCoordinator.value.clearLiveConfiguration(instanceId),- ],- { concurrency: "unbounded", discard: true },- )- : Effect.void,- ),+ ...(cursor === undefined ? {} : { cursor }),+ }),+ ),+ deleteSession: ({ cwd, sessionId }) =>+ provideAcpManagementServices(+ deleteAcpRegistrySession({+ instanceId,+ settings: effectiveConfig,+ cwd,+ environment: processEnvironment,+ sessionId,+ }),+ ),+ listProviders: (cwd) =>+ provideAcpManagementServices(+ listAcpRegistryProviders({+ instanceId,+ settings: effectiveConfig,+ cwd,+ environment: processEnvironment,+ }),+ ),+ setProvider: ({ cwd, providerId, apiType, baseUrl, headers }) =>+ provideAcpManagementServices(+ setAcpRegistryProvider({+ instanceId,+ settings: effectiveConfig,+ cwd,+ environment: processEnvironment,+ providerId,+ apiType,+ baseUrl,+ ...(headers === undefined ? {} : { headers }),+ }),+ ).pipe(Effect.tap(() => liveSnapshotSemaphore.withPermit(invalidateEnrichmentCache))),+ disableProvider: ({ cwd, providerId }) =>+ provideAcpManagementServices(+ disableAcpRegistryProvider({+ instanceId,+ settings: effectiveConfig,+ cwd,+ environment: processEnvironment,+ providerId,+ }),+ ).pipe(Effect.tap(() => liveSnapshotSemaphore.withPermit(invalidateEnrichmentCache))),+ logout: (cwd) => {+ const logout = logoutAcpRegistry({+ instanceId,+ settings: effectiveConfig,+ cwd,+ environment: processEnvironment,+ }).pipe(+ Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog),+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),+ Effect.provideService(Crypto.Crypto, crypto),+ Effect.tap(() => confirmedAuthentication.set(false)),+ Effect.tap(() =>+ liveSnapshotSemaphore.withPermit(+ invalidateEnrichmentCache.pipe(+ Effect.andThen(+ Option.isSome(runtimeCoordinator)+ ? Effect.all(+ [+ runtimeCoordinator.value.clearAvailableCommands(instanceId),+ runtimeCoordinator.value.clearLiveConfiguration(instanceId),+ ],+ { concurrency: "unbounded", discard: true },+ )+ : Effect.void,),),),- );- return Option.isSome(runtimeCoordinator)- ? logout.pipe(- Effect.provideService(- AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator,- runtimeCoordinator.value,- ),- )- : logout;- },+ ),+ );+ return Option.isSome(runtimeCoordinator)+ ? logout.pipe(+ Effect.provideService(+ AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator,+ runtimeCoordinator.value,+ ),+ )+ : logout;},- } satisfies ProviderInstance;- }),+ },+ } satisfies ProviderInstance;+ }),};diff --git a/packages/provider-core/src/server/ProviderLatestVersions.ts b/packages/provider-core/src/server/ProviderLatestVersions.tsindex 57b7129e4fa..99884f368a2 100644--- a/packages/provider-core/src/server/ProviderLatestVersions.ts+++ b/packages/provider-core/src/server/ProviderLatestVersions.ts@@ -25,36 +25,33 @@ export class ProviderLatestVersions extends Context.Service<}>()("@t3tools/provider-core/server/ProviderLatestVersions") {}-export const make = (seed: Iterable<readonly [key: string, version: string | null]> = []) =>- Effect.gen(function* () {- const entries = yield* Ref.make(- new Map<string, Entry>(- Array.from(seed, ([key, version]) => [- key,- { version, expiresAt: Number.MAX_SAFE_INTEGER },- ]),- ),- );- return ProviderLatestVersions.of({- cached: (key, lookup, options) =>- Effect.gen(function* () {- const now = DateTime.toEpochMillis(yield* DateTime.now);- const existing = (yield* Ref.get(entries)).get(key);- if (!options?.fresh && existing && existing.expiresAt > now) return existing.version;- const version = yield* lookup;- const ttl = version === null ? MISSING_TTL : FOUND_TTL;- yield* Ref.update(entries, (current) =>- new Map(current).set(key, { version, expiresAt: now + Duration.toMillis(ttl) }),- );- return version;- }),- invalidate: (key) =>- Ref.update(entries, (current) => {- const next = new Map(current);- next.delete(key);- return next;- }),- });+export const make = Effect.fn("ProviderLatestVersions.make")(function* (+ seed: Iterable<readonly [key: string, version: string | null]> = [],+) {+ const entries = yield* Ref.make(+ new Map<string, Entry>(+ Array.from(seed, ([key, version]) => [key, { version, expiresAt: Number.MAX_SAFE_INTEGER }]),+ ),+ );+ return ProviderLatestVersions.of({+ cached: Effect.fn("ProviderLatestVersions.cached")(function* (key, lookup, options) {+ const now = DateTime.toEpochMillis(yield* DateTime.now);+ const existing = (yield* Ref.get(entries)).get(key);+ if (!options?.fresh && existing && existing.expiresAt > now) return existing.version;+ const version = yield* lookup;+ const ttl = version === null ? MISSING_TTL : FOUND_TTL;+ yield* Ref.update(entries, (current) =>+ new Map(current).set(key, { version, expiresAt: now + Duration.toMillis(ttl) }),+ );+ return version;+ }),+ invalidate: (key) =>+ Ref.update(entries, (current) => {+ const next = new Map(current);+ next.delete(key);+ return next;+ }),});+});export const layer = Layer.effect(ProviderLatestVersions, make());diff --git a/packages/provider-core/src/server/managedProvider.ts b/packages/provider-core/src/server/managedProvider.tsindex c63534c3a89..98ff340ddda 100644--- a/packages/provider-core/src/server/managedProvider.ts+++ b/packages/provider-core/src/server/managedProvider.ts@@ -192,8 +192,9 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(const applySnapshot = (nextSettings: Settings, options?: { readonly forceRefresh?: boolean }) =>refreshSemaphore.withPermits(1)(applySnapshotBase(nextSettings, options));- const applyUsageLimits: ManagedServerProvider["applyUsageLimits"] = (update) =>- Effect.gen(function* () {+ // Providers call this on every token-usage tick, usually without changing the snapshot.+ const applyUsageLimits: ManagedServerProvider["applyUsageLimits"] = Effect.fnUntraced(+ function* (update) {const snapshotToPublish = yield* Ref.modify(snapshotStateRef, (state) => {const usageLimits = applyUsageLimitsUpdate({previous: state.snapshot.usageLimits,@@ -209,7 +210,8 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(if (snapshotToPublish !== null) {yield* PubSub.publish(changesPubSub, snapshotToPublish);}- });+ },+ );const refreshSnapshot = Effect.fn("refreshSnapshot")(function* () {const nextSettings = yield* input.getSettings;diff --git a/packages/provider-core/src/server/providerAuthFlow.ts b/packages/provider-core/src/server/providerAuthFlow.tsindex c596f8ebc3e..7e30eab3147 100644--- a/packages/provider-core/src/server/providerAuthFlow.ts+++ b/packages/provider-core/src/server/providerAuthFlow.ts@@ -140,40 +140,42 @@ export const make = Effect.fn("ProviderAuthFlow.make")(function* (options: {const controller: ProviderAuth.ProviderAuthController = {credentialBinding: options.credentialBinding,- adoptCredentials: (update, stopSessions) =>- Effect.gen(function* () {- yield* lock.withPermit(- Effect.gen(function* () {- if (operation !== "idle")- return yield* new ProviderSetupError({- instanceId: options.instanceId,- operation: "import",- detail: "Finish or cancel the existing sign-in first.",- });- operation = "stopping";- }),- );- const result = yield* Effect.gen(function* () {- yield* stopOwnedSessions;- yield* stopSessions;- yield* update;- yield* refreshMethods;- }).pipe(Effect.exit);- const state: ProviderAuthState = {- ...empty,- methods: snapshot.value.state.methods ?? [],- phase: Exit.isSuccess(result) ? "succeeded" : "failed",- message: Exit.isSuccess(result) ? null : failureMessage(result.cause),- };- yield* lock.withPermit(- Effect.gen(function* () {- yield* SubscriptionRef.set(snapshot, { owner: null, state });- operation = "idle";- }),- );- if (Exit.isFailure(result)) return yield* Effect.failCause(result.cause);- return state;- }).pipe(Effect.uninterruptible),+ adoptCredentials: Effect.fn("providerAuthFlow.adoptCredentials")(function* (+ update,+ stopSessions,+ ) {+ yield* lock.withPermit(+ Effect.gen(function* () {+ if (operation !== "idle")+ return yield* new ProviderSetupError({+ instanceId: options.instanceId,+ operation: "import",+ detail: "Finish or cancel the existing sign-in first.",+ });+ operation = "stopping";+ }),+ );+ const result = yield* Effect.gen(function* () {+ yield* stopOwnedSessions;+ yield* stopSessions;+ yield* update;+ yield* refreshMethods;+ }).pipe(Effect.exit);+ const state: ProviderAuthState = {+ ...empty,+ methods: snapshot.value.state.methods ?? [],+ phase: Exit.isSuccess(result) ? "succeeded" : "failed",+ message: Exit.isSuccess(result) ? null : failureMessage(result.cause),+ };+ yield* lock.withPermit(+ Effect.gen(function* () {+ yield* SubscriptionRef.set(snapshot, { owner: null, state });+ operation = "idle";+ }),+ );+ if (Exit.isFailure(result)) return yield* Effect.failCause(result.cause);+ return state;+ }, Effect.uninterruptible),refreshMethods,invalidate: lock.withPermit(Effect.gen(function* () {@@ -279,21 +281,21 @@ export const make = Effect.fn("ProviderAuthFlow.make")(function* (options: {expiresAt: flow.expiresAt,...(returnUrl ? { returnUrl } : {}),...(callbackMode ? { callbackMode } : {}),- setInteraction: (interaction, respond, complete) =>- Effect.gen(function* () {- if (active !== flow) return;- flow.respond = respond;- flow.complete = complete;- yield* publish(flow, {- phase: "waiting",- interaction,- authorizationUrl:- interaction.type === "browser" || interaction.type === "deviceCode"- ? interaction.url- : null,- message: "Complete sign-in to continue.",- });- }),+ // Terminal sign-in updates this for every output chunk within the auth operation.+ setInteraction: Effect.fnUntraced(function* (interaction, respond, complete) {+ if (active !== flow) return;+ flow.respond = respond;+ flow.complete = complete;+ yield* publish(flow, {+ phase: "waiting",+ interaction,+ authorizationUrl:+ interaction.type === "browser" || interaction.type === "deviceCode"+ ? interaction.url+ : null,+ message: "Complete sign-in to continue.",+ });+ }),verifying: Effect.gen(function* () {flow.respond = undefined;flow.complete = undefined;@@ -424,69 +426,67 @@ export const make = Effect.fn("ProviderAuthFlow.make")(function* (options: {return snapshot.value.state;}),),- cancel: (owner, id) =>- Effect.gen(function* () {- const flow = yield* lock.withPermit(- Effect.gen(function* () {- const flow = yield* requireFlow(owner, id);- yield* publish(flow, {- phase: "cancelled",- interaction: null,- authorizationUrl: null,- expiresAt: null,- message: "Sign-in cancelled.",+ cancel: Effect.fn("providerAuthFlow.cancel")(function* (owner, id) {+ const flow = yield* lock.withPermit(+ Effect.gen(function* () {+ const flow = yield* requireFlow(owner, id);+ yield* publish(flow, {+ phase: "cancelled",+ interaction: null,+ authorizationUrl: null,+ expiresAt: null,+ message: "Sign-in cancelled.",+ });+ active = undefined;+ operation = "stopping";+ return flow;+ }),+ );+ if (flow.responseFiber) yield* Fiber.interrupt(flow.responseFiber);+ if (flow.fiber) yield* Fiber.interrupt(flow.fiber);+ operation = "idle";+ return snapshot.value.state;+ }, Effect.uninterruptible),+ logout: Effect.fn("providerAuthFlow.logout")(function* (stopSessions) {+ const flow = yield* lock.withPermit(+ Effect.gen(function* () {+ if (operation !== "idle" && operation !== "auth")+ return yield* new ProviderSetupError({+ instanceId: options.instanceId,+ operation: "logout",+ detail: "Provider setup is already stopping.",});- active = undefined;- operation = "stopping";- return flow;- }),- );- if (flow.responseFiber) yield* Fiber.interrupt(flow.responseFiber);- if (flow.fiber) yield* Fiber.interrupt(flow.fiber);- operation = "idle";- return snapshot.value.state;- }).pipe(Effect.uninterruptible),- logout: (stopSessions) =>- Effect.gen(function* () {- const flow = yield* lock.withPermit(- Effect.gen(function* () {- if (operation !== "idle" && operation !== "auth")- return yield* new ProviderSetupError({- instanceId: options.instanceId,- operation: "logout",- detail: "Provider setup is already stopping.",- });- operation = "stopping";- const flow = active;- active = undefined;- return flow;- }),- );- const result = yield* Effect.gen(function* () {- if (flow?.responseFiber) yield* Fiber.interrupt(flow.responseFiber);- if (flow?.fiber) yield* Fiber.interrupt(flow.fiber);- yield* stopSessions.pipe(Effect.ensuring(stopOwnedSessions));- const message = yield* options.logout;- if (options.refreshMethodsAfterAuth) yield* refreshMethods;- return message;- }).pipe(Effect.exit);- const state: ProviderAuthState = {- ...empty,- methods: snapshot.value.state.methods ?? [],- phase: Exit.isSuccess(result) ? "idle" : "failed",- message: Exit.isSuccess(result)- ? (result.value ?? "Signed out.")- : "Could not sign out. Try again.",- };- yield* lock.withPermit(- Effect.gen(function* () {- yield* SubscriptionRef.set(snapshot, { owner: null, state });- operation = "idle";- }),- );- if (Exit.isFailure(result)) return yield* Effect.failCause(result.cause);- return state;- }).pipe(Effect.uninterruptible),+ operation = "stopping";+ const flow = active;+ active = undefined;+ return flow;+ }),+ );+ const result = yield* Effect.gen(function* () {+ if (flow?.responseFiber) yield* Fiber.interrupt(flow.responseFiber);+ if (flow?.fiber) yield* Fiber.interrupt(flow.fiber);+ yield* stopSessions.pipe(Effect.ensuring(stopOwnedSessions));+ const message = yield* options.logout;+ if (options.refreshMethodsAfterAuth) yield* refreshMethods;+ return message;+ }).pipe(Effect.exit);+ const state: ProviderAuthState = {+ ...empty,+ methods: snapshot.value.state.methods ?? [],+ phase: Exit.isSuccess(result) ? "idle" : "failed",+ message: Exit.isSuccess(result)+ ? (result.value ?? "Signed out.")+ : "Could not sign out. Try again.",+ };+ yield* lock.withPermit(+ Effect.gen(function* () {+ yield* SubscriptionRef.set(snapshot, { owner: null, state });+ operation = "idle";+ }),+ );+ if (Exit.isFailure(result)) return yield* Effect.failCause(result.cause);+ return state;+ }, Effect.uninterruptible),subscribe: (owner) =>SubscriptionRef.changes(snapshot).pipe(Stream.map((current) =>diff --git a/packages/provider-core/src/server/snapshotProbe.ts b/packages/provider-core/src/server/snapshotProbe.tsindex b3f1ee5a283..75ca132579d 100644--- a/packages/provider-core/src/server/snapshotProbe.ts+++ b/packages/provider-core/src/server/snapshotProbe.ts@@ -105,30 +105,32 @@ export function isCommandMissingCause(error: unknown): boolean {return error instanceof PlatformError.PlatformError && error.reason._tag === "NotFound";}-export const spawnAndCollect = (binaryPath: string, command: ChildProcess.Command) =>- Effect.gen(function* () {- const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;- const child = yield* spawner.spawn(command);- const [stdout, stderr, exitCode] = yield* Effect.all(- [- collectStreamAsString(child.stdout),- collectStreamAsString(child.stderr),- child.exitCode.pipe(Effect.map(Number)),- ],- { concurrency: "unbounded" },- );+export const spawnAndCollect = Effect.fn("snapshotProbe.spawnAndCollect")(function* (+ binaryPath: string,+ command: ChildProcess.Command,+) {+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;+ const child = yield* spawner.spawn(command);+ const [stdout, stderr, exitCode] = yield* Effect.all(+ [+ collectStreamAsString(child.stdout),+ collectStreamAsString(child.stderr),+ child.exitCode.pipe(Effect.map(Number)),+ ],+ { concurrency: "unbounded" },+ );- const result: CommandResult = { stdout, stderr, code: exitCode };- if (yield* isWindowsCommandNotFound(exitCode, stderr)) {- return yield* new ProviderCommandNotFoundError({- binaryPath,- exitCode,- stdoutLength: stdout.length,- stderrLength: stderr.length,- });- }- return result;- }).pipe(Effect.scoped);+ const result: CommandResult = { stdout, stderr, code: exitCode };+ if (yield* isWindowsCommandNotFound(exitCode, stderr)) {+ return yield* new ProviderCommandNotFoundError({+ binaryPath,+ exitCode,+ stdoutLength: stdout.length,+ stderrLength: stderr.length,+ });+ }+ return result;+}, Effect.scoped);export function parseGenericCliVersion(output: string): string | null {// "opencode v2.0.3"-style output: the optional "v" has to be consumed first,diff --git a/packages/provider-core/src/server/snapshotSettings.ts b/packages/provider-core/src/server/snapshotSettings.tsindex aa2991b47d5..299911fcab9 100644--- a/packages/provider-core/src/server/snapshotSettings.ts+++ b/packages/provider-core/src/server/snapshotSettings.ts@@ -27,22 +27,20 @@ export function haveProviderSnapshotSettingsChanged<Settings>(return !Equal.equals(previous, next);}-export const makeProviderSnapshotSettingsSource = <Settings>(- provider: Settings,-): Effect.Effect<+export const makeProviderSnapshotSettingsSource = Effect.fn(+ "snapshotSettings.makeProviderSnapshotSettingsSource",+)(function* <Settings>(provider: Settings): Effect.fn.Return<{readonly getSettings: Effect.Effect<ProviderSnapshotSettings<Settings>, ServerSettingsError>;readonly streamSettings: Stream.Stream<ProviderSnapshotSettings<Settings>>;},never,ProviderHost.ProviderHost-> =>- Effect.gen(function* () {- const { settings } = yield* ProviderHost.ProviderHost;- const mapSettings = (current: ServerSettings) =>- makeProviderSnapshotSettings(provider, current);- return {- getSettings: settings.get.pipe(Effect.map(mapSettings)),- streamSettings: settings.changes.pipe(Stream.map(mapSettings)),- };- });+> {+ const { settings } = yield* ProviderHost.ProviderHost;+ const mapSettings = (current: ServerSettings) => makeProviderSnapshotSettings(provider, current);+ return {+ getSettings: settings.get.pipe(Effect.map(mapSettings)),+ streamSettings: settings.changes.pipe(Stream.map(mapSettings)),+ };+});diff --git a/packages/provider-core/src/server/subagentProjection.ts b/packages/provider-core/src/server/subagentProjection.tsindex 8ebdfbceb45..d5e87153ea1 100644--- a/packages/provider-core/src/server/subagentProjection.ts+++ b/packages/provider-core/src/server/subagentProjection.ts@@ -276,17 +276,17 @@ function writtenIds(return new Set(emitted.flatMap((event) => (event.type === type ? [event.payload.id] : [])));}-export const endOrphanedNativeSubagent = <E>(input: {- readonly projection: Pick<OrchestrationV2ThreadProjection, "nodes" | "subagents" | "turnItems">;- readonly subagentId: NodeId;- readonly status: "completed" | "failed" | "interrupted" | "cancelled";- readonly completedAt?: DateTime.Utc;- readonly result?: string | null;- readonly now: DateTime.Utc;- readonly emitted: ReadonlyArray<OrchestrationV2DomainEvent>;- readonly allocateEventId: () => Effect.Effect<EventId, E>;-}) =>- Effect.gen(function* () {+export const endOrphanedNativeSubagent = Effect.fn("subagentProjection.endOrphanedNativeSubagent")(+ function* <E>(input: {+ readonly projection: Pick<OrchestrationV2ThreadProjection, "nodes" | "subagents" | "turnItems">;+ readonly subagentId: NodeId;+ readonly status: "completed" | "failed" | "interrupted" | "cancelled";+ readonly completedAt?: DateTime.Utc;+ readonly result?: string | null;+ readonly now: DateTime.Utc;+ readonly emitted: ReadonlyArray<OrchestrationV2DomainEvent>;+ readonly allocateEventId: () => Effect.Effect<EventId, E>;+ }) {const { now, status, subagentId, completedAt = now } = input;const subagent = input.projection.subagents.find((entry) => entry.id === subagentId);if (subagent?.origin !== "provider_native") return [];@@ -351,9 +351,12 @@ export const endOrphanedNativeSubagent = <E>(input: {});}return events;- });+ },+);-export const endRunlessRootTurns = <E>(input: {+export const endRunlessRootTurns = Effect.fn("subagentProjection.endRunlessRootTurns")(function* <+ E,+>(input: {readonly threadId: ThreadId;readonly providerInstanceId: ProviderInstanceId;readonly projection: Pick<OrchestrationV2ThreadProjection, "nodes" | "turnItems">;@@ -362,63 +365,62 @@ export const endRunlessRootTurns = <E>(input: {readonly now: DateTime.Utc;readonly emitted: ReadonlyArray<OrchestrationV2DomainEvent>;readonly allocateEventId: () => Effect.Effect<EventId, E>;-}) =>- Effect.gen(function* () {- const { now, status, completedAt = now } = input;- const endedNodeIds = writtenIds(input.emitted, "node.updated");- const endedItemIds = writtenIds(input.emitted, "turn-item.updated");- const scope = {- threadId: input.threadId,- providerInstanceId: input.providerInstanceId,- occurredAt: now,- };- const events: Array<OrchestrationV2DomainEvent> = [];- for (const node of input.projection.nodes) {+}) {+ const { now, status, completedAt = now } = input;+ const endedNodeIds = writtenIds(input.emitted, "node.updated");+ const endedItemIds = writtenIds(input.emitted, "turn-item.updated");+ const scope = {+ threadId: input.threadId,+ providerInstanceId: input.providerInstanceId,+ occurredAt: now,+ };+ const events: Array<OrchestrationV2DomainEvent> = [];+ for (const node of input.projection.nodes) {+ if (+ node.kind !== "root_turn" ||+ node.runId !== null ||+ !isOrchestrationV2WorkActive(node.status)+ ) {+ continue;+ }+ if (!endedNodeIds.has(node.id)) {+ events.push({+ ...scope,+ id: yield* input.allocateEventId(),+ type: "node.updated",+ nodeId: node.id,+ payload: { ...node, status, completedAt },+ });+ }+ for (const item of input.projection.turnItems) {if (- node.kind !== "root_turn" ||- node.runId !== null ||- !isOrchestrationV2WorkActive(node.status)+ item.nodeId !== node.id ||+ item.runId !== null ||+ !isOrchestrationV2WorkActive(item.status) ||+ endedItemIds.has(item.id)) {continue;}- if (!endedNodeIds.has(node.id)) {- events.push({- ...scope,- id: yield* input.allocateEventId(),- type: "node.updated",- nodeId: node.id,- payload: { ...node, status, completedAt },- });- }- for (const item of input.projection.turnItems) {- if (- item.nodeId !== node.id ||- item.runId !== null ||- !isOrchestrationV2WorkActive(item.status) ||- endedItemIds.has(item.id)- ) {- continue;- }- events.push({- ...scope,- id: yield* input.allocateEventId(),- type: "turn-item.updated",- nodeId: node.id,- payload: {- ...item,- status:- status === "completed" &&- (item.type === "command_execution" || item.type === "dynamic_tool")- ? "failed"- : status,- completedAt,- updatedAt: now,- ...(item.type === "reasoning" || item.type === "assistant_message"- ? { streaming: false }- : {}),- },- });- }+ events.push({+ ...scope,+ id: yield* input.allocateEventId(),+ type: "turn-item.updated",+ nodeId: node.id,+ payload: {+ ...item,+ status:+ status === "completed" &&+ (item.type === "command_execution" || item.type === "dynamic_tool")+ ? "failed"+ : status,+ completedAt,+ updatedAt: now,+ ...(item.type === "reasoning" || item.type === "assistant_message"+ ? { streaming: false }+ : {}),+ },+ });}- return events;- });+ }+ return events;+});