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

acpSupport.ts

238 lines8.9 KB

1import type * as EffectAcpSchema from "effect-acp/compat";
2import {
3 type ModelSelection,
4 type ProviderOptionDescriptor,
5 ProviderDriverKind,
6 type RuntimeMode,
7} from "@t3tools/contracts";
8import type { FxSettings } from "../settings.ts";
9import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
10import type * as Crypto from "effect/Crypto";
11import * as Effect from "effect/Effect";
12import * as Layer from "effect/Layer";
13import type * as Scope from "effect/Scope";
14import type * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
15import * as EffectAcpErrors from "effect-acp/errors";
16​
17import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
18import { collectSessionConfigOptionValues } from "@t3tools/provider-acp/server/runtimeModel";
19import {
20 acpPermissionDisposition,
21 type AcpPermissionDisposition,
22} from "@t3tools/provider-acp/server/clientPolicy";
23import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
24​
25export const FX_DRIVER_KIND = ProviderDriverKind.make("fx");
26/** T3's slug for "Default": the model `fx status` reports, never an fx model id. */
27export const FX_DEFAULT_MODEL_SLUG = "default";
28const FX_MODEL_CONFIG_ID = "model";
29const FX_MODE_CONFIG_ID = "mode";
30const FX_EFFORT_CONFIG_ID = "effort";
31const FX_DEFAULT_EFFORT = "medium";
32​
33const FX_EFFORT_LABELS = {
34 auto: "Auto",
35 low: "Low",
36 medium: "Medium",
37 high: "High",
38 xhigh: "Extra High",
39 max: "Max",
40} as const;
41​
42export const FX_EFFORT_OPTION_DESCRIPTOR: ProviderOptionDescriptor = {
43 id: FX_EFFORT_CONFIG_ID,
44 label: "Effort",
45 type: "select",
46 options: Object.entries(FX_EFFORT_LABELS).map(([id, label]) => ({
47 id,
48 label,
49 ...(id === FX_DEFAULT_EFFORT ? { isDefault: true } : {}),
50 })),
51};
52​
53export const FX_SUPPORTED_RUNTIME_MODES = [
54 "approval-required",
55 "auto",
56] as const satisfies ReadonlyArray<RuntimeMode>;
57/** fx 0.0.13 answers a cancelled prompt with `stopReason: cancelled`. */
58export const FX_ACP_CANCEL_BEHAVIOR = "wait-for-prompt" as const;
59​
60/**
61 * Supervised runs fx's `ask` mode and Auto its automatic review. An explicit
62 * approval or sandbox policy must not launch automatic review, which would
63 * perform writes the policy meant to confine.
64 */
65export function fxSessionModeForPolicy(
66 policy: ProviderAdapter.ProviderAdapterV2RuntimePolicy,
67): "ask" | "auto" {
68 return policy.runtimeMode === "auto" &&
69 policy.approvalPolicy === undefined &&
70 policy.sandboxPolicy === undefined
71 ? "auto"
72 : "ask";
74​
75/** In automatic review fx asks only about what it refused itself, so every prompt reaches the user. */
76export function fxPermissionDisposition(
77 policy: ProviderAdapter.ProviderAdapterV2RuntimePolicy,
78 request: EffectAcpSchema.RequestPermissionRequest,
79): AcpPermissionDisposition {
80 return fxSessionModeForPolicy(policy) === "auto"
81 ? "ask"
82 : acpPermissionDisposition({ ...policy, runtimeMode: "approval-required" }, request);
84​
85/**
86 * fx's id for a requested mode, first advertised match wins. fx 0.0.13 calls
87 * automatic review `code`; fx after vercel-labs/fx#1189 calls it `auto`.
88 * `code` is also accepted as a request because the shared plan restore
89 * passes a session's saved mode id back.
90 */
91function fxModeId(requested: string, advertised: ReadonlyArray<string>): string | undefined {
92 const candidates =
93 requested === "ask"
94 ? ["ask"]
95 : requested === "auto" || requested === "code"
96 ? ["auto", "code"]
97 : [];
98 return candidates.find((id) => advertised.includes(id));
100​
101/**
102 * fx 0.0.13 reports `ask` on a new or loaded session but enforces its saved
103 * default until a client writes the mode, and the runtime skips writes that
104 * match the reported mode. So the first write after start or load always goes
105 * out. A mode fx does not advertise fails before anything is sent.
106 */
107export function withFxSessionMode(
108 runtime: AcpSessionRuntime.AcpSessionRuntime["Service"],
109): AcpSessionRuntime.AcpSessionRuntime["Service"] {
110 let pendingSessionId: string | undefined;
111 const activated = <E, R>(
112 effect: Effect.Effect<AcpSessionRuntime.AcpSessionRuntimeStartResult, E, R>,
113 ) =>
114 effect.pipe(
115 Effect.tap((result) =>
116 Effect.sync(() => {
117 pendingSessionId = result.sessionId;
118 }),
119 ),
120 );
121 return {
122 ...runtime,
123 start: () => activated(runtime.start()),
124 loadSession: (sessionId, options) => activated(runtime.loadSession(sessionId, options)),
125 resumeSession: (sessionId, options) => activated(runtime.resumeSession(sessionId, options)),
126 forkSession: (sessionId, options) => activated(runtime.forkSession(sessionId, options)),
127 setMode: Effect.fn("setFxMode")(function* (requested) {
128 const state = yield* runtime.getModeState;
129 const advertised = state?.availableModes.map((mode) => mode.id) ?? [];
130 const target = fxModeId(requested, advertised);
131 if (target === undefined) {
132 return yield* new EffectAcpErrors.AcpRequestError({
133 code: -32602,
134 errorMessage: `fx cannot run in mode "${requested}"; it advertises ${advertised.join(", ") || "no modes"}.`,
135 data: {
136 configId: FX_MODE_CONFIG_ID,
137 allowedValues: advertised,
138 receivedValue: requested,
139 },
140 });
141 }
142 const sessionId = pendingSessionId;
143 if (sessionId === undefined || state?.currentModeId !== target) {
144 const response = yield* runtime.setMode(target);
145 pendingSessionId = undefined;
146 return response;
147 }
148 yield* runtime.request("session/set_config_option", {
149 sessionId,
150 configId: FX_MODE_CONFIG_ID,
151 value: target,
152 });
153 // Only a write fx took counts, so a retried setup sends it again.
154 pendingSessionId = undefined;
155 return {};
156 }),
157 };
159​
160/**
161 * Writes config id `model` (fx's `provider` option shares its category).
162 * "Default" picks the model `fx status` reports when the session lists it.
163 * An unlisted model the thread picked is still sent: fx's backends accept or
164 * refuse it themselves, so a thread never runs on a model it did not pick.
165 */
166export const applyFxModelSelection = Effect.fn("applyFxModelSelection")(function* (
167 runtime: AcpSessionRuntime.AcpSessionRuntime["Service"],
168 modelSelection: ModelSelection,
169 defaultModel: Effect.Effect<string | undefined> | undefined,
170): Effect.fn.Return<string | undefined, EffectAcpErrors.AcpError> {
171 const option = (yield* runtime.getConfigOptions).find(
172 (entry) => entry.id === FX_MODEL_CONFIG_ID && entry.type === "select",
173 );
174 const current = option?.type === "select" ? option.currentValue : undefined;
175 const requested = modelSelection.model.trim();
176 const isDefault = requested.length === 0 || requested === FX_DEFAULT_MODEL_SLUG;
177 const target = isDefault ? defaultModel && (yield* defaultModel) : requested;
178 if (target === undefined || target === current) return current;
179 // The status default can belong to another fx backend than the session's
180 // (after `fx provider`, or a loaded older session); then the session's
181 // own model stands.
182 if (
183 isDefault &&
184 (option === undefined || !collectSessionConfigOptionValues(option).includes(target))
185 ) {
186 return current;
187 }
188 yield* runtime.setConfigOption(FX_MODEL_CONFIG_ID, target, { allowUnlistedValue: true });
189 return target;
190});
191​
192/** The shared option loop writes a stored effort; a thread without one starts at medium. */
193export const applyFxEffortDefault = Effect.fn("applyFxEffortDefault")(function* (
194 runtime: AcpSessionRuntime.AcpSessionRuntime["Service"],
195 modelSelection: ModelSelection,
196): Effect.fn.Return<void, EffectAcpErrors.AcpError> {
197 if (getModelSelectionStringOptionValue(modelSelection, FX_EFFORT_CONFIG_ID)) return;
198 const option = (yield* runtime.getConfigOptions).find(
199 (entry) => entry.id === FX_EFFORT_CONFIG_ID && entry.type === "select",
200 );
201 if (
202 option !== undefined &&
203 collectSessionConfigOptionValues(option).includes(FX_DEFAULT_EFFORT)
204 ) {
205 yield* runtime.setConfigOption(FX_EFFORT_CONFIG_ID, FX_DEFAULT_EFFORT);
206 }
207});
208​
209interface FxAcpRuntimeInput extends Omit<
210 AcpSessionRuntime.AcpSessionRuntimeOptions,
211 "authMethodId" | "spawn" | "cancelBehavior"
212> {
213 readonly fxSettings: Pick<FxSettings, "binaryPath">;
214 readonly environment?: NodeJS.ProcessEnv;
216​
217export const makeFxAcpRuntime = Effect.fn("makeFxAcpRuntime")(function* (
218 input: FxAcpRuntimeInput,
219): Effect.fn.Return<
220 AcpSessionRuntime.AcpSessionRuntime["Service"],
221 EffectAcpErrors.AcpError,
222 ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | Scope.Scope
223> {
224 const { fxSettings, environment, ...runtimeOptions } = input;
225 const context = yield* Layer.build(
226 AcpSessionRuntime.layer({
227 ...runtimeOptions,
228 spawn: {
229 command: fxSettings.binaryPath || "fx",
230 args: ["acp"],
231 cwd: input.cwd,
232 env: { ...environment },
233 },
234 cancelBehavior: FX_ACP_CANCEL_BEHAVIOR,
235 }),
236 );
237 return yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(Effect.provide(context));
238});