Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f5a4bbcb1c | ||
|
|
fdcb05d3f6 | ||
|
|
2121682546 | ||
|
|
d2b00e6550 | ||
|
|
e0facb03bd | ||
|
|
73152abe81 | ||
|
|
c5bfff1583 |
No files matched your search
@@ -6,6 +6,7 @@ import { execFileSync } from "node:child_process";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
ProviderKind,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationThread,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -205,7 +206,7 @@ export interface OrchestrationIntegrationHarness {
|
||||
}
|
||||
|
||||
interface MakeOrchestrationIntegrationHarnessOptions {
|
||||
readonly provider?: "codex" | "claudeCode";
|
||||
readonly provider?: ProviderKind;
|
||||
readonly realCodex?: boolean;
|
||||
}
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
ProviderTurnStartResult,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
ProviderKind,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Queue, Stream } from "effect";
|
||||
|
||||
@@ -35,7 +36,7 @@ export interface TestTurnResponse {
|
||||
export type FixtureProviderRuntimeEvent = {
|
||||
readonly type: string;
|
||||
readonly eventId: EventId;
|
||||
readonly provider: "codex" | "claudeCode";
|
||||
readonly provider: ProviderKind;
|
||||
readonly createdAt: string;
|
||||
readonly threadId: string;
|
||||
readonly turnId?: string | undefined;
|
||||
@@ -177,7 +178,7 @@ function normalizeFixtureEvent(rawEvent: Record<string, unknown>): ProviderRunti
|
||||
|
||||
export interface TestProviderAdapterHarness {
|
||||
readonly adapter: ProviderAdapterShape<ProviderAdapterError>;
|
||||
readonly provider: "codex" | "claudeCode";
|
||||
readonly provider: ProviderKind;
|
||||
readonly queueTurnResponse: (
|
||||
threadId: ThreadId,
|
||||
response: TestTurnResponse,
|
||||
@@ -197,7 +198,7 @@ export interface TestProviderAdapterHarness {
|
||||
}
|
||||
|
||||
interface MakeTestProviderAdapterHarnessOptions {
|
||||
readonly provider?: "codex" | "claudeCode";
|
||||
readonly provider?: ProviderKind;
|
||||
}
|
||||
|
||||
function nowIso(): string {
|
||||
@@ -205,7 +206,7 @@ function nowIso(): string {
|
||||
}
|
||||
|
||||
function sessionNotFound(
|
||||
provider: "codex" | "claudeCode",
|
||||
provider: ProviderKind,
|
||||
threadId: ThreadId,
|
||||
): ProviderAdapterSessionNotFoundError {
|
||||
return new ProviderAdapterSessionNotFoundError({
|
||||
@@ -215,7 +216,7 @@ function sessionNotFound(
|
||||
}
|
||||
|
||||
function missingSessionEffect(
|
||||
provider: "codex" | "claudeCode",
|
||||
provider: ProviderKind,
|
||||
threadId: ThreadId,
|
||||
): Effect.Effect<never, ProviderAdapterError> {
|
||||
return Effect.fail(sessionNotFound(provider, threadId));
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
EventId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ProviderKind,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
@@ -36,7 +37,7 @@ const PROJECT_ID = asProjectId("project-1");
|
||||
const THREAD_ID = ThreadId.makeUnsafe("thread-1");
|
||||
const FIXTURE_TURN_ID = "fixture-turn";
|
||||
const APPROVAL_REQUEST_ID = asApprovalRequestId("req-approval-1");
|
||||
type IntegrationProvider = "codex" | "claudeCode";
|
||||
type IntegrationProvider = ProviderKind;
|
||||
|
||||
function nowIso() {
|
||||
return new Date().toISOString();
|
||||
|
||||
@@ -3,7 +3,7 @@ import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { execFileSync } from "node:child_process";
|
||||
|
||||
import type { ProviderRuntimeEvent, ProviderSession } from "@t3tools/contracts";
|
||||
import type { ProviderKind, ProviderRuntimeEvent, ProviderSession } from "@t3tools/contracts";
|
||||
import {
|
||||
CommandId,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
@@ -44,7 +44,7 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
type LegacyProviderRuntimeEvent = {
|
||||
readonly type: string;
|
||||
readonly eventId: EventId;
|
||||
readonly provider: "codex" | "claudeCode";
|
||||
readonly provider: ProviderKind;
|
||||
readonly createdAt: string;
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId?: string | undefined;
|
||||
@@ -235,7 +235,7 @@ describe("CheckpointReactor", () => {
|
||||
readonly projectWorkspaceRoot?: string;
|
||||
readonly threadWorktreePath?: string | null;
|
||||
readonly providerSessionCwd?: string;
|
||||
readonly providerName?: "codex" | "claudeCode";
|
||||
readonly providerName?: ProviderKind;
|
||||
}) {
|
||||
const cwd = createGitRepository();
|
||||
tempDirs.push(cwd);
|
||||
|
||||
@@ -2,7 +2,11 @@ import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import type { OrchestrationReadModel, ProviderRuntimeEvent } from "@t3tools/contracts";
|
||||
import type {
|
||||
OrchestrationReadModel,
|
||||
ProviderKind,
|
||||
ProviderRuntimeEvent,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
CommandId,
|
||||
@@ -45,7 +49,7 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
type LegacyProviderRuntimeEvent = {
|
||||
readonly type: string;
|
||||
readonly eventId: EventId;
|
||||
readonly provider: "codex" | "claudeCode";
|
||||
readonly provider: ProviderKind;
|
||||
readonly createdAt: string;
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId?: string | undefined;
|
||||
|
||||
@@ -331,9 +331,9 @@ describe("ClaudeCodeAdapterLive", () => {
|
||||
"thread.started",
|
||||
"content.delta",
|
||||
"item.started",
|
||||
"item.completed",
|
||||
"item.updated",
|
||||
"item.completed",
|
||||
"item.completed",
|
||||
"turn.completed",
|
||||
],
|
||||
);
|
||||
@@ -369,6 +369,186 @@ describe("ClaudeCodeAdapterLive", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("maps Claude reasoning deltas, streamed tool inputs, and tool results", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeCodeAdapter;
|
||||
|
||||
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 12).pipe(
|
||||
Stream.runCollect,
|
||||
Effect.forkChild,
|
||||
);
|
||||
|
||||
const session = yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeCode",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const turn = yield* adapter.sendTurn({
|
||||
threadId: session.threadId,
|
||||
input: "hello",
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
harness.query.emit({
|
||||
type: "stream_event",
|
||||
session_id: "sdk-session-tool-streams",
|
||||
uuid: "stream-thinking",
|
||||
parent_tool_use_id: null,
|
||||
event: {
|
||||
type: "content_block_delta",
|
||||
index: 0,
|
||||
delta: {
|
||||
type: "thinking_delta",
|
||||
thinking: "Let",
|
||||
},
|
||||
},
|
||||
} as unknown as SDKMessage);
|
||||
|
||||
harness.query.emit({
|
||||
type: "stream_event",
|
||||
session_id: "sdk-session-tool-streams",
|
||||
uuid: "stream-tool-start",
|
||||
parent_tool_use_id: null,
|
||||
event: {
|
||||
type: "content_block_start",
|
||||
index: 1,
|
||||
content_block: {
|
||||
type: "tool_use",
|
||||
id: "tool-grep-1",
|
||||
name: "Grep",
|
||||
input: {},
|
||||
},
|
||||
},
|
||||
} as unknown as SDKMessage);
|
||||
|
||||
harness.query.emit({
|
||||
type: "stream_event",
|
||||
session_id: "sdk-session-tool-streams",
|
||||
uuid: "stream-tool-input-1",
|
||||
parent_tool_use_id: null,
|
||||
event: {
|
||||
type: "content_block_delta",
|
||||
index: 1,
|
||||
delta: {
|
||||
type: "input_json_delta",
|
||||
partial_json: '{"pattern":"foo","path":"src"}',
|
||||
},
|
||||
},
|
||||
} as unknown as SDKMessage);
|
||||
|
||||
harness.query.emit({
|
||||
type: "stream_event",
|
||||
session_id: "sdk-session-tool-streams",
|
||||
uuid: "stream-tool-stop",
|
||||
parent_tool_use_id: null,
|
||||
event: {
|
||||
type: "content_block_stop",
|
||||
index: 1,
|
||||
},
|
||||
} as unknown as SDKMessage);
|
||||
|
||||
harness.query.emit({
|
||||
type: "user",
|
||||
session_id: "sdk-session-tool-streams",
|
||||
uuid: "user-tool-result",
|
||||
parent_tool_use_id: null,
|
||||
message: {
|
||||
role: "user",
|
||||
content: [
|
||||
{
|
||||
type: "tool_result",
|
||||
tool_use_id: "tool-grep-1",
|
||||
content: "src/example.ts:1:foo",
|
||||
},
|
||||
],
|
||||
},
|
||||
} as unknown as SDKMessage);
|
||||
|
||||
harness.query.emit({
|
||||
type: "result",
|
||||
subtype: "success",
|
||||
is_error: false,
|
||||
errors: [],
|
||||
session_id: "sdk-session-tool-streams",
|
||||
uuid: "result-tool-streams",
|
||||
} as unknown as SDKMessage);
|
||||
|
||||
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
|
||||
assert.deepEqual(
|
||||
runtimeEvents.map((event) => event.type),
|
||||
[
|
||||
"session.started",
|
||||
"session.configured",
|
||||
"session.state.changed",
|
||||
"turn.started",
|
||||
"thread.started",
|
||||
"content.delta",
|
||||
"item.started",
|
||||
"item.updated",
|
||||
"item.updated",
|
||||
"item.completed",
|
||||
"item.completed",
|
||||
"turn.completed",
|
||||
],
|
||||
);
|
||||
|
||||
const reasoningDelta = runtimeEvents.find(
|
||||
(event) => event.type === "content.delta" && event.payload.streamKind === "reasoning_text",
|
||||
);
|
||||
assert.equal(reasoningDelta?.type, "content.delta");
|
||||
if (reasoningDelta?.type === "content.delta") {
|
||||
assert.equal(reasoningDelta.payload.delta, "Let");
|
||||
assert.equal(String(reasoningDelta.turnId), String(turn.turnId));
|
||||
}
|
||||
|
||||
const toolStarted = runtimeEvents.find((event) => event.type === "item.started");
|
||||
assert.equal(toolStarted?.type, "item.started");
|
||||
if (toolStarted?.type === "item.started") {
|
||||
assert.equal(toolStarted.payload.itemType, "dynamic_tool_call");
|
||||
}
|
||||
|
||||
const toolInputUpdated = runtimeEvents.find(
|
||||
(event) =>
|
||||
event.type === "item.updated" &&
|
||||
(event.payload.data as { input?: { pattern?: string; path?: string } } | undefined)?.input
|
||||
?.pattern === "foo",
|
||||
);
|
||||
assert.equal(toolInputUpdated?.type, "item.updated");
|
||||
if (toolInputUpdated?.type === "item.updated") {
|
||||
assert.deepEqual(toolInputUpdated.payload.data, {
|
||||
toolName: "Grep",
|
||||
input: {
|
||||
pattern: "foo",
|
||||
path: "src",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const toolResultUpdated = runtimeEvents.find(
|
||||
(event) =>
|
||||
event.type === "item.updated" &&
|
||||
(event.payload.data as { result?: { tool_use_id?: string } } | undefined)?.result
|
||||
?.tool_use_id === "tool-grep-1",
|
||||
);
|
||||
assert.equal(toolResultUpdated?.type, "item.updated");
|
||||
if (toolResultUpdated?.type === "item.updated") {
|
||||
assert.equal(
|
||||
(
|
||||
toolResultUpdated.payload.data as {
|
||||
result?: { content?: string };
|
||||
}
|
||||
).result?.content,
|
||||
"src/example.ts:1:foo",
|
||||
);
|
||||
}
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"emits completion only after turn result when assistant frames arrive before deltas",
|
||||
() => {
|
||||
@@ -688,6 +868,79 @@ describe("ClaudeCodeAdapterLive", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("classifies Agent tools and read-only Claude tools correctly for approvals", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeCodeAdapter;
|
||||
|
||||
const session = yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeCode",
|
||||
runtimeMode: "approval-required",
|
||||
});
|
||||
|
||||
yield* Stream.take(adapter.streamEvents, 3).pipe(Stream.runDrain);
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
const canUseTool = createInput?.options.canUseTool;
|
||||
assert.equal(typeof canUseTool, "function");
|
||||
if (!canUseTool) {
|
||||
return;
|
||||
}
|
||||
|
||||
const agentPermissionPromise = canUseTool(
|
||||
"Agent",
|
||||
{},
|
||||
{
|
||||
signal: new AbortController().signal,
|
||||
toolUseID: "tool-agent-1",
|
||||
},
|
||||
);
|
||||
|
||||
const agentRequested = yield* Stream.runHead(adapter.streamEvents);
|
||||
assert.equal(agentRequested._tag, "Some");
|
||||
if (agentRequested._tag !== "Some" || agentRequested.value.type !== "request.opened") {
|
||||
return;
|
||||
}
|
||||
assert.equal(agentRequested.value.payload.requestType, "dynamic_tool_call");
|
||||
|
||||
yield* adapter.respondToRequest(
|
||||
session.threadId,
|
||||
ApprovalRequestId.makeUnsafe(String(agentRequested.value.requestId)),
|
||||
"accept",
|
||||
);
|
||||
yield* Stream.runHead(adapter.streamEvents);
|
||||
yield* Effect.promise(() => agentPermissionPromise);
|
||||
|
||||
const grepPermissionPromise = canUseTool(
|
||||
"Grep",
|
||||
{ pattern: "foo", path: "src" },
|
||||
{
|
||||
signal: new AbortController().signal,
|
||||
toolUseID: "tool-grep-approval-1",
|
||||
},
|
||||
);
|
||||
|
||||
const grepRequested = yield* Stream.runHead(adapter.streamEvents);
|
||||
assert.equal(grepRequested._tag, "Some");
|
||||
if (grepRequested._tag !== "Some" || grepRequested.value.type !== "request.opened") {
|
||||
return;
|
||||
}
|
||||
assert.equal(grepRequested.value.payload.requestType, "file_read_approval");
|
||||
|
||||
yield* adapter.respondToRequest(
|
||||
session.threadId,
|
||||
ApprovalRequestId.makeUnsafe(String(grepRequested.value.requestId)),
|
||||
"accept",
|
||||
);
|
||||
yield* Stream.runHead(adapter.streamEvents);
|
||||
yield* Effect.promise(() => grepPermissionPromise);
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("passes parsed resume cursor values to Claude query options", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
@@ -858,11 +1111,13 @@ describe("ClaudeCodeAdapterLive", () => {
|
||||
turnId?: string;
|
||||
};
|
||||
}> = [];
|
||||
const nativeThreadIds: Array<string | null> = [];
|
||||
const harness = makeHarness({
|
||||
nativeEventLogger: {
|
||||
filePath: "memory://claude-native-events",
|
||||
write: (event) => {
|
||||
write: (event, threadId) => {
|
||||
nativeEvents.push(event as (typeof nativeEvents)[number]);
|
||||
nativeThreadIds.push(threadId ?? null);
|
||||
return Effect.void;
|
||||
},
|
||||
close: () => Effect.void,
|
||||
@@ -939,6 +1194,10 @@ describe("ClaudeCodeAdapterLive", () => {
|
||||
),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
nativeThreadIds.every((threadId) => threadId === String(THREAD_ID)),
|
||||
true,
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
|
||||
@@ -28,6 +28,7 @@ import {
|
||||
type ProviderRuntimeTurnStatus,
|
||||
type ProviderSendTurnInput,
|
||||
type ProviderSession,
|
||||
type RuntimeContentStreamKind,
|
||||
RuntimeItemId,
|
||||
RuntimeRequestId,
|
||||
RuntimeTaskId,
|
||||
@@ -48,6 +49,11 @@ import { ClaudeCodeAdapter, type ClaudeCodeAdapterShape } from "../Services/Clau
|
||||
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
|
||||
|
||||
const PROVIDER = "claudeCode" as const;
|
||||
type ClaudeTextStreamKind = Extract<RuntimeContentStreamKind, "assistant_text" | "reasoning_text">;
|
||||
type ClaudeToolResultStreamKind = Extract<
|
||||
RuntimeContentStreamKind,
|
||||
"command_output" | "file_change_output"
|
||||
>;
|
||||
|
||||
type PromptQueueItem =
|
||||
| {
|
||||
@@ -88,6 +94,9 @@ interface ToolInFlight {
|
||||
readonly toolName: string;
|
||||
readonly title: string;
|
||||
readonly detail?: string;
|
||||
readonly input: Record<string, unknown>;
|
||||
readonly partialInputJson: string;
|
||||
readonly lastEmittedInputFingerprint?: string;
|
||||
}
|
||||
|
||||
interface ClaudeSessionContext {
|
||||
@@ -205,6 +214,9 @@ function readClaudeResumeState(resumeCursor: unknown): ClaudeResumeState | undef
|
||||
|
||||
function classifyToolItemType(toolName: string): CanonicalItemType {
|
||||
const normalized = toolName.toLowerCase();
|
||||
if (normalized.includes("agent")) {
|
||||
return "collab_agent_tool_call";
|
||||
}
|
||||
if (
|
||||
normalized.includes("bash") ||
|
||||
normalized.includes("command") ||
|
||||
@@ -227,17 +239,37 @@ function classifyToolItemType(toolName: string): CanonicalItemType {
|
||||
if (normalized.includes("mcp")) {
|
||||
return "mcp_tool_call";
|
||||
}
|
||||
if (normalized.includes("websearch") || normalized.includes("web search")) {
|
||||
return "web_search";
|
||||
}
|
||||
if (normalized.includes("image")) {
|
||||
return "image_view";
|
||||
}
|
||||
return "dynamic_tool_call";
|
||||
}
|
||||
|
||||
function classifyRequestType(toolName: string): CanonicalRequestType {
|
||||
function isReadOnlyToolName(toolName: string): boolean {
|
||||
const normalized = toolName.toLowerCase();
|
||||
if (normalized === "read" || normalized.includes("read file") || normalized.includes("view")) {
|
||||
return (
|
||||
normalized === "read" ||
|
||||
normalized.includes("read file") ||
|
||||
normalized.includes("view") ||
|
||||
normalized.includes("grep") ||
|
||||
normalized.includes("glob") ||
|
||||
normalized.includes("search")
|
||||
);
|
||||
}
|
||||
|
||||
function classifyRequestType(toolName: string): CanonicalRequestType {
|
||||
if (isReadOnlyToolName(toolName)) {
|
||||
return "file_read_approval";
|
||||
}
|
||||
return classifyToolItemType(toolName) === "command_execution"
|
||||
const itemType = classifyToolItemType(toolName);
|
||||
return itemType === "command_execution"
|
||||
? "command_execution_approval"
|
||||
: "file_change_approval";
|
||||
: itemType === "file_change"
|
||||
? "file_change_approval"
|
||||
: "dynamic_tool_call";
|
||||
}
|
||||
|
||||
function summarizeToolRequest(toolName: string, input: Record<string, unknown>): string {
|
||||
@@ -262,6 +294,12 @@ function titleForTool(itemType: CanonicalItemType): string {
|
||||
return "File change";
|
||||
case "mcp_tool_call":
|
||||
return "MCP tool call";
|
||||
case "collab_agent_tool_call":
|
||||
return "Agent task";
|
||||
case "web_search":
|
||||
return "Web search";
|
||||
case "image_view":
|
||||
return "Image view";
|
||||
case "dynamic_tool_call":
|
||||
return "Tool call";
|
||||
default:
|
||||
@@ -312,7 +350,7 @@ function turnStatusFromResult(result: SDKResultMessage): ProviderRuntimeTurnStat
|
||||
return "failed";
|
||||
}
|
||||
|
||||
function streamKindFromDeltaType(deltaType: string): "assistant_text" | "reasoning_text" {
|
||||
function streamKindFromDeltaType(deltaType: string): ClaudeTextStreamKind {
|
||||
return deltaType.includes("thinking") ? "reasoning_text" : "assistant_text";
|
||||
}
|
||||
|
||||
@@ -350,6 +388,109 @@ function extractAssistantText(message: SDKMessage): string {
|
||||
return fragments.join("");
|
||||
}
|
||||
|
||||
function extractTextContent(value: unknown): string {
|
||||
if (typeof value === "string") {
|
||||
return value;
|
||||
}
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
return value.map((entry) => extractTextContent(entry)).join("");
|
||||
}
|
||||
|
||||
if (!value || typeof value !== "object") {
|
||||
return "";
|
||||
}
|
||||
|
||||
const record = value as {
|
||||
text?: unknown;
|
||||
content?: unknown;
|
||||
};
|
||||
|
||||
if (typeof record.text === "string") {
|
||||
return record.text;
|
||||
}
|
||||
|
||||
return extractTextContent(record.content);
|
||||
}
|
||||
|
||||
function tryParseJsonRecord(value: string): Record<string, unknown> | undefined {
|
||||
try {
|
||||
const parsed = JSON.parse(value);
|
||||
return parsed && typeof parsed === "object" && !Array.isArray(parsed)
|
||||
? (parsed as Record<string, unknown>)
|
||||
: undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function toolInputFingerprint(input: Record<string, unknown>): string | undefined {
|
||||
try {
|
||||
return JSON.stringify(input);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function toolResultStreamKind(itemType: CanonicalItemType): ClaudeToolResultStreamKind | undefined {
|
||||
switch (itemType) {
|
||||
case "command_execution":
|
||||
return "command_output";
|
||||
case "file_change":
|
||||
return "file_change_output";
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function toolResultBlocksFromUserMessage(message: SDKMessage): Array<{
|
||||
readonly toolUseId: string;
|
||||
readonly block: Record<string, unknown>;
|
||||
readonly text: string;
|
||||
readonly isError: boolean;
|
||||
}> {
|
||||
if (message.type !== "user") {
|
||||
return [];
|
||||
}
|
||||
|
||||
const content = (message.message as { content?: unknown } | undefined)?.content;
|
||||
if (!Array.isArray(content)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const blocks: Array<{
|
||||
readonly toolUseId: string;
|
||||
readonly block: Record<string, unknown>;
|
||||
readonly text: string;
|
||||
readonly isError: boolean;
|
||||
}> = [];
|
||||
|
||||
for (const entry of content) {
|
||||
if (!entry || typeof entry !== "object") {
|
||||
continue;
|
||||
}
|
||||
|
||||
const block = entry as Record<string, unknown>;
|
||||
if (block.type !== "tool_result") {
|
||||
continue;
|
||||
}
|
||||
|
||||
const toolUseId = typeof block.tool_use_id === "string" ? block.tool_use_id : undefined;
|
||||
if (!toolUseId) {
|
||||
continue;
|
||||
}
|
||||
|
||||
blocks.push({
|
||||
toolUseId,
|
||||
block,
|
||||
text: extractTextContent(block.content),
|
||||
isError: block.is_error === true,
|
||||
});
|
||||
}
|
||||
|
||||
return blocks;
|
||||
}
|
||||
|
||||
function toSessionError(
|
||||
threadId: ThreadId,
|
||||
cause: unknown,
|
||||
@@ -433,6 +574,10 @@ function sdkNativeItemId(message: SDKMessage): string | undefined {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (message.type === "user") {
|
||||
return toolResultBlocksFromUserMessage(message)[0]?.toolUseId;
|
||||
}
|
||||
|
||||
if (message.type === "stream_event") {
|
||||
const event = message.event as {
|
||||
type?: unknown;
|
||||
@@ -505,7 +650,7 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) {
|
||||
payload: message,
|
||||
},
|
||||
},
|
||||
null,
|
||||
context.session.threadId,
|
||||
);
|
||||
});
|
||||
|
||||
@@ -681,6 +826,40 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const [index, tool] of context.inFlightTools.entries()) {
|
||||
const toolStamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
type: "item.completed",
|
||||
eventId: toolStamp.eventId,
|
||||
provider: PROVIDER,
|
||||
createdAt: toolStamp.createdAt,
|
||||
threadId: context.session.threadId,
|
||||
turnId: turnState.turnId,
|
||||
itemId: asRuntimeItemId(tool.itemId),
|
||||
payload: {
|
||||
itemType: tool.itemType,
|
||||
status: status === "completed" ? "completed" : "failed",
|
||||
title: tool.title,
|
||||
...(tool.detail ? { detail: tool.detail } : {}),
|
||||
data: {
|
||||
toolName: tool.toolName,
|
||||
input: tool.input,
|
||||
},
|
||||
},
|
||||
providerRefs: {
|
||||
...providerThreadRef(context),
|
||||
providerTurnId: turnState.turnId,
|
||||
providerItemId: ProviderItemId.makeUnsafe(tool.itemId),
|
||||
},
|
||||
raw: {
|
||||
source: "claude.sdk.message",
|
||||
method: "claude/result",
|
||||
payload: result ?? { status },
|
||||
},
|
||||
});
|
||||
context.inFlightTools.delete(index);
|
||||
}
|
||||
|
||||
if (!turnState.messageCompleted) {
|
||||
if (!turnState.emittedTextDelta && turnState.fallbackAssistantText.length > 0) {
|
||||
const deltaStamp = yield* makeEventStamp();
|
||||
@@ -780,10 +959,18 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) {
|
||||
|
||||
if (event.type === "content_block_delta") {
|
||||
if (
|
||||
event.delta.type === "text_delta" &&
|
||||
event.delta.text.length > 0 &&
|
||||
(event.delta.type === "text_delta" || event.delta.type === "thinking_delta") &&
|
||||
context.turnState
|
||||
) {
|
||||
const deltaText =
|
||||
event.delta.type === "text_delta"
|
||||
? event.delta.text
|
||||
: typeof event.delta.thinking === "string"
|
||||
? event.delta.thinking
|
||||
: "";
|
||||
if (deltaText.length === 0) {
|
||||
return;
|
||||
}
|
||||
if (!context.turnState.emittedTextDelta) {
|
||||
context.turnState = {
|
||||
...context.turnState,
|
||||
@@ -801,7 +988,7 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) {
|
||||
itemId: asRuntimeItemId(context.turnState.assistantItemId),
|
||||
payload: {
|
||||
streamKind: streamKindFromDeltaType(event.delta.type),
|
||||
delta: event.delta.text,
|
||||
delta: deltaText,
|
||||
},
|
||||
providerRefs: {
|
||||
...providerThreadRef(context),
|
||||
@@ -814,6 +1001,77 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) {
|
||||
payload: message,
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.delta.type === "input_json_delta") {
|
||||
const tool = context.inFlightTools.get(event.index);
|
||||
if (!tool || typeof event.delta.partial_json !== "string") {
|
||||
return;
|
||||
}
|
||||
|
||||
const partialInputJson = tool.partialInputJson + event.delta.partial_json;
|
||||
const parsedInput = tryParseJsonRecord(partialInputJson);
|
||||
const detail = parsedInput
|
||||
? summarizeToolRequest(tool.toolName, parsedInput)
|
||||
: tool.detail;
|
||||
let nextTool: ToolInFlight = {
|
||||
...tool,
|
||||
partialInputJson,
|
||||
...(parsedInput ? { input: parsedInput } : {}),
|
||||
...(detail ? { detail } : {}),
|
||||
};
|
||||
|
||||
const nextFingerprint =
|
||||
parsedInput && Object.keys(parsedInput).length > 0
|
||||
? toolInputFingerprint(parsedInput)
|
||||
: undefined;
|
||||
context.inFlightTools.set(event.index, nextTool);
|
||||
|
||||
if (
|
||||
!parsedInput ||
|
||||
!nextFingerprint ||
|
||||
tool.lastEmittedInputFingerprint === nextFingerprint
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
nextTool = {
|
||||
...nextTool,
|
||||
lastEmittedInputFingerprint: nextFingerprint,
|
||||
};
|
||||
context.inFlightTools.set(event.index, nextTool);
|
||||
|
||||
const stamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
type: "item.updated",
|
||||
eventId: stamp.eventId,
|
||||
provider: PROVIDER,
|
||||
createdAt: stamp.createdAt,
|
||||
threadId: context.session.threadId,
|
||||
...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
|
||||
itemId: asRuntimeItemId(nextTool.itemId),
|
||||
payload: {
|
||||
itemType: nextTool.itemType,
|
||||
status: "inProgress",
|
||||
title: nextTool.title,
|
||||
...(nextTool.detail ? { detail: nextTool.detail } : {}),
|
||||
data: {
|
||||
toolName: nextTool.toolName,
|
||||
input: nextTool.input,
|
||||
},
|
||||
},
|
||||
providerRefs: {
|
||||
...providerThreadRef(context),
|
||||
...(context.turnState ? { providerTurnId: String(context.turnState.turnId) } : {}),
|
||||
providerItemId: ProviderItemId.makeUnsafe(nextTool.itemId),
|
||||
},
|
||||
raw: {
|
||||
source: "claude.sdk.message",
|
||||
method: "claude/stream_event/content_block_delta/input_json_delta",
|
||||
payload: message,
|
||||
},
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -836,6 +1094,8 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) {
|
||||
: {};
|
||||
const itemId = block.id;
|
||||
const detail = summarizeToolRequest(toolName, toolInput);
|
||||
const inputFingerprint =
|
||||
Object.keys(toolInput).length > 0 ? toolInputFingerprint(toolInput) : undefined;
|
||||
|
||||
const tool: ToolInFlight = {
|
||||
itemId,
|
||||
@@ -843,6 +1103,9 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) {
|
||||
toolName,
|
||||
title: titleForTool(itemType),
|
||||
detail,
|
||||
input: toolInput,
|
||||
partialInputJson: "",
|
||||
...(inputFingerprint ? { lastEmittedInputFingerprint: inputFingerprint } : {}),
|
||||
};
|
||||
context.inFlightTools.set(index, tool);
|
||||
|
||||
@@ -885,22 +1148,99 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) {
|
||||
if (!tool) {
|
||||
return;
|
||||
}
|
||||
context.inFlightTools.delete(index);
|
||||
|
||||
let finalTool = tool;
|
||||
if (tool.partialInputJson.length > 0) {
|
||||
const parsedInput = tryParseJsonRecord(tool.partialInputJson);
|
||||
if (parsedInput) {
|
||||
const detail = summarizeToolRequest(tool.toolName, parsedInput);
|
||||
finalTool = {
|
||||
...tool,
|
||||
input: parsedInput,
|
||||
...(detail ? { detail } : {}),
|
||||
};
|
||||
context.inFlightTools.set(index, finalTool);
|
||||
}
|
||||
}
|
||||
|
||||
const stamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
type: "item.completed",
|
||||
type: "item.updated",
|
||||
eventId: stamp.eventId,
|
||||
provider: PROVIDER,
|
||||
createdAt: stamp.createdAt,
|
||||
threadId: context.session.threadId,
|
||||
...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
|
||||
itemId: asRuntimeItemId(finalTool.itemId),
|
||||
payload: {
|
||||
itemType: finalTool.itemType,
|
||||
status: "inProgress",
|
||||
title: finalTool.title,
|
||||
...(finalTool.detail ? { detail: finalTool.detail } : {}),
|
||||
data: {
|
||||
toolName: finalTool.toolName,
|
||||
input: finalTool.input,
|
||||
},
|
||||
},
|
||||
providerRefs: {
|
||||
...providerThreadRef(context),
|
||||
...(context.turnState ? { providerTurnId: String(context.turnState.turnId) } : {}),
|
||||
providerItemId: ProviderItemId.makeUnsafe(finalTool.itemId),
|
||||
},
|
||||
raw: {
|
||||
source: "claude.sdk.message",
|
||||
method: "claude/stream_event/content_block_stop",
|
||||
payload: message,
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
const handleUserMessage = (
|
||||
context: ClaudeSessionContext,
|
||||
message: SDKMessage,
|
||||
): Effect.Effect<void> =>
|
||||
Effect.gen(function* () {
|
||||
if (message.type !== "user") {
|
||||
return;
|
||||
}
|
||||
|
||||
if (context.turnState) {
|
||||
context.turnState.items.push(message.message);
|
||||
}
|
||||
|
||||
for (const toolResult of toolResultBlocksFromUserMessage(message)) {
|
||||
const toolEntry = Array.from(context.inFlightTools.entries()).find(
|
||||
([, tool]) => tool.itemId === toolResult.toolUseId,
|
||||
);
|
||||
if (!toolEntry) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const [index, tool] = toolEntry;
|
||||
const itemStatus = toolResult.isError ? "failed" : "completed";
|
||||
const toolData = {
|
||||
toolName: tool.toolName,
|
||||
input: tool.input,
|
||||
result: toolResult.block,
|
||||
};
|
||||
|
||||
const updatedStamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
type: "item.updated",
|
||||
eventId: updatedStamp.eventId,
|
||||
provider: PROVIDER,
|
||||
createdAt: updatedStamp.createdAt,
|
||||
threadId: context.session.threadId,
|
||||
...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
|
||||
itemId: asRuntimeItemId(tool.itemId),
|
||||
payload: {
|
||||
itemType: tool.itemType,
|
||||
status: "completed",
|
||||
status: toolResult.isError ? "failed" : "inProgress",
|
||||
title: tool.title,
|
||||
...(tool.detail ? { detail: tool.detail } : {}),
|
||||
data: toolData,
|
||||
},
|
||||
providerRefs: {
|
||||
...providerThreadRef(context),
|
||||
@@ -909,10 +1249,68 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) {
|
||||
},
|
||||
raw: {
|
||||
source: "claude.sdk.message",
|
||||
method: "claude/stream_event/content_block_stop",
|
||||
method: "claude/user",
|
||||
payload: message,
|
||||
},
|
||||
});
|
||||
|
||||
const streamKind = toolResultStreamKind(tool.itemType);
|
||||
if (streamKind && toolResult.text.length > 0 && context.turnState) {
|
||||
const deltaStamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
type: "content.delta",
|
||||
eventId: deltaStamp.eventId,
|
||||
provider: PROVIDER,
|
||||
createdAt: deltaStamp.createdAt,
|
||||
threadId: context.session.threadId,
|
||||
turnId: context.turnState.turnId,
|
||||
itemId: asRuntimeItemId(tool.itemId),
|
||||
payload: {
|
||||
streamKind,
|
||||
delta: toolResult.text,
|
||||
},
|
||||
providerRefs: {
|
||||
...providerThreadRef(context),
|
||||
providerTurnId: context.turnState.turnId,
|
||||
providerItemId: ProviderItemId.makeUnsafe(tool.itemId),
|
||||
},
|
||||
raw: {
|
||||
source: "claude.sdk.message",
|
||||
method: "claude/user",
|
||||
payload: message,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const completedStamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
type: "item.completed",
|
||||
eventId: completedStamp.eventId,
|
||||
provider: PROVIDER,
|
||||
createdAt: completedStamp.createdAt,
|
||||
threadId: context.session.threadId,
|
||||
...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
|
||||
itemId: asRuntimeItemId(tool.itemId),
|
||||
payload: {
|
||||
itemType: tool.itemType,
|
||||
status: itemStatus,
|
||||
title: tool.title,
|
||||
...(tool.detail ? { detail: tool.detail } : {}),
|
||||
data: toolData,
|
||||
},
|
||||
providerRefs: {
|
||||
...providerThreadRef(context),
|
||||
...(context.turnState ? { providerTurnId: String(context.turnState.turnId) } : {}),
|
||||
providerItemId: ProviderItemId.makeUnsafe(tool.itemId),
|
||||
},
|
||||
raw: {
|
||||
source: "claude.sdk.message",
|
||||
method: "claude/user",
|
||||
payload: message,
|
||||
},
|
||||
});
|
||||
|
||||
context.inFlightTools.delete(index);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1242,6 +1640,7 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) {
|
||||
yield* handleStreamEvent(context, message);
|
||||
return;
|
||||
case "user":
|
||||
yield* handleUserMessage(context, message);
|
||||
return;
|
||||
case "assistant":
|
||||
yield* handleAssistantMessage(context, message);
|
||||
|
||||
@@ -5,9 +5,11 @@ import * as PlatformError from "effect/PlatformError";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import {
|
||||
checkClaudeCodeProviderStatus,
|
||||
checkCodexProviderStatus,
|
||||
hasCustomModelProvider,
|
||||
parseAuthStatusFromOutput,
|
||||
parseClaudeAuthStatusFromOutput,
|
||||
readCodexConfigModelProvider,
|
||||
} from "./ProviderHealth";
|
||||
|
||||
@@ -464,4 +466,175 @@ it.layer(NodeServices.layer)("ProviderHealth", (it) => {
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
// ── checkClaudeCodeProviderStatus tests ──────────────────────────
|
||||
|
||||
describe("checkClaudeCodeProviderStatus", () => {
|
||||
it.effect("returns ready when claude is installed and authenticated", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeCodeProviderStatus;
|
||||
assert.strictEqual(status.provider, "claudeCode");
|
||||
assert.strictEqual(status.status, "ready");
|
||||
assert.strictEqual(status.available, true);
|
||||
assert.strictEqual(status.authStatus, "authenticated");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "auth status")
|
||||
return {
|
||||
stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
|
||||
stderr: "",
|
||||
code: 0,
|
||||
};
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns unavailable when claude is missing", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeCodeProviderStatus;
|
||||
assert.strictEqual(status.provider, "claudeCode");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.available, false);
|
||||
assert.strictEqual(status.authStatus, "unknown");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Claude Code CLI (`claude`) is not installed or not on PATH.",
|
||||
);
|
||||
}).pipe(Effect.provide(failingSpawnerLayer("spawn claude ENOENT"))),
|
||||
);
|
||||
|
||||
it.effect("returns error when version check fails with non-zero exit code", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeCodeProviderStatus;
|
||||
assert.strictEqual(status.provider, "claudeCode");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.available, false);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version")
|
||||
return { stdout: "", stderr: "Something went wrong", code: 1 };
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns unauthenticated when auth status reports not logged in", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeCodeProviderStatus;
|
||||
assert.strictEqual(status.provider, "claudeCode");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.available, true);
|
||||
assert.strictEqual(status.authStatus, "unauthenticated");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Claude Code is not authenticated. Run `claude auth login` and try again.",
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "auth status")
|
||||
return {
|
||||
stdout: '{"loggedIn":false}\n',
|
||||
stderr: "",
|
||||
code: 1,
|
||||
};
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns unauthenticated when output includes 'not logged in'", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeCodeProviderStatus;
|
||||
assert.strictEqual(status.provider, "claudeCode");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.available, true);
|
||||
assert.strictEqual(status.authStatus, "unauthenticated");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "auth status") return { stdout: "Not logged in\n", stderr: "", code: 1 };
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns warning when auth status command is unsupported", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeCodeProviderStatus;
|
||||
assert.strictEqual(status.provider, "claudeCode");
|
||||
assert.strictEqual(status.status, "warning");
|
||||
assert.strictEqual(status.available, true);
|
||||
assert.strictEqual(status.authStatus, "unknown");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Claude Code authentication status command is unavailable in this version of Claude Code.",
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
|
||||
if (joined === "auth status")
|
||||
return { stdout: "", stderr: "error: unknown command 'auth'", code: 2 };
|
||||
throw new Error(`Unexpected args: ${joined}`);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
// ── parseClaudeAuthStatusFromOutput pure tests ────────────────────
|
||||
|
||||
describe("parseClaudeAuthStatusFromOutput", () => {
|
||||
it("exit code 0 with no auth markers is ready", () => {
|
||||
const parsed = parseClaudeAuthStatusFromOutput({ stdout: "OK\n", stderr: "", code: 0 });
|
||||
assert.strictEqual(parsed.status, "ready");
|
||||
assert.strictEqual(parsed.authStatus, "authenticated");
|
||||
});
|
||||
|
||||
it("JSON with loggedIn=true is authenticated", () => {
|
||||
const parsed = parseClaudeAuthStatusFromOutput({
|
||||
stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
|
||||
stderr: "",
|
||||
code: 0,
|
||||
});
|
||||
assert.strictEqual(parsed.status, "ready");
|
||||
assert.strictEqual(parsed.authStatus, "authenticated");
|
||||
});
|
||||
|
||||
it("JSON with loggedIn=false is unauthenticated", () => {
|
||||
const parsed = parseClaudeAuthStatusFromOutput({
|
||||
stdout: '{"loggedIn":false}\n',
|
||||
stderr: "",
|
||||
code: 0,
|
||||
});
|
||||
assert.strictEqual(parsed.status, "error");
|
||||
assert.strictEqual(parsed.authStatus, "unauthenticated");
|
||||
});
|
||||
|
||||
it("JSON without auth marker is warning", () => {
|
||||
const parsed = parseClaudeAuthStatusFromOutput({
|
||||
stdout: '{"ok":true}\n',
|
||||
stderr: "",
|
||||
code: 0,
|
||||
});
|
||||
assert.strictEqual(parsed.status, "warning");
|
||||
assert.strictEqual(parsed.authStatus, "unknown");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -26,6 +26,7 @@ import { ProviderHealth, type ProviderHealthShape } from "../Services/ProviderHe
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 4_000;
|
||||
const CODEX_PROVIDER = "codex" as const;
|
||||
const CLAUDE_CODE_PROVIDER = "claudeCode" as const;
|
||||
|
||||
// ── Pure helpers ────────────────────────────────────────────────────
|
||||
|
||||
@@ -44,12 +45,7 @@ function nonEmptyTrimmed(value: string | undefined): string | undefined {
|
||||
function isCommandMissingCause(error: unknown): boolean {
|
||||
if (!(error instanceof Error)) return false;
|
||||
const lower = error.message.toLowerCase();
|
||||
return (
|
||||
lower.includes("command not found: codex") ||
|
||||
lower.includes("spawn codex enoent") ||
|
||||
lower.includes("enoent") ||
|
||||
lower.includes("notfound")
|
||||
);
|
||||
return lower.includes("enoent") || lower.includes("notfound");
|
||||
}
|
||||
|
||||
function detailFromResult(
|
||||
@@ -264,6 +260,27 @@ const runCodexCommand = (args: ReadonlyArray<string>) =>
|
||||
return { stdout, stderr, code: exitCode } satisfies CommandResult;
|
||||
}).pipe(Effect.scoped);
|
||||
|
||||
const runClaudeCommand = (args: ReadonlyArray<string>) =>
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const command = ChildProcess.make("claude", [...args], {
|
||||
shell: process.platform === "win32",
|
||||
});
|
||||
|
||||
const child = yield* spawner.spawn(command);
|
||||
|
||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||
[
|
||||
collectStreamAsString(child.stdout),
|
||||
collectStreamAsString(child.stderr),
|
||||
child.exitCode.pipe(Effect.map(Number)),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
return { stdout, stderr, code: exitCode } satisfies CommandResult;
|
||||
}).pipe(Effect.scoped);
|
||||
|
||||
// ── Health check ────────────────────────────────────────────────────
|
||||
|
||||
export const checkCodexProviderStatus: Effect.Effect<
|
||||
@@ -390,18 +407,199 @@ export const checkCodexProviderStatus: Effect.Effect<
|
||||
} satisfies ServerProviderStatus;
|
||||
});
|
||||
|
||||
// ── Claude Code health check ────────────────────────────────────────
|
||||
|
||||
export function parseClaudeAuthStatusFromOutput(result: CommandResult): {
|
||||
readonly status: ServerProviderStatusState;
|
||||
readonly authStatus: ServerProviderAuthStatus;
|
||||
readonly message?: string;
|
||||
} {
|
||||
const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
|
||||
|
||||
if (
|
||||
lowerOutput.includes("unknown command") ||
|
||||
lowerOutput.includes("unrecognized command") ||
|
||||
lowerOutput.includes("unexpected argument")
|
||||
) {
|
||||
return {
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
message:
|
||||
"Claude Code authentication status command is unavailable in this version of Claude Code.",
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
lowerOutput.includes("not logged in") ||
|
||||
lowerOutput.includes("login required") ||
|
||||
lowerOutput.includes("authentication required") ||
|
||||
lowerOutput.includes("run `claude login`") ||
|
||||
lowerOutput.includes("run claude login")
|
||||
) {
|
||||
return {
|
||||
status: "error",
|
||||
authStatus: "unauthenticated",
|
||||
message: "Claude Code is not authenticated. Run `claude auth login` and try again.",
|
||||
};
|
||||
}
|
||||
|
||||
// `claude auth status` returns JSON with a `loggedIn` boolean.
|
||||
const parsedAuth = (() => {
|
||||
const trimmed = result.stdout.trim();
|
||||
if (!trimmed || (!trimmed.startsWith("{") && !trimmed.startsWith("["))) {
|
||||
return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
|
||||
}
|
||||
try {
|
||||
return {
|
||||
attemptedJsonParse: true as const,
|
||||
auth: extractAuthBoolean(JSON.parse(trimmed)),
|
||||
};
|
||||
} catch {
|
||||
return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
|
||||
}
|
||||
})();
|
||||
|
||||
if (parsedAuth.auth === true) {
|
||||
return { status: "ready", authStatus: "authenticated" };
|
||||
}
|
||||
if (parsedAuth.auth === false) {
|
||||
return {
|
||||
status: "error",
|
||||
authStatus: "unauthenticated",
|
||||
message: "Claude Code is not authenticated. Run `claude auth login` and try again.",
|
||||
};
|
||||
}
|
||||
if (parsedAuth.attemptedJsonParse) {
|
||||
return {
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
message:
|
||||
"Could not verify Claude Code authentication status from JSON output (missing auth marker).",
|
||||
};
|
||||
}
|
||||
if (result.code === 0) {
|
||||
return { status: "ready", authStatus: "authenticated" };
|
||||
}
|
||||
|
||||
const detail = detailFromResult(result);
|
||||
return {
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
message: detail
|
||||
? `Could not verify Claude Code authentication status. ${detail}`
|
||||
: "Could not verify Claude Code authentication status.",
|
||||
};
|
||||
}
|
||||
|
||||
export const checkClaudeCodeProviderStatus: Effect.Effect<
|
||||
ServerProviderStatus,
|
||||
never,
|
||||
ChildProcessSpawner.ChildProcessSpawner
|
||||
> = Effect.gen(function* () {
|
||||
const checkedAt = new Date().toISOString();
|
||||
|
||||
// Probe 1: `claude --version` — is the CLI reachable?
|
||||
const versionProbe = yield* runClaudeCommand(["--version"]).pipe(
|
||||
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
);
|
||||
|
||||
if (Result.isFailure(versionProbe)) {
|
||||
const error = versionProbe.failure;
|
||||
return {
|
||||
provider: CLAUDE_CODE_PROVIDER,
|
||||
status: "error" as const,
|
||||
available: false,
|
||||
authStatus: "unknown" as const,
|
||||
checkedAt,
|
||||
message: isCommandMissingCause(error)
|
||||
? "Claude Code CLI (`claude`) is not installed or not on PATH."
|
||||
: `Failed to execute Claude Code CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
|
||||
};
|
||||
}
|
||||
|
||||
if (Option.isNone(versionProbe.success)) {
|
||||
return {
|
||||
provider: CLAUDE_CODE_PROVIDER,
|
||||
status: "error" as const,
|
||||
available: false,
|
||||
authStatus: "unknown" as const,
|
||||
checkedAt,
|
||||
message: "Claude Code CLI is installed but failed to run. Timed out while running command.",
|
||||
};
|
||||
}
|
||||
|
||||
const version = versionProbe.success.value;
|
||||
if (version.code !== 0) {
|
||||
const detail = detailFromResult(version);
|
||||
return {
|
||||
provider: CLAUDE_CODE_PROVIDER,
|
||||
status: "error" as const,
|
||||
available: false,
|
||||
authStatus: "unknown" as const,
|
||||
checkedAt,
|
||||
message: detail
|
||||
? `Claude Code CLI is installed but failed to run. ${detail}`
|
||||
: "Claude Code CLI is installed but failed to run.",
|
||||
};
|
||||
}
|
||||
|
||||
// Probe 2: `claude auth status` — is the user authenticated?
|
||||
const authProbe = yield* runClaudeCommand(["auth", "status"]).pipe(
|
||||
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
);
|
||||
|
||||
if (Result.isFailure(authProbe)) {
|
||||
const error = authProbe.failure;
|
||||
return {
|
||||
provider: CLAUDE_CODE_PROVIDER,
|
||||
status: "warning" as const,
|
||||
available: true,
|
||||
authStatus: "unknown" as const,
|
||||
checkedAt,
|
||||
message:
|
||||
error instanceof Error
|
||||
? `Could not verify Claude Code authentication status: ${error.message}.`
|
||||
: "Could not verify Claude Code authentication status.",
|
||||
};
|
||||
}
|
||||
|
||||
if (Option.isNone(authProbe.success)) {
|
||||
return {
|
||||
provider: CLAUDE_CODE_PROVIDER,
|
||||
status: "warning" as const,
|
||||
available: true,
|
||||
authStatus: "unknown" as const,
|
||||
checkedAt,
|
||||
message:
|
||||
"Could not verify Claude Code authentication status. Timed out while running command.",
|
||||
};
|
||||
}
|
||||
|
||||
const parsed = parseClaudeAuthStatusFromOutput(authProbe.success.value);
|
||||
return {
|
||||
provider: CLAUDE_CODE_PROVIDER,
|
||||
status: parsed.status,
|
||||
available: true,
|
||||
authStatus: parsed.authStatus,
|
||||
checkedAt,
|
||||
...(parsed.message ? { message: parsed.message } : {}),
|
||||
} satisfies ServerProviderStatus;
|
||||
});
|
||||
|
||||
// ── Layer ───────────────────────────────────────────────────────────
|
||||
|
||||
export const ProviderHealthLive = Layer.effect(
|
||||
ProviderHealth,
|
||||
Effect.gen(function* () {
|
||||
const codexStatusFiber = yield* checkCodexProviderStatus.pipe(
|
||||
Effect.map(Array.of),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
const statusesFiber = yield* Effect.all(
|
||||
[checkCodexProviderStatus, checkClaudeCodeProviderStatus],
|
||||
{ concurrency: "unbounded" },
|
||||
).pipe(Effect.forkScoped);
|
||||
|
||||
return {
|
||||
getStatuses: Fiber.join(codexStatusFiber),
|
||||
getStatuses: Fiber.join(statusesFiber),
|
||||
} satisfies ProviderHealthShape;
|
||||
}),
|
||||
);
|
||||
@@ -52,7 +52,7 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
type LegacyProviderRuntimeEvent = {
|
||||
readonly type: string;
|
||||
readonly eventId: EventId;
|
||||
readonly provider: "codex" | "claudeCode";
|
||||
readonly provider: ProviderKind;
|
||||
readonly createdAt: string;
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId?: string | undefined;
|
||||
|
||||
@@ -17,7 +17,7 @@ import {
|
||||
MenuSubTrigger,
|
||||
MenuTrigger,
|
||||
} from "../ui/menu";
|
||||
import { ClaudeAI, Gemini, Icon, OpenAI, OpenCodeIcon } from "../Icons";
|
||||
import { ClaudeAI, CursorIcon, Gemini, Icon, OpenAI, OpenCodeIcon } from "../Icons";
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
function isAvailableProviderOption(option: (typeof PROVIDER_OPTIONS)[number]): option is {
|
||||
@@ -64,6 +64,7 @@ function resolveModelForProviderPicker(
|
||||
const PROVIDER_ICON_BY_PROVIDER: Record<ProviderPickerKind, Icon> = {
|
||||
codex: OpenAI,
|
||||
claudeCode: ClaudeAI,
|
||||
cursor: CursorIcon,
|
||||
};
|
||||
|
||||
export const AVAILABLE_PROVIDER_OPTIONS = PROVIDER_OPTIONS.filter(isAvailableProviderOption);
|
||||
@@ -174,10 +175,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
|
||||
<MenuItem key={option.value} disabled>
|
||||
<OptionIcon
|
||||
aria-hidden="true"
|
||||
className={cn(
|
||||
"size-4 shrink-0 opacity-80",
|
||||
option.value === "claudeCode" ? "" : "text-muted-foreground/85",
|
||||
)}
|
||||
className="size-4 shrink-0 text-muted-foreground/85 opacity-80"
|
||||
/>
|
||||
<span>{option.label}</span>
|
||||
<span className="ms-auto text-[11px] text-muted-foreground/80 uppercase tracking-[0.08em]">
|
||||
|
||||
@@ -673,16 +673,23 @@ describe("deriveActiveWorkStartedAt", () => {
|
||||
});
|
||||
|
||||
describe("PROVIDER_OPTIONS", () => {
|
||||
it("advertises the supported providers", () => {
|
||||
it("advertises Claude Code as available while keeping Cursor as a placeholder", () => {
|
||||
const claude = PROVIDER_OPTIONS.find((option) => option.value === "claudeCode");
|
||||
const cursor = PROVIDER_OPTIONS.find((option) => option.value === "cursor");
|
||||
expect(PROVIDER_OPTIONS).toEqual([
|
||||
{ value: "codex", label: "Codex", available: true },
|
||||
{ value: "claudeCode", label: "Claude Code", available: true },
|
||||
{ value: "cursor", label: "Cursor", available: false },
|
||||
]);
|
||||
expect(claude).toEqual({
|
||||
value: "claudeCode",
|
||||
label: "Claude Code",
|
||||
available: true,
|
||||
});
|
||||
expect(cursor).toEqual({
|
||||
value: "cursor",
|
||||
label: "Cursor",
|
||||
available: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -18,7 +18,7 @@ import type {
|
||||
TurnDiffSummary,
|
||||
} from "./types";
|
||||
|
||||
export type ProviderPickerKind = ProviderKind;
|
||||
export type ProviderPickerKind = ProviderKind | "cursor";
|
||||
|
||||
export const PROVIDER_OPTIONS: Array<{
|
||||
value: ProviderPickerKind;
|
||||
@@ -27,6 +27,7 @@ export const PROVIDER_OPTIONS: Array<{
|
||||
}> = [
|
||||
{ value: "codex", label: "Codex", available: true },
|
||||
{ value: "claudeCode", label: "Claude Code", available: true },
|
||||
{ value: "cursor", label: "Cursor", available: false },
|
||||
];
|
||||
|
||||
export interface WorkLogEntry {
|
||||
|
||||
@@ -130,11 +130,11 @@ it.effect("preserves explicit provider and runtime mode in thread.turn.start", (
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
},
|
||||
provider: "claudeCode",
|
||||
provider: "codex",
|
||||
runtimeMode: "full-access",
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
assert.strictEqual(parsed.provider, "claudeCode");
|
||||
assert.strictEqual(parsed.provider, "codex");
|
||||
assert.strictEqual(parsed.runtimeMode, "full-access");
|
||||
assert.strictEqual(parsed.interactionMode, DEFAULT_PROVIDER_INTERACTION_MODE);
|
||||
}),
|
||||
|
||||
@@ -43,20 +43,24 @@ export const ProviderSandboxMode = Schema.Literals([
|
||||
]);
|
||||
export type ProviderSandboxMode = typeof ProviderSandboxMode.Type;
|
||||
export const DEFAULT_PROVIDER_KIND: ProviderKind = "codex";
|
||||
const CodexProviderStartOptions = Schema.Struct({
|
||||
|
||||
export const CodexProviderStartOptions = Schema.Struct({
|
||||
binaryPath: Schema.optional(TrimmedNonEmptyString),
|
||||
homePath: Schema.optional(TrimmedNonEmptyString),
|
||||
});
|
||||
const ProviderStartOptions = Schema.Struct({
|
||||
codex: Schema.optional(CodexProviderStartOptions),
|
||||
claudeCode: Schema.optional(
|
||||
Schema.Struct({
|
||||
binaryPath: Schema.optional(TrimmedNonEmptyString),
|
||||
permissionMode: Schema.optional(TrimmedNonEmptyString),
|
||||
maxThinkingTokens: Schema.optional(NonNegativeInt),
|
||||
}),
|
||||
),
|
||||
|
||||
export const ClaudeCodeProviderStartOptions = Schema.Struct({
|
||||
binaryPath: Schema.optional(TrimmedNonEmptyString),
|
||||
permissionMode: Schema.optional(TrimmedNonEmptyString),
|
||||
maxThinkingTokens: Schema.optional(NonNegativeInt),
|
||||
});
|
||||
|
||||
export const ProviderStartOptions = Schema.Struct({
|
||||
codex: Schema.optional(CodexProviderStartOptions),
|
||||
claudeCode: Schema.optional(ClaudeCodeProviderStartOptions),
|
||||
});
|
||||
export type ProviderStartOptions = typeof ProviderStartOptions.Type;
|
||||
|
||||
export const RuntimeMode = Schema.Literals(["approval-required", "full-access"]);
|
||||
export type RuntimeMode = typeof RuntimeMode.Type;
|
||||
export const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
|
||||
|
||||
@@ -5,7 +5,6 @@ import {
|
||||
ApprovalRequestId,
|
||||
EventId,
|
||||
IsoDateTime,
|
||||
NonNegativeInt,
|
||||
ProviderItemId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
@@ -20,11 +19,11 @@ import {
|
||||
ProviderKind,
|
||||
ProviderRequestKind,
|
||||
ProviderSandboxMode,
|
||||
ProviderStartOptions,
|
||||
ProviderUserInputAnswers,
|
||||
RuntimeMode,
|
||||
} from "./orchestration";
|
||||
|
||||
const TrimmedNonEmptyStringSchema = TrimmedNonEmptyString;
|
||||
const ProviderSessionStatus = Schema.Literals([
|
||||
"connecting",
|
||||
"ready",
|
||||
@@ -37,39 +36,22 @@ export const ProviderSession = Schema.Struct({
|
||||
provider: ProviderKind,
|
||||
status: ProviderSessionStatus,
|
||||
runtimeMode: RuntimeMode,
|
||||
cwd: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
model: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
cwd: Schema.optional(TrimmedNonEmptyString),
|
||||
model: Schema.optional(TrimmedNonEmptyString),
|
||||
threadId: ThreadId,
|
||||
resumeCursor: Schema.optional(Schema.Unknown),
|
||||
activeTurnId: Schema.optional(TurnId),
|
||||
createdAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
lastError: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
lastError: Schema.optional(TrimmedNonEmptyString),
|
||||
});
|
||||
export type ProviderSession = typeof ProviderSession.Type;
|
||||
|
||||
const CodexProviderStartOptions = Schema.Struct({
|
||||
binaryPath: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
homePath: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
});
|
||||
|
||||
const ClaudeCodeProviderStartOptions = Schema.Struct({
|
||||
binaryPath: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
permissionMode: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
maxThinkingTokens: Schema.optional(NonNegativeInt),
|
||||
});
|
||||
|
||||
export const ProviderStartOptions = Schema.Struct({
|
||||
codex: Schema.optional(CodexProviderStartOptions),
|
||||
claudeCode: Schema.optional(ClaudeCodeProviderStartOptions),
|
||||
});
|
||||
export type ProviderStartOptions = typeof ProviderStartOptions.Type;
|
||||
|
||||
export const ProviderSessionStartInput = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
provider: Schema.optional(ProviderKind),
|
||||
cwd: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
model: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
cwd: Schema.optional(TrimmedNonEmptyString),
|
||||
model: Schema.optional(TrimmedNonEmptyString),
|
||||
modelOptions: Schema.optional(ProviderModelOptions),
|
||||
resumeCursor: Schema.optional(Schema.Unknown),
|
||||
approvalPolicy: Schema.optional(ProviderApprovalPolicy),
|
||||
@@ -82,12 +64,12 @@ export type ProviderSessionStartInput = typeof ProviderSessionStartInput.Type;
|
||||
export const ProviderSendTurnInput = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
input: Schema.optional(
|
||||
TrimmedNonEmptyStringSchema.check(Schema.isMaxLength(PROVIDER_SEND_TURN_MAX_INPUT_CHARS)),
|
||||
TrimmedNonEmptyString.check(Schema.isMaxLength(PROVIDER_SEND_TURN_MAX_INPUT_CHARS)),
|
||||
),
|
||||
attachments: Schema.optional(
|
||||
Schema.Array(ChatAttachment).check(Schema.isMaxLength(PROVIDER_SEND_TURN_MAX_ATTACHMENTS)),
|
||||
),
|
||||
model: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
model: Schema.optional(TrimmedNonEmptyString),
|
||||
modelOptions: Schema.optional(ProviderModelOptions),
|
||||
interactionMode: Schema.optional(ProviderInteractionMode),
|
||||
});
|
||||
@@ -133,8 +115,8 @@ export const ProviderEvent = Schema.Struct({
|
||||
provider: ProviderKind,
|
||||
threadId: ThreadId,
|
||||
createdAt: IsoDateTime,
|
||||
method: TrimmedNonEmptyStringSchema,
|
||||
message: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
method: TrimmedNonEmptyString,
|
||||
message: Schema.optional(TrimmedNonEmptyString),
|
||||
turnId: Schema.optional(TurnId),
|
||||
itemId: Schema.optional(ProviderItemId),
|
||||
requestId: Schema.optional(ApprovalRequestId),
|
||||
|
||||
Reference in new issue
Block a user