feat: claude code added #82
Closedt3dotgg(GitHub profile, opens in a new tab)wants to merge 1 commit into
main fromtheo/claudeopened View on GitHub- @@ -0,0 +258,21 @@258+259+ if (input.input) {260+ userContent.push({261+ type: "text",262+ text: input.input,263+ });264+ }265+ for (const attachment of input.attachments ?? []) {266+ if (attachment.type !== "image") {267+ continue;268+ }269+270+ const parsed = parseDataUrl(attachment.dataUrl);271+ if (!parsed) {272+ throw new Error(`Attachment '${attachment.name}' is not a valid base64 data URL.`);273+ }274+275+ userContent.push({276+ type: "image",277+ });278+ }
- @@ -0,0 +234,21 @@234+ });235+ this.emitLifecycleEvent(236+ context,237+ "session/ready",238+ `Connected to session ${context.session.threadId ?? context.session.sessionId}`,239+ );240+ return { ...context.session };241+ } catch (error) {242+ const message = error instanceof Error ? error.message : "Failed to start Claude session.";243+ this.updateSession(context, {244+ status: "error",245+ lastError: message,246+ });247+ this.emitErrorEvent(context, "session/startFailed", message);248+ this.stopSession(sessionId);249+ throw new Error(message, { cause: error });250+ }251+ }252+253+ async sendTurn(input: ProviderSendTurnInput): Promise<ProviderTurnStartResult> {254+ const context = this.requireSession(input.sessionId);@@ -0,0 +362,21 @@362+ }363+364+ async readThread(sessionId: string): Promise<CodexThreadSnapshot> {365+ const context = this.requireSession(sessionId);366+ return {367+ threadId: context.session.threadId ?? context.session.sessionId,368+ turns: context.turns.map((turn) => ({369+ id: turn.id,370+ items: [...turn.items],371+ })),372+ };373+ }374+375+ async rollbackThread(sessionId: string, numTurns: number): Promise<CodexThreadSnapshot> {376+ const context = this.requireSession(sessionId);377+ if (!Number.isInteger(numTurns) || numTurns < 1) {378+ throw new Error("numTurns must be an integer >= 1.");379+ }380+381+ const nextLength = Math.max(0, context.turns.length - numTurns);382+ context.turns = context.turns.slice(0, nextLength);@@ -0,0 +452,21 @@452+ hasSession(sessionId: string): boolean {453+ return this.sessions.has(sessionId);454+ }455+456+ stopAll(): void {457+ for (const sessionId of this.sessions.keys()) {458+ this.stopSession(sessionId);459+ }460+ }461+462+ private resolvePermissionMode(input: ProviderSessionStartInput): PermissionMode {463+ if (input.permissionMode) {464+ return input.permissionMode;465+ }466+ return input.approvalPolicy === "never" ? "bypassPermissions" : "default";467+ }468+469+ private assertClaudeAvailable(binaryPath: string): void {470+ if (binaryPath !== "claude" && !fs.existsSync(binaryPath)) {471+ throw new Error(`Claude Code binary not found at '${binaryPath}'.`);472+ }@@ -39,0 +59,21 @@59+ "claude-opus-4-6": "opus",60+ "opus-4-5": "opus",61+ "claude-opus-4-5": "opus",62+ "opus-4-1": "opus",63+ "claude-opus-4-1": "opus",64+ haiku: "haiku",65+ "haiku-4-5": "haiku",66+ "claude-haiku-4-5": "haiku",67+};68+69+export function normalizeClaudeModelSlug(model: string | null | undefined): ClaudeModelSlug | null {70+ if (typeof model !== "string") {71+ return null;72+ }73+74+ const trimmed = model.trim();75+ if (!trimmed) {76+ return null;77+ }78+79+ return CLAUDE_MODEL_SLUG_ALIASES[trimmed] ?? (trimmed as ClaudeModelSlug);@@ -0,0 +936,21 @@936+ turnId: context.currentTurn?.turnId,937+ requestId,938+ requestKind,939+ payload: {940+ toolName,941+ input: toolInput,942+ toolUseId: options.toolUseID,943+ blockedPath: options.blockedPath,944+ reason: options.decisionReason,945+ },946+ });947+948+ const onAbort = () => {949+ if (settled) {950+ return;951+ }952+ settled = true;953+ context.pendingApprovals.delete(requestId);954+ reject(new Error("Permission request was cancelled."));955+ };956+ options.signal.addEventListener("abort", onAbort, { once: true });@@ -0,0 +456,21 @@456+ stopAll(): void {457+ for (const sessionId of this.sessions.keys()) {458+ this.stopSession(sessionId);459+ }460+ }461+462+ private resolvePermissionMode(input: ProviderSessionStartInput): PermissionMode {463+ if (input.permissionMode) {464+ return input.permissionMode;465+ }466+ return input.approvalPolicy === "never" ? "bypassPermissions" : "default";467+ }468+469+ private assertClaudeAvailable(binaryPath: string): void {470+ if (binaryPath !== "claude" && !fs.existsSync(binaryPath)) {471+ throw new Error(`Claude Code binary not found at '${binaryPath}'.`);472+ }473+474+ const probe = spawnSync(binaryPath, ["--version"], {475+ stdio: "ignore",476+ });
- @@ -0,0 +113,21 @@113+ abortController: AbortController;114+ currentModel: string | undefined;115+}116+117+export class ClaudeCodeManager extends EventEmitter<ClaudeCodeManagerEvents> {118+ private sessions = new Map<string, ClaudeSessionContext>();119+```120+121+**Session lifecycle:**122+123+```124+startSession(input)125+Resolve claude binary path (bundled or system `claude`)126+Validate claude is available: execSync(`claude -v`)127+Create AbortController128+Set up async generator for multi-turn messages129+Call claudeQuery({ prompt: asyncGenerator, options: { ... } })130+Start consuming the async iterable in background, emitting ProviderEvents131+Return ProviderSession with status "ready"132+133+sendTurn(input)@@ -0,0 +307,21 @@307+ source: {308+ type: "base64",309+ media_type: parsed.mimeType,310+ data: parsed.base64Data,311+ },312+ });313+ }314+315+ context.currentTurn = {316+ turnId,317+ assistantItemId,318+ userContent,319+ assistantText: "",320+ assistantStarted: false,321+ };322+323+ this.updateSession(context, {324+ status: "running",325+ activeTurnId: turnId,326+ });327+ this.emitEvent({@@ -0,0 +293,21 @@293+ type: "text",294+ text: input.input,295+ });296+ }297+ for (const attachment of input.attachments ?? []) {298+ if (attachment.type !== "image") {299+ continue;300+ }301+ const parsed = parseDataUrl(attachment.dataUrl);302+ if (!parsed) {303+ throw new Error(`Attachment '${attachment.name}' is not a valid base64 data URL.`);304+ }305+ messageContent.push({306+ type: "image",307+ source: {308+ type: "base64",309+ media_type: parsed.mimeType,310+ data: parsed.base64Data,311+ },312+ });313+ }@@ -0,0 +489,21 @@489+ if (context.stopping) {490+ return;491+ }492+ const message = error instanceof Error ? error.message : "Claude session crashed.";493+ this.updateSession(context, {494+ status: "error",495+ lastError: message,496+ });497+ this.emitErrorEvent(context, "session/exited", message);498+ this.sessions.delete(context.session.sessionId);499+ return;500+ }501+502+ if (!context.stopping && this.sessions.has(context.session.sessionId)) {503+ this.updateSession(context, {504+ status: "closed",505+ activeTurnId: undefined,506+ });507+ this.emitLifecycleEvent(context, "session/exited", "Claude session ended.");508+ this.sessions.delete(context.session.sessionId);509+ }@@ -0,0 +1010,21 @@1010+ message,1011+ threadId: context.session.threadId,1012+ });1013+ }1014+1015+ private emitErrorEvent(context: ClaudeSessionContext, method: string, message: string): void {1016+ this.emitEvent({1017+ id: randomUUID(),1018+ kind: "error",1019+ provider: "claudeCode",1020+ sessionId: context.session.sessionId,1021+ createdAt: new Date().toISOString(),1022+ method,1023+ message,1024+ threadId: context.session.threadId,1025+ });1026+ }1027+1028+ private emitEvent(event: ProviderEvent): void {1029+ this.emit("event", event);1030+ }@@ -235,12 +235,20 @@235235236236 await this.codex.respondToRequest(input.sessionId, input.requestId, input.decision);237237 }238238239239 stopSession(raw: ProviderStopSessionInput): void {240240 const input = providerStopSessionInputSchema.parse(raw);241- this.codex.stopSession(input.sessionId);241+ if (!this.hasSession(input.sessionId)) {242+ return;243+ }244+ const backend = this.resolveBackend(input.sessionId);245+ if (backend === "claudeCode") {246+ this.claude.stopSession(input.sessionId);247+ } else {248+ this.codex.stopSession(input.sessionId);249+ }242250 this.sessionThreadIds.delete(input.sessionId);243251 this.pendingEventsBySession.delete(input.sessionId);244252 this.sessionCheckpointCwds.delete(input.sessionId);245253 this.filesystemLocks.delete(input.sessionId);246254 }
juliusmarminge closed this
Sign in to join this conversation.
Walkthrough#
Introduces Claude Code integration via the Claude Agent SDK alongside existing Codex support. Adds ClaudeCodeManager backend, provider-aware routing in ProviderManager, extended contracts for Claude models and session parameters, and frontend updates for provider selection, model options, and state management.
Changes#
apps/server/src/claudeCodeManager.ts,apps/server/src/claudeCodeManager.test.ts,apps/server/package.jsonapps/server/src/providerManager.ts,apps/server/src/providerManager.test.tspackages/contracts/src/model.ts,packages/contracts/src/model.test.ts,packages/contracts/src/provider.ts,packages/contracts/src/provider.test.tsapps/web/src/model-logic.ts,apps/web/src/model-logic.test.tsapps/web/src/ChatView.tsx,apps/web/src/session-logic.ts,apps/web/src/session-logic.test.tsapps/web/src/store.ts,apps/web/src/store.test.ts,apps/web/src/persistenceSchema.ts,apps/web/src/persistenceSchema.test.ts,apps/web/src/threadFactory.ts,apps/web/src/types.ts.plans/claude-agent-sdk.md,TODO.md,apps/web/src/index.cssEstimated code review effort#
🎯 4 (Complex) | ⏱️ ~50 minutes
🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)#
✅ Passed checks (2 passed)
✨ Finishing Touches
🧪 Generate unit tests (beta)
Tip
Issue Planner is now in beta. Read the docs and try it out! Share your feedback on Discord.
Comment `@coderabbitai help` to get the list of available commands and usage tips.