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 */
105function 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 prefix = decodeJsonString(`"${(clipped[2] ?? "").replace(/\\u[0-9a-fA-F]{0,3}$/, "")}"`);
113 const cut = text[clipped[0].length] !== '"';
114 return {
115 ok: clipped[1] === "true",
116 result: Option.isSome(prefix) ? `${prefix.value}${cut ? "…" : ""}` : null,
117 };
118}
119
120/** fx streams no child frames over ACP, so each `subagent` call becomes a child thread holding its task and reply. */
121function extractFxSubagentUpdate(tool: AcpToolCallState): AcpAdapterV2SubagentUpdate | undefined {
122 if (tool.data.name !== "subagent") return undefined;
123 const input = decodeFxSubagentInput(tool.data.rawInput);
124 if (Option.isNone(input)) return undefined;
125 const request = "request" in input.value ? input.value.request : input.value;
126 const text = Option.getOrUndefined(decodeFxToolContent(tool.data.content))?.[0]?.content.text;
127 const outcome = text === undefined ? undefined : fxSubagentOutcome(text);
128 const status =
129 tool.status === "completed"
130 ? outcome?.ok === false
131 ? "failed"
132 : "completed"
133 : tool.status === "failed"
134 ? "failed"
135 : "running";
136 return {
137 nativeTaskId: tool.toolCallId,
138 childSessionId: null,
139 prompt: request.action === "run" ? request.task : request.message,
140 title: request.action === "message" ? request.agent : null,
141 model: request.model ?? null,
142 status,
143 result: status === "running" ? null : (outcome?.result ?? text ?? null),
144 };
145}
146
147export interface FxAdapterV2Options {
148 readonly instanceId: Parameters<typeof makeAcpAdapterV2>[0]["instanceId"];
149 readonly settings: FxSettings;
150 readonly environment: NodeJS.ProcessEnv;
151 readonly selfInvocation: SelfInvocation;
152 /** fx's id for "Default", the model the provider snapshot read from `fx status`. */
153 readonly defaultModel?: Effect.Effect<string | undefined>;
154 readonly nativeLogging?: Parameters<typeof makeAcpAdapterV2>[0]["nativeLogging"];
155 readonly testHooks?: Parameters<typeof makeAcpAdapterV2>[0]["testHooks"];
156 /** Replaces the `fx acp` launch (replay tests). fx's session setup still applies. */
157 readonly makeRuntime?: (
158 input: AcpAdapterV2RuntimeInput,
159 ) => Effect.Effect<
160 AcpSessionRuntime.AcpSessionRuntime["Service"],
161 EffectAcpErrors.AcpError,
162 ChildProcessSpawner.ChildProcessSpawner | SecureRandom.SecureRandom | Scope.Scope
163 >;
164 readonly assertComplete?: Effect.Effect<void, EffectAcpErrors.AcpError>;
165}
166
167function makeFxAcpAdapterFlavor(options: FxAdapterV2Options): AcpAdapterV2Flavor {
168 const makeRuntime =
169 options.makeRuntime ??
170 (({ runtimePolicy: _runtimePolicy, processEnvironment, ...input }: AcpAdapterV2RuntimeInput) =>
171 makeFxAcpRuntime({
172 ...input,
173 fxSettings: options.settings,
174 environment: { ...options.environment, ...processEnvironment },
175 }));
176 return {
177 driver: FX_DRIVER_KIND,
178 runtimeHarness: "fx",
179 capabilities: FxProviderCapabilitiesV2,
180 makeRuntime: (input) => makeRuntime(input).pipe(Effect.map(withFxSessionMode)),
181 applyModelSelection: ({ runtime, modelSelection }) =>
182 applyFxModelSelection(runtime, modelSelection, options.defaultModel).pipe(
183 Effect.tap(() => applyFxEffortDefault(runtime, modelSelection)),
184 ),
185 sessionModeForPolicy: fxSessionModeForPolicy,
186 permissionDisposition: fxPermissionDisposition,
187 extractSubagentUpdate: extractFxSubagentUpdate,
188 ...(options.assertComplete === undefined ? {} : { assertComplete: options.assertComplete }),
189 };
190}
191
192export const makeFxAdapterV2 = Effect.fn("makeFxAdapterV2")(function* (
193 options: FxAdapterV2Options,
194) {
195 return yield* makeAcpAdapterV2({
196 instanceId: options.instanceId,
197 flavor: makeFxAcpAdapterFlavor(options),
198 selfInvocation: options.selfInvocation,
199 ...(options.nativeLogging === undefined ? {} : { nativeLogging: options.nativeLogging }),
200 ...(options.testHooks === undefined ? {} : { testHooks: options.testHooks }),
201 });
202});
203
204export type FxAdapterV2DriverEnv =
205 | ChildProcessSpawner.ChildProcessSpawner
206 | SecureRandom.SecureRandom
207 | FileSystem.FileSystem
208 | IdAllocator.IdAllocatorV2
209 | Path.Path
210 | McpProviderSessions.McpProviderSessions
211 | ProviderEventLoggers.ProviderEventLoggers
212 | ProviderHost.ProviderHost;
213
214/** `defaultModel` reads fx's id for "Default" from the provider snapshot. */
215export const makeFxAdapterV2Driver = (
216 defaultModel: Effect.Effect<string | undefined>,
217): ProviderAdapterDriver<FxSettings, FxAdapterV2DriverEnv> => ({
218 driverKind: FX_DRIVER_KIND,
219 configSchema: FxSettings,
220 defaultConfig: (): FxSettings => DEFAULT_FX_SETTINGS,
221 create: Effect.fn("FxAdapterV2Driver.create")(
222 function* (input: ProviderAdapterDriverCreateInput<FxSettings>) {
223 const hostEnvironment = yield* HostProcess.Environment;
224 const selfInvocation = yield* resolveSelfInvocation();
225 const providerEventLoggers = yield* ProviderEventLoggers.ProviderEventLoggers;
226 const makeNativeLogger = yield* makeAcpNativeLoggerFactory();
227 return yield* makeFxAdapterV2({
228 instanceId: input.instanceId,
229 settings: { ...input.config, enabled: input.enabled },
230 environment: yield* mergeProviderInstanceEnvironment(input.environment, hostEnvironment),
231 selfInvocation,
232 defaultModel,
233 nativeLogging: (threadId) =>
234 makeNativeLogger({
235 nativeEventLogger: providerEventLoggers.native,
236 provider: FX_DRIVER_KIND,
237 threadId,
238 }),
239 });
240 },
241 (effect, input) =>
242 effect.pipe(
243 Effect.mapError(
244 (cause) =>
245 new ProviderAdapterDriverCreateError({
246 driver: FX_DRIVER_KIND,
247 instanceId: input.instanceId,
248 detail: "Failed to create the fx ACP adapter.",
249 cause,
250 }),
251 ),
252 ),
253 ),
254});