Skip to content
TypeScript

fix(grok): health check, model selection, and stop all work against the real CLI (#9154)

Theo Brownea434677eca73
diff --git a/apps/server/scripts/acp-mock-agent.ts b/apps/server/scripts/acp-mock-agent.ts
index e51a8883f4f..294c143bc3b 100644
--- a/apps/server/scripts/acp-mock-agent.ts
+++ b/apps/server/scripts/acp-mock-agent.ts
@@ -293,13 +293,22 @@ function modeState(): AcpSchema.SessionModeState {
};
}
+// Mirrors the real Grok ACP: it advertises versioned model ids, never the CLI's own
+// "grok-build" product name, and it rejects unknown ids in session/set_model.
const grokAcpModels: ReadonlyArray<AcpSchema.ModelInfo> = [
{
- modelId: "grok-build",
- name: "Grok Build",
- ...(initialGrokReasoningEffort
- ? { _meta: { reasoningEffort: initialGrokReasoningEffort } }
- : {}),
+ modelId: "grok-4.6",
+ name: "Grok 4.6",
+ _meta: {
+ totalContextTokens: 500_000,
+ supportsReasoningEffort: true,
+ reasoningEffort: initialGrokReasoningEffort ?? "high",
+ reasoningEfforts: [
+ { id: "xhigh", value: "xhigh", label: "Extra High Effort", default: false },
+ { id: "high", value: "high", label: "High Effort", default: true },
+ { id: "low", value: "low", label: "Low Effort", default: false },
+ ],
+ },
},
{ modelId: "grok-mock-alt", name: "Grok Mock Alt" },
];
@@ -307,7 +316,7 @@ const grokAcpModels: ReadonlyArray<AcpSchema.ModelInfo> = [
function modelState(): AcpSchema.SessionModelState {
const modelId = grokAcpModels.some((model) => model.modelId === currentModelId)
? currentModelId
- : "grok-build";
+ : "grok-4.6";
return {
currentModelId: modelId,
availableModels: grokAcpModels,
@@ -324,6 +333,9 @@ const program = Effect.gen(function* () {
return {
protocolVersion: 1,
agentCapabilities: { loadSession: true },
+ // Grok advertises model state before any session exists; the provider
+ // health check reads it from here without authenticating.
+ _meta: { modelState: modelState() },
};
}),
);
diff --git a/apps/server/src/provider/Layers/GrokAdapter.test.ts b/apps/server/src/provider/Layers/GrokAdapter.test.ts
index eeee17d9ac6..e2649006b8f 100644
--- a/apps/server/src/provider/Layers/GrokAdapter.test.ts
+++ b/apps/server/src/provider/Layers/GrokAdapter.test.ts
@@ -720,13 +720,13 @@ it.layer(grokAdapterTestLayer)("GrokAdapterLive", (it) => {
0,
);
- yield* Fiber.interrupt(steerSendTurnFiber);
yield* adapter.interruptTurn(threadId);
const completed = yield* Deferred.await(turnCompleted).pipe(
Effect.timeout("2 seconds"),
TestClock.withLive,
);
yield* Fiber.join(firstSendTurnFiber);
+ yield* Fiber.interrupt(steerSendTurnFiber);
assert.equal(completed.payload.state, "cancelled");
yield* Fiber.interrupt(runtimeEventsFiber);
@@ -1122,6 +1122,316 @@ it.layer(grokAdapterTestLayer)("GrokAdapterLive", (it) => {
}).pipe(TestClock.withLive),
);
+ it.effect("cancels an in-flight prompt when a mid-turn sendTurn steers", () =>
+ Effect.gen(function* () {
+ const threadId = ThreadId.make("grok-steer-cancels-in-flight");
+ const tempDir = yield* Effect.promise(() =>
+ NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "grok-acp-steer-")),
+ );
+ const requestLogPath = NodePath.join(tempDir, "requests.ndjson");
+ const wrapperPath = yield* Effect.promise(() =>
+ makeMockGrokWrapper({
+ T3_ACP_HANG_FIRST_PROMPT_FOREVER: "1",
+ T3_ACP_REQUEST_LOG_PATH: requestLogPath,
+ }),
+ );
+ const adapter = yield* makeTestAdapter(wrapperPath);
+
+ const runtimeEvents: ProviderRuntimeEvent[] = [];
+ const firstTurnStarted = yield* Deferred.make<TurnId>();
+ const turnCompleted = yield* Deferred.make<void>();
+ const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
+ Effect.gen(function* () {
+ runtimeEvents.push(event);
+ if (String(event.threadId) !== String(threadId)) {
+ return;
+ }
+ if (event.type === "turn.started" && event.turnId !== undefined) {
+ yield* Deferred.succeed(firstTurnStarted, event.turnId).pipe(Effect.ignore);
+ return;
+ }
+ if (event.type === "turn.completed") {
+ yield* Deferred.succeed(turnCompleted, undefined).pipe(Effect.ignore);
+ }
+ }),
+ ).pipe(Effect.forkChild);
+
+ yield* adapter.startSession({
+ threadId,
+ provider: ProviderDriverKind.make("grok"),
+ cwd: process.cwd(),
+ runtimeMode: "full-access",
+ });
+
+ const firstSendTurnFiber = yield* adapter
+ .sendTurn({ threadId, input: "hang until steered", attachments: [] })
+ .pipe(Effect.forkChild);
+ const firstTurnId = yield* Deferred.await(firstTurnStarted).pipe(Effect.timeout("2 seconds"));
+ yield* waitForFileContent(requestLogPath, 80, '"method":"session/prompt"');
+
+ const steered = yield* adapter
+ .sendTurn({ threadId, input: "take this instead", attachments: [] })
+ .pipe(Effect.timeout("3 seconds"));
+ yield* Fiber.join(firstSendTurnFiber).pipe(Effect.timeout("3 seconds"));
+ yield* Deferred.await(turnCompleted).pipe(Effect.timeout("3 seconds"));
+
+ const requestLog = yield* Effect.promise(() => readJsonLines(requestLogPath));
+ const methods = requestLog.flatMap((entry) =>
+ typeof entry.method === "string" ? [entry.method] : [],
+ );
+ const turnStartedEvents = runtimeEvents.filter(
+ (event) => event.type === "turn.started" && String(event.threadId) === String(threadId),
+ );
+ const turnCompletedEvents = runtimeEvents.filter(
+ (event): event is Extract<ProviderRuntimeEvent, { type: "turn.completed" }> =>
+ event.type === "turn.completed" && String(event.threadId) === String(threadId),
+ );
+ const readySessions = yield* adapter.listSessions();
+ const readySession = readySessions.find((session) => session.threadId === threadId);
+
+ assert.equal(String(steered.turnId), String(firstTurnId));
+ assert.isTrue(methods.includes("session/cancel"));
+ assert.isAtLeast(methods.filter((method) => method === "session/prompt").length, 2);
+ assert.lengthOf(turnStartedEvents, 1);
+ assert.lengthOf(turnCompletedEvents, 1);
+ assert.equal(turnCompletedEvents[0]?.payload.state, "completed");
+ assert.equal(readySession?.status, "ready");
+ assert.isUndefined(readySession?.activeTurnId);
+
+ yield* Fiber.interrupt(runtimeEventsFiber);
+ yield* adapter.stopSession(threadId);
+ }).pipe(TestClock.withLive),
+ );
+
+ it.effect(
+ "steers a prompt that has not started ACP yet instead of letting it start after cancel",
+ () =>
+ Effect.gen(function* () {
+ const threadId = ThreadId.make("grok-steer-during-prep");
+ const tempDir = yield* Effect.promise(() =>
+ NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "grok-acp-steer-prep-")),
+ );
+ const requestLogPath = NodePath.join(tempDir, "requests.ndjson");
+ const wrapperPath = yield* Effect.promise(() =>
+ makeMockGrokWrapper({
+ T3_ACP_HANG_FIRST_PROMPT_FOREVER: "1",
+ T3_ACP_REQUEST_LOG_PATH: requestLogPath,
+ }),
+ );
+ const adapter = yield* makeTestAdapter(wrapperPath);
+
+ const runtimeEvents: ProviderRuntimeEvent[] = [];
+ const firstTurnStarted = yield* Deferred.make<TurnId>();
+ const turnCompleted = yield* Deferred.make<void>();
+ const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
+ Effect.gen(function* () {
+ runtimeEvents.push(event);
+ if (String(event.threadId) !== String(threadId)) {
+ return;
+ }
+ if (event.type === "turn.started" && event.turnId !== undefined) {
+ yield* Deferred.succeed(firstTurnStarted, event.turnId).pipe(Effect.ignore);
+ return;
+ }
+ if (event.type === "turn.completed") {
+ yield* Deferred.succeed(turnCompleted, undefined).pipe(Effect.ignore);
+ }
+ }),
+ ).pipe(Effect.forkChild);
+
+ yield* adapter.startSession({
+ threadId,
+ provider: ProviderDriverKind.make("grok"),
+ cwd: process.cwd(),
+ runtimeMode: "full-access",
+ });
+
+ const firstSendTurnFiber = yield* adapter
+ .sendTurn({ threadId, input: "still preparing", attachments: [] })
+ .pipe(Effect.forkChild);
+ const firstTurnId = yield* Deferred.await(firstTurnStarted).pipe(
+ Effect.timeout("2 seconds"),
+ );
+
+ const steered = yield* adapter
+ .sendTurn({ threadId, input: "steer before first prompt starts", attachments: [] })
+ .pipe(Effect.timeout("3 seconds"));
+ yield* Fiber.join(firstSendTurnFiber).pipe(Effect.timeout("3 seconds"));
+ yield* Deferred.await(turnCompleted).pipe(Effect.timeout("3 seconds"));
+
+ const turnCompletedEvents = runtimeEvents.filter(
+ (event): event is Extract<ProviderRuntimeEvent, { type: "turn.completed" }> =>
+ event.type === "turn.completed" && String(event.threadId) === String(threadId),
+ );
+ const readySessions = yield* adapter.listSessions();
+ const readySession = readySessions.find((session) => session.threadId === threadId);
+
+ assert.equal(String(steered.turnId), String(firstTurnId));
+ assert.lengthOf(turnCompletedEvents, 1);
+ assert.equal(turnCompletedEvents[0]?.payload.state, "completed");
+ assert.equal(readySession?.status, "ready");
+ assert.isUndefined(readySession?.activeTurnId);
+
+ yield* Fiber.interrupt(runtimeEventsFiber);
+ yield* adapter.stopSession(threadId);
+ }).pipe(TestClock.withLive),
+ );
+
+ it.effect("keeps the original prompt running when a steer fails during preparation", () =>
+ Effect.gen(function* () {
+ const threadId = ThreadId.make("grok-failed-steer-keeps-original-prompt");
+ const tempDir = yield* Effect.promise(() =>
+ NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "grok-acp-failed-steer-")),
+ );
+ const requestLogPath = NodePath.join(tempDir, "requests.ndjson");
+ const wrapperPath = yield* Effect.promise(() =>
+ makeMockGrokWrapper({
+ T3_ACP_HANG_FIRST_PROMPT_FOREVER: "1",
+ T3_ACP_REQUEST_LOG_PATH: requestLogPath,
+ }),
+ );
+ const adapter = yield* makeTestAdapter(wrapperPath);
+
+ const runtimeEvents: ProviderRuntimeEvent[] = [];
+ const firstTurnStarted = yield* Deferred.make<TurnId>();
+ const turnCompleted = yield* Deferred.make<void>();
+ const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
+ Effect.gen(function* () {
+ runtimeEvents.push(event);
+ if (String(event.threadId) !== String(threadId)) {
+ return;
+ }
+ if (event.type === "turn.started" && event.turnId !== undefined) {
+ yield* Deferred.succeed(firstTurnStarted, event.turnId).pipe(Effect.ignore);
+ return;
+ }
+ if (event.type === "turn.completed") {
+ yield* Deferred.succeed(turnCompleted, undefined).pipe(Effect.ignore);
+ }
+ }),
+ ).pipe(Effect.forkChild);
+
+ yield* adapter.startSession({
+ threadId,
+ provider: ProviderDriverKind.make("grok"),
+ cwd: process.cwd(),
+ runtimeMode: "full-access",
+ });
+
+ const firstSendTurnFiber = yield* adapter
+ .sendTurn({ threadId, input: "hang until a failed steer", attachments: [] })
+ .pipe(Effect.forkChild);
+ const firstTurnId = yield* Deferred.await(firstTurnStarted).pipe(Effect.timeout("2 seconds"));
+
+ const steerError = yield* Effect.flip(
+ adapter.sendTurn({
+ threadId,
+ input: " ",
+ attachments: [],
+ }),
+ );
+ yield* waitForFileContent(requestLogPath, 80, '"method":"session/prompt"');
+ for (let yieldAttempt = 0; yieldAttempt < 8; yieldAttempt += 1) {
+ yield* Effect.yieldNow;
+ }
+
+ const sessionsAfterFailedSteer = yield* adapter.listSessions();
+ const sessionAfterFailedSteer = sessionsAfterFailedSteer.find(
+ (session) => session.threadId === threadId,
+ );
+ const completedBeforeInterrupt = runtimeEvents.filter(
+ (event): event is Extract<ProviderRuntimeEvent, { type: "turn.completed" }> =>
+ event.type === "turn.completed" && String(event.threadId) === String(threadId),
+ );
+
+ yield* adapter.interruptTurn(threadId, firstTurnId).pipe(Effect.timeout("2 seconds"));
+ yield* Fiber.join(firstSendTurnFiber).pipe(Effect.timeout("3 seconds"));
+ yield* Deferred.await(turnCompleted).pipe(Effect.timeout("3 seconds"));
+
+ const turnCompletedEvents = runtimeEvents.filter(
+ (event): event is Extract<ProviderRuntimeEvent, { type: "turn.completed" }> =>
+ event.type === "turn.completed" && String(event.threadId) === String(threadId),
+ );
+ const readySessions = yield* adapter.listSessions();
+ const readySession = readySessions.find((session) => session.threadId === threadId);
+
+ assert.equal(steerError._tag, "ProviderAdapterValidationError");
+ assert.equal(sessionAfterFailedSteer?.status, "running");
+ assert.equal(String(sessionAfterFailedSteer?.activeTurnId), String(firstTurnId));
+ assert.lengthOf(completedBeforeInterrupt, 0);
+ assert.lengthOf(turnCompletedEvents, 1);
+ assert.equal(String(turnCompletedEvents[0]?.turnId), String(firstTurnId));
+ assert.equal(turnCompletedEvents[0]?.payload.state, "cancelled");
+ assert.equal(readySession?.status, "ready");
+ assert.isUndefined(readySession?.activeTurnId);
+
+ yield* Fiber.interrupt(runtimeEventsFiber);
+ yield* adapter.stopSession(threadId);
+ }).pipe(TestClock.withLive),
+ );
+
+ it.effect("does not double-complete when interrupt wins before a prompt starts ACP", () =>
+ Effect.gen(function* () {
+ const threadId = ThreadId.make("grok-interrupt-before-prompt-start");
+ const wrapperPath = yield* Effect.promise(() =>
+ makeMockGrokWrapper({
+ T3_ACP_HANG_FIRST_PROMPT_FOREVER: "1",
+ }),
+ );
+ const adapter = yield* makeTestAdapter(wrapperPath);
+
+ const runtimeEvents: ProviderRuntimeEvent[] = [];
+ const firstTurnStarted = yield* Deferred.make<TurnId>();
+ const turnCompleted = yield* Deferred.make<void>();
+ const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
+ Effect.gen(function* () {
+ runtimeEvents.push(event);
+ if (String(event.threadId) !== String(threadId)) {
+ return;
+ }
+ if (event.type === "turn.started" && event.turnId !== undefined) {
+ yield* Deferred.succeed(firstTurnStarted, event.turnId).pipe(Effect.ignore);
+ return;
+ }
+ if (event.type === "turn.completed") {
+ yield* Deferred.succeed(turnCompleted, undefined).pipe(Effect.ignore);
+ }
+ }),
+ ).pipe(Effect.forkChild);
+
+ yield* adapter.startSession({
+ threadId,
+ provider: ProviderDriverKind.make("grok"),
+ cwd: process.cwd(),
+ runtimeMode: "full-access",
+ });
+
+ const firstSendTurnFiber = yield* adapter
+ .sendTurn({ threadId, input: "interrupt before prompt starts", attachments: [] })
+ .pipe(Effect.forkChild);
+ const firstTurnId = yield* Deferred.await(firstTurnStarted).pipe(Effect.timeout("2 seconds"));
+ yield* adapter.interruptTurn(threadId, firstTurnId).pipe(Effect.timeout("2 seconds"));
+ yield* Fiber.join(firstSendTurnFiber).pipe(Effect.timeout("3 seconds"));
+ yield* Deferred.await(turnCompleted).pipe(Effect.timeout("3 seconds"));
+
+ const turnCompletedEvents = runtimeEvents.filter(
+ (event): event is Extract<ProviderRuntimeEvent, { type: "turn.completed" }> =>
+ event.type === "turn.completed" && String(event.threadId) === String(threadId),
+ );
+ const readySessions = yield* adapter.listSessions();
+ const readySession = readySessions.find((session) => session.threadId === threadId);
+
+ assert.lengthOf(turnCompletedEvents, 1);
+ assert.equal(String(turnCompletedEvents[0]?.turnId), String(firstTurnId));
+ assert.equal(turnCompletedEvents[0]?.payload.state, "cancelled");
+ assert.equal(readySession?.status, "ready");
+ assert.isUndefined(readySession?.activeTurnId);
+
+ yield* Fiber.interrupt(runtimeEventsFiber);
+ yield* adapter.stopSession(threadId);
+ }).pipe(TestClock.withLive),
+ );
+
it.effect("drops late ACP notifications after a turn is cancelled", () =>
Effect.gen(function* () {
const threadId = ThreadId.make("grok-drop-late-cancelled-notifications");
@@ -1429,7 +1739,8 @@ it.layer(grokAdapterTestLayer)("GrokAdapterLive", (it) => {
assert.equal(error._tag, "ProviderAdapterRequestError");
assert.include(error.message, "Grok usage limit reached. Try again later.");
assert.equal(readySession?.status, "ready");
- assert.equal(readySession?.model, "grok-build");
+ // "grok-build" resolves to the session's current model instead of going over the wire.
+ assert.equal(readySession?.model, "grok-4.6");
assert.isUndefined(readySession?.activeTurnId);
assert.lengthOf(terminalEvents, 1);
const [terminalEvent] = terminalEvents;
diff --git a/apps/server/src/provider/Layers/GrokAdapter.ts b/apps/server/src/provider/Layers/GrokAdapter.ts
index 4bec298c628..da9bdf6030f 100644
--- a/apps/server/src/provider/Layers/GrokAdapter.ts
+++ b/apps/server/src/provider/Layers/GrokAdapter.ts
@@ -151,8 +151,15 @@ interface GrokSessionContext {
interruptedTurnIds: Set<TurnId>;
/** Number of sendTurn prompts currently in flight or being prepared.
* >0 means a turn is actively running, so a new sendTurn is a steer that
- * continues it, and only the last remaining prompt settles the turn. */
+ * cancels the in-flight prompt and continues the same turn. Only the last
+ * remaining prompt settles the turn. */
promptsInFlight: number;
+ /** Monotonic id assigned to each sendTurn. Steers discard older epochs. */
+ promptEpoch: number;
+ /** Prompt epochs below this value must not start an ACP session/prompt. */
+ discardBeforeEpoch: number;
+ /** Serializes cancel-then-prompt so a steer cannot miss or hit the wrong RPC. */
+ readonly promptLifecycle: Semaphore.Semaphore;
readonly livenessSignals: Queue.Queue<GrokTurnLivenessSignal>;
livenessTurnId: TurnId | undefined;
lastTurnActivityAtNanos: bigint | undefined;
@@ -1279,6 +1286,9 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
activeTurnId: undefined,
interruptedTurnIds: new Set(),
promptsInFlight: 0,
+ promptEpoch: 0,
+ discardBeforeEpoch: 0,
+ promptLifecycle: yield* Semaphore.make(1),
livenessSignals: yield* Queue.sliding<GrokTurnLivenessSignal>(1),
livenessTurnId: undefined,
lastTurnActivityAtNanos: undefined,
@@ -1466,15 +1476,18 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
input.threadId,
Effect.gen(function* () {
const ctx = yield* requireSession(input.threadId);
- // A sendTurn while a prompt is in flight is a steer: the agent
- // folds the new prompt into the ongoing work, so the active turn
- // id is reused instead of opening a new turn.
+ // A sendTurn while a prompt is in flight is a steer: reuse the
+ // active turn and cancel the in-flight ACP prompt so Grok takes
+ // the new instruction immediately, matching Claude/Codex, instead
+ // of waiting behind serialized session/prompt.
const steeringTurnId = ctx.promptsInFlight > 0 ? ctx.activeTurnId : undefined;
const turnId = steeringTurnId ?? TurnId.make(yield* randomUUIDv4);
// Count this prompt immediately so a superseded in-flight prompt
// resolving from here on does not settle the turn; decremented on
// preparation failure here, and after the prompt below otherwise.
ctx.promptsInFlight += 1;
+ ctx.promptEpoch += 1;
+ const promptEpoch = ctx.promptEpoch;
// Bind the turn id before cooperative yields so interruptTurn can
// settle this prompt even if stop arrives during preparation.
ctx.activeTurnId = turnId;
@@ -1610,6 +1623,14 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
turnId,
payload: displayModel ? { model: displayModel } : {},
});
+ } else {
+ // Discard the previous epoch only after this replacement is
+ // ready. A failed steer must not skip the live prompt, which
+ // settles without a terminal event when emitTurnCompletion is
+ // false.
+ yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals);
+ yield* settlePendingUserInputsAsCancelled(ctx.pendingUserInputs);
+ ctx.discardBeforeEpoch = promptEpoch;
}
return {
@@ -1618,6 +1639,9 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
displayModel,
promptParts,
turnId,
+ promptEpoch,
+ promptLifecycle: ctx.promptLifecycle,
+ steeringTurnId,
};
}).pipe(
Effect.tapCause(() =>
@@ -1644,31 +1668,91 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
const promptFailureMessageRef = yield* Ref.make<string | undefined>(undefined);
return yield* Effect.gen(function* () {
- const result = yield* prepared.acp
- .prompt({
- prompt: prepared.promptParts,
- })
- .pipe(
- Effect.tap((promptResult) =>
- Effect.all(
- [
- Ref.set(promptRpcSucceeded, true),
- Ref.set(promptResultRef, promptResult),
- markPromptResponseReady(input.threadId, prepared.acpSessionId, prepared.turnId),
- ],
- { discard: true },
- ),
- ),
- Effect.tapError((error) =>
- Ref.set(
- promptFailureMessageRef,
- mapAcpToAdapterError(PROVIDER, input.threadId, "session/prompt", error).message,
- ).pipe(Effect.andThen(prepared.acp.drainEvents)),
- ),
- Effect.mapError((error) =>
- mapAcpToAdapterError(PROVIDER, input.threadId, "session/prompt", error),
+ const promptStart = yield* prepared.promptLifecycle.withPermit(
+ Effect.gen(function* () {
+ const liveCtx = sessions.get(input.threadId);
+ const interrupted = liveCtx?.interruptedTurnIds.has(prepared.turnId) === true;
+ if (
+ !liveCtx ||
+ liveCtx.acpSessionId !== prepared.acpSessionId ||
+ prepared.promptEpoch < liveCtx.discardBeforeEpoch ||
+ interrupted
+ ) {
+ return { _tag: "Skipped" as const, interrupted };
+ }
+ if (prepared.steeringTurnId !== undefined) {
+ yield* Effect.ignore(
+ liveCtx.acp.cancel.pipe(
+ Effect.mapError((error) =>
+ mapAcpToAdapterError(PROVIDER, input.threadId, "session/cancel", error),
+ ),
+ ),
+ );
+ }
+ if (liveCtx.interruptedTurnIds.has(prepared.turnId)) {
+ return { _tag: "Skipped" as const, interrupted: true };
+ }
+ const dispatched = yield* Deferred.make<void>();
+ const fiber = yield* liveCtx.acp
+ .prompt({ prompt: prepared.promptParts }, { dispatched })
+ .pipe(Effect.forkChild({ startImmediately: true }));
+ // Hold the lifecycle permit until the runtime has registered this
+ // prompt's RPC fiber, so a later steer's session/cancel targets
+ // this prompt. Fall through if the prompt fails before that point.
+ yield* Effect.raceFirst(
+ Deferred.await(dispatched),
+ Fiber.await(fiber).pipe(Effect.asVoid),
+ );
+ return { _tag: "Started" as const, fiber };
+ }),
+ );
+ if (promptStart._tag === "Skipped") {
+ // Settle after releasing promptLifecycle. Holding both locks
+ // deadlocks the next sendTurn, which takes the thread lock first.
+ yield* withThreadLock(
+ input.threadId,
+ settlePromptInFlight(
+ input.threadId,
+ prepared.turnId,
+ prepared.acpSessionId,
+ promptStart.interrupted
+ ? {
+ completedStopReason: "cancelled",
+ settleAllPrompts: true,
+ }
+ : { emitTurnCompletion: false },
),
);
+ yield* Ref.set(promptSettled, true);
+ const liveCtx = sessions.get(input.threadId);
+ return {
+ threadId: input.threadId,
+ turnId: prepared.turnId,
+ resumeCursor: liveCtx?.session.resumeCursor,
+ };
+ }
+
+ const result = yield* Fiber.join(promptStart.fiber).pipe(
+ Effect.tap((promptResult) =>
+ Effect.all(
+ [
+ Ref.set(promptRpcSucceeded, true),
+ Ref.set(promptResultRef, promptResult),
+ markPromptResponseReady(input.threadId, prepared.acpSessionId, prepared.turnId),
+ ],
+ { discard: true },
+ ),
+ ),
+ Effect.tapError((error) =>
+ Ref.set(
+ promptFailureMessageRef,
+ mapAcpToAdapterError(PROVIDER, input.threadId, "session/prompt", error).message,
+ ).pipe(Effect.andThen(prepared.acp.drainEvents)),
+ ),
+ Effect.mapError((error) =>
+ mapAcpToAdapterError(PROVIDER, input.threadId, "session/prompt", error),
+ ),
+ );
return yield* withThreadLock(
input.threadId,
diff --git a/apps/server/src/provider/Layers/GrokProvider.test.ts b/apps/server/src/provider/Layers/GrokProvider.test.ts
index 307f55eeb5a..e7c62f4cbf7 100644
--- a/apps/server/src/provider/Layers/GrokProvider.test.ts
+++ b/apps/server/src/provider/Layers/GrokProvider.test.ts
@@ -1,3 +1,7 @@
+// @effect-diagnostics nodeBuiltinImport:off - resolves the mock ACP agent script path relative to this test file.
+import * as NodePath from "node:path";
+import * as NodeURL from "node:url";
+
import * as NodeServices from "@effect/platform-node/NodeServices";
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
@@ -8,11 +12,74 @@ import { GrokSettings } from "@t3tools/contracts";
import {
buildGrokModelCapabilities,
+ buildGrokModelsFromSessionModelState,
buildInitialGrokProviderSnapshot,
checkGrokProviderStatus,
+ parseGrokModelsCliOutput,
} from "./GrokProvider.ts";
const decodeGrokSettings = Schema.decodeSync(GrokSettings);
+const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
+
+const LOGGED_IN_MODELS_OUTPUT = [
+ "You are logged in with grok.com.",
+ "",
+ "Default model: grok-4.6",
+ "",
+ "Available models:",
+ " * grok-4.6 (default)",
+ " - grok-4.5",
+ "",
+].join("\n");
+
+const LOGGED_OUT_MODELS_OUTPUT = LOGGED_IN_MODELS_OUTPUT.replace(
+ "You are logged in with grok.com.",
+ "You are not authenticated.",
+);
+
+describe("parseGrokModelsCliOutput", () => {
+ it("reads login state and model slugs, marking the default", () => {
+ const parsed = parseGrokModelsCliOutput(LOGGED_IN_MODELS_OUTPUT);
+ expect(parsed.authenticated).toBe(true);
+ expect(parsed.models.map((model) => [model.slug, model.isDefault ?? false])).toEqual([
+ ["grok-4.6", true],
+ ["grok-4.5", false],
+ ]);
+ });
+
+ it("detects a logged-out CLI even though it exits 0", () => {
+ expect(parseGrokModelsCliOutput(LOGGED_OUT_MODELS_OUTPUT).authenticated).toBe(false);
+ });
+
+ it("returns unknown auth for unrecognized output", () => {
+ expect(parseGrokModelsCliOutput("grok 9.9.9\n").authenticated).toBeNull();
+ });
+});
+
+describe("buildGrokModelsFromSessionModelState", () => {
+ it("marks the agent's current model as default and keeps reasoning options", () => {
+ const models = buildGrokModelsFromSessionModelState({
+ currentModelId: "grok-4.6",
+ availableModels: [
+ {
+ modelId: "grok-4.6",
+ name: "Grok 4.6",
+ _meta: {
+ supportsReasoningEffort: true,
+ reasoningEffort: "high",
+ reasoningEfforts: [{ value: "high", label: "High", default: true }],
+ },
+ },
+ { modelId: "grok-4.5", name: "Grok 4.5" },
+ ],
+ });
+ expect(models.map((model) => [model.slug, model.isDefault ?? false])).toEqual([
+ ["grok-4.6", true],
+ ["grok-4.5", false],
+ ]);
+ expect(models[0]?.capabilities?.optionDescriptors).toHaveLength(1);
+ });
+});
describe("buildGrokModelCapabilities", () => {
it("preserves ACP-provided reasoning labels and the active default", () => {
@@ -264,30 +331,139 @@ it.layer(NodeServices.layer)("checkGrokProviderStatus", (it) => {
}),
);
- it.effect("reports an error when ACP model discovery is unavailable", () =>
+ // Single-quotes a path for /bin/sh. Temp dirs and execPath never contain quotes.
+ const shellQuote = (value: string) => `'${value.replaceAll("'", `'\\''`)}'`;
+
+ // A shell stand-in for the Grok CLI: `--version` and `models` print canned text,
+ // and `agent stdio` execs the mock ACP agent so `initialize` returns model metadata.
+ const writeFakeGrokCli = (input: { readonly modelsOutput: string; readonly acp: boolean }) =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-grok-probe-" });
+ const modelsPath = path.join(dir, "models.txt");
+ yield* fs.writeFileString(modelsPath, input.modelsOutput);
+ const grokPath = path.join(dir, "grok");
+ const mockAgentPath = path.resolve(__dirname, "../../../scripts/acp-mock-agent.ts");
+ yield* fs.writeFileString(
+ grokPath,
+ [
+ "#!/bin/sh",
+ 'case "$1" in',
+ ' --version) printf "grok 1.0.13\\n"; exit 0;;',
+ ` models) cat ${shellQuote(modelsPath)}; exit 0;;`,
+ input.acp
+ ? ` agent) exec ${shellQuote(process.execPath)} ${shellQuote(mockAgentPath)};;`
+ : " agent) exit 3;;",
+ "esac",
+ "exit 1",
+ "",
+ ].join("\n"),
+ );
+ yield* fs.chmod(grokPath, 0o755);
+ return grokPath;
+ });
+
+ it.effect("reports ready with ACP-discovered models when logged in", () =>
Effect.gen(function* () {
const snapshot = yield* Effect.scoped(
Effect.gen(function* () {
- const fs = yield* FileSystem.FileSystem;
- const path = yield* Path.Path;
- const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-grok-success-" });
- const grokPath = path.join(dir, "grok");
- yield* fs.writeFileString(
- grokPath,
- ["#!/bin/sh", 'printf "grok-cli 0.0.99\\n"', "exit 0", ""].join("\n"),
+ const grokPath = yield* writeFakeGrokCli({
+ modelsOutput: LOGGED_IN_MODELS_OUTPUT,
+ acp: true,
+ });
+ return yield* checkGrokProviderStatus(
+ decodeGrokSettings({ enabled: true, binaryPath: grokPath }),
+ { ...process.env, XAI_API_KEY: "" },
);
- yield* fs.chmod(grokPath, 0o755);
+ }),
+ );
+ expect(snapshot.status).toBe("ready");
+ expect(snapshot.version).toBe("1.0.13");
+ expect(snapshot.auth).toEqual({
+ status: "authenticated",
+ type: "cached_token",
+ label: "Grok account",
+ });
+ // The mock agent advertises grok-4.6 with reasoning options in initialize._meta.
+ expect(snapshot.models.map((model) => model.slug)).toEqual(["grok-4.6", "grok-mock-alt"]);
+ expect(snapshot.models[0]?.isDefault).toBe(true);
+ expect(
+ snapshot.models[0]?.capabilities?.optionDescriptors?.map((option) => option.id) ?? [],
+ ).toEqual(["reasoningEffort"]);
+ }),
+ );
+
+ it.effect("reports unauthenticated from `grok models` without starting a session", () =>
+ Effect.gen(function* () {
+ const snapshot = yield* Effect.scoped(
+ Effect.gen(function* () {
+ const grokPath = yield* writeFakeGrokCli({
+ modelsOutput: LOGGED_OUT_MODELS_OUTPUT,
+ acp: true,
+ });
return yield* checkGrokProviderStatus(
decodeGrokSettings({ enabled: true, binaryPath: grokPath }),
+ { ...process.env, XAI_API_KEY: "" },
);
}),
);
expect(snapshot.status).toBe("error");
+ expect(snapshot.auth.status).toBe("unauthenticated");
+ expect(snapshot.message).toContain("grok login");
+ expect(snapshot.models.map((model) => model.slug)).toEqual(["grok-4.6", "grok-mock-alt"]);
+ }),
+ );
+
+ it.effect("falls back to CLI-listed models with a warning when ACP initialize fails", () =>
+ Effect.gen(function* () {
+ const snapshot = yield* Effect.scoped(
+ Effect.gen(function* () {
+ const grokPath = yield* writeFakeGrokCli({
+ modelsOutput: LOGGED_IN_MODELS_OUTPUT,
+ acp: false,
+ });
+ return yield* checkGrokProviderStatus(
+ decodeGrokSettings({ enabled: true, binaryPath: grokPath }),
+ { ...process.env, XAI_API_KEY: "" },
+ );
+ }),
+ );
+
+ expect(snapshot.status).toBe("warning");
expect(snapshot.installed).toBe(true);
- expect(snapshot.models.map((model) => model.slug)).toEqual(["grok-build"]);
- expect(snapshot.message).toContain("ACP startup failed");
+ expect(snapshot.auth.status).toBe("authenticated");
+ expect(snapshot.models.map((model) => [model.slug, model.isDefault ?? false])).toEqual([
+ ["grok-4.6", true],
+ ["grok-4.5", false],
+ ]);
+ expect(snapshot.message).toContain("ACP initialize failed");
+ }),
+ );
+
+ it.effect("treats XAI_API_KEY as authenticated regardless of CLI login state", () =>
+ Effect.gen(function* () {
+ const snapshot = yield* Effect.scoped(
+ Effect.gen(function* () {
+ const grokPath = yield* writeFakeGrokCli({
+ modelsOutput: LOGGED_OUT_MODELS_OUTPUT,
+ acp: false,
+ });
+ return yield* checkGrokProviderStatus(
+ decodeGrokSettings({ enabled: true, binaryPath: grokPath }),
+ { ...process.env, XAI_API_KEY: "xai-test-key" },
+ );
+ }),
+ );
+
+ expect(snapshot.auth).toEqual({
+ status: "authenticated",
+ type: "api_key",
+ label: "xAI API key",
+ });
+ expect(snapshot.status).toBe("warning");
}),
);
});
diff --git a/apps/server/src/provider/Layers/GrokProvider.ts b/apps/server/src/provider/Layers/GrokProvider.ts
index 923e1781711..753dc2f4a43 100644
--- a/apps/server/src/provider/Layers/GrokProvider.ts
+++ b/apps/server/src/provider/Layers/GrokProvider.ts
@@ -2,6 +2,7 @@ import {
type GrokSettings,
type ModelCapabilities,
type ServerProvider,
+ type ServerProviderAuth,
type ServerProviderModel,
} from "@t3tools/contracts";
import type * as EffectAcpSchema from "effect-acp/schema";
@@ -18,6 +19,7 @@ import { createModelCapabilities } from "@t3tools/shared/model";
import { resolveSpawnCommand } from "@t3tools/shared/shell";
import {
+ AUTH_PROBE_TIMEOUT_MS,
buildServerProvider,
isCommandMissingCause,
parseGenericCliVersion,
@@ -30,10 +32,12 @@ import {
type ProviderMaintenanceCapabilities,
} from "../providerMaintenance.ts";
import {
+ GROK_DEFAULT_MODEL_SLUG,
isValidGrokReasoningEffortToken,
makeGrokAcpRuntime,
resolveGrokAcpBaseModelId,
} from "../acp/GrokAcpSupport.ts";
+import { sessionModelStateFromInitialize } from "../acp/AcpRuntimeModel.ts";
import { discoverGrokSkills } from "../Drivers/GrokSkills.ts";
const GROK_PRESENTATION = {
@@ -46,11 +50,13 @@ const EMPTY_CAPABILITIES: ModelCapabilities = createModelCapabilities({
});
const VERSION_PROBE_TIMEOUT_MS = 4_000;
-const GROK_ACP_MODEL_DISCOVERY_TIMEOUT_MS = 15_000;
+// `initialize` is a single local round trip, so this is generous even on slow machines.
+const GROK_ACP_INITIALIZE_TIMEOUT_MS = 8_000;
+const GROK_API_KEY_ENV = "XAI_API_KEY";
const GROK_BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
{
- slug: "grok-build",
+ slug: GROK_DEFAULT_MODEL_SLUG,
name: "Grok Build",
isCustom: false,
capabilities: EMPTY_CAPABILITIES,
@@ -201,56 +207,94 @@ export function buildGrokModelCapabilities(model: EffectAcpSchema.ModelInfo): Mo
: EMPTY_CAPABILITIES;
}
-function buildGrokDiscoveredModelsFromSessionModelState(
+/** Models advertised by the ACP agent, with the session's current model marked as default. */
+export function buildGrokModelsFromSessionModelState(
modelState: EffectAcpSchema.SessionModelState | null | undefined,
): ReadonlyArray<ServerProviderModel> {
if (!modelState || modelState.availableModels.length === 0) {
return [];
}
+ const currentModelId = modelState.currentModelId.trim();
const seen = new Set<string>();
- return modelState.availableModels
- .map((model): ServerProviderModel | undefined => {
- const slug = resolveGrokAcpBaseModelId(model.modelId);
- if (!slug || seen.has(slug)) {
- return undefined;
- }
- seen.add(slug);
- return {
+ return modelState.availableModels.flatMap((model): ServerProviderModel[] => {
+ const slug = resolveGrokAcpBaseModelId(model.modelId);
+ if (!slug || seen.has(slug)) {
+ return [];
+ }
+ seen.add(slug);
+ return [
+ {
slug,
name: model.name.trim() || slug,
isCustom: false,
+ ...(model.modelId.trim() === currentModelId ? { isDefault: true } : {}),
capabilities: buildGrokModelCapabilities(model),
- };
- })
- .filter((model): model is ServerProviderModel => model !== undefined);
+ },
+ ];
+ });
}
-const discoverGrokModelsViaAcp = (
- grokSettings: GrokSettings,
- environment: NodeJS.ProcessEnv = process.env,
-) =>
- Effect.gen(function* () {
- const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
- const acp = yield* makeGrokAcpRuntime({
- grokSettings,
- environment,
- childProcessSpawner,
- cwd: process.cwd(),
- clientInfo: { name: "t3-code-provider-probe", version: "0.0.0" },
+export interface GrokModelsCliOutput {
+ /** True or false when the CLI printed a login line, null when it printed neither. */
+ readonly authenticated: boolean | null;
+ readonly models: ReadonlyArray<ServerProviderModel>;
+}
+
+/**
+ * Parses `grok models`. The command exits 0 whether or not the user is logged in, so the
+ * text is the only signal. Current output looks like:
+ *
+ * You are logged in with grok.com.
+ * Default model: grok-4.6
+ * Available models:
+ * * grok-4.6 (default)
+ * - grok-4.5
+ */
+export function parseGrokModelsCliOutput(output: string): GrokModelsCliOutput {
+ const authenticated = /you are logged in/i.test(output)
+ ? true
+ : /not authenticated|not logged in/i.test(output)
+ ? false
+ : null;
+
+ const seen = new Set<string>();
+ const models: ServerProviderModel[] = [];
+ for (const line of output.split(/\r?\n/)) {
+ const bullet = line.match(/^\s*[*-]\s+(\S+)(.*)$/);
+ if (!bullet?.[1]) {
+ continue;
+ }
+ const slug = resolveGrokAcpBaseModelId(bullet[1]);
+ if (seen.has(slug)) {
+ continue;
+ }
+ seen.add(slug);
+ models.push({
+ slug,
+ name: displayNameFromGrokModelSlug(slug),
+ isCustom: false,
+ ...(/\(default\)/i.test(bullet[2] ?? "") ? { isDefault: true } : {}),
+ capabilities: EMPTY_CAPABILITIES,
});
- const started = yield* acp.start();
- return buildGrokDiscoveredModelsFromSessionModelState(started.sessionSetupResult.models);
- }).pipe(Effect.scoped);
+ }
+ return { authenticated, models };
+}
+
+function displayNameFromGrokModelSlug(slug: string): string {
+ return slug
+ .split(/[-_]/g)
+ .map((part) => (part.toLowerCase() === "grok" ? "Grok" : part))
+ .join(" ");
+}
-const runGrokVersionCommand = (
+const runGrokCliCommand = (
grokSettings: GrokSettings,
- environment: NodeJS.ProcessEnv = process.env,
+ args: ReadonlyArray<string>,
+ environment: NodeJS.ProcessEnv,
) =>
Effect.gen(function* () {
const command = grokSettings.binaryPath || "grok";
- const spawnCommand = yield* resolveSpawnCommand(command, ["--version"], {
- env: environment,
- });
+ const spawnCommand = yield* resolveSpawnCommand(command, args, { env: environment });
return yield* spawnAndCollect(
command,
ChildProcess.make(spawnCommand.command, spawnCommand.args, {
@@ -260,6 +304,27 @@ const runGrokVersionCommand = (
);
});
+/**
+ * Reads model metadata from `initialize._meta.modelState`. This never calls `authenticate`
+ * or `session/new`, so it cannot open a browser login or boot the workspace's MCP servers.
+ */
+const discoverGrokModelsViaAcpInitialize = (
+ grokSettings: GrokSettings,
+ environment: NodeJS.ProcessEnv,
+) =>
+ Effect.gen(function* () {
+ const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
+ const acp = yield* makeGrokAcpRuntime({
+ grokSettings,
+ environment,
+ childProcessSpawner,
+ cwd: process.cwd(),
+ clientInfo: { name: "t3-code-provider-probe", version: "0.0.0" },
+ });
+ const initialized = yield* acp.initialize();
+ return buildGrokModelsFromSessionModelState(sessionModelStateFromInitialize(initialized));
+ }).pipe(Effect.scoped);
+
export const checkGrokProviderStatus = Effect.fn("checkGrokProviderStatus")(function* (
grokSettings: GrokSettings,
environment: NodeJS.ProcessEnv = process.env,
@@ -288,7 +353,7 @@ export const checkGrokProviderStatus = Effect.fn("checkGrokProviderStatus")(func
});
}
- const versionResult = yield* runGrokVersionCommand(grokSettings, environment).pipe(
+ const versionResult = yield* runGrokCliCommand(grokSettings, ["--version"], environment).pipe(
Effect.timeoutOption(VERSION_PROBE_TIMEOUT_MS),
Effect.result,
);
@@ -354,55 +419,76 @@ export const checkGrokProviderStatus = Effect.fn("checkGrokProviderStatus")(func
});
}
+ // `grok models` reports login state and model slugs without starting the agent.
+ const modelsResult = yield* runGrokCliCommand(grokSettings, ["models"], environment).pipe(
+ Effect.timeoutOption(AUTH_PROBE_TIMEOUT_MS),
+ Effect.result,
+ );
+ // Only a clean exit is parsed. Failed invocations print help or error text that
+ // must not be read as model slugs or as a login verdict.
+ const modelsOutput =
+ Result.isSuccess(modelsResult) &&
+ Option.isSome(modelsResult.success) &&
+ modelsResult.success.value.code === 0
+ ? modelsResult.success.value
+ : undefined;
+ const cliModels: GrokModelsCliOutput = modelsOutput
+ ? parseGrokModelsCliOutput(`${modelsOutput.stdout}\n${modelsOutput.stderr}`)
+ : { authenticated: null, models: [] };
+ if (!modelsOutput) {
+ yield* Effect.logWarning("Grok CLI model listing failed or timed out.", {
+ errorTag: Result.isFailure(modelsResult)
+ ? modelsResult.failure._tag
+ : Option.isNone(modelsResult.success)
+ ? "Timeout"
+ : `ExitCode${modelsResult.success.value.code}`,
+ });
+ }
+
+ const auth: ServerProviderAuth = environment[GROK_API_KEY_ENV]?.trim()
+ ? { status: "authenticated", type: "api_key", label: "xAI API key" }
+ : cliModels.authenticated === true
+ ? { status: "authenticated", type: "cached_token", label: "Grok account" }
+ : cliModels.authenticated === false
+ ? { status: "unauthenticated" }
+ : { status: "unknown" };
+
const skills = yield* discoverGrokSkills(grokSettings, environment, cwd);
- const discoveryExit = yield* discoverGrokModelsViaAcp(grokSettings, environment).pipe(
- Effect.timeoutOption(GROK_ACP_MODEL_DISCOVERY_TIMEOUT_MS),
+ const acpExit = yield* discoverGrokModelsViaAcpInitialize(grokSettings, environment).pipe(
+ Effect.timeoutOption(GROK_ACP_INITIALIZE_TIMEOUT_MS),
Effect.exit,
);
- if (Exit.isFailure(discoveryExit)) {
- yield* Effect.logWarning("Grok ACP model discovery failed", {
- errorTag: causeErrorTag(discoveryExit.cause),
- });
- return buildServerProvider({
- presentation: GROK_PRESENTATION,
- enabled: grokSettings.enabled,
- checkedAt,
- models: fallbackModels,
- skills,
- probe: {
- installed: true,
- version,
- status: "error",
- auth: { status: "unknown" },
- message: "Grok CLI is installed but ACP startup failed. Check server logs for details.",
- },
+ const acpModels = Exit.isSuccess(acpExit) ? Option.getOrElse(acpExit.value, () => []) : [];
+ const acpFailed = Exit.isFailure(acpExit) || Option.isNone(acpExit.value);
+ if (acpFailed) {
+ yield* Effect.logWarning("Grok ACP initialize probe failed or timed out.", {
+ errorTag: Exit.isFailure(acpExit) ? causeErrorTag(acpExit.cause) : "Timeout",
});
}
- if (Option.isNone(discoveryExit.value)) {
- yield* Effect.logWarning(
- `Grok ACP model discovery timed out after ${GROK_ACP_MODEL_DISCOVERY_TIMEOUT_MS}ms.`,
- );
+
+ const discoveredModels = acpModels.length > 0 ? acpModels : cliModels.models;
+ const models =
+ discoveredModels.length > 0
+ ? grokModelsFromSettings(grokSettings.customModels, discoveredModels)
+ : fallbackModels;
+
+ if (auth.status === "unauthenticated") {
return buildServerProvider({
presentation: GROK_PRESENTATION,
enabled: grokSettings.enabled,
checkedAt,
- models: fallbackModels,
+ models,
skills,
probe: {
installed: true,
version,
status: "error",
- auth: { status: "unknown" },
- message: `Grok CLI is installed but ACP startup timed out after ${GROK_ACP_MODEL_DISCOVERY_TIMEOUT_MS}ms.`,
+ auth,
+ message: "Grok CLI is installed but not logged in. Run `grok login`.",
},
});
}
- const discoveredModels = discoveryExit.value.value;
- const models =
- discoveredModels.length > 0
- ? grokModelsFromSettings(grokSettings.customModels, discoveredModels)
- : fallbackModels;
return buildServerProvider({
presentation: GROK_PRESENTATION,
@@ -413,8 +499,15 @@ export const checkGrokProviderStatus = Effect.fn("checkGrokProviderStatus")(func
probe: {
installed: true,
version,
- status: "ready",
- auth: { status: "unknown" },
+ // A failed metadata probe degrades the model picker, it does not make chats fail.
+ status: acpFailed ? "warning" : "ready",
+ auth,
+ ...(acpFailed
+ ? {
+ message:
+ "Grok CLI is installed but ACP initialize failed. Model options may be incomplete.",
+ }
+ : {}),
},
});
});
diff --git a/apps/server/src/provider/acp/AcpRuntimeModel.ts b/apps/server/src/provider/acp/AcpRuntimeModel.ts
index a81a2faf5e0..c680143e405 100644
--- a/apps/server/src/provider/acp/AcpRuntimeModel.ts
+++ b/apps/server/src/provider/acp/AcpRuntimeModel.ts
@@ -713,13 +713,24 @@ export const waitForSessionLoadReplayIdle = (input: {
}
});
+/**
+ * Model state some agents (Grok) advertise in `initialize._meta.modelState`, before any
+ * session exists. Undefined when the agent does not advertise it or the shape is unknown.
+ */
+export function sessionModelStateFromInitialize(
+ initializeResult: EffectAcpSchema.InitializeResponse,
+): EffectAcpSchema.SessionModelState | undefined {
+ const meta = initializeResult._meta;
+ const modelState = isRecord(meta) ? meta.modelState : undefined;
+ return isSessionModelState(modelState) ? modelState : undefined;
+}
+
export function syntheticLoadSessionResponseFromInitialize(
initializeResult: EffectAcpSchema.InitializeResponse,
): EffectAcpSchema.LoadSessionResponse {
const meta = initializeResult._meta;
- const modelState = isRecord(meta) ? meta.modelState : undefined;
const modeState = isRecord(meta) ? meta.modeState : undefined;
- const models = isSessionModelState(modelState) ? modelState : undefined;
+ const models = sessionModelStateFromInitialize(initializeResult);
const modes = isSessionModeState(modeState) ? modeState : undefined;
return {
diff --git a/apps/server/src/provider/acp/AcpSessionRuntime.ts b/apps/server/src/provider/acp/AcpSessionRuntime.ts
index 2a4cb6a2337..14ef1540fb8 100644
--- a/apps/server/src/provider/acp/AcpSessionRuntime.ts
+++ b/apps/server/src/provider/acp/AcpSessionRuntime.ts
@@ -182,6 +182,16 @@ export class AcpSessionRuntime extends Context.Service<
* @see https://agentclientprotocol.com/protocol/extensibility
*/
readonly handleExtNotification: EffectAcpClient.AcpClient["Service"]["handleExtNotification"];
+ /**
+ * Sends only `initialize` and returns the agent's response. Health probes use this to read
+ * advertised capabilities without authenticating or opening a session, so a probe can never
+ * start an interactive login or boot MCP servers.
+ * @see https://agentclientprotocol.com/protocol/schema#initialize
+ */
+ readonly initialize: () => Effect.Effect<
+ EffectAcpSchema.InitializeResponse,
+ EffectAcpErrors.AcpError
+ >;
/**
* Initializes the ACP connection, authenticates, and loads, resumes, or creates the session.
* Concurrent calls share the same in-flight startup and a failed startup may be retried.
@@ -196,11 +206,14 @@ export class AcpSessionRuntime extends Context.Service<
/** Latest configuration options observed from session setup and configuration writes. */
readonly getConfigOptions: Effect.Effect<ReadonlyArray<EffectAcpSchema.SessionConfigOption>>;
/**
- * Sends a prompt turn to the active session.
+ * Sends a prompt turn to the active session. `options.dispatched` settles once the
+ * `session/prompt` RPC is registered as the active prompt, so a caller that forks this
+ * effect knows when a later `cancel` will target this prompt.
* @see https://agentclientprotocol.com/protocol/schema#session/prompt
*/
readonly prompt: (
payload: Omit<EffectAcpSchema.PromptRequest, "sessionId">,
+ options?: { readonly dispatched?: Deferred.Deferred<void> },
) => Effect.Effect<EffectAcpSchema.PromptResponse, EffectAcpErrors.AcpError>;
/**
* Sends a real ACP `session/cancel` notification for the active session.
@@ -537,18 +550,19 @@ export const make = (
),
);
+ const initializePayload = {
+ protocolVersion: 1,
+ clientCapabilities: initializeClientCapabilities,
+ clientInfo: options.clientInfo,
+ } satisfies EffectAcpSchema.InitializeRequest;
+ const sendInitialize = runLoggedRequest(
+ "initialize",
+ initializePayload,
+ acp.agent.initialize(initializePayload),
+ );
+
const startOnce = Effect.gen(function* () {
- const initializePayload = {
- protocolVersion: 1,
- clientCapabilities: initializeClientCapabilities,
- clientInfo: options.clientInfo,
- } satisfies EffectAcpSchema.InitializeRequest;
-
- const initializeResult = yield* runLoggedRequest(
- "initialize",
- initializePayload,
- acp.agent.initialize(initializePayload),
- );
+ const initializeResult = yield* sendInitialize;
const authenticatePayload = {
methodId: options.authMethodId,
@@ -713,6 +727,7 @@ export const make = (
handleUnknownExtNotification: acp.handleUnknownExtNotification,
handleExtRequest: acp.handleExtRequest,
handleExtNotification: acp.handleExtNotification,
+ initialize: () => sendInitialize,
start: () => start,
getEvents: () => Stream.fromQueue(eventQueue),
drainEvents: Effect.gen(function* () {
@@ -725,7 +740,7 @@ export const make = (
}),
getModeState: Ref.get(modeStateRef),
getConfigOptions: Ref.get(configOptionsRef),
- prompt: (payload) =>
+ prompt: (payload, promptOptions?) =>
promptSerializationSemaphore.withPermit(
Effect.gen(function* () {
const started = yield* getStartedState;
@@ -746,6 +761,9 @@ export const make = (
acp.agent.prompt(requestPayload),
).pipe(Effect.forkIn(runtimeScope));
yield* Ref.set(activePromptFiberRef, Option.some(promptRpcFiber));
+ if (promptOptions?.dispatched) {
+ yield* Deferred.succeed(promptOptions.dispatched, undefined);
+ }
return yield* Fiber.join(promptRpcFiber).pipe(
Effect.catchCause((cause) =>
Cause.hasInterruptsOnly(cause)
@@ -774,9 +792,9 @@ export const make = (
if (Option.isSome(activePromptFiber)) {
yield* Fiber.interrupt(activePromptFiber.value).pipe(Effect.ignore);
}
- yield* acp.agent
- .cancel({ sessionId: started.sessionId })
- .pipe(Effect.ignore, Effect.forkIn(runtimeScope));
+ // Await the notification write so a replacement session/prompt
+ // cannot race ahead of session/cancel on the wire.
+ yield* acp.agent.cancel({ sessionId: started.sessionId }).pipe(Effect.ignore);
}),
),
),
diff --git a/apps/server/src/provider/acp/GrokAcpSupport.test.ts b/apps/server/src/provider/acp/GrokAcpSupport.test.ts
index a85f7174a1c..3f64128c584 100644
--- a/apps/server/src/provider/acp/GrokAcpSupport.test.ts
+++ b/apps/server/src/provider/acp/GrokAcpSupport.test.ts
@@ -178,6 +178,36 @@ describe("applyGrokAcpModelSelection", () => {
}),
);
+ it.effect("keeps the session's current model when the product slug is requested", () =>
+ Effect.gen(function* () {
+ const { runtime, modelCalls } = makeRecordingRuntime();
+ const result = yield* applyGrokAcpModelSelection({
+ runtime,
+ currentModelId: "grok-4.6",
+ requestedModelId: "grok-build",
+ mapError: (cause) => cause.message,
+ });
+ expect(modelCalls).toEqual([]);
+ expect(result).toBe("grok-4.6");
+ }),
+ );
+
+ it.effect("applies reasoning to the current model when the product slug is requested", () =>
+ Effect.gen(function* () {
+ const { runtime, modelCalls } = makeRecordingRuntime();
+ const result = yield* applyGrokAcpModelSelection({
+ runtime,
+ currentModelId: "grok-4.6",
+ currentReasoningEffort: "high",
+ requestedModelId: "grok-build",
+ requestedReasoningEffort: "xhigh",
+ mapError: (cause) => cause.message,
+ });
+ expect(modelCalls).toEqual([{ modelId: "grok-4.6", meta: { reasoningEffort: "xhigh" } }]);
+ expect(result).toBe("grok-4.6");
+ }),
+ );
+
it.effect("skips set_model when no model is requested", () =>
Effect.gen(function* () {
const { runtime, modelCalls } = makeRecordingRuntime();
diff --git a/apps/server/src/provider/acp/GrokAcpSupport.ts b/apps/server/src/provider/acp/GrokAcpSupport.ts
index 001f0adfe7b..e3500383526 100644
--- a/apps/server/src/provider/acp/GrokAcpSupport.ts
+++ b/apps/server/src/provider/acp/GrokAcpSupport.ts
@@ -98,10 +98,16 @@ export const makeGrokAcpRuntime = (
return yield* makeXAiPromptCompletionRuntime(runtime);
});
+/**
+ * T3's built-in Grok slug. It is the CLI's product name, not a model id the ACP accepts,
+ * so selecting it means "use whatever model the Grok session currently runs on".
+ */
+export const GROK_DEFAULT_MODEL_SLUG = "grok-build";
+
export function resolveGrokAcpBaseModelId(model: string | null | undefined): string {
const trimmed = model?.trim();
- const base = trimmed && trimmed.length > 0 ? trimmed : "grok-build";
- return normalizeModelSlug(base, GROK_DRIVER_KIND) ?? "grok-build";
+ const base = trimmed && trimmed.length > 0 ? trimmed : GROK_DEFAULT_MODEL_SLUG;
+ return normalizeModelSlug(base, GROK_DRIVER_KIND) ?? GROK_DEFAULT_MODEL_SLUG;
}
const GROK_REASONING_EFFORT_TOKEN = /^[a-z0-9][a-z0-9._-]{0,31}$/i;
@@ -155,15 +161,17 @@ export function applyGrokAcpModelSelection<E>(input: {
readonly requestedReasoningEffort?: string | undefined;
readonly mapError: (cause: EffectAcpErrors.AcpError) => E;
}): Effect.Effect<string | undefined, E> {
- const modelChanged =
- input.requestedModelId !== undefined && input.requestedModelId !== input.currentModelId;
+ // The product slug is never sent over the wire; it keeps the session's current model.
+ const requestedModelId =
+ input.requestedModelId === GROK_DEFAULT_MODEL_SLUG ? undefined : input.requestedModelId;
+ const modelChanged = requestedModelId !== undefined && requestedModelId !== input.currentModelId;
const reasoningProvided = input.requestedReasoningEffort !== undefined;
const reasoningEffort = reasoningProvided
? normalizeGrokReasoningEffort(input.requestedReasoningEffort)
: undefined;
const reasoningEffortChanged =
reasoningProvided && reasoningEffort !== input.currentReasoningEffort;
- const targetModelId = input.requestedModelId ?? input.currentModelId;
+ const targetModelId = requestedModelId ?? input.currentModelId;
if ((!modelChanged && !reasoningEffortChanged) || targetModelId === undefined) {
return Effect.succeed(input.currentModelId);
}
diff --git a/apps/server/src/provider/acp/XAiAcpExtension.ts b/apps/server/src/provider/acp/XAiAcpExtension.ts
index 543edb39bb6..620545569aa 100644
--- a/apps/server/src/provider/acp/XAiAcpExtension.ts
+++ b/apps/server/src/provider/acp/XAiAcpExtension.ts
@@ -447,11 +447,11 @@ export const makeXAiPromptCompletionRuntime = Effect.fn("makeXAiPromptCompletion
runtime
.start()
.pipe(Effect.tap((started) => Ref.set(activeSessionIdRef, started.sessionId))),
- prompt: (payload) =>
+ prompt: (payload, promptOptions?) =>
Effect.gen(function* () {
const sessionId = yield* Ref.get(activeSessionIdRef);
if (sessionId === undefined) {
- return yield* runtime.prompt(payload);
+ return yield* runtime.prompt(payload, promptOptions);
}
const promptId = yield* allocatePromptFallbackId;
@@ -470,7 +470,7 @@ export const makeXAiPromptCompletionRuntime = Effect.fn("makeXAiPromptCompletion
} satisfies Omit<EffectAcpSchema.PromptRequest, "sessionId">;
return yield* Effect.raceFirst(
- runtime.prompt(requestPayload),
+ runtime.prompt(requestPayload, promptOptions),
Deferred.await(fallback.deferred),
).pipe(
Effect.tap((response) =>
diff --git a/docs/internals/providers.md b/docs/internals/providers.md
index 75163f0cc0f..5229ad7781a 100644
--- a/docs/internals/providers.md
+++ b/docs/internals/providers.md
@@ -39,6 +39,17 @@ directory to route session and turn operations for a thread, so callers name a t
Adding a driver means writing the driver plus adapter and adding it to `BUILT_IN_DRIVERS`. No
orchestration, contract, or client change is required for the common case.
+### Grok health check
+
+`checkGrokProviderStatus` never opens an ACP session. It runs `grok --version`, then `grok models`
+for login state and model slugs, then a single ACP `initialize` and reads models from
+`_meta.modelState`. `authenticate` and `session/new` are skipped on purpose: `authenticate` can open
+a browser login and `session/new` boots every configured MCP server, both of which made background
+probes hang or surprise the user. A failed `initialize` degrades to `warning` with the CLI's model
+list instead of persisting `error` over a working install. The built-in `grok-build` slug is the
+CLI's product name, not an ACP model id. `applyGrokAcpModelSelection` treats it as "keep the
+session's current model" and never sends it in `session/set_model`.
+
## OpenCode server ownership and catalog
Each OpenCode provider instance owns one lazy local server for catalog discovery and
diff --git a/packages/contracts/src/model.ts b/packages/contracts/src/model.ts
index 92080d0cb4a..6610a265d61 100644
--- a/packages/contracts/src/model.ts
+++ b/packages/contracts/src/model.ts
@@ -151,6 +151,7 @@ export const DEFAULT_MODEL_BY_PROVIDER: Partial<Record<ProviderDriverKind, strin
[CODEX_DRIVER_KIND]: DEFAULT_MODEL,
[CLAUDE_DRIVER_KIND]: "claude-sonnet-5",
[CURSOR_DRIVER_KIND]: "auto",
+ // Product slug, not an ACP model id. The Grok adapter treats it as "the session's current model".
[GROK_DRIVER_KIND]: "grok-build",
[OPENCODE_DRIVER_KIND]: "openai/gpt-5",
};
diff --git a/packages/effect-acp/src/protocol.test.ts b/packages/effect-acp/src/protocol.test.ts
index 7ca86b063e2..b518d1db00f 100644
--- a/packages/effect-acp/src/protocol.test.ts
+++ b/packages/effect-acp/src/protocol.test.ts
@@ -229,25 +229,24 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
yield* transport.notify("session/cancel", { sessionId: "session-1" });
+ // A notification must not carry `id` or `headers`. Grok CLI drops frames that do.
assert.deepEqual(events, [
{
direction: "outgoing",
stage: "decoded",
payload: {
- _tag: "Request",
- id: "",
+ _tag: "Notification",
tag: "session/cancel",
payload: {
sessionId: "session-1",
},
- headers: [],
},
},
{
direction: "outgoing",
stage: "raw",
payload:
- '{"jsonrpc":"2.0","method":"session/cancel","params":{"sessionId":"session-1"},"id":"","headers":[]}\n',
+ '{"jsonrpc":"2.0","method":"session/cancel","params":{"sessionId":"session-1"}}\n',
},
]);
}),
@@ -293,11 +292,13 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
serverRequestMethods: new Set(),
});
+ // Notifications encode through Schema, so the cause is the schema failure rather
+ // than the raw TypeError JSON.stringify throws. The ACP error shape is what callers see.
const bigintError = yield* transport.notify("x/test", 1n).pipe(Effect.flip);
assert.instanceOf(bigintError, AcpError.AcpProtocolParseError);
assert.equal(bigintError.operation, "encode-message");
assert.equal(bigintError.method, "x/test");
- assert.instanceOf(bigintError.cause, TypeError);
+ assert.isDefined(bigintError.cause);
assert.equal(
bigintError.message,
"ACP protocol operation 'encode-message' failed for method 'x/test'.",
@@ -309,7 +310,7 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
assert.instanceOf(circularError, AcpError.AcpProtocolParseError);
assert.equal(circularError.operation, "encode-message");
assert.equal(circularError.method, "x/test");
- assert.instanceOf(circularError.cause, TypeError);
+ assert.isDefined(circularError.cause);
const requestError = yield* transport.request("x/request", 1n).pipe(
Effect.match({
diff --git a/packages/effect-acp/src/protocol.ts b/packages/effect-acp/src/protocol.ts
index 44a48bd1ef7..9f993dedb6e 100644
--- a/packages/effect-acp/src/protocol.ts
+++ b/packages/effect-acp/src/protocol.ts
@@ -1,6 +1,7 @@
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Deferred from "effect/Deferred";
+import * as Exit from "effect/Exit";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
@@ -77,6 +78,16 @@ const decodeElicitationComplete = Schema.decodeUnknownEffect(
);
const parserFactory = RpcSerialization.ndJsonRpc();
const MAX_BUFFERED_RAW_NOTIFICATIONS = 32;
+// Outbound JSON-RPC notification: no `id`, so peers never treat it as a request.
+const encodeJsonRpcNotification = Schema.encodeUnknownExit(
+ Schema.fromJsonString(
+ Schema.Struct({
+ jsonrpc: Schema.Literal("2.0"),
+ method: Schema.String,
+ params: Schema.Unknown,
+ }),
+ ),
+);
export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(function* (
options: AcpPatchedProtocolOptions,
@@ -109,6 +120,11 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi
const offerOutgoing = Effect.fn("offerOutgoing")(function* (
message: RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded,
) {
+ // RpcClient emits `@effect/rpc/Interrupt` when a pending request's fiber is interrupted.
+ // ACP has no such method; agents log it as an error and cannot act on it, so drop it.
+ if (message._tag === "Interrupt") {
+ return;
+ }
yield* logProtocol({
direction: "outgoing",
stage: "decoded",
@@ -521,17 +537,29 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi
supportsSpanPropagation: true,
});
+ // JSON-RPC notifications carry no `id`. The generic Request encoder emits `id: ""` plus
+ // `headers`, which real agents (Grok CLI) parse as a malformed request and silently drop.
+ // That made `session/cancel` a no-op against Grok while the lenient mock agent accepted it.
const sendNotification = Effect.fn("sendNotification")(function* (
method: string,
payload: unknown,
) {
- yield* offerOutgoing({
- _tag: "Request",
- id: "",
- tag: method,
- payload,
- headers: [],
+ yield* logProtocol({
+ direction: "outgoing",
+ stage: "decoded",
+ payload: { _tag: "Notification", tag: method, payload },
});
+ const exit = encodeJsonRpcNotification({ jsonrpc: "2.0", method, params: payload });
+ if (Exit.isFailure(exit)) {
+ return yield* AcpError.AcpProtocolParseError.fromEncodingError(
+ method,
+ undefined,
+ Cause.squash(exit.cause),
+ );
+ }
+ const encoded = `${exit.value}\n`;
+ yield* logProtocol({ direction: "outgoing", stage: "raw", payload: encoded });
+ yield* Queue.offer(outgoing, encoded);
});
const sendRequest = Effect.fn("sendRequest")(function* (method: string, payload: unknown) {