feat(grok): Grok Build workflows, usage, rewind — supersedes #6383 #7070
Closedmaslinedwin(GitHub profile, opens in a new tab)wants to merge 28 commits into
main fromrefs/pull/7070/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/server/src/provider/Layers/GrokAdapter.ts line 399OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -275,0 +379,21 @@379+ title: input.update.name,380+ ...(phases.length > 0 ? { phases } : {}),381+ runHandles: { runId: input.update.runId },382+ },383+ raw,384+ });385+ }386+387+ let workflowTokens = 0;388+ for (const [agentIndex, agent] of input.update.agents.entries()) {389+ workflowTokens += agent.tokensUsed;390+ const agentStarted = ctx.workflowAgentIds.has(agent.agentId);391+ if (!agentStarted) {392+ ctx.workflowAgentIds.add(agent.agentId);393+ }394+ const agentStatus = grokWorkflowAgentStatus(agent.state);395+ const agentPayload = {396+ taskId: RuntimeTaskId.make(agent.agentId),397+ description: agent.label,398+ taskType: "subagent",399+ agentId: input.update.runId,apps/server/src/provider/Layers/GrokProvider.ts lines 126 to 129OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -113,9 +118,12 @@113118 return undefined;114119 }115120 seen.add(slug);121+ const meta = parseGrokAcpModelMeta(model._meta);116122 return {117123 slug,118124 name: model.name.trim() || slug,119125 isCustom: false,120- capabilities: EMPTY_CAPABILITIES,126+ capabilities: meta.supportsReasoningEffort127+ ? grokReasoningEffortCapabilities(meta.reasoningEfforts)128+ : FALLBACK_CAPABILITIES,121129 };apps/server/src/provider/Layers/GrokAdapter.ts line 744Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -549,3 +747,7 @@549747 const cwd = path.resolve(input.cwd.trim());550748 const grokModelSelection =551749 input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined;750+ const requestedStartModelId = grokModelSelection?.model751+ ? resolveGrokAcpBaseModelId(grokModelSelection.model)752+ : undefined;753+ const requestedStartEffort = requestedGrokReasoningEffort(grokModelSelection, []);apps/server/src/provider/Layers/GrokAdapter.ts line 360OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -275,0 +340,21 @@340+ runHandles: { runId: input.update.runId },341+ };342+ yield* offerRuntimeEvent({343+ type: runStarted ? "task.progress" : "task.started",344+ ...stamp,345+ provider: PROVIDER,346+ threadId: input.threadId,347+ turnId: input.turnId,348+ payload: runStarted349+ ? {350+ ...runPayload,351+ summary:352+ input.update.currentAgentLabel ??353+ input.update.currentPhase ??354+ input.update.status,355+ status: runStatus,356+ }357+ : runPayload,358+ raw,359+ });360+ if (runStarted && grokWorkflowRunIsTerminal(input.update.status)) {
- apps/server/src/provider/Layers/GrokAdapter.ts line 429OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -275,0 +409,21 @@409+ provider: PROVIDER,410+ threadId: input.threadId,411+ turnId: input.turnId,412+ payload: agentStarted413+ ? {414+ ...agentPayload,415+ summary: agent.state,416+ status: agentStatus,417+ ...(agent.tokensUsed > 0 || agent.durationMs > 0418+ ? {419+ typedUsage: {420+ totalTokens: agent.tokensUsed,421+ ...(agent.durationMs > 0 ? { durationMs: agent.durationMs } : {}),422+ },423+ }424+ : {}),425+ }426+ : agentPayload,427+ raw,428+ });429+ if (agentStarted && grokWorkflowAgentIsTerminal(agent.state)) {apps/server/src/provider/Layers/GrokAdapter.ts line 471OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -275,0 +451,21 @@451+ raw,452+ });453+ }454+ }455+456+ if (workflowTokens > 0) {457+ yield* offerRuntimeEvent({458+ type: "thread.token-usage.updated",459+ ...(yield* makeEventStamp()),460+ provider: PROVIDER,461+ threadId: input.threadId,462+ turnId: input.turnId,463+ payload: {464+ usage: {465+ usedTokens: workflowTokens,466+ lastUsedTokens: workflowTokens,467+ },468+ },469+ raw,470+ });471+ }apps/server/src/provider/Layers/GrokProvider.ts line 128OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -113,8 +118,11 @@113118 return undefined;114119 }115120 seen.add(slug);121+ const meta = parseGrokAcpModelMeta(model._meta);116122 return {117123 slug,118124 name: model.name.trim() || slug,119125 isCustom: false,120- capabilities: EMPTY_CAPABILITIES,126+ capabilities: meta.supportsReasoningEffort127+ ? grokReasoningEffortCapabilities(meta.reasoningEfforts)128+ : FALLBACK_CAPABILITIES,
- apps/server/src/provider/acp/GrokAcpWorkflow.ts line 479OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +459,21 @@459+ ...(update.parentSessionId ? { parentAgentId: update.parentSessionId } : {}),460+ ...(update.childSessionId ? { agentPath: update.childSessionId } : {}),461+ timelineBypass: true,462+ };463+464+ if (update.kind === "spawned" && !seenSubagentIds.has(update.subagentId)) {465+ seenSubagentIds.add(update.subagentId);466+ events.push({ type: "task.started", payload: linkage });467+ } else if (update.kind === "progress") {468+ if (!seenSubagentIds.has(update.subagentId)) {469+ seenSubagentIds.add(update.subagentId);470+ events.push({ type: "task.started", payload: linkage });471+ }472+ if (!completedSubagentIds.has(update.subagentId)) {473+ events.push({474+ type: "task.progress",475+ payload: {476+ ...linkage,477+ status: "running",478+ summary: update.role ?? "running",479+ ...(update.tokensUsed !== undefined || update.durationMs !== undefinedapps/server/src/provider/acp/GrokAcpWorkflow.ts line 149Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +120,21 @@120+ const runId = readString(update.run_id) ?? readString(update.runId);121+ const name = readString(update.name);122+ if (runId === undefined || name === undefined) {123+ return undefined;124+ }125+ if (126+ tag === undefined &&127+ (readString(update.status) === undefined || !Array.isArray(update.phases))128+ ) {129+ return undefined;130+ }131+ const phases = Array.isArray(update.phases)132+ ? update.phases.flatMap((entry): ReadonlyArray<GrokWorkflowPhase> => {133+ const record = asRecord(entry);134+ const title = readString(record?.title);135+ const state = readString(record?.state);136+ return title && state ? [{ title, state }] : [];137+ })138+ : [];139+ const agents = Array.isArray(update.agents)140+ ? update.agents.flatMap((entry): ReadonlyArray<GrokWorkflowAgent> => {apps/server/src/provider/Layers/GrokAdapter.ts line 1110OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -952,6 +1090,21 @@1090+ ? (ctx.reasoningEffortMenus.get(requestedTurnModelId) ?? [])1091+ : ctx.currentModelId1092+ ? (ctx.reasoningEffortMenus.get(ctx.currentModelId) ?? [])1093+ : [];1094+ const turnSelection = yield* applyGrokAcpModelSelection({9521095 runtime: ctx.acp,9531096 currentModelId: ctx.currentModelId,9541097 requestedModelId: requestedTurnModelId,1098+ currentReasoningEffort: ctx.currentReasoningEffort,1099+ requestedReasoningEffort: requestedGrokReasoningEffort(1100+ turnModelSelection,1101+ advertisedTurnEfforts,1102+ ),9551103 mapError: (cause) =>9561104 mapAcpToAdapterError(PROVIDER, input.threadId, "session/set_model", cause),9571105 });1106+ const currentModelId = turnSelection.modelId;1107+ ctx.currentModelId = currentModelId;1108+ ctx.currentReasoningEffort = turnSelection.reasoningEffort;1109+ if (currentModelId) {1110+ ctx.maxTokens = ctx.maxTokensByModel.get(currentModelId) ?? ctx.maxTokens;
- apps/server/src/provider/Layers/GrokAdapter.ts line 1938Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1405,17 +1571,6 @@1405157114061572 const rollbackThread: GrokAdapterShape["rollbackThread"] = (threadId, numTurns) =>1407- Effect.gen(function* () {1408- yield* requireSession(threadId);1409- if (!Number.isInteger(numTurns) || numTurns < 1) {1410- return yield* new ProviderAdapterValidationError({1411- provider: PROVIDER,1412- operation: "rollbackThread",1413- issue: "numTurns must be an integer >= 1.",1414- });1415- }1416- return yield* new ProviderAdapterRequestError({1417- provider: PROVIDER,1418- method: "thread/rollback",1419- detail: "Grok ACP sessions do not support provider-side rollback yet.",1420- });1421- });1573+ withThreadLock(1574+ threadId,1575+ Effect.gen(function* () {1576+ const ctx = yield* requireSession(threadId);
- apps/server/src/provider/acp/GrokAcpWorkflow.ts line 341Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +305,21 @@305+ return "completed";306+}307+308+function typedUsageFromCounts(input: {309+ readonly tokensUsed?: number;310+ readonly durationMs?: number;311+ readonly toolCallCount?: number;312+}): Record<string, unknown> | undefined {313+ if (314+ input.tokensUsed === undefined &&315+ input.durationMs === undefined &&316+ input.toolCallCount === undefined317+ ) {318+ return undefined;319+ }320+ return {321+ totalTokens: input.tokensUsed ?? 0,322+ ...(input.durationMs !== undefined ? { durationMs: input.durationMs } : {}),323+ ...(input.toolCallCount !== undefined ? { toolUses: input.toolCallCount } : {}),324+ };325+}
- apps/server/src/provider/Layers/GrokProvider.ts line 297OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -251,3 +294,4 @@251294 });252295 }253296297+ const hasAuthMaterial = yield* grokHasLocalAuthMaterial(environment);apps/server/src/provider/acp/GrokAcpToolUpdates.ts line 85OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +65,21 @@65+ }66+ return value;67+}68+69+/** Shrink cumulative Grok terminal payloads before they hit ingestion / NDJSON. */70+export function boundGrokToolCallForEvent(input: {71+ readonly toolCall: AcpToolCallState;72+ readonly rawPayload: unknown;73+}): { readonly toolCall: AcpToolCallState; readonly rawPayload: unknown } {74+ const serialized = JSON.stringify(input.toolCall.data) ?? "";75+ const rawSerialized = JSON.stringify(input.rawPayload) ?? "";76+ if (77+ serialized.length <= GROK_TOOL_CONTENT_CHAR_LIMIT &&78+ rawSerialized.length <= GROK_TOOL_CONTENT_CHAR_LIMIT79+ ) {80+ return input;81+ }82+ return {83+ toolCall: {84+ ...input.toolCall,85+ data: boundUnknown(input.toolCall.data) as Record<string, unknown>,apps/server/src/provider/acp/GrokAcpToolUpdates.ts lines 14 to 19OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1,19 @@1+import type { AcpToolCallState } from "./AcpRuntimeModel.ts";2+3+/** In-progress execute updates faster than this are dropped (#6556). */4+export const GROK_TOOL_UPDATE_MIN_INTERVAL_MS = 250;5+/** Keep the tail of cumulative terminal output so a progress bar still reads. */6+export const GROK_TOOL_CONTENT_CHAR_LIMIT = 8_192;7+8+export interface GrokToolUpdateGate {9+ fingerprint: string;10+ lastEmittedAt: number;11+}12+13+export function grokToolCallFingerprint(toolCall: AcpToolCallState): string {14+ const content = toolCall.data.content;15+ const contentLength =16+ typeof content === "string" ? content.length : JSON.stringify(content ?? "").length;17+ return [toolCall.toolCallId, toolCall.status ?? "", toolCall.title ?? "", contentLength].join(18+ "\u001f",19+ );apps/server/src/provider/Layers/GrokAdapter.ts line 1020Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -663,3 +780,14 @@663780 ),664781 { discard: true },665782 );783+ // Grok Build's private session channel. Claude maps workflow_progress784+ // onto task.*; Codex maps collabAgent/* the same way. Keep that785+ // seam: parse here, emit canonical events, never a third UI shape.786+ yield* Effect.forEach(787+ ["x.ai/session_notification", "_x.ai/session_notification"] as const,788+ (method) =>789+ acp.handleExtNotification(method, XAiSessionNotification, (params) =>790+ mapAcpCallbackFailure(791+ Effect.gen(function* () {792+ yield* logNative(input.threadId, method, params);793+ const ctx = sessions.get(input.threadId);
- apps/server/src/provider/Layers/GrokAdapter.ts lines 242 to 247OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -191,4 +228,20 @@191228 : "reject_once";192229 const option = request.options.find((entry) => entry.kind === kind);193- return option?.optionId.trim() || undefined;230+ if (option?.optionId.trim()) {231+ return option.optionId.trim();232+ }233+ // Grok often omits allow_always (#6502). Falling back to allow_once keeps234+ // the turn alive instead of answering the permission request as cancelled.235+ if (decision === "acceptForSession") {236+ const once = request.options.find((entry) => entry.kind === "allow_once");237+ return once?.optionId.trim() || undefined;238+ }239+ return undefined;240+}241+242+function selectPermissionOptionId(243+ request: EffectAcpSchema.RequestPermissionRequest,244+ decision: Exclude<ProviderApprovalDecision, "cancel">,245+): string | undefined {246+ return selectGrokPermissionOptionId(request, decision);194247 }apps/server/src/provider/Layers/GrokAdapter.ts lines 1036 to 1036OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -844,4 +1032,5 @@8441032 "session/update",8451033 );8461034 return;847- case "ToolCallUpdated":1035+ case "ToolCallUpdated": {1036+ const nowMs = Date.now();apps/server/src/provider/Layers/GrokAdapter.ts lines 1747 to 1747OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1422,0 +1727,21 @@1727+ force: true,1728+ })1729+ .pipe(1730+ Effect.mapError((error) =>1731+ mapAcpToAdapterError(PROVIDER, threadId, "_x.ai/rewind/execute", error),1732+ ),1733+ );1734+ const committedCtx = yield* requireSession(threadId);1735+ if (committedCtx.acpSessionId !== acpSessionId) {1736+ return yield* new ProviderAdapterRequestError({1737+ provider: PROVIDER,1738+ method: "_x.ai/rewind/execute",1739+ detail: "Grok session changed before rewind completed.",1740+ });1741+ }1742+ const executed = parseGrokRewindExecute(executePayload);1743+ if (!executed?.success) {1744+ return yield* new ProviderAdapterRequestError({1745+ provider: PROVIDER,1746+ method: "_x.ai/rewind/execute",1747+ detail: executed?.error ?? "Grok rewind did not succeed.",
- apps/server/src/provider/Layers/GrokProvider.ts line 143OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -116,10 +124,20 @@116124 return {117125 slug,118126 name: model.name.trim() || slug,119127 isCustom: false,120- capabilities: EMPTY_CAPABILITIES,128+ capabilities: grokDiscoveredModelCapabilities(meta),121129 };122130 })123131 .filter((model): model is ServerProviderModel => model !== undefined);124132 }125133134+const grokAuthFileCandidates = (135+ environment: NodeJS.ProcessEnv,136+ path: Path.Path["Service"],137+): ReadonlyArray<string> => {138+ const home =139+ environment.GROK_HOME?.trim() || environment.HOME?.trim() || environment.USERPROFILE?.trim();140+ if (!home) {141+ return [];142+ }143+ return [path.join(home, ".grok", "auth.json"), path.join(home, ".grok", "credentials.json")];
- apps/server/src/provider/Layers/GrokAdapter.ts line 2009OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1422,0 +1741,21 @@1741+ })1742+ .pipe(1743+ Effect.mapError((error) =>1744+ mapAcpToAdapterError(PROVIDER, threadId, "_x.ai/rewind/execute", error),1745+ ),1746+ );1747+ const committedCtx = yield* requireSession(threadId);1748+ if (committedCtx.acpSessionId !== acpSessionId) {1749+ return yield* new ProviderAdapterRequestError({1750+ provider: PROVIDER,1751+ method: "_x.ai/rewind/execute",1752+ detail: "Grok session changed before rewind completed.",1753+ });1754+ }1755+ const executed = parseGrokRewindExecute(executePayload);1756+ if (!executed?.success) {1757+ return yield* new ProviderAdapterRequestError({1758+ provider: PROVIDER,1759+ method: "_x.ai/rewind/execute",1760+ detail: "Grok rewind did not succeed.",1761+ ...(executed?.error ? { cause: executed.error } : {}),apps/server/src/provider/Layers/GrokAdapter.ts line 1110OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -888,3 +1104,7 @@8881104 ctx.notificationFiber = nf;8891105 sessions.set(input.threadId, ctx);8901106 sessionScopeTransferred = true;1107+ yield* Effect.forEach(pendingSessionNotifications, (pending) =>1108+ applySessionNotification(ctx, pending.method, pending.params),1109+ );1110+ pendingSessionNotifications.length = 0;apps/server/src/provider/acp/GrokAcpToolUpdates.ts line 42Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +2,21 @@2+3+/** In-progress execute updates faster than this are dropped (#6556). */4+export const GROK_TOOL_UPDATE_MIN_INTERVAL_MS = 250;5+/** Keep the tail of cumulative terminal output so a progress bar still reads. */6+export const GROK_TOOL_CONTENT_CHAR_LIMIT = 8_192;7+8+export interface GrokToolUpdateGate {9+ fingerprint: string;10+ lastEmittedAt: number;11+}12+13+export function grokToolCallFingerprint(toolCall: AcpToolCallState): string {14+ const data = JSON.stringify(toolCall.data) ?? "";15+ return [16+ toolCall.toolCallId,17+ toolCall.status ?? "",18+ toolCall.title ?? "",19+ toolCall.detail ?? "",20+ String(data.length),21+ data.slice(-128),22+ ].join("\u001f");
- apps/server/src/provider/Layers/GrokAdapter.ts line 1939Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1417,6 +1693,17 @@1417- provider: PROVIDER,1418- method: "thread/rollback",1419- detail: "Grok ACP sessions do not support provider-side rollback yet.",1420- });1693+ const updatedAt = yield* nowIso;1694+ ctx.promptsInFlight = 0;1695+ ctx.activeTurnId = undefined;1696+ const { activeTurnId: _activeTurnId, ...readySession } = ctx.session;1697+ ctx.session = {1698+ ...readySession,1699+ status: "ready",1700+ updatedAt,1701+ };14211702 });142217031704+ const rollbackThread: GrokAdapterShape["rollbackThread"] = (threadId, numTurns) =>1705+ withThreadLock(1706+ threadId,1707+ Effect.gen(function* () {1708+ const ctx = yield* requireSession(threadId);1709+ if (!Number.isInteger(numTurns) || numTurns < 1) {apps/server/src/provider/Layers/GrokAdapter.ts line 1116OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -888,3 +1110,7 @@8881110 ctx.notificationFiber = nf;8891111 sessions.set(input.threadId, ctx);8901112 sessionScopeTransferred = true;1113+ // Keep live notifications queued until every buffered startup1114+ // update has been applied. `sessions.set` would otherwise let a1115+ // later tick mutate workflow state mid-replay.1116+ for (;;) {
- apps/server/src/provider/acp/GrokAcpSupport.ts lines 409 to 418OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -93,0 +398,21 @@398+ | EffectAcpSchema.LoadSessionResponse399+ | EffectAcpSchema.NewSessionResponse400+ | EffectAcpSchema.ResumeSessionResponse,401+): number | undefined {402+ const currentModelId = sessionSetupResult.models?.currentModelId;403+ const current = sessionSetupResult.models?.availableModels.find(404+ (model) => model.modelId === currentModelId,405+ );406+ return parseGrokAcpModelMeta(current?._meta).totalContextTokens;407+}408+409+export function isGrokAcpAuthFailure(error: unknown): boolean {410+ const text = [411+ error instanceof Error ? `${error.name} ${error.message}` : "",412+ typeof error === "string" ? error : "",413+ String(error),414+ ].join(" ");415+ return /authenticat|unauthorized|not logged in|login required|no credentials|cached_token|xai\.api_key|401\b/i.test(416+ text,417+ );418+}
- apps/server/src/provider/Layers/GrokAdapter.ts line 1751OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1422,0 +1731,21 @@1731+ const pointsPayload = yield* ctx.acp1732+ .request("_x.ai/rewind/points", {1733+ sessionId: acpSessionId,1734+ })1735+ .pipe(1736+ Effect.mapError((error) =>1737+ mapAcpToAdapterError(PROVIDER, threadId, "_x.ai/rewind/points", error),1738+ ),1739+ );1740+ const liveCtx = yield* requireSession(threadId);1741+ if (liveCtx.acpSessionId !== acpSessionId) {1742+ return yield* new ProviderAdapterRequestError({1743+ provider: PROVIDER,1744+ method: "_x.ai/rewind/execute",1745+ detail: "Grok session changed before rewind completed.",1746+ });1747+ }1748+ const target = grokRewindTargetForTurnCount(1749+ parseGrokRewindPoints(pointsPayload),1750+ promptCount,1751+ );apps/server/src/provider/Layers/GrokAdapter.ts line 1421Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -948,7 +1185,18 @@9481185 const requestedTurnModelId = turnModelSelection?.model9491186 ? resolveGrokAcpBaseModelId(turnModelSelection.model)9501187 : undefined;951- const currentModelId = yield* applyGrokAcpModelSelection({1188+ const advertisedTurnEfforts = requestedTurnModelId1189+ ? (ctx.reasoningEffortMenus.get(requestedTurnModelId) ?? [])1190+ : ctx.currentModelId1191+ ? (ctx.reasoningEffortMenus.get(ctx.currentModelId) ?? [])1192+ : [];1193+ const turnSelection = yield* applyGrokAcpModelSelection({9521194 runtime: ctx.acp,9531195 currentModelId: ctx.currentModelId,1196+ availableModelIds: ctx.availableModelIds,9541197 requestedModelId: requestedTurnModelId,1198+ currentReasoningEffort: ctx.currentReasoningEffort,1199+ requestedReasoningEffort: requestedGrokReasoningEffort(1200+ turnModelSelection,1201+ advertisedTurnEfforts,1202+ ),
- @@ -24,3 +24,8 @@2424 color: "#d97757",2525 mark: ClaudeAI,2626 },27+ grok: {28+ label: "Grok Build",29+ color: "#8884d8",30+ mark: GrokIcon,31+ },
- apps/server/src/usage/usageTranscripts.ts lines 371 to 371OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -299,0 +351,21 @@351+ try {352+ parsed = JSON.parse(line);353+ } catch {354+ return null;355+ }356+ if (typeof parsed !== "object" || parsed === null) return null;357+ const record = parsed as Record<string, unknown>;358+ const params =359+ typeof record.params === "object" && record.params !== null360+ ? (record.params as Record<string, unknown>)361+ : record;362+ const update =363+ typeof params.update === "object" && params.update !== null364+ ? (params.update as Record<string, unknown>)365+ : params;366+ const tag = update.sessionUpdate ?? update.session_update;367+ if (tag !== "turn_completed" && tag !== "turnCompleted") return null;368+369+ const usageRaw = update.usage;370+ if (typeof usageRaw !== "object" || usageRaw === null) return null;371+ const usage = usageRaw as Record<string, unknown>;apps/server/src/usage/usageTranscripts.ts lines 422 to 422OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -299,0 +402,21 @@402+ reasoningTokens,403+ };404+ if (totalTokens(totals) === 0) return null;405+406+ const promptId =407+ (typeof update.prompt_id === "string" && update.prompt_id) ||408+ (typeof update.promptId === "string" && update.promptId) ||409+ "";410+ const sessionId =411+ (typeof params.sessionId === "string" && params.sessionId) ||412+ (typeof params.session_id === "string" && params.session_id) ||413+ "";414+415+ return {416+ provider: "grok",417+ timestampMs,418+ model: grokModelId(usage),419+ sessionId,420+ totals,421+ reportedCostUsd: grokCompleteCostUsd(usage),422+ dedupeKey: promptId.length > 0 ? `${sessionId}:${promptId}` : sessionId || null,apps/server/src/provider/Layers/GrokAdapter.ts lines 1939 to 1939OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1422,0 +1919,21 @@1919+ const acpSessionId = ctx.acpSessionId;1920+ const pointsPayload = yield* ctx.acp1921+ .request("_x.ai/rewind/points", {1922+ sessionId: acpSessionId,1923+ })1924+ .pipe(1925+ Effect.mapError((error) =>1926+ mapAcpToAdapterError(PROVIDER, threadId, "_x.ai/rewind/points", error),1927+ ),1928+ );1929+ const liveCtx = yield* requireSession(threadId);1930+ if (liveCtx.acpSessionId !== acpSessionId) {1931+ return yield* new ProviderAdapterRequestError({1932+ provider: PROVIDER,1933+ method: "_x.ai/rewind/execute",1934+ detail: "Grok session changed before rewind completed.",1935+ });1936+ }1937+ const rewindPoints = parseGrokRewindPoints(pointsPayload);1938+ const target = grokRewindTargetKeepingPromptCount(rewindPoints, keepPromptCount);1939+ if (!target && rewindPoints.length === 0) {@@ -129,3 +130,5 @@129130 continue;130131 }131132133+ if (provider === "grok") {134+ if (!mightCarryUsage(line, provider)) continue;
Sign in to join this conversation.


Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID:
219cc4f4-51d5-4477-a535-cddbdffedc68You can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share