The best way to control Claude Code, Codex and more from any computer or phone

main
ts 372 lines 14 KB
Raw
1 import type * as EffectAcpSchema from "effect-acp/compat";
2 import {
3 type ModelSelection,
4 type ProviderOptionDescriptor,
5 ProviderDriverKind,
6 type RuntimeMode,
7 } from "@t3tools/contracts";
8 import type { FxSettings } from "../settings.ts";
9 import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
10 import type * as SecureRandom from "effect/crypto/SecureRandom";
11 import * as Effect from "effect/Effect";
12 import * as Layer from "effect/Layer";
13 import * as Option from "effect/Option";
14 import * as Schema from "effect/Schema";
15 import type * as Scope from "effect/Scope";
16 import type * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
17 import * as EffectAcpErrors from "effect-acp/errors";
18
19 import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
20 import { collectSessionConfigOptionValues } from "@t3tools/provider-acp/server/runtimeModel";
21 import {
22 acpPermissionDisposition,
23 type AcpPermissionDisposition,
24 } from "@t3tools/provider-acp/server/clientPolicy";
25 import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
26
27 export const FX_DRIVER_KIND = ProviderDriverKind.make("fx");
28 /** T3's slug for "Default": the model `fx status` reports, never an fx model id. */
29 export const FX_DEFAULT_MODEL_SLUG = "default";
30 const FX_PROVIDER_CONFIG_ID = "provider";
31 const FX_MODEL_CONFIG_ID = "model";
32 export const FX_MODE_CONFIG_ID = "mode";
33 const FX_EFFORT_CONFIG_ID = "effort";
34 const FX_DEFAULT_EFFORT = "medium";
35
36 const FX_EFFORT_LABELS = {
37 auto: "Auto",
38 low: "Low",
39 medium: "Medium",
40 high: "High",
41 xhigh: "Extra High",
42 max: "Max",
43 } as const;
44
45 export const FX_EFFORT_OPTION_DESCRIPTOR: ProviderOptionDescriptor = {
46 id: FX_EFFORT_CONFIG_ID,
47 label: "Effort",
48 type: "select",
49 options: Object.entries(FX_EFFORT_LABELS).map(([id, label]) => ({
50 id,
51 label,
52 ...(id === FX_DEFAULT_EFFORT ? { isDefault: true } : {}),
53 })),
54 };
55
56 /** Every fx offers these; the provider snapshot adds Full access where `fx status` lists `full-access`. */
57 export const FX_SUPPORTED_RUNTIME_MODES = [
58 "approval-required",
59 "auto",
60 ] as const satisfies ReadonlyArray<RuntimeMode>;
61 /** fx 0.0.14+; fx 0.0.13 has no such mode. */
62 export const FX_FULL_ACCESS_MODE_ID = "full-access";
63 /** fx 0.0.13 answers a cancelled prompt with `stopReason: cancelled`. */
64 export const FX_ACP_CANCEL_BEHAVIOR = "wait-for-prompt" as const;
65 /** fx inherits the user's `~/.fx/mcp.json` servers only when session setup asks for them. */
66 export const FX_SESSION_META = { fx: { profileMcpServers: true } };
67
68 const isCancelledFxCommand = Schema.is(
69 Schema.Struct({
70 update: Schema.Struct({
71 command_result: Schema.Struct({
72 exit_code: Schema.Null,
73 signal: Schema.Null,
74 timed_out: Schema.Literal(false),
75 termination_indeterminate: Schema.Literal(true),
76 }),
77 }),
78 }),
79 );
80 const decodeFxToolUpdate = Schema.decodeUnknownOption(
81 Schema.Struct({
82 update: Schema.Struct({ content: Schema.Array(Schema.Unknown) }),
83 }),
84 );
85 const decodeFxContentText = Schema.decodeUnknownOption(
86 Schema.Struct({ content: Schema.Struct({ text: Schema.String }) }),
87 );
88 const decodeFxCancelledError = Schema.decodeUnknownOption(
89 Schema.fromJsonString(
90 Schema.Struct({
91 error: Schema.Union([
92 Schema.Struct({ details: Schema.Struct({ error: Schema.Literal("Cancelled") }) }),
93 Schema.Struct({ code: Schema.Literal("Cancelled") }),
94 ]),
95 }),
96 ),
97 );
98
99 export function fxToolCallWasCancelled(payload: unknown): boolean {
100 const update = decodeFxToolUpdate(payload);
101 const texts = Option.isSome(update)
102 ? update.value.update.content.map(
103 (item) => Option.getOrUndefined(decodeFxContentText(item))?.content.text,
104 )
105 : [];
106 const firstText = texts[0];
107 if (
108 firstText !== undefined &&
109 (/^Cancelled\.?$/.test(firstText) || Option.isSome(decodeFxCancelledError(firstText)))
110 ) {
111 return true;
112 }
113 // fx also uses indeterminate status for real failures, whose error JSON can be clipped.
114 return (
115 isCancelledFxCommand(payload) &&
116 texts.every((text) => text === undefined || !/^\s*\{\s*"error"\s*:/.test(text))
117 );
118 }
119
120 /**
121 * Supervised runs fx's `ask` mode, Auto its automatic review and Full access
122 * its `full-access`. An explicit approval or sandbox policy runs `ask`, so it
123 * never launches a mode that performs writes the policy meant to confine.
124 */
125 export function fxSessionModeForPolicy(
126 policy: ProviderAdapter.ProviderAdapterV2RuntimePolicy,
127 ): "ask" | "auto" | typeof FX_FULL_ACCESS_MODE_ID {
128 if (policy.approvalPolicy !== undefined || policy.sandboxPolicy !== undefined) return "ask";
129 switch (policy.runtimeMode) {
130 case "auto":
131 return "auto";
132 case "full-access":
133 return FX_FULL_ACCESS_MODE_ID;
134 default:
135 return "ask";
136 }
137 }
138
139 /**
140 * In automatic review fx asks only about what it refused itself, so every
141 * prompt reaches the user. Full access answers by the shared ACP policy.
142 */
143 export function fxPermissionDisposition(
144 policy: ProviderAdapter.ProviderAdapterV2RuntimePolicy,
145 request: EffectAcpSchema.RequestPermissionRequest,
146 ): AcpPermissionDisposition {
147 switch (fxSessionModeForPolicy(policy)) {
148 case "auto":
149 return "ask";
150 case FX_FULL_ACCESS_MODE_ID:
151 return acpPermissionDisposition(policy, request);
152 case "ask":
153 return acpPermissionDisposition({ ...policy, runtimeMode: "approval-required" }, request);
154 }
155 }
156
157 /**
158 * fx's id for a requested mode, first advertised match wins. fx 0.0.13 calls
159 * automatic review `code`; fx after vercel-labs/fx#1189 calls it `auto`.
160 * `code` is also accepted as a request because the shared plan restore
161 * passes a session's saved mode id back.
162 */
163 function fxModeId(requested: string, advertised: ReadonlyArray<string>): string | undefined {
164 const candidates =
165 requested === "ask" || requested === FX_FULL_ACCESS_MODE_ID
166 ? [requested]
167 : requested === "auto" || requested === "code"
168 ? ["auto", "code"]
169 : [];
170 return candidates.find((id) => advertised.includes(id));
171 }
172
173 /**
174 * fx 0.0.13 reports `ask` on a new or loaded session but enforces its saved
175 * default until a client writes the mode, and the runtime skips writes that
176 * match the reported mode. So the first write after start or load always goes
177 * out. A mode fx does not advertise fails before anything is sent.
178 */
179 export function withFxSessionMode(
180 runtime: AcpSessionRuntime.AcpSessionRuntime["Service"],
181 ): AcpSessionRuntime.AcpSessionRuntime["Service"] {
182 let pendingSessionId: string | undefined;
183 const activated = <E, R>(
184 effect: Effect.Effect<AcpSessionRuntime.AcpSessionRuntimeStartResult, E, R>,
185 ) =>
186 effect.pipe(
187 Effect.tap((result) =>
188 Effect.sync(() => {
189 pendingSessionId = result.sessionId;
190 }),
191 ),
192 );
193 return {
194 ...runtime,
195 start: () => activated(runtime.start()),
196 loadSession: (sessionId, options) => activated(runtime.loadSession(sessionId, options)),
197 resumeSession: (sessionId, options) => activated(runtime.resumeSession(sessionId, options)),
198 forkSession: (sessionId, options) => activated(runtime.forkSession(sessionId, options)),
199 setMode: Effect.fn("setFxMode")(function* (requested) {
200 const state = yield* runtime.getModeState;
201 const advertised = state?.availableModes.map((mode) => mode.id) ?? [];
202 const target = fxModeId(requested, advertised);
203 if (target === undefined) {
204 return yield* new EffectAcpErrors.AcpRequestError({
205 code: -32602,
206 errorMessage: `fx cannot run in mode "${requested}"; it advertises ${advertised.join(", ") || "no modes"}.`,
207 data: {
208 configId: FX_MODE_CONFIG_ID,
209 allowedValues: advertised,
210 receivedValue: requested,
211 },
212 });
213 }
214 const sessionId = pendingSessionId;
215 if (sessionId === undefined || state?.currentModeId !== target) {
216 const response = yield* runtime.setMode(target);
217 pendingSessionId = undefined;
218 return response;
219 }
220 yield* runtime.request("session/set_config_option", {
221 sessionId,
222 configId: FX_MODE_CONFIG_ID,
223 value: target,
224 });
225 // Only a write fx took counts, so a retried setup sends it again.
226 pendingSessionId = undefined;
227 return {};
228 }),
229 };
230 }
231
232 /** A model on one fx backend (`gateway`, `codex`, `grok`, or a configured endpoint's id). */
233 export interface FxModelChoice {
234 readonly backend: string | undefined;
235 readonly model: string;
236 }
237
238 /** fx backend ids never contain `:`, so the first one ends the backend. */
239 export const fxModelSlug = (backend: string, model: string) => `${backend}:${model}`;
240
241 /** A slug without a known backend is a model id for the session's current backend. */
242 function parseFxModelSlug(slug: string, backends: ReadonlyArray<string>): FxModelChoice {
243 const separator = slug.indexOf(":");
244 const backend = separator > 0 ? slug.slice(0, separator) : undefined;
245 return backend !== undefined && backends.includes(backend)
246 ? { backend, model: slug.slice(separator + 1) }
247 : { backend: undefined, model: slug };
248 }
249
250 const selectOption = (
251 options: ReadonlyArray<EffectAcpSchema.SessionConfigOption>,
252 id: string,
253 ): Extract<EffectAcpSchema.SessionConfigOption, { type: "select" }> | undefined => {
254 const option = options.find((entry) => entry.id === id);
255 return option?.type === "select" ? option : undefined;
256 };
257
258 /** fx's model catalog changes with its backend, so it must be read after the provider write. */
259 export const applyFxModelSelection = Effect.fn("applyFxModelSelection")(function* (
260 runtime: Pick<
261 AcpSessionRuntime.AcpSessionRuntime["Service"],
262 "getConfigOptions" | "setConfigOption"
263 >,
264 modelSelection: ModelSelection,
265 defaultChoice: Effect.Effect<FxModelChoice | undefined> | undefined,
266 ): Effect.fn.Return<string | undefined, EffectAcpErrors.AcpError> {
267 const originalOptions = yield* runtime.getConfigOptions;
268 const backendOption = selectOption(originalOptions, FX_PROVIDER_CONFIG_ID);
269 const originalBackend = backendOption?.currentValue;
270 const originalModel = selectOption(originalOptions, FX_MODEL_CONFIG_ID)?.currentValue;
271 const requested = modelSelection.model.trim();
272 const isDefault = requested.length === 0 || requested === FX_DEFAULT_MODEL_SLUG;
273 const target = isDefault
274 ? defaultChoice && (yield* defaultChoice)
275 : parseFxModelSlug(
276 requested,
277 backendOption ? collectSessionConfigOptionValues(backendOption) : [],
278 );
279 const canSelectBackend =
280 target?.backend === undefined ||
281 (backendOption !== undefined &&
282 (target.backend === backendOption.currentValue ||
283 collectSessionConfigOptionValues(backendOption).includes(target.backend)));
284 const changingBackend =
285 target?.backend !== undefined &&
286 backendOption !== undefined &&
287 canSelectBackend &&
288 target.backend !== backendOption.currentValue;
289 return yield* Effect.gen(function* () {
290 if (changingBackend && target?.backend !== undefined) {
291 yield* runtime.setConfigOption(FX_PROVIDER_CONFIG_ID, target.backend);
292 }
293 const modelOption = selectOption(yield* runtime.getConfigOptions, FX_MODEL_CONFIG_ID);
294 const current = modelOption?.currentValue;
295 if (target === undefined || target.model === current) return current;
296 if (isDefault && !canSelectBackend) return current;
297 if (
298 isDefault &&
299 (modelOption === undefined ||
300 !collectSessionConfigOptionValues(modelOption).includes(target.model))
301 ) {
302 return yield* new EffectAcpErrors.AcpRequestError({
303 code: -32602,
304 errorMessage: "The default fx model is unavailable on its configured backend.",
305 data: { configId: FX_MODEL_CONFIG_ID },
306 });
307 }
308 yield* runtime.setConfigOption(FX_MODEL_CONFIG_ID, target.model, { allowUnlistedValue: true });
309 return target.model;
310 }).pipe(
311 Effect.onError(() => {
312 if (!changingBackend || originalBackend === undefined) return Effect.void;
313 return Effect.gen(function* () {
314 yield* runtime.setConfigOption(FX_PROVIDER_CONFIG_ID, originalBackend);
315 const restoredModel = selectOption(yield* runtime.getConfigOptions, FX_MODEL_CONFIG_ID);
316 if (originalModel !== undefined && restoredModel?.currentValue !== originalModel) {
317 yield* runtime.setConfigOption(FX_MODEL_CONFIG_ID, originalModel, {
318 allowUnlistedValue: true,
319 });
320 }
321 }).pipe(Effect.ignoreCause({ log: true }));
322 }),
323 );
324 });
325
326 /** The shared option loop writes a stored effort; a thread without one starts at medium. */
327 export const applyFxEffortDefault = Effect.fn("applyFxEffortDefault")(function* (
328 runtime: AcpSessionRuntime.AcpSessionRuntime["Service"],
329 modelSelection: ModelSelection,
330 ): Effect.fn.Return<void, EffectAcpErrors.AcpError> {
331 if (getModelSelectionStringOptionValue(modelSelection, FX_EFFORT_CONFIG_ID)) return;
332 const option = (yield* runtime.getConfigOptions).find(
333 (entry) => entry.id === FX_EFFORT_CONFIG_ID && entry.type === "select",
334 );
335 if (
336 option !== undefined &&
337 collectSessionConfigOptionValues(option).includes(FX_DEFAULT_EFFORT)
338 ) {
339 yield* runtime.setConfigOption(FX_EFFORT_CONFIG_ID, FX_DEFAULT_EFFORT);
340 }
341 });
342
343 interface FxAcpRuntimeInput extends Omit<
344 AcpSessionRuntime.AcpSessionRuntimeOptions,
345 "authMethodId" | "spawn" | "cancelBehavior"
346 > {
347 readonly fxSettings: Pick<FxSettings, "binaryPath">;
348 readonly environment?: NodeJS.ProcessEnv;
349 }
350
351 export const makeFxAcpRuntime = Effect.fn("makeFxAcpRuntime")(function* (
352 input: FxAcpRuntimeInput,
353 ): Effect.fn.Return<
354 AcpSessionRuntime.AcpSessionRuntime["Service"],
355 EffectAcpErrors.AcpError,
356 ChildProcessSpawner.ChildProcessSpawner | SecureRandom.SecureRandom | Scope.Scope
357 > {
358 const { fxSettings, environment, ...runtimeOptions } = input;
359 const context = yield* Layer.build(
360 AcpSessionRuntime.layer({
361 ...runtimeOptions,
362 spawn: {
363 command: fxSettings.binaryPath || "fx",
364 args: ["acp"],
365 cwd: input.cwd,
366 env: { ...environment },
367 },
368 cancelBehavior: FX_ACP_CANCEL_BEHAVIOR,
369 }),
370 );
371 return yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(Effect.provide(context));
372 });