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

adapter.ts

484 lines19.1 KB

1import { makeProviderFailure } from "@t3tools/provider-core/server/failure";
2import {
3 XAiPromptFailureText,
4 isXAiTaskCompletedWakeNotification,
5 xAiRateLimitedErrorCode,
6} from "./xaiAcpExtension.ts";
7import { discoverGrokSkills, leadingGrokSkillMention } from "./skills.ts";
8import * as HostProcess from "@t3tools/shared/HostProcess";
9import { resolveSelfInvocation, type SelfInvocation } from "@t3tools/shared/nodeRuntime";
10import {
11 defaultInstanceIdForDriver,
12 ProviderDriverKind,
13 type OrchestrationV2ProviderCapabilities,
14 type RuntimeMode,
15} from "@t3tools/contracts";
16import { GrokSettings } from "../settings.ts";
17import * as SecureRandom from "effect/crypto/SecureRandom";
18import * as Effect from "effect/Effect";
19import * as FileSystem from "effect/FileSystem";
20import * as Path from "effect/Path";
21import * as Schema from "effect/Schema";
22import type * as Scope from "effect/Scope";
23import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
24import * as EffectAcpErrors from "effect-acp/errors";
25import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
26​
27import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
28import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
29import { makeAcpNativeLoggerFactory } from "@t3tools/provider-acp/server/nativeLogging";
30import {
31 applyGrokAcpModelSelection,
32 currentGrokModelIdFromSessionSetup,
33 GROK_DEFAULT_MODEL_SLUG,
34 grokApprovalOptions,
35 makeGrokAcpRuntime,
36 resolveGrokAcpBaseModelId,
37} from "./acpSupport.ts";
38import { grokReasoningOptionsFromModel } from "./status.ts";
39import {
40 extractGrokPlanMarkdownFromToolCallData,
41 extractXAiAcpBackgroundToolMutation,
42 extractXAiAcpSubagentEndNotice,
43 extractXAiAcpSubagentUpdate,
44 extractXAiAskUserQuestionIdentity,
45 extractXAiAskUserQuestions,
46 extractXAiBackgroundTaskCompletion,
47 extractXAiKilledBackgroundTasks,
48 extractXAiMonitorTaskId,
49 xAiBackgroundShellTaskId,
50 isXAiPersistentMonitor,
51 extractXAiExitPlanMarkdown,
52 registerXAiSubagentFinished,
53 makeXAiAskUserQuestionCancelledResponse,
54 makeXAiAskUserQuestionResponse,
55 makeXAiExitPlanModeCapturedResponse,
56 normalizeXAiAcpToolCallState,
57 registerXAiBackgroundTaskTracking,
58 XAiAskUserQuestionRequest,
59 XAiExitPlanModeRequest,
60} from "./xaiAcpExtension.ts";
61import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
62import { acpPermissionDisposition } from "@t3tools/provider-acp/server/clientPolicy";
63import {
64 findModelConfigOption,
65 sessionModelStateFromInitialize,
66} from "@t3tools/provider-acp/server/runtimeModel";
67import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
68import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
69import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
70import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
71import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
72import {
73 ProviderAdapterDriverCreateError,
74 type ProviderAdapterDriver,
75 type ProviderAdapterDriverCreateInput,
76} from "@t3tools/provider-core/server/adapterDriver";
77import {
78 AcpProviderCapabilitiesV2,
79 makeAcpAdapterV2,
80 type AcpAdapterV2ExtensionContext,
81 type AcpAdapterV2Flavor,
82 type AcpAdapterV2RuntimeInput,
83} from "@t3tools/provider-acp/server/adapter";
84​
85const isXAiPromptFailureText = Schema.is(XAiPromptFailureText);
86​
87export const GROK_PROVIDER = ProviderDriverKind.make("grok");
88const GROK_DRIVER_KIND = GROK_PROVIDER;
89export const GROK_DEFAULT_INSTANCE_ID = defaultInstanceIdForDriver(GROK_DRIVER_KIND);
90const DEFAULT_GROK_SETTINGS = Schema.decodeSync(GrokSettings)({});
91const isAcpRequestError = Schema.is(EffectAcpErrors.AcpRequestError);
92​
93const GrokProviderCapabilitiesV2 = {
94 ...AcpProviderCapabilitiesV2,
95 sessions: {
96 ...AcpProviderCapabilitiesV2.sessions,
97 supportsModelSwitchInSession: true,
98 supportsRuntimeModeSwitchInSession: false,
99 },
100 threads: {
101 ...AcpProviderCapabilitiesV2.threads,
102 canReadThreadSnapshot: true,
103 canForkThread: false,
104 canForkFromTurn: false,
105 },
106 subagents: {
107 ...AcpProviderCapabilitiesV2.subagents,
108 supportsSubagents: true,
109 exposesSubagentThreadIds: true,
110 emitsSubagentLifecycle: true,
111 },
112 tools: {
113 ...AcpProviderCapabilitiesV2.tools,
114 supportsMcpTools: true,
115 },
116 checkpointing: {
117 ...AcpProviderCapabilitiesV2.checkpointing,
118 providerCanReadConversationSnapshot: true,
119 },
120 // Cancelling a Grok prompt kills its running foreground tool.
121 turns: { ...AcpProviderCapabilitiesV2.turns, supportsSteeringByInterruptRestart: false },
122} satisfies OrchestrationV2ProviderCapabilities;
123​
124export interface GrokAdapterV2Options {
125 readonly instanceId: Parameters<typeof makeAcpAdapterV2>[0]["instanceId"];
126 readonly settings: GrokSettings;
127 readonly environment: NodeJS.ProcessEnv;
128 readonly hostPlatform: NodeJS.Platform;
129 readonly selfInvocation: SelfInvocation;
130 readonly nativeLogging?: Parameters<typeof makeAcpAdapterV2>[0]["nativeLogging"];
131 readonly continuationRequests?: Parameters<typeof makeAcpAdapterV2>[0]["continuationRequests"];
132 readonly testHooks?: Parameters<typeof makeAcpAdapterV2>[0]["testHooks"];
133 readonly makeRuntime?: (
134 input: AcpAdapterV2RuntimeInput,
135 ) => Effect.Effect<
136 AcpSessionRuntime.AcpSessionRuntime["Service"],
137 EffectAcpErrors.AcpError,
138 ChildProcessSpawner.ChildProcessSpawner | SecureRandom.SecureRandom | Scope.Scope
139 >;
140 readonly assertComplete?: Effect.Effect<void, EffectAcpErrors.AcpError>;
142​
143const registerGrokAcpExtensions: NonNullable<AcpAdapterV2Flavor["registerExtensions"]> = ({
144 runtime,
145 requestUserInput,
146 applyBackgroundTaskMutation,
147 finishSubagent,
148 captureProposedPlan,
149 lastProposedPlanMarkdown,
150}) =>
151 registerXAiBackgroundTaskTracking(runtime, applyBackgroundTaskMutation).pipe(
152 Effect.andThen(registerXAiSubagentFinished(runtime, finishSubagent)),
153 Effect.andThen(registerGrokAskUserQuestionExtensions({ runtime, requestUserInput })),
154 Effect.andThen(
155 registerGrokExitPlanModeExtensions({
156 runtime,
157 captureProposedPlan,
158 lastProposedPlanMarkdown,
159 }),
160 ),
161 );
162​
163// Capture the reverse-requested plan, then abandon the native gate to finish the turn.
164const registerGrokExitPlanModeExtensions = ({
165 runtime,
166 captureProposedPlan,
167 lastProposedPlanMarkdown,
168}: Pick<
169 AcpAdapterV2ExtensionContext,
170 "runtime" | "captureProposedPlan" | "lastProposedPlanMarkdown"
171>) =>
172 Effect.forEach(
173 ["x.ai/exit_plan_mode", "_x.ai/exit_plan_mode"] as const,
174 (method) =>
175 runtime.handleExtRequest(method, XAiExitPlanModeRequest, (params) =>
176 Effect.gen(function* () {
177 const fallback = yield* lastProposedPlanMarkdown;
178 yield* captureProposedPlan({
179 planMarkdown: extractXAiExitPlanMarkdown(params, fallback),
180 });
181 return makeXAiExitPlanModeCapturedResponse();
182 }),
183 ),
184 { discard: true },
185 );
186​
187const registerGrokAskUserQuestionExtensions = ({
188 runtime,
189 requestUserInput,
190}: Pick<AcpAdapterV2ExtensionContext, "runtime" | "requestUserInput">) =>
191 Effect.forEach(
192 ["x.ai/ask_user_question", "_x.ai/ask_user_question"] as const,
193 (method) =>
194 runtime.handleExtRequest(method, XAiAskUserQuestionRequest, (params, requestContext) => {
195 const identity = extractXAiAskUserQuestionIdentity(params);
196 const questions = extractXAiAskUserQuestions(params).map((question) => ({
197 ...question,
198 options: [...question.options],
199 }));
200 return requestUserInput(
201 {
202 nativeItemId: `${identity.sessionId}:xai-question:${identity.toolCallId}`,
203 nativeRequestId: identity.toolCallId,
204 questions,
205 },
206 requestContext,
207 ).pipe(
208 Effect.flatMap(({ acknowledgeNativeResponse, answers }) =>
209 Effect.succeed(
210 answers === null
211 ? makeXAiAskUserQuestionCancelledResponse()
212 : makeXAiAskUserQuestionResponse(params, answers),
213 ).pipe(Effect.tap(() => acknowledgeNativeResponse)),
214 ),
215 );
216 }),
217 { discard: true },
218 );
219​
220/** Explicit policy overrides launch in ask mode so Grok cannot bypass T3 approval checks. */
221export function grokLaunchRuntimeMode(
222 runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy,
223): RuntimeMode {
224 return runtimePolicy.approvalPolicy === undefined && runtimePolicy.sandboxPolicy === undefined
225 ? runtimePolicy.runtimeMode
226 : "approval-required";
228​
229/** The capability id the composer stores Grok's reasoning effort under. */
230const GROK_REASONING_EFFORT_OPTION_ID = "reasoningEffort";
231​
232// Protocol 1 sends the effort as `session/set_model` metadata on every call: that response
233// carries no config options, so there is no live effort to compare against. Newer protocols
234// write the `thought_level` config option after the model switch. An effort the model does
235// not offer, or that Grok refuses, is skipped with a warning and Grok's default applies.
236const applyGrokSessionModelSelection: NonNullable<AcpAdapterV2Flavor["applyModelSelection"]> =
237 Effect.fn("GrokAdapter.applyModelSelection")(function* ({
238 runtime,
239 startResult,
240 modelSelection,
241 }) {
242 const requestedModelId = resolveGrokAcpBaseModelId(modelSelection.model);
243 const requestedEffort = getModelSelectionStringOptionValue(
244 modelSelection,
245 GROK_REASONING_EFFORT_OPTION_ID,
246 );
247 const skipEffort = (detail: string) =>
248 Effect.logWarning("Grok session skipped the requested reasoning effort", {
249 sessionId: startResult.sessionId,
250 reasoningEffort: requestedEffort,
251 detail,
252 });
253​
254 if (startResult.initializeResult.protocolVersion === 1) {
255 const setup = startResult.sessionSetupResult;
256 const currentModelId = currentGrokModelIdFromSessionSetup(setup);
257 const targetModelId =
258 requestedModelId === GROK_DEFAULT_MODEL_SLUG ? currentModelId : requestedModelId;
259 const targetModel = setup.models?.availableModels.find(
260 (model) => model.modelId.trim() === targetModelId,
261 );
262 const offeredEfforts =
263 targetModel === undefined
264 ? []
265 : grokReasoningOptionsFromModel(targetModel).options.map((option) => option.value);
266 const effort =
267 requestedEffort !== undefined &&
268 (offeredEfforts.length === 0 || offeredEfforts.includes(requestedEffort))
269 ? requestedEffort
270 : undefined;
271 if (requestedEffort !== undefined && effort === undefined) {
272 yield* skipEffort(`${targetModelId} does not offer it`);
273 }
274 const apply = (requestedReasoningEffort: string | undefined) =>
275 applyGrokAcpModelSelection({
276 runtime,
277 currentModelId,
278 requestedModelId,
279 requestedReasoningEffort,
280 mapError: (cause) => cause,
281 });
282 return yield* effort === undefined
283 ? apply(undefined)
284 : apply(effort).pipe(
285 Effect.catchTags({
286 AcpRequestError: (error) =>
287 skipEffort(error.message).pipe(Effect.andThen(apply(undefined))),
288 }),
289 );
290 }
291​
292 const appliedModelId = yield* applyGrokAcpModelSelection({
293 runtime: { setSessionModel: (model) => runtime.setModel(model).pipe(Effect.as({})) },
294 currentModelId: findModelConfigOption(yield* runtime.getConfigOptions)?.currentValue,
295 requestedModelId,
296 mapError: (cause) => cause,
297 });
298 if (requestedEffort === undefined) {
299 return appliedModelId;
300 }
301 // Read after the model switch: the effort choices belong to the new model.
302 const effortOption = (yield* runtime.getConfigOptions).find(
303 (option) => option.type === "select" && option.category === "thought_level",
304 );
305 if (effortOption === undefined) {
306 yield* skipEffort("the session has no reasoning effort option");
307 return appliedModelId;
308 }
309 // setConfigOption rejects a value the option does not offer and skips the current one.
310 yield* runtime
311 .setConfigOption(effortOption.id, requestedEffort)
312 .pipe(Effect.catchTags({ AcpRequestError: (error) => skipEffort(error.message) }));
313 return appliedModelId;
314 });
315​
316export function makeGrokAcpAdapterFlavor(
317 options: GrokAdapterV2Options,
318 homeDirectory: string,
319): AcpAdapterV2Flavor {
320 return {
321 driver: GROK_PROVIDER,
322 runtimeHarness: "Grok",
323 capabilities: GrokProviderCapabilitiesV2,
324 interruptPromptOnCancel: false,
325 // User Stop restarts the process group; steering cancels softly to preserve background work.
326 restartRuntimeAfterInterrupt: true,
327 terminateRuntimeProcessGroupOnInterrupt: true,
328 // Settled Grok sessions accept concurrent prompts; skip cancel to preserve background subagents.
329 preserveRuntimeOnSettledInterrupt: true,
330 // Grok accepts image blocks despite advertising promptCapabilities.image:false.
331 supportsImagePrompts: true,
332 supportsCompaction: true,
333 // Grok expands only a leading `/name`, while the `$` picker inserts `$name` from the
334 // `grok inspect` catalog. Ask that catalog again so other `$` text is left alone.
335 rewriteUserText: (text, turnInput) => {
336 const mention = leadingGrokSkillMention(text);
337 if (mention === undefined) return Effect.succeed(text);
338 return discoverGrokSkills(
339 options.settings,
340 options.environment,
341 turnInput.runtimePolicy.cwd ?? undefined,
342 ).pipe(
343 Effect.map((skills) =>
344 skills.some((skill) => skill.enabled && skill.name === mention.name)
345 ? `/${mention.name}${mention.rest}`
346 : text,
347 ),
348 Effect.orElseSucceed(() => text),
349 );
350 },
351 resolveModelId: (selection) => resolveGrokAcpBaseModelId(selection.model),
352 getModelContextWindow: (selection, session) => {
353 if (selection.instanceId !== options.instanceId) return undefined;
354 const modelId = resolveGrokAcpBaseModelId(selection.model);
355 const models =
356 session.sessionSetupResult.models ??
357 sessionModelStateFromInitialize(session.initializeResult);
358 const window = models?.availableModels.find((model) => model.modelId === modelId)?._meta
359 ?.totalContextTokens;
360 // contextWindows includes selectable larger windows; totalContextTokens is the default.
361 return typeof window === "number" && Number.isSafeInteger(window) && window > 0
362 ? window
363 : undefined;
364 },
365 applyModelSelection: applyGrokSessionModelSelection,
366 ownedModelOptionIds: [GROK_REASONING_EFFORT_OPTION_ID],
367 makeRuntime:
368 options.makeRuntime ??
369 (({ runtimePolicy, ...input }) =>
370 makeGrokAcpRuntime({
371 ...input,
372 interruptPromptOnCancel: input.interruptPromptOnCancel ?? false,
373 grokSettings: options.settings,
374 environment: options.environment,
375 runtimeMode: grokLaunchRuntimeMode(runtimePolicy),
376 })),
377 // Auto prompts represent classifier refusals and must reach the user.
378 permissionDisposition: (policy, request) =>
379 grokLaunchRuntimeMode(policy) === "auto" ? "ask" : acpPermissionDisposition(policy, request),
380 approvalOptions: grokApprovalOptions,
381 promptFailure: (cause) =>
382 makeProviderFailure({
383 cause,
384 ...(isAcpRequestError(cause)
385 ? {
386 message: isXAiPromptFailureText(cause.cause)
387 ? cause.cause.message
388 : cause.errorMessage,
389 code: String(cause.code),
390 class: cause.code === xAiRateLimitedErrorCode ? "usage_limit" : "provider_error",
391 }
392 : { class: "provider_error" }),
393 }),
394 registerExtensions: registerGrokAcpExtensions,
395 extractSubagentUpdate: extractXAiAcpSubagentUpdate,
396 extractSubagentEndNotice: extractXAiAcpSubagentEndNotice,
397 normalizeToolCall: normalizeXAiAcpToolCallState,
398 extractProposedPlanMarkdown: (toolCall) =>
399 extractGrokPlanMarkdownFromToolCallData(toolCall.data, {
400 platform: options.hostPlatform,
401 environment: options.environment,
402 homeDirectory,
403 }),
404 extractBackgroundTaskId: extractXAiMonitorTaskId,
405 isBackgroundCommandTool: (toolCall) => xAiBackgroundShellTaskId(toolCall) !== undefined,
406 extractBackgroundToolMutation: extractXAiAcpBackgroundToolMutation,
407 extractBackgroundTaskCompletion: (toolCall) => [
408 ...extractXAiBackgroundTaskCompletion(toolCall),
409 ...extractXAiKilledBackgroundTasks(toolCall),
410 ],
411 isPersistentBackgroundTool: isXAiPersistentMonitor,
412 isProviderWakeNotification: isXAiTaskCompletedWakeNotification,
413 deferFinalizeForBackgroundWork: true,
414 enablePostSettleContinuation: true,
415 ...(options.assertComplete === undefined ? {} : { assertComplete: options.assertComplete }),
416 };
418​
419export const makeGrokAdapterV2 = Effect.fn("makeGrokAdapterV2")(function* (
420 options: GrokAdapterV2Options,
421) {
422 return yield* makeAcpAdapterV2({
423 instanceId: options.instanceId,
424 flavor: makeGrokAcpAdapterFlavor(options, yield* HostProcess.HomeDirectory),
425 selfInvocation: options.selfInvocation,
426 ...(options.nativeLogging === undefined ? {} : { nativeLogging: options.nativeLogging }),
427 ...(options.continuationRequests === undefined
428 ? {}
429 : { continuationRequests: options.continuationRequests }),
430 ...(options.testHooks === undefined ? {} : { testHooks: options.testHooks }),
431 });
432});
433​
434export type GrokAdapterV2DriverEnv =
435 | ChildProcessSpawner.ChildProcessSpawner
436 | SecureRandom.SecureRandom
437 | FileSystem.FileSystem
438 | IdAllocator.IdAllocatorV2
439 | Path.Path
440 | McpProviderSessions.McpProviderSessions
441 | ProviderEventLoggers.ProviderEventLoggers
442 | ProviderHost.ProviderHost;
443​
444export const GrokAdapterV2Driver: ProviderAdapterDriver<GrokSettings, GrokAdapterV2DriverEnv> = {
445 driverKind: GROK_DRIVER_KIND,
446 configSchema: GrokSettings,
447 defaultConfig: (): GrokSettings => DEFAULT_GROK_SETTINGS,
448 create: Effect.fn("GrokAdapterV2Driver.create")(
449 function* (input: ProviderAdapterDriverCreateInput<GrokSettings>) {
450 const hostEnvironment = yield* HostProcess.Environment;
451 const hostPlatform = yield* HostProcess.Platform;
452 const selfInvocation = yield* resolveSelfInvocation();
453 const providerEventLoggers = yield* ProviderEventLoggers.ProviderEventLoggers;
454 const continuationRequests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
455 const makeNativeLogger = yield* makeAcpNativeLoggerFactory();
456 return yield* makeGrokAdapterV2({
457 instanceId: input.instanceId,
458 settings: { ...input.config, enabled: input.enabled },
459 environment: yield* mergeProviderInstanceEnvironment(input.environment, hostEnvironment),
460 hostPlatform,
461 selfInvocation,
462 continuationRequests,
463 nativeLogging: (threadId) =>
464 makeNativeLogger({
465 nativeEventLogger: providerEventLoggers.native,
466 provider: GROK_PROVIDER,
467 threadId,
468 }),
469 });
470 },
471 (effect, input) =>
472 effect.pipe(
473 Effect.mapError(
474 (cause) =>
475 new ProviderAdapterDriverCreateError({
476 driver: GROK_DRIVER_KIND,
477 instanceId: input.instanceId,
478 detail: "Failed to create Grok ACP adapter.",
479 cause,
480 }),
481 ),
482 ),
483 ),
484};