Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

adapter.ts

311 lines12.0 KB

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