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

GrokAcpSupport.ts

212 lines8.3 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​
35export function grokAcpSpawnArgs(runtimeMode?: RuntimeMode): ReadonlyArray<string> {
36 switch (runtimeMode) {
37 case "approval-required":
38 return ["--permission-mode", "default", "agent", "stdio"];
39 case "auto-accept-edits":
40 return ["--permission-mode", "acceptEdits", "agent", "stdio"];
41 case "auto":
42 return ["--permission-mode", "auto", "agent", "stdio"];
43 case "full-access":
44 return ["agent", "--always-approve", "stdio"];
45 default:
46 return ["agent", "stdio"];
47 }
49​
50export function buildGrokAcpSpawnInput(
51 grokSettings: GrokAcpRuntimeGrokSettings | null | undefined,
52 cwd: string,
53 environment?: NodeJS.ProcessEnv,
54 runtimeMode?: RuntimeMode,
55): AcpSessionRuntime.AcpSpawnInput {
56 return {
57 command: grokSettings?.binaryPath || "grok",
58 args: [...grokAcpSpawnArgs(runtimeMode)],
59 cwd,
60 env: {
61 ...environment,
62 [GROK_OAUTH2_REFERRER_ENV]: T3_CODE_OAUTH_REFERRER,
63 },
64 };
66​
67function resolveGrokAuthMethodId(environment: NodeJS.ProcessEnv | undefined): string {
68 return environment?.[GROK_API_KEY_ENV]?.trim()
69 ? GROK_AUTH_METHOD_API_KEY
70 : GROK_AUTH_METHOD_CACHED_TOKEN;
72​
73export function grokAcpRuntimeProcessOwnership(
74 processGroupPlatform: NodeJS.Platform,
75): Pick<
76 AcpSessionRuntime.AcpSessionRuntimeOptions,
77 "ownDescendantProcessGroups" | "ownDetachedProcessGroup" | "processGroupPlatform"
78> {
79 return {
80 // macOS keeps the prior provider-group teardown until a stable libproc
81 // identity provider can cover Grok's nested detached tool groups.
82 ownDescendantProcessGroups: processGroupPlatform === "linux",
83 ownDetachedProcessGroup: true,
84 processGroupPlatform,
85 };
87​
88export const makeGrokAcpRuntime = (
89 input: GrokAcpRuntimeInput,
90): Effect.Effect<
91 AcpSessionRuntime.AcpSessionRuntime["Service"],
92 EffectAcpErrors.AcpError,
93 Crypto.Crypto | Scope.Scope
94> =>
95 Effect.gen(function* () {
96 const processGroupPlatform = yield* HostProcessPlatform.pipe(
97 Effect.provide(NodeServices.layer),
98 );
99 const acpContext = yield* Layer.build(
100 AcpSessionRuntime.layer({
101 ...input,
102 spawn: buildGrokAcpSpawnInput(
103 input.grokSettings,
104 input.cwd,
105 input.environment,
106 input.runtimeMode,
107 ),
108 authMethodId: resolveGrokAuthMethodId(input.environment),
109 // Current Grok treats Ctrl+C cancellation as a barrier against stale
110 // background-task wake prompts until the next genuine user turn.
111 cancelMeta: { ...input.cancelMeta, cancelTrigger: "ctrl_c" },
112 ...grokAcpRuntimeProcessOwnership(processGroupPlatform),
113 }).pipe(
114 Layer.provide(
115 Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, input.childProcessSpawner),
116 ),
117 ),
118 );
119 const runtime = yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(
120 Effect.provide(acpContext),
121 );
122 return yield* makeXAiPromptCompletionRuntime(runtime);
123 });
124​
125/**
126 * T3's built-in Grok slug. It is the CLI's product name, not a model id the ACP accepts,
127 * so selecting it means "use whatever model the Grok session currently runs on".
128 */
129export const GROK_DEFAULT_MODEL_SLUG = "grok-build";
130​
131export function resolveGrokAcpBaseModelId(model: string | null | undefined): string {
132 const trimmed = model?.trim();
133 const base = trimmed && trimmed.length > 0 ? trimmed : GROK_DEFAULT_MODEL_SLUG;
134 return normalizeModelSlug(base, GROK_DRIVER_KIND) ?? GROK_DEFAULT_MODEL_SLUG;
136​
137const GROK_REASONING_EFFORT_TOKEN = /^[a-z0-9][a-z0-9._-]{0,31}$/i;
138​
139export function isValidGrokReasoningEffortToken(value: string): boolean {
140 return GROK_REASONING_EFFORT_TOKEN.test(value);
142​
143function normalizeGrokReasoningEffort(value: string | undefined): string | undefined {
144 const effort = value?.trim();
145 return effort && isValidGrokReasoningEffortToken(effort) ? effort : undefined;
147​
148export function currentGrokModelIdFromSessionSetup(
149 sessionSetupResult:
150 | EffectAcpSchema.LoadSessionResponse
151 | EffectAcpSchema.NewSessionResponse
152 | EffectAcpSchema.ResumeSessionResponse,
153): string | undefined {
154 return sessionSetupResult.models?.currentModelId?.trim() || undefined;
156​
157export function currentGrokReasoningEffortFromSessionSetup(
158 sessionSetupResult:
159 | EffectAcpSchema.LoadSessionResponse
160 | EffectAcpSchema.NewSessionResponse
161 | EffectAcpSchema.ResumeSessionResponse,
162): string | undefined {
163 const modelState = sessionSetupResult.models;
164 if (!modelState) {
165 return undefined;
166 }
167 const currentModelId = modelState.currentModelId.trim();
168 if (currentModelId.length === 0) {
169 return undefined;
170 }
171 const currentModel = modelState.availableModels.find(
172 (model) => model.modelId.trim() === currentModelId,
173 );
174 const reasoningEffort = currentModel?._meta?.reasoningEffort;
175 return typeof reasoningEffort === "string"
176 ? normalizeGrokReasoningEffort(reasoningEffort)
177 : undefined;
179​
180export function applyGrokAcpModelSelection<E>(input: {
181 readonly runtime: Pick<AcpSessionRuntime.AcpSessionRuntime["Service"], "setSessionModel">;
182 readonly currentModelId: string | undefined;
183 readonly currentReasoningEffort?: string | undefined;
184 readonly requestedModelId: string | undefined;
185 readonly requestedReasoningEffort?: string | undefined;
186 readonly mapError: (cause: EffectAcpErrors.AcpError) => E;
187}): Effect.Effect<string | undefined, E> {
188 // The product slug is never sent over the wire; it keeps the session's current model.
189 const requestedModelId =
190 input.requestedModelId === GROK_DEFAULT_MODEL_SLUG ? undefined : input.requestedModelId;
191 const modelChanged = requestedModelId !== undefined && requestedModelId !== input.currentModelId;
192 const reasoningProvided = input.requestedReasoningEffort !== undefined;
193 const reasoningEffort = reasoningProvided
194 ? normalizeGrokReasoningEffort(input.requestedReasoningEffort)
195 : undefined;
196 const reasoningEffortChanged =
197 reasoningProvided && reasoningEffort !== input.currentReasoningEffort;
198 const targetModelId = requestedModelId ?? input.currentModelId;
199 if ((!modelChanged && !reasoningEffortChanged) || targetModelId === undefined) {
200 return Effect.succeed(input.currentModelId);
201 }
202 const reasoningMeta =
203 reasoningProvided && reasoningEffort !== undefined ? { reasoningEffort } : undefined;
204 // When reasoning was explicitly provided but invalid (normalize => undefined), we deliberately
205 // send no meta so the invalid value is dropped rather than forwarded. When reasoning was not
206 // provided at all, we also send no meta, but we only reach this call when the model itself
207 // changed - an omitted reasoning preference must not be treated as an explicit clear of the
208 // CLI-advertised default (e.g. Extra High) on same-model reselections.
209 return input.runtime
210 .setSessionModel(targetModelId, reasoningMeta)
211 .pipe(Effect.mapError(input.mapError), Effect.as(targetModelId));