Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
feat: add persistent Grok Build support (#745)
Gustavo Ye95e0415d03c9
diff --git a/src/daemon/agent-driver/src/adapters/grok/acp-lane.test.ts b/src/daemon/agent-driver/src/adapters/grok/acp-lane.test.tsnew file mode 100644index 000000000..7c87b024b--- /dev/null+++ b/src/daemon/agent-driver/src/adapters/grok/acp-lane.test.ts@@ -0,0 +1,958 @@+import { EventEmitter } from "node:events";+import { mkdtemp, rm } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { PassThrough } from "node:stream";+import { beforeEach, describe, expect, it, vi } from "vitest";+import type { AdapterEvent, SpawnedProcessHandle } from "../../internal/adapter.js";+import { createAgentDriverSdk } from "../../sdk.js";+import { fakeLaunchContext } from "../../testing/adapter-fixture.js";+import { createFakeAgentDriverHost } from "../../testing/fake-host.js";+import { GrokAcpLane } from "./acp-lane.js";+import { GrokDriver } from "./index.js";++const killProcessTree = vi.hoisted(() => vi.fn(async () => {}));++vi.mock("../../internal/killTree.js", async () => {+ const actual = await vi.importActual<typeof import("../../internal/killTree.js")>("../../internal/killTree.js");+ return { ...actual, killProcessTree };+});++type RpcMessage = Record<string, unknown>;+type FakeProcess = SpawnedProcessHandle & {+ stdout: PassThrough;+ stderr: PassThrough;+ stdin: PassThrough;+ emit(event: string, ...args: unknown[]): boolean;+};++function fakeProcess(onMessage: (process: FakeProcess, message: RpcMessage) => void): FakeProcess {+ const process = Object.assign(new EventEmitter(), {+ stdout: new PassThrough(),+ stderr: new PassThrough(),+ stdin: new PassThrough(),+ pid: undefined,+ exitCode: null,+ signalCode: null,+ kill: vi.fn(() => true),+ }) as unknown as FakeProcess;+ let buffer = "";+ process.stdin.on("data", (chunk) => {+ buffer += chunk.toString();+ const lines = buffer.split("\n");+ buffer = lines.pop() ?? "";+ for (const line of lines) {+ if (line.trim()) onMessage(process, JSON.parse(line) as RpcMessage);+ }+ });+ return process;+}++function send(process: FakeProcess, message: RpcMessage): void {+ process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", ...message })}\n`);+}++function respond(process: FakeProcess, request: RpcMessage, result: unknown): void {+ send(process, { id: request.id, result });+}++function fail(process: FakeProcess, request: RpcMessage, message: string, code = -32000): void {+ send(process, { id: request.id, error: { code, message } });+}++const modelState = {+ currentModelId: "grok-4.6",+ availableModels: [{+ modelId: "grok-4.6",+ name: "Grok 4.6",+ _meta: {+ supportsReasoningEffort: true,+ reasoningEffort: "high",+ reasoningEfforts: ["xhigh", "high", "medium", "low"],+ },+ }],+};++function context(overrides: Record<string, unknown> = {}) {+ return fakeLaunchContext("grok", "/tmp/grok-acp-test", {+ config: { runtimeConfig: { model: { kind: "default" } } },+ ...overrides,+ });+}++function eventsFrom(lane: GrokAcpLane): AdapterEvent[] {+ const events: AdapterEvent[] = [];+ lane.on("runtime_event", (event) => events.push(event));+ lane.on("error", () => {});+ return events;+}++function installServer(options: {+ sessionId?: string;+ loadError?: string;+ authError?: string;+ replayBeforeSessionResponse?: boolean;+ omitLoadSessionId?: boolean;+ responseSessionId?: string;+ billingError?: string | { message: string; code: number };+ authMethods?: Array<{ id: string }>;+ initializeResult?: RpcMessage;+ sessionResult?: unknown;+ setModelError?: string;+ onSessionResponse?: () => void;+} = {}) {+ const messages: RpcMessage[] = [];+ const prompts: RpcMessage[] = [];+ const sessionId = options.sessionId ?? "grok-session";+ const process = fakeProcess((proc, message) => {+ messages.push(message);+ switch (message.method) {+ case "initialize":+ respond(proc, message, options.initializeResult ?? {+ protocolVersion: 1,+ agentCapabilities: { loadSession: true },+ authMethods: options.authMethods ?? [{ id: "cached_token" }, { id: "grok.com" }],+ _meta: { modelState },+ });+ break;+ case "authenticate":+ if (options.authError) fail(proc, message, options.authError);+ else respond(proc, message, {});+ break;+ case "session/new":+ case "session/load":+ if (options.loadError && message.method === "session/load") {+ fail(proc, message, options.loadError);+ break;+ }+ if (options.replayBeforeSessionResponse) {+ send(proc, {+ method: "session/update",+ params: {+ sessionId,+ _meta: { isReplay: true },+ update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text: "must not replay" } },+ },+ });+ send(proc, {+ method: "_x.ai/session/update",+ params: { sessionId, update: { sessionUpdate: "turn_completed" } },+ });+ }+ respond(proc, message, options.sessionResult ?? {+ ...(message.method === "session/load" && options.omitLoadSessionId+ ? {}+ : { sessionId: options.responseSessionId ?? sessionId }),+ models: modelState,+ });+ options.onSessionResponse?.();+ break;+ case "_x.ai/billing":+ if (options.billingError) {+ const failure = typeof options.billingError === "string"+ ? { message: options.billingError, code: -32000 }+ : options.billingError;+ fail(proc, message, failure.message, failure.code);+ }+ else respond(proc, message, {+ subscriptionTier: "SuperGrok",+ config: {+ currentPeriod: {+ type: "USAGE_PERIOD_TYPE_WEEKLY",+ creditUsagePercent: 25,+ },+ },+ });+ break;+ case "session/set_model":+ if (options.setModelError) fail(proc, message, options.setModelError);+ else respond(proc, message, {});+ break;+ case "session/close":+ respond(proc, message, {});+ break;+ case "session/prompt":+ prompts.push(message);+ break;+ }+ });+ return { process, messages, prompts };+}++describe("Grok ACP persistent lane", () => {+ beforeEach(() => {+ killProcessTree.mockClear();+ });+ it("creates one session, rejects busy input, maps events, and grants active allow-once", async () => {+ const server = installServer({ replayBeforeSessionResponse: true });+ const raw = vi.fn();+ const lane = new GrokAcpLane({ spawn: async () => ({ process: server.process }) }, context(), {+ onRawStdoutLine: raw,+ });+ const events = eventsFrom(lane);++ await expect(lane.start({ text: "hello", terminalOwner: "root-owner" })).resolves.toEqual({+ ok: true,+ acceptedAs: "prompt",+ receipt: "root-owner",+ });+ expect(lane.currentSessionId).toBe("grok-session");+ expect(server.messages.map((message) => message.method).filter(Boolean)).toEqual([+ "initialize",+ "authenticate",+ "_x.ai/billing",+ "session/new",+ "session/prompt",+ ]);+ expect(server.messages.find((message) => message.method === "session/new")?.params).toMatchObject({+ _meta: { yoloMode: true },+ });+ expect(JSON.stringify(events)).not.toContain("must not replay");+ expect(events.filter((event) => event.kind === "turn_end")).toHaveLength(0);+ expect(raw).toHaveBeenCalled();++ await expect(lane.send({ text: "busy", mode: "busy" })).resolves.toMatchObject({+ ok: false,+ reason: "runtime_busy",+ });+ expect(server.prompts).toHaveLength(1);+ expect(server.messages.some((message) => String(message.method).includes("interject"))).toBe(false);++ send(server.process, {+ method: "session/request_permission",+ id: "permission-1",+ params: {+ sessionId: "grok-session",+ options: [{ optionId: "deny", kind: "reject_once" }, { optionId: "allow", kind: "allow_once" }],+ },+ });+ expect(server.messages.at(-1)).toEqual({+ jsonrpc: "2.0",+ id: "permission-1",+ result: { outcome: { outcome: "selected", optionId: "allow" } },+ });++ send(server.process, {+ method: "session/update",+ params: {+ sessionId: "grok-session",+ update: { sessionUpdate: "agent_thought_chunk", content: { type: "text", text: "reason" } },+ },+ });+ send(server.process, {+ method: "session/update",+ params: {+ sessionId: "grok-session",+ update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text: "answer" } },+ },+ });+ send(server.process, {+ method: "session/update",+ params: {+ sessionId: "grok-session",+ update: { sessionUpdate: "plan", entries: [] },+ },+ });+ send(server.process, {+ method: "session/update",+ params: {+ sessionId: "grok-session",+ update: { sessionUpdate: "tool_call", toolCallId: "tool-1", title: "Read", rawInput: { path: "README.md" } },+ },+ });+ send(server.process, {+ method: "session/update",+ params: {+ sessionId: "grok-session",+ update: { sessionUpdate: "tool_call_update", toolCallId: "tool-1", title: "Read", status: "completed" },+ },+ });+ expect(events).toEqual(expect.arrayContaining([+ { kind: "assistant_reasoning_delta", text: "reason" },+ { kind: "assistant_message_delta", text: "answer" },+ { kind: "internal_progress", source: "grok.acp", itemType: "plan" },+ { kind: "tool_call", callId: "tool-1", name: "Read", input: { path: "README.md" } },+ { kind: "tool_output", callId: "tool-1", name: "Read" },+ ]));++ respond(server.process, server.prompts[0]!, { stopReason: "end_turn" });+ expect(events.filter((event) => event.kind === "turn_end")).toEqual([{+ kind: "turn_end",+ sessionId: "grok-session",+ turnOwner: "root-owner",+ }]);+ });++ it("loads the exact session, gates replay, and only the matching prompt response terminates", async () => {+ const server = installServer({+ sessionId: "saved-session",+ replayBeforeSessionResponse: true,+ omitLoadSessionId: true,+ });+ const lane = new GrokAcpLane(+ { spawn: async () => ({ process: server.process }) },+ context({+ config: {+ sessionId: "saved-session",+ runtimeConfig: { model: { kind: "named", name: "grok-4.6" }, reasoningEffort: "xhigh" },+ },+ }),+ );+ const events = eventsFrom(lane);++ await expect(lane.start({ text: "resume", sessionId: "saved-session" })).resolves.toMatchObject({ ok: true });+ expect(server.messages.map((message) => message.method).filter(Boolean)).toEqual([+ "initialize",+ "authenticate",+ "_x.ai/billing",+ "session/load",+ "session/set_model",+ "session/prompt",+ ]);+ expect(server.messages.find((message) => message.method === "session/load")?.params).toMatchObject({+ sessionId: "saved-session",+ });+ expect(server.messages.find((message) => message.method === "session/set_model")?.params).toEqual({+ sessionId: "saved-session",+ modelId: "grok-4.6",+ _meta: { reasoningEffort: "xhigh" },+ });+ expect(JSON.stringify(events)).not.toContain("must not replay");++ send(server.process, { id: 999, result: { stopReason: "end_turn" } });+ send(server.process, {+ method: "_x.ai/session/update",+ params: { sessionId: "saved-session", update: { sessionUpdate: "turn_completed" } },+ });+ expect(events.filter((event) => event.kind === "turn_end")).toHaveLength(0);++ respond(server.process, server.prompts[0]!, { stopReason: "end_turn" });+ expect(events.filter((event) => event.kind === "turn_end")).toHaveLength(1);+ await expect(lane.send({ text: "second", mode: "idle", terminalOwner: "second-owner" })).resolves.toEqual({+ ok: true,+ acceptedAs: "prompt",+ receipt: "second-owner",+ });+ respond(server.process, server.prompts[0]!, { stopReason: "end_turn" });+ expect(events.filter((event) => event.kind === "turn_end")).toHaveLength(1);+ respond(server.process, server.prompts[1]!, { stopReason: "end_turn" });+ expect(events.filter((event) => event.kind === "turn_end")).toHaveLength(2);+ });++ it("cancels only an active prompt and closes the session before killing the process", async () => {+ const server = installServer();+ const lane = new GrokAcpLane({ spawn: async () => ({ process: server.process }) }, context());+ eventsFrom(lane);++ await lane.start({ text: "interrupt me" });+ await expect(lane.interrupt({ requestId: "interrupt-1" })).resolves.toBe(true);+ expect(server.messages.at(-1)).toMatchObject({+ method: "session/cancel",+ params: { sessionId: "grok-session" },+ });+ respond(server.process, server.prompts[0]!, { stopReason: "cancelled" });+ await expect(lane.interrupt({ requestId: "interrupt-2" })).resolves.toBe(false);++ await lane.stop({ reason: "shutdown", forceAfterMs: 10 });+ expect(server.messages.map((message) => message.method).filter(Boolean)).toContain("session/close");+ expect(server.process.kill).toHaveBeenCalledTimes(1);+ });++ it("returns reset-required for a missing saved session and gives bounded auth guidance", async () => {+ const missing = installServer({ sessionId: "missing", loadError: "Session not found" });+ const missingLane = new GrokAcpLane(+ { spawn: async () => ({ process: missing.process }) },+ context({ config: { sessionId: "missing", runtimeConfig: { model: { kind: "default" } } } }),+ );+ eventsFrom(missingLane);+ await expect(missingLane.start({ text: "resume", sessionId: "missing" })).resolves.toEqual({+ ok: false,+ reason: "reset_required",+ error: "Grok session could not be loaded; reset this agent to start a new session",+ });+ expect(missing.messages.some((message) => message.method === "session/new")).toBe(false);++ const auth = installServer({ authError: "token=secret [email protected]" });+ const authLane = new GrokAcpLane({ spawn: async () => ({ process: auth.process }) }, context());+ eventsFrom(authLane);+ await expect(authLane.start({ text: "auth" })).resolves.toEqual({+ ok: false,+ reason: "authentication",+ error: "Grok authentication failed; run `grok login` and retry",+ });+ expect(auth.process.kill).toHaveBeenCalledTimes(1);++ const loginRequired = installServer({ authMethods: [{ id: "grok.com" }] });+ const loginRequiredLane = new GrokAcpLane(+ { spawn: async () => ({ process: loginRequired.process }) },+ context(),+ );+ eventsFrom(loginRequiredLane);+ await expect(loginRequiredLane.start({ text: "auth" })).resolves.toEqual({+ ok: false,+ reason: "authentication",+ error: "Grok authentication failed; run `grok login` and retry",+ });+ expect(loginRequired.messages.some((message) => message.method === "authenticate")).toBe(false);+ expect(loginRequired.process.kill).toHaveBeenCalledTimes(1);+ });++ it("requires a loaded session response to preserve the saved session identity", async () => {+ const server = installServer({ sessionId: "saved-session", responseSessionId: "other-session" });+ const lane = new GrokAcpLane(+ { spawn: async () => ({ process: server.process }) },+ context({ config: { sessionId: "saved-session", runtimeConfig: { model: { kind: "default" } } } }),+ );+ eventsFrom(lane);+ await expect(lane.start({ text: "resume", sessionId: "saved-session" })).resolves.toEqual({+ ok: false,+ reason: "reset_required",+ error: "Grok ACP loaded a different session; reset this agent before continuing",+ });+ expect(server.messages.some((message) => message.method === "session/prompt")).toBe(false);+ });++ it("drops replayed text, tools, and terminal updates even after the lane is ready", async () => {+ const server = installServer();+ const lane = new GrokAcpLane({ spawn: async () => ({ process: server.process }) }, context());+ const events = eventsFrom(lane);+ await lane.start({ text: "live" });++ for (const update of [+ { sessionUpdate: "agent_message_chunk", content: { type: "text", text: "late replay" } },+ { sessionUpdate: "tool_call", toolCallId: "replayed-tool", title: "Replay", rawInput: {} },+ ]) {+ send(server.process, {+ method: "session/update",+ params: { sessionId: "grok-session", _meta: { isReplay: true }, update },+ });+ }+ send(server.process, {+ method: "_x.ai/session/update",+ params: {+ sessionId: "grok-session",+ _meta: { isReplay: true },+ update: { sessionUpdate: "turn_completed", promptId: "alook-4", usage: { inputTokens: 9 } },+ },+ });++ expect(JSON.stringify(events)).not.toContain("late replay");+ expect(JSON.stringify(events)).not.toContain("replayed-tool");+ expect(events.filter((event) => event.kind === "turn_end")).toHaveLength(0);+ expect(events.filter((event) => event.kind === "telemetry" && event.name === "token_usage")).toHaveLength(0);+ });++ it("prefers prompt-response usage over a same-prompt private fallback and emits it once", async () => {+ const server = installServer();+ const lane = new GrokAcpLane({ spawn: async () => ({ process: server.process }) }, context());+ const events = eventsFrom(lane);+ await lane.start({ text: "usage" });+ const prompt = server.prompts[0]!;+ const promptId = (prompt.params as { _meta: { promptId: string } })._meta.promptId;++ send(server.process, {+ method: "_x.ai/session/update",+ params: {+ sessionId: "grok-session",+ update: {+ sessionUpdate: "turn_completed",+ promptId,+ usage: { inputTokens: 999, outputTokens: 999 },+ },+ },+ });+ respond(server.process, prompt, {+ stopReason: "end_turn",+ _meta: {+ usage: {+ inputTokens: 100,+ outputTokens: 20,+ cachedReadTokens: 10,+ reasoningTokens: 5,+ },+ },+ });+ send(server.process, {+ method: "_x.ai/session/update",+ params: {+ sessionId: "grok-session",+ update: { sessionUpdate: "turn_completed", promptId, usage: { inputTokens: 777 } },+ },+ });++ expect(events.filter((event) => event.kind === "telemetry" && event.name === "token_usage")).toEqual([{+ kind: "telemetry",+ name: "token_usage",+ source: "grok.acp",+ usage: { input: 90, output: 20, cache: 10 },+ }]);+ });++ it("uses same-prompt private usage only as fallback and keeps billing failures nonfatal", async () => {+ const server = installServer({ billingError: "billing unavailable" });+ const lane = new GrokAcpLane({ spawn: async () => ({ process: server.process }) }, context());+ const events = eventsFrom(lane);+ await lane.start({ text: "fallback" });+ const prompt = server.prompts[0]!;+ const promptId = (prompt.params as { _meta: { promptId: string } })._meta.promptId;+ send(server.process, {+ method: "_x.ai/session/update",+ params: {+ sessionId: "grok-session",+ update: {+ sessionUpdate: "turn_completed",+ promptId,+ usage: { inputTokens: 30, outputTokens: 8, cachedReadTokens: 4, reasoningTokens: 2 },+ },+ },+ });+ respond(server.process, prompt, { stopReason: "end_turn" });+ await vi.waitFor(() => expect(events.some(+ (event) => event.kind === "telemetry" && event.name === "rate_limits" && event.quota.status === "error",+ )).toBe(true));+ expect(events.filter((event) => event.kind === "telemetry" && event.name === "token_usage")).toEqual([{+ kind: "telemetry",+ name: "token_usage",+ source: "grok.acp",+ usage: { input: 26, output: 8, cache: 4 },+ }]);+ expect(events.filter((event) => event.kind === "error")).toHaveLength(0);+ expect(events.filter((event) => event.kind === "turn_end")).toHaveLength(1);+ });++ it("enforces lifecycle and live-settings boundaries", async () => {+ const server = installServer();+ const lane = new GrokAcpLane({ spawn: async () => ({ process: server.process }) }, context());+ eventsFrom(lane);++ await expect(lane.send({ text: "early", mode: "idle" })).resolves.toEqual({+ ok: false,+ reason: "closed",+ });+ await expect(lane.updateSettings({ reasoningEffort: "low" })).resolves.toMatchObject({+ status: "failed",+ error: { code: "settings_session_unavailable", retryable: true },+ });+ await lane.start({ text: "settings" });+ await expect(lane.start({ text: "again" })).resolves.toMatchObject({+ ok: false,+ reason: "runtime_error",+ });+ await expect(lane.updateSettings({ reasoningEffort: "low" })).resolves.toMatchObject({+ status: "failed",+ error: { code: "settings_runtime_busy", retryable: true },+ });+ respond(server.process, server.prompts[0]!, { stopReason: "end_turn" });+ await expect(lane.updateSettings({ reasoningEffort: "max" })).resolves.toMatchObject({+ status: "failed",+ error: { code: "unsupported_reasoning_effort" },+ });+ await expect(lane.updateSettings({ reasoningEffort: "low" })).resolves.toEqual({ status: "applied" });+ expect(server.messages.at(-1)).toMatchObject({+ method: "session/set_model",+ params: { sessionId: "grok-session", modelId: "grok-4.6", _meta: { reasoningEffort: "low" } },+ });++ const noCatalog = installServer({+ initializeResult: {+ protocolVersion: 1,+ agentCapabilities: { loadSession: true },+ authMethods: [{ id: "cached_token" }],+ },+ sessionResult: { sessionId: "grok-session" },+ });+ const noCatalogLane = new GrokAcpLane(+ { spawn: async () => ({ process: noCatalog.process }) },+ context(),+ );+ eventsFrom(noCatalogLane);+ await noCatalogLane.start({ text: "no catalog" });+ respond(noCatalog.process, noCatalog.prompts[0]!, { stopReason: "end_turn" });+ await expect(noCatalogLane.updateSettings({ reasoningEffort: null })).resolves.toMatchObject({+ status: "failed",+ error: { code: "settings_model_unavailable" },+ });++ const rejected = installServer({ setModelError: "not accepted" });+ const rejectedLane = new GrokAcpLane(+ { spawn: async () => ({ process: rejected.process }) },+ context(),+ );+ eventsFrom(rejectedLane);+ await rejectedLane.start({ text: "reject settings" });+ respond(rejected.process, rejected.prompts[0]!, { stopReason: "end_turn" });+ await expect(rejectedLane.updateSettings({ reasoningEffort: "high" })).resolves.toMatchObject({+ status: "failed",+ error: { code: "settings_update_failed", retryable: true },+ });+ });++ it.each([+ {+ name: "protocol",+ initializeResult: {+ protocolVersion: 2,+ agentCapabilities: { loadSession: true },+ authMethods: [{ id: "cached_token" }],+ },+ error: "protocol version 1",+ },+ {+ name: "load capability",+ initializeResult: {+ protocolVersion: 1,+ agentCapabilities: { loadSession: false },+ authMethods: [{ id: "cached_token" }],+ },+ error: "persistent session loading",+ },+ {+ name: "cached authentication",+ initializeResult: {+ protocolVersion: 1,+ agentCapabilities: { loadSession: true },+ authMethods: [{ id: "other" }],+ },+ error: "cached-token authentication",+ },+ ])("fails the strict handshake without $name", async ({ initializeResult, error }) => {+ const server = installServer({ initializeResult });+ const lane = new GrokAcpLane({ spawn: async () => ({ process: server.process }) }, context());+ eventsFrom(lane);+ await expect(lane.start({ text: "strict" })).resolves.toMatchObject({+ ok: false,+ reason: "incompatible_configuration",+ error: expect.stringContaining(error),+ });+ });++ it("rejects malformed session and configured model responses", async () => {+ const loadFailure = installServer({ loadError: "Permission denied" });+ const loadLane = new GrokAcpLane(+ { spawn: async () => ({ process: loadFailure.process }) },+ context({ config: { sessionId: "saved", runtimeConfig: { model: { kind: "default" } } } }),+ );+ eventsFrom(loadLane);+ await expect(loadLane.start({ text: "load", sessionId: "saved" })).rejects.toThrow("Permission denied");++ for (const sessionResult of ["invalid", {}, { sessionId: " " }]) {+ const server = installServer({ sessionResult });+ const lane = new GrokAcpLane({ spawn: async () => ({ process: server.process }) }, context());+ eventsFrom(lane);+ await expect(lane.start({ text: "bad session" })).rejects.toThrow(/valid session/);+ }++ const invalidLoaded = installServer({ sessionResult: { sessionId: " " } });+ const invalidLoadedLane = new GrokAcpLane(+ { spawn: async () => ({ process: invalidLoaded.process }) },+ context({ config: { sessionId: "saved", runtimeConfig: { model: { kind: "default" } } } }),+ );+ eventsFrom(invalidLoadedLane);+ await expect(invalidLoadedLane.start({ text: "bad load", sessionId: "saved" }))+ .rejects.toThrow("invalid session id");++ const unavailableModel = installServer();+ const unavailableModelLane = new GrokAcpLane(+ { spawn: async () => ({ process: unavailableModel.process }) },+ context({ config: { runtimeConfig: { model: { kind: "named", name: "missing-model" } } } }),+ );+ eventsFrom(unavailableModelLane);+ await expect(unavailableModelLane.start({ text: "model" })).resolves.toMatchObject({+ ok: false,+ reason: "incompatible_configuration",+ error: expect.stringContaining("model is unavailable"),+ });++ const unavailableEffort = installServer();+ const unavailableEffortLane = new GrokAcpLane(+ { spawn: async () => ({ process: unavailableEffort.process }) },+ context({ config: { runtimeConfig: { model: { kind: "default" }, reasoningEffort: "max" } } }),+ );+ eventsFrom(unavailableEffortLane);+ await expect(unavailableEffortLane.start({ text: "effort" })).resolves.toMatchObject({+ ok: false,+ reason: "incompatible_configuration",+ error: expect.stringContaining("reasoning effort is unavailable"),+ });+ });++ it("settles malformed and failed prompt responses without leaking ownership", async () => {+ const server = installServer();+ const lane = new GrokAcpLane({ spawn: async () => ({ process: server.process }) }, context());+ const events = eventsFrom(lane);+ await lane.start({ text: "first" });++ send(server.process, { id: server.prompts[0]!.id, error: {} });+ await expect(lane.send({ text: "second", mode: "idle" })).resolves.toMatchObject({ ok: true });+ send(server.process, { id: server.prompts[1]!.id });+ await expect(lane.send({ text: "third", mode: "idle" })).resolves.toMatchObject({ ok: true });+ respond(server.process, server.prompts[2]!, { stopReason: "vendor_stop" });++ expect(events.filter((event) => event.kind === "error")).toEqual([+ expect.objectContaining({ code: "grok.rpc_error", message: "Grok ACP request failed" }),+ expect.objectContaining({ code: "grok.invalid_response" }),+ expect.objectContaining({ code: "grok.invalid_stop_reason" }),+ ]);+ expect(events.filter((event) => event.kind === "turn_end")).toHaveLength(3);+ send(server.process, { id: "unknown", result: {} });+ });++ it("diagnoses protocol extensions, unsafe updates, and permission fences", async () => {+ const server = installServer();+ const lane = new GrokAcpLane({ spawn: async () => ({ process: server.process }) }, context());+ const events = eventsFrom(lane);+ const stderr: string[] = [];+ lane.on("stderr", (text) => stderr.push(text));+ await lane.start({ text: "protocol" });++ send(server.process, { id: "client-request", method: "terminal_create", params: {} });+ send(server.process, { method: "vendor/extension", params: {} });+ send(server.process, { method: "secret=value", params: {} });+ send(server.process, {+ id: "permission-denied",+ method: "session/request_permission",+ params: { sessionId: "other", options: [{ optionId: "always", kind: "allow_always" }] },+ });+ send(server.process, { method: "_x.ai/models/update", params: modelState });+ const update = (sessionId: string, body: RpcMessage) => send(server.process, {+ method: "session/update",+ params: { sessionId, update: body },+ });+ update("other", { sessionUpdate: "agent_message_chunk", content: { type: "text", text: "hidden" } });+ update("grok-session", { sessionUpdate: "user_message_chunk", content: { type: "text", text: "echo" } });+ update("grok-session", { sessionUpdate: "tool_call", toolCallId: 7, title: "bad" });+ update("grok-session", { sessionUpdate: "current_model_update", model_id: "grok-next" });+ update("grok-session", { sessionUpdate: "vendor_secret" });+ server.process.stderr.write(" warning from grok \n");++ expect(server.messages).toContainEqual({+ jsonrpc: "2.0",+ id: "client-request",+ error: { code: -32601, message: "Unsupported Grok ACP client request" },+ });+ expect(server.messages).toContainEqual({+ jsonrpc: "2.0",+ id: "permission-denied",+ result: { outcome: { outcome: "cancelled" } },+ });+ expect(stderr).toEqual(["warning from grok"]);++ respond(server.process, server.prompts[0]!, { stopReason: "end_turn" });+ update("grok-session", { sessionUpdate: "plan" });+ expect(events).toEqual(expect.arrayContaining([+ expect.objectContaining({ kind: "runtime_diagnostic", message: expect.stringContaining("terminal_create") }),+ expect.objectContaining({ kind: "runtime_diagnostic", message: expect.stringContaining("unknown") }),+ expect.objectContaining({ kind: "runtime_diagnostic", message: expect.stringContaining("different session") }),+ expect.objectContaining({ kind: "runtime_diagnostic", message: expect.stringContaining("without an active prompt") }),+ ]));+ expect(JSON.stringify(events)).not.toContain("secret=value");+ expect(JSON.stringify(events)).not.toContain("hidden");+ });++ it.each([+ { code: -32601, expected: "unavailable" },+ { code: 401, expected: "unauthorized" },+ ])("classifies billing RPC error $code as $expected", async ({ code, expected }) => {+ const server = installServer({ billingError: { message: "billing rejected", code } });+ const lane = new GrokAcpLane({ spawn: async () => ({ process: server.process }) }, context());+ const events = eventsFrom(lane);+ await lane.start({ text: "billing" });+ await vi.waitFor(() => expect(events).toContainEqual(expect.objectContaining({+ kind: "telemetry",+ name: "rate_limits",+ quota: expect.objectContaining({ status: "error", code: expected, retryable: false }),+ })));+ });++ it("fails closed on malformed transport and cleans process failures", async () => {+ const timeoutProcess = fakeProcess(() => {});+ const timeoutLane = new GrokAcpLane(+ { spawn: async () => ({ process: timeoutProcess }) },+ context(),+ { handshakeTimeoutMs: 5 },+ );+ eventsFrom(timeoutLane);+ await expect(timeoutLane.start({ text: "timeout" })).rejects.toThrow("initialize timed out");++ const unwritable = fakeProcess(() => {});+ unwritable.stdin.end();+ const unwritableLane = new GrokAcpLane({ spawn: async () => ({ process: unwritable }) }, context());+ eventsFrom(unwritableLane);+ await expect(unwritableLane.start({ text: "write" })).rejects.toThrow("stdin is not writable");++ const omittedResult = fakeProcess((process, message) => {+ if (message.method === "initialize") send(process, { id: message.id });+ });+ const omittedResultLane = new GrokAcpLane(+ { spawn: async () => ({ process: omittedResult }) },+ context(),+ );+ eventsFrom(omittedResultLane);+ await expect(omittedResultLane.start({ text: "omitted result" })).rejects.toThrow("response omitted result");++ let promptWriteServer!: ReturnType<typeof installServer>;+ promptWriteServer = installServer({ onSessionResponse: () => promptWriteServer.process.stdin.end() });+ const promptWriteLane = new GrokAcpLane(+ { spawn: async () => ({ process: promptWriteServer.process }) },+ context(),+ );+ eventsFrom(promptWriteLane);+ await expect(promptWriteLane.start({ text: "prompt write" })).rejects.toThrow("stdin is not writable");++ const server = installServer();+ const lane = new GrokAcpLane({ spawn: async () => ({ process: server.process }) }, context());+ const errors: Error[] = [];+ const exits: unknown[] = [];+ const events = eventsFrom(lane);+ lane.on("error", (error) => errors.push(error instanceof Error ? error : new Error(String(error))));+ lane.on("exit", (value) => exits.push(value));+ await lane.start({ text: "runtime" });+ send(server.process, {+ method: "session/update",+ params: {+ sessionId: "grok-session",+ update: { sessionUpdate: "tool_call", toolCallId: "open", title: "Open", rawInput: {} },+ },+ });+ server.process.emit("error", new Error("EIO"));+ server.process.emit("error", new Error("duplicate"));+ await vi.waitFor(() => expect(exits).toEqual([{ code: null, signal: null, reason: "runtime_exit" }]));+ expect(errors).toEqual([new Error("EIO")]);+ expect(events).toContainEqual({ kind: "tool_output", callId: "open", name: "Open" });+ await vi.waitFor(() => expect(server.process.kill).toHaveBeenCalledOnce());++ const startupMessages: RpcMessage[] = [];+ const startup = fakeProcess((_process, message) => startupMessages.push(message));+ const startupLane = new GrokAcpLane(+ { spawn: async () => ({ process: startup }) },+ context(),+ { handshakeTimeoutMs: 1_000 },+ );+ const startupErrors: Error[] = [];+ startupLane.on("runtime_event", () => {});+ startupLane.on("error", (error) => startupErrors.push(error instanceof Error ? error : new Error(String(error))));+ const starting = startupLane.start({ text: "startup" });+ await vi.waitFor(() => expect(startupMessages.map((message) => message.method)).toEqual(["initialize"]));+ startup.emit("error", new Error("startup EIO"));+ await expect(starting).rejects.toThrow("startup EIO");+ expect(startupErrors).toEqual([new Error("startup EIO")]);++ const exited = installServer();+ const exitedLane = new GrokAcpLane({ spawn: async () => ({ process: exited.process }) }, context());+ const exitedEvents = eventsFrom(exitedLane);+ const exitedSignals: unknown[] = [];+ exitedLane.on("exit", (value) => exitedSignals.push(value));+ await exitedLane.start({ text: "exit" });+ send(exited.process, {+ method: "session/update",+ params: {+ sessionId: "grok-session",+ update: { sessionUpdate: "tool_call", toolCallId: "exit-tool", title: "Exit", rawInput: {} },+ },+ });+ exited.process.emit("exit", 17, null);+ expect(exitedSignals).toEqual([{ code: 17, signal: null, reason: "runtime_exit" }]);+ expect(exitedEvents).toContainEqual({ kind: "tool_output", callId: "exit-tool", name: "Exit" });+ });++ it("covers stop races, protocol failures, close fallback, and detached cleanup", async () => {+ let releaseSpawn!: (value: { process: FakeProcess }) => void;+ const delayedProcess = fakeProcess(() => {});+ const delayedLane = new GrokAcpLane({+ spawn: () => new Promise((resolve) => { releaseSpawn = resolve; }),+ }, context());+ eventsFrom(delayedLane);+ const delayedStart = delayedLane.start({ text: "delayed" });+ const delayedStop = delayedLane.stop({ reason: "race", forceAfterMs: 0 });+ releaseSpawn({ process: delayedProcess });+ await delayedStop;+ await expect(delayedStart).rejects.toThrow("start was cancelled");++ let finalLane!: GrokAcpLane;+ const finalServer = installServer({ onSessionResponse: () => {+ void finalLane.stop({ reason: "race", forceAfterMs: 0 });+ } });+ finalLane = new GrokAcpLane({ spawn: async () => ({ process: finalServer.process }) }, context());+ eventsFrom(finalLane);+ await expect(finalLane.start({ text: "final race" })).rejects.toThrow("start was cancelled");++ const protocolServer = installServer();+ const protocolLane = new GrokAcpLane(+ { spawn: async () => ({ process: protocolServer.process }) },+ context(),+ );+ const protocolErrors: Error[] = [];+ protocolLane.on("runtime_event", () => {});+ protocolLane.on("error", (error) => protocolErrors.push(error instanceof Error ? error : new Error(String(error))));+ await protocolLane.start({ text: "protocol" });+ protocolServer.process.stdout.write("{not-json}\n");+ await vi.waitFor(() => expect(protocolErrors).toContainEqual(new Error("Grok ACP emitted malformed JSON")));++ const replyFailureServer = installServer();+ const replyFailureLane = new GrokAcpLane(+ { spawn: async () => ({ process: replyFailureServer.process }) },+ context(),+ );+ const replyFailureErrors: Error[] = [];+ replyFailureLane.on("runtime_event", () => {});+ replyFailureLane.on("error", (error) => replyFailureErrors.push(error instanceof Error ? error : new Error(String(error))));+ await replyFailureLane.start({ text: "reply failure" });+ replyFailureServer.process.stdin.end();+ send(replyFailureServer.process, { id: "client-request", method: "terminal_create", params: {} });+ await vi.waitFor(() => expect(replyFailureErrors).toContainEqual(+ new Error("Grok ACP could not answer a client-side protocol request"),+ ));++ for (const wire of [{ jsonrpc: "1.0" }, { jsonrpc: "2.0" }]) {+ const wireServer = installServer();+ const wireLane = new GrokAcpLane({ spawn: async () => ({ process: wireServer.process }) }, context());+ const wireErrors: Error[] = [];+ wireLane.on("runtime_event", () => {});+ wireLane.on("error", (error) => wireErrors.push(error instanceof Error ? error : new Error(String(error))));+ await wireLane.start({ text: "wire" });+ send(wireServer.process, wire);+ await vi.waitFor(() => expect(wireErrors).toHaveLength(1));+ }++ const closeServer = installServer();+ Object.defineProperty(closeServer.process, "pid", { value: 41_001, configurable: true });+ const closeLane = new GrokAcpLane({ spawn: async () => ({ process: closeServer.process }) }, context());+ eventsFrom(closeLane);+ await closeLane.start({ text: "close" });+ closeServer.process.stdin.end();+ await closeLane.stop({ reason: "test", forceAfterMs: 10 });+ expect(killProcessTree).toHaveBeenCalledWith(41_001, { graceMs: 10 });+ });++ it("preserves Grok authentication as a public authentication failure", async () => {+ const auth = installServer({ authError: "token=secret [email protected]" });+ vi.spyOn(GrokDriver.prototype, "openLane").mockImplementation(async (ctx) => (+ new GrokAcpLane({ spawn: async () => ({ process: auth.process }) }, ctx)+ ));+ const sdk = createAgentDriverSdk({ host: createFakeAgentDriverHost() });+ const workingDirectory = await mkdtemp(join(tmpdir(), "grok-public-auth-"));+ try {+ const opened = await sdk.open({+ backend: "grok",+ config: { model: { kind: "default" } },+ launch: {+ workingDirectory,+ instructions: { format: "markdown", content: "" },+ launchId: "grok-public-auth-test",+ },+ });+ if (!opened.ok) throw new Error(opened.error.message);+ const events: unknown[] = [];+ const collecting = (async () => { for await (const event of opened.session.events) events.push(event); })();+ await expect(opened.session.start({ id: "auth", kind: "user", text: "auth" })).resolves.toMatchObject({+ status: "rejected",+ error: { category: "authentication", code: "authentication_required" },+ });+ await opened.session.closed;+ await collecting;+ expect(JSON.stringify(events)).not.toMatch(/secret|user@example\.com/);+ } finally {+ await rm(workingDirectory, { recursive: true, force: true });+ }+ });+});diff --git a/src/daemon/agent-driver/src/adapters/grok/acp-lane.ts b/src/daemon/agent-driver/src/adapters/grok/acp-lane.tsnew file mode 100644index 000000000..3c825976f--- /dev/null+++ b/src/daemon/agent-driver/src/adapters/grok/acp-lane.ts@@ -0,0 +1,846 @@+import { randomBytes } from "node:crypto";+import { EventEmitter } from "node:events";+import type {+ AdapterEvent,+ AdapterLaunchContext,+ LaneAdmission,+ LaneInterruptInput,+ LaneSendInput,+ LaneStartInput,+ LaneStopInput,+ RuntimeLane,+ RuntimeLaneEventMap,+ SpawnedProcess,+ SpawnedProcessHandle,+} from "../../internal/adapter.js";+import type {+ AgentDriverError,+ ReasoningEffort,+ RuntimeReasoningCatalog,+ RuntimeSettingsUpdate,+ RuntimeSettingsUpdateResult,+} from "../../contract.js";+import { resolveLaunchFieldsOrDefault } from "../../internal/config.js";+import { killProcessTree, SESSION_STOP_GRACE_MS } from "../../internal/killTree.js";+import { SettledUsageProjector } from "../../internal/token-usage.js";+import { asRecord } from "../../internal/utils.js";+import { parseGrokModelCatalog } from "./catalog-probe.js";+import { normalizeGrokBilling, projectGrokUsage } from "./telemetry.js";++const ACP_PROTOCOL_VERSION = 1;+const AUTH_METHOD_ID = "cached_token";+const INTERACTIVE_AUTH_METHOD_IDS = new Set(["grok.com"]);+const HANDSHAKE_TIMEOUT_MS = 15_000;+const SESSION_CLOSE_TIMEOUT_MS = 1_000;+const PROMPT_STOP_REASONS = new Set([+ "end_turn",+ "max_tokens",+ "max_turn_requests",+ "refusal",+ "cancelled",+]);++type JsonRpcId = number | string;+type JsonRecord = Record<string, unknown>;++interface PendingCall {+ readonly kind: "call";+ readonly method: string;+ readonly resolve: (result: unknown) => void;+ readonly reject: (error: Error) => void;+ readonly timer?: ReturnType<typeof setTimeout>;+}++interface PromptRequest {+ readonly requestId: number;+ readonly receipt: string;+ readonly providerPromptId: string;+ fallbackUsage?: unknown;+}++interface PendingPrompt {+ readonly kind: "prompt";+ readonly method: "session/prompt";+ readonly prompt: PromptRequest;+}++type PendingRequest = PendingCall | PendingPrompt;++interface RpcRequest {+ readonly id: number;+ readonly promise: Promise<unknown>;+}++export interface GrokAcpProcessFactory {+ spawn(ctx: AdapterLaunchContext): Promise<SpawnedProcess>;+}++interface GrokAcpLaneOptions {+ readonly onRawStdoutLine?: (line: string) => void;+ readonly handshakeTimeoutMs?: number;+}++class GrokAcpResetRequiredError extends Error {}+class GrokAcpIncompatibleError extends Error {}+class GrokAcpAuthenticationError extends Error {}++class GrokAcpRpcError extends Error {+ constructor(readonly method: string, readonly code: number | undefined, message: string) {+ super(message);+ }+}++function safeLabel(value: unknown): string {+ return typeof value === "string" && /^[a-z0-9_.\/-]{1,96}$/i.test(value) ? value : "unknown";+}++function rpcErrorMessage(error: unknown): string {+ const payload = asRecord(error);+ return typeof payload?.message === "string" && payload.message.trim()+ ? payload.message+ : "Grok ACP request failed";+}++function isMissingSessionError(error: unknown): boolean {+ const message = error instanceof Error ? error.message : String(error);+ return /\bsession\b.*\b(not found|missing|unknown|invalid)\b/i.test(message)+ || /\b(not found|missing|unknown|invalid)\b.*\bsession\b/i.test(message);+}++function settingsError(+ category: AgentDriverError["category"],+ code: string,+ message: string,+ retryable = false,+): AgentDriverError {+ return { category, code, message, retryable };+}++export class GrokAcpLane implements RuntimeLane {+ private readonly events = new EventEmitter();+ private readonly pending = new Map<number, PendingRequest>();+ private readonly openToolCalls = new Map<string, string>();+ private readonly usageProjector = new SettledUsageProjector();+ private readonly quotaSourceEpoch = randomBytes(16).toString("base64url");+ private process: SpawnedProcessHandle | null = null;+ private stdoutBuffer = "";+ private requestSequence = 0;+ private started = false;+ private ready = false;+ private sessionId: string | null = null;+ private currentPromptRequestId: number | null = null;+ private terminalOwner: string | null = null;+ private catalog: RuntimeReasoningCatalog | undefined;+ private currentModelId: string | undefined;+ private currentReasoningEffort: ReasoningEffort | undefined;+ private requestedStopReason?: string;+ private spawnPromise?: Promise<SpawnedProcess>;+ private stopPromise?: Promise<void>;+ private suppressExit = false;+ private processTerminal = false;+ private processActivated = false;+ private processStartError: Error | null = null;+ private billingInFlight = false;++ constructor(+ private readonly factory: GrokAcpProcessFactory,+ private readonly ctx: AdapterLaunchContext,+ private readonly options: GrokAcpLaneOptions = {},+ ) {}++ get currentSessionId(): string | null {+ return this.sessionId;+ }++ on<K extends keyof RuntimeLaneEventMap>(+ event: K,+ listener: (value: RuntimeLaneEventMap[K]) => void,+ ): void {+ this.events.on(event, listener);+ }++ async start(input: LaneStartInput): Promise<LaneAdmission> {+ if (this.started) return { ok: false, reason: "runtime_error", error: "Grok ACP session already started" };+ this.started = true;+ const launchCtx: AdapterLaunchContext = {+ ...this.ctx,+ prompt: input.text,+ config: { ...this.ctx.config, sessionId: input.sessionId ?? this.ctx.config.sessionId },+ };+ try {+ this.spawnPromise = this.factory.spawn(launchCtx).then((spawned) => {+ this.process = spawned.process;+ this.attachProcess(spawned.process);+ return spawned;+ });+ await this.spawnPromise;+ if (this.requestedStopReason) {+ await this.stop({ reason: this.requestedStopReason, forceAfterMs: 0 });+ throw new Error("Grok ACP start was cancelled");+ }+ await this.handshake(launchCtx);+ if (this.requestedStopReason) {+ await this.stop({ reason: this.requestedStopReason, forceAfterMs: 0 });+ throw new Error("Grok ACP start was cancelled");+ }+ if (this.processStartError) throw this.processStartError;+ if (this.processTerminal || this.isClosed()) throw new Error("Grok ACP process exited during startup");+ const sessionId = this.sessionId;+ if (!sessionId) throw new Error("Grok ACP handshake completed without a session id");+ this.processActivated = true;+ this.ready = true;+ this.events.emit("runtime_event", { kind: "session_init", sessionId } satisfies AdapterEvent);+ return this.admitPrompt(input.text, input.terminalOwner);+ } catch (error) {+ this.suppressExit = true;+ await this.stop({ reason: "failed_start", forceAfterMs: 0 }).catch(() => {});+ if (error instanceof GrokAcpResetRequiredError) {+ return { ok: false, reason: "reset_required", error: error.message };+ }+ if (error instanceof GrokAcpIncompatibleError) {+ return { ok: false, reason: "incompatible_configuration", error: error.message };+ }+ if (error instanceof GrokAcpAuthenticationError) {+ return { ok: false, reason: "authentication", error: error.message };+ }+ throw error;+ }+ }++ send(input: LaneSendInput): Promise<LaneAdmission> {+ if (!this.ready || !this.process || this.isClosed()) {+ return Promise.resolve({ ok: false, reason: "closed" });+ }+ if (input.mode === "busy" || this.currentPromptRequestId !== null) {+ return Promise.resolve({+ ok: false,+ reason: "runtime_busy",+ error: "Grok ACP accepts messages only at a safe prompt boundary",+ });+ }+ return Promise.resolve(this.admitPrompt(input.text, input.terminalOwner));+ }++ interrupt(_input: LaneInterruptInput): Promise<boolean> {+ if (!this.ready || !this.sessionId || this.currentPromptRequestId === null || this.isClosed()) {+ return Promise.resolve(false);+ }+ this.write({ jsonrpc: "2.0", method: "session/cancel", params: { sessionId: this.sessionId } });+ return Promise.resolve(true);+ }++ async updateSettings(input: RuntimeSettingsUpdate): Promise<RuntimeSettingsUpdateResult> {+ if (!this.ready || !this.sessionId || this.isClosed()) {+ return { status: "failed", error: settingsError("process", "settings_session_unavailable", "Grok session is not available", true) };+ }+ if (this.currentPromptRequestId !== null) {+ return { status: "failed", error: settingsError("configuration", "settings_runtime_busy", "Grok settings change requires an idle session", true) };+ }+ const modelId = this.currentModelId ?? this.catalog?.defaultModelId;+ if (!modelId) {+ return { status: "failed", error: settingsError("configuration", "settings_model_unavailable", "Grok did not publish the active model") };+ }+ if (input.reasoningEffort !== null && !this.supportsReasoning(modelId, input.reasoningEffort)) {+ return { status: "failed", error: settingsError("configuration", "unsupported_reasoning_effort", "Configured Grok reasoning effort is unavailable") };+ }+ try {+ await this.setModel(modelId, input.reasoningEffort ?? undefined);+ this.currentReasoningEffort = input.reasoningEffort ?? undefined;+ return { status: "applied" };+ } catch {+ return { status: "failed", error: settingsError("protocol", "settings_update_failed", "Grok rejected the settings update", true) };+ }+ }++ stop(input: LaneStopInput = {}): Promise<void> {+ this.requestedStopReason ??= input.reason ?? "requested_stop";+ this.ready = false;+ this.currentPromptRequestId = null;+ this.terminalOwner = null;+ this.finishOpenTools();+ this.stopPromise ??= this.stopPhysicalOnce(input);+ return this.stopPromise;+ }++ private async stopPhysicalOnce(input: LaneStopInput): Promise<void> {+ await this.spawnPromise?.catch(() => undefined);+ const proc = this.process;+ if (!proc) return;+ if (this.sessionId && !this.isClosed() && (input.forceAfterMs ?? SESSION_STOP_GRACE_MS) > 0) {+ await Promise.resolve().then(() => this.call(+ "session/close",+ { sessionId: this.sessionId },+ Math.min(input.forceAfterMs ?? SESSION_CLOSE_TIMEOUT_MS, SESSION_CLOSE_TIMEOUT_MS),+ )).catch(() => undefined);+ }+ this.rejectAllPending(new Error("Grok ACP lane stopped"));+ if (proc.pid) {+ await killProcessTree(proc.pid, { graceMs: input.forceAfterMs ?? SESSION_STOP_GRACE_MS });+ } else if (!this.isClosed()) {+ proc.kill(input.signal ?? "SIGTERM");+ }+ }++ private async handshake(ctx: AdapterLaunchContext): Promise<void> {+ const initialize = asRecord(await this.call("initialize", {+ protocolVersion: ACP_PROTOCOL_VERSION,+ clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },+ clientInfo: { name: "alook-agent-driver", version: "0.1.31" },+ }));+ if (initialize?.protocolVersion !== ACP_PROTOCOL_VERSION) {+ throw new GrokAcpIncompatibleError("Installed Grok ACP does not support protocol version 1");+ }+ const capabilities = asRecord(initialize.agentCapabilities);+ if (capabilities?.loadSession !== true) {+ throw new GrokAcpIncompatibleError("Installed Grok ACP does not support persistent session loading");+ }+ const authMethods = Array.isArray(initialize.authMethods) ? initialize.authMethods : [];+ const authMethodIds = authMethods.flatMap((method) => {+ const id = asRecord(method)?.id;+ return typeof id === "string" ? [id] : [];+ });+ if (!authMethodIds.includes(AUTH_METHOD_ID)) {+ if (authMethodIds.some((id) => INTERACTIVE_AUTH_METHOD_IDS.has(id))) {+ throw new GrokAcpAuthenticationError("Grok authentication failed; run `grok login` and retry");+ }+ throw new GrokAcpIncompatibleError("Installed Grok ACP does not expose cached-token authentication");+ }+ this.adoptCatalogFromInitialize(initialize);+ try {+ await this.call("authenticate", { methodId: AUTH_METHOD_ID });+ } catch {+ throw new GrokAcpAuthenticationError("Grok authentication failed; run `grok login` and retry");+ }+ void this.refreshBilling();++ const requestedSessionId = ctx.config.sessionId;+ let session: JsonRecord | null;+ if (requestedSessionId) {+ try {+ session = asRecord(await this.call("session/load", {+ sessionId: requestedSessionId,+ cwd: ctx.workingDirectory,+ mcpServers: [],+ }));+ } catch (error) {+ if (isMissingSessionError(error)) {+ throw new GrokAcpResetRequiredError("Grok session could not be loaded; reset this agent to start a new session");+ }+ throw error;+ }+ } else {+ session = asRecord(await this.call("session/new", {+ cwd: ctx.workingDirectory,+ mcpServers: [],+ _meta: { yoloMode: true },+ }));+ }+ if (!session) throw new Error("Grok ACP did not return a valid session response");+ const returnedSessionId = session.sessionId;+ if (requestedSessionId) {+ if (returnedSessionId !== undefined && (typeof returnedSessionId !== "string" || !returnedSessionId.trim())) {+ throw new Error("Grok ACP returned an invalid session id");+ }+ if (typeof returnedSessionId === "string" && returnedSessionId !== requestedSessionId) {+ throw new GrokAcpResetRequiredError("Grok ACP loaded a different session; reset this agent before continuing");+ }+ this.sessionId = requestedSessionId;+ } else {+ if (typeof returnedSessionId !== "string" || !returnedSessionId.trim()) {+ throw new Error("Grok ACP did not return a valid session id");+ }+ this.sessionId = returnedSessionId;+ }+ this.catalog = parseGrokModelCatalog(session.models) ?? this.catalog;+ await this.configureModel(ctx);+ }++ private adoptCatalogFromInitialize(initialize: JsonRecord): void {+ const meta = asRecord(initialize._meta) ?? asRecord(initialize.meta);+ this.catalog = parseGrokModelCatalog(meta?.modelState) ?? this.catalog;+ this.currentModelId = this.catalog?.defaultModelId ?? this.currentModelId;+ }++ private async configureModel(ctx: AdapterLaunchContext): Promise<void> {+ const configured = resolveLaunchFieldsOrDefault(ctx.config.runtimeConfig);+ const requestedModel = configured.model;+ const modelId = requestedModel ?? this.catalog?.defaultModelId;+ if (requestedModel && !this.catalog?.models.some((model) => model.id === requestedModel)) {+ throw new GrokAcpIncompatibleError(`Configured Grok model is unavailable: ${requestedModel}`);+ }+ if (configured.reasoningEffort && (!modelId || !this.supportsReasoning(modelId, configured.reasoningEffort))) {+ throw new GrokAcpIncompatibleError(`Configured Grok reasoning effort is unavailable: ${configured.reasoningEffort}`);+ }+ this.currentModelId = modelId;+ this.currentReasoningEffort = configured.reasoningEffort;+ if (requestedModel || configured.reasoningEffort) {+ if (!modelId) throw new GrokAcpIncompatibleError("Grok did not publish a model catalog");+ await this.setModel(modelId, configured.reasoningEffort);+ }+ }++ private supportsReasoning(modelId: string, effort: ReasoningEffort): boolean {+ const model = this.catalog?.models.find((candidate) => candidate.id === modelId);+ return Boolean(model?.supportedReasoningEfforts.some((candidate) => candidate.value === effort));+ }++ private async setModel(modelId: string, reasoningEffort?: ReasoningEffort): Promise<void> {+ if (!this.sessionId) throw new Error("Grok ACP session is not ready");+ await this.call("session/set_model", {+ sessionId: this.sessionId,+ modelId,+ ...(reasoningEffort ? { _meta: { reasoningEffort } } : {}),+ });+ }++ private admitPrompt(text: string, requestedOwner?: string): LaneAdmission {+ if (!this.sessionId) return { ok: false, reason: "not_ready", error: "Grok ACP session is not ready" };+ const requestId = ++this.requestSequence;+ const receipt = requestedOwner?.trim() || `grok:acp:${requestId}`;+ const prompt: PromptRequest = { requestId, receipt, providerPromptId: `alook-${requestId}` };+ this.currentPromptRequestId = requestId;+ this.terminalOwner = receipt;+ this.openToolCalls.clear();+ this.pending.set(requestId, { kind: "prompt", method: "session/prompt", prompt });+ try {+ this.write({+ jsonrpc: "2.0",+ id: requestId,+ method: "session/prompt",+ params: {+ sessionId: this.sessionId,+ prompt: [{ type: "text", text }],+ _meta: { promptId: prompt.providerPromptId },+ },+ });+ } catch (error) {+ this.pending.delete(requestId);+ this.currentPromptRequestId = null;+ this.terminalOwner = null;+ throw error;+ }+ return { ok: true, acceptedAs: "prompt", receipt };+ }++ private completePrompt(prompt: PromptRequest, value: unknown): void {+ if (this.currentPromptRequestId !== prompt.requestId) return;+ const result = asRecord(value);+ if (!result || typeof result.stopReason !== "string" || !PROMPT_STOP_REASONS.has(result.stopReason)) {+ this.failPrompt(prompt, new Error("Grok ACP prompt response did not contain a supported stopReason"), "grok.invalid_stop_reason");+ return;+ }+ const terminalOwner = this.terminalOwner ?? prompt.receipt;+ const meta = asRecord(result._meta) ?? asRecord(result.meta);+ const responseUsage = projectGrokUsage(+ this.usageProjector,+ this.sessionId ?? "unknown",+ prompt.providerPromptId,+ meta?.usage,+ );+ const usage = responseUsage ?? projectGrokUsage(+ this.usageProjector,+ this.sessionId ?? "unknown",+ prompt.providerPromptId,+ prompt.fallbackUsage,+ );+ this.currentPromptRequestId = null;+ this.terminalOwner = null;+ this.finishOpenTools();+ if (usage) this.events.emit("runtime_event", usage);+ this.events.emit("runtime_event", {+ kind: "turn_end",+ sessionId: this.sessionId ?? undefined,+ turnOwner: terminalOwner,+ } satisfies AdapterEvent);+ void this.refreshBilling();+ }++ private failPrompt(prompt: PromptRequest, error: unknown, code = "grok.prompt_failed"): void {+ if (this.currentPromptRequestId !== prompt.requestId) return;+ const terminalOwner = this.terminalOwner ?? prompt.receipt;+ this.currentPromptRequestId = null;+ this.terminalOwner = null;+ this.finishOpenTools();+ this.events.emit("runtime_event", {+ kind: "error",+ code,+ message: error instanceof Error ? error.message : String(error),+ } satisfies AdapterEvent);+ this.events.emit("runtime_event", {+ kind: "turn_end",+ sessionId: this.sessionId ?? undefined,+ turnOwner: terminalOwner,+ } satisfies AdapterEvent);+ void this.refreshBilling();+ }++ private call(method: string, params: JsonRecord, timeoutMs?: number): Promise<unknown> {+ return this.request(method, params, timeoutMs ?? this.options.handshakeTimeoutMs ?? HANDSHAKE_TIMEOUT_MS).promise;+ }++ private request(method: string, params: JsonRecord, timeoutMs?: number): RpcRequest {+ const id = ++this.requestSequence;+ let resolve!: (result: unknown) => void;+ let reject!: (error: Error) => void;+ const promise = new Promise<unknown>((accept, decline) => {+ resolve = accept;+ reject = decline;+ });+ const timer = timeoutMs === undefined ? undefined : setTimeout(() => {+ const pending = this.pending.get(id);+ if (!pending || pending.kind !== "call") return;+ this.pending.delete(id);+ pending.reject(new Error(`Grok ACP ${method} timed out`));+ }, timeoutMs);+ timer?.unref?.();+ this.pending.set(id, { kind: "call", method, resolve, reject, ...(timer ? { timer } : {}) });+ try {+ this.write({ jsonrpc: "2.0", id, method, params });+ } catch (error) {+ const pending = this.pending.get(id);+ this.pending.delete(id);+ if (pending?.kind === "call" && pending.timer) clearTimeout(pending.timer);+ throw error instanceof Error ? error : new Error(String(error));+ }+ return { id, promise };+ }++ private write(message: JsonRecord): void {+ const stdin = this.process?.stdin;+ if (!stdin || stdin.destroyed || stdin.writableEnded || stdin.writable === false) {+ throw new Error("Grok ACP stdin is not writable");+ }+ stdin.write(`${JSON.stringify(message)}\n`);+ }++ private attachProcess(proc: SpawnedProcessHandle): void {+ proc.stdout?.on("data", (chunk) => {+ this.stdoutBuffer += chunk.toString();+ const lines = this.stdoutBuffer.split("\n");+ this.stdoutBuffer = lines.pop() ?? "";+ for (const line of lines) {+ if (!line.trim()) continue;+ try {+ this.options.onRawStdoutLine?.(line);+ } catch {}+ let message: unknown;+ try {+ message = JSON.parse(line);+ } catch {+ this.protocolFailure("Grok ACP emitted malformed JSON");+ continue;+ }+ try {+ this.handleMessage(message);+ } catch {+ this.protocolFailure("Grok ACP could not answer a client-side protocol request");+ }+ }+ });+ proc.stderr?.on("data", (chunk) => {+ const text = chunk.toString().trim();+ if (text) this.events.emit("stderr", text);+ });+ proc.on("error", (error) => {+ if (this.process !== proc || this.processTerminal) return;+ const normalized = error instanceof Error ? error : new Error(String(error));+ this.rejectAllPending(normalized);+ if (!this.processActivated || this.requestedStopReason) {+ if (!this.processActivated) this.processStartError ??= normalized;+ this.events.emit("error", normalized);+ return;+ }+ this.processTerminal = true;+ this.ready = false;+ this.currentPromptRequestId = null;+ this.terminalOwner = null;+ this.finishOpenTools();+ this.stopPromise ??= this.stopPhysicalOnce({ reason: "runtime_error", forceAfterMs: 0 });+ void this.stopPromise.catch(() => {});+ this.events.emit("error", normalized);+ if (!this.suppressExit) this.events.emit("exit", { code: null, signal: null, reason: "runtime_exit" });+ });+ proc.on("exit", (code, signal) => {+ if (this.processTerminal || this.process !== proc) return;+ this.processTerminal = true;+ this.ready = false;+ this.currentPromptRequestId = null;+ this.terminalOwner = null;+ this.finishOpenTools();+ this.rejectAllPending(new Error("Grok ACP process exited"));+ if (this.suppressExit || !this.processActivated) return;+ this.events.emit("exit", {+ code,+ signal,+ reason: this.requestedStopReason ? "requested" : "runtime_exit",+ });+ });+ }++ private handleMessage(value: unknown): void {+ const message = asRecord(value);+ if (!message || message.jsonrpc !== "2.0") {+ this.protocolFailure("Grok ACP emitted an invalid JSON-RPC message");+ return;+ }+ if (typeof message.method === "string") {+ if (message.id !== undefined) this.handleRequest(message.id as JsonRpcId, message.method, message.params);+ else this.handleNotification(message.method, message.params);+ return;+ }+ if (typeof message.id === "number" || typeof message.id === "string") {+ this.handleResponse(message.id, message);+ return;+ }+ this.protocolFailure("Grok ACP emitted an unrecognized JSON-RPC message");+ }++ private handleResponse(id: JsonRpcId, message: JsonRecord): void {+ const pending = typeof id === "number" ? this.pending.get(id) : undefined;+ if (typeof id !== "number" || !pending) {+ this.diagnostic("warning", "Grok ACP emitted a duplicate or unknown response id");+ return;+ }+ if (pending.kind === "prompt") {+ this.pending.delete(id);+ if (message.error !== undefined) {+ const payload = asRecord(message.error);+ const code = typeof payload?.code === "number" && Number.isSafeInteger(payload.code) ? payload.code : undefined;+ this.failPrompt(+ pending.prompt,+ new GrokAcpRpcError(pending.method, code, rpcErrorMessage(message.error)),+ code === undefined ? "grok.rpc_error" : `grok.rpc.${code}`,+ );+ } else if (!("result" in message)) {+ this.failPrompt(pending.prompt, new Error("Grok ACP response omitted result"), "grok.invalid_response");+ } else {+ this.completePrompt(pending.prompt, message.result);+ }+ return;+ }+ if (message.error !== undefined) {+ const payload = asRecord(message.error);+ this.settleRequest(id, false, new GrokAcpRpcError(+ pending.method,+ typeof payload?.code === "number" && Number.isSafeInteger(payload.code) ? payload.code : undefined,+ rpcErrorMessage(message.error),+ ));+ return;+ }+ if (!("result" in message)) {+ this.settleRequest(id, false, new Error("Grok ACP response omitted result"));+ return;+ }+ this.settleRequest(id, true, message.result);+ }++ private settleRequest(id: number, ok: boolean, value: unknown): void {+ const pending = this.pending.get(id);+ if (!pending || pending.kind !== "call") return;+ this.pending.delete(id);+ if (pending.timer) clearTimeout(pending.timer);+ if (ok) pending.resolve(value);+ else pending.reject(value instanceof Error ? value : new Error(String(value)));+ }++ private handleRequest(id: JsonRpcId, method: string, params: unknown): void {+ if (method !== "session/request_permission") {+ this.write({ jsonrpc: "2.0", id, error: { code: -32601, message: "Unsupported Grok ACP client request" } });+ this.diagnostic("warning", `Unsupported Grok ACP client request: ${safeLabel(method)}`);+ return;+ }+ const payload = asRecord(params);+ const options = Array.isArray(payload?.options) ? payload.options.map(asRecord).filter(Boolean) as JsonRecord[] : [];+ const allowOnce = options.find((option) => option.kind === "allow_once" && typeof option.optionId === "string" && option.optionId.trim());+ if (!this.ready || this.currentPromptRequestId === null || payload?.sessionId !== this.sessionId || !allowOnce) {+ this.write({ jsonrpc: "2.0", id, result: { outcome: { outcome: "cancelled" } } });+ this.diagnostic("error", "Grok ACP permission request was not allowed for the active prompt");+ return;+ }+ this.write({+ jsonrpc: "2.0",+ id,+ result: { outcome: { outcome: "selected", optionId: allowOnce.optionId } },+ });+ }++ private handleNotification(method: string, params: unknown): void {+ if (method === "_x.ai/models/update" || method === "x.ai/models/update") {+ this.catalog = parseGrokModelCatalog(params) ?? this.catalog;+ this.currentModelId ??= this.catalog?.defaultModelId;+ return;+ }+ if (method === "session/update") {+ this.handleSessionUpdate(params);+ return;+ }+ if (method === "_x.ai/session/update" || method === "x.ai/session/update") {+ this.handlePrivateSessionUpdate(params);+ return;+ }+ this.diagnostic("warning", `Unsupported Grok ACP notification: ${safeLabel(method)}`);+ }++ private handleSessionUpdate(params: unknown): void {+ const payload = asRecord(params);+ const update = asRecord(payload?.update) ?? {};+ const replay = asRecord(payload?._meta)?.isReplay === true || asRecord(update?._meta)?.isReplay === true;+ if (replay || !this.ready) return;+ if (!payload || payload.sessionId !== this.sessionId) {+ this.diagnostic("warning", "Grok ACP emitted an update for a different session");+ return;+ }+ if (this.currentPromptRequestId === null) {+ this.diagnostic("warning", "Grok ACP emitted a session update without an active prompt");+ return;+ }+ const updateType = update?.sessionUpdate;+ switch (updateType) {+ case "agent_message_chunk":+ case "agent_thought_chunk": {+ const content = asRecord(update.content);+ if (content?.type === "text" && typeof content.text === "string") {+ this.events.emit("runtime_event", {+ kind: updateType === "agent_message_chunk" ? "assistant_message_delta" : "assistant_reasoning_delta",+ text: content.text,+ } satisfies AdapterEvent);+ }+ return;+ }+ case "user_message_chunk":+ return;+ case "tool_call": {+ if (typeof update.toolCallId !== "string" || typeof update.title !== "string") {+ this.diagnostic("warning", "Grok ACP emitted a malformed tool_call update");+ return;+ }+ this.openToolCalls.set(update.toolCallId, update.title);+ this.events.emit("runtime_event", {+ kind: "tool_call",+ callId: update.toolCallId,+ name: update.title,+ input: update.rawInput,+ } satisfies AdapterEvent);+ return;+ }+ case "tool_call_update": {+ if (+ typeof update.toolCallId === "string"+ && (update.status === "completed" || update.status === "failed")+ ) {+ const name = this.openToolCalls.get(update.toolCallId);+ if (name) {+ this.openToolCalls.delete(update.toolCallId);+ this.events.emit("runtime_event", {+ kind: "tool_output",+ callId: update.toolCallId,+ name: typeof update.title === "string" ? update.title : name,+ } satisfies AdapterEvent);+ }+ }+ return;+ }+ case "plan":+ this.events.emit("runtime_event", { kind: "internal_progress", source: "grok.acp", itemType: "plan" } satisfies AdapterEvent);+ return;+ case "current_model_update": {+ const modelId = typeof update.modelId === "string" ? update.modelId : update.model_id;+ if (typeof modelId === "string") this.currentModelId = modelId;+ return;+ }+ default:+ this.diagnostic("warning", `Unsupported Grok ACP session update: ${safeLabel(updateType)}`);+ }+ }++ private handlePrivateSessionUpdate(params: unknown): void {+ const payload = asRecord(params);+ const update = asRecord(payload?.update) ?? payload;+ const replay = asRecord(payload?._meta)?.isReplay === true || asRecord(update?._meta)?.isReplay === true;+ if (replay || !this.ready || !payload || payload.sessionId !== this.sessionId) return;+ const pending = this.currentPrompt();+ if (!pending || update?.sessionUpdate !== "turn_completed") return;+ const updateMeta = asRecord(update._meta);+ const payloadMeta = asRecord(payload._meta);+ const promptId = update.promptId ?? update.prompt_id+ ?? updateMeta?.promptId ?? updateMeta?.prompt_id+ ?? payload.promptId ?? payload.prompt_id+ ?? payloadMeta?.promptId ?? payloadMeta?.prompt_id;+ if (promptId !== pending.providerPromptId) return;+ pending.fallbackUsage ??= update.usage ?? updateMeta?.usage ?? payload.usage ?? payloadMeta?.usage;+ }++ private currentPrompt(): PromptRequest | null {+ if (this.currentPromptRequestId === null) return null;+ const pending = this.pending.get(this.currentPromptRequestId);+ return pending?.kind === "prompt" ? pending.prompt : null;+ }++ private async refreshBilling(): Promise<void> {+ if (this.billingInFlight || this.requestedStopReason || this.isClosed()) return;+ this.billingInFlight = true;+ try {+ const result = await this.call("_x.ai/billing", {});+ if (this.requestedStopReason) return;+ const payload = asRecord(result);+ this.events.emit("runtime_event", {+ kind: "telemetry",+ name: "rate_limits",+ source: "grok_billing",+ quota: normalizeGrokBilling(payload?.billing ?? result, this.quotaSourceEpoch),+ } satisfies AdapterEvent);+ } catch (error) {+ if (this.requestedStopReason) return;+ const code = error instanceof GrokAcpRpcError && error.code === -32601+ ? "unavailable"+ : error instanceof GrokAcpRpcError && (error.code === 401 || error.code === -32001)+ ? "unauthorized"+ : "provider_error";+ this.events.emit("runtime_event", {+ kind: "telemetry",+ name: "rate_limits",+ source: "grok_billing",+ quota: {+ status: "error",+ sourceEpoch: this.quotaSourceEpoch,+ code,+ retryable: code !== "unauthorized" && code !== "unavailable",+ },+ } satisfies AdapterEvent);+ } finally {+ this.billingInFlight = false;+ }+ }++ private finishOpenTools(): void {+ for (const [callId, name] of this.openToolCalls) {+ this.events.emit("runtime_event", { kind: "tool_output", callId, name } satisfies AdapterEvent);+ }+ this.openToolCalls.clear();+ }++ private diagnostic(severity: "error" | "warning", message: string): void {+ this.events.emit("runtime_event", { kind: "runtime_diagnostic", severity, source: "grok.acp", message } satisfies AdapterEvent);+ }++ private protocolFailure(message: string): void {+ const error = new Error(message);+ this.rejectAllPending(error);+ this.events.emit("error", error);+ void this.stop({ reason: "protocol_error", forceAfterMs: 0 }).catch(() => {});+ }++ private rejectAllPending(error: Error): void {+ for (const [id, pending] of [...this.pending]) {+ this.pending.delete(id);+ if (pending.kind === "call") {+ if (pending.timer) clearTimeout(pending.timer);+ pending.reject(error);+ }+ }+ }++ private isClosed(): boolean {+ return this.process ? this.process.exitCode !== null || this.process.signalCode !== null : false;+ }+}diff --git a/src/daemon/agent-driver/src/adapters/grok/catalog-probe.ts b/src/daemon/agent-driver/src/adapters/grok/catalog-probe.tsnew file mode 100644index 000000000..43ba52119--- /dev/null+++ b/src/daemon/agent-driver/src/adapters/grok/catalog-probe.ts@@ -0,0 +1,264 @@+import type { RuntimeReasoningCatalog } from "../../contract.js";+import type { SpawnedProcessHandle } from "../../internal/adapter.js";+import { killProcessTree, spawnAgentProcess } from "../../internal/killTree.js";+import { normalizeRuntimeModelId, RUNTIME_MODEL_CATALOG_MAX } from "../../internal/modelCatalog.js";+import { resolveSpawnSpec } from "../../internal/probe.js";+import { asRecord, jsonRpcRequest, tryParseJsonLine } from "../../internal/utils.js";++const ACP_PROTOCOL_VERSION = 1;+const AUTH_METHOD_ID = "cached_token";+const INTERACTIVE_AUTH_METHOD_IDS = new Set(["grok.com"]);+const CATALOG_PROBE_TIMEOUT_MS = 15_000;+const CATALOG_NOTIFICATION_GRACE_MS = 50;+const CATALOG_PROBE_OUTPUT_MAX_BYTES = 1024 * 1024;+const MODEL_DISPLAY_NAME_MAX = 256;+const DESCRIPTION_MAX = 512;++type ProbeSpawn = (+ command: string,+ args: string[],+ options: { cwd: string; env: NodeJS.ProcessEnv; shell: boolean },+) => SpawnedProcessHandle;++interface GrokAcpCatalogProbeOptions {+ readonly cwd?: string;+ readonly timeoutMs?: number;+ readonly outputMaxBytes?: number;+ readonly catalogGraceMs?: number;+ readonly spawn?: ProbeSpawn;+ readonly cleanup?: (process: SpawnedProcessHandle) => Promise<void>;+}++export type GrokAcpProbeResult =+ | { readonly status: "compatible"; readonly reasoning?: RuntimeReasoningCatalog }+ | {+ readonly status: "unhealthy";+ readonly lastError:+ | "grok_acp_spawn_failed"+ | "grok_acp_transport_unavailable"+ | "grok_acp_invalid_response"+ | "grok_acp_initialize_failed"+ | "grok_acp_protocol_incompatible"+ | "grok_acp_load_session_unsupported"+ | "grok_acp_cached_auth_unsupported"+ | "grok_acp_authentication_failed"+ | "grok_acp_output_limit"+ | "grok_acp_process_failed"+ | "grok_acp_probe_failed"+ | "grok_acp_probe_timeout";+ };++function boundedText(value: unknown, max: number): string | undefined {+ if (typeof value !== "string") return undefined;+ const text = value.trim();+ return text && text.length <= max ? text : undefined;+}++function modelMeta(model: Record<string, unknown>): Record<string, unknown> {+ return asRecord(model._meta) ?? asRecord(model.meta) ?? {};+}++function reasoningCatalog(model: Record<string, unknown>) {+ const meta = modelMeta(model);+ if (meta.supportsReasoningEffort !== true) {+ return { supportedReasoningEfforts: [] as RuntimeReasoningCatalog["models"][number]["supportedReasoningEfforts"] };+ }+ const raw = Array.isArray(meta.reasoningEfforts)+ ? meta.reasoningEfforts+ : Array.isArray(meta.reasoning_efforts)+ ? meta.reasoning_efforts+ : [];+ const seen = new Set<string>();+ const supportedReasoningEfforts: RuntimeReasoningCatalog["models"][number]["supportedReasoningEfforts"][number][] = [];+ let markedDefault: string | undefined;+ for (const item of raw) {+ const row = typeof item === "string" ? { value: item } : asRecord(item);+ const value = normalizeRuntimeModelId(row?.value ?? row?.id);+ if (!value || seen.has(value)) continue;+ seen.add(value);+ const description = boundedText(row?.description, DESCRIPTION_MAX);+ supportedReasoningEfforts.push({ value, ...(description ? { description } : {}) });+ if (row?.default === true) markedDefault = value;+ }+ const reportedDefault = normalizeRuntimeModelId(meta.reasoningEffort ?? meta.reasoning_effort);+ const defaultReasoningEffort = [reportedDefault, markedDefault]+ .find((value) => value && seen.has(value));+ return {+ supportedReasoningEfforts,+ ...(defaultReasoningEffort ? { defaultReasoningEffort } : {}),+ };+}++export function parseGrokModelCatalog(value: unknown): RuntimeReasoningCatalog | undefined {+ const snapshot = asRecord(value);+ const available = Array.isArray(snapshot?.availableModels) ? snapshot.availableModels : [];+ const seen = new Set<string>();+ const models: RuntimeReasoningCatalog["models"][number][] = [];+ for (const item of available) {+ const model = asRecord(item);+ const id = normalizeRuntimeModelId(model?.modelId);+ if (!model || !id || seen.has(id)) continue;+ if (models.length >= RUNTIME_MODEL_CATALOG_MAX) return undefined;+ seen.add(id);+ const displayName = boundedText(model.name, MODEL_DISPLAY_NAME_MAX);+ models.push({ id, ...(displayName ? { displayName } : {}), ...reasoningCatalog(model) });+ }+ if (models.length === 0) return undefined;+ const currentModelId = normalizeRuntimeModelId(snapshot?.currentModelId);+ return {+ updateMode: "live_next_turn",+ ...(currentModelId && seen.has(currentModelId) ? { defaultModelId: currentModelId } : {}),+ models,+ };+}++function catalogFromInitialize(result: Record<string, unknown>): RuntimeReasoningCatalog | undefined {+ const meta = asRecord(result._meta) ?? asRecord(result.meta);+ return parseGrokModelCatalog(meta?.modelState);+}++async function cleanupProbeProcess(process: SpawnedProcessHandle): Promise<void> {+ if (process.pid) {+ await killProcessTree(process.pid, { graceMs: 250 }).catch(() => {});+ return;+ }+ if (process.exitCode === null && process.signalCode === null) process.kill("SIGTERM");+}++export async function probeGrokAcpCatalog(+ command?: string,+ options: GrokAcpCatalogProbeOptions = {},+): Promise<GrokAcpProbeResult> {+ const cwd = options.cwd ?? process.cwd();+ const spec = resolveSpawnSpec("grok", ["agent", "--no-leader", "stdio"], command);+ let processHandle: SpawnedProcessHandle;+ try {+ processHandle = (options.spawn ?? spawnAgentProcess)(spec.command, spec.args, {+ cwd,+ env: { ...process.env, CI: "1", GROK_DISABLE_AUTOUPDATER: "1" },+ shell: spec.shell,+ });+ } catch {+ return { status: "unhealthy", lastError: "grok_acp_spawn_failed" };+ }++ return new Promise((resolve) => {+ let settled = false;+ let buffer = "";+ let outputBytes = 0;+ let expectedId = 1;+ let authenticated = false;+ let catalog: RuntimeReasoningCatalog | undefined;+ let catalogGraceTimer: ReturnType<typeof setTimeout> | undefined;+ const finish = (value: GrokAcpProbeResult) => {+ if (settled) return;+ settled = true;+ clearTimeout(timer);+ if (catalogGraceTimer) clearTimeout(catalogGraceTimer);+ const cleanup = options.cleanup ?? cleanupProbeProcess;+ void Promise.resolve().then(() => cleanup(processHandle)).catch(() => {}).finally(() => resolve(value));+ };+ const write = (method: string, params: Record<string, unknown>, id: number) => {+ const stdin = processHandle.stdin;+ if (!stdin || stdin.destroyed || stdin.writableEnded || stdin.writable === false) {+ return finish({ status: "unhealthy", lastError: "grok_acp_transport_unavailable" });+ }+ try {+ stdin.write(`${jsonRpcRequest(method, params, id)}\n`);+ } catch {+ finish({ status: "unhealthy", lastError: "grok_acp_transport_unavailable" });+ }+ };+ const onLine = (line: string) => {+ const message = asRecord(tryParseJsonLine(line));+ if (!message) return finish({ status: "unhealthy", lastError: "grok_acp_invalid_response" });+ if (typeof message.method === "string") {+ if (message.method === "_x.ai/models/update" || message.method === "x.ai/models/update") {+ catalog = parseGrokModelCatalog(message.params) ?? catalog;+ if (authenticated && catalog) finish({ status: "compatible", reasoning: catalog });+ }+ return;+ }+ if (message.id !== expectedId) return;+ if (message.error !== undefined) {+ return finish({+ status: "unhealthy",+ lastError: expectedId === 1+ ? "grok_acp_initialize_failed"+ : "grok_acp_authentication_failed",+ });+ }+ if (!("result" in message)) {+ return finish({ status: "unhealthy", lastError: "grok_acp_invalid_response" });+ }+ const result = asRecord(message.result) ?? {};+ if (expectedId === 1) {+ const capabilities = asRecord(result.agentCapabilities);+ const methods = Array.isArray(result.authMethods) ? result.authMethods : [];+ const methodIds = methods.flatMap((method) => {+ const id = asRecord(method)?.id;+ return typeof id === "string" ? [id] : [];+ });+ if (result.protocolVersion !== ACP_PROTOCOL_VERSION) {+ return finish({ status: "unhealthy", lastError: "grok_acp_protocol_incompatible" });+ }+ if (capabilities?.loadSession !== true) {+ return finish({ status: "unhealthy", lastError: "grok_acp_load_session_unsupported" });+ }+ if (!methodIds.includes(AUTH_METHOD_ID)) {+ if (methodIds.some((id) => INTERACTIVE_AUTH_METHOD_IDS.has(id))) {+ return finish({ status: "unhealthy", lastError: "grok_acp_authentication_failed" });+ }+ return finish({ status: "unhealthy", lastError: "grok_acp_cached_auth_unsupported" });+ }+ catalog = catalogFromInitialize(result) ?? catalog;+ expectedId = 2;+ write("authenticate", { methodId: AUTH_METHOD_ID }, expectedId);+ return;+ }+ authenticated = true;+ if (catalog) return finish({ status: "compatible", reasoning: catalog });+ catalogGraceTimer = setTimeout(+ () => finish({ status: "compatible" }),+ options.catalogGraceMs ?? CATALOG_NOTIFICATION_GRACE_MS,+ );+ catalogGraceTimer.unref?.();+ };++ const timer = setTimeout(+ () => finish({ status: "unhealthy", lastError: "grok_acp_probe_timeout" }),+ options.timeoutMs ?? CATALOG_PROBE_TIMEOUT_MS,+ );+ timer.unref?.();+ processHandle.stdout?.on("data", (chunk) => {+ if (settled) return;+ const text = chunk.toString();+ outputBytes += Buffer.byteLength(text);+ if (outputBytes > (options.outputMaxBytes ?? CATALOG_PROBE_OUTPUT_MAX_BYTES)) {+ return finish({ status: "unhealthy", lastError: "grok_acp_output_limit" });+ }+ buffer += text;+ const lines = buffer.split("\n");+ buffer = lines.pop() ?? "";+ for (const line of lines) if (line.trim()) onLine(line);+ });+ processHandle.stderr?.on("data", (chunk) => {+ if (settled) return;+ outputBytes += Buffer.byteLength(chunk.toString());+ if (outputBytes > (options.outputMaxBytes ?? CATALOG_PROBE_OUTPUT_MAX_BYTES)) {+ finish({ status: "unhealthy", lastError: "grok_acp_output_limit" });+ }+ });+ const finishFromProcess = () => finish({+ status: "unhealthy",+ lastError: "grok_acp_process_failed",+ });+ processHandle.on("error", finishFromProcess);+ processHandle.on("exit", finishFromProcess);+ write("initialize", {+ protocolVersion: ACP_PROTOCOL_VERSION,+ clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },+ clientInfo: { name: "alook-agent-driver-probe", version: "0.1.31" },+ }, expectedId);+ });+}diff --git a/src/daemon/agent-driver/src/adapters/grok/index.test.ts b/src/daemon/agent-driver/src/adapters/grok/index.test.tsnew file mode 100644index 000000000..97b1ea827--- /dev/null+++ b/src/daemon/agent-driver/src/adapters/grok/index.test.ts@@ -0,0 +1,410 @@+import { EventEmitter } from "node:events";+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { PassThrough } from "node:stream";+import { afterEach, describe, expect, it, vi } from "vitest";+import type { SpawnedProcessHandle } from "../../internal/adapter.js";+import { fakeLaunchContext } from "../../testing/adapter-fixture.js";+import { parseGrokModelCatalog, probeGrokAcpCatalog } from "./catalog-probe.js";+import { GrokDriver } from "./index.js";++type FakeProcess = SpawnedProcessHandle & {+ stdout: PassThrough;+ stderr: PassThrough;+ stdin: PassThrough;+ emit(event: string, ...args: unknown[]): boolean;+};++const temporaryDirectories: string[] = [];++afterEach(() => {+ vi.restoreAllMocks();+ for (const directory of temporaryDirectories.splice(0)) rmSync(directory, { recursive: true, force: true });+});++function fakeProcess(onMessage: (process: FakeProcess, message: Record<string, unknown>) => void): FakeProcess {+ const process = Object.assign(new EventEmitter(), {+ stdout: new PassThrough(),+ stderr: new PassThrough(),+ stdin: new PassThrough(),+ pid: 4242,+ exitCode: null,+ signalCode: null,+ kill: vi.fn(() => true),+ }) as unknown as FakeProcess;+ let buffer = "";+ process.stdin.on("data", (chunk) => {+ buffer += chunk.toString();+ const lines = buffer.split("\n");+ buffer = lines.pop() ?? "";+ for (const line of lines) {+ if (line.trim()) onMessage(process, JSON.parse(line) as Record<string, unknown>);+ }+ });+ return process;+}++function respond(process: FakeProcess, request: Record<string, unknown>, result: unknown): void {+ process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", id: request.id, result })}\n`);+}++const modelState = {+ currentModelId: "grok-4.6",+ availableModels: [{+ modelId: "grok-4.6",+ name: "Grok 4.6",+ _meta: {+ supportsReasoningEffort: true,+ reasoningEffort: "high",+ reasoningEfforts: [+ { id: "deep", value: "xhigh", description: "Maximum reasoning" },+ { value: "high", default: true },+ { value: "medium" },+ { value: "low" },+ ],+ },+ }],+};++describe("Grok ACP model catalog", () => {+ it("preserves provider ids and dynamic reasoning values", () => {+ expect(parseGrokModelCatalog(modelState)).toEqual({+ updateMode: "live_next_turn",+ defaultModelId: "grok-4.6",+ models: [{+ id: "grok-4.6",+ displayName: "Grok 4.6",+ supportedReasoningEfforts: [+ { value: "xhigh", description: "Maximum reasoning" },+ { value: "high" },+ { value: "medium" },+ { value: "low" },+ ],+ defaultReasoningEffort: "high",+ }],+ });+ });++ it("normalizes models without reasoning and snake-case reasoning metadata", () => {+ expect(parseGrokModelCatalog({+ currentModelId: "plain",+ availableModels: [+ { modelId: "plain", name: "Plain" },+ { modelId: "snake", meta: { supportsReasoningEffort: true, reasoning_efforts: ["high"] } },+ { modelId: "empty", _meta: { supportsReasoningEffort: true } },+ ],+ })).toMatchObject({+ defaultModelId: "plain",+ models: [+ { id: "plain", supportedReasoningEfforts: [] },+ { id: "snake", supportedReasoningEfforts: [{ value: "high" }] },+ { id: "empty", supportedReasoningEfforts: [] },+ ],+ });+ });++ it("uses only initialize/authenticate, never creates a session, and cleans exactly once", async () => {+ const messages: Record<string, unknown>[] = [];+ const cleanup = vi.fn(async () => {});+ const process = fakeProcess((proc, message) => {+ messages.push(message);+ if (message.method === "initialize") {+ respond(proc, message, {+ protocolVersion: 1,+ agentCapabilities: { loadSession: true },+ authMethods: [{ id: "cached_token", name: "Cached token" }, { id: "grok.com" }],+ _meta: { modelState },+ });+ } else if (message.method === "authenticate") {+ respond(proc, message, {});+ }+ });+ let spawn: { command: string; args: string[]; options: { env: NodeJS.ProcessEnv } } | undefined;++ await expect(probeGrokAcpCatalog("/opt/grok", {+ cwd: "/tmp",+ spawn: (command, args, options) => {+ spawn = { command, args, options };+ return process;+ },+ cleanup,+ })).resolves.toEqual({+ status: "compatible",+ reasoning: parseGrokModelCatalog(modelState),+ });++ expect(spawn).toMatchObject({+ command: "/opt/grok",+ args: ["agent", "--no-leader", "stdio"],+ options: { env: { GROK_DISABLE_AUTOUPDATER: "1" } },+ });+ expect(messages.map((message) => message.method)).toEqual(["initialize", "authenticate"]);+ expect(messages.some((message) => String(message.method).startsWith("session/"))).toBe(false);+ expect(cleanup).toHaveBeenCalledTimes(1);+ });++ it("accepts the bounded model update fallback after auth", async () => {+ const cleanup = vi.fn(async () => {});+ const process = fakeProcess((proc, message) => {+ if (message.method === "initialize") {+ respond(proc, message, {+ protocolVersion: 1,+ agentCapabilities: { loadSession: true },+ authMethods: [{ id: "cached_token" }],+ });+ } else if (message.method === "authenticate") {+ respond(proc, message, {});+ proc.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", method: "_x.ai/models/update", params: modelState })}\n`);+ }+ });++ await expect(probeGrokAcpCatalog(undefined, { spawn: () => process, cleanup }))+ .resolves.toEqual({+ status: "compatible",+ reasoning: parseGrokModelCatalog(modelState),+ });+ expect(cleanup).toHaveBeenCalledTimes(1);+ });++ it.each([+ ["malformed response", (process: FakeProcess) => process.stdout.write("not-json\n"), "grok_acp_invalid_response"],+ ["protocol mismatch", (process: FakeProcess, message: Record<string, unknown>) => respond(process, message, {+ protocolVersion: 2,+ agentCapabilities: { loadSession: true },+ authMethods: [{ id: "cached_token" }],+ }), "grok_acp_protocol_incompatible"],+ ["missing loadSession", (process: FakeProcess, message: Record<string, unknown>) => respond(process, message, {+ protocolVersion: 1,+ agentCapabilities: { loadSession: false },+ authMethods: [{ id: "cached_token" }],+ }), "grok_acp_load_session_unsupported"],+ ["interactive login required", (process: FakeProcess, message: Record<string, unknown>) => respond(process, message, {+ protocolVersion: 1,+ agentCapabilities: { loadSession: true },+ authMethods: [{ id: "grok.com" }],+ }), "grok_acp_authentication_failed"],+ ["unsupported auth shape", (process: FakeProcess, message: Record<string, unknown>) => respond(process, message, {+ protocolVersion: 1,+ agentCapabilities: { loadSession: true },+ authMethods: [{ id: "unknown" }],+ }), "grok_acp_cached_auth_unsupported"],+ ] as const)("reports %s as unhealthy without provider details", async (_name, onMessage, lastError) => {+ const cleanup = vi.fn(async () => {});+ await expect(probeGrokAcpCatalog(undefined, {+ spawn: () => fakeProcess(onMessage),+ cleanup,+ timeoutMs: 25,+ })).resolves.toEqual({ status: "unhealthy", lastError });+ expect(cleanup).toHaveBeenCalledTimes(1);+ });++ it("reports authentication failure while accepting authenticated ACP without a catalog", async () => {+ const authFailure = fakeProcess((process, message) => {+ if (message.method === "initialize") {+ respond(process, message, {+ protocolVersion: 1,+ agentCapabilities: { loadSession: true },+ authMethods: [{ id: "cached_token" }],+ });+ } else {+ process.stdout.write(`${JSON.stringify({+ jsonrpc: "2.0",+ id: message.id,+ error: { code: -32_000, message: "secret provider detail" },+ })}\n`);+ }+ });+ await expect(probeGrokAcpCatalog(undefined, {+ spawn: () => authFailure,+ cleanup: async () => {},+ })).resolves.toEqual({+ status: "unhealthy",+ lastError: "grok_acp_authentication_failed",+ });++ const authenticated = fakeProcess((process, message) => {+ if (message.method === "initialize") {+ respond(process, message, {+ protocolVersion: 1,+ agentCapabilities: { loadSession: true },+ authMethods: [{ id: "cached_token" }],+ });+ } else {+ respond(process, message, {});+ }+ });+ await expect(probeGrokAcpCatalog(undefined, {+ spawn: () => authenticated,+ cleanup: async () => {},+ catalogGraceMs: 1,+ })).resolves.toEqual({ status: "compatible" });+ });++ it("reports spawn, process-exit, and initialize failures without leaking details", async () => {+ await expect(probeGrokAcpCatalog(undefined, {+ spawn: () => { throw new Error("secret spawn detail"); },+ })).resolves.toEqual({ status: "unhealthy", lastError: "grok_acp_spawn_failed" });++ const exited = fakeProcess((process) => process.emit("exit", 1, null));+ await expect(probeGrokAcpCatalog(undefined, {+ spawn: () => exited,+ cleanup: async () => {},+ })).resolves.toEqual({ status: "unhealthy", lastError: "grok_acp_process_failed" });++ const initializeFailure = fakeProcess((process, message) => {+ process.stdout.write(`${JSON.stringify({+ jsonrpc: "2.0",+ id: message.id,+ error: { code: -32_000, message: "secret initialize detail" },+ })}\n`);+ });+ await expect(probeGrokAcpCatalog(undefined, {+ spawn: () => initializeFailure,+ cleanup: async () => {},+ })).resolves.toEqual({ status: "unhealthy", lastError: "grok_acp_initialize_failed" });++ const cleanup = vi.fn(async () => {});+ const exitedAfterAuth = fakeProcess((process, message) => {+ if (message.method === "initialize") {+ respond(process, message, {+ protocolVersion: 1,+ agentCapabilities: { loadSession: true },+ authMethods: [{ id: "cached_token" }],+ });+ } else {+ respond(process, message, {});+ process.emit("exit", 0, null);+ }+ });+ await expect(probeGrokAcpCatalog(undefined, {+ spawn: () => exitedAfterAuth,+ cleanup,+ })).resolves.toEqual({ status: "unhealthy", lastError: "grok_acp_process_failed" });+ expect(cleanup).toHaveBeenCalledTimes(1);+ });++ it("bounds oversized and silent probes with one cleanup", async () => {++ const oversizedCleanup = vi.fn(async () => {});+ await expect(probeGrokAcpCatalog(undefined, {+ spawn: () => fakeProcess((process) => process.stderr.write("x".repeat(65))),+ cleanup: oversizedCleanup,+ outputMaxBytes: 64,+ timeoutMs: 25,+ })).resolves.toEqual({ status: "unhealthy", lastError: "grok_acp_output_limit" });+ expect(oversizedCleanup).toHaveBeenCalledTimes(1);++ const timeoutCleanup = vi.fn(async () => {});+ await expect(probeGrokAcpCatalog(undefined, {+ spawn: () => fakeProcess(() => {}),+ cleanup: timeoutCleanup,+ timeoutMs: 5,+ })).resolves.toEqual({ status: "unhealthy", lastError: "grok_acp_probe_timeout" });+ expect(timeoutCleanup).toHaveBeenCalledTimes(1);+ });++ it("covers default cleanup, transport failures, missing results, and stdout bounds", async () => {+ const cleaned = fakeProcess((process, message) => {+ if (message.method === "initialize") {+ respond(process, message, {+ protocolVersion: 1,+ agentCapabilities: { loadSession: true },+ authMethods: [{ id: "cached_token" }],+ _meta: { modelState },+ });+ } else {+ respond(process, message, {});+ }+ });+ Object.defineProperty(cleaned, "pid", { value: undefined, configurable: true });+ await expect(probeGrokAcpCatalog(undefined, { spawn: () => cleaned })).resolves.toMatchObject({+ status: "compatible",+ });+ expect(cleaned.kill).toHaveBeenCalledWith("SIGTERM");++ const unavailable = fakeProcess(() => {});+ unavailable.stdin.end();+ await expect(probeGrokAcpCatalog(undefined, {+ spawn: () => unavailable,+ cleanup: async () => {},+ })).resolves.toEqual({ status: "unhealthy", lastError: "grok_acp_transport_unavailable" });++ const throwing = fakeProcess(() => {});+ throwing.stdin.write = (() => { throw new Error("closed"); }) as typeof throwing.stdin.write;+ await expect(probeGrokAcpCatalog(undefined, {+ spawn: () => throwing,+ cleanup: async () => {},+ })).resolves.toEqual({ status: "unhealthy", lastError: "grok_acp_transport_unavailable" });++ const omitted = fakeProcess((process, message) => {+ process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", id: message.id })}\n`);+ });+ await expect(probeGrokAcpCatalog(undefined, {+ spawn: () => omitted,+ cleanup: async () => {},+ })).resolves.toEqual({ status: "unhealthy", lastError: "grok_acp_invalid_response" });++ const oversized = fakeProcess((process) => process.stdout.write("x".repeat(65)));+ await expect(probeGrokAcpCatalog(undefined, {+ spawn: () => oversized,+ cleanup: async () => {},+ outputMaxBytes: 64,+ })).resolves.toEqual({ status: "unhealthy", lastError: "grok_acp_output_limit" });+ });+});++describe("GrokDriver launch boundary", () => {+ it("declares persistent safe-boundary ACP and launches the owned no-leader process", async () => {+ const spawn = vi.fn(() => fakeProcess(() => {}));+ const driver = new GrokDriver(async () => ({ status: "compatible" }), spawn);+ const workingDirectory = mkdtempSync(join(tmpdir(), "grok-driver-test-"));+ temporaryDirectories.push(workingDirectory);+ const context = fakeLaunchContext("grok", workingDirectory, {+ config: {+ runtimeConfig: {+ model: { kind: "default" },+ environment: { GROK_DISABLE_AUTOUPDATER: "0", USER_VALUE: "kept" },+ command: process.execPath,+ },+ },+ });++ await driver.spawn(context);++ expect(driver.execution).toEqual({+ lifetime: "session",+ transport: { kind: "stdio_rpc", protocol: "grok.acp.v1" },+ wakeStart: "immediate",+ terminalOwnership: "transport_request",+ });+ expect(spawn).toHaveBeenCalledWith(process.execPath, ["agent", "--no-leader", "stdio"], expect.objectContaining({+ cwd: workingDirectory,+ shell: false,+ env: expect.objectContaining({ GROK_DISABLE_AUTOUPDATER: "1", USER_VALUE: "kept" }),+ }));+ });++ it("requires an authenticated compatible ACP probe before reporting healthy", async () => {+ const catalog = parseGrokModelCatalog(modelState);+ const success = vi.fn(async () => ({ status: "compatible" as const, reasoning: catalog }));+ await expect(new GrokDriver(success).probe(process.execPath)).resolves.toMatchObject({+ status: "healthy",+ reasoning: catalog,+ });+ expect(success).toHaveBeenCalledWith(process.execPath);++ await expect(new GrokDriver(async () => ({ status: "compatible" })).probe(process.execPath))+ .resolves.toMatchObject({ status: "healthy", reasoning: undefined });++ await expect(new GrokDriver(async () => ({+ status: "unhealthy",+ lastError: "grok_acp_authentication_failed",+ })).probe(process.execPath)).resolves.toMatchObject({+ status: "unhealthy",+ lastError: "grok_acp_authentication_failed",+ });+ await expect(new GrokDriver(async () => { throw new Error("provider secret"); }).probe(process.execPath))+ .resolves.toMatchObject({ status: "unhealthy", lastError: "grok_acp_probe_failed" });+ });+});diff --git a/src/daemon/agent-driver/src/adapters/grok/index.ts b/src/daemon/agent-driver/src/adapters/grok/index.tsnew file mode 100644index 000000000..57a2aecae--- /dev/null+++ b/src/daemon/agent-driver/src/adapters/grok/index.ts@@ -0,0 +1,73 @@+import type {+ AdapterLaunchContext,+ BackendAdapter,+ RuntimeLane,+ RuntimeLaneOpenOptions,+ SpawnedProcess,+ SpawnedProcessHandle,+} from "../../internal/adapter.js";+import { prepareCliTransport } from "../../internal/cliTransport.js";+import { resolveLaunchFieldsOrDefault } from "../../internal/config.js";+import { spawnAgentProcess } from "../../internal/killTree.js";+import { probeCliRuntime, resolveSpawnSpec } from "../../internal/probe.js";+import { GrokAcpLane, type GrokAcpProcessFactory } from "./acp-lane.js";+import { probeGrokAcpCatalog, type GrokAcpProbeResult } from "./catalog-probe.js";+import { discoverGrokRecentContext } from "./recent-context.js";++type GrokSpawn = (+ command: string,+ args: string[],+ options: { cwd: string; env: NodeJS.ProcessEnv; shell: boolean },+) => SpawnedProcessHandle;++export class GrokDriver implements BackendAdapter, GrokAcpProcessFactory {+ readonly id = "grok";+ readonly instructionDelivery = { kind: "workspace_file", canonical: "AGENTS.md", aliases: ["CLAUDE.md"] } as const;+ readonly execution = {+ lifetime: "session",+ transport: { kind: "stdio_rpc", protocol: "grok.acp.v1" },+ wakeStart: "immediate",+ terminalOwnership: "transport_request",+ } as const;++ discoverRecentContext(request: Parameters<typeof discoverGrokRecentContext>[0]) {+ return discoverGrokRecentContext(request);+ }++ constructor(+ private readonly catalogProbe: (command?: string) => Promise<GrokAcpProbeResult> = probeGrokAcpCatalog,+ private readonly spawnProcess: GrokSpawn = spawnAgentProcess,+ ) {}++ async probe(command?: string) {+ const result = probeCliRuntime("grok", {}, command);+ if (result.status !== "healthy") return result;+ let acpProbe: GrokAcpProbeResult;+ try {+ acpProbe = await this.catalogProbe(command);+ } catch {+ acpProbe = { status: "unhealthy", lastError: "grok_acp_probe_failed" };+ }+ if (acpProbe.status === "unhealthy") {+ return { ...result, status: "unhealthy" as const, lastError: acpProbe.lastError };+ }+ return { ...result, reasoning: acpProbe.reasoning };+ }++ async openLane(ctx: AdapterLaunchContext, options?: RuntimeLaneOpenOptions): Promise<RuntimeLane> {+ return new GrokAcpLane(this, ctx, { onRawStdoutLine: options?.onRawStdoutLine });+ }++ async spawn(ctx: AdapterLaunchContext): Promise<SpawnedProcess> {+ const { spawnEnv } = await prepareCliTransport(ctx, { GROK_DISABLE_AUTOUPDATER: "1" });+ const override = resolveLaunchFieldsOrDefault(ctx.config.runtimeConfig).command;+ const spec = resolveSpawnSpec("grok", ["agent", "--no-leader", "stdio"], override);+ return {+ process: this.spawnProcess(spec.command, spec.args, {+ cwd: ctx.workingDirectory,+ env: { ...spawnEnv, GROK_DISABLE_AUTOUPDATER: "1" },+ shell: spec.shell,+ }),+ };+ }+}diff --git a/src/daemon/agent-driver/src/adapters/grok/recent-context.test.ts b/src/daemon/agent-driver/src/adapters/grok/recent-context.test.tsnew file mode 100644index 000000000..6b38efe72--- /dev/null+++ b/src/daemon/agent-driver/src/adapters/grok/recent-context.test.ts@@ -0,0 +1,203 @@+import { EventEmitter } from "node:events";+import path from "node:path";+import { PassThrough } from "node:stream";+import { describe, expect, it, vi } from "vitest";+import type { SpawnedProcessHandle } from "../../internal/adapter.js";+import { discoverGrokRecentContext } from "./recent-context.js";++type RpcRequest = { id: number; method: string; params: Record<string, unknown> };++function fakeRpcProcess(onRequest: (request: RpcRequest, respond: (result: unknown) => void) => void) {+ const stdout = new PassThrough();+ const stdin = new PassThrough();+ const requests: RpcRequest[] = [];+ let buffer = "";+ const process = Object.assign(new EventEmitter(), {+ stdout,+ stderr: new PassThrough(),+ stdin,+ pid: undefined,+ exitCode: null,+ signalCode: null,+ kill: vi.fn(() => true),+ }) as unknown as SpawnedProcessHandle;+ stdin.on("data", (chunk) => {+ buffer += chunk.toString();+ const lines = buffer.split("\n");+ buffer = lines.pop() ?? "";+ for (const line of lines) {+ if (!line.trim()) continue;+ const request = JSON.parse(line) as RpcRequest;+ requests.push(request);+ onRequest(request, (result) => queueMicrotask(() => {+ stdout.write(`${JSON.stringify({ jsonrpc: "2.0", id: request.id, result })}\n`);+ }));+ }+ });+ return { process, requests };+}++describe("Grok recent-context discovery", () => {+ it("uses the persistent ACP list API, paginates, deduplicates, and cleans up", async () => {+ const root = path.parse(process.cwd()).root;+ const projectA = path.join(root, "projects", "grok-a");+ const projectB = path.join(root, "projects", "grok-b");+ const rpc = fakeRpcProcess((request, respond) => {+ if (request.method === "initialize") {+ respond({+ protocolVersion: 1,+ agentCapabilities: { sessionCapabilities: { list: true } },+ authMethods: [{ id: "cached_token" }],+ });+ } else if (request.method === "authenticate") {+ respond({});+ } else if (request.params.cursor === "next") {+ respond({ sessions: [{ cwd: projectB, updatedAt: "2026-09-02T00:00:00Z" }] });+ } else {+ respond({+ sessions: [+ { cwd: projectA, updatedAt: "2026-09-03T00:00:00Z" },+ { cwd: projectA, updatedAt: "2026-09-01T00:00:00Z" },+ { cwd: "relative", updatedAt: "2026-09-04T00:00:00Z" },+ ],+ nextCursor: "next",+ });+ }+ });+ const cleanup = vi.fn(async () => {});+ const spawn = vi.fn(() => rpc.process);++ const result = await discoverGrokRecentContext({+ recentSessionFilesTopK: 5,+ recentProjectsTopK: 2,+ command: "/opt/grok build",+ }, { spawn, cleanup, cwd: projectA });++ expect(result).toEqual({+ sessionFiles: { capability: "unavailable", items: [] },+ recentProjects: [+ { projectPath: projectA, modifiedAt: "2026-09-03T00:00:00.000Z" },+ { projectPath: projectB, modifiedAt: "2026-09-02T00:00:00.000Z" },+ ],+ });+ expect(spawn).toHaveBeenCalledWith("/opt/grok build", ["agent", "--no-leader", "stdio"], expect.objectContaining({+ cwd: projectA,+ env: expect.objectContaining({ GROK_DISABLE_AUTOUPDATER: "1" }),+ shell: false,+ }));+ expect(rpc.requests.map((request) => request.method)).toEqual([+ "initialize",+ "authenticate",+ "session/list",+ "session/list",+ ]);+ expect(rpc.requests.some((request) => request.method === "session/new")).toBe(false);+ expect(cleanup).toHaveBeenCalledOnce();+ });++ it("fails closed when list or authentication capability is missing", async () => {+ for (const initialize of [+ { protocolVersion: 1, agentCapabilities: {}, authMethods: [{ id: "cached_token" }] },+ { protocolVersion: 1, agentCapabilities: { sessionCapabilities: { list: true } }, authMethods: [] },+ ]) {+ const rpc = fakeRpcProcess((_request, respond) => respond(initialize));+ await expect(discoverGrokRecentContext({+ recentSessionFilesTopK: 0,+ recentProjectsTopK: 1,+ }, { spawn: () => rpc.process, cleanup: async () => {} })).rejects.toThrow(/unavailable/);+ }+ });++ it("accepts the data compatibility field and flushes a final line without a newline", async () => {+ const root = path.parse(process.cwd()).root;+ const project = path.join(root, "projects", "grok-final");+ const stdout = new PassThrough();+ const stdin = new PassThrough();+ let buffer = "";+ const processHandle = Object.assign(new EventEmitter(), {+ stdout,+ stderr: new PassThrough(),+ stdin,+ pid: undefined,+ exitCode: null,+ signalCode: null,+ kill: vi.fn(() => true),+ }) as unknown as SpawnedProcessHandle;+ stdin.on("data", (chunk) => {+ buffer += chunk.toString();+ const lines = buffer.split("\n");+ buffer = lines.pop() ?? "";+ for (const line of lines) {+ if (!line.trim()) continue;+ const request = JSON.parse(line) as RpcRequest;+ if (request.method === "initialize") {+ stdout.write(`${JSON.stringify({ jsonrpc: "2.0", id: request.id, result: {+ protocolVersion: 1,+ agentCapabilities: { sessionCapabilities: { list: {} } },+ authMethods: [{ id: "cached_token" }],+ } })}\n`);+ } else if (request.method === "authenticate") {+ stdout.write(`${JSON.stringify({ jsonrpc: "2.0", id: request.id, result: {} })}\n`);+ } else {+ stdout.end(JSON.stringify({+ jsonrpc: "2.0",+ id: request.id,+ result: { data: [{ cwd: project, updatedAt: "2026-09-04T00:00:00Z" }] },+ }));+ }+ }+ });++ await expect(discoverGrokRecentContext({+ recentSessionFilesTopK: 0,+ recentProjectsTopK: 1,+ }, { spawn: () => processHandle, cleanup: async () => {} })).resolves.toMatchObject({+ recentProjects: [{ projectPath: project }],+ });+ });++ it("returns an empty result when the list response omits sessions and a cursor", async () => {+ const rpc = fakeRpcProcess((request, respond) => {+ if (request.method === "initialize") {+ respond({+ protocolVersion: 1,+ agentCapabilities: { sessionCapabilities: { list: true } },+ authMethods: [{ id: "cached_token" }],+ });+ } else {+ respond({});+ }+ });++ await expect(discoverGrokRecentContext({+ recentSessionFilesTopK: 0,+ recentProjectsTopK: 1,+ }, { spawn: () => rpc.process, cleanup: async () => {} })).resolves.toEqual({+ sessionFiles: { capability: "unavailable", items: [] },+ recentProjects: [],+ });+ });++ it("fails on an incompatible protocol and an early process exit", async () => {+ const incompatible = fakeRpcProcess((_request, respond) => respond({+ protocolVersion: 2,+ agentCapabilities: { sessionCapabilities: { list: true } },+ authMethods: [{ id: "cached_token" }],+ }));+ await expect(discoverGrokRecentContext({+ recentSessionFilesTopK: 0,+ recentProjectsTopK: 1,+ }, { spawn: () => incompatible.process, cleanup: async () => {} }))+ .rejects.toThrow("protocol is incompatible");++ let exited!: ReturnType<typeof fakeRpcProcess>;+ exited = fakeRpcProcess(() => queueMicrotask(() => {+ (exited.process as unknown as EventEmitter).emit("exit", 1, null);+ }));+ await expect(discoverGrokRecentContext({+ recentSessionFilesTopK: 0,+ recentProjectsTopK: 1,+ }, { spawn: () => exited.process, cleanup: async () => {} }))+ .rejects.toThrow("process exited early");+ });+});diff --git a/src/daemon/agent-driver/src/adapters/grok/recent-context.ts b/src/daemon/agent-driver/src/adapters/grok/recent-context.tsnew file mode 100644index 000000000..e72461e99--- /dev/null+++ b/src/daemon/agent-driver/src/adapters/grok/recent-context.ts@@ -0,0 +1,123 @@+import type { RecentContextDiscoveryData, RecentContextDiscoveryRequest } from "../../contract.js";+import {+ type DiscoveryProcessControl,+ type DiscoveryProcessDependencies,+ runBoundedDiscoveryProcess,+} from "../../internal/discovery-process.js";+import { spawnAgentProcess } from "../../internal/killTree.js";+import { resolveSpawnSpec } from "../../internal/probe.js";+import { RecentContextCollector } from "../../internal/recent-context.js";+import { asRecord, jsonRpcRequest, tryParseJsonLine } from "../../internal/utils.js";++const ACP_PROTOCOL_VERSION = 1;+const AUTH_METHOD_ID = "cached_token";+const GROK_DISCOVERY_TIMEOUT_MS = 30_000;+const GROK_DISCOVERY_OUTPUT_MAX_BYTES = 4 * 1024 * 1024;++type GrokRecentContextDependencies = DiscoveryProcessDependencies;++export async function discoverGrokRecentContext(+ request: RecentContextDiscoveryRequest,+ dependencies: GrokRecentContextDependencies = {},+): Promise<RecentContextDiscoveryData> {+ const collector = new RecentContextCollector(request, "unavailable");+ if (collector.satisfied) return collector.result();+ const spec = resolveSpawnSpec("grok", ["agent", "--no-leader", "stdio"], request.command);+ const processHandle = (dependencies.spawn ?? spawnAgentProcess)(spec.command, spec.args, {+ cwd: dependencies.cwd ?? process.cwd(),+ env: { ...process.env, GROK_DISABLE_AUTOUPDATER: "1" },+ shell: spec.shell,+ });++ let buffer = "";+ let requestId = 0;+ let expectedId = 0;+ let expectedMethod = "";+ const seenCursors = new Set<string>();+ const requestRpc = (+ method: string,+ params: Record<string, unknown>,+ control: DiscoveryProcessControl<RecentContextDiscoveryData>,+ ) => {+ expectedId = ++requestId;+ expectedMethod = method;+ control.write(`${jsonRpcRequest(method, params, expectedId)}\n`);+ };+ const requestPage = (control: DiscoveryProcessControl<RecentContextDiscoveryData>, cursor?: string) =>+ requestRpc("session/list", cursor ? { cursor } : {}, control);+ const onLine = (line: string, control: DiscoveryProcessControl<RecentContextDiscoveryData>) => {+ const message = asRecord(tryParseJsonLine(line));+ if (!message || message.id !== expectedId) return;+ if (message.error !== undefined) return control.fail("Grok discovery request failed");+ const result = asRecord(message.result);+ if (!result) return control.fail("Grok discovery returned an invalid response");+ if (expectedMethod === "initialize") {+ if (result.protocolVersion !== ACP_PROTOCOL_VERSION) {+ return control.fail("Grok discovery protocol is incompatible");+ }+ const capabilities = asRecord(result.agentCapabilities);+ const sessionCapabilities = asRecord(capabilities?.sessionCapabilities);+ if (sessionCapabilities?.list !== true && !asRecord(sessionCapabilities?.list)) {+ return control.fail("Grok session listing is unavailable");+ }+ const authMethods = Array.isArray(result.authMethods) ? result.authMethods : [];+ if (!authMethods.some((method) => asRecord(method)?.id === AUTH_METHOD_ID)) {+ return control.fail("Grok discovery authentication is unavailable");+ }+ requestRpc("authenticate", { methodId: AUTH_METHOD_ID }, control);+ return;+ }+ if (expectedMethod === "authenticate") {+ requestPage(control);+ return;+ }+ if (expectedMethod !== "session/list") return control.fail("Grok discovery state is invalid");+ const sessions = Array.isArray(result.sessions)+ ? result.sessions+ : Array.isArray(result.data)+ ? result.data+ : [];+ for (const value of sessions) {+ const session = asRecord(value);+ if (!session) continue;+ collector.add({ projectPath: session.cwd, modifiedAt: session.updatedAt });+ if (collector.satisfied) return control.finish(collector.result());+ }+ const nextCursor = typeof result.nextCursor === "string" && result.nextCursor+ ? result.nextCursor+ : undefined;+ if (!nextCursor) return control.finish(collector.result());+ if (seenCursors.has(nextCursor)) return control.fail("Grok discovery cursor repeated");+ seenCursors.add(nextCursor);+ requestPage(control, nextCursor);+ };++ return runBoundedDiscoveryProcess({+ process: processHandle,+ label: "Grok",+ timeoutMs: dependencies.timeoutMs ?? GROK_DISCOVERY_TIMEOUT_MS,+ outputMaxBytes: dependencies.outputMaxBytes ?? GROK_DISCOVERY_OUTPUT_MAX_BYTES,+ cleanup: dependencies.cleanup,+ exitEvent: "exit",+ onStdout: (text, final, control) => {+ buffer += text;+ const lines = buffer.split("\n");+ buffer = lines.pop() ?? "";+ for (const line of lines) if (line.trim()) onLine(line, control);+ if (final && buffer.trim()) {+ const line = buffer;+ buffer = "";+ onLine(line, control);+ }+ },+ onExit: (_code, _signal, control) => control.fail("Grok discovery process exited early"),+ onStart: (control) => requestRpc("initialize", {+ protocolVersion: ACP_PROTOCOL_VERSION,+ clientCapabilities: {+ fs: { readTextFile: false, writeTextFile: false },+ terminal: false,+ },+ clientInfo: { name: "alook-agent-driver-discovery", version: "0.1.31" },+ }, control),+ });+}diff --git a/src/daemon/agent-driver/src/adapters/grok/telemetry.test.ts b/src/daemon/agent-driver/src/adapters/grok/telemetry.test.tsnew file mode 100644index 000000000..809c8a134--- /dev/null+++ b/src/daemon/agent-driver/src/adapters/grok/telemetry.test.ts@@ -0,0 +1,152 @@+import { describe, expect, it } from "vitest";+import { SettledUsageProjector } from "../../internal/token-usage.js";+import { normalizeGrokBilling, projectGrokUsage } from "./telemetry.js";++const epoch = "abcdefghijklmnopqrstuv";++describe("Grok telemetry", () => {+ it("projects disjoint input/cache while keeping output inclusive of reasoning and deduplicates", () => {+ const projector = new SettledUsageProjector();+ const usage = {+ inputTokens: 120,+ outputTokens: 40,+ cachedReadTokens: 15,+ cacheCreationTokens: 5,+ reasoningTokens: 10,+ };+ expect(projectGrokUsage(projector, "session", "prompt", usage)).toEqual({+ kind: "telemetry",+ name: "token_usage",+ source: "grok.acp",+ usage: { input: 100, output: 40, cache: 20 },+ });+ expect(projectGrokUsage(projector, "session", "prompt", usage)).toBeNull();+ });++ it("does not invent incomplete or malformed usage", () => {+ const projector = new SettledUsageProjector();+ expect(projectGrokUsage(projector, "session", "incomplete", {+ usageIsIncomplete: true,+ inputTokens: 10,+ })).toBeNull();+ expect(projectGrokUsage(projector, "session", "malformed", {+ inputTokens: 10,+ cachedReadTokens: 20,+ outputTokens: -1,+ })).toEqual({+ kind: "telemetry",+ name: "token_usage",+ source: "grok.acp",+ usage: { input: null, output: null, cache: 20 },+ });+ });++ it("maps weekly billing and the official unified zero shape", () => {+ expect(normalizeGrokBilling({+ subscriptionTier: "SuperGrok",+ config: {+ currentPeriod: {+ type: "USAGE_PERIOD_TYPE_WEEKLY",+ creditUsagePercent: 12.5,+ start: "2026-09-01T00:00:00Z",+ end: "2026-09-08T00:00:00Z",+ },+ },+ }, epoch)).toEqual({+ status: "available",+ sourceEpoch: epoch,+ planName: "SuperGrok",+ freshForSeconds: 300,+ limits: [{+ bucket: {+ limitId: "grok-build",+ product: { kind: "reported", id: "grok", displayName: "Grok Build" },+ model: { kind: "not_applicable" },+ window: {+ kind: "provider_defined",+ id: "USAGE_PERIOD_TYPE_WEEKLY",+ durationSeconds: 604800,+ displayName: "Weekly limit",+ },+ },+ usedPercent: 12.5,+ resetsAt: "2026-09-08T00:00:00.000Z",+ }],+ });++ expect(normalizeGrokBilling({+ config: {+ isUnifiedBillingUser: true,+ currentPeriod: { type: "USAGE_PERIOD_TYPE_WEEKLY" },+ onDemandCap: { val: 0 },+ onDemandUsed: { val: 0 },+ prepaidBalance: { val: 0 },+ },+ }, epoch)).toMatchObject({+ status: "available",+ limits: [{ usedPercent: 0 }],+ });+ });++ it("returns schema-shaped errors instead of claiming quota for unusable billing", () => {+ expect(normalizeGrokBilling({}, epoch)).toEqual({+ status: "error",+ sourceEpoch: epoch,+ code: "invalid_response",+ retryable: true,+ });+ });++ it("uses legacy billing dates, duration, and plan-name fallbacks", () => {+ expect(normalizeGrokBilling({+ subscription_tier: "Legacy",+ config: {+ currentPeriod: {+ type: "USAGE_PERIOD_TYPE_MONTHLY",+ creditUsagePercent: 20,+ billingPeriodStart: "2026-09-01T00:00:00Z",+ billingPeriodEnd: "2026-10-01T00:00:00Z",+ },+ },+ }, epoch)).toMatchObject({+ status: "available",+ planName: "Legacy",+ limits: [{+ bucket: { window: { durationSeconds: 2_592_000 } },+ resetsAt: "2026-10-01T00:00:00.000Z",+ }],+ });++ expect(normalizeGrokBilling({+ config: {+ currentPeriod: { creditUsagePercent: 30 },+ billingPeriodStart: "2026-09-01T00:00:00Z",+ billingPeriodEnd: "2026-09-11T00:00:00Z",+ },+ }, epoch)).toMatchObject({+ status: "available",+ limits: [{ bucket: { window: { durationSeconds: 864_000 } } }],+ });++ expect(normalizeGrokBilling({+ config: { currentPeriod: { creditUsagePercent: 40 } },+ }, epoch)).toEqual({+ status: "available",+ sourceEpoch: epoch,+ freshForSeconds: 300,+ limits: [{+ bucket: {+ limitId: "grok-build",+ product: { kind: "reported", id: "grok", displayName: "Grok Build" },+ model: { kind: "not_applicable" },+ window: {+ kind: "provider_defined",+ id: "grok-build",+ displayName: "Grok Build limit",+ },+ },+ usedPercent: 40,+ }],+ });+ });+});diff --git a/src/daemon/agent-driver/src/adapters/grok/telemetry.ts b/src/daemon/agent-driver/src/adapters/grok/telemetry.tsnew file mode 100644index 000000000..f35f6a04c--- /dev/null+++ b/src/daemon/agent-driver/src/adapters/grok/telemetry.ts@@ -0,0 +1,115 @@+import type { AdapterEvent } from "../../internal/adapter.js";+import { SettledUsageProjector } from "../../internal/token-usage.js";+import type { ProviderQuotaObservation } from "../../contract.js";+import { asRecord } from "../../internal/utils.js";++const SEVEN_DAY_SECONDS = 7 * 24 * 60 * 60;++function number(value: unknown): number | undefined {+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined;+}++function amount(value: unknown): number | undefined {+ const row = asRecord(value);+ return number(row?.val ?? value);+}++export function projectGrokUsage(+ projector: SettledUsageProjector,+ sessionId: string,+ promptId: string,+ value: unknown,+): AdapterEvent | null {+ const usage = asRecord(value);+ if (!usage || usage.usageIsIncomplete === true) return null;+ return projector.project({+ runtime: "grok",+ backendSessionId: sessionId,+ providerRecordId: promptId,+ source: "grok.acp",+ input: usage.inputTokens,+ output: usage.outputTokens,+ reasoning: usage.reasoningTokens,+ cacheRead: usage.cachedReadTokens,+ cacheWrite: usage.cacheCreationTokens,+ inputIncludesCache: true,+ outputIncludesReasoning: true,+ });+}++function invalidQuota(sourceEpoch: string): ProviderQuotaObservation {+ return { status: "error", sourceEpoch, code: "invalid_response", retryable: true };+}++export function normalizeGrokBilling(value: unknown, sourceEpoch: string): ProviderQuotaObservation {+ const billing = asRecord(value);+ const config = asRecord(billing?.config);+ if (!billing || !config) return invalidQuota(sourceEpoch);+ const history = Array.isArray(config.history) ? config.history : [];+ const period = asRecord(config.currentPeriod) ?? asRecord(history.at(-1)) ?? config;+ let usedPercent = number(period.creditUsagePercent) ?? number(config.creditUsagePercent);+ if (usedPercent === undefined) {+ const limit = amount(period.monthlyLimit ?? config.monthlyLimit);+ const used = amount(period.totalUsed ?? period.includedUsed ?? period.used ?? config.totalUsed ?? config.used);+ if (limit && used !== undefined) usedPercent = (used / limit) * 100;+ }+ if (+ usedPercent === undefined+ && config.isUnifiedBillingUser === true+ && asRecord(config.currentPeriod)?.type === "USAGE_PERIOD_TYPE_WEEKLY"+ && amount(config.onDemandCap) === 0+ && amount(config.onDemandUsed) === 0+ && amount(config.prepaidBalance) === 0+ ) usedPercent = 0;+ if (usedPercent === undefined) return invalidQuota(sourceEpoch);++ const start = typeof period.start === "string"+ ? period.start+ : typeof period.billingPeriodStart === "string"+ ? period.billingPeriodStart+ : typeof config.billingPeriodStart === "string"+ ? config.billingPeriodStart+ : undefined;+ const end = typeof period.end === "string"+ ? period.end+ : typeof period.billingPeriodEnd === "string"+ ? period.billingPeriodEnd+ : typeof config.billingPeriodEnd === "string"+ ? config.billingPeriodEnd+ : undefined;+ const startMs = start ? Date.parse(start) : Number.NaN;+ const endMs = end ? Date.parse(end) : Number.NaN;+ const durationSeconds = period.type === "USAGE_PERIOD_TYPE_WEEKLY"+ ? SEVEN_DAY_SECONDS+ : Number.isFinite(startMs) && Number.isFinite(endMs) && endMs > startMs+ ? Math.round((endMs - startMs) / 1_000)+ : undefined;+ const resetsAt = Number.isFinite(endMs) ? new Date(endMs).toISOString() : undefined;+ const periodId = typeof period.type === "string" && period.type.trim() ? period.type : "grok-build";+ const planName = typeof billing.subscriptionTier === "string" && billing.subscriptionTier.trim()+ ? billing.subscriptionTier+ : typeof billing.subscription_tier === "string" && billing.subscription_tier.trim()+ ? billing.subscription_tier+ : undefined;+ return {+ status: "available",+ sourceEpoch,+ ...(planName ? { planName } : {}),+ freshForSeconds: 300,+ limits: [{+ bucket: {+ limitId: "grok-build",+ product: { kind: "reported", id: "grok", displayName: "Grok Build" },+ model: { kind: "not_applicable" },+ window: {+ kind: "provider_defined",+ id: periodId,+ ...(durationSeconds ? { durationSeconds } : {}),+ displayName: period.type === "USAGE_PERIOD_TYPE_WEEKLY" ? "Weekly limit" : "Grok Build limit",+ },+ },+ usedPercent: Math.min(100, usedPercent),+ ...(resetsAt ? { resetsAt } : {}),+ }],+ };+}diff --git a/src/daemon/agent-driver/src/builtin-config.test.ts b/src/daemon/agent-driver/src/builtin-config.test.tsindex fe8a9bd9a..86196506f 100644--- a/src/daemon/agent-driver/src/builtin-config.test.ts+++ b/src/daemon/agent-driver/src/builtin-config.test.ts@@ -32,10 +32,25 @@ describe("builtin config boundary", () => {});});- it.each(["codex", "cursor", "opencode", "pi"])("maps %s without daemon-side switches", (runtime) => {+ it.each(["codex", "cursor", "grok", "opencode", "pi"])("maps %s without daemon-side switches", (runtime) => {expect(toBuiltinBackendSelection(config(runtime))).toMatchObject({ backend: runtime });});+ it("maps Grok reasoning without provider configuration", () => {+ expect(toBuiltinBackendSelection(config("grok", {+ reasoningEffort: "xhigh",+ provider: { kind: "custom", apiUrl: "https://example.invalid", apiKey: "must-not-leak" },+ }))).toEqual({+ backend: "grok",+ config: {+ model: { kind: "default" },+ command: undefined,+ environment: undefined,+ reasoningEffort: "xhigh",+ },+ });+ });+it("rejects unknown runtime ids", () => {expect(() => toBuiltinBackendSelection(config("unknown"))).toThrow("Unknown runtime: unknown");});diff --git a/src/daemon/agent-driver/src/builtin-config.ts b/src/daemon/agent-driver/src/builtin-config.tsindex 8e3ca29a5..aa80dcad3 100644--- a/src/daemon/agent-driver/src/builtin-config.ts+++ b/src/daemon/agent-driver/src/builtin-config.ts@@ -50,6 +50,8 @@ export function toBuiltinBackendSelection(config: BuiltinRuntimeConfigInput): Bu};case "cursor":return { backend: "cursor", config: base };+ case "grok":+ return { backend: "grok", config: { ...base, reasoningEffort: config.reasoningEffort } };case "opencode":return { backend: "opencode", config: base };case "pi":diff --git a/src/daemon/agent-driver/src/contract.ts b/src/daemon/agent-driver/src/contract.tsindex 9464a4d13..fbce5a1ee 100644--- a/src/daemon/agent-driver/src/contract.ts+++ b/src/daemon/agent-driver/src/contract.ts@@ -2,7 +2,7 @@ export type JsonPrimitive = string | number | boolean | null;export type JsonValue = JsonPrimitive | JsonObject | readonly JsonValue[];export type JsonObject = { readonly [key: string]: JsonValue };-export type BuiltinBackendId = "claude" | "codex" | "cursor" | "opencode" | "pi";+export type BuiltinBackendId = "claude" | "codex" | "cursor" | "grok" | "opencode" | "pi";export type ReasoningEffort =| "minimal"| "low"@@ -77,6 +77,9 @@ export interface ModelBackendConfig extends BaseBackendConfig {}export type CursorConfig = ModelBackendConfig;+export interface GrokConfig extends ModelBackendConfig {+ readonly reasoningEffort?: ReasoningEffort;+}export type OpenCodeConfig = ModelBackendConfig;export interface PiConfig extends Omit<BaseBackendConfig, "command"> {@@ -122,6 +125,7 @@ export type FixedCapabilities<export type ClaudeCapabilities = FixedCapabilities<true, true, true, true, true, "safe_boundary_queue", "persistent">;export type CodexCapabilities = FixedCapabilities<false, true, true, false, true, "safe_boundary_queue", "persistent">;export type CursorCapabilities = FixedCapabilities<false, false, false, false, true, "steer", "persistent">;+export type GrokCapabilities = FixedCapabilities<false, true, false, false, true, "safe_boundary_queue", "persistent">;export type OpenCodeCapabilities = FixedCapabilities<false, false, false, false, true, "steer", "persistent">;export type PiCapabilities = FixedCapabilities<true, true, false, false, false, "steer", "persistent">;@@ -141,6 +145,7 @@ export interface BuiltinBackendSpecs {readonly claude: BackendTypeSpec<ClaudeConfig, ClaudeCapabilities, {}, never>;readonly codex: BackendTypeSpec<CodexConfig, CodexCapabilities, {}, never>;readonly cursor: BackendTypeSpec<CursorConfig, CursorCapabilities, {}, never>;+ readonly grok: BackendTypeSpec<GrokConfig, GrokCapabilities, {}, never>;readonly opencode: BackendTypeSpec<OpenCodeConfig, OpenCodeCapabilities, {}, never>;readonly pi: BackendTypeSpec<PiConfig, PiCapabilities, {}, never>;}diff --git a/src/daemon/agent-driver/src/controller/logical-session.test.ts b/src/daemon/agent-driver/src/controller/logical-session.test.tsindex 645976df3..8d6ff6fc0 100644--- a/src/daemon/agent-driver/src/controller/logical-session.test.ts+++ b/src/daemon/agent-driver/src/controller/logical-session.test.ts@@ -32,6 +32,7 @@ const configs: Record<BuiltinBackendId, unknown> = {claude: { model: { kind: "default" }, provider: { kind: "default" }, mode: "default" },codex: { model: { kind: "default" }, mode: "default" },cursor: { model: { kind: "default" } },+ grok: { model: { kind: "default" } },opencode: { model: { kind: "default" } },pi: { model: { kind: "default" }, provider: { kind: "default" } },};@@ -254,10 +255,10 @@ function executionFor(backend: BuiltinBackendId): BackendExecution {terminalOwnership: "transport_request",};}- if (backend === "cursor") {+ if (backend === "cursor" || backend === "grok") {return {lifetime: "session",- transport: { kind: "stdio_rpc", protocol: "cursor.test.v1" },+ transport: { kind: "stdio_rpc", protocol: `${backend}.test.v1` },wakeStart: "immediate",terminalOwnership: "transport_request",};@@ -352,7 +353,7 @@ async function take(return events;}-describe.each(["claude", "codex", "cursor", "opencode", "pi"] as const)("%s logical-session conformance", (backend) => {+describe.each(["claude", "codex", "cursor", "grok", "opencode", "pi"] as const)("%s logical-session conformance", (backend) => {it("projects the public bounded turn-silence defaults", async () => {const { session } = makeSession(backend);expect(session.snapshot().diagnostics.turnSilence).toEqual({@@ -1293,6 +1294,33 @@ describe("backend-owned delivery behavior", () => {await session.stop({ reason: "shutdown", forceAfterMs: 10 });});+ it("keeps a safe-boundary command queued when Grok reports busy and starts it after the root terminal", async () => {+ const lane = new ControlledRuntimeLane();+ lane.startAdmission = { ok: true, acceptedAs: "prompt", receipt: "grok:test:1" };+ const sends: LaneSendInput[] = [];+ lane.sendImpl = async (input) => {+ sends.push(input);+ return input.mode === "busy"+ ? { ok: false, reason: "runtime_busy" }+ : { ok: true, acceptedAs: "prompt", receipt: input.terminalOwner! };+ };+ const { session } = makeSession("grok", { lane });+ await expect(session.start({ id: "one", kind: "user", text: "start" })).resolves.toMatchObject({ status: "accepted" });+ expect(await session.send({ id: "two", kind: "user", text: "follow" })).toEqual({+ status: "queued",+ reason: "unsafe_boundary",+ commandId: "two",+ });+ await vi.waitFor(() => expect(sends).toHaveLength(1));+ expect(session.snapshot().queuedCommands).toEqual([{ commandId: "two", kind: "user" }]);++ lane.emit({ kind: "turn_end", sessionId: "grok-session", turnOwner: "grok:test:1" });+ await vi.waitFor(() => expect(sends).toHaveLength(2));+ expect(sends[1]).toMatchObject({ text: "follow", mode: "idle" });+ expect(session.snapshot().queuedCommands).toEqual([]);+ await session.stop({ reason: "shutdown", forceAfterMs: 10 });+ });+it("flushes a safe-boundary message queued while the persistent lane is still starting", async () => {const { session, driver } = makeSession("claude");const gate = deferred();diff --git a/src/daemon/agent-driver/src/controller/logical-session.ts b/src/daemon/agent-driver/src/controller/logical-session.tsindex 861b99ee8..1846e4452 100644--- a/src/daemon/agent-driver/src/controller/logical-session.ts+++ b/src/daemon/agent-driver/src/controller/logical-session.ts@@ -170,7 +170,10 @@ function driverError(}class StructuredLaneAdmissionError extends Error {- constructor(readonly code: "reset_required" | "incompatible_configuration", message: string) {+ constructor(+ readonly code: "reset_required" | "incompatible_configuration" | "authentication_required" | "runtime_busy",+ message: string,+ ) {super(message);}}@@ -594,7 +597,12 @@ implements AgentSession<Specs, Id> {return admission.accepted ? acceptedReceipt : { status: "rejected", reason: "closed" };}const failure = error instanceof StructuredLaneAdmissionError- ? driverError("configuration", error.code, error.message, false)+ ? driverError(+ error.code === "authentication_required" ? "authentication" : "configuration",+ error.code,+ error.message,+ false,+ ): driverError("process", "failed_to_start", String(error), true);if (this.launch.resumeSessionId && this.resumeOutcome === "pending") {this.resumeOutcome = error instanceof StructuredLaneAdmissionError && error.code === "reset_required"@@ -678,6 +686,9 @@ implements AgentSession<Specs, Id> {if (admission.reason === "reset_required" || admission.reason === "incompatible_configuration") {throw new StructuredLaneAdmissionError(admission.reason, admission.error ?? admission.reason);}+ if (admission.reason === "authentication") {+ throw new StructuredLaneAdmissionError("authentication_required", admission.error ?? admission.reason);+ }throw new Error(admission.error ?? admission.reason);}if (!this.isOpenCurrent(generation)) {@@ -1056,14 +1067,19 @@ implements AgentSession<Specs, Id> {private async drainSafeBoundaryQueue(): Promise<void> {while (this.canFlushSafeBoundaryQueue()) {const item = this.queued.shift()!;- this.recordQueueDwell(item);const activeTurn = this.activeTurn!;const delivery: SafeBoundaryDelivery = { item, activeTurn, finalized: false };this.safeBoundaryDelivery = delivery;try {await this.sendLane(item.message.text, "busy");} catch (error) {+ if (error instanceof StructuredLaneAdmissionError && error.code === "runtime_busy") {+ this.queued.unshift(item);+ this.toolBoundaryFlushDisabled = true;+ return;+ }if (!delivery.finalized) {+ this.recordQueueDwell(item);delivery.finalized = true;this.emit({type: "command_failed",@@ -1077,6 +1093,7 @@ implements AgentSession<Specs, Id> {if (this.safeBoundaryDelivery === delivery) this.safeBoundaryDelivery = undefined;}if (delivery.finalized) continue;+ this.recordQueueDwell(item);delivery.finalized = true;activeTurn.commandIds.push(item.message.id);this.emit({@@ -1548,7 +1565,12 @@ implements AgentSession<Specs, Id> {terminalOwner: mode === "idle" ? this.activeTurn?.terminalOwner : undefined,}).then((result) => {- if (!result.ok) throw new Error(String("reason" in result ? result.reason : "runtime rejected delivery"));+ if (!result.ok) {+ if (result.reason === "runtime_busy") {+ throw new StructuredLaneAdmissionError("runtime_busy", result.error ?? result.reason);+ }+ throw new Error(result.error ?? result.reason);+ }return result;});}diff --git a/src/daemon/agent-driver/src/internal/adapter.ts b/src/daemon/agent-driver/src/internal/adapter.tsindex 0856fd71f..841afb175 100644--- a/src/daemon/agent-driver/src/internal/adapter.ts+++ b/src/daemon/agent-driver/src/internal/adapter.ts@@ -3,6 +3,7 @@ import type {ClaudeConfig,CodexConfig,CursorConfig,+ GrokConfig,OpenCodeConfig,PiConfig,PreparedExecutionResource,@@ -15,7 +16,7 @@ import type {} from "../contract.js";import type { ProviderQuotaObservation, TokenUsageDelta } from "../contract.js";-export type BackendConfig = ClaudeConfig | CodexConfig | CursorConfig | OpenCodeConfig | PiConfig;+export type BackendConfig = ClaudeConfig | CodexConfig | CursorConfig | GrokConfig | OpenCodeConfig | PiConfig;export type WellKnownTransportKind =| "stdio_stream"diff --git a/src/daemon/agent-driver/src/public-contract.ts b/src/daemon/agent-driver/src/public-contract.tsindex f54a8af38..c2ac63e39 100644--- a/src/daemon/agent-driver/src/public-contract.ts+++ b/src/daemon/agent-driver/src/public-contract.ts@@ -7,8 +7,8 @@ export type {JsonPrimitive, JsonValue, JsonObject, BuiltinBackendId, ReasoningEffort, RuntimeReasoningCatalog,RuntimeSettingsUpdate, RuntimeSettingsUpdateResult, ModelSelection, DefaultProvider,ClaudeProvider, PiProvider, BaseBackendConfig, ClaudeConfig, CodexConfig, ModelBackendConfig, CursorConfig,- OpenCodeConfig, PiConfig, BackendCapabilities, ClaudeCapabilities, CodexCapabilities, CursorCapabilities,- OpenCodeCapabilities, PiCapabilities, BackendExtensionSpec, BackendTypeSpec, BuiltinBackendSpecs, BackendId,+ GrokConfig, OpenCodeConfig, PiConfig, BackendCapabilities, ClaudeCapabilities, CodexCapabilities, CursorCapabilities,+ GrokCapabilities, OpenCodeCapabilities, PiCapabilities, BackendExtensionSpec, BackendTypeSpec, BuiltinBackendSpecs, BackendId,FixedCapabilities, ConfigOf, CapabilitiesOf, ExtensionsOf, ExtraEventOf, AgentInstructions, AgentLaunchContext, AgentMessage,AgentDriverError, OpenSessionResult, DeliveryReceipt, InterruptResult, StopInput, StopReceipt, HostCleanupResult,AgentSessionResult, AgentTurnResult, TokenMetricDelta, TokenUsageDelta, QuotaErrorCode,diff --git a/src/daemon/agent-driver/src/registry.test.ts b/src/daemon/agent-driver/src/registry.test.tsindex f1b60ddd3..59bc84410 100644--- a/src/daemon/agent-driver/src/registry.test.ts+++ b/src/daemon/agent-driver/src/registry.test.ts@@ -16,6 +16,7 @@ const EXPECTED: Record<BuiltinBackendId, BackendCapabilities> = {claude: { modelSelection: "launchable", providerConfiguration: true, reasoningEffort: true, fastMode: true, disallowedTools: true, commandOverride: true, resume: "by_id", sessionLifetime: "persistent", midTurnDelivery: "safe_boundary_queue", interrupt: true },codex: { modelSelection: "launchable", providerConfiguration: false, reasoningEffort: true, fastMode: true, disallowedTools: false, commandOverride: true, resume: "by_id", sessionLifetime: "persistent", midTurnDelivery: "safe_boundary_queue", interrupt: true },cursor: { modelSelection: "launchable", providerConfiguration: false, reasoningEffort: false, fastMode: false, disallowedTools: false, commandOverride: true, resume: "by_id", sessionLifetime: "persistent", midTurnDelivery: "steer", interrupt: true },+ grok: { modelSelection: "launchable", providerConfiguration: false, reasoningEffort: true, fastMode: false, disallowedTools: false, commandOverride: true, resume: "by_id", sessionLifetime: "persistent", midTurnDelivery: "safe_boundary_queue", interrupt: true },opencode: { modelSelection: "launchable", providerConfiguration: false, reasoningEffort: false, fastMode: false, disallowedTools: false, commandOverride: true, resume: "by_id", sessionLifetime: "persistent", midTurnDelivery: "steer", interrupt: true },pi: { modelSelection: "launchable", providerConfiguration: true, reasoningEffort: true, fastMode: false, disallowedTools: false, commandOverride: false, resume: "by_id", sessionLifetime: "persistent", midTurnDelivery: "steer", interrupt: true },};@@ -53,6 +54,12 @@ describe("driver.capabilities", () => {wakeStart: "immediate",terminalOwnership: "transport_request",},+ grok: {+ lifetime: "session",+ transport: { kind: "stdio_rpc", protocol: "grok.acp.v1" },+ wakeStart: "immediate",+ terminalOwnership: "transport_request",+ },opencode: {lifetime: "session",transport: { kind: "http_sse", protocol: "opencode.v2.service.1.17.20" },diff --git a/src/daemon/agent-driver/src/registry.ts b/src/daemon/agent-driver/src/registry.tsindex 15c099c1c..8ef3eef73 100644--- a/src/daemon/agent-driver/src/registry.ts+++ b/src/daemon/agent-driver/src/registry.ts@@ -9,6 +9,7 @@ import type {import { ClaudeDriver } from "./adapters/claude/index.js";import { CodexDriver } from "./adapters/codex/index.js";import { CursorDriver } from "./adapters/cursor/index.js";+import { GrokDriver } from "./adapters/grok/index.js";import { OpenCodeDriver } from "./adapters/opencode/index.js";import { PiDriver } from "./adapters/pi/index.js";import type { BackendAdapter } from "./internal/adapter.js";@@ -182,7 +183,7 @@ export function assertAdapterCompatibility(}}-export const BUILTIN_BACKEND_IDS = ["claude", "codex", "cursor", "opencode", "pi"] as const;+export const BUILTIN_BACKEND_IDS = ["claude", "codex", "cursor", "grok", "opencode", "pi"] as const;const capabilities = {claude: {@@ -197,6 +198,10 @@ const capabilities = {modelSelection: "launchable", providerConfiguration: false, reasoningEffort: false, fastMode: false,disallowedTools: false, commandOverride: true, resume: "by_id", sessionLifetime: "persistent", midTurnDelivery: "steer", interrupt: true,},+ grok: {+ modelSelection: "launchable", providerConfiguration: false, reasoningEffort: true, fastMode: false,+ disallowedTools: false, commandOverride: true, resume: "by_id", sessionLifetime: "persistent", midTurnDelivery: "safe_boundary_queue", interrupt: true,+ },opencode: {modelSelection: "launchable", providerConfiguration: false, reasoningEffort: false, fastMode: false,disallowedTools: false, commandOverride: true, resume: "by_id", sessionLifetime: "persistent", midTurnDelivery: "steer", interrupt: true,@@ -212,6 +217,7 @@ export function createBuiltinAgentDriverRegistry(): AgentDriverRegistry<BuiltinB{ id: "claude", contractVersion: 1, capabilities: capabilities.claude, createAdapter: () => new ClaudeDriver() },{ id: "codex", contractVersion: 1, capabilities: capabilities.codex, createAdapter: () => new CodexDriver() },{ id: "cursor", contractVersion: 1, capabilities: capabilities.cursor, createAdapter: () => new CursorDriver() },+ { id: "grok", contractVersion: 1, capabilities: capabilities.grok, createAdapter: () => new GrokDriver() },{ id: "opencode", contractVersion: 1, capabilities: capabilities.opencode, createAdapter: () => new OpenCodeDriver() },{ id: "pi", contractVersion: 1, capabilities: capabilities.pi, createAdapter: () => new PiDriver() },]);diff --git a/src/daemon/agent-driver/src/sdk.test.ts b/src/daemon/agent-driver/src/sdk.test.tsindex b4ecbad18..67595415d 100644--- a/src/daemon/agent-driver/src/sdk.test.ts+++ b/src/daemon/agent-driver/src/sdk.test.ts@@ -58,7 +58,7 @@ function sdkTestLane(receipt = "fresh-receipt") {describe("createAgentDriverSdk", () => {it("exposes the built-ins with default options", () => {- expect(createAgentDriverSdk().backendIds).toEqual(["claude", "codex", "cursor", "opencode", "pi"]);+ expect(createAgentDriverSdk().backendIds).toEqual(["claude", "codex", "cursor", "grok", "opencode", "pi"]);expect(SESSION_FILE_DISCOVERY_CAPABILITIES).toEqual(["supported", "unavailable"]);});@@ -84,20 +84,21 @@ describe("createAgentDriverSdk", () => {});});- it.each(["claude", "codex", "cursor", "opencode"] as const)(+ it.each(["claude", "codex", "cursor", "grok", "opencode"] as const)("forwards an explicit command override through the real %s probe",async (backend) => {- await expect(createAgentDriverSdk().probe({ backend, command: process.execPath })).resolves.toMatchObject({- status: "healthy",- });+ const result = await createAgentDriverSdk().probe({ backend, command: process.execPath });+ expect(result).toMatchObject(backend === "grok"+ ? { status: "unhealthy", error: { code: "grok_acp_process_failed" } }+ : { status: "healthy" });},);it("public SDK factory delegates to the built-in logical SDK", () => {- expect(createPublicAgentDriverSdk().backendIds).toEqual(["claude", "codex", "cursor", "opencode", "pi"]);+ expect(createPublicAgentDriverSdk().backendIds).toEqual(["claude", "codex", "cursor", "grok", "opencode", "pi"]);});- it.each(["claude", "codex", "cursor", "opencode", "pi"] as const)(+ it.each(["claude", "codex", "cursor", "grok", "opencode", "pi"] as const)("dispatches zero-bound discovery through the built-in %s adapter",async (backend) => {await expect(createAgentDriverSdk().discoverRecentContext({@@ -107,7 +108,7 @@ describe("createAgentDriverSdk", () => {})).resolves.toEqual({ok: true,sessionFiles: {- capability: backend === "cursor" || backend === "opencode" ? "unavailable" : "supported",+ capability: backend === "cursor" || backend === "grok" || backend === "opencode" ? "unavailable" : "supported",items: [],},recentProjects: [],diff --git a/src/daemon/agent-driver/src/testing/builtin-adapter-conformance.test.ts b/src/daemon/agent-driver/src/testing/builtin-adapter-conformance.test.tsindex 25aaf3b3b..ceb148488 100644--- a/src/daemon/agent-driver/src/testing/builtin-adapter-conformance.test.ts+++ b/src/daemon/agent-driver/src/testing/builtin-adapter-conformance.test.ts@@ -14,6 +14,7 @@ describe("builtin adapter protocol conformance", () => {claude: ["session", "stdio_stream", "claude.stream-json.v1", "safe_boundary_queue", "vendor_message"],codex: ["session", "stdio_rpc", "codex.app-server.v1", "safe_boundary_queue", "transport_request"],cursor: ["session", "stdio_rpc", "cursor.acp.v1", "steer", "transport_request"],+ grok: ["session", "stdio_rpc", "grok.acp.v1", "safe_boundary_queue", "transport_request"],opencode: ["session", "http_sse", "opencode.v2.service.1.17.20", "steer", "transport_request"],pi: ["session", "in_process_sdk", "pi_sdk", "steer", "prompt_invocation"],} as const;diff --git a/src/daemon/agent-driver/src/testing/builtin-session-conformance.test.ts b/src/daemon/agent-driver/src/testing/builtin-session-conformance.test.tsindex 13a050809..034d9f81c 100644--- a/src/daemon/agent-driver/src/testing/builtin-session-conformance.test.ts+++ b/src/daemon/agent-driver/src/testing/builtin-session-conformance.test.ts@@ -26,7 +26,9 @@ import type {import { ClaudeDriver } from "../adapters/claude/index.js";import { CodexDriver } from "../adapters/codex/index.js";import { CursorDriver } from "../adapters/cursor/index.js";+import { GrokDriver } from "../adapters/grok/index.js";import { CursorAcpLane } from "../adapters/cursor/acp-lane.js";+import { GrokAcpLane } from "../adapters/grok/acp-lane.js";import { OpenCodeDriver } from "../adapters/opencode/index.js";import { PiDriver } from "../adapters/pi/index.js";import { ProcessLane } from "../controller/process-host.js";@@ -39,6 +41,7 @@ const configs: { [Id in BuiltinBackendId]: ConfigOf<BuiltinBackendSpecs, Id> } =claude: { model: { kind: "default" }, provider: { kind: "default" }, mode: "default" },codex: { model: { kind: "default" }, mode: "default" },cursor: { model: { kind: "default" } },+ grok: { model: { kind: "default" } },opencode: { model: { kind: "default" } },pi: { model: { kind: "default" }, provider: { kind: "default" } },};@@ -165,7 +168,7 @@ function installVendorHarness(backend: BuiltinBackendId): VendorHarness {return lane;});} else {- const classes = { claude: ClaudeDriver, codex: CodexDriver, cursor: CursorDriver };+ const classes = { claude: ClaudeDriver, codex: CodexDriver, cursor: CursorDriver, grok: GrokDriver };if (backend === "claude") {const beginTurn = ClaudeDriver.prototype.beginTurn;vi.spyOn(ClaudeDriver.prototype, "beginTurn").mockImplementation(function (this: ClaudeDriver) {@@ -199,7 +202,7 @@ function installVendorHarness(backend: BuiltinBackendId): VendorHarness {if (!line.trim()) continue;const message = JSON.parse(line) as Record<string, unknown>;stdinMessages.push(message);- if (backend !== "cursor") continue;+ if (backend !== "cursor" && backend !== "grok") continue;const respond = (result: unknown) => process.stdout.write(`${JSON.stringify({jsonrpc: "2.0",id: message.id,@@ -209,15 +212,33 @@ function installVendorHarness(backend: BuiltinBackendId): VendorHarness {respond({protocolVersion: 1,agentCapabilities: { loadSession: true },- authMethods: [{ id: "cursor_login", name: "Cursor Login" }],+ authMethods: [{ id: backend === "grok" ? "cached_token" : "cursor_login" }],+ ...(backend === "grok" ? {+ _meta: {+ modelState: {+ currentModelId: "grok-4.6",+ availableModels: [{+ modelId: "grok-4.6",+ name: "Grok 4.6",+ _meta: { supportsReasoningEffort: true, reasoningEfforts: ["high", "medium", "low"] },+ }],+ },+ },+ } : {}),});} else if (message.method === "authenticate") {respond({});+ } else if (message.method === "_x.ai/billing") {+ respond({+ config: { currentPeriod: { type: "USAGE_PERIOD_TYPE_WEEKLY", creditUsagePercent: 0 } },+ });} else if (message.method === "session/load") {const params = message.params as { sessionId?: string } | undefined;- respond({ sessionId: params?.sessionId ?? "cursor-resumed", configOptions: [] });+ respond({ sessionId: params?.sessionId ?? `${backend}-resumed`, configOptions: [] });} else if (message.method === "session/new") {- respond({ sessionId: "cursor-resumed", configOptions: [] });+ respond({ sessionId: `${backend}-resumed`, configOptions: [] });+ } else if (message.method === "session/close") {+ respond({});}}});@@ -269,6 +290,7 @@ function installVendorHarness(backend: BuiltinBackendId): VendorHarness {} });break;case "cursor":+ case "grok":break;case "opencode":openCodeLanes[0]!.emit({ kind: "assistant_reasoning_completed", text: `turn-${turn}` });@@ -291,6 +313,7 @@ function installVendorHarness(backend: BuiltinBackendId): VendorHarness {} });break;case "cursor":+ case "grok":{const prompts = stdinMessages.filter((message) => message.method === "session/prompt");const prompt = prompts[turn - 1]!;@@ -320,7 +343,8 @@ function installVendorHarness(backend: BuiltinBackendId): VendorHarness {threadId: "codex-resumed", turn: { id: `codex-turn-${turn}`, status: "completed" },} });break;- case "cursor": {+ case "cursor":+ case "grok": {const prompts = stdinMessages.filter((message) => message.method === "session/prompt");const prompt = prompts[turn - 1]!;write({ jsonrpc: "2.0", id: prompt.id, result: { stopReason: "end_turn", ...overrides } });@@ -460,7 +484,7 @@ async function runPublicSessionLifecycle(backend: BuiltinBackendId): Promise<voiharness.completeTurn(1);await settle();- if (backend === "cursor") {+ if (backend === "cursor" || backend === "grok") {await vi.waitFor(() => {expect(harness.stdinMessages.filter((message) => message.method === "session/prompt")).toHaveLength(2);});@@ -476,14 +500,14 @@ async function runPublicSessionLifecycle(backend: BuiltinBackendId): Promise<voiexpect(await settlePromptAdmission(backend, harness, 2, reuse)).toMatchObject({ status: "accepted" });if (backend === "pi") harness.handles[0]!.isStreaming = true;}- if (backend !== "cursor") {+ if (backend !== "cursor" && backend !== "grok") {if (backend !== "codex") harness.sessionReady(2);await settle();harness.completeTurn(2);await settle();}- if (backend === "claude" || backend === "codex") {+ if (backend === "claude" || backend === "codex" || backend === "grok") {expect(harness.processes).toHaveLength(1);expect(harness.processes[0]!.kill).not.toHaveBeenCalled();}@@ -544,7 +568,7 @@ function emitStaleTerminal(backend: BuiltinBackendId, harness: VendorHarness): vharness.duplicateTurn(1);}-describe.each(["claude", "codex", "cursor", "opencode", "pi"] as const)(+describe.each(["claude", "codex", "cursor", "grok", "opencode", "pi"] as const)("%s shared persistent stress conformance",(backend) => {it("runs ten sequential public turns through one physical open", async () => {@@ -631,7 +655,7 @@ describe.each(["claude", "codex", "cursor", "opencode", "pi"] as const)(},);-describe.each(["claude", "codex", "cursor", "opencode", "pi"] as const)(+describe.each(["claude", "codex", "cursor", "grok", "opencode", "pi"] as const)("%s registered public-session lifecycle conformance",(backend) => {it("runs resume, busy admission, interrupt reuse, environment, release, and requested stop through sdk.open", async () => {@@ -648,7 +672,7 @@ describe.each(["claude", "codex", "cursor", "opencode", "pi"] as const)(? PiDriver.prototype: backend === "opencode"? OpenCodeDriver.prototype- : ({ claude: ClaudeDriver, codex: CodexDriver, cursor: CursorDriver, opencode: OpenCodeDriver } as const)[backend].prototype;+ : ({ claude: ClaudeDriver, codex: CodexDriver, cursor: CursorDriver, grok: GrokDriver, opencode: OpenCodeDriver } as const)[backend].prototype;const existing = (prototype as unknown as Record<string, ReturnType<typeof vi.fn>>)[method]!;existing.mockImplementationOnce(async (...args: unknown[]) => {await openGate;@@ -699,7 +723,7 @@ describe.each(["claude", "codex", "cursor", "opencode", "pi"] as const)(? PiDriver.prototype: backend === "opencode"? OpenCodeDriver.prototype- : ({ claude: ClaudeDriver, codex: CodexDriver, cursor: CursorDriver } as const)[backend].prototype;+ : ({ claude: ClaudeDriver, codex: CodexDriver, cursor: CursorDriver, grok: GrokDriver } as const)[backend].prototype;(prototype as unknown as Record<string, ReturnType<typeof vi.fn>>)[method]!.mockRejectedValueOnce(new Error("apiKey=supersecret failed at /Users/Alice Smith/private key.json"),);@@ -748,6 +772,8 @@ describe.each(["claude", "codex", "cursor", "opencode", "pi"] as const)(? vi.spyOn(SdkLane.prototype, "stop"): backend === "cursor"? vi.spyOn(CursorAcpLane.prototype, "stop")+ : backend === "grok"+ ? vi.spyOn(GrokAcpLane.prototype, "stop"): backend === "opencode"? vi.spyOn(HarnessRuntimeLane.prototype, "stop"): vi.spyOn(ProcessLane.prototype, "stop");@@ -781,6 +807,8 @@ describe.each(["claude", "codex", "cursor", "opencode", "pi"] as const)(? vi.spyOn(SdkLane.prototype, "stop"): backend === "cursor"? vi.spyOn(CursorAcpLane.prototype, "stop")+ : backend === "grok"+ ? vi.spyOn(GrokAcpLane.prototype, "stop"): backend === "opencode"? vi.spyOn(HarnessRuntimeLane.prototype, "stop"): vi.spyOn(ProcessLane.prototype, "stop");diff --git a/src/daemon/src/daemon/createDaemon.test.ts b/src/daemon/src/daemon/createDaemon.test.tsindex 27fe0e277..cb03ca9a2 100644--- a/src/daemon/src/daemon/createDaemon.test.ts+++ b/src/daemon/src/daemon/createDaemon.test.ts@@ -492,7 +492,7 @@ describe("createDaemon", () => {}});- it("commits terminal usage before idle and attaches the current backend quota", async () => {+ it.each(["codex", "grok"] as const)("re-emits enriched idle when terminal %s telemetry arrives after turn completion", async (backendId) => {const sockets: FakeSocket[] = [];const sessions: DaemonFakeSession[] = [];const workingDirectoryBase = mkdtempSync(join(tmpdir(), "daemon-provider-telemetry-"));@@ -511,8 +511,8 @@ describe("createDaemon", () => {serverUrl: "http://server.invalid",serverWsUrl: "ws://x",webSocketFactory: factory(sockets) as never,- runtimeReport: [{ id: "codex" }],- driverFor: () => fullFakeDriver("codex"),+ runtimeReport: [{ id: backendId }],+ driverFor: () => fullFakeDriver(backendId),sessionFactory: () => {const session = daemonFakeSession();sessions.push(session);@@ -527,15 +527,26 @@ describe("createDaemon", () => {sockets[0]!.emit("message", JSON.stringify({type: "agent:wake",agentId: "bot_1",- config: { version: 1, runtime: "codex", model: { kind: "default" }, mode: { kind: "default" } },+ config: { version: 1, runtime: backendId, model: { kind: "default" }, mode: { kind: "default" } },launchId: "launch_1",unreadNotice: { kind: "unread_notice", channel: "/demo#1234/general", latestSeq: 1 },}));await vi.waitFor(() => expect(sessions).toHaveLength(1));+ await sessions[0]!.fire("runtime_event", { kind: "turn_end", sessionId: "test-session" });++ const frames = () => sockets[0]!.sent.map((frame) => JSON.parse(frame) as any);+ await vi.waitFor(() => expect(frames().some((frame) =>+ frame.type === "agent_activity"+ && frame.agentId === "bot_1"+ && frame.state === "idle"+ && frame.dailyUsage === undefined+ && frame.quota === undefined+ )).toBe(true));+await sessions[0]!.fire("agent_event", {type: "token_usage",turnId: "daemon-test-turn",- source: "codex_thread_token_usage_updated",+ source: `${backendId}_settled_usage`,usage: {input: 20,output: 5,@@ -544,15 +555,15 @@ describe("createDaemon", () => {});await sessions[0]!.fire("agent_event", {type: "rate_limits",- source: "codex_account_rate_limits_updated",+ source: `${backendId}_rate_limits_updated`,quota: {status: "available",sourceEpoch: "A".repeat(22),freshForSeconds: 300,limits: [{bucket: {- limitId: "codex",- product: { kind: "reported", id: "codex", displayName: "Codex" },+ limitId: backendId,+ product: { kind: "reported", id: backendId, displayName: backendId === "grok" ? "Grok Build" : "Codex" },model: { kind: "not_applicable" },window: { kind: "rolling", durationSeconds: 18_000, displayName: "5 hour usage limit" },},@@ -560,9 +571,7 @@ describe("createDaemon", () => {}],},});- await sessions[0]!.fire("runtime_event", { kind: "turn_end", sessionId: "test-session" });- const frames = () => sockets[0]!.sent.map((frame) => JSON.parse(frame) as any);expect(frames().find((frame) => frame.type === "ready")?.timeZone).toBe(Intl.DateTimeFormat().resolvedOptions().timeZone);await vi.waitFor(() => expect(frames().some((frame) =>@@ -579,7 +588,7 @@ describe("createDaemon", () => {const readyBefore = frames().filter((frame) => frame.type === "ready").length;await sessions[0]!.fire("agent_event", {type: "rate_limits",- source: "codex_account_rate_limits_updated",+ source: `${backendId}_rate_limits_updated`,quota: {status: "error",sourceEpoch: "B".repeat(22),@@ -589,7 +598,7 @@ describe("createDaemon", () => {});await vi.waitFor(() => expect(frames().filter((frame) => frame.type === "ready")).toHaveLength(readyBefore + 1));expect(frames().filter((frame) => frame.type === "ready").at(-1)?.providerQuotas).toEqual([{- agentBackendId: "codex",+ agentBackendId: backendId,observation: {status: "error",sourceEpoch: "B".repeat(22),@@ -679,6 +688,65 @@ describe("createDaemon", () => {}});+ it("logs and contains daily token usage persistence failures", async () => {+ const sockets: FakeSocket[] = [];+ const sessions: DaemonFakeSession[] = [];+ const logger = stubLogger();+ const workingDirectoryBase = mkdtempSync(join(tmpdir(), "daemon-telemetry-failure-"));+ startupSweepDirs.push(workingDirectoryBase);+ mkdirSync(join(workingDirectoryBase, "bot_1"), { recursive: true });+ vi.stubGlobal("fetch", vi.fn(async (input: string | URL | Request) => {+ const url = String(input);+ if (url.includes("/enroll-agent")) return Response.json({ runnerKey: "runner_test" });+ if (url.includes("/daemon/bots")) {+ return Response.json({ bots: [{ id: "bot_1", name: "Bot", discriminator: "0001" }] });+ }+ return Response.json({ attempted: 0 });+ }));+ const daemon = await createDaemon({+ machineKey: "cmk_telemetry_failure",+ serverUrl: "http://server.invalid",+ serverWsUrl: "ws://x",+ webSocketFactory: factory(sockets) as never,+ runtimeReport: [{ id: "codex" }],+ driverFor: () => fullFakeDriver("codex"),+ sessionFactory: () => {+ const session = daemonFakeSession();+ sessions.push(session);+ return session;+ },+ capabilities: [],+ workingDirectoryBase,+ logger,+ });++ try {+ sockets[0]!.emit("open");+ sockets[0]!.emit("message", JSON.stringify({+ type: "agent:wake",+ agentId: "bot_1",+ config: { version: 1, runtime: "codex", model: { kind: "default" }, mode: { kind: "default" } },+ launchId: "launch_telemetry_failure",+ unreadNotice: { kind: "unread_notice", channel: "/demo#1234/general", latestSeq: 1 },+ }));+ await vi.waitFor(() => expect(sessions).toHaveLength(1));+ await sessions[0]!.fire("agent_event", {+ type: "token_usage",+ turnId: "daemon-test-turn",+ source: "test_invalid_usage",+ usage: { input: -1, output: 0, cache: 0 },+ });++ await vi.waitFor(() => expect(logger.calls.warn).toContainEqual([+ "root",+ "daily token usage persistence failed",+ [{ agentId: "bot_1" }],+ ]));+ } finally {+ await daemon.stop();+ }+ });+it("opens the builtin session factory and reports host preparation failures", async () => {const dir = mkdtempSync(join(tmpdir(), "daemon-builtin-session-"));try {diff --git a/src/daemon/src/daemon/createDaemon.ts b/src/daemon/src/daemon/createDaemon.tsindex a0e34d35b..bab16edb4 100644--- a/src/daemon/src/daemon/createDaemon.ts+++ b/src/daemon/src/daemon/createDaemon.ts@@ -70,7 +70,7 @@ const RUNTIME_RAW_TRACE_MAX_BYTES = 8 * 1024 * 1024;export const RUNTIME_RAW_TRACE_AGENT_IDS_ENV = "ALOOK_RUNTIME_RAW_TRACE_AGENT_IDS";/** How often the daemon rewrites the `daemon status` snapshot file (batch E2). */const STATUS_WRITE_INTERVAL_MS = 5_000;-const TOKEN_USAGE_BACKENDS = new Set<BuiltinBackendId>(["claude", "codex", "opencode", "pi"]);+const TOKEN_USAGE_BACKENDS = new Set<BuiltinBackendId>(["claude", "codex", "grok", "opencode", "pi"]);const ONBOARDING_RECENT_SESSION_FILES_TOP_K = 10;const ONBOARDING_RECENT_PROJECTS_TOP_K = 5;@@ -409,10 +409,10 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDaconst dailyTokenUsage = new DailyTokenUsageStore(workingDirectoryBase);const providerQuotaReader = opts.providerQuotaReader?? (opts.sessionFactory ? async () => null : readBuiltinProviderQuota);- const providerQuotaByBackend = new Map<"claude" | "codex", ProviderQuotaSnapshot>();+ const providerQuotaByBackend = new Map<"claude" | "codex" | "grok", ProviderQuotaSnapshot>();let requestReadyQuotaResend = (): void => {};const recordProviderQuota = (- backendId: "claude" | "codex",+ backendId: "claude" | "codex" | "grok",quota: ProviderQuotaObservation,): void => {const previous = providerQuotaByBackend.get(backendId);@@ -465,7 +465,7 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDaconst observed = await providerQuotaReader("claude");if (observed) recordProviderQuota("claude", observed);}- const quota = backendId === "claude" || backendId === "codex"+ const quota = backendId === "claude" || backendId === "codex" || backendId === "grok"? providerQuotaByBackend.get(backendId): undefined;const usageWindow = backendId && TOKEN_USAGE_BACKENDS.has(backendId)@@ -484,6 +484,11 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDalet reportAgentActivity = (info: { agentId: string; state: HostAgentActivity["state"] }): void => {void channelRef?.reportAgentActivity?.(info);};+ const reportTelemetryForIdleAgent = (agentId: string): void => {+ if (managerRef?.agentActivity(agentId) === "idle") {+ reportAgentActivity({ agentId, state: "idle" });+ }+ };let reminderSchedulerRef: MessageReminderScheduler | null = null;const selfSleepScheduler = opts.onSelfSleep? new DaemonSelfSleepScheduler({@@ -1015,13 +1020,16 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa}},onTokenUsage: ({ agentId, usage }) => {- void dailyTokenUsage.record(agentId, usage).catch(() => {- log.warn("daily token usage persistence failed", { agentId });- });+ void dailyTokenUsage.record(agentId, usage)+ .then(() => reportTelemetryForIdleAgent(agentId))+ .catch(() => {+ log.warn("daily token usage persistence failed", { agentId });+ });},- onProviderQuota: ({ backendId, quota }) => {- if (backendId !== "claude" && backendId !== "codex") return;+ onProviderQuota: ({ agentId, backendId, quota }) => {+ if (backendId !== "claude" && backendId !== "codex" && backendId !== "grok") return;recordProviderQuota(backendId, quota);+ reportTelemetryForIdleAgent(agentId);},// Bot audit log — Producer A (runtime thinking + non-Bash tool_call).// Bash suppression + thinking truncation happen inside managerRuntime.diff --git a/src/daemon/src/discovery.test.ts b/src/daemon/src/discovery.test.tsindex 986820b69..ad91f99cc 100644--- a/src/daemon/src/discovery.test.ts+++ b/src/daemon/src/discovery.test.ts@@ -12,7 +12,7 @@ import {} from "./discovery";import * as drivers from "./drivers/index";-const EXPECTED_RUNTIMES = ["claude", "codex", "cursor", "opencode", "pi"];+const EXPECTED_RUNTIMES = ["claude", "codex", "cursor", "grok", "opencode", "pi"];const tmpDirs: string[] = [];function mkTmp(): string {@@ -175,7 +175,7 @@ describe("detectRuntimes", () => {}});- it("advertises exactly the five supported runtimes", () => {+ it("advertises exactly the six supported runtimes", () => {const advertised = runtimes.map((r) => r.id).sort();expect(advertised).toEqual([...EXPECTED_RUNTIMES].sort());});@@ -226,7 +226,7 @@ describe("detectRuntimes", () => {});describe("driver registry", () => {- it("contains exactly the five supported runtimes", () => {+ it("contains exactly the six supported runtimes", () => {expect(drivers.listRuntimeIds().slice().sort()).toEqual([...EXPECTED_RUNTIMES].sort());});diff --git a/src/daemon/src/runtimeConfig.test.ts b/src/daemon/src/runtimeConfig.test.tsindex 5299974ff..0edfdd1df 100644--- a/src/daemon/src/runtimeConfig.test.ts+++ b/src/daemon/src/runtimeConfig.test.ts@@ -3,7 +3,7 @@ import { runtimeModelName, toAgentBackendSelection } from "./runtimeConfig";import { makeRuntimeConfig } from "./runtimeConfig";describe("runtimeModelName", () => {- for (const runtime of ["claude", "codex", "cursor", "opencode", "pi"]) {+ for (const runtime of ["claude", "codex", "cursor", "grok", "opencode", "pi"]) {it(`${runtime}: projects a named model without interpreting the backend`, () => {expect(runtimeModelName(makeRuntimeConfig({ runtime, model: { kind: "named", name: "opus" } }))).toBe("opus");@@ -25,6 +25,10 @@ describe("toAgentBackendSelection", () => {it("maps every runtime into the agent-driver contract", () => {expect(toAgentBackendSelection(makeRuntimeConfig({ runtime: "codex" }))).toMatchObject({ backend: "codex" });expect(toAgentBackendSelection(makeRuntimeConfig({ runtime: "cursor" }))).toMatchObject({ backend: "cursor" });+ expect(toAgentBackendSelection(makeRuntimeConfig({ runtime: "grok", reasoningEffort: "high" }))).toMatchObject({+ backend: "grok",+ config: { reasoningEffort: "high" },+ });expect(toAgentBackendSelection(makeRuntimeConfig({ runtime: "opencode" }))).toMatchObject({ backend: "opencode" });expect(toAgentBackendSelection(makeRuntimeConfig({ runtime: "pi" }))).toMatchObject({backend: "pi",diff --git a/src/shared/src/db/community-machine-schema.ts b/src/shared/src/db/community-machine-schema.tsindex 42dd8bb85..e01221b37 100644--- a/src/shared/src/db/community-machine-schema.ts+++ b/src/shared/src/db/community-machine-schema.ts@@ -281,7 +281,7 @@ export const communityMachineBackendQuota = sqliteTable(machineId: text("machine_id").notNull().references(() => communityMachine.id, { onDelete: "cascade" }),- agentBackendId: text("agent_backend_id").$type<"claude" | "codex">().notNull(),+ agentBackendId: text("agent_backend_id").$type<"claude" | "codex" | "grok">().notNull(),sourceEpoch: text("source_epoch").notNull(),status: text("status").$type<MachineBackendQuotaStatus>().notNull(),planName: text("plan_name"),diff --git a/src/shared/src/provider-telemetry.ts b/src/shared/src/provider-telemetry.tsindex b93902bf5..3377ff30d 100644--- a/src/shared/src/provider-telemetry.ts+++ b/src/shared/src/provider-telemetry.ts@@ -108,7 +108,7 @@ export const ProviderQuotaObservationSchema = z.union([export type ProviderQuotaObservation = z.infer<typeof ProviderQuotaObservationSchema>;export const ProviderQuotaSnapshotSchema = z.object({- agentBackendId: z.enum(["claude", "codex"]),+ agentBackendId: z.enum(["claude", "codex", "grok"]),observation: ProviderQuotaObservationSchema,}).strict();export type ProviderQuotaSnapshot = z.infer<typeof ProviderQuotaSnapshotSchema>;diff --git a/src/shared/src/runtime-config.ts b/src/shared/src/runtime-config.tsindex f169afad2..97552e4e7 100644--- a/src/shared/src/runtime-config.ts+++ b/src/shared/src/runtime-config.ts@@ -75,7 +75,7 @@ export type ModeConfig = { kind: "default" | "fast" };export interface RuntimeConfig {version: number;- /** "claude" | "codex" | "cursor" | "opencode" | "pi" | "mock" */+ /** "claude" | "codex" | "cursor" | "grok" | "opencode" | "pi" | "mock" */runtime: string;model: ModelConfig;mode: ModeConfig;diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.tsindex 71b116572..1c7ff2c46 100644--- a/src/shared/src/schemas.ts+++ b/src/shared/src/schemas.ts@@ -990,7 +990,7 @@ export const HostReadyMessageSchema = z.object({osRelease: z.string().optional(),daemonVersion: z.string().optional(),timeZone: z.string().min(1).max(128).optional(),- providerQuotas: z.array(ProviderQuotaSnapshotSchema).max(2).optional().default([]),+ providerQuotas: z.array(ProviderQuotaSnapshotSchema).max(3).optional().default([]),});export type HostReadyMessage = z.infer<typeof HostReadyMessageSchema>;diff --git a/src/shared/test/schemas/community-runtime.test.ts b/src/shared/test/schemas/community-runtime.test.tsindex 2ba6c6263..48ae6b75d 100644--- a/src/shared/test/schemas/community-runtime.test.ts+++ b/src/shared/test/schemas/community-runtime.test.ts@@ -307,6 +307,28 @@ describe("HostReadyMessageSchema", () => {expect(parsed.runtimeReport).toEqual([{ id: "claude", status: "healthy" }]);});+ it("accepts one quota snapshot for each supported provider backend", () => {+ const providerQuotas = (["claude", "codex", "grok"] as const).map((agentBackendId) => ({+ agentBackendId,+ observation: {+ status: "error" as const,+ sourceEpoch: "A".repeat(22),+ code: "unavailable" as const,+ retryable: false,+ },+ }));+ expect(HostReadyMessageSchema.parse({+ type: "ready",+ runtimeReport: [],+ providerQuotas,+ }).providerQuotas).toEqual(providerQuotas);+ expect(HostReadyMessageSchema.safeParse({+ type: "ready",+ runtimeReport: [],+ providerQuotas: [...providerQuotas, providerQuotas[0]],+ }).success).toBe(false);+ });+it.each([125, 256, 257])("accepts and de-dupes a complete %i-item runningAgents report", (count) => {const ids = Array.from({ length: count }, (_, index) => `agent_${index}`);const parsed = HostReadyMessageSchema.parse({diff --git a/src/web/migrations/0097_community_machine_backend_quota_grok.sql b/src/web/migrations/0097_community_machine_backend_quota_grok.sqlnew file mode 100644index 000000000..d774d38bf--- /dev/null+++ b/src/web/migrations/0097_community_machine_backend_quota_grok.sql@@ -0,0 +1,51 @@+PRAGMA defer_foreign_keys=ON;++CREATE TABLE community_machine_backend_quota_new (+ machine_id TEXT NOT NULL REFERENCES community_machine(id) ON DELETE CASCADE,+ agent_backend_id TEXT NOT NULL CHECK (agent_backend_id IN ('claude', 'codex', 'grok')),+ source_epoch TEXT NOT NULL CHECK (length(source_epoch) = 22 AND source_epoch NOT GLOB '*[^A-Za-z0-9_-]*'),+ status TEXT NOT NULL CHECK (status IN ('available', 'error')),+ plan_name TEXT,+ fresh_for_seconds INTEGER,+ limits TEXT,+ error_code TEXT,+ retryable INTEGER,+ observed_at TEXT NOT NULL,+ updated_at TEXT NOT NULL,+ PRIMARY KEY (machine_id, agent_backend_id),+ CHECK (+ (status = 'available' AND fresh_for_seconds BETWEEN 1 AND 86400 AND json_valid(limits) AND json_array_length(limits) BETWEEN 1 AND 8 AND error_code IS NULL AND retryable IS NULL)+ OR+ (status = 'error' AND plan_name IS NULL AND fresh_for_seconds IS NULL AND limits IS NULL AND error_code IN ('unavailable', 'unauthorized', 'network', 'provider_error', 'invalid_response') AND retryable IN (0, 1))+ )+);++INSERT INTO community_machine_backend_quota_new (+ machine_id,+ agent_backend_id,+ source_epoch,+ status,+ plan_name,+ fresh_for_seconds,+ limits,+ error_code,+ retryable,+ observed_at,+ updated_at+)+SELECT+ machine_id,+ agent_backend_id,+ source_epoch,+ status,+ plan_name,+ fresh_for_seconds,+ limits,+ error_code,+ retryable,+ observed_at,+ updated_at+FROM community_machine_backend_quota;++DROP TABLE community_machine_backend_quota;+ALTER TABLE community_machine_backend_quota_new RENAME TO community_machine_backend_quota;diff --git a/src/web/src/app/api/community/bots/route.test.ts b/src/web/src/app/api/community/bots/route.test.tsindex cddc50177..73c9e4c45 100644--- a/src/web/src/app/api/community/bots/route.test.ts+++ b/src/web/src/app/api/community/bots/route.test.ts@@ -266,6 +266,7 @@ describe("GET /api/community/bots — heatmap activity", () => {{ id: "bot_claude", runtime: "claude" },{ id: "bot_codex", runtime: "codex" },{ id: "bot_cursor", runtime: "cursor" },+ { id: "bot_grok", runtime: "grok" },{ id: "bot_opencode", runtime: "opencode" },{ id: "bot_pi", runtime: "pi" },{ id: "bot_unknown", runtime: "custom" },@@ -307,6 +308,7 @@ describe("GET /api/community/bots — heatmap activity", () => {bot_claude: "supported",bot_codex: "supported",bot_cursor: "unsupported",+ bot_grok: "supported",bot_opencode: "supported",bot_pi: "supported",bot_unknown: "unknown",diff --git a/src/web/src/app/api/community/bots/route.ts b/src/web/src/app/api/community/bots/route.tsindex 1674c277b..cf9355cc8 100644--- a/src/web/src/app/api/community/bots/route.ts+++ b/src/web/src/app/api/community/bots/route.ts@@ -57,7 +57,7 @@ export const GET = withAuth(async (_req, ctx) => {image: canonicalUserImage(bot.id, bot.image, bot.avatarVersion),dailyActivity: activityByBot.get(bot.id) ?? [],usage: {- capability: (["claude", "codex", "opencode", "pi"] as string[]).includes(bot.runtime)+ capability: (["claude", "codex", "grok", "opencode", "pi"] as string[]).includes(bot.runtime)? "supported" as const: bot.runtime === "cursor"? "unsupported" as constdiff --git a/src/web/src/app/api/community/machines/route.test.ts b/src/web/src/app/api/community/machines/route.test.tsindex 6f43166a2..48bef9174 100644--- a/src/web/src/app/api/community/machines/route.test.ts+++ b/src/web/src/app/api/community/machines/route.test.ts@@ -73,6 +73,7 @@ describe("GET /api/community/machines — provider quota", () => {availableRuntimes: [{ id: "codex", status: "healthy" },{ id: "claude", status: "unhealthy" },+ { id: "grok", status: "healthy" },{ id: "cursor", status: "healthy" },],}])@@ -100,6 +101,27 @@ describe("GET /api/community/machines — provider quota", () => {},},},+ {+ observedAt,+ quota: {+ agentBackendId: "grok",+ observation: {+ status: "available",+ sourceEpoch: "G".repeat(22),+ planName: "SuperGrok",+ freshForSeconds: 300,+ limits: [{+ bucket: {+ limitId: "grok-build",+ product: { kind: "reported", id: "grok", displayName: "Grok Build" },+ model: { kind: "not_applicable" },+ window: { kind: "provider_defined", id: "weekly", displayName: "Weekly limit" },+ },+ usedPercent: 12.5,+ }],+ },+ },+ },{observedAt,quota: {@@ -136,6 +158,17 @@ describe("GET /api/community/machines — provider quota", () => {runtimeState: "unhealthy",snapshot: { status: "error", code: "unauthorized" },},+ {+ scope: { kind: "machine_backend", machineId: "cm_1", agentBackendId: "grok" },+ capability: "supported",+ runtimeState: "healthy",+ snapshot: {+ status: "available",+ observedAt,+ planName: "SuperGrok",+ limits: [expect.objectContaining({ usedPercent: 12.5 })],+ },+ },{scope: { kind: "machine_backend", machineId: "cm_1", agentBackendId: "cursor" },capability: "unsupported",diff --git a/src/web/src/app/api/community/machines/route.ts b/src/web/src/app/api/community/machines/route.tsindex b10d99374..508da6b04 100644--- a/src/web/src/app/api/community/machines/route.ts+++ b/src/web/src/app/api/community/machines/route.ts@@ -11,7 +11,7 @@ export const GET = withAuth(async (_req, ctx) => {const withQuota = machines.map((machine) => {const stored = quotaByMachine.get(machine.id) ?? []const quota = machine.availableRuntimes.map((runtime) => {- const capability = runtime.id === "claude" || runtime.id === "codex"+ const capability = runtime.id === "claude" || runtime.id === "codex" || runtime.id === "grok"? "supported" as const: runtime.id === "cursor" || runtime.id === "opencode" || runtime.id === "pi"? "unsupported" as constdiff --git a/src/web/src/app/globals.css b/src/web/src/app/globals.cssindex e7d6a82cf..c0ff6a95d 100644--- a/src/web/src/app/globals.css+++ b/src/web/src/app/globals.css@@ -62,19 +62,36 @@}.community-ws-connecting-loader {- display: block;- width: 100px;- height: 100px;- overflow: visible;- color: var(--primary);+ display: flex;+ align-items: center;+ justify-content: center;+ gap: 10px;+ color: var(--foreground);+ user-select: none;+}++.community-ws-connecting-orb {+ width: 20px;+ height: 20px;+ flex: 0 0 auto;+ border-radius: 999px;background: transparent;- mix-blend-mode: normal;+ transform: rotate(90deg);+ animation: community-ws-connecting-orb 1.5s linear infinite;+ will-change: transform;}-.community-ws-connecting-dot {- transform-box: fill-box;- transform-origin: center;- animation: community-ws-connecting 1s infinite;+.community-ws-connecting-text {+ display: inline-flex;+ gap: 1px;+ line-height: 1;+}++.community-ws-connecting-letter {+ display: inline-block;+ opacity: 0.4;+ animation: community-ws-connecting-letter 1.8s ease-in-out infinite;+ will-change: opacity;}body.driver-active .community-ws-reconnect-overlay,@@ -82,17 +99,64 @@ body.driver-active .community-ws-reconnect-overlay * {pointer-events: auto;}-@keyframes community-ws-connecting {- 90%,+@keyframes community-ws-connecting-orb {+ 0% {+ background: transparent;+ box-shadow:+ inset 0 1px 1px #fff,+ inset 0 3px 5px #ff5f9f,+ inset 0 4px 4px #0693ff;+ transform: rotate(90deg);+ }++ 50% {+ background: #7c0911;+ box-shadow:+ inset 0 1px 1px #fff,+ inset 0 3px 5px #d60a47,+ inset 0 4px 4px #fbef19;+ transform: rotate(270deg);+ }++ 100% {+ background: transparent;+ box-shadow:+ inset 0 1px 1px #fff,+ inset 0 3px 5px #ff5f9f,+ inset 0 4px 4px #28a9ff;+ transform: rotate(450deg);+ }+}++@keyframes community-ws-connecting-letter {+ 0%,100% {- transform: translateX(60px);+ opacity: 0.4;+ }++ 50% {+ opacity: 1;}}@media (prefers-reduced-motion: reduce) {- .community-ws-connecting-dot {+ .community-ws-connecting-orb {+ background: #7c0911;+ box-shadow:+ inset 0 1px 1px #fff,+ inset 0 3px 5px #d60a47,+ inset 0 4px 4px #fbef19;+ transform: rotate(270deg);+ }++ .community-ws-connecting-orb,+ .community-ws-connecting-letter {animation: none;}++ .community-ws-connecting-letter {+ opacity: 1;+ }}.community-guide-me {diff --git a/src/web/src/components/community/bots/bot-quota-summary.dom.test.ts b/src/web/src/components/community/bots/bot-quota-summary.dom.test.tsindex 467d24b57..a78a460bc 100644--- a/src/web/src/components/community/bots/bot-quota-summary.dom.test.ts+++ b/src/web/src/components/community/bots/bot-quota-summary.dom.test.ts@@ -39,6 +39,8 @@ import {quotaBucketIdentity,remainingPercent,selectMostConstrainedLimit,+ sortQuotaEntries,+ summarizeQuotaEntries,} from "./bot-quota-summary"function limit({@@ -127,6 +129,24 @@ describe("quota helpers", () => {expect(groups[0]!.limits.map(quotaBucketIdentity)).toHaveLength(2)expect(new Set(groups[0]!.limits.map(quotaBucketIdentity)).size).toBe(2)})++ it("summarizes every backend with data and sorts data ahead of placeholders", () => {+ const codex = quotaEntry([limit({ usedPercent: 82 })], "available", "codex")+ const grok = quotaEntry([limit({ usedPercent: 35 })], "available", "grok")+ const claude: MachineBackendQuota = {+ scope: { kind: "machine_backend", machineId: "m1", agentBackendId: "claude" },+ capability: "supported",+ runtimeState: "healthy",+ snapshot: { status: "pending" },+ }++ expect(summarizeQuotaEntries([grok, claude, codex]).map(({ entry, limit: item }) => [+ entry.scope.agentBackendId,+ remainingPercent(item),+ ])).toEqual([["codex", 18], ["grok", 65]])+ expect(sortQuotaEntries([claude, grok, codex]).map((entry) => entry.scope.agentBackendId))+ .toEqual(["codex", "grok", "claude"])+ })})describe("MachineQuotaSummary", () => {@@ -138,6 +158,13 @@ describe("MachineQuotaSummary", () => {usedPercent: 55.5,})const codex = quotaEntry([weekly, rolling])+ const grok = quotaEntry([limit({+ limitId: "grok-primary",+ productId: "grok",+ productName: "Grok",+ modelId: "grok-4.6",+ usedPercent: 35,+ })], "available", "grok")const pi: MachineBackendQuota = {scope: { kind: "machine_backend", machineId: "m1", agentBackendId: "pi" },capability: "unsupported",@@ -150,10 +177,17 @@ describe("MachineQuotaSummary", () => {runtimeState: "healthy",snapshot: { status: "pending" },}- const renderer = render([pi, codex, claude])+ const renderer = render([pi, codex, claude, grok])const trigger = renderer.getByTestId("community-machine-quota-m1")expect(trigger).toHaveAttribute("aria-expanded", "false")- expect(text(trigger)).toContain("Quota · Spark · 18% left · 2 limits")+ expect(text(trigger)).toBe("Quota·18%·65%")+ expect(trigger).toHaveAttribute(+ "aria-label",+ expect.stringContaining("Codex 18% left; Grok 65% left"),+ )+ expect([...trigger.querySelectorAll<HTMLElement>("[data-provider-logo]")]+ .map((node) => node.dataset.providerLogo))+ .toEqual(["codex", "grok"])fireEvent.click(trigger)expect(renderer.getByTestId("community-machine-quota-m1")).toHaveAttribute("aria-expanded", "true")@@ -161,6 +195,7 @@ describe("MachineQuotaSummary", () => {expect(text(detail)).toContain("Machine quota")expect(text(detail)).toContain("Claude")expect(text(detail)).toContain("Codex")+ expect(text(detail)).toContain("Grok")expect(text(detail)).toContain("Pi")expect(text(detail)).toContain("Pending")expect(text(detail)).toContain("Not supported")@@ -171,14 +206,17 @@ describe("MachineQuotaSummary", () => {expect(text(detail)).toContain("2m ago")expect([...detail.querySelectorAll<HTMLElement>("[data-provider-logo]")].map((node) => node.dataset.providerLogo))- .toEqual(["claude", "codex", "pi"])+ .toEqual(["codex", "grok", "claude", "pi"])+ expect([...detail.querySelectorAll<HTMLElement>("[data-quota-backend]")]+ .map((node) => node.dataset.quotaBackend))+ .toEqual(["codex", "grok", "claude", "pi"])})it("shows one limit's server-authored window and stale state", () => {const renderer = render([quotaEntry([limit({ usedPercent: 37.5 })], "stale")])const trigger = renderer.getByTestId("community-machine-quota-m1")- expect(text(trigger)).toContain("Quota · Spark · 62.5% left")- expect(text(trigger)).toContain("Stale")+ expect(text(trigger)).toBe("Quota·62.5%stale")+ expect(trigger).toHaveAttribute("aria-label", expect.stringContaining("Codex 62.5% left, stale"))})it("renders honest fixed-height placeholders for missing capability states", () => {diff --git a/src/web/src/components/community/bots/bot-quota-summary.tsx b/src/web/src/components/community/bots/bot-quota-summary.tsxindex 673fec19d..15dc5344b 100644--- a/src/web/src/components/community/bots/bot-quota-summary.tsx+++ b/src/web/src/components/community/bots/bot-quota-summary.tsx@@ -155,22 +155,28 @@ function backendPlaceholder(entry: MachineBackendQuota): string {return "Unavailable"}-function constrainedEntry(entries: MachineBackendQuota[]): {+type BackendQuotaSummary = {entry: MachineBackendQuotalimit: QuotaLimit-} | null {- const usable = entries.filter(hasQuotaLimits)- const limit = selectMostConstrainedLimit(usable.flatMap((entry) => (- entry.snapshot.status === "available" || entry.snapshot.status === "stale"- ? entry.snapshot.limits- : []- )))- if (!limit) return null- const entry = usable.find((candidate) => (- (candidate.snapshot.status === "available" || candidate.snapshot.status === "stale")- && candidate.snapshot.limits.includes(limit)- ))- return entry ? { entry, limit } : null+}++export function summarizeQuotaEntries(entries: MachineBackendQuota[]): BackendQuotaSummary[] {+ return entries+ .filter(hasQuotaLimits)+ .toSorted((a, b) => a.scope.agentBackendId.localeCompare(b.scope.agentBackendId))+ .flatMap((entry) => {+ if (entry.snapshot.status !== "available" && entry.snapshot.status !== "stale") return []+ const limit = selectMostConstrainedLimit(entry.snapshot.limits)+ return limit ? [{ entry, limit }] : []+ })+}++export function sortQuotaEntries(entries: MachineBackendQuota[]): MachineBackendQuota[] {+ return entries.toSorted((a, b) => {+ const dataRank = Number(hasQuotaLimits(b)) - Number(hasQuotaLimits(a))+ if (dataRank !== 0) return dataRank+ return a.scope.agentBackendId.localeCompare(b.scope.agentBackendId)+ })}export function MachineQuotaSummary({@@ -200,23 +206,18 @@ export function MachineQuotaSummary({)}- const constrained = constrainedEntry(entries)- if (!constrained) return null+ const backendSummaries = summarizeQuotaEntries(entries)+ if (backendSummaries.length === 0) return nullconst limitCount = entries.reduce((count, entry) => (entry.snapshot.status === "available" || entry.snapshot.status === "stale"? count + entry.snapshot.limits.length: count), 0)- const stale = constrained.entry.snapshot.status === "stale"- const summary = [- "Quota",- productLabel(constrained.limit),- percentLabel(constrained.limit),- ...(limitCount > 1 ? [`${limitCount} limits`] : []),- ].join(" · ")- const sortedEntries = entries.toSorted((a, b) => (- a.scope.agentBackendId.localeCompare(b.scope.agentBackendId)- ))+ const summary = backendSummaries.map(({ entry, limit }) => {+ const stale = entry.snapshot.status === "stale" ? ", stale" : ""+ return `${backendLabel(entry.scope.agentBackendId)} ${percentLabel(limit)}${stale}`+ }).join("; ")+ const sortedEntries = sortQuotaEntries(entries)return (<Popover open={open} onOpenChange={setOpen}>@@ -225,16 +226,35 @@ export function MachineQuotaSummary({<buttontype="button"aria-expanded={open}- aria-label={`Quota details: ${summary}${stale ? ". Stale" : ""}`}+ aria-label={`Quota details: ${summary}. ${limitCount} ${limitCount === 1 ? "limit" : "limits"}`}data-testid={tid.machineQuota(machineId)}- className="group flex h-11 max-w-full min-w-0 items-center gap-1.5 rounded-md text-left text-xs text-muted-foreground transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none sm:h-7"+ className="group flex min-h-11 max-w-full min-w-0 flex-wrap items-center gap-x-2 gap-y-1 rounded-md py-2 text-left text-xs text-muted-foreground transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none sm:min-h-7 sm:py-1">- <ProviderLogo- provider={constrained.entry.scope.agentBackendId}- className="size-3.5 shrink-0"- />- <span className="truncate text-foreground/85">{summary}</span>- {stale && <span className="shrink-0 text-warning">Stale</span>}+ <span className="shrink-0 text-foreground/70">Quota</span>+ <span aria-hidden className="shrink-0 text-border">·</span>+ {backendSummaries.map(({ entry, limit }, index) => {+ const stale = entry.snapshot.status === "stale"+ const label = `${backendLabel(entry.scope.agentBackendId)}: ${percentLabel(limit)}${stale ? " (stale)" : ""}`+ return (+ <span key={entry.scope.agentBackendId} className="contents">+ {index > 0 && <span aria-hidden className="shrink-0 text-border">·</span>}+ <span+ aria-label={label}+ title={label}+ className="inline-flex shrink-0 items-center gap-1.5"+ >+ <ProviderLogo+ provider={entry.scope.agentBackendId}+ className="size-3.5 shrink-0"+ />+ <span className={stale ? "font-mono tabular-nums text-warning" : "font-mono tabular-nums text-foreground/85"}>+ {remainingPercent(limit)}%+ </span>+ {stale && <span className="text-[10px] text-warning">stale</span>}+ </span>+ </span>+ )+ })}<ChevronDown className="size-3 shrink-0 transition-transform group-data-popup-open:rotate-180" /></button>}@@ -250,7 +270,11 @@ export function MachineQuotaSummary({const snapshot = entry.snapshotif (snapshot.status !== "available" && snapshot.status !== "stale") {return (- <section key={entry.scope.agentBackendId} className="flex flex-col gap-2">+ <section+ key={entry.scope.agentBackendId}+ data-quota-backend={entry.scope.agentBackendId}+ className="flex flex-col gap-2"+ ><div className="flex min-w-0 items-center gap-1.5"><ProviderLogo provider={entry.scope.agentBackendId} className="size-3.5 shrink-0" /><span className="truncate text-xs font-medium text-foreground">@@ -265,7 +289,11 @@ export function MachineQuotaSummary({}const groups = groupQuotaLimits(snapshot.limits)return (- <section key={entry.scope.agentBackendId} className="flex flex-col gap-2">+ <section+ key={entry.scope.agentBackendId}+ data-quota-backend={entry.scope.agentBackendId}+ className="flex flex-col gap-2"+ ><div className="flex min-w-0 items-center justify-between gap-3"><div className="flex min-w-0 items-center gap-1.5"><ProviderLogo provider={entry.scope.agentBackendId} className="size-3.5 shrink-0" />diff --git a/src/web/src/components/community/bots/bot-select-menu.contract.test.ts b/src/web/src/components/community/bots/bot-select-menu.contract.test.tsnew file mode 100644index 000000000..dbed48780--- /dev/null+++ b/src/web/src/components/community/bots/bot-select-menu.contract.test.ts@@ -0,0 +1,21 @@+import { readFileSync } from "node:fs"+import { dirname, resolve } from "node:path"+import { fileURLToPath } from "node:url"+import { describe, expect, it } from "vitest"++const directory = dirname(fileURLToPath(import.meta.url))++describe("bot select menu spacing", () => {+ it("gives model and effort menus a shared padded content and row rhythm", () => {+ const menuSource = readFileSync(resolve(directory, "bot-select-menu.tsx"), "utf8")+ const modelSource = readFileSync(resolve(directory, "model-field.tsx"), "utf8")+ const effortSource = readFileSync(resolve(directory, "reasoning-effort-field.tsx"), "utf8")++ expect(menuSource).toContain('cn("p-1.5", className)')+ expect(menuSource).toContain('cn("min-h-10 py-2 pr-9 pl-3 leading-snug", className)')+ expect(modelSource).toContain("<BotSelectMenuContent")+ expect(modelSource).toContain("<BotSelectMenuItem")+ expect(effortSource).toContain("<BotSelectMenuContent")+ expect(effortSource).toContain("<BotSelectMenuItem")+ })+})diff --git a/src/web/src/components/community/bots/bot-select-menu.tsx b/src/web/src/components/community/bots/bot-select-menu.tsxnew file mode 100644index 000000000..5028fc4ae--- /dev/null+++ b/src/web/src/components/community/bots/bot-select-menu.tsx@@ -0,0 +1,28 @@+import type { ComponentProps } from "react"++import { SelectContent, SelectItem } from "@/components/ui/select"+import { cn } from "@/lib/utils"++export function BotSelectMenuContent({+ className,+ ...props+}: ComponentProps<typeof SelectContent>) {+ return (+ <SelectContent+ className={cn("p-1.5", className)}+ {...props}+ />+ )+}++export function BotSelectMenuItem({+ className,+ ...props+}: ComponentProps<typeof SelectItem>) {+ return (+ <SelectItem+ className={cn("min-h-10 py-2 pr-9 pl-3 leading-snug", className)}+ {...props}+ />+ )+}diff --git a/src/web/src/components/community/bots/model-field.tsx b/src/web/src/components/community/bots/model-field.tsxindex 545990223..594c5bfdc 100644--- a/src/web/src/components/community/bots/model-field.tsx+++ b/src/web/src/components/community/bots/model-field.tsx@@ -14,10 +14,9 @@ import {Select,SelectTrigger,SelectValue,- SelectContent,- SelectItem,SelectSeparator,} from "@/components/ui/select"+import { BotSelectMenuContent, BotSelectMenuItem } from "./bot-select-menu"/*** Per-bot model picker. A `Select` over `[Default, Custom…, ...catalog]` plus a@@ -112,11 +111,11 @@ export function ModelField({><SelectValue placeholder={defaultLabel} /></SelectTrigger>- <SelectContent className="overflow-y-hidden">+ <BotSelectMenuContent className="overflow-y-hidden">{modelIds.length === 0 ? (<>- <SelectItem value={MODEL_SELECT_DEFAULT}>{defaultLabel}</SelectItem>- <SelectItem value={MODEL_SELECT_CUSTOM}>Custom…</SelectItem>+ <BotSelectMenuItem value={MODEL_SELECT_DEFAULT}>{defaultLabel}</BotSelectMenuItem>+ <BotSelectMenuItem value={MODEL_SELECT_CUSTOM}>Custom…</BotSelectMenuItem></>) : (<>@@ -148,16 +147,16 @@ export function ModelField({className="h-10 font-mono sm:h-8"/></div>- <SelectItem value={MODEL_SELECT_DEFAULT}>{defaultLabel}</SelectItem>- <SelectItem value={MODEL_SELECT_CUSTOM}>Custom…</SelectItem>- <SelectSeparator />+ <BotSelectMenuItem value={MODEL_SELECT_DEFAULT}>{defaultLabel}</BotSelectMenuItem>+ <BotSelectMenuItem value={MODEL_SELECT_CUSTOM}>Custom…</BotSelectMenuItem>+ <SelectSeparator className="mx-1 my-1.5" /></div><divdata-testid="bot-model-probe-results"className="thin-scrollbar max-h-[min(18rem,50dvh)] overflow-y-auto">{filteredModels.map((model) => (- <SelectItem key={model.id} value={model.id}>+ <BotSelectMenuItem key={model.id} value={model.id}>{model.displayName && model.displayName !== model.id ? (<div className="flex min-w-0 flex-col items-start gap-0.5"><span>{model.displayName}</span>@@ -168,7 +167,7 @@ export function ModelField({) : (<span className="font-mono">{model.id}</span>)}- </SelectItem>+ </BotSelectMenuItem>))}{normalizedFilter && filteredModels.length === 0 ? (<p role="status" className="px-2 py-2 text-xs text-muted-foreground">@@ -178,7 +177,7 @@ export function ModelField({</div></>)}- </SelectContent>+ </BotSelectMenuContent></Select>{isCustom && (<Inputdiff --git a/src/web/src/components/community/bots/reasoning-effort-field.tsx b/src/web/src/components/community/bots/reasoning-effort-field.tsxindex 88f2cfb56..b4a79ee00 100644--- a/src/web/src/components/community/bots/reasoning-effort-field.tsx+++ b/src/web/src/components/community/bots/reasoning-effort-field.tsx@@ -10,12 +10,11 @@ import {import { Label } from "@/components/ui/label"import {Select,- SelectContent,- SelectItem,SelectTrigger,SelectValue,} from "@/components/ui/select"import { tid } from "@/lib/community/testids"+import { BotSelectMenuContent, BotSelectMenuItem } from "./bot-select-menu"const DEFAULT_VALUE = "__default__"const REASONING_CATALOG_MIN_DAEMON_VERSION = "0.1.25"@@ -95,14 +94,14 @@ export function ReasoningEffortField({><SelectValue placeholder={defaultLabel} /></SelectTrigger>- <SelectContent>- <SelectItem value={DEFAULT_VALUE}>{defaultLabel}</SelectItem>+ <BotSelectMenuContent>+ <BotSelectMenuItem value={DEFAULT_VALUE}>{defaultLabel}</BotSelectMenuItem>{options.map((option) => (- <SelectItem key={option.value} value={option.value}>+ <BotSelectMenuItem key={option.value} value={option.value}>{effortLabel(option.value)}- </SelectItem>+ </BotSelectMenuItem>))}- </SelectContent>+ </BotSelectMenuContent></Select><p id="bot-reasoning-effort-help" className="text-xs text-muted-foreground">{help}diff --git a/src/web/src/components/community/onboarding/onboarding-form-options.test.ts b/src/web/src/components/community/onboarding/onboarding-form-options.test.tsindex 0631893e8..2ec102dd7 100644--- a/src/web/src/components/community/onboarding/onboarding-form-options.test.ts+++ b/src/web/src/components/community/onboarding/onboarding-form-options.test.ts@@ -6,13 +6,18 @@ import {} from "./onboarding-form-options"describe("onboarding form options", () => {- it("offers exactly the five supported harnesses", () => {- expect(ONBOARDING_HARNESSES.map(({ value }) => value)).toEqual([- "claude",- "codex",- "cursor",- "opencode",- "pi",+ it("offers exactly the six supported harnesses with their provider logos", () => {+ expect(ONBOARDING_HARNESSES.map(({ value, label, provider }) => ({+ value,+ label,+ provider,+ }))).toEqual([+ { value: "claude", label: "Claude Code", provider: "claude" },+ { value: "codex", label: "Codex", provider: "codex" },+ { value: "grok", label: "Grok Build", provider: "grok" },+ { value: "cursor", label: "Cursor", provider: "cursor" },+ { value: "opencode", label: "OpenCode", provider: "opencode" },+ { value: "pi", label: "Pi", provider: "pi" },])})diff --git a/src/web/src/components/community/onboarding/onboarding-form-options.ts b/src/web/src/components/community/onboarding/onboarding-form-options.tsindex 93ab370f7..04a8e400b 100644--- a/src/web/src/components/community/onboarding/onboarding-form-options.ts+++ b/src/web/src/components/community/onboarding/onboarding-form-options.ts@@ -18,6 +18,11 @@ export const ONBOARDING_HARNESSES = [label: "Codex",provider: "codex",},+ {+ value: "grok",+ label: "Grok Build",+ provider: "grok",+ },{value: "cursor",label: "Cursor",diff --git a/src/web/src/components/community/onboarding/starter-packs.test.ts b/src/web/src/components/community/onboarding/starter-packs.test.tsindex bfb6f2f8a..095c3bcd2 100644--- a/src/web/src/components/community/onboarding/starter-packs.test.ts+++ b/src/web/src/components/community/onboarding/starter-packs.test.ts@@ -79,12 +79,20 @@ describe("starter packs", () => {expect(prompts[0]).toContain("You are the Lead")expect(prompts[0]).toContain("recent-context index appended below")expect(prompts[0]).toContain("Before opening or reading any specific session or project")+ expect(prompts[0]).toContain("mentions @Ada#0042")expect(prompts[0]).toContain("explains what you propose to explore and why")- expect(prompts[0]).toContain("invites the owner to guide or redirect you")expect(prompts[0]).toContain("begin exploring without waiting for a reply")- expect(prompts[0]).not.toContain("Wait for the owner's guidance")- expect(prompts[0].indexOf("invites the owner to guide or redirect you")).toBeLessThan(- prompts[0].indexOf("begin exploring without waiting for a reply"),+ expect(prompts[0]).toContain("Exploration is read-only")+ expect(prompts[0]).toContain("After you finish exploring")+ expect(prompts[0]).toContain("offers up to three concrete action suggestions")+ expect(prompts[0]).toContain("Then wait for the owner to choose, redirect, or confirm an action")+ expect(prompts[0]).toContain("Do not open a task thread, assign work, or begin executing")+ expect(prompts[0]).toContain("Open a task thread only after the owner chooses or assigns concrete work")+ expect(prompts[0].indexOf("begin exploring without waiting for a reply")).toBeLessThan(+ prompts[0].indexOf("After you finish exploring"),+ )+ expect(prompts[0].indexOf("offers up to three concrete action suggestions")).toBeLessThan(+ prompts[0].indexOf("Then wait for the owner to choose, redirect, or confirm an action"),)expect(prompts[0]).toContain("grounded in what the owner has actually been working on")expect(prompts[0]).toContain("ask the owner what they want to start with")diff --git a/src/web/src/components/community/onboarding/starter-packs.ts b/src/web/src/components/community/onboarding/starter-packs.tsindex 4229a47e6..b8d885897 100644--- a/src/web/src/components/community/onboarding/starter-packs.ts+++ b/src/web/src/components/community/onboarding/starter-packs.ts@@ -280,7 +280,7 @@ export function starterPackWakePrompt({"","## How this team works","",- "Read the exact public channel listed in the Alook space section below before doing anything else. Keep future work and handoffs in the same task thread.",+ "Read the exact public channel listed in the Alook space section below before doing anything else. Open a task thread only after the owner chooses or assigns concrete work, then keep that work and its handoffs in the same thread.",]if (bot.key === "lead") {@@ -288,7 +288,7 @@ export function starterPackWakePrompt({"","## Your first move","",- "You are the Lead. After saving your memory, read the public channel and review only the recent-context index appended below. Before opening or reading any specific session or project, send one brief message in the public channel that introduces the team, explains what you propose to explore and why, and invites the owner to guide or redirect you. Once that message is sent, begin exploring without waiting for a reply. If the owner replies later, follow their latest guidance. Inspect only the relevant sessions or projects, following the selective-reading instructions below, and propose up to three concrete next actions grounded in what the owner has actually been working on. Do not paste private paths or unrelated content into Alook. If no useful recent context exists, ask the owner what they want to start with instead of inventing generic suggestions. If a Lead already posted this initial message, do not repeat or summarize it; continue from the owner's latest guidance.",+ `You are the Lead. After saving your memory, read the public channel and review only the recent-context index appended below. Before opening or reading any specific session or project, send one brief message in the public channel that mentions ${ownerHandle}, explains what you propose to explore and why, and invites the owner to guide or redirect you. Once that message is sent, begin exploring without waiting for a reply. Exploration is read-only: inspect only the relevant sessions or projects, following the selective-reading instructions below. After you finish exploring, send one brief message in the public channel that mentions ${ownerHandle} and offers up to three concrete action suggestions grounded in what the owner has actually been working on. Then wait for the owner to choose, redirect, or confirm an action. Do not open a task thread, assign work, or begin executing any suggestion until the owner confirms concrete work. Do not paste private paths or unrelated content into Alook. If no useful recent context exists, ask the owner what they want to start with and wait instead of inventing generic suggestions. If a Lead already posted the pre-exploration message, do not repeat it. If the Lead already posted action suggestions, do not repeat or begin them; follow the owner's latest guidance.`,)return briefing.join("\n")}diff --git a/src/web/src/components/community/shell/community-ws-reconnect-overlay.dom.test.ts b/src/web/src/components/community/shell/community-ws-reconnect-overlay.dom.test.tsindex c2b84ab96..baaeda221 100644--- a/src/web/src/components/community/shell/community-ws-reconnect-overlay.dom.test.ts+++ b/src/web/src/components/community/shell/community-ws-reconnect-overlay.dom.test.ts@@ -53,14 +53,14 @@ describe("CommunityWsReconnectBoundary", () => {)expect(screen.getByRole("status")).toHaveAttribute("aria-atomic", "true")expect(screen.getByRole("status")).toHaveAttribute("aria-live", "polite")+ expect(screen.getByRole("status")).toHaveAttribute("data-slot", "text-loader")+ expect(screen.getByRole("status")).toHaveAttribute("data-variant", "default")expect(screen.getByRole("heading", { name: "Connecting…" })).toBeInTheDocument()- const motion = overlay.querySelector<SVGElement>("[data-connecting-motion]")!- expect(motion.tagName.toLowerCase()).toBe("svg")- expect(motion).toHaveClass("community-ws-connecting-loader")- expect(motion.querySelectorAll("rect")).toHaveLength(2)- expect(motion.querySelector("circle")).toHaveClass("community-ws-connecting-dot")- expect(motion.querySelectorAll("filter")).toHaveLength(1)- expect(motion.querySelectorAll("feBlend")).toHaveLength(1)+ const motion = overlay.querySelector<HTMLElement>("[data-connecting-motion]")!+ expect(motion.tagName.toLowerCase()).toBe("span")+ expect(motion).toHaveClass("community-ws-connecting-orb")+ expect(overlay.querySelectorAll(".community-ws-connecting-letter")).toHaveLength(11)+ expect(overlay.querySelector(".community-ws-connecting-text")).toHaveTextContent("Connecting…")expect(screen.queryByTestId(tid.wsRetry)).not.toBeInTheDocument()expect(focus).toHaveBeenCalledOnce()})diff --git a/src/web/src/components/community/shell/community-ws-reconnect-overlay.tsx b/src/web/src/components/community/shell/community-ws-reconnect-overlay.tsxindex 0a1430c54..ddac09201 100644--- a/src/web/src/components/community/shell/community-ws-reconnect-overlay.tsx+++ b/src/web/src/components/community/shell/community-ws-reconnect-overlay.tsx@@ -6,6 +6,8 @@ import { Button } from "@/components/ui/button"import { tid } from "@/lib/community/testids"import { useCommunityWsStore } from "@/stores/community/ws"+const CONNECTING_LABEL = "Connecting…"+export function CommunityWsReconnectBoundary({ children }: { children: ReactNode }) {const connectionStatus = useCommunityWsStore((state) => state.connectionStatus)const reconnectNow = useCommunityWsStore((state) => state.reconnectNow)@@ -73,44 +75,35 @@ export function CommunityWsReconnectBoundary({ children }: { children: ReactNode</Button></>) : (- <div role="status" aria-live="polite" aria-atomic="true" className="flex flex-col items-center">- <svg+ <div+ role="status"+ aria-live="polite"+ aria-atomic="true"+ data-slot="text-loader"+ data-variant="default"+ className="community-ws-connecting-loader"+ >+ {/* Adapted from OpensourceUI's TextLoader. See ../../home/opensourceui-mockups.LICENSE.txt. */}+ <spanaria-hidden="true"data-connecting-motion=""- className="community-ws-connecting-loader mb-4"- viewBox="0 0 100 100"+ className="community-ws-connecting-orb"+ />+ <h2+ id="community-ws-reconnect-title"+ aria-label={CONNECTING_LABEL}+ className="community-ws-connecting-text font-heading text-base font-medium">- <defs>- <filter- id="community-ws-connecting-goo"- x="-20%"- y="-20%"- width="140%"- height="140%"- colorInterpolationFilters="sRGB"+ {CONNECTING_LABEL.split("").map((letter, index) => (+ <span+ key={`${letter}-${index}`}+ aria-hidden="true"+ className="community-ws-connecting-letter"+ style={{ animationDelay: `${index * 0.09}s` }}>- <feGaussianBlur in="SourceGraphic" stdDeviation="5" result="blur" />- <feColorMatrix- in="blur"- values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 20 -10"- result="goo"- />- <feBlend in="SourceGraphic" in2="goo" />- </filter>- </defs>- <g fill="currentColor" filter="url(#community-ws-connecting-goo)">- <rect x="10" y="30" width="20" height="40" rx="10" />- <circle- className="community-ws-connecting-dot"- cx="20"- cy="50"- r="10"- />- <rect x="70" y="30" width="20" height="40" rx="10" />- </g>- </svg>- <h2 id="community-ws-reconnect-title" className="font-heading text-base font-medium">- Connecting…+ {letter}+ </span>+ ))}</h2></div>)}diff --git a/src/web/src/components/home/homepage-faq.test.ts b/src/web/src/components/home/homepage-faq.test.tsindex a22f18824..b83ae9e6e 100644--- a/src/web/src/components/home/homepage-faq.test.ts+++ b/src/web/src/components/home/homepage-faq.test.ts@@ -49,7 +49,7 @@ describe("HomepageFaq", () => {expect(HOME_FAQS.map(({ answer }) => answer)).toEqual(["Alook is where people and AI agents share the same rooms. Your local coding agents get persistent identities — a handle, inbox, and memberships — so your team can address them in servers, channels, and DMs the same way you'd reach a person.","A machine running Node.js 20.9+ and a supported coding agent. Run the daemon pairing command, and your agent joins the room. No extra AI subscription through Alook — you bring the runtime you already pay for.",- "Yes. Alook connects to the coding agents already on your machine. It does not supply or host its own models. Your existing Claude Code or Codex installation keeps its tools, credentials, and codebase access — Alook gives it a way to be reached.",+ "Yes. Alook connects to the coding agents already on your machine. It does not supply or host its own models. Each supported local runtime keeps its tools, credentials, and codebase access — Alook gives it a way to be reached.","Discord and Slack are built for people messaging each other. Bots are add-ons. In Alook, agents are first-class participants with their own handles, inboxes, and memberships. Work can wait in an agent's inbox, handoffs stay visible, and the daemon keeps the agent reachable without an interactive terminal session.","Buzz centers a sovereign Nostr relay and signed-event stack — workflows, voice, Git, broader infrastructure. Alook offers a hosted room layer (also self-hostable) focused on the coding agents you already run. Same Apache-2.0 license, different operating model and surface area.","Managed workspaces like Oasis can supply cloud-hosted agents and connect outside services. Alook does not supply models or route them. Instead, it gives your existing local agents persistent account handles, an inbox, server/channel/DM memberships, and daemon wake semantics — the agent stays a participant even after a session ends.",diff --git a/src/web/src/components/home/landing-content.test.ts b/src/web/src/components/home/landing-content.test.tsindex 24d3859ca..b40697dfa 100644--- a/src/web/src/components/home/landing-content.test.ts+++ b/src/web/src/components/home/landing-content.test.ts@@ -69,9 +69,14 @@ describe("landing content contract", () => {})it("keeps provider examples compact", () => {- expect(LANDING_PROVIDERS).toContain("claude")- expect(LANDING_PROVIDERS).toContain("codex")- expect(LANDING_PROVIDERS).toContain("cursor")+ expect(LANDING_PROVIDERS).toEqual([+ { id: "claude", label: "Claude Code" },+ { id: "codex", label: "Codex" },+ { id: "grok", label: "Grok Build" },+ { id: "cursor", label: "Cursor" },+ { id: "opencode", label: "OpenCode" },+ { id: "pi", label: "Pi" },+ ])})it("cycles several truthful typewriter cases", () => {@@ -180,6 +185,10 @@ describe("landing content contract", () => {const motionStyles = readFileSync(path.join(root, "src/components/home/landing-shell-motion.module.css"), "utf8")const reachSource = readFileSync(path.join(root, "src/components/home/landing-reach-motion.tsx"), "utf8")const reachStyles = readFileSync(path.join(root, "src/components/home/landing-reach-motion.module.css"), "utf8")+ const reachMockupLicense = readFileSync(+ path.join(root, "src/components/home/opensourceui-mockups.LICENSE.txt"),+ "utf8",+ )const shellSource = readFileSync(path.join(root, "src/components/home/landing-shell-motion.tsx"), "utf8")const playbackSource = readFileSync(path.join(root, "src/components/home/use-landing-motion-playback.ts"), "utf8")const heroSource = readFileSync(path.join(root, "src/components/home/hero-section.tsx"), "utf8")@@ -216,7 +225,7 @@ describe("landing content contract", () => {expect(BRAND_DESCRIPTION).toContain("shared rooms")expect(LANDING_META_TITLE).toBe("AI Agent Collaboration Rooms for Local Agents — Alook")expect(LANDING_META_DESCRIPTION).toBe(- "Share your local AI agents with your team. Claude Code, Codex, Cursor, OpenCode, and Pi get persistent identities and memory — while running on your machine. Open source.",+ "Share your local AI agents with your team. Claude Code, Codex, Grok Build, Cursor, OpenCode, and Pi get persistent identities and memory — while running on your machine. Open source.",)expect(brandCopySource).not.toContain("Personal Company")expect(rootRoute).toContain("LANDING_META_TITLE")@@ -359,8 +368,9 @@ describe("landing content contract", () => {expect(landingPageSource).toContain("Share what already works")expect(landingPageSource).toContain("Invite your team to talk with your AI agents")expect(normalizedLandingPageSource).toContain(- "Your agents already handle real work — Claude Code, Codex, Cursor, OpenCode, or Pi. Alook lets your team collaborate with them directly in shared channels, without forwarding messages or sharing screens.",+ "Your agents already handle real work — Claude Code, Codex, Grok Build, Cursor, OpenCode, or Pi. Alook lets your team collaborate with them directly in shared channels, without forwarding messages or sharing screens.",)+ expect(landingPageSource).toContain('data-testid="landing-runtime-badges"')expect(landingPageSource).toContain("Across every room")expect(landingPageSource).toContain("One persistent agent identity")expect(landingPageSource).not.toContain("One persistent identity across rooms")@@ -439,7 +449,15 @@ describe("landing content contract", () => {expect(normalizedLandingPageSource).toContain("Desktop or phone — you stay in the same room with the same people and agents; nothing drops when you switch.",)- expect(reachSource).toContain("<p>Desktop</p>")+ expect(reachSource).toContain('data-slot="laptop-mockup-card"')+ expect(reachSource).toContain('data-variant="starlight"')+ expect(reachSource).toContain('data-testid="landing-laptop-mockup"')+ expect(reachSource).toContain('data-slot="phone-mockup-card"')+ expect(reachSource).toContain('data-variant="titanium"')+ expect(reachSource).toContain('data-testid="landing-phone-mockup"')+ expect(reachSource).toContain("styles.phoneDynamicIsland")+ expect(reachSource).toContain("styles.phoneHomeIndicator")+ expect(reachSource).not.toContain("styles.deviceBar")expect(shellSource).toContain("<span>Phone</span>")expect(`${reachSource} ${shellSource}`).not.toContain("Alook Web")expect(reachSource).toContain('<LandingShellMotion scene="server" beat={beat} />')@@ -450,14 +468,17 @@ describe("landing content contract", () => {expect(shellSource).toContain("stage.getBoundingClientRect().width / 390")expect(motionStyles).toContain("transform: scale(var(--mobile-stage-scale))")expect(motionStyles).toMatch(/\.mobileMessages\s*\{[\s\S]*?justify-content: flex-start;/)- expect(reachStyles).toContain("width: clamp(148px, 42%, 196px)")- expect(reachStyles).toContain("clamp(-220px, -42vw, -160px)")- expect(reachStyles).toContain("width: clamp(96px, 24%, 224px)")- expect(reachStyles).toContain("right: clamp(20px, 12%, 120px)")- expect(reachStyles).toContain("bottom: clamp(24px, 8%, 64px)")+ expect(reachStyles).toContain("width: clamp(146px, 42%, 190px)")+ expect(reachStyles).toContain("clamp(-210px, -40vw, -150px)")+ expect(reachStyles).toContain("width: clamp(108px, 24%, 224px)")+ expect(reachStyles).toContain("aspect-ratio: 70.6 / 146.6")+ expect(reachStyles).toContain("right: clamp(14px, 5%, 56px)")+ expect(reachStyles).toContain("bottom: clamp(24px, 7%, 56px)")expect(reachStyles).toContain("aspect-ratio: 1120 / 760")- expect(reachStyles).toContain("clamp(12px, 4vw, 24px)")- expect(reachStyles).toMatch(/\.desktopShell\s*\{[\s\S]*?left: 9%;/)+ expect(reachStyles).toContain("clamp(14px, 4vw, 24px)")+ expect(reachStyles).toMatch(/\.desktopShell\s*\{[\s\S]*?left: 1%;/)+ expect(reachStyles).toMatch(/\.laptopBase\s*\{[\s\S]*?linear-gradient/)+ expect(reachMockupLicense).toContain("Copyright (c) 2026 Bidyut Kundu")expect(landingPageSource).toContain("BRAND_SLOGAN")expect(landingPageSource).toContain("Alook holds the room")expect(landingPageSource).toContain("Run AI agents locally on your machine")diff --git a/src/web/src/components/home/landing-content.ts b/src/web/src/components/home/landing-content.tsindex 380c67187..2f5f07598 100644--- a/src/web/src/components/home/landing-content.ts+++ b/src/web/src/components/home/landing-content.ts@@ -4,7 +4,7 @@ import { BRAND_SLOGAN } from "@/lib/brand-copy"export const LANDING_META_TITLE = "AI Agent Collaboration Rooms for Local Agents — Alook"export const LANDING_META_DESCRIPTION =- "Share your local AI agents with your team. Claude Code, Codex, Cursor, OpenCode, and Pi get persistent identities and memory — while running on your machine. Open source."+ "Share your local AI agents with your team. Claude Code, Codex, Grok Build, Cursor, OpenCode, and Pi get persistent identities and memory — while running on your machine. Open source."export const LANDING_SECTION_ORDER = ["hero",@@ -93,7 +93,14 @@ export const LANDING_CONTINUITY = {"Your agent holds context between sessions and moves tasks forward without you repeating instructions. An inbox catches what arrives while you’re away.",} as const-export const LANDING_PROVIDERS = ["claude", "codex", "cursor", "opencode", "pi"] as const+export const LANDING_PROVIDERS = [+ { id: "claude", label: "Claude Code" },+ { id: "codex", label: "Codex" },+ { id: "grok", label: "Grok Build" },+ { id: "cursor", label: "Cursor" },+ { id: "opencode", label: "OpenCode" },+ { id: "pi", label: "Pi" },+] as constexport const HOME_FAQS = [{@@ -109,7 +116,7 @@ export const HOME_FAQS = [{question: "Can I bring agents I already use?",answer:- "Yes. Alook connects to the coding agents already on your machine. It does not supply or host its own models. Your existing Claude Code or Codex installation keeps its tools, credentials, and codebase access — Alook gives it a way to be reached.",+ "Yes. Alook connects to the coding agents already on your machine. It does not supply or host its own models. Each supported local runtime keeps its tools, credentials, and codebase access — Alook gives it a way to be reached.",},{question: "How is Alook different from Discord or Slack?",diff --git a/src/web/src/components/home/landing-page.tsx b/src/web/src/components/home/landing-page.tsxindex 685c2858a..fa3c13b8a 100644--- a/src/web/src/components/home/landing-page.tsx+++ b/src/web/src/components/home/landing-page.tsx@@ -96,11 +96,15 @@ function ContinuityTimeline() {function RuntimeBadges() {return (- <div className={styles.runtimeBadges} aria-label="Supported local runtimes">+ <div+ className={styles.runtimeBadges}+ aria-label="Supported local runtimes"+ data-testid="landing-runtime-badges"+ >{LANDING_PROVIDERS.map((provider) => (- <span key={provider}>- <ProviderLogo provider={provider} className="size-4" />- {provider === "opencode" ? "OpenCode" : provider[0].toUpperCase() + provider.slice(1)}+ <span key={provider.id}>+ <ProviderLogo provider={provider.id} className="size-4" />+ {provider.label}</span>))}</div>@@ -311,9 +315,9 @@ export function LandingPage({ isLoggedIn }: { isLoggedIn: boolean }) {<h2>Invite your team to talk with your AI agents</h2></div><p>- Your agents already handle real work — Claude Code, Codex, Cursor, OpenCode, or Pi. Alook lets your- team collaborate with them directly in shared channels, without forwarding messages or sharing- screens.+ Your agents already handle real work — Claude Code, Codex, Grok Build, Cursor, OpenCode, or Pi. Alook+ lets your team collaborate with them directly in shared channels, without forwarding messages or+ sharing screens.</p></div><ProductScene scene="server" />diff --git a/src/web/src/components/home/landing-reach-motion.module.css b/src/web/src/components/home/landing-reach-motion.module.cssindex 1df684f42..910b3fd6e 100644--- a/src/web/src/components/home/landing-reach-motion.module.css+++ b/src/web/src/components/home/landing-reach-motion.module.css@@ -9,54 +9,161 @@.desktopShell {position: absolute;- top: 0;- left: 9%;- width: 82%;+ top: 3%;+ left: 1%;+ display: flex;+ width: 94%;+ flex-direction: column;+ align-items: center;+}++.laptopLid {+ width: 88.89%;overflow: hidden;- border: 1px solid var(--landing-border);- border-radius: var(--radius-xl);- background: var(--background);- box-shadow: var(--shadow-md);+ border: 2px solid #d8cdb8;+ border-bottom: 0;+ border-radius: 12px 12px 0 0;+ box-shadow:+ 0 34px 76px rgb(20 32 25 / 28%),+ 0 12px 28px rgb(20 32 25 / 16%);}-.deviceBar {- display: flex;- height: 32px;- align-items: center;- gap: 6px;- padding: 0 12px;- border-bottom: 1px solid var(--border);- background: var(--muted);+.laptopBezel {+ padding: 6px 6px 0;+ background: #26262c;}-.deviceBar > span {- width: 7px;- height: 7px;- border-radius: 999px;- background: var(--muted-foreground);- opacity: 0.36;+.laptopScreen {+ overflow: hidden;+ border-radius: 4px 4px 0 0;+ background: #111216;}-.deviceBar p {- margin-left: 8px;- color: var(--muted-foreground);- font-family: var(--font-mono);- font-size: 0.6rem;+.laptopBase {+ position: relative;+ width: 100%;+ height: clamp(10px, 1.1vw, 14px);+ border-radius: 0 0 12px 12px;+ background: linear-gradient(to bottom, #f0e6d4, #dcd0b8);+ box-shadow: 0 20px 36px rgb(20 32 25 / 22%);+}++.laptopNotch {+ position: absolute;+ top: 0;+ left: 50%;+ width: clamp(48px, 15%, 72px);+ height: 4px;+ border-radius: 0 0 6px 6px;+ background: #c9bc9e;+ transform: translateX(-50%);}.phone {+ --phone-corner-radius: clamp(18px, 2.6vw, 30px);+position: absolute;z-index: 5;- right: clamp(20px, 12%, 120px);- bottom: clamp(24px, 8%, 64px);- width: clamp(96px, 24%, 224px);- aspect-ratio: 390 / 788;+ right: clamp(14px, 5%, 56px);+ bottom: clamp(24px, 7%, 56px);+ width: clamp(108px, 24%, 224px);+ aspect-ratio: 70.6 / 146.6;+ padding: 2px;+ border-radius: var(--phone-corner-radius);+ background: #9a9590;+ color: var(--foreground);+ box-shadow:+ 0 34px 72px rgb(20 32 25 / 34%),+ 0 14px 28px rgb(20 32 25 / 22%);+}++.phoneBezel {+ position: relative;+ width: 100%;+ height: 100%;+ overflow: hidden;+ border-radius: calc(var(--phone-corner-radius) - 2px);+ background: #050505;+}++.phoneScreen {+ position: absolute;+ inset: 3.5px;overflow: hidden;- border: 3px solid var(--foreground);- border-radius: 24px;+ border-radius: calc(var(--phone-corner-radius) - 5.5px);background: var(--background);- color: var(--foreground);- box-shadow: var(--shadow-md);+}++.phoneMuteButton,+.phoneVolumeUpButton,+.phoneVolumeDownButton,+.phonePowerButton {+ position: absolute;+ z-index: 2;+ width: 2px;+ border-radius: 2px 0 0 2px;+ background: #8f8a85;+}++.phoneMuteButton {+ top: 15.5%;+ left: -2px;+ height: 3.2%;+}++.phoneVolumeUpButton {+ top: 21%;+ left: -2px;+ height: 7.2%;+}++.phoneVolumeDownButton {+ top: 30.5%;+ left: -2px;+ height: 7.2%;+}++.phonePowerButton {+ top: 23%;+ right: -2px;+ height: 11.5%;+ border-radius: 0 2px 2px 0;+}++.phoneDynamicIsland {+ position: absolute;+ z-index: 20;+ top: 1.7%;+ left: 50%;+ width: 25.8%;+ height: 3.8%;+ min-height: 5px;+ border-radius: 999px;+ background: #050505;+ transform: translateX(-50%);+}++.phoneDynamicIsland > span {+ position: absolute;+ top: 50%;+ right: 8%;+ width: 12%;+ aspect-ratio: 1;+ border-radius: 999px;+ background: rgb(106 144 200 / 20%);+ transform: translateY(-50%);+}++.phoneHomeIndicator {+ position: absolute;+ z-index: 20;+ bottom: 1%;+ left: 50%;+ width: 32%;+ height: 3px;+ border-radius: 999px;+ background: rgb(5 5 5 / 28%);+ transform: translateX(-50%);}@media (max-width: 720px) {@@ -78,8 +185,8 @@position: relative;right: auto;bottom: auto;- width: clamp(148px, 42%, 196px);- margin: clamp(-220px, -42vw, -160px) clamp(12px, 4vw, 24px) 0 auto;+ width: clamp(146px, 42%, 190px);+ margin: clamp(-210px, -40vw, -150px) clamp(14px, 4vw, 24px) 0 auto;}}diff --git a/src/web/src/components/home/landing-reach-motion.tsx b/src/web/src/components/home/landing-reach-motion.tsxindex 33fa1ec65..3a301f95d 100644--- a/src/web/src/components/home/landing-reach-motion.tsx+++ b/src/web/src/components/home/landing-reach-motion.tsx@@ -13,6 +13,11 @@ import {import styles from "./landing-reach-motion.module.css"import { useLandingMotionPlayback } from "./use-landing-motion-playback"+/**+ * Device shell anatomy adapted from OpensourceUI's LaptopMockupCard and+ * PhoneMockupCard. See ./opensourceui-mockups.LICENSE.txt.+ */+function useReducedMotion() {const [reduced, setReduced] = useState(false)@@ -62,18 +67,43 @@ export function LandingReachMotion() {data-beat={beat}aria-label="The same Alook room updating on desktop and mobile">- <div className={styles.desktopShell}>- <div className={styles.deviceBar} aria-hidden>- <span />- <span />- <span />- <p>Desktop</p>+ <div+ className={styles.desktopShell}+ data-slot="laptop-mockup-card"+ data-variant="starlight"+ data-testid="landing-laptop-mockup"+ >+ <div className={styles.laptopLid}>+ <div className={styles.laptopBezel}>+ <div className={styles.laptopScreen}>+ <LandingShellMotion scene="server" beat={beat} />+ </div>+ </div>+ </div>+ <div className={styles.laptopBase} aria-hidden="true">+ <span className={styles.laptopNotch} /></div>- <LandingShellMotion scene="server" beat={beat} /></div>- <div className={styles.phone}>- <LandingMobileChatMotion beat={beat} />+ <div+ className={styles.phone}+ data-slot="phone-mockup-card"+ data-variant="titanium"+ data-testid="landing-phone-mockup"+ >+ <span className={styles.phoneMuteButton} aria-hidden="true" />+ <span className={styles.phoneVolumeUpButton} aria-hidden="true" />+ <span className={styles.phoneVolumeDownButton} aria-hidden="true" />+ <span className={styles.phonePowerButton} aria-hidden="true" />+ <div className={styles.phoneBezel}>+ <div className={styles.phoneScreen}>+ <LandingMobileChatMotion beat={beat} />+ <span className={styles.phoneDynamicIsland} aria-hidden="true">+ <span />+ </span>+ <span className={styles.phoneHomeIndicator} aria-hidden="true" />+ </div>+ </div></div></div>)diff --git a/src/web/src/components/home/opensourceui-mockups.LICENSE.txt b/src/web/src/components/home/opensourceui-mockups.LICENSE.txtnew file mode 100644index 000000000..360c0a306--- /dev/null+++ b/src/web/src/components/home/opensourceui-mockups.LICENSE.txt@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Bidyut Kundu++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/src/web/src/components/provider-logo.test.ts b/src/web/src/components/provider-logo.test.tsnew file mode 100644index 000000000..35565e9ac--- /dev/null+++ b/src/web/src/components/provider-logo.test.ts@@ -0,0 +1,18 @@+import { createElement } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import { describe, expect, it } from "vitest";+import { ProviderLogo } from "./provider-logo";++describe("ProviderLogo", () => {+ it("renders the official Grok logomark for the grok runtime", () => {+ const markup = renderToStaticMarkup(+ createElement(ProviderLogo, { provider: "grok", className: "size-6" }),+ );++ expect(markup).toContain('data-provider-logo="grok"');+ expect(markup).toContain('viewBox="0 0 1024 1024"');+ expect(markup).toContain('class="size-6"');+ expect(markup.match(/class="fill-current"/g)).toHaveLength(2);+ expect(markup.match(/<path/g)).toHaveLength(2);+ });+});diff --git a/src/web/src/components/provider-logo.tsx b/src/web/src/components/provider-logo.tsxindex 33e50a42e..c8230465d 100644--- a/src/web/src/components/provider-logo.tsx+++ b/src/web/src/components/provider-logo.tsx@@ -137,6 +137,27 @@ function KimiLogo({ className }: { className: string }) {);}+function GrokLogo({ className }: { className: string }) {+ return (+ <svg+ viewBox="0 0 1024 1024"+ fill="none"+ className={className}+ data-provider-logo="grok"+ aria-hidden="true"+ >+ <path+ d="M395.479 633.828L735.91 381.105C752.599 368.715 776.454 373.548 784.406 392.792C826.26 494.285 807.561 616.253 724.288 699.996C641.016 783.739 525.151 802.104 419.247 760.277L303.556 814.143C469.49 928.202 670.987 899.995 796.901 773.282C896.776 672.843 927.708 535.937 898.785 412.476L899.047 412.739C857.105 231.37 909.358 158.874 1016.4 10.6326C1018.93 7.11771 1021.47 3.60279 1024 0L883.144 141.651V141.212L395.392 633.916"+ className="fill-current"+ />+ <path+ d="M325.226 695.251C206.128 580.84 226.662 403.776 328.285 301.668C403.431 226.097 526.549 195.254 634.026 240.596L749.454 186.994C728.657 171.88 702.007 155.623 671.424 144.2C533.19 86.9942 367.693 115.465 255.323 228.382C147.234 337.081 113.244 504.215 171.613 646.833C215.216 753.423 143.739 828.818 71.7385 904.916C46.2237 931.893 20.6216 958.87 0 987.429L325.139 695.339"+ className="fill-current"+ />+ </svg>+ );+}+export function ProviderLogo({provider,className = "h-4 w-4",@@ -167,6 +188,8 @@ export function ProviderLogo({return <AntigravityLogo className={className} />;case "kimi":return <KimiLogo className={className} />;+ case "grok":+ return <GrokLogo className={className} />;default:return <Monitor className={className} />;}diff --git a/src/web/src/lib/runtime-display.test.ts b/src/web/src/lib/runtime-display.test.tsindex 543f826ca..c2330d278 100644--- a/src/web/src/lib/runtime-display.test.ts+++ b/src/web/src/lib/runtime-display.test.ts@@ -5,6 +5,7 @@ describe("runtimeDisplayName", () => {it("maps known providers to friendly names", () => {expect(runtimeDisplayName("claude")).toBe("Claude Code");expect(runtimeDisplayName("codex")).toBe("Codex");+ expect(runtimeDisplayName("grok")).toBe("Grok Build");expect(runtimeDisplayName("opencode")).toBe("OpenCode");});diff --git a/src/web/src/lib/runtime-display.ts b/src/web/src/lib/runtime-display.tsindex 86d063136..c16afda6f 100644--- a/src/web/src/lib/runtime-display.ts+++ b/src/web/src/lib/runtime-display.ts@@ -8,6 +8,7 @@const PROVIDER_DISPLAY_NAMES: Record<string, string> = {claude: "Claude Code",codex: "Codex",+ grok: "Grok Build",opencode: "OpenCode",};diff --git a/src/web/src/test/e2e-ui/25-community-ws-reconnect-overlay.spec.ts b/src/web/src/test/e2e-ui/25-community-ws-reconnect-overlay.spec.tsindex 3ec83c58a..1b631e8e8 100644--- a/src/web/src/test/e2e-ui/25-community-ws-reconnect-overlay.spec.ts+++ b/src/web/src/test/e2e-ui/25-community-ws-reconnect-overlay.spec.ts@@ -35,14 +35,16 @@ test("real WebSocket outage blocks the whole community surface and Retry restoreconst rect = element.getBoundingClientRect()const content = element.previousElementSibling as HTMLElement | nullconst connectingMotion = element.querySelector<HTMLElement>("[data-connecting-motion]")- const connectingDot = element.querySelector<SVGCircleElement>(".community-ws-connecting-dot")+ const connectingLetter = element.querySelector<HTMLElement>(".community-ws-connecting-letter")const connectingStyle = connectingMotion ? getComputedStyle(connectingMotion) : null+ const loaderStyle = getComputedStyle(element.querySelector<HTMLElement>("[data-slot='text-loader']")!)return {ariaHidden: content?.getAttribute("aria-hidden"),inert: content?.hasAttribute("inert"),- animationName: connectingDot ? getComputedStyle(connectingDot).animationName : null,+ iconAnimationName: connectingStyle?.animationName,+ letterAnimationName: connectingLetter ? getComputedStyle(connectingLetter).animationName : null,loaderBackground: connectingStyle?.backgroundColor,- loaderBlendMode: connectingStyle?.mixBlendMode,+ loaderDisplay: loaderStyle.display,loaderElement: connectingMotion?.tagName.toLowerCase(),rect: { x: rect.x, y: rect.y, width: rect.width, height: rect.height },viewport: { width: innerWidth, height: innerHeight },@@ -51,10 +53,11 @@ test("real WebSocket outage blocks the whole community surface and Retry restoreexpect(reconnectingEvidence).toMatchObject({ariaHidden: "true",inert: true,- animationName: "none",- loaderBackground: "rgba(0, 0, 0, 0)",- loaderBlendMode: "normal",- loaderElement: "svg",+ iconAnimationName: "none",+ letterAnimationName: "none",+ loaderBackground: "rgb(124, 9, 17)",+ loaderDisplay: "flex",+ loaderElement: "span",rect: { x: 0, y: 0, width: 390, height: 844 },viewport: { width: 390, height: 844 },})diff --git a/src/web/src/test/e2e-ui/31-machine-guide-motion.spec.ts b/src/web/src/test/e2e-ui/31-machine-guide-motion.spec.tsindex 306d7c384..06a620dc7 100644--- a/src/web/src/test/e2e-ui/31-machine-guide-motion.spec.ts+++ b/src/web/src/test/e2e-ui/31-machine-guide-motion.spec.ts@@ -21,5 +21,18 @@ for (const viewport of [).toBeVisible()await expect(onboarding.getByLabel("Step 1 of 3")).toBeVisible()await expect(page.getByTestId(tid.machineFirstSignupGuide)).toHaveCount(0)++ const grok = page.getByTestId(tid.onboardingHarnessOption("grok"))+ await expect(grok).toBeVisible()+ await expect(grok).toContainText("Grok Build")+ await expect(grok.locator('[data-provider-logo="grok"]')).toBeVisible()+ await grok.click()+ await onboarding.getByRole("button", { name: "Continue", exact: true }).click()++ const machineStep = page.getByTestId(tid.onboardingMachineDialog)+ await expect(machineStep).toBeVisible()+ await expect(machineStep.getByRole("heading", { name: /Connect your Grok Build machine/ }))+ .toBeVisible()+ await expect(machineStep.locator('[data-provider-logo="grok"]')).toBeVisible()})}diff --git a/src/web/src/test/e2e-ui/35-bot-token-usage-quota.spec.ts b/src/web/src/test/e2e-ui/35-bot-token-usage-quota.spec.tsindex bb437938d..aed1a262c 100644--- a/src/web/src/test/e2e-ui/35-bot-token-usage-quota.spec.ts+++ b/src/web/src/test/e2e-ui/35-bot-token-usage-quota.spec.ts@@ -95,6 +95,7 @@ const machine = {{ id: "codex", status: "healthy" },{ id: "pi", status: "healthy" },{ id: "claude", status: "healthy" },+ { id: "grok", status: "healthy" },],createdAt: "2026-08-29T00:00:00.000Z",updatedAt: "2026-08-29T01:00:00.000Z",@@ -157,6 +158,26 @@ const machine = {}],},},+ {+ scope: { kind: "machine_backend", machineId: "machine_telemetry", agentBackendId: "grok" },+ capability: "supported",+ runtimeState: "healthy",+ snapshot: {+ status: "available",+ observedAt: new Date().toISOString(),+ planName: "SuperGrok",+ limits: [{+ bucket: {+ limitId: "two-hour",+ product: { kind: "reported", id: "grok", displayName: "Grok" },+ model: { kind: "reported", id: "grok-4.6" },+ window: { kind: "rolling", durationSeconds: 7_200, displayName: "2 hour usage limit" },+ },+ usedPercent: 28,+ resetsAt: "2026-08-29T03:00:00.000Z",+ }],+ },+ },],}@@ -294,7 +315,10 @@ test("My Bots restores the 30-day token heatmap across PC and mobile", async ({)).toHaveCount(30)const quota = page.getByTestId(tid.machineQuota(machine.id))await expect(quota).toHaveCount(1)- await expect(quota).toContainText("Quota · Spark · 18% left · 3 limits")+ await expect(quota).toHaveAttribute(+ "aria-label",+ "Quota details: Claude 64% left; Codex 18% left; Grok 72% left. 4 limits",+ )await expect(page.getByTestId(tid.botUsageDay("bot_codex", "2026-08-24"))).toHaveClass(/bg-muted-foreground\/15/)@@ -335,10 +359,17 @@ test("My Bots restores the 30-day token heatmap across PC and mobile", async ({await expect(quotaDetail).toContainText("Claude")await expect(quotaDetail).toContainText("Max")await expect(quotaDetail).toContainText("64% left")+ await expect(quotaDetail).toContainText("Grok")+ await expect(quotaDetail).toContainText("SuperGrok")+ await expect(quotaDetail).toContainText("72% left")await expect(quotaDetail).toContainText("5 hour usage limit")await expect(quotaDetail).toContainText("Weekly usage limit")await expect(quotaDetail).toContainText("gpt-5.3-codex-spark")await expect(quotaDetail).toHaveCSS("opacity", "1")+ expect(await quotaDetail.locator("[data-quota-backend]").evaluateAll((elements) => (+ elements.map((element) => element.getAttribute("data-quota-backend"))+ ))).toEqual(["claude", "codex", "grok", "pi"])+ await attachScreenshot(page, testInfo, "my-bots-machine-quota-popover-pc")await quota.click()await expect(quota).toHaveAttribute("aria-expanded", "false")@@ -396,6 +427,12 @@ test("My Bots restores the 30-day token heatmap across PC and mobile", async ({expect(mobileMetaBox).not.toBeNull()expect(mobileUsageBox!.y).toBeGreaterThan(mobileMetaBox!.y + mobileMetaBox!.height)await attachScreenshot(page, testInfo, "my-bots-token-heatmap-mobile")+ await quota.click()+ await expect(quotaDetail).toBeVisible()+ await expect(quotaDetail).toHaveCSS("opacity", "1")+ await attachScreenshot(page, testInfo, "my-bots-machine-quota-popover-mobile")+ await quota.click()+ await expect(quotaDetail).toBeHidden()await mobileTrigger.click()const usageDialog = page.getByTestId(tid.botUsageDialog("bot_codex"))const dateRail = page.getByTestId(tid.botUsageDateRail("bot_codex"))diff --git a/src/web/src/test/e2e/community-machine-backend-quota-schema.test.ts b/src/web/src/test/e2e/community-machine-backend-quota-schema.test.tsnew file mode 100644index 000000000..a6a773173--- /dev/null+++ b/src/web/src/test/e2e/community-machine-backend-quota-schema.test.ts@@ -0,0 +1,64 @@+import { afterAll, beforeEach, describe, expect, it } from "vitest"+import { sql, sqlQuery, sqlRun } from "@alook/test-utils"++const OWNER_ID = "e2e_backend_quota_owner"+const MACHINE_ID = "e2e_backend_quota_machine"+const SOURCE_EPOCH = "a".repeat(22)+const NOW = "2026-09-08T00:00:00.000Z"+const SUPPORTED_BACKENDS = ["claude", "codex", "grok"] as const++function insertQuota(agentBackendId: string): void {+ sqlRun(+ `INSERT INTO community_machine_backend_quota (+ machine_id, agent_backend_id, source_epoch, status, error_code,+ retryable, observed_at, updated_at+ ) VALUES (?, ?, ?, 'error', 'unavailable', 0, ?, ?)`,+ MACHINE_ID,+ agentBackendId,+ SOURCE_EPOCH,+ NOW,+ NOW,+ )+}++beforeEach(() => {+ sql("PRAGMA foreign_keys = ON")+ sqlRun(`DELETE FROM community_machine_backend_quota WHERE machine_id = ?`, MACHINE_ID)+ sqlRun(`DELETE FROM community_machine WHERE id = ?`, MACHINE_ID)+ sqlRun(`DELETE FROM user WHERE id = ?`, OWNER_ID)+ sqlRun(+ `INSERT INTO user (id, email, name) VALUES (?, ?, ?)`,+ OWNER_ID,+ `${OWNER_ID}@example.com`,+ "Backend Quota Owner",+ )+ sqlRun(+ `INSERT INTO community_machine (id, user_id, created_at, updated_at) VALUES (?, ?, ?, ?)`,+ MACHINE_ID,+ OWNER_ID,+ NOW,+ NOW,+ )+})++afterAll(() => {+ sqlRun(`DELETE FROM community_machine_backend_quota WHERE machine_id = ?`, MACHINE_ID)+ sqlRun(`DELETE FROM community_machine WHERE id = ?`, MACHINE_ID)+ sqlRun(`DELETE FROM user WHERE id = ?`, OWNER_ID)+})++describe("community_machine_backend_quota.agent_backend_id CHECK", () => {+ it.each(SUPPORTED_BACKENDS)("admits supported backend '%s'", (backend) => {+ expect(() => insertQuota(backend)).not.toThrow()+ expect(+ sqlQuery<{ agent_backend_id: string }>(+ `SELECT agent_backend_id FROM community_machine_backend_quota WHERE machine_id = ?`,+ MACHINE_ID,+ ),+ ).toEqual([{ agent_backend_id: backend }])+ })++ it("rejects an unsupported backend", () => {+ expect(() => insertQuota("unsupported")).toThrow(/CHECK constraint failed/i)+ })+})diff --git a/src/ws-do/src/ws-durable/machine-frames.test.ts b/src/ws-do/src/ws-durable/machine-frames.test.tsindex 8533f9083..2831d621b 100644--- a/src/ws-do/src/ws-durable/machine-frames.test.ts+++ b/src/ws-do/src/ws-durable/machine-frames.test.ts@@ -360,6 +360,56 @@ describe("WebSocketDurableObject", () => {expect(mockD1Batch).not.toHaveBeenCalled()})+ it("persists Claude, Codex, and Grok quotas from one ready frame", async () => {+ const { durable, store } = createDO()+ store.set("community-machine-identity", {+ userId: "u_1",+ machineId: "cm_1",+ credentialHash: "0".repeat(64),+ })+ mockUpsertMachineByMachineId.mockResolvedValue({+ machine: {+ id: "cm_1",+ availableRuntimes: [{ id: "claude" }, { id: "codex" }, { id: "grok" }],+ status: "online",+ },+ priorAvailableRuntimes: [],+ priorStatus: "offline",+ })+ const ws = createMockWebSocket()+ ws.serializeAttachment({+ type: "community-machine",+ machineId: "cm_1",+ userId: "u_1",+ authenticated: true,+ })++ await durable.webSocketMessage(ws as any, JSON.stringify({+ type: "ready",+ runtimeReport: [{ id: "claude" }, { id: "codex" }, { id: "grok" }],+ capabilities: ["control-heartbeat-v1"],+ runningAgents: [],+ providerQuotas: ["claude", "codex", "grok"].map((agentBackendId) => ({+ agentBackendId,+ observation: {+ status: "error",+ sourceEpoch: agentBackendId[0]!.toUpperCase().repeat(22),+ code: "network",+ retryable: true,+ },+ })),+ }))++ expect(mockD1Batch).toHaveBeenCalledOnce()+ const statements = mockD1Batch.mock.calls[0]![0] as Array<{ values: unknown[] }>+ expect(statements).toHaveLength(3)+ expect(statements.map((statement) => statement.values[1])).toEqual([+ "claude",+ "codex",+ "grok",+ ])+ })+it("continues core ready reconciliation when optional quota persistence fails", async () => {const { durable, store, storage } = createDO()store.set("community-machine-identity", {diff --git a/src/ws-do/src/ws-durable/machine-ready.ts b/src/ws-do/src/ws-durable/machine-ready.tsindex 1697bfc76..cef877372 100644--- a/src/ws-do/src/ws-durable/machine-ready.ts+++ b/src/ws-do/src/ws-durable/machine-ready.ts@@ -75,7 +75,7 @@ export async function handleReadyFrame(const raw = parsed as Record<string, unknown>const quotaParse = raw.providerQuotas === undefined? null- : ProviderQuotaSnapshotSchema.array().max(2).safeParse(raw.providerQuotas)+ : ProviderQuotaSnapshotSchema.array().max(3).safeParse(raw.providerQuotas)const quotaBackends = quotaParse?.success? new Set(quotaParse.data.map((snapshot) => snapshot.agentBackendId)): null