import{a as e,o as t}from"./chunk-DR8-3Aex.js";import{n,s as r}from"./envUtils-BWeoiL4Y.js";import{Ct as i,H as a,X as o,cn as s}from"./state-sIHsFpDu.js";import{Fa as c,Mr as l,Na as u,Pr as d,S as f,co as p,no as ee,oo as te}from"./paths-Ci1iwL5Y.js";import{E as ne,J as re,U as m,_ as ie,h,l as ae,p as g}from"./debug-otxXY3j-.js";import{n as oe,r as _}from"./analytics-DqMQntaB.js";import{n as se,t as v}from"./cwd--iizewsn.js";import{o as y,s as b,v as x,y as S}from"./log-DSV4Ht5l.js";import{E as C,O as w,T as ce}from"./teammate-CbskW5G9.js";import{$D as le,Eo as ue,Er as de,Fr as fe,HC as pe,Oo as T,Ot as E,Uo as D,WC as O,XS as k,Xl as A,ZS as j,Zl as M,_t as N,cD as P,ck as F,cx as I,eO as L,iO as R,jC as z,kC as B,ko as me,lD as he,lx as ge,pD as _e,px as V,rt as ve,sD as ye,tt as H,ux as U}from"./loadAgentsDir-C_wFhytF.js";import{Qn as be,Zn as xe}from"./prompt-6ZKyqv6z.js";import{X as Se}from"./rcDebugLog-C42A0pX1.js";import{n as Ce,r as we}from"./magicDocs-DPZzG7Z2.js";import{n as Te,t as Ee}from"./pluginAutoupdate-ClrgF5b3.js";import{n as De,r as Oe}from"./registerProtocol-BkNncGMI.js";import{homedir as ke}from"os";import{join as W}from"path";import"crypto";import*as G from"fs/promises";r(),s(),se(),ne(),ie(),ae(),S(),te(),c(),d(),f(),be(),R(),ye(),M(),fe(),we(),H(),y(),m(),D(),F(),H(),L(),m(),y(),D(),F();async function Ae(e,t){if(!e)return;let{join:n}=await import(`path`),r=await import(`fs/promises`),a=n(v(),`.claude`,`skills`,e,`SKILL.md`),o;try{o=await r.readFile(a,`utf-8`)}catch{b(Error(`Failed to read skill file for improvement: ${a}`));return}let s=t.map(e=>`- ${e.section}: ${e.change}`).join(`
`),c=l(),d=_e()?P({sessionId:i(),model:c,provider:u(),name:`skill-improvement-apply`}):null,f=await ve({messages:[ue({content:`You are editing a skill definition file. Apply the following improvements to the skill.

<current_skill_file>
${o}
</current_skill_file>

<improvements>
${s}
</improvements>

Rules:
- Integrate the improvements naturally into the existing structure
- Preserve frontmatter (--- block) exactly as-is
- Preserve the overall format and style
- Do not remove existing content unless an improvement explicitly replaces it
- Output the complete updated file inside <updated_file> tags`})],systemPrompt:Se([`You edit skill definition files to incorporate user preferences. Output only the updated file content.`]),thinkingConfig:{type:`disabled`},tools:[],signal:le().signal,options:{getToolPermissionContext:async()=>xe(),model:c,toolChoice:void 0,isNonInteractiveSession:!1,hasAppendSystemPrompt:!1,temperatureOverride:0,agents:[],querySource:`skill_improvement_apply`,mcpTools:[],langfuseTrace:d}});he(d);let p=T(me(Array.isArray(f.message.content)?f.message.content:[]).trim(),`updated_file`);if(!p){b(Error(`Skill improvement apply: no updated_file tag in response`));return}try{await r.writeFile(a,p,`utf-8`)}catch(e){b(re(e))}}oe(),z(),ce(),y(),U(),j(),ge(),O(),E();var je=30;function K(){let e=((ee()||{}).cleanupPeriodDays??je)*24*60*60*1e3;return new Date(Date.now()-e)}function Me(e,t){return{messages:e.messages+t.messages,errors:e.errors+t.errors}}function Ne(e){let t=e.split(`.`)[0].replace(/T(\d{2})-(\d{2})-(\d{2})-(\d{3})Z/,`T$1:$2:$3.$4Z`);return new Date(t)}async function q(e,t,n){let r={messages:0,errors:0};try{let i=await h().readdir(e);for(let a of i)try{Ne(a.name)<t&&(await h().unlink(W(e,a.name)),n?r.messages++:r.errors++)}catch(e){b(e)}}catch(e){e instanceof Error&&`code`in e&&e.code!==`ENOENT`&&b(e)}return r}async function Pe(){let e=h(),t=K(),n=x.errors(),r=x.baseLogs(),i=await q(n,t,!1);try{let n;try{n=await e.readdir(r)}catch{return i}let a=n.filter(e=>e.isDirectory()&&e.name.startsWith(`mcp-logs-`)).map(e=>W(r,e.name));for(let n of a)i=Me(i,await q(n,t,!0)),await Y(n,e)}catch(e){e instanceof Error&&`code`in e&&e.code!==`ENOENT`&&b(e)}return i}async function J(e,t,n){return(await n.stat(e)).mtime<t?(await n.unlink(e),!0):!1}async function Y(e,t){try{await t.rmdir(e)}catch{}}async function Fe(){let e=K(),t={messages:0,errors:0},n=de(),r=h(),i;try{i=await r.readdir(n)}catch{return t}for(let a of i){if(!a.isDirectory())continue;let i=W(n,a.name),o;try{o=await r.readdir(i)}catch{t.errors++;continue}for(let n of o)if(n.isFile()){if(!n.name.endsWith(`.jsonl`)&&!n.name.endsWith(`.cast`))continue;try{await J(W(i,n.name),e,r)&&t.messages++}catch{t.errors++}}else if(n.isDirectory()){let a=W(i,n.name),o=W(a,pe),s;try{s=await r.readdir(o)}catch{await Y(a,r);continue}for(let n of s)if(n.isFile())try{await J(W(o,n.name),e,r)&&t.messages++}catch{t.errors++}else if(n.isDirectory()){let i=W(o,n.name),a;try{a=await r.readdir(i)}catch{continue}for(let n of a)if(n.isFile())try{await J(W(i,n.name),e,r)&&t.messages++}catch{t.errors++}await Y(i,r)}await Y(o,r),await Y(a,r)}await Y(i,r)}return t}async function Ie(e,t,n=!0){let r=K(),i={messages:0,errors:0},a=h(),o;try{o=await a.readdir(e)}catch{return i}for(let n of o)if(!(!n.isFile()||!n.name.endsWith(t)))try{await J(W(e,n.name),r,a)&&i.messages++}catch{i.errors++}return n&&await Y(e,a),i}function X(){return Ie(W(n(),`plans`),`.md`)}async function Le(){let e=K(),t={messages:0,errors:0},r=h();try{let i=W(n(),`file-history`),a;try{a=await r.readdir(i)}catch{return t}let o=a.filter(e=>e.isDirectory()).map(e=>W(i,e.name));await Promise.all(o.map(async n=>{try{(await r.stat(n)).mtime<e&&(await r.rm(n,{recursive:!0,force:!0}),t.messages++)}catch{t.errors++}})),await Y(i,r)}catch(e){b(e)}return t}async function Re(){let e=K(),t={messages:0,errors:0},r=h();try{let i=W(n(),`session-env`),a;try{a=await r.readdir(i)}catch{return t}let o=a.filter(e=>e.isDirectory()).map(e=>W(i,e.name));for(let n of o)try{(await r.stat(n)).mtime<e&&(await r.rm(n,{recursive:!0,force:!0}),t.messages++)}catch{t.errors++}await Y(i,r)}catch(e){b(e)}return t}async function ze(){let e=K(),t={messages:0,errors:0},r=h(),i=W(n(),`debug`),a;try{a=await r.readdir(i)}catch{return t}for(let n of a)if(!(!n.isFile()||!n.name.endsWith(`.txt`)||n.name===`latest`))try{await J(W(i,n.name),e,r)&&t.messages++}catch{t.errors++}return t}var Z=1440*60*1e3;async function Q(){let e=W(n(),`.npm-cache-cleanup`);try{let t=await G.stat(e);if(Date.now()-t.mtimeMs<Z){g(`npm cache cleanup: skipping, ran recently`);return}}catch{}try{await C(e,{retries:0,realpath:!1})}catch{g(`npm cache cleanup: skipping, lock held`);return}g(`npm cache cleanup: starting`);let r=W(ke(),`.npm`,`_cacache`),i=Date.now();try{let n=await import(`./lib-inCisXen.js`).then(e=>t(e.default,1)),a=i-Z,o=n.ls.stream(r),s=[];for await(let e of o)e.key.includes(`@anthropic-ai/claude-`)&&s.push({key:e.key,time:e.time});let c=new Map;for(let e of s){let t=e.key.lastIndexOf(`@`),n=t>0?e.key.slice(0,t):e.key,r=c.get(n)??[];r.push(e),c.set(n,r)}let l=[];for(let[,e]of c){e.sort((e,t)=>t.time-e.time);for(let t=0;t<e.length;t++){let n=e[t];(n.time<a||t>=5)&&l.push(n.key)}}await Promise.all(l.map(e=>n.rm.entry(r,e))),await G.writeFile(e,new Date().toISOString());let u=Date.now()-i;l.length>0?g(`npm cache cleanup: Removed ${l.length} old @anthropic-ai entries in ${u}ms`):g(`npm cache cleanup: completed in ${u}ms`),_(`tengu_npm_cache_cleanup`,{success:!0,durationMs:u,entriesRemoved:l.length})}catch(e){b(e),_(`tengu_npm_cache_cleanup`,{success:!1,durationMs:Date.now()-i})}finally{await w(e,{realpath:!1}).catch(()=>{})}}async function Be(){let e=W(n(),`.version-cleanup`);try{let t=await G.stat(e);if(Date.now()-t.mtimeMs<Z){g(`version cleanup: skipping, ran recently`);return}}catch{}try{await C(e,{retries:0,realpath:!1})}catch{g(`version cleanup: skipping, lock held`);return}g(`version cleanup: starting (throttled)`);try{await V(),await G.writeFile(e,new Date().toISOString())}catch(e){b(e)}finally{await w(e,{realpath:!1}).catch(()=>{})}}async function Ve(){let{errors:e}=I();if(e.length>0&&p(`cleanupPeriodDays`)){g(`Skipping cleanup: settings have validation errors but cleanupPeriodDays was explicitly set. Fix settings errors to enable cleanup.`);return}await Pe(),await Fe(),await X(),await Le(),await Re(),await ze(),await B(),await k(K());let t=await N(K());t>0&&_(`tengu_worktree_cleanup`,{removed:t}),process.env.USER_TYPE===`ant`&&await Q()}s(),U(),Te();var He=(De(),e(Oe)),Ue=1440*60*1e3,$=600*1e3;function We(){Ce(),import(`./extractMemories-B3cTWsph.js`).then(({initExtractMemories:e})=>{e()}).catch(()=>{}),A(),Ee(),a()&&He.ensureDeepLinkProtocolRegistered();let e=!0;async function t(){if(a()&&o()>Date.now()-1e3*60){setTimeout(t,$).unref();return}if(e&&(e=!1,await Ve()),a()&&o()>Date.now()-1e3*60){setTimeout(t,$).unref();return}await V()}setTimeout(t,$).unref(),process.env.USER_TYPE===`ant`&&setInterval(()=>{Q(),Be()},Ue).unref()}export{Ae as n,We as t};