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

GrokAcpSupport.ts

180 lines6.8 KB

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;
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 }
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 };
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;
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​
101export function resolveGrokAcpBaseModelId(model: string | null | undefined): string {
102 const trimmed = model?.trim();
103 const base = trimmed && trimmed.length > 0 ? trimmed : "grok-build";
104 return normalizeModelSlug(base, GROK_DRIVER_KIND) ?? "grok-build";
106​
107const GROK_REASONING_EFFORT_TOKEN = /^[a-z0-9][a-z0-9._-]{0,31}$/i;
108​
109export function isValidGrokReasoningEffortToken(value: string): boolean {
110 return GROK_REASONING_EFFORT_TOKEN.test(value);
112​
113export function normalizeGrokReasoningEffort(value: string | undefined): string | undefined {
114 const effort = value?.trim();
115 return effort && isValidGrokReasoningEffortToken(effort) ? effort : undefined;
117​
118export function currentGrokModelIdFromSessionSetup(
119 sessionSetupResult:
120 | EffectAcpSchema.LoadSessionResponse
121 | EffectAcpSchema.NewSessionResponse
122 | EffectAcpSchema.ResumeSessionResponse,
123): string | undefined {
124 return sessionSetupResult.models?.currentModelId?.trim() || undefined;
126​
127export function currentGrokReasoningEffortFromSessionSetup(
128 sessionSetupResult:
129 | EffectAcpSchema.LoadSessionResponse
130 | EffectAcpSchema.NewSessionResponse
131 | EffectAcpSchema.ResumeSessionResponse,
132): string | undefined {
133 const modelState = sessionSetupResult.models;
134 if (!modelState) {
135 return undefined;
136 }
137 const currentModelId = modelState.currentModelId.trim();
138 if (currentModelId.length === 0) {
139 return undefined;
140 }
141 const currentModel = modelState.availableModels.find(
142 (model) => model.modelId.trim() === currentModelId,
143 );
144 const reasoningEffort = currentModel?._meta?.reasoningEffort;
145 return typeof reasoningEffort === "string"
146 ? normalizeGrokReasoningEffort(reasoningEffort)
147 : undefined;
149​
150export function applyGrokAcpModelSelection<E>(input: {
151 readonly runtime: Pick<AcpSessionRuntime.AcpSessionRuntime["Service"], "setSessionModel">;
152 readonly currentModelId: string | undefined;
153 readonly currentReasoningEffort?: string | undefined;
154 readonly requestedModelId: string | undefined;
155 readonly requestedReasoningEffort?: string | undefined;
156 readonly mapError: (cause: EffectAcpErrors.AcpError) => E;
157}): Effect.Effect<string | undefined, E> {
158 const modelChanged =
159 input.requestedModelId !== undefined && input.requestedModelId !== input.currentModelId;
160 const reasoningProvided = input.requestedReasoningEffort !== undefined;
161 const reasoningEffort = reasoningProvided
162 ? normalizeGrokReasoningEffort(input.requestedReasoningEffort)
163 : undefined;
164 const reasoningEffortChanged =
165 reasoningProvided && reasoningEffort !== input.currentReasoningEffort;
166 const targetModelId = input.requestedModelId ?? input.currentModelId;
167 if ((!modelChanged && !reasoningEffortChanged) || targetModelId === undefined) {
168 return Effect.succeed(input.currentModelId);
169 }
170 const reasoningMeta =
171 reasoningProvided && reasoningEffort !== undefined ? { reasoningEffort } : undefined;
172 // When reasoning was explicitly provided but invalid (normalize => undefined), we deliberately
173 // send no meta so the invalid value is dropped rather than forwarded. When reasoning was not
174 // provided at all, we also send no meta, but we only reach this call when the model itself
175 // changed - an omitted reasoning preference must not be treated as an explicit clear of the
176 // CLI-advertised default (e.g. Extra High) on same-model reselections.
177 return input.runtime
178 .setSessionModel(targetModelId, reasoningMeta)
179 .pipe(Effect.mapError(input.mapError), Effect.as(targetModelId));