|
| 1 | +import fs from "node:fs"; |
| 2 | +import os from "node:os"; |
| 3 | +import path from "node:path"; |
| 4 | +import { |
| 5 | + isToolCallBlock, |
| 6 | + isToolResultBlock, |
| 7 | + resolveToolUseId, |
| 8 | + type ToolContentBlock, |
| 9 | +} from "../chat/tool-content.js"; |
| 10 | +import type { SessionEntry } from "../config/sessions.js"; |
| 11 | +import { attachOpenClawTranscriptMeta } from "./session-utils.fs.js"; |
| 12 | + |
| 13 | +export const CLAUDE_CLI_PROVIDER = "claude-cli"; |
| 14 | +const CLAUDE_PROJECTS_RELATIVE_DIR = path.join(".claude", "projects"); |
| 15 | + |
| 16 | +type ClaudeCliProjectEntry = { |
| 17 | + type?: unknown; |
| 18 | + timestamp?: unknown; |
| 19 | + uuid?: unknown; |
| 20 | + isSidechain?: unknown; |
| 21 | + message?: { |
| 22 | + role?: unknown; |
| 23 | + content?: unknown; |
| 24 | + model?: unknown; |
| 25 | + stop_reason?: unknown; |
| 26 | + usage?: { |
| 27 | + input_tokens?: unknown; |
| 28 | + output_tokens?: unknown; |
| 29 | + cache_read_input_tokens?: unknown; |
| 30 | + cache_creation_input_tokens?: unknown; |
| 31 | + }; |
| 32 | + }; |
| 33 | +}; |
| 34 | + |
| 35 | +type ClaudeCliMessage = NonNullable<ClaudeCliProjectEntry["message"]>; |
| 36 | +type ClaudeCliUsage = ClaudeCliMessage["usage"]; |
| 37 | +type TranscriptLikeMessage = Record<string, unknown>; |
| 38 | +type ToolNameRegistry = Map<string, string>; |
| 39 | + |
| 40 | +function resolveHistoryHomeDir(homeDir?: string): string { |
| 41 | + return homeDir?.trim() || process.env.HOME || os.homedir(); |
| 42 | +} |
| 43 | + |
| 44 | +function resolveClaudeProjectsDir(homeDir?: string): string { |
| 45 | + return path.join(resolveHistoryHomeDir(homeDir), CLAUDE_PROJECTS_RELATIVE_DIR); |
| 46 | +} |
| 47 | + |
| 48 | +export function resolveClaudeCliBindingSessionId( |
| 49 | + entry: SessionEntry | undefined, |
| 50 | +): string | undefined { |
| 51 | + const bindingSessionId = entry?.cliSessionBindings?.[CLAUDE_CLI_PROVIDER]?.sessionId?.trim(); |
| 52 | + if (bindingSessionId) { |
| 53 | + return bindingSessionId; |
| 54 | + } |
| 55 | + const legacyMapSessionId = entry?.cliSessionIds?.[CLAUDE_CLI_PROVIDER]?.trim(); |
| 56 | + if (legacyMapSessionId) { |
| 57 | + return legacyMapSessionId; |
| 58 | + } |
| 59 | + const legacyClaudeSessionId = entry?.claudeCliSessionId?.trim(); |
| 60 | + return legacyClaudeSessionId || undefined; |
| 61 | +} |
| 62 | + |
| 63 | +function resolveFiniteNumber(value: unknown): number | undefined { |
| 64 | + return typeof value === "number" && Number.isFinite(value) ? value : undefined; |
| 65 | +} |
| 66 | + |
| 67 | +function resolveTimestampMs(value: unknown): number | undefined { |
| 68 | + if (typeof value !== "string") { |
| 69 | + return undefined; |
| 70 | + } |
| 71 | + const parsed = Date.parse(value); |
| 72 | + return Number.isFinite(parsed) ? parsed : undefined; |
| 73 | +} |
| 74 | + |
| 75 | +function resolveClaudeCliUsage(raw: ClaudeCliUsage) { |
| 76 | + if (!raw || typeof raw !== "object") { |
| 77 | + return undefined; |
| 78 | + } |
| 79 | + const input = resolveFiniteNumber(raw.input_tokens); |
| 80 | + const output = resolveFiniteNumber(raw.output_tokens); |
| 81 | + const cacheRead = resolveFiniteNumber(raw.cache_read_input_tokens); |
| 82 | + const cacheWrite = resolveFiniteNumber(raw.cache_creation_input_tokens); |
| 83 | + if ( |
| 84 | + input === undefined && |
| 85 | + output === undefined && |
| 86 | + cacheRead === undefined && |
| 87 | + cacheWrite === undefined |
| 88 | + ) { |
| 89 | + return undefined; |
| 90 | + } |
| 91 | + return { |
| 92 | + ...(input !== undefined ? { input } : {}), |
| 93 | + ...(output !== undefined ? { output } : {}), |
| 94 | + ...(cacheRead !== undefined ? { cacheRead } : {}), |
| 95 | + ...(cacheWrite !== undefined ? { cacheWrite } : {}), |
| 96 | + }; |
| 97 | +} |
| 98 | + |
| 99 | +function cloneJsonValue<T>(value: T): T { |
| 100 | + return JSON.parse(JSON.stringify(value)) as T; |
| 101 | +} |
| 102 | + |
| 103 | +function normalizeClaudeCliContent( |
| 104 | + content: string | unknown[], |
| 105 | + toolNameRegistry: ToolNameRegistry, |
| 106 | +): string | unknown[] { |
| 107 | + if (!Array.isArray(content)) { |
| 108 | + return cloneJsonValue(content); |
| 109 | + } |
| 110 | + |
| 111 | + const normalized: ToolContentBlock[] = []; |
| 112 | + for (const item of content) { |
| 113 | + if (!item || typeof item !== "object") { |
| 114 | + normalized.push(cloneJsonValue(item as ToolContentBlock)); |
| 115 | + continue; |
| 116 | + } |
| 117 | + const block = cloneJsonValue(item as ToolContentBlock); |
| 118 | + const type = typeof block.type === "string" ? block.type : ""; |
| 119 | + if (type === "tool_use") { |
| 120 | + const id = typeof block.id === "string" ? block.id.trim() : ""; |
| 121 | + const name = typeof block.name === "string" ? block.name.trim() : ""; |
| 122 | + if (id && name) { |
| 123 | + toolNameRegistry.set(id, name); |
| 124 | + } |
| 125 | + if (block.input !== undefined && block.arguments === undefined) { |
| 126 | + block.arguments = cloneJsonValue(block.input); |
| 127 | + } |
| 128 | + block.type = "toolcall"; |
| 129 | + delete block.input; |
| 130 | + normalized.push(block); |
| 131 | + continue; |
| 132 | + } |
| 133 | + if (type === "tool_result") { |
| 134 | + const toolUseId = resolveToolUseId(block); |
| 135 | + if (!block.name && toolUseId) { |
| 136 | + const toolName = toolNameRegistry.get(toolUseId); |
| 137 | + if (toolName) { |
| 138 | + block.name = toolName; |
| 139 | + } |
| 140 | + } |
| 141 | + normalized.push(block); |
| 142 | + continue; |
| 143 | + } |
| 144 | + normalized.push(block); |
| 145 | + } |
| 146 | + return normalized; |
| 147 | +} |
| 148 | + |
| 149 | +function getMessageBlocks(message: unknown): ToolContentBlock[] | null { |
| 150 | + if (!message || typeof message !== "object") { |
| 151 | + return null; |
| 152 | + } |
| 153 | + const content = (message as { content?: unknown }).content; |
| 154 | + return Array.isArray(content) ? (content as ToolContentBlock[]) : null; |
| 155 | +} |
| 156 | + |
| 157 | +function isAssistantToolCallMessage(message: unknown): boolean { |
| 158 | + if (!message || typeof message !== "object") { |
| 159 | + return false; |
| 160 | + } |
| 161 | + const role = (message as { role?: unknown }).role; |
| 162 | + if (role !== "assistant") { |
| 163 | + return false; |
| 164 | + } |
| 165 | + const blocks = getMessageBlocks(message); |
| 166 | + return Boolean(blocks && blocks.length > 0 && blocks.every(isToolCallBlock)); |
| 167 | +} |
| 168 | + |
| 169 | +function isUserToolResultMessage(message: unknown): boolean { |
| 170 | + if (!message || typeof message !== "object") { |
| 171 | + return false; |
| 172 | + } |
| 173 | + const role = (message as { role?: unknown }).role; |
| 174 | + if (role !== "user") { |
| 175 | + return false; |
| 176 | + } |
| 177 | + const blocks = getMessageBlocks(message); |
| 178 | + return Boolean(blocks && blocks.length > 0 && blocks.every(isToolResultBlock)); |
| 179 | +} |
| 180 | + |
| 181 | +function coalesceClaudeCliToolMessages(messages: TranscriptLikeMessage[]): TranscriptLikeMessage[] { |
| 182 | + const coalesced: TranscriptLikeMessage[] = []; |
| 183 | + for (let index = 0; index < messages.length; index += 1) { |
| 184 | + const current = messages[index]; |
| 185 | + const next = messages[index + 1]; |
| 186 | + if (!isAssistantToolCallMessage(current) || !isUserToolResultMessage(next)) { |
| 187 | + coalesced.push(current); |
| 188 | + continue; |
| 189 | + } |
| 190 | + |
| 191 | + const callBlocks = getMessageBlocks(current) ?? []; |
| 192 | + const resultBlocks = getMessageBlocks(next) ?? []; |
| 193 | + const callIds = new Set( |
| 194 | + callBlocks.map(resolveToolUseId).filter((id): id is string => Boolean(id)), |
| 195 | + ); |
| 196 | + const allResultsMatch = |
| 197 | + resultBlocks.length > 0 && |
| 198 | + resultBlocks.every((block) => { |
| 199 | + const toolUseId = resolveToolUseId(block); |
| 200 | + return Boolean(toolUseId && callIds.has(toolUseId)); |
| 201 | + }); |
| 202 | + if (!allResultsMatch) { |
| 203 | + coalesced.push(current); |
| 204 | + continue; |
| 205 | + } |
| 206 | + |
| 207 | + coalesced.push({ |
| 208 | + ...current, |
| 209 | + content: [...callBlocks.map(cloneJsonValue), ...resultBlocks.map(cloneJsonValue)], |
| 210 | + }); |
| 211 | + index += 1; |
| 212 | + } |
| 213 | + return coalesced; |
| 214 | +} |
| 215 | + |
| 216 | +function parseClaudeCliHistoryEntry( |
| 217 | + entry: ClaudeCliProjectEntry, |
| 218 | + cliSessionId: string, |
| 219 | + toolNameRegistry: ToolNameRegistry, |
| 220 | +): TranscriptLikeMessage | null { |
| 221 | + if (entry.isSidechain === true || !entry.message || typeof entry.message !== "object") { |
| 222 | + return null; |
| 223 | + } |
| 224 | + const type = typeof entry.type === "string" ? entry.type : undefined; |
| 225 | + const role = typeof entry.message.role === "string" ? entry.message.role : undefined; |
| 226 | + if ((type !== "user" && type !== "assistant") || role !== type) { |
| 227 | + return null; |
| 228 | + } |
| 229 | + |
| 230 | + const timestamp = resolveTimestampMs(entry.timestamp); |
| 231 | + const baseMeta = { |
| 232 | + importedFrom: CLAUDE_CLI_PROVIDER, |
| 233 | + cliSessionId, |
| 234 | + ...(typeof entry.uuid === "string" && entry.uuid.trim() ? { externalId: entry.uuid } : {}), |
| 235 | + }; |
| 236 | + |
| 237 | + const content = |
| 238 | + typeof entry.message.content === "string" || Array.isArray(entry.message.content) |
| 239 | + ? normalizeClaudeCliContent(entry.message.content, toolNameRegistry) |
| 240 | + : undefined; |
| 241 | + if (content === undefined) { |
| 242 | + return null; |
| 243 | + } |
| 244 | + |
| 245 | + if (type === "user") { |
| 246 | + return attachOpenClawTranscriptMeta( |
| 247 | + { |
| 248 | + role: "user", |
| 249 | + content, |
| 250 | + ...(timestamp !== undefined ? { timestamp } : {}), |
| 251 | + }, |
| 252 | + baseMeta, |
| 253 | + ) as TranscriptLikeMessage; |
| 254 | + } |
| 255 | + |
| 256 | + return attachOpenClawTranscriptMeta( |
| 257 | + { |
| 258 | + role: "assistant", |
| 259 | + content, |
| 260 | + api: "anthropic-messages", |
| 261 | + provider: CLAUDE_CLI_PROVIDER, |
| 262 | + ...(typeof entry.message.model === "string" && entry.message.model.trim() |
| 263 | + ? { model: entry.message.model } |
| 264 | + : {}), |
| 265 | + ...(typeof entry.message.stop_reason === "string" && entry.message.stop_reason.trim() |
| 266 | + ? { stopReason: entry.message.stop_reason } |
| 267 | + : {}), |
| 268 | + ...(resolveClaudeCliUsage(entry.message.usage) |
| 269 | + ? { usage: resolveClaudeCliUsage(entry.message.usage) } |
| 270 | + : {}), |
| 271 | + ...(timestamp !== undefined ? { timestamp } : {}), |
| 272 | + }, |
| 273 | + baseMeta, |
| 274 | + ) as TranscriptLikeMessage; |
| 275 | +} |
| 276 | + |
| 277 | +export function resolveClaudeCliSessionFilePath(params: { |
| 278 | + cliSessionId: string; |
| 279 | + homeDir?: string; |
| 280 | +}): string | undefined { |
| 281 | + const projectsDir = resolveClaudeProjectsDir(params.homeDir); |
| 282 | + let projectEntries: fs.Dirent[]; |
| 283 | + try { |
| 284 | + projectEntries = fs.readdirSync(projectsDir, { withFileTypes: true }); |
| 285 | + } catch { |
| 286 | + return undefined; |
| 287 | + } |
| 288 | + |
| 289 | + for (const entry of projectEntries) { |
| 290 | + if (!entry.isDirectory()) { |
| 291 | + continue; |
| 292 | + } |
| 293 | + const candidate = path.join(projectsDir, entry.name, `${params.cliSessionId}.jsonl`); |
| 294 | + if (fs.existsSync(candidate)) { |
| 295 | + return candidate; |
| 296 | + } |
| 297 | + } |
| 298 | + return undefined; |
| 299 | +} |
| 300 | + |
| 301 | +export function readClaudeCliSessionMessages(params: { |
| 302 | + cliSessionId: string; |
| 303 | + homeDir?: string; |
| 304 | +}): TranscriptLikeMessage[] { |
| 305 | + const filePath = resolveClaudeCliSessionFilePath(params); |
| 306 | + if (!filePath) { |
| 307 | + return []; |
| 308 | + } |
| 309 | + |
| 310 | + let content: string; |
| 311 | + try { |
| 312 | + content = fs.readFileSync(filePath, "utf-8"); |
| 313 | + } catch { |
| 314 | + return []; |
| 315 | + } |
| 316 | + |
| 317 | + const messages: TranscriptLikeMessage[] = []; |
| 318 | + const toolNameRegistry: ToolNameRegistry = new Map(); |
| 319 | + for (const line of content.split(/\r?\n/)) { |
| 320 | + if (!line.trim()) { |
| 321 | + continue; |
| 322 | + } |
| 323 | + try { |
| 324 | + const parsed = JSON.parse(line) as ClaudeCliProjectEntry; |
| 325 | + const message = parseClaudeCliHistoryEntry(parsed, params.cliSessionId, toolNameRegistry); |
| 326 | + if (message) { |
| 327 | + messages.push(message); |
| 328 | + } |
| 329 | + } catch { |
| 330 | + // Ignore malformed external history entries. |
| 331 | + } |
| 332 | + } |
| 333 | + return coalesceClaudeCliToolMessages(messages); |
| 334 | +} |
0 commit comments