The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 23, 00:30 UTC
refactor(provider): trace provider runtime operations (#21991)
Julius Marminge committed
Oct 19, 2026 at 18:30 UTC
0878d3f4d4636b277bab78034b7cf6782669361c
10 files changed
+779
-775
packages/effect-codex-app-server/src/protocol.ts
+24
-21
@@ -217,8 +217,9 @@ export const makeCodexAppServerPatchedProtocol = Effect.fn("makeCodexAppServerPa
217
] as const;
218
}).pipe(Effect.flatten);
219
220
- const offerOutgoing = (message: Record<string, unknown>) =>
221
- Effect.gen(function* () {
220
+ const offerOutgoing =
221
+ /* Every protocol write reaches this helper; request spans cover the operation. */
222
+ Effect.fnUntraced(function* (message: Record<string, unknown>) {
223
const failure = yield* Ref.get(terminationFailure);
224
if (Option.isSome(failure)) return yield* failure.value;
225
@@ -447,25 +448,27 @@ export const makeCodexAppServerPatchedProtocol = Effect.fn("makeCodexAppServerPa
448
449
yield* Stream.fromQueue(outgoing).pipe(Stream.run(options.stdio.stdout()), Effect.forkScoped);
450
450
- const request = (method: string, payload?: unknown) =>
451
- Effect.gen(function* () {
452
- const requestId = yield* Ref.modify(
453
- nextRequestId,
454
- (current) => [current, current + 1] as const,
455
- );
456
- const deferred = yield* Deferred.make<unknown, CodexError.CodexAppServerError>();
457
- yield* Ref.update(pending, (current) =>
458
- new Map(current).set(String(requestId), { deferred, method }),
459
- );
460
- yield* offerOutgoing({
461
- id: requestId,
462
- method,
463
- ...(payload !== undefined ? { params: payload } : {}),
464
- }).pipe(Effect.tapError(() => removePending(String(requestId))));
465
- return yield* Deferred.await(deferred).pipe(
466
- Effect.onInterrupt(() => removePending(String(requestId))),
467
- );
468
- });
451
+ const request = Effect.fn("CodexAppServerProtocol.request")(function* (
452
+ method: string,
453
+ payload?: unknown,
454
+ ) {
455
+ const requestId = yield* Ref.modify(
456
+ nextRequestId,
457
+ (current) => [current, current + 1] as const,
458
+ );
459
+ const deferred = yield* Deferred.make<unknown, CodexError.CodexAppServerError>();
460
+ yield* Ref.update(pending, (current) =>
461
+ new Map(current).set(String(requestId), { deferred, method }),
462
+ );
463
+ yield* offerOutgoing({
464
+ id: requestId,
465
+ method,
466
+ ...(payload !== undefined ? { params: payload } : {}),
467
+ }).pipe(Effect.tapError(() => removePending(String(requestId))));
468
+ return yield* Deferred.await(deferred).pipe(
469
+ Effect.onInterrupt(() => removePending(String(requestId))),
470
+ );
471
+ });
472
473
const notify = (method: string, payload?: unknown) =>
474
offerOutgoing({
packages/provider-acp-registry/src/server/AcpRegistrySupport.ts
+16
-12
@@ -1589,8 +1589,8 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct
1589
return distribution;
1590
});
1591
1592
- const search: AcpRegistryCatalog["Service"]["search"] = (input) =>
1593
- Effect.gen(function* () {
1592
+ const search: AcpRegistryCatalog["Service"]["search"] = Effect.fn("AcpRegistryCatalog.search")(
1593
+ function* (input) {
1594
const registry = yield* refreshRegistry();
1595
const ranked = registry.agents.flatMap((agent) => {
1596
const distribution = resolveAcpRegistryDistribution({
@@ -1632,10 +1632,11 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct
1632
: "registry",
1633
})),
1634
} satisfies AcpRegistrySearchResult;
1635
- });
1635
+ },
1636
+ );
1637
1637
- const prepare: AcpRegistryCatalog["Service"]["prepare"] = (input) =>
1638
- Effect.gen(function* () {
1638
+ const prepare: AcpRegistryCatalog["Service"]["prepare"] = Effect.fn("AcpRegistryCatalog.prepare")(
1639
+ function* (input) {
1640
const registry = yield* refreshRegistry();
1641
const agent = yield* findAgent(registry, input.agentId);
1642
const distribution = yield* compatibleDistribution(agent, "auto");
@@ -1658,7 +1659,8 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct
1659
distribution: distribution.kind,
1660
prepared: true,
1661
} satisfies AcpRegistryPrepareResult;
1661
- });
1662
+ },
1663
+ );
1664
1665
const validateLocalExecutable = (command: string) =>
1666
platform === "win32" && /\.(?:cmd|bat)$/iu.test(command)
@@ -1671,8 +1673,8 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct
1673
)
1674
: Effect.void;
1675
1674
- const inspect: AcpRegistryCatalog["Service"]["inspect"] = (settings, environment) =>
1675
- Effect.gen(function* () {
1676
+ const inspect: AcpRegistryCatalog["Service"]["inspect"] = Effect.fn("AcpRegistryCatalog.inspect")(
1677
+ function* (settings, environment) {
1678
if (settings.source === "local") {
1679
const command = settings.commandPath.trim();
1680
if (!command) return { status: "unconfigured" } as const;
@@ -1782,10 +1784,11 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct
1784
distribution: distribution.kind,
1785
runner,
1786
} as const);
1785
- });
1787
+ },
1788
+ );
1789
1787
- const resolve: AcpRegistryCatalog["Service"]["resolve"] = (settings, cwd, environment) =>
1788
- Effect.gen(function* () {
1790
+ const resolve: AcpRegistryCatalog["Service"]["resolve"] = Effect.fn("AcpRegistryCatalog.resolve")(
1791
+ function* (settings, cwd, environment) {
1792
if (settings.source === "local") {
1793
const executable = settings.commandPath.trim();
1794
if (!executable) {
@@ -1875,7 +1878,8 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct
1878
env: spawnEnvironment,
1879
},
1880
} satisfies ResolvedAcpRegistryAgent;
1878
- });
1881
+ },
1882
+ );
1883
1884
const uninstallManagedBinary: AcpRegistryCatalog["Service"]["uninstallManagedBinary"] = (input) =>
1885
hostSettings
packages/provider-acp-registry/src/server/auth.ts
+87
-92
@@ -227,109 +227,104 @@ export const makeAcpRegistryAuth = Effect.fn("makeAcpRegistryAuth")(function* (o
227
return yield* failure("start", "The provider login command did not finish successfully.");
228
});
229
230
- const authenticate = (methodId: string, context: ProviderAuthFlow.ProviderAuthFlowContext) =>
231
- Effect.gen(function* () {
232
- if (!options.settings.enabled)
233
- return yield* failure("start", "Enable this provider before signing in.");
234
- const login = Effect.scoped(
235
- Effect.gen(function* () {
236
- const resolved = yield* resolve;
237
- const runtimeScope = yield* Scope.make();
238
- yield* Effect.addFinalizer(() => Scope.close(runtimeScope, Exit.void));
239
- const runtime = yield* makeRuntime(resolved.spawn).pipe(
240
- Effect.provideService(Scope.Scope, runtimeScope),
241
- );
242
- yield* runtime.handleElicitation((request) =>
243
- Effect.gen(function* () {
244
- if (
245
- request.mode !== "url" ||
246
- !("url" in request) ||
247
- !("elicitationId" in request) ||
248
- typeof request.url !== "string" ||
249
- typeof request.elicitationId !== "string"
250
- )
251
- return { action: "decline" } as const;
252
- const url = normalizeAcpRegistryWebUrl(request.url);
253
- const id = request.elicitationId.trim();
254
- if (!url || !id || id.length > 128) return { action: "decline" } as const;
255
- const consent = yield* Deferred.make<boolean>();
256
- yield* context.setInteraction(
257
- { type: "browser", id, url, requiresConsent: true },
258
- (response) =>
259
- response.type === "browser"
260
- ? Deferred.succeed(consent, response.action === "accept").pipe(Effect.asVoid)
261
- : Effect.void,
262
- );
263
- return (yield* Deferred.await(consent))
264
- ? ({ action: "accept" } as const)
265
- : ({ action: "decline" } as const);
266
- }),
230
+ const authenticate = Effect.fn("AcpRegistryAuth.authenticate")(function* (
231
+ methodId: string,
232
+ context: ProviderAuthFlow.ProviderAuthFlowContext,
233
+ ) {
234
+ if (!options.settings.enabled)
235
+ return yield* failure("start", "Enable this provider before signing in.");
236
+ const login = Effect.scoped(
237
+ Effect.gen(function* () {
238
+ const resolved = yield* resolve;
239
+ const runtimeScope = yield* Scope.make();
240
+ yield* Effect.addFinalizer(() => Scope.close(runtimeScope, Exit.void));
241
+ const runtime = yield* makeRuntime(resolved.spawn).pipe(
242
+ Effect.provideService(Scope.Scope, runtimeScope),
243
+ );
244
+ yield* runtime.handleElicitation((request) =>
245
+ Effect.gen(function* () {
246
+ if (
247
+ request.mode !== "url" ||
248
+ !("url" in request) ||
249
+ !("elicitationId" in request) ||
250
+ typeof request.url !== "string" ||
251
+ typeof request.elicitationId !== "string"
252
+ )
253
+ return { action: "decline" } as const;
254
+ const url = normalizeAcpRegistryWebUrl(request.url);
255
+ const id = request.elicitationId.trim();
256
+ if (!url || !id || id.length > 128) return { action: "decline" } as const;
257
+ const consent = yield* Deferred.make<boolean>();
258
+ yield* context.setInteraction(
259
+ { type: "browser", id, url, requiresConsent: true },
260
+ (response) =>
261
+ response.type === "browser"
262
+ ? Deferred.succeed(consent, response.action === "accept").pipe(Effect.asVoid)
263
+ : Effect.void,
264
+ );
265
+ return (yield* Deferred.await(consent))
266
+ ? ({ action: "accept" } as const)
267
+ : ({ action: "decline" } as const);
268
+ }),
269
+ );
270
+ const initialized = yield* runtime
271
+ .initialize()
272
+ .pipe(
273
+ Effect.mapError((cause) =>
274
+ failure("start", "Could not initialize the selected ACP agent.", cause),
275
+ ),
276
);
268
- const initialized = yield* runtime
269
- .initialize()
277
+ const method = initialized.authMethods?.find((method) => method.id === methodId);
278
+ if (!method)
279
+ return yield* failure("start", "The agent no longer advertises this sign-in method.");
280
+ if (method.type === "terminal") {
281
+ yield* Scope.close(runtimeScope, Exit.void);
282
+ yield* runTerminal(resolved, method, context).pipe(Effect.scoped);
283
+ // Terminal login is a separate invocation. Reconnect after it exits so
284
+ // the ACP process reads the credentials its login command persisted.
285
+ const verifiedRuntime = yield* makeRuntime(resolved.spawn);
286
+ yield* context.verifying;
287
+ yield* verifiedRuntime
288
+ .start()
289
.pipe(
290
Effect.mapError((cause) =>
272
- failure("start", "Could not initialize the selected ACP agent.", cause),
291
+ failure(
292
+ "verify",
293
+ "The provider could not create a session after terminal sign-in.",
294
+ cause,
295
+ ),
296
),
297
);
275
- const method = initialized.authMethods?.find((method) => method.id === methodId);
276
- if (!method)
277
- return yield* failure("start", "The agent no longer advertises this sign-in method.");
278
- if (method.type === "terminal") {
279
- yield* Scope.close(runtimeScope, Exit.void);
280
- yield* runTerminal(resolved, method, context).pipe(Effect.scoped);
281
- // Terminal login is a separate invocation. Reconnect after it exits so
282
- // the ACP process reads the credentials its login command persisted.
283
- const verifiedRuntime = yield* makeRuntime(resolved.spawn);
284
- yield* context.verifying;
285
- yield* verifiedRuntime
286
- .start()
287
- .pipe(
288
- Effect.mapError((cause) =>
289
- failure(
290
- "verify",
291
- "The provider could not create a session after terminal sign-in.",
292
- cause,
293
- ),
294
- ),
295
- );
296
- } else {
297
- if (method.type === undefined || method.type === "agent") {
298
- if (!runtime.authenticate)
299
- return yield* failure(
300
- "start",
301
- "This runtime does not support explicit ACP sign-in.",
302
- );
303
- yield* runtime
304
- .authenticate(methodId)
305
- .pipe(
306
- Effect.mapError((cause) =>
307
- failure("start", "The ACP agent could not complete sign-in.", cause),
308
- ),
309
- );
310
- }
311
- // Legacy env_var methods use the secret-backed environment fields in
312
- // provider settings. Never send their ID to authenticate.
313
- yield* context.verifying;
298
+ } else {
299
+ if (method.type === undefined || method.type === "agent") {
300
+ if (!runtime.authenticate)
301
+ return yield* failure("start", "This runtime does not support explicit ACP sign-in.");
302
yield* runtime
315
- .start()
303
+ .authenticate(methodId)
304
.pipe(
305
Effect.mapError((cause) =>
318
- failure(
319
- "verify",
320
- "The provider could not create a session after sign-in.",
321
- cause,
322
- ),
306
+ failure("start", "The ACP agent could not complete sign-in.", cause),
307
),
308
);
309
}
326
- }),
327
- );
328
- yield* Option.isSome(coordinator)
329
- ? coordinator.value.withForegroundStartup(agentKey, login)
330
- : login;
331
- yield* options.onChanged(true);
332
- });
310
+ // Legacy env_var methods use the secret-backed environment fields in
311
+ // provider settings. Never send their ID to authenticate.
312
+ yield* context.verifying;
313
+ yield* runtime
314
+ .start()
315
+ .pipe(
316
+ Effect.mapError((cause) =>
317
+ failure("verify", "The provider could not create a session after sign-in.", cause),
318
+ ),
319
+ );
320
+ }
321
+ }),
322
+ );
323
+ yield* Option.isSome(coordinator)
324
+ ? coordinator.value.withForegroundStartup(agentKey, login)
325
+ : login;
326
+ yield* options.onChanged(true);
327
+ });
328
const logout = Effect.scoped(
329
Effect.gen(function* () {
330
const resolved = yield* resolve;
packages/provider-acp-registry/src/server/driver.ts
+403
-402
@@ -464,438 +464,439 @@ export const AcpRegistryDriver: ProviderDriver<AcpRegistrySettings, AcpRegistryD
464
},
465
configSchema: AcpRegistrySettings,
466
defaultConfig: () => decodeSettings({}),
467
- create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
468
- Effect.gen(function* () {
469
- const catalog = yield* AcpRegistrySupport.AcpRegistryCatalog;
470
- const runtimeCoordinator = yield* Effect.serviceOption(
471
- AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator,
472
- );
473
- if (Option.isSome(runtimeCoordinator)) {
474
- yield* runtimeCoordinator.value.clearAvailableCommands(instanceId);
475
- yield* runtimeCoordinator.value.clearLiveConfiguration(instanceId);
476
- yield* Effect.addFinalizer(() =>
477
- runtimeCoordinator.value
478
- .clearAvailableCommands(instanceId)
479
- .pipe(Effect.andThen(runtimeCoordinator.value.clearLiveConfiguration(instanceId))),
480
- );
481
- }
482
- const crypto = yield* Crypto.Crypto;
483
- const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
484
- const hostEnvironment = yield* HostProcess.Environment;
485
- const host = yield* ProviderHost.ProviderHost;
486
- const continuationIdentity = defaultProviderContinuationIdentity({
487
- driverKind: DRIVER_KIND,
488
- instanceId,
489
- });
490
- const identity = {
491
- instanceId,
492
- displayName,
493
- accentColor,
494
- continuationKey: continuationIdentity.continuationKey,
495
- };
496
- const effectiveConfig = { ...config, enabled } satisfies AcpRegistrySettings;
497
- const processEnvironment = yield* mergeProviderInstanceEnvironment(
498
- environment,
499
- hostEnvironment,
467
+ create: Effect.fn("AcpRegistryDriver.create")(function* ({
468
+ instanceId,
469
+ displayName,
470
+ accentColor,
471
+ environment,
472
+ enabled,
473
+ config,
474
+ }) {
475
+ const catalog = yield* AcpRegistrySupport.AcpRegistryCatalog;
476
+ const runtimeCoordinator = yield* Effect.serviceOption(
477
+ AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator,
478
+ );
479
+ if (Option.isSome(runtimeCoordinator)) {
480
+ yield* runtimeCoordinator.value.clearAvailableCommands(instanceId);
481
+ yield* runtimeCoordinator.value.clearLiveConfiguration(instanceId);
482
+ yield* Effect.addFinalizer(() =>
483
+ runtimeCoordinator.value
484
+ .clearAvailableCommands(instanceId)
485
+ .pipe(Effect.andThen(runtimeCoordinator.value.clearLiveConfiguration(instanceId))),
486
);
501
- const orchestrationAdapter = yield* AcpRegistryAdapterV2Driver.create({
487
+ }
488
+ const crypto = yield* Crypto.Crypto;
489
+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
490
+ const hostEnvironment = yield* HostProcess.Environment;
491
+ const host = yield* ProviderHost.ProviderHost;
492
+ const continuationIdentity = defaultProviderContinuationIdentity({
493
+ driverKind: DRIVER_KIND,
494
+ instanceId,
495
+ });
496
+ const identity = {
497
+ instanceId,
498
+ displayName,
499
+ accentColor,
500
+ continuationKey: continuationIdentity.continuationKey,
501
+ };
502
+ const effectiveConfig = { ...config, enabled } satisfies AcpRegistrySettings;
503
+ const processEnvironment = yield* mergeProviderInstanceEnvironment(
504
+ environment,
505
+ hostEnvironment,
506
+ );
507
+ const orchestrationAdapter = yield* AcpRegistryAdapterV2Driver.create({
508
+ instanceId,
509
+ displayName,
510
+ accentColor,
511
+ environment,
512
+ enabled,
513
+ config,
514
+ }).pipe(
515
+ Effect.mapError(
516
+ (cause) =>
517
+ new ProviderDriverError({
518
+ driver: DRIVER_KIND,
519
+ instanceId,
520
+ detail: "Failed to build ACP Registry orchestration adapter.",
521
+ cause,
522
+ }),
523
+ ),
524
+ );
525
+ const readinessInput = {
526
+ ...identity,
527
+ settings: effectiveConfig,
528
+ environment: processEnvironment,
529
+ };
530
+ const confirmedAuthentication =
531
+ yield* AcpRegistryAuthenticationState.makeAcpRegistryAuthenticationState({
532
+ cacheDir: host.paths.providerStatusCacheDir,
533
instanceId,
503
- displayName,
504
- accentColor,
534
+ settings: effectiveConfig,
535
environment,
506
- enabled,
507
- config,
508
- }).pipe(
509
- Effect.mapError(
510
- (cause) =>
511
- new ProviderDriverError({
512
- driver: DRIVER_KIND,
513
- instanceId,
514
- detail: "Failed to build ACP Registry orchestration adapter.",
515
- cause,
536
+ processEnvironment,
537
+ });
538
+ const withLiveRuntimeState = Effect.fn("AcpRegistryDriver.withLiveRuntimeState")(function* (
539
+ input: ServerProvider,
540
+ ) {
541
+ if (input.auth.status === "unauthenticated") yield* confirmedAuthentication.set(false);
542
+ const provider =
543
+ input.enabled &&
544
+ input.installed &&
545
+ input.auth.status === "unknown" &&
546
+ (yield* confirmedAuthentication.get)
547
+ ? { ...input, auth: { ...input.auth, status: "authenticated" as const } }
548
+ : input;
549
+ return yield* Option.isNone(runtimeCoordinator)
550
+ ? Effect.succeed(provider)
551
+ : Effect.all({
552
+ commands: runtimeCoordinator.value.getAvailableCommands(instanceId),
553
+ configuration: runtimeCoordinator.value.getLiveConfiguration(instanceId),
554
+ authAction: runtimeCoordinator.value.getUrlAuthAction(instanceId),
555
+ }).pipe(
556
+ Effect.map(({ commands, configuration, authAction }) => {
557
+ const withCommands = applyAcpRegistryAvailableCommands(provider, commands);
558
+ const withConfiguration = Option.match(configuration, {
559
+ onNone: () => withCommands,
560
+ onSome: (liveConfiguration) =>
561
+ applyAcpRegistryLiveConfiguration(
562
+ withCommands,
563
+ liveConfiguration,
564
+ effectiveConfig.customModels,
565
+ ),
566
+ });
567
+ return applyAcpRegistryUrlAuthAction(withConfiguration, authAction);
568
}),
517
- ),
518
- );
519
- const readinessInput = {
520
- ...identity,
521
- settings: effectiveConfig,
522
- environment: processEnvironment,
523
- };
524
- const confirmedAuthentication =
525
- yield* AcpRegistryAuthenticationState.makeAcpRegistryAuthenticationState({
526
- cacheDir: host.paths.providerStatusCacheDir,
527
- instanceId,
528
- settings: effectiveConfig,
529
- environment,
530
- processEnvironment,
531
- });
532
- const withLiveRuntimeState = (input: ServerProvider) =>
533
- Effect.gen(function* () {
534
- if (input.auth.status === "unauthenticated") yield* confirmedAuthentication.set(false);
535
- const provider =
536
- input.enabled &&
537
- input.installed &&
538
- input.auth.status === "unknown" &&
539
- (yield* confirmedAuthentication.get)
540
- ? { ...input, auth: { ...input.auth, status: "authenticated" as const } }
541
- : input;
542
- return yield* Option.isNone(runtimeCoordinator)
543
- ? Effect.succeed(provider)
544
- : Effect.all({
545
- commands: runtimeCoordinator.value.getAvailableCommands(instanceId),
546
- configuration: runtimeCoordinator.value.getLiveConfiguration(instanceId),
547
- authAction: runtimeCoordinator.value.getUrlAuthAction(instanceId),
548
- }).pipe(
549
- Effect.map(({ commands, configuration, authAction }) => {
550
- const withCommands = applyAcpRegistryAvailableCommands(provider, commands);
551
- const withConfiguration = Option.match(configuration, {
552
- onNone: () => withCommands,
553
- onSome: (liveConfiguration) =>
554
- applyAcpRegistryLiveConfiguration(
555
- withCommands,
556
- liveConfiguration,
557
- effectiveConfig.customModels,
558
- ),
559
- });
560
- return applyAcpRegistryUrlAuthAction(withConfiguration, authAction);
561
- }),
562
- );
563
- });
564
- const checkProvider = checkAcpRegistryProviderReadiness(readinessInput).pipe(
565
- Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog),
566
- Effect.flatMap(withLiveRuntimeState),
567
- );
568
- const enrichProvider = checkAcpRegistryProviderStatus(
569
- {
570
- ...readinessInput,
571
- cwd: host.paths.cwd,
572
- },
573
- probeAcpRegistryConfiguration,
574
- ).pipe(
575
- Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog),
576
- Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
577
- Effect.provideService(Crypto.Crypto, crypto),
578
- );
579
- const enrichmentCache = yield* Ref.make<{
580
- readonly generation: number;
581
- readonly entry: {
582
- readonly provider: ServerProvider;
583
- readonly expiresAt: number;
584
- } | null;
585
- }>({ generation: 0, entry: null });
586
- const liveSnapshotSemaphore = yield* Semaphore.make(1);
587
- const invalidateEnrichmentCache = Ref.update(enrichmentCache, (current) => ({
588
- generation: current.generation + 1,
589
- entry: null,
590
- }));
591
- const enrichProviderCached = (baseSnapshot: ServerProvider) =>
592
- Effect.gen(function* () {
593
- const now = yield* Clock.currentTimeMillis;
594
- const cacheState = yield* Ref.get(enrichmentCache);
595
- const cached = cacheState.entry;
596
- if (
597
- cached !== null &&
598
- cached.expiresAt > now &&
599
- cached.provider.version === baseSnapshot.version
600
- ) {
601
- return {
602
- provider: { ...cached.provider, checkedAt: baseSnapshot.checkedAt },
603
- generation: cacheState.generation,
604
- };
605
- }
606
- const enriched = yield* enrichProvider;
607
- if (enriched.status === "ready") {
608
- yield* Ref.update(enrichmentCache, (current) =>
609
- current.generation === cacheState.generation
610
- ? {
611
- ...current,
612
- entry: {
613
- provider: enriched,
614
- expiresAt: now + PROBE_SUCCESS_TTL_MS,
615
- },
616
- }
617
- : current,
618
- );
619
- }
620
- return { provider: enriched, generation: cacheState.generation };
621
- });
622
- const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);
623
- const snapshot = yield* makeManagedServerProvider<
624
- ProviderSnapshotSettings<AcpRegistrySettings>
625
- >({
626
- resolveMaintenance: () => Effect.succeed(MAINTENANCE),
627
- getSettings: snapshotSettings.getSettings,
628
- streamSettings: snapshotSettings.streamSettings,
629
- haveSettingsChanged: haveProviderSnapshotSettingsChanged,
630
- initialSnapshot: () => checkProvider,
631
- checkProvider,
632
- enrichSnapshot: ({ snapshot, getSnapshot, publishSnapshot }) => {
633
- if (!snapshot.installed) return Effect.void;
634
- const publishEnrichment = (
635
- Option.isSome(runtimeCoordinator)
636
- ? runtimeCoordinator.value.runBackgroundProbe(
637
- effectiveConfig.source === "local"
638
- ? `local:${instanceId}`
639
- : effectiveConfig.agentId,
640
- enrichProviderCached(snapshot),
641
- )
642
- : enrichProviderCached(snapshot).pipe(Effect.map(Option.some))
643
- ).pipe(
644
- Effect.flatMap(
645
- Option.match({
646
- onNone: () => Effect.void,
647
- onSome: ({ provider, generation }) =>
648
- liveSnapshotSemaphore.withPermit(
649
- Ref.get(enrichmentCache).pipe(
650
- Effect.flatMap((current) =>
651
- current.generation === generation
652
- ? withLiveRuntimeState(provider).pipe(Effect.flatMap(publishSnapshot))
653
- : Effect.void,
654
- ),
569
+ );
570
+ });
571
+ const checkProvider = checkAcpRegistryProviderReadiness(readinessInput).pipe(
572
+ Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog),
573
+ Effect.flatMap(withLiveRuntimeState),
574
+ );
575
+ const enrichProvider = checkAcpRegistryProviderStatus(
576
+ {
577
+ ...readinessInput,
578
+ cwd: host.paths.cwd,
579
+ },
580
+ probeAcpRegistryConfiguration,
581
+ ).pipe(
582
+ Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog),
583
+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
584
+ Effect.provideService(Crypto.Crypto, crypto),
585
+ );
586
+ const enrichmentCache = yield* Ref.make<{
587
+ readonly generation: number;
588
+ readonly entry: {
589
+ readonly provider: ServerProvider;
590
+ readonly expiresAt: number;
591
+ } | null;
592
+ }>({ generation: 0, entry: null });
593
+ const liveSnapshotSemaphore = yield* Semaphore.make(1);
594
+ const invalidateEnrichmentCache = Ref.update(enrichmentCache, (current) => ({
595
+ generation: current.generation + 1,
596
+ entry: null,
597
+ }));
598
+ const enrichProviderCached = Effect.fn("AcpRegistryDriver.enrichProviderCached")(function* (
599
+ baseSnapshot: ServerProvider,
600
+ ) {
601
+ const now = yield* Clock.currentTimeMillis;
602
+ const cacheState = yield* Ref.get(enrichmentCache);
603
+ const cached = cacheState.entry;
604
+ if (
605
+ cached !== null &&
606
+ cached.expiresAt > now &&
607
+ cached.provider.version === baseSnapshot.version
608
+ ) {
609
+ return {
610
+ provider: { ...cached.provider, checkedAt: baseSnapshot.checkedAt },
611
+ generation: cacheState.generation,
612
+ };
613
+ }
614
+ const enriched = yield* enrichProvider;
615
+ if (enriched.status === "ready") {
616
+ yield* Ref.update(enrichmentCache, (current) =>
617
+ current.generation === cacheState.generation
618
+ ? {
619
+ ...current,
620
+ entry: {
621
+ provider: enriched,
622
+ expiresAt: now + PROBE_SUCCESS_TTL_MS,
623
+ },
624
+ }
625
+ : current,
626
+ );
627
+ }
628
+ return { provider: enriched, generation: cacheState.generation };
629
+ });
630
+ const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);
631
+ const snapshot = yield* makeManagedServerProvider<
632
+ ProviderSnapshotSettings<AcpRegistrySettings>
633
+ >({
634
+ resolveMaintenance: () => Effect.succeed(MAINTENANCE),
635
+ getSettings: snapshotSettings.getSettings,
636
+ streamSettings: snapshotSettings.streamSettings,
637
+ haveSettingsChanged: haveProviderSnapshotSettingsChanged,
638
+ initialSnapshot: () => checkProvider,
639
+ checkProvider,
640
+ enrichSnapshot: ({ snapshot, getSnapshot, publishSnapshot }) => {
641
+ if (!snapshot.installed) return Effect.void;
642
+ const publishEnrichment = (
643
+ Option.isSome(runtimeCoordinator)
644
+ ? runtimeCoordinator.value.runBackgroundProbe(
645
+ effectiveConfig.source === "local"
646
+ ? `local:${instanceId}`
647
+ : effectiveConfig.agentId,
648
+ enrichProviderCached(snapshot),
649
+ )
650
+ : enrichProviderCached(snapshot).pipe(Effect.map(Option.some))
651
+ ).pipe(
652
+ Effect.flatMap(
653
+ Option.match({
654
+ onNone: () => Effect.void,
655
+ onSome: ({ provider, generation }) =>
656
+ liveSnapshotSemaphore.withPermit(
657
+ Ref.get(enrichmentCache).pipe(
658
+ Effect.flatMap((current) =>
659
+ current.generation === generation
660
+ ? withLiveRuntimeState(provider).pipe(Effect.flatMap(publishSnapshot))
661
+ : Effect.void,
662
),
663
),
657
- }),
658
- ),
659
- );
660
- if (Option.isNone(runtimeCoordinator)) return publishEnrichment;
664
+ ),
665
+ }),
666
+ ),
667
+ );
668
+ if (Option.isNone(runtimeCoordinator)) return publishEnrichment;
669
662
- const publishLiveCommands = runtimeCoordinator.value.watchAvailableCommands(
663
- instanceId,
664
- ({ slashCommands, skills }) =>
665
- liveSnapshotSemaphore.withPermit(
666
- getSnapshot.pipe(
667
- Effect.flatMap((current) =>
668
- publishSnapshot({
669
- ...current,
670
- slashCommands,
671
- skills,
672
- }),
673
- ),
670
+ const publishLiveCommands = runtimeCoordinator.value.watchAvailableCommands(
671
+ instanceId,
672
+ ({ slashCommands, skills }) =>
673
+ liveSnapshotSemaphore.withPermit(
674
+ getSnapshot.pipe(
675
+ Effect.flatMap((current) =>
676
+ publishSnapshot({
677
+ ...current,
678
+ slashCommands,
679
+ skills,
680
+ }),
681
),
682
),
676
- );
677
- const publishLiveConfiguration = runtimeCoordinator.value.watchLiveConfiguration(
678
- instanceId,
679
- (configuration) =>
680
- liveSnapshotSemaphore.withPermit(
681
- getSnapshot.pipe(
682
- Effect.flatMap((current) =>
683
- publishSnapshot(
684
- applyAcpRegistryLiveConfiguration(
685
- current,
686
- configuration,
687
- effectiveConfig.customModels,
688
- ),
683
+ ),
684
+ );
685
+ const publishLiveConfiguration = runtimeCoordinator.value.watchLiveConfiguration(
686
+ instanceId,
687
+ (configuration) =>
688
+ liveSnapshotSemaphore.withPermit(
689
+ getSnapshot.pipe(
690
+ Effect.flatMap((current) =>
691
+ publishSnapshot(
692
+ applyAcpRegistryLiveConfiguration(
693
+ current,
694
+ configuration,
695
+ effectiveConfig.customModels,
696
),
697
),
698
),
699
),
693
- );
694
- const publishUrlAuthAction = runtimeCoordinator.value.watchUrlAuthAction(
695
- instanceId,
696
- (action) =>
697
- liveSnapshotSemaphore.withPermit(
698
- getSnapshot.pipe(
699
- Effect.flatMap((current) =>
700
- publishSnapshot(
701
- applyAcpRegistryUrlAuthAction(current, Option.fromNullishOr(action)),
702
- ),
700
+ ),
701
+ );
702
+ const publishUrlAuthAction = runtimeCoordinator.value.watchUrlAuthAction(
703
+ instanceId,
704
+ (action) =>
705
+ liveSnapshotSemaphore.withPermit(
706
+ getSnapshot.pipe(
707
+ Effect.flatMap((current) =>
708
+ publishSnapshot(
709
+ applyAcpRegistryUrlAuthAction(current, Option.fromNullishOr(action)),
710
),
711
),
712
),
706
- );
707
- return Effect.all(
708
- [
709
- publishEnrichment,
710
- publishLiveCommands,
711
- publishLiveConfiguration,
712
- publishUrlAuthAction,
713
- ],
714
- {
715
- concurrency: "unbounded",
716
- discard: true,
717
- },
718
- );
719
- },
720
- }).pipe(
721
- Effect.mapError(
722
- (cause) =>
723
- new ProviderDriverError({
724
- driver: DRIVER_KIND,
725
- instanceId,
726
- detail: "Failed to build the ACP Registry provider snapshot.",
727
- cause,
728
- }),
729
- ),
730
- );
731
-
732
- const provideAcpManagementServices = <A, E>(
733
- effect: Effect.Effect<
734
- A,
735
- E,
736
- | AcpRegistrySupport.AcpRegistryCatalog
737
- | ChildProcessSpawner.ChildProcessSpawner
738
- | Crypto.Crypto
739
- >,
740
- ): Effect.Effect<A, E> => {
741
- const provided = effect.pipe(
742
- Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog),
743
- Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
744
- Effect.provideService(Crypto.Crypto, crypto),
713
+ ),
714
);
746
- return Option.isSome(runtimeCoordinator)
747
- ? provided.pipe(
748
- Effect.provideService(
749
- AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator,
750
- runtimeCoordinator.value,
751
- ),
752
- )
753
- : provided;
754
- };
715
+ return Effect.all(
716
+ [publishEnrichment, publishLiveCommands, publishLiveConfiguration, publishUrlAuthAction],
717
+ {
718
+ concurrency: "unbounded",
719
+ discard: true,
720
+ },
721
+ );
722
+ },
723
+ }).pipe(
724
+ Effect.mapError(
725
+ (cause) =>
726
+ new ProviderDriverError({
727
+ driver: DRIVER_KIND,
728
+ instanceId,
729
+ detail: "Failed to build the ACP Registry provider snapshot.",
730
+ cause,
731
+ }),
732
+ ),
733
+ );
734
756
- const clearLiveState = Option.isSome(runtimeCoordinator)
757
- ? runtimeCoordinator.value
758
- .clearLiveConfiguration(instanceId)
759
- .pipe(Effect.andThen(runtimeCoordinator.value.clearAvailableCommands(instanceId)))
760
- : Effect.void;
761
- const controller = yield* AcpRegistryAuth.makeAcpRegistryAuth({
762
- instanceId,
763
- settings: effectiveConfig,
764
- cwd: host.paths.cwd,
765
- environment: processEnvironment,
766
- onChanged: (authenticated) =>
767
- confirmedAuthentication
768
- .set(authenticated)
769
- .pipe(
770
- Effect.andThen(authenticated ? Effect.void : clearLiveState),
771
- Effect.andThen(liveSnapshotSemaphore.withPermit(invalidateEnrichmentCache)),
772
- Effect.andThen(snapshot.refresh),
773
- Effect.asVoid,
774
- ),
775
- }).pipe(
735
+ const provideAcpManagementServices = <A, E>(
736
+ effect: Effect.Effect<
737
+ A,
738
+ E,
739
+ | AcpRegistrySupport.AcpRegistryCatalog
740
+ | ChildProcessSpawner.ChildProcessSpawner
741
+ | Crypto.Crypto
742
+ >,
743
+ ): Effect.Effect<A, E> => {
744
+ const provided = effect.pipe(
745
Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog),
746
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
747
Effect.provideService(Crypto.Crypto, crypto),
748
);
780
- const auth = {
781
- ...controller,
782
- invalidate: (controller.invalidate ?? Effect.void).pipe(
783
- Effect.andThen(confirmedAuthentication.set(false)),
784
- Effect.andThen(clearLiveState),
785
- Effect.andThen(liveSnapshotSemaphore.withPermit(invalidateEnrichmentCache)),
786
- Effect.andThen(snapshot.refresh),
787
- Effect.asVoid,
788
- ),
789
- };
749
+ return Option.isSome(runtimeCoordinator)
750
+ ? provided.pipe(
751
+ Effect.provideService(
752
+ AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator,
753
+ runtimeCoordinator.value,
754
+ ),
755
+ )
756
+ : provided;
757
+ };
758
791
- return {
792
- instanceId,
793
- driverKind: DRIVER_KIND,
794
- continuationIdentity,
795
- displayName,
796
- accentColor,
797
- enabled,
798
- auth,
799
- snapshot: {
800
- ...snapshot,
801
- refresh: snapshot.refresh.pipe(
802
- Effect.tap(() => controller.refreshMethods ?? Effect.void),
759
+ const clearLiveState = Option.isSome(runtimeCoordinator)
760
+ ? runtimeCoordinator.value
761
+ .clearLiveConfiguration(instanceId)
762
+ .pipe(Effect.andThen(runtimeCoordinator.value.clearAvailableCommands(instanceId)))
763
+ : Effect.void;
764
+ const controller = yield* AcpRegistryAuth.makeAcpRegistryAuth({
765
+ instanceId,
766
+ settings: effectiveConfig,
767
+ cwd: host.paths.cwd,
768
+ environment: processEnvironment,
769
+ onChanged: (authenticated) =>
770
+ confirmedAuthentication
771
+ .set(authenticated)
772
+ .pipe(
773
+ Effect.andThen(authenticated ? Effect.void : clearLiveState),
774
+ Effect.andThen(liveSnapshotSemaphore.withPermit(invalidateEnrichmentCache)),
775
+ Effect.andThen(snapshot.refresh),
776
+ Effect.asVoid,
777
),
804
- },
805
- orchestrationAdapter,
806
- textGeneration: makeUnsupportedTextGeneration(),
807
- acpSessionManagement: {
808
- listSessions: ({ cwd, cursor }) =>
809
- provideAcpManagementServices(
810
- listAcpRegistrySessions({
811
- instanceId,
812
- settings: effectiveConfig,
813
- cwd,
814
- environment: processEnvironment,
815
- ...(cursor === undefined ? {} : { cursor }),
816
- }),
817
- ),
818
- deleteSession: ({ cwd, sessionId }) =>
819
- provideAcpManagementServices(
820
- deleteAcpRegistrySession({
821
- instanceId,
822
- settings: effectiveConfig,
823
- cwd,
824
- environment: processEnvironment,
825
- sessionId,
826
- }),
827
- ),
828
- listProviders: (cwd) =>
829
- provideAcpManagementServices(
830
- listAcpRegistryProviders({
831
- instanceId,
832
- settings: effectiveConfig,
833
- cwd,
834
- environment: processEnvironment,
835
- }),
836
- ),
837
- setProvider: ({ cwd, providerId, apiType, baseUrl, headers }) =>
838
- provideAcpManagementServices(
839
- setAcpRegistryProvider({
840
- instanceId,
841
- settings: effectiveConfig,
842
- cwd,
843
- environment: processEnvironment,
844
- providerId,
845
- apiType,
846
- baseUrl,
847
- ...(headers === undefined ? {} : { headers }),
848
- }),
849
- ).pipe(Effect.tap(() => liveSnapshotSemaphore.withPermit(invalidateEnrichmentCache))),
850
- disableProvider: ({ cwd, providerId }) =>
851
- provideAcpManagementServices(
852
- disableAcpRegistryProvider({
853
- instanceId,
854
- settings: effectiveConfig,
855
- cwd,
856
- environment: processEnvironment,
857
- providerId,
858
- }),
859
- ).pipe(Effect.tap(() => liveSnapshotSemaphore.withPermit(invalidateEnrichmentCache))),
860
- logout: (cwd) => {
861
- const logout = logoutAcpRegistry({
778
+ }).pipe(
779
+ Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog),
780
+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
781
+ Effect.provideService(Crypto.Crypto, crypto),
782
+ );
783
+ const auth = {
784
+ ...controller,
785
+ invalidate: (controller.invalidate ?? Effect.void).pipe(
786
+ Effect.andThen(confirmedAuthentication.set(false)),
787
+ Effect.andThen(clearLiveState),
788
+ Effect.andThen(liveSnapshotSemaphore.withPermit(invalidateEnrichmentCache)),
789
+ Effect.andThen(snapshot.refresh),
790
+ Effect.asVoid,
791
+ ),
792
+ };
793
+
794
+ return {
795
+ instanceId,
796
+ driverKind: DRIVER_KIND,
797
+ continuationIdentity,
798
+ displayName,
799
+ accentColor,
800
+ enabled,
801
+ auth,
802
+ snapshot: {
803
+ ...snapshot,
804
+ refresh: snapshot.refresh.pipe(Effect.tap(() => controller.refreshMethods ?? Effect.void)),
805
+ },
806
+ orchestrationAdapter,
807
+ textGeneration: makeUnsupportedTextGeneration(),
808
+ acpSessionManagement: {
809
+ listSessions: ({ cwd, cursor }) =>
810
+ provideAcpManagementServices(
811
+ listAcpRegistrySessions({
812
instanceId,
813
settings: effectiveConfig,
814
cwd,
815
environment: processEnvironment,
866
- }).pipe(
867
- Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog),
868
- Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
869
- Effect.provideService(Crypto.Crypto, crypto),
870
- Effect.tap(() => confirmedAuthentication.set(false)),
871
- Effect.tap(() =>
872
- liveSnapshotSemaphore.withPermit(
873
- invalidateEnrichmentCache.pipe(
874
- Effect.andThen(
875
- Option.isSome(runtimeCoordinator)
876
- ? Effect.all(
877
- [
878
- runtimeCoordinator.value.clearAvailableCommands(instanceId),
879
- runtimeCoordinator.value.clearLiveConfiguration(instanceId),
880
- ],
881
- { concurrency: "unbounded", discard: true },
882
- )
883
- : Effect.void,
884
- ),
816
+ ...(cursor === undefined ? {} : { cursor }),
817
+ }),
818
+ ),
819
+ deleteSession: ({ cwd, sessionId }) =>
820
+ provideAcpManagementServices(
821
+ deleteAcpRegistrySession({
822
+ instanceId,
823
+ settings: effectiveConfig,
824
+ cwd,
825
+ environment: processEnvironment,
826
+ sessionId,
827
+ }),
828
+ ),
829
+ listProviders: (cwd) =>
830
+ provideAcpManagementServices(
831
+ listAcpRegistryProviders({
832
+ instanceId,
833
+ settings: effectiveConfig,
834
+ cwd,
835
+ environment: processEnvironment,
836
+ }),
837
+ ),
838
+ setProvider: ({ cwd, providerId, apiType, baseUrl, headers }) =>
839
+ provideAcpManagementServices(
840
+ setAcpRegistryProvider({
841
+ instanceId,
842
+ settings: effectiveConfig,
843
+ cwd,
844
+ environment: processEnvironment,
845
+ providerId,
846
+ apiType,
847
+ baseUrl,
848
+ ...(headers === undefined ? {} : { headers }),
849
+ }),
850
+ ).pipe(Effect.tap(() => liveSnapshotSemaphore.withPermit(invalidateEnrichmentCache))),
851
+ disableProvider: ({ cwd, providerId }) =>
852
+ provideAcpManagementServices(
853
+ disableAcpRegistryProvider({
854
+ instanceId,
855
+ settings: effectiveConfig,
856
+ cwd,
857
+ environment: processEnvironment,
858
+ providerId,
859
+ }),
860
+ ).pipe(Effect.tap(() => liveSnapshotSemaphore.withPermit(invalidateEnrichmentCache))),
861
+ logout: (cwd) => {
862
+ const logout = logoutAcpRegistry({
863
+ instanceId,
864
+ settings: effectiveConfig,
865
+ cwd,
866
+ environment: processEnvironment,
867
+ }).pipe(
868
+ Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog),
869
+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
870
+ Effect.provideService(Crypto.Crypto, crypto),
871
+ Effect.tap(() => confirmedAuthentication.set(false)),
872
+ Effect.tap(() =>
873
+ liveSnapshotSemaphore.withPermit(
874
+ invalidateEnrichmentCache.pipe(
875
+ Effect.andThen(
876
+ Option.isSome(runtimeCoordinator)
877
+ ? Effect.all(
878
+ [
879
+ runtimeCoordinator.value.clearAvailableCommands(instanceId),
880
+ runtimeCoordinator.value.clearLiveConfiguration(instanceId),
881
+ ],
882
+ { concurrency: "unbounded", discard: true },
883
+ )
884
+ : Effect.void,
885
),
886
),
887
),
888
- );
889
- return Option.isSome(runtimeCoordinator)
890
- ? logout.pipe(
891
- Effect.provideService(
892
- AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator,
893
- runtimeCoordinator.value,
894
- ),
895
- )
896
- : logout;
897
- },
888
+ ),
889
+ );
890
+ return Option.isSome(runtimeCoordinator)
891
+ ? logout.pipe(
892
+ Effect.provideService(
893
+ AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator,
894
+ runtimeCoordinator.value,
895
+ ),
896
+ )
897
+ : logout;
898
},
899
- } satisfies ProviderInstance;
900
- }),
899
+ },
900
+ } satisfies ProviderInstance;
901
+ }),
902
};
packages/provider-core/src/server/ProviderLatestVersions.ts
+27
-30
@@ -25,36 +25,33 @@ export class ProviderLatestVersions extends Context.Service<
25
}
26
>()("@t3tools/provider-core/server/ProviderLatestVersions") {}
27
28
-export const make = (seed: Iterable<readonly [key: string, version: string | null]> = []) =>
29
- Effect.gen(function* () {
30
- const entries = yield* Ref.make(
31
- new Map<string, Entry>(
32
- Array.from(seed, ([key, version]) => [
33
- key,
34
- { version, expiresAt: Number.MAX_SAFE_INTEGER },
35
- ]),
36
- ),
37
- );
38
- return ProviderLatestVersions.of({
39
- cached: (key, lookup, options) =>
40
- Effect.gen(function* () {
41
- const now = DateTime.toEpochMillis(yield* DateTime.now);
42
- const existing = (yield* Ref.get(entries)).get(key);
43
- if (!options?.fresh && existing && existing.expiresAt > now) return existing.version;
44
- const version = yield* lookup;
45
- const ttl = version === null ? MISSING_TTL : FOUND_TTL;
46
- yield* Ref.update(entries, (current) =>
47
- new Map(current).set(key, { version, expiresAt: now + Duration.toMillis(ttl) }),
48
- );
49
- return version;
50
- }),
51
- invalidate: (key) =>
52
- Ref.update(entries, (current) => {
53
- const next = new Map(current);
54
- next.delete(key);
55
- return next;
56
- }),
57
- });
28
+export const make = Effect.fn("ProviderLatestVersions.make")(function* (
29
+ seed: Iterable<readonly [key: string, version: string | null]> = [],
30
+) {
31
+ const entries = yield* Ref.make(
32
+ new Map<string, Entry>(
33
+ Array.from(seed, ([key, version]) => [key, { version, expiresAt: Number.MAX_SAFE_INTEGER }]),
34
+ ),
35
+ );
36
+ return ProviderLatestVersions.of({
37
+ cached: Effect.fn("ProviderLatestVersions.cached")(function* (key, lookup, options) {
38
+ const now = DateTime.toEpochMillis(yield* DateTime.now);
39
+ const existing = (yield* Ref.get(entries)).get(key);
40
+ if (!options?.fresh && existing && existing.expiresAt > now) return existing.version;
41
+ const version = yield* lookup;
42
+ const ttl = version === null ? MISSING_TTL : FOUND_TTL;
43
+ yield* Ref.update(entries, (current) =>
44
+ new Map(current).set(key, { version, expiresAt: now + Duration.toMillis(ttl) }),
45
+ );
46
+ return version;
47
+ }),
48
+ invalidate: (key) =>
49
+ Ref.update(entries, (current) => {
50
+ const next = new Map(current);
51
+ next.delete(key);
52
+ return next;
53
+ }),
54
});
55
+});
56
57
export const layer = Layer.effect(ProviderLatestVersions, make());
packages/provider-core/src/server/managedProvider.ts
+5
-3
@@ -192,8 +192,9 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
192
const applySnapshot = (nextSettings: Settings, options?: { readonly forceRefresh?: boolean }) =>
193
refreshSemaphore.withPermits(1)(applySnapshotBase(nextSettings, options));
194
195
- const applyUsageLimits: ManagedServerProvider["applyUsageLimits"] = (update) =>
196
- Effect.gen(function* () {
195
+ // Providers call this on every token-usage tick, usually without changing the snapshot.
196
+ const applyUsageLimits: ManagedServerProvider["applyUsageLimits"] = Effect.fnUntraced(
197
+ function* (update) {
198
const snapshotToPublish = yield* Ref.modify(snapshotStateRef, (state) => {
199
const usageLimits = applyUsageLimitsUpdate({
200
previous: state.snapshot.usageLimits,
@@ -209,7 +210,8 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
210
if (snapshotToPublish !== null) {
211
yield* PubSub.publish(changesPubSub, snapshotToPublish);
212
}
212
- });
213
+ },
214
+ );
215
216
const refreshSnapshot = Effect.fn("refreshSnapshot")(function* () {
217
const nextSettings = yield* input.getSettings;
packages/provider-core/src/server/providerAuthFlow.ts
+111
-111
@@ -140,40 +140,42 @@ export const make = Effect.fn("ProviderAuthFlow.make")(function* (options: {
140
141
const controller: ProviderAuth.ProviderAuthController = {
142
credentialBinding: options.credentialBinding,
143
- adoptCredentials: (update, stopSessions) =>
144
- Effect.gen(function* () {
145
- yield* lock.withPermit(
146
- Effect.gen(function* () {
147
- if (operation !== "idle")
148
- return yield* new ProviderSetupError({
149
- instanceId: options.instanceId,
150
- operation: "import",
151
- detail: "Finish or cancel the existing sign-in first.",
152
- });
153
- operation = "stopping";
154
- }),
155
- );
156
- const result = yield* Effect.gen(function* () {
157
- yield* stopOwnedSessions;
158
- yield* stopSessions;
159
- yield* update;
160
- yield* refreshMethods;
161
- }).pipe(Effect.exit);
162
- const state: ProviderAuthState = {
163
- ...empty,
164
- methods: snapshot.value.state.methods ?? [],
165
- phase: Exit.isSuccess(result) ? "succeeded" : "failed",
166
- message: Exit.isSuccess(result) ? null : failureMessage(result.cause),
167
- };
168
- yield* lock.withPermit(
169
- Effect.gen(function* () {
170
- yield* SubscriptionRef.set(snapshot, { owner: null, state });
171
- operation = "idle";
172
- }),
173
- );
174
- if (Exit.isFailure(result)) return yield* Effect.failCause(result.cause);
175
- return state;
176
- }).pipe(Effect.uninterruptible),
143
+ adoptCredentials: Effect.fn("providerAuthFlow.adoptCredentials")(function* (
144
+ update,
145
+ stopSessions,
146
+ ) {
147
+ yield* lock.withPermit(
148
+ Effect.gen(function* () {
149
+ if (operation !== "idle")
150
+ return yield* new ProviderSetupError({
151
+ instanceId: options.instanceId,
152
+ operation: "import",
153
+ detail: "Finish or cancel the existing sign-in first.",
154
+ });
155
+ operation = "stopping";
156
+ }),
157
+ );
158
+ const result = yield* Effect.gen(function* () {
159
+ yield* stopOwnedSessions;
160
+ yield* stopSessions;
161
+ yield* update;
162
+ yield* refreshMethods;
163
+ }).pipe(Effect.exit);
164
+ const state: ProviderAuthState = {
165
+ ...empty,
166
+ methods: snapshot.value.state.methods ?? [],
167
+ phase: Exit.isSuccess(result) ? "succeeded" : "failed",
168
+ message: Exit.isSuccess(result) ? null : failureMessage(result.cause),
169
+ };
170
+ yield* lock.withPermit(
171
+ Effect.gen(function* () {
172
+ yield* SubscriptionRef.set(snapshot, { owner: null, state });
173
+ operation = "idle";
174
+ }),
175
+ );
176
+ if (Exit.isFailure(result)) return yield* Effect.failCause(result.cause);
177
+ return state;
178
+ }, Effect.uninterruptible),
179
refreshMethods,
180
invalidate: lock.withPermit(
181
Effect.gen(function* () {
@@ -279,21 +281,21 @@ export const make = Effect.fn("ProviderAuthFlow.make")(function* (options: {
281
expiresAt: flow.expiresAt,
282
...(returnUrl ? { returnUrl } : {}),
283
...(callbackMode ? { callbackMode } : {}),
282
- setInteraction: (interaction, respond, complete) =>
283
- Effect.gen(function* () {
284
- if (active !== flow) return;
285
- flow.respond = respond;
286
- flow.complete = complete;
287
- yield* publish(flow, {
288
- phase: "waiting",
289
- interaction,
290
- authorizationUrl:
291
- interaction.type === "browser" || interaction.type === "deviceCode"
292
- ? interaction.url
293
- : null,
294
- message: "Complete sign-in to continue.",
295
- });
296
- }),
284
+ // Terminal sign-in updates this for every output chunk within the auth operation.
285
+ setInteraction: Effect.fnUntraced(function* (interaction, respond, complete) {
286
+ if (active !== flow) return;
287
+ flow.respond = respond;
288
+ flow.complete = complete;
289
+ yield* publish(flow, {
290
+ phase: "waiting",
291
+ interaction,
292
+ authorizationUrl:
293
+ interaction.type === "browser" || interaction.type === "deviceCode"
294
+ ? interaction.url
295
+ : null,
296
+ message: "Complete sign-in to continue.",
297
+ });
298
+ }),
299
verifying: Effect.gen(function* () {
300
flow.respond = undefined;
301
flow.complete = undefined;
@@ -424,69 +426,67 @@ export const make = Effect.fn("ProviderAuthFlow.make")(function* (options: {
426
return snapshot.value.state;
427
}),
428
),
427
- cancel: (owner, id) =>
428
- Effect.gen(function* () {
429
- const flow = yield* lock.withPermit(
430
- Effect.gen(function* () {
431
- const flow = yield* requireFlow(owner, id);
432
- yield* publish(flow, {
433
- phase: "cancelled",
434
- interaction: null,
435
- authorizationUrl: null,
436
- expiresAt: null,
437
- message: "Sign-in cancelled.",
429
+ cancel: Effect.fn("providerAuthFlow.cancel")(function* (owner, id) {
430
+ const flow = yield* lock.withPermit(
431
+ Effect.gen(function* () {
432
+ const flow = yield* requireFlow(owner, id);
433
+ yield* publish(flow, {
434
+ phase: "cancelled",
435
+ interaction: null,
436
+ authorizationUrl: null,
437
+ expiresAt: null,
438
+ message: "Sign-in cancelled.",
439
+ });
440
+ active = undefined;
441
+ operation = "stopping";
442
+ return flow;
443
+ }),
444
+ );
445
+ if (flow.responseFiber) yield* Fiber.interrupt(flow.responseFiber);
446
+ if (flow.fiber) yield* Fiber.interrupt(flow.fiber);
447
+ operation = "idle";
448
+ return snapshot.value.state;
449
+ }, Effect.uninterruptible),
450
+ logout: Effect.fn("providerAuthFlow.logout")(function* (stopSessions) {
451
+ const flow = yield* lock.withPermit(
452
+ Effect.gen(function* () {
453
+ if (operation !== "idle" && operation !== "auth")
454
+ return yield* new ProviderSetupError({
455
+ instanceId: options.instanceId,
456
+ operation: "logout",
457
+ detail: "Provider setup is already stopping.",
458
});
439
- active = undefined;
440
- operation = "stopping";
441
- return flow;
442
- }),
443
- );
444
- if (flow.responseFiber) yield* Fiber.interrupt(flow.responseFiber);
445
- if (flow.fiber) yield* Fiber.interrupt(flow.fiber);
446
- operation = "idle";
447
- return snapshot.value.state;
448
- }).pipe(Effect.uninterruptible),
449
- logout: (stopSessions) =>
450
- Effect.gen(function* () {
451
- const flow = yield* lock.withPermit(
452
- Effect.gen(function* () {
453
- if (operation !== "idle" && operation !== "auth")
454
- return yield* new ProviderSetupError({
455
- instanceId: options.instanceId,
456
- operation: "logout",
457
- detail: "Provider setup is already stopping.",
458
- });
459
- operation = "stopping";
460
- const flow = active;
461
- active = undefined;
462
- return flow;
463
- }),
464
- );
465
- const result = yield* Effect.gen(function* () {
466
- if (flow?.responseFiber) yield* Fiber.interrupt(flow.responseFiber);
467
- if (flow?.fiber) yield* Fiber.interrupt(flow.fiber);
468
- yield* stopSessions.pipe(Effect.ensuring(stopOwnedSessions));
469
- const message = yield* options.logout;
470
- if (options.refreshMethodsAfterAuth) yield* refreshMethods;
471
- return message;
472
- }).pipe(Effect.exit);
473
- const state: ProviderAuthState = {
474
- ...empty,
475
- methods: snapshot.value.state.methods ?? [],
476
- phase: Exit.isSuccess(result) ? "idle" : "failed",
477
- message: Exit.isSuccess(result)
478
- ? (result.value ?? "Signed out.")
479
- : "Could not sign out. Try again.",
480
- };
481
- yield* lock.withPermit(
482
- Effect.gen(function* () {
483
- yield* SubscriptionRef.set(snapshot, { owner: null, state });
484
- operation = "idle";
485
- }),
486
- );
487
- if (Exit.isFailure(result)) return yield* Effect.failCause(result.cause);
488
- return state;
489
- }).pipe(Effect.uninterruptible),
459
+ operation = "stopping";
460
+ const flow = active;
461
+ active = undefined;
462
+ return flow;
463
+ }),
464
+ );
465
+ const result = yield* Effect.gen(function* () {
466
+ if (flow?.responseFiber) yield* Fiber.interrupt(flow.responseFiber);
467
+ if (flow?.fiber) yield* Fiber.interrupt(flow.fiber);
468
+ yield* stopSessions.pipe(Effect.ensuring(stopOwnedSessions));
469
+ const message = yield* options.logout;
470
+ if (options.refreshMethodsAfterAuth) yield* refreshMethods;
471
+ return message;
472
+ }).pipe(Effect.exit);
473
+ const state: ProviderAuthState = {
474
+ ...empty,
475
+ methods: snapshot.value.state.methods ?? [],
476
+ phase: Exit.isSuccess(result) ? "idle" : "failed",
477
+ message: Exit.isSuccess(result)
478
+ ? (result.value ?? "Signed out.")
479
+ : "Could not sign out. Try again.",
480
+ };
481
+ yield* lock.withPermit(
482
+ Effect.gen(function* () {
483
+ yield* SubscriptionRef.set(snapshot, { owner: null, state });
484
+ operation = "idle";
485
+ }),
486
+ );
487
+ if (Exit.isFailure(result)) return yield* Effect.failCause(result.cause);
488
+ return state;
489
+ }, Effect.uninterruptible),
490
subscribe: (owner) =>
491
SubscriptionRef.changes(snapshot).pipe(
492
Stream.map((current) =>
packages/provider-core/src/server/snapshotProbe.ts
+25
-23
@@ -105,30 +105,32 @@ export function isCommandMissingCause(error: unknown): boolean {
105
return error instanceof PlatformError.PlatformError && error.reason._tag === "NotFound";
106
}
107
108
-export const spawnAndCollect = (binaryPath: string, command: ChildProcess.Command) =>
109
- Effect.gen(function* () {
110
- const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
111
- const child = yield* spawner.spawn(command);
112
- const [stdout, stderr, exitCode] = yield* Effect.all(
113
- [
114
- collectStreamAsString(child.stdout),
115
- collectStreamAsString(child.stderr),
116
- child.exitCode.pipe(Effect.map(Number)),
117
- ],
118
- { concurrency: "unbounded" },
119
- );
108
+export const spawnAndCollect = Effect.fn("snapshotProbe.spawnAndCollect")(function* (
109
+ binaryPath: string,
110
+ command: ChildProcess.Command,
111
+) {
112
+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
113
+ const child = yield* spawner.spawn(command);
114
+ const [stdout, stderr, exitCode] = yield* Effect.all(
115
+ [
116
+ collectStreamAsString(child.stdout),
117
+ collectStreamAsString(child.stderr),
118
+ child.exitCode.pipe(Effect.map(Number)),
119
+ ],
120
+ { concurrency: "unbounded" },
121
+ );
122
121
- const result: CommandResult = { stdout, stderr, code: exitCode };
122
- if (yield* isWindowsCommandNotFound(exitCode, stderr)) {
123
- return yield* new ProviderCommandNotFoundError({
124
- binaryPath,
125
- exitCode,
126
- stdoutLength: stdout.length,
127
- stderrLength: stderr.length,
128
- });
129
- }
130
- return result;
131
- }).pipe(Effect.scoped);
123
+ const result: CommandResult = { stdout, stderr, code: exitCode };
124
+ if (yield* isWindowsCommandNotFound(exitCode, stderr)) {
125
+ return yield* new ProviderCommandNotFoundError({
126
+ binaryPath,
127
+ exitCode,
128
+ stdoutLength: stdout.length,
129
+ stderrLength: stderr.length,
130
+ });
131
+ }
132
+ return result;
133
+}, Effect.scoped);
134
135
export function parseGenericCliVersion(output: string): string | null {
136
// "opencode v2.0.3"-style output: the optional "v" has to be consumed first,
packages/provider-core/src/server/snapshotSettings.ts
+11
-13
@@ -27,22 +27,20 @@ export function haveProviderSnapshotSettingsChanged<Settings>(
27
return !Equal.equals(previous, next);
28
}
29
30
-export const makeProviderSnapshotSettingsSource = <Settings>(
31
- provider: Settings,
32
-): Effect.Effect<
30
+export const makeProviderSnapshotSettingsSource = Effect.fn(
31
+ "snapshotSettings.makeProviderSnapshotSettingsSource",
32
+)(function* <Settings>(provider: Settings): Effect.fn.Return<
33
{
34
readonly getSettings: Effect.Effect<ProviderSnapshotSettings<Settings>, ServerSettingsError>;
35
readonly streamSettings: Stream.Stream<ProviderSnapshotSettings<Settings>>;
36
},
37
never,
38
ProviderHost.ProviderHost
39
-> =>
40
- Effect.gen(function* () {
41
- const { settings } = yield* ProviderHost.ProviderHost;
42
- const mapSettings = (current: ServerSettings) =>
43
- makeProviderSnapshotSettings(provider, current);
44
- return {
45
- getSettings: settings.get.pipe(Effect.map(mapSettings)),
46
- streamSettings: settings.changes.pipe(Stream.map(mapSettings)),
47
- };
48
- });
39
+> {
40
+ const { settings } = yield* ProviderHost.ProviderHost;
41
+ const mapSettings = (current: ServerSettings) => makeProviderSnapshotSettings(provider, current);
42
+ return {
43
+ getSettings: settings.get.pipe(Effect.map(mapSettings)),
44
+ streamSettings: settings.changes.pipe(Stream.map(mapSettings)),
45
+ };
46
+});
packages/provider-core/src/server/subagentProjection.ts
+70
-68
@@ -276,17 +276,17 @@ function writtenIds(
276
return new Set(emitted.flatMap((event) => (event.type === type ? [event.payload.id] : [])));
277
}
278
279
-export const endOrphanedNativeSubagent = <E>(input: {
280
- readonly projection: Pick<OrchestrationV2ThreadProjection, "nodes" | "subagents" | "turnItems">;
281
- readonly subagentId: NodeId;
282
- readonly status: "completed" | "failed" | "interrupted" | "cancelled";
283
- readonly completedAt?: DateTime.Utc;
284
- readonly result?: string | null;
285
- readonly now: DateTime.Utc;
286
- readonly emitted: ReadonlyArray<OrchestrationV2DomainEvent>;
287
- readonly allocateEventId: () => Effect.Effect<EventId, E>;
288
-}) =>
289
- Effect.gen(function* () {
279
+export const endOrphanedNativeSubagent = Effect.fn("subagentProjection.endOrphanedNativeSubagent")(
280
+ function* <E>(input: {
281
+ readonly projection: Pick<OrchestrationV2ThreadProjection, "nodes" | "subagents" | "turnItems">;
282
+ readonly subagentId: NodeId;
283
+ readonly status: "completed" | "failed" | "interrupted" | "cancelled";
284
+ readonly completedAt?: DateTime.Utc;
285
+ readonly result?: string | null;
286
+ readonly now: DateTime.Utc;
287
+ readonly emitted: ReadonlyArray<OrchestrationV2DomainEvent>;
288
+ readonly allocateEventId: () => Effect.Effect<EventId, E>;
289
+ }) {
290
const { now, status, subagentId, completedAt = now } = input;
291
const subagent = input.projection.subagents.find((entry) => entry.id === subagentId);
292
if (subagent?.origin !== "provider_native") return [];
@@ -351,9 +351,12 @@ export const endOrphanedNativeSubagent = <E>(input: {
351
});
352
}
353
return events;
354
- });
354
+ },
355
+);
356
356
-export const endRunlessRootTurns = <E>(input: {
357
+export const endRunlessRootTurns = Effect.fn("subagentProjection.endRunlessRootTurns")(function* <
358
+ E,
359
+>(input: {
360
readonly threadId: ThreadId;
361
readonly providerInstanceId: ProviderInstanceId;
362
readonly projection: Pick<OrchestrationV2ThreadProjection, "nodes" | "turnItems">;
@@ -362,63 +365,62 @@ export const endRunlessRootTurns = <E>(input: {
365
readonly now: DateTime.Utc;
366
readonly emitted: ReadonlyArray<OrchestrationV2DomainEvent>;
367
readonly allocateEventId: () => Effect.Effect<EventId, E>;
365
-}) =>
366
- Effect.gen(function* () {
367
- const { now, status, completedAt = now } = input;
368
- const endedNodeIds = writtenIds(input.emitted, "node.updated");
369
- const endedItemIds = writtenIds(input.emitted, "turn-item.updated");
370
- const scope = {
371
- threadId: input.threadId,
372
- providerInstanceId: input.providerInstanceId,
373
- occurredAt: now,
374
- };
375
- const events: Array<OrchestrationV2DomainEvent> = [];
376
- for (const node of input.projection.nodes) {
368
+}) {
369
+ const { now, status, completedAt = now } = input;
370
+ const endedNodeIds = writtenIds(input.emitted, "node.updated");
371
+ const endedItemIds = writtenIds(input.emitted, "turn-item.updated");
372
+ const scope = {
373
+ threadId: input.threadId,
374
+ providerInstanceId: input.providerInstanceId,
375
+ occurredAt: now,
376
+ };
377
+ const events: Array<OrchestrationV2DomainEvent> = [];
378
+ for (const node of input.projection.nodes) {
379
+ if (
380
+ node.kind !== "root_turn" ||
381
+ node.runId !== null ||
382
+ !isOrchestrationV2WorkActive(node.status)
383
+ ) {
384
+ continue;
385
+ }
386
+ if (!endedNodeIds.has(node.id)) {
387
+ events.push({
388
+ ...scope,
389
+ id: yield* input.allocateEventId(),
390
+ type: "node.updated",
391
+ nodeId: node.id,
392
+ payload: { ...node, status, completedAt },
393
+ });
394
+ }
395
+ for (const item of input.projection.turnItems) {
396
if (
378
- node.kind !== "root_turn" ||
379
- node.runId !== null ||
380
- !isOrchestrationV2WorkActive(node.status)
397
+ item.nodeId !== node.id ||
398
+ item.runId !== null ||
399
+ !isOrchestrationV2WorkActive(item.status) ||
400
+ endedItemIds.has(item.id)
401
) {
402
continue;
403
}
384
- if (!endedNodeIds.has(node.id)) {
385
- events.push({
386
- ...scope,
387
- id: yield* input.allocateEventId(),
388
- type: "node.updated",
389
- nodeId: node.id,
390
- payload: { ...node, status, completedAt },
391
- });
392
- }
393
- for (const item of input.projection.turnItems) {
394
- if (
395
- item.nodeId !== node.id ||
396
- item.runId !== null ||
397
- !isOrchestrationV2WorkActive(item.status) ||
398
- endedItemIds.has(item.id)
399
- ) {
400
- continue;
401
- }
402
- events.push({
403
- ...scope,
404
- id: yield* input.allocateEventId(),
405
- type: "turn-item.updated",
406
- nodeId: node.id,
407
- payload: {
408
- ...item,
409
- status:
410
- status === "completed" &&
411
- (item.type === "command_execution" || item.type === "dynamic_tool")
412
- ? "failed"
413
- : status,
414
- completedAt,
415
- updatedAt: now,
416
- ...(item.type === "reasoning" || item.type === "assistant_message"
417
- ? { streaming: false }
418
- : {}),
419
- },
420
- });
421
- }
404
+ events.push({
405
+ ...scope,
406
+ id: yield* input.allocateEventId(),
407
+ type: "turn-item.updated",
408
+ nodeId: node.id,
409
+ payload: {
410
+ ...item,
411
+ status:
412
+ status === "completed" &&
413
+ (item.type === "command_execution" || item.type === "dynamic_tool")
414
+ ? "failed"
415
+ : status,
416
+ completedAt,
417
+ updatedAt: now,
418
+ ...(item.type === "reasoning" || item.type === "assistant_message"
419
+ ? { streaming: false }
420
+ : {}),
421
+ },
422
+ });
423
}
423
- return events;
424
- });
424
+ }
425
+ return events;
426
+});