Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 8 additions & 14 deletions apps/server/src/provider/Layers/ProviderHealth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -535,7 +535,7 @@ it.layer(NodeServices.layer)("ProviderHealth", (it) => {
assert.strictEqual(status.authStatus, "unauthenticated");
assert.strictEqual(
status.message,
"Claude is not configured with a supported Anthropic credential. Set ANTHROPIC_API_KEY or ANTHROPIC_AUTH_TOKEN and try again.",
"Claude is not configured with a supported Anthropic credential. Run `claude auth login`, or set ANTHROPIC_API_KEY / ANTHROPIC_AUTH_TOKEN, and try again.",
);
}).pipe(
Effect.provide(
Expand All @@ -554,17 +554,14 @@ it.layer(NodeServices.layer)("ProviderHealth", (it) => {
),
);

it.effect("returns unauthenticated when auth status reports oauth auth", () =>
it.effect("returns authenticated when auth status reports Claude.ai auth", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus;
assert.strictEqual(status.provider, "claudeAgent");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.available, true);
assert.strictEqual(status.authStatus, "unauthenticated");
assert.strictEqual(
status.message,
"Claude Code is signed in with OAuth, which is not supported here. Set ANTHROPIC_API_KEY or ANTHROPIC_AUTH_TOKEN and try again.",
);
assert.strictEqual(status.authStatus, "authenticated");
assert.strictEqual(status.message, "Claude Code CLI is ready via Claude.ai login.");
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
Expand Down Expand Up @@ -641,12 +638,9 @@ it.layer(NodeServices.layer)("ProviderHealth", (it) => {
stderr: "",
code: 0,
});
assert.strictEqual(parsed.status, "error");
assert.strictEqual(parsed.authStatus, "unauthenticated");
assert.strictEqual(
parsed.message,
"Claude Code is signed in with OAuth, which is not supported here. Set ANTHROPIC_API_KEY or ANTHROPIC_AUTH_TOKEN and try again.",
);
assert.strictEqual(parsed.status, "ready");
assert.strictEqual(parsed.authStatus, "authenticated");
assert.strictEqual(parsed.message, "Claude Code CLI is ready via Claude.ai login.");
});

it("JSON with loggedIn=false is unauthenticated", () => {
Expand Down
22 changes: 11 additions & 11 deletions apps/server/src/provider/Layers/ProviderHealth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,9 +130,10 @@ function extractAuthString(value: unknown): string | undefined {
return undefined;
}

const CLAUDE_OAUTH_AUTH_METHODS = new Set(["claude.ai", "oauth"]);
const CLAUDE_SUPPORTED_AUTH_METHODS = new Set(["apiKey", "authToken"]);
const CLAUDE_AUTH_GUIDANCE = "Set ANTHROPIC_API_KEY or ANTHROPIC_AUTH_TOKEN and try again.";
const CLAUDE_CLI_AUTH_METHODS = new Set(["claude.ai", "oauth"]);
const CLAUDE_SUPPORTED_AUTH_METHODS = new Set(["apiKey", "authToken", "claude.ai", "oauth"]);
const CLAUDE_AUTH_GUIDANCE =
"Run `claude auth login`, or set ANTHROPIC_API_KEY / ANTHROPIC_AUTH_TOKEN, and try again.";

export function parseAuthStatusFromOutput(result: CommandResult): {
readonly status: ServerProviderStatusState;
Expand Down Expand Up @@ -619,14 +620,6 @@ export function parseClaudeAuthStatusFromOutput(result: CommandResult): {

const authMethod = parsedAuth.authMethod?.trim();
const normalizedAuthMethod = authMethod?.toLowerCase();
if (normalizedAuthMethod && CLAUDE_OAUTH_AUTH_METHODS.has(normalizedAuthMethod)) {
return {
status: "error",
authStatus: "unauthenticated",
message: `Claude Code is signed in with OAuth, which is not supported here. ${CLAUDE_AUTH_GUIDANCE}`,
};
}

if (parsedAuth.auth === true) {
if (authMethod && !CLAUDE_SUPPORTED_AUTH_METHODS.has(authMethod)) {
return {
Expand All @@ -635,6 +628,13 @@ export function parseClaudeAuthStatusFromOutput(result: CommandResult): {
message: `Claude authentication status reported an unsupported credential type '${authMethod}'. ${CLAUDE_AUTH_GUIDANCE}`,
};
}
if (normalizedAuthMethod && CLAUDE_CLI_AUTH_METHODS.has(normalizedAuthMethod)) {
return {
status: "ready",
authStatus: "authenticated",
message: "Claude Code CLI is ready via Claude.ai login.",
};
}
return { status: "ready", authStatus: "authenticated" };
}
if (parsedAuth.auth === false) {
Expand Down
76 changes: 75 additions & 1 deletion apps/server/src/sme/Layers/SmeChatServiceLive.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ describe("SmeChatServiceLive", () => {
projectId,
title: "Architecture Q&A",
provider: "claudeAgent",
authMethod: "apiKey",
authMethod: "auto",
model: "claude-sonnet-4-6",
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
Expand Down Expand Up @@ -236,6 +236,80 @@ describe("SmeChatServiceLive", () => {
]);
});

it("honors the selected API key auth method even when an auth token helper is also configured", async () => {
const projectId = ProjectId.makeUnsafe("project-api-key");
const conversationId = SmeConversationId.makeUnsafe("conversation-api-key");
const conversationRow: SmeConversationRow = {
conversationId,
projectId,
title: "API key only",
provider: "claudeAgent",
authMethod: "apiKey",
model: "claude-sonnet-4-6",
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
deletedAt: null,
};
const { repository: messageRepo } = makeMessageRepository();
const sendInputs: Array<any> = [];
const sendClaudeMessage = (input: any) =>
Effect.sync(() => {
sendInputs.push(input);
return "Used API key";
});

const layer = makeSmeChatServiceLive({ sendSmeViaAnthropic: sendClaudeMessage }).pipe(
Layer.provideMerge(Layer.succeed(SmeKnowledgeDocumentRepository, makeDocumentRepository())),
Layer.provideMerge(
Layer.succeed(SmeConversationRepository, makeConversationRepository([conversationRow])),
),
Layer.provideMerge(Layer.succeed(SmeMessageRepository, messageRepo)),
);

const savedEnv = {
ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY,
ANTHROPIC_AUTH_TOKEN: process.env.ANTHROPIC_AUTH_TOKEN,
};
process.env.ANTHROPIC_API_KEY = "api-key-from-env";
delete process.env.ANTHROPIC_AUTH_TOKEN;

try {
await Effect.runPromise(
Effect.gen(function* () {
const service = yield* SmeChatService;
yield* service.sendMessage({
conversationId,
text: "Use the SDK credentials",
providerOptions: {
claudeAgent: {
authTokenHelperCommand: "printf helper-token",
},
},
});
}).pipe(Effect.provide(layer)),
);
} finally {
if (savedEnv.ANTHROPIC_API_KEY === undefined) {
delete process.env.ANTHROPIC_API_KEY;
} else {
process.env.ANTHROPIC_API_KEY = savedEnv.ANTHROPIC_API_KEY;
}
if (savedEnv.ANTHROPIC_AUTH_TOKEN === undefined) {
delete process.env.ANTHROPIC_AUTH_TOKEN;
} else {
process.env.ANTHROPIC_AUTH_TOKEN = savedEnv.ANTHROPIC_AUTH_TOKEN;
}
}

expect(sendInputs).toHaveLength(1);
expect(sendInputs[0].clientOptions).toEqual(
expect.objectContaining({
apiKey: "api-key-from-env",
authToken: null,
}),
);
});

it("fails before sending when Claude credentials are unavailable", async () => {
const projectId = ProjectId.makeUnsafe("project-2");
const conversationId = SmeConversationId.makeUnsafe("conversation-2");
Expand Down
49 changes: 19 additions & 30 deletions apps/server/src/sme/Layers/SmeChatServiceLive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ import crypto from "node:crypto";
import { SmeConversationRepository } from "../../persistence/Services/SmeConversations.ts";
import { SmeKnowledgeDocumentRepository } from "../../persistence/Services/SmeKnowledgeDocuments.ts";
import { SmeMessageRepository } from "../../persistence/Services/SmeMessages.ts";
import { isValidSmeAuthMethod } from "../authValidation.ts";
import { resolveAnthropicClientOptions, sendSmeViaAnthropic } from "../backends/anthropic.ts";
import { isValidSmeAuthMethod, resolveClaudeSmeSetup } from "../authValidation.ts";
import { sendSmeViaAnthropic } from "../backends/anthropic.ts";
import { buildSmeSystemPrompt } from "../promptBuilder.ts";
import {
SmeChatError,
Expand Down Expand Up @@ -161,36 +161,19 @@ const makeSmeChatService = (options?: SmeChatServiceLiveOptions) =>
};
}

const clientOptions = yield* Effect.try({
const resolvedSetup = yield* Effect.try({
try: () =>
resolveAnthropicClientOptions({
resolveClaudeSmeSetup({
authMethod: conversation.authMethod as Extract<
SmeAuthMethod,
"auto" | "apiKey" | "authToken"
>,
providerOptions: providerOptions?.claudeAgent,
}),
catch: (cause) => new SmeChatError("validateSetup", String(cause), cause),
});

if (!clientOptions.apiKey && !clientOptions.authToken) {
return {
ok: false,
severity: "error" as const,
message:
"Claude SME Chat needs an Anthropic API key, auth token, or auth token helper command. Set ANTHROPIC_API_KEY or ANTHROPIC_AUTH_TOKEN, or configure `authTokenHelperCommand` in Settings.",
resolvedAuthMethod: conversation.authMethod,
resolvedAccountType: "unknown" as const,
};
}

return {
ok: true,
severity: "ready" as const,
message:
clientOptions.apiKey !== null
? "Claude SME Chat can use the configured Anthropic API key."
: "Claude SME Chat can use the configured Anthropic auth token.",
resolvedAuthMethod: conversation.authMethod,
resolvedAccountType:
clientOptions.apiKey !== null ? ("apiKey" as const) : ("unknown" as const),
};
return resolvedSetup.validation;
});

const uploadDocument: SmeChatServiceShape["uploadDocument"] = (input) =>
Expand Down Expand Up @@ -454,23 +437,29 @@ const makeSmeChatService = (options?: SmeChatServiceLiveOptions) =>
role: message.role,
text: message.text,
}));
const anthropicClientOptions = yield* Effect.try({
const resolvedAnthropicSetup = yield* Effect.try({
try: () =>
resolveAnthropicClientOptions({
resolveClaudeSmeSetup({
authMethod: conv.authMethod as Extract<
SmeAuthMethod,
"auto" | "apiKey" | "authToken"
>,
providerOptions: input.providerOptions?.claudeAgent,
}),
catch: (cause) => new SmeChatError("sendMessage:providerRuntime", String(cause), cause),
});

if (!anthropicClientOptions.apiKey && !anthropicClientOptions.authToken) {
if (!resolvedAnthropicSetup.clientOptions) {
return yield* Effect.fail(
new SmeChatError(
"sendMessage:providerRuntime",
"Claude SME Chat needs an Anthropic API key, auth token, or auth token helper command. Set ANTHROPIC_API_KEY or ANTHROPIC_AUTH_TOKEN, or configure `authTokenHelperCommand` in Settings.",
resolvedAnthropicSetup.validation.message,
),
);
}

const anthropicClientOptions = resolvedAnthropicSetup.clientOptions;

const systemPrompt = buildSmeSystemPrompt(docs);
const messages: Array<MessageParam> = [
...(promptHistory
Expand Down
Loading
Loading