Flatten Git service layer and switch server paths to base dir (#1255)

This commit is contained in:
Julius Marminge authored and GitHub committed 2026-03-23 17:02:09 -07:00
1 parent 843d6d8678
commit d415558915
17 files changed
+1534 -2249

No files matched your search

@@ -24,6 +24,7 @@ import {
import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore.ts";
import { CheckpointStore } from "../src/checkpointing/Services/CheckpointStore.ts";
import { GitCoreLive } from "../src/git/Layers/GitCore.ts";
import { GitCore, type GitCoreShape } from "../src/git/Services/GitCore.ts";
import { TextGeneration, type TextGenerationShape } from "../src/git/Services/TextGeneration.ts";
import { OrchestrationCommandReceiptRepositoryLive } from "../src/persistence/Layers/OrchestrationCommandReceipts.ts";
@@ -284,12 +285,13 @@ export const makeOrchestrationIntegrationHarness = (
Layer.provide(AnalyticsService.layerTest),
);
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(GitCoreLive));
const runtimeServicesLayer = Layer.mergeAll(
orchestrationLayer,
OrchestrationProjectionSnapshotQueryLive,
ProjectionCheckpointRepositoryLive,
ProjectionPendingApprovalRepositoryLive,
CheckpointStoreLive,
checkpointStoreLayer,
providerLayer,
RuntimeReceiptBusLive,
);
@@ -15,15 +15,14 @@ import { Effect, Layer, FileSystem, Path } from "effect";
import { CheckpointInvariantError } from "../Errors.ts";
import { GitCommandError } from "../../git/Errors.ts";
import { GitServiceLive } from "../../git/Layers/GitService.ts";
import { GitService } from "../../git/Services/GitService.ts";
import { GitCore } from "../../git/Services/GitCore.ts";
import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts";
import { CheckpointRef } from "@t3tools/contracts";
const makeCheckpointStore = Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const git = yield* GitService;
const git = yield* GitCore;
const resolveHeadCommit = (cwd: string): Effect.Effect<string | null, GitCommandError> =>
git
@@ -277,6 +276,4 @@ const makeCheckpointStore = Effect.gen(function* () {
} satisfies CheckpointStoreShape;
});
export const CheckpointStoreLive = Layer.effect(CheckpointStore, makeCheckpointStore).pipe(
Layer.provideMerge(GitServiceLive),
);
export const CheckpointStoreLive = Layer.effect(CheckpointStore, makeCheckpointStore);
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+10 -9
View File
@@ -15,9 +15,8 @@ import {
GitHubCli,
} from "../Services/GitHubCli.ts";
import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts";
import { GitServiceLive } from "./GitService.ts";
import { GitService } from "../Services/GitService.ts";
import { GitCoreLive } from "./GitCore.ts";
import { GitCore } from "../Services/GitCore.ts";
import { makeGitManager } from "./GitManager.ts";
import { ServerConfig } from "../../config.ts";
@@ -107,11 +106,11 @@ function runGit(
): Effect.Effect<
{ readonly code: number; readonly stdout: string; readonly stderr: string },
GitCommandError,
GitService
GitCore
> {
return Effect.gen(function* () {
const gitService = yield* GitService;
return yield* gitService.execute({
const gitCore = yield* GitCore;
return yield* gitCore.execute({
operation: "GitManager.test.runGit",
cwd,
args,
@@ -125,7 +124,7 @@ function initRepo(
): Effect.Effect<
void,
PlatformError.PlatformError | GitCommandError,
FileSystem.FileSystem | Scope.Scope | GitService
FileSystem.FileSystem | Scope.Scope | GitCore
> {
return Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
@@ -141,7 +140,7 @@ function initRepo(
function createBareRemote(): Effect.Effect<
string,
PlatformError.PlatformError | GitCommandError,
FileSystem.FileSystem | Scope.Scope | GitService
FileSystem.FileSystem | Scope.Scope | GitCore
> {
return Effect.gen(function* () {
const remoteDir = yield* makeTempDir("t3code-git-remote-");
@@ -480,7 +479,6 @@ function makeManager(input?: {
});
const gitCoreLayer = GitCoreLive.pipe(
Layer.provideMerge(GitServiceLive),
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(ServerConfigLayer),
);
@@ -497,7 +495,10 @@ function makeManager(input?: {
);
}
const GitManagerTestLayer = Layer.provideMerge(GitServiceLive, NodeServices.layer);
const GitManagerTestLayer = GitCoreLive.pipe(
Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-git-manager-test-" })),
Layer.provideMerge(NodeServices.layer),
);
it.layer(GitManagerTestLayer)("GitManager", (it) => {
it.effect("status includes PR metadata when branch already has an open PR", () =>
@@ -1,59 +0,0 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it, assert } from "@effect/vitest";
import { Effect, Layer, Schema } from "effect";
import { GitCommandError } from "../Errors.ts";
import { GitServiceLive } from "./GitService.ts";
import { GitService } from "../Services/GitService.ts";
const layer = it.layer(Layer.provideMerge(GitServiceLive, NodeServices.layer));
layer("GitServiceLive", (it) => {
it.effect("runGit executes successful git commands", () =>
Effect.gen(function* () {
const gitService = yield* GitService;
const result = yield* gitService.execute({
operation: "GitProcess.test.version",
cwd: process.cwd(),
args: ["--version"],
});
assert.equal(result.code, 0);
assert.ok(result.stdout.toLowerCase().includes("git version"));
}),
);
it.effect("runGit can return non-zero exit codes when allowed", () =>
Effect.gen(function* () {
const gitService = yield* GitService;
const result = yield* gitService.execute({
operation: "GitProcess.test.allowNonZero",
cwd: process.cwd(),
args: ["rev-parse", "--verify", "__definitely_missing_ref__"],
allowNonZeroExit: true,
});
assert.notEqual(result.code, 0);
}),
);
it.effect("runGit fails with GitCommandError when non-zero exits are not allowed", () =>
Effect.gen(function* () {
const gitService = yield* GitService;
const result = yield* Effect.result(
gitService.execute({
operation: "GitProcess.test.failOnNonZero",
cwd: process.cwd(),
args: ["rev-parse", "--verify", "__definitely_missing_ref__"],
}),
);
assert.equal(result._tag, "Failure");
if (result._tag === "Failure") {
assert.ok(Schema.is(GitCommandError)(result.failure));
assert.equal(result.failure.operation, "GitProcess.test.failOnNonZero");
assert.equal(result.failure.command, "git rev-parse --verify __definitely_missing_ref__");
}
}),
);
});
-144
View File
@@ -1,144 +0,0 @@
/**
* Git process helpers - Effect-native git execution with typed errors.
*
* Centralizes child-process git invocation for server modules. This module
* only executes git commands and reports structured failures.
*
* @module GitServiceLive
*/
import { Effect, Layer, Option, Schema, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { GitCommandError } from "../Errors.ts";
import {
ExecuteGitInput,
ExecuteGitResult,
GitService,
GitServiceShape,
} from "../Services/GitService.ts";
const DEFAULT_TIMEOUT_MS = 30_000;
const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
function quoteGitCommand(args: ReadonlyArray<string>): string {
return `git ${args.join(" ")}`;
}
function toGitCommandError(
input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
detail: string,
) {
return (cause: unknown) =>
Schema.is(GitCommandError)(cause)
? cause
: new GitCommandError({
operation: input.operation,
command: quoteGitCommand(input.args),
cwd: input.cwd,
detail: `${cause instanceof Error && cause.message.length > 0 ? cause.message : "Unknown error"} - ${detail}`,
...(cause !== undefined ? { cause } : {}),
});
}
const collectOutput = Effect.fn(function* <E>(
input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
stream: Stream.Stream<Uint8Array, E>,
maxOutputBytes: number,
): Effect.fn.Return<string, GitCommandError> {
const decoder = new TextDecoder();
let bytes = 0;
let text = "";
yield* Stream.runForEach(stream, (chunk) =>
Effect.gen(function* () {
bytes += chunk.byteLength;
if (bytes > maxOutputBytes) {
return yield* new GitCommandError({
operation: input.operation,
command: quoteGitCommand(input.args),
cwd: input.cwd,
detail: `${quoteGitCommand(input.args)} output exceeded ${maxOutputBytes} bytes and was truncated.`,
});
}
text += decoder.decode(chunk, { stream: true });
}),
).pipe(Effect.mapError(toGitCommandError(input, "output stream failed.")));
text += decoder.decode();
return text;
});
const makeGitService = Effect.gen(function* () {
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const execute: GitServiceShape["execute"] = Effect.fnUntraced(function* (input) {
const commandInput = {
...input,
args: [...input.args],
} as const;
const timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
const commandEffect = Effect.gen(function* () {
const child = yield* commandSpawner
.spawn(
ChildProcess.make("git", commandInput.args, {
cwd: commandInput.cwd,
...(input.env ? { env: input.env } : {}),
}),
)
.pipe(Effect.mapError(toGitCommandError(commandInput, "failed to spawn.")));
const [stdout, stderr, exitCode] = yield* Effect.all(
[
collectOutput(commandInput, child.stdout, maxOutputBytes),
collectOutput(commandInput, child.stderr, maxOutputBytes),
child.exitCode.pipe(
Effect.map((value) => Number(value)),
Effect.mapError(toGitCommandError(commandInput, "failed to report exit code.")),
),
],
{ concurrency: "unbounded" },
);
if (!input.allowNonZeroExit && exitCode !== 0) {
const trimmedStderr = stderr.trim();
return yield* new GitCommandError({
operation: commandInput.operation,
command: quoteGitCommand(commandInput.args),
cwd: commandInput.cwd,
detail:
trimmedStderr.length > 0
? `${quoteGitCommand(commandInput.args)} failed: ${trimmedStderr}`
: `${quoteGitCommand(commandInput.args)} failed with code ${exitCode}.`,
});
}
return { code: exitCode, stdout, stderr } satisfies ExecuteGitResult;
});
return yield* commandEffect.pipe(
Effect.scoped,
Effect.timeoutOption(timeoutMs),
Effect.flatMap((result) =>
Option.match(result, {
onNone: () =>
Effect.fail(
new GitCommandError({
operation: commandInput.operation,
command: quoteGitCommand(commandInput.args),
cwd: commandInput.cwd,
detail: `${quoteGitCommand(commandInput.args)} timed out.`,
}),
),
onSome: Effect.succeed,
}),
),
);
});
return {
execute,
} satisfies GitServiceShape;
});
export const GitServiceLive = Layer.effect(GitService, makeGitService);
+21
View File
@@ -24,6 +24,22 @@ import type {
import type { GitCommandError } from "../Errors.ts";
export interface ExecuteGitInput {
readonly operation: string;
readonly cwd: string;
readonly args: ReadonlyArray<string>;
readonly env?: NodeJS.ProcessEnv;
readonly allowNonZeroExit?: boolean;
readonly timeoutMs?: number;
readonly maxOutputBytes?: number;
}
export interface ExecuteGitResult {
readonly code: number;
readonly stdout: string;
readonly stderr: string;
}
export interface GitStatusDetails extends Omit<GitStatusResult, "pr"> {
upstreamRef: string | null;
}
@@ -86,6 +102,11 @@ export interface GitSetBranchUpstreamInput {
* GitCoreShape - Service API for low-level Git repository interactions.
*/
export interface GitCoreShape {
/**
* Execute a raw Git command.
*/
readonly execute: (input: ExecuteGitInput) => Effect.Effect<ExecuteGitResult, GitCommandError>;
/**
* Read Git status for a repository.
*/
@@ -1,45 +0,0 @@
/**
* GitService - Service for Git command execution.
*
* Uses Effect `ServiceMap.Service` for dependency injection and exposes typed
* domain errors for Git command execution.
*
* @module GitService
*/
import { ServiceMap } from "effect";
import type { Effect } from "effect";
import type { GitCommandError } from "../Errors.ts";
export interface ExecuteGitInput {
readonly operation: string;
readonly cwd: string;
readonly args: ReadonlyArray<string>;
readonly env?: NodeJS.ProcessEnv;
readonly allowNonZeroExit?: boolean;
readonly timeoutMs?: number;
readonly maxOutputBytes?: number;
}
export interface ExecuteGitResult {
readonly code: number;
readonly stdout: string;
readonly stderr: string;
}
/**
* GitServiceShape - Service API for Git command execution.
*/
export interface GitServiceShape {
/**
* Execute a Git command.
*/
readonly execute: (input: ExecuteGitInput) => Effect.Effect<ExecuteGitResult, GitCommandError>;
}
/**
* GitService - Service for Git command execution.
*/
export class GitService extends ServiceMap.Service<GitService, GitServiceShape>()(
"t3/git/Services/GitService",
) {}
@@ -19,6 +19,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { CheckpointStoreLive } from "../../checkpointing/Layers/CheckpointStore.ts";
import { CheckpointStore } from "../../checkpointing/Services/CheckpointStore.ts";
import { GitCoreLive } from "../../git/Layers/GitCore.ts";
import { CheckpointReactorLive } from "./CheckpointReactor.ts";
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
@@ -260,7 +261,7 @@ describe("CheckpointReactor", () => {
Layer.provideMerge(orchestrationLayer),
Layer.provideMerge(RuntimeReceiptBusLive),
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
Layer.provideMerge(CheckpointStoreLive),
Layer.provideMerge(CheckpointStoreLive.pipe(Layer.provide(GitCoreLive))),
Layer.provideMerge(ServerConfigLayer),
Layer.provideMerge(NodeServices.layer),
);
@@ -1,149 +0,0 @@
import { EventEmitter } from "node:events";
import { PassThrough } from "node:stream";
import { query, type SpawnOptions, type SpawnedProcess } from "@anthropic-ai/claude-agent-sdk";
import { afterEach, describe, expect, it } from "vitest";
async function* emptyPrompt(): AsyncGenerator<never, void, void> {}
class FakeClaudeCodeProcess implements SpawnedProcess {
readonly stdin = new PassThrough();
readonly stdout = new PassThrough();
killed = false;
exitCode: number | null = null;
private readonly events = new EventEmitter();
private bufferedInput = "";
constructor(
private readonly onMessage: (
message: Record<string, unknown>,
process: FakeClaudeCodeProcess,
) => void,
) {
this.stdin.setEncoding("utf8");
this.stdin.on("data", (chunk: string) => {
this.bufferedInput += chunk;
this.drainInput();
});
}
emitJson(message: unknown): void {
this.stdout.write(`${JSON.stringify(message)}\n`);
}
kill(_signal: NodeJS.Signals): boolean {
this.killed = true;
this.exitCode = 0;
this.stdout.end();
this.events.emit("exit", 0, null);
return true;
}
on(
event: "exit" | "error",
listener:
| ((code: number | null, signal: NodeJS.Signals | null) => void)
| ((error: Error) => void),
): void {
this.events.on(event, listener);
}
once(
event: "exit" | "error",
listener:
| ((code: number | null, signal: NodeJS.Signals | null) => void)
| ((error: Error) => void),
): void {
this.events.once(event, listener);
}
off(
event: "exit" | "error",
listener:
| ((code: number | null, signal: NodeJS.Signals | null) => void)
| ((error: Error) => void),
): void {
this.events.off(event, listener);
}
private drainInput(): void {
while (true) {
const newlineIndex = this.bufferedInput.indexOf("\n");
if (newlineIndex === -1) {
return;
}
const line = this.bufferedInput.slice(0, newlineIndex).trim();
this.bufferedInput = this.bufferedInput.slice(newlineIndex + 1);
if (line.length === 0) {
continue;
}
this.onMessage(JSON.parse(line) as Record<string, unknown>, this);
}
}
}
describe("Claude SDK fast mode probe", () => {
let activeQuery: ReturnType<typeof query> | null = null;
afterEach(() => {
activeQuery?.close();
activeQuery = null;
});
it("passes fast mode through the SDK settings flag", async () => {
let spawnOptions: SpawnOptions | undefined;
activeQuery = query({
prompt: emptyPrompt(),
options: {
persistSession: false,
settings: {
fastMode: true,
},
spawnClaudeCodeProcess: (options): SpawnedProcess => {
spawnOptions = options;
return new FakeClaudeCodeProcess((message, process) => {
if (
message.type !== "control_request" ||
typeof message.request_id !== "string" ||
!message.request ||
typeof message.request !== "object" ||
(message.request as { subtype?: unknown }).subtype !== "initialize"
) {
return;
}
process.emitJson({
type: "control_response",
response: {
subtype: "success",
request_id: message.request_id,
response: {
commands: [],
agents: [],
output_style: "default",
available_output_styles: ["default"],
models: [],
account: {
subscriptionType: "max",
},
fast_mode_state: "on",
},
},
});
});
},
},
});
const initialization = await activeQuery.initializationResult();
expect(initialization.fast_mode_state).toBe("on");
expect(spawnOptions).toBeDefined();
const settingsFlagIndex = spawnOptions?.args.indexOf("--settings") ?? -1;
expect(settingsFlagIndex).toBeGreaterThan(-1);
expect(JSON.parse(spawnOptions?.args[settingsFlagIndex + 1] ?? "")).toEqual({
fastMode: true,
});
});
});
+6 -7
View File
@@ -31,7 +31,6 @@ import { GitManagerLive } from "./git/Layers/GitManager";
import { GitCoreLive } from "./git/Layers/GitCore";
import { GitHubCliLive } from "./git/Layers/GitHubCli";
import { CodexTextGenerationLive } from "./git/Layers/CodexTextGeneration";
import { GitServiceLive } from "./git/Layers/GitService";
import { PtyAdapter } from "./terminal/Services/PTY";
import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
@@ -86,8 +85,8 @@ export function makeServerProviderLayer(): Layer.Layer<
}
export function makeServerRuntimeServicesLayer() {
const gitCoreLayer = GitCoreLive.pipe(Layer.provideMerge(GitServiceLive));
const textGenerationLayer = CodexTextGenerationLive;
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(GitCoreLive));
const orchestrationLayer = OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionPipelineLive),
@@ -97,13 +96,13 @@ export function makeServerRuntimeServicesLayer() {
const checkpointDiffQueryLayer = CheckpointDiffQueryLive.pipe(
Layer.provideMerge(OrchestrationProjectionSnapshotQueryLive),
Layer.provideMerge(CheckpointStoreLive),
Layer.provideMerge(checkpointStoreLayer),
);
const runtimeServicesLayer = Layer.mergeAll(
orchestrationLayer,
OrchestrationProjectionSnapshotQueryLive,
CheckpointStoreLive,
checkpointStoreLayer,
checkpointDiffQueryLayer,
RuntimeReceiptBusLive,
);
@@ -112,7 +111,7 @@ export function makeServerRuntimeServicesLayer() {
);
const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
Layer.provideMerge(runtimeServicesLayer),
Layer.provideMerge(gitCoreLayer),
Layer.provideMerge(GitCoreLive),
Layer.provideMerge(textGenerationLayer),
);
const checkpointReactorLayer = CheckpointReactorLive.pipe(
@@ -127,14 +126,14 @@ export function makeServerRuntimeServicesLayer() {
const terminalLayer = TerminalManagerLive.pipe(Layer.provide(makeRuntimePtyAdapterLayer()));
const gitManagerLayer = GitManagerLive.pipe(
Layer.provideMerge(gitCoreLayer),
Layer.provideMerge(GitCoreLive),
Layer.provideMerge(GitHubCliLive),
Layer.provideMerge(textGenerationLayer),
);
return Layer.mergeAll(
orchestrationReactorLayer,
gitCoreLayer,
GitCoreLive,
gitManagerLayer,
terminalLayer,
KeybindingsLive,
+1 -1
View File
@@ -51,7 +51,7 @@
"@vitejs/plugin-react": "^6.0.0",
"@vitest/browser-playwright": "^4.0.18",
"babel-plugin-react-compiler": "^19.0.0-beta-e552027-20250112",
"msw": "^2.12.10",
"msw": "2.12.11",
"playwright": "^1.58.2",
"tailwindcss": "^4.0.0",
"typescript": "catalog:",
+1 -1
View File
@@ -7,7 +7,7 @@
* - Please do NOT modify this file.
*/
const PACKAGE_VERSION = '2.12.10'
const PACKAGE_VERSION = '2.12.11'
const INTEGRITY_CHECKSUM = '4db4a41e972cec1b64cc569c66952d82'
const IS_MOCKED_RESPONSE = Symbol('isMockedResponse')
const activeClientIds = new Set()
+1 -1
View File
@@ -112,7 +112,7 @@
"@vitejs/plugin-react": "^6.0.0",
"@vitest/browser-playwright": "^4.0.18",
"babel-plugin-react-compiler": "^19.0.0-beta-e552027-20250112",
"msw": "^2.12.10",
"msw": "2.12.11",
"playwright": "^1.58.2",
"tailwindcss": "^4.0.0",
"typescript": "catalog:",
-129
View File
@@ -1,129 +0,0 @@
import { query, type SDKMessage } from "@anthropic-ai/claude-agent-sdk";
type ProbeMode = "off" | "on";
async function* emptyPrompt(): AsyncGenerator<never, void, void> {}
function parseArgs(argv: ReadonlyArray<string>): {
readonly mode: ProbeMode | "both";
readonly model?: string;
readonly cwd?: string;
readonly prompt?: string;
} {
let mode: ProbeMode | "both" = "both";
let model: string | undefined;
let cwd: string | undefined;
let prompt: string | undefined;
for (let index = 0; index < argv.length; index += 1) {
const value = argv[index];
if (!value) {
continue;
}
if (value === "--mode") {
const next = argv[index + 1];
if (next === "off" || next === "on" || next === "both") {
mode = next;
index += 1;
}
continue;
}
if (value === "--model") {
model = argv[index + 1];
index += 1;
continue;
}
if (value === "--cwd") {
cwd = argv[index + 1];
index += 1;
continue;
}
if (value === "--prompt") {
prompt = argv[index + 1] ?? prompt;
index += 1;
}
}
return {
mode,
...(model ? { model } : {}),
...(cwd ? { cwd } : {}),
...(prompt ? { prompt } : {}),
};
}
async function runProbe(input: {
readonly mode: ProbeMode;
readonly model?: string;
readonly cwd?: string;
readonly prompt?: string;
}): Promise<void> {
const messages = query({
prompt: input.prompt ?? emptyPrompt(),
options: {
...(input.model ? { model: input.model } : {}),
...(input.cwd ? { cwd: input.cwd } : {}),
persistSession: false,
tools: [],
permissionMode: "plan",
includePartialMessages: true,
...(input.mode === "on" ? { settings: { fastMode: true } } : {}),
},
});
const summary = {
mode: input.mode,
initFastModeState: null as string | null,
resultFastModeState: null as string | null,
resultSubtype: null as string | null,
resultText: null as string | null,
};
const initialization = await messages.initializationResult();
summary.initFastModeState = initialization.fast_mode_state ?? null;
if (!input.prompt) {
messages.close();
console.log(JSON.stringify(summary, null, 2));
return;
}
for await (const message of messages) {
handleProbeMessage(message, summary);
}
console.log(JSON.stringify(summary, null, 2));
}
function handleProbeMessage(
message: SDKMessage,
summary: {
mode: ProbeMode;
initFastModeState: string | null;
resultFastModeState: string | null;
resultSubtype: string | null;
resultText: string | null;
},
): void {
if (message.type !== "result") {
return;
}
summary.resultSubtype = message.subtype;
summary.resultFastModeState = message.fast_mode_state ?? null;
summary.resultText = message.subtype === "success" ? message.result : message.errors.join("\n");
}
async function main(): Promise<void> {
const args = parseArgs(process.argv.slice(2));
const modes = args.mode === "both" ? (["off", "on"] as const) : [args.mode];
for (const mode of modes) {
await runProbe({
mode,
...(args.model ? { model: args.model } : {}),
...(args.cwd ? { cwd: args.cwd } : {}),
...(args.prompt ? { prompt: args.prompt } : {}),
});
}
}
await main();
-261
View File
@@ -1,261 +0,0 @@
import { query, type SDKMessage, type ThinkingConfig } from "@anthropic-ai/claude-agent-sdk";
type ProbeCase =
| "default"
| "effort-low"
| "effort-high"
| "settings-off"
| "settings-on"
| "thinking-disabled"
| "thinking-enabled";
function parseArgs(argv: ReadonlyArray<string>): {
readonly model: string;
readonly cwd?: string;
readonly prompt: string;
readonly cases: ReadonlyArray<ProbeCase>;
} {
let model = "claude-haiku-4-5";
let cwd: string | undefined;
let prompt =
"Think step by step about this before answering: what is 27 multiplied by 43? Return the final number only.";
let cases: ReadonlyArray<ProbeCase> = [
"default",
"effort-low",
"effort-high",
"settings-off",
"settings-on",
"thinking-disabled",
"thinking-enabled",
];
for (let index = 0; index < argv.length; index += 1) {
const value = argv[index];
if (!value) {
continue;
}
if (value === "--model") {
model = argv[index + 1] ?? model;
index += 1;
continue;
}
if (value === "--cwd") {
cwd = argv[index + 1] ?? cwd;
index += 1;
continue;
}
if (value === "--prompt") {
prompt = argv[index + 1] ?? prompt;
index += 1;
continue;
}
if (value === "--cases") {
const next = argv[index + 1];
if (next) {
const requested = next
.split(",")
.map((entry) => entry.trim())
.filter(
(entry): entry is ProbeCase =>
entry === "default" ||
entry === "effort-low" ||
entry === "effort-high" ||
entry === "settings-off" ||
entry === "settings-on" ||
entry === "thinking-disabled" ||
entry === "thinking-enabled",
);
if (requested.length > 0) {
cases = requested;
}
}
index += 1;
}
}
return {
model,
prompt,
...(cwd ? { cwd } : {}),
cases,
};
}
function caseOptions(caseName: ProbeCase): {
readonly label: ProbeCase;
readonly effort?: "low" | "high";
readonly settings?: { alwaysThinkingEnabled: boolean };
readonly thinking?: ThinkingConfig;
} {
switch (caseName) {
case "effort-low":
return {
label: caseName,
effort: "low",
};
case "effort-high":
return {
label: caseName,
effort: "high",
};
case "settings-off":
return {
label: caseName,
settings: {
alwaysThinkingEnabled: false,
},
};
case "settings-on":
return {
label: caseName,
settings: {
alwaysThinkingEnabled: true,
},
};
case "thinking-disabled":
return {
label: caseName,
thinking: {
type: "disabled",
},
};
case "thinking-enabled":
return {
label: caseName,
thinking: {
type: "enabled",
budgetTokens: 1024,
},
};
default:
return {
label: caseName,
};
}
}
type ProbeSummary = {
readonly case: ProbeCase;
readonly model: string;
initModelInfo: {
value: string | null;
supportsEffort: boolean | null;
supportsAdaptiveThinking: boolean | null;
supportedEffortLevels: ReadonlyArray<string> | null;
} | null;
resultSubtype: string | null;
resultText: string | null;
assistantThinkingBlockCount: number;
streamThinkingEventTypes: Record<string, number>;
error: string | null;
};
async function runCase(input: {
readonly caseName: ProbeCase;
readonly model: string;
readonly cwd?: string;
readonly prompt: string;
}): Promise<ProbeSummary> {
const caseConfig = caseOptions(input.caseName);
const summary: ProbeSummary = {
case: input.caseName,
model: input.model,
initModelInfo: null,
resultSubtype: null,
resultText: null,
assistantThinkingBlockCount: 0,
streamThinkingEventTypes: {},
error: null,
};
try {
const messages = query({
prompt: input.prompt,
options: {
model: input.model,
...(input.cwd ? { cwd: input.cwd } : {}),
persistSession: false,
tools: [],
permissionMode: "bypassPermissions",
includePartialMessages: true,
maxTurns: 1,
...(caseConfig.effort ? { effort: caseConfig.effort } : {}),
...(caseConfig.settings ? { settings: caseConfig.settings } : {}),
...(caseConfig.thinking ? { thinking: caseConfig.thinking } : {}),
},
});
const initialization = await messages.initializationResult();
const initModel =
initialization.models.find((candidate) => candidate.value === input.model) ??
initialization.models.find((candidate) => candidate.value.includes("haiku")) ??
null;
summary.initModelInfo = initModel
? {
value: initModel.value,
supportsEffort: initModel.supportsEffort ?? null,
supportsAdaptiveThinking: initModel.supportsAdaptiveThinking ?? null,
supportedEffortLevels: initModel.supportedEffortLevels ?? null,
}
: null;
for await (const message of messages) {
handleMessage(summary, message);
}
} catch (error) {
summary.error = error instanceof Error ? error.message : String(error);
}
return summary;
}
function handleMessage(summary: ProbeSummary, message: SDKMessage): void {
if (message.type === "stream_event") {
const event = message.event as {
type?: string;
delta?: {
type?: string;
};
};
const eventType = event.delta?.type ?? event.type;
if (typeof eventType === "string" && eventType.includes("thinking")) {
summary.streamThinkingEventTypes[eventType] =
(summary.streamThinkingEventTypes[eventType] ?? 0) + 1;
}
return;
}
if (message.type === "assistant") {
for (const block of message.message.content) {
if (typeof block?.type === "string" && block.type.includes("thinking")) {
summary.assistantThinkingBlockCount += 1;
}
}
return;
}
if (message.type === "result") {
summary.resultSubtype = message.subtype;
summary.resultText = message.subtype === "success" ? message.result : message.errors.join("\n");
}
}
async function main(): Promise<void> {
const args = parseArgs(process.argv.slice(2));
const results: ProbeSummary[] = [];
for (const caseName of args.cases) {
results.push(
await runCase({
caseName,
model: args.model,
...(args.cwd ? { cwd: args.cwd } : {}),
prompt: args.prompt,
}),
);
}
console.log(JSON.stringify(results, null, 2));
}
await main();