aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/claude/index.ts
blob: 8cf512c09845c977ac35cea4ee0377654cccba1a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
import { query, type SDKMessage, type Query } from "@anthropic-ai/claude-agent-sdk";
import type { Session } from "../db/sessions";
import { getPhaseConfig, getNextPhase, getArtifactFilename } from "./phases";
import type { Phase, UserPermissionMode } from "./phases";
import { getProject } from "../db/projects";
import { updateSession } from "../db/sessions";
import { getSetting } from "../db/settings";
import { autoCommitTurn } from "../git";
import fs from "node:fs";
import path from "node:path";

// Track active queries by session ID
const activeQueries = new Map<string, Query>();

// Snapshot of plan.md content per session, updated after each implement turn.
// Used to detect newly-completed tasks for commit messages.
const planSnapshots = new Map<string, string>();

function ensureDir(dirPath: string): void {
  if (!fs.existsSync(dirPath)) {
    fs.mkdirSync(dirPath, { recursive: true });
  }
}

// Artifacts live inside the project directory so the SDK's Write tool can reach them
function getSessionDir(projectPath: string, sessionId: string): string {
  return path.join(projectPath, ".claude-flow", "sessions", sessionId);
}

export interface SendMessageOptions {
  session: Session;
  message: string;
  onMessage: (msg: SDKMessage) => void;
}

export async function sendMessage({
  session,
  message,
  onMessage,
}: SendMessageOptions): Promise<void> {
  const project = getProject(session.project_id);
  if (!project) throw new Error("Project not found");

  // Ensure session artifact directory exists inside the project
  const sessionDir = getSessionDir(project.path, session.id);
  ensureDir(sessionDir);

  // Load any custom system prompt for this phase (null → use default)
  const customSystemPrompt = getSetting(`systemPrompt.${session.phase}`) ?? undefined;

  // Load global model override (empty string or null → let SDK use its default)
  const configuredModel = getSetting("model") || undefined;

  // Load MCP servers config (JSON string → object, or undefined if not set)
  const mcpServersJson = getSetting("mcpServers");
  const mcpServersConfig = mcpServersJson ? JSON.parse(mcpServersJson) : undefined;

  // Build allowedTools list from enabled MCP tools
  // Format: mcp__servername__toolname
  const mcpAllowedTools: string[] = [];
  if (mcpServersConfig) {
    for (const [serverName, config] of Object.entries(mcpServersConfig)) {
      const serverConfig = config as {
        enabledTools?: string[];
        discoveredTools?: Array<{ name: string }>;
      };
      // Use enabledTools if available, otherwise allow all discovered tools
      const enabledTools = serverConfig.enabledTools ||
        serverConfig.discoveredTools?.map((t) => t.name) ||
        [];
      for (const toolName of enabledTools) {
        mcpAllowedTools.push(`mcp__${serverName}__${toolName}`);
      }
    }
  }

  // Strip tool management fields from config before passing to SDK
  // SDK only needs: type, command, args, env, url, headers
  let mcpServers: Record<string, unknown> | undefined;
  if (mcpServersConfig && Object.keys(mcpServersConfig).length > 0) {
    mcpServers = Object.fromEntries(
      Object.entries(mcpServersConfig).map(([name, config]) => {
        const { discoveredTools, enabledTools, ...sdkConfig } = config as Record<string, unknown>;
        return [name, sdkConfig];
      })
    );
  }

  const phaseConfig = getPhaseConfig(
    session.phase as Phase,
    sessionDir,
    session.permission_mode as UserPermissionMode,
    customSystemPrompt
  );

  // Build allowedTools for this phase
  const allowedTools: string[] = [];
  if (session.phase === "implement") {
    // Allow git inspection in implement phase
    allowedTools.push("Bash(git status*)", "Bash(git log*)", "Bash(git diff*)");
  }
  if (mcpAllowedTools.length > 0) {
    // Add enabled MCP tools
    allowedTools.push(...mcpAllowedTools);
  }

  const q = query({
    prompt: message,
    options: {
      cwd: project.path,
      model: configuredModel,
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      mcpServers: mcpServers as any,
      resume: session.claude_session_id ?? undefined,
      tools: phaseConfig.tools,
      permissionMode: phaseConfig.permissionMode,
      // Required companion flag when bypassPermissions is active
      allowDangerouslySkipPermissions: phaseConfig.permissionMode === "bypassPermissions",
      systemPrompt: phaseConfig.systemPrompt,
      // Pre-approve specific tools to avoid permission prompts
      ...(allowedTools.length > 0 && { allowedTools }),
    },
  });

  activeQueries.set(session.id, q);

  try {
    for await (const msg of q) {
      // Capture session ID from init message
      if (msg.type === "system" && msg.subtype === "init") {
        if (!session.claude_session_id) {
          updateSession(session.id, { claude_session_id: msg.session_id });
        }
      }
      onMessage(msg);
    }
  } finally {
    activeQueries.delete(session.id);
  }

  // Auto-commit after a successful implement-phase turn.
  // This runs only if for-await completed without throwing (successful turn).
  // Interrupted / errored turns skip the commit.
  if (session.phase === "implement") {
    const previousPlan = planSnapshots.get(session.id) ?? "";
    const currentPlan = autoCommitTurn(
      project.path,
      session.git_branch,
      previousPlan,
      sessionDir
    );
    planSnapshots.set(session.id, currentPlan);
  }
}

