11import fs from "node:fs" ;
22import readline from "node:readline" ;
33import { setImmediate as yieldToEventLoop } from "node:timers/promises" ;
4+ import { Worker } from "node:worker_threads" ;
5+ import { isRecord } from "@openclaw/normalization-core/record-coerce" ;
46import type { CliSessionReseedReceipt } from "../config/sessions.js" ;
57import { normalizeCliSessionReseedReceipt } from "../config/sessions/cli-session-binding.js" ;
68import {
79 appendCoalescedClaudeCliToolMessage ,
810 createClaudeReseedImportState ,
911 decodeClaudeCliProjectEntry ,
12+ type ClaudeCliProjectEntry ,
1013 parseClaudeCliHistoryEntry ,
1114 redactClaudeCliHistoryMessage ,
1215 resolveClaudeCliSessionFilePath ,
1316} from "./cli-session-history.claude.js" ;
1417
1518const YIELD_BYTES = 256 * 1024 ;
19+ const OFFTHREAD_JSONL_LINE_CHARS = 1024 * 1024 ;
20+ const OVERSIZED_HISTORY_PLACEHOLDER =
21+ "[Claude CLI history record omitted from context because it exceeded 1 MiB.]" ;
22+ const OVERSIZED_ENTRY_WORKER_SOURCE = `
23+ const { parentPort, workerData } = require("node:worker_threads");
24+ const boundedString = (value, max) =>
25+ typeof value === "string" && value.length <= max ? value : undefined;
26+ try {
27+ const entry = JSON.parse(workerData);
28+ const type = entry?.type;
29+ const message = entry?.message;
30+ if ((type !== "user" && type !== "assistant") || !message || message.role !== type) {
31+ parentPort.postMessage(null);
32+ } else {
33+ const rawUsage = message.usage;
34+ const usage = rawUsage && typeof rawUsage === "object"
35+ ? Object.fromEntries(
36+ ["input_tokens", "output_tokens", "cache_read_input_tokens", "cache_creation_input_tokens"]
37+ .flatMap((key) => Number.isFinite(rawUsage[key]) ? [[key, rawUsage[key]]] : []),
38+ )
39+ : undefined;
40+ parentPort.postMessage({
41+ type,
42+ timestamp: boundedString(entry.timestamp, 128),
43+ uuid: boundedString(entry.uuid, 1_024),
44+ isSidechain: entry.isSidechain === true,
45+ isMeta: entry.isMeta === true,
46+ isCompactSummary: entry.isCompactSummary === true,
47+ message: {
48+ role: type,
49+ content: ${ JSON . stringify ( OVERSIZED_HISTORY_PLACEHOLDER ) } ,
50+ model: boundedString(message.model, 256),
51+ stop_reason: boundedString(message.stop_reason, 128),
52+ usage,
53+ },
54+ });
55+ }
56+ } catch {
57+ parentPort.postMessage(null);
58+ }
59+ ` ;
1660type Message = Record < string , unknown > ;
1761type HistoryParams = {
1862 cliSessionId : string ;
@@ -22,6 +66,63 @@ type HistoryParams = {
2266} ;
2367let snapshotCache : { key : string ; pending : Promise < readonly Message [ ] > } | undefined ;
2468
69+ function normalizeOversizedEntry ( value : unknown ) : ClaudeCliProjectEntry | null {
70+ if ( ! isRecord ( value ) || ( value . type !== "user" && value . type !== "assistant" ) ) {
71+ return null ;
72+ }
73+ const message = value . message ;
74+ if ( ! isRecord ( message ) || message . role !== value . type ) {
75+ return null ;
76+ }
77+ const usage = isRecord ( message . usage ) ? message . usage : undefined ;
78+ return {
79+ type : value . type ,
80+ ...( typeof value . timestamp === "string" ? { timestamp : value . timestamp } : { } ) ,
81+ ...( typeof value . uuid === "string" ? { uuid : value . uuid } : { } ) ,
82+ ...( value . isSidechain === true ? { isSidechain : true } : { } ) ,
83+ ...( value . isMeta === true ? { isMeta : true } : { } ) ,
84+ ...( value . isCompactSummary === true ? { isCompactSummary : true } : { } ) ,
85+ message : {
86+ role : value . type ,
87+ content : OVERSIZED_HISTORY_PLACEHOLDER ,
88+ ...( typeof message . model === "string" ? { model : message . model } : { } ) ,
89+ ...( typeof message . stop_reason === "string" ? { stop_reason : message . stop_reason } : { } ) ,
90+ ...( usage
91+ ? {
92+ usage : {
93+ input_tokens : usage . input_tokens ,
94+ output_tokens : usage . output_tokens ,
95+ cache_read_input_tokens : usage . cache_read_input_tokens ,
96+ cache_creation_input_tokens : usage . cache_creation_input_tokens ,
97+ } ,
98+ }
99+ : { } ) ,
100+ } ,
101+ } ;
102+ }
103+
104+ async function decodeOversizedClaudeEntry ( line : string ) : Promise < ClaudeCliProjectEntry | null > {
105+ let worker : Worker ;
106+ try {
107+ worker = new Worker ( OVERSIZED_ENTRY_WORKER_SOURCE , { eval : true , workerData : line } ) ;
108+ } catch {
109+ return null ;
110+ }
111+ return await new Promise ( ( resolve ) => {
112+ let settled = false ;
113+ const finish = ( value : unknown ) => {
114+ if ( settled ) {
115+ return ;
116+ }
117+ settled = true ;
118+ resolve ( normalizeOversizedEntry ( value ) ) ;
119+ } ;
120+ worker . once ( "message" , finish ) ;
121+ worker . once ( "error" , ( ) => finish ( null ) ) ;
122+ worker . once ( "exit" , ( ) => finish ( null ) ) ;
123+ } ) ;
124+ }
125+
25126function fingerprint ( stats : fs . Stats ) : string {
26127 return [ stats . dev , stats . ino , stats . size , stats . mtimeMs , stats . ctimeMs ] . join ( ":" ) ;
27128}
@@ -62,17 +163,30 @@ async function parseSnapshot(filePath: string, params: HistoryParams): Promise<r
62163 let lineNumber = 0 ;
63164 for await ( const line of lines ) {
64165 lineNumber += 1 ;
65- bytesSinceYield += Buffer . byteLength ( line , "utf8" ) + 1 ;
66- if ( bytesSinceYield >= YIELD_BYTES ) {
166+ const oversized = line . length > OFFTHREAD_JSONL_LINE_CHARS ;
167+ if ( oversized ) {
67168 bytesSinceYield = 0 ;
68- await yieldToEventLoop ( ) ;
69- }
70- if ( ! line . trim ( ) ) {
71- continue ;
169+ } else {
170+ bytesSinceYield += Buffer . byteLength ( line , "utf8" ) + 1 ;
171+ if ( bytesSinceYield >= YIELD_BYTES ) {
172+ bytesSinceYield = 0 ;
173+ await yieldToEventLoop ( ) ;
174+ }
175+ if ( ! line . trim ( ) ) {
176+ continue ;
177+ }
72178 }
73179 try {
180+ // Keep large valid user/assistant records visible through a bounded projection;
181+ // unsupported external records are still ignored, but JSON.parse runs off-loop.
182+ const entry = oversized
183+ ? await decodeOversizedClaudeEntry ( line )
184+ : decodeClaudeCliProjectEntry ( line ) ;
185+ if ( ! entry ) {
186+ continue ;
187+ }
74188 const message = parseClaudeCliHistoryEntry (
75- decodeClaudeCliProjectEntry ( line ) ,
189+ entry ,
76190 params . cliSessionId ,
77191 lineNumber ,
78192 toolNames ,
0 commit comments