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

main
ts 296 lines 11.2 KB
Raw
1 import * as HostProcess from "@t3tools/shared/HostProcess";
2 import { resolveSelfInvocation, type SelfInvocation } from "@t3tools/shared/nodeRuntime";
3 import { type OrchestrationV2ProviderCapabilities } from "@t3tools/contracts";
4 import { FxSettings } from "../settings.ts";
5 import type * as SecureRandom from "effect/crypto/SecureRandom";
6 import * as Effect from "effect/Effect";
7 import type * as FileSystem from "effect/FileSystem";
8 import * as Option from "effect/Option";
9 import type * as Path from "effect/Path";
10 import * as Schema from "effect/Schema";
11 import type * as Scope from "effect/Scope";
12 import type * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
13 import type * as EffectAcpErrors from "effect-acp/errors";
14
15 import type * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
16 import type * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
17 import { makeAcpNativeLoggerFactory } from "@t3tools/provider-acp/server/nativeLogging";
18 import {
19 applyFxEffortDefault,
20 applyFxModelSelection,
21 FX_DRIVER_KIND,
22 FX_SESSION_META,
23 fxPermissionDisposition,
24 type FxModelChoice,
25 FX_MODE_CONFIG_ID,
26 fxToolCallWasCancelled,
27 fxSessionModeForPolicy,
28 makeFxAcpRuntime,
29 withFxSessionMode,
30 } from "./acpSupport.ts";
31 import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
32 import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
33 import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
34 import type * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
35 import {
36 ProviderAdapterDriverCreateError,
37 type ProviderAdapterDriver,
38 type ProviderAdapterDriverCreateInput,
39 } from "@t3tools/provider-core/server/adapterDriver";
40 import {
41 AcpProviderCapabilitiesV2,
42 makeAcpAdapterV2,
43 type AcpAdapterV2Flavor,
44 type AcpAdapterV2RuntimeInput,
45 type AcpAdapterV2SubagentUpdate,
46 } from "@t3tools/provider-acp/server/adapter";
47 import type { AcpToolCallState } from "@t3tools/provider-acp/server/runtimeModel";
48
49 export { FX_DRIVER_KIND } from "./acpSupport.ts";
50
51 const DEFAULT_FX_SETTINGS = Schema.decodeSync(FxSettings)({});
52
53 const FxProviderCapabilitiesV2 = {
54 ...AcpProviderCapabilitiesV2,
55 sessions: {
56 ...AcpProviderCapabilitiesV2.sessions,
57 supportsModelSwitchInSession: true,
58 },
59 threads: {
60 ...AcpProviderCapabilitiesV2.threads,
61 canReadThreadSnapshot: true,
62 },
63 tools: {
64 ...AcpProviderCapabilitiesV2.tools,
65 supportsMcpTools: true,
66 },
67 checkpointing: {
68 ...AcpProviderCapabilitiesV2.checkpointing,
69 providerCanReadConversationSnapshot: true,
70 },
71 subagents: {
72 ...AcpProviderCapabilitiesV2.subagents,
73 supportsSubagents: true,
74 emitsSubagentLifecycle: true,
75 },
76 } satisfies OrchestrationV2ProviderCapabilities;
77
78 const FxSubagentRequest = Schema.Union([
79 Schema.Struct({
80 action: Schema.Literal("run"),
81 task: Schema.String,
82 model: Schema.optionalKey(Schema.String),
83 }),
84 Schema.Struct({
85 action: Schema.Literal("message"),
86 agent: Schema.String,
87 message: Schema.String,
88 model: Schema.optionalKey(Schema.String),
89 }),
90 ]);
91 // fx 0.0.14 wraps the arguments in `request`; later fx sends them flat (vercel-labs/fx@df0878eb).
92 const decodeFxSubagentInput = Schema.decodeUnknownOption(
93 Schema.Union([FxSubagentRequest, Schema.Struct({ request: FxSubagentRequest })]),
94 );
95 const decodeFxToolContent = Schema.decodeUnknownOption(
96 Schema.Array(Schema.Struct({ content: Schema.Struct({ text: Schema.String }) })),
97 );
98 const decodeFxSubagentResult = Schema.decodeUnknownOption(
99 Schema.fromJsonString(
100 Schema.Struct({ ok: Schema.Boolean, result: Schema.NullOr(Schema.String) }),
101 ),
102 );
103 const decodeJsonString = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.String));
104 const decodeFxToolError = Schema.decodeUnknownOption(
105 Schema.fromJsonString(
106 Schema.Struct({
107 error: Schema.Struct({
108 message: Schema.optional(Schema.String),
109 code: Schema.optional(Schema.String),
110 details: Schema.optional(Schema.Struct({ error: Schema.optional(Schema.String) })),
111 }),
112 }),
113 ),
114 );
115
116 /**
117 * fx clips every tool result to 199 bytes, so a long sub-agent reply arrives
118 * as cut-off `{"ok":…,"result":"…` JSON. Keeps the readable prefix and marks the cut.
119 */
120 export function fxSubagentOutcome(
121 text: string,
122 ): { readonly ok: boolean; readonly result: string | null } | undefined {
123 const whole = decodeFxSubagentResult(text);
124 if (Option.isSome(whole)) return whole.value;
125 const clipped = /^\{"ok":(true|false),"result":"((?:[^"\\]|\\.)*)/.exec(text);
126 if (clipped === null) return undefined;
127 const fragment = clipped[2] ?? "";
128 const prefix = decodeJsonString(`"${fragment}"`).pipe(
129 Option.orElse(() => decodeJsonString(`"${fragment.replace(/\\u[0-9a-fA-F]{0,3}$/, "")}"`)),
130 );
131 const cut = text[clipped[0].length] !== '"';
132 return {
133 ok: clipped[1] === "true",
134 result: Option.isSome(prefix) ? `${prefix.value}${cut ? "…" : ""}` : null,
135 };
136 }
137
138 /** fx streams no child frames over ACP, so each `subagent` call becomes a child thread holding its task and reply. */
139 function extractFxSubagentUpdate(tool: AcpToolCallState): AcpAdapterV2SubagentUpdate | undefined {
140 if (tool.data.name !== "subagent") return undefined;
141 const input = decodeFxSubagentInput(tool.data.rawInput);
142 if (Option.isNone(input)) return undefined;
143 const request = "request" in input.value ? input.value.request : input.value;
144 const text = Option.getOrUndefined(decodeFxToolContent(tool.data.content))?.[0]?.content.text;
145 const outcome = text === undefined ? undefined : fxSubagentOutcome(text);
146 // A failed call carries fx's error envelope, e.g. `Cancelled` after Stop.
147 const failure = Option.getOrUndefined(
148 text === undefined ? Option.none() : decodeFxToolError(text),
149 )?.error;
150 const status =
151 tool.status === "completed"
152 ? outcome?.ok === false
153 ? "failed"
154 : "completed"
155 : tool.status === "failed"
156 ? "failed"
157 : "running";
158 return {
159 nativeTaskId: tool.toolCallId,
160 childSessionId: null,
161 prompt: request.action === "run" ? request.task : request.message,
162 title: request.action === "message" ? request.agent : null,
163 model: request.model ?? null,
164 status,
165 result:
166 status === "running"
167 ? null
168 : (outcome?.result ??
169 failure?.details?.error ??
170 failure?.message ??
171 failure?.code ??
172 text ??
173 null),
174 };
175 }
176
177 export interface FxAdapterV2Options {
178 readonly instanceId: Parameters<typeof makeAcpAdapterV2>[0]["instanceId"];
179 readonly settings: FxSettings;
180 readonly environment: NodeJS.ProcessEnv;
181 readonly selfInvocation: SelfInvocation;
182 /** The backend and model "Default" runs in a folder, which `fx status` reports there. */
183 readonly defaultChoice?: (cwd: string) => Effect.Effect<FxModelChoice | undefined>;
184 readonly nativeLogging?: Parameters<typeof makeAcpAdapterV2>[0]["nativeLogging"];
185 readonly testHooks?: Parameters<typeof makeAcpAdapterV2>[0]["testHooks"];
186 /** Replaces the `fx acp` launch (replay tests). fx's session setup still applies. */
187 readonly makeRuntime?: (
188 input: AcpAdapterV2RuntimeInput,
189 ) => Effect.Effect<
190 AcpSessionRuntime.AcpSessionRuntime["Service"],
191 EffectAcpErrors.AcpError,
192 ChildProcessSpawner.ChildProcessSpawner | SecureRandom.SecureRandom | Scope.Scope
193 >;
194 readonly assertComplete?: Effect.Effect<void, EffectAcpErrors.AcpError>;
195 }
196
197 function makeFxAcpAdapterFlavor(options: FxAdapterV2Options): AcpAdapterV2Flavor {
198 const makeRuntime =
199 options.makeRuntime ??
200 (({ runtimePolicy: _runtimePolicy, processEnvironment, ...input }: AcpAdapterV2RuntimeInput) =>
201 makeFxAcpRuntime({
202 ...input,
203 fxSettings: options.settings,
204 environment: { ...options.environment, ...processEnvironment },
205 }));
206 // A runtime serves one folder; "Default" resolves there.
207 const runtimeCwds = new WeakMap<AcpSessionRuntime.AcpSessionRuntime["Service"], string>();
208 return {
209 driver: FX_DRIVER_KIND,
210 runtimeHarness: "fx",
211 capabilities: FxProviderCapabilitiesV2,
212 makeRuntime: (input) =>
213 makeRuntime({ ...input, sessionMeta: () => FX_SESSION_META }).pipe(
214 Effect.map(withFxSessionMode),
215 Effect.tap((runtime) => Effect.sync(() => runtimeCwds.set(runtime, input.cwd))),
216 ),
217 applyModelSelection: ({ runtime, modelSelection }) => {
218 const cwd = runtimeCwds.get(runtime);
219 return applyFxModelSelection(
220 runtime,
221 modelSelection,
222 cwd === undefined ? undefined : options.defaultChoice?.(cwd),
223 ).pipe(Effect.tap(() => applyFxEffortDefault(runtime, modelSelection)));
224 },
225 ownedModelOptionIds: [FX_MODE_CONFIG_ID],
226 lockSessionModeToPolicy: true,
227 sessionModeForPolicy: fxSessionModeForPolicy,
228 permissionDisposition: fxPermissionDisposition,
229 extractSubagentUpdate: extractFxSubagentUpdate,
230 isCancelledToolCall: fxToolCallWasCancelled,
231 ...(options.assertComplete === undefined ? {} : { assertComplete: options.assertComplete }),
232 };
233 }
234
235 export const makeFxAdapterV2 = Effect.fn("makeFxAdapterV2")(function* (
236 options: FxAdapterV2Options,
237 ) {
238 return yield* makeAcpAdapterV2({
239 instanceId: options.instanceId,
240 flavor: makeFxAcpAdapterFlavor(options),
241 selfInvocation: options.selfInvocation,
242 ...(options.nativeLogging === undefined ? {} : { nativeLogging: options.nativeLogging }),
243 ...(options.testHooks === undefined ? {} : { testHooks: options.testHooks }),
244 });
245 });
246
247 export type FxAdapterV2DriverEnv =
248 | ChildProcessSpawner.ChildProcessSpawner
249 | SecureRandom.SecureRandom
250 | FileSystem.FileSystem
251 | IdAllocator.IdAllocatorV2
252 | Path.Path
253 | McpProviderSessions.McpProviderSessions
254 | ProviderEventLoggers.ProviderEventLoggers
255 | ProviderHost.ProviderHost;
256
257 export const makeFxAdapterV2Driver = (
258 defaultChoice: (cwd: string) => Effect.Effect<FxModelChoice | undefined>,
259 ): ProviderAdapterDriver<FxSettings, FxAdapterV2DriverEnv> => ({
260 driverKind: FX_DRIVER_KIND,
261 configSchema: FxSettings,
262 defaultConfig: (): FxSettings => DEFAULT_FX_SETTINGS,
263 create: Effect.fn("FxAdapterV2Driver.create")(
264 function* (input: ProviderAdapterDriverCreateInput<FxSettings>) {
265 const hostEnvironment = yield* HostProcess.Environment;
266 const selfInvocation = yield* resolveSelfInvocation();
267 const providerEventLoggers = yield* ProviderEventLoggers.ProviderEventLoggers;
268 const makeNativeLogger = yield* makeAcpNativeLoggerFactory();
269 return yield* makeFxAdapterV2({
270 instanceId: input.instanceId,
271 settings: { ...input.config, enabled: input.enabled },
272 environment: yield* mergeProviderInstanceEnvironment(input.environment, hostEnvironment),
273 selfInvocation,
274 defaultChoice,
275 nativeLogging: (threadId) =>
276 makeNativeLogger({
277 nativeEventLogger: providerEventLoggers.native,
278 provider: FX_DRIVER_KIND,
279 threadId,
280 }),
281 });
282 },
283 (effect, input) =>
284 effect.pipe(
285 Effect.mapError(
286 (cause) =>
287 new ProviderAdapterDriverCreateError({
288 driver: FX_DRIVER_KIND,
289 instanceId: input.instanceId,
290 detail: "Failed to create the fx ACP adapter.",
291 cause,
292 }),
293 ),
294 ),
295 ),
296 });