diff --git a/apps/server/src/provider/Drivers/AcpRegistryDriver.ts b/apps/server/src/provider/Drivers/AcpRegistryDriver.ts new file mode 100644 index 0000000000..2b69b3d461 --- /dev/null +++ b/apps/server/src/provider/Drivers/AcpRegistryDriver.ts @@ -0,0 +1,181 @@ +import { + AcpRegistrySettings, + ProviderDriverKind, + TextGenerationError, + type ServerProvider, +} from "@t3tools/contracts"; +import { Effect, FileSystem, Path, Schema, Stream } from "effect"; +import { ChildProcessSpawner } from "effect/unstable/process"; + +import { ServerConfig } from "../../config.ts"; +import { ProviderDriverError } from "../Errors.ts"; +import { makeCursorAdapter } from "../Layers/CursorAdapter.ts"; +import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts"; +import { makeManagedServerProvider } from "../makeManagedServerProvider.ts"; +import { + defaultProviderContinuationIdentity, + type ProviderDriver, + type ProviderInstance, +} from "../ProviderDriver.ts"; +import { + buildServerProvider, + providerModelsFromSettings, + type ServerProviderDraft, +} from "../providerSnapshot.ts"; +import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts"; + +const DRIVER_KIND = ProviderDriverKind.make("acpRegistry"); + +export type AcpRegistryDriverEnv = + | ChildProcessSpawner.ChildProcessSpawner + | FileSystem.FileSystem + | Path.Path + | ProviderEventLoggers + | ServerConfig; + +const unsupportedTextGeneration = (operation: string) => + Effect.fail( + new TextGenerationError({ + operation, + detail: "Generic ACP providers do not support git text generation yet.", + }), + ); + +const makeTextGeneration = () => ({ + generateCommitMessage: () => unsupportedTextGeneration("generateCommitMessage"), + generatePrContent: () => unsupportedTextGeneration("generatePrContent"), + generateBranchName: () => unsupportedTextGeneration("generateBranchName"), + generateThreadTitle: () => unsupportedTextGeneration("generateThreadTitle"), +}); + +function withIdentity(input: { + readonly instanceId: ProviderInstance["instanceId"]; + readonly displayName: string | undefined; + readonly accentColor: string | undefined; + readonly iconUrl: string | undefined; + readonly continuationGroupKey: string; +}) { + return (snapshot: ServerProviderDraft): ServerProvider => ({ + ...snapshot, + instanceId: input.instanceId, + driver: DRIVER_KIND, + ...(input.displayName ? { displayName: input.displayName } : {}), + ...(input.accentColor ? { accentColor: input.accentColor } : {}), + ...(input.iconUrl ? { iconUrl: input.iconUrl } : {}), + continuation: { groupKey: input.continuationGroupKey }, + }); +} + +function initialSnapshot(settings: AcpRegistrySettings): ServerProviderDraft { + const checkedAt = new Date().toISOString(); + const command = settings.command.trim(); + const enabled = settings.enabled && command.length > 0; + return buildServerProvider({ + presentation: { + displayName: "ACP Registry", + badgeLabel: "ACP", + showInteractionModeToggle: true, + }, + enabled, + checkedAt, + models: providerModelsFromSettings( + [{ slug: "default", name: "Default", isCustom: false, capabilities: null }], + DRIVER_KIND, + settings.customModels, + { optionDescriptors: [] }, + ), + probe: { + installed: enabled, + version: null, + status: enabled ? "ready" : "warning", + auth: { status: "unknown" }, + message: enabled ? "ACP provider configured." : "Configure a launch command to enable.", + }, + }); +} + +export const AcpRegistryDriver: ProviderDriver = { + driverKind: DRIVER_KIND, + metadata: { + displayName: "ACP Registry", + supportsMultipleInstances: true, + }, + configSchema: AcpRegistrySettings, + defaultConfig: (): AcpRegistrySettings => Schema.decodeSync(AcpRegistrySettings)({}), + create: ({ instanceId, displayName, accentColor, iconUrl, environment, enabled, config }) => + Effect.gen(function* () { + const eventLoggers = yield* ProviderEventLoggers; + const effectiveConfig = { ...config, enabled: enabled && config.enabled }; + const effectiveIconUrl = iconUrl ?? effectiveConfig.iconUrl; + const processEnv = { + ...effectiveConfig.env, + ...mergeProviderInstanceEnvironment(environment), + }; + const continuationIdentity = defaultProviderContinuationIdentity({ + driverKind: DRIVER_KIND, + instanceId, + }); + const stamp = withIdentity({ + instanceId, + displayName, + accentColor, + iconUrl: effectiveIconUrl, + continuationGroupKey: continuationIdentity.continuationKey, + }); + + const adapter = yield* makeCursorAdapter( + { + enabled: effectiveConfig.enabled, + binaryPath: effectiveConfig.command || "acp", + apiEndpoint: "", + customModels: effectiveConfig.customModels, + }, + { + provider: DRIVER_KIND, + instanceId, + environment: processEnv, + readyReason: "ACP session ready", + applyCursorModelOptions: false, + normalizeModel: (model) => model?.trim() || "default", + ...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}), + spawn: ({ cwd, environment: spawnEnv }) => ({ + command: effectiveConfig.command.trim(), + args: effectiveConfig.args, + cwd, + ...(spawnEnv ? { env: spawnEnv } : {}), + }), + }, + ); + + const snapshot = yield* makeManagedServerProvider({ + getSettings: Effect.succeed(effectiveConfig), + streamSettings: Stream.never, + haveSettingsChanged: () => false, + initialSnapshot: (settings) => stamp(initialSnapshot(settings)), + checkProvider: Effect.succeed(stamp(initialSnapshot(effectiveConfig))), + }).pipe( + Effect.mapError( + (cause) => + new ProviderDriverError({ + driver: DRIVER_KIND, + instanceId, + detail: `Failed to build ACP Registry snapshot: ${cause.message ?? String(cause)}`, + cause, + }), + ), + ); + + return { + instanceId, + driverKind: DRIVER_KIND, + continuationIdentity, + displayName, + accentColor, + iconUrl: effectiveIconUrl, + enabled: effectiveConfig.enabled, + snapshot, + adapter, + textGeneration: makeTextGeneration(), + } satisfies ProviderInstance; + }), +}; diff --git a/apps/server/src/provider/Drivers/ClaudeDriver.ts b/apps/server/src/provider/Drivers/ClaudeDriver.ts index feddd3b86b..464c12835a 100644 --- a/apps/server/src/provider/Drivers/ClaudeDriver.ts +++ b/apps/server/src/provider/Drivers/ClaudeDriver.ts @@ -52,6 +52,7 @@ const withInstanceIdentity = readonly instanceId: ProviderInstance["instanceId"]; readonly displayName: string | undefined; readonly accentColor: string | undefined; + readonly iconUrl: string | undefined; readonly continuationGroupKey: string; }) => (snapshot: ServerProviderDraft): ServerProvider => ({ @@ -60,6 +61,7 @@ const withInstanceIdentity = driver: DRIVER_KIND, ...(input.displayName ? { displayName: input.displayName } : {}), ...(input.accentColor ? { accentColor: input.accentColor } : {}), + ...(input.iconUrl ? { iconUrl: input.iconUrl } : {}), continuation: { groupKey: input.continuationGroupKey }, }); @@ -71,7 +73,7 @@ export const ClaudeDriver: ProviderDriver = { }, configSchema: ClaudeSettings, defaultConfig: (): ClaudeSettings => Schema.decodeSync(ClaudeSettings)({}), - create: ({ instanceId, displayName, accentColor, environment, enabled, config }) => + create: ({ instanceId, displayName, accentColor, iconUrl, environment, enabled, config }) => Effect.gen(function* () { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const path = yield* Path.Path; @@ -87,6 +89,7 @@ export const ClaudeDriver: ProviderDriver = { instanceId, displayName, accentColor, + iconUrl, continuationGroupKey, }); @@ -148,6 +151,7 @@ export const ClaudeDriver: ProviderDriver = { }, displayName, accentColor, + iconUrl, enabled, snapshot, adapter, diff --git a/apps/server/src/provider/Drivers/CodexDriver.ts b/apps/server/src/provider/Drivers/CodexDriver.ts index 13598ab5f6..bb36d916b4 100644 --- a/apps/server/src/provider/Drivers/CodexDriver.ts +++ b/apps/server/src/provider/Drivers/CodexDriver.ts @@ -67,6 +67,7 @@ const withInstanceIdentity = readonly instanceId: ProviderInstance["instanceId"]; readonly displayName: string | undefined; readonly accentColor: string | undefined; + readonly iconUrl: string | undefined; readonly continuationGroupKey: string; }) => (snapshot: ServerProviderDraft): ServerProvider => ({ @@ -75,6 +76,7 @@ const withInstanceIdentity = driver: DRIVER_KIND, ...(input.displayName ? { displayName: input.displayName } : {}), ...(input.accentColor ? { accentColor: input.accentColor } : {}), + ...(input.iconUrl ? { iconUrl: input.iconUrl } : {}), continuation: { groupKey: input.continuationGroupKey }, }); @@ -86,7 +88,7 @@ export const CodexDriver: ProviderDriver = { }, configSchema: CodexSettings, defaultConfig: (): CodexSettings => Schema.decodeSync(CodexSettings)({}), - create: ({ instanceId, displayName, accentColor, environment, enabled, config }) => + create: ({ instanceId, displayName, accentColor, iconUrl, environment, enabled, config }) => Effect.gen(function* () { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const eventLoggers = yield* ProviderEventLoggers; @@ -97,6 +99,7 @@ export const CodexDriver: ProviderDriver = { instanceId, displayName, accentColor, + iconUrl, continuationGroupKey: continuationIdentity.continuationKey, }); yield* materializeCodexShadowHome(homeLayout).pipe( @@ -162,6 +165,7 @@ export const CodexDriver: ProviderDriver = { continuationIdentity, displayName, accentColor, + iconUrl, enabled, snapshot, adapter, diff --git a/apps/server/src/provider/Drivers/CursorDriver.ts b/apps/server/src/provider/Drivers/CursorDriver.ts index b7eda591bc..45600b4b43 100644 --- a/apps/server/src/provider/Drivers/CursorDriver.ts +++ b/apps/server/src/provider/Drivers/CursorDriver.ts @@ -50,6 +50,7 @@ const withInstanceIdentity = readonly instanceId: ProviderInstance["instanceId"]; readonly displayName: string | undefined; readonly accentColor: string | undefined; + readonly iconUrl: string | undefined; readonly continuationGroupKey: string; }) => (snapshot: ServerProviderDraft): ServerProvider => ({ @@ -58,6 +59,7 @@ const withInstanceIdentity = driver: DRIVER_KIND, ...(input.displayName ? { displayName: input.displayName } : {}), ...(input.accentColor ? { accentColor: input.accentColor } : {}), + ...(input.iconUrl ? { iconUrl: input.iconUrl } : {}), continuation: { groupKey: input.continuationGroupKey }, }); @@ -69,7 +71,7 @@ export const CursorDriver: ProviderDriver = { }, configSchema: CursorSettings, defaultConfig: (): CursorSettings => Schema.decodeSync(CursorSettings)({}), - create: ({ instanceId, displayName, accentColor, environment, enabled, config }) => + create: ({ instanceId, displayName, accentColor, iconUrl, environment, enabled, config }) => Effect.gen(function* () { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const fileSystem = yield* FileSystem.FileSystem; @@ -84,6 +86,7 @@ export const CursorDriver: ProviderDriver = { instanceId, displayName, accentColor, + iconUrl, continuationGroupKey: continuationIdentity.continuationKey, }); const effectiveConfig = { ...config, enabled } satisfies CursorSettings; @@ -139,6 +142,7 @@ export const CursorDriver: ProviderDriver = { continuationIdentity, displayName, accentColor, + iconUrl, enabled, snapshot, adapter, diff --git a/apps/server/src/provider/Drivers/OpenCodeDriver.ts b/apps/server/src/provider/Drivers/OpenCodeDriver.ts index 29f74ead02..f731974953 100644 --- a/apps/server/src/provider/Drivers/OpenCodeDriver.ts +++ b/apps/server/src/provider/Drivers/OpenCodeDriver.ts @@ -51,6 +51,7 @@ const withInstanceIdentity = readonly instanceId: ProviderInstance["instanceId"]; readonly displayName: string | undefined; readonly accentColor: string | undefined; + readonly iconUrl: string | undefined; readonly continuationGroupKey: string; }) => (snapshot: ServerProviderDraft): ServerProvider => ({ @@ -59,6 +60,7 @@ const withInstanceIdentity = driver: DRIVER_KIND, ...(input.displayName ? { displayName: input.displayName } : {}), ...(input.accentColor ? { accentColor: input.accentColor } : {}), + ...(input.iconUrl ? { iconUrl: input.iconUrl } : {}), continuation: { groupKey: input.continuationGroupKey }, }); @@ -70,7 +72,7 @@ export const OpenCodeDriver: ProviderDriver }, configSchema: OpenCodeSettings, defaultConfig: (): OpenCodeSettings => Schema.decodeSync(OpenCodeSettings)({}), - create: ({ instanceId, displayName, accentColor, environment, enabled, config }) => + create: ({ instanceId, displayName, accentColor, iconUrl, environment, enabled, config }) => Effect.gen(function* () { const openCodeRuntime = yield* OpenCodeRuntime; const serverConfig = yield* ServerConfig; @@ -84,6 +86,7 @@ export const OpenCodeDriver: ProviderDriver instanceId, displayName, accentColor, + iconUrl, continuationGroupKey: continuationIdentity.continuationKey, }); const effectiveConfig = { ...config, enabled } satisfies OpenCodeSettings; @@ -126,6 +129,7 @@ export const OpenCodeDriver: ProviderDriver continuationIdentity, displayName, accentColor, + iconUrl, enabled, snapshot, adapter, diff --git a/apps/server/src/provider/Layers/CursorAdapter.ts b/apps/server/src/provider/Layers/CursorAdapter.ts index 34d1221b02..3518006737 100644 --- a/apps/server/src/provider/Layers/CursorAdapter.ts +++ b/apps/server/src/provider/Layers/CursorAdapter.ts @@ -87,6 +87,20 @@ export interface CursorAdapterLiveOptions { readonly environment?: NodeJS.ProcessEnv; readonly nativeEventLogPath?: string; readonly nativeEventLogger?: EventNdjsonLogger; + readonly provider?: ProviderDriverKind; + readonly readyReason?: string; + readonly spawn?: (input: { + readonly settings: CursorSettings; + readonly cwd: string; + readonly environment?: NodeJS.ProcessEnv; + }) => { + readonly command: string; + readonly args: ReadonlyArray; + readonly cwd?: string; + readonly env?: NodeJS.ProcessEnv; + }; + readonly normalizeModel?: (model: string | null | undefined) => string; + readonly applyCursorModelOptions?: boolean; /** * Selections are honored when `modelSelection.instanceId` matches this value. * Defaults to the legacy built-in instance id (`cursor`). @@ -244,6 +258,8 @@ function applyRequestedSessionConfiguration(input: { readonly options?: ReadonlyArray | null | undefined; } | undefined; + readonly normalizeModel: (model: string | null | undefined) => string; + readonly applyCursorModelOptions: boolean; readonly mapError: (context: { readonly cause: import("effect-acp/errors").AcpError; readonly method: "session/set_config_option" | "session/set_mode"; @@ -251,16 +267,30 @@ function applyRequestedSessionConfiguration(input: { }): Effect.Effect { return Effect.gen(function* () { if (input.modelSelection) { - yield* applyCursorAcpModelSelection({ - runtime: input.runtime, - model: input.modelSelection.model, - selections: input.modelSelection.options, - mapError: ({ cause }) => - input.mapError({ - cause, - method: "session/set_config_option", - }), - }); + if (input.applyCursorModelOptions) { + yield* applyCursorAcpModelSelection({ + runtime: input.runtime, + model: input.modelSelection.model, + selections: input.modelSelection.options, + mapError: ({ cause }) => + input.mapError({ + cause, + method: "session/set_config_option", + }), + }); + } else { + const normalizedModel = input.normalizeModel(input.modelSelection.model); + if (normalizedModel !== "default") { + yield* input.runtime.setModel(normalizedModel).pipe( + Effect.mapError((cause) => + input.mapError({ + cause, + method: "session/set_config_option", + }), + ), + ); + } + } } const requestedModeId = resolveRequestedModeId({ @@ -304,6 +334,10 @@ export function makeCursorAdapter( options?: CursorAdapterLiveOptions, ) { return Effect.gen(function* () { + const providerKind = options?.provider ?? PROVIDER; + const readyReason = options?.readyReason ?? "Cursor ACP session ready"; + const normalizeModel = options?.normalizeModel ?? resolveCursorAcpBaseModelId; + const applyCursorModelOptions = options?.applyCursorModelOptions ?? true; const boundInstanceId = options?.instanceId ?? ProviderInstanceId.make("cursor"); const fileSystem = yield* FileSystem.FileSystem; const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; @@ -365,7 +399,7 @@ export function makeCursorAdapter( event: { id: crypto.randomUUID(), kind: "notification", - provider: PROVIDER, + provider: providerKind, createdAt: observedAt, method, threadId, @@ -398,7 +432,7 @@ export function makeCursorAdapter( yield* offerRuntimeEvent( makeAcpPlanUpdatedEvent({ stamp: yield* makeEventStamp(), - provider: PROVIDER, + provider: providerKind, threadId: ctx.threadId, turnId: ctx.activeTurnId, payload, @@ -415,7 +449,7 @@ export function makeCursorAdapter( const ctx = sessions.get(threadId); if (!ctx || ctx.stopped) { return Effect.fail( - new ProviderAdapterSessionNotFoundError({ provider: PROVIDER, threadId }), + new ProviderAdapterSessionNotFoundError({ provider: providerKind, threadId }), ); } return Effect.succeed(ctx); @@ -435,7 +469,7 @@ export function makeCursorAdapter( yield* offerRuntimeEvent({ type: "session.exited", ...(yield* makeEventStamp()), - provider: PROVIDER, + provider: providerKind, threadId: ctx.threadId, payload: { exitKind: "graceful" }, }); @@ -445,16 +479,16 @@ export function makeCursorAdapter( withThreadLock( input.threadId, Effect.gen(function* () { - if (input.provider !== undefined && input.provider !== PROVIDER) { + if (input.provider !== undefined && input.provider !== providerKind) { return yield* new ProviderAdapterValidationError({ - provider: PROVIDER, + provider: providerKind, operation: "startSession", - issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`, + issue: `Expected provider '${providerKind}' but received '${input.provider}'.`, }); } if (!input.cwd?.trim()) { return yield* new ProviderAdapterValidationError({ - provider: PROVIDER, + provider: providerKind, operation: "startSession", issue: "cwd is required and must be non-empty.", }); @@ -480,7 +514,7 @@ export function makeCursorAdapter( const resumeSessionId = parseCursorResume(input.resumeCursor)?.sessionId; const acpNativeLoggers = makeAcpNativeLoggers({ nativeEventLogger, - provider: PROVIDER, + provider: providerKind, threadId: input.threadId, }); @@ -499,6 +533,15 @@ export function makeCursorAdapter( const acp = yield* makeCursorAcpRuntime({ cursorSettings: effectiveCursorSettings, ...(options?.environment ? { environment: options.environment } : {}), + ...(options?.spawn + ? { + spawn: options.spawn({ + settings: effectiveCursorSettings, + cwd, + ...(options.environment ? { environment: options.environment } : {}), + }), + } + : {}), childProcessSpawner, cwd, ...(resumeSessionId ? { resumeSessionId } : {}), @@ -509,7 +552,7 @@ export function makeCursorAdapter( Effect.mapError( (cause) => new ProviderAdapterProcessError({ - provider: PROVIDER, + provider: providerKind, threadId: input.threadId, detail: cause.message, cause, @@ -532,7 +575,7 @@ export function makeCursorAdapter( yield* offerRuntimeEvent({ type: "user-input.requested", ...(yield* makeEventStamp()), - provider: PROVIDER, + provider: providerKind, threadId: input.threadId, turnId: ctx?.activeTurnId, requestId: runtimeRequestId, @@ -548,7 +591,7 @@ export function makeCursorAdapter( yield* offerRuntimeEvent({ type: "user-input.resolved", ...(yield* makeEventStamp()), - provider: PROVIDER, + provider: providerKind, threadId: input.threadId, turnId: ctx?.activeTurnId, requestId: runtimeRequestId, @@ -568,7 +611,7 @@ export function makeCursorAdapter( yield* offerRuntimeEvent({ type: "turn.proposed.completed", ...(yield* makeEventStamp()), - provider: PROVIDER, + provider: providerKind, threadId: input.threadId, turnId: ctx?.activeTurnId, payload: { planMarkdown: extractPlanMarkdown(params) }, @@ -633,7 +676,7 @@ export function makeCursorAdapter( yield* offerRuntimeEvent( makeAcpRequestOpenedEvent({ stamp: yield* makeEventStamp(), - provider: PROVIDER, + provider: providerKind, threadId: input.threadId, turnId: ctx?.activeTurnId, requestId: runtimeRequestId, @@ -650,7 +693,7 @@ export function makeCursorAdapter( yield* offerRuntimeEvent( makeAcpRequestResolvedEvent({ stamp: yield* makeEventStamp(), - provider: PROVIDER, + provider: providerKind, threadId: input.threadId, turnId: ctx?.activeTurnId, requestId: runtimeRequestId, @@ -672,7 +715,7 @@ export function makeCursorAdapter( return yield* acp.start(); }).pipe( Effect.mapError((error) => - mapAcpToAdapterError(PROVIDER, input.threadId, "session/start", error), + mapAcpToAdapterError(providerKind, input.threadId, "session/start", error), ), ); @@ -681,13 +724,15 @@ export function makeCursorAdapter( runtimeMode: input.runtimeMode, interactionMode: undefined, modelSelection: cursorModelSelection, + normalizeModel, + applyCursorModelOptions, mapError: ({ cause, method }) => - mapAcpToAdapterError(PROVIDER, input.threadId, method, cause), + mapAcpToAdapterError(providerKind, input.threadId, method, cause), }); const now = yield* nowIso; const session: ProviderSession = { - provider: PROVIDER, + provider: providerKind, providerInstanceId: boundInstanceId, status: "ready", runtimeMode: input.runtimeMode, @@ -726,7 +771,7 @@ export function makeCursorAdapter( yield* offerRuntimeEvent( makeAcpAssistantItemEvent({ stamp: yield* makeEventStamp(), - provider: PROVIDER, + provider: providerKind, threadId: ctx.threadId, turnId: ctx.activeTurnId, itemId: event.itemId, @@ -738,7 +783,7 @@ export function makeCursorAdapter( yield* offerRuntimeEvent( makeAcpAssistantItemEvent({ stamp: yield* makeEventStamp(), - provider: PROVIDER, + provider: providerKind, threadId: ctx.threadId, turnId: ctx.activeTurnId, itemId: event.itemId, @@ -771,7 +816,7 @@ export function makeCursorAdapter( yield* offerRuntimeEvent( makeAcpToolCallEvent({ stamp: yield* makeEventStamp(), - provider: PROVIDER, + provider: providerKind, threadId: ctx.threadId, turnId: ctx.activeTurnId, toolCall: event.toolCall, @@ -789,7 +834,7 @@ export function makeCursorAdapter( yield* offerRuntimeEvent( makeAcpContentDeltaEvent({ stamp: yield* makeEventStamp(), - provider: PROVIDER, + provider: providerKind, threadId: ctx.threadId, turnId: ctx.activeTurnId, ...(event.itemId ? { itemId: event.itemId } : {}), @@ -810,21 +855,21 @@ export function makeCursorAdapter( yield* offerRuntimeEvent({ type: "session.started", ...(yield* makeEventStamp()), - provider: PROVIDER, + provider: providerKind, threadId: input.threadId, payload: { resume: started.initializeResult }, }); yield* offerRuntimeEvent({ type: "session.state.changed", ...(yield* makeEventStamp()), - provider: PROVIDER, + provider: providerKind, threadId: input.threadId, - payload: { state: "ready", reason: "Cursor ACP session ready" }, + payload: { state: "ready", reason: readyReason }, }); yield* offerRuntimeEvent({ type: "thread.started", ...(yield* makeEventStamp()), - provider: PROVIDER, + provider: providerKind, threadId: input.threadId, payload: { providerThreadId: started.sessionId }, }); @@ -840,7 +885,7 @@ export function makeCursorAdapter( const turnModelSelection = input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined; const model = turnModelSelection?.model ?? ctx.session.model; - const resolvedModel = resolveCursorAcpBaseModelId(model); + const resolvedModel = normalizeModel(model); yield* applyRequestedSessionConfiguration({ runtime: ctx.acp, runtimeMode: ctx.session.runtimeMode, @@ -852,8 +897,10 @@ export function makeCursorAdapter( model, options: turnModelSelection?.options, }, + normalizeModel, + applyCursorModelOptions, mapError: ({ cause, method }) => - mapAcpToAdapterError(PROVIDER, input.threadId, method, cause), + mapAcpToAdapterError(providerKind, input.threadId, method, cause), }); ctx.activeTurnId = turnId; ctx.lastPlanFingerprint = undefined; @@ -866,7 +913,7 @@ export function makeCursorAdapter( yield* offerRuntimeEvent({ type: "turn.started", ...(yield* makeEventStamp()), - provider: PROVIDER, + provider: providerKind, threadId: input.threadId, turnId, payload: { model: resolvedModel }, @@ -884,7 +931,7 @@ export function makeCursorAdapter( }); if (!attachmentPath) { return yield* new ProviderAdapterRequestError({ - provider: PROVIDER, + provider: providerKind, method: "session/prompt", detail: `Invalid attachment id '${attachment.id}'.`, }); @@ -893,7 +940,7 @@ export function makeCursorAdapter( Effect.mapError( (cause) => new ProviderAdapterRequestError({ - provider: PROVIDER, + provider: providerKind, method: "session/prompt", detail: cause.message, cause, @@ -910,7 +957,7 @@ export function makeCursorAdapter( if (promptParts.length === 0) { return yield* new ProviderAdapterValidationError({ - provider: PROVIDER, + provider: providerKind, operation: "sendTurn", issue: "Turn requires non-empty text or attachments.", }); @@ -922,7 +969,7 @@ export function makeCursorAdapter( }) .pipe( Effect.mapError((error) => - mapAcpToAdapterError(PROVIDER, input.threadId, "session/prompt", error), + mapAcpToAdapterError(providerKind, input.threadId, "session/prompt", error), ), ); @@ -937,7 +984,7 @@ export function makeCursorAdapter( yield* offerRuntimeEvent({ type: "turn.completed", ...(yield* makeEventStamp()), - provider: PROVIDER, + provider: providerKind, threadId: input.threadId, turnId, payload: { @@ -961,7 +1008,7 @@ export function makeCursorAdapter( yield* Effect.ignore( ctx.acp.cancel.pipe( Effect.mapError((error) => - mapAcpToAdapterError(PROVIDER, threadId, "session/cancel", error), + mapAcpToAdapterError(providerKind, threadId, "session/cancel", error), ), ), ); @@ -977,7 +1024,7 @@ export function makeCursorAdapter( const pending = ctx.pendingApprovals.get(requestId); if (!pending) { return yield* new ProviderAdapterRequestError({ - provider: PROVIDER, + provider: providerKind, method: "session/request_permission", detail: `Unknown pending approval request: ${requestId}`, }); @@ -995,7 +1042,7 @@ export function makeCursorAdapter( const pending = ctx.pendingUserInputs.get(requestId); if (!pending) { return yield* new ProviderAdapterRequestError({ - provider: PROVIDER, + provider: providerKind, method: "cursor/ask_question", detail: `Unknown pending user-input request: ${requestId}`, }); @@ -1014,7 +1061,7 @@ export function makeCursorAdapter( const ctx = yield* requireSession(threadId); if (!Number.isInteger(numTurns) || numTurns < 1) { return yield* new ProviderAdapterValidationError({ - provider: PROVIDER, + provider: providerKind, operation: "rollbackThread", issue: "numTurns must be an integer >= 1.", }); @@ -1055,7 +1102,7 @@ export function makeCursorAdapter( const streamEvents = Stream.fromPubSub(runtimeEventPubSub); return { - provider: PROVIDER, + provider: providerKind, capabilities: { sessionModelSwitch: "in-session" }, startSession, sendTurn, diff --git a/apps/server/src/provider/Layers/ProviderInstanceRegistryLive.ts b/apps/server/src/provider/Layers/ProviderInstanceRegistryLive.ts index 63f687f55b..3b8d742437 100644 --- a/apps/server/src/provider/Layers/ProviderInstanceRegistryLive.ts +++ b/apps/server/src/provider/Layers/ProviderInstanceRegistryLive.ts @@ -120,6 +120,7 @@ const buildEntry = (input: { instanceId, displayName: entry.displayName, accentColor: entry.accentColor, + iconUrl: entry.iconUrl, reason: `Driver '${entry.driver}' is not registered in this build.`, }), }; @@ -142,6 +143,7 @@ const buildEntry = (input: { instanceId, displayName: entry.displayName, accentColor: entry.accentColor, + iconUrl: entry.iconUrl, reason: `Invalid config for instance '${rawInstanceId}': ${detail}`, }), }; @@ -161,6 +163,7 @@ const buildEntry = (input: { instanceId, displayName: entry.displayName, accentColor: entry.accentColor, + iconUrl: entry.iconUrl, environment: entry.environment ?? [], enabled: entry.enabled ?? decodedConfigEnabled(typedConfig) ?? true, config: typedConfig, @@ -180,6 +183,7 @@ const buildEntry = (input: { instanceId, displayName: entry.displayName, accentColor: entry.accentColor, + iconUrl: entry.iconUrl, reason: `Driver '${entry.driver}' failed to create instance: ${createResult.failure.detail}`, }), }; diff --git a/apps/server/src/provider/ProviderDriver.ts b/apps/server/src/provider/ProviderDriver.ts index bedfd61194..828617959d 100644 --- a/apps/server/src/provider/ProviderDriver.ts +++ b/apps/server/src/provider/ProviderDriver.ts @@ -65,6 +65,7 @@ export interface ProviderInstance { readonly continuationIdentity: ProviderContinuationIdentity; readonly displayName: string | undefined; readonly accentColor?: string | undefined; + readonly iconUrl?: string | undefined; readonly enabled: boolean; readonly snapshot: ServerProviderShape; readonly adapter: ProviderAdapterShape; @@ -96,6 +97,7 @@ export interface ProviderDriverCreateInput { readonly instanceId: ProviderInstanceId; readonly displayName: string | undefined; readonly accentColor?: string | undefined; + readonly iconUrl?: string | undefined; readonly environment: ProviderInstanceEnvironment; readonly enabled: boolean; readonly config: Config; diff --git a/apps/server/src/provider/Services/AcpRegistryClient.ts b/apps/server/src/provider/Services/AcpRegistryClient.ts new file mode 100644 index 0000000000..b521d1e496 --- /dev/null +++ b/apps/server/src/provider/Services/AcpRegistryClient.ts @@ -0,0 +1,13 @@ +import { Schema } from "effect"; + +export class AcpRegistryClientError extends Schema.TaggedErrorClass()( + "AcpRegistryClientError", + { + detail: Schema.String, + cause: Schema.optional(Schema.Defect), + }, +) { + override get message(): string { + return this.detail; + } +} diff --git a/apps/server/src/provider/acp/CursorAcpSupport.ts b/apps/server/src/provider/acp/CursorAcpSupport.ts index 3e405dd7ff..7bd4edcab2 100644 --- a/apps/server/src/provider/acp/CursorAcpSupport.ts +++ b/apps/server/src/provider/acp/CursorAcpSupport.ts @@ -2,6 +2,7 @@ import { type CursorSettings, type ProviderOptionSelection } from "@t3tools/cont import { Effect, Layer, Scope } from "effect"; import { ChildProcessSpawner } from "effect/unstable/process"; import type * as EffectAcpErrors from "effect-acp/errors"; +import type * as EffectAcpSchema from "effect-acp/schema"; import { CURSOR_PARAMETERIZED_MODEL_PICKER_CAPABILITIES, @@ -24,6 +25,9 @@ export interface CursorAcpRuntimeInput extends Omit< readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"]; readonly cursorSettings: CursorAcpRuntimeCursorSettings | null | undefined; readonly environment?: NodeJS.ProcessEnv; + readonly spawn?: AcpSpawnInput; + readonly authMethodId?: string; + readonly clientCapabilities?: EffectAcpSchema.InitializeRequest["clientCapabilities"]; } export interface CursorAcpModelSelectionErrorContext { @@ -55,9 +59,12 @@ export const makeCursorAcpRuntime = ( const acpContext = yield* Layer.build( AcpSessionRuntime.layer({ ...input, - spawn: buildCursorAcpSpawnInput(input.cursorSettings, input.cwd, input.environment), - authMethodId: "cursor_login", - clientCapabilities: CURSOR_PARAMETERIZED_MODEL_PICKER_CAPABILITIES, + spawn: + input.spawn ?? + buildCursorAcpSpawnInput(input.cursorSettings, input.cwd, input.environment), + authMethodId: input.authMethodId ?? "cursor_login", + clientCapabilities: + input.clientCapabilities ?? CURSOR_PARAMETERIZED_MODEL_PICKER_CAPABILITIES, }).pipe( Layer.provide( Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, input.childProcessSpawner), diff --git a/apps/server/src/provider/builtInDrivers.ts b/apps/server/src/provider/builtInDrivers.ts index 5af56dc6b0..4c5a5bb7c5 100644 --- a/apps/server/src/provider/builtInDrivers.ts +++ b/apps/server/src/provider/builtInDrivers.ts @@ -24,6 +24,7 @@ import { ClaudeDriver, type ClaudeDriverEnv } from "./Drivers/ClaudeDriver.ts"; import { CodexDriver, type CodexDriverEnv } from "./Drivers/CodexDriver.ts"; import { CursorDriver, type CursorDriverEnv } from "./Drivers/CursorDriver.ts"; import { OpenCodeDriver, type OpenCodeDriverEnv } from "./Drivers/OpenCodeDriver.ts"; +import { AcpRegistryDriver, type AcpRegistryDriverEnv } from "./Drivers/AcpRegistryDriver.ts"; import type { AnyProviderDriver } from "./ProviderDriver.ts"; /** @@ -35,7 +36,8 @@ export type BuiltInDriversEnv = | ClaudeDriverEnv | CodexDriverEnv | CursorDriverEnv - | OpenCodeDriverEnv; + | OpenCodeDriverEnv + | AcpRegistryDriverEnv; /** * Ordered list of built-in drivers. Order matters only for tie-breaking in @@ -47,4 +49,5 @@ export const BUILT_IN_DRIVERS: ReadonlyArray)[getAcpBinaryPlatformKey()]; + if (!target || typeof target !== "object" || globalThis.Array.isArray(target)) return null; + const record = target as Record; + if (typeof record.archive !== "string" || typeof record.cmd !== "string") return null; + return { archive: record.archive, cmd: record.cmd }; +} + +async function fileExists(path: string): Promise { + try { + await access(path); + return true; + } catch { + return false; + } +} + +function normalizeArchiveCommandPath(command: string): string { + const trimmed = command.trim(); + if (!trimmed) { + throw new Error("Registry binary command must not be empty."); + } + if (isAbsolute(trimmed)) { + throw new Error("Registry binary command must be a relative archive path."); + } + const withoutLeadingDot = trimmed.replace(/^(?:\.[/\\])+/u, ""); + const parts = withoutLeadingDot + .split(/[/\\]+/u) + .filter((part) => part.length > 0 && part !== "."); + if (parts.length === 0 || parts.some((part) => part === "..")) { + throw new Error("Registry binary command resolves outside the archive."); + } + return join(...parts); +} + +function resolveInstallRootFromBinaryPath(binaryPath: string, commandRelativePath: string): string { + const depth = commandRelativePath.split(/[/\\]+/u).filter((part) => part.length > 0).length; + let installRoot = binaryPath; + for (let index = 0; index < depth; index += 1) { + installRoot = dirname(installRoot); + } + return installRoot; +} + +function resolveAcpBinaryInstallPath( + config: { readonly stateDir: string }, + agent: AcpRegistryAgent, +) { + const commandPath = normalizeArchiveCommandPath(getBinaryTarget(agent)?.cmd ?? agent.id); + return join(config.stateDir, ACP_BINARY_INSTALLS_DIR, agent.id, agent.version, commandPath); +} + +function expandUserPath(path: string): string { + if (path === "~") return homedir(); + if (path.startsWith("~/") || path.startsWith("~\\")) return join(homedir(), path.slice(2)); + return path; +} + +function normalizeAcpBinaryInstallPath(path: string): string { + const expanded = expandUserPath(path.trim()); + return isAbsolute(expanded) ? expanded : resolve(expanded); +} + +function displayPath(path: string): string { + const home = homedir(); + return path === home || path.startsWith(`${home}/`) || path.startsWith(`${home}\\`) + ? `~${path.slice(home.length)}` + : path; +} + +function isPathInside(parent: string, child: string): boolean { + const relativePath = relative(parent, child); + return relativePath === "" || (!relativePath.startsWith("..") && !isAbsolute(relativePath)); +} + +function toBinaryInstallPreview( + config: { readonly stateDir: string }, + agent: AcpRegistryAgent, + target: BinaryDistributionTarget, +) { + const defaultInstallPath = resolveAcpBinaryInstallPath(config, agent); + return { + archiveUrl: target.archive, + defaultInstallPath: displayPath(defaultInstallPath), + platformKey: getAcpBinaryPlatformKey(), + command: target.cmd, + }; +} + +function resolveAcpBinaryManifestPath( + config: { readonly stateDir: string }, + agent: AcpRegistryAgent, +) { + return join(dirname(resolveAcpBinaryInstallPath(config, agent)), ACP_BINARY_MANIFEST_FILE); +} + +async function readAcpBinaryManifest( + config: { readonly stateDir: string }, + agent: AcpRegistryAgent, +): Promise { + const manifestPath = resolveAcpBinaryManifestPath(config, agent); + try { + const raw = await readFile(manifestPath, "utf8"); + const parsed = JSON.parse(raw) as Partial; + if ( + parsed.layoutVersion === 2 && + parsed.agentId === agent.id && + parsed.version === agent.version && + parsed.platformKey === getAcpBinaryPlatformKey() && + typeof parsed.command === "string" && + (await fileExists(parsed.command)) + ) { + return parsed as AcpBinaryInstallManifest; + } + return null; + } catch { + return null; + } +} + +async function downloadFile(url: string, destination: string): Promise { + const response = await fetch(url); + if (!response.ok || !response.body) { + throw new Error(`Download failed with status ${response.status}`); + } + await pipeline(response.body, createWriteStream(destination)); +} + +async function extractArchive(archivePath: string, destinationDir: string): Promise { + if (archivePath.endsWith(".tar.gz") || archivePath.endsWith(".tgz")) { + await execFileAsync("tar", ["-xzf", archivePath, "-C", destinationDir]); + return; + } + if (archivePath.endsWith(".zip")) { + if (platform() === "win32") { + await execFileAsync("powershell.exe", [ + "-NoProfile", + "-Command", + "Expand-Archive", + "-LiteralPath", + archivePath, + "-DestinationPath", + destinationDir, + "-Force", + ]); + return; + } + await execFileAsync("unzip", ["-q", archivePath, "-d", destinationDir]); + return; + } + throw new Error("Unsupported binary archive format."); +} + +async function installAcpBinaryAgent(input: { + readonly config: { readonly stateDir: string }; + readonly agent: AcpRegistryAgent; + readonly installPath?: string | undefined; +}): Promise { + const target = getBinaryTarget(input.agent); + if (!target) { + throw new Error(`No binary is available for ${getAcpBinaryPlatformKey()}.`); + } + const installPath = normalizeAcpBinaryInstallPath( + input.installPath?.trim() || resolveAcpBinaryInstallPath(input.config, input.agent), + ); + const commandPath = normalizeArchiveCommandPath(target.cmd); + const installRoot = resolveInstallRootFromBinaryPath(installPath, commandPath); + if (installRoot === dirname(installRoot)) { + throw new Error(`Binary path is too shallow for registry command '${target.cmd}'.`); + } + const manifestPath = resolveAcpBinaryManifestPath(input.config, input.agent); + const tempDir = await mkdtemp(join(tmpdir(), "t3-acp-agent-")); + try { + const archivePath = join( + tempDir, + basename(new URL(target.archive).pathname) || "agent.archive", + ); + const extractDir = join(tempDir, "extract"); + await mkdir(extractDir, { recursive: true }); + await downloadFile(target.archive, archivePath); + await extractArchive(archivePath, extractDir); + + const extractedCommand = resolve(extractDir, commandPath); + if (!isPathInside(extractDir, extractedCommand)) { + throw new Error(`Registry binary command resolves outside the archive.`); + } + if (!(await fileExists(extractedCommand))) { + throw new Error(`Installed archive did not contain expected command '${target.cmd}'.`); + } + await mkdir(installRoot, { recursive: true }); + await cp(extractDir, installRoot, { + recursive: true, + force: true, + errorOnExist: false, + }); + if (!(await fileExists(installPath))) { + await mkdir(dirname(installPath), { recursive: true }); + await copyFile(extractedCommand, installPath); + } + if (platform() !== "win32") { + await chmod(installPath, 0o755); + } + } finally { + await rm(tempDir, { recursive: true, force: true }); + } + const manifest: AcpBinaryInstallManifest = { + layoutVersion: 2, + agentId: input.agent.id, + version: input.agent.version, + platformKey: getAcpBinaryPlatformKey(), + command: installPath, + archiveUrl: target.archive, + }; + await mkdir(dirname(manifestPath), { recursive: true }); + await writeFile(manifestPath, JSON.stringify(manifest, null, 2)); + return { ...target, command: installPath }; +} + +async function toAcpLaunchSpec( + agent: AcpRegistryAgent, + config: { readonly stateDir: string }, +): Promise<{ + readonly supported: boolean; + readonly distributionType: "npx" | "uvx" | "binary" | "binaryUnsupported"; + readonly launch: { + readonly command: string; + readonly args: readonly string[]; + readonly env: Record; + } | null; + readonly binaryInstall?: { + readonly archiveUrl: string; + readonly defaultInstallPath: string; + readonly platformKey: string; + readonly command: string; + }; +}> { + if (agent.distribution.npx) { + return { + supported: true as const, + distributionType: "npx" as const, + launch: { + command: "npx", + args: ["-y", agent.distribution.npx.package, ...(agent.distribution.npx.args ?? [])], + env: agent.distribution.npx.env ?? {}, + }, + }; + } + if (agent.distribution.uvx) { + return { + supported: true as const, + distributionType: "uvx" as const, + launch: { + command: "uvx", + args: [agent.distribution.uvx.package, ...(agent.distribution.uvx.args ?? [])], + env: agent.distribution.uvx.env ?? {}, + }, + }; + } + const manifest = await readAcpBinaryManifest(config, agent); + const target = getBinaryTarget(agent); + if (manifest) { + return { + supported: true as const, + distributionType: "binary" as const, + launch: { + command: manifest.command, + args: [], + env: {}, + }, + ...(target ? { binaryInstall: toBinaryInstallPreview(config, agent, target) } : {}), + }; + } + return { + supported: false as const, + distributionType: "binaryUnsupported" as const, + launch: null, + ...(target ? { binaryInstall: toBinaryInstallPreview(config, agent, target) } : {}), + }; +} function toAuthAccessStreamEvent( change: BootstrapCredentialChange | SessionCredentialChange, @@ -162,6 +494,110 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) => clientSessions: serverAuth.listClientSessions(currentSessionId).pipe(Effect.orDie), }); + const loadAcpRegistryIndex = serverSettings.getSettings.pipe( + Effect.flatMap((settings) => + Effect.tryPromise({ + try: async () => { + const response = await fetch(settings.providers.acpRegistry.registryUrl); + if (!response.ok) { + throw new Error(`Registry request failed with status ${response.status}`); + } + return response.json(); + }, + catch: (cause) => + new AcpRegistryClientError({ + detail: cause instanceof Error ? cause.message : String(cause), + cause, + }), + }), + ), + Effect.flatMap((raw) => Schema.decodeUnknownEffect(AcpRegistryIndex)(raw)), + ); + + const listAcpRegistry = Effect.all({ + registry: loadAcpRegistryIndex, + config: Effect.succeed(config), + }).pipe( + Effect.flatMap(({ registry, config }) => + Effect.tryPromise({ + try: async (): Promise => ({ + registryVersion: registry.version, + agents: ( + await Promise.all( + registry.agents.map(async (agent) => { + const resolved = await toAcpLaunchSpec(agent, config); + return { + agent, + supported: resolved.supported, + distributionType: resolved.distributionType, + launch: resolved.launch, + ...(resolved.binaryInstall ? { binaryInstall: resolved.binaryInstall } : {}), + }; + }), + ) + ).toSorted((left, right) => left.agent.name.localeCompare(right.agent.name)), + }), + catch: (cause) => + new AcpRegistryClientError({ + detail: cause instanceof Error ? cause.message : String(cause), + cause, + }), + }), + ), + ); + + const installAcpRegistryBinary = (input: { + readonly agentId: string; + readonly installPath?: string | undefined; + }) => + Effect.all({ + registry: loadAcpRegistryIndex, + config: Effect.succeed(config), + }).pipe( + Effect.flatMap(({ registry, config }) => + Effect.tryPromise({ + try: async (): Promise => { + const agent = registry.agents.find((entry) => entry.id === input.agentId); + if (!agent) { + return { + ok: false, + error: `No ACP registry agent found for '${input.agentId}'.`, + }; + } + const installed = await installAcpBinaryAgent({ + config, + agent, + installPath: input.installPath, + }); + return { + ok: true, + agent: { + agent, + supported: true, + distributionType: "binary", + binaryInstall: toBinaryInstallPreview(config, agent, installed), + launch: { + command: installed.command, + args: [], + env: {}, + }, + }, + }; + }, + catch: (cause): AcpRegistryInstallBinaryResult => ({ + ok: false, + error: cause instanceof Error ? cause.message : String(cause), + }), + }), + ), + Effect.catch((cause: unknown) => + Effect.succeed({ + ok: false, + error: cause instanceof Error ? cause.message : String(cause), + } satisfies AcpRegistryInstallBinaryResult), + ), + ); + const appendSetupScriptActivity = (input: { readonly threadId: ThreadId; readonly kind: "setup-script.requested" | "setup-script.started" | "setup-script.failed"; @@ -783,6 +1219,32 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) => "rpc.aggregate": "server", }, ), + [WS_METHODS.serverListAcpRegistry]: (_input) => + observeRpcEffect( + WS_METHODS.serverListAcpRegistry, + listAcpRegistry.pipe( + Effect.tapError((error) => + Effect.logWarning("failed to list ACP registry agents", { + error: error.message, + }), + ), + Effect.orElseSucceed(() => ({ + registryVersion: "unavailable", + agents: [], + })), + ), + { + "rpc.aggregate": "server", + }, + ), + [WS_METHODS.serverInstallAcpRegistryBinary]: (input) => + observeRpcEffect( + WS_METHODS.serverInstallAcpRegistryBinary, + installAcpRegistryBinary(input), + { + "rpc.aggregate": "server", + }, + ), [WS_METHODS.projectsSearchEntries]: (input) => observeRpcEffect( WS_METHODS.projectsSearchEntries, diff --git a/apps/web/src/components/KeybindingsToast.browser.tsx b/apps/web/src/components/KeybindingsToast.browser.tsx index df1c6ba542..04242067f1 100644 --- a/apps/web/src/components/KeybindingsToast.browser.tsx +++ b/apps/web/src/components/KeybindingsToast.browser.tsx @@ -103,6 +103,7 @@ function createBaseServerConfig(): ServerConfig { model: "gpt-5.4-mini", }, providers: { + ...DEFAULT_SERVER_SETTINGS.providers, codex: { enabled: true, binaryPath: "", diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 2b7f62e8af..535a6b68ef 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -99,6 +99,7 @@ import { proposedPlanTitle } from "../../proposedPlan"; import { getProviderInteractionModeToggle } from "../../providerModels"; import { deriveProviderInstanceEntries, + isModelPickerProviderInstanceEntry, resolveProviderDriverKindForInstanceSelection, sortProviderInstanceEntries, type ProviderInstanceEntry, @@ -574,7 +575,12 @@ export const ChatComposer = memo( // configured instance (default built-in + any custom `providerInstances.*`), // sorted default-first per driver kind for a stable picker order. const providerInstanceEntries = useMemo>( - () => sortProviderInstanceEntries(deriveProviderInstanceEntries(providerStatuses)), + () => + sortProviderInstanceEntries( + deriveProviderInstanceEntries(providerStatuses).filter( + isModelPickerProviderInstanceEntry, + ), + ), [providerStatuses], ); const selectedProviderByThreadId = composerDraft.activeProvider ?? null; diff --git a/apps/web/src/components/chat/ModelListRow.tsx b/apps/web/src/components/chat/ModelListRow.tsx index 064df338e4..6661d0aacd 100644 --- a/apps/web/src/components/chat/ModelListRow.tsx +++ b/apps/web/src/components/chat/ModelListRow.tsx @@ -5,8 +5,8 @@ import { getDisplayModelName, getTriggerDisplayModelLabel, type ModelEsque, - PROVIDER_ICON_BY_PROVIDER, } from "./providerIconUtils"; +import { ProviderInstanceIcon } from "./ProviderInstanceIcon"; import { ComboboxItem } from "../ui/combobox"; import { Kbd } from "../ui/kbd"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; @@ -26,6 +26,7 @@ export const ModelListRow = memo(function ModelListRow(props: { */ providerDisplayName: string; providerAccentColor?: string | undefined; + providerIconUrl?: string | undefined; isFavorite: boolean; showProvider: boolean; preferShortName?: boolean; @@ -34,7 +35,6 @@ export const ModelListRow = memo(function ModelListRow(props: { jumpLabel?: string | null; onToggleFavorite: () => void; }) { - const ProviderIcon = PROVIDER_ICON_BY_PROVIDER[props.driverKind] ?? null; const providerLabel = props.model.subProvider ? `${props.providerDisplayName} · ${props.model.subProvider}` : props.providerDisplayName; @@ -104,7 +104,13 @@ export const ModelListRow = memo(function ModelListRow(props: { {props.showProvider && (
- {ProviderIcon ? : null} + {props.providerAccentColor ? ( { + const lockedHeaderEntry = useMemo(() => { if (!isLocked || !props.lockedProvider) return null; const matches = instanceEntries.filter((entry) => matchesLockedProvider(entry)); if (matches.length === 0) return null; const active = matches.find((entry) => entry.instanceId === props.activeInstanceId); - return (active ?? matches[0])?.displayName ?? null; + return active ?? matches[0] ?? null; }, [ isLocked, matchesLockedProvider, @@ -524,12 +525,18 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { )} > {/* Locked provider header (only shown in locked mode) */} - {isLocked && !showLockedInstanceSidebar && LockedProviderIcon && lockedHeaderLabel && ( + {isLocked && !showLockedInstanceSidebar && lockedHeaderEntry ? (
- - {lockedHeaderLabel} + + {lockedHeaderEntry.displayName}
- )} + ) : null} {/* Sidebar (only in unlocked mode) */} {showSidebar && ( @@ -626,6 +633,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { driverKind={model.driverKind} providerDisplayName={model.instanceDisplayName} providerAccentColor={model.instanceAccentColor} + providerIconUrl={model.instanceIconUrl} isFavorite={favoritesSet.has(modelKey)} showProvider={!isLocked || showLockedInstanceSidebar} preferShortName={!isLocked} diff --git a/apps/web/src/components/chat/ModelPickerSidebar.tsx b/apps/web/src/components/chat/ModelPickerSidebar.tsx index 121b5267a3..90fa124a1f 100644 --- a/apps/web/src/components/chat/ModelPickerSidebar.tsx +++ b/apps/web/src/components/chat/ModelPickerSidebar.tsx @@ -158,6 +158,7 @@ export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: { driverKind={entry.driverKind} displayName={entry.displayName} accentColor={entry.accentColor} + iconUrl={entry.iconUrl} showBadge={showInstanceBadge} className="size-6" iconClassName="size-5" diff --git a/apps/web/src/components/chat/ProviderInstanceIcon.tsx b/apps/web/src/components/chat/ProviderInstanceIcon.tsx index 154cada19a..88701f3c55 100644 --- a/apps/web/src/components/chat/ProviderInstanceIcon.tsx +++ b/apps/web/src/components/chat/ProviderInstanceIcon.tsx @@ -1,4 +1,4 @@ -import { type CSSProperties, memo } from "react"; +import { type CSSProperties, memo, useEffect, useState } from "react"; import { type ProviderDriverKind } from "@t3tools/contracts"; import { PROVIDER_ICON_BY_PROVIDER } from "./providerIconUtils"; @@ -18,6 +18,7 @@ export const ProviderInstanceIcon = memo(function ProviderInstanceIcon(props: { driverKind: ProviderDriverKind; displayName: string; accentColor?: string | undefined; + iconUrl?: string | undefined; showBadge?: boolean; className?: string; iconClassName?: string; @@ -25,10 +26,17 @@ export const ProviderInstanceIcon = memo(function ProviderInstanceIcon(props: { statusDotClassName?: string; }) { const Icon = PROVIDER_ICON_BY_PROVIDER[props.driverKind] ?? null; + const [imageFailed, setImageFailed] = useState(false); + const customIconUrl = props.iconUrl?.trim(); + const showCustomIcon = Boolean(customIconUrl) && !imageFailed; const accentStyle = props.accentColor ? ({ "--provider-accent": props.accentColor } as CSSProperties) : undefined; + useEffect(() => { + setImageFailed(false); + }, [customIconUrl]); + return ( - {Icon ? ( + {showCustomIcon ? ( + setImageFailed(true)} + draggable={false} + /> + ) : Icon ? ( ) : ( diff --git a/apps/web/src/components/chat/ProviderModelPicker.tsx b/apps/web/src/components/chat/ProviderModelPicker.tsx index 4a2860ee46..30b1f3f753 100644 --- a/apps/web/src/components/chat/ProviderModelPicker.tsx +++ b/apps/web/src/components/chat/ProviderModelPicker.tsx @@ -129,6 +129,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { driverKind={activeEntry.driverKind} displayName={activeEntry.displayName} accentColor={activeEntry.accentColor} + iconUrl={activeEntry.iconUrl} showBadge={showInstanceBadge} className={showInstanceBadge ? "size-5" : "size-4"} iconClassName={cn("size-4", props.activeProviderIconClassName)} diff --git a/apps/web/src/components/chat/providerIconUtils.ts b/apps/web/src/components/chat/providerIconUtils.ts index 88b56295f3..77880818a0 100644 --- a/apps/web/src/components/chat/providerIconUtils.ts +++ b/apps/web/src/components/chat/providerIconUtils.ts @@ -1,5 +1,5 @@ import { ProviderDriverKind } from "@t3tools/contracts"; -import { ClaudeAI, CursorIcon, Icon, OpenAI, OpenCodeIcon } from "../Icons"; +import { ACPRegistryIcon, ClaudeAI, CursorIcon, Icon, OpenAI, OpenCodeIcon } from "../Icons"; import { PROVIDER_OPTIONS } from "../../session-logic"; export const PROVIDER_ICON_BY_PROVIDER: Partial> = { @@ -7,6 +7,7 @@ export const PROVIDER_ICON_BY_PROVIDER: Partial [ProviderDriverKind.make("claudeAgent")]: ClaudeAI, [ProviderDriverKind.make("opencode")]: OpenCodeIcon, [ProviderDriverKind.make("cursor")]: CursorIcon, + [ProviderDriverKind.make("acpRegistry")]: ACPRegistryIcon, }; function isAvailableProviderOption(option: (typeof PROVIDER_OPTIONS)[number]): option is { diff --git a/apps/web/src/components/settings/AddProviderInstanceDialog.tsx b/apps/web/src/components/settings/AddProviderInstanceDialog.tsx index b8bce8f0cd..9e1b7c08a2 100644 --- a/apps/web/src/components/settings/AddProviderInstanceDialog.tsx +++ b/apps/web/src/components/settings/AddProviderInstanceDialog.tsx @@ -1,19 +1,39 @@ "use client"; -import { CheckIcon } from "lucide-react"; +import { + ArrowRightIcon, + CheckIcon, + Loader2Icon, + PlusIcon, + RefreshCwIcon, + SearchIcon, + XIcon, +} from "lucide-react"; import { Radio as RadioPrimitive } from "@base-ui/react/radio"; import { useCallback, useEffect, useMemo, useState } from "react"; import { ProviderInstanceId, ProviderDriverKind, + type ResolvedRegistryAcpAgent, type ProviderInstanceConfig, + type ProviderInstanceEnvironmentVariable, } from "@t3tools/contracts"; import { useSettings, useUpdateSettings } from "../../hooks/useSettings"; +import { ensureLocalApi } from "../../localApi"; import { cn } from "../../lib/utils"; import { normalizeProviderAccentColor } from "../../providerInstances"; import { Button } from "../ui/button"; -import { ACPRegistryIcon, Gemini, GithubCopilotIcon, PiAgentIcon } from "../Icons"; +import { Gemini, GithubCopilotIcon, PiAgentIcon } from "../Icons"; +import { + AlertDialog, + AlertDialogClose, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogPopup, + AlertDialogTitle, +} from "../ui/alert-dialog"; import { Dialog, DialogDescription, @@ -25,6 +45,7 @@ import { import { Badge } from "../ui/badge"; import { Input } from "../ui/input"; import { RadioGroup } from "../ui/radio-group"; +import { ScrollArea } from "../ui/scroll-area"; import { toastManager } from "../ui/toast"; import { DRIVER_OPTION_BY_VALUE, DRIVER_OPTIONS, type DriverOption } from "./providerDriverMeta"; @@ -59,8 +80,11 @@ function deriveInstanceId(driver: ProviderDriverKind, label: string): string { } const INSTANCE_ID_PATTERN = /^[a-zA-Z][a-zA-Z0-9_-]*$/; +const ENVIRONMENT_VARIABLE_NAME_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]*$/; const DEFAULT_DRIVER_KIND = ProviderDriverKind.make("codex"); +const ACP_REGISTRY_DRIVER_KIND = ProviderDriverKind.make("acpRegistry"); const DEFAULT_DRIVER_OPTION = DRIVER_OPTIONS[0]!; +const MANUAL_ACP_REGISTRY_OPTION = "__manual__"; const COMING_SOON_DRIVER_OPTIONS: readonly DriverOption[] = [ { value: ProviderDriverKind.make("githubCopilot"), @@ -74,12 +98,6 @@ const COMING_SOON_DRIVER_OPTIONS: readonly DriverOption[] = [ icon: Gemini, fields: [], }, - { - value: ProviderDriverKind.make("acpRegistry"), - label: "ACP Registry", - icon: ACPRegistryIcon, - fields: [], - }, { value: ProviderDriverKind.make("piAgent"), label: "Pi Agent", @@ -88,6 +106,13 @@ const COMING_SOON_DRIVER_OPTIONS: readonly DriverOption[] = [ }, ]; +let environmentVariableDraftId = 0; +const nextEnvironmentVariableDraftId = () => `add-provider-env-${environmentVariableDraftId++}`; + +type EnvironmentVariableDraft = ProviderInstanceEnvironmentVariable & { + readonly id: string; +}; + /** * Validate an instance id against the same slug rules the server applies in * `ProviderInstanceId` (see `packages/contracts/src/providerInstance.ts`). @@ -103,6 +128,76 @@ function validateInstanceId(id: string, existing: ReadonlySet): string | return null; } +function stringifyArgs(args: ReadonlyArray | null | undefined): string { + return (args ?? []).join(" "); +} + +function acpRegistryAgentSearchText(entry: ResolvedRegistryAcpAgent): string { + return [ + entry.agent.name, + entry.agent.id, + entry.agent.description, + entry.agent.repository, + entry.agent.website, + entry.distributionType, + entry.launch?.command, + ...(entry.launch?.args ?? []), + ] + .filter((value): value is string => typeof value === "string" && value.length > 0) + .join(" ") + .toLowerCase(); +} + +function envRecordToVariables( + env: Record | null | undefined, +): ReadonlyArray { + return Object.entries(env ?? {}) + .filter(([name]) => ENVIRONMENT_VARIABLE_NAME_PATTERN.test(name)) + .map(([name, value]) => ({ + id: nextEnvironmentVariableDraftId(), + name, + value, + sensitive: false, + })); +} + +function emptyEnvironmentVariable(): EnvironmentVariableDraft { + return { + id: nextEnvironmentVariableDraftId(), + name: "", + value: "", + sensitive: true, + } as EnvironmentVariableDraft; +} + +function acpDistributionLabel(entry: ResolvedRegistryAcpAgent): string { + switch (entry.distributionType) { + case "npx": + return "npx"; + case "uvx": + return "uvx"; + case "binary": + return "Installed"; + case "binaryUnsupported": + return "Binary"; + case "manual": + return "Manual"; + } +} + +type AcpRegistryState = + | { readonly status: "idle" | "loading"; readonly agents: readonly ResolvedRegistryAcpAgent[] } + | { + readonly status: "loaded"; + readonly registryVersion: string; + readonly agents: readonly ResolvedRegistryAcpAgent[]; + } + | { + readonly status: "error"; + readonly agents: readonly ResolvedRegistryAcpAgent[]; + readonly error: string; + }; + interface AddProviderInstanceDialogProps { open: boolean; onOpenChange: (open: boolean) => void; @@ -115,13 +210,30 @@ export function AddProviderInstanceDialog({ open, onOpenChange }: AddProviderIns const [wizardStep, setWizardStep] = useState(0); const [driver, setDriver] = useState(DEFAULT_DRIVER_KIND); const [label, setLabel] = useState(""); + const [labelDirty, setLabelDirty] = useState(false); const [accentColor, setAccentColor] = useState(""); const [instanceId, setInstanceId] = useState(""); const [instanceIdDirty, setInstanceIdDirty] = useState(false); + const [environmentVariables, setEnvironmentVariables] = useState< + ReadonlyArray + >([]); // Driver-specific field values keyed by `${driver}:${fieldKey}` so toggling // between drivers during the same dialog session doesn't lose in-progress // input. Only the active driver's values are persisted on save. const [fieldValues, setFieldValues] = useState>({}); + const [acpRegistryState, setAcpRegistryState] = useState({ + status: "idle", + agents: [], + }); + const [acpRegistrySearch, setAcpRegistrySearch] = useState(""); + const [selectedAcpRegistryAgentId, setSelectedAcpRegistryAgentId] = useState( + MANUAL_ACP_REGISTRY_OPTION, + ); + const [installingAcpAgentId, setInstallingAcpAgentId] = useState(null); + const [installConfirmAgent, setInstallConfirmAgent] = useState( + null, + ); + const [installPath, setInstallPath] = useState(""); // Errors are suppressed until the user has tried to submit once. After that // they update live so fixing the problem clears the message in place. const [hasAttemptedSubmit, setHasAttemptedSubmit] = useState(false); @@ -130,6 +242,7 @@ export function AddProviderInstanceDialog({ open, onOpenChange }: AddProviderIns () => new Set(Object.keys(settings.providerInstances ?? {})), [settings.providerInstances], ); + const isAcpRegistryDriver = driver === ACP_REGISTRY_DRIVER_KIND; // Reset the form every time the dialog opens so each creation starts // from a clean slate. @@ -137,11 +250,18 @@ export function AddProviderInstanceDialog({ open, onOpenChange }: AddProviderIns if (!open) return; setDriver(DEFAULT_DRIVER_KIND); setLabel(""); + setLabelDirty(false); setAccentColor(""); setInstanceId(""); setWizardStep(0); setInstanceIdDirty(false); + setEnvironmentVariables([]); setFieldValues({}); + setAcpRegistrySearch(""); + setSelectedAcpRegistryAgentId(MANUAL_ACP_REGISTRY_OPTION); + setInstallingAcpAgentId(null); + setInstallConfirmAgent(null); + setInstallPath(""); setHasAttemptedSubmit(false); }, [open]); @@ -152,12 +272,74 @@ export function AddProviderInstanceDialog({ open, onOpenChange }: AddProviderIns setInstanceId(deriveInstanceId(driver, label)); }, [driver, label, instanceIdDirty]); + useEffect(() => { + setWizardStep((step) => Math.min(step, isAcpRegistryDriver ? 3 : 2)); + }, [isAcpRegistryDriver]); + const driverOption = DRIVER_OPTION_BY_VALUE[driver] ?? DEFAULT_DRIVER_OPTION; const instanceIdError = validateInstanceId(instanceId, existingIds); const showInstanceIdError = hasAttemptedSubmit && instanceIdError !== null; const previewLabel = label.trim() || `${driverOption.label} Workspace`; - const wizardSteps = ["Driver", "Identity", "Config"] as const; - const wizardStepSummaries = [driverOption.label, previewLabel, null] as const; + const wizardSteps = isAcpRegistryDriver + ? (["Driver", "Registry", "Identity", "Config"] as const) + : (["Driver", "Identity", "Config"] as const); + const registryStepIndex = isAcpRegistryDriver ? 1 : -1; + const identityStepIndex = isAcpRegistryDriver ? 2 : 1; + const configStepIndex = wizardSteps.length - 1; + const selectedAcpRegistryAgent = useMemo( + () => + acpRegistryState.agents.find((entry) => entry.agent.id === selectedAcpRegistryAgentId) ?? + null, + [acpRegistryState.agents, selectedAcpRegistryAgentId], + ); + const selectedAcpRegistryAgentNeedsInstall = + selectedAcpRegistryAgent?.distributionType === "binaryUnsupported" && + Boolean(selectedAcpRegistryAgent.binaryInstall); + const installingConfirmAgent = + installConfirmAgent !== null && installingAcpAgentId === installConfirmAgent.agent.id; + const wizardStepSummaries = [ + driverOption.label, + ...(isAcpRegistryDriver + ? [ + selectedAcpRegistryAgent + ? selectedAcpRegistryAgent.agent.name + : selectedAcpRegistryAgentId === MANUAL_ACP_REGISTRY_OPTION + ? "Manual" + : null, + ] + : []), + previewLabel, + null, + ] as const; + const filteredAcpRegistryAgents = useMemo(() => { + const query = acpRegistrySearch.trim().toLowerCase(); + const agents = acpRegistryState.agents; + if (!query) return agents; + return agents.filter((entry) => acpRegistryAgentSearchText(entry).includes(query)); + }, [acpRegistrySearch, acpRegistryState.agents]); + + const loadAcpRegistry = useCallback(async () => { + setAcpRegistryState((current) => ({ status: "loading", agents: current.agents })); + try { + const result = await ensureLocalApi().server.listAcpRegistry(); + setAcpRegistryState({ + status: "loaded", + registryVersion: result.registryVersion, + agents: result.agents, + }); + } catch (error) { + setAcpRegistryState((current) => ({ + status: "error", + agents: current.agents, + error: error instanceof Error ? error.message : "Registry request failed.", + })); + } + }, []); + + useEffect(() => { + if (!open || !isAcpRegistryDriver || acpRegistryState.status !== "idle") return; + void loadAcpRegistry(); + }, [acpRegistryState.status, isAcpRegistryDriver, loadAcpRegistry, open]); const getFieldValue = useCallback( (fieldKey: string) => fieldValues[`${driver}:${fieldKey}`] ?? "", @@ -174,25 +356,157 @@ export function AddProviderInstanceDialog({ open, onOpenChange }: AddProviderIns [driver], ); + const applyAcpRegistryAgent = useCallback( + (entry: ResolvedRegistryAcpAgent) => { + const launch = entry.launch; + if (!launch) return; + setSelectedAcpRegistryAgentId(entry.agent.id); + setFieldValues((existing) => ({ + ...existing, + [`${ACP_REGISTRY_DRIVER_KIND}:command`]: launch.command, + [`${ACP_REGISTRY_DRIVER_KIND}:args`]: stringifyArgs(launch.args), + })); + setEnvironmentVariables(envRecordToVariables(launch.env)); + if (!labelDirty) { + setLabel(entry.agent.name); + } + if (!instanceIdDirty) { + setInstanceId(deriveInstanceId(ACP_REGISTRY_DRIVER_KIND, entry.agent.name)); + } + }, + [instanceIdDirty, labelDirty], + ); + + const selectInstallableAcpRegistryAgent = useCallback( + (entry: ResolvedRegistryAcpAgent) => { + setSelectedAcpRegistryAgentId(entry.agent.id); + setInstallPath(entry.binaryInstall?.defaultInstallPath ?? ""); + setEnvironmentVariables([]); + if (!labelDirty) { + setLabel(entry.agent.name); + } + if (!instanceIdDirty) { + setInstanceId(deriveInstanceId(ACP_REGISTRY_DRIVER_KIND, entry.agent.name)); + } + }, + [instanceIdDirty, labelDirty], + ); + + const selectManualAcpRegistryAgent = useCallback(() => { + setSelectedAcpRegistryAgentId(MANUAL_ACP_REGISTRY_OPTION); + setEnvironmentVariables([]); + }, []); + + const handleInstallAcpRegistryAgent = useCallback(async () => { + const entry = installConfirmAgent; + if (!entry) return; + setInstallingAcpAgentId(entry.agent.id); + try { + const trimmedInstallPath = installPath.trim(); + const result = await ensureLocalApi().server.installAcpRegistryBinary({ + agentId: entry.agent.id, + ...(trimmedInstallPath ? { installPath: trimmedInstallPath } : {}), + }); + if (!result.ok || !result.agent) { + throw new Error(result.error ?? "Install failed."); + } + setAcpRegistryState((current) => ({ + ...current, + agents: current.agents.map((candidate) => + candidate.agent.id === result.agent?.agent.id ? result.agent : candidate, + ), + })); + applyAcpRegistryAgent(result.agent); + setInstallConfirmAgent(null); + setWizardStep(identityStepIndex); + toastManager.add({ + type: "success", + title: "ACP agent installed", + description: `${entry.agent.name} is ready to use.`, + }); + } catch (error) { + toastManager.add({ + type: "error", + title: "Could not install ACP agent", + description: error instanceof Error ? error.message : "Install failed.", + }); + } finally { + setInstallingAcpAgentId(null); + } + }, [applyAcpRegistryAgent, identityStepIndex, installConfirmAgent, installPath]); + + const handleAdvanceWizard = useCallback(() => { + if (wizardStep === registryStepIndex && selectedAcpRegistryAgentNeedsInstall) { + setInstallPath(selectedAcpRegistryAgent?.binaryInstall?.defaultInstallPath ?? ""); + setInstallConfirmAgent(selectedAcpRegistryAgent); + return; + } + setWizardStep((step) => Math.min(configStepIndex, step + 1)); + }, [ + configStepIndex, + registryStepIndex, + selectedAcpRegistryAgent, + selectedAcpRegistryAgentNeedsInstall, + wizardStep, + ]); + + const updateEnvironmentVariable = useCallback( + ( + index: number, + patch: Partial>, + ) => { + setEnvironmentVariables((existing) => + existing.map((variable, variableIndex) => + variableIndex === index ? { ...variable, ...patch } : variable, + ), + ); + }, + [], + ); + + const removeEnvironmentVariable = useCallback((index: number) => { + setEnvironmentVariables((existing) => + existing.filter((_variable, variableIndex) => variableIndex !== index), + ); + }, []); + const handleSave = useCallback(() => { setHasAttemptedSubmit(true); if (instanceIdError !== null) return; // Build the config blob from non-empty driver-specific field values. // Empty strings are dropped so defaults remain in effect on the server. - const config: Record = {}; + const config: Record = {}; for (const field of driverOption.fields) { const value = (fieldValues[`${driver}:${field.key}`] ?? "").trim(); - if (value.length > 0) config[field.key] = value; + if (value.length > 0) { + config[field.key] = field.key === "args" ? value.split(/\s+/).filter(Boolean) : value; + } + } + if (driver === ACP_REGISTRY_DRIVER_KIND && selectedAcpRegistryAgent) { + config.registryAgentId = selectedAcpRegistryAgent.agent.id; + config.importedVersion = selectedAcpRegistryAgent.agent.version; + config.distributionType = selectedAcpRegistryAgent.distributionType; } const hasConfig = Object.keys(config).length > 0; const normalizedAccentColor = normalizeProviderAccentColor(accentColor); + const cleanedEnvironment = environmentVariables + .map((variable) => ({ + value: variable.value, + sensitive: variable.sensitive, + name: variable.name.trim(), + })) + .filter((variable) => ENVIRONMENT_VARIABLE_NAME_PATTERN.test(variable.name)); const nextInstance: ProviderInstanceConfig = { driver, enabled: true, ...(label.trim().length > 0 ? { displayName: label.trim() } : {}), ...(normalizedAccentColor ? { accentColor: normalizedAccentColor } : {}), + ...(cleanedEnvironment.length > 0 ? { environment: cleanedEnvironment } : {}), + ...(selectedAcpRegistryAgent?.agent.icon + ? { iconUrl: selectedAcpRegistryAgent.agent.icon } + : {}), ...(hasConfig ? { config } : {}), }; // `ProviderInstanceId.make` revalidates the slug; we've already checked @@ -223,271 +537,559 @@ export function AddProviderInstanceDialog({ open, onOpenChange }: AddProviderIns driver, driverOption, fieldValues, + environmentVariables, instanceId, instanceIdError, label, accentColor, onOpenChange, + selectedAcpRegistryAgent, settings.providerInstances, updateSettings, ]); return ( - - -
- - Add provider instance - - Configure an additional provider instance — for example, a second Codex install - pointed at a different workspace. - -
- {wizardSteps.map((step, index) => ( - - ))} -
-
- -
-
- - Driver - - setDriver(ProviderDriverKind.make(value))} - aria-labelledby="add-instance-driver-label" - className="grid grid-cols-2 gap-2.5" + <> + + +
+ + Add provider instance + + Configure an additional provider instance — for example, a second Codex install + pointed at a different workspace. + +
- {DRIVER_OPTIONS.map((option) => { - const IconComponent = option.icon; - const isSelected = option.value === driver; - return ( - ( +
+ {index < wizardStep ? : null} + + + Step {index + 1} + + + {step} + {index < wizardStep && wizardStepSummaries[index] + ? `: ${wizardStepSummaries[index]}` + : ""} + + + ))} +
+ - - -
+ { + if (!nextOpen && !installingConfirmAgent) setInstallConfirmAgent(null); + }} + > + + + Install {installConfirmAgent?.agent.name}? + + T3 Code will download and extract this agent binary from the archive URL published in + the ACP registry. The registry does not currently provide checksums or signatures, so + only install agents from publishers you trust. + + {installConfirmAgent?.binaryInstall ? ( +
+
+ Download URL + +
+ {installConfirmAgent.binaryInstall.archiveUrl} +
+
+
+
+ +
+
) : null} -
- - - - {wizardStep < wizardSteps.length - 1 ? ( - - ) : ( - - )} - -
- -
+ + + + ); } diff --git a/apps/web/src/components/settings/ProviderInstanceCard.tsx b/apps/web/src/components/settings/ProviderInstanceCard.tsx index 21889412c3..6808e85da8 100644 --- a/apps/web/src/components/settings/ProviderInstanceCard.tsx +++ b/apps/web/src/components/settings/ProviderInstanceCard.tsx @@ -97,6 +97,9 @@ function redactedEmailPlaceholder(email: string): string { function readConfigString(config: unknown, key: string): string { if (config === null || typeof config !== "object") return ""; const value = (config as Record)[key]; + if (Array.isArray(value) && value.every((entry) => typeof entry === "string")) { + return value.join(" "); + } return typeof value === "string" ? value : ""; } @@ -586,7 +589,14 @@ export function ProviderInstanceCard({ }; const updateConfigField = (key: string, value: string) => { - const nextConfig = nextConfigBlobWithString(instance.config, key, value); + const nextConfig = + key === "args" + ? nextConfigBlobWithValue( + instance.config, + key, + value.trim().length > 0 ? value.trim().split(/\s+/).filter(Boolean) : [], + ) + : nextConfigBlobWithString(instance.config, key, value); const { config: _omit, ...rest } = instance; onUpdate( nextConfig !== undefined @@ -622,6 +632,7 @@ export function ProviderInstanceCard({ driverKind={driverKind} displayName={displayName} accentColor={accentColor} + iconUrl={instance.iconUrl ?? liveProvider?.iconUrl} showBadge={Boolean(accentColor)} statusDotClassName={statusStyle.dot} className="size-5" diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index a58f0ebc39..d330009ab5 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -38,6 +38,7 @@ import { } from "../../modelSelection"; import { deriveProviderInstanceEntries, + isModelPickerProviderInstanceEntry, sortProviderInstanceEntries, } from "../../providerInstances"; import { ensureLocalApi, readLocalApi } from "../../localApi"; @@ -557,7 +558,7 @@ export function GeneralSettingsPanel() { const textGenModel = textGenerationModelSelection.model; const textGenModelOptions = textGenerationModelSelection.options; const gitModelInstanceEntries = sortProviderInstanceEntries( - deriveProviderInstanceEntries(serverProviders), + deriveProviderInstanceEntries(serverProviders).filter(isModelPickerProviderInstanceEntry), ); const textGenInstanceEntry = gitModelInstanceEntries.find( (entry) => entry.instanceId === textGenInstanceId, diff --git a/apps/web/src/components/settings/providerDriverMeta.ts b/apps/web/src/components/settings/providerDriverMeta.ts index 38f8039647..97c3362ff8 100644 --- a/apps/web/src/components/settings/providerDriverMeta.ts +++ b/apps/web/src/components/settings/providerDriverMeta.ts @@ -1,5 +1,5 @@ import { ProviderDriverKind } from "@t3tools/contracts"; -import { ClaudeAI, CursorIcon, type Icon, OpenAI, OpenCodeIcon } from "../Icons"; +import { ACPRegistryIcon, ClaudeAI, CursorIcon, type Icon, OpenAI, OpenCodeIcon } from "../Icons"; /** * A single editable field exposed on a provider instance. `key` must match @@ -135,6 +135,25 @@ export const DRIVER_OPTIONS: readonly DriverOption[] = [ }, ], }, + { + value: ProviderDriverKind.make("acpRegistry"), + label: "ACP Registry", + icon: ACPRegistryIcon, + fields: [ + { + key: "command", + label: "Command", + placeholder: "npx", + description: "Executable used to launch the ACP agent.", + }, + { + key: "args", + label: "Arguments", + placeholder: "-y @example/acp-agent", + description: "Space-separated launch arguments passed to the command.", + }, + ], + }, ]; export const DRIVER_OPTION_BY_VALUE: Partial> = diff --git a/apps/web/src/localApi.ts b/apps/web/src/localApi.ts index 4401b5b778..417592e1e1 100644 --- a/apps/web/src/localApi.ts +++ b/apps/web/src/localApi.ts @@ -115,6 +115,8 @@ export function createLocalApi(rpcClient: WsRpcClient): LocalApi { upsertKeybinding: rpcClient.server.upsertKeybinding, getSettings: rpcClient.server.getSettings, updateSettings: rpcClient.server.updateSettings, + listAcpRegistry: rpcClient.server.listAcpRegistry, + installAcpRegistryBinary: rpcClient.server.installAcpRegistryBinary, }, }; } diff --git a/apps/web/src/modelSelection.ts b/apps/web/src/modelSelection.ts index 8ba0c8fa5d..5fb79a8db9 100644 --- a/apps/web/src/modelSelection.ts +++ b/apps/web/src/modelSelection.ts @@ -20,7 +20,11 @@ import { resolveSelectableProvider, } from "./providerModels"; import { ModelEsque } from "./components/chat/providerIconUtils"; -import { type ProviderInstanceEntry, deriveProviderInstanceEntries } from "./providerInstances"; +import { + type ProviderInstanceEntry, + deriveProviderInstanceEntries, + isModelPickerProviderInstanceEntry, +} from "./providerInstances"; import { sortModelsForProviderInstance } from "./modelOrdering"; const MAX_CUSTOM_MODEL_COUNT = 32; @@ -238,9 +242,9 @@ export function resolveAppModelSelectionForInstance( providers: ReadonlyArray, selectedModel: string | null | undefined, ): string | null { - const entry = deriveProviderInstanceEntries(providers).find( - (candidate) => candidate.instanceId === instanceId, - ); + const entry = deriveProviderInstanceEntries(providers) + .filter(isModelPickerProviderInstanceEntry) + .find((candidate) => candidate.instanceId === instanceId); if (!entry) return null; const options = getAppModelOptionsForInstance(settings, entry); return ( @@ -263,7 +267,9 @@ export function getCustomModelOptionsByInstance( _selectedModel?: string | null, ): ReadonlyMap> { const out = new Map>(); - for (const entry of deriveProviderInstanceEntries(providers)) { + for (const entry of deriveProviderInstanceEntries(providers).filter( + isModelPickerProviderInstanceEntry, + )) { out.set(entry.instanceId, getAppModelOptionsForInstance(settings, entry)); } return out; @@ -277,7 +283,9 @@ export function resolveAppModelSelectionState( instanceId: DEFAULT_TEXT_GENERATION_INSTANCE_ID, model: DEFAULT_GIT_TEXT_GENERATION_MODEL, }; - const entries = deriveProviderInstanceEntries(providers); + const entries = deriveProviderInstanceEntries(providers).filter( + isModelPickerProviderInstanceEntry, + ); const selectedEntry = entries.find( (entry) => entry.instanceId === selection.instanceId && entry.enabled && entry.isAvailable, ); diff --git a/apps/web/src/providerInstances.test.ts b/apps/web/src/providerInstances.test.ts index 7104f365eb..9c2c3225fc 100644 --- a/apps/web/src/providerInstances.test.ts +++ b/apps/web/src/providerInstances.test.ts @@ -2,6 +2,7 @@ import { ProviderDriverKind, ProviderInstanceId, type ServerProvider } from "@t3 import { describe, expect, it } from "vitest"; import { deriveProviderInstanceEntries, + isModelPickerProviderInstanceEntry, resolveSelectableProviderInstance, resolveProviderDriverKindForInstanceSelection, } from "./providerInstances"; @@ -44,6 +45,25 @@ describe("deriveProviderInstanceEntries", () => { }); }); +describe("isModelPickerProviderInstanceEntry", () => { + it("hides the default ACP Registry catalog while keeping imported ACP agents", () => { + const entries = deriveProviderInstanceEntries([ + provider({ + provider: ProviderDriverKind.make("acpRegistry"), + instanceId: "acpRegistry", + displayName: "ACP Registry", + }), + provider({ + provider: ProviderDriverKind.make("acpRegistry"), + instanceId: "acpRegistry_auggie_cli", + displayName: "Auggie CLI", + }), + ]); + + expect(entries.map(isModelPickerProviderInstanceEntry)).toEqual([false, true]); + }); +}); + describe("resolveSelectableProviderInstance", () => { it("returns the requested instance when it is enabled and available", () => { const requested = ProviderInstanceId.make("claude_work"); diff --git a/apps/web/src/providerInstances.ts b/apps/web/src/providerInstances.ts index 6ff0bd1ab9..154b0e4aa3 100644 --- a/apps/web/src/providerInstances.ts +++ b/apps/web/src/providerInstances.ts @@ -24,6 +24,8 @@ import { import { formatProviderDriverKindLabel } from "./providerModels"; +const ACP_REGISTRY_DRIVER_KIND = "acpRegistry"; + /** * UI-facing projection of one configured provider instance. Carries the * snapshot verbatim for callers that need server-side fields we don't @@ -35,6 +37,7 @@ export interface ProviderInstanceEntry { readonly driverKind: ProviderDriverKind; readonly displayName: string; readonly accentColor?: string | undefined; + readonly iconUrl?: string | undefined; readonly continuationGroupKey?: string | undefined; readonly enabled: boolean; readonly installed: boolean; @@ -140,6 +143,7 @@ export function deriveProviderInstanceEntries( driverKind, displayName, accentColor: normalizeProviderAccentColor(snapshot.accentColor), + ...(snapshot.iconUrl ? { iconUrl: snapshot.iconUrl } : {}), continuationGroupKey: snapshot.continuation?.groupKey, enabled: snapshot.enabled, installed: snapshot.installed, @@ -184,6 +188,15 @@ export function sortProviderInstanceEntries( return sorted; } +/** + * The ACP Registry default slot is a catalog/import surface, not an agent + * users should chat with. Registry-created provider instances share the same + * driver kind, but have their own non-default ids and remain selectable. + */ +export function isModelPickerProviderInstanceEntry(entry: ProviderInstanceEntry): boolean { + return !(entry.driverKind === ACP_REGISTRY_DRIVER_KIND && entry.isDefault); +} + /** * Look up a single instance entry by exact `instanceId`. Missing snapshots * are not inferred from driver kind in UI routing code. diff --git a/apps/web/src/rpc/wsRpcClient.ts b/apps/web/src/rpc/wsRpcClient.ts index f1183c1e9c..43f9824d17 100644 --- a/apps/web/src/rpc/wsRpcClient.ts +++ b/apps/web/src/rpc/wsRpcClient.ts @@ -114,6 +114,10 @@ export interface WsRpcClient { readonly updateSettings: ( patch: ServerSettingsPatch, ) => ReturnType>; + readonly listAcpRegistry: RpcUnaryNoArgMethod; + readonly installAcpRegistryBinary: RpcUnaryMethod< + typeof WS_METHODS.serverInstallAcpRegistryBinary + >; readonly subscribeConfig: RpcStreamMethod; readonly subscribeLifecycle: RpcStreamMethod; readonly subscribeAuthAccess: RpcStreamMethod; @@ -219,6 +223,10 @@ export function createWsRpcClient(transport: WsTransport): WsRpcClient { getSettings: () => transport.request((client) => client[WS_METHODS.serverGetSettings]({})), updateSettings: (patch) => transport.request((client) => client[WS_METHODS.serverUpdateSettings]({ patch })), + listAcpRegistry: () => + transport.request((client) => client[WS_METHODS.serverListAcpRegistry]({})), + installAcpRegistryBinary: (input) => + transport.request((client) => client[WS_METHODS.serverInstallAcpRegistryBinary](input)), subscribeConfig: (listener, options) => transport.subscribe( (client) => client[WS_METHODS.subscribeServerConfig]({}), diff --git a/packages/contracts/src/acp.ts b/packages/contracts/src/acp.ts new file mode 100644 index 0000000000..cd26f4696c --- /dev/null +++ b/packages/contracts/src/acp.ts @@ -0,0 +1,104 @@ +import { Effect, Schema } from "effect"; +import { IsoDateTime, TrimmedNonEmptyString } from "./baseSchemas.ts"; + +export const AcpDistributionType = Schema.Literals([ + "manual", + "npx", + "uvx", + "binary", + "binaryUnsupported", +]); +export type AcpDistributionType = typeof AcpDistributionType.Type; + +export const AcpLaunchSpec = Schema.Struct({ + command: TrimmedNonEmptyString, + args: Schema.Array(TrimmedNonEmptyString).pipe(Schema.withDecodingDefault(Effect.succeed([]))), + env: Schema.Record(Schema.String, Schema.String).pipe( + Schema.withDecodingDefault(Effect.succeed({})), + ), +}); +export type AcpLaunchSpec = typeof AcpLaunchSpec.Type; + +export const AcpRegistryAgent = Schema.Struct({ + id: TrimmedNonEmptyString, + name: TrimmedNonEmptyString, + version: TrimmedNonEmptyString, + description: TrimmedNonEmptyString, + repository: Schema.optional(TrimmedNonEmptyString), + website: Schema.optional(TrimmedNonEmptyString), + authors: Schema.optional(Schema.Array(TrimmedNonEmptyString)), + license: Schema.optional(TrimmedNonEmptyString), + icon: Schema.optional(TrimmedNonEmptyString), + distribution: Schema.Struct({ + npx: Schema.optional( + Schema.Struct({ + package: TrimmedNonEmptyString, + args: Schema.optional(Schema.Array(TrimmedNonEmptyString)), + env: Schema.optional(Schema.Record(Schema.String, Schema.String)), + }), + ), + uvx: Schema.optional( + Schema.Struct({ + package: TrimmedNonEmptyString, + args: Schema.optional(Schema.Array(TrimmedNonEmptyString)), + env: Schema.optional(Schema.Record(Schema.String, Schema.String)), + }), + ), + binary: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)), + }), +}); +export type AcpRegistryAgent = typeof AcpRegistryAgent.Type; + +export const AcpRegistryIndex = Schema.Struct({ + version: TrimmedNonEmptyString, + agents: Schema.Array(AcpRegistryAgent), +}); +export type AcpRegistryIndex = typeof AcpRegistryIndex.Type; + +export const ResolvedRegistryAcpAgent = Schema.Struct({ + agent: AcpRegistryAgent, + supported: Schema.Boolean, + distributionType: AcpDistributionType, + launch: Schema.NullOr(AcpLaunchSpec), + binaryInstall: Schema.optional( + Schema.Struct({ + archiveUrl: TrimmedNonEmptyString, + defaultInstallPath: TrimmedNonEmptyString, + platformKey: TrimmedNonEmptyString, + command: TrimmedNonEmptyString, + }), + ), +}); +export type ResolvedRegistryAcpAgent = typeof ResolvedRegistryAcpAgent.Type; + +export const AcpRegistryListResult = Schema.Struct({ + registryVersion: TrimmedNonEmptyString, + agents: Schema.Array(ResolvedRegistryAcpAgent), +}); +export type AcpRegistryListResult = typeof AcpRegistryListResult.Type; + +export const AcpRegistryInstallBinaryInput = Schema.Struct({ + agentId: TrimmedNonEmptyString, + installPath: Schema.optional(TrimmedNonEmptyString), +}); +export type AcpRegistryInstallBinaryInput = typeof AcpRegistryInstallBinaryInput.Type; + +export const AcpRegistryInstallBinaryResult = Schema.Struct({ + ok: Schema.Boolean, + agent: Schema.optional(ResolvedRegistryAcpAgent), + error: Schema.optional(TrimmedNonEmptyString), +}); +export type AcpRegistryInstallBinaryResult = typeof AcpRegistryInstallBinaryResult.Type; + +export const ServerAcpAgentStatus = Schema.Struct({ + agentServerId: TrimmedNonEmptyString, + enabled: Schema.Boolean, + installed: Schema.Boolean, + status: Schema.Literals(["ready", "warning", "error", "disabled"]), + authStatus: Schema.Literals(["authenticated", "unauthenticated", "unknown"]), + checkedAt: IsoDateTime, + displayName: TrimmedNonEmptyString, + message: Schema.optional(TrimmedNonEmptyString), + version: Schema.NullOr(TrimmedNonEmptyString), +}); +export type ServerAcpAgentStatus = typeof ServerAcpAgentStatus.Type; diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index ad90571740..276a395b14 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -6,6 +6,7 @@ export * from "./terminal.ts"; export * from "./provider.ts"; export * from "./providerInstance.ts"; export * from "./providerRuntime.ts"; +export * from "./acp.ts"; export * from "./model.ts"; export * from "./keybindings.ts"; export * from "./server.ts"; diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts index a63c6de962..ea05716ca2 100644 --- a/packages/contracts/src/ipc.ts +++ b/packages/contracts/src/ipc.ts @@ -18,6 +18,11 @@ import type { GitStatusResult, GitCreateBranchResult, } from "./git.ts"; +import type { + AcpRegistryInstallBinaryInput, + AcpRegistryInstallBinaryResult, + AcpRegistryListResult, +} from "./acp.ts"; import type { FilesystemBrowseInput, FilesystemBrowseResult } from "./filesystem.ts"; import type { ProjectSearchEntriesInput, @@ -227,6 +232,10 @@ export interface LocalApi { upsertKeybinding: (input: ServerUpsertKeybindingInput) => Promise; getSettings: () => Promise; updateSettings: (patch: ServerSettingsPatch) => Promise; + listAcpRegistry: () => Promise; + installAcpRegistryBinary: ( + input: AcpRegistryInstallBinaryInput, + ) => Promise; }; } diff --git a/packages/contracts/src/model.ts b/packages/contracts/src/model.ts index cd8ab45a4b..5b521ed58f 100644 --- a/packages/contracts/src/model.ts +++ b/packages/contracts/src/model.ts @@ -129,6 +129,7 @@ const CODEX_DRIVER_KIND = ProviderDriverKind.make("codex"); const CLAUDE_DRIVER_KIND = ProviderDriverKind.make("claudeAgent"); const CURSOR_DRIVER_KIND = ProviderDriverKind.make("cursor"); const OPENCODE_DRIVER_KIND = ProviderDriverKind.make("opencode"); +const ACP_REGISTRY_DRIVER_KIND = ProviderDriverKind.make("acpRegistry"); export const DEFAULT_MODEL = "gpt-5.4"; export const DEFAULT_GIT_TEXT_GENERATION_MODEL = "gpt-5.4-mini"; @@ -138,6 +139,7 @@ export const DEFAULT_MODEL_BY_PROVIDER: Partial> [CLAUDE_DRIVER_KIND]: "Claude", [CURSOR_DRIVER_KIND]: "Cursor", [OPENCODE_DRIVER_KIND]: "OpenCode", + [ACP_REGISTRY_DRIVER_KIND]: "ACP Registry", }; diff --git a/packages/contracts/src/providerInstance.ts b/packages/contracts/src/providerInstance.ts index d5bb25f772..f62cafa52e 100644 --- a/packages/contracts/src/providerInstance.ts +++ b/packages/contracts/src/providerInstance.ts @@ -124,6 +124,7 @@ export const ProviderInstanceConfig = Schema.Struct({ driver: ProviderDriverKind, displayName: Schema.optional(TrimmedNonEmptyString), accentColor: Schema.optional(TrimmedNonEmptyString), + iconUrl: Schema.optional(TrimmedNonEmptyString), environment: Schema.optionalKey(ProviderInstanceEnvironment), enabled: Schema.optionalKey(Schema.Boolean), config: Schema.optionalKey(Schema.Unknown), diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index ca68d5cfe4..ad634b2306 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -4,6 +4,11 @@ import * as RpcGroup from "effect/unstable/rpc/RpcGroup"; import { OpenError, OpenInEditorInput } from "./editor.ts"; import { AuthAccessStreamEvent } from "./auth.ts"; +import { + AcpRegistryInstallBinaryInput, + AcpRegistryInstallBinaryResult, + AcpRegistryListResult, +} from "./acp.ts"; import { FilesystemBrowseInput, FilesystemBrowseResult, @@ -119,6 +124,8 @@ export const WS_METHODS = { serverUpsertKeybinding: "server.upsertKeybinding", serverGetSettings: "server.getSettings", serverUpdateSettings: "server.updateSettings", + serverListAcpRegistry: "server.listAcpRegistry", + serverInstallAcpRegistryBinary: "server.installAcpRegistryBinary", // Streaming subscriptions subscribeGitStatus: "subscribeGitStatus", @@ -165,6 +172,19 @@ export const WsServerUpdateSettingsRpc = Rpc.make(WS_METHODS.serverUpdateSetting error: ServerSettingsError, }); +export const WsServerListAcpRegistryRpc = Rpc.make(WS_METHODS.serverListAcpRegistry, { + payload: Schema.Struct({}), + success: AcpRegistryListResult, +}); + +export const WsServerInstallAcpRegistryBinaryRpc = Rpc.make( + WS_METHODS.serverInstallAcpRegistryBinary, + { + payload: AcpRegistryInstallBinaryInput, + success: AcpRegistryInstallBinaryResult, + }, +); + export const WsProjectsSearchEntriesRpc = Rpc.make(WS_METHODS.projectsSearchEntries, { payload: ProjectSearchEntriesInput, success: ProjectSearchEntriesResult, @@ -370,6 +390,8 @@ export const WsRpcGroup = RpcGroup.make( WsServerUpsertKeybindingRpc, WsServerGetSettingsRpc, WsServerUpdateSettingsRpc, + WsServerListAcpRegistryRpc, + WsServerInstallAcpRegistryBinaryRpc, WsProjectsSearchEntriesRpc, WsProjectsWriteFileRpc, WsShellOpenInEditorRpc, diff --git a/packages/contracts/src/server.ts b/packages/contracts/src/server.ts index 1381faf5df..774bd70c2a 100644 --- a/packages/contracts/src/server.ts +++ b/packages/contracts/src/server.ts @@ -118,6 +118,7 @@ export const ServerProvider = Schema.Struct({ driver: ProviderDriverKind, displayName: Schema.optional(TrimmedNonEmptyString), accentColor: Schema.optional(TrimmedNonEmptyString), + iconUrl: Schema.optional(TrimmedNonEmptyString), badgeLabel: Schema.optional(TrimmedNonEmptyString), continuation: Schema.optional(ServerProviderContinuation), showInteractionModeToggle: Schema.optional(Schema.Boolean), diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 4a10c4cc6c..42b1d995d9 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -130,6 +130,26 @@ export const OpenCodeSettings = Schema.Struct({ }); export type OpenCodeSettings = typeof OpenCodeSettings.Type; +export const AcpRegistrySettings = Schema.Struct({ + enabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), + registryUrl: TrimmedString.pipe( + Schema.withDecodingDefault( + Effect.succeed("https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json"), + ), + ), + command: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))), + args: Schema.Array(Schema.String).pipe(Schema.withDecodingDefault(Effect.succeed([]))), + env: Schema.Record(Schema.String, Schema.String).pipe( + Schema.withDecodingDefault(Effect.succeed({})), + ), + iconUrl: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))), + registryAgentId: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))), + importedVersion: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))), + distributionType: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))), + customModels: Schema.Array(Schema.String).pipe(Schema.withDecodingDefault(Effect.succeed([]))), +}); +export type AcpRegistrySettings = typeof AcpRegistrySettings.Type; + export const ObservabilitySettings = Schema.Struct({ otlpTracesUrl: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))), otlpMetricsUrl: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))), @@ -162,6 +182,7 @@ export const ServerSettings = Schema.Struct({ claudeAgent: ClaudeSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))), cursor: CursorSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))), opencode: OpenCodeSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))), + acpRegistry: AcpRegistrySettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))), }).pipe(Schema.withDecodingDefault(Effect.succeed({}))), // New driver-agnostic instance map. Keyed by `ProviderInstanceId`; values // are `ProviderInstanceConfig` envelopes. The driver-specific config blob @@ -237,6 +258,19 @@ const OpenCodeSettingsPatch = Schema.Struct({ customModels: Schema.optionalKey(Schema.Array(Schema.String)), }); +const AcpRegistrySettingsPatch = Schema.Struct({ + enabled: Schema.optionalKey(Schema.Boolean), + registryUrl: Schema.optionalKey(Schema.String), + command: Schema.optionalKey(Schema.String), + args: Schema.optionalKey(Schema.Array(Schema.String)), + env: Schema.optionalKey(Schema.Record(Schema.String, Schema.String)), + iconUrl: Schema.optionalKey(Schema.String), + registryAgentId: Schema.optionalKey(Schema.String), + importedVersion: Schema.optionalKey(Schema.String), + distributionType: Schema.optionalKey(Schema.String), + customModels: Schema.optionalKey(Schema.Array(Schema.String)), +}); + export const ServerSettingsPatch = Schema.Struct({ // Server settings enableAssistantStreaming: Schema.optionalKey(Schema.Boolean), @@ -255,6 +289,7 @@ export const ServerSettingsPatch = Schema.Struct({ claudeAgent: Schema.optionalKey(ClaudeSettingsPatch), cursor: Schema.optionalKey(CursorSettingsPatch), opencode: Schema.optionalKey(OpenCodeSettingsPatch), + acpRegistry: Schema.optionalKey(AcpRegistrySettingsPatch), }), ), // Whole-map replacement for the new instance config. Patching individual