fix(grok): improve skills, plans, usage, and turn reliability (#8358)
Co-authored-by: Dara Adedeji <[email protected]> Co-authored-by: Ahmed Besic <[email protected]> Co-authored-by: Michael Brown <[email protected]> Co-authored-by: Lars Nieuwenhuis <[email protected]> Co-authored-by: Guilherme Barros <[email protected]> Co-authored-by: PC <pc@localhost> Co-authored-by: 1xpixi <[email protected]>
This commit is contained in:
33 files changed
+3860
-146
No files matched your search
@@ -5,21 +5,23 @@ import { useAppearancePreferences } from "../settings/appearance/AppearancePrefe
|
||||
* Series and table order. The chart stacks providers from the bottom in this
|
||||
* order, so it also fixes which band sits on top of the bars.
|
||||
*/
|
||||
export const PROVIDER_ORDER: readonly UsageProviderKind[] = ["codex", "claude"];
|
||||
export const PROVIDER_ORDER: readonly UsageProviderKind[] = ["codex", "claude", "grok"];
|
||||
|
||||
export const PROVIDER_LABEL: Record<UsageProviderKind, string> = {
|
||||
claude: "Claude Code",
|
||||
codex: "Codex",
|
||||
grok: "Grok Build",
|
||||
};
|
||||
|
||||
/**
|
||||
* Claude's brand orange holds in both themes; Codex is neutral and must flip
|
||||
* with the theme or its bars vanish against the matching background.
|
||||
* Claude's brand orange holds in both themes; Codex and Grok are neutrals and
|
||||
* must flip with the theme or their bars vanish against the matching background.
|
||||
*/
|
||||
export function useProviderColors(): Record<UsageProviderKind, string> {
|
||||
const { themeAppearance: scheme } = useAppearancePreferences();
|
||||
return {
|
||||
claude: "#d97757",
|
||||
codex: scheme === "dark" ? "#e6e6e6" : "#3c3c43",
|
||||
grok: scheme === "dark" ? "#a1a1aa" : "#52525b",
|
||||
};
|
||||
}
|
||||
@@ -19,7 +19,15 @@ const emitInterleavedAssistantToolCalls =
|
||||
const emitGenericToolPlaceholders = process.env.T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS === "1";
|
||||
const emitAskQuestion = process.env.T3_ACP_EMIT_ASK_QUESTION === "1";
|
||||
const emitXAiAskUserQuestion = process.env.T3_ACP_EMIT_XAI_ASK_USER_QUESTION === "1";
|
||||
const emitXAiExitPlanMode = process.env.T3_ACP_EMIT_XAI_EXIT_PLAN_MODE === "1";
|
||||
const emitXAiPlanMdWrite = process.env.T3_ACP_EMIT_XAI_PLAN_MD_WRITE === "1";
|
||||
const emitXAiPromptCompleteThenHang = process.env.T3_ACP_EMIT_XAI_PROMPT_COMPLETE_THEN_HANG === "1";
|
||||
const emitXAiRateLimitThenHang = process.env.T3_ACP_EMIT_XAI_RATE_LIMIT_THEN_HANG === "1";
|
||||
const emitXAiAskUserQuestionThenHang =
|
||||
process.env.T3_ACP_EMIT_XAI_ASK_USER_QUESTION_THEN_HANG === "1";
|
||||
const emitContentThenHang = process.env.T3_ACP_EMIT_CONTENT_THEN_HANG === "1";
|
||||
const emitPlanThenHang = process.env.T3_ACP_EMIT_PLAN_THEN_HANG === "1";
|
||||
const emitActiveToolThenHang = process.env.T3_ACP_EMIT_ACTIVE_TOOL_THEN_HANG === "1";
|
||||
const emitForeignSessionUpdates = process.env.T3_ACP_EMIT_FOREIGN_SESSION_UPDATES === "1";
|
||||
const hangPromptForever = process.env.T3_ACP_HANG_PROMPT_FOREVER === "1";
|
||||
const hangFirstPromptForever = process.env.T3_ACP_HANG_FIRST_PROMPT_FOREVER === "1";
|
||||
@@ -39,12 +47,19 @@ const failPrompt = process.env.T3_ACP_FAIL_PROMPT === "1";
|
||||
const failSetConfigOption = process.env.T3_ACP_FAIL_SET_CONFIG_OPTION === "1";
|
||||
const exitOnSetConfigOption = process.env.T3_ACP_EXIT_ON_SET_CONFIG_OPTION === "1";
|
||||
const promptResponseText = process.env.T3_ACP_PROMPT_RESPONSE_TEXT;
|
||||
const initialGrokReasoningEffort =
|
||||
process.env.T3_ACP_INITIAL_GROK_REASONING_EFFORT?.trim() || undefined;
|
||||
const promptDelayMs = Number(process.env.T3_ACP_PROMPT_DELAY_MS ?? "0");
|
||||
const permissionOptionIds = {
|
||||
allowOnce: process.env.T3_ACP_ALLOW_ONCE_OPTION_ID ?? "allow-once",
|
||||
allowAlways: process.env.T3_ACP_ALLOW_ALWAYS_OPTION_ID ?? "allow-always",
|
||||
rejectOnce: process.env.T3_ACP_REJECT_ONCE_OPTION_ID ?? "reject-once",
|
||||
};
|
||||
const omitAllowAlways = process.env.T3_ACP_OMIT_ALLOW_ALWAYS === "1";
|
||||
const permissionRequestCount = Math.max(
|
||||
1,
|
||||
Number(process.env.T3_ACP_PERMISSION_REQUEST_COUNT ?? "1") || 1,
|
||||
);
|
||||
const sessionId = "mock-session-1";
|
||||
|
||||
let currentModeId = "ask";
|
||||
@@ -279,7 +294,13 @@ function modeState(): AcpSchema.SessionModeState {
|
||||
}
|
||||
|
||||
const grokAcpModels: ReadonlyArray<AcpSchema.ModelInfo> = [
|
||||
{ modelId: "grok-build", name: "Grok Build" },
|
||||
{
|
||||
modelId: "grok-build",
|
||||
name: "Grok Build",
|
||||
...(initialGrokReasoningEffort
|
||||
? { _meta: { reasoningEffort: initialGrokReasoningEffort } }
|
||||
: {}),
|
||||
},
|
||||
{ modelId: "grok-mock-alt", name: "Grok Mock Alt" },
|
||||
];
|
||||
|
||||
@@ -522,6 +543,68 @@ const program = Effect.gen(function* () {
|
||||
return yield* Effect.never;
|
||||
}
|
||||
|
||||
if (emitXAiRateLimitThenHang) {
|
||||
writeJsonRpcNotification("_x.ai/session/prompt_complete", {
|
||||
sessionId: requestedSessionId,
|
||||
promptId: promptIdFromRequestMeta(request) ?? "mock-xai-rate-limit-prompt-1",
|
||||
stopReason: "rate_limit",
|
||||
agentResult: null,
|
||||
});
|
||||
return yield* Effect.never;
|
||||
}
|
||||
|
||||
if (emitContentThenHang) {
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "partial before stall" },
|
||||
},
|
||||
});
|
||||
return yield* Effect.never;
|
||||
}
|
||||
|
||||
if (emitPlanThenHang) {
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "plan",
|
||||
entries: [
|
||||
{
|
||||
content: "Wait for more ACP progress",
|
||||
priority: "high",
|
||||
status: "in_progress",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
return yield* Effect.never;
|
||||
}
|
||||
|
||||
if (emitActiveToolThenHang) {
|
||||
const toolCallId = "tool-call-long-running-1";
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId,
|
||||
title: "Long-running tool",
|
||||
kind: "execute",
|
||||
status: "pending",
|
||||
rawInput: { command: ["long-running-tool"] },
|
||||
},
|
||||
});
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId,
|
||||
status: "in_progress",
|
||||
},
|
||||
});
|
||||
return yield* Effect.never;
|
||||
}
|
||||
|
||||
if (emitXAiPromptCompleteThenHang) {
|
||||
writeJsonRpcNotification("session/update", {
|
||||
sessionId: requestedSessionId,
|
||||
@@ -656,37 +739,58 @@ const program = Effect.gen(function* () {
|
||||
},
|
||||
});
|
||||
|
||||
const permission = yield* agent.client.requestPermission({
|
||||
sessionId: requestedSessionId,
|
||||
toolCall: {
|
||||
toolCallId,
|
||||
title: "`cat server/package.json`",
|
||||
kind: "execute",
|
||||
status: "pending",
|
||||
content: [
|
||||
{
|
||||
type: "content",
|
||||
content: {
|
||||
type: "text",
|
||||
text: "Not in allowlist: cat server/package.json",
|
||||
const permissionOptions: Array<AcpSchema.PermissionOption> = [
|
||||
{ optionId: permissionOptionIds.allowOnce, name: "Allow once", kind: "allow_once" },
|
||||
...(omitAllowAlways
|
||||
? []
|
||||
: [
|
||||
{
|
||||
optionId: permissionOptionIds.allowAlways,
|
||||
name: "Allow always",
|
||||
kind: "allow_always" as const,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
options: [
|
||||
{ optionId: permissionOptionIds.allowOnce, name: "Allow once", kind: "allow_once" },
|
||||
{
|
||||
optionId: permissionOptionIds.allowAlways,
|
||||
name: "Allow always",
|
||||
kind: "allow_always",
|
||||
},
|
||||
{ optionId: permissionOptionIds.rejectOnce, name: "Reject", kind: "reject_once" },
|
||||
],
|
||||
});
|
||||
]),
|
||||
{ optionId: permissionOptionIds.rejectOnce, name: "Reject", kind: "reject_once" },
|
||||
];
|
||||
|
||||
const cancelled =
|
||||
cancelledSessions.delete(requestedSessionId) ||
|
||||
permission.outcome.outcome === "cancelled";
|
||||
let cancelled = cancelledSessions.delete(requestedSessionId);
|
||||
for (let index = 0; index < permissionRequestCount; index++) {
|
||||
const command =
|
||||
index > 0
|
||||
? (process.env.T3_ACP_SECOND_PERMISSION_COMMAND ?? "cat server/package.json")
|
||||
: "cat server/package.json";
|
||||
const permission = yield* agent.client.requestPermission({
|
||||
sessionId: requestedSessionId,
|
||||
toolCall: {
|
||||
toolCallId: index === 0 ? toolCallId : `${toolCallId}-${index + 1}`,
|
||||
title: process.env.T3_ACP_PERMISSION_TITLE ?? `\`${command}\``,
|
||||
kind: "execute",
|
||||
status: "pending",
|
||||
rawInput: {
|
||||
variant: "Bash",
|
||||
command,
|
||||
description: index === 0 ? "Read package metadata" : "Read it again",
|
||||
},
|
||||
content: [
|
||||
{
|
||||
type: "content",
|
||||
content: {
|
||||
type: "text",
|
||||
text: `Not in allowlist: ${command}`,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
options: permissionOptions,
|
||||
});
|
||||
cancelled =
|
||||
cancelled ||
|
||||
cancelledSessions.delete(requestedSessionId) ||
|
||||
permission.outcome.outcome === "cancelled";
|
||||
if (cancelled) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
@@ -773,7 +877,7 @@ const program = Effect.gen(function* () {
|
||||
return { stopReason: "end_turn" };
|
||||
}
|
||||
|
||||
if (emitXAiAskUserQuestion) {
|
||||
if (emitXAiAskUserQuestion || emitXAiAskUserQuestionThenHang) {
|
||||
const result = yield* agent.client.extRequest("_x.ai/ask_user_question", {
|
||||
method: "x.ai/ask_user_question",
|
||||
params: {
|
||||
@@ -807,6 +911,84 @@ const program = Effect.gen(function* () {
|
||||
throw new Error("Expected accepted _x.ai/ask_user_question response answers.");
|
||||
}
|
||||
|
||||
if (emitXAiAskUserQuestionThenHang) {
|
||||
return yield* Effect.never;
|
||||
}
|
||||
|
||||
return { stopReason: "end_turn" };
|
||||
}
|
||||
|
||||
if (emitXAiPlanMdWrite) {
|
||||
// Match Grok's real session layout so isGrokPlanMarkdownPath accepts it.
|
||||
const planRoot = process.env.T3_ACP_PLAN_ROOT ?? "/tmp/mock-home/.grok";
|
||||
const planPath = `${planRoot}/sessions/${requestedSessionId}/plan.md`;
|
||||
const planBody = "# Mock plan\n\n- Write the feature\n- Add a test\n- Ship it\n";
|
||||
// enter_plan_mode first so the adapter arms planModeActive.
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "enter-plan-mode-1",
|
||||
title: "enter_plan_mode",
|
||||
kind: "other",
|
||||
status: "completed",
|
||||
rawInput: { variant: "EnterPlanMode" },
|
||||
},
|
||||
});
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "plan-md-write-1",
|
||||
title: "write",
|
||||
kind: "edit",
|
||||
status: "pending",
|
||||
rawInput: { file_path: planPath, content: planBody },
|
||||
},
|
||||
});
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId: "plan-md-write-1",
|
||||
kind: "edit",
|
||||
status: "completed",
|
||||
title: `Write \`${planPath}\``,
|
||||
rawInput: { file_path: planPath, content: planBody },
|
||||
content: [
|
||||
{
|
||||
type: "diff",
|
||||
path: planPath,
|
||||
oldText: "",
|
||||
newText: planBody,
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
return { stopReason: "end_turn" };
|
||||
}
|
||||
|
||||
if (emitXAiExitPlanMode) {
|
||||
const result = yield* agent.client.extRequest("_x.ai/exit_plan_mode", {
|
||||
method: "x.ai/exit_plan_mode",
|
||||
params: {
|
||||
sessionId: requestedSessionId,
|
||||
toolCallId: "exit-plan-mode-tool-call-1",
|
||||
planContent: "# Exit plan\n\n- Step one\n- Step two\n",
|
||||
},
|
||||
});
|
||||
if (typeof result !== "object" || result === null || !("outcome" in result)) {
|
||||
throw new Error("Expected _x.ai/exit_plan_mode response outcome.");
|
||||
}
|
||||
if (
|
||||
result.outcome !== "abandoned" &&
|
||||
result.outcome !== "approved" &&
|
||||
result.outcome !== "request_changes"
|
||||
) {
|
||||
throw new Error(
|
||||
`Expected exit_plan_mode outcome abandoned|approved|request_changes, got ${String(result.outcome)}`,
|
||||
);
|
||||
}
|
||||
return { stopReason: "end_turn" };
|
||||
}
|
||||
|
||||
|
||||
@@ -88,6 +88,7 @@ export const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv> = {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const { cwd } = yield* ServerConfig;
|
||||
const eventLoggers = yield* ProviderEventLoggers;
|
||||
const processEnv = mergeProviderInstanceEnvironment(environment);
|
||||
const continuationIdentity = defaultProviderContinuationIdentity({
|
||||
@@ -113,7 +114,7 @@ export const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv> = {
|
||||
});
|
||||
const textGeneration = yield* makeGrokTextGeneration(effectiveConfig, processEnv);
|
||||
|
||||
const checkProvider = checkGrokProviderStatus(effectiveConfig, processEnv).pipe(
|
||||
const checkProvider = checkGrokProviderStatus(effectiveConfig, processEnv, cwd).pipe(
|
||||
Effect.map(stampIdentity),
|
||||
Effect.provideService(Crypto.Crypto, crypto),
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Sink from "effect/Sink";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { discoverGrokSkills, parseGrokInspectSkills } from "./GrokSkills.ts";
|
||||
|
||||
const inspectPayload = (skills: ReadonlyArray<unknown>) => JSON.stringify({ skills });
|
||||
|
||||
describe("parseGrokInspectSkills", () => {
|
||||
it("maps inspect entries onto provider skills, sorted by name", () => {
|
||||
const skills = parseGrokInspectSkills(
|
||||
inspectPayload([
|
||||
{
|
||||
name: "writing-docs",
|
||||
description: "Write user docs.",
|
||||
source: { type: "user", path: "/home/dev/.grok/skills/writing-docs/SKILL.md" },
|
||||
userInvocable: true,
|
||||
},
|
||||
{
|
||||
name: "deploy",
|
||||
description: "Deploy the app.",
|
||||
source: {
|
||||
type: "plugin",
|
||||
path: "/home/dev/.grok/installed-plugins/pkg/plug/skills/deploy/SKILL.md",
|
||||
},
|
||||
userInvocable: true,
|
||||
},
|
||||
]),
|
||||
);
|
||||
|
||||
expect(skills).toEqual([
|
||||
{
|
||||
name: "deploy",
|
||||
description: "Deploy the app.",
|
||||
path: "/home/dev/.grok/installed-plugins/pkg/plug/skills/deploy/SKILL.md",
|
||||
scope: "plugin",
|
||||
enabled: true,
|
||||
},
|
||||
{
|
||||
name: "writing-docs",
|
||||
description: "Write user docs.",
|
||||
path: "/home/dev/.grok/skills/writing-docs/SKILL.md",
|
||||
scope: "user",
|
||||
enabled: true,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("disables skills the CLI marks as not user-invocable", () => {
|
||||
const skills = parseGrokInspectSkills(
|
||||
inspectPayload([
|
||||
{
|
||||
name: "internal-helper",
|
||||
source: { type: "bundled", path: "/opt/grok/bundled/skills/internal-helper/SKILL.md" },
|
||||
userInvocable: false,
|
||||
},
|
||||
]),
|
||||
);
|
||||
|
||||
expect(skills).toEqual([
|
||||
{
|
||||
name: "internal-helper",
|
||||
path: "/opt/grok/bundled/skills/internal-helper/SKILL.md",
|
||||
scope: "bundled",
|
||||
enabled: false,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("skips entries without a name or a filesystem path", () => {
|
||||
const skills = parseGrokInspectSkills(
|
||||
inspectPayload([
|
||||
{ name: " ", source: { type: "user", path: "/tmp/skills/a/SKILL.md" } },
|
||||
{ name: "no-path", source: { type: "user" } },
|
||||
{ name: "no-source" },
|
||||
"not-an-object",
|
||||
{ name: "kept", source: { type: "project", path: "/repo/.grok/skills/kept/SKILL.md" } },
|
||||
]),
|
||||
);
|
||||
|
||||
expect(skills.map((skill) => skill.name)).toEqual(["kept"]);
|
||||
});
|
||||
|
||||
it("returns an empty list for malformed or unexpected output", () => {
|
||||
expect(parseGrokInspectSkills("not json")).toEqual([]);
|
||||
expect(parseGrokInspectSkills("null")).toEqual([]);
|
||||
expect(parseGrokInspectSkills(JSON.stringify({ skills: "nope" }))).toEqual([]);
|
||||
expect(parseGrokInspectSkills(JSON.stringify({}))).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("discoverGrokSkills", () => {
|
||||
it.effect("spawns the inspect probe in the configured cwd", () => {
|
||||
const spawnCwds: Array<string | undefined> = [];
|
||||
const spawner = ChildProcessSpawner.make((command) => {
|
||||
spawnCwds.push(command._tag === "StandardCommand" ? command.options.cwd : undefined);
|
||||
return Effect.succeed(
|
||||
ChildProcessSpawner.makeHandle({
|
||||
pid: ChildProcessSpawner.ProcessId(1),
|
||||
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
|
||||
isRunning: Effect.succeed(false),
|
||||
kill: () => Effect.void,
|
||||
unref: Effect.succeed(Effect.void),
|
||||
stdin: Sink.drain,
|
||||
stdout: Stream.encodeText(
|
||||
Stream.make(
|
||||
inspectPayload([
|
||||
{
|
||||
name: "kept",
|
||||
source: { type: "project", path: "/workspaces/demo/.grok/skills/kept/SKILL.md" },
|
||||
},
|
||||
]),
|
||||
),
|
||||
),
|
||||
stderr: Stream.empty,
|
||||
all: Stream.empty,
|
||||
getInputFd: () => Sink.drain,
|
||||
getOutputFd: () => Stream.empty,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const skills = yield* discoverGrokSkills({ binaryPath: "grok" }, {}, "/workspaces/demo").pipe(
|
||||
Effect.provide(Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner)),
|
||||
);
|
||||
|
||||
expect(spawnCwds).toEqual(["/workspaces/demo"]);
|
||||
expect(skills.map((skill) => skill.name)).toEqual(["kept"]);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,119 @@
|
||||
/**
|
||||
* GrokSkills — skill discovery for the `$` picker via `grok inspect --json`.
|
||||
*
|
||||
* Unlike Claude Code, the Grok CLI reports its full skill catalog itself:
|
||||
* `grok inspect --json` returns `skills[]` with `name`, `description`,
|
||||
* `source.type` (`user` / `project` / `bundled` / `plugin`), `source.path`
|
||||
* (the absolute `SKILL.md` path), and `userInvocable`. Asking the CLI beats
|
||||
* scanning the filesystem because the catalog honors Grok's own skill config
|
||||
* (ignore lists, disabled skills) and includes plugin skills, which live
|
||||
* three levels deep under `~/.grok/installed-plugins/` where a flat scan
|
||||
* cannot see them. This mirrors how the Codex app-server reports skills over
|
||||
* `skills/list`. Discovery is best-effort: an older CLI without `inspect`,
|
||||
* a timeout, or malformed output yields an empty list, never a degraded
|
||||
* provider snapshot.
|
||||
*
|
||||
* @module provider/Drivers/GrokSkills
|
||||
*/
|
||||
import type { GrokSettings, ServerProviderSkill } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Result from "effect/Result";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { resolveSpawnCommand } from "@t3tools/shared/shell";
|
||||
|
||||
import { spawnAndCollect } from "../providerSnapshot.ts";
|
||||
|
||||
const GROK_SKILLS_PROBE_TIMEOUT_MS = 4_000;
|
||||
|
||||
/**
|
||||
* Map `grok inspect --json` output onto provider skills. Entries without a
|
||||
* name or a filesystem path are skipped; `userInvocable: false` skills are
|
||||
* kept but disabled so pickers that filter on `enabled` hide them.
|
||||
*/
|
||||
export function parseGrokInspectSkills(stdout: string): ReadonlyArray<ServerProviderSkill> {
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(stdout);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
if (typeof parsed !== "object" || parsed === null) {
|
||||
return [];
|
||||
}
|
||||
const entries = (parsed as Record<string, unknown>).skills;
|
||||
if (!Array.isArray(entries)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const skillsByName = new Map<string, ServerProviderSkill>();
|
||||
for (const entry of entries) {
|
||||
if (typeof entry !== "object" || entry === null) {
|
||||
continue;
|
||||
}
|
||||
const record = entry as Record<string, unknown>;
|
||||
const name = typeof record.name === "string" ? record.name.trim() : "";
|
||||
const source =
|
||||
typeof record.source === "object" && record.source !== null
|
||||
? (record.source as Record<string, unknown>)
|
||||
: undefined;
|
||||
const path = typeof source?.path === "string" ? source.path.trim() : "";
|
||||
if (!name || !path) {
|
||||
continue;
|
||||
}
|
||||
const scope = typeof source?.type === "string" ? source.type.trim() : "";
|
||||
const description = typeof record.description === "string" ? record.description.trim() : "";
|
||||
skillsByName.set(name, {
|
||||
name,
|
||||
path,
|
||||
enabled: record.userInvocable !== false,
|
||||
...(scope ? { scope } : {}),
|
||||
...(description ? { description } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
return [...skillsByName.values()].sort((left, right) => left.name.localeCompare(right.name));
|
||||
}
|
||||
|
||||
/**
|
||||
* Run `grok inspect --json` and map the reported catalog onto provider
|
||||
* skills. Never fails: any spawn error, non-zero exit, or timeout resolves
|
||||
* to an empty list.
|
||||
*/
|
||||
export const discoverGrokSkills = Effect.fn("discoverGrokSkills")(function* (
|
||||
grokSettings: Pick<GrokSettings, "binaryPath">,
|
||||
environment: NodeJS.ProcessEnv = process.env,
|
||||
cwd?: string,
|
||||
): Effect.fn.Return<
|
||||
ReadonlyArray<ServerProviderSkill>,
|
||||
never,
|
||||
ChildProcessSpawner.ChildProcessSpawner
|
||||
> {
|
||||
const command = grokSettings.binaryPath || "grok";
|
||||
const inspectResult = yield* Effect.gen(function* () {
|
||||
const spawnCommand = yield* resolveSpawnCommand(command, ["inspect", "--json"], {
|
||||
env: environment,
|
||||
});
|
||||
return yield* spawnAndCollect(
|
||||
command,
|
||||
ChildProcess.make(spawnCommand.command, spawnCommand.args, {
|
||||
...(cwd ? { cwd } : {}),
|
||||
env: environment,
|
||||
shell: spawnCommand.shell,
|
||||
}),
|
||||
);
|
||||
}).pipe(Effect.timeoutOption(GROK_SKILLS_PROBE_TIMEOUT_MS), Effect.result);
|
||||
|
||||
if (Result.isFailure(inspectResult) || Option.isNone(inspectResult.success)) {
|
||||
yield* Effect.logDebug("Grok skill discovery failed; continuing without skills.");
|
||||
return [];
|
||||
}
|
||||
const output = inspectResult.success.value;
|
||||
if (output.code !== 0) {
|
||||
yield* Effect.logDebug("Grok skill discovery exited non-zero; continuing without skills.", {
|
||||
exitCode: output.code,
|
||||
});
|
||||
return [];
|
||||
}
|
||||
return parseGrokInspectSkills(output.stdout);
|
||||
});
|
||||
@@ -26,7 +26,13 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { grokPromptSettlementBelongsToContext, makeGrokAdapter } from "./GrokAdapter.ts";
|
||||
import {
|
||||
grokPromptSettlementBelongsToContext,
|
||||
isGrokEnterPlanModeToolCall,
|
||||
makeGrokAdapter,
|
||||
nextGrokPlanModeActive,
|
||||
selectGrokPermissionOptionId,
|
||||
} from "./GrokAdapter.ts";
|
||||
const decodeGrokSettings = Schema.decodeSync(GrokSettings);
|
||||
|
||||
const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
|
||||
@@ -89,6 +95,90 @@ const grokAdapterTestLayer = ServerConfig.layerTest(process.cwd(), {
|
||||
const makeTestAdapter = (binaryPath: string, options?: Parameters<typeof makeGrokAdapter>[1]) =>
|
||||
makeGrokAdapter(decodeGrokSettings({ binaryPath }), options).pipe(Effect.orDie);
|
||||
|
||||
it("detects enter_plan_mode tool calls from title and rawInput", () => {
|
||||
assert.isTrue(
|
||||
isGrokEnterPlanModeToolCall({
|
||||
title: "enter_plan_mode",
|
||||
data: { toolCallId: "1" },
|
||||
}),
|
||||
);
|
||||
assert.isTrue(
|
||||
isGrokEnterPlanModeToolCall({
|
||||
title: "Plan mode entered",
|
||||
data: { toolCallId: "1", rawInput: { variant: "EnterPlanMode" } },
|
||||
}),
|
||||
);
|
||||
assert.isFalse(
|
||||
isGrokEnterPlanModeToolCall({
|
||||
title: "write",
|
||||
data: { toolCallId: "1", rawInput: { file_path: "/tmp/x", content: "y" } },
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("only sets planModeActive after a successful enter_plan_mode", () => {
|
||||
const enter = {
|
||||
title: "enter_plan_mode",
|
||||
data: { toolCallId: "1" },
|
||||
};
|
||||
assert.isFalse(nextGrokPlanModeActive(false, { ...enter, status: "pending" }));
|
||||
assert.isTrue(nextGrokPlanModeActive(false, { ...enter, status: "inProgress" }));
|
||||
assert.isTrue(nextGrokPlanModeActive(false, { ...enter, status: "completed" }));
|
||||
assert.isFalse(nextGrokPlanModeActive(false, { ...enter, status: "failed" }));
|
||||
assert.isFalse(nextGrokPlanModeActive(true, { ...enter, status: "failed" }));
|
||||
assert.isTrue(
|
||||
nextGrokPlanModeActive(true, {
|
||||
title: "write",
|
||||
status: "completed",
|
||||
data: { toolCallId: "2" },
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
function grokPermissionRequest(
|
||||
options: ReadonlyArray<{
|
||||
readonly optionId: string;
|
||||
readonly kind: "allow_once" | "allow_always" | "reject_once" | "reject_always";
|
||||
}>,
|
||||
) {
|
||||
return {
|
||||
sessionId: "mock-session-1",
|
||||
toolCall: {
|
||||
toolCallId: "tool-call-1",
|
||||
title: "cat package.json",
|
||||
kind: "execute" as const,
|
||||
status: "pending" as const,
|
||||
},
|
||||
options: options.map((option) => ({
|
||||
optionId: option.optionId,
|
||||
name: option.kind,
|
||||
kind: option.kind,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
it("maps Always allow to allow_once when Grok omits allow_always", () => {
|
||||
const request = grokPermissionRequest([
|
||||
{ optionId: "allow-once", kind: "allow_once" },
|
||||
{ optionId: "reject-once", kind: "reject_once" },
|
||||
]);
|
||||
|
||||
assert.equal(selectGrokPermissionOptionId(request, "acceptForSession"), "allow-once");
|
||||
assert.equal(selectGrokPermissionOptionId(request, "accept"), "allow-once");
|
||||
assert.equal(selectGrokPermissionOptionId(request, "decline"), "reject-once");
|
||||
});
|
||||
|
||||
it("prefers allow_always when Grok offers it", () => {
|
||||
const request = grokPermissionRequest([
|
||||
{ optionId: "allow-once", kind: "allow_once" },
|
||||
{ optionId: "allow-always", kind: "allow_always" },
|
||||
{ optionId: "reject-once", kind: "reject_once" },
|
||||
]);
|
||||
|
||||
assert.equal(selectGrokPermissionOptionId(request, "acceptForSession"), "allow-always");
|
||||
assert.equal(selectGrokPermissionOptionId(request, "accept"), "allow-once");
|
||||
});
|
||||
|
||||
it("requires a settlement to match the live Grok turn", () => {
|
||||
const staleTurnId = TurnId.make("stale-turn");
|
||||
const replacementTurnId = TurnId.make("replacement-turn");
|
||||
@@ -418,6 +508,362 @@ it.layer(grokAdapterTestLayer)("GrokAdapterLive", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not time out a Grok turn before ACP emits progress", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-watchdog-silent-turn");
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeMockGrokWrapper({
|
||||
T3_ACP_HANG_PROMPT_FOREVER: "1",
|
||||
}),
|
||||
);
|
||||
const adapter = yield* makeTestAdapter(wrapperPath, {
|
||||
turnInactivityTimeoutMs: 1_000,
|
||||
});
|
||||
const runtimeEvents: ProviderRuntimeEvent[] = [];
|
||||
const turnStarted = yield* Deferred.make<void>();
|
||||
const turnCompleted =
|
||||
yield* Deferred.make<Extract<ProviderRuntimeEvent, { type: "turn.completed" }>>();
|
||||
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
Effect.gen(function* () {
|
||||
if (String(event.threadId) !== String(threadId)) {
|
||||
return;
|
||||
}
|
||||
runtimeEvents.push(event);
|
||||
if (event.type === "turn.started") {
|
||||
yield* Deferred.succeed(turnStarted, undefined).pipe(Effect.ignore);
|
||||
}
|
||||
if (event.type === "turn.completed") {
|
||||
yield* Deferred.succeed(turnCompleted, event).pipe(Effect.ignore);
|
||||
}
|
||||
}),
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const sendTurnFiber = yield* adapter
|
||||
.sendTurn({ threadId, input: "silence forever", attachments: [] })
|
||||
.pipe(Effect.forkChild);
|
||||
yield* Deferred.await(turnStarted);
|
||||
|
||||
yield* TestClock.adjust("5 seconds");
|
||||
yield* Effect.yieldNow;
|
||||
const steerSendTurnFiber = yield* adapter
|
||||
.sendTurn({ threadId, input: "keep reasoning", attachments: [] })
|
||||
.pipe(Effect.forkChild);
|
||||
for (let yieldAttempt = 0; yieldAttempt < 12; yieldAttempt += 1) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
yield* TestClock.adjust("5 seconds");
|
||||
yield* Effect.yieldNow;
|
||||
assert.lengthOf(
|
||||
runtimeEvents.filter(
|
||||
(event) => event.type === "turn.completed" && String(event.threadId) === String(threadId),
|
||||
),
|
||||
0,
|
||||
);
|
||||
|
||||
yield* adapter.interruptTurn(threadId);
|
||||
const completed = yield* Deferred.await(turnCompleted).pipe(
|
||||
Effect.timeout("2 seconds"),
|
||||
TestClock.withLive,
|
||||
);
|
||||
yield* Fiber.join(sendTurnFiber);
|
||||
yield* Fiber.interrupt(steerSendTurnFiber);
|
||||
|
||||
assert.equal(completed.payload.state, "cancelled");
|
||||
const session = (yield* adapter.listSessions()).find(
|
||||
(candidate) => candidate.threadId === threadId,
|
||||
);
|
||||
assert.equal(session?.status, "ready");
|
||||
assert.isUndefined(session?.activeTurnId);
|
||||
|
||||
yield* Fiber.interrupt(runtimeEventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("fails a Grok turn that stalls after ACP content begins", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-watchdog-content-stall");
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeMockGrokWrapper({
|
||||
T3_ACP_EMIT_CONTENT_THEN_HANG: "1",
|
||||
}),
|
||||
);
|
||||
const adapter = yield* makeTestAdapter(wrapperPath, {
|
||||
turnInactivityTimeoutMs: 1_000,
|
||||
});
|
||||
const contentDelta = yield* Deferred.make<void>();
|
||||
const turnCompleted =
|
||||
yield* Deferred.make<Extract<ProviderRuntimeEvent, { type: "turn.completed" }>>();
|
||||
const runtimeEvents: ProviderRuntimeEvent[] = [];
|
||||
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
Effect.gen(function* () {
|
||||
if (String(event.threadId) !== String(threadId)) {
|
||||
return;
|
||||
}
|
||||
runtimeEvents.push(event);
|
||||
if (event.type === "content.delta") {
|
||||
yield* Deferred.succeed(contentDelta, undefined).pipe(Effect.ignore);
|
||||
}
|
||||
if (event.type === "turn.completed") {
|
||||
yield* Deferred.succeed(turnCompleted, event).pipe(Effect.ignore);
|
||||
}
|
||||
}),
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
const sendTurnFiber = yield* adapter
|
||||
.sendTurn({ threadId, input: "start then stall", attachments: [] })
|
||||
.pipe(Effect.forkChild);
|
||||
yield* Deferred.await(contentDelta).pipe(Effect.timeout("2 seconds"), TestClock.withLive);
|
||||
|
||||
yield* TestClock.adjust("999 millis");
|
||||
yield* Effect.yieldNow;
|
||||
assert.lengthOf(
|
||||
runtimeEvents.filter(
|
||||
(event) => event.type === "turn.completed" && String(event.threadId) === String(threadId),
|
||||
),
|
||||
0,
|
||||
);
|
||||
|
||||
yield* TestClock.adjust("1 millis");
|
||||
for (let yieldAttempt = 0; yieldAttempt < 4; yieldAttempt += 1) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
const completed = yield* Deferred.await(turnCompleted).pipe(
|
||||
Effect.timeout("2 seconds"),
|
||||
TestClock.withLive,
|
||||
);
|
||||
yield* Fiber.join(sendTurnFiber);
|
||||
|
||||
assert.equal(completed.payload.state, "failed");
|
||||
assert.equal(
|
||||
runtimeEvents.filter(
|
||||
(event) => event.type === "turn.completed" && String(event.threadId) === String(threadId),
|
||||
).length,
|
||||
1,
|
||||
);
|
||||
|
||||
yield* Fiber.interrupt(runtimeEventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("refreshes Grok liveness when a turn is steered", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-watchdog-steer");
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeMockGrokWrapper({
|
||||
T3_ACP_EMIT_CONTENT_THEN_HANG: "1",
|
||||
}),
|
||||
);
|
||||
const adapter = yield* makeTestAdapter(wrapperPath, {
|
||||
turnInactivityTimeoutMs: 1_000,
|
||||
});
|
||||
const contentDelta = yield* Deferred.make<void>();
|
||||
const turnCompleted =
|
||||
yield* Deferred.make<Extract<ProviderRuntimeEvent, { type: "turn.completed" }>>();
|
||||
const runtimeEvents: ProviderRuntimeEvent[] = [];
|
||||
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
Effect.gen(function* () {
|
||||
if (String(event.threadId) !== String(threadId)) {
|
||||
return;
|
||||
}
|
||||
runtimeEvents.push(event);
|
||||
if (event.type === "content.delta") {
|
||||
yield* Deferred.succeed(contentDelta, undefined).pipe(Effect.ignore);
|
||||
}
|
||||
if (event.type === "turn.completed") {
|
||||
yield* Deferred.succeed(turnCompleted, event).pipe(Effect.ignore);
|
||||
}
|
||||
}),
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
const firstSendTurnFiber = yield* adapter
|
||||
.sendTurn({ threadId, input: "start then steer", attachments: [] })
|
||||
.pipe(Effect.forkChild);
|
||||
yield* Deferred.await(contentDelta).pipe(Effect.timeout("2 seconds"), TestClock.withLive);
|
||||
|
||||
yield* TestClock.adjust("999 millis");
|
||||
const steerSendTurnFiber = yield* adapter
|
||||
.sendTurn({ threadId, input: "continue working", attachments: [] })
|
||||
.pipe(Effect.forkChild);
|
||||
for (let yieldAttempt = 0; yieldAttempt < 12; yieldAttempt += 1) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
|
||||
yield* TestClock.adjust("1 millis");
|
||||
for (let yieldAttempt = 0; yieldAttempt < 4; yieldAttempt += 1) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
assert.lengthOf(
|
||||
runtimeEvents.filter(
|
||||
(event) => event.type === "turn.completed" && String(event.threadId) === String(threadId),
|
||||
),
|
||||
0,
|
||||
);
|
||||
|
||||
yield* Fiber.interrupt(steerSendTurnFiber);
|
||||
yield* adapter.interruptTurn(threadId);
|
||||
const completed = yield* Deferred.await(turnCompleted).pipe(
|
||||
Effect.timeout("2 seconds"),
|
||||
TestClock.withLive,
|
||||
);
|
||||
yield* Fiber.join(firstSendTurnFiber);
|
||||
assert.equal(completed.payload.state, "cancelled");
|
||||
|
||||
yield* Fiber.interrupt(runtimeEventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("refreshes Grok liveness when ACP updates its plan", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-watchdog-plan-stall");
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeMockGrokWrapper({
|
||||
T3_ACP_EMIT_PLAN_THEN_HANG: "1",
|
||||
}),
|
||||
);
|
||||
const adapter = yield* makeTestAdapter(wrapperPath, {
|
||||
turnInactivityTimeoutMs: 1_000,
|
||||
});
|
||||
const planUpdated = yield* Deferred.make<void>();
|
||||
const turnCompleted =
|
||||
yield* Deferred.make<Extract<ProviderRuntimeEvent, { type: "turn.completed" }>>();
|
||||
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
Effect.gen(function* () {
|
||||
if (String(event.threadId) !== String(threadId)) {
|
||||
return;
|
||||
}
|
||||
if (event.type === "turn.plan.updated") {
|
||||
yield* Deferred.succeed(planUpdated, undefined).pipe(Effect.ignore);
|
||||
}
|
||||
if (event.type === "turn.completed") {
|
||||
yield* Deferred.succeed(turnCompleted, event).pipe(Effect.ignore);
|
||||
}
|
||||
}),
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
const sendTurnFiber = yield* adapter
|
||||
.sendTurn({ threadId, input: "update plan then stall", attachments: [] })
|
||||
.pipe(Effect.forkChild);
|
||||
yield* Deferred.await(planUpdated).pipe(Effect.timeout("2 seconds"), TestClock.withLive);
|
||||
|
||||
yield* TestClock.adjust("1 second");
|
||||
for (let yieldAttempt = 0; yieldAttempt < 4; yieldAttempt += 1) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
const completed = yield* Deferred.await(turnCompleted).pipe(
|
||||
Effect.timeout("2 seconds"),
|
||||
TestClock.withLive,
|
||||
);
|
||||
yield* Fiber.join(sendTurnFiber);
|
||||
|
||||
assert.equal(completed.payload.state, "failed");
|
||||
yield* Fiber.interrupt(runtimeEventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("settles a stalled Grok turn after the active-tool deadline", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-watchdog-active-tool");
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeMockGrokWrapper({
|
||||
T3_ACP_EMIT_ACTIVE_TOOL_THEN_HANG: "1",
|
||||
}),
|
||||
);
|
||||
const adapter = yield* makeTestAdapter(wrapperPath, {
|
||||
turnInactivityTimeoutMs: 1_000,
|
||||
activeToolInactivityTimeoutMs: 5_000,
|
||||
});
|
||||
const activeTool = yield* Deferred.make<void>();
|
||||
const turnCompleted =
|
||||
yield* Deferred.make<Extract<ProviderRuntimeEvent, { type: "turn.completed" }>>();
|
||||
const runtimeEvents: ProviderRuntimeEvent[] = [];
|
||||
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
Effect.gen(function* () {
|
||||
if (String(event.threadId) !== String(threadId)) {
|
||||
return;
|
||||
}
|
||||
runtimeEvents.push(event);
|
||||
if (event.type === "item.updated") {
|
||||
yield* Deferred.succeed(activeTool, undefined).pipe(Effect.ignore);
|
||||
}
|
||||
if (event.type === "turn.completed") {
|
||||
yield* Deferred.succeed(turnCompleted, event).pipe(Effect.ignore);
|
||||
}
|
||||
}),
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
const sendTurnFiber = yield* adapter
|
||||
.sendTurn({ threadId, input: "run a long tool", attachments: [] })
|
||||
.pipe(Effect.forkChild);
|
||||
yield* Deferred.await(activeTool).pipe(Effect.timeout("2 seconds"), TestClock.withLive);
|
||||
for (let yieldAttempt = 0; yieldAttempt < 4; yieldAttempt += 1) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
|
||||
yield* TestClock.adjust("4999 millis");
|
||||
yield* Effect.yieldNow;
|
||||
assert.lengthOf(
|
||||
runtimeEvents.filter(
|
||||
(event) => event.type === "turn.completed" && String(event.threadId) === String(threadId),
|
||||
),
|
||||
0,
|
||||
);
|
||||
assert.equal(
|
||||
(yield* adapter.listSessions()).find((candidate) => candidate.threadId === threadId)
|
||||
?.status,
|
||||
"running",
|
||||
);
|
||||
|
||||
yield* TestClock.adjust("1 millis");
|
||||
for (let yieldAttempt = 0; yieldAttempt < 4; yieldAttempt += 1) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
const completed = yield* Deferred.await(turnCompleted).pipe(
|
||||
Effect.timeout("2 seconds"),
|
||||
TestClock.withLive,
|
||||
);
|
||||
yield* Fiber.join(sendTurnFiber);
|
||||
assert.equal(completed.payload.state, "failed");
|
||||
|
||||
yield* Fiber.interrupt(runtimeEventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("retains turn transcript when sendTurn is interrupted after prompt success", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-send-turn-interrupt-after-prompt");
|
||||
@@ -943,6 +1389,64 @@ it.layer(grokAdapterTestLayer)("GrokAdapterLive", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("surfaces Grok usage limits without clearing the selected model", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-usage-limit-error");
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeMockGrokWrapper({
|
||||
T3_ACP_EMIT_XAI_RATE_LIMIT_THEN_HANG: "1",
|
||||
}),
|
||||
);
|
||||
const adapter = yield* makeTestAdapter(wrapperPath);
|
||||
const runtimeEvents: ProviderRuntimeEvent[] = [];
|
||||
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
Effect.sync(() => {
|
||||
runtimeEvents.push(event);
|
||||
}),
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("grok"), model: "grok-build" },
|
||||
});
|
||||
|
||||
const error = yield* Effect.flip(
|
||||
adapter.sendTurn({
|
||||
threadId,
|
||||
input: "hit the usage limit",
|
||||
attachments: [],
|
||||
}),
|
||||
);
|
||||
const readySessions = yield* adapter.listSessions();
|
||||
const readySession = readySessions.find((session) => session.threadId === threadId);
|
||||
const terminalEvents = runtimeEvents.filter(
|
||||
(event) => event.type === "turn.completed" && event.threadId === threadId,
|
||||
);
|
||||
|
||||
assert.equal(error._tag, "ProviderAdapterRequestError");
|
||||
assert.include(error.message, "Grok usage limit reached. Try again later.");
|
||||
assert.equal(readySession?.status, "ready");
|
||||
assert.equal(readySession?.model, "grok-build");
|
||||
assert.isUndefined(readySession?.activeTurnId);
|
||||
assert.lengthOf(terminalEvents, 1);
|
||||
const [terminalEvent] = terminalEvents;
|
||||
assert.equal(terminalEvent?.type, "turn.completed");
|
||||
if (terminalEvent?.type === "turn.completed") {
|
||||
assert.equal(terminalEvent.payload.state, "failed");
|
||||
assert.include(
|
||||
terminalEvent.payload.errorMessage ?? "",
|
||||
"Grok usage limit reached. Try again later.",
|
||||
);
|
||||
}
|
||||
|
||||
yield* Fiber.interrupt(runtimeEventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("ignores replayed session/load updates when resuming a Grok session", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-load-replay-filter");
|
||||
@@ -1097,6 +1601,247 @@ it.layer(grokAdapterTestLayer)("GrokAdapterLive", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("captures xAI exit_plan_mode as a proposed plan and unblocks the turn", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-xai-exit-plan-mode");
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeMockGrokWrapper({ T3_ACP_EMIT_XAI_EXIT_PLAN_MODE: "1" }),
|
||||
);
|
||||
const adapter = yield* makeTestAdapter(wrapperPath);
|
||||
const proposed =
|
||||
yield* Deferred.make<Extract<ProviderRuntimeEvent, { type: "turn.proposed.completed" }>>();
|
||||
const turnCompleted = yield* Deferred.make<void>();
|
||||
|
||||
const eventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) => {
|
||||
if (String(event.threadId) !== String(threadId)) {
|
||||
return Effect.void;
|
||||
}
|
||||
if (event.type === "turn.proposed.completed") {
|
||||
return Deferred.succeed(proposed, event).pipe(Effect.ignore);
|
||||
}
|
||||
if (event.type === "turn.completed") {
|
||||
return Deferred.succeed(turnCompleted, undefined).pipe(Effect.ignore);
|
||||
}
|
||||
return Effect.void;
|
||||
}).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
yield* adapter.sendTurn({ threadId, input: "present the plan", attachments: [] });
|
||||
|
||||
const proposedEvent = yield* Deferred.await(proposed);
|
||||
assert.equal(proposedEvent.type, "turn.proposed.completed");
|
||||
assert.equal(proposedEvent.payload.planMarkdown, "# Exit plan\n\n- Step one\n- Step two");
|
||||
assert.equal(proposedEvent.raw?.method, "_x.ai/exit_plan_mode");
|
||||
yield* Deferred.await(turnCompleted);
|
||||
|
||||
yield* Fiber.interrupt(eventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("surfaces plan.md writes as a proposed plan while plan mode is active", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-xai-plan-md-write");
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeMockGrokWrapper({ T3_ACP_EMIT_XAI_PLAN_MD_WRITE: "1" }),
|
||||
);
|
||||
const adapter = yield* makeTestAdapter(wrapperPath);
|
||||
const proposed =
|
||||
yield* Deferred.make<Extract<ProviderRuntimeEvent, { type: "turn.proposed.completed" }>>();
|
||||
|
||||
const eventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) => {
|
||||
if (String(event.threadId) !== String(threadId)) {
|
||||
return Effect.void;
|
||||
}
|
||||
if (event.type === "turn.proposed.completed") {
|
||||
return Deferred.succeed(proposed, event).pipe(Effect.ignore);
|
||||
}
|
||||
return Effect.void;
|
||||
}).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
yield* adapter.sendTurn({ threadId, input: "write the plan", attachments: [] });
|
||||
|
||||
const proposedEvent = yield* Deferred.await(proposed);
|
||||
assert.equal(
|
||||
proposedEvent.payload.planMarkdown,
|
||||
"# Mock plan\n\n- Write the feature\n- Add a test\n- Ship it",
|
||||
);
|
||||
assert.equal(proposedEvent.raw?.method, "session/update");
|
||||
|
||||
yield* Fiber.interrupt(eventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps a Grok turn running when Always allow has no allow_always option", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-always-allow-without-allow-always");
|
||||
const tempDir = yield* Effect.promise(() =>
|
||||
NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "grok-acp-")),
|
||||
);
|
||||
const requestLogPath = NodePath.join(tempDir, "requests.ndjson");
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeMockGrokWrapper({
|
||||
T3_ACP_REQUEST_LOG_PATH: requestLogPath,
|
||||
T3_ACP_EMIT_TOOL_CALLS: "1",
|
||||
T3_ACP_OMIT_ALLOW_ALWAYS: "1",
|
||||
T3_ACP_PERMISSION_REQUEST_COUNT: "2",
|
||||
}),
|
||||
);
|
||||
const adapter = yield* makeTestAdapter(wrapperPath);
|
||||
const openedCount = yield* Ref.make(0);
|
||||
const eventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
event.type === "request.opened"
|
||||
? Effect.gen(function* () {
|
||||
yield* Ref.update(openedCount, (count) => count + 1);
|
||||
yield* adapter.respondToRequest(
|
||||
threadId,
|
||||
ApprovalRequestId.make(String(event.requestId)),
|
||||
"acceptForSession",
|
||||
);
|
||||
})
|
||||
: Effect.void,
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "approval-required",
|
||||
});
|
||||
yield* adapter.sendTurn({
|
||||
threadId,
|
||||
input: "approve this session",
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
assert.equal(yield* Ref.get(openedCount), 1);
|
||||
|
||||
const requests = yield* Effect.promise(() => readJsonLines(requestLogPath));
|
||||
const permissionResults = requests.filter(
|
||||
(entry) =>
|
||||
!("method" in entry) &&
|
||||
typeof entry.result === "object" &&
|
||||
entry.result !== null &&
|
||||
"outcome" in entry.result &&
|
||||
typeof entry.result.outcome === "object" &&
|
||||
entry.result.outcome !== null &&
|
||||
"optionId" in entry.result.outcome,
|
||||
);
|
||||
assert.equal(permissionResults.length, 2);
|
||||
assert.isTrue(
|
||||
permissionResults.every(
|
||||
(entry) =>
|
||||
typeof entry.result === "object" &&
|
||||
entry.result !== null &&
|
||||
"outcome" in entry.result &&
|
||||
typeof entry.result.outcome === "object" &&
|
||||
entry.result.outcome !== null &&
|
||||
"optionId" in entry.result.outcome &&
|
||||
entry.result.outcome.optionId === "allow-once",
|
||||
),
|
||||
);
|
||||
|
||||
yield* Fiber.interrupt(eventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("asks before a different command after Always allow this session", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-session-approval-scope");
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeMockGrokWrapper({
|
||||
T3_ACP_EMIT_TOOL_CALLS: "1",
|
||||
T3_ACP_OMIT_ALLOW_ALWAYS: "1",
|
||||
T3_ACP_PERMISSION_REQUEST_COUNT: "2",
|
||||
T3_ACP_PERMISSION_TITLE: "Terminal",
|
||||
T3_ACP_SECOND_PERMISSION_COMMAND: "rm server/package.json",
|
||||
}),
|
||||
);
|
||||
const adapter = yield* makeTestAdapter(wrapperPath);
|
||||
const openedCount = yield* Ref.make(0);
|
||||
const eventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
event.type === "request.opened"
|
||||
? Effect.gen(function* () {
|
||||
const count = yield* Ref.updateAndGet(openedCount, (value) => value + 1);
|
||||
yield* adapter.respondToRequest(
|
||||
threadId,
|
||||
ApprovalRequestId.make(String(event.requestId)),
|
||||
count === 1 ? "acceptForSession" : "decline",
|
||||
);
|
||||
})
|
||||
: Effect.void,
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "approval-required",
|
||||
});
|
||||
yield* adapter.sendTurn({ threadId, input: "check approval scope", attachments: [] });
|
||||
assert.equal(yield* Ref.get(openedCount), 2);
|
||||
yield* Fiber.interrupt(eventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("captures a plan under the provider instance GROK_HOME", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-instance-plan-home");
|
||||
const grokHome = yield* Effect.promise(() =>
|
||||
NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "grok-instance-home-")),
|
||||
);
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeMockGrokWrapper({
|
||||
T3_ACP_EMIT_XAI_PLAN_MD_WRITE: "1",
|
||||
T3_ACP_PLAN_ROOT: grokHome,
|
||||
}),
|
||||
);
|
||||
const adapter = yield* makeTestAdapter(wrapperPath, {
|
||||
environment: { ...process.env, GROK_HOME: grokHome },
|
||||
});
|
||||
const plans = yield* Ref.make<ReadonlyArray<string>>([]);
|
||||
const completed = yield* Deferred.make<void>();
|
||||
const eventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) => {
|
||||
if (event.type === "turn.proposed.completed") {
|
||||
return Ref.update(plans, (current) => [...current, event.payload.planMarkdown]);
|
||||
}
|
||||
return event.type === "turn.completed"
|
||||
? Deferred.succeed(completed, undefined).pipe(Effect.asVoid)
|
||||
: Effect.void;
|
||||
}).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
yield* adapter.sendTurn({ threadId, input: "write the plan", attachments: [] });
|
||||
yield* Deferred.await(completed);
|
||||
assert.deepEqual(yield* Ref.get(plans), [
|
||||
"# Mock plan\n\n- Write the feature\n- Add a test\n- Ship it",
|
||||
]);
|
||||
yield* Fiber.interrupt(eventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("handles xAI ask_user_question extension requests", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-xai-ask-user-question");
|
||||
@@ -1159,6 +1904,82 @@ it.layer(grokAdapterTestLayer)("GrokAdapterLive", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("settles a stalled Grok turn after its first activity is user input", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-xai-ask-user-question");
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeMockGrokWrapper({ T3_ACP_EMIT_XAI_ASK_USER_QUESTION_THEN_HANG: "1" }),
|
||||
);
|
||||
const adapter = yield* makeTestAdapter(wrapperPath, {
|
||||
turnInactivityTimeoutMs: 1_000,
|
||||
});
|
||||
const requested =
|
||||
yield* Deferred.make<Extract<ProviderRuntimeEvent, { type: "user-input.requested" }>>();
|
||||
const resolved =
|
||||
yield* Deferred.make<Extract<ProviderRuntimeEvent, { type: "user-input.resolved" }>>();
|
||||
const completed =
|
||||
yield* Deferred.make<Extract<ProviderRuntimeEvent, { type: "turn.completed" }>>();
|
||||
|
||||
const eventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) => {
|
||||
if (String(event.threadId) !== String(threadId)) {
|
||||
return Effect.void;
|
||||
}
|
||||
if (event.type === "user-input.requested") {
|
||||
return Deferred.succeed(requested, event).pipe(Effect.ignore);
|
||||
}
|
||||
if (event.type === "user-input.resolved") {
|
||||
return Deferred.succeed(resolved, event).pipe(Effect.ignore);
|
||||
}
|
||||
if (event.type === "turn.completed") {
|
||||
return Deferred.succeed(completed, event).pipe(Effect.ignore);
|
||||
}
|
||||
return Effect.void;
|
||||
}).pipe(Effect.forkChild);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("grok"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const sendTurnFiber = yield* adapter
|
||||
.sendTurn({ threadId, input: "ask before continuing", attachments: [] })
|
||||
.pipe(Effect.forkChild);
|
||||
|
||||
const requestedEvent = yield* Deferred.await(requested);
|
||||
assert.equal(requestedEvent.payload.questions.length, 1);
|
||||
assert.equal(requestedEvent.payload.questions[0]?.id, "Which scope should Grok use?");
|
||||
assert.equal(requestedEvent.payload.questions[0]?.question, "Which scope should Grok use?");
|
||||
assert.equal(requestedEvent.raw?.method, "_x.ai/ask_user_question");
|
||||
|
||||
yield* adapter.respondToUserInput(
|
||||
threadId,
|
||||
ApprovalRequestId.make(String(requestedEvent.requestId)),
|
||||
{
|
||||
"Which scope should Grok use?": "Workspace",
|
||||
},
|
||||
);
|
||||
|
||||
const resolvedEvent = yield* Deferred.await(resolved);
|
||||
assert.deepEqual(resolvedEvent.payload.answers, {
|
||||
"Which scope should Grok use?": "Workspace",
|
||||
});
|
||||
assert.equal(String(resolvedEvent.turnId), String(requestedEvent.turnId));
|
||||
|
||||
yield* TestClock.adjust("1 second");
|
||||
const completedEvent = yield* Deferred.await(completed).pipe(
|
||||
Effect.timeout("2 seconds"),
|
||||
TestClock.withLive,
|
||||
);
|
||||
assert.equal(completedEvent.payload.state, "failed");
|
||||
yield* Fiber.join(sendTurnFiber);
|
||||
|
||||
yield* Fiber.interrupt(eventsFiber);
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("continues streaming events when native notification logging fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("grok-native-log-failure");
|
||||
|
||||
@@ -12,9 +12,14 @@ import {
|
||||
type ThreadId,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { HostProcessEnvironment, HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
|
||||
import { stableStringify } from "@t3tools/shared/relaySigning";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
@@ -22,6 +27,7 @@ import * as FileSystem from "effect/FileSystem";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
@@ -56,15 +62,21 @@ import { makeAcpNativeLoggerFactory } from "../acp/AcpNativeLogging.ts";
|
||||
import {
|
||||
applyGrokAcpModelSelection,
|
||||
currentGrokModelIdFromSessionSetup,
|
||||
currentGrokReasoningEffortFromSessionSetup,
|
||||
makeGrokAcpRuntime,
|
||||
normalizeGrokReasoningEffort,
|
||||
resolveGrokAcpBaseModelId,
|
||||
} from "../acp/GrokAcpSupport.ts";
|
||||
import {
|
||||
extractGrokPlanMarkdownFromToolCallData,
|
||||
extractXAiAskUserQuestions,
|
||||
extractXAiExitPlanMarkdown,
|
||||
makeXAiAskUserQuestionCancelledResponse,
|
||||
makeXAiAskUserQuestionResponse,
|
||||
makeXAiExitPlanModeCapturedResponse,
|
||||
promptResponseHasMissingXAiStopReason,
|
||||
XAiAskUserQuestionRequest,
|
||||
XAiExitPlanModeRequest,
|
||||
} from "../acp/XAiAcpExtension.ts";
|
||||
import { type GrokAdapterShape } from "../Services/GrokAdapter.ts";
|
||||
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
|
||||
@@ -73,6 +85,15 @@ const encodeUnknownJsonStringExit = Schema.encodeUnknownExit(Schema.fromJsonStri
|
||||
|
||||
const PROVIDER = ProviderDriverKind.make("grok");
|
||||
const GROK_RESUME_VERSION = 1 as const;
|
||||
const NANOS_PER_MILLI = 1_000_000n;
|
||||
// ACP does not expose Grok's private `streaming_reasoning` phase. Once it has
|
||||
// emitted standard ACP progress, ten silent minutes is long enough to avoid
|
||||
// treating legitimate reasoning as a stalled stream.
|
||||
const DEFAULT_GROK_TURN_INACTIVITY_TIMEOUT_MS = 10 * 60 * 1_000;
|
||||
// A tool can legitimately run without emitting text for much longer than
|
||||
// reasoning. It still needs a deadline so a lost tool update cannot leave the
|
||||
// turn working forever.
|
||||
const DEFAULT_GROK_ACTIVE_TOOL_INACTIVITY_TIMEOUT_MS = 30 * 60 * 1_000;
|
||||
|
||||
function encodeJsonStringForDiagnostics(input: unknown): string | undefined {
|
||||
const result = encodeUnknownJsonStringExit(input);
|
||||
@@ -84,6 +105,10 @@ export interface GrokAdapterLiveOptions {
|
||||
readonly nativeEventLogPath?: string;
|
||||
readonly nativeEventLogger?: EventNdjsonLogger;
|
||||
readonly instanceId?: ProviderInstanceId;
|
||||
/** Override the conservative ACP turn liveness timeout in focused tests. */
|
||||
readonly turnInactivityTimeoutMs?: number;
|
||||
/** Override the longer active-tool liveness timeout in focused tests. */
|
||||
readonly activeToolInactivityTimeoutMs?: number;
|
||||
}
|
||||
|
||||
interface PendingApproval {
|
||||
@@ -98,6 +123,10 @@ interface PendingUserInput {
|
||||
readonly resolution: Deferred.Deferred<PendingUserInputResolution>;
|
||||
}
|
||||
|
||||
interface GrokTurnLivenessSignal {
|
||||
readonly turnId: TurnId;
|
||||
}
|
||||
|
||||
interface GrokSessionContext {
|
||||
readonly threadId: ThreadId;
|
||||
readonly acpSessionId: string;
|
||||
@@ -109,6 +138,14 @@ interface GrokSessionContext {
|
||||
readonly pendingUserInputs: Map<ApprovalRequestId, PendingUserInput>;
|
||||
turns: Array<{ id: TurnId; items: Array<unknown> }>;
|
||||
lastPlanFingerprint: string | undefined;
|
||||
/**
|
||||
* Latest plan.md body + turn it was emitted for. Dedupe is turn-scoped so a
|
||||
* later turn re-proposing the same text still gets a new proposed-plan card.
|
||||
*/
|
||||
lastKnownProposedPlanMarkdown: string | undefined;
|
||||
lastKnownProposedPlanTurnId: TurnId | undefined;
|
||||
/** True after enter_plan_mode until the turn ends or exit_plan_mode resolves. */
|
||||
planModeActive: boolean;
|
||||
activeTurnId: TurnId | undefined;
|
||||
/** Turns already interrupted; late prompt RPCs must not resurrect them. */
|
||||
interruptedTurnIds: Set<TurnId>;
|
||||
@@ -116,7 +153,15 @@ interface GrokSessionContext {
|
||||
* >0 means a turn is actively running, so a new sendTurn is a steer that
|
||||
* continues it, and only the last remaining prompt settles the turn. */
|
||||
promptsInFlight: number;
|
||||
readonly livenessSignals: Queue.Queue<GrokTurnLivenessSignal>;
|
||||
livenessTurnId: TurnId | undefined;
|
||||
lastTurnActivityAtNanos: bigint | undefined;
|
||||
readonly activeToolCallIds: Set<string>;
|
||||
livenessUpdatesInFlight: number;
|
||||
/** Prompt RPCs that returned before their turn settlement acquired the lock. */
|
||||
promptResponsesReady: number;
|
||||
currentModelId: string | undefined;
|
||||
currentReasoningEffort: string | undefined;
|
||||
stopped: boolean;
|
||||
}
|
||||
|
||||
@@ -164,6 +209,54 @@ const resolveNotificationTurnId = (ctx: GrokSessionContext): TurnId | undefined
|
||||
|
||||
const resolveCallbackTurnId = (ctx: GrokSessionContext): TurnId | undefined => ctx.activeTurnId;
|
||||
|
||||
function clearProposedPlanFallback(ctx: GrokSessionContext): void {
|
||||
ctx.lastKnownProposedPlanMarkdown = undefined;
|
||||
ctx.lastKnownProposedPlanTurnId = undefined;
|
||||
ctx.planModeActive = false;
|
||||
}
|
||||
|
||||
/** Detect Grok's enter_plan_mode tool call from ACP tool state. */
|
||||
export function isGrokEnterPlanModeToolCall(toolCall: {
|
||||
readonly title?: string;
|
||||
readonly data: Record<string, unknown>;
|
||||
}): boolean {
|
||||
const title = toolCall.title?.trim().toLowerCase() ?? "";
|
||||
if (
|
||||
title === "enter_plan_mode" ||
|
||||
title === "plan: enter" ||
|
||||
title === "plan mode entered" ||
|
||||
title.includes("enter_plan_mode")
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
const rawInput = toolCall.data.rawInput;
|
||||
if (isRecord(rawInput) && rawInput.variant === "EnterPlanMode") {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Failed enter_plan_mode must not leave planModeActive stuck on. */
|
||||
export function nextGrokPlanModeActive(
|
||||
currentlyActive: boolean,
|
||||
toolCall: {
|
||||
readonly title?: string;
|
||||
readonly status?: "pending" | "inProgress" | "completed" | "failed";
|
||||
readonly data: Record<string, unknown>;
|
||||
},
|
||||
): boolean {
|
||||
if (!isGrokEnterPlanModeToolCall(toolCall)) {
|
||||
return currentlyActive;
|
||||
}
|
||||
if (toolCall.status === "failed") {
|
||||
return false;
|
||||
}
|
||||
if (toolCall.status === "completed" || toolCall.status === "inProgress") {
|
||||
return true;
|
||||
}
|
||||
return currentlyActive;
|
||||
}
|
||||
|
||||
const resolveSessionCallbackTurnId = (
|
||||
sessions: ReadonlyMap<ThreadId, GrokSessionContext>,
|
||||
threadId: ThreadId,
|
||||
@@ -179,26 +272,38 @@ function parseGrokResume(raw: unknown): { sessionId: string } | undefined {
|
||||
return { sessionId: raw.sessionId.trim() };
|
||||
}
|
||||
|
||||
function selectPermissionOptionId(
|
||||
export function selectGrokPermissionOptionId(
|
||||
request: EffectAcpSchema.RequestPermissionRequest,
|
||||
decision: Exclude<ProviderApprovalDecision, "cancel">,
|
||||
): string | undefined {
|
||||
const kind =
|
||||
const preferredKind =
|
||||
decision === "acceptForSession"
|
||||
? "allow_always"
|
||||
: decision === "accept"
|
||||
? "allow_once"
|
||||
: "reject_once";
|
||||
const option = request.options.find((entry) => entry.kind === kind);
|
||||
return option?.optionId.trim() || undefined;
|
||||
const preferred = request.options.find((entry) => entry.kind === preferredKind);
|
||||
const preferredId = preferred?.optionId.trim();
|
||||
if (preferredId) {
|
||||
return preferredId;
|
||||
}
|
||||
// Grok 4.6 often omits allow_always. T3 still offers "Always allow this session".
|
||||
if (decision === "acceptForSession") {
|
||||
const once = request.options.find((entry) => entry.kind === "allow_once");
|
||||
const onceId = once?.optionId.trim();
|
||||
if (onceId) {
|
||||
return onceId;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function selectAutoApprovedPermissionOption(
|
||||
request: EffectAcpSchema.RequestPermissionRequest,
|
||||
): string | undefined {
|
||||
return (
|
||||
selectPermissionOptionId(request, "acceptForSession") ??
|
||||
selectPermissionOptionId(request, "accept")
|
||||
selectGrokPermissionOptionId(request, "acceptForSession") ??
|
||||
selectGrokPermissionOptionId(request, "accept")
|
||||
);
|
||||
}
|
||||
|
||||
@@ -240,10 +345,31 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
const managedNativeEventLogger =
|
||||
options?.nativeEventLogger === undefined ? nativeEventLogger : undefined;
|
||||
const makeAcpNativeLoggers = yield* makeAcpNativeLoggerFactory();
|
||||
const hostPlatform = yield* HostProcessPlatform;
|
||||
const hostEnvironment = yield* HostProcessEnvironment;
|
||||
const grokPlanPathHost = {
|
||||
platform: hostPlatform,
|
||||
environment: options?.environment ?? hostEnvironment,
|
||||
};
|
||||
|
||||
const sessions = new Map<ThreadId, GrokSessionContext>();
|
||||
const threadLocksRef = yield* SynchronizedRef.make(new Map<string, Semaphore.Semaphore>());
|
||||
const runtimeEventPubSub = yield* PubSub.unbounded<ProviderRuntimeEvent>();
|
||||
const requestedTurnInactivityTimeoutMs = options?.turnInactivityTimeoutMs;
|
||||
const turnInactivityTimeoutMs =
|
||||
typeof requestedTurnInactivityTimeoutMs === "number" &&
|
||||
Number.isFinite(requestedTurnInactivityTimeoutMs)
|
||||
? Math.max(1, Math.floor(requestedTurnInactivityTimeoutMs))
|
||||
: DEFAULT_GROK_TURN_INACTIVITY_TIMEOUT_MS;
|
||||
const turnInactivityTimeoutNanos = BigInt(turnInactivityTimeoutMs) * NANOS_PER_MILLI;
|
||||
const requestedActiveToolInactivityTimeoutMs = options?.activeToolInactivityTimeoutMs;
|
||||
const activeToolInactivityTimeoutMs =
|
||||
typeof requestedActiveToolInactivityTimeoutMs === "number" &&
|
||||
Number.isFinite(requestedActiveToolInactivityTimeoutMs)
|
||||
? Math.max(1, Math.floor(requestedActiveToolInactivityTimeoutMs))
|
||||
: DEFAULT_GROK_ACTIVE_TOOL_INACTIVITY_TIMEOUT_MS;
|
||||
const activeToolInactivityTimeoutNanos =
|
||||
BigInt(activeToolInactivityTimeoutMs) * NANOS_PER_MILLI;
|
||||
|
||||
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
|
||||
const randomUUIDv4 = crypto.randomUUIDv4.pipe(
|
||||
@@ -294,6 +420,146 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
const withThreadLock = <A, E, R>(threadId: string, effect: Effect.Effect<A, E, R>) =>
|
||||
Effect.flatMap(getThreadSemaphore(threadId), (semaphore) => semaphore.withPermit(effect));
|
||||
|
||||
const signalTurnLiveness = (ctx: GrokSessionContext, turnId: TurnId) =>
|
||||
Queue.offer(ctx.livenessSignals, { turnId }).pipe(Effect.asVoid);
|
||||
|
||||
const beginTurnLiveness = (ctx: GrokSessionContext, turnId: TurnId) =>
|
||||
Effect.sync(() => {
|
||||
ctx.livenessTurnId = turnId;
|
||||
// Do not start a deadline until ACP has made observable progress.
|
||||
// Grok's private reasoning phase is not present in the ACP stream.
|
||||
ctx.lastTurnActivityAtNanos = undefined;
|
||||
ctx.activeToolCallIds.clear();
|
||||
});
|
||||
|
||||
const clearTurnLiveness = (ctx: GrokSessionContext) => {
|
||||
const turnId = ctx.livenessTurnId;
|
||||
ctx.livenessTurnId = undefined;
|
||||
ctx.lastTurnActivityAtNanos = undefined;
|
||||
ctx.activeToolCallIds.clear();
|
||||
ctx.livenessUpdatesInFlight = 0;
|
||||
ctx.promptResponsesReady = 0;
|
||||
return turnId === undefined ? Effect.void : signalTurnLiveness(ctx, turnId);
|
||||
};
|
||||
|
||||
const recordTurnActivity = Effect.fn("GrokAdapter.recordTurnActivity")(function* (
|
||||
ctx: GrokSessionContext,
|
||||
turnId: TurnId,
|
||||
event: Extract<
|
||||
AcpSessionRuntime.AcpSessionRuntimeEvent,
|
||||
{
|
||||
_tag:
|
||||
| "AssistantItemStarted"
|
||||
| "AssistantItemCompleted"
|
||||
| "PlanUpdated"
|
||||
| "ToolCallUpdated"
|
||||
| "ContentDelta";
|
||||
}
|
||||
>,
|
||||
) {
|
||||
if (
|
||||
ctx.livenessTurnId !== turnId ||
|
||||
(event._tag === "ContentDelta" && event.text.length === 0)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
ctx.livenessUpdatesInFlight += 1;
|
||||
try {
|
||||
const activityAtNanos = yield* Clock.monotonicTimeNanos;
|
||||
if (ctx.livenessTurnId !== turnId || ctx.interruptedTurnIds.has(turnId)) {
|
||||
return;
|
||||
}
|
||||
if (event._tag === "ToolCallUpdated") {
|
||||
if (event.toolCall.status === "completed" || event.toolCall.status === "failed") {
|
||||
ctx.activeToolCallIds.delete(event.toolCall.toolCallId);
|
||||
} else {
|
||||
// A tool update without a terminal status receives a longer
|
||||
// deadline so a long-running tool is not mistaken for a stall.
|
||||
ctx.activeToolCallIds.add(event.toolCall.toolCallId);
|
||||
}
|
||||
}
|
||||
ctx.lastTurnActivityAtNanos = activityAtNanos;
|
||||
} finally {
|
||||
// Decrement before signaling. The watchdog treats in-flight updates as a
|
||||
// pause; if it consumed a signal while the counter was still > 0 it would
|
||||
// wait on the next take with no follow-up wake after this decrement.
|
||||
ctx.livenessUpdatesInFlight = Math.max(0, ctx.livenessUpdatesInFlight - 1);
|
||||
yield* signalTurnLiveness(ctx, turnId);
|
||||
}
|
||||
});
|
||||
|
||||
const hasLivenessPause = (ctx: GrokSessionContext) =>
|
||||
ctx.pendingApprovals.size > 0 ||
|
||||
ctx.pendingUserInputs.size > 0 ||
|
||||
ctx.livenessUpdatesInFlight > 0;
|
||||
|
||||
const livenessTimeoutFor = (ctx: GrokSessionContext) =>
|
||||
ctx.activeToolCallIds.size > 0
|
||||
? {
|
||||
milliseconds: activeToolInactivityTimeoutMs,
|
||||
nanos: activeToolInactivityTimeoutNanos,
|
||||
}
|
||||
: { milliseconds: turnInactivityTimeoutMs, nanos: turnInactivityTimeoutNanos };
|
||||
|
||||
const signalSessionTurnLiveness = (threadId: ThreadId, turnId: TurnId | undefined) => {
|
||||
const ctx = sessions.get(threadId);
|
||||
return ctx && turnId !== undefined ? signalTurnLiveness(ctx, turnId) : Effect.void;
|
||||
};
|
||||
|
||||
const resumeSessionTurnLiveness = Effect.fn("GrokAdapter.resumeSessionTurnLiveness")(function* (
|
||||
threadId: ThreadId,
|
||||
turnId: TurnId | undefined,
|
||||
) {
|
||||
const ctx = sessions.get(threadId);
|
||||
if (!ctx || turnId === undefined || ctx.livenessTurnId !== turnId) {
|
||||
return;
|
||||
}
|
||||
// An approval or user-input wait can last longer than the watchdog.
|
||||
// Its resolution gives the provider a fresh window to resume output.
|
||||
ctx.lastTurnActivityAtNanos = yield* Clock.monotonicTimeNanos;
|
||||
yield* signalTurnLiveness(ctx, turnId);
|
||||
});
|
||||
|
||||
const refreshSessionTurnLiveness = Effect.fn("GrokAdapter.refreshSessionTurnLiveness")(
|
||||
function* (threadId: ThreadId, turnId: TurnId | undefined) {
|
||||
const ctx = sessions.get(threadId);
|
||||
if (
|
||||
!ctx ||
|
||||
turnId === undefined ||
|
||||
ctx.livenessTurnId !== turnId ||
|
||||
ctx.lastTurnActivityAtNanos === undefined
|
||||
) {
|
||||
return;
|
||||
}
|
||||
ctx.lastTurnActivityAtNanos = yield* Clock.monotonicTimeNanos;
|
||||
yield* signalTurnLiveness(ctx, turnId);
|
||||
},
|
||||
);
|
||||
|
||||
const markPromptResponseReady = Effect.fn("GrokAdapter.markPromptResponseReady")(function* (
|
||||
threadId: ThreadId,
|
||||
acpSessionId: string,
|
||||
turnId: TurnId,
|
||||
) {
|
||||
const ctx = sessions.get(threadId);
|
||||
if (
|
||||
ctx &&
|
||||
ctx.acpSessionId === acpSessionId &&
|
||||
!ctx.stopped &&
|
||||
!ctx.interruptedTurnIds.has(turnId) &&
|
||||
ctx.livenessTurnId === turnId &&
|
||||
ctx.activeTurnId === turnId &&
|
||||
ctx.session.activeTurnId === turnId
|
||||
) {
|
||||
ctx.promptResponsesReady += 1;
|
||||
yield* signalTurnLiveness(ctx, turnId);
|
||||
}
|
||||
});
|
||||
|
||||
const consumePromptResponseReady = (ctx: GrokSessionContext) => {
|
||||
ctx.promptResponsesReady = Math.max(0, ctx.promptResponsesReady - 1);
|
||||
};
|
||||
|
||||
const settlePromptInFlight = (
|
||||
threadId: ThreadId,
|
||||
turnId: TurnId,
|
||||
@@ -373,6 +639,7 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
updatedAt,
|
||||
};
|
||||
}
|
||||
yield* clearTurnLiveness(liveCtx);
|
||||
return;
|
||||
}
|
||||
settleTurnId = fallbackTurnId;
|
||||
@@ -389,6 +656,7 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
}
|
||||
liveCtx.promptsInFlight = remainingPrompts;
|
||||
}
|
||||
yield* clearTurnLiveness(liveCtx);
|
||||
const updatedAt = yield* nowIso;
|
||||
const canEmitTurnCompletion =
|
||||
liveCtx.session.status === "running" || liveCtx.session.status === "connecting";
|
||||
@@ -397,6 +665,9 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
options?.completedStopReason !== undefined && canEmitTurnCompletion;
|
||||
const { activeTurnId: _activeTurnId, ...readySession } = liveCtx.session;
|
||||
liveCtx.activeTurnId = undefined;
|
||||
// Drop turn-scoped plan fallback so a later empty exit_plan cannot
|
||||
// resurrect this turn's markdown as a fresh proposal.
|
||||
clearProposedPlanFallback(liveCtx);
|
||||
liveCtx.session = {
|
||||
...readySession,
|
||||
status: "ready",
|
||||
@@ -432,6 +703,104 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
}
|
||||
});
|
||||
|
||||
const isLiveTurn = (ctx: GrokSessionContext, turnId: TurnId) =>
|
||||
ctx.promptsInFlight > 0 &&
|
||||
ctx.promptsInFlight > ctx.promptResponsesReady &&
|
||||
ctx.activeTurnId === turnId &&
|
||||
ctx.session.activeTurnId === turnId &&
|
||||
(ctx.session.status === "running" || ctx.session.status === "connecting");
|
||||
|
||||
const settleStalledTurn = Effect.fn("GrokAdapter.settleStalledTurn")(function* (
|
||||
ctx: GrokSessionContext,
|
||||
turnId: TurnId,
|
||||
) {
|
||||
return yield* withThreadLock(
|
||||
ctx.threadId,
|
||||
Effect.gen(function* () {
|
||||
const liveCtx = sessions.get(ctx.threadId);
|
||||
if (
|
||||
liveCtx !== ctx ||
|
||||
ctx.stopped ||
|
||||
!isLiveTurn(ctx, turnId) ||
|
||||
ctx.interruptedTurnIds.has(turnId) ||
|
||||
hasLivenessPause(ctx)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const lastActivityAtNanos = ctx.lastTurnActivityAtNanos;
|
||||
if (lastActivityAtNanos === undefined) {
|
||||
return;
|
||||
}
|
||||
const nowNanos = yield* Clock.monotonicTimeNanos;
|
||||
if (
|
||||
ctx.interruptedTurnIds.has(turnId) ||
|
||||
!isLiveTurn(ctx, turnId) ||
|
||||
hasLivenessPause(ctx) ||
|
||||
nowNanos - lastActivityAtNanos < livenessTimeoutFor(ctx).nanos
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Mark before cancel/drain so notifications already in flight finish
|
||||
// before the terminal event, while late notifications are dropped.
|
||||
ctx.interruptedTurnIds.add(turnId);
|
||||
yield* Effect.ignore(
|
||||
ctx.acp.cancel.pipe(
|
||||
Effect.mapError((error) =>
|
||||
mapAcpToAdapterError(PROVIDER, ctx.threadId, "session/cancel", error),
|
||||
),
|
||||
),
|
||||
);
|
||||
yield* Effect.ignore(ctx.acp.drainEvents);
|
||||
yield* settlePromptInFlight(ctx.threadId, turnId, ctx.acpSessionId, {
|
||||
errorMessage: `Grok ACP turn stalled without content or tool progress for ${livenessTimeoutFor(ctx).milliseconds}ms.`,
|
||||
settleAllPrompts: true,
|
||||
});
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
const runTurnLivenessWatchdog = Effect.fn("GrokAdapter.runTurnLivenessWatchdog")(
|
||||
function* (ctx: GrokSessionContext) {
|
||||
while (true) {
|
||||
if (ctx.stopped) {
|
||||
return;
|
||||
}
|
||||
const turnId = ctx.livenessTurnId;
|
||||
if (
|
||||
turnId === undefined ||
|
||||
ctx.interruptedTurnIds.has(turnId) ||
|
||||
!isLiveTurn(ctx, turnId) ||
|
||||
hasLivenessPause(ctx)
|
||||
) {
|
||||
yield* Queue.take(ctx.livenessSignals);
|
||||
continue;
|
||||
}
|
||||
|
||||
const lastActivityAtNanos = ctx.lastTurnActivityAtNanos;
|
||||
if (lastActivityAtNanos === undefined) {
|
||||
yield* Queue.take(ctx.livenessSignals);
|
||||
continue;
|
||||
}
|
||||
const nowNanos = yield* Clock.monotonicTimeNanos;
|
||||
const remainingNanos = livenessTimeoutFor(ctx).nanos - (nowNanos - lastActivityAtNanos);
|
||||
if (remainingNanos <= 0n) {
|
||||
yield* settleStalledTurn(ctx, turnId);
|
||||
continue;
|
||||
}
|
||||
|
||||
const wakeReason = yield* Effect.raceFirst(
|
||||
Effect.sleep(Duration.nanos(remainingNanos)).pipe(Effect.as("timeout" as const)),
|
||||
Queue.take(ctx.livenessSignals).pipe(Effect.as("activity" as const)),
|
||||
);
|
||||
if (wakeReason === "timeout") {
|
||||
yield* settleStalledTurn(ctx, turnId);
|
||||
}
|
||||
}
|
||||
},
|
||||
Effect.catch(() => Effect.void),
|
||||
);
|
||||
|
||||
const logNative = (threadId: ThreadId, method: string, payload: unknown) =>
|
||||
Effect.gen(function* () {
|
||||
if (!nativeEventLogger) return;
|
||||
@@ -495,6 +864,45 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
);
|
||||
});
|
||||
|
||||
/** Surface Grok plan.md as T3's proposed-plan card (while writing + on exit). */
|
||||
const emitProposedPlanCompleted = (
|
||||
ctx: GrokSessionContext,
|
||||
turnId: TurnId | undefined,
|
||||
stamp: { readonly eventId: EventId; readonly createdAt: string },
|
||||
planMarkdown: string,
|
||||
raw: { readonly method: string; readonly payload: unknown },
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const trimmed = planMarkdown.trim();
|
||||
if (trimmed.length === 0) {
|
||||
ctx.lastKnownProposedPlanMarkdown = "";
|
||||
ctx.lastKnownProposedPlanTurnId = turnId;
|
||||
return;
|
||||
}
|
||||
// Turn-scoped dedupe: identical text on a later turn must still emit.
|
||||
if (
|
||||
ctx.lastKnownProposedPlanMarkdown === trimmed &&
|
||||
ctx.lastKnownProposedPlanTurnId === turnId
|
||||
) {
|
||||
return;
|
||||
}
|
||||
ctx.lastKnownProposedPlanMarkdown = trimmed;
|
||||
ctx.lastKnownProposedPlanTurnId = turnId;
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.proposed.completed",
|
||||
...stamp,
|
||||
provider: PROVIDER,
|
||||
threadId: ctx.threadId,
|
||||
turnId,
|
||||
payload: { planMarkdown: trimmed },
|
||||
raw: {
|
||||
source: "acp.grok.extension",
|
||||
method: raw.method,
|
||||
payload: raw.payload,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
const requireSession = (
|
||||
threadId: ThreadId,
|
||||
): Effect.Effect<GrokSessionContext, ProviderAdapterSessionNotFoundError> => {
|
||||
@@ -556,6 +964,7 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
|
||||
const pendingApprovals = new Map<ApprovalRequestId, PendingApproval>();
|
||||
const pendingUserInputs = new Map<ApprovalRequestId, PendingUserInput>();
|
||||
const sessionApprovedOperations = new Set<string>();
|
||||
const sessionScope = yield* Scope.make("sequential");
|
||||
let sessionScopeTransferred = false;
|
||||
yield* Effect.addFinalizer(() =>
|
||||
@@ -575,6 +984,7 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
...(options?.environment ? { environment: options.environment } : {}),
|
||||
childProcessSpawner,
|
||||
cwd,
|
||||
runtimeMode: input.runtimeMode,
|
||||
...(resumeSessionId ? { resumeSessionId } : {}),
|
||||
clientInfo: { name: "t3-code", version: "0.0.0" },
|
||||
...(mcpSession
|
||||
@@ -621,6 +1031,7 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
const resolution = yield* Deferred.make<PendingUserInputResolution>();
|
||||
const turnId = resolveSessionCallbackTurnId(sessions, input.threadId);
|
||||
pendingUserInputs.set(requestId, { resolution });
|
||||
yield* signalSessionTurnLiveness(input.threadId, turnId);
|
||||
yield* offerRuntimeEvent({
|
||||
type: "user-input.requested",
|
||||
...(yield* makeEventStamp()),
|
||||
@@ -637,6 +1048,7 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
});
|
||||
const resolved = yield* Deferred.await(resolution);
|
||||
pendingUserInputs.delete(requestId);
|
||||
yield* resumeSessionTurnLiveness(input.threadId, turnId);
|
||||
const resolvedAnswers = resolved._tag === "answered" ? resolved.answers : {};
|
||||
yield* offerRuntimeEvent({
|
||||
type: "user-input.resolved",
|
||||
@@ -663,12 +1075,77 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
),
|
||||
{ discard: true },
|
||||
);
|
||||
// Grok intercepts exit_plan_mode and reverse-requests client approval.
|
||||
// Capture plan into T3 proposed-plan UI and abandon the native gate so
|
||||
// the turn does not hang (Claude ExitPlanMode pattern).
|
||||
yield* Effect.forEach(
|
||||
["x.ai/exit_plan_mode", "_x.ai/exit_plan_mode"] as const,
|
||||
(method) =>
|
||||
acp.handleExtRequest(method, XAiExitPlanModeRequest, (params) =>
|
||||
mapAcpCallbackFailure(
|
||||
Effect.gen(function* () {
|
||||
yield* logNative(input.threadId, method, params);
|
||||
const turnId = resolveSessionCallbackTurnId(sessions, input.threadId);
|
||||
const ctx = sessions.get(input.threadId);
|
||||
const planMarkdown = extractXAiExitPlanMarkdown(
|
||||
params,
|
||||
ctx?.lastKnownProposedPlanMarkdown,
|
||||
);
|
||||
if (ctx) {
|
||||
yield* emitProposedPlanCompleted(
|
||||
ctx,
|
||||
turnId,
|
||||
yield* makeEventStamp(),
|
||||
planMarkdown,
|
||||
{ method, payload: params },
|
||||
);
|
||||
ctx.planModeActive = false;
|
||||
} else {
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.proposed.completed",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId,
|
||||
payload: { planMarkdown },
|
||||
raw: {
|
||||
source: "acp.grok.extension",
|
||||
method,
|
||||
payload: params,
|
||||
},
|
||||
});
|
||||
}
|
||||
return makeXAiExitPlanModeCapturedResponse();
|
||||
}),
|
||||
),
|
||||
),
|
||||
{ discard: true },
|
||||
);
|
||||
yield* acp.handleRequestPermission((params) =>
|
||||
mapAcpCallbackFailure(
|
||||
Effect.gen(function* () {
|
||||
yield* logNative(input.threadId, "session/request_permission", params);
|
||||
if (input.runtimeMode === "full-access") {
|
||||
const autoApprovedOptionId = selectAutoApprovedPermissionOption(params);
|
||||
const permissionRequest = parsePermissionRequest(params);
|
||||
const command = permissionRequest.toolCall?.command;
|
||||
const { kind, title, rawInput, locations } = params.toolCall;
|
||||
let operationInput = rawInput;
|
||||
if (isRecord(rawInput) && rawInput.variant === "Bash") {
|
||||
const { description: _description, ...shellInput } = rawInput;
|
||||
operationInput = shellInput;
|
||||
}
|
||||
// Remember the operation, not the tool-call id or every future tool.
|
||||
// Generic titles without input cannot identify an operation safely.
|
||||
const approvalKey =
|
||||
command || (isRecord(rawInput) && Object.keys(rawInput).length > 0)
|
||||
? stableStringify({ kind, title, command, input: operationInput, locations })
|
||||
: undefined;
|
||||
const alreadyApproved =
|
||||
approvalKey !== undefined && sessionApprovedOperations.has(approvalKey);
|
||||
if (input.runtimeMode === "full-access" || alreadyApproved) {
|
||||
const autoApprovedOptionId =
|
||||
input.runtimeMode === "full-access"
|
||||
? selectAutoApprovedPermissionOption(params)
|
||||
: selectGrokPermissionOptionId(params, "accept");
|
||||
if (autoApprovedOptionId !== undefined) {
|
||||
return {
|
||||
outcome: {
|
||||
@@ -678,12 +1155,12 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
};
|
||||
}
|
||||
}
|
||||
const permissionRequest = parsePermissionRequest(params);
|
||||
const requestId = ApprovalRequestId.make(yield* randomUUIDv4);
|
||||
const runtimeRequestId = RuntimeRequestId.make(requestId);
|
||||
const decision = yield* Deferred.make<ProviderApprovalDecision>();
|
||||
const turnId = resolveSessionCallbackTurnId(sessions, input.threadId);
|
||||
pendingApprovals.set(requestId, { decision });
|
||||
yield* signalSessionTurnLiveness(input.threadId, turnId);
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpRequestOpenedEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
@@ -704,6 +1181,7 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
);
|
||||
const resolved = yield* Deferred.await(decision);
|
||||
pendingApprovals.delete(requestId);
|
||||
yield* resumeSessionTurnLiveness(input.threadId, turnId);
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpRequestResolvedEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
@@ -716,7 +1194,16 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
}),
|
||||
);
|
||||
const selectedOptionId =
|
||||
resolved === "cancel" ? undefined : selectPermissionOptionId(params, resolved);
|
||||
resolved === "cancel"
|
||||
? undefined
|
||||
: selectGrokPermissionOptionId(params, resolved);
|
||||
if (
|
||||
resolved === "acceptForSession" &&
|
||||
selectedOptionId &&
|
||||
approvalKey !== undefined
|
||||
) {
|
||||
sessionApprovedOperations.add(approvalKey);
|
||||
}
|
||||
return {
|
||||
outcome: selectedOptionId
|
||||
? {
|
||||
@@ -738,10 +1225,22 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
const requestedStartModelId = grokModelSelection?.model
|
||||
? resolveGrokAcpBaseModelId(grokModelSelection.model)
|
||||
: undefined;
|
||||
const currentStartModelId = currentGrokModelIdFromSessionSetup(
|
||||
started.sessionSetupResult,
|
||||
);
|
||||
const currentStartReasoningEffort = currentGrokReasoningEffortFromSessionSetup(
|
||||
started.sessionSetupResult,
|
||||
);
|
||||
const requestedStartReasoningEffort = getModelSelectionStringOptionValue(
|
||||
grokModelSelection,
|
||||
"reasoningEffort",
|
||||
);
|
||||
const boundModelId = yield* applyGrokAcpModelSelection({
|
||||
runtime: acp,
|
||||
currentModelId: currentGrokModelIdFromSessionSetup(started.sessionSetupResult),
|
||||
currentModelId: currentStartModelId,
|
||||
currentReasoningEffort: currentStartReasoningEffort,
|
||||
requestedModelId: requestedStartModelId,
|
||||
requestedReasoningEffort: requestedStartReasoningEffort,
|
||||
mapError: (cause) =>
|
||||
mapAcpToAdapterError(PROVIDER, input.threadId, "session/set_model", cause),
|
||||
});
|
||||
@@ -774,10 +1273,23 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
pendingUserInputs,
|
||||
turns: [],
|
||||
lastPlanFingerprint: undefined,
|
||||
lastKnownProposedPlanMarkdown: undefined,
|
||||
lastKnownProposedPlanTurnId: undefined,
|
||||
planModeActive: false,
|
||||
activeTurnId: undefined,
|
||||
interruptedTurnIds: new Set(),
|
||||
promptsInFlight: 0,
|
||||
livenessSignals: yield* Queue.sliding<GrokTurnLivenessSignal>(1),
|
||||
livenessTurnId: undefined,
|
||||
lastTurnActivityAtNanos: undefined,
|
||||
activeToolCallIds: new Set(),
|
||||
livenessUpdatesInFlight: 0,
|
||||
promptResponsesReady: 0,
|
||||
currentModelId: boundModelId,
|
||||
currentReasoningEffort:
|
||||
requestedStartReasoningEffort !== undefined
|
||||
? normalizeGrokReasoningEffort(requestedStartReasoningEffort)
|
||||
: currentStartReasoningEffort,
|
||||
stopped: false,
|
||||
};
|
||||
|
||||
@@ -807,6 +1319,15 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
event._tag === "AssistantItemStarted" ||
|
||||
event._tag === "AssistantItemCompleted" ||
|
||||
event._tag === "PlanUpdated" ||
|
||||
event._tag === "ToolCallUpdated" ||
|
||||
event._tag === "ContentDelta"
|
||||
) {
|
||||
yield* recordTurnActivity(ctx, notificationTurnId, event);
|
||||
}
|
||||
const stamp = yield* makeEventStamp();
|
||||
|
||||
switch (event._tag) {
|
||||
@@ -844,7 +1365,7 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
"session/update",
|
||||
);
|
||||
return;
|
||||
case "ToolCallUpdated":
|
||||
case "ToolCallUpdated": {
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpToolCallEvent({
|
||||
stamp,
|
||||
@@ -855,7 +1376,30 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
rawPayload: event.rawPayload,
|
||||
}),
|
||||
);
|
||||
ctx.planModeActive = nextGrokPlanModeActive(ctx.planModeActive, event.toolCall);
|
||||
// Only promote session plan.md writes while plan mode is
|
||||
// active — avoids treating unrelated plan files as proposals.
|
||||
// Fresh stamp: must not share eventId with the tool lifecycle event.
|
||||
if (ctx.planModeActive) {
|
||||
const planMarkdown = extractGrokPlanMarkdownFromToolCallData(
|
||||
event.toolCall.data,
|
||||
grokPlanPathHost,
|
||||
);
|
||||
if (planMarkdown !== undefined) {
|
||||
yield* emitProposedPlanCompleted(
|
||||
ctx,
|
||||
notificationTurnId,
|
||||
yield* makeEventStamp(),
|
||||
planMarkdown,
|
||||
{
|
||||
method: "session/update",
|
||||
payload: event.rawPayload,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
case "ContentDelta":
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpContentDeltaEvent({
|
||||
@@ -887,6 +1431,7 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
|
||||
ctx.notificationFiber = nf;
|
||||
sessions.set(input.threadId, ctx);
|
||||
yield* runTurnLivenessWatchdog(ctx).pipe(Effect.forkIn(ctx.scope), Effect.asVoid);
|
||||
sessionScopeTransferred = true;
|
||||
|
||||
yield* offerRuntimeEvent({
|
||||
@@ -933,6 +1478,11 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
// Bind the turn id before cooperative yields so interruptTurn can
|
||||
// settle this prompt even if stop arrives during preparation.
|
||||
ctx.activeTurnId = turnId;
|
||||
// New turn: do not fall back to a previous turn's plan.md body when
|
||||
// exit_plan_mode omits planContent.
|
||||
if (steeringTurnId === undefined) {
|
||||
clearProposedPlanFallback(ctx);
|
||||
}
|
||||
ctx.session = {
|
||||
...ctx.session,
|
||||
status: steeringTurnId === undefined ? "connecting" : "running",
|
||||
@@ -948,13 +1498,10 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
const requestedTurnModelId = turnModelSelection?.model
|
||||
? resolveGrokAcpBaseModelId(turnModelSelection.model)
|
||||
: undefined;
|
||||
const currentModelId = yield* applyGrokAcpModelSelection({
|
||||
runtime: ctx.acp,
|
||||
currentModelId: ctx.currentModelId,
|
||||
requestedModelId: requestedTurnModelId,
|
||||
mapError: (cause) =>
|
||||
mapAcpToAdapterError(PROVIDER, input.threadId, "session/set_model", cause),
|
||||
});
|
||||
const requestedTurnReasoningEffort = getModelSelectionStringOptionValue(
|
||||
turnModelSelection,
|
||||
"reasoningEffort",
|
||||
);
|
||||
|
||||
const text = input.input?.trim();
|
||||
const imagePromptParts = yield* Effect.forEach(
|
||||
@@ -1003,7 +1550,21 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
});
|
||||
}
|
||||
|
||||
const currentModelId = yield* applyGrokAcpModelSelection({
|
||||
runtime: ctx.acp,
|
||||
currentModelId: ctx.currentModelId,
|
||||
currentReasoningEffort: ctx.currentReasoningEffort,
|
||||
requestedModelId: requestedTurnModelId,
|
||||
requestedReasoningEffort: requestedTurnReasoningEffort,
|
||||
mapError: (cause) =>
|
||||
mapAcpToAdapterError(PROVIDER, input.threadId, "session/set_model", cause),
|
||||
});
|
||||
ctx.currentModelId = currentModelId;
|
||||
if (requestedTurnReasoningEffort !== undefined) {
|
||||
ctx.currentReasoningEffort = normalizeGrokReasoningEffort(
|
||||
requestedTurnReasoningEffort,
|
||||
);
|
||||
}
|
||||
const displayModel = currentModelId
|
||||
? resolveGrokAcpBaseModelId(currentModelId)
|
||||
: undefined;
|
||||
@@ -1032,6 +1593,11 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
updatedAt: yield* nowIso,
|
||||
...(displayModel ? { model: displayModel } : {}),
|
||||
};
|
||||
if (steeringTurnId === undefined) {
|
||||
yield* beginTurnLiveness(ctx, turnId);
|
||||
} else {
|
||||
yield* refreshSessionTurnLiveness(input.threadId, turnId);
|
||||
}
|
||||
|
||||
if (steeringTurnId === undefined) {
|
||||
yield* offerRuntimeEvent({
|
||||
@@ -1082,10 +1648,14 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
})
|
||||
.pipe(
|
||||
Effect.tap((promptResult) =>
|
||||
Effect.all([
|
||||
Ref.set(promptRpcSucceeded, true),
|
||||
Ref.set(promptResultRef, promptResult),
|
||||
]),
|
||||
Effect.all(
|
||||
[
|
||||
Ref.set(promptRpcSucceeded, true),
|
||||
Ref.set(promptResultRef, promptResult),
|
||||
markPromptResponseReady(input.threadId, prepared.acpSessionId, prepared.turnId),
|
||||
],
|
||||
{ discard: true },
|
||||
),
|
||||
),
|
||||
Effect.tapError((error) =>
|
||||
Ref.set(
|
||||
@@ -1126,6 +1696,7 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
yield* prepared.acp.drainEvents;
|
||||
consumePromptResponseReady(ctx);
|
||||
if (ctx.interruptedTurnIds.has(prepared.turnId)) {
|
||||
yield* Ref.set(promptSettled, true);
|
||||
return {
|
||||
@@ -1184,6 +1755,7 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
updatedAt: completedAt,
|
||||
...(prepared.displayModel ? { model: prepared.displayModel } : {}),
|
||||
};
|
||||
yield* clearTurnLiveness(ctx);
|
||||
const completedStopReason = completedStopReasonFromPromptResponse(result);
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.completed",
|
||||
@@ -1240,6 +1812,7 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
if (ctx.interruptedTurnIds.has(prepared.turnId)) {
|
||||
return;
|
||||
}
|
||||
consumePromptResponseReady(ctx);
|
||||
if (
|
||||
ctx.promptsInFlight <= 0 ||
|
||||
ctx.activeTurnId !== prepared.turnId ||
|
||||
@@ -1356,6 +1929,7 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
status: "ready",
|
||||
updatedAt,
|
||||
};
|
||||
yield* clearTurnLiveness(ctx);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -6,10 +6,183 @@ import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { GrokSettings } from "@t3tools/contracts";
|
||||
|
||||
import { buildInitialGrokProviderSnapshot, checkGrokProviderStatus } from "./GrokProvider.ts";
|
||||
import {
|
||||
buildGrokModelCapabilities,
|
||||
buildInitialGrokProviderSnapshot,
|
||||
checkGrokProviderStatus,
|
||||
} from "./GrokProvider.ts";
|
||||
|
||||
const decodeGrokSettings = Schema.decodeSync(GrokSettings);
|
||||
|
||||
describe("buildGrokModelCapabilities", () => {
|
||||
it("preserves ACP-provided reasoning labels and the active default", () => {
|
||||
const capabilities = buildGrokModelCapabilities({
|
||||
modelId: "grok-4.6",
|
||||
name: "Grok 4.6",
|
||||
_meta: {
|
||||
supportsReasoningEffort: true,
|
||||
reasoningEffort: "xhigh",
|
||||
reasoningEfforts: [
|
||||
{ value: "xhigh", label: "Extra High Effort", default: true },
|
||||
{ value: "high", label: "High Effort", default: true },
|
||||
{ value: "medium", label: "Medium Effort" },
|
||||
{ value: "low", label: "Low Effort" },
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
expect(capabilities.optionDescriptors).toEqual([
|
||||
{
|
||||
id: "reasoningEffort",
|
||||
label: "Reasoning",
|
||||
type: "select",
|
||||
currentValue: "xhigh",
|
||||
options: [
|
||||
{ id: "xhigh", label: "Extra High Effort", isDefault: true },
|
||||
{ id: "high", label: "High Effort" },
|
||||
{ id: "medium", label: "Medium Effort" },
|
||||
{ id: "low", label: "Low Effort" },
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("uses raw ACP values when option labels are omitted", () => {
|
||||
const capabilities = buildGrokModelCapabilities({
|
||||
modelId: "grok-4.6",
|
||||
name: "Grok 4.6",
|
||||
_meta: {
|
||||
supportsReasoningEffort: true,
|
||||
reasoningEffort: "xhigh",
|
||||
reasoningEfforts: [{ value: "xhigh" }, { value: "medium" }],
|
||||
},
|
||||
});
|
||||
|
||||
expect(capabilities.optionDescriptors).toEqual([
|
||||
{
|
||||
id: "reasoningEffort",
|
||||
label: "Reasoning",
|
||||
type: "select",
|
||||
currentValue: "xhigh",
|
||||
options: [
|
||||
{ id: "xhigh", label: "xhigh" },
|
||||
{ id: "medium", label: "medium" },
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps ACP current effort separate from its collapsed advertised default", () => {
|
||||
const capabilities = buildGrokModelCapabilities({
|
||||
modelId: "grok-4.6",
|
||||
name: "Grok 4.6",
|
||||
_meta: {
|
||||
supportsReasoningEffort: true,
|
||||
reasoningEffort: "medium",
|
||||
reasoningEfforts: [
|
||||
{ value: "xhigh", label: "Extra High Effort", default: true },
|
||||
{ value: "high", label: "High Effort", default: true },
|
||||
{ value: "medium", label: "Medium Effort" },
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
expect(capabilities.optionDescriptors).toEqual([
|
||||
{
|
||||
id: "reasoningEffort",
|
||||
label: "Reasoning",
|
||||
type: "select",
|
||||
currentValue: "medium",
|
||||
options: [
|
||||
{ id: "xhigh", label: "Extra High Effort", isDefault: true },
|
||||
{ id: "high", label: "High Effort" },
|
||||
{ id: "medium", label: "Medium Effort" },
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("preserves ACP descriptions and falls back from invalid values to valid ids", () => {
|
||||
const capabilities = buildGrokModelCapabilities({
|
||||
modelId: "grok-4.6",
|
||||
name: "Grok 4.6",
|
||||
_meta: {
|
||||
supportsReasoningEffort: true,
|
||||
reasoningEffort: "high",
|
||||
reasoningEfforts: [
|
||||
{
|
||||
id: "high",
|
||||
value: "not a token",
|
||||
label: "High Effort",
|
||||
description: "Higher implementation quality",
|
||||
default: true,
|
||||
},
|
||||
{ id: "bad id", value: "also invalid", label: "Invalid" },
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
expect(capabilities.optionDescriptors).toEqual([
|
||||
{
|
||||
id: "reasoningEffort",
|
||||
label: "Reasoning",
|
||||
type: "select",
|
||||
currentValue: "high",
|
||||
options: [
|
||||
{
|
||||
id: "high",
|
||||
label: "High Effort",
|
||||
description: "Higher implementation quality",
|
||||
isDefault: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("accepts an advertised ACP menu when the support flag is omitted", () => {
|
||||
const capabilities = buildGrokModelCapabilities({
|
||||
modelId: "grok-4.6",
|
||||
name: "Grok 4.6",
|
||||
_meta: {
|
||||
reasoningEffort: "high",
|
||||
reasoningEfforts: [{ value: "high", label: "High Effort", default: true }],
|
||||
},
|
||||
});
|
||||
|
||||
expect(capabilities.optionDescriptors).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("honors an explicit ACP opt-out even when a menu is present", () => {
|
||||
const capabilities = buildGrokModelCapabilities({
|
||||
modelId: "grok-4.6",
|
||||
name: "Grok 4.6",
|
||||
_meta: {
|
||||
supportsReasoningEffort: false,
|
||||
reasoningEfforts: [{ value: "high", label: "High Effort", default: true }],
|
||||
},
|
||||
});
|
||||
|
||||
expect(capabilities.optionDescriptors).toEqual([]);
|
||||
});
|
||||
|
||||
it("does not synthesize a reasoning menu when ACP omits it", () => {
|
||||
expect(
|
||||
buildGrokModelCapabilities({
|
||||
modelId: "grok-4.6",
|
||||
name: "Grok 4.6",
|
||||
_meta: { supportsReasoningEffort: true, reasoningEffort: "xhigh" },
|
||||
}).optionDescriptors,
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps non-reasoning Grok models free of reasoning controls", () => {
|
||||
expect(
|
||||
buildGrokModelCapabilities({ modelId: "grok-build", name: "Grok Build" }).optionDescriptors,
|
||||
).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildInitialGrokProviderSnapshot", () => {
|
||||
it.effect("returns a disabled snapshot when settings.enabled is false", () =>
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -29,7 +29,12 @@ import {
|
||||
enrichProviderSnapshotWithVersionAdvisory,
|
||||
type ProviderMaintenanceCapabilities,
|
||||
} from "../providerMaintenance.ts";
|
||||
import { makeGrokAcpRuntime, resolveGrokAcpBaseModelId } from "../acp/GrokAcpSupport.ts";
|
||||
import {
|
||||
isValidGrokReasoningEffortToken,
|
||||
makeGrokAcpRuntime,
|
||||
resolveGrokAcpBaseModelId,
|
||||
} from "../acp/GrokAcpSupport.ts";
|
||||
import { discoverGrokSkills } from "../Drivers/GrokSkills.ts";
|
||||
|
||||
const GROK_PRESENTATION = {
|
||||
displayName: "Grok",
|
||||
@@ -99,6 +104,104 @@ function grokModelsFromSettings(
|
||||
return providerModelsFromSettings(builtInModels, customModels ?? [], EMPTY_CAPABILITIES);
|
||||
}
|
||||
|
||||
function nonEmptyString(value: unknown): string | undefined {
|
||||
return typeof value === "string" ? value.trim() || undefined : undefined;
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function grokReasoningOptionsFromModel(model: EffectAcpSchema.ModelInfo): {
|
||||
readonly options: ReadonlyArray<{
|
||||
value: string;
|
||||
label: string;
|
||||
description?: string;
|
||||
isDefault?: boolean;
|
||||
}>;
|
||||
readonly currentValue: string | undefined;
|
||||
} {
|
||||
const meta = model._meta;
|
||||
if (!meta || meta.supportsReasoningEffort === false) {
|
||||
return { options: [], currentValue: undefined };
|
||||
}
|
||||
|
||||
const currentEffort = nonEmptyString(meta.reasoningEffort);
|
||||
const advertisedOptions = Array.isArray(meta.reasoningEfforts) ? meta.reasoningEfforts : [];
|
||||
const seen = new Set<string>();
|
||||
const options: Array<{
|
||||
value: string;
|
||||
label: string;
|
||||
description?: string;
|
||||
advertisedDefault: boolean;
|
||||
}> = [];
|
||||
|
||||
for (const entry of advertisedOptions) {
|
||||
if (!isRecord(entry)) {
|
||||
continue;
|
||||
}
|
||||
const rawValue = nonEmptyString(entry.value);
|
||||
const rawId = nonEmptyString(entry.id);
|
||||
const value =
|
||||
rawValue && isValidGrokReasoningEffortToken(rawValue)
|
||||
? rawValue
|
||||
: rawId && isValidGrokReasoningEffortToken(rawId)
|
||||
? rawId
|
||||
: undefined;
|
||||
if (value === undefined || seen.has(value)) {
|
||||
continue;
|
||||
}
|
||||
seen.add(value);
|
||||
const description = nonEmptyString(entry.description);
|
||||
options.push({
|
||||
value,
|
||||
label: nonEmptyString(entry.label) ?? value,
|
||||
...(description ? { description } : {}),
|
||||
advertisedDefault: entry.default === true || entry.isDefault === true,
|
||||
});
|
||||
}
|
||||
|
||||
const currentValue =
|
||||
currentEffort && options.some((option) => option.value === currentEffort)
|
||||
? currentEffort
|
||||
: undefined;
|
||||
const advertisedDefaults = options.filter((option) => option.advertisedDefault);
|
||||
const selectedDefault =
|
||||
advertisedDefaults.find((option) => option.value === currentValue)?.value ??
|
||||
advertisedDefaults[0]?.value;
|
||||
return {
|
||||
options: options.map(({ value, label, description }) => ({
|
||||
value,
|
||||
label,
|
||||
...(description ? { description } : {}),
|
||||
...(value === selectedDefault ? { isDefault: true } : {}),
|
||||
})),
|
||||
currentValue: currentValue ?? selectedDefault,
|
||||
};
|
||||
}
|
||||
|
||||
export function buildGrokModelCapabilities(model: EffectAcpSchema.ModelInfo): ModelCapabilities {
|
||||
const reasoning = grokReasoningOptionsFromModel(model);
|
||||
return reasoning.options.length > 0
|
||||
? createModelCapabilities({
|
||||
optionDescriptors: [
|
||||
{
|
||||
id: "reasoningEffort",
|
||||
label: "Reasoning",
|
||||
type: "select",
|
||||
options: reasoning.options.map((option) => ({
|
||||
id: option.value,
|
||||
label: option.label,
|
||||
...(option.description ? { description: option.description } : {}),
|
||||
...(option.isDefault ? { isDefault: true } : {}),
|
||||
})),
|
||||
...(reasoning.currentValue ? { currentValue: reasoning.currentValue } : {}),
|
||||
},
|
||||
],
|
||||
})
|
||||
: EMPTY_CAPABILITIES;
|
||||
}
|
||||
|
||||
function buildGrokDiscoveredModelsFromSessionModelState(
|
||||
modelState: EffectAcpSchema.SessionModelState | null | undefined,
|
||||
): ReadonlyArray<ServerProviderModel> {
|
||||
@@ -117,7 +220,7 @@ function buildGrokDiscoveredModelsFromSessionModelState(
|
||||
slug,
|
||||
name: model.name.trim() || slug,
|
||||
isCustom: false,
|
||||
capabilities: EMPTY_CAPABILITIES,
|
||||
capabilities: buildGrokModelCapabilities(model),
|
||||
};
|
||||
})
|
||||
.filter((model): model is ServerProviderModel => model !== undefined);
|
||||
@@ -161,6 +264,7 @@ const runGrokVersionCommand = (
|
||||
export const checkGrokProviderStatus = Effect.fn("checkGrokProviderStatus")(function* (
|
||||
grokSettings: GrokSettings,
|
||||
environment: NodeJS.ProcessEnv = process.env,
|
||||
cwd?: string,
|
||||
): Effect.fn.Return<
|
||||
ServerProviderDraft,
|
||||
never,
|
||||
@@ -251,6 +355,8 @@ export const checkGrokProviderStatus = Effect.fn("checkGrokProviderStatus")(func
|
||||
});
|
||||
}
|
||||
|
||||
const skills = yield* discoverGrokSkills(grokSettings, environment, cwd);
|
||||
|
||||
const discoveryExit = yield* discoverGrokModelsViaAcp(grokSettings, environment).pipe(
|
||||
Effect.timeoutOption(GROK_ACP_MODEL_DISCOVERY_TIMEOUT_MS),
|
||||
Effect.exit,
|
||||
@@ -264,6 +370,7 @@ export const checkGrokProviderStatus = Effect.fn("checkGrokProviderStatus")(func
|
||||
enabled: grokSettings.enabled,
|
||||
checkedAt,
|
||||
models: fallbackModels,
|
||||
skills,
|
||||
probe: {
|
||||
installed: true,
|
||||
version,
|
||||
@@ -282,6 +389,7 @@ export const checkGrokProviderStatus = Effect.fn("checkGrokProviderStatus")(func
|
||||
enabled: grokSettings.enabled,
|
||||
checkedAt,
|
||||
models: fallbackModels,
|
||||
skills,
|
||||
probe: {
|
||||
installed: true,
|
||||
version,
|
||||
@@ -302,6 +410,7 @@ export const checkGrokProviderStatus = Effect.fn("checkGrokProviderStatus")(func
|
||||
enabled: grokSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
skills,
|
||||
probe: {
|
||||
installed: true,
|
||||
version,
|
||||
|
||||
@@ -330,7 +330,7 @@ describe("AcpSessionRuntime", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("suppresses generic placeholder tool updates until completion", () =>
|
||||
it.effect("emits status-only tool updates through completion", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
|
||||
yield* runtime.start();
|
||||
@@ -340,13 +340,22 @@ describe("AcpSessionRuntime", () => {
|
||||
});
|
||||
expect(promptResult).toMatchObject({ stopReason: "end_turn" });
|
||||
|
||||
const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.getEvents(), 1)));
|
||||
expect(notes.map((note) => note._tag)).toEqual(["ToolCallUpdated"]);
|
||||
const toolCall = notes[0];
|
||||
expect(toolCall?._tag).toBe("ToolCallUpdated");
|
||||
if (toolCall?._tag === "ToolCallUpdated") {
|
||||
expect(toolCall.toolCall.status).toBe("completed");
|
||||
expect(toolCall.toolCall.title).toBe("Read file");
|
||||
const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.getEvents(), 3)));
|
||||
expect(notes.map((note) => note._tag)).toEqual([
|
||||
"ToolCallUpdated",
|
||||
"ToolCallUpdated",
|
||||
"ToolCallUpdated",
|
||||
]);
|
||||
const toolCalls = notes.flatMap((note) =>
|
||||
note._tag === "ToolCallUpdated" ? [note.toolCall] : [],
|
||||
);
|
||||
expect(toolCalls.map((toolCall) => toolCall.status)).toEqual([
|
||||
"pending",
|
||||
"inProgress",
|
||||
"completed",
|
||||
]);
|
||||
for (const toolCall of toolCalls) {
|
||||
expect(toolCall.title).toBe("Read file");
|
||||
}
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
parseSessionUpdateEvent,
|
||||
sessionUpdateIsReplay,
|
||||
syntheticLoadSessionResponseFromInitialize,
|
||||
toolCallProgressLength,
|
||||
type AcpToolCallState,
|
||||
} from "./AcpRuntimeModel.ts";
|
||||
|
||||
@@ -542,6 +543,130 @@ describe("AcpRuntimeModel", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps a retained tail on the original text entries around non-text content", () => {
|
||||
const prefix = "a".repeat(4_000);
|
||||
const suffix = "b".repeat(5_000);
|
||||
const { events } = parseSessionUpdateEvent({
|
||||
sessionId: "session-1",
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId: "tool-1",
|
||||
kind: "edit",
|
||||
status: "in_progress",
|
||||
content: [
|
||||
{ type: "content", content: { type: "text", text: prefix } },
|
||||
{ type: "diff", path: "/repo/file.ts", oldText: "before", newText: "after" },
|
||||
{ type: "content", content: { type: "text", text: suffix } },
|
||||
],
|
||||
},
|
||||
} satisfies EffectAcpSchema.SessionNotification);
|
||||
|
||||
const event = events[0];
|
||||
if (event?._tag !== "ToolCallUpdated") {
|
||||
throw new Error("expected a ToolCallUpdated event");
|
||||
}
|
||||
const content = event.toolCall.data.content as ReadonlyArray<EffectAcpSchema.ToolCallContent>;
|
||||
expect(content).toHaveLength(3);
|
||||
const firstText = content[0];
|
||||
if (firstText?.type !== "content" || firstText.content.type !== "text") {
|
||||
throw new Error("expected a bounded prefix text entry");
|
||||
}
|
||||
expect(firstText.content.text.startsWith("[Earlier output truncated]")).toBe(true);
|
||||
expect(firstText.content.text.endsWith("a".repeat(100))).toBe(true);
|
||||
expect(content[1]).toEqual({
|
||||
type: "diff",
|
||||
path: "/repo/file.ts",
|
||||
oldText: "before",
|
||||
newText: "after",
|
||||
});
|
||||
expect(content[2]).toEqual({
|
||||
type: "content",
|
||||
content: { type: "text", text: suffix },
|
||||
});
|
||||
});
|
||||
|
||||
it("bounds oversized whitespace-only tool call content that has no trimmed text", () => {
|
||||
// Whitespace-only entries are skipped when extracting display text (`chunks.length === 0`)
|
||||
// and used to be returned unchanged, which let a redrawing terminal persist unbounded
|
||||
// buffers on `toolCall.data.content` and `rawPayload`.
|
||||
const hugeWhitespace = " \n\t".repeat(30_000);
|
||||
expect(hugeWhitespace.length).toBeGreaterThan(60_000);
|
||||
|
||||
const { events } = parseSessionUpdateEvent({
|
||||
sessionId: "session-1",
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId: "tool-1",
|
||||
kind: "other",
|
||||
status: "in_progress",
|
||||
content: [{ type: "content", content: { type: "text", text: hugeWhitespace } }],
|
||||
},
|
||||
} satisfies EffectAcpSchema.SessionNotification);
|
||||
|
||||
const event = events[0];
|
||||
if (event?._tag !== "ToolCallUpdated") {
|
||||
throw new Error("expected a ToolCallUpdated event");
|
||||
}
|
||||
|
||||
expect(event.toolCall.detail).toBeUndefined();
|
||||
const content = event.toolCall.data.content as ReadonlyArray<EffectAcpSchema.ToolCallContent>;
|
||||
const textEntry = content[0];
|
||||
if (textEntry?.type !== "content" || textEntry.content.type !== "text") {
|
||||
throw new Error("expected a bounded text entry");
|
||||
}
|
||||
expect(textEntry.content.text.length).toBeLessThan(8_100);
|
||||
expect(textEntry.content.text.startsWith("[Earlier output truncated]")).toBe(true);
|
||||
|
||||
const rawUpdate = (
|
||||
event.rawPayload as {
|
||||
readonly update: {
|
||||
readonly content: ReadonlyArray<{ readonly content: { text: string } }>;
|
||||
};
|
||||
}
|
||||
).update;
|
||||
expect(rawUpdate.content[0]?.content.text.length).toBeLessThan(8_100);
|
||||
expect(JSON.stringify(event).length).toBeLessThan(hugeWhitespace.length);
|
||||
});
|
||||
|
||||
it("bounds oversized whitespace-padded text entries even when trimmed content fits", () => {
|
||||
const padded = `${" ".repeat(40_000)}ok${" ".repeat(40_000)}`;
|
||||
expect(padded.length).toBeGreaterThan(60_000);
|
||||
|
||||
const { events } = parseSessionUpdateEvent({
|
||||
sessionId: "session-1",
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId: "tool-1",
|
||||
kind: "other",
|
||||
status: "in_progress",
|
||||
content: [{ type: "content", content: { type: "text", text: padded } }],
|
||||
},
|
||||
} satisfies EffectAcpSchema.SessionNotification);
|
||||
|
||||
const event = events[0];
|
||||
if (event?._tag !== "ToolCallUpdated") {
|
||||
throw new Error("expected a ToolCallUpdated event");
|
||||
}
|
||||
|
||||
expect(event.toolCall.detail).toBe("ok");
|
||||
const content = event.toolCall.data.content as ReadonlyArray<EffectAcpSchema.ToolCallContent>;
|
||||
const textEntry = content[0];
|
||||
if (textEntry?.type !== "content" || textEntry.content.type !== "text") {
|
||||
throw new Error("expected a bounded text entry");
|
||||
}
|
||||
expect(textEntry.content.text).toBe("ok");
|
||||
|
||||
const rawUpdate = (
|
||||
event.rawPayload as {
|
||||
readonly update: {
|
||||
readonly content: ReadonlyArray<{ readonly content: { text: string } }>;
|
||||
};
|
||||
}
|
||||
).update;
|
||||
expect(rawUpdate.content[0]?.content.text).toBe("ok");
|
||||
expect(JSON.stringify(event).length).toBeLessThan(padded.length);
|
||||
});
|
||||
|
||||
describe("decideToolCallUpdateEmission", () => {
|
||||
const toolCall = (detail: string | undefined, status?: AcpToolCallState["status"]) =>
|
||||
({
|
||||
@@ -552,6 +677,17 @@ describe("AcpRuntimeModel", () => {
|
||||
data: {},
|
||||
}) satisfies AcpToolCallState;
|
||||
|
||||
it("emits the first in-progress tool_call even when it has no detail", () => {
|
||||
expect(
|
||||
decideToolCallUpdateEmission({
|
||||
previous: undefined,
|
||||
next: { toolCallId: "tool-1", title: "Grok Tool", status: "pending", data: {} },
|
||||
lastEmittedDetailLength: undefined,
|
||||
skippedSinceEmit: 0,
|
||||
}),
|
||||
).toEqual({ emit: true, skippedSinceEmit: 0 });
|
||||
});
|
||||
|
||||
it("always emits terminal (completed/failed) status updates regardless of growth", () => {
|
||||
expect(
|
||||
decideToolCallUpdateEmission({
|
||||
@@ -573,16 +709,66 @@ describe("AcpRuntimeModel", () => {
|
||||
});
|
||||
|
||||
it("skips updates whose bounded detail did not change", () => {
|
||||
const previous = toolCall("frame 1", "inProgress");
|
||||
expect(
|
||||
decideToolCallUpdateEmission({
|
||||
previous: toolCall("frame 1", "inProgress"),
|
||||
next: toolCall("frame 1", "inProgress"),
|
||||
previous,
|
||||
next: previous,
|
||||
lastEmittedDetailLength: 7,
|
||||
skippedSinceEmit: 0,
|
||||
}),
|
||||
).toEqual({ emit: false, skippedSinceEmit: 0 });
|
||||
});
|
||||
|
||||
it("coalesces command-tool updates whose content grew while detail stayed the command", () => {
|
||||
const commandCall = (stdout: string): AcpToolCallState => ({
|
||||
toolCallId: "tool-1",
|
||||
title: "Ran command",
|
||||
status: "inProgress",
|
||||
command: "ls",
|
||||
detail: "ls",
|
||||
data: {
|
||||
command: "ls",
|
||||
content: [{ type: "content", content: { type: "text", text: stdout } }],
|
||||
},
|
||||
});
|
||||
|
||||
let previous: AcpToolCallState | undefined;
|
||||
let lastEmittedDetailLength: number | undefined;
|
||||
let skippedSinceEmit = 0;
|
||||
const emissions: Array<boolean> = [];
|
||||
|
||||
for (let i = 1; i <= 12; i += 1) {
|
||||
const next = commandCall("x".repeat(i));
|
||||
const decision = decideToolCallUpdateEmission({
|
||||
previous,
|
||||
next,
|
||||
lastEmittedDetailLength,
|
||||
skippedSinceEmit,
|
||||
});
|
||||
emissions.push(decision.emit);
|
||||
skippedSinceEmit = decision.skippedSinceEmit;
|
||||
if (decision.emit) {
|
||||
lastEmittedDetailLength = toolCallProgressLength(next);
|
||||
}
|
||||
previous = next;
|
||||
}
|
||||
|
||||
const emittedIndices = emissions.flatMap((emitted, index) => (emitted ? [index + 1] : []));
|
||||
expect(emittedIndices).toEqual([1, 11]);
|
||||
});
|
||||
|
||||
it("emits pending to inProgress status changes even when detail and output are unchanged", () => {
|
||||
expect(
|
||||
decideToolCallUpdateEmission({
|
||||
previous: toolCall("same", "pending"),
|
||||
next: toolCall("same", "inProgress"),
|
||||
lastEmittedDetailLength: 4,
|
||||
skippedSinceEmit: 0,
|
||||
}),
|
||||
).toEqual({ emit: true, skippedSinceEmit: 0 });
|
||||
});
|
||||
|
||||
it("emits immediately when the title changes, even with no growth", () => {
|
||||
const decision = decideToolCallUpdateEmission({
|
||||
previous: { toolCallId: "tool-1", title: "Reading file", detail: "x", data: {} },
|
||||
|
||||
@@ -316,6 +316,32 @@ function toolCallContentText(entry: EffectAcpSchema.ToolCallContent): string | u
|
||||
return entry.content.text;
|
||||
}
|
||||
|
||||
// Trim is used for display `text`, so whitespace-only (or whitespace-padded) entries never
|
||||
// contribute to `chunks` and used to take the early returns with the original array. Bound
|
||||
// each text entry independently so those paths cannot persist an unbounded terminal buffer
|
||||
// on `toolCall.data.content` / `rawPayload`.
|
||||
function boundToolCallContentEntries(
|
||||
content: ReadonlyArray<EffectAcpSchema.ToolCallContent>,
|
||||
): ReadonlyArray<EffectAcpSchema.ToolCallContent> {
|
||||
let changed = false;
|
||||
const bounded = content.map((entry) => {
|
||||
const text = toolCallContentText(entry);
|
||||
if (text === undefined || text.length <= TOOL_CALL_CONTENT_MAX_CHARS) {
|
||||
return entry;
|
||||
}
|
||||
changed = true;
|
||||
const trimmed = text.trim();
|
||||
return {
|
||||
type: "content",
|
||||
content: {
|
||||
type: "text",
|
||||
text: boundToolCallOutputText(trimmed.length > 0 ? trimmed : text),
|
||||
},
|
||||
} as const;
|
||||
});
|
||||
return changed ? bounded : content;
|
||||
}
|
||||
|
||||
function extractTextContentFromToolCallContent(
|
||||
content: ReadonlyArray<EffectAcpSchema.ToolCallContent> | null | undefined,
|
||||
): ExtractedToolCallContent {
|
||||
@@ -330,31 +356,74 @@ function extractTextContentFromToolCallContent(
|
||||
}
|
||||
}
|
||||
if (chunks.length === 0) {
|
||||
return { text: undefined, content };
|
||||
return { text: undefined, content: boundToolCallContentEntries(content) };
|
||||
}
|
||||
const joined = chunks.join("\n");
|
||||
if (joined.length <= TOOL_CALL_CONTENT_MAX_CHARS) {
|
||||
return { text: joined, content };
|
||||
return { text: joined, content: boundToolCallContentEntries(content) };
|
||||
}
|
||||
const bounded = boundToolCallOutputText(joined);
|
||||
// Collapse the text entries into a single bounded one at the final contributing text entry,
|
||||
// and leave every other entry kind (diffs, images, resource links) in its original relative
|
||||
// order. The retained tail came from that text entry, so placing it there also preserves its
|
||||
// ordering relative to interleaved non-text content and ignores later blank text entries.
|
||||
const lastContributingTextIndex = content.reduce(
|
||||
(lastIndex, entry, index) => (toolCallContentText(entry)?.trim() ? index : lastIndex),
|
||||
-1,
|
||||
);
|
||||
const boundedContent = content.flatMap((entry, index) => {
|
||||
const tail = joined.slice(joined.length - TOOL_CALL_CONTENT_MAX_CHARS);
|
||||
return {
|
||||
text: bounded,
|
||||
content: distributeRetainedTailAcrossContent(content, tail),
|
||||
};
|
||||
}
|
||||
|
||||
// Walk the original text entries from the joined tail window so a retained slice that
|
||||
// spans entries around an image/diff stays on those entries. Non-text kinds keep their
|
||||
// relative order; blank text entries are dropped; the truncation marker is prepended to
|
||||
// the first remaining text entry.
|
||||
function distributeRetainedTailAcrossContent(
|
||||
content: ReadonlyArray<EffectAcpSchema.ToolCallContent>,
|
||||
tail: string,
|
||||
): ReadonlyArray<EffectAcpSchema.ToolCallContent> {
|
||||
const textRanges: Array<
|
||||
| {
|
||||
readonly start: number;
|
||||
readonly end: number;
|
||||
readonly text: string;
|
||||
}
|
||||
| undefined
|
||||
> = Array.from({ length: content.length });
|
||||
let offset = 0;
|
||||
let seenText = false;
|
||||
for (const [index, entry] of content.entries()) {
|
||||
const text = toolCallContentText(entry)?.trim();
|
||||
if (!text) {
|
||||
continue;
|
||||
}
|
||||
if (seenText) {
|
||||
offset += 1;
|
||||
}
|
||||
seenText = true;
|
||||
const start = offset;
|
||||
const end = offset + text.length;
|
||||
textRanges[index] = { start, end, text };
|
||||
offset = end;
|
||||
}
|
||||
const tailStart = Math.max(0, offset - tail.length);
|
||||
let markerPending = true;
|
||||
return content.flatMap((entry, index) => {
|
||||
if (toolCallContentText(entry) === undefined) {
|
||||
return [entry];
|
||||
}
|
||||
if (index !== lastContributingTextIndex) {
|
||||
const range = textRanges[index];
|
||||
if (range === undefined) {
|
||||
return [];
|
||||
}
|
||||
return [{ type: "content", content: { type: "text", text: bounded } } as const];
|
||||
const overlapStart = Math.max(range.start, tailStart);
|
||||
const overlapEnd = Math.min(range.end, offset);
|
||||
if (overlapEnd <= overlapStart) {
|
||||
return [];
|
||||
}
|
||||
let piece = range.text.slice(overlapStart - range.start, overlapEnd - range.start);
|
||||
if (markerPending) {
|
||||
piece = `${TOOL_CALL_CONTENT_TRUNCATION_MARKER}${piece}`;
|
||||
markerPending = false;
|
||||
}
|
||||
return [{ type: "content", content: { type: "text", text: piece } } as const];
|
||||
});
|
||||
return { text: bounded, content: boundedContent };
|
||||
}
|
||||
|
||||
function normalizeToolKind(kind: unknown): string | undefined {
|
||||
@@ -518,6 +587,42 @@ export interface AcpToolCallEmitDecision {
|
||||
readonly skippedSinceEmit: number;
|
||||
}
|
||||
|
||||
function toolCallOutputUnchanged(previous: AcpToolCallState, next: AcpToolCallState): boolean {
|
||||
return (
|
||||
previous.data.content === next.data.content && previous.data.rawOutput === next.data.rawOutput
|
||||
);
|
||||
}
|
||||
|
||||
// Command tools keep `detail` equal to the command, so live stdout lives on
|
||||
// `data.content` / `data.rawOutput`. Measure that too, otherwise coalescing never
|
||||
// sees growth and in-progress output is held until completed/failed.
|
||||
export function toolCallProgressLength(state: AcpToolCallState): number {
|
||||
let contentChars = 0;
|
||||
const content = state.data.content;
|
||||
if (Array.isArray(content)) {
|
||||
for (const entry of content) {
|
||||
if (!isRecord(entry)) {
|
||||
continue;
|
||||
}
|
||||
const text = toolCallContentText(entry as EffectAcpSchema.ToolCallContent);
|
||||
if (text) {
|
||||
contentChars += text.length;
|
||||
}
|
||||
}
|
||||
}
|
||||
let rawOutputChars = 0;
|
||||
const rawOutput = state.data.rawOutput;
|
||||
if (isRecord(rawOutput)) {
|
||||
for (const field of RAW_OUTPUT_TEXT_FIELDS) {
|
||||
const value = rawOutput[field];
|
||||
if (typeof value === "string") {
|
||||
rawOutputChars += value.length;
|
||||
}
|
||||
}
|
||||
}
|
||||
return Math.max(state.detail?.length ?? 0, contentChars, rawOutputChars);
|
||||
}
|
||||
|
||||
export function decideToolCallUpdateEmission(
|
||||
input: AcpToolCallEmitDecisionInput,
|
||||
): AcpToolCallEmitDecision {
|
||||
@@ -525,19 +630,16 @@ export function decideToolCallUpdateEmission(
|
||||
if (next.status === "completed" || next.status === "failed") {
|
||||
return { emit: true, skippedSinceEmit: 0 };
|
||||
}
|
||||
if (!next.detail) {
|
||||
return { emit: false, skippedSinceEmit };
|
||||
}
|
||||
if (previous === undefined || previous.title !== next.title) {
|
||||
if (previous === undefined || previous.title !== next.title || previous.status !== next.status) {
|
||||
return { emit: true, skippedSinceEmit: 0 };
|
||||
}
|
||||
if (previous.detail === next.detail) {
|
||||
if (previous.detail === next.detail && toolCallOutputUnchanged(previous, next)) {
|
||||
return { emit: false, skippedSinceEmit };
|
||||
}
|
||||
const progressLength = toolCallProgressLength(next);
|
||||
const grewMeaningfully =
|
||||
lastEmittedDetailLength === undefined ||
|
||||
Math.abs(next.detail.length - lastEmittedDetailLength) >=
|
||||
TOOL_CALL_UPDATE_MIN_DETAIL_GROWTH_CHARS;
|
||||
Math.abs(progressLength - lastEmittedDetailLength) >= TOOL_CALL_UPDATE_MIN_DETAIL_GROWTH_CHARS;
|
||||
if (grewMeaningfully || skippedSinceEmit + 1 >= TOOL_CALL_UPDATE_COALESCE_LIMIT) {
|
||||
return { emit: true, skippedSinceEmit: 0 };
|
||||
}
|
||||
|
||||
@@ -27,6 +27,7 @@ import {
|
||||
extractModelConfigId,
|
||||
findSessionConfigOption,
|
||||
mergeToolCallState,
|
||||
toolCallProgressLength,
|
||||
parseSessionModeState,
|
||||
parseSessionUpdateEvent,
|
||||
sessionUpdateIsReplay,
|
||||
@@ -233,6 +234,7 @@ export class AcpSessionRuntime extends Context.Service<
|
||||
*/
|
||||
readonly setSessionModel: (
|
||||
modelId: string,
|
||||
meta?: EffectAcpSchema.SetSessionModelRequest["_meta"],
|
||||
) => Effect.Effect<EffectAcpSchema.SetSessionModelResponse, EffectAcpErrors.AcpError>;
|
||||
/**
|
||||
* Sends a generic ACP extension request and records it through the request logger.
|
||||
@@ -796,12 +798,13 @@ export const make = (
|
||||
Effect.flatMap((started) => setConfigOption(started.modelConfigId ?? "model", model)),
|
||||
Effect.asVoid,
|
||||
),
|
||||
setSessionModel: (modelId) =>
|
||||
setSessionModel: (modelId, meta) =>
|
||||
getStartedState.pipe(
|
||||
Effect.flatMap((started) => {
|
||||
const requestPayload = {
|
||||
sessionId: started.sessionId,
|
||||
modelId,
|
||||
...(meta !== undefined ? { _meta: meta } : {}),
|
||||
} satisfies EffectAcpSchema.SetSessionModelRequest;
|
||||
return runLoggedRequest(
|
||||
"session/set_model",
|
||||
@@ -893,7 +896,7 @@ const handleSessionUpdate = ({
|
||||
next.set(nextToolCall.toolCallId, {
|
||||
state: nextToolCall,
|
||||
lastEmittedDetailLength: decision.emit
|
||||
? nextToolCall.detail?.length
|
||||
? toolCallProgressLength(nextToolCall)
|
||||
: tracked?.lastEmittedDetailLength,
|
||||
skippedSinceEmit: decision.skippedSinceEmit,
|
||||
});
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/**
|
||||
* Optional integration check against a real `grok agent stdio` install.
|
||||
* Enable with: T3_GROK_ACP_PROBE=1 bun run test GrokAcpCliProbe
|
||||
* Enable with: T3_GROK_ACP_PROBE=1 vp test run GrokAcpCliProbe
|
||||
* Set T3_GROK_LIVE_TURN=1 to also send a small prompt to the real model.
|
||||
*
|
||||
* The probe assumes either `XAI_API_KEY` is set in the environment or
|
||||
* the user has previously run `grok login`. Without credentials the
|
||||
@@ -10,6 +11,10 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { describe, expect } from "vite-plus/test";
|
||||
|
||||
@@ -66,4 +71,60 @@ describe.runIf(process.env.T3_GROK_ACP_PROBE === "1")("Grok ACP CLI probe", () =
|
||||
yield* runtime.setSessionModel(currentModelId);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("session/set_model accepts advertised reasoning effort metadata", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* makeProbeRuntime;
|
||||
const started = yield* runtime.start();
|
||||
const modelState = started.sessionSetupResult.models;
|
||||
const currentModelId = modelState?.currentModelId.trim();
|
||||
expect(currentModelId).toBeDefined();
|
||||
if (!currentModelId) return;
|
||||
|
||||
const currentModel = modelState?.availableModels.find(
|
||||
(model) => model.modelId.trim() === currentModelId,
|
||||
);
|
||||
const reasoningEffort = currentModel?._meta?.reasoningEffort;
|
||||
expect(typeof reasoningEffort).toBe("string");
|
||||
if (typeof reasoningEffort !== "string") return;
|
||||
|
||||
yield* runtime.setSessionModel(currentModelId, { reasoningEffort });
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect.skipIf(process.env.T3_GROK_LIVE_TURN !== "1")(
|
||||
"finishes a real Grok turn and streams its answer",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const cwd = yield* fileSystem.makeTempDirectoryScoped();
|
||||
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const runtime = yield* makeGrokAcpRuntime({
|
||||
grokSettings: { binaryPath: "grok" },
|
||||
environment: process.env,
|
||||
childProcessSpawner,
|
||||
cwd,
|
||||
runtimeMode: "approval-required",
|
||||
clientInfo: { name: "t3-grok-probe", version: "0.0.0" },
|
||||
});
|
||||
yield* runtime.start();
|
||||
const chunks: string[] = [];
|
||||
const events = yield* Stream.runForEach(runtime.getEvents(), (event) => {
|
||||
if (event._tag === "EventStreamBarrier") {
|
||||
return Deferred.succeed(event.acknowledge, undefined);
|
||||
}
|
||||
if (event._tag === "ContentDelta") {
|
||||
chunks.push(event.text);
|
||||
}
|
||||
return Effect.void;
|
||||
}).pipe(Effect.forkChild);
|
||||
const result = yield* runtime.prompt({
|
||||
prompt: [{ type: "text", text: "Reply exactly GROK_T3_OK. Do not use any tools." }],
|
||||
});
|
||||
yield* runtime.drainEvents;
|
||||
expect(result.stopReason).toBe("end_turn");
|
||||
expect(chunks.join("")).toContain("GROK_T3_OK");
|
||||
yield* Fiber.interrupt(events);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
});
|
||||
@@ -5,6 +5,8 @@ import * as EffectAcpErrors from "effect-acp/errors";
|
||||
import {
|
||||
applyGrokAcpModelSelection,
|
||||
buildGrokAcpSpawnInput,
|
||||
grokAcpSpawnArgs,
|
||||
isValidGrokReasoningEffortToken,
|
||||
resolveGrokAcpBaseModelId,
|
||||
} from "./GrokAcpSupport.ts";
|
||||
|
||||
@@ -16,6 +18,35 @@ describe("resolveGrokAcpBaseModelId", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("grokAcpSpawnArgs", () => {
|
||||
it("inherits the Grok CLI config when no T3 runtime mode is set", () => {
|
||||
expect(grokAcpSpawnArgs()).toEqual(["agent", "stdio"]);
|
||||
});
|
||||
|
||||
it("forces Grok to ask when T3 is Supervised", () => {
|
||||
expect(grokAcpSpawnArgs("approval-required")).toEqual([
|
||||
"--permission-mode",
|
||||
"default",
|
||||
"agent",
|
||||
"stdio",
|
||||
]);
|
||||
});
|
||||
|
||||
it("maps Full access to Grok always-approve", () => {
|
||||
expect(grokAcpSpawnArgs("full-access")).toEqual(["agent", "--always-approve", "stdio"]);
|
||||
});
|
||||
|
||||
it("maps Auto-accept edits and Auto onto Grok permission modes", () => {
|
||||
expect(grokAcpSpawnArgs("auto-accept-edits")).toEqual([
|
||||
"--permission-mode",
|
||||
"acceptEdits",
|
||||
"agent",
|
||||
"stdio",
|
||||
]);
|
||||
expect(grokAcpSpawnArgs("auto")).toEqual(["--permission-mode", "auto", "agent", "stdio"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildGrokAcpSpawnInput", () => {
|
||||
it("passes the T3 Code referrer through Grok OAuth env", () => {
|
||||
const spawn = buildGrokAcpSpawnInput({ binaryPath: "/usr/local/bin/grok" }, "/tmp/project", {
|
||||
@@ -33,15 +64,38 @@ describe("buildGrokAcpSpawnInput", () => {
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("puts Supervised on the Grok argv so config always-approve cannot win", () => {
|
||||
const spawn = buildGrokAcpSpawnInput(
|
||||
{ binaryPath: "/usr/local/bin/grok" },
|
||||
"/tmp/project",
|
||||
undefined,
|
||||
"approval-required",
|
||||
);
|
||||
expect(spawn.args).toEqual(["--permission-mode", "default", "agent", "stdio"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("isValidGrokReasoningEffortToken", () => {
|
||||
it("accepts future ACP tokens and rejects malformed metadata values", () => {
|
||||
expect(isValidGrokReasoningEffortToken("xhigh")).toBe(true);
|
||||
expect(isValidGrokReasoningEffortToken("turbo_v2")).toBe(true);
|
||||
expect(isValidGrokReasoningEffortToken("not a token")).toBe(false);
|
||||
expect(isValidGrokReasoningEffortToken("-leading-dash")).toBe(false);
|
||||
expect(isValidGrokReasoningEffortToken("x".repeat(33))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("applyGrokAcpModelSelection", () => {
|
||||
const makeRecordingRuntime = (failure?: EffectAcpErrors.AcpError) => {
|
||||
const modelCalls: Array<string> = [];
|
||||
const modelCalls: Array<{
|
||||
modelId: string;
|
||||
meta?: { readonly [key: string]: unknown } | null;
|
||||
}> = [];
|
||||
const runtime = {
|
||||
setSessionModel: (modelId: string) =>
|
||||
setSessionModel: (modelId: string, meta?: { readonly [key: string]: unknown } | null) =>
|
||||
Effect.gen(function* () {
|
||||
modelCalls.push(modelId);
|
||||
modelCalls.push(meta === undefined ? { modelId } : { modelId, meta });
|
||||
if (failure) return yield* failure;
|
||||
return {};
|
||||
}),
|
||||
@@ -58,11 +112,58 @@ describe("applyGrokAcpModelSelection", () => {
|
||||
requestedModelId: "grok-mock-alt",
|
||||
mapError: (cause) => cause.message,
|
||||
});
|
||||
expect(modelCalls).toEqual(["grok-mock-alt"]);
|
||||
expect(modelCalls).toEqual([{ modelId: "grok-mock-alt" }]);
|
||||
expect(result).toBe("grok-mock-alt");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("applies reasoning effort through session/set_model metadata", () =>
|
||||
Effect.gen(function* () {
|
||||
const { runtime, modelCalls } = makeRecordingRuntime();
|
||||
const result = yield* applyGrokAcpModelSelection({
|
||||
runtime,
|
||||
currentModelId: "grok-4.6",
|
||||
currentReasoningEffort: "high",
|
||||
requestedModelId: "grok-4.6",
|
||||
requestedReasoningEffort: "xhigh",
|
||||
mapError: (cause) => cause.message,
|
||||
});
|
||||
expect(modelCalls).toEqual([{ modelId: "grok-4.6", meta: { reasoningEffort: "xhigh" } }]);
|
||||
expect(result).toBe("grok-4.6");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not clear reasoning when same-model selection omits effort", () =>
|
||||
Effect.gen(function* () {
|
||||
const { runtime, modelCalls } = makeRecordingRuntime();
|
||||
const result = yield* applyGrokAcpModelSelection({
|
||||
runtime,
|
||||
currentModelId: "grok-4.6",
|
||||
currentReasoningEffort: "high",
|
||||
requestedModelId: "grok-4.6",
|
||||
requestedReasoningEffort: undefined,
|
||||
mapError: (cause) => cause.message,
|
||||
});
|
||||
expect(modelCalls).toEqual([]);
|
||||
expect(result).toBe("grok-4.6");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("drops malformed effort metadata instead of sending it", () =>
|
||||
Effect.gen(function* () {
|
||||
const { runtime, modelCalls } = makeRecordingRuntime();
|
||||
yield* applyGrokAcpModelSelection({
|
||||
runtime,
|
||||
currentModelId: "grok-4.6",
|
||||
currentReasoningEffort: "high",
|
||||
requestedModelId: "grok-4.6",
|
||||
requestedReasoningEffort: "not a token",
|
||||
mapError: (cause) => cause.message,
|
||||
});
|
||||
expect(modelCalls).toEqual([{ modelId: "grok-4.6" }]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("skips set_model when requested matches current", () =>
|
||||
Effect.gen(function* () {
|
||||
const { runtime, modelCalls } = makeRecordingRuntime();
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { type GrokSettings, ProviderDriverKind } from "@t3tools/contracts";
|
||||
import { type GrokSettings, ProviderDriverKind, type RuntimeMode } from "@t3tools/contracts";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
@@ -27,16 +27,33 @@ interface GrokAcpRuntimeInput extends Omit<
|
||||
readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"];
|
||||
readonly grokSettings: GrokAcpRuntimeGrokSettings | null | undefined;
|
||||
readonly environment?: NodeJS.ProcessEnv;
|
||||
readonly runtimeMode?: RuntimeMode;
|
||||
}
|
||||
|
||||
export function grokAcpSpawnArgs(runtimeMode?: RuntimeMode): ReadonlyArray<string> {
|
||||
switch (runtimeMode) {
|
||||
case "approval-required":
|
||||
return ["--permission-mode", "default", "agent", "stdio"];
|
||||
case "auto-accept-edits":
|
||||
return ["--permission-mode", "acceptEdits", "agent", "stdio"];
|
||||
case "auto":
|
||||
return ["--permission-mode", "auto", "agent", "stdio"];
|
||||
case "full-access":
|
||||
return ["agent", "--always-approve", "stdio"];
|
||||
default:
|
||||
return ["agent", "stdio"];
|
||||
}
|
||||
}
|
||||
|
||||
export function buildGrokAcpSpawnInput(
|
||||
grokSettings: GrokAcpRuntimeGrokSettings | null | undefined,
|
||||
cwd: string,
|
||||
environment?: NodeJS.ProcessEnv,
|
||||
runtimeMode?: RuntimeMode,
|
||||
): AcpSessionRuntime.AcpSpawnInput {
|
||||
return {
|
||||
command: grokSettings?.binaryPath || "grok",
|
||||
args: ["agent", "stdio"],
|
||||
args: [...grokAcpSpawnArgs(runtimeMode)],
|
||||
cwd,
|
||||
env: {
|
||||
...environment,
|
||||
@@ -62,7 +79,12 @@ export const makeGrokAcpRuntime = (
|
||||
const acpContext = yield* Layer.build(
|
||||
AcpSessionRuntime.layer({
|
||||
...input,
|
||||
spawn: buildGrokAcpSpawnInput(input.grokSettings, input.cwd, input.environment),
|
||||
spawn: buildGrokAcpSpawnInput(
|
||||
input.grokSettings,
|
||||
input.cwd,
|
||||
input.environment,
|
||||
input.runtimeMode,
|
||||
),
|
||||
authMethodId: resolveGrokAuthMethodId(input.environment),
|
||||
}).pipe(
|
||||
Layer.provide(
|
||||
@@ -82,6 +104,17 @@ export function resolveGrokAcpBaseModelId(model: string | null | undefined): str
|
||||
return normalizeModelSlug(base, GROK_DRIVER_KIND) ?? "grok-build";
|
||||
}
|
||||
|
||||
const GROK_REASONING_EFFORT_TOKEN = /^[a-z0-9][a-z0-9._-]{0,31}$/i;
|
||||
|
||||
export function isValidGrokReasoningEffortToken(value: string): boolean {
|
||||
return GROK_REASONING_EFFORT_TOKEN.test(value);
|
||||
}
|
||||
|
||||
export function normalizeGrokReasoningEffort(value: string | undefined): string | undefined {
|
||||
const effort = value?.trim();
|
||||
return effort && isValidGrokReasoningEffortToken(effort) ? effort : undefined;
|
||||
}
|
||||
|
||||
export function currentGrokModelIdFromSessionSetup(
|
||||
sessionSetupResult:
|
||||
| EffectAcpSchema.LoadSessionResponse
|
||||
@@ -91,18 +124,57 @@ export function currentGrokModelIdFromSessionSetup(
|
||||
return sessionSetupResult.models?.currentModelId?.trim() || undefined;
|
||||
}
|
||||
|
||||
export function currentGrokReasoningEffortFromSessionSetup(
|
||||
sessionSetupResult:
|
||||
| EffectAcpSchema.LoadSessionResponse
|
||||
| EffectAcpSchema.NewSessionResponse
|
||||
| EffectAcpSchema.ResumeSessionResponse,
|
||||
): string | undefined {
|
||||
const modelState = sessionSetupResult.models;
|
||||
if (!modelState) {
|
||||
return undefined;
|
||||
}
|
||||
const currentModelId = modelState.currentModelId.trim();
|
||||
if (currentModelId.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
const currentModel = modelState.availableModels.find(
|
||||
(model) => model.modelId.trim() === currentModelId,
|
||||
);
|
||||
const reasoningEffort = currentModel?._meta?.reasoningEffort;
|
||||
return typeof reasoningEffort === "string"
|
||||
? normalizeGrokReasoningEffort(reasoningEffort)
|
||||
: undefined;
|
||||
}
|
||||
|
||||
export function applyGrokAcpModelSelection<E>(input: {
|
||||
readonly runtime: Pick<AcpSessionRuntime.AcpSessionRuntime["Service"], "setSessionModel">;
|
||||
readonly currentModelId: string | undefined;
|
||||
readonly currentReasoningEffort?: string | undefined;
|
||||
readonly requestedModelId: string | undefined;
|
||||
readonly requestedReasoningEffort?: string | undefined;
|
||||
readonly mapError: (cause: EffectAcpErrors.AcpError) => E;
|
||||
}): Effect.Effect<string | undefined, E> {
|
||||
const shouldSwitchModel =
|
||||
const modelChanged =
|
||||
input.requestedModelId !== undefined && input.requestedModelId !== input.currentModelId;
|
||||
if (!shouldSwitchModel) {
|
||||
const reasoningProvided = input.requestedReasoningEffort !== undefined;
|
||||
const reasoningEffort = reasoningProvided
|
||||
? normalizeGrokReasoningEffort(input.requestedReasoningEffort)
|
||||
: undefined;
|
||||
const reasoningEffortChanged =
|
||||
reasoningProvided && reasoningEffort !== input.currentReasoningEffort;
|
||||
const targetModelId = input.requestedModelId ?? input.currentModelId;
|
||||
if ((!modelChanged && !reasoningEffortChanged) || targetModelId === undefined) {
|
||||
return Effect.succeed(input.currentModelId);
|
||||
}
|
||||
const reasoningMeta =
|
||||
reasoningProvided && reasoningEffort !== undefined ? { reasoningEffort } : undefined;
|
||||
// When reasoning was explicitly provided but invalid (normalize => undefined), we deliberately
|
||||
// send no meta so the invalid value is dropped rather than forwarded. When reasoning was not
|
||||
// provided at all, we also send no meta, but we only reach this call when the model itself
|
||||
// changed - an omitted reasoning preference must not be treated as an explicit clear of the
|
||||
// CLI-advertised default (e.g. Extra High) on same-model reselections.
|
||||
return input.runtime
|
||||
.setSessionModel(input.requestedModelId)
|
||||
.pipe(Effect.mapError(input.mapError), Effect.as(input.requestedModelId));
|
||||
.setSessionModel(targetModelId, reasoningMeta)
|
||||
.pipe(Effect.mapError(input.mapError), Effect.as(targetModelId));
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off
|
||||
import * as NodeOS from "node:os";
|
||||
import * as NodePath from "node:path";
|
||||
import * as NodeURL from "node:url";
|
||||
|
||||
@@ -9,11 +10,17 @@ import * as Schema from "effect/Schema";
|
||||
import { describe, expect } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
extractGrokPlanMarkdownFromToolCallData,
|
||||
extractXAiAskUserQuestions,
|
||||
extractXAiExitPlanMarkdown,
|
||||
isGrokPlanMarkdownPath,
|
||||
makeXAiAskUserQuestionCancelledResponse,
|
||||
makeXAiAskUserQuestionResponse,
|
||||
makeXAiExitPlanModeCapturedResponse,
|
||||
makeXAiPromptCompletionRuntime,
|
||||
XAI_EMPTY_PLAN_MARKDOWN,
|
||||
XAiAskUserQuestionRequest,
|
||||
XAiExitPlanModeRequest,
|
||||
} from "./XAiAcpExtension.ts";
|
||||
import * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
|
||||
|
||||
@@ -299,6 +306,27 @@ describe("XAiAcpExtension", () => {
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("fails a hung standard prompt from an xAI rate-limit completion", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* makePromptCompletionRuntime({
|
||||
T3_ACP_EMIT_XAI_RATE_LIMIT_THEN_HANG: "1",
|
||||
});
|
||||
yield* runtime.start();
|
||||
|
||||
const error = yield* Effect.flip(
|
||||
runtime.prompt({
|
||||
prompt: [{ type: "text", text: "hi" }],
|
||||
}),
|
||||
);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
_tag: "AcpRequestError",
|
||||
code: -32003,
|
||||
errorMessage: "Grok usage limit reached. Try again later.",
|
||||
});
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("ignores stale xAI completion from an already settled prompt", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* makePromptCompletionRuntime({
|
||||
@@ -329,4 +357,170 @@ describe("XAiAcpExtension", () => {
|
||||
});
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it("extracts plan markdown from exit_plan_mode payloads", () => {
|
||||
const decode = Schema.decodeUnknownSync(XAiExitPlanModeRequest);
|
||||
const direct = decode({
|
||||
sessionId: "session-1",
|
||||
toolCallId: "exit-1",
|
||||
planContent: "# Plan\n\n- do the thing\n",
|
||||
});
|
||||
expect(extractXAiExitPlanMarkdown(direct)).toBe("# Plan\n\n- do the thing");
|
||||
|
||||
const wrapped = decode({
|
||||
method: "_x.ai/exit_plan_mode",
|
||||
params: {
|
||||
sessionId: "session-1",
|
||||
toolCallId: "exit-1",
|
||||
planContent: null,
|
||||
},
|
||||
});
|
||||
expect(extractXAiExitPlanMarkdown(wrapped, " # fallback plan ")).toBe("# fallback plan");
|
||||
expect(extractXAiExitPlanMarkdown(wrapped, "")).toBe(XAI_EMPTY_PLAN_MARKDOWN);
|
||||
expect(extractXAiExitPlanMarkdown(wrapped)).toBe(XAI_EMPTY_PLAN_MARKDOWN);
|
||||
});
|
||||
|
||||
it("builds an abandoned exit_plan_mode response that captures the plan", () => {
|
||||
expect(makeXAiExitPlanModeCapturedResponse()).toEqual({
|
||||
outcome: "abandoned",
|
||||
feedback:
|
||||
"The client captured your proposed plan. Stop here and wait for the user's feedback or implementation request in a later turn.",
|
||||
});
|
||||
});
|
||||
|
||||
it("identifies Grok plan.md paths and extracts markdown from tool call data", () => {
|
||||
const linuxHost = { platform: "linux" as const, environment: {} };
|
||||
const windowsHost = { platform: "win32" as const, environment: {} };
|
||||
const grokHomeHost = {
|
||||
platform: "linux" as const,
|
||||
environment: { GROK_HOME: "/opt/grok-data" },
|
||||
};
|
||||
const home = NodeOS.homedir().replace(/\\/g, "/");
|
||||
const sessionPlan = `${home}/.grok/sessions/abc/plan.md`;
|
||||
const nestedSessionPlan = `${home}/.grok/sessions/%2Fhome%2Fproj/019fd20e-c563-70a0-b801-a6bc51815a9b/plan.md`;
|
||||
expect(isGrokPlanMarkdownPath(sessionPlan, linuxHost)).toBe(true);
|
||||
expect(isGrokPlanMarkdownPath(nestedSessionPlan, linuxHost)).toBe(true);
|
||||
expect(isGrokPlanMarkdownPath("~/.grok/sessions/abc/plan.md", linuxHost)).toBe(true);
|
||||
expect(isGrokPlanMarkdownPath("/tmp/mock-home/.grok/sessions/sess/plan.md", linuxHost)).toBe(
|
||||
true,
|
||||
);
|
||||
expect(isGrokPlanMarkdownPath("/home/other/.grok/sessions/sess/plan.md", linuxHost)).toBe(true);
|
||||
expect(isGrokPlanMarkdownPath("/HOME/other/.grok/sessions/sess/plan.md", linuxHost)).toBe(
|
||||
false,
|
||||
);
|
||||
expect(isGrokPlanMarkdownPath("C:/Users/other/.grok/sessions/id/plan.md", windowsHost)).toBe(
|
||||
true,
|
||||
);
|
||||
expect(isGrokPlanMarkdownPath("c:/users/OTHER/.GROK/SESSIONS/id/PLAN.MD", windowsHost)).toBe(
|
||||
true,
|
||||
);
|
||||
expect(
|
||||
isGrokPlanMarkdownPath("C:\\Users\\other\\.grok\\sessions\\id\\plan.md", windowsHost),
|
||||
).toBe(true);
|
||||
expect(isGrokPlanMarkdownPath("/opt/grok-data/sessions/sess/plan.md", grokHomeHost)).toBe(true);
|
||||
expect(
|
||||
isGrokPlanMarkdownPath("/OPT/GROK-DATA/sessions/sess/plan.md", {
|
||||
platform: "win32",
|
||||
environment: { GROK_HOME: "/opt/grok-data" },
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(isGrokPlanMarkdownPath("/OPT/GROK-DATA/sessions/sess/plan.md", grokHomeHost)).toBe(
|
||||
false,
|
||||
);
|
||||
// Workspace plan.md must not be treated as the session plan file.
|
||||
expect(isGrokPlanMarkdownPath("plan.md", linuxHost)).toBe(false);
|
||||
expect(isGrokPlanMarkdownPath("/repo/docs/plan.md", linuxHost)).toBe(false);
|
||||
expect(isGrokPlanMarkdownPath("/tmp/other.md", linuxHost)).toBe(false);
|
||||
expect(isGrokPlanMarkdownPath("/repo/.grok/sessions/example/plan.md", linuxHost)).toBe(false);
|
||||
expect(
|
||||
isGrokPlanMarkdownPath(`${home}/project/.grok/sessions/example/plan.md`, linuxHost),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isGrokPlanMarkdownPath("/home/other/.grok/sessions/../../project/plan.md", linuxHost),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isGrokPlanMarkdownPath("/home/other/.grok/sessions/foo/../../../project/plan.md", linuxHost),
|
||||
).toBe(false);
|
||||
|
||||
expect(
|
||||
extractGrokPlanMarkdownFromToolCallData(
|
||||
{
|
||||
rawInput: {
|
||||
file_path: sessionPlan,
|
||||
content: "# From rawInput\n\n- a\n",
|
||||
},
|
||||
},
|
||||
linuxHost,
|
||||
),
|
||||
).toBe("# From rawInput\n\n- a");
|
||||
|
||||
expect(
|
||||
extractGrokPlanMarkdownFromToolCallData(
|
||||
{
|
||||
content: [
|
||||
{
|
||||
type: "diff",
|
||||
path: sessionPlan,
|
||||
oldText: "",
|
||||
newText: "# From diff\n\n- b\n",
|
||||
},
|
||||
],
|
||||
},
|
||||
linuxHost,
|
||||
),
|
||||
).toBe("# From diff\n\n- b");
|
||||
|
||||
expect(
|
||||
extractGrokPlanMarkdownFromToolCallData(
|
||||
{
|
||||
rawInput: { file_path: sessionPlan, content: "" },
|
||||
content: [
|
||||
{
|
||||
type: "diff",
|
||||
path: sessionPlan,
|
||||
oldText: "",
|
||||
newText: "# From diff after empty rawInput\n",
|
||||
},
|
||||
],
|
||||
},
|
||||
linuxHost,
|
||||
),
|
||||
).toBe("# From diff after empty rawInput");
|
||||
|
||||
expect(
|
||||
extractGrokPlanMarkdownFromToolCallData(
|
||||
{
|
||||
rawInput: { file_path: sessionPlan, content: "" },
|
||||
},
|
||||
linuxHost,
|
||||
),
|
||||
).toBe("");
|
||||
|
||||
expect(
|
||||
extractGrokPlanMarkdownFromToolCallData(
|
||||
{
|
||||
content: [{ type: "diff", path: sessionPlan, oldText: "# old", newText: "" }],
|
||||
},
|
||||
linuxHost,
|
||||
),
|
||||
).toBe("");
|
||||
|
||||
expect(
|
||||
extractGrokPlanMarkdownFromToolCallData(
|
||||
{
|
||||
rawInput: { file_path: "/tmp/readme.md", content: "nope" },
|
||||
},
|
||||
linuxHost,
|
||||
),
|
||||
).toBeUndefined();
|
||||
|
||||
expect(
|
||||
extractGrokPlanMarkdownFromToolCallData(
|
||||
{
|
||||
rawInput: { file_path: "/repo/docs/plan.md", content: "# Project plan\n" },
|
||||
},
|
||||
linuxHost,
|
||||
),
|
||||
).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,11 @@
|
||||
import * as NodeOS from "node:os";
|
||||
|
||||
import type { ProviderUserInputAnswers, UserInputQuestion } from "@t3tools/contracts";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as EffectAcpErrors from "effect-acp/errors";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
|
||||
import type * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
|
||||
@@ -19,11 +22,15 @@ type XAiPromptCompleteNotification = typeof XAiPromptCompleteNotification.Type;
|
||||
interface PendingXAiPromptCompletion {
|
||||
readonly sessionId: string;
|
||||
readonly promptId: string;
|
||||
readonly deferred: Deferred.Deferred<EffectAcpSchema.PromptResponse>;
|
||||
readonly deferred: Deferred.Deferred<
|
||||
EffectAcpSchema.PromptResponse,
|
||||
EffectAcpErrors.AcpRequestError
|
||||
>;
|
||||
}
|
||||
|
||||
const completedXAiPromptIdLimit = 128;
|
||||
const xAiStopReasonMissingMetaKey = "xAiStopReasonMissing";
|
||||
const xAiRateLimitedErrorCode = -32003;
|
||||
|
||||
const XAiAskUserQuestionOption = Schema.Struct({
|
||||
label: Schema.String,
|
||||
@@ -196,6 +203,218 @@ export function makeXAiAskUserQuestionCancelledResponse(): XAiAskUserQuestionCan
|
||||
return { outcome: "cancelled" };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// x.ai/exit_plan_mode — plan approval gate (mirrors Grok Build TUI plan window)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const XAiExitPlanModeParams = Schema.Struct({
|
||||
sessionId: Schema.String,
|
||||
toolCallId: Schema.String,
|
||||
planContent: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
});
|
||||
|
||||
const XAiWrappedExitPlanModeParams = Schema.Struct({
|
||||
method: Schema.Literals(["x.ai/exit_plan_mode", "_x.ai/exit_plan_mode"]),
|
||||
params: XAiExitPlanModeParams,
|
||||
});
|
||||
|
||||
export const XAiExitPlanModeRequest = Schema.Union([
|
||||
XAiExitPlanModeParams,
|
||||
XAiWrappedExitPlanModeParams,
|
||||
]);
|
||||
|
||||
type XAiExitPlanModeRequestParams = typeof XAiExitPlanModeParams.Type;
|
||||
type XAiExitPlanModeRequest = typeof XAiExitPlanModeRequest.Type;
|
||||
|
||||
function unwrapExitPlanModeParams(params: XAiExitPlanModeRequest): XAiExitPlanModeRequestParams {
|
||||
return "params" in params ? params.params : params;
|
||||
}
|
||||
|
||||
/** Empty-state copy when Grok exits plan mode without a plan file. */
|
||||
export const XAI_EMPTY_PLAN_MARKDOWN =
|
||||
"# No plan written yet\n\n(The agent exited plan mode without writing a plan.)";
|
||||
|
||||
export function extractXAiExitPlanMarkdown(
|
||||
params: XAiExitPlanModeRequest,
|
||||
fallback?: string | null,
|
||||
): string {
|
||||
const content = unwrapExitPlanModeParams(params).planContent;
|
||||
const fromRequest = typeof content === "string" ? trimmed(content) : undefined;
|
||||
if (fromRequest) {
|
||||
return fromRequest;
|
||||
}
|
||||
const fromFallback = fallback?.trim();
|
||||
if (fromFallback && fromFallback.length > 0) {
|
||||
return fromFallback;
|
||||
}
|
||||
return XAI_EMPTY_PLAN_MARKDOWN;
|
||||
}
|
||||
|
||||
export type XAiExitPlanModeOutcome = "approved" | "abandoned" | "request_changes";
|
||||
|
||||
export interface XAiExitPlanModeResponse {
|
||||
readonly outcome: XAiExitPlanModeOutcome;
|
||||
readonly feedback?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Client captured the plan for T3's proposed-plan card. Abandon the native
|
||||
* Grok plan-approval gate so the turn unblocks; the user implements via T3 UI.
|
||||
*/
|
||||
export function makeXAiExitPlanModeCapturedResponse(feedback?: string): XAiExitPlanModeResponse {
|
||||
return {
|
||||
outcome: "abandoned",
|
||||
feedback:
|
||||
feedback ??
|
||||
"The client captured your proposed plan. Stop here and wait for the user's feedback or implementation request in a later turn.",
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeFsPath(value: string): string {
|
||||
return value.trim().replace(/\\/g, "/").replace(/\/+$/, "");
|
||||
}
|
||||
|
||||
function pathHasTraversalSegment(normalized: string): boolean {
|
||||
return normalized.split("/").includes("..");
|
||||
}
|
||||
|
||||
function addGrokSessionPrefix(
|
||||
prefixes: Set<string>,
|
||||
homeOrRoot: string,
|
||||
nestedGrokDir: boolean,
|
||||
): void {
|
||||
const root = normalizeFsPath(homeOrRoot);
|
||||
if (!root) {
|
||||
return;
|
||||
}
|
||||
prefixes.add(nestedGrokDir ? `${root}/.grok/sessions/` : `${root}/sessions/`);
|
||||
}
|
||||
|
||||
/** Injected host bits so these helpers stay off `process.platform` / `process.env`. */
|
||||
export interface GrokPlanPathHost {
|
||||
readonly platform: NodeJS.Platform;
|
||||
readonly environment: NodeJS.ProcessEnv;
|
||||
}
|
||||
|
||||
function grokPlanSessionPrefixes(environment: NodeJS.ProcessEnv): ReadonlySet<string> {
|
||||
const prefixes = new Set<string>();
|
||||
addGrokSessionPrefix(prefixes, NodeOS.homedir(), true);
|
||||
addGrokSessionPrefix(prefixes, "~", true);
|
||||
addGrokSessionPrefix(prefixes, environment.HOME ?? "", true);
|
||||
addGrokSessionPrefix(prefixes, environment.USERPROFILE ?? "", true);
|
||||
// ACP mock and isolated Grok spawns use a HOME that is not the server process home.
|
||||
addGrokSessionPrefix(prefixes, "/tmp/mock-home", true);
|
||||
const grokHome = environment.GROK_HOME ?? "";
|
||||
addGrokSessionPrefix(prefixes, grokHome, false);
|
||||
addGrokSessionPrefix(prefixes, grokHome, true);
|
||||
return prefixes;
|
||||
}
|
||||
|
||||
const CANONICAL_HOME_GROK_SESSION_PATH =
|
||||
/^(?:\/home\/[^/]+|\/Users\/[^/]+|[a-zA-Z]:\/Users\/[^/]+)\/\.grok\/sessions\/(?:[^/]+\/)+plan\.md$/;
|
||||
const CASE_INSENSITIVE_CANONICAL_HOME_GROK_SESSION_PATH = new RegExp(
|
||||
CANONICAL_HOME_GROK_SESSION_PATH.source,
|
||||
"i",
|
||||
);
|
||||
|
||||
/**
|
||||
* True when a path is Grok's session plan file under a Grok home
|
||||
* (`~/.grok/sessions/.../plan.md`, `$HOME/.grok/sessions/...`, or `$GROK_HOME/sessions/...`).
|
||||
* Deliberately does not match workspace files named `plan.md` (e.g. docs/plan.md
|
||||
* or a repo-local `.grok/sessions/.../plan.md`).
|
||||
*/
|
||||
export function isGrokPlanMarkdownPath(
|
||||
path: string | undefined | null,
|
||||
host: GrokPlanPathHost,
|
||||
): boolean {
|
||||
if (typeof path !== "string") {
|
||||
return false;
|
||||
}
|
||||
const normalized = path.trim().replace(/\\/g, "/");
|
||||
const win32 = host.platform === "win32";
|
||||
const haystack = win32 ? normalized.toLowerCase() : normalized;
|
||||
if (
|
||||
normalized.length === 0 ||
|
||||
!haystack.endsWith("/plan.md") ||
|
||||
pathHasTraversalSegment(normalized)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
for (const prefix of grokPlanSessionPrefixes(host.environment)) {
|
||||
const needle = win32 ? prefix.toLowerCase() : prefix;
|
||||
if (!haystack.startsWith(needle)) {
|
||||
continue;
|
||||
}
|
||||
const rest = haystack.slice(needle.length);
|
||||
// Session layout: <home>/.grok/sessions/<encoded-cwd>/<session-id>/plan.md
|
||||
if (rest !== "plan.md" && rest.endsWith("plan.md")) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return (
|
||||
win32 ? CASE_INSENSITIVE_CANONICAL_HOME_GROK_SESSION_PATH : CANONICAL_HOME_GROK_SESSION_PATH
|
||||
).test(haystack);
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract plan markdown from a Grok write/edit tool call targeting plan.md.
|
||||
* Used so T3 can show the plan while plan mode is still active (before exit).
|
||||
*/
|
||||
export function extractGrokPlanMarkdownFromToolCallData(
|
||||
data: Record<string, unknown> | undefined,
|
||||
host: GrokPlanPathHost,
|
||||
): string | undefined {
|
||||
if (!data) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
let sawPlanWrite = false;
|
||||
const takePlanText = (
|
||||
value: string | undefined,
|
||||
filePath: string | undefined,
|
||||
): string | undefined => {
|
||||
if (!isGrokPlanMarkdownPath(filePath, host) || value === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
sawPlanWrite = true;
|
||||
const trimmed = value.trim();
|
||||
return trimmed.length > 0 ? trimmed : undefined;
|
||||
};
|
||||
|
||||
const rawInput = data.rawInput;
|
||||
if (isRecord(rawInput)) {
|
||||
const filePath =
|
||||
(typeof rawInput.file_path === "string" ? rawInput.file_path : undefined) ??
|
||||
(typeof rawInput.path === "string" ? rawInput.path : undefined);
|
||||
const content = typeof rawInput.content === "string" ? rawInput.content : undefined;
|
||||
const fromRaw = takePlanText(content, filePath);
|
||||
if (fromRaw !== undefined) {
|
||||
return fromRaw;
|
||||
}
|
||||
}
|
||||
|
||||
const content = data.content;
|
||||
if (Array.isArray(content)) {
|
||||
for (const block of content) {
|
||||
if (!isRecord(block) || block.type !== "diff") {
|
||||
continue;
|
||||
}
|
||||
const path = typeof block.path === "string" ? block.path : undefined;
|
||||
const newText = typeof block.newText === "string" ? block.newText : undefined;
|
||||
const fromDiff = takePlanText(newText, path);
|
||||
if (fromDiff !== undefined) {
|
||||
return fromDiff;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return sawPlanWrite ? "" : undefined;
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds Grok's private prompt-completion fallback around a standards-only ACP runtime.
|
||||
* The underlying runtime remains unaware of xAI methods and metadata.
|
||||
@@ -278,7 +497,7 @@ const registerXAiPromptCompletionFallback = (
|
||||
sessionId: string,
|
||||
promptId: string,
|
||||
) =>
|
||||
Deferred.make<EffectAcpSchema.PromptResponse>().pipe(
|
||||
Deferred.make<EffectAcpSchema.PromptResponse, EffectAcpErrors.AcpRequestError>().pipe(
|
||||
Effect.tap((deferred) =>
|
||||
Ref.update(pendingRef, (pending) => [...pending, { sessionId, promptId, deferred }]),
|
||||
),
|
||||
@@ -287,7 +506,7 @@ const registerXAiPromptCompletionFallback = (
|
||||
|
||||
const unregisterXAiPromptCompletionFallback = (
|
||||
pendingRef: Ref.Ref<ReadonlyArray<PendingXAiPromptCompletion>>,
|
||||
deferred: Deferred.Deferred<EffectAcpSchema.PromptResponse>,
|
||||
deferred: Deferred.Deferred<EffectAcpSchema.PromptResponse, EffectAcpErrors.AcpRequestError>,
|
||||
) => Ref.update(pendingRef, (pending) => pending.filter((entry) => entry.deferred !== deferred));
|
||||
|
||||
const abortPendingPromptCompletions = (
|
||||
@@ -358,13 +577,48 @@ const resolveXAiPromptCompletionFallback = ({
|
||||
return [Effect.void, pending] as const;
|
||||
}
|
||||
return [
|
||||
Deferred.succeed(entry.deferred, promptResponseFromXAi(notification)).pipe(Effect.asVoid),
|
||||
settleXAiPromptCompletion(entry.deferred, notification),
|
||||
[...pending.slice(0, index), ...pending.slice(index + 1)],
|
||||
] as const;
|
||||
}).pipe(Effect.flatten);
|
||||
}),
|
||||
);
|
||||
|
||||
const settleXAiPromptCompletion = (
|
||||
deferred: Deferred.Deferred<EffectAcpSchema.PromptResponse, EffectAcpErrors.AcpRequestError>,
|
||||
notification: XAiPromptCompleteNotification,
|
||||
) => {
|
||||
if (notification.stopReason === "rate_limit") {
|
||||
return Deferred.fail(
|
||||
deferred,
|
||||
new EffectAcpErrors.AcpRequestError({
|
||||
code: xAiRateLimitedErrorCode,
|
||||
errorMessage: "Grok usage limit reached. Try again later.",
|
||||
}),
|
||||
).pipe(Effect.asVoid);
|
||||
}
|
||||
if (notification.stopReason === "error") {
|
||||
return Deferred.fail(
|
||||
deferred,
|
||||
EffectAcpErrors.AcpRequestError.internalError(
|
||||
xAiAgentResultMessage(notification.agentResult) ?? "Grok prompt failed.",
|
||||
),
|
||||
).pipe(Effect.asVoid);
|
||||
}
|
||||
return Deferred.succeed(deferred, promptResponseFromXAi(notification)).pipe(Effect.asVoid);
|
||||
};
|
||||
|
||||
function xAiAgentResultMessage(value: unknown): string | undefined {
|
||||
if (typeof value === "string") {
|
||||
return trimmed(value);
|
||||
}
|
||||
if (value === null || typeof value !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
const message = "message" in value ? value.message : undefined;
|
||||
return typeof message === "string" ? trimmed(message) : undefined;
|
||||
}
|
||||
|
||||
const rememberCompletedXAiPromptId = (
|
||||
completedPromptIdsRef: Ref.Ref<ReadonlyArray<string>>,
|
||||
response: EffectAcpSchema.PromptResponse,
|
||||
|
||||
@@ -8,6 +8,7 @@ import type * as EffectAcpErrors from "effect-acp/errors";
|
||||
|
||||
import { type GrokSettings, type ModelSelection } from "@t3tools/contracts";
|
||||
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||
import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
|
||||
import { extractJsonObject } from "@t3tools/shared/schemaJson";
|
||||
|
||||
import { TextGenerationError } from "@t3tools/contracts";
|
||||
@@ -26,6 +27,7 @@ import {
|
||||
import {
|
||||
applyGrokAcpModelSelection,
|
||||
currentGrokModelIdFromSessionSetup,
|
||||
currentGrokReasoningEffortFromSessionSetup,
|
||||
makeGrokAcpRuntime,
|
||||
resolveGrokAcpBaseModelId,
|
||||
} from "../provider/acp/GrokAcpSupport.ts";
|
||||
@@ -83,10 +85,18 @@ export const makeGrokTextGeneration = Effect.fn("makeGrokTextGeneration")(functi
|
||||
|
||||
const promptResult = yield* Effect.gen(function* () {
|
||||
const started = yield* runtime.start();
|
||||
const requestedReasoningEffort = getModelSelectionStringOptionValue(
|
||||
modelSelection,
|
||||
"reasoningEffort",
|
||||
);
|
||||
yield* applyGrokAcpModelSelection({
|
||||
runtime,
|
||||
currentModelId: currentGrokModelIdFromSessionSetup(started.sessionSetupResult),
|
||||
currentReasoningEffort: currentGrokReasoningEffortFromSessionSetup(
|
||||
started.sessionSetupResult,
|
||||
),
|
||||
requestedModelId: resolvedModel,
|
||||
requestedReasoningEffort,
|
||||
mapError: (cause) =>
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
/**
|
||||
* UsageService - scans provider transcripts and returns priced usage buckets.
|
||||
*
|
||||
* The scan reads the provider CLIs' own session files rather than T3 Code's
|
||||
* orchestration projections, so usage covers turns driven outside T3 Code too.
|
||||
* This is the approach `ccusage` takes.
|
||||
* The scan reads the provider CLIs' own session files (Claude Code, Codex, and
|
||||
* Grok Build) rather than T3 Code's orchestration projections, so usage covers
|
||||
* turns driven outside T3 Code too. This is the approach `ccusage` takes.
|
||||
*
|
||||
* Transcripts are append-only, so parsed records are memoised per file by
|
||||
* `(size, mtime)`. A cold 30-day scan of ~1.4 GB lands around 2-3 seconds; warm
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
type UsageSummaryInput,
|
||||
UsageReadError,
|
||||
} from "@t3tools/contracts";
|
||||
import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Context from "effect/Context";
|
||||
@@ -34,6 +35,7 @@ import * as Schema from "effect/Schema";
|
||||
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
|
||||
|
||||
import { ServerConfig } from "../config.ts";
|
||||
import { expandHomePath } from "../pathExpansion.ts";
|
||||
import * as ServerSettings from "../serverSettings.ts";
|
||||
import { resolveClaudeHomePath } from "../provider/Drivers/ClaudeHome.ts";
|
||||
import { resolveCodexHomeLayout } from "../provider/Drivers/CodexHomeLayout.ts";
|
||||
@@ -123,6 +125,7 @@ export const make = Effect.gen(function* () {
|
||||
const config = yield* ServerConfig;
|
||||
const settingsService = yield* ServerSettings.ServerSettingsService;
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const hostEnvironment = yield* HostProcessEnvironment;
|
||||
|
||||
const fileCache: ScanCache = new Map();
|
||||
let cacheDirty = false;
|
||||
@@ -218,10 +221,22 @@ export const make = Effect.gen(function* () {
|
||||
const claudeHome = yield* resolveClaudeHomePath(settings.providers.claudeAgent);
|
||||
const claudeDir = yield* resolveClaudeTranscriptDir(claudeHome);
|
||||
const codexLayout = yield* resolveCodexHomeLayout(settings.providers.codex);
|
||||
// Grok Settings only expose the binary path; home is `$GROK_HOME` or `~/.grok`.
|
||||
// Empty/whitespace GROK_HOME must fall back: coalescing alone would scan cwd.
|
||||
const grokHomeEnv = hostEnvironment["GROK_HOME"]?.trim() ?? "";
|
||||
const grokHome =
|
||||
grokHomeEnv.length > 0
|
||||
? path.resolve(expandHomePath(grokHomeEnv))
|
||||
: path.join(NodeOS.homedir(), ".grok");
|
||||
|
||||
return [
|
||||
{ provider: "claude" as const, dir: claudeDir },
|
||||
{ provider: "codex" as const, dir: path.join(codexLayout.sharedHomePath, "sessions") },
|
||||
{
|
||||
provider: "grok" as const,
|
||||
dir: path.join(grokHome, "sessions"),
|
||||
fileName: "updates.jsonl",
|
||||
},
|
||||
];
|
||||
});
|
||||
|
||||
@@ -353,7 +368,7 @@ export const make = Effect.gen(function* () {
|
||||
const livePaths = new Set<string>();
|
||||
const walkedRoots: string[] = [];
|
||||
|
||||
for (const { provider, dir } of dirs) {
|
||||
for (const { provider, dir, fileName } of dirs) {
|
||||
const volumeId = yield* Effect.promise(() => readDirectoryVolumeId(dir));
|
||||
const exists = yield* fileSystem
|
||||
.exists(dir)
|
||||
@@ -373,7 +388,9 @@ export const make = Effect.gen(function* () {
|
||||
}
|
||||
|
||||
walkedRoots.push(dir);
|
||||
const files = yield* Effect.promise(() => listTranscriptFiles(dir, windowStartMs));
|
||||
const files = yield* Effect.promise(() =>
|
||||
listTranscriptFiles(dir, windowStartMs, fileName === undefined ? undefined : { fileName }),
|
||||
);
|
||||
let scannedFiles = 0;
|
||||
let skippedFiles = 0;
|
||||
// Distinct per directory. Buckets carry per-cell session counts, but a
|
||||
|
||||
@@ -42,12 +42,21 @@ describe("scan cache round trip", () => {
|
||||
["/a.jsonl", 100, [record(), record({ dedupeKey: "msg_2:", model: "claude-opus-5" })]],
|
||||
["/b.jsonl", 200, [record({ sessionId: "session-b", reportedCostUsd: 1.5 })]],
|
||||
]);
|
||||
original.set("/grok.jsonl", {
|
||||
size: 40,
|
||||
mtimeMs: 300,
|
||||
provider: "grok",
|
||||
records: [
|
||||
record({ provider: "grok", model: "grok-4.5-build", dedupeKey: "s:p:grok-4.5-build" }),
|
||||
],
|
||||
});
|
||||
|
||||
const restored = decodeScanCache(JSON.parse(JSON.stringify(encodeScanCache(original))));
|
||||
|
||||
expect(restored.size).toBe(2);
|
||||
expect(restored.size).toBe(3);
|
||||
expect(restored.get("/a.jsonl")).toEqual(original.get("/a.jsonl"));
|
||||
expect(restored.get("/b.jsonl")).toEqual(original.get("/b.jsonl"));
|
||||
expect(restored.get("/grok.jsonl")).toEqual(original.get("/grok.jsonl"));
|
||||
});
|
||||
|
||||
it("interns repeated model and session strings", () => {
|
||||
|
||||
@@ -134,7 +134,7 @@ export function decodeScanCache(document: unknown): ScanCache {
|
||||
if (typeof raw !== "object" || raw === null) continue;
|
||||
const entry = raw as Partial<SerializedFile>;
|
||||
if (typeof entry.s !== "number" || typeof entry.m !== "number") continue;
|
||||
if (entry.p !== "claude" && entry.p !== "codex") continue;
|
||||
if (entry.p !== "claude" && entry.p !== "codex" && entry.p !== "grok") continue;
|
||||
if (!isRecordArray(entry.r)) continue;
|
||||
|
||||
const provider: UsageProviderKind = entry.p;
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
mightCarryUsage,
|
||||
parseClaudeLine,
|
||||
parseCodexLine,
|
||||
parseGrokLine,
|
||||
type UsageRecord,
|
||||
} from "./usageTranscripts.ts";
|
||||
|
||||
@@ -37,12 +38,18 @@ export interface TranscriptFile {
|
||||
* Errors on individual entries are swallowed: session files rotate and get
|
||||
* removed while the walk is in flight, and a partial listing is far better than
|
||||
* failing the page.
|
||||
*
|
||||
* `fileName` restricts the walk to a single basename (Grok's `updates.jsonl`).
|
||||
* Grok sessions also ship multi-megabyte `chat_history` and `events` logs that
|
||||
* never carry usage, so the basename filter keeps a cold scan off those files.
|
||||
*/
|
||||
export async function listTranscriptFiles(
|
||||
root: string,
|
||||
sinceMs: number,
|
||||
options?: { readonly fileName?: string },
|
||||
): Promise<readonly TranscriptFile[]> {
|
||||
const found: TranscriptFile[] = [];
|
||||
const fileName = options?.fileName;
|
||||
|
||||
const walk = async (dir: string): Promise<void> => {
|
||||
let entries;
|
||||
@@ -57,7 +64,11 @@ export async function listTranscriptFiles(
|
||||
await walk(child);
|
||||
continue;
|
||||
}
|
||||
if (!entry.name.endsWith(".jsonl")) continue;
|
||||
if (fileName !== undefined) {
|
||||
if (entry.name !== fileName) continue;
|
||||
} else if (!entry.name.endsWith(".jsonl")) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
const stats = await NodeFSP.stat(child);
|
||||
if (stats.mtimeMs >= sinceMs) {
|
||||
@@ -129,6 +140,12 @@ export async function readTranscriptRecords(
|
||||
continue;
|
||||
}
|
||||
|
||||
if (provider === "grok") {
|
||||
if (!mightCarryUsage(line, provider)) continue;
|
||||
for (const grokRecord of parseGrokLine(line)) records.push(grokRecord);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!mightCarryUsage(line, provider)) continue;
|
||||
const record = parseClaudeLine(line);
|
||||
if (record !== null) records.push(record);
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
|
||||
import {
|
||||
GROK_COST_USD_TICKS_PER_DOLLAR,
|
||||
initialCodexScanState,
|
||||
parseClaudeLine,
|
||||
parseCodexLine,
|
||||
parseGrokLine,
|
||||
totalTokens,
|
||||
} from "./usageTranscripts.ts";
|
||||
|
||||
@@ -249,3 +251,316 @@ describe("totalTokens", () => {
|
||||
).toBe(100);
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseGrokLine", () => {
|
||||
/** Shaped after a real Grok Build `turn_completed` session update. */
|
||||
function turnCompleted(overrides?: {
|
||||
sessionId?: string;
|
||||
promptId?: string;
|
||||
timestamp?: number;
|
||||
agentTimestampMs?: number;
|
||||
usage?: Record<string, unknown>;
|
||||
modelUsage?: Record<string, Record<string, unknown>> | null;
|
||||
}): string {
|
||||
const modelUsage =
|
||||
overrides && "modelUsage" in overrides
|
||||
? overrides.modelUsage
|
||||
: {
|
||||
"grok-4.5-build": {
|
||||
inputTokens: 20_272,
|
||||
outputTokens: 272,
|
||||
totalTokens: 20_544,
|
||||
cachedReadTokens: 11_264,
|
||||
cacheCreationTokens: 0,
|
||||
reasoningTokens: 180,
|
||||
costUsdTicks: 230_272_000,
|
||||
},
|
||||
};
|
||||
|
||||
return JSON.stringify({
|
||||
timestamp: overrides?.timestamp ?? 1_786_372_566,
|
||||
method: "_x.ai/session/update",
|
||||
params: {
|
||||
sessionId: overrides?.sessionId ?? "019fec1a-12f7-72f2-9b1f-7778a00aea3c",
|
||||
update: {
|
||||
sessionUpdate: "turn_completed",
|
||||
prompt_id: overrides?.promptId ?? "prompt-1",
|
||||
stop_reason: "end_turn",
|
||||
usage: {
|
||||
inputTokens: 20_272,
|
||||
outputTokens: 272,
|
||||
totalTokens: 20_544,
|
||||
cachedReadTokens: 11_264,
|
||||
cacheCreationTokens: 0,
|
||||
reasoningTokens: 180,
|
||||
costUsdTicks: 230_272_000,
|
||||
...(modelUsage === null ? {} : { modelUsage }),
|
||||
...overrides?.usage,
|
||||
},
|
||||
},
|
||||
_meta: {
|
||||
eventId: "event-1",
|
||||
agentTimestampMs: overrides?.agentTimestampMs ?? 1_786_372_566_485,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
it("extracts per-model totals and provider-reported cost ticks", () => {
|
||||
const records = parseGrokLine(turnCompleted());
|
||||
|
||||
expect(records).toHaveLength(1);
|
||||
const [record] = records;
|
||||
expect(record?.provider).toBe("grok");
|
||||
expect(record?.model).toBe("grok-4.5-build");
|
||||
expect(record?.sessionId).toBe("019fec1a-12f7-72f2-9b1f-7778a00aea3c");
|
||||
expect(record?.timestampMs).toBe(1_786_372_566_485);
|
||||
expect(record?.totals).toEqual({
|
||||
uncachedInputTokens: 20_272 - 11_264,
|
||||
cachedInputTokens: 11_264,
|
||||
cacheCreationTokens: 0,
|
||||
outputTokens: 272,
|
||||
reasoningTokens: 180,
|
||||
});
|
||||
expect(record?.reportedCostUsd).toBeCloseTo(230_272_000 / GROK_COST_USD_TICKS_PER_DOLLAR, 12);
|
||||
expect(record?.dedupeKey).toBe("019fec1a-12f7-72f2-9b1f-7778a00aea3c:prompt-1:grok-4.5-build");
|
||||
});
|
||||
|
||||
it("emits one record per model when modelUsage has several entries", () => {
|
||||
const records = parseGrokLine(
|
||||
turnCompleted({
|
||||
modelUsage: {
|
||||
"grok-4.5": {
|
||||
inputTokens: 1000,
|
||||
outputTokens: 50,
|
||||
cachedReadTokens: 400,
|
||||
reasoningTokens: 20,
|
||||
costUsdTicks: 50_000_000,
|
||||
},
|
||||
"grok-composer-2.5-fast": {
|
||||
inputTokens: 200,
|
||||
outputTokens: 30,
|
||||
cachedReadTokens: 100,
|
||||
reasoningTokens: 0,
|
||||
costUsdTicks: 10_000_000,
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
expect(records.map((record) => record.model).toSorted()).toEqual([
|
||||
"grok-4.5",
|
||||
"grok-composer-2.5-fast",
|
||||
]);
|
||||
expect(records.every((record) => record.provider === "grok")).toBe(true);
|
||||
expect(records.find((record) => record.model === "grok-4.5")?.reportedCostUsd).toBeCloseTo(
|
||||
0.005,
|
||||
12,
|
||||
);
|
||||
});
|
||||
|
||||
it("inherits top-level cost ticks for a single model without its own ticks", () => {
|
||||
const records = parseGrokLine(
|
||||
turnCompleted({
|
||||
modelUsage: {
|
||||
"grok-4.5-build": {
|
||||
inputTokens: 1000,
|
||||
outputTokens: 10,
|
||||
cachedReadTokens: 0,
|
||||
reasoningTokens: 0,
|
||||
},
|
||||
},
|
||||
usage: { costUsdTicks: GROK_COST_USD_TICKS_PER_DOLLAR },
|
||||
}),
|
||||
);
|
||||
|
||||
expect(records).toHaveLength(1);
|
||||
expect(records[0]?.reportedCostUsd).toBe(1);
|
||||
});
|
||||
|
||||
it("falls back to a generic grok model when modelUsage is absent", () => {
|
||||
const records = parseGrokLine(turnCompleted({ modelUsage: null }));
|
||||
|
||||
expect(records).toHaveLength(1);
|
||||
const [record] = records;
|
||||
expect(record?.provider).toBe("grok");
|
||||
expect(record?.model).toBe("grok");
|
||||
expect(record?.totals).toEqual({
|
||||
uncachedInputTokens: 20_272 - 11_264,
|
||||
cachedInputTokens: 11_264,
|
||||
cacheCreationTokens: 0,
|
||||
outputTokens: 272,
|
||||
reasoningTokens: 180,
|
||||
});
|
||||
expect(record?.reportedCostUsd).toBeCloseTo(230_272_000 / GROK_COST_USD_TICKS_PER_DOLLAR, 12);
|
||||
expect(record?.dedupeKey).toBe("019fec1a-12f7-72f2-9b1f-7778a00aea3c:prompt-1:grok");
|
||||
});
|
||||
|
||||
it("pro-rates top-level cost ticks across multi-model turns without per-model ticks", () => {
|
||||
const records = parseGrokLine(
|
||||
turnCompleted({
|
||||
modelUsage: {
|
||||
"grok-4.5": {
|
||||
inputTokens: 300,
|
||||
outputTokens: 0,
|
||||
cachedReadTokens: 0,
|
||||
reasoningTokens: 0,
|
||||
},
|
||||
"grok-composer-2.5-fast": {
|
||||
inputTokens: 100,
|
||||
outputTokens: 0,
|
||||
cachedReadTokens: 0,
|
||||
reasoningTokens: 0,
|
||||
},
|
||||
},
|
||||
usage: { costUsdTicks: GROK_COST_USD_TICKS_PER_DOLLAR },
|
||||
}),
|
||||
);
|
||||
|
||||
expect(records).toHaveLength(2);
|
||||
const byModel = Object.fromEntries(records.map((record) => [record.model, record]));
|
||||
expect(byModel["grok-4.5"]?.reportedCostUsd).toBeCloseTo(0.75, 12);
|
||||
expect(byModel["grok-composer-2.5-fast"]?.reportedCostUsd).toBeCloseTo(0.25, 12);
|
||||
const sum =
|
||||
(byModel["grok-4.5"]?.reportedCostUsd ?? 0) +
|
||||
(byModel["grok-composer-2.5-fast"]?.reportedCostUsd ?? 0);
|
||||
expect(sum).toBeCloseTo(1, 12);
|
||||
});
|
||||
|
||||
it("pro-rates aggregate cost when a zero-token sibling carries costUsdTicks: 0", () => {
|
||||
const records = parseGrokLine(
|
||||
turnCompleted({
|
||||
modelUsage: {
|
||||
"grok-4.5": {
|
||||
inputTokens: 300,
|
||||
outputTokens: 0,
|
||||
cachedReadTokens: 0,
|
||||
reasoningTokens: 0,
|
||||
},
|
||||
"grok-composer-2.5-fast": {
|
||||
inputTokens: 100,
|
||||
outputTokens: 0,
|
||||
cachedReadTokens: 0,
|
||||
reasoningTokens: 0,
|
||||
},
|
||||
"empty-sibling": {
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
cachedReadTokens: 0,
|
||||
reasoningTokens: 0,
|
||||
costUsdTicks: 0,
|
||||
},
|
||||
},
|
||||
usage: { costUsdTicks: GROK_COST_USD_TICKS_PER_DOLLAR },
|
||||
}),
|
||||
);
|
||||
|
||||
expect(records).toHaveLength(2);
|
||||
expect(records.every((record) => record.model !== "empty-sibling")).toBe(true);
|
||||
const byModel = Object.fromEntries(records.map((record) => [record.model, record]));
|
||||
expect(byModel["grok-4.5"]?.reportedCostUsd).toBeCloseTo(0.75, 12);
|
||||
expect(byModel["grok-composer-2.5-fast"]?.reportedCostUsd).toBeCloseTo(0.25, 12);
|
||||
const sum =
|
||||
(byModel["grok-4.5"]?.reportedCostUsd ?? 0) +
|
||||
(byModel["grok-composer-2.5-fast"]?.reportedCostUsd ?? 0);
|
||||
expect(sum).toBeCloseTo(1, 12);
|
||||
});
|
||||
|
||||
it("allocates leftover aggregate ticks to models that omit per-model ticks", () => {
|
||||
const records = parseGrokLine(
|
||||
turnCompleted({
|
||||
modelUsage: {
|
||||
"grok-4.5": {
|
||||
inputTokens: 300,
|
||||
outputTokens: 0,
|
||||
cachedReadTokens: 0,
|
||||
reasoningTokens: 0,
|
||||
costUsdTicks: 0.4 * GROK_COST_USD_TICKS_PER_DOLLAR,
|
||||
},
|
||||
"grok-composer-2.5-fast": {
|
||||
inputTokens: 100,
|
||||
outputTokens: 0,
|
||||
cachedReadTokens: 0,
|
||||
reasoningTokens: 0,
|
||||
},
|
||||
},
|
||||
usage: { costUsdTicks: GROK_COST_USD_TICKS_PER_DOLLAR },
|
||||
}),
|
||||
);
|
||||
|
||||
expect(records).toHaveLength(2);
|
||||
const byModel = Object.fromEntries(records.map((record) => [record.model, record]));
|
||||
expect(byModel["grok-4.5"]?.reportedCostUsd).toBeCloseTo(0.4, 12);
|
||||
expect(byModel["grok-composer-2.5-fast"]?.reportedCostUsd).toBeCloseTo(0.6, 12);
|
||||
const sum =
|
||||
(byModel["grok-4.5"]?.reportedCostUsd ?? 0) +
|
||||
(byModel["grok-composer-2.5-fast"]?.reportedCostUsd ?? 0);
|
||||
expect(sum).toBeCloseTo(1, 12);
|
||||
});
|
||||
|
||||
it("does not invent a colliding dedupe key when prompt_id is missing", () => {
|
||||
const line = JSON.stringify({
|
||||
timestamp: 1_786_372_566,
|
||||
method: "_x.ai/session/update",
|
||||
params: {
|
||||
sessionId: "s1",
|
||||
update: {
|
||||
sessionUpdate: "turn_completed",
|
||||
usage: {
|
||||
inputTokens: 10,
|
||||
outputTokens: 2,
|
||||
modelUsage: {
|
||||
"grok-4.5": { inputTokens: 10, outputTokens: 2 },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(parseGrokLine(line)[0]?.dedupeKey).toBeNull();
|
||||
});
|
||||
|
||||
it("ignores non-turn lines and empty usage", () => {
|
||||
expect(parseGrokLine(JSON.stringify({ method: "session/update", params: {} }))).toEqual([]);
|
||||
expect(parseGrokLine("not json")).toEqual([]);
|
||||
expect(
|
||||
parseGrokLine(
|
||||
turnCompleted({
|
||||
modelUsage: {
|
||||
"grok-4.5-build": {
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
cachedReadTokens: 0,
|
||||
reasoningTokens: 0,
|
||||
costUsdTicks: 0,
|
||||
},
|
||||
},
|
||||
}),
|
||||
),
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it("falls back to the outer unix-seconds timestamp when agent meta is missing", () => {
|
||||
const line = JSON.stringify({
|
||||
timestamp: 1_786_372_566,
|
||||
method: "_x.ai/session/update",
|
||||
params: {
|
||||
sessionId: "s1",
|
||||
update: {
|
||||
sessionUpdate: "turn_completed",
|
||||
prompt_id: "p1",
|
||||
usage: {
|
||||
inputTokens: 10,
|
||||
outputTokens: 2,
|
||||
modelUsage: {
|
||||
"grok-4.5": { inputTokens: 10, outputTokens: 2 },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const records = parseGrokLine(line);
|
||||
expect(records[0]?.timestampMs).toBe(1_786_372_566_000);
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,8 @@
|
||||
/**
|
||||
* Pure parsers for the provider CLIs' on-disk session transcripts.
|
||||
*
|
||||
* Both parsers are line-at-a-time reducers so callers can stream large files
|
||||
* without materialising them. Neither touches the filesystem.
|
||||
* Each parser is a line-at-a-time reducer so callers can stream large files
|
||||
* without materialising them. None of them touch the filesystem.
|
||||
*
|
||||
* @module usageTranscripts
|
||||
*/
|
||||
@@ -68,7 +68,20 @@ export function totalTokens(totals: UsageTokenTotals): number {
|
||||
* an order of magnitude.
|
||||
*/
|
||||
export function mightCarryUsage(line: string, provider: UsageProviderKind): boolean {
|
||||
return provider === "claude" ? line.includes('"usage"') : line.includes('"token_count"');
|
||||
if (provider === "claude") return line.includes('"usage"');
|
||||
if (provider === "grok") return line.includes('"turn_completed"');
|
||||
return line.includes('"token_count"');
|
||||
}
|
||||
|
||||
/**
|
||||
* Grok reports cost in integer ticks where `1 USD = 10^10` ticks. See Grok
|
||||
* headless `total_cost_usd_ticks`. Convert to dollars for pricing.
|
||||
*/
|
||||
export const GROK_COST_USD_TICKS_PER_DOLLAR = 10_000_000_000;
|
||||
|
||||
export function grokCostTicksToUsd(ticks: unknown): number | null {
|
||||
if (typeof ticks !== "number" || !Number.isFinite(ticks) || ticks < 0) return null;
|
||||
return ticks / GROK_COST_USD_TICKS_PER_DOLLAR;
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
@@ -297,4 +310,179 @@ export function parseCodexLine(line: string, state: CodexScanState): UsageRecord
|
||||
};
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* Grok Build */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
interface GrokUsageTotals {
|
||||
readonly inputTokens: number;
|
||||
readonly outputTokens: number;
|
||||
readonly cachedReadTokens: number;
|
||||
readonly cacheCreationTokens: number;
|
||||
readonly reasoningTokens: number;
|
||||
readonly costUsdTicks: number | null;
|
||||
}
|
||||
|
||||
function readGrokUsageTotals(value: unknown): GrokUsageTotals | null {
|
||||
if (typeof value !== "object" || value === null) return null;
|
||||
const record = value as Record<string, unknown>;
|
||||
return {
|
||||
inputTokens: int(record["inputTokens"]),
|
||||
outputTokens: int(record["outputTokens"]),
|
||||
cachedReadTokens: int(record["cachedReadTokens"]),
|
||||
cacheCreationTokens: int(record["cacheCreationTokens"]),
|
||||
reasoningTokens: int(record["reasoningTokens"]),
|
||||
costUsdTicks:
|
||||
typeof record["costUsdTicks"] === "number" && Number.isFinite(record["costUsdTicks"])
|
||||
? record["costUsdTicks"]
|
||||
: null,
|
||||
};
|
||||
}
|
||||
|
||||
function grokTotalsToUsage(totals: GrokUsageTotals): UsageTokenTotals {
|
||||
const cachedInputTokens = totals.cachedReadTokens;
|
||||
const cacheCreationTokens = totals.cacheCreationTokens;
|
||||
// Grok reports `inputTokens` inclusive of the cached portion, matching Codex.
|
||||
const uncachedInputTokens = Math.max(
|
||||
0,
|
||||
totals.inputTokens - cachedInputTokens - cacheCreationTokens,
|
||||
);
|
||||
const outputTokens = totals.outputTokens;
|
||||
return {
|
||||
uncachedInputTokens,
|
||||
cachedInputTokens,
|
||||
cacheCreationTokens,
|
||||
outputTokens,
|
||||
reasoningTokens: Math.min(outputTokens, totals.reasoningTokens),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses one line of a Grok Build `updates.jsonl` session log.
|
||||
*
|
||||
* Usage lands on `turn_completed` session updates. Per-model breakdowns live
|
||||
* under `usage.modelUsage`; when present each model becomes its own record.
|
||||
*
|
||||
* Returns every record for the line (0 or more). Callers stream line-by-line
|
||||
* and flatten.
|
||||
*/
|
||||
export function parseGrokLine(line: string): readonly UsageRecord[] {
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(line);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
if (typeof parsed !== "object" || parsed === null) return [];
|
||||
|
||||
const record = parsed as Record<string, unknown>;
|
||||
const params = record["params"];
|
||||
if (typeof params !== "object" || params === null) return [];
|
||||
const paramsRecord = params as Record<string, unknown>;
|
||||
|
||||
const update = paramsRecord["update"];
|
||||
if (typeof update !== "object" || update === null) return [];
|
||||
const updateRecord = update as Record<string, unknown>;
|
||||
if (updateRecord["sessionUpdate"] !== "turn_completed") return [];
|
||||
|
||||
const usage = updateRecord["usage"];
|
||||
if (typeof usage !== "object" || usage === null) return [];
|
||||
const usageRecord = usage as Record<string, unknown>;
|
||||
|
||||
const sessionId = typeof paramsRecord["sessionId"] === "string" ? paramsRecord["sessionId"] : "";
|
||||
const promptId = typeof updateRecord["prompt_id"] === "string" ? updateRecord["prompt_id"] : null;
|
||||
|
||||
// Prefer the high-resolution agent clock; fall back to the outer unix seconds.
|
||||
const meta = paramsRecord["_meta"];
|
||||
let timestampMs: number | null = null;
|
||||
if (typeof meta === "object" && meta !== null) {
|
||||
const agentTimestampMs = (meta as Record<string, unknown>)["agentTimestampMs"];
|
||||
if (typeof agentTimestampMs === "number" && Number.isFinite(agentTimestampMs)) {
|
||||
timestampMs = agentTimestampMs;
|
||||
}
|
||||
}
|
||||
if (timestampMs === null) {
|
||||
const timestamp = record["timestamp"];
|
||||
if (typeof timestamp === "number" && Number.isFinite(timestamp)) {
|
||||
timestampMs = timestamp > 1e12 ? timestamp : timestamp * 1000;
|
||||
}
|
||||
}
|
||||
if (timestampMs === null) return [];
|
||||
|
||||
const topLevel = readGrokUsageTotals(usageRecord);
|
||||
if (topLevel === null) return [];
|
||||
|
||||
const modelUsage = usageRecord["modelUsage"];
|
||||
const modelEntries: Array<{ model: string; totals: GrokUsageTotals }> = [];
|
||||
if (typeof modelUsage === "object" && modelUsage !== null) {
|
||||
for (const [model, raw] of Object.entries(modelUsage as Record<string, unknown>)) {
|
||||
if (model.length === 0) continue;
|
||||
const totals = readGrokUsageTotals(raw);
|
||||
if (totals === null) continue;
|
||||
modelEntries.push({ model, totals });
|
||||
}
|
||||
}
|
||||
|
||||
if (modelEntries.length === 0) {
|
||||
if (totalTokens(grokTotalsToUsage(topLevel)) === 0) return [];
|
||||
return [
|
||||
{
|
||||
provider: "grok",
|
||||
timestampMs,
|
||||
model: "grok",
|
||||
sessionId,
|
||||
totals: grokTotalsToUsage(topLevel),
|
||||
reportedCostUsd: grokCostTicksToUsd(topLevel.costUsdTicks),
|
||||
// No prompt id means we cannot tell two same-second updates apart.
|
||||
dedupeKey: promptId === null ? null : `${sessionId}:${promptId}:grok`,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
// Cost allocation:
|
||||
// 1. Emitted models with their own costUsdTicks keep those values.
|
||||
// 2. Remaining aggregate cost (top-level minus those per-model ticks,
|
||||
// clamped at 0) is pro-rated across emitted models that lack ticks,
|
||||
// by token share among the unticked models only.
|
||||
// 3. When no model has per-model ticks, remaining equals the full
|
||||
// aggregate and every emitted model gets a token-share slice.
|
||||
// Zero-token rows are never emitted and never count toward used ticks.
|
||||
const topLevelCostUsd = grokCostTicksToUsd(topLevel.costUsdTicks);
|
||||
let usedTickedCostUsd = 0;
|
||||
let untickedTokenDenominator = 0;
|
||||
for (const entry of modelEntries) {
|
||||
const tokens = totalTokens(grokTotalsToUsage(entry.totals));
|
||||
if (tokens === 0) continue;
|
||||
if (entry.totals.costUsdTicks !== null) {
|
||||
usedTickedCostUsd += grokCostTicksToUsd(entry.totals.costUsdTicks) ?? 0;
|
||||
} else {
|
||||
untickedTokenDenominator += tokens;
|
||||
}
|
||||
}
|
||||
const remainingCostUsd =
|
||||
topLevelCostUsd === null ? null : Math.max(0, topLevelCostUsd - usedTickedCostUsd);
|
||||
|
||||
const results: UsageRecord[] = [];
|
||||
for (const entry of modelEntries) {
|
||||
const totals = grokTotalsToUsage(entry.totals);
|
||||
if (totalTokens(totals) === 0) continue;
|
||||
|
||||
let reportedCostUsd = grokCostTicksToUsd(entry.totals.costUsdTicks);
|
||||
if (reportedCostUsd === null && remainingCostUsd !== null && untickedTokenDenominator > 0) {
|
||||
reportedCostUsd = remainingCostUsd * (totalTokens(totals) / untickedTokenDenominator);
|
||||
}
|
||||
|
||||
results.push({
|
||||
provider: "grok",
|
||||
timestampMs,
|
||||
model: entry.model,
|
||||
sessionId,
|
||||
totals,
|
||||
reportedCostUsd,
|
||||
dedupeKey: promptId === null ? null : `${sessionId}:${promptId}:${entry.model}`,
|
||||
});
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
export { EMPTY_TOTALS };
|
||||
@@ -86,6 +86,7 @@ describe("buildDayColumns", () => {
|
||||
expect(first?.bands).toEqual([
|
||||
{ provider: "codex", value: 10 },
|
||||
{ provider: "claude", value: 20 },
|
||||
{ provider: "grok", value: 0 },
|
||||
]);
|
||||
});
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { UsageProviderKind } from "@t3tools/contracts";
|
||||
|
||||
import { ClaudeAI, type Icon, OpenAI } from "../Icons";
|
||||
import { ClaudeAI, GrokIcon, type Icon, OpenAI } from "../Icons";
|
||||
|
||||
type UsageProviderPresentation = {
|
||||
readonly label: string;
|
||||
@@ -24,6 +24,12 @@ export const PROVIDER_PRESENTATION = {
|
||||
color: "#d97757",
|
||||
mark: ClaudeAI,
|
||||
},
|
||||
grok: {
|
||||
label: "Grok Build",
|
||||
// Contrast-aware neutral between the Codex series and muted chart chrome.
|
||||
color: "color-mix(in oklab, var(--contrast-foreground) 72%, var(--background))",
|
||||
mark: GrokIcon,
|
||||
},
|
||||
} satisfies Record<UsageProviderKind, UsageProviderPresentation>;
|
||||
|
||||
/** Stable provider reading order across charts, summaries, tables, and hover rows. */
|
||||
|
||||
@@ -68,6 +68,10 @@ them on in **Settings** → the provider's card when you want to use them.
|
||||
Cursor is the one to watch: install Cursor CLI, which provides the `cursor-agent` binary that
|
||||
T3 Code looks for, but authenticate with `agent login`, not `cursor-agent login`.
|
||||
|
||||
Grok models that support adjustable reasoning show a **Reasoning** control beside the model picker.
|
||||
The available levels and default come from the installed Grok Build CLI, so they can vary by model
|
||||
and CLI version.
|
||||
|
||||
Run the login command on the machine running the T3 Code server, not on the device you browse
|
||||
from.
|
||||
|
||||
|
||||
@@ -26,6 +26,9 @@ unattended until it finishes or asks a question of its own.
|
||||
Approvals appear inline in the conversation. Approve or reject one and the agent continues from
|
||||
there.
|
||||
|
||||
For Grok, **Always allow this session** remembers the matching command or tool input. Other
|
||||
actions still ask for approval. It does not change the thread to **Full access**.
|
||||
|
||||
## Choosing a Mode
|
||||
|
||||
Use **Full access** for work in a worktree or a sandbox you can throw away.
|
||||
@@ -40,8 +43,9 @@ shell commands.
|
||||
|
||||
Each provider maps these modes onto its own approval and sandbox settings. Codex, for example,
|
||||
translates the mode into its approval policy and sandbox level, so **Supervised** runs the CLI
|
||||
with prompting enabled and a restricted workspace while **Full access** disables both. The
|
||||
labels above describe what you get; the exact per-provider translation is internal and may
|
||||
change.
|
||||
with prompting enabled and a restricted workspace while **Full access** disables both. Grok
|
||||
threads do the same: **Supervised** starts Grok in ask mode even if your Grok CLI config is
|
||||
set to always-approve, and **Full access** starts Grok with always-approve. The labels above
|
||||
describe what you get; the exact per-provider translation is internal and may change.
|
||||
|
||||
Mobile offers the same four modes with the same labels and descriptions.
|
||||
+7
-4
@@ -1,9 +1,12 @@
|
||||
# Review usage
|
||||
|
||||
The Usage page combines Codex and Claude Code activity from your connected environments. It reads
|
||||
the providers' local session history and shows API-equivalent token cost, processed tokens, cache
|
||||
savings, provider shares, and model breakdowns. Subscription billing is separate from the raw token
|
||||
cost shown here.
|
||||
The Usage page combines Codex, Claude Code, and Grok Build activity from your connected
|
||||
environments. It reads the providers' local session history and shows API-equivalent token cost,
|
||||
processed tokens, cache savings, provider shares, and model breakdowns. Subscription billing is
|
||||
separate from the raw token cost shown here.
|
||||
|
||||
Grok Build totals come from persisted session updates. Interactive turns that never wrote a
|
||||
completed-turn record will not appear.
|
||||
|
||||
Use **Past 24h** for an hourly chart covering the exact rolling 24-hour period. The **7 days**,
|
||||
**30 days**, and **90 days** ranges use daily resolution. Cost and token toggles update both the
|
||||
|
||||
@@ -2,10 +2,10 @@
|
||||
* Usage reporting contract.
|
||||
*
|
||||
* Each environment scans the provider CLIs' own on-disk session transcripts
|
||||
* (`~/.claude/projects/**\/*.jsonl`, `~/.codex/sessions/**\/*.jsonl`) rather than
|
||||
* relying on T3 Code's own orchestration projections, so usage stays complete
|
||||
* even for turns that were never driven through T3 Code. This mirrors the
|
||||
* approach `ccusage` takes.
|
||||
* (`~/.claude/projects/**\/*.jsonl`, `~/.codex/sessions/**\/*.jsonl`,
|
||||
* `~/.grok/sessions/**\/updates.jsonl`) rather than relying on T3 Code's own
|
||||
* orchestration projections, so usage stays complete even for turns that were
|
||||
* never driven through T3 Code. This mirrors the approach `ccusage` takes.
|
||||
*
|
||||
* Environments return pre-aggregated `(day, hourStart?, provider, model)`
|
||||
* buckets. Raw transcript records never cross the wire.
|
||||
@@ -21,9 +21,18 @@ import { NonNegativeInt, TrimmedNonEmptyString } from "./baseSchemas.ts";
|
||||
* client renders partial coverage when an environment reports an older version
|
||||
* rather than failing the whole page.
|
||||
*/
|
||||
export const USAGE_CONTRACT_VERSION = 4 as const;
|
||||
export const USAGE_CONTRACT_VERSION = 5 as const;
|
||||
|
||||
export const UsageProviderKind = Schema.Literals(["claude", "codex"]);
|
||||
/**
|
||||
* Oldest {@link UsageSummary} version a current client will still merge.
|
||||
*
|
||||
* v5 only adds `grok` to {@link UsageProviderKind}; v4 Claude/Codex buckets
|
||||
* remain valid, so mixed-version environments keep those totals instead of
|
||||
* treating every older server as stale.
|
||||
*/
|
||||
export const USAGE_MERGE_COMPATIBLE_SINCE = 4 as const;
|
||||
|
||||
export const UsageProviderKind = Schema.Literals(["claude", "codex", "grok"]);
|
||||
export type UsageProviderKind = typeof UsageProviderKind.Type;
|
||||
|
||||
/**
|
||||
|
||||
@@ -158,7 +158,7 @@ describe("mergeUsage", () => {
|
||||
summary(
|
||||
[bucket()],
|
||||
[{ provider: "claude", hostId: "linux", homePath: "/b" }],
|
||||
USAGE_CONTRACT_VERSION - 1,
|
||||
USAGE_CONTRACT_VERSION - 2,
|
||||
),
|
||||
),
|
||||
],
|
||||
@@ -169,6 +169,32 @@ describe("mergeUsage", () => {
|
||||
expect(merged.staleEnvironments).toEqual(["env-b"]);
|
||||
});
|
||||
|
||||
it("keeps the previous compatible contract version so additive provider expansions still merge", () => {
|
||||
const merged = mergeUsage(
|
||||
[
|
||||
environment(
|
||||
"env-a",
|
||||
summary(
|
||||
[bucket({ costUsd: 10 })],
|
||||
[{ provider: "claude", hostId: "mac", homePath: "/a" }],
|
||||
),
|
||||
),
|
||||
environment(
|
||||
"env-b",
|
||||
summary(
|
||||
[bucket({ costUsd: 4, provider: "codex", model: "gpt-5.6-sol" })],
|
||||
[{ provider: "codex", hostId: "linux", homePath: "/b" }],
|
||||
USAGE_CONTRACT_VERSION - 1,
|
||||
),
|
||||
),
|
||||
],
|
||||
USAGE_CONTRACT_VERSION,
|
||||
);
|
||||
|
||||
expect(merged.costUsd).toBe(14);
|
||||
expect(merged.staleEnvironments).toEqual([]);
|
||||
});
|
||||
|
||||
it("derives provider shares and cost quality", () => {
|
||||
const merged = mergeUsage(
|
||||
[
|
||||
|
||||
@@ -6,12 +6,13 @@
|
||||
*
|
||||
* @module usageMerge
|
||||
*/
|
||||
import type {
|
||||
EnvironmentId,
|
||||
UsageBucket,
|
||||
UsageProviderKind,
|
||||
UsageSourceFingerprint,
|
||||
UsageSummary,
|
||||
import {
|
||||
USAGE_MERGE_COMPATIBLE_SINCE,
|
||||
type EnvironmentId,
|
||||
type UsageBucket,
|
||||
type UsageProviderKind,
|
||||
type UsageSourceFingerprint,
|
||||
type UsageSummary,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
export interface EnvironmentUsage {
|
||||
@@ -172,6 +173,10 @@ function bucketTokens(bucket: UsageBucket): number {
|
||||
);
|
||||
}
|
||||
|
||||
function isCompatibleContractVersion(version: number, expected: number): boolean {
|
||||
return version >= USAGE_MERGE_COMPATIBLE_SINCE && version <= expected;
|
||||
}
|
||||
|
||||
const EMPTY_MERGED: MergedUsage = {
|
||||
costUsd: 0,
|
||||
uncachedInputTokens: 0,
|
||||
@@ -201,8 +206,10 @@ const EMPTY_MERGED: MergedUsage = {
|
||||
* Merges every connected environment's summary.
|
||||
*
|
||||
* `expectedContractVersion` guards against an environment running older server
|
||||
* code: rather than blocking the page, its data is excluded and its id is
|
||||
* reported so the UI can say coverage is partial.
|
||||
* code: rather than blocking the page, incompatible data is excluded and its
|
||||
* id is reported so the UI can say coverage is partial. Versions in
|
||||
* [{@link USAGE_MERGE_COMPATIBLE_SINCE}, expected] still merge, so an additive
|
||||
* provider expansion does not drop Claude/Codex totals from older servers.
|
||||
*/
|
||||
export function mergeUsage(
|
||||
environments: readonly EnvironmentUsage[],
|
||||
@@ -213,7 +220,7 @@ export function mergeUsage(
|
||||
const current: EnvironmentUsage[] = [];
|
||||
const staleEnvironments: EnvironmentId[] = [];
|
||||
for (const environment of environments) {
|
||||
if (environment.summary.contractVersion === expectedContractVersion) {
|
||||
if (isCompatibleContractVersion(environment.summary.contractVersion, expectedContractVersion)) {
|
||||
current.push(environment);
|
||||
} else {
|
||||
staleEnvironments.push(environment.environmentId);
|
||||
|
||||
Reference in new issue
Block a user