The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 03:37 UTC
| 1 | import type * as EffectAcpSchema from "effect-acp/compat"; |
| 2 | import * as NodeServices from "@effect/platform-node/NodeServices"; |
| 3 | import { |
| 4 | type ProviderApprovalOption, |
| 5 | ProviderDriverKind, |
| 6 | type RuntimeMode, |
| 7 | } from "@t3tools/contracts"; |
| 8 | import type { GrokSettings } from "../settings.ts"; |
| 9 | import * as SecureRandom from "effect/crypto/SecureRandom"; |
| 10 | import * as Effect from "effect/Effect"; |
| 11 | import * as Layer from "effect/Layer"; |
| 12 | import * as Scope from "effect/Scope"; |
| 13 | import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; |
| 14 | import * as EffectAcpErrors from "effect-acp/errors"; |
| 15 | import * as HostProcess from "@t3tools/shared/HostProcess"; |
| 16 | import { normalizeModelSlug } from "@t3tools/shared/model"; |
| 17 | |
| 18 | import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime"; |
| 19 | import { makeXAiPromptCompletionRuntime } from "./xaiAcpExtension.ts"; |
| 20 | |
| 21 | const GROK_API_KEY_ENV = "XAI_API_KEY"; |
| 22 | const GROK_OAUTH2_REFERRER_ENV = "GROK_OAUTH2_REFERRER"; |
| 23 | const T3_CODE_OAUTH_REFERRER = "t3code"; |
| 24 | const GROK_AUTH_METHOD_API_KEY = "xai.api_key"; |
| 25 | const GROK_AUTH_METHOD_CACHED_TOKEN = "cached_token"; |
| 26 | const GROK_DRIVER_KIND = ProviderDriverKind.make("grok"); |
| 27 | |
| 28 | type GrokAcpRuntimeGrokSettings = Pick<GrokSettings, "binaryPath">; |
| 29 | |
| 30 | interface 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 | // grok agent treats settings-only acceptEdits as ask; it has no Auto-accept edits launch mode. |
| 40 | export const GROK_SUPPORTED_RUNTIME_MODES = [ |
| 41 | "approval-required", |
| 42 | "auto", |
| 43 | "full-access", |
| 44 | ] as const satisfies ReadonlyArray<RuntimeMode>; |
| 45 | |
| 46 | // argv overrides Grok config so Supervised cannot inherit always-approve. |
| 47 | export function grokAcpSpawnArgs(runtimeMode?: RuntimeMode): ReadonlyArray<string> { |
| 48 | switch (runtimeMode) { |
| 49 | case undefined: |
| 50 | return ["agent", "stdio"]; |
| 51 | case "auto": |
| 52 | return ["--permission-mode", "auto", "agent", "stdio"]; |
| 53 | case "full-access": |
| 54 | return ["agent", "--always-approve", "stdio"]; |
| 55 | default: |
| 56 | return ["--permission-mode", "default", "agent", "stdio"]; |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | function buildGrokAcpSpawnInput( |
| 61 | grokSettings: GrokAcpRuntimeGrokSettings | null | undefined, |
| 62 | cwd: string, |
| 63 | environment?: NodeJS.ProcessEnv, |
| 64 | runtimeMode?: RuntimeMode, |
| 65 | ): AcpSessionRuntime.AcpSpawnInput { |
| 66 | return { |
| 67 | command: grokSettings?.binaryPath || "grok", |
| 68 | args: [...grokAcpSpawnArgs(runtimeMode)], |
| 69 | cwd, |
| 70 | env: { |
| 71 | ...environment, |
| 72 | [GROK_OAUTH2_REFERRER_ENV]: T3_CODE_OAUTH_REFERRER, |
| 73 | }, |
| 74 | }; |
| 75 | } |
| 76 | |
| 77 | function resolveGrokAuthMethodId(environment: NodeJS.ProcessEnv | undefined): string { |
| 78 | return environment?.[GROK_API_KEY_ENV]?.trim() |
| 79 | ? GROK_AUTH_METHOD_API_KEY |
| 80 | : GROK_AUTH_METHOD_CACHED_TOKEN; |
| 81 | } |
| 82 | |
| 83 | function grokAcpRuntimeProcessOwnership( |
| 84 | processGroupPlatform: NodeJS.Platform, |
| 85 | ): Pick< |
| 86 | AcpSessionRuntime.AcpSessionRuntimeOptions, |
| 87 | "ownDescendantProcessGroups" | "ownDetachedProcessGroup" | "processGroupPlatform" |
| 88 | > { |
| 89 | return { |
| 90 | // macOS lacks a stable libproc identity provider for Grok's nested detached tool groups. |
| 91 | ownDescendantProcessGroups: processGroupPlatform === "linux", |
| 92 | ownDetachedProcessGroup: true, |
| 93 | processGroupPlatform, |
| 94 | }; |
| 95 | } |
| 96 | |
| 97 | // Grok Ctrl+C blocks stale background wakes until the next genuine user turn. |
| 98 | export const GROK_ACP_CANCEL_META = { cancelTrigger: "ctrl_c" } as const; |
| 99 | |
| 100 | // generic silently denies Auto refusals; extension prompts without persistent command grants. |
| 101 | export const GROK_ACP_INITIALIZE_META = { clientType: "extension" } as const; |
| 102 | |
| 103 | // Only allow-edits-session is session-scoped; other allow-always choices persist project grants. |
| 104 | const GROK_ALLOW_EDITS_SESSION_OPTION_ID = "allow-edits-session"; |
| 105 | |
| 106 | export function grokApprovalOptions( |
| 107 | request: EffectAcpSchema.RequestPermissionRequest, |
| 108 | ): ReadonlyArray<ProviderApprovalOption> { |
| 109 | const has = (kind: EffectAcpSchema.PermissionOption["kind"], optionId?: string) => |
| 110 | request.options.some( |
| 111 | (option) => |
| 112 | option.kind === kind && (optionId === undefined || option.optionId.trim() === optionId), |
| 113 | ); |
| 114 | return [ |
| 115 | { decision: "cancel", label: "Cancel" }, |
| 116 | ...(has("reject_once") ? [{ decision: "decline", label: "Decline" } as const] : []), |
| 117 | ...(has("allow_always", GROK_ALLOW_EDITS_SESSION_OPTION_ID) |
| 118 | ? [{ decision: "acceptForSession", label: "Allow all edits this session" } as const] |
| 119 | : []), |
| 120 | ...(has("allow_once") ? [{ decision: "accept", label: "Approve" } as const] : []), |
| 121 | ]; |
| 122 | } |
| 123 | |
| 124 | export const makeGrokAcpRuntime = Effect.fn("GrokAcpSupport.makeGrokAcpRuntime")(function* ( |
| 125 | input: GrokAcpRuntimeInput, |
| 126 | ): Effect.fn.Return< |
| 127 | AcpSessionRuntime.AcpSessionRuntime["Service"], |
| 128 | EffectAcpErrors.AcpError, |
| 129 | ChildProcessSpawner.ChildProcessSpawner | SecureRandom.SecureRandom | Scope.Scope |
| 130 | > { |
| 131 | const processGroupPlatform = yield* HostProcess.Platform.pipe(Effect.provide(NodeServices.layer)); |
| 132 | const acpContext = yield* Layer.build( |
| 133 | AcpSessionRuntime.layer({ |
| 134 | ...input, |
| 135 | spawn: buildGrokAcpSpawnInput( |
| 136 | input.grokSettings, |
| 137 | input.cwd, |
| 138 | input.environment, |
| 139 | input.runtimeMode, |
| 140 | ), |
| 141 | authMethodId: resolveGrokAuthMethodId(input.environment), |
| 142 | cancelMeta: { ...input.cancelMeta, ...GROK_ACP_CANCEL_META }, |
| 143 | initializeMeta: GROK_ACP_INITIALIZE_META, |
| 144 | // Grok's session/load can stay unanswered after replay finishes. |
| 145 | sessionLoadReplayIdleReadiness: true, |
| 146 | ...grokAcpRuntimeProcessOwnership(processGroupPlatform), |
| 147 | }), |
| 148 | ); |
| 149 | const runtime = yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe( |
| 150 | Effect.provide(acpContext), |
| 151 | ); |
| 152 | return yield* makeXAiPromptCompletionRuntime(runtime); |
| 153 | }); |
| 154 | |
| 155 | // This product name is not an ACP model ID; it selects the current session model. |
| 156 | export const GROK_DEFAULT_MODEL_SLUG = "grok-build"; |
| 157 | |
| 158 | export function resolveGrokAcpBaseModelId(model: string | null | undefined): string { |
| 159 | const trimmed = model?.trim(); |
| 160 | const base = trimmed && trimmed.length > 0 ? trimmed : GROK_DEFAULT_MODEL_SLUG; |
| 161 | return normalizeModelSlug(base, GROK_DRIVER_KIND) ?? GROK_DEFAULT_MODEL_SLUG; |
| 162 | } |
| 163 | |
| 164 | const GROK_REASONING_EFFORT_TOKEN = /^[a-z0-9][a-z0-9._-]{0,31}$/i; |
| 165 | |
| 166 | export function isValidGrokReasoningEffortToken(value: string): boolean { |
| 167 | return GROK_REASONING_EFFORT_TOKEN.test(value); |
| 168 | } |
| 169 | |
| 170 | function normalizeGrokReasoningEffort(value: string | undefined): string | undefined { |
| 171 | const effort = value?.trim(); |
| 172 | return effort && isValidGrokReasoningEffortToken(effort) ? effort : undefined; |
| 173 | } |
| 174 | |
| 175 | export function currentGrokModelIdFromSessionSetup( |
| 176 | sessionSetupResult: |
| 177 | | EffectAcpSchema.LoadSessionResponse |
| 178 | | EffectAcpSchema.NewSessionResponse |
| 179 | | EffectAcpSchema.ResumeSessionResponse, |
| 180 | ): string | undefined { |
| 181 | return sessionSetupResult.models?.currentModelId?.trim() || undefined; |
| 182 | } |
| 183 | |
| 184 | export function currentGrokReasoningEffortFromSessionSetup( |
| 185 | sessionSetupResult: |
| 186 | | EffectAcpSchema.LoadSessionResponse |
| 187 | | EffectAcpSchema.NewSessionResponse |
| 188 | | EffectAcpSchema.ResumeSessionResponse, |
| 189 | ): string | undefined { |
| 190 | const modelState = sessionSetupResult.models; |
| 191 | if (!modelState) { |
| 192 | return undefined; |
| 193 | } |
| 194 | const currentModelId = modelState.currentModelId.trim(); |
| 195 | if (currentModelId.length === 0) { |
| 196 | return undefined; |
| 197 | } |
| 198 | const currentModel = modelState.availableModels.find( |
| 199 | (model) => model.modelId.trim() === currentModelId, |
| 200 | ); |
| 201 | const reasoningEffort = currentModel?._meta?.reasoningEffort; |
| 202 | return typeof reasoningEffort === "string" |
| 203 | ? normalizeGrokReasoningEffort(reasoningEffort) |
| 204 | : undefined; |
| 205 | } |
| 206 | |
| 207 | export function applyGrokAcpModelSelection<E>(input: { |
| 208 | readonly runtime: Pick<AcpSessionRuntime.AcpSessionRuntime["Service"], "setSessionModel">; |
| 209 | readonly currentModelId: string | undefined; |
| 210 | readonly currentReasoningEffort?: string | undefined; |
| 211 | readonly requestedModelId: string | undefined; |
| 212 | readonly requestedReasoningEffort?: string | undefined; |
| 213 | readonly mapError: (cause: EffectAcpErrors.AcpError) => E; |
| 214 | }): Effect.Effect<string | undefined, E> { |
| 215 | const requestedModelId = |
| 216 | input.requestedModelId === GROK_DEFAULT_MODEL_SLUG ? undefined : input.requestedModelId; |
| 217 | const modelChanged = requestedModelId !== undefined && requestedModelId !== input.currentModelId; |
| 218 | const reasoningProvided = input.requestedReasoningEffort !== undefined; |
| 219 | const reasoningEffort = reasoningProvided |
| 220 | ? normalizeGrokReasoningEffort(input.requestedReasoningEffort) |
| 221 | : undefined; |
| 222 | const reasoningEffortChanged = |
| 223 | reasoningProvided && reasoningEffort !== input.currentReasoningEffort; |
| 224 | const targetModelId = requestedModelId ?? input.currentModelId; |
| 225 | if ((!modelChanged && !reasoningEffortChanged) || targetModelId === undefined) { |
| 226 | return Effect.succeed(input.currentModelId); |
| 227 | } |
| 228 | const reasoningMeta = |
| 229 | reasoningProvided && reasoningEffort !== undefined ? { reasoningEffort } : undefined; |
| 230 | return input.runtime |
| 231 | .setSessionModel(targetModelId, reasoningMeta) |
| 232 | .pipe(Effect.mapError(input.mapError), Effect.as(targetModelId)); |
| 233 | } |