Add ACP agent registry support
- Wire ACP agent registry and client into server startup - Mark ACP session failures on active sendTurn errors - Add ACP adapter coverage and native event logging
This commit is contained in:
1 parent
93338cd619
commit
eb44e0f8e4
44 files changed
+7013
-218
No files matched your search
@@ -106,7 +106,7 @@ function withRealCodexHarness<A, E>(
|
||||
const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
|
||||
Effect.gen(function* () {
|
||||
const createdAt = nowIso();
|
||||
const provider = harness.adapterHarness?.provider ?? "codex";
|
||||
const provider = (harness.adapterHarness?.provider ?? "codex") as Exclude<ProviderKind, "acp">;
|
||||
const defaultModel = DEFAULT_MODEL_BY_PROVIDER[provider];
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
|
||||
@@ -51,7 +51,8 @@ const makeRoutingTextGeneration = Effect.gen(function* () {
|
||||
cursor,
|
||||
};
|
||||
|
||||
const route = (provider: TextGenerationProvider) => providerToService[provider];
|
||||
const route = (provider: string) =>
|
||||
providerToService[provider as TextGenerationProvider] ?? providerToService.codex;
|
||||
|
||||
return {
|
||||
generateCommitMessage: (input) =>
|
||||
|
||||
@@ -0,0 +1,460 @@
|
||||
/**
|
||||
* CliConfig - CLI/runtime bootstrap service definitions.
|
||||
*
|
||||
* Defines startup-only service contracts used while resolving process config
|
||||
* and constructing server runtime layers.
|
||||
*
|
||||
* @module CliConfig
|
||||
*/
|
||||
import { Config, Data, Effect, FileSystem, Layer, Option, Path, Schema, ServiceMap } from "effect";
|
||||
import { Command, Flag } from "effect/unstable/cli";
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
import {
|
||||
DEFAULT_PORT,
|
||||
deriveServerPaths,
|
||||
resolveStaticDir,
|
||||
ServerConfig,
|
||||
type RuntimeMode,
|
||||
type ServerConfigShape,
|
||||
} from "./config";
|
||||
import { fixPath, resolveBaseDir } from "./os-jank";
|
||||
import { Open } from "./open";
|
||||
import * as SqlitePersistence from "./persistence/Layers/Sqlite";
|
||||
import { makeServerProviderLayer, makeServerRuntimeServicesLayer } from "./serverLayers";
|
||||
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
|
||||
import { ProviderRegistryLive } from "./provider/Layers/ProviderRegistry";
|
||||
import { AcpAgentRegistryLive } from "./provider/Layers/AcpAgentRegistry";
|
||||
import { AcpRegistryClientLive } from "./provider/acp/AcpRegistryClient";
|
||||
import { Server } from "./wsServer";
|
||||
import { ServerLoggerLive } from "./serverLogger";
|
||||
import { AnalyticsServiceLayerLive } from "./telemetry/Layers/AnalyticsService";
|
||||
import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
|
||||
import { readBootstrapEnvelope } from "./bootstrap";
|
||||
import { ServerSettingsLive } from "./serverSettings";
|
||||
|
||||
export class StartupError extends Data.TaggedError("StartupError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
const PortSchema = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }));
|
||||
|
||||
const BootstrapEnvelopeSchema = Schema.Struct({
|
||||
mode: Schema.optional(Schema.String),
|
||||
port: Schema.optional(PortSchema),
|
||||
host: Schema.optional(Schema.String),
|
||||
t3Home: Schema.optional(Schema.String),
|
||||
devUrl: Schema.optional(Schema.URLFromString),
|
||||
noBrowser: Schema.optional(Schema.Boolean),
|
||||
authToken: Schema.optional(Schema.String),
|
||||
autoBootstrapProjectFromCwd: Schema.optional(Schema.Boolean),
|
||||
logWebSocketEvents: Schema.optional(Schema.Boolean),
|
||||
});
|
||||
|
||||
interface CliInput {
|
||||
readonly mode: Option.Option<RuntimeMode>;
|
||||
readonly port: Option.Option<number>;
|
||||
readonly host: Option.Option<string>;
|
||||
readonly t3Home: Option.Option<string>;
|
||||
readonly devUrl: Option.Option<URL>;
|
||||
readonly noBrowser: Option.Option<boolean>;
|
||||
readonly authToken: Option.Option<string>;
|
||||
readonly bootstrapFd: Option.Option<number>;
|
||||
readonly autoBootstrapProjectFromCwd: Option.Option<boolean>;
|
||||
readonly logWebSocketEvents: Option.Option<boolean>;
|
||||
}
|
||||
|
||||
/**
|
||||
* CliConfigShape - Startup helpers required while building server layers.
|
||||
*/
|
||||
export interface CliConfigShape {
|
||||
/**
|
||||
* Current process working directory.
|
||||
*/
|
||||
readonly cwd: string;
|
||||
|
||||
/**
|
||||
* Apply OS-specific PATH normalization.
|
||||
*/
|
||||
readonly fixPath: Effect.Effect<void>;
|
||||
|
||||
/**
|
||||
* Resolve static web asset directory for server mode.
|
||||
*/
|
||||
readonly resolveStaticDir: Effect.Effect<string | undefined>;
|
||||
}
|
||||
|
||||
/**
|
||||
* CliConfig - Service tag for startup CLI/runtime helpers.
|
||||
*/
|
||||
export class CliConfig extends ServiceMap.Service<CliConfig, CliConfigShape>()(
|
||||
"t3/main/CliConfig",
|
||||
) {
|
||||
static readonly layer = Layer.effect(
|
||||
CliConfig,
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
return {
|
||||
cwd: process.cwd(),
|
||||
fixPath: Effect.sync(fixPath),
|
||||
resolveStaticDir: resolveStaticDir().pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(Path.Path, path),
|
||||
),
|
||||
} satisfies CliConfigShape;
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const CliEnvConfig = Config.all({
|
||||
mode: Config.string("T3CODE_MODE").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.map((value) => (value === "desktop" ? "desktop" : "web"))),
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
port: Config.port("T3CODE_PORT").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
host: Config.string("T3CODE_HOST").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
t3Home: Config.string("T3CODE_HOME").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
devUrl: Config.url("VITE_DEV_SERVER_URL").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
noBrowser: Config.boolean("T3CODE_NO_BROWSER").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
authToken: Config.string("T3CODE_AUTH_TOKEN").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
bootstrapFd: Config.int("T3CODE_BOOTSTRAP_FD").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
autoBootstrapProjectFromCwd: Config.boolean("T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
logWebSocketEvents: Config.boolean("T3CODE_LOG_WS_EVENTS").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
});
|
||||
|
||||
const resolveBooleanFlag = (flag: Option.Option<boolean>, envValue: boolean) =>
|
||||
Option.getOrElse(Option.filter(flag, Boolean), () => envValue);
|
||||
|
||||
const resolveOptionPrecedence = <Value>(
|
||||
...values: ReadonlyArray<Option.Option<Value>>
|
||||
): Option.Option<Value> => Option.firstSomeOf(values);
|
||||
|
||||
const isValidPort = (value: number): boolean => value >= 1 && value <= 65_535;
|
||||
const isRuntimeMode = (value: string): value is RuntimeMode =>
|
||||
value === "web" || value === "desktop";
|
||||
|
||||
const ServerConfigLive = (input: CliInput) =>
|
||||
Layer.effect(
|
||||
ServerConfig,
|
||||
Effect.gen(function* () {
|
||||
const cliConfig = yield* CliConfig;
|
||||
const { findAvailablePort } = yield* NetService;
|
||||
const env = yield* CliEnvConfig.asEffect().pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new StartupError({ message: "Failed to read environment configuration", cause }),
|
||||
),
|
||||
);
|
||||
|
||||
const bootstrapFd = Option.getOrUndefined(input.bootstrapFd) ?? env.bootstrapFd;
|
||||
const bootstrapEnvelope =
|
||||
bootstrapFd !== undefined
|
||||
? yield* readBootstrapEnvelope(BootstrapEnvelopeSchema, bootstrapFd)
|
||||
: Option.none();
|
||||
|
||||
const mode: RuntimeMode = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
input.mode,
|
||||
Option.fromUndefinedOr(env.mode),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.filter(Option.fromUndefinedOr(bootstrap.mode), isRuntimeMode),
|
||||
),
|
||||
),
|
||||
() => "web",
|
||||
);
|
||||
const port = yield* Option.match(
|
||||
resolveOptionPrecedence(
|
||||
input.port,
|
||||
Option.fromUndefinedOr(env.port),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.filter(Option.fromUndefinedOr(bootstrap.port), isValidPort),
|
||||
),
|
||||
),
|
||||
{
|
||||
onSome: (value) => Effect.succeed(value),
|
||||
onNone: () => {
|
||||
if (mode === "desktop") {
|
||||
return Effect.succeed(DEFAULT_PORT);
|
||||
}
|
||||
return findAvailablePort(DEFAULT_PORT);
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const devUrl = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
input.devUrl,
|
||||
Option.fromUndefinedOr(env.devUrl),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.devUrl),
|
||||
),
|
||||
),
|
||||
() => undefined,
|
||||
);
|
||||
const baseDir = yield* resolveBaseDir(
|
||||
Option.getOrUndefined(
|
||||
resolveOptionPrecedence(
|
||||
input.t3Home,
|
||||
Option.fromUndefinedOr(env.t3Home),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.t3Home),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);
|
||||
const noBrowser = resolveBooleanFlag(
|
||||
input.noBrowser,
|
||||
Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
Option.fromUndefinedOr(env.noBrowser),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.noBrowser),
|
||||
),
|
||||
),
|
||||
() => mode === "desktop",
|
||||
),
|
||||
);
|
||||
const authToken = resolveOptionPrecedence(
|
||||
input.authToken,
|
||||
Option.fromUndefinedOr(env.authToken),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.authToken),
|
||||
),
|
||||
);
|
||||
const autoBootstrapProjectFromCwd = resolveBooleanFlag(
|
||||
input.autoBootstrapProjectFromCwd,
|
||||
Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
Option.fromUndefinedOr(env.autoBootstrapProjectFromCwd),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.autoBootstrapProjectFromCwd),
|
||||
),
|
||||
),
|
||||
() => mode === "web",
|
||||
),
|
||||
);
|
||||
const logWebSocketEvents = resolveBooleanFlag(
|
||||
input.logWebSocketEvents,
|
||||
Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
Option.fromUndefinedOr(env.logWebSocketEvents),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.logWebSocketEvents),
|
||||
),
|
||||
),
|
||||
() => Boolean(devUrl),
|
||||
),
|
||||
);
|
||||
const staticDir = devUrl ? undefined : yield* cliConfig.resolveStaticDir;
|
||||
const host = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
input.host,
|
||||
Option.fromUndefinedOr(env.host),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.host)),
|
||||
),
|
||||
() => (mode === "desktop" ? "127.0.0.1" : undefined),
|
||||
);
|
||||
|
||||
const config: ServerConfigShape = {
|
||||
mode,
|
||||
port,
|
||||
cwd: cliConfig.cwd,
|
||||
host,
|
||||
baseDir,
|
||||
...derivedPaths,
|
||||
staticDir,
|
||||
devUrl,
|
||||
noBrowser,
|
||||
authToken: Option.getOrUndefined(authToken),
|
||||
autoBootstrapProjectFromCwd,
|
||||
logWebSocketEvents,
|
||||
} satisfies ServerConfigShape;
|
||||
|
||||
return config;
|
||||
}),
|
||||
);
|
||||
|
||||
const LayerLive = (input: CliInput) =>
|
||||
Layer.empty.pipe(
|
||||
Layer.provideMerge(makeServerRuntimeServicesLayer()),
|
||||
Layer.provideMerge(makeServerProviderLayer()),
|
||||
Layer.provideMerge(ProviderRegistryLive),
|
||||
Layer.provideMerge(AcpAgentRegistryLive),
|
||||
Layer.provideMerge(AcpRegistryClientLive),
|
||||
Layer.provideMerge(SqlitePersistence.layerConfig),
|
||||
Layer.provideMerge(ServerLoggerLive),
|
||||
Layer.provideMerge(AnalyticsServiceLayerLive),
|
||||
Layer.provideMerge(ServerSettingsLive),
|
||||
Layer.provideMerge(ServerConfigLive(input)),
|
||||
);
|
||||
|
||||
const isWildcardHost = (host: string | undefined): boolean =>
|
||||
host === "0.0.0.0" || host === "::" || host === "[::]";
|
||||
|
||||
const formatHostForUrl = (host: string): string =>
|
||||
host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
|
||||
|
||||
export const recordStartupHeartbeat = Effect.gen(function* () {
|
||||
const analytics = yield* AnalyticsService;
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
|
||||
const { threadCount, projectCount } = yield* projectionSnapshotQuery.getSnapshot().pipe(
|
||||
Effect.map((snapshot) => ({
|
||||
threadCount: snapshot.threads.length,
|
||||
projectCount: snapshot.projects.length,
|
||||
})),
|
||||
Effect.catch((cause) =>
|
||||
Effect.logWarning("failed to gather startup snapshot for telemetry", { cause }).pipe(
|
||||
Effect.as({
|
||||
threadCount: 0,
|
||||
projectCount: 0,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
yield* analytics.record("server.boot.heartbeat", {
|
||||
threadCount,
|
||||
projectCount,
|
||||
});
|
||||
});
|
||||
|
||||
const makeServerRuntimeProgram = (input: CliInput) =>
|
||||
Effect.gen(function* () {
|
||||
const { start, stopSignal } = yield* Server;
|
||||
const openDeps = yield* Open;
|
||||
|
||||
const config = yield* ServerConfig;
|
||||
|
||||
if (!config.devUrl && !config.staticDir) {
|
||||
yield* Effect.logWarning(
|
||||
"web bundle missing and no VITE_DEV_SERVER_URL; web UI unavailable",
|
||||
{
|
||||
hint: "Run `bun run --cwd apps/web build` or set VITE_DEV_SERVER_URL for dev mode.",
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
yield* start;
|
||||
yield* Effect.forkChild(recordStartupHeartbeat);
|
||||
|
||||
const localUrl = `http://localhost:${config.port}`;
|
||||
const bindUrl =
|
||||
config.host && !isWildcardHost(config.host)
|
||||
? `http://${formatHostForUrl(config.host)}:${config.port}`
|
||||
: localUrl;
|
||||
const { authToken, devUrl, ...safeConfig } = config;
|
||||
yield* Effect.logInfo("T3 Code running", {
|
||||
...safeConfig,
|
||||
devUrl: devUrl?.toString(),
|
||||
authEnabled: Boolean(authToken),
|
||||
});
|
||||
|
||||
if (!config.noBrowser) {
|
||||
const target = config.devUrl?.toString() ?? bindUrl;
|
||||
yield* openDeps.openBrowser(target).pipe(
|
||||
Effect.catch(() =>
|
||||
Effect.logInfo("browser auto-open unavailable", {
|
||||
hint: `Open ${target} in your browser.`,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return yield* stopSignal;
|
||||
}).pipe(Effect.provide(LayerLive(input)));
|
||||
|
||||
const makeServerProgram = (input: CliInput) =>
|
||||
Effect.gen(function* () {
|
||||
const cliConfig = yield* CliConfig;
|
||||
yield* cliConfig.fixPath;
|
||||
return yield* makeServerRuntimeProgram(input);
|
||||
});
|
||||
|
||||
/**
|
||||
* These flags mirrors the environment variables and the config shape.
|
||||
*/
|
||||
|
||||
const modeFlag = Flag.choice("mode", ["web", "desktop"]).pipe(
|
||||
Flag.withDescription("Runtime mode. `desktop` keeps loopback defaults unless overridden."),
|
||||
Flag.optional,
|
||||
);
|
||||
const portFlag = Flag.integer("port").pipe(
|
||||
Flag.withSchema(PortSchema),
|
||||
Flag.withDescription("Port for the HTTP/WebSocket server."),
|
||||
Flag.optional,
|
||||
);
|
||||
const hostFlag = Flag.string("host").pipe(
|
||||
Flag.withDescription("Host/interface to bind (for example 127.0.0.1, 0.0.0.0, or a Tailnet IP)."),
|
||||
Flag.optional,
|
||||
);
|
||||
const t3HomeFlag = Flag.string("home-dir").pipe(
|
||||
Flag.withDescription("Base directory for all T3 Code data (equivalent to T3CODE_HOME)."),
|
||||
Flag.optional,
|
||||
);
|
||||
const devUrlFlag = Flag.string("dev-url").pipe(
|
||||
Flag.withSchema(Schema.URLFromString),
|
||||
Flag.withDescription("Dev web URL to proxy/redirect to (equivalent to VITE_DEV_SERVER_URL)."),
|
||||
Flag.optional,
|
||||
);
|
||||
const noBrowserFlag = Flag.boolean("no-browser").pipe(
|
||||
Flag.withDescription("Disable automatic browser opening."),
|
||||
Flag.optional,
|
||||
);
|
||||
const authTokenFlag = Flag.string("auth-token").pipe(
|
||||
Flag.withDescription("Auth token required for WebSocket connections."),
|
||||
Flag.withAlias("token"),
|
||||
Flag.optional,
|
||||
);
|
||||
const bootstrapFdFlag = Flag.integer("bootstrap-fd").pipe(
|
||||
Flag.withSchema(Schema.Int),
|
||||
Flag.withDescription("Read one-time bootstrap secrets from the given file descriptor."),
|
||||
Flag.optional,
|
||||
);
|
||||
const autoBootstrapProjectFromCwdFlag = Flag.boolean("auto-bootstrap-project-from-cwd").pipe(
|
||||
Flag.withDescription(
|
||||
"Create a project for the current working directory on startup when missing.",
|
||||
),
|
||||
Flag.optional,
|
||||
);
|
||||
const logWebSocketEventsFlag = Flag.boolean("log-websocket-events").pipe(
|
||||
Flag.withDescription(
|
||||
"Emit server-side logs for outbound WebSocket push traffic (equivalent to T3CODE_LOG_WS_EVENTS).",
|
||||
),
|
||||
Flag.withAlias("log-ws-events"),
|
||||
Flag.optional,
|
||||
);
|
||||
|
||||
export const t3Cli = Command.make("t3", {
|
||||
mode: modeFlag,
|
||||
port: portFlag,
|
||||
host: hostFlag,
|
||||
t3Home: t3HomeFlag,
|
||||
devUrl: devUrlFlag,
|
||||
noBrowser: noBrowserFlag,
|
||||
authToken: authTokenFlag,
|
||||
bootstrapFd: bootstrapFdFlag,
|
||||
autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag,
|
||||
logWebSocketEvents: logWebSocketEventsFlag,
|
||||
}).pipe(
|
||||
Command.withDescription("Run the T3 Code server."),
|
||||
Command.withHandler((input) => Effect.scoped(makeServerProgram(input))),
|
||||
);
|
||||
@@ -1273,23 +1273,30 @@ describe("ProviderCommandReactor", () => {
|
||||
expect(thread?.session?.runtimeMode).toBe("full-access");
|
||||
});
|
||||
|
||||
it("rejects provider changes after a thread is already bound to a session provider", async () => {
|
||||
const harness = await createHarness();
|
||||
it("marks the thread session errored when sendTurn fails after the session is running", async () => {
|
||||
const harness = await createHarness({
|
||||
threadModelSelection: { provider: "acp", model: "default", agentServerId: "mistral-vibe" },
|
||||
});
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-provider-switch-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-send-failure-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-provider-switch-1"),
|
||||
messageId: asMessageId("user-message-send-failure-1"),
|
||||
role: "user",
|
||||
text: "first",
|
||||
attachments: [],
|
||||
},
|
||||
modelSelection: {
|
||||
provider: "acp",
|
||||
model: "default",
|
||||
agentServerId: "mistral-vibe",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
runtimeMode: "full-access",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
@@ -1297,50 +1304,62 @@ describe("ProviderCommandReactor", () => {
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
|
||||
harness.sendTurn.mockImplementationOnce(
|
||||
(_: unknown) =>
|
||||
Effect.fail(
|
||||
new ProviderAdapterRequestError({
|
||||
provider: "acp",
|
||||
method: "session/prompt",
|
||||
detail: "Invalid API key. Please check your API key and try again.",
|
||||
}),
|
||||
) as unknown as Effect.Effect<{ threadId: ThreadId; turnId: TurnId }, never, never>,
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-provider-switch-2"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-send-failure-2"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-provider-switch-2"),
|
||||
messageId: asMessageId("user-message-send-failure-2"),
|
||||
role: "user",
|
||||
text: "second",
|
||||
attachments: [],
|
||||
},
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
provider: "acp",
|
||||
model: "default",
|
||||
agentServerId: "mistral-vibe",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
runtimeMode: "full-access",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(async () => {
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
return (
|
||||
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
|
||||
false
|
||||
const thread = readModel.threads.find(
|
||||
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
|
||||
);
|
||||
return thread?.session?.status === "error";
|
||||
});
|
||||
|
||||
expect(harness.startSession.mock.calls.length).toBe(1);
|
||||
expect(harness.sendTurn.mock.calls.length).toBe(1);
|
||||
expect(harness.stopSession.mock.calls.length).toBe(0);
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread?.session?.threadId).toBe("thread-1");
|
||||
expect(thread?.session?.providerName).toBe("codex");
|
||||
expect(thread?.session?.runtimeMode).toBe("approval-required");
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
expect(thread?.session).toMatchObject({
|
||||
threadId: "thread-1",
|
||||
status: "error",
|
||||
providerName: "acp",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
lastError: expect.stringContaining("Invalid API key"),
|
||||
});
|
||||
expect(
|
||||
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
|
||||
).toMatchObject({
|
||||
payload: {
|
||||
detail: expect.stringContaining("cannot switch to 'claudeAgent'"),
|
||||
detail: expect.stringContaining("Invalid API key"),
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -205,16 +205,29 @@ const make = Effect.gen(function* () {
|
||||
createdAt: input.createdAt,
|
||||
});
|
||||
|
||||
const formatFailureDetail = (cause: Cause.Cause<unknown>): string => {
|
||||
const failReason = cause.reasons.find(Cause.isFailReason);
|
||||
const providerError = Schema.is(ProviderAdapterRequestError)(failReason?.error)
|
||||
? failReason.error
|
||||
: undefined;
|
||||
if (providerError) {
|
||||
return providerError.detail;
|
||||
}
|
||||
return Cause.pretty(cause);
|
||||
};
|
||||
const setThreadSessionErrorIfActive = (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly detail: string;
|
||||
readonly createdAt: string;
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
const thread = yield* resolveThread(input.threadId);
|
||||
if (!thread?.session || thread.session.status === "stopped") {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* setThreadSession({
|
||||
threadId: input.threadId,
|
||||
session: {
|
||||
...thread.session,
|
||||
status: "error",
|
||||
activeTurnId: null,
|
||||
lastError: input.detail,
|
||||
updatedAt: input.createdAt,
|
||||
},
|
||||
createdAt: input.createdAt,
|
||||
});
|
||||
});
|
||||
|
||||
const setThreadSession = (input: {
|
||||
readonly threadId: ThreadId;
|
||||
@@ -645,8 +658,24 @@ const make = Effect.gen(function* () {
|
||||
interactionMode: event.payload.interactionMode,
|
||||
createdAt: event.payload.createdAt,
|
||||
}).pipe(
|
||||
Effect.map(Option.some),
|
||||
Effect.catchCause((cause) => handleTurnStartFailure(cause).pipe(Effect.as(Option.none()))),
|
||||
Effect.catchCause((cause) => {
|
||||
const detail = Cause.pretty(cause);
|
||||
return Effect.gen(function* () {
|
||||
yield* appendProviderFailureActivity({
|
||||
threadId: event.payload.threadId,
|
||||
kind: "provider.turn.start.failed",
|
||||
summary: "Provider turn start failed",
|
||||
detail,
|
||||
turnId: null,
|
||||
createdAt: event.payload.createdAt,
|
||||
});
|
||||
yield* setThreadSessionErrorIfActive({
|
||||
threadId: event.payload.threadId,
|
||||
detail,
|
||||
createdAt: event.payload.createdAt,
|
||||
});
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
if (Option.isNone(sendTurnRequest)) {
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
import { assert, beforeEach, describe, it, vi } from "vitest";
|
||||
|
||||
import { type AcpAgentServer, ThreadId } from "@t3tools/contracts";
|
||||
import { Effect, Fiber, Layer, Queue, Stream } from "effect";
|
||||
|
||||
import type { AcpInboundMessage } from "../acp/AcpTypes.ts";
|
||||
import { AcpAdapter } from "../Services/AcpAdapter.ts";
|
||||
import { AcpAgentRegistry } from "../Services/AcpAgentRegistry.ts";
|
||||
|
||||
const transportState: {
|
||||
requestCalls: Array<{ method: string; params: unknown }>;
|
||||
notifyCalls: Array<{ method: string; params: unknown }>;
|
||||
notificationQueue: Queue.Queue<AcpInboundMessage> | null;
|
||||
} = {
|
||||
requestCalls: [],
|
||||
notifyCalls: [],
|
||||
notificationQueue: null,
|
||||
};
|
||||
|
||||
vi.mock("../acp/AcpJsonRpcConnection.ts", async () => {
|
||||
const { Effect, Queue, Stream } = await import("effect");
|
||||
|
||||
return {
|
||||
spawnAcpChildProcess: vi.fn(() =>
|
||||
Effect.succeed({
|
||||
stdin: { end: vi.fn() },
|
||||
stdout: {},
|
||||
kill: vi.fn(),
|
||||
}),
|
||||
),
|
||||
attachAcpJsonRpcConnection: vi.fn(() =>
|
||||
Effect.gen(function* () {
|
||||
const notificationQueue = yield* Queue.unbounded<AcpInboundMessage>();
|
||||
transportState.notificationQueue = notificationQueue;
|
||||
|
||||
return {
|
||||
request: (method: string, params?: unknown) =>
|
||||
Effect.gen(function* () {
|
||||
transportState.requestCalls.push({ method, params });
|
||||
switch (method) {
|
||||
case "initialize":
|
||||
return { protocolVersion: 1 };
|
||||
case "session/new":
|
||||
return { sessionId: "session-1" };
|
||||
case "session/prompt":
|
||||
yield* Queue.offer(notificationQueue, {
|
||||
_tag: "notification",
|
||||
method: "session/update",
|
||||
params: {
|
||||
sessionId: "session-1",
|
||||
update: {
|
||||
sessionUpdate: "assistant_message_chunk",
|
||||
content: { type: "text", text: "hi" },
|
||||
},
|
||||
},
|
||||
});
|
||||
return { stopReason: "end_turn" };
|
||||
case "session/cancel":
|
||||
return {};
|
||||
default:
|
||||
return {};
|
||||
}
|
||||
}),
|
||||
notify: (method: string, params?: unknown) =>
|
||||
Effect.sync(() => {
|
||||
transportState.notifyCalls.push({ method, params });
|
||||
}),
|
||||
registerHandler: () => Effect.void,
|
||||
notifications: Stream.fromQueue(notificationQueue),
|
||||
};
|
||||
}),
|
||||
),
|
||||
disposeAcpChild: vi.fn(() => undefined),
|
||||
};
|
||||
});
|
||||
|
||||
import { makeAcpAdapterLive } from "./AcpAdapter.ts";
|
||||
|
||||
describe("AcpAdapterLive", () => {
|
||||
beforeEach(() => {
|
||||
transportState.requestCalls = [];
|
||||
transportState.notifyCalls = [];
|
||||
transportState.notificationQueue = null;
|
||||
});
|
||||
|
||||
it("writes native ACP observability records for inbound notifications and responses", async () => {
|
||||
const nativeEvents: Array<{
|
||||
event?: {
|
||||
provider?: string;
|
||||
kind?: string;
|
||||
method?: string;
|
||||
};
|
||||
}> = [];
|
||||
const threadId = ThreadId.makeUnsafe("thread-acp-native");
|
||||
const agentServer: AcpAgentServer = {
|
||||
id: "agent-1",
|
||||
name: "Agent 1",
|
||||
enabled: true,
|
||||
source: "manual",
|
||||
distributionType: "manual",
|
||||
launch: { command: "npx", args: ["-y", "agent-1"] },
|
||||
};
|
||||
|
||||
const adapterLayer = makeAcpAdapterLive({
|
||||
nativeEventLogger: {
|
||||
filePath: "memory://acp-native-events",
|
||||
write: (event, loggedThreadId) => {
|
||||
nativeEvents.push(event as (typeof nativeEvents)[number]);
|
||||
assert.equal(loggedThreadId, threadId);
|
||||
return Effect.void;
|
||||
},
|
||||
close: () => Effect.void,
|
||||
},
|
||||
}).pipe(
|
||||
Layer.provide(
|
||||
Layer.succeed(AcpAgentRegistry, {
|
||||
getAgentServers: Effect.succeed([agentServer]),
|
||||
listStatuses: Effect.succeed([]),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const result = await Effect.runPromise(
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* AcpAdapter;
|
||||
const session = yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: "acp",
|
||||
modelSelection: { provider: "acp", agentServerId: "agent-1", model: "default" },
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
const deltaEventFiber = yield* adapter.streamEvents.pipe(
|
||||
Stream.filter((event) => event.type === "content.delta"),
|
||||
Stream.runHead,
|
||||
Effect.forkChild,
|
||||
);
|
||||
const turn = yield* adapter.sendTurn({
|
||||
threadId: session.threadId,
|
||||
input: "hello",
|
||||
attachments: [],
|
||||
});
|
||||
yield* adapter.interruptTurn(session.threadId);
|
||||
const deltaEvent = yield* Fiber.join(deltaEventFiber);
|
||||
return { turn, deltaEvent };
|
||||
}).pipe(Effect.provide(adapterLayer)),
|
||||
);
|
||||
|
||||
assert.equal(result.deltaEvent._tag, "Some");
|
||||
if (result.deltaEvent._tag === "Some") {
|
||||
assert.equal(result.deltaEvent.value.type, "content.delta");
|
||||
if (result.deltaEvent.value.type === "content.delta") {
|
||||
assert.equal(result.deltaEvent.value.payload.delta, "hi");
|
||||
}
|
||||
}
|
||||
assert.equal(
|
||||
transportState.requestCalls.map((call) => call.method).join(","),
|
||||
"initialize,session/new,session/prompt",
|
||||
);
|
||||
assert.deepEqual(transportState.notifyCalls, [
|
||||
{
|
||||
method: "session/cancel",
|
||||
params: { sessionId: "session-1" },
|
||||
},
|
||||
]);
|
||||
assert.equal(nativeEvents.length > 0, true);
|
||||
assert.equal(
|
||||
nativeEvents.some(
|
||||
(record) =>
|
||||
record.event?.provider === "acp" &&
|
||||
record.event?.kind === "notification" &&
|
||||
record.event?.method === "session/update",
|
||||
),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
nativeEvents.some(
|
||||
(record) =>
|
||||
record.event?.provider === "acp" &&
|
||||
record.event?.kind === "response" &&
|
||||
record.event?.method === "session/prompt",
|
||||
),
|
||||
true,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,625 @@
|
||||
import type { ChildProcessWithoutNullStreams } from "node:child_process";
|
||||
import nodePath from "node:path";
|
||||
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
EventId,
|
||||
type ProviderApprovalDecision,
|
||||
type ProviderRuntimeEvent,
|
||||
type ProviderSession,
|
||||
type ProviderUserInputAnswers,
|
||||
RuntimeRequestId,
|
||||
TurnId,
|
||||
type ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Cause, Deferred, Effect, Exit, Fiber, Layer, Queue, Schema, Stream } from "effect";
|
||||
|
||||
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
|
||||
import {
|
||||
attachAcpJsonRpcConnection,
|
||||
disposeAcpChild,
|
||||
spawnAcpChildProcess,
|
||||
type AcpJsonRpcConnection,
|
||||
} from "../acp/AcpJsonRpcConnection.ts";
|
||||
import type { AcpInboundMessage } from "../acp/AcpTypes.ts";
|
||||
import { AcpProcessExitedError, AcpRpcError, type AcpError } from "../acp/AcpErrors.ts";
|
||||
import {
|
||||
ProviderAdapterProcessError,
|
||||
ProviderAdapterRequestError,
|
||||
ProviderAdapterSessionClosedError,
|
||||
ProviderAdapterSessionNotFoundError,
|
||||
ProviderAdapterValidationError,
|
||||
} from "../Errors.ts";
|
||||
import { AcpAgentRegistry } from "../Services/AcpAgentRegistry.ts";
|
||||
import { AcpAdapter, type AcpAdapterShape } from "../Services/AcpAdapter.ts";
|
||||
|
||||
const PROVIDER = "acp" as const;
|
||||
const ACP_RESUME_VERSION = 1 as const;
|
||||
|
||||
export interface AcpAdapterLiveOptions {
|
||||
readonly nativeEventLogPath?: string;
|
||||
readonly nativeEventLogger?: EventNdjsonLogger;
|
||||
}
|
||||
|
||||
interface AcpSessionContext {
|
||||
threadId: ThreadId;
|
||||
session: ProviderSession;
|
||||
child: ChildProcessWithoutNullStreams;
|
||||
conn: AcpJsonRpcConnection;
|
||||
acpSessionId: string;
|
||||
notificationFiber?: Fiber.Fiber<void, never>;
|
||||
pendingApprovals: Map<
|
||||
ApprovalRequestId,
|
||||
{ readonly decision: Deferred.Deferred<ProviderApprovalDecision> }
|
||||
>;
|
||||
turns: Array<{ id: TurnId; items: ReadonlyArray<unknown> }>;
|
||||
activeTurnId?: TurnId;
|
||||
stopped: boolean;
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function parseResume(raw: unknown): { sessionId: string } | undefined {
|
||||
if (!isRecord(raw) || raw.schemaVersion !== ACP_RESUME_VERSION) {
|
||||
return undefined;
|
||||
}
|
||||
return typeof raw.sessionId === "string" && raw.sessionId.trim().length > 0
|
||||
? { sessionId: raw.sessionId.trim() }
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function mapAcpToAdapterError(threadId: ThreadId, method: string, error: AcpError) {
|
||||
if (Schema.is(AcpProcessExitedError)(error)) {
|
||||
return new ProviderAdapterSessionClosedError({ provider: PROVIDER, threadId, cause: error });
|
||||
}
|
||||
if (Schema.is(AcpRpcError)(error)) {
|
||||
return new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method,
|
||||
detail: error.message,
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
return new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method,
|
||||
detail: error.message,
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
function extractTextChunk(params: unknown): string | undefined {
|
||||
if (!isRecord(params)) {
|
||||
return undefined;
|
||||
}
|
||||
const update = isRecord(params.update) ? params.update : params;
|
||||
if (typeof update.sessionUpdate !== "string") {
|
||||
return undefined;
|
||||
}
|
||||
if (
|
||||
update.sessionUpdate !== "agent_message_chunk" &&
|
||||
update.sessionUpdate !== "assistant_message_chunk"
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
const content = update.content;
|
||||
return isRecord(content) && content.type === "text" && typeof content.text === "string"
|
||||
? content.text
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function extractPermissionDetail(params: unknown): string | undefined {
|
||||
if (!isRecord(params) || !isRecord(params.toolCall)) {
|
||||
return undefined;
|
||||
}
|
||||
if (typeof params.toolCall.title === "string" && params.toolCall.title.trim().length > 0) {
|
||||
return params.toolCall.title.trim();
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function approvalOutcome(decision: ProviderApprovalDecision): string {
|
||||
switch (decision) {
|
||||
case "acceptForSession":
|
||||
return "allow-always";
|
||||
case "accept":
|
||||
return "allow-once";
|
||||
case "decline":
|
||||
case "cancel":
|
||||
default:
|
||||
return "reject-once";
|
||||
}
|
||||
}
|
||||
|
||||
function makeAcpAdapter(options?: AcpAdapterLiveOptions) {
|
||||
return Effect.gen(function* () {
|
||||
const agentRegistry = yield* AcpAgentRegistry;
|
||||
const nativeEventLogger =
|
||||
options?.nativeEventLogger ??
|
||||
(options?.nativeEventLogPath !== undefined
|
||||
? yield* makeEventNdjsonLogger(options.nativeEventLogPath, {
|
||||
stream: "native",
|
||||
})
|
||||
: undefined);
|
||||
const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
|
||||
const sessions = new Map<ThreadId, AcpSessionContext>();
|
||||
|
||||
const nowIso = Effect.sync(() => new Date().toISOString());
|
||||
const makeEventStamp = () =>
|
||||
Effect.gen(function* () {
|
||||
return {
|
||||
eventId: EventId.makeUnsafe(crypto.randomUUID()),
|
||||
createdAt: yield* nowIso,
|
||||
};
|
||||
});
|
||||
|
||||
const offerRuntimeEvent = (event: ProviderRuntimeEvent) =>
|
||||
Queue.offer(runtimeEventQueue, event);
|
||||
|
||||
const logNativeInbound = (
|
||||
threadId: ThreadId,
|
||||
input: {
|
||||
readonly kind: "notification" | "request" | "response" | "error";
|
||||
readonly method: string;
|
||||
readonly payload: unknown;
|
||||
},
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
if (!nativeEventLogger) return;
|
||||
const observedAt = new Date().toISOString();
|
||||
yield* nativeEventLogger.write(
|
||||
{
|
||||
observedAt,
|
||||
event: {
|
||||
id: crypto.randomUUID(),
|
||||
kind: input.kind,
|
||||
provider: PROVIDER,
|
||||
createdAt: observedAt,
|
||||
method: input.method,
|
||||
threadId,
|
||||
payload: input.payload,
|
||||
},
|
||||
},
|
||||
threadId,
|
||||
);
|
||||
});
|
||||
|
||||
const requestWithNativeLogging = (
|
||||
threadId: ThreadId,
|
||||
conn: AcpJsonRpcConnection,
|
||||
method: string,
|
||||
params?: unknown,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* Effect.exit(conn.request(method, params));
|
||||
if (Exit.isSuccess(result)) {
|
||||
yield* logNativeInbound(threadId, {
|
||||
kind: "response",
|
||||
method,
|
||||
payload: result.value,
|
||||
});
|
||||
return result.value;
|
||||
}
|
||||
const squashed = Cause.squash(result.cause);
|
||||
yield* logNativeInbound(threadId, {
|
||||
kind: "error",
|
||||
method,
|
||||
payload:
|
||||
squashed instanceof Error
|
||||
? { message: squashed.message, name: squashed.name }
|
||||
: { message: String(squashed ?? "Unknown ACP error") },
|
||||
});
|
||||
return yield* Effect.failCause(result.cause);
|
||||
});
|
||||
|
||||
const stopSessionInternal = (ctx: AcpSessionContext) =>
|
||||
Effect.gen(function* () {
|
||||
if (ctx.stopped) return;
|
||||
ctx.stopped = true;
|
||||
if (ctx.notificationFiber) {
|
||||
yield* Fiber.interrupt(ctx.notificationFiber);
|
||||
}
|
||||
disposeAcpChild(ctx.child);
|
||||
sessions.delete(ctx.threadId);
|
||||
});
|
||||
|
||||
const requireSession = (threadId: ThreadId) => {
|
||||
const ctx = sessions.get(threadId);
|
||||
if (!ctx) {
|
||||
return Effect.fail(
|
||||
new ProviderAdapterSessionNotFoundError({ provider: PROVIDER, threadId }),
|
||||
);
|
||||
}
|
||||
if (ctx.stopped) {
|
||||
return Effect.fail(new ProviderAdapterSessionClosedError({ provider: PROVIDER, threadId }));
|
||||
}
|
||||
return Effect.succeed(ctx);
|
||||
};
|
||||
|
||||
const startSession: AcpAdapterShape["startSession"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const acpSelection = input.modelSelection;
|
||||
if (acpSelection?.provider !== "acp") {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: PROVIDER,
|
||||
operation: "startSession",
|
||||
issue: "ACP sessions require an ACP model selection with agentServerId.",
|
||||
});
|
||||
}
|
||||
const agentServers = yield* agentRegistry.getAgentServers.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderAdapterProcessError({
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
detail: cause.message,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const agentServer = agentServers.find(
|
||||
(candidate) => candidate.id === acpSelection.agentServerId,
|
||||
);
|
||||
if (!agentServer || !agentServer.enabled) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: PROVIDER,
|
||||
operation: "startSession",
|
||||
issue: `Unknown or disabled ACP agent '${acpSelection.agentServerId}'.`,
|
||||
});
|
||||
}
|
||||
const cwd = input.cwd?.trim() ? nodePath.resolve(input.cwd.trim()) : undefined;
|
||||
const child = yield* spawnAcpChildProcess({
|
||||
command: agentServer.launch.command,
|
||||
args: [...agentServer.launch.args],
|
||||
...(cwd ? { cwd } : {}),
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderAdapterProcessError({
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
detail: cause.message,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const conn = yield* attachAcpJsonRpcConnection(child).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderAdapterProcessError({
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
detail: "Failed to attach ACP transport.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const ctx: AcpSessionContext = {
|
||||
threadId: input.threadId,
|
||||
session: {} as ProviderSession,
|
||||
child,
|
||||
conn,
|
||||
acpSessionId: "",
|
||||
pendingApprovals: new Map(),
|
||||
turns: [],
|
||||
stopped: false,
|
||||
};
|
||||
|
||||
yield* conn.registerHandler("session/request_permission", (params) =>
|
||||
Effect.gen(function* () {
|
||||
yield* logNativeInbound(input.threadId, {
|
||||
kind: "request",
|
||||
method: "session/request_permission",
|
||||
payload: params,
|
||||
});
|
||||
const requestId = ApprovalRequestId.makeUnsafe(crypto.randomUUID());
|
||||
const decision = yield* Deferred.make<ProviderApprovalDecision>();
|
||||
ctx.pendingApprovals.set(requestId, { decision });
|
||||
yield* offerRuntimeEvent({
|
||||
type: "request.opened",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
agentServerId: agentServer.id,
|
||||
threadId: input.threadId,
|
||||
turnId: ctx.activeTurnId,
|
||||
requestId: RuntimeRequestId.makeUnsafe(requestId),
|
||||
payload: {
|
||||
requestType: "command_execution_approval",
|
||||
detail: extractPermissionDetail(params) ?? "ACP permission request",
|
||||
args: params,
|
||||
},
|
||||
raw: { source: "acp.jsonrpc", method: "session/request_permission", payload: params },
|
||||
});
|
||||
const resolved = yield* Deferred.await(decision);
|
||||
ctx.pendingApprovals.delete(requestId);
|
||||
yield* offerRuntimeEvent({
|
||||
type: "request.resolved",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
agentServerId: agentServer.id,
|
||||
threadId: input.threadId,
|
||||
turnId: ctx.activeTurnId,
|
||||
requestId: RuntimeRequestId.makeUnsafe(requestId),
|
||||
payload: { requestType: "command_execution_approval", decision: resolved },
|
||||
});
|
||||
return { outcome: { outcome: "selected", optionId: approvalOutcome(resolved) } };
|
||||
}),
|
||||
);
|
||||
|
||||
yield* requestWithNativeLogging(input.threadId, conn, "initialize", {
|
||||
protocolVersion: 1,
|
||||
clientCapabilities: {
|
||||
fs: { readTextFile: false, writeTextFile: false },
|
||||
terminal: false,
|
||||
},
|
||||
clientInfo: { name: "t3-code", version: "0.0.0" },
|
||||
}).pipe(
|
||||
Effect.mapError((cause) => mapAcpToAdapterError(input.threadId, "initialize", cause)),
|
||||
);
|
||||
|
||||
const resume = parseResume(input.resumeCursor);
|
||||
const created = resume
|
||||
? yield* Effect.exit(
|
||||
requestWithNativeLogging(input.threadId, conn, "session/load", {
|
||||
sessionId: resume.sessionId,
|
||||
...(cwd ? { cwd } : {}),
|
||||
}),
|
||||
).pipe(
|
||||
Effect.flatMap((result) =>
|
||||
Exit.isSuccess(result)
|
||||
? Effect.succeed(result.value)
|
||||
: requestWithNativeLogging(input.threadId, conn, "session/new", {
|
||||
...(cwd ? { cwd } : {}),
|
||||
mcpServers: [],
|
||||
}).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
mapAcpToAdapterError(input.threadId, "session/new", cause),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
: yield* requestWithNativeLogging(input.threadId, conn, "session/new", {
|
||||
...(cwd ? { cwd } : {}),
|
||||
mcpServers: [],
|
||||
}).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
mapAcpToAdapterError(input.threadId, "session/new", cause),
|
||||
),
|
||||
);
|
||||
|
||||
const sessionId =
|
||||
resume?.sessionId ??
|
||||
(isRecord(created) && typeof created.sessionId === "string"
|
||||
? created.sessionId
|
||||
: undefined);
|
||||
if (!sessionId) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "session/new",
|
||||
detail: "session/new missing sessionId",
|
||||
});
|
||||
}
|
||||
|
||||
const session: ProviderSession = {
|
||||
provider: PROVIDER,
|
||||
agentServerId: agentServer.id,
|
||||
status: "ready",
|
||||
runtimeMode: input.runtimeMode,
|
||||
...(cwd ? { cwd } : {}),
|
||||
threadId: input.threadId,
|
||||
resumeCursor: { schemaVersion: ACP_RESUME_VERSION, sessionId },
|
||||
createdAt: yield* nowIso,
|
||||
updatedAt: yield* nowIso,
|
||||
};
|
||||
|
||||
ctx.session = session;
|
||||
ctx.acpSessionId = sessionId;
|
||||
|
||||
const notificationFiber = yield* Stream.runDrain(
|
||||
Stream.mapEffect(conn.notifications, (message: AcpInboundMessage) =>
|
||||
Effect.gen(function* () {
|
||||
if (message._tag !== "notification") {
|
||||
return;
|
||||
}
|
||||
yield* logNativeInbound(input.threadId, {
|
||||
kind: "notification",
|
||||
method: message.method,
|
||||
payload: message.params,
|
||||
});
|
||||
if (message.method !== "session/update") {
|
||||
return;
|
||||
}
|
||||
const text = extractTextChunk(message.params);
|
||||
if (!text) {
|
||||
return;
|
||||
}
|
||||
yield* offerRuntimeEvent({
|
||||
type: "content.delta",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
agentServerId: agentServer.id,
|
||||
threadId: input.threadId,
|
||||
turnId: ctx.activeTurnId,
|
||||
payload: { streamKind: "assistant_text", delta: text },
|
||||
raw: { source: "acp.jsonrpc", method: "session/update", payload: message.params },
|
||||
});
|
||||
}),
|
||||
),
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
ctx.notificationFiber = notificationFiber;
|
||||
sessions.set(input.threadId, ctx);
|
||||
|
||||
yield* offerRuntimeEvent({
|
||||
type: "session.started",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
agentServerId: agentServer.id,
|
||||
threadId: input.threadId,
|
||||
payload: { message: `${agentServer.name} ACP session started` },
|
||||
});
|
||||
yield* offerRuntimeEvent({
|
||||
type: "session.state.changed",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
agentServerId: agentServer.id,
|
||||
threadId: input.threadId,
|
||||
payload: { state: "ready", reason: "ACP session ready" },
|
||||
});
|
||||
yield* offerRuntimeEvent({
|
||||
type: "thread.started",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
agentServerId: agentServer.id,
|
||||
threadId: input.threadId,
|
||||
payload: { providerThreadId: sessionId },
|
||||
});
|
||||
|
||||
return session;
|
||||
});
|
||||
|
||||
const sendTurn: AcpAdapterShape["sendTurn"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const ctx = yield* requireSession(input.threadId);
|
||||
if (
|
||||
(!input.input || input.input.trim().length === 0) &&
|
||||
(!input.attachments || input.attachments.length === 0)
|
||||
) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: PROVIDER,
|
||||
operation: "sendTurn",
|
||||
issue: "Turn requires non-empty text or attachments.",
|
||||
});
|
||||
}
|
||||
const turnId = TurnId.makeUnsafe(crypto.randomUUID());
|
||||
ctx.activeTurnId = turnId;
|
||||
ctx.session = { ...ctx.session, activeTurnId: turnId, updatedAt: yield* nowIso };
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.started",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
agentServerId: ctx.session.agentServerId,
|
||||
threadId: input.threadId,
|
||||
turnId,
|
||||
payload: {},
|
||||
});
|
||||
const promptParts = input.input?.trim() ? [{ type: "text", text: input.input.trim() }] : [];
|
||||
const result = yield* requestWithNativeLogging(input.threadId, ctx.conn, "session/prompt", {
|
||||
sessionId: ctx.acpSessionId,
|
||||
prompt: promptParts,
|
||||
}).pipe(
|
||||
Effect.mapError((cause) => mapAcpToAdapterError(input.threadId, "session/prompt", cause)),
|
||||
);
|
||||
ctx.turns.push({ id: turnId, items: [{ prompt: promptParts, result }] });
|
||||
ctx.session = {
|
||||
...ctx.session,
|
||||
activeTurnId: turnId,
|
||||
updatedAt: yield* nowIso,
|
||||
};
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.completed",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
agentServerId: ctx.session.agentServerId,
|
||||
threadId: input.threadId,
|
||||
turnId,
|
||||
payload: {
|
||||
state: "completed",
|
||||
stopReason:
|
||||
isRecord(result) && typeof result.stopReason === "string" ? result.stopReason : null,
|
||||
},
|
||||
});
|
||||
return { threadId: input.threadId, turnId, resumeCursor: ctx.session.resumeCursor };
|
||||
});
|
||||
|
||||
const interruptTurn: AcpAdapterShape["interruptTurn"] = (threadId) =>
|
||||
Effect.gen(function* () {
|
||||
const ctx = yield* requireSession(threadId);
|
||||
yield* Effect.ignore(
|
||||
ctx.conn.notify("session/cancel", {
|
||||
sessionId: ctx.acpSessionId,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
const respondToRequest: AcpAdapterShape["respondToRequest"] = (threadId, requestId, decision) =>
|
||||
Effect.gen(function* () {
|
||||
const ctx = yield* requireSession(threadId);
|
||||
const pending = ctx.pendingApprovals.get(requestId);
|
||||
if (!pending) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "session/request_permission",
|
||||
detail: `Unknown pending approval request: ${requestId}`,
|
||||
});
|
||||
}
|
||||
yield* Deferred.succeed(pending.decision, decision);
|
||||
});
|
||||
|
||||
const respondToUserInput: AcpAdapterShape["respondToUserInput"] = (
|
||||
_threadId,
|
||||
_requestId,
|
||||
_answers: ProviderUserInputAnswers,
|
||||
) =>
|
||||
Effect.fail(
|
||||
new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "session/request_user_input",
|
||||
detail: "Generic ACP adapter does not support structured user input yet.",
|
||||
}),
|
||||
);
|
||||
|
||||
const stopSession: AcpAdapterShape["stopSession"] = (threadId) =>
|
||||
Effect.gen(function* () {
|
||||
const ctx = yield* requireSession(threadId);
|
||||
yield* stopSessionInternal(ctx);
|
||||
});
|
||||
|
||||
yield* Effect.addFinalizer(() =>
|
||||
Effect.forEach(sessions.values(), stopSessionInternal, { discard: true }).pipe(
|
||||
Effect.tap(() => Queue.shutdown(runtimeEventQueue)),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
provider: PROVIDER,
|
||||
capabilities: { sessionModelSwitch: "unsupported" },
|
||||
startSession,
|
||||
sendTurn,
|
||||
interruptTurn,
|
||||
respondToRequest,
|
||||
respondToUserInput,
|
||||
stopSession,
|
||||
listSessions: () =>
|
||||
Effect.sync(() => Array.from(sessions.values(), (ctx) => ({ ...ctx.session }))),
|
||||
hasSession: (threadId) =>
|
||||
Effect.sync(() => {
|
||||
const session = sessions.get(threadId);
|
||||
return session !== undefined && !session.stopped;
|
||||
}),
|
||||
readThread: (threadId) =>
|
||||
Effect.gen(function* () {
|
||||
const ctx = yield* requireSession(threadId);
|
||||
return { threadId, turns: ctx.turns };
|
||||
}),
|
||||
rollbackThread: (threadId, numTurns) =>
|
||||
Effect.gen(function* () {
|
||||
const ctx = yield* requireSession(threadId);
|
||||
const nextLength = Math.max(0, ctx.turns.length - numTurns);
|
||||
ctx.turns.splice(nextLength);
|
||||
return { threadId, turns: ctx.turns };
|
||||
}),
|
||||
stopAll: () => Effect.forEach(sessions.values(), stopSessionInternal, { discard: true }),
|
||||
streamEvents: Stream.fromQueue(runtimeEventQueue),
|
||||
} satisfies AcpAdapterShape;
|
||||
});
|
||||
}
|
||||
|
||||
export const AcpAdapterLive = Layer.effect(AcpAdapter, makeAcpAdapter());
|
||||
|
||||
export function makeAcpAdapterLive(options?: AcpAdapterLiveOptions) {
|
||||
return Layer.effect(AcpAdapter, makeAcpAdapter(options));
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import nodeFs from "node:fs";
|
||||
import nodePath from "node:path";
|
||||
|
||||
import { type AcpAgentServer, type ServerAcpAgentStatus } from "@t3tools/contracts";
|
||||
import { Effect, Layer } from "effect";
|
||||
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { AcpAgentRegistry, type AcpAgentRegistryShape } from "../Services/AcpAgentRegistry.ts";
|
||||
|
||||
function commandExists(command: string): boolean {
|
||||
if (nodePath.isAbsolute(command)) {
|
||||
try {
|
||||
nodeFs.accessSync(command, nodeFs.constants.X_OK);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const pathValue = process.env.PATH ?? "";
|
||||
const pathEntries = pathValue.split(nodePath.delimiter).filter(Boolean);
|
||||
const executableNames =
|
||||
process.platform === "win32"
|
||||
? [command, `${command}.exe`, `${command}.cmd`, `${command}.bat`]
|
||||
: [command];
|
||||
|
||||
return pathEntries.some((entry) =>
|
||||
executableNames.some((name) => {
|
||||
try {
|
||||
nodeFs.accessSync(nodePath.join(entry, name), nodeFs.constants.X_OK);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function toStatus(agent: AcpAgentServer, checkedAt: string): ServerAcpAgentStatus {
|
||||
const installed = commandExists(agent.launch.command);
|
||||
return {
|
||||
agentServerId: agent.id,
|
||||
displayName: agent.name,
|
||||
enabled: agent.enabled,
|
||||
installed,
|
||||
status: agent.enabled ? (installed ? "ready" : "error") : "disabled",
|
||||
authStatus: "unknown",
|
||||
checkedAt,
|
||||
version: agent.importedVersion ?? null,
|
||||
...(installed
|
||||
? {}
|
||||
: {
|
||||
message:
|
||||
agent.distributionType === "binaryUnsupported"
|
||||
? "Binary ACP agents are discoverable but require manual setup in this version."
|
||||
: `Command '${agent.launch.command}' was not found.`,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
const makeAcpAgentRegistry = Effect.gen(function* () {
|
||||
const settings = yield* ServerSettingsService;
|
||||
|
||||
const getAgentServers: AcpAgentRegistryShape["getAgentServers"] = settings.getSettings.pipe(
|
||||
Effect.map((serverSettings) => serverSettings.providers.acp.agentServers),
|
||||
);
|
||||
|
||||
const listStatuses: AcpAgentRegistryShape["listStatuses"] = Effect.gen(function* () {
|
||||
const agents = yield* getAgentServers;
|
||||
const checkedAt = new Date().toISOString();
|
||||
return agents.map((agent) => toStatus(agent, checkedAt));
|
||||
});
|
||||
|
||||
return {
|
||||
getAgentServers,
|
||||
listStatuses,
|
||||
} satisfies AcpAgentRegistryShape;
|
||||
});
|
||||
|
||||
export const AcpAgentRegistryLive = Layer.effect(AcpAgentRegistry, makeAcpAgentRegistry);
|
||||
@@ -4,6 +4,8 @@ import { assertFailure } from "@effect/vitest/utils";
|
||||
|
||||
import { Effect, Layer, Stream } from "effect";
|
||||
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { AcpAdapter, type AcpAdapterShape } from "../Services/AcpAdapter.ts";
|
||||
import { ClaudeAdapter, ClaudeAdapterShape } from "../Services/ClaudeAdapter.ts";
|
||||
import { CodexAdapter, CodexAdapterShape } from "../Services/CodexAdapter.ts";
|
||||
import { CursorAdapter, CursorAdapterShape } from "../Services/CursorAdapter.ts";
|
||||
@@ -63,6 +65,23 @@ const fakeCursorAdapter: CursorAdapterShape = {
|
||||
streamEvents: Stream.empty,
|
||||
};
|
||||
|
||||
const fakeAcpAdapter: AcpAdapterShape = {
|
||||
provider: "acp",
|
||||
capabilities: { sessionModelSwitch: "unsupported" },
|
||||
startSession: vi.fn(),
|
||||
sendTurn: vi.fn(),
|
||||
interruptTurn: vi.fn(),
|
||||
respondToRequest: vi.fn(),
|
||||
respondToUserInput: vi.fn(),
|
||||
stopSession: vi.fn(),
|
||||
listSessions: vi.fn(),
|
||||
hasSession: vi.fn(),
|
||||
readThread: vi.fn(),
|
||||
rollbackThread: vi.fn(),
|
||||
stopAll: vi.fn(),
|
||||
streamEvents: Stream.empty,
|
||||
};
|
||||
|
||||
const layer = it.layer(
|
||||
Layer.mergeAll(
|
||||
Layer.provide(
|
||||
@@ -71,6 +90,8 @@ const layer = it.layer(
|
||||
Layer.succeed(CodexAdapter, fakeCodexAdapter),
|
||||
Layer.succeed(ClaudeAdapter, fakeClaudeAdapter),
|
||||
Layer.succeed(CursorAdapter, fakeCursorAdapter),
|
||||
Layer.succeed(AcpAdapter, fakeAcpAdapter),
|
||||
ServerSettingsService.layerTest(),
|
||||
),
|
||||
),
|
||||
NodeServices.layer,
|
||||
@@ -89,7 +110,7 @@ layer("ProviderAdapterRegistryLive", (it) => {
|
||||
assert.equal(cursor, fakeCursorAdapter);
|
||||
|
||||
const providers = yield* registry.listProviders();
|
||||
assert.deepEqual(providers, ["codex", "claudeAgent", "cursor"]);
|
||||
assert.deepEqual(providers, ["codex", "claudeAgent", "cursor", "acp"]);
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ import { Effect, Layer } from "effect";
|
||||
|
||||
import { ProviderUnsupportedError, type ProviderAdapterError } from "../Errors.ts";
|
||||
import type { ProviderAdapterShape } from "../Services/ProviderAdapter.ts";
|
||||
import { AcpAdapter } from "../Services/AcpAdapter.ts";
|
||||
import {
|
||||
ProviderAdapterRegistry,
|
||||
type ProviderAdapterRegistryShape,
|
||||
@@ -28,7 +29,7 @@ const makeProviderAdapterRegistry = (options?: ProviderAdapterRegistryLiveOption
|
||||
const adapters =
|
||||
options?.adapters !== undefined
|
||||
? options.adapters
|
||||
: [yield* CodexAdapter, yield* ClaudeAdapter, yield* CursorAdapter];
|
||||
: [yield* CodexAdapter, yield* ClaudeAdapter, yield* CursorAdapter, yield* AcpAdapter];
|
||||
const byProvider = new Map(adapters.map((adapter) => [adapter.provider, adapter]));
|
||||
|
||||
const getByProvider: ProviderAdapterRegistryShape["getByProvider"] = (provider) => {
|
||||
|
||||
@@ -766,16 +766,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
}
|
||||
return { stdout: "", stderr: "spawn ENOENT", code: 1 };
|
||||
}
|
||||
if (joined === "about --format json") {
|
||||
return {
|
||||
stdout: JSON.stringify({
|
||||
cliVersion: "2026.04.09-f2b0fcd",
|
||||
userEmail: null,
|
||||
}),
|
||||
stderr: "",
|
||||
code: 0,
|
||||
};
|
||||
}
|
||||
if (joined === "about") {
|
||||
return { stdout: "", stderr: "spawn ENOENT", code: 1 };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
import { ServiceMap } from "effect";
|
||||
|
||||
import type { ProviderAdapterError } from "../Errors.ts";
|
||||
import type { ProviderAdapterShape } from "./ProviderAdapter.ts";
|
||||
|
||||
export interface AcpAdapterShape extends ProviderAdapterShape<ProviderAdapterError> {
|
||||
readonly provider: "acp";
|
||||
}
|
||||
|
||||
export class AcpAdapter extends ServiceMap.Service<AcpAdapter, AcpAdapterShape>()(
|
||||
"t3/provider/Services/AcpAdapter",
|
||||
) {}
|
||||
@@ -0,0 +1,12 @@
|
||||
import type { AcpAgentServer, ServerAcpAgentStatus } from "@t3tools/contracts";
|
||||
import { ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
export interface AcpAgentRegistryShape {
|
||||
readonly listStatuses: Effect.Effect<ReadonlyArray<ServerAcpAgentStatus>, Error>;
|
||||
readonly getAgentServers: Effect.Effect<ReadonlyArray<AcpAgentServer>, Error>;
|
||||
}
|
||||
|
||||
export class AcpAgentRegistry extends ServiceMap.Service<AcpAgentRegistry, AcpAgentRegistryShape>()(
|
||||
"t3/provider/Services/AcpAgentRegistry",
|
||||
) {}
|
||||
@@ -0,0 +1,12 @@
|
||||
import type { AcpRegistryListResult } from "@t3tools/contracts";
|
||||
import { ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
export interface AcpRegistryClientShape {
|
||||
readonly listAgents: Effect.Effect<AcpRegistryListResult, Error>;
|
||||
}
|
||||
|
||||
export class AcpRegistryClient extends ServiceMap.Service<
|
||||
AcpRegistryClient,
|
||||
AcpRegistryClientShape
|
||||
>()("t3/provider/Services/AcpRegistryClient") {}
|
||||
@@ -32,7 +32,7 @@ describe("AcpJsonRpcConnection", () => {
|
||||
cwd: process.cwd(),
|
||||
mcpServers: [],
|
||||
});
|
||||
expect(newResult).toEqual({ sessionId: "mock-session-1" });
|
||||
expect(newResult).toMatchObject({ sessionId: "mock-session-1" });
|
||||
|
||||
const promptResult = yield* conn.request("session/prompt", {
|
||||
sessionId: "mock-session-1",
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
import {
|
||||
AcpRegistryIndex,
|
||||
type AcpRegistryAgent,
|
||||
type AcpRegistryListResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Layer, Schema } from "effect";
|
||||
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { AcpRegistryClient, type AcpRegistryClientShape } from "../Services/AcpRegistryClient.ts";
|
||||
|
||||
class AcpRegistryClientError extends Schema.TaggedErrorClass<AcpRegistryClientError>()(
|
||||
"AcpRegistryClientError",
|
||||
{
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {}
|
||||
|
||||
function toLaunchSpec(agent: AcpRegistryAgent) {
|
||||
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 ?? [])],
|
||||
},
|
||||
};
|
||||
}
|
||||
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 ?? [])],
|
||||
},
|
||||
};
|
||||
}
|
||||
return {
|
||||
supported: false as const,
|
||||
distributionType: "binaryUnsupported" as const,
|
||||
launch: null,
|
||||
};
|
||||
}
|
||||
|
||||
const makeAcpRegistryClient = Effect.gen(function* () {
|
||||
const settings = yield* ServerSettingsService;
|
||||
|
||||
const listAgents: AcpRegistryClientShape["listAgents"] = settings.getSettings.pipe(
|
||||
Effect.flatMap((serverSettings) =>
|
||||
Effect.tryPromise({
|
||||
try: async () => {
|
||||
const response = await fetch(serverSettings.providers.acp.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 : "Failed to fetch ACP registry",
|
||||
...(cause !== undefined ? { cause } : {}),
|
||||
}),
|
||||
}),
|
||||
),
|
||||
Effect.flatMap((raw) => Schema.decodeUnknownEffect(AcpRegistryIndex)(raw)),
|
||||
Effect.map(
|
||||
(registry): AcpRegistryListResult => ({
|
||||
registryVersion: registry.version,
|
||||
agents: registry.agents
|
||||
.map((agent) => {
|
||||
const resolved = toLaunchSpec(agent);
|
||||
return {
|
||||
agent,
|
||||
supported: resolved.supported,
|
||||
distributionType: resolved.distributionType,
|
||||
launch: resolved.launch,
|
||||
};
|
||||
})
|
||||
.toSorted((left, right) => left.agent.name.localeCompare(right.agent.name)),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
listAgents,
|
||||
} satisfies AcpRegistryClientShape;
|
||||
});
|
||||
|
||||
export const AcpRegistryClientLive = Layer.effect(AcpRegistryClient, makeAcpRegistryClient);
|
||||
@@ -20,6 +20,8 @@ import { ProviderUnsupportedError } from "./provider/Errors";
|
||||
import { makeClaudeAdapterLive } from "./provider/Layers/ClaudeAdapter";
|
||||
import { makeCodexAdapterLive } from "./provider/Layers/CodexAdapter";
|
||||
import { makeCursorAdapterLive } from "./provider/Layers/CursorAdapter";
|
||||
import { makeAcpAdapterLive } from "./provider/Layers/AcpAdapter";
|
||||
import { AcpAgentRegistryLive } from "./provider/Layers/AcpAgentRegistry";
|
||||
import { ProviderAdapterRegistryLive } from "./provider/Layers/ProviderAdapterRegistry";
|
||||
import { makeProviderServiceLive } from "./provider/Layers/ProviderService";
|
||||
import { ProviderSessionDirectoryLive } from "./provider/Layers/ProviderSessionDirectory";
|
||||
@@ -82,10 +84,14 @@ export function makeServerProviderLayer(): Layer.Layer<
|
||||
const cursorAdapterLayer = makeCursorAdapterLive(
|
||||
nativeEventLogger ? { nativeEventLogger } : undefined,
|
||||
);
|
||||
const acpAdapterLayer = makeAcpAdapterLive(
|
||||
nativeEventLogger ? { nativeEventLogger } : undefined,
|
||||
).pipe(Layer.provide(AcpAgentRegistryLive));
|
||||
const adapterRegistryLayer = ProviderAdapterRegistryLive.pipe(
|
||||
Layer.provide(codexAdapterLayer),
|
||||
Layer.provide(claudeAdapterLayer),
|
||||
Layer.provide(cursorAdapterLayer),
|
||||
Layer.provide(acpAdapterLayer),
|
||||
Layer.provideMerge(providerSessionDirectoryLayer),
|
||||
);
|
||||
return makeProviderServiceLive(
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -178,6 +178,7 @@ function createBaseServerConfig(): ServerConfig {
|
||||
skills: [],
|
||||
},
|
||||
],
|
||||
acpAgentServers: [],
|
||||
availableEditors: [],
|
||||
observability: {
|
||||
logsDirectoryPath: "/repo/project/.t3/logs",
|
||||
|
||||
@@ -104,7 +104,12 @@ import {
|
||||
import { newCommandId, newDraftId, newMessageId, newThreadId } from "~/lib/utils";
|
||||
import { getProviderModelCapabilities, resolveSelectableProvider } from "../providerModels";
|
||||
import { useSettings } from "../hooks/useSettings";
|
||||
import { resolveAppModelSelection } from "../modelSelection";
|
||||
import {
|
||||
getModelSelectionOptions,
|
||||
isBuiltInProviderKind,
|
||||
resolveAppModelSelection,
|
||||
resolveBuiltInSelectableProvider,
|
||||
} from "../modelSelection";
|
||||
import { isTerminalFocused } from "../lib/terminalFocus";
|
||||
import { deriveLogicalProjectKeyFromSettings } from "../logicalProject";
|
||||
import {
|
||||
@@ -1031,19 +1036,71 @@ export default function ChatView(props: ChatViewProps) {
|
||||
const activeEnvRuntimeState = useSavedEnvironmentRuntimeStore((s) =>
|
||||
activeThread?.environmentId ? s.byId[activeThread.environmentId] : null,
|
||||
);
|
||||
// Use the server config for the thread's environment. For the primary
|
||||
// environment fall back to the global atom; for remote environments use
|
||||
// the runtime state stored by the environment manager.
|
||||
const serverConfig =
|
||||
primaryEnvironmentId && activeThread?.environmentId === primaryEnvironmentId
|
||||
? primaryServerConfig
|
||||
: (activeEnvRuntimeState?.serverConfig ?? primaryServerConfig);
|
||||
const providerStatuses = serverConfig?.providers ?? EMPTY_PROVIDERS;
|
||||
const lockedProvider: ProviderKind | null = hasThreadStarted
|
||||
? (sessionProvider ?? threadProvider ?? selectedProviderByThreadId ?? null)
|
||||
: null;
|
||||
const serverConfigQuery = useQuery(serverConfigQueryOptions());
|
||||
const providerStatuses = serverConfigQuery.data?.providers ?? EMPTY_PROVIDERS;
|
||||
const acpAgents = settings.providers.acp.enabled
|
||||
? settings.providers.acp.agentServers.filter((agent) => agent.enabled)
|
||||
: [];
|
||||
const unlockedSelectedProvider = resolveSelectableProvider(
|
||||
providerStatuses,
|
||||
selectedProviderByThreadId ?? threadProvider ?? "codex",
|
||||
);
|
||||
const selectedProvider: ProviderKind = lockedProvider ?? unlockedSelectedProvider;
|
||||
const { modelOptions: composerModelOptions, selectedModel } = useEffectiveComposerModelState({
|
||||
threadId,
|
||||
providers: providerStatuses,
|
||||
selectedProvider,
|
||||
threadModelSelection: activeThread?.modelSelection,
|
||||
projectModelSelection: activeProject?.defaultModelSelection,
|
||||
settings,
|
||||
});
|
||||
const selectedProviderModels = getProviderModels(providerStatuses, selectedProvider);
|
||||
const composerProviderState = useMemo(
|
||||
() =>
|
||||
getComposerProviderState({
|
||||
provider: selectedProvider,
|
||||
model: selectedModel,
|
||||
models: selectedProviderModels,
|
||||
prompt,
|
||||
modelOptions: composerModelOptions,
|
||||
}),
|
||||
[composerModelOptions, prompt, selectedModel, selectedProvider, selectedProviderModels],
|
||||
);
|
||||
const selectedPromptEffort = composerProviderState.promptEffort;
|
||||
const selectedModelOptionsForDispatch = composerProviderState.modelOptionsForDispatch;
|
||||
const selectedAcpAgentId =
|
||||
(composerDraft.modelSelectionByProvider.acp?.provider === "acp"
|
||||
? composerDraft.modelSelectionByProvider.acp.agentServerId
|
||||
: undefined) ??
|
||||
(activeThread?.modelSelection.provider === "acp"
|
||||
? activeThread.modelSelection.agentServerId
|
||||
: undefined) ??
|
||||
(activeProject?.defaultModelSelection?.provider === "acp"
|
||||
? activeProject.defaultModelSelection.agentServerId
|
||||
: undefined) ??
|
||||
acpAgents[0]?.id ??
|
||||
null;
|
||||
const selectedModelSelection = useMemo<ModelSelection>(
|
||||
() =>
|
||||
selectedProvider === "acp"
|
||||
? {
|
||||
provider: "acp",
|
||||
agentServerId: selectedAcpAgentId ?? "default",
|
||||
model: "default",
|
||||
}
|
||||
: {
|
||||
provider: selectedProvider,
|
||||
model: selectedModel,
|
||||
...(selectedModelOptionsForDispatch
|
||||
? { options: selectedModelOptionsForDispatch }
|
||||
: {}),
|
||||
},
|
||||
[selectedAcpAgentId, selectedModel, selectedModelOptionsForDispatch, selectedProvider],
|
||||
);
|
||||
const selectedModelForPicker = selectedModel;
|
||||
const phase = derivePhase(activeThread?.session ?? null);
|
||||
const threadActivities = activeThread?.activities ?? EMPTY_ACTIVITIES;
|
||||
const workLogEntries = useMemo(
|
||||
@@ -1430,6 +1487,7 @@ export default function ChatView(props: ChatViewProps) {
|
||||
claudeAgent:
|
||||
providerStatuses.find((provider) => provider.provider === "claudeAgent")?.models ?? [],
|
||||
cursor: providerStatuses.find((provider) => provider.provider === "cursor")?.models ?? [],
|
||||
acp: [],
|
||||
}),
|
||||
[providerStatuses],
|
||||
);
|
||||
@@ -2062,8 +2120,8 @@ export default function ChatView(props: ChatViewProps) {
|
||||
input.modelSelection !== undefined &&
|
||||
(input.modelSelection.model !== serverThread.modelSelection.model ||
|
||||
input.modelSelection.provider !== serverThread.modelSelection.provider ||
|
||||
JSON.stringify(input.modelSelection.options ?? null) !==
|
||||
JSON.stringify(serverThread.modelSelection.options ?? null))
|
||||
JSON.stringify(getModelSelectionOptions(input.modelSelection) ?? null) !==
|
||||
JSON.stringify(getModelSelectionOptions(serverThread.modelSelection) ?? null))
|
||||
) {
|
||||
await api.orchestration.dispatchCommand({
|
||||
type: "thread.meta.update",
|
||||
@@ -2653,14 +2711,70 @@ export default function ChatView(props: ChatViewProps) {
|
||||
titleSeed = "New thread";
|
||||
}
|
||||
}
|
||||
const title = truncate(titleSeed);
|
||||
const threadCreateModelSelection = createModelSelection(
|
||||
ctxSelectedProvider,
|
||||
ctxSelectedModel ||
|
||||
activeProject.defaultModelSelection?.model ||
|
||||
DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
ctxSelectedModelSelection.options,
|
||||
);
|
||||
const title = truncateTitle(titleSeed);
|
||||
let threadCreateModelSelection: ModelSelection;
|
||||
if (selectedProvider === "acp") {
|
||||
threadCreateModelSelection = {
|
||||
provider: "acp",
|
||||
agentServerId:
|
||||
selectedModelSelection.provider === "acp"
|
||||
? selectedModelSelection.agentServerId
|
||||
: "default",
|
||||
model: selectedModelSelection.model,
|
||||
};
|
||||
} else {
|
||||
const selectedOptions = getModelSelectionOptions(selectedModelSelection);
|
||||
threadCreateModelSelection = {
|
||||
provider: selectedProvider,
|
||||
model:
|
||||
selectedModel ||
|
||||
activeProject.defaultModelSelection?.model ||
|
||||
DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
...(selectedOptions ? { options: selectedOptions } : {}),
|
||||
} as ModelSelection;
|
||||
}
|
||||
|
||||
if (isLocalDraftThread) {
|
||||
await api.orchestration.dispatchCommand({
|
||||
type: "thread.create",
|
||||
commandId: newCommandId(),
|
||||
threadId: threadIdForSend,
|
||||
projectId: activeProject.id,
|
||||
title,
|
||||
modelSelection: threadCreateModelSelection,
|
||||
runtimeMode,
|
||||
interactionMode,
|
||||
branch: nextThreadBranch,
|
||||
worktreePath: nextThreadWorktreePath,
|
||||
createdAt: activeThread.createdAt,
|
||||
});
|
||||
createdServerThreadForLocalDraft = true;
|
||||
}
|
||||
|
||||
let setupScript: ProjectScript | null = null;
|
||||
if (baseBranchForWorktree) {
|
||||
setupScript = setupProjectScript(activeProject.scripts);
|
||||
}
|
||||
if (setupScript) {
|
||||
let shouldRunSetupScript = false;
|
||||
if (isServerThread) {
|
||||
shouldRunSetupScript = true;
|
||||
} else {
|
||||
if (createdServerThreadForLocalDraft) {
|
||||
shouldRunSetupScript = true;
|
||||
}
|
||||
}
|
||||
if (shouldRunSetupScript) {
|
||||
const setupScriptOptions: Parameters<typeof runProjectScript>[1] = {
|
||||
worktreePath: nextThreadWorktreePath,
|
||||
rememberAsLastInvoked: false,
|
||||
};
|
||||
if (nextThreadWorktreePath) {
|
||||
setupScriptOptions.cwd = nextThreadWorktreePath;
|
||||
}
|
||||
await runProjectScript(setupScript, setupScriptOptions);
|
||||
}
|
||||
}
|
||||
|
||||
// Auto-title from first message
|
||||
if (isFirstMessage && isServerThread) {
|
||||
@@ -3224,7 +3338,11 @@ export default function ChatView(props: ChatViewProps) {
|
||||
scheduleComposerFocus();
|
||||
return;
|
||||
}
|
||||
const resolvedProvider = resolveSelectableProvider(providerStatuses, provider);
|
||||
if (!isBuiltInProviderKind(provider)) {
|
||||
scheduleComposerFocus();
|
||||
return;
|
||||
}
|
||||
const resolvedProvider = resolveBuiltInSelectableProvider(providerStatuses, provider);
|
||||
const resolvedModel = resolveAppModelSelection(
|
||||
resolvedProvider,
|
||||
settings,
|
||||
@@ -3252,10 +3370,29 @@ export default function ChatView(props: ChatViewProps) {
|
||||
settings,
|
||||
],
|
||||
);
|
||||
const onEnvModeChange = useCallback(
|
||||
(mode: DraftThreadEnvMode) => {
|
||||
if (canOverrideServerThreadEnvMode) {
|
||||
setPendingServerThreadEnvMode(mode);
|
||||
const onAcpAgentSelect = useCallback(
|
||||
(agentServerId: string) => {
|
||||
if (!activeThread) return;
|
||||
const nextModelSelection: ModelSelection = {
|
||||
provider: "acp",
|
||||
agentServerId,
|
||||
model: "default",
|
||||
};
|
||||
setComposerDraftModelSelection(activeThread.id, nextModelSelection);
|
||||
setStickyComposerModelSelection(nextModelSelection);
|
||||
scheduleComposerFocus();
|
||||
},
|
||||
[
|
||||
activeThread,
|
||||
scheduleComposerFocus,
|
||||
setComposerDraftModelSelection,
|
||||
setStickyComposerModelSelection,
|
||||
],
|
||||
);
|
||||
const setPromptFromTraits = useCallback(
|
||||
(nextPrompt: string) => {
|
||||
const currentPrompt = promptRef.current;
|
||||
if (nextPrompt === currentPrompt) {
|
||||
scheduleComposerFocus();
|
||||
return;
|
||||
}
|
||||
@@ -3631,6 +3768,8 @@ export default function ChatView(props: ChatViewProps) {
|
||||
lockedProvider={lockedProvider}
|
||||
providers={providerStatuses}
|
||||
modelOptionsByProvider={modelOptionsByProvider}
|
||||
acpAgents={acpAgents}
|
||||
activeAcpAgentId={selectedAcpAgentId}
|
||||
{...(composerProviderState.modelPickerIconClassName
|
||||
? {
|
||||
activeProviderIconClassName:
|
||||
@@ -3638,6 +3777,7 @@ export default function ChatView(props: ChatViewProps) {
|
||||
}
|
||||
: {})}
|
||||
onProviderModelChange={onProviderModelSelect}
|
||||
onAcpAgentSelect={onAcpAgentSelect}
|
||||
/>
|
||||
|
||||
{isComposerFooterCompact ? (
|
||||
|
||||
@@ -84,6 +84,7 @@ function createBaseServerConfig(): ServerConfig {
|
||||
skills: [],
|
||||
},
|
||||
],
|
||||
acpAgentServers: [],
|
||||
availableEditors: [],
|
||||
observability: {
|
||||
logsDirectoryPath: "/repo/project/.t3/logs",
|
||||
@@ -100,6 +101,7 @@ function createBaseServerConfig(): ServerConfig {
|
||||
codex: { enabled: true, binaryPath: "", homePath: "", customModels: [] },
|
||||
claudeAgent: { enabled: true, binaryPath: "", customModels: [] },
|
||||
cursor: { enabled: true, binaryPath: "", apiEndpoint: "", customModels: [] },
|
||||
acp: { enabled: true, registryUrl: "", agentServers: [] },
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
@@ -8,6 +8,7 @@ import { render } from "vitest-browser-react";
|
||||
import { CompactComposerControlsMenu } from "./CompactComposerControlsMenu";
|
||||
import { TraitsMenuContent } from "./TraitsPicker";
|
||||
import { useComposerDraftStore } from "../../composerDraftStore";
|
||||
import { getModelSelectionOptions } from "../../modelSelection";
|
||||
|
||||
const LOCAL_ENVIRONMENT_ID = EnvironmentId.make("environment-local");
|
||||
|
||||
@@ -18,24 +19,19 @@ async function mountMenu(props?: { modelSelection?: ModelSelection; prompt?: str
|
||||
const provider = props?.modelSelection?.provider ?? "claudeAgent";
|
||||
const model = props?.modelSelection?.model ?? DEFAULT_MODEL_BY_PROVIDER[provider];
|
||||
|
||||
useComposerDraftStore.setState({
|
||||
draftsByThreadKey: {
|
||||
[threadKey]: {
|
||||
prompt: props?.prompt ?? "",
|
||||
images: [],
|
||||
nonPersistedImageIds: [],
|
||||
persistedAttachments: [],
|
||||
terminalContexts: [],
|
||||
modelSelectionByProvider: {
|
||||
[provider]: {
|
||||
provider,
|
||||
model,
|
||||
...(props?.modelSelection?.options ? { options: props.modelSelection.options } : {}),
|
||||
},
|
||||
},
|
||||
activeProvider: provider,
|
||||
runtimeMode: null,
|
||||
interactionMode: null,
|
||||
draftsByThreadId[threadId] = {
|
||||
prompt: props?.prompt ?? "",
|
||||
images: [],
|
||||
nonPersistedImageIds: [],
|
||||
persistedAttachments: [],
|
||||
terminalContexts: [],
|
||||
modelSelectionByProvider: {
|
||||
[provider]: {
|
||||
provider,
|
||||
model,
|
||||
...(getModelSelectionOptions(props?.modelSelection)
|
||||
? { options: getModelSelectionOptions(props?.modelSelection) }
|
||||
: {}),
|
||||
},
|
||||
},
|
||||
draftThreadsByThreadKey: {},
|
||||
@@ -44,7 +40,7 @@ async function mountMenu(props?: { modelSelection?: ModelSelection; prompt?: str
|
||||
const host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
const onPromptChange = vi.fn();
|
||||
const providerOptions = props?.modelSelection?.options;
|
||||
const providerOptions = getModelSelectionOptions(props?.modelSelection);
|
||||
const models =
|
||||
provider === "claudeAgent"
|
||||
? [
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { type ProviderKind, type ServerProvider } from "@t3tools/contracts";
|
||||
import { type AcpAgentServer, type ProviderKind, type ServerProvider } from "@t3tools/contracts";
|
||||
import { resolveModelSlugForProvider, resolveSelectableModel } from "@t3tools/shared/model";
|
||||
import { memo, useState } from "react";
|
||||
import type { VariantProps } from "class-variance-authority";
|
||||
import { type ProviderPickerKind, PROVIDER_OPTIONS } from "../../session-logic";
|
||||
import { ChevronDownIcon } from "lucide-react";
|
||||
import { type BuiltInProviderKind } from "../../modelSelection";
|
||||
import { BotIcon, ChevronDownIcon } from "lucide-react";
|
||||
import { Button, buttonVariants } from "../ui/button";
|
||||
import {
|
||||
Menu,
|
||||
@@ -23,18 +24,19 @@ import { cn } from "~/lib/utils";
|
||||
import { getProviderSnapshot } from "../../providerModels";
|
||||
|
||||
function isAvailableProviderOption(option: (typeof PROVIDER_OPTIONS)[number]): option is {
|
||||
value: ProviderKind;
|
||||
value: BuiltInProviderKind;
|
||||
label: string;
|
||||
available: true;
|
||||
} {
|
||||
return option.available;
|
||||
}
|
||||
|
||||
const PROVIDER_ICON_BY_PROVIDER: Record<ProviderPickerKind, Icon> = {
|
||||
const PROVIDER_ICON_BY_PROVIDER: Record<ProviderPickerKind | "acp", Icon> = {
|
||||
codex: OpenAI,
|
||||
claudeAgent: ClaudeAI,
|
||||
opencode: OpenCodeIcon,
|
||||
cursor: CursorIcon,
|
||||
acp: OpenCodeIcon,
|
||||
};
|
||||
|
||||
export const AVAILABLE_PROVIDER_OPTIONS = PROVIDER_OPTIONS.filter(isAvailableProviderOption);
|
||||
@@ -45,15 +47,78 @@ function providerIconClassName(
|
||||
provider: ProviderKind | ProviderPickerKind,
|
||||
fallbackClassName: string,
|
||||
): string {
|
||||
return provider === "claudeAgent" ? "text-[#d97757]" : fallbackClassName;
|
||||
if (provider === "claudeAgent") {
|
||||
return "text-[#d97757]";
|
||||
}
|
||||
if (provider === "acp") {
|
||||
return "text-foreground/85";
|
||||
}
|
||||
return fallbackClassName;
|
||||
}
|
||||
|
||||
const AcpAgentIcon = memo(function AcpAgentIcon(props: {
|
||||
iconUrl?: string | undefined;
|
||||
className?: string | undefined;
|
||||
fallbackClassName?: string | undefined;
|
||||
}) {
|
||||
const [failedIconUrl, setFailedIconUrl] = useState<string | null>(null);
|
||||
const iconUrl =
|
||||
props.iconUrl && props.iconUrl !== failedIconUrl
|
||||
? props.iconUrl.trim() || undefined
|
||||
: undefined;
|
||||
|
||||
if (iconUrl) {
|
||||
return (
|
||||
<img
|
||||
aria-hidden="true"
|
||||
src={iconUrl}
|
||||
alt=""
|
||||
className={cn(
|
||||
"size-4 shrink-0 object-contain opacity-80 dark:invert dark:opacity-85",
|
||||
props.className,
|
||||
)}
|
||||
onError={() => setFailedIconUrl(iconUrl)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<BotIcon
|
||||
aria-hidden="true"
|
||||
className={cn(
|
||||
"size-4 shrink-0",
|
||||
providerIconClassName("acp", props.fallbackClassName ?? "text-foreground/85"),
|
||||
props.className,
|
||||
)}
|
||||
/>
|
||||
);
|
||||
});
|
||||
|
||||
const AcpAgentLabel = memo(function AcpAgentLabel(props: {
|
||||
name: string;
|
||||
iconUrl?: string | undefined;
|
||||
iconClassName?: string | undefined;
|
||||
}) {
|
||||
return (
|
||||
<span className="inline-flex min-w-0 items-center gap-2">
|
||||
<AcpAgentIcon
|
||||
iconUrl={props.iconUrl}
|
||||
className={props.iconClassName}
|
||||
fallbackClassName="text-foreground/85"
|
||||
/>
|
||||
<span className="truncate">{props.name}</span>
|
||||
</span>
|
||||
);
|
||||
});
|
||||
|
||||
export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
|
||||
provider: ProviderKind;
|
||||
model: string;
|
||||
lockedProvider: ProviderKind | null;
|
||||
providers?: ReadonlyArray<ServerProvider>;
|
||||
modelOptionsByProvider: Record<ProviderKind, ReadonlyArray<{ slug: string; name: string }>>;
|
||||
acpAgents?: ReadonlyArray<Pick<AcpAgentServer, "id" | "name" | "enabled" | "iconUrl">>;
|
||||
activeAcpAgentId?: string | null;
|
||||
activeProviderIconClassName?: string;
|
||||
compact?: boolean;
|
||||
disabled?: boolean;
|
||||
@@ -61,15 +126,22 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
|
||||
triggerClassName?: string;
|
||||
disabledReason?: string;
|
||||
onProviderModelChange: (provider: ProviderKind, model: string) => void;
|
||||
onAcpAgentSelect?: (agentServerId: string) => void;
|
||||
}) {
|
||||
const [isMenuOpen, setIsMenuOpen] = useState(false);
|
||||
const activeProvider = props.lockedProvider ?? props.provider;
|
||||
const selectedProviderOptions = props.modelOptionsByProvider[activeProvider];
|
||||
const selectedModelValue =
|
||||
resolveSelectableModel(activeProvider, props.model, selectedProviderOptions) ?? props.model;
|
||||
activeProvider === "acp"
|
||||
? (props.activeAcpAgentId ?? props.model)
|
||||
: (resolveSelectableModel(activeProvider, props.model, selectedProviderOptions) ??
|
||||
props.model);
|
||||
const selectedAcpAgent = props.acpAgents?.find((agent) => agent.id === props.activeAcpAgentId);
|
||||
const selectedModelLabel =
|
||||
selectedProviderOptions.find((option) => option.slug === selectedModelValue)?.name ??
|
||||
props.model;
|
||||
activeProvider === "acp"
|
||||
? (selectedAcpAgent?.name ?? "ACP Agent")
|
||||
: (selectedProviderOptions.find((option) => option.slug === selectedModelValue)?.name ??
|
||||
props.model);
|
||||
const ProviderIcon = PROVIDER_ICON_BY_PROVIDER[activeProvider];
|
||||
const handleModelChange = (provider: ProviderKind, value: string) => {
|
||||
if (props.disabled) return;
|
||||
@@ -81,6 +153,11 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
|
||||
props.onProviderModelChange(provider, resolvedModel);
|
||||
setIsMenuOpen(false);
|
||||
};
|
||||
const handleAcpAgentChange = (agentServerId: string) => {
|
||||
if (props.disabled || !props.onAcpAgentSelect) return;
|
||||
props.onAcpAgentSelect(agentServerId);
|
||||
setIsMenuOpen(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<Menu
|
||||
@@ -115,36 +192,64 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
|
||||
props.compact ? "max-w-36 sm:pl-1" : undefined,
|
||||
)}
|
||||
>
|
||||
<ProviderIcon
|
||||
aria-hidden="true"
|
||||
className={cn(
|
||||
"size-4 shrink-0",
|
||||
providerIconClassName(activeProvider, "text-muted-foreground/70"),
|
||||
props.activeProviderIconClassName,
|
||||
)}
|
||||
/>
|
||||
{activeProvider === "acp" ? (
|
||||
<AcpAgentIcon
|
||||
iconUrl={selectedAcpAgent?.iconUrl}
|
||||
className={props.activeProviderIconClassName}
|
||||
/>
|
||||
) : (
|
||||
<ProviderIcon
|
||||
aria-hidden="true"
|
||||
className={cn(
|
||||
"size-4 shrink-0",
|
||||
providerIconClassName(activeProvider, "text-muted-foreground/70"),
|
||||
props.activeProviderIconClassName,
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
<span className="min-w-0 flex-1 truncate">{selectedModelLabel}</span>
|
||||
<ChevronDownIcon aria-hidden="true" className="size-3 shrink-0 opacity-60" />
|
||||
</span>
|
||||
</MenuTrigger>
|
||||
<MenuPopup align="start">
|
||||
{props.lockedProvider !== null ? (
|
||||
<MenuGroup>
|
||||
<MenuRadioGroup
|
||||
value={selectedModelValue}
|
||||
onValueChange={(value) => handleModelChange(props.lockedProvider!, value)}
|
||||
>
|
||||
{props.modelOptionsByProvider[props.lockedProvider].map((modelOption) => (
|
||||
<MenuRadioItem
|
||||
key={`${props.lockedProvider}:${modelOption.slug}`}
|
||||
value={modelOption.slug}
|
||||
onClick={() => setIsMenuOpen(false)}
|
||||
>
|
||||
{modelOption.name}
|
||||
</MenuRadioItem>
|
||||
))}
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
props.lockedProvider === "acp" ? (
|
||||
<MenuGroup>
|
||||
<MenuRadioGroup
|
||||
value={props.activeAcpAgentId ?? ""}
|
||||
onValueChange={handleAcpAgentChange}
|
||||
>
|
||||
{(props.acpAgents ?? [])
|
||||
.filter((agent) => agent.enabled)
|
||||
.map((agent) => (
|
||||
<MenuRadioItem
|
||||
key={agent.id}
|
||||
value={agent.id}
|
||||
onClick={() => setIsMenuOpen(false)}
|
||||
>
|
||||
<AcpAgentLabel name={agent.name} iconUrl={agent.iconUrl} />
|
||||
</MenuRadioItem>
|
||||
))}
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
) : (
|
||||
<MenuGroup>
|
||||
<MenuRadioGroup
|
||||
value={selectedModelValue}
|
||||
onValueChange={(value) => handleModelChange(props.lockedProvider!, value)}
|
||||
>
|
||||
{props.modelOptionsByProvider[props.lockedProvider].map((modelOption) => (
|
||||
<MenuRadioItem
|
||||
key={`${props.lockedProvider}:${modelOption.slug}`}
|
||||
value={modelOption.slug}
|
||||
onClick={() => setIsMenuOpen(false)}
|
||||
>
|
||||
{modelOption.name}
|
||||
</MenuRadioItem>
|
||||
))}
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
)
|
||||
) : (
|
||||
<>
|
||||
{AVAILABLE_PROVIDER_OPTIONS.map((option) => {
|
||||
@@ -215,6 +320,39 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
|
||||
</MenuSub>
|
||||
);
|
||||
})}
|
||||
{(props.acpAgents?.some((agent) => agent.enabled) ?? false) && <MenuDivider />}
|
||||
<MenuSub>
|
||||
<MenuSubTrigger>
|
||||
<OpenCodeIcon
|
||||
aria-hidden="true"
|
||||
className={cn(
|
||||
"size-4 shrink-0",
|
||||
providerIconClassName("acp", "text-muted-foreground/85"),
|
||||
)}
|
||||
/>
|
||||
ACP Agents
|
||||
</MenuSubTrigger>
|
||||
<MenuSubPopup className="[--available-height:min(24rem,70vh)]" sideOffset={4}>
|
||||
<MenuGroup>
|
||||
<MenuRadioGroup
|
||||
value={props.activeAcpAgentId ?? ""}
|
||||
onValueChange={handleAcpAgentChange}
|
||||
>
|
||||
{(props.acpAgents ?? [])
|
||||
.filter((agent) => agent.enabled)
|
||||
.map((agent) => (
|
||||
<MenuRadioItem
|
||||
key={agent.id}
|
||||
value={agent.id}
|
||||
onClick={() => setIsMenuOpen(false)}
|
||||
>
|
||||
<AcpAgentLabel name={agent.name} iconUrl={agent.iconUrl} />
|
||||
</MenuRadioItem>
|
||||
))}
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
</MenuSubPopup>
|
||||
</MenuSub>
|
||||
{UNAVAILABLE_PROVIDER_OPTIONS.length > 0 && <MenuDivider />}
|
||||
{UNAVAILABLE_PROVIDER_OPTIONS.map((option) => {
|
||||
const OptionIcon = PROVIDER_ICON_BY_PROVIDER[option.value];
|
||||
|
||||
@@ -127,6 +127,7 @@ function getProviderStateFromCapabilities(
|
||||
codex: normalizeCodexModelOptionsWithCapabilities(caps, providerOptions),
|
||||
cursor: normalizeCursorModelOptionsWithCapabilities(caps, providerOptions),
|
||||
claudeAgent: normalizeClaudeModelOptionsWithCapabilities(caps, providerOptions),
|
||||
acp: undefined,
|
||||
}[provider];
|
||||
|
||||
// Ultrathink styling (driven by capabilities data, not provider identity)
|
||||
@@ -282,6 +283,15 @@ const composerProviderRegistry: Record<ProviderKind, ProviderRegistryEntry> = {
|
||||
/>
|
||||
) : null,
|
||||
},
|
||||
acp: {
|
||||
getState: (input) => ({
|
||||
provider: input.provider,
|
||||
promptEffort: null,
|
||||
modelOptionsForDispatch: undefined,
|
||||
}),
|
||||
renderTraitsMenuContent: () => null,
|
||||
renderTraitsPicker: () => null,
|
||||
},
|
||||
};
|
||||
|
||||
export function getComposerProviderState(input: ComposerProviderStateInput): ComposerProviderState {
|
||||
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
DraftId,
|
||||
} from "./composerDraftStore";
|
||||
import { removeLocalStorageItem, setLocalStorageItem } from "./hooks/useLocalStorage";
|
||||
import { getModelSelectionOptions } from "./modelSelection";
|
||||
import {
|
||||
INLINE_TERMINAL_CONTEXT_PLACEHOLDER,
|
||||
insertInlineTerminalContextPlaceholder,
|
||||
@@ -93,7 +94,7 @@ function resetComposerDraftStore() {
|
||||
function modelSelection(
|
||||
provider: "codex" | "claudeAgent" | "cursor",
|
||||
model: string,
|
||||
options?: ModelSelection["options"],
|
||||
options?: NonNullable<ReturnType<typeof getModelSelectionOptions>>,
|
||||
): ModelSelection {
|
||||
return {
|
||||
provider,
|
||||
@@ -1096,9 +1097,13 @@ describe("composerDraftStore modelSelection", () => {
|
||||
// Now set options for only codex — claudeAgent should be untouched
|
||||
store.setModelOptions(threadRef, providerModelOptions({ codex: { reasoningEffort: "xhigh" } }));
|
||||
|
||||
const draft = draftFor(threadId, TEST_ENVIRONMENT_ID);
|
||||
expect(draft?.modelSelectionByProvider.codex?.options).toEqual({ reasoningEffort: "xhigh" });
|
||||
expect(draft?.modelSelectionByProvider.claudeAgent?.options).toEqual({ effort: "max" });
|
||||
const draft = useComposerDraftStore.getState().draftsByThreadId[threadId];
|
||||
expect(getModelSelectionOptions(draft?.modelSelectionByProvider.codex)).toEqual({
|
||||
reasoningEffort: "xhigh",
|
||||
});
|
||||
expect(getModelSelectionOptions(draft?.modelSelectionByProvider.claudeAgent)).toEqual({
|
||||
effort: "max",
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves other provider options when switching the active model selection", () => {
|
||||
@@ -1118,7 +1123,9 @@ describe("composerDraftStore modelSelection", () => {
|
||||
expect(draft?.modelSelectionByProvider.claudeAgent).toEqual(
|
||||
modelSelection("claudeAgent", "claude-opus-4-6", { effort: "max" }),
|
||||
);
|
||||
expect(draft?.modelSelectionByProvider.codex?.options).toEqual({ fastMode: true });
|
||||
expect(getModelSelectionOptions(draft?.modelSelectionByProvider.codex)).toEqual({
|
||||
fastMode: true,
|
||||
});
|
||||
expect(draft?.activeProvider).toBe("claudeAgent");
|
||||
});
|
||||
|
||||
@@ -1284,7 +1291,9 @@ describe("composerDraftStore provider-scoped option updates", () => {
|
||||
expect(draft?.modelSelectionByProvider.codex).toEqual(
|
||||
modelSelection("codex", "gpt-5.3-codex", { reasoningEffort: "medium" }),
|
||||
);
|
||||
expect(draft?.modelSelectionByProvider.claudeAgent?.options).toEqual({ effort: "max" });
|
||||
expect(getModelSelectionOptions(draft?.modelSelectionByProvider.claudeAgent)).toEqual({
|
||||
effort: "max",
|
||||
});
|
||||
expect(draft?.activeProvider).toBe("codex");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -392,7 +392,7 @@ interface ComposerDraftModelState {
|
||||
function providerModelOptionsFromSelection(
|
||||
modelSelection: ModelSelection | null | undefined,
|
||||
): ProviderModelOptions | null {
|
||||
if (!modelSelection?.options) {
|
||||
if (modelSelection?.provider === "acp" || !modelSelection?.options) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -407,7 +407,7 @@ function modelSelectionByProviderToOptions(
|
||||
if (!map) return null;
|
||||
const result: Record<string, unknown> = {};
|
||||
for (const [provider, selection] of Object.entries(map)) {
|
||||
if (selection?.options) {
|
||||
if (selection?.provider !== "acp" && selection?.options) {
|
||||
result[provider] = selection.options;
|
||||
}
|
||||
}
|
||||
@@ -533,7 +533,9 @@ function shouldRemoveDraft(draft: ComposerThreadDraftState): boolean {
|
||||
}
|
||||
|
||||
function normalizeProviderKind(value: unknown): ProviderKind | null {
|
||||
return value === "codex" || value === "claudeAgent" || value === "cursor" ? value : null;
|
||||
return value === "codex" || value === "claudeAgent" || value === "cursor" || value === "acp"
|
||||
? value
|
||||
: null;
|
||||
}
|
||||
|
||||
function normalizeProviderModelOptions(
|
||||
@@ -669,6 +671,17 @@ function normalizeModelSelection(
|
||||
if (!model) {
|
||||
return null;
|
||||
}
|
||||
if (provider === "acp") {
|
||||
const agentServerId = candidate?.agentServerId;
|
||||
if (typeof agentServerId !== "string" || agentServerId.trim().length === 0) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
provider,
|
||||
model,
|
||||
agentServerId: agentServerId.trim(),
|
||||
};
|
||||
}
|
||||
const modelOptions = normalizeProviderModelOptions(
|
||||
candidate?.options ? { [provider]: candidate.options } : legacy?.modelOptions,
|
||||
provider,
|
||||
@@ -687,6 +700,9 @@ function legacySyncModelSelectionOptions(
|
||||
if (modelSelection === null) {
|
||||
return null;
|
||||
}
|
||||
if (modelSelection.provider === "acp") {
|
||||
return modelSelection;
|
||||
}
|
||||
const options = modelOptions?.[modelSelection.provider];
|
||||
return createModelSelection(modelSelection.provider, modelSelection.model, options);
|
||||
}
|
||||
@@ -695,7 +711,7 @@ function legacyMergeModelSelectionIntoProviderModelOptions(
|
||||
modelSelection: ModelSelection | null,
|
||||
currentModelOptions: ProviderModelOptions | null | undefined,
|
||||
): ProviderModelOptions | null {
|
||||
if (modelSelection?.options === undefined) {
|
||||
if (modelSelection?.provider === "acp" || modelSelection?.options === undefined) {
|
||||
return normalizeProviderModelOptions(currentModelOptions);
|
||||
}
|
||||
return legacyReplaceProviderModelOptions(
|
||||
@@ -763,6 +779,23 @@ export function deriveEffectiveComposerModelState(input: {
|
||||
projectModelSelection: ModelSelection | null | undefined;
|
||||
settings: UnifiedSettings;
|
||||
}): EffectiveComposerModelState {
|
||||
if (input.selectedProvider === "acp") {
|
||||
const activeSelection = input.draft?.modelSelectionByProvider?.acp;
|
||||
const selectedAgentServerId =
|
||||
(activeSelection?.provider === "acp" ? activeSelection.agentServerId : undefined) ??
|
||||
(input.threadModelSelection?.provider === "acp"
|
||||
? input.threadModelSelection.agentServerId
|
||||
: undefined) ??
|
||||
(input.projectModelSelection?.provider === "acp"
|
||||
? input.projectModelSelection.agentServerId
|
||||
: undefined) ??
|
||||
input.settings.providers.acp.agentServers.find((agent) => agent.enabled)?.id ??
|
||||
"default";
|
||||
return {
|
||||
selectedModel: selectedAgentServerId,
|
||||
modelOptions: null,
|
||||
};
|
||||
}
|
||||
const baseModel =
|
||||
normalizeModelSlug(
|
||||
input.threadModelSelection?.model ?? input.projectModelSelection?.model,
|
||||
@@ -1803,28 +1836,515 @@ function toHydratedDraftThreadState(
|
||||
|
||||
const composerDraftStore = create<ComposerDraftStoreState>()(
|
||||
persist(
|
||||
(setBase, get) => {
|
||||
const set = setBase;
|
||||
|
||||
return {
|
||||
draftsByThreadKey: {},
|
||||
draftThreadsByThreadKey: {},
|
||||
logicalProjectDraftThreadKeyByLogicalProjectKey: {},
|
||||
stickyModelSelectionByProvider: {},
|
||||
stickyActiveProvider: null,
|
||||
getComposerDraft: (target) => getComposerDraftState(get(), target),
|
||||
getDraftThreadByLogicalProjectKey: (logicalProjectKey) => {
|
||||
return get().getDraftSessionByLogicalProjectKey(logicalProjectKey);
|
||||
},
|
||||
getDraftSessionByLogicalProjectKey: (logicalProjectKey) => {
|
||||
const normalizedLogicalProjectKey = logicalProjectDraftKey(logicalProjectKey);
|
||||
if (normalizedLogicalProjectKey.length === 0) {
|
||||
return null;
|
||||
(set, get) => ({
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
stickyModelSelectionByProvider: {},
|
||||
stickyActiveProvider: null,
|
||||
getDraftThreadByProjectId: (projectId) => {
|
||||
if (projectId.length === 0) {
|
||||
return null;
|
||||
}
|
||||
const threadId = get().projectDraftThreadIdByProjectId[projectId];
|
||||
if (!threadId) {
|
||||
return null;
|
||||
}
|
||||
const draftThread = get().draftThreadsByThreadId[threadId];
|
||||
if (!draftThread || draftThread.projectId !== projectId) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
threadId,
|
||||
...draftThread,
|
||||
};
|
||||
},
|
||||
getDraftThread: (threadId) => {
|
||||
if (threadId.length === 0) {
|
||||
return null;
|
||||
}
|
||||
return get().draftThreadsByThreadId[threadId] ?? null;
|
||||
},
|
||||
setProjectDraftThreadId: (projectId, threadId, options) => {
|
||||
if (projectId.length === 0 || threadId.length === 0) {
|
||||
return;
|
||||
}
|
||||
set((state) => {
|
||||
const existingThread = state.draftThreadsByThreadId[threadId];
|
||||
const previousThreadIdForProject = state.projectDraftThreadIdByProjectId[projectId];
|
||||
const nextWorktreePath =
|
||||
options?.worktreePath === undefined
|
||||
? (existingThread?.worktreePath ?? null)
|
||||
: (options.worktreePath ?? null);
|
||||
const nextDraftThread: DraftThreadState = {
|
||||
projectId,
|
||||
createdAt: options?.createdAt ?? existingThread?.createdAt ?? new Date().toISOString(),
|
||||
runtimeMode:
|
||||
options?.runtimeMode ?? existingThread?.runtimeMode ?? DEFAULT_RUNTIME_MODE,
|
||||
interactionMode:
|
||||
options?.interactionMode ??
|
||||
existingThread?.interactionMode ??
|
||||
DEFAULT_INTERACTION_MODE,
|
||||
branch:
|
||||
options?.branch === undefined
|
||||
? (existingThread?.branch ?? null)
|
||||
: (options.branch ?? null),
|
||||
worktreePath: nextWorktreePath,
|
||||
envMode:
|
||||
options?.envMode ??
|
||||
(nextWorktreePath ? "worktree" : (existingThread?.envMode ?? "local")),
|
||||
};
|
||||
const hasSameProjectMapping = previousThreadIdForProject === threadId;
|
||||
const hasSameDraftThread =
|
||||
existingThread &&
|
||||
existingThread.projectId === nextDraftThread.projectId &&
|
||||
existingThread.createdAt === nextDraftThread.createdAt &&
|
||||
existingThread.runtimeMode === nextDraftThread.runtimeMode &&
|
||||
existingThread.interactionMode === nextDraftThread.interactionMode &&
|
||||
existingThread.branch === nextDraftThread.branch &&
|
||||
existingThread.worktreePath === nextDraftThread.worktreePath &&
|
||||
existingThread.envMode === nextDraftThread.envMode;
|
||||
if (hasSameProjectMapping && hasSameDraftThread) {
|
||||
return state;
|
||||
}
|
||||
const draftId =
|
||||
get().logicalProjectDraftThreadKeyByLogicalProjectKey[normalizedLogicalProjectKey];
|
||||
if (!draftId) {
|
||||
return null;
|
||||
const nextProjectDraftThreadIdByProjectId: Record<ProjectId, ThreadId> = {
|
||||
...state.projectDraftThreadIdByProjectId,
|
||||
[projectId]: threadId,
|
||||
};
|
||||
const nextDraftThreadsByThreadId: Record<ThreadId, DraftThreadState> = {
|
||||
...state.draftThreadsByThreadId,
|
||||
[threadId]: nextDraftThread,
|
||||
};
|
||||
let nextDraftsByThreadId = state.draftsByThreadId;
|
||||
if (
|
||||
previousThreadIdForProject &&
|
||||
previousThreadIdForProject !== threadId &&
|
||||
!Object.values(nextProjectDraftThreadIdByProjectId).includes(previousThreadIdForProject)
|
||||
) {
|
||||
delete nextDraftThreadsByThreadId[previousThreadIdForProject];
|
||||
if (state.draftsByThreadId[previousThreadIdForProject] !== undefined) {
|
||||
nextDraftsByThreadId = { ...state.draftsByThreadId };
|
||||
delete nextDraftsByThreadId[previousThreadIdForProject];
|
||||
}
|
||||
}
|
||||
return {
|
||||
draftsByThreadId: nextDraftsByThreadId,
|
||||
draftThreadsByThreadId: nextDraftThreadsByThreadId,
|
||||
projectDraftThreadIdByProjectId: nextProjectDraftThreadIdByProjectId,
|
||||
};
|
||||
});
|
||||
},
|
||||
setDraftThreadContext: (threadId, options) => {
|
||||
if (threadId.length === 0) {
|
||||
return;
|
||||
}
|
||||
set((state) => {
|
||||
const existing = state.draftThreadsByThreadId[threadId];
|
||||
if (!existing) {
|
||||
return state;
|
||||
}
|
||||
const nextProjectId = options.projectId ?? existing.projectId;
|
||||
if (nextProjectId.length === 0) {
|
||||
return state;
|
||||
}
|
||||
const nextWorktreePath =
|
||||
options.worktreePath === undefined
|
||||
? existing.worktreePath
|
||||
: (options.worktreePath ?? null);
|
||||
const nextDraftThread: DraftThreadState = {
|
||||
projectId: nextProjectId,
|
||||
createdAt:
|
||||
options.createdAt === undefined
|
||||
? existing.createdAt
|
||||
: options.createdAt || existing.createdAt,
|
||||
runtimeMode: options.runtimeMode ?? existing.runtimeMode,
|
||||
interactionMode: options.interactionMode ?? existing.interactionMode,
|
||||
branch: options.branch === undefined ? existing.branch : (options.branch ?? null),
|
||||
worktreePath: nextWorktreePath,
|
||||
envMode:
|
||||
options.envMode ?? (nextWorktreePath ? "worktree" : (existing.envMode ?? "local")),
|
||||
};
|
||||
const isUnchanged =
|
||||
nextDraftThread.projectId === existing.projectId &&
|
||||
nextDraftThread.createdAt === existing.createdAt &&
|
||||
nextDraftThread.runtimeMode === existing.runtimeMode &&
|
||||
nextDraftThread.interactionMode === existing.interactionMode &&
|
||||
nextDraftThread.branch === existing.branch &&
|
||||
nextDraftThread.worktreePath === existing.worktreePath &&
|
||||
nextDraftThread.envMode === existing.envMode;
|
||||
if (isUnchanged) {
|
||||
return state;
|
||||
}
|
||||
const nextProjectDraftThreadIdByProjectId: Record<ProjectId, ThreadId> = {
|
||||
...state.projectDraftThreadIdByProjectId,
|
||||
[nextProjectId]: threadId,
|
||||
};
|
||||
if (existing.projectId !== nextProjectId) {
|
||||
if (nextProjectDraftThreadIdByProjectId[existing.projectId] === threadId) {
|
||||
delete nextProjectDraftThreadIdByProjectId[existing.projectId];
|
||||
}
|
||||
}
|
||||
return {
|
||||
draftThreadsByThreadId: {
|
||||
...state.draftThreadsByThreadId,
|
||||
[threadId]: nextDraftThread,
|
||||
},
|
||||
projectDraftThreadIdByProjectId: nextProjectDraftThreadIdByProjectId,
|
||||
};
|
||||
});
|
||||
},
|
||||
clearProjectDraftThreadId: (projectId) => {
|
||||
if (projectId.length === 0) {
|
||||
return;
|
||||
}
|
||||
set((state) => {
|
||||
const threadId = state.projectDraftThreadIdByProjectId[projectId];
|
||||
if (threadId === undefined) {
|
||||
return state;
|
||||
}
|
||||
const { [projectId]: _removed, ...restProjectMappingsRaw } =
|
||||
state.projectDraftThreadIdByProjectId;
|
||||
const restProjectMappings = restProjectMappingsRaw as Record<ProjectId, ThreadId>;
|
||||
const nextDraftThreadsByThreadId: Record<ThreadId, DraftThreadState> = {
|
||||
...state.draftThreadsByThreadId,
|
||||
};
|
||||
let nextDraftsByThreadId = state.draftsByThreadId;
|
||||
if (!Object.values(restProjectMappings).includes(threadId)) {
|
||||
delete nextDraftThreadsByThreadId[threadId];
|
||||
if (state.draftsByThreadId[threadId] !== undefined) {
|
||||
nextDraftsByThreadId = { ...state.draftsByThreadId };
|
||||
delete nextDraftsByThreadId[threadId];
|
||||
}
|
||||
}
|
||||
return {
|
||||
draftsByThreadId: nextDraftsByThreadId,
|
||||
draftThreadsByThreadId: nextDraftThreadsByThreadId,
|
||||
projectDraftThreadIdByProjectId: restProjectMappings,
|
||||
};
|
||||
});
|
||||
},
|
||||
clearProjectDraftThreadById: (projectId, threadId) => {
|
||||
if (projectId.length === 0 || threadId.length === 0) {
|
||||
return;
|
||||
}
|
||||
set((state) => {
|
||||
if (state.projectDraftThreadIdByProjectId[projectId] !== threadId) {
|
||||
return state;
|
||||
}
|
||||
const { [projectId]: _removed, ...restProjectMappingsRaw } =
|
||||
state.projectDraftThreadIdByProjectId;
|
||||
const restProjectMappings = restProjectMappingsRaw as Record<ProjectId, ThreadId>;
|
||||
const nextDraftThreadsByThreadId: Record<ThreadId, DraftThreadState> = {
|
||||
...state.draftThreadsByThreadId,
|
||||
};
|
||||
let nextDraftsByThreadId = state.draftsByThreadId;
|
||||
if (!Object.values(restProjectMappings).includes(threadId)) {
|
||||
delete nextDraftThreadsByThreadId[threadId];
|
||||
if (state.draftsByThreadId[threadId] !== undefined) {
|
||||
nextDraftsByThreadId = { ...state.draftsByThreadId };
|
||||
delete nextDraftsByThreadId[threadId];
|
||||
}
|
||||
}
|
||||
return {
|
||||
draftsByThreadId: nextDraftsByThreadId,
|
||||
draftThreadsByThreadId: nextDraftThreadsByThreadId,
|
||||
projectDraftThreadIdByProjectId: restProjectMappings,
|
||||
};
|
||||
});
|
||||
},
|
||||
clearDraftThread: (threadId) => {
|
||||
if (threadId.length === 0) {
|
||||
return;
|
||||
}
|
||||
const existing = get().draftsByThreadId[threadId];
|
||||
if (existing) {
|
||||
for (const image of existing.images) {
|
||||
revokeObjectPreviewUrl(image.previewUrl);
|
||||
}
|
||||
}
|
||||
set((state) => {
|
||||
const hasDraftThread = state.draftThreadsByThreadId[threadId] !== undefined;
|
||||
const hasProjectMapping = Object.values(state.projectDraftThreadIdByProjectId).includes(
|
||||
threadId,
|
||||
);
|
||||
const hasComposerDraft = state.draftsByThreadId[threadId] !== undefined;
|
||||
if (!hasDraftThread && !hasProjectMapping && !hasComposerDraft) {
|
||||
return state;
|
||||
}
|
||||
const nextProjectDraftThreadIdByProjectId = Object.fromEntries(
|
||||
Object.entries(state.projectDraftThreadIdByProjectId).filter(
|
||||
([, draftThreadId]) => draftThreadId !== threadId,
|
||||
),
|
||||
) as Record<ProjectId, ThreadId>;
|
||||
const { [threadId]: _removedDraftThread, ...restDraftThreadsByThreadId } =
|
||||
state.draftThreadsByThreadId;
|
||||
const { [threadId]: _removedComposerDraft, ...restDraftsByThreadId } =
|
||||
state.draftsByThreadId;
|
||||
return {
|
||||
draftsByThreadId: restDraftsByThreadId,
|
||||
draftThreadsByThreadId: restDraftThreadsByThreadId,
|
||||
projectDraftThreadIdByProjectId: nextProjectDraftThreadIdByProjectId,
|
||||
};
|
||||
});
|
||||
},
|
||||
setStickyModelSelection: (modelSelection) => {
|
||||
const normalized = normalizeModelSelection(modelSelection);
|
||||
set((state) => {
|
||||
if (!normalized) {
|
||||
return state;
|
||||
}
|
||||
const nextMap: Partial<Record<ProviderKind, ModelSelection>> = {
|
||||
...state.stickyModelSelectionByProvider,
|
||||
[normalized.provider]: normalized,
|
||||
};
|
||||
if (Equal.equals(state.stickyModelSelectionByProvider, nextMap)) {
|
||||
return state.stickyActiveProvider === normalized.provider
|
||||
? state
|
||||
: { stickyActiveProvider: normalized.provider };
|
||||
}
|
||||
return {
|
||||
stickyModelSelectionByProvider: nextMap,
|
||||
stickyActiveProvider: normalized.provider,
|
||||
};
|
||||
});
|
||||
},
|
||||
applyStickyState: (threadId) => {
|
||||
if (threadId.length === 0) {
|
||||
return;
|
||||
}
|
||||
set((state) => {
|
||||
const stickyMap = state.stickyModelSelectionByProvider;
|
||||
const stickyActiveProvider = state.stickyActiveProvider;
|
||||
if (Object.keys(stickyMap).length === 0 && stickyActiveProvider === null) {
|
||||
return state;
|
||||
}
|
||||
const existing = state.draftsByThreadId[threadId];
|
||||
const base = existing ?? createEmptyThreadDraft();
|
||||
const nextMap = { ...base.modelSelectionByProvider };
|
||||
for (const [provider, selection] of Object.entries(stickyMap)) {
|
||||
if (selection) {
|
||||
const current = nextMap[provider as ProviderKind];
|
||||
nextMap[provider as ProviderKind] = {
|
||||
...selection,
|
||||
model: current?.model ?? selection.model,
|
||||
};
|
||||
}
|
||||
}
|
||||
if (
|
||||
Equal.equals(base.modelSelectionByProvider, nextMap) &&
|
||||
base.activeProvider === stickyActiveProvider
|
||||
) {
|
||||
return state;
|
||||
}
|
||||
const nextDraft: ComposerThreadDraftState = {
|
||||
...base,
|
||||
modelSelectionByProvider: nextMap,
|
||||
activeProvider: stickyActiveProvider,
|
||||
};
|
||||
const nextDraftsByThreadId = { ...state.draftsByThreadId };
|
||||
if (shouldRemoveDraft(nextDraft)) {
|
||||
delete nextDraftsByThreadId[threadId];
|
||||
} else {
|
||||
nextDraftsByThreadId[threadId] = nextDraft;
|
||||
}
|
||||
return { draftsByThreadId: nextDraftsByThreadId };
|
||||
});
|
||||
},
|
||||
setPrompt: (threadId, prompt) => {
|
||||
if (threadId.length === 0) {
|
||||
return;
|
||||
}
|
||||
set((state) => {
|
||||
const existing = state.draftsByThreadId[threadId] ?? createEmptyThreadDraft();
|
||||
const nextDraft: ComposerThreadDraftState = {
|
||||
...existing,
|
||||
prompt,
|
||||
};
|
||||
const nextDraftsByThreadId = { ...state.draftsByThreadId };
|
||||
if (shouldRemoveDraft(nextDraft)) {
|
||||
delete nextDraftsByThreadId[threadId];
|
||||
} else {
|
||||
nextDraftsByThreadId[threadId] = nextDraft;
|
||||
}
|
||||
return { draftsByThreadId: nextDraftsByThreadId };
|
||||
});
|
||||
},
|
||||
setTerminalContexts: (threadId, contexts) => {
|
||||
if (threadId.length === 0) {
|
||||
return;
|
||||
}
|
||||
const normalizedContexts = normalizeTerminalContextsForThread(threadId, contexts);
|
||||
set((state) => {
|
||||
const existing = state.draftsByThreadId[threadId] ?? createEmptyThreadDraft();
|
||||
const nextDraft: ComposerThreadDraftState = {
|
||||
...existing,
|
||||
prompt: ensureInlineTerminalContextPlaceholders(
|
||||
existing.prompt,
|
||||
normalizedContexts.length,
|
||||
),
|
||||
terminalContexts: normalizedContexts,
|
||||
};
|
||||
const nextDraftsByThreadId = { ...state.draftsByThreadId };
|
||||
if (shouldRemoveDraft(nextDraft)) {
|
||||
delete nextDraftsByThreadId[threadId];
|
||||
} else {
|
||||
nextDraftsByThreadId[threadId] = nextDraft;
|
||||
}
|
||||
return { draftsByThreadId: nextDraftsByThreadId };
|
||||
});
|
||||
},
|
||||
setModelSelection: (threadId, modelSelection) => {
|
||||
if (threadId.length === 0) {
|
||||
return;
|
||||
}
|
||||
const normalized = normalizeModelSelection(modelSelection);
|
||||
set((state) => {
|
||||
const existing = state.draftsByThreadId[threadId];
|
||||
if (!existing && normalized === null) {
|
||||
return state;
|
||||
}
|
||||
const base = existing ?? createEmptyThreadDraft();
|
||||
const nextMap = { ...base.modelSelectionByProvider };
|
||||
if (normalized) {
|
||||
const current = nextMap[normalized.provider];
|
||||
if (normalized.provider === "acp") {
|
||||
nextMap[normalized.provider] = normalized;
|
||||
} else if (normalized.options !== undefined) {
|
||||
// Explicit options provided → use them
|
||||
nextMap[normalized.provider] = normalized;
|
||||
} else {
|
||||
// No options in selection → preserve existing options, update provider+model
|
||||
nextMap[normalized.provider] = {
|
||||
provider: normalized.provider,
|
||||
model: normalized.model,
|
||||
...(current?.provider !== "acp" && current?.options
|
||||
? { options: current.options }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
}
|
||||
const nextActiveProvider = normalized?.provider ?? base.activeProvider;
|
||||
if (
|
||||
Equal.equals(base.modelSelectionByProvider, nextMap) &&
|
||||
base.activeProvider === nextActiveProvider
|
||||
) {
|
||||
return state;
|
||||
}
|
||||
const nextDraft: ComposerThreadDraftState = {
|
||||
...base,
|
||||
modelSelectionByProvider: nextMap,
|
||||
activeProvider: nextActiveProvider,
|
||||
};
|
||||
const nextDraftsByThreadId = { ...state.draftsByThreadId };
|
||||
if (shouldRemoveDraft(nextDraft)) {
|
||||
delete nextDraftsByThreadId[threadId];
|
||||
} else {
|
||||
nextDraftsByThreadId[threadId] = nextDraft;
|
||||
}
|
||||
return { draftsByThreadId: nextDraftsByThreadId };
|
||||
});
|
||||
},
|
||||
setModelOptions: (threadId, modelOptions) => {
|
||||
if (threadId.length === 0) {
|
||||
return;
|
||||
}
|
||||
const normalizedOpts = normalizeProviderModelOptions(modelOptions);
|
||||
set((state) => {
|
||||
const existing = state.draftsByThreadId[threadId];
|
||||
if (!existing && normalizedOpts === null) {
|
||||
return state;
|
||||
}
|
||||
const base = existing ?? createEmptyThreadDraft();
|
||||
const nextMap = { ...base.modelSelectionByProvider };
|
||||
for (const provider of ["codex", "claudeAgent", "cursor"] as const) {
|
||||
// Only touch providers explicitly present in the input
|
||||
if (!normalizedOpts || !(provider in normalizedOpts)) continue;
|
||||
const opts = normalizedOpts[provider];
|
||||
const current = nextMap[provider];
|
||||
if (opts) {
|
||||
nextMap[provider] = {
|
||||
provider,
|
||||
model: current?.model ?? DEFAULT_MODEL_BY_PROVIDER[provider],
|
||||
options: opts,
|
||||
} as ModelSelection;
|
||||
} else if (current?.provider !== "acp" && current?.options) {
|
||||
// Remove options but keep the selection
|
||||
const { options: _, ...rest } = current;
|
||||
nextMap[provider] = rest as ModelSelection;
|
||||
}
|
||||
}
|
||||
if (Equal.equals(base.modelSelectionByProvider, nextMap)) {
|
||||
return state;
|
||||
}
|
||||
const nextDraft: ComposerThreadDraftState = {
|
||||
...base,
|
||||
modelSelectionByProvider: nextMap,
|
||||
};
|
||||
const nextDraftsByThreadId = { ...state.draftsByThreadId };
|
||||
if (shouldRemoveDraft(nextDraft)) {
|
||||
delete nextDraftsByThreadId[threadId];
|
||||
} else {
|
||||
nextDraftsByThreadId[threadId] = nextDraft;
|
||||
}
|
||||
return { draftsByThreadId: nextDraftsByThreadId };
|
||||
});
|
||||
},
|
||||
setProviderModelOptions: (threadId, provider, nextProviderOptions, options) => {
|
||||
if (threadId.length === 0) {
|
||||
return;
|
||||
}
|
||||
const normalizedProvider = normalizeProviderKind(provider);
|
||||
if (normalizedProvider === null) {
|
||||
return;
|
||||
}
|
||||
// Normalize just this provider's options
|
||||
const normalizedOpts = normalizeProviderModelOptions(
|
||||
{ [normalizedProvider]: nextProviderOptions },
|
||||
normalizedProvider,
|
||||
);
|
||||
const providerOpts = normalizedOpts?.[normalizedProvider];
|
||||
|
||||
set((state) => {
|
||||
const existing = state.draftsByThreadId[threadId];
|
||||
const base = existing ?? createEmptyThreadDraft();
|
||||
|
||||
// Update the map entry for this provider
|
||||
const nextMap = { ...base.modelSelectionByProvider };
|
||||
const currentForProvider = nextMap[normalizedProvider];
|
||||
if (providerOpts) {
|
||||
nextMap[normalizedProvider] = {
|
||||
provider: normalizedProvider,
|
||||
model: currentForProvider?.model ?? DEFAULT_MODEL_BY_PROVIDER[normalizedProvider],
|
||||
options: providerOpts,
|
||||
} as ModelSelection;
|
||||
} else if (currentForProvider?.provider !== "acp" && currentForProvider?.options) {
|
||||
const { options: _, ...rest } = currentForProvider;
|
||||
nextMap[normalizedProvider] = rest as ModelSelection;
|
||||
}
|
||||
|
||||
// Handle sticky persistence
|
||||
let nextStickyMap = state.stickyModelSelectionByProvider;
|
||||
let nextStickyActiveProvider = state.stickyActiveProvider;
|
||||
if (options?.persistSticky === true) {
|
||||
nextStickyMap = { ...state.stickyModelSelectionByProvider };
|
||||
const stickyBase =
|
||||
nextStickyMap[normalizedProvider] ??
|
||||
base.modelSelectionByProvider[normalizedProvider] ??
|
||||
({
|
||||
provider: normalizedProvider,
|
||||
model: DEFAULT_MODEL_BY_PROVIDER[normalizedProvider],
|
||||
} as ModelSelection);
|
||||
if (providerOpts) {
|
||||
nextStickyMap[normalizedProvider] = {
|
||||
...stickyBase,
|
||||
provider: normalizedProvider,
|
||||
options: providerOpts,
|
||||
} as ModelSelection;
|
||||
} else if (stickyBase.provider !== "acp" && stickyBase.options) {
|
||||
const { options: _, ...rest } = stickyBase;
|
||||
nextStickyMap[normalizedProvider] = rest as ModelSelection;
|
||||
}
|
||||
nextStickyActiveProvider = base.activeProvider ?? normalizedProvider;
|
||||
}
|
||||
const draftThread = get().draftThreadsByThreadKey[draftId];
|
||||
if (!draftThread || isDraftThreadPromoting(draftThread)) {
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { queryOptions } from "@tanstack/react-query";
|
||||
import { ensureNativeApi } from "~/nativeApi";
|
||||
|
||||
export const serverQueryKeys = {
|
||||
all: ["server"] as const,
|
||||
config: () => ["server", "config"] as const,
|
||||
acpRegistry: () => ["server", "acp-registry"] as const,
|
||||
};
|
||||
|
||||
/**
|
||||
* Server config query options.
|
||||
*
|
||||
* `staleTime` is kept short so that push-driven `invalidateQueries` calls in
|
||||
* the EventRouter always trigger a refetch, and so the query re-fetches when
|
||||
* the component re-mounts (e.g. navigating away from settings and back).
|
||||
*/
|
||||
export function serverConfigQueryOptions() {
|
||||
return queryOptions({
|
||||
queryKey: serverQueryKeys.config(),
|
||||
queryFn: async () => {
|
||||
const api = ensureNativeApi();
|
||||
return api.server.getConfig();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function serverAcpRegistryQueryOptions() {
|
||||
return queryOptions({
|
||||
queryKey: serverQueryKeys.acpRegistry(),
|
||||
queryFn: async () => {
|
||||
const api = ensureNativeApi();
|
||||
return api.server.listAcpRegistry();
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import {
|
||||
DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER,
|
||||
type ModelSelection,
|
||||
type ProviderKind,
|
||||
type ProviderModelOptions,
|
||||
type ServerProvider,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
@@ -19,6 +20,12 @@ import {
|
||||
|
||||
const MAX_CUSTOM_MODEL_COUNT = 32;
|
||||
export const MAX_CUSTOM_MODEL_LENGTH = 256;
|
||||
export type BuiltInProviderKind = Exclude<ProviderKind, "acp">;
|
||||
export const BUILT_IN_PROVIDER_KINDS = [
|
||||
"codex",
|
||||
"claudeAgent",
|
||||
"cursor",
|
||||
] as const satisfies readonly BuiltInProviderKind[];
|
||||
|
||||
export type ProviderCustomModelConfig = {
|
||||
provider: ProviderKind;
|
||||
@@ -34,6 +41,27 @@ export interface AppModelOption {
|
||||
isCustom: boolean;
|
||||
}
|
||||
|
||||
export function getModelSelectionOptions(
|
||||
selection: ModelSelection | null | undefined,
|
||||
): ProviderModelOptions[ProviderKind] | undefined {
|
||||
return selection?.provider === "acp" ? undefined : selection?.options;
|
||||
}
|
||||
|
||||
export function isBuiltInProviderKind(provider: ProviderKind): provider is BuiltInProviderKind {
|
||||
return provider !== "acp";
|
||||
}
|
||||
|
||||
export function resolveBuiltInSelectableProvider(
|
||||
providers: ReadonlyArray<ServerProvider>,
|
||||
provider: ProviderKind | null | undefined,
|
||||
): BuiltInProviderKind {
|
||||
const resolved = resolveSelectableProvider(
|
||||
providers.filter((candidate) => candidate.provider !== "acp"),
|
||||
provider === "acp" ? "codex" : provider,
|
||||
);
|
||||
return resolved === "acp" ? "codex" : resolved;
|
||||
}
|
||||
|
||||
const PROVIDER_CUSTOM_MODEL_CONFIG: Record<ProviderKind, ProviderCustomModelConfig> = {
|
||||
codex: {
|
||||
provider: "codex",
|
||||
@@ -56,6 +84,13 @@ const PROVIDER_CUSTOM_MODEL_CONFIG: Record<ProviderKind, ProviderCustomModelConf
|
||||
placeholder: "your-cursor-model-slug",
|
||||
example: "claude-sonnet-4-6",
|
||||
},
|
||||
acp: {
|
||||
provider: "acp",
|
||||
title: "ACP",
|
||||
description: "ACP agents do not currently expose custom model slugs in T3 Code.",
|
||||
placeholder: "acp-agent",
|
||||
example: "acp-agent",
|
||||
},
|
||||
};
|
||||
|
||||
export const MODEL_PROVIDER_SETTINGS = Object.values(PROVIDER_CUSTOM_MODEL_CONFIG);
|
||||
@@ -95,6 +130,9 @@ export function getAppModelOptions(
|
||||
provider: ProviderKind,
|
||||
selectedModel?: string | null,
|
||||
): AppModelOption[] {
|
||||
if (provider === "acp") {
|
||||
return [];
|
||||
}
|
||||
const options: AppModelOption[] = getProviderModels(providers, provider).map(
|
||||
({ slug, name, isCustom }) => ({
|
||||
slug,
|
||||
@@ -182,6 +220,7 @@ export function getCustomModelOptionsByProvider(
|
||||
"cursor",
|
||||
selectedProvider === "cursor" ? selectedModel : undefined,
|
||||
),
|
||||
acp: [],
|
||||
};
|
||||
}
|
||||
|
||||
@@ -193,7 +232,7 @@ export function resolveAppModelSelectionState(
|
||||
provider: "codex" as const,
|
||||
model: DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER.codex,
|
||||
};
|
||||
const provider = resolveSelectableProvider(providers, selection.provider);
|
||||
const provider = resolveBuiltInSelectableProvider(providers, selection.provider);
|
||||
|
||||
// When the provider changed due to fallback (e.g. selected provider was disabled),
|
||||
// don't carry over the old provider's model — use the fallback provider's default.
|
||||
@@ -205,7 +244,7 @@ export function resolveAppModelSelectionState(
|
||||
models: getProviderModels(providers, provider),
|
||||
prompt: "",
|
||||
modelOptions: {
|
||||
[provider]: provider === selection.provider ? selection.options : undefined,
|
||||
[provider]: provider === selection.provider ? getModelSelectionOptions(selection) : undefined,
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -63,6 +63,9 @@ export function getProviderModelCapabilities(
|
||||
model: string | null | undefined,
|
||||
provider: ProviderKind,
|
||||
): ModelCapabilities {
|
||||
if (provider === "acp") {
|
||||
return EMPTY_CAPABILITIES;
|
||||
}
|
||||
const slug = normalizeModelSlug(model, provider);
|
||||
return models.find((candidate) => candidate.slug === slug)?.capabilities ?? EMPTY_CAPABILITIES;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import { createFileRoute } from "@tanstack/react-router";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import {
|
||||
ArrowUpCircleIcon,
|
||||
CheckIcon,
|
||||
ChevronDownIcon,
|
||||
GlobeIcon,
|
||||
InfoIcon,
|
||||
LoaderIcon,
|
||||
PlusIcon,
|
||||
@@ -10,16 +13,21 @@ import {
|
||||
Undo2Icon,
|
||||
XIcon,
|
||||
} from "lucide-react";
|
||||
import { GitHubIcon } from "../components/Icons";
|
||||
import { type ReactNode, useCallback, useEffect, useRef, useState } from "react";
|
||||
import {
|
||||
type AcpAgentServer,
|
||||
type ModelSelection,
|
||||
type ResolvedRegistryAcpAgent,
|
||||
PROVIDER_DISPLAY_NAMES,
|
||||
type ProviderKind,
|
||||
type ServerProvider,
|
||||
type ServerProviderModel,
|
||||
} from "@t3tools/contracts";
|
||||
import { normalizeModelSlug } from "@t3tools/shared/model";
|
||||
import { useSettings, useUpdateSettings } from "../hooks/useSettings";
|
||||
import {
|
||||
type BuiltInProviderKind,
|
||||
getModelSelectionOptions,
|
||||
getCustomModelOptionsByProvider,
|
||||
MAX_CUSTOM_MODEL_LENGTH,
|
||||
resolveAppModelSelectionState,
|
||||
@@ -27,6 +35,15 @@ import {
|
||||
import { APP_VERSION } from "../branding";
|
||||
import { Button } from "../components/ui/button";
|
||||
import { Collapsible, CollapsibleContent } from "../components/ui/collapsible";
|
||||
import {
|
||||
Dialog,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogPanel,
|
||||
DialogPopup,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "../components/ui/dialog";
|
||||
import { Input } from "../components/ui/input";
|
||||
import {
|
||||
Select,
|
||||
@@ -44,7 +61,11 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "../components/ui/tooltip"
|
||||
import { resolveAndPersistPreferredEditor } from "../editorPreferences";
|
||||
import { isElectron } from "../env";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { serverConfigQueryOptions, serverQueryKeys } from "../lib/serverReactQuery";
|
||||
import {
|
||||
serverAcpRegistryQueryOptions,
|
||||
serverConfigQueryOptions,
|
||||
serverQueryKeys,
|
||||
} from "../lib/serverReactQuery";
|
||||
import { cn } from "../lib/utils";
|
||||
import { formatRelativeTime } from "../timestampFormat";
|
||||
import { ensureNativeApi, readNativeApi } from "../nativeApi";
|
||||
@@ -77,8 +98,58 @@ const TIMESTAMP_FORMAT_LABELS = {
|
||||
|
||||
const EMPTY_SERVER_PROVIDERS: ReadonlyArray<ServerProvider> = [];
|
||||
|
||||
function slugifyAcpAgentId(value: string): string {
|
||||
const normalized = value
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-+|-+$/g, "");
|
||||
return normalized || "acp-agent";
|
||||
}
|
||||
|
||||
function parseArgsInput(value: string): string[] {
|
||||
return value
|
||||
.split(/\s+/)
|
||||
.map((part) => part.trim())
|
||||
.filter((part) => part.length > 0);
|
||||
}
|
||||
|
||||
function getBinaryLaunchSpec(
|
||||
input: ResolvedRegistryAcpAgent,
|
||||
): { command: string; args: string[] } | null {
|
||||
const binary = input.agent.distribution.binary;
|
||||
if (!binary) return null;
|
||||
// Try current platform key (e.g. "darwin-arm64", "linux-x64")
|
||||
const platformKey = `${navigator.platform.includes("Mac") ? "darwin" : navigator.platform.includes("Win") ? "windows" : "linux"}-${navigator.userAgent.includes("arm") ? "arm64" : "x64"}`;
|
||||
const entry = binary[platformKey] ?? Object.values(binary)[0];
|
||||
if (!entry) return null;
|
||||
return { command: entry.cmd, args: entry.args ? [...entry.args] : [] };
|
||||
}
|
||||
|
||||
function makeImportedAcpAgent(input: ResolvedRegistryAcpAgent): AcpAgentServer {
|
||||
const launch = input.launch ??
|
||||
getBinaryLaunchSpec(input) ?? {
|
||||
command: input.agent.id,
|
||||
args: [],
|
||||
};
|
||||
return {
|
||||
id: input.agent.id,
|
||||
name: input.agent.name,
|
||||
enabled: true,
|
||||
source: "registry",
|
||||
distributionType: input.distributionType,
|
||||
registryAgentId: input.agent.id,
|
||||
importedVersion: input.agent.version,
|
||||
description: input.agent.description,
|
||||
...(input.agent.website ? { website: input.agent.website } : {}),
|
||||
...(input.agent.repository ? { repository: input.agent.repository } : {}),
|
||||
...(input.agent.icon ? { iconUrl: input.agent.icon } : {}),
|
||||
launch,
|
||||
};
|
||||
}
|
||||
|
||||
type InstallProviderSettings = {
|
||||
provider: ProviderKind;
|
||||
provider: BuiltInProviderKind;
|
||||
title: string;
|
||||
binaryPlaceholder: string;
|
||||
binaryDescription: ReactNode;
|
||||
@@ -294,9 +365,12 @@ function SettingsRouteView() {
|
||||
const settings = useSettings();
|
||||
const { updateSettings, resetSettings } = useUpdateSettings();
|
||||
const serverConfigQuery = useQuery(serverConfigQueryOptions());
|
||||
const acpRegistryQuery = useQuery(serverAcpRegistryQueryOptions());
|
||||
const [isOpeningKeybindings, setIsOpeningKeybindings] = useState(false);
|
||||
const [openKeybindingsError, setOpenKeybindingsError] = useState<string | null>(null);
|
||||
const [openProviderDetails, setOpenProviderDetails] = useState<Record<ProviderKind, boolean>>({
|
||||
const [openProviderDetails, setOpenProviderDetails] = useState<
|
||||
Record<BuiltInProviderKind, boolean>
|
||||
>({
|
||||
codex: Boolean(
|
||||
settings.providers.codex.binaryPath !== DEFAULT_UNIFIED_SETTINGS.providers.codex.binaryPath ||
|
||||
settings.providers.codex.homePath !== DEFAULT_UNIFIED_SETTINGS.providers.codex.homePath ||
|
||||
@@ -316,16 +390,25 @@ function SettingsRouteView() {
|
||||
),
|
||||
});
|
||||
const [customModelInputByProvider, setCustomModelInputByProvider] = useState<
|
||||
Record<ProviderKind, string>
|
||||
Record<BuiltInProviderKind, string>
|
||||
>({
|
||||
codex: "",
|
||||
claudeAgent: "",
|
||||
cursor: "",
|
||||
});
|
||||
const [customModelErrorByProvider, setCustomModelErrorByProvider] = useState<
|
||||
Partial<Record<ProviderKind, string | null>>
|
||||
Partial<Record<BuiltInProviderKind, string | null>>
|
||||
>({});
|
||||
const [isRefreshingProviders, setIsRefreshingProviders] = useState(false);
|
||||
const [acpDialogOpen, setAcpDialogOpen] = useState(false);
|
||||
const [acpDialogTab, setAcpDialogTab] = useState<"registry" | "manual">("registry");
|
||||
const [acpRegistrySearch, setAcpRegistrySearch] = useState("");
|
||||
const [openAcpAgentDetails, setOpenAcpAgentDetails] = useState<Record<string, boolean>>({});
|
||||
const [manualAcpName, setManualAcpName] = useState("");
|
||||
const [manualAcpCommand, setManualAcpCommand] = useState("");
|
||||
const [manualAcpArgs, setManualAcpArgs] = useState("");
|
||||
const [manualAcpEnabled, setManualAcpEnabled] = useState(true);
|
||||
const [manualAcpError, setManualAcpError] = useState<string | null>(null);
|
||||
const refreshingRef = useRef(false);
|
||||
const queryClient = useQueryClient();
|
||||
useRelativeTimeTick();
|
||||
@@ -347,17 +430,30 @@ function SettingsRouteView() {
|
||||
});
|
||||
}, [queryClient]);
|
||||
|
||||
const modelListRefs = useRef<Partial<Record<ProviderKind, HTMLDivElement | null>>>({});
|
||||
const modelListRefs = useRef<Partial<Record<BuiltInProviderKind, HTMLDivElement | null>>>({});
|
||||
|
||||
const codexHomePath = settings.providers.codex.homePath;
|
||||
const keybindingsConfigPath = serverConfigQuery.data?.keybindingsConfigPath ?? null;
|
||||
const availableEditors = serverConfigQuery.data?.availableEditors;
|
||||
const serverProviders = serverConfigQuery.data?.providers ?? EMPTY_SERVER_PROVIDERS;
|
||||
const acpAgentStatuses = serverConfigQuery.data?.acpAgentServers ?? [];
|
||||
const registeredAcpAgents = settings.providers.acp.agentServers;
|
||||
const filteredRegistryAgents = (acpRegistryQuery.data?.agents ?? []).filter((entry) => {
|
||||
const search = acpRegistrySearch.trim().toLowerCase();
|
||||
if (!search) {
|
||||
return true;
|
||||
}
|
||||
return (
|
||||
entry.agent.name.toLowerCase().includes(search) ||
|
||||
entry.agent.id.toLowerCase().includes(search) ||
|
||||
entry.agent.description.toLowerCase().includes(search)
|
||||
);
|
||||
});
|
||||
|
||||
const textGenerationModelSelection = resolveAppModelSelectionState(settings, serverProviders);
|
||||
const textGenProvider = textGenerationModelSelection.provider;
|
||||
const textGenModel = textGenerationModelSelection.model;
|
||||
const textGenModelOptions = textGenerationModelSelection.options;
|
||||
const textGenModelOptions = getModelSelectionOptions(textGenerationModelSelection);
|
||||
const gitModelOptionsByProvider = getCustomModelOptionsByProvider(
|
||||
settings,
|
||||
serverProviders,
|
||||
@@ -373,6 +469,10 @@ function SettingsRouteView() {
|
||||
settings.textGenerationModelSelection ?? null,
|
||||
DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection ?? null,
|
||||
);
|
||||
const areAcpSettingsDirty = !Equal.equals(
|
||||
settings.providers.acp,
|
||||
DEFAULT_UNIFIED_SETTINGS.providers.acp,
|
||||
);
|
||||
const changedSettingLabels = [
|
||||
...(theme !== "system" ? ["Theme"] : []),
|
||||
...(settings.timestampFormat !== DEFAULT_UNIFIED_SETTINGS.timestampFormat
|
||||
@@ -392,6 +492,7 @@ function SettingsRouteView() {
|
||||
: []),
|
||||
...(isGitWritingModelDirty ? ["Git writing model"] : []),
|
||||
...(areProviderSettingsDirty ? ["Providers"] : []),
|
||||
...(areAcpSettingsDirty ? ["ACP Agents"] : []),
|
||||
];
|
||||
|
||||
const openKeybindingsFile = useCallback(() => {
|
||||
@@ -418,7 +519,7 @@ function SettingsRouteView() {
|
||||
}, [availableEditors, keybindingsConfigPath]);
|
||||
|
||||
const addCustomModel = useCallback(
|
||||
(provider: ProviderKind) => {
|
||||
(provider: BuiltInProviderKind) => {
|
||||
const customModelInput = customModelInputByProvider[provider];
|
||||
const customModels = settings.providers[provider].customModels;
|
||||
const normalized = normalizeModelSlug(customModelInput, provider);
|
||||
@@ -492,7 +593,7 @@ function SettingsRouteView() {
|
||||
);
|
||||
|
||||
const removeCustomModel = useCallback(
|
||||
(provider: ProviderKind, slug: string) => {
|
||||
(provider: BuiltInProviderKind, slug: string) => {
|
||||
const customModels = settings.providers[provider].customModels;
|
||||
updateSettings({
|
||||
providers: {
|
||||
@@ -511,6 +612,90 @@ function SettingsRouteView() {
|
||||
[settings, updateSettings],
|
||||
);
|
||||
|
||||
const upsertAcpAgent = useCallback(
|
||||
(agent: AcpAgentServer) => {
|
||||
const existingIndex = settings.providers.acp.agentServers.findIndex(
|
||||
(candidate) => candidate.id === agent.id,
|
||||
);
|
||||
const nextAgents = [...settings.providers.acp.agentServers];
|
||||
if (existingIndex >= 0) {
|
||||
nextAgents[existingIndex] = agent;
|
||||
} else {
|
||||
nextAgents.push(agent);
|
||||
}
|
||||
updateSettings({
|
||||
providers: {
|
||||
...settings.providers,
|
||||
acp: {
|
||||
...settings.providers.acp,
|
||||
agentServers: nextAgents,
|
||||
},
|
||||
},
|
||||
});
|
||||
void queryClient.invalidateQueries({ queryKey: serverQueryKeys.config() });
|
||||
},
|
||||
[queryClient, settings.providers, updateSettings],
|
||||
);
|
||||
|
||||
const removeAcpAgent = useCallback(
|
||||
(agentId: string) => {
|
||||
updateSettings({
|
||||
providers: {
|
||||
...settings.providers,
|
||||
acp: {
|
||||
...settings.providers.acp,
|
||||
agentServers: settings.providers.acp.agentServers.filter(
|
||||
(agent) => agent.id !== agentId,
|
||||
),
|
||||
},
|
||||
},
|
||||
});
|
||||
void queryClient.invalidateQueries({ queryKey: serverQueryKeys.config() });
|
||||
},
|
||||
[queryClient, settings.providers, updateSettings],
|
||||
);
|
||||
|
||||
const addManualAcpAgent = useCallback(() => {
|
||||
const name = manualAcpName.trim();
|
||||
const command = manualAcpCommand.trim();
|
||||
if (!name) {
|
||||
setManualAcpError("Enter an ACP agent name.");
|
||||
return;
|
||||
}
|
||||
if (!command || /\s/.test(command)) {
|
||||
setManualAcpError("Enter a plain executable command, not a shell snippet.");
|
||||
return;
|
||||
}
|
||||
const id = slugifyAcpAgentId(name);
|
||||
if (settings.providers.acp.agentServers.some((agent) => agent.id === id)) {
|
||||
setManualAcpError("An ACP agent with that name already exists.");
|
||||
return;
|
||||
}
|
||||
upsertAcpAgent({
|
||||
id,
|
||||
name,
|
||||
enabled: manualAcpEnabled,
|
||||
source: "manual",
|
||||
distributionType: "manual",
|
||||
launch: {
|
||||
command,
|
||||
args: parseArgsInput(manualAcpArgs),
|
||||
},
|
||||
});
|
||||
setManualAcpName("");
|
||||
setManualAcpCommand("");
|
||||
setManualAcpArgs("");
|
||||
setManualAcpEnabled(true);
|
||||
setManualAcpError(null);
|
||||
}, [
|
||||
manualAcpArgs,
|
||||
manualAcpCommand,
|
||||
manualAcpEnabled,
|
||||
manualAcpName,
|
||||
settings.providers.acp.agentServers,
|
||||
upsertAcpAgent,
|
||||
]);
|
||||
|
||||
const providerCards = PROVIDER_SETTINGS.map((providerSettings) => {
|
||||
const liveProvider = serverProviders.find(
|
||||
(candidate) => candidate.provider === providerSettings.provider,
|
||||
@@ -855,6 +1040,9 @@ function SettingsRouteView() {
|
||||
triggerVariant="outline"
|
||||
triggerClassName="min-w-0 max-w-none shrink-0 text-foreground/90 hover:text-foreground"
|
||||
onProviderModelChange={(provider, model) => {
|
||||
if (provider === "acp") {
|
||||
return;
|
||||
}
|
||||
updateSettings({
|
||||
textGenerationModelSelection: resolveAppModelSelectionState(
|
||||
{
|
||||
@@ -880,15 +1068,21 @@ function SettingsRouteView() {
|
||||
triggerVariant="outline"
|
||||
triggerClassName="min-w-0 max-w-none shrink-0 text-foreground/90 hover:text-foreground"
|
||||
onModelOptionsChange={(nextOptions) => {
|
||||
const nextSelection: ModelSelection = nextOptions
|
||||
? ({
|
||||
provider: textGenProvider,
|
||||
model: textGenModel,
|
||||
options: nextOptions,
|
||||
} as ModelSelection)
|
||||
: ({
|
||||
provider: textGenProvider,
|
||||
model: textGenModel,
|
||||
} as ModelSelection);
|
||||
updateSettings({
|
||||
textGenerationModelSelection: resolveAppModelSelectionState(
|
||||
{
|
||||
...settings,
|
||||
textGenerationModelSelection: {
|
||||
provider: textGenProvider,
|
||||
model: textGenModel,
|
||||
...(nextOptions ? { options: nextOptions } : {}),
|
||||
},
|
||||
textGenerationModelSelection: nextSelection,
|
||||
},
|
||||
serverProviders,
|
||||
),
|
||||
@@ -1283,6 +1477,470 @@ function SettingsRouteView() {
|
||||
})}
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsSection
|
||||
title="ACP Agents"
|
||||
headerAction={
|
||||
<div className="flex items-center gap-2">
|
||||
{areAcpSettingsDirty ? (
|
||||
<SettingResetButton
|
||||
label="ACP agents"
|
||||
onClick={() =>
|
||||
updateSettings({
|
||||
providers: {
|
||||
...settings.providers,
|
||||
acp: DEFAULT_UNIFIED_SETTINGS.providers.acp,
|
||||
},
|
||||
})
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
<Dialog
|
||||
open={acpDialogOpen}
|
||||
onOpenChange={(open) => {
|
||||
setAcpDialogOpen(open);
|
||||
if (!open) {
|
||||
setAcpRegistrySearch("");
|
||||
setManualAcpError(null);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<DialogTrigger
|
||||
render={
|
||||
<Button size="xs" variant="outline">
|
||||
<PlusIcon className="size-3" />
|
||||
Add agent
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<DialogPopup className="h-[80dvh] max-w-4xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Add ACP Agent</DialogTitle>
|
||||
<DialogDescription>
|
||||
Install an agent from the public registry or configure one manually.
|
||||
</DialogDescription>
|
||||
<div className="flex gap-1 rounded-lg border border-border/60 bg-muted/50 p-1">
|
||||
<button
|
||||
type="button"
|
||||
className={cn(
|
||||
"flex-1 rounded-md px-3 py-1.5 text-xs font-medium transition-colors",
|
||||
acpDialogTab === "registry"
|
||||
? "bg-background text-foreground shadow-xs"
|
||||
: "text-muted-foreground hover:text-foreground",
|
||||
)}
|
||||
onClick={() => setAcpDialogTab("registry")}
|
||||
>
|
||||
Registry
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={cn(
|
||||
"flex-1 rounded-md px-3 py-1.5 text-xs font-medium transition-colors",
|
||||
acpDialogTab === "manual"
|
||||
? "bg-background text-foreground shadow-xs"
|
||||
: "text-muted-foreground hover:text-foreground",
|
||||
)}
|
||||
onClick={() => setAcpDialogTab("manual")}
|
||||
>
|
||||
Manual
|
||||
</button>
|
||||
</div>
|
||||
</DialogHeader>
|
||||
<DialogPanel>
|
||||
{acpDialogTab === "registry" ? (
|
||||
<div className="space-y-3">
|
||||
<Input
|
||||
value={acpRegistrySearch}
|
||||
onChange={(event) => setAcpRegistrySearch(event.target.value)}
|
||||
placeholder="Search ACP registry"
|
||||
spellCheck={false}
|
||||
/>
|
||||
{acpRegistryQuery.isError ? (
|
||||
<p className="text-xs text-destructive">
|
||||
{acpRegistryQuery.error instanceof Error
|
||||
? acpRegistryQuery.error.message
|
||||
: "Failed to load ACP registry."}
|
||||
</p>
|
||||
) : null}
|
||||
<div className="grid grid-cols-1 gap-2 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{filteredRegistryAgents.map((entry) => {
|
||||
const installedAgent = registeredAcpAgents.find(
|
||||
(agent) => agent.registryAgentId === entry.agent.id,
|
||||
);
|
||||
const isInstalled = Boolean(installedAgent);
|
||||
const isUpToDate =
|
||||
isInstalled &&
|
||||
installedAgent?.importedVersion === entry.agent.version;
|
||||
const importedAgent = makeImportedAcpAgent(entry);
|
||||
return (
|
||||
<div
|
||||
key={entry.agent.id}
|
||||
className="flex flex-col rounded-xl border border-border/60 bg-background/60 p-3"
|
||||
>
|
||||
<div className="flex flex-1 items-start gap-3">
|
||||
{entry.agent.icon ? (
|
||||
<img
|
||||
src={entry.agent.icon}
|
||||
alt=""
|
||||
className="size-8 shrink-0 rounded-lg dark:invert"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex size-8 shrink-0 items-center justify-center rounded-lg bg-muted text-xs font-medium text-muted-foreground">
|
||||
{entry.agent.name.charAt(0).toUpperCase()}
|
||||
</div>
|
||||
)}
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span className="truncate text-sm font-medium text-foreground">
|
||||
{entry.agent.name}
|
||||
</span>
|
||||
<code className="shrink-0 text-[10px] text-muted-foreground">
|
||||
v{entry.agent.version}
|
||||
</code>
|
||||
</div>
|
||||
<p className="mt-0.5 line-clamp-2 text-[11px] leading-snug text-muted-foreground">
|
||||
{entry.agent.description}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-3 flex items-center justify-between">
|
||||
<div className="flex items-center gap-1">
|
||||
{entry.agent.repository ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<button
|
||||
type="button"
|
||||
className="inline-flex size-6 items-center justify-center rounded-md text-foreground/70 transition-colors hover:text-foreground"
|
||||
onClick={() =>
|
||||
void ensureNativeApi().shell.openExternal(
|
||||
entry.agent.repository!,
|
||||
)
|
||||
}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<GitHubIcon className="size-3.5" />
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="bottom">Repository</TooltipPopup>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
{entry.agent.website ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<button
|
||||
type="button"
|
||||
className="inline-flex size-6 items-center justify-center rounded-md text-foreground/70 transition-colors hover:text-foreground"
|
||||
onClick={() =>
|
||||
void ensureNativeApi().shell.openExternal(
|
||||
entry.agent.website!,
|
||||
)
|
||||
}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<GlobeIcon className="size-3.5" />
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="bottom">Website</TooltipPopup>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
</div>
|
||||
{isUpToDate ? (
|
||||
<span className="flex items-center gap-1 text-xs text-success">
|
||||
<CheckIcon className="size-3" />
|
||||
Installed
|
||||
</span>
|
||||
) : isInstalled ? (
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
className="border-amber-500/40 text-amber-400 hover:border-amber-500/60 hover:text-amber-300"
|
||||
onClick={() => upsertAcpAgent(importedAgent)}
|
||||
>
|
||||
<ArrowUpCircleIcon className="size-3" />
|
||||
Update
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
onClick={() => upsertAcpAgent(importedAgent)}
|
||||
>
|
||||
<PlusIcon className="size-3" />
|
||||
Add
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
{!acpRegistryQuery.isLoading && filteredRegistryAgents.length === 0 ? (
|
||||
<p className="py-6 text-center text-xs text-muted-foreground">
|
||||
No ACP registry agents found.
|
||||
</p>
|
||||
) : null}
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-[11px] text-muted-foreground">
|
||||
{settings.providers.acp.registryUrl}
|
||||
</span>
|
||||
<Button
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
onClick={() =>
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: serverQueryKeys.acpRegistry(),
|
||||
})
|
||||
}
|
||||
disabled={acpRegistryQuery.isFetching}
|
||||
>
|
||||
{acpRegistryQuery.isFetching ? (
|
||||
<LoaderIcon className="size-3 animate-spin" />
|
||||
) : (
|
||||
<RefreshCwIcon className="size-3" />
|
||||
)}
|
||||
Refresh
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Register an unpublished or private local ACP server by providing its
|
||||
executable command.
|
||||
</p>
|
||||
<div className="space-y-3">
|
||||
<label className="block">
|
||||
<span className="mb-1.5 block text-xs font-medium text-foreground">
|
||||
Display name
|
||||
</span>
|
||||
<Input
|
||||
value={manualAcpName}
|
||||
onChange={(event) => {
|
||||
setManualAcpName(event.target.value);
|
||||
if (manualAcpError) setManualAcpError(null);
|
||||
}}
|
||||
placeholder="My Agent"
|
||||
spellCheck={false}
|
||||
/>
|
||||
</label>
|
||||
<label className="block">
|
||||
<span className="mb-1.5 block text-xs font-medium text-foreground">
|
||||
Launch command
|
||||
</span>
|
||||
<Input
|
||||
value={manualAcpCommand}
|
||||
onChange={(event) => {
|
||||
setManualAcpCommand(event.target.value);
|
||||
if (manualAcpError) setManualAcpError(null);
|
||||
}}
|
||||
placeholder="my-agent"
|
||||
spellCheck={false}
|
||||
/>
|
||||
<span className="mt-1 block text-[11px] text-muted-foreground">
|
||||
A single executable name or path. No shell syntax.
|
||||
</span>
|
||||
</label>
|
||||
<label className="block">
|
||||
<span className="mb-1.5 block text-xs font-medium text-foreground">
|
||||
Arguments
|
||||
</span>
|
||||
<Input
|
||||
value={manualAcpArgs}
|
||||
onChange={(event) => setManualAcpArgs(event.target.value)}
|
||||
placeholder="--port 3000 --verbose"
|
||||
spellCheck={false}
|
||||
/>
|
||||
<span className="mt-1 block text-[11px] text-muted-foreground">
|
||||
Space-separated arguments passed to the launch command.
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
{manualAcpError ? (
|
||||
<p className="text-xs text-destructive">{manualAcpError}</p>
|
||||
) : null}
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full"
|
||||
onClick={() => {
|
||||
addManualAcpAgent();
|
||||
if (
|
||||
manualAcpName.trim() &&
|
||||
manualAcpCommand.trim() &&
|
||||
!/\s/.test(manualAcpCommand.trim()) &&
|
||||
!settings.providers.acp.agentServers.some(
|
||||
(agent) => agent.id === slugifyAcpAgentId(manualAcpName.trim()),
|
||||
)
|
||||
) {
|
||||
setAcpDialogOpen(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<PlusIcon className="size-3.5" />
|
||||
Add ACP Agent
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</DialogPanel>
|
||||
</DialogPopup>
|
||||
</Dialog>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
{registeredAcpAgents.map((agent) => {
|
||||
const status = acpAgentStatuses.find(
|
||||
(candidate) => candidate.agentServerId === agent.id,
|
||||
);
|
||||
return (
|
||||
<div
|
||||
key={agent.id}
|
||||
className="border-t border-border first:border-t-0"
|
||||
data-slot="settings-row"
|
||||
>
|
||||
<div className="px-4 py-4 sm:px-5">
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="min-w-0 flex-1 space-y-1">
|
||||
<div className="flex min-h-5 items-center gap-1.5">
|
||||
<span
|
||||
className={cn(
|
||||
"size-2 shrink-0 rounded-full",
|
||||
agent.enabled ? "bg-success" : "bg-amber-400",
|
||||
)}
|
||||
/>
|
||||
<h3 className="text-sm font-medium text-foreground">{agent.name}</h3>
|
||||
{agent.importedVersion ? (
|
||||
<code className="text-xs text-muted-foreground">
|
||||
v{agent.importedVersion}
|
||||
</code>
|
||||
) : null}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{agent.source === "registry"
|
||||
? `Imported from ACP registry${agent.importedVersion ? ` (v${agent.importedVersion})` : ""}`
|
||||
: "Manually configured ACP agent"}
|
||||
{status?.message ? ` — ${status.message}` : null}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">
|
||||
<Button
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
className="h-7 px-2 text-xs text-muted-foreground hover:text-foreground"
|
||||
onClick={() => removeAcpAgent(agent.id)}
|
||||
>
|
||||
Remove
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="h-7 px-2 text-xs text-muted-foreground hover:text-foreground"
|
||||
onClick={() =>
|
||||
setOpenAcpAgentDetails((existing) => ({
|
||||
...existing,
|
||||
[agent.id]: !existing[agent.id],
|
||||
}))
|
||||
}
|
||||
aria-label={`Toggle ${agent.name} details`}
|
||||
>
|
||||
<ChevronDownIcon
|
||||
className={cn(
|
||||
"size-3.5 transition-transform",
|
||||
openAcpAgentDetails[agent.id] && "rotate-180",
|
||||
)}
|
||||
/>
|
||||
</Button>
|
||||
<Switch
|
||||
checked={agent.enabled}
|
||||
onCheckedChange={(checked) =>
|
||||
upsertAcpAgent({ ...agent, enabled: Boolean(checked) })
|
||||
}
|
||||
aria-label={`Enable ${agent.name}`}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Collapsible
|
||||
open={Boolean(openAcpAgentDetails[agent.id])}
|
||||
onOpenChange={(open) =>
|
||||
setOpenAcpAgentDetails((existing) => ({
|
||||
...existing,
|
||||
[agent.id]: open,
|
||||
}))
|
||||
}
|
||||
>
|
||||
<CollapsibleContent>
|
||||
<div className="space-y-0">
|
||||
<div className="border-t border-border/60 px-4 py-3 sm:px-5">
|
||||
<label htmlFor={`acp-agent-${agent.id}-command`} className="block">
|
||||
<span className="text-xs font-medium text-foreground">
|
||||
Launch command
|
||||
</span>
|
||||
<Input
|
||||
id={`acp-agent-${agent.id}-command`}
|
||||
className="mt-1.5"
|
||||
value={agent.launch.command}
|
||||
onChange={(event) =>
|
||||
upsertAcpAgent({
|
||||
...agent,
|
||||
launch: {
|
||||
...agent.launch,
|
||||
command: event.target.value,
|
||||
},
|
||||
})
|
||||
}
|
||||
placeholder="Executable command"
|
||||
spellCheck={false}
|
||||
/>
|
||||
<span className="mt-1 block text-xs text-muted-foreground">
|
||||
The executable used to start this ACP agent.
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
<div className="border-t border-border/60 px-4 py-3 sm:px-5">
|
||||
<label htmlFor={`acp-agent-${agent.id}-args`} className="block">
|
||||
<span className="text-xs font-medium text-foreground">Arguments</span>
|
||||
<Input
|
||||
id={`acp-agent-${agent.id}-args`}
|
||||
className="mt-1.5"
|
||||
value={agent.launch.args.join(" ")}
|
||||
onChange={(event) =>
|
||||
upsertAcpAgent({
|
||||
...agent,
|
||||
launch: {
|
||||
...agent.launch,
|
||||
args: parseArgsInput(event.target.value),
|
||||
},
|
||||
})
|
||||
}
|
||||
placeholder="Space-separated arguments"
|
||||
spellCheck={false}
|
||||
/>
|
||||
<span className="mt-1 block text-xs text-muted-foreground">
|
||||
Additional arguments passed to the launch command.
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
{registeredAcpAgents.length === 0 ? (
|
||||
<div
|
||||
className="border-t border-border px-4 py-4 first:border-t-0 sm:px-5"
|
||||
data-slot="settings-row"
|
||||
>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
No ACP agents registered. Click "Add agent" to browse the registry or configure
|
||||
one manually.
|
||||
</p>
|
||||
</div>
|
||||
) : null}
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsSection title="Advanced">
|
||||
<SettingsRow
|
||||
title="Keybindings"
|
||||
|
||||
@@ -6,7 +6,6 @@ import {
|
||||
type OrchestrationLatestTurn,
|
||||
type OrchestrationThreadActivity,
|
||||
type OrchestrationProposedPlanId,
|
||||
type ProviderKind,
|
||||
type ToolLifecycleItemType,
|
||||
type UserInputQuestion,
|
||||
type ThreadId,
|
||||
@@ -22,7 +21,7 @@ import type {
|
||||
TurnDiffSummary,
|
||||
} from "./types";
|
||||
|
||||
export type ProviderPickerKind = ProviderKind;
|
||||
export type ProviderPickerKind = "codex" | "claudeAgent" | "cursor";
|
||||
|
||||
export const PROVIDER_OPTIONS: Array<{
|
||||
value: ProviderPickerKind;
|
||||
|
||||
@@ -0,0 +1,237 @@
|
||||
import {
|
||||
type GitActionProgressEvent,
|
||||
ORCHESTRATION_WS_CHANNELS,
|
||||
ORCHESTRATION_WS_METHODS,
|
||||
type ContextMenuItem,
|
||||
type NativeApi,
|
||||
ServerConfigUpdatedPayload,
|
||||
ServerProviderUpdatedPayload,
|
||||
WS_CHANNELS,
|
||||
WS_METHODS,
|
||||
type WsWelcomePayload,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { showContextMenuFallback } from "./contextMenuFallback";
|
||||
import { WsTransport } from "./wsTransport";
|
||||
|
||||
let instance: { api: NativeApi; transport: WsTransport } | null = null;
|
||||
const welcomeListeners = new Set<(payload: WsWelcomePayload) => void>();
|
||||
const serverConfigUpdatedListeners = new Set<(payload: ServerConfigUpdatedPayload) => void>();
|
||||
const providersUpdatedListeners = new Set<(payload: ServerProviderUpdatedPayload) => void>();
|
||||
const gitActionProgressListeners = new Set<(payload: GitActionProgressEvent) => void>();
|
||||
|
||||
/**
|
||||
* Subscribe to the server welcome message. If a welcome was already received
|
||||
* before this call, the listener fires synchronously with the cached payload.
|
||||
* This avoids the race between WebSocket connect and React effect registration.
|
||||
*/
|
||||
export function onServerWelcome(listener: (payload: WsWelcomePayload) => void): () => void {
|
||||
welcomeListeners.add(listener);
|
||||
|
||||
const latestWelcome = instance?.transport.getLatestPush(WS_CHANNELS.serverWelcome)?.data ?? null;
|
||||
if (latestWelcome) {
|
||||
try {
|
||||
listener(latestWelcome);
|
||||
} catch {
|
||||
// Swallow listener errors
|
||||
}
|
||||
}
|
||||
|
||||
return () => {
|
||||
welcomeListeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribe to server config update events. Replays the latest update for
|
||||
* late subscribers to avoid missing config validation feedback.
|
||||
*/
|
||||
export function onServerConfigUpdated(
|
||||
listener: (payload: ServerConfigUpdatedPayload) => void,
|
||||
): () => void {
|
||||
serverConfigUpdatedListeners.add(listener);
|
||||
|
||||
const latestConfig =
|
||||
instance?.transport.getLatestPush(WS_CHANNELS.serverConfigUpdated)?.data ?? null;
|
||||
if (latestConfig) {
|
||||
try {
|
||||
listener(latestConfig);
|
||||
} catch {
|
||||
// Swallow listener errors
|
||||
}
|
||||
}
|
||||
|
||||
return () => {
|
||||
serverConfigUpdatedListeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
export function onServerProvidersUpdated(
|
||||
listener: (payload: ServerProviderUpdatedPayload) => void,
|
||||
): () => void {
|
||||
providersUpdatedListeners.add(listener);
|
||||
|
||||
const latestProviders =
|
||||
instance?.transport.getLatestPush(WS_CHANNELS.serverProvidersUpdated)?.data ?? null;
|
||||
if (latestProviders) {
|
||||
try {
|
||||
listener(latestProviders);
|
||||
} catch {
|
||||
// Swallow listener errors
|
||||
}
|
||||
}
|
||||
|
||||
return () => {
|
||||
providersUpdatedListeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
export function createWsNativeApi(): NativeApi {
|
||||
if (instance) return instance.api;
|
||||
|
||||
const transport = new WsTransport();
|
||||
|
||||
transport.subscribe(WS_CHANNELS.serverWelcome, (message) => {
|
||||
const payload = message.data;
|
||||
for (const listener of welcomeListeners) {
|
||||
try {
|
||||
listener(payload);
|
||||
} catch {
|
||||
// Swallow listener errors
|
||||
}
|
||||
}
|
||||
});
|
||||
transport.subscribe(WS_CHANNELS.serverConfigUpdated, (message) => {
|
||||
const payload = message.data;
|
||||
for (const listener of serverConfigUpdatedListeners) {
|
||||
try {
|
||||
listener(payload);
|
||||
} catch {
|
||||
// Swallow listener errors
|
||||
}
|
||||
}
|
||||
});
|
||||
transport.subscribe(WS_CHANNELS.serverProvidersUpdated, (message) => {
|
||||
const payload = message.data;
|
||||
for (const listener of providersUpdatedListeners) {
|
||||
try {
|
||||
listener(payload);
|
||||
} catch {
|
||||
// Swallow listener errors
|
||||
}
|
||||
}
|
||||
});
|
||||
transport.subscribe(WS_CHANNELS.gitActionProgress, (message) => {
|
||||
const payload = message.data;
|
||||
for (const listener of gitActionProgressListeners) {
|
||||
try {
|
||||
listener(payload);
|
||||
} catch {
|
||||
// Swallow listener errors
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const api: NativeApi = {
|
||||
dialogs: {
|
||||
pickFolder: async () => {
|
||||
if (!window.desktopBridge) return null;
|
||||
return window.desktopBridge.pickFolder();
|
||||
},
|
||||
confirm: async (message) => {
|
||||
if (window.desktopBridge) {
|
||||
return window.desktopBridge.confirm(message);
|
||||
}
|
||||
return window.confirm(message);
|
||||
},
|
||||
},
|
||||
terminal: {
|
||||
open: (input) => transport.request(WS_METHODS.terminalOpen, input),
|
||||
write: (input) => transport.request(WS_METHODS.terminalWrite, input),
|
||||
resize: (input) => transport.request(WS_METHODS.terminalResize, input),
|
||||
clear: (input) => transport.request(WS_METHODS.terminalClear, input),
|
||||
restart: (input) => transport.request(WS_METHODS.terminalRestart, input),
|
||||
close: (input) => transport.request(WS_METHODS.terminalClose, input),
|
||||
onEvent: (callback) =>
|
||||
transport.subscribe(WS_CHANNELS.terminalEvent, (message) => callback(message.data)),
|
||||
},
|
||||
projects: {
|
||||
searchEntries: (input) => transport.request(WS_METHODS.projectsSearchEntries, input),
|
||||
writeFile: (input) => transport.request(WS_METHODS.projectsWriteFile, input),
|
||||
},
|
||||
shell: {
|
||||
openInEditor: (cwd, editor) =>
|
||||
transport.request(WS_METHODS.shellOpenInEditor, { cwd, editor }),
|
||||
openExternal: async (url) => {
|
||||
if (window.desktopBridge) {
|
||||
const opened = await window.desktopBridge.openExternal(url);
|
||||
if (!opened) {
|
||||
throw new Error("Unable to open link.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Some mobile browsers can return null here even when the tab opens.
|
||||
// Avoid false negatives and let the browser handle popup policy.
|
||||
window.open(url, "_blank", "noopener,noreferrer");
|
||||
},
|
||||
},
|
||||
git: {
|
||||
pull: (input) => transport.request(WS_METHODS.gitPull, input),
|
||||
status: (input) => transport.request(WS_METHODS.gitStatus, input),
|
||||
runStackedAction: (input) =>
|
||||
transport.request(WS_METHODS.gitRunStackedAction, input, { timeoutMs: null }),
|
||||
listBranches: (input) => transport.request(WS_METHODS.gitListBranches, input),
|
||||
createWorktree: (input) => transport.request(WS_METHODS.gitCreateWorktree, input),
|
||||
removeWorktree: (input) => transport.request(WS_METHODS.gitRemoveWorktree, input),
|
||||
createBranch: (input) => transport.request(WS_METHODS.gitCreateBranch, input),
|
||||
checkout: (input) => transport.request(WS_METHODS.gitCheckout, input),
|
||||
init: (input) => transport.request(WS_METHODS.gitInit, input),
|
||||
resolvePullRequest: (input) => transport.request(WS_METHODS.gitResolvePullRequest, input),
|
||||
preparePullRequestThread: (input) =>
|
||||
transport.request(WS_METHODS.gitPreparePullRequestThread, input),
|
||||
onActionProgress: (callback) => {
|
||||
gitActionProgressListeners.add(callback);
|
||||
return () => {
|
||||
gitActionProgressListeners.delete(callback);
|
||||
};
|
||||
},
|
||||
},
|
||||
contextMenu: {
|
||||
show: async <T extends string>(
|
||||
items: readonly ContextMenuItem<T>[],
|
||||
position?: { x: number; y: number },
|
||||
): Promise<T | null> => {
|
||||
if (window.desktopBridge) {
|
||||
return window.desktopBridge.showContextMenu(items, position) as Promise<T | null>;
|
||||
}
|
||||
return showContextMenuFallback(items, position);
|
||||
},
|
||||
},
|
||||
server: {
|
||||
getConfig: () => transport.request(WS_METHODS.serverGetConfig),
|
||||
refreshProviders: () => transport.request(WS_METHODS.serverRefreshProviders),
|
||||
upsertKeybinding: (input) => transport.request(WS_METHODS.serverUpsertKeybinding, input),
|
||||
getSettings: () => transport.request(WS_METHODS.serverGetSettings),
|
||||
updateSettings: (patch) => transport.request(WS_METHODS.serverUpdateSettings, { patch }),
|
||||
listAcpRegistry: () => transport.request(WS_METHODS.serverListAcpRegistry),
|
||||
},
|
||||
orchestration: {
|
||||
getSnapshot: () => transport.request(ORCHESTRATION_WS_METHODS.getSnapshot),
|
||||
dispatchCommand: (command) =>
|
||||
transport.request(ORCHESTRATION_WS_METHODS.dispatchCommand, { command }),
|
||||
getTurnDiff: (input) => transport.request(ORCHESTRATION_WS_METHODS.getTurnDiff, input),
|
||||
getFullThreadDiff: (input) =>
|
||||
transport.request(ORCHESTRATION_WS_METHODS.getFullThreadDiff, input),
|
||||
replayEvents: (fromSequenceExclusive) =>
|
||||
transport.request(ORCHESTRATION_WS_METHODS.replayEvents, { fromSequenceExclusive }),
|
||||
onDomainEvent: (callback) =>
|
||||
transport.subscribe(ORCHESTRATION_WS_CHANNELS.domainEvent, (message) =>
|
||||
callback(message.data),
|
||||
),
|
||||
},
|
||||
};
|
||||
|
||||
instance = { api, transport };
|
||||
return api;
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import { Schema } from "effect";
|
||||
import { IsoDateTime, TrimmedNonEmptyString } from "./baseSchemas";
|
||||
|
||||
export const AcpAgentServerId = TrimmedNonEmptyString.check(
|
||||
Schema.isMaxLength(128),
|
||||
Schema.isPattern(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
|
||||
);
|
||||
export type AcpAgentServerId = typeof AcpAgentServerId.Type;
|
||||
|
||||
export const AcpDistributionType = Schema.Literals(["manual", "npx", "uvx", "binaryUnsupported"]);
|
||||
export type AcpDistributionType = typeof AcpDistributionType.Type;
|
||||
|
||||
export const AcpAgentSource = Schema.Literals(["manual", "registry"]);
|
||||
export type AcpAgentSource = typeof AcpAgentSource.Type;
|
||||
|
||||
export const AcpLaunchSpec = Schema.Struct({
|
||||
command: TrimmedNonEmptyString,
|
||||
args: Schema.Array(TrimmedNonEmptyString).pipe(Schema.withDecodingDefault(() => [])),
|
||||
});
|
||||
export type AcpLaunchSpec = typeof AcpLaunchSpec.Type;
|
||||
|
||||
export const AcpAgentServer = Schema.Struct({
|
||||
id: AcpAgentServerId,
|
||||
name: TrimmedNonEmptyString,
|
||||
enabled: Schema.Boolean.pipe(Schema.withDecodingDefault(() => true)),
|
||||
source: AcpAgentSource,
|
||||
distributionType: AcpDistributionType,
|
||||
launch: AcpLaunchSpec,
|
||||
description: Schema.optional(TrimmedNonEmptyString),
|
||||
website: Schema.optional(TrimmedNonEmptyString),
|
||||
repository: Schema.optional(TrimmedNonEmptyString),
|
||||
iconUrl: Schema.optional(TrimmedNonEmptyString),
|
||||
registryAgentId: Schema.optional(TrimmedNonEmptyString),
|
||||
importedVersion: Schema.optional(TrimmedNonEmptyString),
|
||||
});
|
||||
export type AcpAgentServer = typeof AcpAgentServer.Type;
|
||||
|
||||
export const ServerAcpAgentStatus = Schema.Struct({
|
||||
agentServerId: AcpAgentServerId,
|
||||
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;
|
||||
|
||||
const AcpRegistryBinaryDistribution = Schema.Record(
|
||||
Schema.String,
|
||||
Schema.Struct({
|
||||
archive: TrimmedNonEmptyString,
|
||||
cmd: TrimmedNonEmptyString,
|
||||
args: Schema.optional(Schema.Array(TrimmedNonEmptyString)),
|
||||
}),
|
||||
);
|
||||
|
||||
export const AcpRegistryAgent = Schema.Struct({
|
||||
id: AcpAgentServerId,
|
||||
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({
|
||||
binary: Schema.optional(AcpRegistryBinaryDistribution),
|
||||
npx: Schema.optional(
|
||||
Schema.Struct({
|
||||
package: TrimmedNonEmptyString,
|
||||
args: Schema.optional(Schema.Array(TrimmedNonEmptyString)),
|
||||
}),
|
||||
),
|
||||
uvx: Schema.optional(
|
||||
Schema.Struct({
|
||||
package: TrimmedNonEmptyString,
|
||||
args: Schema.optional(Schema.Array(TrimmedNonEmptyString)),
|
||||
}),
|
||||
),
|
||||
}),
|
||||
});
|
||||
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),
|
||||
});
|
||||
export type ResolvedRegistryAcpAgent = typeof ResolvedRegistryAcpAgent.Type;
|
||||
|
||||
export const AcpRegistryListResult = Schema.Struct({
|
||||
registryVersion: TrimmedNonEmptyString,
|
||||
agents: Schema.Array(ResolvedRegistryAcpAgent),
|
||||
});
|
||||
export type AcpRegistryListResult = typeof AcpRegistryListResult.Type;
|
||||
@@ -1,17 +1,15 @@
|
||||
export * from "./baseSchemas.ts";
|
||||
export * from "./auth.ts";
|
||||
export * from "./environment.ts";
|
||||
export * from "./ipc.ts";
|
||||
export * from "./terminal.ts";
|
||||
export * from "./provider.ts";
|
||||
export * from "./providerRuntime.ts";
|
||||
export * from "./model.ts";
|
||||
export * from "./keybindings.ts";
|
||||
export * from "./server.ts";
|
||||
export * from "./settings.ts";
|
||||
export * from "./git.ts";
|
||||
export * from "./orchestration.ts";
|
||||
export * from "./editor.ts";
|
||||
export * from "./project.ts";
|
||||
export * from "./filesystem.ts";
|
||||
export * from "./rpc.ts";
|
||||
export * from "./baseSchemas";
|
||||
export * from "./acp";
|
||||
export * from "./ipc";
|
||||
export * from "./terminal";
|
||||
export * from "./provider";
|
||||
export * from "./providerRuntime";
|
||||
export * from "./model";
|
||||
export * from "./ws";
|
||||
export * from "./keybindings";
|
||||
export * from "./server";
|
||||
export * from "./settings";
|
||||
export * from "./git";
|
||||
export * from "./orchestration";
|
||||
export * from "./editor";
|
||||
export * from "./project";
|
||||
@@ -29,7 +29,8 @@ import type {
|
||||
ServerConfig,
|
||||
ServerProviderUpdatedPayload,
|
||||
ServerUpsertKeybindingResult,
|
||||
} from "./server.ts";
|
||||
} from "./server";
|
||||
import type { AcpRegistryListResult } from "./acp";
|
||||
import type {
|
||||
TerminalClearInput,
|
||||
TerminalCloseInput,
|
||||
@@ -219,6 +220,7 @@ export interface LocalApi {
|
||||
upsertKeybinding: (input: ServerUpsertKeybindingInput) => Promise<ServerUpsertKeybindingResult>;
|
||||
getSettings: () => Promise<ServerSettings>;
|
||||
updateSettings: (patch: ServerSettingsPatch) => Promise<ServerSettings>;
|
||||
listAcpRegistry: () => Promise<AcpRegistryListResult>;
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -40,6 +40,7 @@ export const ProviderModelOptions = Schema.Struct({
|
||||
codex: Schema.optional(CodexModelOptions),
|
||||
claudeAgent: Schema.optional(ClaudeModelOptions),
|
||||
cursor: Schema.optional(CursorModelOptions),
|
||||
acp: Schema.optional(Schema.Struct({})),
|
||||
});
|
||||
export type ProviderModelOptions = typeof ProviderModelOptions.Type;
|
||||
|
||||
@@ -72,6 +73,7 @@ export const DEFAULT_MODEL_BY_PROVIDER: Record<ProviderKind, string> = {
|
||||
codex: "gpt-5.4",
|
||||
claudeAgent: "claude-sonnet-4-6",
|
||||
cursor: "auto",
|
||||
acp: "default",
|
||||
};
|
||||
|
||||
export const DEFAULT_MODEL = DEFAULT_MODEL_BY_PROVIDER.codex;
|
||||
@@ -81,6 +83,7 @@ export const DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER: Record<ProviderKind,
|
||||
codex: "gpt-5.4-mini",
|
||||
claudeAgent: "claude-haiku-4-5",
|
||||
cursor: "composer-2",
|
||||
acp: "default",
|
||||
};
|
||||
|
||||
export const MODEL_SLUG_ALIASES_BY_PROVIDER: Record<ProviderKind, Record<string, string>> = {
|
||||
@@ -127,6 +130,7 @@ export const MODEL_SLUG_ALIASES_BY_PROVIDER: Record<ProviderKind, Record<string,
|
||||
"opus-4.5-thinking": "claude-opus-4-5",
|
||||
"opus-4.5": "claude-opus-4-5",
|
||||
},
|
||||
acp: {},
|
||||
};
|
||||
|
||||
// ── Provider display names ────────────────────────────────────────────
|
||||
@@ -135,4 +139,5 @@ export const PROVIDER_DISPLAY_NAMES: Record<ProviderKind, string> = {
|
||||
codex: "Codex",
|
||||
claudeAgent: "Claude",
|
||||
cursor: "Cursor",
|
||||
acp: "ACP Agent",
|
||||
};
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Option, Schema, SchemaIssue, Struct } from "effect";
|
||||
import { AcpAgentServerId } from "./acp";
|
||||
import { ClaudeModelOptions, CodexModelOptions, CursorModelOptions } from "./model";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
@@ -28,7 +29,7 @@ export const ORCHESTRATION_WS_CHANNELS = {
|
||||
domainEvent: "orchestration.domainEvent",
|
||||
} as const;
|
||||
|
||||
export const ProviderKind = Schema.Literals(["codex", "claudeAgent", "cursor"]);
|
||||
export const ProviderKind = Schema.Literals(["codex", "claudeAgent", "cursor", "acp"]);
|
||||
export type ProviderKind = typeof ProviderKind.Type;
|
||||
export const ProviderApprovalPolicy = Schema.Literals([
|
||||
"untrusted",
|
||||
@@ -67,10 +68,18 @@ export const CursorModelSelection = Schema.Struct({
|
||||
});
|
||||
export type CursorModelSelection = typeof CursorModelSelection.Type;
|
||||
|
||||
export const AcpModelSelection = Schema.Struct({
|
||||
provider: Schema.Literal("acp"),
|
||||
agentServerId: AcpAgentServerId,
|
||||
model: TrimmedNonEmptyString,
|
||||
});
|
||||
export type AcpModelSelection = typeof AcpModelSelection.Type;
|
||||
|
||||
export const ModelSelection = Schema.Union([
|
||||
CodexModelSelection,
|
||||
ClaudeModelSelection,
|
||||
CursorModelSelection,
|
||||
AcpModelSelection,
|
||||
]);
|
||||
export type ModelSelection = typeof ModelSelection.Type;
|
||||
|
||||
|
||||
@@ -24,10 +24,10 @@ describe("ProviderSessionStartInput", () => {
|
||||
});
|
||||
expect(parsed.runtimeMode).toBe("full-access");
|
||||
expect(parsed.modelSelection?.provider).toBe("codex");
|
||||
expect(parsed.modelSelection?.model).toBe("gpt-5.3-codex");
|
||||
if (parsed.modelSelection?.provider !== "codex") {
|
||||
throw new Error("Expected codex modelSelection");
|
||||
}
|
||||
expect(parsed.modelSelection.model).toBe("gpt-5.3-codex");
|
||||
expect(parsed.modelSelection.options?.reasoningEffort).toBe("high");
|
||||
expect(parsed.modelSelection.options?.fastMode).toBe(true);
|
||||
});
|
||||
@@ -59,10 +59,10 @@ describe("ProviderSessionStartInput", () => {
|
||||
});
|
||||
expect(parsed.provider).toBe("claudeAgent");
|
||||
expect(parsed.modelSelection?.provider).toBe("claudeAgent");
|
||||
expect(parsed.modelSelection?.model).toBe("claude-sonnet-4-6");
|
||||
if (parsed.modelSelection?.provider !== "claudeAgent") {
|
||||
throw new Error("Expected claude modelSelection");
|
||||
}
|
||||
expect(parsed.modelSelection.model).toBe("claude-sonnet-4-6");
|
||||
expect(parsed.modelSelection.options?.thinking).toBe(true);
|
||||
expect(parsed.modelSelection.options?.effort).toBe("max");
|
||||
expect(parsed.modelSelection.options?.fastMode).toBe(true);
|
||||
@@ -83,8 +83,8 @@ describe("ProviderSessionStartInput", () => {
|
||||
});
|
||||
expect(parsed.provider).toBe("cursor");
|
||||
expect(parsed.modelSelection?.provider).toBe("cursor");
|
||||
expect(parsed.modelSelection?.model).toBe("composer-2");
|
||||
if (parsed.modelSelection?.provider === "cursor") {
|
||||
expect(parsed.modelSelection.model).toBe("composer-2");
|
||||
expect(parsed.modelSelection.options?.fastMode).toBe(true);
|
||||
}
|
||||
});
|
||||
@@ -105,10 +105,10 @@ describe("ProviderSendTurnInput", () => {
|
||||
});
|
||||
|
||||
expect(parsed.modelSelection?.provider).toBe("codex");
|
||||
expect(parsed.modelSelection?.model).toBe("gpt-5.3-codex");
|
||||
if (parsed.modelSelection?.provider !== "codex") {
|
||||
throw new Error("Expected codex modelSelection");
|
||||
}
|
||||
expect(parsed.modelSelection.model).toBe("gpt-5.3-codex");
|
||||
expect(parsed.modelSelection.options?.reasoningEffort).toBe("xhigh");
|
||||
expect(parsed.modelSelection.options?.fastMode).toBe(true);
|
||||
});
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Schema } from "effect";
|
||||
import { TrimmedNonEmptyString } from "./baseSchemas.ts";
|
||||
import { AcpAgentServerId } from "./acp";
|
||||
import { TrimmedNonEmptyString } from "./baseSchemas";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
EventId,
|
||||
@@ -33,6 +34,7 @@ const ProviderSessionStatus = Schema.Literals([
|
||||
|
||||
export const ProviderSession = Schema.Struct({
|
||||
provider: ProviderKind,
|
||||
agentServerId: Schema.optional(AcpAgentServerId),
|
||||
status: ProviderSessionStatus,
|
||||
runtimeMode: RuntimeMode,
|
||||
cwd: Schema.optional(TrimmedNonEmptyString),
|
||||
@@ -109,6 +111,7 @@ export const ProviderEvent = Schema.Struct({
|
||||
id: EventId,
|
||||
kind: ProviderEventKind,
|
||||
provider: ProviderKind,
|
||||
agentServerId: Schema.optional(AcpAgentServerId),
|
||||
threadId: ThreadId,
|
||||
createdAt: IsoDateTime,
|
||||
method: TrimmedNonEmptyString,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Effect, Schema } from "effect";
|
||||
import { Option, Schema } from "effect";
|
||||
import { AcpAgentServerId } from "./acp";
|
||||
import {
|
||||
EventId,
|
||||
IsoDateTime,
|
||||
@@ -245,6 +246,7 @@ const RuntimeErrorType = Schema.Literal("runtime.error");
|
||||
const ProviderRuntimeEventBase = Schema.Struct({
|
||||
eventId: EventId,
|
||||
provider: ProviderKind,
|
||||
agentServerId: Schema.optional(AcpAgentServerId),
|
||||
threadId: ThreadId,
|
||||
createdAt: IsoDateTime,
|
||||
turnId: Schema.optional(TurnId),
|
||||
|
||||
@@ -1,18 +1,11 @@
|
||||
import { Effect, Schema } from "effect";
|
||||
import { ExecutionEnvironmentDescriptor } from "./environment.ts";
|
||||
import { ServerAuthDescriptor } from "./auth.ts";
|
||||
import {
|
||||
IsoDateTime,
|
||||
NonNegativeInt,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
TrimmedNonEmptyString,
|
||||
} from "./baseSchemas.ts";
|
||||
import { KeybindingRule, ResolvedKeybindingsConfig } from "./keybindings.ts";
|
||||
import { EditorId } from "./editor.ts";
|
||||
import { ModelCapabilities } from "./model.ts";
|
||||
import { ProviderKind } from "./orchestration.ts";
|
||||
import { ServerSettings } from "./settings.ts";
|
||||
import { Schema } from "effect";
|
||||
import { ServerAcpAgentStatus } from "./acp";
|
||||
import { IsoDateTime, TrimmedNonEmptyString } from "./baseSchemas";
|
||||
import { KeybindingRule, ResolvedKeybindingsConfig } from "./keybindings";
|
||||
import { EditorId } from "./editor";
|
||||
import { ModelCapabilities } from "./model";
|
||||
import { ProviderKind } from "./orchestration";
|
||||
import { ServerSettings } from "./settings";
|
||||
|
||||
const KeybindingsMalformedConfigIssue = Schema.Struct({
|
||||
kind: Schema.Literal("keybindings.malformed-config"),
|
||||
@@ -119,6 +112,7 @@ export const ServerConfig = Schema.Struct({
|
||||
keybindings: ResolvedKeybindingsConfig,
|
||||
issues: ServerConfigIssues,
|
||||
providers: ServerProviders,
|
||||
acpAgentServers: Schema.Array(ServerAcpAgentStatus),
|
||||
availableEditors: Schema.Array(EditorId),
|
||||
observability: ServerObservability,
|
||||
settings: ServerSettings,
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { Effect } from "effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SchemaTransformation from "effect/SchemaTransformation";
|
||||
import { TrimmedNonEmptyString, TrimmedString } from "./baseSchemas.ts";
|
||||
import { AcpAgentServer } from "./acp";
|
||||
import { TrimmedNonEmptyString, TrimmedString } from "./baseSchemas";
|
||||
import {
|
||||
ClaudeModelOptions,
|
||||
CodexModelOptions,
|
||||
@@ -99,6 +100,17 @@ export const CursorSettings = Schema.Struct({
|
||||
});
|
||||
export type CursorSettings = typeof CursorSettings.Type;
|
||||
|
||||
export const AcpSettings = Schema.Struct({
|
||||
enabled: Schema.Boolean.pipe(Schema.withDecodingDefault(() => true)),
|
||||
registryUrl: TrimmedString.pipe(
|
||||
Schema.withDecodingDefault(
|
||||
() => "https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json",
|
||||
),
|
||||
),
|
||||
agentServers: Schema.Array(AcpAgentServer).pipe(Schema.withDecodingDefault(() => [])),
|
||||
});
|
||||
export type AcpSettings = typeof AcpSettings.Type;
|
||||
|
||||
export const ServerSettings = Schema.Struct({
|
||||
enableAssistantStreaming: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
|
||||
defaultThreadEnvMode: ThreadEnvMode.pipe(
|
||||
@@ -119,6 +131,7 @@ export const ServerSettings = Schema.Struct({
|
||||
codex: CodexSettings.pipe(Schema.withDecodingDefault(() => ({}))),
|
||||
claudeAgent: ClaudeSettings.pipe(Schema.withDecodingDefault(() => ({}))),
|
||||
cursor: CursorSettings.pipe(Schema.withDecodingDefault(() => ({}))),
|
||||
acp: AcpSettings.pipe(Schema.withDecodingDefault(() => ({}))),
|
||||
}).pipe(Schema.withDecodingDefault(() => ({}))),
|
||||
});
|
||||
export type ServerSettings = typeof ServerSettings.Type;
|
||||
@@ -195,6 +208,11 @@ const ModelSelectionPatch = Schema.Union([
|
||||
model: Schema.optionalKey(TrimmedNonEmptyString),
|
||||
options: Schema.optionalKey(CursorModelOptionsPatch),
|
||||
}),
|
||||
Schema.Struct({
|
||||
provider: Schema.optionalKey(Schema.Literal("acp")),
|
||||
agentServerId: Schema.optionalKey(TrimmedNonEmptyString),
|
||||
model: Schema.optionalKey(TrimmedNonEmptyString),
|
||||
}),
|
||||
]);
|
||||
|
||||
const CodexSettingsPatch = Schema.Struct({
|
||||
@@ -233,6 +251,12 @@ const CursorSettingsPatch = Schema.Struct({
|
||||
customModels: Schema.optionalKey(Schema.Array(Schema.String)),
|
||||
});
|
||||
|
||||
const AcpSettingsPatch = Schema.Struct({
|
||||
enabled: Schema.optionalKey(Schema.Boolean),
|
||||
registryUrl: Schema.optionalKey(Schema.String),
|
||||
agentServers: Schema.optionalKey(Schema.Array(AcpAgentServer)),
|
||||
});
|
||||
|
||||
export const ServerSettingsPatch = Schema.Struct({
|
||||
enableAssistantStreaming: Schema.optionalKey(Schema.Boolean),
|
||||
defaultThreadEnvMode: Schema.optionalKey(ThreadEnvMode),
|
||||
@@ -249,6 +273,7 @@ export const ServerSettingsPatch = Schema.Struct({
|
||||
codex: Schema.optionalKey(CodexSettingsPatch),
|
||||
claudeAgent: Schema.optionalKey(ClaudeSettingsPatch),
|
||||
cursor: Schema.optionalKey(CursorSettingsPatch),
|
||||
acp: Schema.optionalKey(AcpSettingsPatch),
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
@@ -0,0 +1,259 @@
|
||||
import { Schema, Struct } from "effect";
|
||||
import { NonNegativeInt, ProjectId, ThreadId, TrimmedNonEmptyString } from "./baseSchemas";
|
||||
|
||||
import {
|
||||
ClientOrchestrationCommand,
|
||||
OrchestrationEvent,
|
||||
ORCHESTRATION_WS_CHANNELS,
|
||||
OrchestrationGetFullThreadDiffInput,
|
||||
ORCHESTRATION_WS_METHODS,
|
||||
OrchestrationGetSnapshotInput,
|
||||
OrchestrationGetTurnDiffInput,
|
||||
OrchestrationReplayEventsInput,
|
||||
} from "./orchestration";
|
||||
import {
|
||||
GitActionProgressEvent,
|
||||
GitCheckoutInput,
|
||||
GitCreateBranchInput,
|
||||
GitPreparePullRequestThreadInput,
|
||||
GitCreateWorktreeInput,
|
||||
GitInitInput,
|
||||
GitListBranchesInput,
|
||||
GitPullInput,
|
||||
GitPullRequestRefInput,
|
||||
GitRemoveWorktreeInput,
|
||||
GitRunStackedActionInput,
|
||||
GitStatusInput,
|
||||
} from "./git";
|
||||
import {
|
||||
TerminalClearInput,
|
||||
TerminalCloseInput,
|
||||
TerminalEvent,
|
||||
TerminalOpenInput,
|
||||
TerminalResizeInput,
|
||||
TerminalRestartInput,
|
||||
TerminalWriteInput,
|
||||
} from "./terminal";
|
||||
import { KeybindingRule } from "./keybindings";
|
||||
import { ProjectSearchEntriesInput, ProjectWriteFileInput } from "./project";
|
||||
import { OpenInEditorInput } from "./editor";
|
||||
import { ServerConfigUpdatedPayload, ServerProviderUpdatedPayload } from "./server";
|
||||
import { ServerSettingsPatch } from "./settings";
|
||||
|
||||
// ── WebSocket RPC Method Names ───────────────────────────────────────
|
||||
|
||||
export const WS_METHODS = {
|
||||
// Project registry methods
|
||||
projectsList: "projects.list",
|
||||
projectsAdd: "projects.add",
|
||||
projectsRemove: "projects.remove",
|
||||
projectsSearchEntries: "projects.searchEntries",
|
||||
projectsWriteFile: "projects.writeFile",
|
||||
|
||||
// Shell methods
|
||||
shellOpenInEditor: "shell.openInEditor",
|
||||
|
||||
// Git methods
|
||||
gitPull: "git.pull",
|
||||
gitStatus: "git.status",
|
||||
gitRunStackedAction: "git.runStackedAction",
|
||||
gitListBranches: "git.listBranches",
|
||||
gitCreateWorktree: "git.createWorktree",
|
||||
gitRemoveWorktree: "git.removeWorktree",
|
||||
gitCreateBranch: "git.createBranch",
|
||||
gitCheckout: "git.checkout",
|
||||
gitInit: "git.init",
|
||||
gitResolvePullRequest: "git.resolvePullRequest",
|
||||
gitPreparePullRequestThread: "git.preparePullRequestThread",
|
||||
|
||||
// Terminal methods
|
||||
terminalOpen: "terminal.open",
|
||||
terminalWrite: "terminal.write",
|
||||
terminalResize: "terminal.resize",
|
||||
terminalClear: "terminal.clear",
|
||||
terminalRestart: "terminal.restart",
|
||||
terminalClose: "terminal.close",
|
||||
|
||||
// Server meta
|
||||
serverGetConfig: "server.getConfig",
|
||||
serverRefreshProviders: "server.refreshProviders",
|
||||
serverUpsertKeybinding: "server.upsertKeybinding",
|
||||
serverGetSettings: "server.getSettings",
|
||||
serverUpdateSettings: "server.updateSettings",
|
||||
serverListAcpRegistry: "server.listAcpRegistry",
|
||||
} as const;
|
||||
|
||||
// ── Push Event Channels ──────────────────────────────────────────────
|
||||
|
||||
export const WS_CHANNELS = {
|
||||
gitActionProgress: "git.actionProgress",
|
||||
terminalEvent: "terminal.event",
|
||||
serverWelcome: "server.welcome",
|
||||
serverConfigUpdated: "server.configUpdated",
|
||||
serverProvidersUpdated: "server.providersUpdated",
|
||||
} as const;
|
||||
|
||||
// -- Tagged Union of all request body schemas ─────────────────────────
|
||||
|
||||
const tagRequestBody = <const Tag extends string, const Fields extends Schema.Struct.Fields>(
|
||||
tag: Tag,
|
||||
schema: Schema.Struct<Fields>,
|
||||
) =>
|
||||
schema.mapFields(
|
||||
Struct.assign({ _tag: Schema.tag(tag) }),
|
||||
// PreserveChecks is safe here. No existing schema should have checks depending on the tag
|
||||
{ unsafePreserveChecks: true },
|
||||
);
|
||||
|
||||
const WebSocketRequestBody = Schema.Union([
|
||||
// Orchestration methods
|
||||
tagRequestBody(
|
||||
ORCHESTRATION_WS_METHODS.dispatchCommand,
|
||||
Schema.Struct({ command: ClientOrchestrationCommand }),
|
||||
),
|
||||
tagRequestBody(ORCHESTRATION_WS_METHODS.getSnapshot, OrchestrationGetSnapshotInput),
|
||||
tagRequestBody(ORCHESTRATION_WS_METHODS.getTurnDiff, OrchestrationGetTurnDiffInput),
|
||||
tagRequestBody(ORCHESTRATION_WS_METHODS.getFullThreadDiff, OrchestrationGetFullThreadDiffInput),
|
||||
tagRequestBody(ORCHESTRATION_WS_METHODS.replayEvents, OrchestrationReplayEventsInput),
|
||||
|
||||
// Project Search
|
||||
tagRequestBody(WS_METHODS.projectsSearchEntries, ProjectSearchEntriesInput),
|
||||
tagRequestBody(WS_METHODS.projectsWriteFile, ProjectWriteFileInput),
|
||||
|
||||
// Shell methods
|
||||
tagRequestBody(WS_METHODS.shellOpenInEditor, OpenInEditorInput),
|
||||
|
||||
// Git methods
|
||||
tagRequestBody(WS_METHODS.gitPull, GitPullInput),
|
||||
tagRequestBody(WS_METHODS.gitStatus, GitStatusInput),
|
||||
tagRequestBody(WS_METHODS.gitRunStackedAction, GitRunStackedActionInput),
|
||||
tagRequestBody(WS_METHODS.gitListBranches, GitListBranchesInput),
|
||||
tagRequestBody(WS_METHODS.gitCreateWorktree, GitCreateWorktreeInput),
|
||||
tagRequestBody(WS_METHODS.gitRemoveWorktree, GitRemoveWorktreeInput),
|
||||
tagRequestBody(WS_METHODS.gitCreateBranch, GitCreateBranchInput),
|
||||
tagRequestBody(WS_METHODS.gitCheckout, GitCheckoutInput),
|
||||
tagRequestBody(WS_METHODS.gitInit, GitInitInput),
|
||||
tagRequestBody(WS_METHODS.gitResolvePullRequest, GitPullRequestRefInput),
|
||||
tagRequestBody(WS_METHODS.gitPreparePullRequestThread, GitPreparePullRequestThreadInput),
|
||||
|
||||
// Terminal methods
|
||||
tagRequestBody(WS_METHODS.terminalOpen, TerminalOpenInput),
|
||||
tagRequestBody(WS_METHODS.terminalWrite, TerminalWriteInput),
|
||||
tagRequestBody(WS_METHODS.terminalResize, TerminalResizeInput),
|
||||
tagRequestBody(WS_METHODS.terminalClear, TerminalClearInput),
|
||||
tagRequestBody(WS_METHODS.terminalRestart, TerminalRestartInput),
|
||||
tagRequestBody(WS_METHODS.terminalClose, TerminalCloseInput),
|
||||
|
||||
// Server meta
|
||||
tagRequestBody(WS_METHODS.serverGetConfig, Schema.Struct({})),
|
||||
tagRequestBody(WS_METHODS.serverRefreshProviders, Schema.Struct({})),
|
||||
tagRequestBody(WS_METHODS.serverUpsertKeybinding, KeybindingRule),
|
||||
tagRequestBody(WS_METHODS.serverGetSettings, Schema.Struct({})),
|
||||
tagRequestBody(WS_METHODS.serverUpdateSettings, Schema.Struct({ patch: ServerSettingsPatch })),
|
||||
tagRequestBody(WS_METHODS.serverListAcpRegistry, Schema.Struct({})),
|
||||
]);
|
||||
|
||||
export const WebSocketRequest = Schema.Struct({
|
||||
id: TrimmedNonEmptyString,
|
||||
body: WebSocketRequestBody,
|
||||
});
|
||||
export type WebSocketRequest = typeof WebSocketRequest.Type;
|
||||
|
||||
export const WebSocketResponse = Schema.Struct({
|
||||
id: TrimmedNonEmptyString,
|
||||
result: Schema.optional(Schema.Unknown),
|
||||
error: Schema.optional(
|
||||
Schema.Struct({
|
||||
message: Schema.String,
|
||||
}),
|
||||
),
|
||||
});
|
||||
export type WebSocketResponse = typeof WebSocketResponse.Type;
|
||||
|
||||
export const WsPushSequence = NonNegativeInt;
|
||||
export type WsPushSequence = typeof WsPushSequence.Type;
|
||||
|
||||
export const WsWelcomePayload = Schema.Struct({
|
||||
cwd: TrimmedNonEmptyString,
|
||||
projectName: TrimmedNonEmptyString,
|
||||
bootstrapProjectId: Schema.optional(ProjectId),
|
||||
bootstrapThreadId: Schema.optional(ThreadId),
|
||||
});
|
||||
export type WsWelcomePayload = typeof WsWelcomePayload.Type;
|
||||
|
||||
export interface WsPushPayloadByChannel {
|
||||
readonly [WS_CHANNELS.serverWelcome]: WsWelcomePayload;
|
||||
readonly [WS_CHANNELS.serverConfigUpdated]: typeof ServerConfigUpdatedPayload.Type;
|
||||
readonly [WS_CHANNELS.serverProvidersUpdated]: typeof ServerProviderUpdatedPayload.Type;
|
||||
readonly [WS_CHANNELS.gitActionProgress]: typeof GitActionProgressEvent.Type;
|
||||
readonly [WS_CHANNELS.terminalEvent]: typeof TerminalEvent.Type;
|
||||
readonly [ORCHESTRATION_WS_CHANNELS.domainEvent]: OrchestrationEvent;
|
||||
}
|
||||
|
||||
export type WsPushChannel = keyof WsPushPayloadByChannel;
|
||||
export type WsPushData<C extends WsPushChannel> = WsPushPayloadByChannel[C];
|
||||
|
||||
const makeWsPushSchema = <const Channel extends string, Payload extends Schema.Schema<any>>(
|
||||
channel: Channel,
|
||||
payload: Payload,
|
||||
) =>
|
||||
Schema.Struct({
|
||||
type: Schema.Literal("push"),
|
||||
sequence: WsPushSequence,
|
||||
channel: Schema.Literal(channel),
|
||||
data: payload,
|
||||
});
|
||||
|
||||
export const WsPushServerWelcome = makeWsPushSchema(WS_CHANNELS.serverWelcome, WsWelcomePayload);
|
||||
export const WsPushServerConfigUpdated = makeWsPushSchema(
|
||||
WS_CHANNELS.serverConfigUpdated,
|
||||
ServerConfigUpdatedPayload,
|
||||
);
|
||||
export const WsPushServerProvidersUpdated = makeWsPushSchema(
|
||||
WS_CHANNELS.serverProvidersUpdated,
|
||||
ServerProviderUpdatedPayload,
|
||||
);
|
||||
export const WsPushGitActionProgress = makeWsPushSchema(
|
||||
WS_CHANNELS.gitActionProgress,
|
||||
GitActionProgressEvent,
|
||||
);
|
||||
export const WsPushTerminalEvent = makeWsPushSchema(WS_CHANNELS.terminalEvent, TerminalEvent);
|
||||
export const WsPushOrchestrationDomainEvent = makeWsPushSchema(
|
||||
ORCHESTRATION_WS_CHANNELS.domainEvent,
|
||||
OrchestrationEvent,
|
||||
);
|
||||
|
||||
export const WsPushChannelSchema = Schema.Literals([
|
||||
WS_CHANNELS.gitActionProgress,
|
||||
WS_CHANNELS.serverWelcome,
|
||||
WS_CHANNELS.serverConfigUpdated,
|
||||
WS_CHANNELS.serverProvidersUpdated,
|
||||
WS_CHANNELS.terminalEvent,
|
||||
ORCHESTRATION_WS_CHANNELS.domainEvent,
|
||||
]);
|
||||
export type WsPushChannelSchema = typeof WsPushChannelSchema.Type;
|
||||
|
||||
export const WsPush = Schema.Union([
|
||||
WsPushServerWelcome,
|
||||
WsPushServerConfigUpdated,
|
||||
WsPushServerProvidersUpdated,
|
||||
WsPushGitActionProgress,
|
||||
WsPushTerminalEvent,
|
||||
WsPushOrchestrationDomainEvent,
|
||||
]);
|
||||
export type WsPush = typeof WsPush.Type;
|
||||
|
||||
export type WsPushMessage<C extends WsPushChannel> = Extract<WsPush, { channel: C }>;
|
||||
|
||||
export const WsPushEnvelopeBase = Schema.Struct({
|
||||
type: Schema.Literal("push"),
|
||||
sequence: WsPushSequence,
|
||||
channel: WsPushChannelSchema,
|
||||
data: Schema.Unknown,
|
||||
});
|
||||
export type WsPushEnvelopeBase = typeof WsPushEnvelopeBase.Type;
|
||||
|
||||
// ── Union of all server → client messages ─────────────────────────────
|
||||
|
||||
export const WsResponse = Schema.Union([WebSocketResponse, WsPush]);
|
||||
export type WsResponse = typeof WsResponse.Type;
|
||||
Reference in new issue
Block a user