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

GrokAcpSupport.ts

231 lines8.9 KB

1import type * as EffectAcpSchema from "effect-acp/compat";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { type GrokSettings, ProviderDriverKind, type RuntimeMode } from "@t3tools/contracts";
4import * as Crypto from "effect/Crypto";
5import * as Effect from "effect/Effect";
6import * as Layer from "effect/Layer";
7import * as Scope from "effect/Scope";
8import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
9import * as EffectAcpErrors from "effect-acp/errors";
10import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
11import { normalizeModelSlug } from "@t3tools/shared/model";
12​
13import * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
14import { makeXAiPromptCompletionRuntime } from "./XAiAcpExtension.ts";
15​
16const GROK_API_KEY_ENV = "XAI_API_KEY";
17const GROK_OAUTH2_REFERRER_ENV = "GROK_OAUTH2_REFERRER";
18const T3_CODE_OAUTH_REFERRER = "t3code";
19const GROK_AUTH_METHOD_API_KEY = "xai.api_key";
20const GROK_AUTH_METHOD_CACHED_TOKEN = "cached_token";
21const GROK_DRIVER_KIND = ProviderDriverKind.make("grok");
22​
23type GrokAcpRuntimeGrokSettings = Pick<GrokSettings, "binaryPath">;
24​
25interface GrokAcpRuntimeInput extends Omit<
26 AcpSessionRuntime.AcpSessionRuntimeOptions,
27 "authMethodId" | "clientCapabilities" | "spawn"
28> {
29 readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"];
30 readonly grokSettings: GrokAcpRuntimeGrokSettings | null | undefined;
31 readonly environment?: NodeJS.ProcessEnv;
32 readonly runtimeMode?: RuntimeMode;
34​
35/**
36 * The runtime modes `grok agent` can launch in: ask, its auto classifier, and
37 * always-approve. It has no Auto-accept edits: `acceptEdits` only exists as a
38 * settings-file `permissions.defaultMode`, and `grok agent` treats it as ask.
39 */
40export const GROK_SUPPORTED_RUNTIME_MODES = [
41 "approval-required",
42 "auto",
43 "full-access",
44] as const satisfies ReadonlyArray<RuntimeMode>;
45​
46/**
47 * Launch argv for a runtime mode. `--permission-mode` on the argv beats the
48 * user's Grok config, so Supervised cannot inherit a configured always-approve.
49 * A mode Grok does not offer launches asking.
50 */
51export function grokAcpSpawnArgs(runtimeMode?: RuntimeMode): ReadonlyArray<string> {
52 switch (runtimeMode) {
53 case undefined:
54 return ["agent", "stdio"];
55 case "auto":
56 return ["--permission-mode", "auto", "agent", "stdio"];
57 case "full-access":
58 return ["agent", "--always-approve", "stdio"];
59 default:
60 return ["--permission-mode", "default", "agent", "stdio"];
61 }
63​
64export function buildGrokAcpSpawnInput(
65 grokSettings: GrokAcpRuntimeGrokSettings | null | undefined,
66 cwd: string,
67 environment?: NodeJS.ProcessEnv,
68 runtimeMode?: RuntimeMode,
69): AcpSessionRuntime.AcpSpawnInput {
70 return {
71 command: grokSettings?.binaryPath || "grok",
72 args: [...grokAcpSpawnArgs(runtimeMode)],
73 cwd,
74 env: {
75 ...environment,
76 [GROK_OAUTH2_REFERRER_ENV]: T3_CODE_OAUTH_REFERRER,
77 },
78 };
80​
81function resolveGrokAuthMethodId(environment: NodeJS.ProcessEnv | undefined): string {
82 return environment?.[GROK_API_KEY_ENV]?.trim()
83 ? GROK_AUTH_METHOD_API_KEY
84 : GROK_AUTH_METHOD_CACHED_TOKEN;
86​
87export function grokAcpRuntimeProcessOwnership(
88 processGroupPlatform: NodeJS.Platform,
89): Pick<
90 AcpSessionRuntime.AcpSessionRuntimeOptions,
91 "ownDescendantProcessGroups" | "ownDetachedProcessGroup" | "processGroupPlatform"
92> {
93 return {
94 // macOS keeps the prior provider-group teardown until a stable libproc
95 // identity provider can cover Grok's nested detached tool groups.
96 ownDescendantProcessGroups: processGroupPlatform === "linux",
97 ownDetachedProcessGroup: true,
98 processGroupPlatform,
99 };
101​
102/**
103 * Current Grok treats Ctrl+C cancellation as a barrier against stale
104 * background-task wake prompts until the next genuine user turn. Replay sends
105 * the same metadata so recorded cancels match.
106 */
107export const GROK_ACP_CANCEL_META = { cancelTrigger: "ctrl_c" } as const;
108​
109export const makeGrokAcpRuntime = (
110 input: GrokAcpRuntimeInput,
111): Effect.Effect<
112 AcpSessionRuntime.AcpSessionRuntime["Service"],
113 EffectAcpErrors.AcpError,
114 Crypto.Crypto | Scope.Scope
115> =>
116 Effect.gen(function* () {
117 const processGroupPlatform = yield* HostProcessPlatform.pipe(
118 Effect.provide(NodeServices.layer),
119 );
120 const acpContext = yield* Layer.build(
121 AcpSessionRuntime.layer({
122 ...input,
123 spawn: buildGrokAcpSpawnInput(
124 input.grokSettings,
125 input.cwd,
126 input.environment,
127 input.runtimeMode,
128 ),
129 authMethodId: resolveGrokAuthMethodId(input.environment),
130 cancelMeta: { ...input.cancelMeta, ...GROK_ACP_CANCEL_META },
131 ...grokAcpRuntimeProcessOwnership(processGroupPlatform),
132 }).pipe(
133 Layer.provide(
134 Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, input.childProcessSpawner),
135 ),
136 ),
137 );
138 const runtime = yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(
139 Effect.provide(acpContext),
140 );
141 return yield* makeXAiPromptCompletionRuntime(runtime);
142 });
143​
144/**
145 * T3's built-in Grok slug. It is the CLI's product name, not a model id the ACP accepts,
146 * so selecting it means "use whatever model the Grok session currently runs on".
147 */
148export const GROK_DEFAULT_MODEL_SLUG = "grok-build";
149​
150export function resolveGrokAcpBaseModelId(model: string | null | undefined): string {
151 const trimmed = model?.trim();
152 const base = trimmed && trimmed.length > 0 ? trimmed : GROK_DEFAULT_MODEL_SLUG;
153 return normalizeModelSlug(base, GROK_DRIVER_KIND) ?? GROK_DEFAULT_MODEL_SLUG;
155​
156const GROK_REASONING_EFFORT_TOKEN = /^[a-z0-9][a-z0-9._-]{0,31}$/i;
157​
158export function isValidGrokReasoningEffortToken(value: string): boolean {
159 return GROK_REASONING_EFFORT_TOKEN.test(value);
161​
162function normalizeGrokReasoningEffort(value: string | undefined): string | undefined {
163 const effort = value?.trim();
164 return effort && isValidGrokReasoningEffortToken(effort) ? effort : undefined;
166​
167export function currentGrokModelIdFromSessionSetup(
168 sessionSetupResult:
169 | EffectAcpSchema.LoadSessionResponse
170 | EffectAcpSchema.NewSessionResponse
171 | EffectAcpSchema.ResumeSessionResponse,
172): string | undefined {
173 return sessionSetupResult.models?.currentModelId?.trim() || undefined;
175​
176export function currentGrokReasoningEffortFromSessionSetup(
177 sessionSetupResult:
178 | EffectAcpSchema.LoadSessionResponse
179 | EffectAcpSchema.NewSessionResponse
180 | EffectAcpSchema.ResumeSessionResponse,
181): string | undefined {
182 const modelState = sessionSetupResult.models;
183 if (!modelState) {
184 return undefined;
185 }
186 const currentModelId = modelState.currentModelId.trim();
187 if (currentModelId.length === 0) {
188 return undefined;
189 }
190 const currentModel = modelState.availableModels.find(
191 (model) => model.modelId.trim() === currentModelId,
192 );
193 const reasoningEffort = currentModel?._meta?.reasoningEffort;
194 return typeof reasoningEffort === "string"
195 ? normalizeGrokReasoningEffort(reasoningEffort)
196 : undefined;
198​
199export function applyGrokAcpModelSelection<E>(input: {
200 readonly runtime: Pick<AcpSessionRuntime.AcpSessionRuntime["Service"], "setSessionModel">;
201 readonly currentModelId: string | undefined;
202 readonly currentReasoningEffort?: string | undefined;
203 readonly requestedModelId: string | undefined;
204 readonly requestedReasoningEffort?: string | undefined;
205 readonly mapError: (cause: EffectAcpErrors.AcpError) => E;
206}): Effect.Effect<string | undefined, E> {
207 // The product slug is never sent over the wire; it keeps the session's current model.
208 const requestedModelId =
209 input.requestedModelId === GROK_DEFAULT_MODEL_SLUG ? undefined : input.requestedModelId;
210 const modelChanged = requestedModelId !== undefined && requestedModelId !== input.currentModelId;
211 const reasoningProvided = input.requestedReasoningEffort !== undefined;
212 const reasoningEffort = reasoningProvided
213 ? normalizeGrokReasoningEffort(input.requestedReasoningEffort)
214 : undefined;
215 const reasoningEffortChanged =
216 reasoningProvided && reasoningEffort !== input.currentReasoningEffort;
217 const targetModelId = requestedModelId ?? input.currentModelId;
218 if ((!modelChanged && !reasoningEffortChanged) || targetModelId === undefined) {
219 return Effect.succeed(input.currentModelId);
220 }
221 const reasoningMeta =
222 reasoningProvided && reasoningEffort !== undefined ? { reasoningEffort } : undefined;
223 // When reasoning was explicitly provided but invalid (normalize => undefined), we deliberately
224 // send no meta so the invalid value is dropped rather than forwarded. When reasoning was not
225 // provided at all, we also send no meta, but we only reach this call when the model itself
226 // changed - an omitted reasoning preference must not be treated as an explicit clear of the
227 // CLI-advertised default (e.g. Extra High) on same-model reselections.
228 return input.runtime
229 .setSessionModel(targetModelId, reasoningMeta)
230 .pipe(Effect.mapError(input.mapError), Effect.as(targetModelId));