Open History to see the last commit
1import { type GrokSettings, ProviderDriverKind, type RuntimeMode } from "@t3tools/contracts";
2import * as Crypto from "effect/Crypto";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Scope from "effect/Scope";
6import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
7import * as EffectAcpErrors from "effect-acp/errors";
8import type * as EffectAcpSchema from "effect-acp/schema";
9import { normalizeModelSlug } from "@t3tools/shared/model";
10
11import * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
12import { makeXAiPromptCompletionRuntime } from "./XAiAcpExtension.ts";
13
14const GROK_API_KEY_ENV = "XAI_API_KEY";
15const GROK_OAUTH2_REFERRER_ENV = "GROK_OAUTH2_REFERRER";
16const T3_CODE_OAUTH_REFERRER = "t3code";
17const GROK_AUTH_METHOD_API_KEY = "xai.api_key";
18const GROK_AUTH_METHOD_CACHED_TOKEN = "cached_token";
19const GROK_DRIVER_KIND = ProviderDriverKind.make("grok");
20
21type GrokAcpRuntimeGrokSettings = Pick<GrokSettings, "binaryPath">;
22
23interface GrokAcpRuntimeInput extends Omit<
24 AcpSessionRuntime.AcpSessionRuntimeOptions,
25 "authMethodId" | "clientCapabilities" | "spawn"
26> {
27 readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"];
28 readonly grokSettings: GrokAcpRuntimeGrokSettings | null | undefined;
29 readonly environment?: NodeJS.ProcessEnv;
30 readonly runtimeMode?: RuntimeMode;
31}
32
33export function grokAcpSpawnArgs(runtimeMode?: RuntimeMode): ReadonlyArray<string> {
34 switch (runtimeMode) {
35 case "approval-required":
36 return ["--permission-mode", "default", "agent", "stdio"];
37 case "auto-accept-edits":
38 return ["--permission-mode", "acceptEdits", "agent", "stdio"];
39 case "auto":
40 return ["--permission-mode", "auto", "agent", "stdio"];
41 case "full-access":
42 return ["agent", "--always-approve", "stdio"];
43 default:
44 return ["agent", "stdio"];
45 }
46}
47
48export function buildGrokAcpSpawnInput(
49 grokSettings: GrokAcpRuntimeGrokSettings | null | undefined,
50 cwd: string,
51 environment?: NodeJS.ProcessEnv,
52 runtimeMode?: RuntimeMode,
53): AcpSessionRuntime.AcpSpawnInput {
54 return {
55 command: grokSettings?.binaryPath || "grok",
56 args: [...grokAcpSpawnArgs(runtimeMode)],
57 cwd,
58 env: {
59 ...environment,
60 [GROK_OAUTH2_REFERRER_ENV]: T3_CODE_OAUTH_REFERRER,
61 },
62 };
63}
64
65function resolveGrokAuthMethodId(environment: NodeJS.ProcessEnv | undefined): string {
66 return environment?.[GROK_API_KEY_ENV]?.trim()
67 ? GROK_AUTH_METHOD_API_KEY
68 : GROK_AUTH_METHOD_CACHED_TOKEN;
69}
70
71export const makeGrokAcpRuntime = (
72 input: GrokAcpRuntimeInput,
73): Effect.Effect<
74 AcpSessionRuntime.AcpSessionRuntime["Service"],
75 EffectAcpErrors.AcpError,
76 Crypto.Crypto | Scope.Scope
77> =>
78 Effect.gen(function* () {
79 const acpContext = yield* Layer.build(
80 AcpSessionRuntime.layer({
81 ...input,
82 spawn: buildGrokAcpSpawnInput(
83 input.grokSettings,
84 input.cwd,
85 input.environment,
86 input.runtimeMode,
87 ),
88 authMethodId: resolveGrokAuthMethodId(input.environment),
89 }).pipe(
90 Layer.provide(
91 Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, input.childProcessSpawner),
92 ),
93 ),
94 );
95 const runtime = yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(
96 Effect.provide(acpContext),
97 );
98 return yield* makeXAiPromptCompletionRuntime(runtime);
99 });
100
101/**
102 * T3's built-in Grok slug. It is the CLI's product name, not a model id the ACP accepts,
103 * so selecting it means "use whatever model the Grok session currently runs on".
104 */
105export const GROK_DEFAULT_MODEL_SLUG = "grok-build";
106
107export function resolveGrokAcpBaseModelId(model: string | null | undefined): string {
108 const trimmed = model?.trim();
109 const base = trimmed && trimmed.length > 0 ? trimmed : GROK_DEFAULT_MODEL_SLUG;
110 return normalizeModelSlug(base, GROK_DRIVER_KIND) ?? GROK_DEFAULT_MODEL_SLUG;
111}
112
113const GROK_REASONING_EFFORT_TOKEN = /^[a-z0-9][a-z0-9._-]{0,31}$/i;
114
115export function isValidGrokReasoningEffortToken(value: string): boolean {
116 return GROK_REASONING_EFFORT_TOKEN.test(value);
117}
118
119export function normalizeGrokReasoningEffort(value: string | undefined): string | undefined {
120 const effort = value?.trim();
121 return effort && isValidGrokReasoningEffortToken(effort) ? effort : undefined;
122}
123
124export function currentGrokModelIdFromSessionSetup(
125 sessionSetupResult:
126 | EffectAcpSchema.LoadSessionResponse
127 | EffectAcpSchema.NewSessionResponse
128 | EffectAcpSchema.ResumeSessionResponse,
129): string | undefined {
130 return sessionSetupResult.models?.currentModelId?.trim() || undefined;
131}
132
133export function currentGrokReasoningEffortFromSessionSetup(
134 sessionSetupResult:
135 | EffectAcpSchema.LoadSessionResponse
136 | EffectAcpSchema.NewSessionResponse
137 | EffectAcpSchema.ResumeSessionResponse,
138): string | undefined {
139 const modelState = sessionSetupResult.models;
140 if (!modelState) {
141 return undefined;
142 }
143 const currentModelId = modelState.currentModelId.trim();
144 if (currentModelId.length === 0) {
145 return undefined;
146 }
147 const currentModel = modelState.availableModels.find(
148 (model) => model.modelId.trim() === currentModelId,
149 );
150 const reasoningEffort = currentModel?._meta?.reasoningEffort;
151 return typeof reasoningEffort === "string"
152 ? normalizeGrokReasoningEffort(reasoningEffort)
153 : undefined;
154}
155
156export function applyGrokAcpModelSelection<E>(input: {
157 readonly runtime: Pick<AcpSessionRuntime.AcpSessionRuntime["Service"], "setSessionModel">;
158 readonly currentModelId: string | undefined;
159 readonly currentReasoningEffort?: string | undefined;
160 readonly requestedModelId: string | undefined;
161 readonly requestedReasoningEffort?: string | undefined;
162 readonly mapError: (cause: EffectAcpErrors.AcpError) => E;
163}): Effect.Effect<string | undefined, E> {
164 // The product slug is never sent over the wire; it keeps the session's current model.
165 const requestedModelId =
166 input.requestedModelId === GROK_DEFAULT_MODEL_SLUG ? undefined : input.requestedModelId;
167 const modelChanged = requestedModelId !== undefined && requestedModelId !== input.currentModelId;
168 const reasoningProvided = input.requestedReasoningEffort !== undefined;
169 const reasoningEffort = reasoningProvided
170 ? normalizeGrokReasoningEffort(input.requestedReasoningEffort)
171 : undefined;
172 const reasoningEffortChanged =
173 reasoningProvided && reasoningEffort !== input.currentReasoningEffort;
174 const targetModelId = requestedModelId ?? input.currentModelId;
175 if ((!modelChanged && !reasoningEffortChanged) || targetModelId === undefined) {
176 return Effect.succeed(input.currentModelId);
177 }
178 const reasoningMeta =
179 reasoningProvided && reasoningEffort !== undefined ? { reasoningEffort } : undefined;
180 // When reasoning was explicitly provided but invalid (normalize => undefined), we deliberately
181 // send no meta so the invalid value is dropped rather than forwarded. When reasoning was not
182 // provided at all, we also send no meta, but we only reach this call when the model itself
183 // changed - an omitted reasoning preference must not be treated as an explicit clear of the
184 // CLI-advertised default (e.g. Extra High) on same-model reselections.
185 return input.runtime
186 .setSessionModel(targetModelId, reasoningMeta)
187 .pipe(Effect.mapError(input.mapError), Effect.as(targetModelId));
188}