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