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

adapter.ts

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