| 7684 | `;try{_.appendFileSync(q,z,{mode:384})}catch{_.mkdirSync(Iq8(q),{mode:448}),_.appendFileSync(q,z,{mode:384})}}function FRY(q){let K;try{K=WRY(q,"r");let _=PRY(K),z=Math.max(0,_.size-ue),Y=Buffer.allocUnsafe(Math.min(ue,_.size-z)),$=DRY(K,Y,0,Y.length,z);return Y.toString("utf8",0,$)}catch{return""}finally{if(K!==void 0)try{XRY(K)}catch{}}}async function $s(q,K,_,z="user"){let Y=_??JT(q);if(jZ(Y,{type:"custom-title",customTitle:K,sessionId:q}),q===N8())dY().currentSessionTitle=K;d("tengu_session_renamed",{source:z})}function Q97(q,K){jZ(JT(q),{type:"ai-title",aiTitle:K,sessionId:q})}function URY(q,K){jZ(JT(q),{type:"task-summary",summary:K,sessionId:q,timestamp:new Date().toISOString()})}async function nU8(q,K,_){let z=_??JT(q);if(jZ(z,{type:"tag",tag:K,sessionId:q}),q===N8())dY().currentSessionTag=K;d("tengu_session_tagged",{})}async function QRY(q,K,_,z,Y){let $=Y??JT(q);if(jZ($,{type:"pr-link",sessionId:q,prNumber:K,prUrl:_,prRepository:z,timestamp:new Date().toISOString()}),q===N8()){let A=dY();A.currentSessionPrNumber=K,A.currentSessionPrUrl=_,A.currentSessionPrRepository=z}d("tengu_session_linked_to_pr",{prNumber:K})}function q97(q){if(q===N8())return dY().currentSessionTag;return}function k0(q){if(q===N8())return dY().currentSessionTitle;return}function d97(){return dY().currentSessionAgentColor}function Ld(q){let K=dY();if(q.customTitle)K.currentSessionTitle??=q.customTitle;if(q.tag!==void 0)K.currentSessionTag=q.tag||void 0;if(q.agentName)K.currentSessionAgentName=q.agentName;if(q.agentColor)K.currentSessionAgentColor=q.agentColor;if(q.agentSetting)K.currentSessionAgentSetting=q.agentSetting;if(q.mode)K.currentSessionMode=q.mode;if(q.worktreeSession!==void 0)K.currentSessionWorktree=q.worktreeSession;if(q.prNumber!==void 0)K.currentSessionPrNumber=q.prNumber;if(q.prUrl)K.currentSessionPrUrl=q.prUrl;if(q.prRepository)K.currentSessionPrRepository=q.prRepository}function j78(){let q=dY();q.currentSessionTitle=void 0,q.currentSessionTag=void 0,q.currentSessionAgentName=void 0,q.currentSessionAgentColor=void 0,q.currentSessionLastPrompt=void 0,q.currentSessionAgentSetting=void 0,q.currentSessionMode=void 0,q.currentSessionWorktree=void 0,q.currentSessionPrNumber=void 0,q.currentSessionPrUrl=void 0,q.currentSessionPrRepository=void 0}function xp8(){dY().reAppendSessionMetadata()}async function o78(q,K,_,z="user"){let Y=_??JT(q);if(jZ(Y,{type:"agent-name",agentName:K,sessionId:q}),q===N8())dY().currentSessionAgentName=K,cQ(K);d("tengu_agent_name_set",{source:z})}async function Gg8(q,K,_){let z=_??JT(q);if(jZ(z,{type:"agent-color",agentColor:K,sessionId:q}),q===N8())dY().currentSessionAgentColor=K;d("tengu_agent_color_set",{})}function uq8(q){dY().currentSessionAgentSetting=q}function c97(q){dY().currentSessionTitle=q}function dRY(q){dY().currentSessionMode=q}function Oy(q){let K=q?{originalCwd:q.originalCwd,worktreePath:q.worktreePath,worktreeName:q.worktreeName,worktreeBranch:q.worktreeBranch,originalBranch:q.originalBranch,originalHeadCommit:q.originalHeadCommit,sessionId:q.sessionId,tmuxSessionName:q.tmuxSessionName,hookBased:q.hookBased}:null,_=dY();if(_.currentSessionWorktree=K,_.sessionFile)jZ(_.sessionFile,{type:"worktree-state",worktreeSession:K,sessionId:N8()})}function SA(q){if(q.sessionId)return q.sessionId;return q.messages[0]?.sessionId}function qR(q){return q.messages.length===0&&q.sessionId!==void 0}async function om(q){if(!qR(q))return q;let K=q.fullPath;if(!K)return q;try{let{messages:_,summaries:z,customTitles:Y,tags:$,agentNames:A,agentColors:O,agentSettings:w,prNumbers:j,prUrls:H,prRepositories:J,modes:M,worktreeStates:X,fileHistorySnapshots:P,attributionSnapshots:W,contentReplacements:D,contextCollapseCommits:f,contextCollapseSnapshot:G,leafUuids:Z}=await $a(K);if(_.size===0)return q;let T=JQ8(_.values(),(E)=>Z.has(E.uuid)&&(E.type==="user"||E.type==="assistant"));if(!T)return q;let v=XK6(_,T),V=T.sessionId;return{...q,messages:KL6(v),firstPrompt:F97(v),messageCount:U97(v),summary:T?z.get(T.uuid):q.summary,customTitle:V?Y.get(V):q.customTitle,tag:V?$.get(V):q.tag,agentName:V?A.get(V):q.agentName,agentColor:V?O.get(V):q.agentColor,agentSetting:V?w.get(V):q.agentSetting,mode:V?M.get(V):q.mode,worktreeSession:V&&X.has(V)?X.get(V):q.worktreeSession,prNumber:V?j.get(V):q.prNumber,prUrl:V?H.get(V):q.prUrl,prRepository:V?J.get(V):q.prRepository,gitBranch:T?.gitBranch??q.gitBranch,isSidechain:v[0]?.isSidechain??q.isSidechain,teamName:v[0]?.teamName??q.teamName,leafUuid:T?.uuid??q.leafUuid,fileHistorySnapshots:MQ8(P,v),attributionSnapshots:XQ8(W,v),contentReplacements:V?D.get(V)??[]:q.contentReplacements,contextCollapseCommits:V?f.filter((E)=>E.sessionId===V):void 0,contextCollapseSnapshot:V&&G?.sessionId===V?G:void 0}}catch{return q}}async function kd(q,K){let{limit:_,exact:z}=K||{},Y=await As(r1()),$=await CBK(Y),{logs:A}=await kJ6($,0,$.length),O=q.toLowerCase().trim(),w=A.filter((J)=>{let M=J.customTitle?.toLowerCase().trim();if(!M)return!1;return z?M===O:M.includes(O)}),j=new Map;for(let J of w){let M=SA(J);if(M){let X=j.get(M);if(!X||J.modified>X.modified)j.set(M,J)}}let H=Array.from(j.values());if(H.sort((J,M)=>M.modified.getTime()-J.modified.getTime()),_)return H.slice(0,_);return H}function nRY(q,K){if(q===null||q.length===0)return K;if(q.length<lRY)return Buffer.concat([q,K]);if(q[0]===123){for(let z of jQ8)if(q.compare(z,0,z.length,1,1+z.length)===0)return Buffer.concat([q,K])}let _=K.indexOf(10);return _===-1?null:K.subarray(_+1)}async function iRY(q,K){let{createReadStream:_}=await import("fs"),z=10,Y=_(q,{end:K-1}),$=[],A=null;for await(let O of Y){let j=nRY(A,O);if(j===null){A=null;continue}let H=!1;for(let J of jQ8)if(j.includes(J)){H=!0;break}if(H){let J=0,M=j.indexOf(10);while(M!==-1){for(let X of jQ8){let P=j.indexOf(X,J);if(P!==-1&&P<M){$.push(j.toString("utf-8",J,M));break}}J=M+1,M=j.indexOf(10,J)}A=j.subarray(J)}else{let J=j.lastIndexOf(10);A=J>=0?j.subarray(J+1):j}if(A.length>65536)A=null}if(A!==null&&A.length>0){for(let O of jQ8)if(A.includes(O)){$.push(A.toString("utf-8"));break}}return $}function rRY(q,K,_){let O=0,w=!1,j=!1,H=0;for(let J=K;H<_.length;J++){if(J===_[H]){if(O===1&&!w)return _[H];H++}let M=q[J];if(j)j=!1;else if(w){if(M===92)j=!0;else if(M===34)w=!1}else if(M===34)w=!0;else if(M===123)O++;else if(M===125)O--}return _.at(-1)}function oRY(q){let Y=Buffer.from('{"parentUuid":'),$=Buffer.from('"uuid":"'),A=Buffer.from('"isSidechain":true'),O=36,w=Buffer.from('","timestamp":"'),j=w.length,H=Y.length,J=$.length,M=[],X=[],P=new Map,W=0,D=q.length;while(W<D){let S=q.indexOf(10,W),R=S===-1?D:S+1;if(R-W>H&&q[W]===123&&q.compare(Y,0,H,W,W+H)===0){let x=q[W+H]===34?W+H+1:-1,I=-1,B=-1,p,C=W;for(;;){let F=q.indexOf($,C);if(F<0||F>=R)break;if(I<0)I=F;let U=F+J+36;if(U+j<=R&&q.compare(w,0,j,U,U+j)===0)if(B<0)B=F;else(p??=[B]).push(F);C=F+J}let g=p?rRY(q,W,p):B>=0?B:I;if(g>=0){let F=g+J,U=q.toString("latin1",F,F+36);P.set(U,M.length),M.push(W,R,x)}else X.push(W,R)}else X.push(W,R);W=R}let f=-1;for(let S=M.length-3;S>=0;S-=3){let R=q.indexOf(A,M[S]);if(R===-1||R>=M[S+1]){f=S;break}}if(f<0)return q;let G=new Set,Z=new Set,T=0,v=f;while(v!==void 0){if(G.has(v))break;G.add(v),Z.add(M[v]),T+=M[v+1]-M[v];let S=M[v+2];if(S<0)break;let R=q.toString("latin1",S,S+36);v=P.get(R)}if(D-T<D>>1)return q;let V=[],E=0;for(let S=0;S<M.length;S+=3){let R=M[S];while(E<X.length&&X[E]<R)V.push(q.subarray(X[E],X[E+1])),E+=2;if(Z.has(R))V.push(q.subarray(R,M[S+1]))}while(E<X.length)V.push(q.subarray(X[E],X[E+1])),E+=2;return Buffer.concat(V)}async function $a(q,K){let _=new Map,z=new Map,Y=new Map,$=new Map,A=new Map,O=new Map,w=new Map,j=new Map,H=new Map,J=new Map,M=new Map,X=new Map,P=new Map,W=new Map,D=new Map,f=new Map,G=[],Z;try{let R=null,x=null,I=!1;if(!i6(process.env.CLAUDE_CODE_DISABLE_PRECOMPACT_SKIP)){let{size:C}=await C97(q);if(C>D41){let g=await g$8(q,C);if(R=g.postBoundaryBuf,I=g.hasPreservedSegment,g.boundaryStartOffset>0)x=await iRY(q,g.boundaryStartOffset)}}if(R??=await dS6(q),!K?.keepAllLeaves&&!I&&!i6(process.env.CLAUDE_CODE_DISABLE_PRECOMPACT_SKIP)&&R.length>D41)R=oRY(R);if(x&&x.length>0){let C=LB(Buffer.from(x.join(` |
| 7685 | `)));for(let g of C)if(g.type==="summary"&&g.leafUuid)z.set(g.leafUuid,g.summary);else if(g.type==="custom-title"&&g.sessionId)Y.set(g.sessionId,g.customTitle);else if(g.type==="tag"&&g.sessionId)$.set(g.sessionId,g.tag);else if(g.type==="agent-name"&&g.sessionId)A.set(g.sessionId,g.agentName);else if(g.type==="agent-color"&&g.sessionId)O.set(g.sessionId,g.agentColor);else if(g.type==="agent-setting"&&g.sessionId)w.set(g.sessionId,g.agentSetting);else if(g.type==="mode"&&g.sessionId)M.set(g.sessionId,g.mode);else if(g.type==="worktree-state"&&g.sessionId)X.set(g.sessionId,g.worktreeSession);else if(g.type==="pr-link"&&g.sessionId)j.set(g.sessionId,g.prNumber),H.set(g.sessionId,g.prUrl),J.set(g.sessionId,g.prRepository)}let B=LB(R),p=new Map;for(let C of B){if(kRY(C)){let g=C.parentUuid;p.set(C.uuid,g&&p.has(g)?p.get(g)??null:g);continue}if(Oa(C)){if(C.parentUuid&&p.has(C.parentUuid))C.parentUuid=p.get(C.parentUuid)??null;if(_.set(C.uuid,C),bD(C))G.length=0,Z=void 0}else if(C.type==="summary"&&C.leafUuid)z.set(C.leafUuid,C.summary);else if(C.type==="custom-title"&&C.sessionId)Y.set(C.sessionId,C.customTitle);else if(C.type==="tag"&&C.sessionId)$.set(C.sessionId,C.tag);else if(C.type==="agent-name"&&C.sessionId)A.set(C.sessionId,C.agentName);else if(C.type==="agent-color"&&C.sessionId)O.set(C.sessionId,C.agentColor);else if(C.type==="agent-setting"&&C.sessionId)w.set(C.sessionId,C.agentSetting);else if(C.type==="mode"&&C.sessionId)M.set(C.sessionId,C.mode);else if(C.type==="worktree-state"&&C.sessionId)X.set(C.sessionId,C.worktreeSession);else if(C.type==="pr-link"&&C.sessionId)j.set(C.sessionId,C.prNumber),H.set(C.sessionId,C.prUrl),J.set(C.sessionId,C.prRepository);else if(C.type==="file-history-snapshot")P.set(C.messageId,C);else if(C.type==="attribution-snapshot")W.set(C.messageId,C);else if(C.type==="content-replacement")if(C.agentId){let g=f.get(C.agentId)??[];f.set(C.agentId,g),g.push(...C.replacements)}else{let g=D.get(C.sessionId)??[];D.set(C.sessionId,g),g.push(...C.replacements)}else if(C.type==="marble-origami-commit")G.push(C);else if(C.type==="marble-origami-snapshot")Z=C}}catch{}xRY(_),IRY(_);let T=[..._.values()],v=new Set(T.map((R)=>R.parentUuid).filter((R)=>R!==null)),V=T.filter((R)=>!v.has(R.uuid)),E=new Set,S=!1;if(g8("tengu_pebble_leaf_prune",!1)){let R=new Set;for(let x of T)if(x.parentUuid&&(x.type==="user"||x.type==="assistant"))R.add(x.parentUuid);for(let x of V){let I=new Set,B=x;while(B){if(I.has(B.uuid)){S=!0;break}if(I.add(B.uuid),B.type==="user"||B.type==="assistant"){if(!R.has(B.uuid))E.add(B.uuid);break}B=B.parentUuid?_.get(B.parentUuid):void 0}}}else for(let R of V){let x=new Set,I=R;while(I){if(x.has(I.uuid)){S=!0;break}if(x.add(I.uuid),I.type==="user"||I.type==="assistant"){E.add(I.uuid);break}I=I.parentUuid?_.get(I.parentUuid):void 0}}if(S)d("tengu_transcript_parent_cycle",{});return{messages:_,summaries:z,customTitles:Y,tags:$,agentNames:A,agentColors:O,agentSettings:w,prNumbers:j,prUrls:H,prRepositories:J,modes:M,worktreeStates:X,fileHistorySnapshots:P,attributionSnapshots:W,contentReplacements:D,agentContentReplacements:f,contextCollapseCommits:G,contextCollapseSnapshot:Z,leafUuids:E}}async function SBK(q){let K=HZ(Q36()??_2(r1()),`${q}.jsonl`);return $a(K)}function u87(){US6.cache.clear?.()}async function l97(q,K){return(await US6(q)).has(K)}async function f68(q){let{messages:K,summaries:_,customTitles:z,tags:Y,agentSettings:$,worktreeStates:A,fileHistorySnapshots:O,attributionSnapshots:w,contentReplacements:j,contextCollapseCommits:H,contextCollapseSnapshot:J}=await SBK(q);if(K.size===0)return null;if(!US6.cache.has(q))US6.cache.set(q,Promise.resolve(new Set(K.keys())));let M=JQ8(K.values(),(G)=>!G.isSidechain);if(!M)return null;let X=XK6(K,M),P=_.get(M.uuid),W=z.get(M.sessionId),D=Y.get(M.sessionId),f=$.get(q);return{...S97(X,0,P,W,MQ8(O,X),D,JT(q),XQ8(w,X),f,j.get(q)??[]),worktreeSession:A.get(q),contextCollapseCommits:H.filter((G)=>G.sessionId===q),contextCollapseSnapshot:J?.sessionId===q?J:void 0}}async function _L6(q){let K=await hBK(q),{logs:_}=await kJ6(K,0,K.length),z=hW6(_);return z.forEach((Y,$)=>{Y.value=$}),z}async function I57(q,K){if(K?.skipIndex)return aRY(q);return(await PQ8(q,K?.initialEnrichCount??DQ8)).logs}async function aRY(q){let K=Rp(),_;try{_=await QS6(K,{withFileTypes:!0})}catch{return[]}let z=_.filter((w)=>w.isDirectory()).map((w)=>HZ(K,w.name)),$=(await Promise.all(z.map((w)=>qhY(w,q)))).flat(),A=new Map;for(let w of $){let j=`${w.sessionId??""}:${w.leafUuid??""}`,H=A.get(j);if(!H||w.modified.getTime()>H.modified.getTime())A.set(j,w)}let O=hW6([...A.values()]);return O.forEach((w,j)=>{w.value=j}),O}async function PQ8(q,K=DQ8){let _=Rp(),z;try{z=await QS6(_,{withFileTypes:!0})}catch{return{logs:[],allStatLogs:[],nextIndex:0}}let Y=z.filter((j)=>j.isDirectory()).map((j)=>HZ(_,j.name)),$=[];for(let j of Y)$.push(...await pS6(j,q));let A=bBK($),{logs:O,nextIndex:w}=await kJ6(A,0,K);return O.forEach((j,H)=>{j.value=H}),{logs:O,allStatLogs:A,nextIndex:w}}async function YU8(q,K,_=DQ8){return(await mq8(q,K,_)).logs}async function mq8(q,K,_=DQ8){N(`/resume: loading sessions for cwd=${r1()}, worktrees=[${q.join(", ")}]`);let z=await CBK(q,K);N(`/resume: found ${z.length} session files on disk`);let{logs:Y,nextIndex:$}=await kJ6(z,0,_);return Y.forEach((A,O)=>{A.value=O}),{logs:Y,allStatLogs:z,nextIndex:$}}async function CBK(q,K){let _=Rp();if(q.length<=1){let w=r1(),j=_2(w);return pS6(j,void 0,w)}let z=process.platform==="win32",Y=q.map((w)=>{let j=JP(w);return{path:w,prefix:z?j.toLowerCase():j}});Y.sort((w,j)=>j.prefix.length-w.prefix.length);let $=[],A=new Set,O;try{O=await QS6(_,{withFileTypes:!0})}catch(w){N(`Failed to read projects dir ${_}, falling back to current project: ${w}`);let j=_2(r1());return pS6(j,K,r1())}for(let w of O){if(!w.isDirectory())continue;let j=z?w.name.toLowerCase():w.name;if(A.has(j))continue;for(let{path:H,prefix:J}of Y)if(j===J||j.startsWith(J+"-")){A.add(j),$.push(...await pS6(HZ(_,w.name),void 0,H));break}}return bBK($)}async function AK6(q){let K=c0(q);try{let{messages:_,agentContentReplacements:z}=await $a(K),Y=Array.from(_.values()).filter((j)=>j.agentId===q&&j.isSidechain);if(Y.length===0)return null;let $=new Set(Y.map((j)=>j.parentUuid)),A=JQ8(Y,(j)=>!$.has(j.uuid));if(!A)return null;return{messages:XK6(_,A).filter((j)=>j.agentId===q).map(({isSidechain:j,parentUuid:H,...J})=>J),contentReplacements:z.get(q)??[]}}catch{return null}}function n97(q){let K=[];for(let _ of q)if(_.type==="progress"&&_.data&&typeof _.data==="object"&&"type"in _.data&&(_.data.type==="agent_progress"||_.data.type==="skill_progress")&&"agentId"in _.data&&typeof _.data.agentId==="string")K.push(_.data.agentId);return cJ(K)}function Mq7(q){let K={};for(let _ of Object.values(q))if(_.type==="in_process_teammate"&&_.identity?.agentId&&_.messages&&_.messages.length>0)K[_.identity.agentId]=_.messages;return K}async function WQ8(q){let K=await Promise.all(q.map(async(z)=>{try{let Y=await AK6(pO(z));if(Y&&Y.messages.length>0)return{agentId:z,transcript:Y.messages};return null}catch{return null}})),_={};for(let z of K)if(z)_[z.agentId]=z.transcript;return _}async function Xq7(){let q=HZ(Q36()??_2(r1()),N8(),"subagents"),K;try{K=await QS6(q,{withFileTypes:!0})}catch{return{}}let _=K.filter((z)=>z.isFile()&&z.name.startsWith("agent-")&&z.name.endsWith(".jsonl")).map((z)=>z.name.slice(6,-6));return WQ8(_)}function pq8(q){if(q.type==="progress")return!1;if(q.type==="attachment"&&HQ8()!=="ant"){if(q.attachment.type==="hook_additional_context"&&i6(process.env.CLAUDE_CODE_SAVE_HOOK_ADDITIONAL_CONTEXT))return!0;return!1}return!0}function sRY(q){let K=new Set;for(let _ of q)if(_.type==="assistant"&&Array.isArray(_.message.content)){for(let z of _.message.content)if(z.type==="tool_use"&&z.name===FS)K.add(z.id)}return K}function tRY(q,K){return q.flatMap((_)=>{if(_.type==="assistant"&&Array.isArray(_.message.content)){let z=_.message.content,$=z.some((A)=>A.type==="tool_use"&&A.name===FS)?z.filter((A)=>!(A.type==="tool_use"&&A.name===FS)):z;if($.length===0)return[];if(_.isVirtual){let{isVirtual:A,...O}=_;return[{...O,message:{..._.message,content:$}}]}if($!==z)return[{..._,message:{..._.message,content:$}}];return[_]}if(_.type==="user"&&Array.isArray(_.message.content)){let z=_.message.content,$=z.some((A)=>A.type==="tool_result"&&K.has(A.tool_use_id))?z.filter((A)=>!(A.type==="tool_result"&&K.has(A.tool_use_id))):z;if($.length===0)return[];if(_.isVirtual){let{isVirtual:A,...O}=_;return[{...O,message:{..._.message,content:$}}]}if($!==z)return[{..._,message:{..._.message,content:$}}];return[_]}if("isVirtual"in _&&_.isVirtual){let{isVirtual:z,...Y}=_;return[Y]}return[_]})}function Bq8(q,K=q){let _=q.filter(pq8);return HQ8()!=="ant"?tRY(_,sRY(K)):_}async function eRY(q){return(await _L6())[q]||null}async function i97(q){try{let K=Y$(),{messages:_}=await $a(K),z=null;for(let Y of _.values())if(Y.type==="assistant"){let $=Y.message.content;if(Array.isArray($)){for(let A of $)if(A.type==="tool_use"&&A.id===q){z=Y;break}}}else if(Y.type==="user"){let $=Y.message.content;if(Array.isArray($)){for(let A of $)if(A.type==="tool_result"&&A.tool_use_id===q)return null}}return z}catch{return null}}async function Cq8(q){let K=new Map,_;try{_=await QS6(q,{withFileTypes:!0})}catch{return K}let z=[];for(let Y of _){if(!Y.isFile()||!Y.name.endsWith(".jsonl"))continue;let $=BL(GRY(Y.name,".jsonl"));if(!$)continue;z.push({sessionId:$,filePath:HZ(q,Y.name)})}return await Promise.all(z.map(async({sessionId:Y,filePath:$})=>{try{let A=await C97($);K.set(Y,{path:$,mtime:A.mtime.getTime(),ctime:A.birthtime.getTime(),size:A.size})}catch{N(`Failed to stat session file: ${$}`)}})),K}async function AQ8(q,K){let{messages:_,summaries:z,customTitles:Y,tags:$,agentNames:A,agentColors:O,agentSettings:w,prNumbers:j,prUrls:H,prRepositories:J,modes:M,fileHistorySnapshots:X,attributionSnapshots:P,contentReplacements:W,leafUuids:D}=await $a(q,{keepAllLeaves:!0});if(_.size===0)return[];let f=[],G=new Map;for(let T of _.values())if(D.has(T.uuid))f.push(T);else if(T.parentUuid){let v=G.get(T.parentUuid);if(v)v.push(T);else G.set(T.parentUuid,[T])}let Z=[];for(let T of f){let v=XK6(_,T);if(v.length===0)continue;let V=G.get(T.uuid);if(V)V.sort((R,x)=>R.timestamp<x.timestamp?-1:R.timestamp>x.timestamp?1:0),v.push(...V);let E=v[0],S=T.sessionId;Z.push({date:T.timestamp,messages:KL6(v),fullPath:q,value:0,created:new Date(E.timestamp),modified:new Date(T.timestamp),firstPrompt:F97(v),messageCount:U97(v),isSidechain:E.isSidechain??!1,sessionId:S,leafUuid:T.uuid,summary:z.get(T.uuid),customTitle:Y.get(S),tag:$.get(S),agentName:A.get(S),agentColor:O.get(S),agentSetting:w.get(S),mode:M.get(S),prNumber:j.get(S),prUrl:H.get(S),prRepository:J.get(S),gitBranch:T.gitBranch,projectPath:K??E.cwd,fileHistorySnapshots:MQ8(X,v),attributionSnapshots:XQ8(P,v),contentReplacements:W.get(S)??[]})}return Z}async function qhY(q,K){let _=await Cq8(q);if(_.size===0)return[];let z;if(K&&_.size>K)z=[..._.values()].sort(($,A)=>A.mtime-$.mtime).slice(0,K);else z=[..._.values()];let Y=[];for(let $ of z)try{let A=await AQ8($.path);Y.push(...A)}catch{N(`Failed to load session file: ${$.path}`)}return Y}async function KhY(q,K,_){let{head:z,tail:Y}=await HR7(q,K,_);if(!z)return{firstPrompt:"",isSidechain:!1};let $=z.includes('"isSidechain":true')||z.includes('"isSidechain": true'),A=UW6(z,"cwd"),O=UW6(z,"teamName"),w=UW6(z,"agentSetting"),j=UT(Y,"lastPrompt")||_hY(z)||VBK(z,"content",200)||VBK(z,"text",200)||"",H=UT(Y,"customTitle")??UT(z,"customTitle")??UT(Y,"aiTitle")??UT(z,"aiTitle"),J=UT(Y,"summary"),M=UT(Y,"tag"),X=UT(Y,"gitBranch")??UW6(z,"gitBranch"),P=UT(Y,"prUrl"),W=UT(Y,"prRepository"),D,f=UT(Y,"prNumber");if(f)D=parseInt(f,10)||void 0;if(!D){let G=Y.lastIndexOf('"prNumber":');if(G>=0){let Z=Y.slice(G+11,G+25),T=parseInt(Z.trim(),10);if(T>0)D=T}}return{firstPrompt:j,gitBranch:X,isSidechain:$,projectPath:A,teamName:O,customTitle:H,summary:J,tag:M,agentSetting:w,prNumber:D,prUrl:P,prRepository:W}}function _hY(q){let K=0,_=!1,z="";while(K<q.length){let Y=q.indexOf(` |
| 7686 | `,K),$=Y>=0?q.slice(K,Y):q.slice(K);if(K=Y>=0?Y+1:q.length,!$.includes('"type":"user"')&&!$.includes('"type": "user"'))continue;if($.includes('"tool_result"'))continue;if($.includes('"isMeta":true')||$.includes('"isMeta": true'))continue;try{let A=r8($);if(A.type!=="user")continue;let O=A.message;if(!O)continue;let w=O.content,j=[];if(typeof w==="string")j.push(w);else if(Array.isArray(w))for(let H of w){let J=H;if(J.type==="text"&&typeof J.text==="string")j.push(J.text)}for(let H of j){if(!H)continue;let J=H.replace(/\n/g," ").trim(),M=o4(J,CZ);if(M){let P=M.replace(/^\//,""),W=o4(J,"command-args")?.trim()||"";if(RQ().has(P)||!W){if(!z)z=M;continue}return W?`${M} ${W}`:M}let X=o4(J,"bash-input");if(X)return`! ${X}`;if(NBK.test(J))continue;if(J.length>200)J=J.slice(0,200).trim()+"…";return J}}catch{continue}}if(z)return z;return""}function VBK(q,K,_){let z=[`"${K}":"`,`"${K}": "`];for(let Y of z){let $=q.indexOf(Y);if($<0)continue;let A=$+Y.length,O=A,w=0;while(O<q.length&&w<_){if(q[O]==="\\"){O+=2,w++;continue}if(q[O]==='"')break;O++,w++}return q.slice(A,O).replace(/\\n/g," ").replace(/\\t/g," ").trim()}return""}function bBK(q){let K=new Map;for(let _ of q){if(!_.sessionId)continue;let z=K.get(_.sessionId);if(!z||_.modified.getTime()>z.modified.getTime())K.set(_.sessionId,_)}return hW6([...K.values()]).map((_,z)=>({..._,value:z}))}async function pS6(q,K,_){let Y=[...(await Cq8(q)).entries()].sort((O,w)=>w[1].mtime-O[1].mtime);if(K&&Y.length>K)Y=Y.slice(0,K);let $=[];for(let[O,w]of Y)$.push({date:new Date(w.mtime).toISOString(),messages:[],isLite:!0,fullPath:w.path,value:0,created:new Date(w.ctime),modified:new Date(w.mtime),firstPrompt:"",messageCount:0,fileSize:w.size,isSidechain:!1,sessionId:O,projectPath:_});let A=hW6($);return A.forEach((O,w)=>{O.value=w}),A}async function zhY(q,K){if(!q.isLite||!q.fullPath)return q;let _=await KhY(q.fullPath,q.fileSize??0,K),z={...q,isLite:!1,firstPrompt:_.firstPrompt,gitBranch:_.gitBranch,isSidechain:_.isSidechain,teamName:_.teamName,customTitle:_.customTitle,summary:_.summary,tag:_.tag,agentSetting:_.agentSetting,prNumber:_.prNumber,prUrl:_.prUrl,prRepository:_.prRepository,projectPath:_.projectPath??q.projectPath};if(!z.firstPrompt&&!z.customTitle)z.firstPrompt="(session)";if(z.isSidechain)return N(`Session ${q.sessionId} filtered from /resume: isSidechain=true`),null;if(z.teamName)return N(`Session ${q.sessionId} filtered from /resume: teamName=${z.teamName}`),null;return z}async function kJ6(q,K,_){let z=[],Y=Buffer.alloc(ue),$=K;while($<q.length&&z.length<_){let w=q[$];$++;let j=await zhY(w,Y);if(j)z.push(j)}let A=$-K,O=A-z.length;if(O>0)N(`/resume: enriched ${A} sessions, ${O} filtered out, ${z.length} visible (${q.length-$} remaining on disk)`);return{logs:z,nextIndex:$}}var TRY,vRY=52428800,NBK,VRY,$78=52428800,x97,_2,TJ6=null,vBK=!1,kBK=10,cRY,jQ8,lRY=25,US6,DQ8=50;var _K=y(()=>{F4();k8();v8();yA();RY();o1();Ax8();k16();M0();c9();lQ();I7();_8();oY();m8();y8();U7();e7();a78();E5();RA();vO();E8();i1();dz();QW6();U1();l8();jm();TRY={ISSUES_EXPLAINER:"report the issue at https://github.com/anthropics/claude-code/issues",PACKAGE_URL:"@anthropic-ai/claude-code",README_URL:"https://code.claude.com/docs/en/overview",VERSION:"2.1.88",FEEDBACK_CHANNEL:"https://github.com/anthropics/claude-code/issues",BUILD_TIME:"2026-03-30T21:59:52Z"}.VERSION,NBK=/^(?:\s*<[a-z][\w-]*[\s>]|\[Request interrupted by user[^\]]*\])/;VRY=new Set(["bash_progress","powershell_progress","mcp_progress",...[]]);x97=new Map;_2=_1((q)=>{return HZ(Rp(),JP(q))});cRY=['"type":"summary"','"type":"custom-title"','"type":"tag"','"type":"agent-name"','"type":"agent-color"','"type":"agent-setting"','"type":"mode"','"type":"worktree-state"','"type":"pr-link"'],jQ8=cRY.map((q)=>Buffer.from(q));US6=_1(async(q)=>{let{messages:K}=await SBK(q);return new Set(K.keys())},(q)=>q)});var xBK={};T8(xBK,{buildCombinedMemoryPrompt:()=>YhY});function YhY(q,K=!1){let _=Vj(),z=wu(),Y=K?["## How to save memories","","Write each memory to its own file in the chosen directory (private or team, per the type's scope guidance) using this frontmatter format:","",...jp,"","- Keep the name, description, and type fields in memory files up-to-date with the content","- Organize memory semantically by topic, not chronologically","- Update or remove memories that turn out to be wrong or outdated","- Do not write duplicate memories. First check if there is an existing memory you can update before writing a new one."]:["## How to save memories","","Saving a memory is a two-step process:","","**Step 1** — write the memory to its own file in the chosen directory (private or team, per the type's scope guidance) using this frontmatter format:","",...jp,"",`**Step 2** — add a pointer to that file in the same directory's \`${oP}\`. Each directory (private and team) has its own \`${oP}\` index — each entry should be one line, under ~150 characters: \`- [Title](file.md) — one-line hook\`. They have no frontmatter. Never write memory content directly into a \`${oP}\`.`,"",`- Both \`${oP}\` indexes are loaded into your conversation context — lines after ${nK6} will be truncated, so keep them concise`,"- Keep the name, description, and type fields in memory files up-to-date with the content","- Organize memory semantically by topic, not chronologically","- Update or remove memories that turn out to be wrong or outdated","- Do not write duplicate memories. First check if there is an existing memory you can update before writing a new one."];return["# Memory","",`You have a persistent, file-based memory system with two directories: a private directory at \`${_}\` and a shared team directory at \`${z}\`. ${uBK}`,"","You should build up this memory system over time so that future conversations can have a complete picture of who the user is, how they'd like to collaborate with you, what behaviors to avoid or repeat, and the context behind the work the user gives you.","","If the user explicitly asks you to remember something, save it immediately as whichever type fits best. If they ask you to forget something, find and remove the relevant entry.","","## Memory scope","","There are two scope levels:","",`- private: memories that are private between you and the current user. They persist across conversations with only this specific user and are stored at the root \`${_}\`.`,`- team: memories that are shared with and contributed by all of the users who work within this project directory. Team memories are synced at the beginning of every session and they are stored at \`${z}\`.`,"",...Hp8,...XH6,"- You MUST avoid saving sensitive data within shared team memories. For example, never save API keys or user credentials.","",...Y,"","## When to access memories","- When memories (personal or team) seem relevant, or the user references prior work with them or others in their organization.","- You MUST access memory when the user explicitly asks you to check, recall, or remember.","- If the user says to *ignore* or *not use* memory: proceed as if MEMORY.md were empty. Do not apply remembered facts, cite, compare against, or mention memory content.",X87,"",...Mp8,"","## Memory and other forms of persistence","Memory is one of several persistence mechanisms available to you as you assist the user in a given conversation. The distinction is often that memory can be recalled in future conversations and should not be used for persisting information that is only useful within the scope of the current conversation.","- When to use or update a plan instead of memory: If you are about to start a non-trivial implementation task and would like to reach alignment with the user on your approach you should use a Plan rather than saving this information to memory. Similarly, if you already have a plan within the conversation and you have changed your approach persist that change by updating the plan rather than saving a memory.","- When to use or update tasks instead of memory: When you need to break your work in current conversation into discrete steps or keep track of your progress use tasks instead of saving to memory. Tasks are great for persisting information about the work that needs to be done in the current conversation, but memory should be reserved for information that will be useful in future conversations.",...q??[],"",...r97(_)].join(` |
| 7687 | `)}var IBK=y(()=>{n76();j18();rw();YL()});function HI1(q){let K=q.trim(),_=K.split(` |
| 7688 | `),z=_.length,Y=K.length,$=z>nK6,A=Y>gq8;if(!$&&!A)return{content:K,lineCount:z,byteCount:Y,wasLineTruncated:$,wasByteTruncated:A};let O=$?_.slice(0,nK6).join(` |
| 7689 | `):K;if(O.length>gq8){let j=O.lastIndexOf(` |
| 7690 | `,gq8);O=O.slice(0,j>0?j:gq8)}let w=A&&!$?`${m4(Y)} (limit: ${m4(gq8)}) — index entries are too long`:$&&!A?`${z} lines (limit: ${nK6})`:`${z} lines and ${m4(Y)}`;return{content:O+` |
| 7691 | |
| 7692 | > WARNING: ${oP} is ${w}. Only part of it was loaded. Keep index entries to one line under ~200 chars; move detail into topic files.`,lineCount:z,byteCount:Y,wasLineTruncated:$,wasByteTruncated:A}}async function ZQ8(q){let K=X8();try{await K.mkdir(q)}catch(_){let z=_ instanceof Error&&"code"in _&&typeof _.code==="string"?_.code:void 0;N(`ensureMemoryDirExists failed for ${q}: ${z??String(_)}`,{level:"debug"})}}function fQ8(q,K){X8().readdir(q).then((z)=>{let Y=0,$=0;for(let A of z)if(A.isFile())Y++;else if(A.isDirectory())$++;d("tengu_memdir_loaded",{...K,total_file_count:Y,total_subdir_count:$})},()=>{d("tengu_memdir_loaded",K)})}function pBK(q,K,_,z=!1){let Y=z?["## How to save memories","","Write each memory to its own file (e.g., `user_role.md`, `feedback_testing.md`) using this frontmatter format:","",...jp,"","- Keep the name, description, and type fields in memory files up-to-date with the content","- Organize memory semantically by topic, not chronologically","- Update or remove memories that turn out to be wrong or outdated","- Do not write duplicate memories. First check if there is an existing memory you can update before writing a new one."]:["## How to save memories","","Saving a memory is a two-step process:","","**Step 1** — write the memory to its own file (e.g., `user_role.md`, `feedback_testing.md`) using this frontmatter format:","",...jp,"",`**Step 2** — add a pointer to that file in \`${oP}\`. \`${oP}\` is an index, not a memory — each entry should be one line, under ~150 characters: \`- [Title](file.md) — one-line hook\`. It has no frontmatter. Never write memory content directly into \`${oP}\`.`,"",`- \`${oP}\` is always loaded into your conversation context — lines after ${nK6} will be truncated, so keep the index concise`,"- Keep the name, description, and type fields in memory files up-to-date with the content","- Organize memory semantically by topic, not chronologically","- Update or remove memories that turn out to be wrong or outdated","- Do not write duplicate memories. First check if there is an existing memory you can update before writing a new one."],$=[`# ${q}`,"",`You have a persistent, file-based memory system at \`${K}\`. ${D87}`,"","You should build up this memory system over time so that future conversations can have a complete picture of who the user is, how they'd like to collaborate with you, what behaviors to avoid or repeat, and the context behind the work the user gives you.","","If the user explicitly asks you to remember something, save it immediately as whichever type fits best. If they ask you to forget something, find and remove the relevant entry.","",...Jp8,...XH6,"",...Y,"",...$WK,"",...Mp8,"","## Memory and other forms of persistence","Memory is one of several persistence mechanisms available to you as you assist the user in a given conversation. The distinction is often that memory can be recalled in future conversations and should not be used for persisting information that is only useful within the scope of the current conversation.","- When to use or update a plan instead of memory: If you are about to start a non-trivial implementation task and would like to reach alignment with the user on your approach you should use a Plan rather than saving this information to memory. Similarly, if you already have a plan within the conversation and you have changed your approach persist that change by updating the plan rather than saving a memory.","- When to use or update tasks instead of memory: When you need to break your work in current conversation into discrete steps or keep track of your progress use tasks instead of saving to memory. Tasks are great for persisting information about the work that needs to be done in the current conversation, but memory should be reserved for information that will be useful in future conversations.","",..._??[],""];return $.push(...r97(K)),$}function BBK(q){let{displayName:K,memoryDir:_,extraGuidelines:z}=q,Y=X8(),$=_+oP,A="";try{A=Y.readFileSync($,{encoding:"utf-8"})}catch{}let O=pBK(K,_,z);if(A.trim()){let w=HI1(A),j=K===$hY?"auto":"agent";fQ8(_,{content_length:w.byteCount,line_count:w.lineCount,was_truncated:w.wasLineTruncated,was_byte_truncated:w.wasByteTruncated,memory_type:j}),O.push(`## ${oP}`,"",w.content)}else O.push(`## ${oP}`,"",`Your ${oP} is currently empty. When you save new memories, they will appear here.`);return O.join(` |
| 7693 | `)}function r97(q){if(!g8("tengu_coral_fern",!1))return[];let K=_2(r1()),_=Nj()||i$6(),z=_?`grep -rn "<search term>" ${q} --include="*.md"`:`${n3} with pattern="<search term>" path="${q}" glob="*.md"`,Y=_?`grep -rn "<search term>" ${K}/ --include="*.jsonl"`:`${n3} with pattern="<search term>" path="${K}/" glob="*.jsonl"`;return["## Searching past context","","When looking for past context:","1. Search topic files in your memory directory:","```",z,"```","2. Session transcript logs (last resort — large files, slow):","```",Y,"```","Use narrow search terms (error messages, file paths, function names) rather than broad keywords.",""]}async function GQ8(){let q=l3(),K=g8("tengu_moth_copse",!1),_=process.env.CLAUDE_COWORK_MEMORY_EXTRA_GUIDELINES,z=_&&_.trim().length>0?[_]:void 0;if(mBK.isTeamMemoryEnabled()){let Y=Vj(),$=mBK.getTeamMemPath();return await ZQ8($),fQ8(Y,{memory_type:"auto"}),fQ8($,{memory_type:"team"}),AhY.buildCombinedMemoryPrompt(z,K)}if(q){let Y=Vj();return await ZQ8(Y),fQ8(Y,{memory_type:"auto"}),pBK("auto memory",Y,z,K).join(` |
| 7694 | `)}if(d("tengu_memdir_disabled",{disabled_by_env_var:i6(process.env.CLAUDE_CODE_DISABLE_AUTO_MEMORY),disabled_by_setting:!i6(process.env.CLAUDE_CODE_DISABLE_AUTO_MEMORY)&&N7().autoMemoryEnabled===!1}),g8("tengu_herring_clock",!1))d("tengu_team_memdir_disabled",{});return null}var mBK,oP="MEMORY.md",nK6=200,gq8=25000,$hY="auto memory",AhY,D87="This directory already exists — write to it directly with the Write tool (do not run mkdir or check for its existence).",uBK="Both directories already exist — write to them directly with the Write tool (do not run mkdir or check for their existence).";var n76=y(()=>{e7();rw();v8();o1();k8();qM();k16();_8();ju();m8();U7();_K();U1();j18();mBK=(YL(),Eq(Pi));AhY=(IBK(),Eq(xBK))});import{join as ys,normalize as OhY,sep as Rd}from"path";function whY(q){return q.replace(/:/g,"-")}function gBK(q){if(process.env.CLAUDE_CODE_REMOTE_MEMORY_DIR)return ys(process.env.CLAUDE_CODE_REMOTE_MEMORY_DIR,"projects",JP(jH(Fz())??Fz()),"agent-memory-local",q)+Rd;return ys(Z8(),".claude","agent-memory-local",q)+Rd}function Nk6(q,K){let _=whY(q);switch(K){case"project":return ys(Z8(),".claude","agent-memory",_)+Rd;case"local":return gBK(_);case"user":return ys(D16(),"agent-memory",_)+Rd}}function i88(q){let K=OhY(q),_=D16();if(K.startsWith(ys(_,"agent-memory")+Rd))return!0;if(K.startsWith(ys(Z8(),".claude","agent-memory")+Rd))return!0;if(process.env.CLAUDE_CODE_REMOTE_MEMORY_DIR){if(K.includes(Rd+"agent-memory-local"+Rd)&&K.startsWith(ys(process.env.CLAUDE_CODE_REMOTE_MEMORY_DIR,"projects")+Rd))return!0}else if(K.startsWith(ys(Z8(),".claude","agent-memory-local")+Rd))return!0;return!1}function IU8(q){switch(q){case"user":return`User (${ys(D16(),"agent-memory")}/)`;case"project":return"Project (.claude/agent-memory/)";case"local":return`Local (${gBK("...")})`;default:return"None"}}function kO6(q,K){let _;switch(K){case"user":_="- Since this memory is user-scope, keep learnings general since they apply across all projects";break;case"project":_="- Since this memory is project-scope and shared with your team via version control, tailor your memories to this project";break;case"local":_="- Since this memory is local-scope (not checked into version control), tailor your memories to this project and machine";break}let z=Nk6(q,K);ZQ8(z);let Y=process.env.CLAUDE_COWORK_MEMORY_EXTRA_GUIDELINES;return BBK({displayName:"Persistent Agent Memory",memoryDir:z,extraGuidelines:Y&&Y.trim().length>0?[_,Y]:[_]})}var pu=y(()=>{v8();n76();rw();I7();E5();dz()});import{randomBytes as jhY}from"crypto";import{homedir as UBK,tmpdir as HhY}from"os";import{join as Wk,normalize as cS6,posix as l56,sep as JZ}from"path";function oD(q){return q.toLowerCase()}function XhY(q){let K=lq(q),_=oD(K),z=[{dir:lq(Wk(r1(),".claude","skills")),prefix:"/.claude/skills/"},{dir:lq(Wk(UBK(),".claude","skills")),prefix:"~/.claude/skills/"}];for(let{dir:Y,prefix:$}of z){let A=oD(Y);for(let O of[JZ,"/"])if(_.startsWith(A+O.toLowerCase())){let w=K.slice(Y.length+O.length),j=w.indexOf("/"),H=JZ==="\\"?w.indexOf("\\"):-1,J=j===-1?H:H===-1?j:Math.min(j,H);if(J<=0)return null;let M=w.slice(0,J);if(!M||M==="."||M.includes(".."))return null;if(/[*?[\]]/.test(M))return null;return{skillName:M,pattern:$+M+"/**"}}}return null}function s97(q,K){if(Z1()==="windows"){let _=ff(q),z=ff(K);return l56.relative(_,z)}return l56.relative(q,K)}function MN4(q){if(Z1()==="windows")return ff(q);return q}function PhY(){return cT.map((q)=>Hj(q)).filter((q)=>q!==void 0)}function Hs1(q){let K=lq(q),_=oD(K);if(_.endsWith(`${JZ}.claude${JZ}settings.json`)||_.endsWith(`${JZ}.claude${JZ}settings.local.json`))return!0;return PhY().some((z)=>oD(z)===_)}function WhY(q){if(Hs1(q))return!0;let K=Wk(r1(),".claude","commands"),_=Wk(r1(),".claude","agents"),z=Wk(r1(),".claude","skills");return cV(q,K)||cV(q,_)||cV(q,z)}function QBK(q){let K=Wk(hA(),CQ()),_=cS6(q);return _.startsWith(K)&&_.endsWith(".md")}function TQ8(){return Wk(_2(Z8()),N8(),"session-memory")+JZ}function Fk6(){return Wk(TQ8(),"summary.md")}function DhY(q){return cS6(q).startsWith(TQ8())}function fhY(q){let K=_2(Z8()),_=cS6(q);return _===K||_.startsWith(K+JZ)}function Sd(){return tY("tengu_scratch")}function Na1(){if(Z1()==="windows")return"claude";return`claude-${process.getuid?.()??0}`}function vQ8(){return Wk(AC(),JP(r1()))+JZ}function n56(){return Wk(vQ8(),N8(),"scratchpad")}async function dBK(){if(!Sd())throw Error("Scratchpad directory feature is not enabled");let q=X8(),K=n56();return await q.mkdir(K,{mode:448}),K}function cBK(q){if(!Sd())return!1;let K=n56(),_=cS6(q);return _===K||_.startsWith(K+JZ)}function ZhY(q){let _=lq(q).split(JZ),z=_.at(-1);if(q.startsWith("\\\\")||q.startsWith("//"))return!0;for(let Y=0;Y<_.length;Y++){let $=_[Y],A=oD($);for(let O of MhY){if(A!==oD(O))continue;if(O===".claude"){let w=_[Y+1];if(w&&oD(w)==="worktrees")break}return!0}}if(z){let Y=oD(z);if(JhY.some(($)=>oD($)===Y))return!0}return!1}function lBK(q){if(Z1()==="windows"||Z1()==="wsl"){if(q.indexOf(":",2)!==-1)return!0}if(/~\d/.test(q))return!0;if(q.startsWith("\\\\?\\")||q.startsWith("\\\\.\\")||q.startsWith("//?/")||q.startsWith("//./"))return!0;if(/[.\s]+$/.test(q))return!0;if(/\.(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$/i.test(q))return!0;if(/(^|\/|\\)\.{3,}(\/|\\|$)/.test(q))return!0;if(SF(q))return!0;return!1}function In6(q,K){let _=K??hx(q);for(let z of _)if(lBK(z))return{safe:!1,message:`Claude requested permissions to write to ${q}, which contains a suspicious Windows path pattern that requires manual approval.`,classifierApprovable:!1};for(let z of _)if(WhY(z))return{safe:!1,message:`Claude requested permissions to write to ${q}, but you haven't granted it yet.`,classifierApprovable:!0};for(let z of _)if(ZhY(z))return{safe:!1,message:`Claude requested permissions to edit ${q} which is a sensitive file.`,classifierApprovable:!0};return{safe:!0}}function ku(q){return new Set([r1(),...q.additionalWorkingDirectories.keys()])}function XL(q,K,_){let z=_??hx(q),Y=Array.from(ku(K)).flatMap(($)=>GhY($));return z.every(($)=>Y.some((A)=>cV($,A)))}function cV(q,K){let _=lq(q),z=lq(K),Y=_.replace(/^\/private\/var\//,"/var/").replace(/^\/private\/tmp(\/|$)/,"/tmp$1"),$=z.replace(/^\/private\/var\//,"/var/").replace(/^\/private\/tmp(\/|$)/,"/tmp$1"),A=oD(Y),O=oD($),w=s97(O,A);if(w==="")return!0;if(yB(w))return!1;return!l56.isAbsolute(w)}function ThY(q){switch(q){case"cliArg":case"command":case"session":return lq(r1());case"userSettings":case"policySettings":case"projectSettings":case"localSettings":case"flagSettings":return V_6(q)}}function a97(q){return l56.join(hd,q)}function vhY({patternRoot:q,pattern:K,rootPath:_}){let z=l56.join(q,K);if(q===_)return a97(K);else if(z.startsWith(`${_}${hd}`)){let Y=z.slice(_.length);return a97(Y)}else{let Y=l56.relative(_,q);if(!Y||Y.startsWith(`..${hd}`)||Y==="..")return null;else{let $=l56.join(Y,K);return a97($)}}}function oL6(q,K){let _=new Set(q.get(null)??[]);for(let[z,Y]of q.entries()){if(z===null)continue;for(let $ of Y){let A=vhY({patternRoot:z,pattern:$,rootPath:K});if(A)_.add(A)}}return Array.from(_)}function aL6(q){let K=nBK(q,"read","deny"),_=new Map;for(let[z,Y]of K.entries())_.set(z,Array.from(Y.keys()));return _}function khY(q,K){if(q.startsWith(`${hd}${hd}`)){let z=q.slice(1);if(Z1()==="windows"&&z.match(/^\/[a-z]\//i)){let Y=z[1]?.toUpperCase()??"C",$=z.slice(2),A=`${Y}:\\`;return{relativePattern:$.startsWith("/")?$.slice(1):$,root:A}}return{relativePattern:z,root:hd}}else if(q.startsWith(`~${hd}`))return{relativePattern:q.slice(1),root:UBK().normalize("NFC")};else if(q.startsWith(hd))return{relativePattern:q,root:ThY(K)};let _=q;if(q.startsWith(`.${hd}`))_=q.slice(2);return{relativePattern:_,root:null}}function nBK(q,K,_){let z=(()=>{switch(K){case"edit":return X4;case"read":return Cq}})(),Y=uj6(q,z,_),$=new Map;for(let[A,O]of Y.entries()){let{relativePattern:w,root:j}=khY(A,O.source),H=$.get(j);if(H===void 0)H=new Map,$.set(j,H);H.set(w,O)}return $}function VH(q,K,_,z){let Y=lq(q);if(Z1()==="windows"&&Y.includes("\\"))Y=ff(Y);let $=nBK(K,_,z);for(let[A,O]of $.entries()){let w=Array.from(O.keys()).map((M)=>{let X=M;if(X.endsWith("/**"))X=X.slice(0,-3);return X}),j=FBK.default().add(w),H=s97(A??Z8(),Y??Z8());if(H.startsWith(`..${hd}`))continue;if(!H)continue;let J=j.test(H);if(J.ignored&&J.rule){let M=J.rule.pattern,X=M+"/**";if(O.has(X))return O.get(X)??null;return O.get(M)??null}}return null}function RK6(q,K,_){if(typeof q.getPath!=="function")return{behavior:"ask",message:`Claude requested permissions to use ${q.name}, but you haven't granted it yet.`};let z=q.getPath(K),Y=hx(z);for(let H of Y)if(H.startsWith("\\\\")||H.startsWith("//"))return{behavior:"ask",message:`Claude requested permissions to read from ${z}, which appears to be a UNC path that could access network resources.`,decisionReason:{type:"other",reason:"UNC path detected (defense-in-depth check)"}};for(let H of Y)if(lBK(H))return{behavior:"ask",message:`Claude requested permissions to read from ${z}, which contains a suspicious Windows path pattern that requires manual approval.`,decisionReason:{type:"other",reason:"Path contains suspicious Windows-specific patterns (alternate data streams, short names, long path prefixes, or three or more consecutive dots) that require manual verification"}};for(let H of Y){let J=VH(H,_,"read","deny");if(J)return{behavior:"deny",message:`Permission to read ${z} has been denied.`,decisionReason:{type:"rule",rule:J}}}for(let H of Y){let J=VH(H,_,"read","ask");if(J)return{behavior:"ask",message:`Claude requested permissions to read from ${z}, but you haven't granted it yet.`,decisionReason:{type:"rule",rule:J}}}let $=Qj6(q,K,_,Y);if($.behavior==="allow")return $;if(XL(z,_,Y))return{behavior:"allow",updatedInput:K,decisionReason:{type:"mode",mode:"default"}};let O=lq(z),w=mn6(O,K);if(w.behavior!=="passthrough")return w;let j=VH(z,_,"read","allow");if(j)return{behavior:"allow",updatedInput:K,decisionReason:{type:"rule",rule:j}};return{behavior:"ask",message:`Claude requested permissions to read from ${z}, but you haven't granted it yet.`,suggestions:Fq8(z,"read",_,Y),decisionReason:{type:"workingDir",reason:"Path is outside allowed working directories"}}}function Qj6(q,K,_,z){if(typeof q.getPath!=="function")return{behavior:"ask",message:`Claude requested permissions to use ${q.name}, but you haven't granted it yet.`};let Y=q.getPath(K),$=z??hx(Y);for(let M of $){let X=VH(M,_,"edit","deny");if(X)return{behavior:"deny",message:`Permission to edit ${Y} has been denied.`,decisionReason:{type:"rule",rule:X}}}let A=lq(Y),O=un6(A,K);if(O.behavior!=="passthrough")return O;let w=VH(Y,{..._,alwaysAllowRules:{session:_.alwaysAllowRules.session??[]}},"edit","allow");if(w){let M=w.ruleValue.ruleContent;if(M&&(M.startsWith(Uf8.slice(0,-2))||M.startsWith(Qf8.slice(0,-2)))&&!M.includes("..")&&M.endsWith("/**"))return{behavior:"allow",updatedInput:K,decisionReason:{type:"rule",rule:w}}}let j=In6(Y,$);if(!j.safe){let M=XhY(Y),X=M?[{type:"addRules",rules:[{toolName:X4,ruleContent:M.pattern}],behavior:"allow",destination:"session"}]:Fq8(Y,"write",_,$);return{behavior:"ask",message:j.message,suggestions:X,decisionReason:{type:"safetyCheck",reason:j.message,classifierApprovable:j.classifierApprovable}}}for(let M of $){let X=VH(M,_,"edit","ask");if(X)return{behavior:"ask",message:`Claude requested permissions to write to ${Y}, but you haven't granted it yet.`,decisionReason:{type:"rule",rule:X}}}let H=XL(Y,_,$);if(_.mode==="acceptEdits"&&H)return{behavior:"allow",updatedInput:K,decisionReason:{type:"mode",mode:_.mode}};let J=VH(Y,_,"edit","allow");if(J)return{behavior:"allow",updatedInput:K,decisionReason:{type:"rule",rule:J}};return{behavior:"ask",message:`Claude requested permissions to write to ${Y}, but you haven't granted it yet.`,suggestions:Fq8(Y,"write",_,$),decisionReason:!H?{type:"workingDir",reason:"Path is outside allowed working directories"}:void 0}}function Fq8(q,K,_,z){let Y=!XL(q,_,z);if(K==="read"&&Y){let A=IZ(q);return hx(A).map((j)=>Kw6(j,"session")).filter((j)=>j!==void 0)}let $=_.mode==="default"||_.mode==="plan";if(K==="write"||K==="create"){let A=$?[{type:"setMode",mode:"acceptEdits",destination:"session"}]:[];if(Y){let O=IZ(q),w=hx(O);A.push({type:"addDirectories",directories:w,destination:"session"})}return A}return $?[{type:"setMode",mode:"acceptEdits",destination:"session"}]:[]}function un6(q,K){let _=cS6(q);if(QBK(_))return{behavior:"allow",updatedInput:K,decisionReason:{type:"other",reason:"Plan files for current session are allowed for writing"}};if(cBK(_))return{behavior:"allow",updatedInput:K,decisionReason:{type:"other",reason:"Scratchpad files for current session are allowed for writing"}};if(i88(_))return{behavior:"allow",updatedInput:K,decisionReason:{type:"other",reason:"Agent memory files are allowed for writing"}};if(!Gf8()&&f16(_))return{behavior:"allow",updatedInput:K,decisionReason:{type:"other",reason:"auto memory files are allowed for writing"}};if(oD(_)===oD(Wk(r1(),".claude","launch.json")))return{behavior:"allow",updatedInput:K,decisionReason:{type:"other",reason:"Preview launch config is allowed for writing"}};return{behavior:"passthrough",message:""}}function mn6(q,K){let _=cS6(q);if(DhY(_))return{behavior:"allow",updatedInput:K,decisionReason:{type:"other",reason:"Session memory files are allowed for reading"}};if(fhY(_))return{behavior:"allow",updatedInput:K,decisionReason:{type:"other",reason:"Project directory files are allowed for reading"}};if(QBK(_))return{behavior:"allow",updatedInput:K,decisionReason:{type:"other",reason:"Plan files for current session are allowed for reading"}};let z=Bq6(),Y=z.endsWith(JZ)?z:z+JZ;if(_===z||_.startsWith(Y))return{behavior:"allow",updatedInput:K,decisionReason:{type:"other",reason:"Tool result files are allowed for reading"}};if(cBK(_))return{behavior:"allow",updatedInput:K,decisionReason:{type:"other",reason:"Scratchpad files for current session are allowed for reading"}};let $=vQ8();if(_.startsWith($))return{behavior:"allow",updatedInput:K,decisionReason:{type:"other",reason:"Project temp directory files are allowed for reading"}};if(i88(_))return{behavior:"allow",updatedInput:K,decisionReason:{type:"other",reason:"Agent memory files are allowed for reading"}};if(f16(_))return{behavior:"allow",updatedInput:K,decisionReason:{type:"other",reason:"auto memory files are allowed for reading"}};let A=Wk(c1(),"tasks")+JZ;if(_===A.slice(0,-1)||_.startsWith(A))return{behavior:"allow",updatedInput:K,decisionReason:{type:"other",reason:"Task files are allowed for reading"}};let O=Wk(c1(),"teams")+JZ;if(_===O.slice(0,-1)||_.startsWith(O))return{behavior:"allow",updatedInput:K,decisionReason:{type:"other",reason:"Team files are allowed for reading"}};let w=o37()+JZ;if(_.startsWith(w))return{behavior:"allow",updatedInput:K,decisionReason:{type:"other",reason:"Bundled skill reference files are allowed for reading"}};return{behavior:"passthrough",message:""}}var FBK,JhY,MhY,hd,AC,o37,GhY;var Tz=y(()=>{F4();rw();pu();v8();o1();IY();I7();m8();e7();dz();SJ();vK();_K();kO();U1();Vv6();IG();NB();LH();Fj();FBK=O6(n$6(),1),JhY=[".gitconfig",".gitmodules",".bashrc",".bash_profile",".zshrc",".zprofile",".profile",".ripgreprc",".mcp.json",".claude.json"],MhY=[".git",".vscode",".idea",".claude"];hd=l56.sep;AC=_1(function(){let K=process.env.CLAUDE_CODE_TMPDIR||(Z1()==="windows"?HhY():"/tmp"),_=X8(),z=K;try{z=_.realpathSync(K)}catch{}return Wk(z,Na1())+JZ}),o37=_1(function(){let K=jhY(16).toString("hex");return Wk(AC(),"bundled-skills",{ISSUES_EXPLAINER:"report the issue at https://github.com/anthropics/claude-code/issues",PACKAGE_URL:"@anthropic-ai/claude-code",README_URL:"https://code.claude.com/docs/en/overview",VERSION:"2.1.88",FEEDBACK_CHANNEL:"https://github.com/anthropics/claude-code/issues",BUILD_TIME:"2026-03-30T21:59:52Z"}.VERSION,K)});GhY=_1(hx)});import{constants as VJ6}from"fs";import{mkdir as VhY,open as oBK,stat as nl2,symlink as iBK,unlink as NhY}from"fs/promises";import{join as aBK}from"path";function vL6(){if(t97===void 0)t97=aBK(vQ8(),N8(),"tasks");return t97}async function q_7(){await VhY(vL6(),{recursive:!0})}function sz(q){return aBK(vL6(),`${q}.output`)}function NQ8(q){return rBK.add(q),q.finally(()=>rBK.delete(q)).catch(()=>{}),q}class jI8{#q;#K=null;#_=[];#Y=0;#z=!1;#O=null;#$=null;constructor(q){this.#q=sz(q)}append(q){if(this.#z)return;if(this.#Y+=q.length,this.#Y>VQ8)this.#z=!0,this.#_.push(` |