export function interruptSession(sessionId: string): void {
  const q = activeQueries.get(sessionId);
  if (q) {
    q.close();
    activeQueries.delete(sessionId);
  }
}

/**
 * Trigger a review: Claude reads the document and addresses user annotations
 */
export async function triggerReview(
  session: Session,
  onMessage: (msg: SDKMessage) => void
): Promise<void> {
  const artifactPath = getArtifactPath(session);
  const message = `I've updated ${artifactPath} with annotations. Read the file, find all my inline notes (marked with // REVIEW:, // NOTE:, TODO:, or similar), address each one, and update the document accordingly. Do not implement anything yet.`;

  await sendMessage({ session, message, onMessage });
}

/**
 * Advance to the next phase
 */
export function advancePhase(session: Session): Phase | null {
  const nextPhase = getNextPhase(session.phase as Phase);
  if (nextPhase) {
    updateSession(session.id, { phase: nextPhase });
  }
  return nextPhase;
}

/**
 * Get the artifact path for a session and phase (inside the project directory)
 */
export function getArtifactPath(session: Session): string {
  const project = getProject(session.project_id);
  if (!project) throw new Error("Project not found");
  const filename = getArtifactFilename(session.phase as Phase);
  return path.join(getSessionDir(project.path, session.id), filename);
}

/**
 * Read an artifact file for a session
 */
export function readSessionArtifact(
  projectId: string,
  sessionId: string,
  filename: string
): string | null {
  const project = getProject(projectId);
  if (!project) return null;
  const filePath = path.join(getSessionDir(project.path, sessionId), filename);
  if (fs.existsSync(filePath)) {
    return fs.readFileSync(filePath, "utf-8");
  }
  return null;
}

/**
 * Write an artifact file for a session
 */
export function writeSessionArtifact(
  projectId: string,
  sessionId: string,
  filename: string,
  content: string
): void {
  const project = getProject(projectId);
  if (!project) throw new Error("Project not found");
  const dir = getSessionDir(project.path, sessionId);
  ensureDir(dir);
  fs.writeFileSync(path.join(dir, filename), content, "utf-8");
}

/**
 * Read CLAUDE.md from project root
 */
export function readClaudeMd(projectPath: string): string | null {
  const filePath = path.join(projectPath, "CLAUDE.md");
  if (fs.existsSync(filePath)) {
    return fs.readFileSync(filePath, "utf-8");
  }
  return null;
}

/**
 * Write CLAUDE.md to project root
 */
export function writeClaudeMd(projectPath: string, content: string): void {
  const filePath = path.join(projectPath, "CLAUDE.md");
  fs.writeFileSync(filePath, content, "utf-8");
}

/**
 * Clear session artifacts
 */
export function clearSessionArtifacts(projectId: string, sessionId: string): void {
  const project = getProject(projectId);
  if (!project) return;
  const dir = getSessionDir(project.path, sessionId);
  if (fs.existsSync(dir)) {
    fs.rmSync(dir, { recursive: true, force: true });
  }
}

// Re-export types
export type { SDKMessage } from "@anthropic-ai/claude-agent-sdk";
export type { Phase, UserPermissionMode } from "./phases";