Open History to see the last commit
1import type * as EffectAcpSchema from "effect-acp/compat";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import {
4 type GrokSettings,
5 type ProviderApprovalOption,
6 ProviderDriverKind,
7 type RuntimeMode,
8} from "@t3tools/contracts";
9import * as Crypto from "effect/Crypto";
10import * as Effect from "effect/Effect";
11import * as Layer from "effect/Layer";
12import * as Scope from "effect/Scope";
13import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
14import * as EffectAcpErrors from "effect-acp/errors";
15import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
16import { normalizeModelSlug } from "@t3tools/shared/model";
17
18import * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
19import { makeXAiPromptCompletionRuntime } from "./XAiAcpExtension.ts";
20
21const GROK_API_KEY_ENV = "XAI_API_KEY";
22const GROK_OAUTH2_REFERRER_ENV = "GROK_OAUTH2_REFERRER";
23const T3_CODE_OAUTH_REFERRER = "t3code";
24const GROK_AUTH_METHOD_API_KEY = "xai.api_key";
25const GROK_AUTH_METHOD_CACHED_TOKEN = "cached_token";
26const GROK_DRIVER_KIND = ProviderDriverKind.make("grok");
27
28type GrokAcpRuntimeGrokSettings = Pick<GrokSettings, "binaryPath">;
29
30interface GrokAcpRuntimeInput extends Omit<
31 AcpSessionRuntime.AcpSessionRuntimeOptions,
32 "authMethodId" | "clientCapabilities" | "spawn"
33> {
34 readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"];
35 readonly grokSettings: GrokAcpRuntimeGrokSettings | null | undefined;
36 readonly environment?: NodeJS.ProcessEnv;
37 readonly runtimeMode?: RuntimeMode;
38}
39
40/**
41 * The runtime modes `grok agent` can launch in: ask, its auto classifier, and
42 * always-approve. It has no Auto-accept edits: `acceptEdits` only exists as a
43 * settings-file `permissions.defaultMode`, and `grok agent` treats it as ask.
44 */
45export const GROK_SUPPORTED_RUNTIME_MODES = [
46 "approval-required",
47 "auto",
48 "full-access",
49] as const satisfies ReadonlyArray<RuntimeMode>;
50
51/**
52 * Launch argv for a runtime mode. `--permission-mode` on the argv beats the
53 * user's Grok config, so Supervised cannot inherit a configured always-approve.
54 * A mode Grok does not offer launches asking.
55 */
56export function grokAcpSpawnArgs(runtimeMode?: RuntimeMode): ReadonlyArray<string> {
57 switch (runtimeMode) {
58 case undefined:
59 return ["agent", "stdio"];
60 case "auto":
61 return ["--permission-mode", "auto", "agent", "stdio"];
62 case "full-access":
63 return ["agent", "--always-approve", "stdio"];
64 default:
65 return ["--permission-mode", "default", "agent", "stdio"];
66 }
67}
68
69export function buildGrokAcpSpawnInput(
70 grokSettings: GrokAcpRuntimeGrokSettings | null | undefined,
71 cwd: string,
72 environment?: NodeJS.ProcessEnv,
73 runtimeMode?: RuntimeMode,
74): AcpSessionRuntime.AcpSpawnInput {
75 return {
76 command: grokSettings?.binaryPath || "grok",
77 args: [...grokAcpSpawnArgs(runtimeMode)],
78 cwd,
79 env: {
80 ...environment,
81 [GROK_OAUTH2_REFERRER_ENV]: T3_CODE_OAUTH_REFERRER,
82 },
83 };
84}
85
86function resolveGrokAuthMethodId(environment: NodeJS.ProcessEnv | undefined): string {
87 return environment?.[GROK_API_KEY_ENV]?.trim()
88 ? GROK_AUTH_METHOD_API_KEY
89 : GROK_AUTH_METHOD_CACHED_TOKEN;
90}
91
92export function grokAcpRuntimeProcessOwnership(
93 processGroupPlatform: NodeJS.Platform,
94): Pick<
95 AcpSessionRuntime.AcpSessionRuntimeOptions,
96 "ownDescendantProcessGroups" | "ownDetachedProcessGroup" | "processGroupPlatform"
97> {
98 return {
99 // macOS keeps the prior provider-group teardown until a stable libproc
100 // identity provider can cover Grok's nested detached tool groups.
101 ownDescendantProcessGroups: processGroupPlatform === "linux",
102 ownDetachedProcessGroup: true,
103 processGroupPlatform,
104 };
105}
106
107/**
108 * Current Grok treats Ctrl+C cancellation as a barrier against stale
109 * background-task wake prompts until the next genuine user turn. Replay sends
110 * the same metadata so recorded cancels match.
111 */
112export const GROK_ACP_CANCEL_META = { cancelTrigger: "ctrl_c" } as const;
113
114/**
115 * Grok's Auto mode asks the client about an action its classifier blocks only
116 * when the client declares a type that can show a prompt; the default
117 * (`generic`) gets a silent denial instead. `extension` is the prompting type
118 * that keeps the permission options T3 already maps (no always-approve row,
119 * no per-command persistent grants).
120 */
121export const GROK_ACP_INITIALIZE_META = { clientType: "extension" } as const;
122
123/**
124 * Grok's only session-scoped `allow_always` answer: "Yes, allow all edits
125 * during this session" on an edit prompt. Its bash, monitor and MCP
126 * `always-allow` rows instead save a grant for the whole project that outlives
127 * the session (grok-build `crates/codegen/xai-grok-workspace/src/permission/`
128 * `prompter.rs` `ALLOW_EDITS_SESSION_OPTION_ID`, `grants.rs`
129 * `record_prompt_outcome`).
130 */
131const GROK_ALLOW_EDITS_SESSION_OPTION_ID = "allow-edits-session";
132
133/**
134 * The approval choices a Grok permission prompt can honor. The session choice
135 * appears only where Grok's answer lasts for the session.
136 */
137export function grokApprovalOptions(
138 request: EffectAcpSchema.RequestPermissionRequest,
139): ReadonlyArray<ProviderApprovalOption> {
140 const has = (kind: EffectAcpSchema.PermissionOption["kind"], optionId?: string) =>
141 request.options.some(
142 (option) =>
143 option.kind === kind && (optionId === undefined || option.optionId.trim() === optionId),
144 );
145 return [
146 { decision: "cancel", label: "Cancel" },
147 ...(has("reject_once") ? [{ decision: "decline", label: "Decline" } as const] : []),
148 ...(has("allow_always", GROK_ALLOW_EDITS_SESSION_OPTION_ID)
149 ? [{ decision: "acceptForSession", label: "Allow all edits this session" } as const]
150 : []),
151 ...(has("allow_once") ? [{ decision: "accept", label: "Approve" } as const] : []),
152 ];
153}
154
155export const makeGrokAcpRuntime = (
156 input: GrokAcpRuntimeInput,
157): Effect.Effect<
158 AcpSessionRuntime.AcpSessionRuntime["Service"],
159 EffectAcpErrors.AcpError,
160 Crypto.Crypto | Scope.Scope
161> =>
162 Effect.gen(function* () {
163 const processGroupPlatform = yield* HostProcessPlatform.pipe(
164 Effect.provide(NodeServices.layer),
165 );
166 const acpContext = yield* Layer.build(
167 AcpSessionRuntime.layer({
168 ...input,
169 spawn: buildGrokAcpSpawnInput(
170 input.grokSettings,
171 input.cwd,
172 input.environment,
173 input.runtimeMode,
174 ),
175 authMethodId: resolveGrokAuthMethodId(input.environment),
176 cancelMeta: { ...input.cancelMeta, ...GROK_ACP_CANCEL_META },
177 initializeMeta: GROK_ACP_INITIALIZE_META,
178 ...grokAcpRuntimeProcessOwnership(processGroupPlatform),
179 }).pipe(
180 Layer.provide(
181 Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, input.childProcessSpawner),
182 ),
183 ),
184 );
185 const runtime = yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(
186 Effect.provide(acpContext),
187 );
188 return yield* makeXAiPromptCompletionRuntime(runtime);
189 });
190
191/**
192 * T3's built-in Grok slug. It is the CLI's product name, not a model id the ACP accepts,
193 * so selecting it means "use whatever model the Grok session currently runs on".
194 */
195export const GROK_DEFAULT_MODEL_SLUG = "grok-build";
196
197export function resolveGrokAcpBaseModelId(model: string | null | undefined): string {
198 const trimmed = model?.trim();
199 const base = trimmed && trimmed.length > 0 ? trimmed : GROK_DEFAULT_MODEL_SLUG;
200 return normalizeModelSlug(base, GROK_DRIVER_KIND) ?? GROK_DEFAULT_MODEL_SLUG;
201}
202
203const GROK_REASONING_EFFORT_TOKEN = /^[a-z0-9][a-z0-9._-]{0,31}$/i;
204
205export function isValidGrokReasoningEffortToken(value: string): boolean {
206 return GROK_REASONING_EFFORT_TOKEN.test(value);
207}
208
209function normalizeGrokReasoningEffort(value: string | undefined): string | undefined {
210 const effort = value?.trim();
211 return effort && isValidGrokReasoningEffortToken(effort) ? effort : undefined;
212}
213
214export function currentGrokModelIdFromSessionSetup(
215 sessionSetupResult:
216 | EffectAcpSchema.LoadSessionResponse
217 | EffectAcpSchema.NewSessionResponse
218 | EffectAcpSchema.ResumeSessionResponse,
219): string | undefined {
220 return sessionSetupResult.models?.currentModelId?.trim() || undefined;
221}
222
223export function currentGrokReasoningEffortFromSessionSetup(
224 sessionSetupResult:
225 | EffectAcpSchema.LoadSessionResponse
226 | EffectAcpSchema.NewSessionResponse
227 | EffectAcpSchema.ResumeSessionResponse,
228): string | undefined {
229 const modelState = sessionSetupResult.models;
230 if (!modelState) {
231 return undefined;
232 }
233 const currentModelId = modelState.currentModelId.trim();
234 if (currentModelId.length === 0) {
235 return undefined;
236 }
237 const currentModel = modelState.availableModels.find(
238 (model) => model.modelId.trim() === currentModelId,
239 );
240 const reasoningEffort = currentModel?._meta?.reasoningEffort;
241 return typeof reasoningEffort === "string"
242 ? normalizeGrokReasoningEffort(reasoningEffort)
243 : undefined;
244}
245
246export function applyGrokAcpModelSelection<E>(input: {
247 readonly runtime: Pick<AcpSessionRuntime.AcpSessionRuntime["Service"], "setSessionModel">;
248 readonly currentModelId: string | undefined;
249 readonly currentReasoningEffort?: string | undefined;
250 readonly requestedModelId: string | undefined;
251 readonly requestedReasoningEffort?: string | undefined;
252 readonly mapError: (cause: EffectAcpErrors.AcpError) => E;
253}): Effect.Effect<string | undefined, E> {
254 // The product slug is never sent over the wire; it keeps the session's current model.
255 const requestedModelId =
256 input.requestedModelId === GROK_DEFAULT_MODEL_SLUG ? undefined : input.requestedModelId;
257 const modelChanged = requestedModelId !== undefined && requestedModelId !== input.currentModelId;
258 const reasoningProvided = input.requestedReasoningEffort !== undefined;
259 const reasoningEffort = reasoningProvided
260 ? normalizeGrokReasoningEffort(input.requestedReasoningEffort)
261 : undefined;
262 const reasoningEffortChanged =
263 reasoningProvided && reasoningEffort !== input.currentReasoningEffort;
264 const targetModelId = requestedModelId ?? input.currentModelId;
265 if ((!modelChanged && !reasoningEffortChanged) || targetModelId === undefined) {
266 return Effect.succeed(input.currentModelId);
267 }
268 const reasoningMeta =
269 reasoningProvided && reasoningEffort !== undefined ? { reasoningEffort } : undefined;
270 // When reasoning was explicitly provided but invalid (normalize => undefined), we deliberately
271 // send no meta so the invalid value is dropped rather than forwarded. When reasoning was not
272 // provided at all, we also send no meta, but we only reach this call when the model itself
273 // changed - an omitted reasoning preference must not be treated as an explicit clear of the
274 // CLI-advertised default (e.g. Extra High) on same-model reselections.
275 return input.runtime
276 .setSessionModel(targetModelId, reasoningMeta)
277 .pipe(Effect.mapError(input.mapError), Effect.as(targetModelId));
278}