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