mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-26 23:28:43 +00:00
feat(core): add a configDir setting to the Claude Agent provider (#62514)
This commit is contained in:
parent
cd0d037d68
commit
789f310a4a
17 changed files with 333 additions and 33 deletions
|
|
@ -170,7 +170,7 @@ export default { path: file, version: ${JSON.stringify(opencodePty.version)}, sh
|
|||
const executablePath = await compileExecutable(item)
|
||||
console.log(`building ${name}`)
|
||||
const result = await Bun.build({
|
||||
entrypoints: ["./src/index.ts", "./src/photon-worker.ts"],
|
||||
entrypoints: ["./src/index.ts", "./src/photon-worker.ts", "./src/claude-folder-worker.ts"],
|
||||
tsconfig: "./tsconfig.json",
|
||||
plugins: [
|
||||
appAssetsPlugin,
|
||||
|
|
|
|||
3
packages/cli/src/claude-folder-worker.ts
Normal file
3
packages/cli/src/claude-folder-worker.ts
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
// Third compile entrypoint: it lands next to index.js and the shared chunks in
|
||||
// the executable, where ClaudeIO resolves "./claude-folder-worker.js".
|
||||
import "../../core/src/plugin/provider/claude-agent/claude/claude-folder-worker"
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
import { parentPort, workerData } from "node:worker_threads"
|
||||
import { ClaudeIO } from "./io.js"
|
||||
|
||||
const helper: (...args: string[]) => Promise<unknown> =
|
||||
ClaudeIO.helpers[workerData.name as keyof typeof ClaudeIO.helpers]
|
||||
try {
|
||||
parentPort?.postMessage({ value: await helper(...workerData.args) })
|
||||
} catch (error) {
|
||||
parentPort?.postMessage({ error })
|
||||
}
|
||||
|
|
@ -1,6 +1,8 @@
|
|||
export * as ClaudeIO from "./io.js"
|
||||
|
||||
import type { Options } from "@anthropic-ai/claude-agent-sdk"
|
||||
import { readdir, stat } from "node:fs/promises"
|
||||
import path from "node:path"
|
||||
import { which } from "../../../../util/which.js"
|
||||
import { ClaudeFork } from "./fork.js"
|
||||
import { ClaudeSDK } from "./sdk.js"
|
||||
|
|
@ -12,21 +14,75 @@ export interface Interface {
|
|||
readonly which: () => string | undefined
|
||||
// Before our isolation settings
|
||||
readonly env: () => Record<string, string | undefined>
|
||||
readonly sessionExists: (sessionID: string) => Promise<boolean>
|
||||
readonly fork: (sessionID: string, messageID: string) => Promise<ClaudeFork.Result | undefined>
|
||||
readonly remove: (sessionID: string) => Promise<void>
|
||||
readonly sessionExists: (sessionID: string, configDir?: string) => Promise<boolean>
|
||||
readonly fork: (sessionID: string, messageID: string, configDir?: string) => Promise<ClaudeFork.Result | undefined>
|
||||
readonly remove: (sessionID: string, configDir?: string) => Promise<void>
|
||||
}
|
||||
|
||||
export const real: Interface = {
|
||||
which: () => process.env.OPENCODE_CLAUDE_PATH || which("claude") || undefined,
|
||||
env: () => process.env,
|
||||
sessionExists: async (sessionID) => {
|
||||
sessionExists: async (sessionID, configDir) => {
|
||||
if (configDir) {
|
||||
// Look for the transcript the way the SDK does. Loading the SDK in a worker for this would slow every resume.
|
||||
const projects = path.join(configDir, "projects")
|
||||
const folders = await readdir(projects).catch(() => [])
|
||||
for (const folder of folders) {
|
||||
const file = await stat(path.join(projects, folder, `${sessionID}.jsonl`)).catch(() => undefined)
|
||||
if (file && file.size > 0) return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
const { getSessionInfo } = await ClaudeSDK.load()
|
||||
return (await getSessionInfo(sessionID)) !== undefined
|
||||
},
|
||||
fork: async (sessionID, messageID, configDir) => {
|
||||
if (!configDir) return helpers.fork(sessionID, messageID)
|
||||
try {
|
||||
return await inFolder(configDir, "fork", [sessionID, messageID])
|
||||
} catch (error) {
|
||||
// Without the worker, a fresh Claude session replays the history instead.
|
||||
if (error instanceof WorkerUnavailableError) return undefined
|
||||
throw error
|
||||
}
|
||||
},
|
||||
remove: (sessionID, configDir) =>
|
||||
configDir ? inFolder(configDir, "remove", [sessionID]) : helpers.remove(sessionID),
|
||||
}
|
||||
|
||||
class WorkerUnavailableError extends Error {}
|
||||
|
||||
export const helpers = {
|
||||
fork: ClaudeFork.create,
|
||||
remove: async (sessionID) => {
|
||||
remove: async (sessionID: string) => {
|
||||
const { deleteSession } = await ClaudeSDK.load()
|
||||
await deleteSession(sessionID)
|
||||
},
|
||||
}
|
||||
|
||||
type HelperResult<Name extends keyof typeof helpers> = Awaited<ReturnType<(typeof helpers)[Name]>>
|
||||
|
||||
// The SDK's session helpers take no folder and read CLAUDE_CONFIG_DIR from process.env. A worker has its own, so they
|
||||
// see another folder without changing it for other sessions.
|
||||
async function inFolder<Name extends keyof typeof helpers>(
|
||||
configDir: string,
|
||||
name: Name,
|
||||
args: Parameters<(typeof helpers)[Name]>,
|
||||
): Promise<HelperResult<Name>> {
|
||||
const { Worker } = await import("node:worker_threads")
|
||||
const worker = new Worker(new URL("./claude-folder-worker.js", import.meta.url), {
|
||||
env: { ...process.env, CLAUDE_CONFIG_DIR: configDir },
|
||||
workerData: { name, args },
|
||||
})
|
||||
return new Promise<HelperResult<Name>>((resolve, reject) => {
|
||||
worker.once("message", (reply) => {
|
||||
if ("error" in reply) return reject(reply.error)
|
||||
resolve(reply.value)
|
||||
})
|
||||
// The worker reports helper failures as messages, so an error here means it could not start.
|
||||
worker.once("error", (cause) =>
|
||||
reject(new WorkerUnavailableError("Claude folder worker failed to start", { cause })),
|
||||
)
|
||||
worker.once("exit", () => reject(new Error(`Claude session helper ${name} exited without a result`)))
|
||||
}).finally(() => worker.terminate())
|
||||
}
|
||||
|
|
|
|||
|
|
@ -112,6 +112,13 @@ export function isLoggedIn(account: AccountInfo) {
|
|||
return account.tokenSource !== "none" || account.apiKeySource !== undefined
|
||||
}
|
||||
|
||||
export function loginMessage(configDir: string | undefined) {
|
||||
if (!configDir) return "Claude Code is not logged in. Run `claude auth login` in a terminal."
|
||||
if (process.platform === "win32")
|
||||
return `Claude Code is not logged in. Run \`$env:CLAUDE_CONFIG_DIR = "${configDir}"; claude auth login\` in PowerShell.`
|
||||
return `Claude Code is not logged in. Run \`CLAUDE_CONFIG_DIR="${configDir}" claude auth login\` in a terminal.`
|
||||
}
|
||||
|
||||
async function* waitFor(done: Promise<void>): AsyncGenerator<never> {
|
||||
await done
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,6 +2,8 @@ export * as ClaudeQueryOptions from "./query-options.js"
|
|||
|
||||
import type { LanguageModelV3FunctionTool } from "@ai-sdk/provider"
|
||||
import type { Options } from "@anthropic-ai/claude-agent-sdk"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
import { ToolHooks } from "../tools/hooks.js"
|
||||
import type { PendingTools } from "../tools/pending.js"
|
||||
import { ToolServer } from "../tools/server.js"
|
||||
|
|
@ -44,6 +46,12 @@ export function connectionEnv(connection: {
|
|||
if (typeof settings.authToken === "string") env.ANTHROPIC_AUTH_TOKEN = settings.authToken
|
||||
if (typeof settings.headerTimeout === "number") env.API_TIMEOUT_MS = String(settings.headerTimeout)
|
||||
if (typeof settings.chunkTimeout === "number") env.CLAUDE_STREAM_IDLE_TIMEOUT_MS = String(settings.chunkTimeout)
|
||||
if (typeof settings.configDir === "string") {
|
||||
// Claude Code does not expand ~, so a configDir like ~/.claude-work would point inside the project.
|
||||
// An absolute path also means Claude Code and our own transcript lookups agree on the folder.
|
||||
const dir = settings.configDir
|
||||
env.CLAUDE_CONFIG_DIR = path.resolve(dir.startsWith("~/") ? path.join(os.homedir(), dir.slice(2)) : dir)
|
||||
}
|
||||
const headers: string[] = []
|
||||
for (const [name, value] of Object.entries(connection.headers ?? {})) {
|
||||
headers.push(`${name}: ${value}`)
|
||||
|
|
@ -55,6 +63,16 @@ export function connectionEnv(connection: {
|
|||
return env
|
||||
}
|
||||
|
||||
// Claude Code keeps its state in ~/.claude.json only while CLAUDE_CONFIG_DIR is unset. Naming the default folder moves
|
||||
// that to ~/.claude/.claude.json, which can hold an older model list, so the default folder is used by not naming it.
|
||||
export function withoutDefaultFolder(connection: Readonly<Record<string, string>>, io: ClaudeIO.Interface) {
|
||||
if (connection.CLAUDE_CONFIG_DIR !== path.join(os.homedir(), ".claude")) return connection
|
||||
// With the variable already set for opencode, leaving it out would run that folder instead.
|
||||
if (io.env().CLAUDE_CONFIG_DIR !== undefined) return connection
|
||||
const { CLAUDE_CONFIG_DIR: _, ...rest } = connection
|
||||
return rest
|
||||
}
|
||||
|
||||
export function base(input: {
|
||||
executable: string
|
||||
io: ClaudeIO.Interface
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ import type {
|
|||
} from "@ai-sdk/provider"
|
||||
import { Effect, Fiber, Semaphore } from "effect"
|
||||
import { ClaudeIO } from "./io.js"
|
||||
import { ClaudeProbe } from "./probe.js"
|
||||
import type { ClaudeStatus } from "./status.js"
|
||||
import { ClaudeQueryOptions } from "./query-options.js"
|
||||
import { ClaudeSession } from "./session.js"
|
||||
|
|
@ -58,6 +59,7 @@ interface Entry {
|
|||
readonly lock: Semaphore.Semaphore
|
||||
process?: LiveProcess
|
||||
record?: SessionRecord.Record
|
||||
configDir?: string
|
||||
idle?: Fiber.Fiber<void, never>
|
||||
active?: Fiber.Fiber<unknown, unknown>
|
||||
}
|
||||
|
|
@ -197,7 +199,15 @@ export function registry() {
|
|||
)
|
||||
const process = opened.process
|
||||
// A new process reports its version, login and models, which keeps the model list current without a separate check.
|
||||
if (starting) yield* input.status.report({ type: "ready", probe: opened.probe, fromChat: true })
|
||||
if (starting) {
|
||||
const configDir = request.connection?.CLAUDE_CONFIG_DIR
|
||||
yield* input.status.report({ type: "ready", probe: opened.probe, configDir, fromChat: true })
|
||||
// Fail before sending the prompt, because Claude Code's own error does not say which folder needs a login.
|
||||
if (!ClaudeProbe.isLoggedIn(opened.probe.account)) {
|
||||
yield* stop(entry)
|
||||
return yield* Effect.fail(new Error(ClaudeProbe.loginMessage(configDir)))
|
||||
}
|
||||
}
|
||||
// Apply controls before sending input or releasing parked tool results.
|
||||
if (process.model !== request.model) {
|
||||
yield* attempt(() => process.session.setModel(request.model))
|
||||
|
|
@ -316,7 +326,7 @@ export function registry() {
|
|||
})
|
||||
: undefined
|
||||
entry.record = { claudeSessionID: session.id, history, interrupted: interrupted && !completed }
|
||||
yield* records.set(request.sessionID, entry.record)
|
||||
yield* records.set(request.sessionID, entry.record, request.connection?.CLAUDE_CONFIG_DIR)
|
||||
})
|
||||
|
||||
yield* step.pipe(
|
||||
|
|
@ -336,7 +346,9 @@ export function registry() {
|
|||
yield* stop(entry).pipe(Effect.catch((error) => Effect.logWarning(error)))
|
||||
const sessionID = entry.record?.claudeSessionID
|
||||
if (sessionID)
|
||||
yield* attempt(() => input.io.remove(sessionID)).pipe(Effect.catch((error) => Effect.logWarning(error)))
|
||||
yield* attempt(() => input.io.remove(sessionID, request.connection?.CLAUDE_CONFIG_DIR)).pipe(
|
||||
Effect.catch((error) => Effect.logWarning(error)),
|
||||
)
|
||||
temporary.delete(entry)
|
||||
return
|
||||
}
|
||||
|
|
@ -355,7 +367,9 @@ export function registry() {
|
|||
if (!source || !boundary) return 0
|
||||
// Validate catch-up input before creating a forked transcript on disk.
|
||||
yield* attemptSync(() => CatchUp.content(request.prompt, boundary.start))
|
||||
const fork = yield* attempt(() => input.io.fork(source.claudeSessionID, boundary.messageID))
|
||||
const fork = yield* attempt(() =>
|
||||
input.io.fork(source.claudeSessionID, boundary.messageID, request.connection?.CLAUDE_CONFIG_DIR),
|
||||
)
|
||||
if (!fork) return 0
|
||||
const history = boundary.history.map((checkpoint) => ({
|
||||
hash: checkpoint.hash,
|
||||
|
|
@ -370,7 +384,9 @@ export function registry() {
|
|||
if (!sourceID) return 0
|
||||
const source = entries.get(sourceID)
|
||||
const copy = Effect.gen(function* () {
|
||||
const record = source?.record ?? (yield* records.get(sourceID))
|
||||
const configDir = request.connection?.CLAUDE_CONFIG_DIR
|
||||
const record =
|
||||
source?.record && source.configDir === configDir ? source.record : yield* records.get(sourceID, configDir)
|
||||
return yield* branch(entry, request, record)
|
||||
})
|
||||
// Hold the source only while copying its settled prefix, never during side-call inference.
|
||||
|
|
@ -393,7 +409,10 @@ export function registry() {
|
|||
return { start, continuation: undefined }
|
||||
}
|
||||
|
||||
if (!entry.record) entry.record = yield* records.get(request.sessionID)
|
||||
const configDir = request.connection?.CLAUDE_CONFIG_DIR
|
||||
if (entry.configDir !== configDir) entry.record = undefined
|
||||
entry.configDir = configDir
|
||||
if (!entry.record) entry.record = yield* records.get(request.sessionID, configDir)
|
||||
const decision = SyncDecision.decide(request.prompt, entry.record)
|
||||
const start = yield* Effect.gen(function* () {
|
||||
if (decision.kind === "fresh" || decision.kind === "changed") {
|
||||
|
|
@ -406,7 +425,7 @@ export function registry() {
|
|||
}
|
||||
if (entry.process || !entry.record) return decision.start
|
||||
const sessionID = entry.record.claudeSessionID
|
||||
const exists = yield* attempt(() => input.io.sessionExists(sessionID))
|
||||
const exists = yield* attempt(() => input.io.sessionExists(sessionID, configDir))
|
||||
if (exists) return decision.start
|
||||
entry.record = undefined
|
||||
return 0
|
||||
|
|
@ -447,7 +466,9 @@ export function registry() {
|
|||
return entry
|
||||
}
|
||||
|
||||
const run = Effect.fn("ClaudeSessions.run")(function* (request: Request) {
|
||||
const run = Effect.fn("ClaudeSessions.run")(function* (asked: Request) {
|
||||
const connection = asked.connection && ClaudeQueryOptions.withoutDefaultFolder(asked.connection, input.io)
|
||||
const request = { ...asked, connection }
|
||||
const entry = entryFor(request)
|
||||
yield* entry.lock.withPermit(
|
||||
Effect.gen(function* () {
|
||||
|
|
|
|||
|
|
@ -9,7 +9,12 @@ export type State =
|
|||
| { readonly type: "checking" }
|
||||
| { readonly type: "missing" }
|
||||
| { readonly type: "failed"; readonly message: string }
|
||||
| { readonly type: "ready"; readonly probe: ClaudeProbe.Result; readonly fromChat?: boolean }
|
||||
| {
|
||||
readonly type: "ready"
|
||||
readonly probe: ClaudeProbe.Result
|
||||
readonly configDir?: string
|
||||
readonly fromChat?: boolean
|
||||
}
|
||||
|
||||
export interface Interface {
|
||||
readonly state: SubscriptionRef.SubscriptionRef<State>
|
||||
|
|
@ -29,9 +34,9 @@ export const make = Effect.fn("ClaudeStatus.make")(function* (
|
|||
const refresh = Effect.fn("ClaudeStatus.refresh")(function* () {
|
||||
const executable = io.which()
|
||||
if (!executable) return yield* SubscriptionRef.set(state, { type: "missing" })
|
||||
const env = yield* connection()
|
||||
const env = ClaudeQueryOptions.withoutDefaultFolder(yield* connection(), io)
|
||||
const next = yield* ClaudeProbe.run(ClaudeQueryOptions.base({ executable, io, connection: env })).pipe(
|
||||
Effect.map((probe): State => ({ type: "ready", probe })),
|
||||
Effect.map((probe): State => ({ type: "ready", probe, configDir: env.CLAUDE_CONFIG_DIR })),
|
||||
Effect.catch((error) =>
|
||||
Effect.logWarning("Claude Code login check failed", { cause: error.cause }).pipe(
|
||||
Effect.as<State>({
|
||||
|
|
@ -44,7 +49,14 @@ export const make = Effect.fn("ClaudeStatus.make")(function* (
|
|||
yield* SubscriptionRef.set(state, next)
|
||||
}, lock.withPermit)
|
||||
|
||||
const report = (next: State) => SubscriptionRef.set(state, next)
|
||||
// A model with its own configDir runs another account, which must not replace the provider's login, prices and models.
|
||||
const report = Effect.fn("ClaudeStatus.report")(function* (next: State) {
|
||||
if (next.type === "ready") {
|
||||
const own = ClaudeQueryOptions.withoutDefaultFolder(yield* connection(), io).CLAUDE_CONFIG_DIR
|
||||
if (next.configDir !== own) return
|
||||
}
|
||||
yield* SubscriptionRef.set(state, next)
|
||||
})
|
||||
|
||||
return { state, refresh, report } satisfies Interface
|
||||
})
|
||||
|
|
|
|||
|
|
@ -57,6 +57,6 @@ function problem(state: ClaudeStatus.State): IntegrationConnection.Status | unde
|
|||
// The message already says what went wrong with Claude Code.
|
||||
if (state.type === "failed") return { status: "needs_auth", message: state.message }
|
||||
if (state.type === "ready" && !ClaudeProbe.isLoggedIn(state.probe.account))
|
||||
return { status: "needs_auth", message: "Claude Code is not logged in. Run `claude auth login` in a terminal." }
|
||||
return { status: "needs_auth", message: ClaudeProbe.loginMessage(state.configDir) }
|
||||
return undefined
|
||||
}
|
||||
|
|
|
|||
|
|
@ -19,10 +19,15 @@ export interface Storage {
|
|||
|
||||
export function make(storage: Storage) {
|
||||
return {
|
||||
get: Effect.fn("SessionRecord.get")(function* (sessionID: string) {
|
||||
const saved = Schema.decodeUnknownOption(Record)(yield* storage.get(`sessions/${sessionID}`))
|
||||
get: Effect.fn("SessionRecord.get")(function* (sessionID: string, configDir?: string) {
|
||||
const saved = Schema.decodeUnknownOption(Record)(yield* storage.get(key(sessionID, configDir)))
|
||||
return Option.getOrUndefined(saved)
|
||||
}),
|
||||
set: (sessionID: string, record: Record) => storage.set(`sessions/${sessionID}`, record),
|
||||
set: (sessionID: string, record: Record, configDir?: string) => storage.set(key(sessionID, configDir), record),
|
||||
}
|
||||
}
|
||||
|
||||
// Each Claude config folder has its own transcripts, so a chat keeps one record per folder.
|
||||
function key(sessionID: string, configDir?: string) {
|
||||
return configDir ? `sessions/${sessionID}:${configDir}` : `sessions/${sessionID}`
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { describe, expect } from "bun:test"
|
||||
import path from "node:path"
|
||||
import { Effect } from "effect"
|
||||
import { SessionRecord } from "@opencode/core/plugin/provider/claude-agent/sync/record"
|
||||
import { RequestKind } from "@opencode/core/plugin/provider/claude-agent/language-model/request-kind"
|
||||
|
|
@ -38,6 +39,30 @@ describe("Claude history branches", () => {
|
|||
}),
|
||||
)
|
||||
|
||||
it.effect("a branch is forked and deleted in the chat's own Claude config folder", () =>
|
||||
Effect.gen(function* () {
|
||||
const claude = FakeClaude.make([
|
||||
FakeClaude.expectStartup(),
|
||||
FakeClaude.expectTurn(),
|
||||
FakeClaude.expectStartup(),
|
||||
FakeClaude.expectTurn({ recording: "api-error" }),
|
||||
FakeClaude.expectInterrupt(),
|
||||
FakeClaude.expectInterrupt(),
|
||||
])
|
||||
const test = yield* TestSessions.start(claude)
|
||||
const folder = path.resolve("/claude-work")
|
||||
const work = yield* TestSessions.model(test.sessions, { configDir: folder })
|
||||
yield* TestSessions.reply(work, first)
|
||||
yield* TestSessions.reply(work, TestSessions.followup("Summarize"), "session-a", "compaction")
|
||||
expect(claude.forks).toHaveLength(1)
|
||||
expect(claude.forks[0]!.configDir).toBe(folder)
|
||||
// The fake reports a removal from a different folder as an error in check().
|
||||
expect(claude.removed).toEqual([claude.forks[0]!.sessionID])
|
||||
yield* test.registry.close()
|
||||
claude.check()
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("an unsupported attachment in changed history fails with its own message before forking", () =>
|
||||
Effect.gen(function* () {
|
||||
const claude = FakeClaude.make([
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { describe, expect } from "bun:test"
|
||||
import { Effect, Fiber } from "effect"
|
||||
import path from "node:path"
|
||||
import { Effect, Fiber, SubscriptionRef } from "effect"
|
||||
import { TestClock } from "effect/testing"
|
||||
import { ClaudeSessions } from "@opencode/core/plugin/provider/claude-agent/claude/sessions"
|
||||
import { ClaudeAgentLanguageModel } from "@opencode/core/plugin/provider/claude-agent/language-model/claude-agent-language-model"
|
||||
|
|
@ -87,6 +88,65 @@ describe("Claude sessions", () => {
|
|||
}),
|
||||
)
|
||||
|
||||
it.effect("each Claude config folder keeps its own Claude session, and switching back catches up", () =>
|
||||
Effect.gen(function* () {
|
||||
const claude = FakeClaude.make([
|
||||
FakeClaude.expectStartup(),
|
||||
FakeClaude.expectTurn(),
|
||||
FakeClaude.expectInterrupt(),
|
||||
FakeClaude.expectStartup(),
|
||||
FakeClaude.expectTurn({ index: 1 }),
|
||||
FakeClaude.expectInterrupt(),
|
||||
FakeClaude.expectStartup(),
|
||||
FakeClaude.expectTurn({ recording: "text-resume" }),
|
||||
FakeClaude.expectInterrupt(),
|
||||
])
|
||||
const test = yield* TestSessions.start(claude)
|
||||
const folder = path.resolve("/claude-work")
|
||||
const work = yield* TestSessions.model(test.sessions, { configDir: folder })
|
||||
yield* TestSessions.reply(test.model, first)
|
||||
const id = claude.runs[0]!.args.find((arg) => arg.startsWith("--session-id="))!.split("=")[1]
|
||||
const prompt = TestSessions.followup()
|
||||
yield* TestSessions.reply(work, prompt)
|
||||
prompt.push(
|
||||
{ role: "assistant", content: [{ type: "text", text: "COPPER-OTTER" }] },
|
||||
{ role: "user", content: [{ type: "text", text: "And once more?" }] },
|
||||
)
|
||||
yield* TestSessions.reply(test.model, prompt)
|
||||
const user = (run: number) =>
|
||||
JSON.stringify(claude.runs[run]!.received.find((message) => message.type === "user").message.content)
|
||||
// The other folder cannot resume this login's transcript, so it starts its own from the whole history.
|
||||
expect(claude.runs[1]!.env.CLAUDE_CONFIG_DIR).toBe(folder)
|
||||
expect(claude.runs[1]!.args.some((arg) => arg.startsWith("--resume="))).toBe(false)
|
||||
expect(user(1)).toContain("Remember the marker COPPER-OTTER")
|
||||
const other = (yield* SessionRecord.make(test.storage).get("session-a", folder))!
|
||||
expect(other.claudeSessionID).not.toBe(id)
|
||||
expect(claude.runs[2]!.args).toContain(`--resume=${id}`)
|
||||
expect(user(2)).toContain("What was the marker?")
|
||||
expect(user(2)).not.toContain("Remember the marker COPPER-OTTER")
|
||||
expect((yield* SessionRecord.make(test.storage).get("session-a"))!.claudeSessionID).toBe(id)
|
||||
yield* test.registry.close()
|
||||
claude.check()
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("a logged-out model folder fails with the command to log in to it, and leaves the provider's status", () =>
|
||||
Effect.gen(function* () {
|
||||
const claude = FakeClaude.make([
|
||||
FakeClaude.expectStartup({ account: { tokenSource: "none", apiProvider: "firstParty" } }),
|
||||
FakeClaude.expectInterrupt(),
|
||||
])
|
||||
const test = yield* TestSessions.start(claude)
|
||||
const folder = path.resolve("/claude-work")
|
||||
const work = yield* TestSessions.model(test.sessions, { configDir: folder })
|
||||
const error = yield* TestSessions.reply(work, first).pipe(Effect.flip)
|
||||
expect(String(error.cause)).toContain(`"${folder}"`)
|
||||
expect((yield* SubscriptionRef.get(test.input.status.state)).type).toBe("checking")
|
||||
yield* test.registry.close()
|
||||
claude.check()
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("cancellation drains past the interrupt receipt before accepting another turn", () =>
|
||||
Effect.gen(function* () {
|
||||
const drain = Promise.withResolvers<void>()
|
||||
|
|
|
|||
|
|
@ -205,7 +205,7 @@ export function make(script: readonly Step[], options?: { readonly probes?: bool
|
|||
const runs: Run[] = []
|
||||
const errors: string[] = []
|
||||
const transcripts = new Map<string, SessionMessage[]>()
|
||||
const forks: Array<{ source: string; boundary: string; sessionID: string }> = []
|
||||
const forks: Array<{ source: string; boundary: string; sessionID: string; configDir?: string }> = []
|
||||
const removed: string[] = []
|
||||
let next = 0
|
||||
let completed = 0
|
||||
|
|
@ -349,7 +349,7 @@ export function make(script: readonly Step[], options?: { readonly probes?: bool
|
|||
transcripts,
|
||||
forks,
|
||||
removed,
|
||||
async fork(source: string, boundary: string) {
|
||||
async fork(source: string, boundary: string, configDir?: string) {
|
||||
const history = transcripts.get(source) ?? []
|
||||
const end = history.findIndex((message) => message.uuid === boundary)
|
||||
if (end < 0) return
|
||||
|
|
@ -361,10 +361,13 @@ export function make(script: readonly Step[], options?: { readonly probes?: bool
|
|||
return { ...message, session_id: sessionID, uuid }
|
||||
})
|
||||
transcripts.set(sessionID, copied)
|
||||
forks.push({ source, boundary, sessionID })
|
||||
forks.push({ source, boundary, sessionID, configDir })
|
||||
return { sessionID, messages }
|
||||
},
|
||||
async remove(sessionID: string) {
|
||||
async remove(sessionID: string, configDir?: string) {
|
||||
// A fork can only be deleted from the config folder it was written to.
|
||||
const fork = forks.find((fork) => fork.sessionID === sessionID)
|
||||
if (fork && fork.configDir !== configDir) errors.push(`removed ${sessionID} from the wrong config folder`)
|
||||
transcripts.delete(sessionID)
|
||||
removed.push(sessionID)
|
||||
},
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ export * as TestSessions from "./sessions"
|
|||
import type { LanguageModelV3Prompt, LanguageModelV3StreamPart } from "@ai-sdk/provider"
|
||||
import type { SessionRequestKind } from "@opencode/plugin/effect/session"
|
||||
import { Effect } from "effect"
|
||||
import { ClaudeQueryOptions } from "@opencode/core/plugin/provider/claude-agent/claude/query-options"
|
||||
import { ClaudeSessions } from "@opencode/core/plugin/provider/claude-agent/claude/sessions"
|
||||
import { ClaudeStatus } from "@opencode/core/plugin/provider/claude-agent/claude/status"
|
||||
import { ClaudeAgentLanguageModel } from "@opencode/core/plugin/provider/claude-agent/language-model/claude-agent-language-model"
|
||||
|
|
@ -38,11 +39,13 @@ export function followup(text = "What was the marker? Reply only with it."): Lan
|
|||
]
|
||||
}
|
||||
|
||||
export const model = Effect.fn(function* (sessions: ClaudeSessions.Interface) {
|
||||
export const model = Effect.fn(function* (sessions: ClaudeSessions.Interface, settings?: Record<string, unknown>) {
|
||||
const context = yield* Effect.context<never>()
|
||||
return new ClaudeAgentLanguageModel.Model("haiku", {
|
||||
run: (request, signal) => Effect.runPromiseWith(context)(sessions.run(request), { signal }),
|
||||
})
|
||||
return new ClaudeAgentLanguageModel.Model(
|
||||
"haiku",
|
||||
{ run: (request, signal) => Effect.runPromiseWith(context)(sessions.run(request), { signal }) },
|
||||
ClaudeQueryOptions.connectionEnv({ settings }),
|
||||
)
|
||||
})
|
||||
|
||||
export const start = Effect.fn(function* (claude: FakeClaude.Fake, saved = storage()) {
|
||||
|
|
|
|||
|
|
@ -28,6 +28,8 @@ import { Session } from "@opencode/core/session"
|
|||
import { SessionInbox } from "@opencode/core/session/inbox"
|
||||
import { describe, expect } from "bun:test"
|
||||
import { Effect } from "effect"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
import { FakeClaude } from "./lib/fake-claude"
|
||||
import { FakeIO } from "./lib/fake-io"
|
||||
import { TestSessions } from "./lib/sessions"
|
||||
|
|
@ -517,7 +519,7 @@ describe("ClaudeAgentPlugin provider config", () => {
|
|||
provider.body = { metadata: { user_id: "dan" } }
|
||||
})
|
||||
editor.models.update(ClaudeProvider.ID, haiku.id, (model) => {
|
||||
model.settings = { baseURL: "https://haiku-gateway.example" }
|
||||
model.settings = { baseURL: "https://haiku-gateway.example", configDir: "~/.claude-work" }
|
||||
model.headers = { "X-Model": "haiku" }
|
||||
})
|
||||
})
|
||||
|
|
@ -548,6 +550,7 @@ describe("ClaudeAgentPlugin provider config", () => {
|
|||
// Model settings override the provider's, and only configured headers are sent, not opencode's own
|
||||
const chat = claude.runs.find((run) => run.args.includes("--include-partial-messages"))!.env
|
||||
expect(chat.ANTHROPIC_BASE_URL).toBe("https://haiku-gateway.example")
|
||||
expect(chat.CLAUDE_CONFIG_DIR).toBe(path.join(os.homedir(), ".claude-work"))
|
||||
expect(chat.ANTHROPIC_AUTH_TOKEN).toBe("config-token")
|
||||
expect(chat.ANTHROPIC_CUSTOM_HEADERS).toBe("X-Team: core\nX-Model: haiku")
|
||||
expect(chat.CLAUDE_CODE_EXTRA_BODY).toBe(JSON.stringify({ metadata: { user_id: "dan" } }))
|
||||
|
|
@ -556,6 +559,39 @@ describe("ClaudeAgentPlugin provider config", () => {
|
|||
}),
|
||||
)
|
||||
|
||||
it.live("runs the default folder without naming it, so Claude Code keeps its usual state file", () =>
|
||||
Effect.gen(function* () {
|
||||
const claude = FakeClaude.make(
|
||||
[FakeClaude.expectStartup(), FakeClaude.expectTurn(), FakeClaude.expectInterrupt()],
|
||||
{ probes: true },
|
||||
)
|
||||
const registry = yield* addPlugin(FakeIO.make({ claude }))
|
||||
const providers = yield* Provider.Service
|
||||
yield* providers.transform((editor) => {
|
||||
editor.update(ClaudeProvider.ID, (provider) => {
|
||||
provider.settings = { configDir: "~/.claude" }
|
||||
})
|
||||
})
|
||||
yield* connect
|
||||
yield* eventually(claudeModels, (models) => models.some((model) => model.id === "sonnet"))
|
||||
const models = yield* Model.Service
|
||||
const aisdk = yield* AISDK.Service
|
||||
const model = yield* models.get(ClaudeProvider.ID, haiku.id)
|
||||
if (!model) throw new Error("Expected the haiku model")
|
||||
const language = yield* aisdk.language(model)
|
||||
const result = yield* Effect.promise(() =>
|
||||
language.doStream({
|
||||
prompt: TestSessions.prompt("Remember the marker COPPER-OTTER. Reply only with that marker."),
|
||||
headers: { [RequestKind.SESSION_HEADER]: "session-a", [RequestKind.HEADER]: "primary" },
|
||||
}),
|
||||
)
|
||||
expect(TestSessions.text(yield* Effect.promise(() => TestSessions.collect(result.stream)))).toBe("COPPER-OTTER")
|
||||
expect(claude.runs.map((run) => run.env.CLAUDE_CONFIG_DIR)).toEqual([undefined, undefined])
|
||||
yield* registry.close()
|
||||
claude.check()
|
||||
}),
|
||||
)
|
||||
|
||||
it.live("leaves the user's environment alone when nothing is configured", () =>
|
||||
Effect.gen(function* () {
|
||||
const onConnect = FakeClaude.expectStartup()
|
||||
|
|
|
|||
|
|
@ -79,11 +79,48 @@ your shell.
|
|||
| `settings.authToken` | `ANTHROPIC_AUTH_TOKEN` |
|
||||
| `settings.headerTimeout` | `API_TIMEOUT_MS` |
|
||||
| `settings.chunkTimeout` | `CLAUDE_STREAM_IDLE_TIMEOUT_MS` |
|
||||
| `settings.configDir` | `CLAUDE_CONFIG_DIR` |
|
||||
| `headers` | `ANTHROPIC_CUSTOM_HEADERS` |
|
||||
| `body` | `CLAUDE_CODE_EXTRA_BODY` |
|
||||
|
||||
Set them on a model to override the provider's values for that model.
|
||||
|
||||
## Use a second Claude account
|
||||
|
||||
Sign in to the second account in its own folder. Your usual login stays unchanged.
|
||||
|
||||
```bash
|
||||
CLAUDE_CONFIG_DIR="$HOME/.claude-2" claude auth login
|
||||
```
|
||||
|
||||
In PowerShell:
|
||||
|
||||
```powershell
|
||||
$env:CLAUDE_CONFIG_DIR = "$HOME\.claude-2"; claude auth login
|
||||
```
|
||||
|
||||
Then add models that use that folder:
|
||||
|
||||
```jsonc title="opencode.jsonc"
|
||||
{
|
||||
"$schema": "https://opencode.ai/config.json",
|
||||
"providers": {
|
||||
"claude-agent": {
|
||||
"models": {
|
||||
"sonnet-2": {
|
||||
"modelID": "sonnet",
|
||||
"name": "Sonnet (Claude 2)",
|
||||
"settings": { "configDir": "~/.claude-2" },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
To use one account for every model in a project, set `settings.configDir` on the provider in that project's config
|
||||
instead.
|
||||
|
||||
## Limitations
|
||||
|
||||
- Claude Code must be installed on the same machine as the OpenCode server. Claude Agent is not available in remote
|
||||
|
|
@ -98,5 +135,5 @@ Set them on a model to override the provider's values for that model.
|
|||
| Error or symptom | Check |
|
||||
| --- | --- |
|
||||
| `Claude Code is not installed` | Install Claude Code, or set `OPENCODE_CLAUDE_PATH` to its path. |
|
||||
| `Claude Code is not logged in` | Run `claude auth login`, then connect Claude Agent again. |
|
||||
| `Claude Code is not logged in` | Run `claude auth login`, then connect Claude Agent again. With `configDir`, run the command the error shows for that folder. |
|
||||
| `Claude Code ... is too old` | Run `claude update`. |
|
||||
|
|
|
|||
|
|
@ -84,6 +84,7 @@ Users can configure the `claude-agent` provider and its models in opencode confi
|
|||
| `settings.authToken` | `ANTHROPIC_AUTH_TOKEN` |
|
||||
| `settings.headerTimeout` | `API_TIMEOUT_MS` |
|
||||
| `settings.chunkTimeout` | `CLAUDE_STREAM_IDLE_TIMEOUT_MS` |
|
||||
| `settings.configDir` | `CLAUDE_CONFIG_DIR` |
|
||||
| `headers` | `ANTHROPIC_CUSTOM_HEADERS` |
|
||||
| `body` | `CLAUDE_CODE_EXTRA_BODY` |
|
||||
| effort | the SDK's `effort` option |
|
||||
|
|
@ -93,6 +94,9 @@ Users can configure the `claude-agent` provider and its models in opencode confi
|
|||
- Settings are applied in this order, with later ones winning: the user's shell, then opencode config, then the settings we turn off.
|
||||
- Changing any of these restarts the Claude process.
|
||||
- Without an explicit max output, we drop opencode's automatic limit and let Claude pick its own.
|
||||
- `configDir` expands a leading `~/`, because Claude Code does not. Each config folder has its own transcripts, so a session keeps one record per folder, and forks are made and deleted in the folder they belong to.
|
||||
- A model with its own `configDir` runs another account. Its chats do not change the provider's login status, prices or model list, which describe the provider's own folder.
|
||||
- A `configDir` of `~/.claude` is the default folder, and is used by not setting `CLAUDE_CONFIG_DIR`. Setting it moves Claude Code's state from `~/.claude.json` to `~/.claude/.claude.json`, which can hold an older model list, and would give existing sessions a new record. It stays set when opencode itself was started with `CLAUDE_CONFIG_DIR`, since leaving it out would then run that folder.
|
||||
|
||||
## History and Switching Models
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue