openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
272 lines (271 loc) • 10.3 kB
JavaScript
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs";
import { S as parseDateStringTimestampMs, s as asFiniteNumber } from "./number-coercion-D6u-4YD8.mjs";
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { r as isToolResultBlock, s as resolveToolUseId, t as isToolCallBlock } from "./tool-content-DG-uYHoo.mjs";
import { r as getCliSessionBinding } from "./cli-session-binding-BEOgFSDg.mjs";
import { t as attachOpenClawTranscriptMeta } from "./session-transcript-entry-message-BrwStPpF.mjs";
import "./session-accessor.sqlite-transcript-store-DRtj0wNT.mjs";
import { i as parseCliReseedPrompt, n as stripCliSessionDriftNote, r as hashCliReseedPrompt } from "./cli-session-drift-CvaL5sfX.mjs";
import { i as stripCliImageTurnContext, r as readCliImageTurnContext } from "./cli-image-turn-correlation-DVP0DD-I.mjs";
import { n as resolveClaudeCliProjectsDir } from "./claude-cli-project-dir-DwJdMUca.mjs";
import fs from "node:fs";
import path from "node:path";
//#region src/gateway/cli-session-history.claude.ts
const CLAUDE_CLI_PROVIDER = "claude-cli";
function decodeClaudeCliProjectEntry(e) {
const t = JSON.parse(e);
if (!isRecord(t)) throw new Error("Claude history row must be an object");
return t;
}
function normalizeClaudeCliSessionId(e) {
const t = e.trim();
return !t || t === "." || t === ".." || path.isAbsolute(t) || t.includes("/") || t.includes("\\") ? void 0 : t;
}
function resolveClaudeSessionCandidate(e, t) {
const n = path.resolve(e, `${t}.jsonl`);
return n.startsWith(`${path.resolve(e)}${path.sep}`) ? n : void 0;
}
function resolveClaudeCliBindingSessionId(e) {
return getCliSessionBinding(e, CLAUDE_CLI_PROVIDER)?.sessionId;
}
function resolveClaudeCliUsage(e) {
if (!e || typeof e !== "object") return;
const t = asFiniteNumber(e.input_tokens);
const n = asFiniteNumber(e.output_tokens);
const r = asFiniteNumber(e.cache_read_input_tokens);
const i = asFiniteNumber(e.cache_creation_input_tokens);
if (t === void 0 && n === void 0 && r === void 0 && i === void 0) return;
return {
...t !== void 0 ? { input: t } : {},
...n !== void 0 ? { output: n } : {},
...r !== void 0 ? { cacheRead: r } : {},
...i !== void 0 ? { cacheWrite: i } : {}
};
}
function removeContentBlock(e, t) {
e.splice(t, 1);
return e.length > 0 ? e : null;
}
function normalizeClaudeCliContent(e, t) {
if (!Array.isArray(e)) return e;
return e.map((e) => {
if (!isRecord(e)) return e;
const n = { ...e };
const r = typeof n.type === "string" ? n.type : "";
if (r === "tool_use") {
const e = normalizeOptionalString(n.id) ?? "";
const r = normalizeOptionalString(n.name) ?? "";
if (e && r) t.set(e, r);
if (n.input !== void 0 && n.arguments === void 0) n.arguments = n.input;
n.type = "toolcall";
delete n.input;
} else if (r === "tool_result") {
const e = resolveToolUseId(n);
if (!n.name && e) {
const r = t.get(e);
if (r) n.name = r;
}
}
return n;
});
}
function appendCoalescedClaudeCliToolMessage(e, t) {
const n = e.at(-1);
const r = n?.role === "assistant" && Array.isArray(n.content) ? n.content : [];
const i = t.role === "user" && Array.isArray(t.content) ? t.content : [];
if (r.length > 0 && r.every(isToolCallBlock) && i.length > 0 && i.every(isToolResultBlock)) {
const t = new Set(r.map(resolveToolUseId).filter((e) => Boolean(e)));
if (i.every((e) => {
const n = resolveToolUseId(e);
return Boolean(n && t.has(n));
})) {
e[e.length - 1] = {
...n,
content: [...r, ...i]
};
return;
}
}
e.push(t);
}
function isClaudeCliVisibleHarnessContext(e) {
return e.isCompactSummary === true || e.isVisibleInTranscriptOnly === true;
}
function isClaudeCliInterrupt(e, t) {
if (!Array.isArray(t) || t.length !== 1 || "promptSource" in e || "turnOrigin" in e || "turnPosition" in e || "permissionMode" in e) return false;
const n = t[0];
return isRecord(n) && n.type === "text" && (n.text === "[Request interrupted by user]" || n.text === "[Request interrupted by user for tool use]");
}
function isClaudeCliTaskNotification(e, t) {
return isRecord(e.origin) && e.origin.kind === "task-notification" && typeof t === "string" && t.startsWith("<task-notification>") && t.endsWith("</task-notification>");
}
function resolveClaudeCliPromptTextCandidates(e, t) {
if (e.isMeta === true || isClaudeCliVisibleHarnessContext(e)) return [];
if (typeof t === "string") return [{ text: t }];
if (t.some((e) => e !== null && typeof e === "object" && "type" in e && e.type === "tool_result")) return [];
return t.flatMap((e, t) => e !== null && typeof e === "object" && "type" in e && e.type === "text" && "text" in e && typeof e.text === "string" ? [{
text: e.text,
blockIndex: t
}] : []);
}
function resolveClaudeCliInternalSourceTool(e) {
if (stripCliSessionDriftNote(`${e}\n\n`) === "") return "cli_session_resume";
if (/^<command-name>\/compact<\/command-name>\s*<command-message>compact<\/command-message>\s*<command-args>[\s\S]*<\/command-args>$/u.test(e) || /^<local-command-stdout>Compacted\s*<\/local-command-stdout>$/u.test(e)) return "claude_cli_command";
}
function parseClaudeCliHistoryEntry(e, t, n, r, i) {
if (e.isSidechain === true || e.isMeta === true || !e.message || typeof e.message !== "object") return null;
const a = typeof e.type === "string" ? e.type : void 0;
const o = typeof e.message.role === "string" ? e.message.role : void 0;
if (a !== "user" && a !== "assistant" || o !== a) return null;
if (a === "assistant" && e.message.model === "<synthetic>") return null;
const s = parseDateStringTimestampMs(e.timestamp);
const c = normalizeOptionalString(e.uuid);
const l = {
id: c ?? `${CLAUDE_CLI_PROVIDER}:${t}:line:${n}`,
importedFrom: CLAUDE_CLI_PROVIDER,
cliSessionId: t,
...c ? { externalId: c } : {}
};
let u = typeof e.message.content === "string" || Array.isArray(e.message.content) ? normalizeClaudeCliContent(e.message.content, r) : void 0;
if (u === void 0) return null;
if (a === "user") {
if (isClaudeCliInterrupt(e, u)) return null;
const t = i.reseedState;
const n = resolveClaudeCliPromptTextCandidates(e, u);
if (i.reseedMode === "recover" && t && !t.inspectedFirstUser && n.length > 0) {
t.inspectedFirstUser = true;
if (t.receipt) {
const e = n.length === 1 ? n[0] : void 0;
if (e && hashCliReseedPrompt(e.text) === t.receipt.promptHash) {
if (e.blockIndex === void 0 || !Array.isArray(u)) return null;
const t = removeContentBlock(u, e.blockIndex);
if (!t) return null;
u = t;
}
} else for (const e of n) {
const t = parseCliReseedPrompt(e.text);
if (t.kind === "legacy") {
if (e.blockIndex === void 0) {
if (!t.userMessage) return null;
u = t.userMessage;
} else if (Array.isArray(u)) {
if (!t.userMessage) {
const t = removeContentBlock(u, e.blockIndex);
if (!t) return null;
u = t;
break;
}
const n = u[e.blockIndex];
if (n && typeof n === "object") n.text = t.userMessage;
}
break;
}
}
}
const r = resolveClaudeCliPromptTextCandidates(e, u);
const a = r.length === 1 ? resolveClaudeCliInternalSourceTool(r[0].text) : void 0;
const o = typeof u === "string" ? readCliImageTurnContext(u) : void 0;
if (o && typeof u === "string") u = stripCliImageTurnContext(u, o);
const c = isClaudeCliTaskNotification(e, u) ? "claude_cli_task_notification" : isClaudeCliVisibleHarnessContext(e) ? "cli_harness_context" : a;
const d = c ? {
kind: "internal_system",
sourceTool: c
} : void 0;
return attachOpenClawTranscriptMeta({
role: "user",
content: u,
...a ? { display: false } : {},
...d ? { provenance: d } : {},
...s !== void 0 ? { timestamp: s } : {}
}, {
...l,
...o ? { cliImageTurnKey: o } : {}
});
}
const d = resolveClaudeCliUsage(e.message.usage);
return attachOpenClawTranscriptMeta({
role: "assistant",
content: u,
api: "anthropic-messages",
provider: CLAUDE_CLI_PROVIDER,
...normalizeOptionalString(e.message.model) ? { model: e.message.model } : {},
...normalizeOptionalString(e.message.stop_reason) ? { stopReason: e.message.stop_reason === "tool_use" ? "toolUse" : e.message.stop_reason } : {},
...d ? { usage: d } : {},
...s !== void 0 ? { timestamp: s } : {}
}, l);
}
async function resolveClaudeCliSessionFilePathAsync(e) {
const t = normalizeClaudeCliSessionId(e.cliSessionId);
if (!t) return;
const n = e.projectsDir ?? resolveClaudeCliProjectsDir();
let r;
try {
r = await fs.promises.readdir(n, { withFileTypes: true });
} catch {
return;
}
const i = 16;
for (let e = 0; e < r.length; e += i) {
const a = (await Promise.all(r.slice(e, e + i).map(async (e) => {
if (!e.isDirectory()) return;
const r = resolveClaudeSessionCandidate(path.join(n, e.name), t);
if (!r) return;
try {
await fs.promises.access(r);
return r;
} catch {
return;
}
}))).find((e) => e !== void 0);
if (a) return a;
}
}
async function readClaudeCliFallbackSeed(e) {
const t = await resolveClaudeCliSessionFilePathAsync(e);
if (!t) return;
let n;
try {
n = await fs.promises.readFile(t, "utf-8");
} catch {
return;
}
let r;
let i;
let a;
let o = [];
const s = /* @__PURE__ */ new Map();
const c = n.split(/\r?\n/);
for (let t = 0; t < c.length; t += 1) {
const n = c[t] ?? "";
if (!n.trim()) continue;
let l;
try {
l = decodeClaudeCliProjectEntry(n);
} catch {
continue;
}
const u = l.type === "summary" ? normalizeOptionalString(l.summary) : void 0;
if (u) {
r = u;
continue;
}
if (l.type === "system" && l.subtype === "compact_boundary") {
i = r;
r = void 0;
a = normalizeOptionalString(l.content) ?? a;
o = [];
s.clear();
continue;
}
const d = parseClaudeCliHistoryEntry(l, e.cliSessionId, t + 1, s, { reseedMode: "preserve" });
if (d) appendCoalescedClaudeCliToolMessage(o, d);
}
const l = i ?? r ?? a;
if (!l && o.length === 0) return;
return {
...l ? { summaryText: l } : {},
recentTurns: o
};
}
//#endregion
export { resolveClaudeCliPromptTextCandidates as a, resolveClaudeCliBindingSessionId as i, parseClaudeCliHistoryEntry as n, readClaudeCliFallbackSeed as r, decodeClaudeCliProjectEntry as t };