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
67export function 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
90export function 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 = (
149 input: GrokAcpRuntimeInput,
150): Effect.Effect<
151 AcpSessionRuntime.AcpSessionRuntime["Service"],
152 EffectAcpErrors.AcpError,
153 ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | Scope.Scope
154> =>
155 Effect.gen(function* () {
156 const processGroupPlatform = yield* HostProcess.Platform.pipe(
157 Effect.provide(NodeServices.layer),
158 );
159 const acpContext = yield* Layer.build(
160 AcpSessionRuntime.layer({
161 ...input,
162 spawn: buildGrokAcpSpawnInput(
163 input.grokSettings,
164 input.cwd,
165 input.environment,
166 input.runtimeMode,
167 ),
168 authMethodId: resolveGrokAuthMethodId(input.environment),
169 cancelMeta: { ...input.cancelMeta, ...GROK_ACP_CANCEL_META },
170 initializeMeta: GROK_ACP_INITIALIZE_META,
171 ...grokAcpRuntimeProcessOwnership(processGroupPlatform),
172 }),
173 );
174 const runtime = yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(
175 Effect.provide(acpContext),
176 );
177 return yield* makeXAiPromptCompletionRuntime(runtime);
178 });
179
180/**
181 * It is the CLI's product name, not a model id the ACP accepts, so selecting it
182 * means "use whatever model the Grok session currently runs on".
183 */
184export const GROK_DEFAULT_MODEL_SLUG = "grok-build";
185
186export function resolveGrokAcpBaseModelId(model: string | null | undefined): string {
187 const trimmed = model?.trim();
188 const base = trimmed && trimmed.length > 0 ? trimmed : GROK_DEFAULT_MODEL_SLUG;
189 return normalizeModelSlug(base, GROK_DRIVER_KIND) ?? GROK_DEFAULT_MODEL_SLUG;
190}
191
192const GROK_REASONING_EFFORT_TOKEN = /^[a-z0-9][a-z0-9._-]{0,31}$/i;
193
194export function isValidGrokReasoningEffortToken(value: string): boolean {
195 return GROK_REASONING_EFFORT_TOKEN.test(value);
196}
197
198function normalizeGrokReasoningEffort(value: string | undefined): string | undefined {
199 const effort = value?.trim();
200 return effort && isValidGrokReasoningEffortToken(effort) ? effort : undefined;
201}
202
203export function currentGrokModelIdFromSessionSetup(
204 sessionSetupResult:
205 | EffectAcpSchema.LoadSessionResponse
206 | EffectAcpSchema.NewSessionResponse
207 | EffectAcpSchema.ResumeSessionResponse,
208): string | undefined {
209 return sessionSetupResult.models?.currentModelId?.trim() || undefined;
210}
211
212export function currentGrokReasoningEffortFromSessionSetup(
213 sessionSetupResult:
214 | EffectAcpSchema.LoadSessionResponse
215 | EffectAcpSchema.NewSessionResponse
216 | EffectAcpSchema.ResumeSessionResponse,
217): string | undefined {
218 const modelState = sessionSetupResult.models;
219 if (!modelState) {
220 return undefined;
221 }
222 const currentModelId = modelState.currentModelId.trim();
223 if (currentModelId.length === 0) {
224 return undefined;
225 }
226 const currentModel = modelState.availableModels.find(
227 (model) => model.modelId.trim() === currentModelId,
228 );
229 const reasoningEffort = currentModel?._meta?.reasoningEffort;
230 return typeof reasoningEffort === "string"
231 ? normalizeGrokReasoningEffort(reasoningEffort)
232 : undefined;
233}
234
235export function applyGrokAcpModelSelection<E>(input: {
236 readonly runtime: Pick<AcpSessionRuntime.AcpSessionRuntime["Service"], "setSessionModel">;
237 readonly currentModelId: string | undefined;
238 readonly currentReasoningEffort?: string | undefined;
239 readonly requestedModelId: string | undefined;
240 readonly requestedReasoningEffort?: string | undefined;
241 readonly mapError: (cause: EffectAcpErrors.AcpError) => E;
242}): Effect.Effect<string | undefined, E> {
243 const requestedModelId =
244 input.requestedModelId === GROK_DEFAULT_MODEL_SLUG ? undefined : input.requestedModelId;
245 const modelChanged = requestedModelId !== undefined && requestedModelId !== input.currentModelId;
246 const reasoningProvided = input.requestedReasoningEffort !== undefined;
247 const reasoningEffort = reasoningProvided
248 ? normalizeGrokReasoningEffort(input.requestedReasoningEffort)
249 : undefined;
250 const reasoningEffortChanged =
251 reasoningProvided && reasoningEffort !== input.currentReasoningEffort;
252 const targetModelId = requestedModelId ?? input.currentModelId;
253 if ((!modelChanged && !reasoningEffortChanged) || targetModelId === undefined) {
254 return Effect.succeed(input.currentModelId);
255 }
256 const reasoningMeta =
257 reasoningProvided && reasoningEffort !== undefined ? { reasoningEffort } : undefined;
258 return input.runtime
259 .setSessionModel(targetModelId, reasoningMeta)
260 .pipe(Effect.mapError(input.mapError), Effect.as(targetModelId));
261}