MCPcopy Create free account
hub / github.com/ChinaSiro/claude-code-sourcemap / XDK

Function XDK

package/cli.js:4458–4494  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

4456
4457User context: ${Y}`;else if(j.newCustomInstructions)H=j.newCustomInstructions;else if(Y)H=`User context: ${Y}`;_.setStreamMode?.("requesting"),_.setResponseLength?.(()=>0),_.onCompactProgress?.({type:"compact_start"});let J=oWK(H,$),M=U8({content:J}),X={preCompactTokenCount:w,direction:$,messagesSummarized:A.length},P=$==="up_to"?A:q,W=$==="up_to"?{...z,forkContextMessages:A}:z,D,f,G=0;for(;;){if(D=await $DK({messages:P,summaryRequest:M,appState:_.getAppState(),context:_,preCompactTokenCount:w,cacheSafeParams:W}),f=D18(D),!f?.startsWith(Um))break;G++;let t=G<=qDK?KDK(P,D):null;if(!t)throw d("tengu_partial_compact_failed",{reason:"prompt_too_long",...X,ptlAttempts:G}),Error(_DK);d("tengu_compact_ptl_retry",{attempt:G,droppedMessages:P.length-t.length,remainingMessages:t.length,path:"partial"}),P=t,W={...W,forkContextMessages:t}}if(!f)throw d("tengu_partial_compact_failed",{reason:"no_summary",...X}),Error("Failed to generate conversation summary - response did not contain valid text content");else if(so(f))throw d("tengu_partial_compact_failed",{reason:"api_error",...X}),Error(f);let Z=qI1(_.readFileState);_.readFileState.clear(),_.loadedNestedMemoryPaths?.clear();let[T,v]=await Promise.all([ADK(Z,_,eWK,O),jDK(_)]),V=[...T,...v],E=hp8(_.agentId);if(E)V.push(E);let S=await wDK(_);if(S)V.push(S);let R=ODK(_.agentId);if(R)V.push(R);for(let t of Sp8(_.options.tools,_.options.mainLoopModel,O,{callSite:"compact_partial"}))V.push(V4(t));for(let t of Cp8(_,O))V.push(V4(t));for(let t of bp8(_.options.mcpClients,_.options.tools,_.options.mainLoopModel,O))V.push(V4(t));_.onCompactProgress?.({type:"hooks_start",hookType:"session_start"});let x=await xD("compact",{model:_.options.mainLoopModel}),I=NL([D]),B=qU(D);d("tengu_partial_compact",{preCompactTokenCount:w,postCompactTokenCount:I,messagesKept:O.length,messagesSummarized:A.length,direction:$,hasUserFeedback:!!Y,trigger:"message_selector",compactionInputTokens:B?.input_tokens,compactionOutputTokens:B?.output_tokens,compactionCacheReadTokens:B?.cache_read_input_tokens??0,compactionCacheCreationTokens:B?.cache_creation_input_tokens??0});let p=$==="up_to"?q.slice(0,K).findLast((t)=>t.type!=="progress")?.uuid:O.at(-1)?.uuid,C=f18("manual",w??0,p,Y,A.length),g=iQ(q);if(g.size>0)C.compactMetadata.preCompactDiscoveredTools=[...g].sort();let F=Y$(),U=[U8({content:P18(f,!1,F),isCompactSummary:!0,...O.length>0?{summarizeMetadata:{messagesSummarized:A.length,userContext:Y,direction:$}}:{isVisibleInTranscriptOnly:!0}})];bt(),xp8(),_.onCompactProgress?.({type:"hooks_start",hookType:"post_compact"});let c=await Ip8({trigger:"manual",compactSummary:f},_.abortController.signal),K6=$==="up_to"?U.at(-1)?.uuid??C.uuid:C.uuid;return{boundaryMarker:b87(C,K6,O),summaryMessages:U,messagesToKeep:O,attachments:V,hookResults:x,userDisplayMessage:c.userDisplayMessage,preCompactTokenCount:w,postCompactTokenCount:I,compactionUsage:B}}catch(A){throw YDK(A,_),A}finally{_.setStreamMode?.("requesting"),_.setResponseLength?.(()=>0),_.onCompactProgress?.({type:"compact_end"}),_.setSDKStatus?.(null)}}function YDK(q,K){if(!nt(q,co)&&!nt(q,eR6))K.addNotification?.({key:"error-compacting-conversation",text:"Error compacting conversation",priority:"immediate",color:"error"})}function x3Y(){return async()=>({behavior:"deny",message:"Tool use is not allowed during compaction",decisionReason:{type:"other",reason:"compaction agent should only produce text summary"}})}async function $DK({messages:q,summaryRequest:K,appState:_,context:z,preCompactTokenCount:Y,cacheSafeParams:$}){let A=g8("tengu_compact_cache_prefix",!0),O=QPK()?setInterval((w)=>{UPK(),w?.("compacting")},30000,z.setSDKStatus):void 0;try{if(A)try{let H=await hG({promptMessages:[K],cacheSafeParams:$,canUseTool:x3Y(),querySource:"compact",forkLabel:"compact",maxTurns:1,skipCacheWrite:!0,overrides:{abortController:z.abortController}}),J=uP(H.messages),M=J?D18(J):null;if(J&&M&&!J.isApiErrorMessage){if(!M.startsWith(Um))d("tengu_compact_cache_sharing_success",{preCompactTokenCount:Y,outputTokens:H.totalUsage.output_tokens,cacheReadInputTokens:H.totalUsage.cache_read_input_tokens,cacheCreationInputTokens:H.totalUsage.cache_creation_input_tokens,cacheHitRate:H.totalUsage.cache_read_input_tokens>0?H.totalUsage.cache_read_input_tokens/(H.totalUsage.cache_read_input_tokens+H.totalUsage.cache_creation_input_tokens+H.totalUsage.input_tokens):0});return J}N(`Compact cache sharing: no text in response, falling back. Response: ${g6(J)}`,{level:"warn"}),d("tengu_compact_cache_sharing_fallback",{reason:"no_text_response",preCompactTokenCount:Y})}catch(H){H6(H),d("tengu_compact_cache_sharing_fallback",{reason:"error",preCompactTokenCount:Y})}let w=g8("tengu_compact_streaming_retry",!1),j=w?S3Y:1;for(let H=1;H<=j;H++){let J=!1,M;z.setResponseLength?.(()=>0);let P=await W18(z.options.mainLoopModel,z.options.tools,async()=>_.toolPermissionContext,z.options.agentDefinitions.activeAgents,"compact")?u2([i_,Tr6,...z.options.tools.filter((G)=>G.isMcp)],"name"):[i_],D=fR6({messages:bP(C3Y(b3Y([...i2(q),K])),z.options.tools),systemPrompt:iK(["You are a helpful AI assistant tasked with summarizing conversations."]),thinkingConfig:{type:"disabled"},tools:P,signal:z.abortController.signal,options:{async getToolPermissionContext(){return z.getAppState().toolPermissionContext},model:z.options.mainLoopModel,toolChoice:void 0,isNonInteractiveSession:z.options.isNonInteractiveSession,hasAppendSystemPrompt:!!z.options.appendSystemPrompt,maxOutputTokensOverride:Math.min(iSq,Z18(z.options.mainLoopModel)),querySource:"compact",agents:z.options.agentDefinitions.activeAgents,mcpTools:[],effortValue:_.effortValue}})[Symbol.asyncIterator](),f=await D.next();while(!f.done){let G=f.value;if(!J&&G.type==="stream_event"&&G.event.type==="content_block_start"&&G.event.content_block.type==="text")J=!0,z.setStreamMode?.("responding");if(G.type==="stream_event"&&G.event.type==="content_block_delta"&&G.event.delta.type==="text_delta"){let Z=G.event.delta.text.length;z.setResponseLength?.((T)=>T+Z)}if(G.type==="assistant")M=G;f=await D.next()}if(M)return M;if(H<j){d("tengu_compact_streaming_retry",{attempt:H,preCompactTokenCount:Y,hasStartedStreaming:J}),await R7(hC(H),z.abortController.signal,{abortError:()=>new V_});continue}throw N(`Compact streaming failed after ${H} attempts. hasStartedStreaming=${J}`,{level:"error"}),d("tengu_compact_failed",{reason:"no_streaming_response",preCompactTokenCount:Y,hasStartedStreaming:J,retryEnabled:w,attempts:H,promptCacheSharingEnabled:A}),Error(tR6)}throw Error(tR6)}finally{clearInterval(O)}}async function ADK(q,K,_,z=[]){let Y=I3Y(z),$=Object.entries(q).map(([w,j])=>({filename:w,...j})).filter((w)=>!m3Y(w.filename,K.agentId)&&!Y.has(lq(w.filename))).sort((w,j)=>j.timestamp-w.timestamp).slice(0,_),A=await Promise.all($.map(async(w)=>{let j=await I87(w.filename,{...K,fileReadingLimits:{maxTokens:L3Y}},"tengu_post_compact_file_restore_success","tengu_post_compact_file_restore_error","compact");return j?V4(j):null})),O=0;return A.filter((w)=>{if(w===null)return!1;let j=E3(g6(w));if(O+j<=E3Y)return O+=j,!0;return!1})}function hp8(q){let K=mX(q);if(!K)return null;let _=nP(q);return V4({type:"plan_file_reference",planFilePath:_,planContent:K})}function ODK(q){let K=X38(q);if(K.size===0)return null;let _=0,z=Array.from(K.values()).sort((Y,$)=>$.invokedAt-Y.invokedAt).map((Y)=>({name:Y.skillName,path:Y.skillPath,content:u3Y(Y.content,R3Y)})).filter((Y)=>{let $=E3(Y.content);if(_+$>h3Y)return!1;return _+=$,!0});if(z.length===0)return null;return V4({type:"invoked_skills",skills:z})}async function wDK(q){if(q.getAppState().toolPermissionContext.mode!=="plan")return null;let _=nP(q.agentId),z=mX(q.agentId)!==null;return V4({type:"plan_mode",reminderType:"full",isSubAgent:!!q.agentId,planFilePath:_,planExists:z})}async function jDK(q){let K=q.getAppState();return Object.values(K.tasks).filter((z)=>z.type==="local_agent").flatMap((z)=>{if(z.retrieved||z.status==="pending"||z.agentId===q.agentId)return[];return[V4({type:"task_status",taskId:z.agentId,taskType:"local_agent",description:z.description,status:z.status,deltaSummary:z.status==="running"?z.progress?.summary??null:z.error??null,outputFilePath:sz(z.agentId)})]})}function I3Y(q){let K=new Set;for(let z of q){if(z.type!=="user"||!Array.isArray(z.message.content))continue;for(let Y of z.message.content)if(Y.type==="tool_result"&&typeof Y.content==="string"&&Y.content.startsWith(_T6))K.add(Y.tool_use_id)}let _=new Set;for(let z of q){if(z.type!=="assistant"||!Array.isArray(z.message.content))continue;for(let Y of z.message.content){if(Y.type!=="tool_use"||Y.name!==Cq||K.has(Y.id))continue;let $=Y.input;if($&&typeof $==="object"&&"file_path"in $&&typeof $.file_path==="string")_.add(lq($.file_path))}}return _}function u3Y(q,K){if(E3(q)<=K)return q;let _=K*4-tWK.length;return q.slice(0,_)+tWK}function m3Y(q,K){let _=lq(q);try{let z=lq(nP(K));if(_===z)return!0}catch{}try{if(new Set(cWK.map((Y)=>lq(l$6(Y)))).has(_))return!0}catch{}return!1}var eWK=5,E3Y=50000,L3Y=5000,R3Y=5000,h3Y=25000,S3Y=2,eR6="Not enough messages to compact.",qDK=3,sWK="[earlier conversation truncated for compaction retry]",_DK="Conversation too long. Press esc twice to go up a few messages and try again.",co="API Error: Request was aborted.",tR6="Compaction interrupted · This may be due to network issues — please try again.",tWK=`
4458
4459[... skill content truncated for compaction; use Read on the skill path if you need the full text]`;var no=y(()=>{Fu();LZ();v8();v8();$p();IY();Uk8();lP();V1();fP();XJ4();_8();y8();NG();nv();y$();E8();lWK();i1();dz();SJ();rR6();JK6();_K();l8();Ij();EG();RC();o1();k8();ew();SC();Q76();Wr();S87();ON();C87()});function Hp(q){let K=q===void 0||q.startsWith("repl_main_thread")||q==="sdk";if(Xr(),K)bO.cache.clear?.(),Xr6("compact");La(),z4K(),zp8(),Gg4(),u87()}var G18=y(()=>{kR6();jN();DN();_K6();wM();_K();Ts6();EC()});import{readFile as WDK}from"fs/promises";import{join as DDK}from"path";function XDK(){return`IMPORTANT: This message and these instructions are NOT part of the actual user conversation. Do NOT include any references to "note-taking", "session notes extraction", or these update instructions in the notes content.
4460
4461Based on the user conversation above (EXCLUDING this note-taking instruction message as well as system prompt, claude.md entries, or any past session summaries), update the session notes file.
4462
4463The file {{notesPath}} has already been read for you. Here are its current contents:
4464<current_notes_content>
4465{{currentNotes}}
4466</current_notes_content>
4467
4468Your ONLY task is to use the Edit tool to update the notes file, then stop. You can make multiple edits (update every section as needed) - make all Edit tool calls in parallel in a single message. Do not call any other tools.
4469
4470CRITICAL RULES FOR EDITING:
4471- The file must maintain its exact structure with all sections, headers, and italic descriptions intact
4472-- NEVER modify, delete, or add section headers (the lines starting with '#' like # Task specification)
4473-- NEVER modify or delete the italic _section description_ lines (these are the lines in italics immediately following each header - they start and end with underscores)
4474-- The italic _section descriptions_ are TEMPLATE INSTRUCTIONS that must be preserved exactly as-is - they guide what content belongs in each section
4475-- ONLY update the actual content that appears BELOW the italic _section descriptions_ within each existing section
4476-- Do NOT add any new sections, summaries, or information outside the existing structure
4477- Do NOT reference this note-taking process or instructions anywhere in the notes
4478- It's OK to skip updating a section if there are no substantial new insights to add. Do not add filler content like "No info yet", just leave sections blank/unedited if appropriate.
4479- Write DETAILED, INFO-DENSE content for each section - include specifics like file paths, function names, error messages, exact commands, technical details, etc.
4480- For "Key results", include the complete, exact output the user requested (e.g., full table, full answer, etc.)
4481- Do not include information that's already in the CLAUDE.md files included in the context
4482- Keep each section under ~${up8} tokens/words - if a section is approaching this limit, condense it by cycling out less important details while preserving the most critical information
4483- Focus on actionable, specific information that would help someone understand or recreate the work discussed in the conversation
4484- IMPORTANT: Always update "Current State" to reflect the most recent work - this is critical for continuity after compaction
4485
4486Use the Edit tool with file_path: {{notesPath}}
4487
4488STRUCTURE PRESERVATION REMINDER:
4489Each section has TWO parts that must be preserved exactly as they appear in the current file:
44901. The section header (line starting with #)
44912. The italic description line (the _italicized text_ immediately after the header - this is a template instruction)
4492
4493You ONLY update the actual content that comes AFTER these two preserved lines. The italic description lines starting and ending with underscores are part of the template structure, NOT content to be edited or removed.
4494
4495REMEMBER: Use the Edit tool in parallel and stop. Do not continue after the edits. Only include insights from the actual user conversation, never from these note-taking instructions. Do not delete or change section headers or italic _section descriptions_.`}async function m87(){let q=DDK(c1(),"session-memory","config","template.md");try{return await WDK(q,{encoding:"utf-8"})}catch(K){if(s1(K)==="ENOENT")return MDK;return H6(x1(K)),MDK}}async function B3Y(){let q=DDK(c1(),"session-memory","config","prompt.md");try{return await WDK(q,{encoding:"utf-8"})}catch(K){if(s1(K)==="ENOENT")return XDK();return H6(x1(K)),XDK()}}function g3Y(q){let K={},_=q.split(`
4496`),z="",Y=[];for(let $ of _)if($.startsWith("# ")){if(z&&Y.length>0){let A=Y.join(`
4497`).trim();K[z]=E3(A)}z=$,Y=[]}else Y.push($);if(z&&Y.length>0){let $=Y.join(`

Callers 1

B3YFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected