@unity-china/codely-cli 1.0.0-rc.53 → 1.0.0-rc.54
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bundle/gemini.js +2 -2
- package/package.json +1 -1
package/bundle/gemini.js
CHANGED
|
@@ -2982,7 +2982,7 @@ Next steps:
|
|
|
2982
2982
|
email = codely-cli@unity.cn
|
|
2983
2983
|
[commit]
|
|
2984
2984
|
gpgsign = false
|
|
2985
|
-
`);let o=v3(e);await o.checkIsRepo(Zqe.IS_REPO_ROOT)||(await o.init(!1,{"--initial-branch":"main"}),await o.commit("Initial commit",{"--allow-empty":null}));let a=pp.join(this.projectRoot,".gitignore"),c=pp.join(e,".gitignore"),l="";try{l=await _d.readFile(a,"utf-8")}catch(u){if(ri(u)&&u.code!=="ENOENT")throw u}await _d.writeFile(c,l)}get shadowGitRepository(){let e=this.getHistoryDir();return v3(this.projectRoot).env({GIT_DIR:pp.join(e,".git"),GIT_WORK_TREE:this.projectRoot,HOME:e,XDG_CONFIG_HOME:e})}async getCurrentCommitHash(){return(await this.shadowGitRepository.raw("rev-parse","HEAD")).trim()}async getCurrentGitCommitHash(){try{return(await v3(this.projectRoot).raw("rev-parse","HEAD")).trim()}catch(e){return console.warn(`Failed to get current Git commit hash: ${e}`),""}}async createFileSnapshot(e){let n=new Date().toISOString().replace(/[:.]/g,"-"),r=`${n}-${Math.random().toString(36).substr(2,9)}`,o=await this.getCurrentGitCommitHash(),s=await this.getChangedFiles();if(s.length===0)return r;let a=pp.join(this.getHistoryDir(),"snapshots",r);await _d.mkdir(a,{recursive:!0});let c={timestamp:n,commitHash:r,baseCommitHash:o,message:e,files:[]};for(let u of s)try{if(u.status==="deleted")c.files.push({relativePath:u.relativePath,backupPath:"",status:"deleted"});else{let d=pp.join(this.projectRoot,u.relativePath);if(await this.fileExists(d)){let p=u.relativePath.replace(/[/\\]/g,"_"),h=pp.join(a,p);await _d.mkdir(pp.dirname(h),{recursive:!0}),await _d.copyFile(d,h),c.files.push({relativePath:u.relativePath,backupPath:h,status:u.status,originalPath:u.originalPath})}else console.warn(`Source file does not exist, skipping backup: ${u.relativePath}`)}}catch(d){console.warn(`Failed to backup file ${u.relativePath}: ${d}`)}let l=pp.join(a,"manifest.json");return await _d.writeFile(l,JSON.stringify(c,null,2)),r}async restoreProjectFromSnapshot(e){let n=pp.join(this.getHistoryDir(),"snapshots",e),r=pp.join(n,"manifest.json");try{let o=await _d.readFile(r,"utf-8"),s=JSON.parse(o),a=v3(this.projectRoot),l=(await a.status()).files.length>0,u=null;if(l)try{(await a.stash(["push","-m",`Auto-stash before checkpoint restore ${e}`])).includes("No local changes to save")||(u="stash@{0}")}catch(d){console.warn(`Failed to stash changes before restore: ${d}`)}if(s.baseCommitHash)try{await a.reset(["--hard",s.baseCommitHash]),console.log(`Reset to base commit: ${s.baseCommitHash}`),await a.clean("f",["-d"]),console.log("Cleaned untracked files created after snapshot")}catch(d){console.warn(`Failed to reset to base commit ${s.baseCommitHash}: ${d}`)}for(let d of s.files)try{let p=pp.join(this.projectRoot,d.relativePath);if(d.status==="deleted")try{await _d.unlink(p)}catch(h){ri(h)&&h.code!=="ENOENT"&&console.warn(`Failed to delete file ${d.relativePath}: ${h}`)}else if(d.status==="untracked"){if(d.backupPath&&await this.fileExists(d.backupPath)){let h=pp.dirname(p);await _d.mkdir(h,{recursive:!0}),await _d.copyFile(d.backupPath,p)}}else if(d.backupPath&&await this.fileExists(d.backupPath)){let h=pp.dirname(p);await _d.mkdir(h,{recursive:!0}),await _d.copyFile(d.backupPath,p)}else console.warn(`Backup file not found, cannot restore: ${d.relativePath}`)}catch(p){console.warn(`Failed to restore file ${d.relativePath}: ${p}`)}u&&(console.log(`Previous changes were stashed as: ${u}`),console.log('Use "git stash pop" to restore your previous changes if needed.'))}catch(o){throw new Error(`Failed to restore from snapshot ${e}: ${o}`)}}async getChangedFiles(){try{let n=await v3(this.projectRoot).status(),r=[],o=[];for(let u of n.files){let d=u.path,p=u.index,h=u.working_dir,m;if(p==="A")m="added",o.push(d);else if(p==="M"||h==="M")m="modified",o.push(d);else if(p==="D"||h==="D")m="deleted";else if(p==="R")m="renamed",o.push(d);else if(p==="?"&&h==="?")m="untracked",o.push(d);else continue;r.push({relativePath:d,status:m})}for(let u of n.renamed)r.find(p=>p.relativePath===u.to)||(o.push(u.to),u.from&&o.push(u.from),r.push({relativePath:u.to,status:"renamed",originalPath:u.from}));let s=o.map(u=>pp.join(this.projectRoot,u)),a=this.fileDiscoveryService.filterFiles(s,{respectGitIgnore:!0,respectGeminiIgnore:!1}),c=new Set(a.map(u=>pp.relative(this.projectRoot,u)));return r.filter(u=>u.status==="deleted"?!0:c.has(u.relativePath))}catch(e){return console.warn(`Failed to get changed files: ${e}`),[]}}async fileExists(e){try{return await _d.access(e),!0}catch{return!1}}async cleanupOldSnapshots(e=50){try{let n=pp.join(this.getHistoryDir(),"snapshots");try{let r=await _d.readdir(n);if(r.length<=e)return;let o=await Promise.all(r.map(async a=>{let c=pp.join(n,a),l=await _d.stat(c);return{name:a,path:c,mtime:l.mtime}}));o.sort((a,c)=>c.mtime.getTime()-a.mtime.getTime());let s=o.slice(e);for(let a of s)try{await _d.rm(a.path,{recursive:!0,force:!0})}catch(c){console.warn(`Failed to delete old snapshot ${a.name}: ${c}`)}}catch(r){ri(r)&&r.code!=="ENOENT"&&console.warn(`Failed to clean up snapshots: ${r}`)}}catch(n){console.warn(`Failed to clean up old snapshots: ${n}`)}}}});function e8n(){let t=["www-browser"],e=process.env.BROWSER;if(e&&t.includes(e)||process.env.CI||process.env.DEBIAN_FRONTEND==="noninteractive")return!1;let n=!!process.env.SSH_CONNECTION;return!(process.platform==="linux"&&!["DISPLAY","WAYLAND_DISPLAY","MIR_SOCKET"].some(s=>!!process.env[s])||n&&process.platform!=="linux")}var t8n=x(()=>{"use strict";f();});import lRe from"node:fs/promises";import Psa from"node:path";function n8n(t){let e=Psa.join(t,"goals"),n=Psa.join(e,"active.json"),r=`${n}.tmp`;return{async load(){try{let o=await lRe.readFile(n,"utf-8");return JSON.parse(o)}catch(o){return o.code!=="ENOENT"&&console.warn("[goalStore] Failed to load persisted goal state:",o),{...JNp}}},async save(o){await lRe.mkdir(e,{recursive:!0}),await lRe.writeFile(r,JSON.stringify(o,null,2),"utf-8"),await lRe.rename(r,n)},async clear(){await lRe.rm(n,{force:!0}),await lRe.rm(r,{force:!0})}}}var JNp,r8n=x(()=>{"use strict";f();JNp={schemaVersion:1,goal:null,pendingTemplate:null}});import{randomUUID as XNp}from"node:crypto";function o8n(t){return t!==null&&(t.status==="active"||t.status==="budget_limited")}function ZNp(t){return t?.timeUsedSeconds??0}function s8n(t){let e=n8n(t.projectTempDir),n=t.now??(()=>new Date),r={schemaVersion:1,goal:null,pendingTemplate:null},o=Promise.resolve(),s=!1,a=null,c=2,l=0,u=null,d=()=>{An.emitGoalStateChanged({goal:r.goal,pendingTemplate:r.pendingTemplate})},p=async()=>{let T;if(o=o.then(async()=>{try{if(r.goal===null){await e.clear();return}await e.save(r)}catch(C){T=C}}),await o,T!==void 0)throw T},h=()=>{p().catch(()=>{})},m=(T,C)=>({...T,updatedAt:C}),A=()=>{if(!r.goal)throw new Error("No active goal");return r.goal},g=async(T,C)=>(r={schemaVersion:1,goal:T,pendingTemplate:C},await p(),d(),T),_=T=>{if(!o8n(r.goal)){r.goal===null&&(a=null);return}if(a===null){a=T;return}let C=Math.max(0,Math.floor((T.getTime()-a.getTime())/1e3));a=T,!(C<=0)&&(r.goal={...r.goal,timeUsedSeconds:ZNp(r.goal)+C,updatedAt:T.toISOString()})},E=T=>T.tokenBudget!==null&&T.tokensUsed>=T.tokenBudget;return{async load(){let T=n(),C=await e.load();r={...C,goal:C.goal?{...C.goal,timeUsedSeconds:C.goal.timeUsedSeconds??0}:null},a=o8n(r.goal)?T:null},async flush(){await o},getActive(){return r.goal},shouldAutoContinue(){return r.goal?r.goal.status==="budget_limited"?r.pendingTemplate==="budget_limit":r.goal.status!=="active"||r.goal.tokenBudget===null||l>=c?!1:!E(r.goal):!1},async set(T,C){let b=n(),N=b.toISOString(),v={id:XNp(),objective:T,status:"active",tokenBudget:C,tokensUsed:0,timeUsedSeconds:0,createdAt:N,updatedAt:N};return a=b,s=!1,g(v,"continuation")},async edit(T){let C=n();_(C);let b=A(),N=m({...b,objective:T},C.toISOString());return g(N,"objective_updated")},async setBudget(T){let C=n();_(C);let b=A(),N=b.status==="budget_limited"&&(T===null||T>b.tokensUsed),v=N?"active":b.status,D=N?null:r.pendingTemplate,M=m({...b,status:v,tokenBudget:T},C.toISOString());return v!=="budget_limited"&&(s=!1),g(M,D)},async pause(){let T=n();_(T);let C=A(),b=m({...C,status:"paused"},T.toISOString());return s=!1,a=null,g(b,null)},async resume(){let T=n(),C=A(),b=m({...C,status:"active"},T.toISOString());return a=T,g(b,"continuation")},async clear(){let T=n();_(T),s=!1,a=null,r={schemaVersion:1,goal:null,pendingTemplate:null},await p(),d()},async complete(T){let C=n();_(C);let b=A(),N=m({...b,status:"complete"},C.toISOString());return s=!1,a=null,g(N,null)},buildAttachmentForThisTurn(){let T=n();if(_(T),s=!1,!r.goal)return null;if(r.goal.status==="paused"||r.goal.status==="complete")return r.pendingTemplate=null,null;if(r.goal.status==="budget_limited"&&r.pendingTemplate!=="budget_limit")return null;let b={type:"goal_context",templateKind:r.goal.status==="budget_limited"?"budget_limit":r.pendingTemplate??"continuation_short",objective:r.goal.objective,status:r.goal.status,tokenBudget:r.goal.tokenBudget,tokensUsed:r.goal.tokensUsed,timeUsedSeconds:r.goal.timeUsedSeconds};return r.goal.status==="budget_limited"&&(s=!0),r.pendingTemplate=null,h(),d(),b},noteTurnStarted(){if(!r.goal||!o8n(r.goal)){u=null;return}u=r.goal.tokensUsed,h(),d()},noteTurnEnded(){if(!r.goal||u===null)return;r.goal.tokensUsed-u>0?l=0:l+=1,u=null},noteTokens(T){let C=n();if(!r.goal||r.goal.status==="paused"||r.goal.status==="complete"||(_(C),r.goal.status==="budget_limited"&&r.pendingTemplate!=="budget_limit"&&!s))return;T>0&&(l=0);let b=r.goal.status,N=r.goal.status==="active"&&r.goal.tokenBudget!==null&&r.goal.tokensUsed+T>=r.goal.tokenBudget?"budget_limited":r.goal.status;r.goal=m({...r.goal,tokensUsed:r.goal.tokensUsed+T,status:N},C.toISOString()),r.goal.status==="budget_limited"&&b!=="budget_limited"&&(r.pendingTemplate="budget_limit"),h(),d()},noteAborted(){let T=n();if(!r.goal||r.goal.status!=="active")return;_(T);let C=m({...r.goal,status:"paused"},T.toISOString());s=!1,a=null,r.goal=C,h(),d()}}}var Msa=x(()=>{"use strict";f();r8n();N0();});var Dsa=x(()=>{"use strict";f();});var i8n=x(()=>{"use strict";f();r8n();Msa();Dsa();C4n();});import*as Hx from"fs";import*as L_ from"path";var HLt,wsa=x(()=>{"use strict";f();HLt=class{directories;initialDirectories;constructor(e,n=[]){this.directories=new Set,this.initialDirectories=new Set,this.addDirectoryInternal(e),this.addInitialDirectoryInternal(e);for(let r of n)this.addDirectoryInternal(r),this.addInitialDirectoryInternal(r)}addDirectory(e,n=process.cwd()){this.addDirectoryInternal(e,n)}addDirectoryInternal(e,n=process.cwd()){let r=L_.isAbsolute(e)?e:L_.resolve(n,e);if(!Hx.existsSync(r))throw new Error(`Directory does not exist: ${r}`);if(!Hx.statSync(r).isDirectory())throw new Error(`Path is not a directory: ${r}`);let s;try{s=Hx.realpathSync(r)}catch{throw new Error(`Failed to resolve path: ${r}`)}this.directories.add(s)}addInitialDirectoryInternal(e,n=process.cwd()){let r=L_.isAbsolute(e)?e:L_.resolve(n,e);if(!Hx.existsSync(r))throw new Error(`Directory does not exist: ${r}`);if(!Hx.statSync(r).isDirectory())throw new Error(`Path is not a directory: ${r}`);let s;try{s=Hx.realpathSync(r)}catch{throw new Error(`Failed to resolve path: ${r}`)}this.initialDirectories.add(s)}getDirectories(){return Array.from(this.directories)}getInitialDirectories(){return Array.from(this.initialDirectories)}setDirectories(e){this.directories.clear();for(let n of e)this.addDirectoryInternal(n)}isPathWithinWorkspace(e){try{let n=L_.resolve(e),r=n;if(Hx.existsSync(n))try{r=Hx.realpathSync(n)}catch{return!1}else r=this.resolveViaAncestor(n);for(let o of this.directories)if(this.isPathWithinRoot(r,o))return!0;return!1}catch{return!1}}resolveViaAncestor(e){let n=e,r=[];for(;n!==L_.dirname(n);){let o=L_.dirname(n);if(r.push(L_.basename(n)),Hx.existsSync(o))try{let s=Hx.realpathSync(o);return L_.join(s,...r.reverse())}catch{return e}n=o}return e}isPathWithinRoot(e,n){let r=L_.relative(n,e);return!r.startsWith(`..${L_.sep}`)&&r!==".."&&!L_.isAbsolute(r)}}});import*as RK from"node:fs/promises";import*as qLt from"node:path";function uRe(){return process.env.CLI_EMBED_ASSET_HASH||"1.0.0-rc.53"}function eOp(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function dRe(){let t=globalThis.__CODELY_EMBEDDED_ASSETS;if(!eOp(t))return null;for(let[e,n]of Object.entries(t))if(typeof e!="string"||typeof n!="string")return null;return t}function QLt(){return dRe()!==null}function qG(t){let e=dRe();return e?e[t]??null:null}function R1(t=""){let e=dRe();if(!e)return[];let n=Object.keys(e);return t?n.filter(r=>r.startsWith(t)):n}function i3e(t="policies/"){let e=dRe();return e?Object.entries(e).filter(([n,r])=>n.startsWith(t)&&n.endsWith(".toml")&&r.length>0).map(([n,r])=>({fileName:n.slice(t.length),filePath:r})).sort((n,r)=>n.fileName.localeCompare(r.fileName)):[]}async function Lsa(t){let e=qG(t);if(!e)throw new Error(`Embedded asset not found: ${t}`);return RK.readFile(e,"utf8")}async function Usa(t){let e=qG(t);if(!e)throw new Error(`Embedded asset not found: ${t}`);let n=await RK.readFile(e);return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}async function a3e(t,e){let n=qG(t);if(!n)throw new Error(`Embedded asset not found: ${t}`);await RK.mkdir(qLt.dirname(e),{recursive:!0});let r=await RK.readFile(n);await RK.writeFile(e,r)}async function bK(t){let{prefix:e,outDir:n,filter:r}=t,o=R1(e),s=0,a=0,c=e.endsWith("/")?e:`${e}/`;for(let l of o){if(!l.startsWith(c))continue;if(r&&!r(l)){a+=1;continue}let u=l.slice(c.length);if(!u)continue;let d=qLt.join(n,u);await a3e(l,d),s+=1}return{written:s,skipped:a}}var fRe=x(()=>{"use strict";f();});function b1(){return globalThis.__CODELY_PACKAGED_EXECUTABLE===!0}var pRe=x(()=>{"use strict";f();});import Fsa from"node:fs/promises";import x3 from"node:path";import{fileURLToPath as tOp}from"node:url";function Gsa(t){return t===c3e?"user":t===l3e?"admin":"default"}function lOp(t){return t.issues.map(e=>` - Field "${e.path.join(".")}": ${e.message}`).join(`
|
|
2985
|
+
`);let o=v3(e);await o.checkIsRepo(Zqe.IS_REPO_ROOT)||(await o.init(!1,{"--initial-branch":"main"}),await o.commit("Initial commit",{"--allow-empty":null}));let a=pp.join(this.projectRoot,".gitignore"),c=pp.join(e,".gitignore"),l="";try{l=await _d.readFile(a,"utf-8")}catch(u){if(ri(u)&&u.code!=="ENOENT")throw u}await _d.writeFile(c,l)}get shadowGitRepository(){let e=this.getHistoryDir();return v3(this.projectRoot).env({GIT_DIR:pp.join(e,".git"),GIT_WORK_TREE:this.projectRoot,HOME:e,XDG_CONFIG_HOME:e})}async getCurrentCommitHash(){return(await this.shadowGitRepository.raw("rev-parse","HEAD")).trim()}async getCurrentGitCommitHash(){try{return(await v3(this.projectRoot).raw("rev-parse","HEAD")).trim()}catch(e){return console.warn(`Failed to get current Git commit hash: ${e}`),""}}async createFileSnapshot(e){let n=new Date().toISOString().replace(/[:.]/g,"-"),r=`${n}-${Math.random().toString(36).substr(2,9)}`,o=await this.getCurrentGitCommitHash(),s=await this.getChangedFiles();if(s.length===0)return r;let a=pp.join(this.getHistoryDir(),"snapshots",r);await _d.mkdir(a,{recursive:!0});let c={timestamp:n,commitHash:r,baseCommitHash:o,message:e,files:[]};for(let u of s)try{if(u.status==="deleted")c.files.push({relativePath:u.relativePath,backupPath:"",status:"deleted"});else{let d=pp.join(this.projectRoot,u.relativePath);if(await this.fileExists(d)){let p=u.relativePath.replace(/[/\\]/g,"_"),h=pp.join(a,p);await _d.mkdir(pp.dirname(h),{recursive:!0}),await _d.copyFile(d,h),c.files.push({relativePath:u.relativePath,backupPath:h,status:u.status,originalPath:u.originalPath})}else console.warn(`Source file does not exist, skipping backup: ${u.relativePath}`)}}catch(d){console.warn(`Failed to backup file ${u.relativePath}: ${d}`)}let l=pp.join(a,"manifest.json");return await _d.writeFile(l,JSON.stringify(c,null,2)),r}async restoreProjectFromSnapshot(e){let n=pp.join(this.getHistoryDir(),"snapshots",e),r=pp.join(n,"manifest.json");try{let o=await _d.readFile(r,"utf-8"),s=JSON.parse(o),a=v3(this.projectRoot),l=(await a.status()).files.length>0,u=null;if(l)try{(await a.stash(["push","-m",`Auto-stash before checkpoint restore ${e}`])).includes("No local changes to save")||(u="stash@{0}")}catch(d){console.warn(`Failed to stash changes before restore: ${d}`)}if(s.baseCommitHash)try{await a.reset(["--hard",s.baseCommitHash]),console.log(`Reset to base commit: ${s.baseCommitHash}`),await a.clean("f",["-d"]),console.log("Cleaned untracked files created after snapshot")}catch(d){console.warn(`Failed to reset to base commit ${s.baseCommitHash}: ${d}`)}for(let d of s.files)try{let p=pp.join(this.projectRoot,d.relativePath);if(d.status==="deleted")try{await _d.unlink(p)}catch(h){ri(h)&&h.code!=="ENOENT"&&console.warn(`Failed to delete file ${d.relativePath}: ${h}`)}else if(d.status==="untracked"){if(d.backupPath&&await this.fileExists(d.backupPath)){let h=pp.dirname(p);await _d.mkdir(h,{recursive:!0}),await _d.copyFile(d.backupPath,p)}}else if(d.backupPath&&await this.fileExists(d.backupPath)){let h=pp.dirname(p);await _d.mkdir(h,{recursive:!0}),await _d.copyFile(d.backupPath,p)}else console.warn(`Backup file not found, cannot restore: ${d.relativePath}`)}catch(p){console.warn(`Failed to restore file ${d.relativePath}: ${p}`)}u&&(console.log(`Previous changes were stashed as: ${u}`),console.log('Use "git stash pop" to restore your previous changes if needed.'))}catch(o){throw new Error(`Failed to restore from snapshot ${e}: ${o}`)}}async getChangedFiles(){try{let n=await v3(this.projectRoot).status(),r=[],o=[];for(let u of n.files){let d=u.path,p=u.index,h=u.working_dir,m;if(p==="A")m="added",o.push(d);else if(p==="M"||h==="M")m="modified",o.push(d);else if(p==="D"||h==="D")m="deleted";else if(p==="R")m="renamed",o.push(d);else if(p==="?"&&h==="?")m="untracked",o.push(d);else continue;r.push({relativePath:d,status:m})}for(let u of n.renamed)r.find(p=>p.relativePath===u.to)||(o.push(u.to),u.from&&o.push(u.from),r.push({relativePath:u.to,status:"renamed",originalPath:u.from}));let s=o.map(u=>pp.join(this.projectRoot,u)),a=this.fileDiscoveryService.filterFiles(s,{respectGitIgnore:!0,respectGeminiIgnore:!1}),c=new Set(a.map(u=>pp.relative(this.projectRoot,u)));return r.filter(u=>u.status==="deleted"?!0:c.has(u.relativePath))}catch(e){return console.warn(`Failed to get changed files: ${e}`),[]}}async fileExists(e){try{return await _d.access(e),!0}catch{return!1}}async cleanupOldSnapshots(e=50){try{let n=pp.join(this.getHistoryDir(),"snapshots");try{let r=await _d.readdir(n);if(r.length<=e)return;let o=await Promise.all(r.map(async a=>{let c=pp.join(n,a),l=await _d.stat(c);return{name:a,path:c,mtime:l.mtime}}));o.sort((a,c)=>c.mtime.getTime()-a.mtime.getTime());let s=o.slice(e);for(let a of s)try{await _d.rm(a.path,{recursive:!0,force:!0})}catch(c){console.warn(`Failed to delete old snapshot ${a.name}: ${c}`)}}catch(r){ri(r)&&r.code!=="ENOENT"&&console.warn(`Failed to clean up snapshots: ${r}`)}}catch(n){console.warn(`Failed to clean up old snapshots: ${n}`)}}}});function e8n(){let t=["www-browser"],e=process.env.BROWSER;if(e&&t.includes(e)||process.env.CI||process.env.DEBIAN_FRONTEND==="noninteractive")return!1;let n=!!process.env.SSH_CONNECTION;return!(process.platform==="linux"&&!["DISPLAY","WAYLAND_DISPLAY","MIR_SOCKET"].some(s=>!!process.env[s])||n&&process.platform!=="linux")}var t8n=x(()=>{"use strict";f();});import lRe from"node:fs/promises";import Psa from"node:path";function n8n(t){let e=Psa.join(t,"goals"),n=Psa.join(e,"active.json"),r=`${n}.tmp`;return{async load(){try{let o=await lRe.readFile(n,"utf-8");return JSON.parse(o)}catch(o){return o.code!=="ENOENT"&&console.warn("[goalStore] Failed to load persisted goal state:",o),{...JNp}}},async save(o){await lRe.mkdir(e,{recursive:!0}),await lRe.writeFile(r,JSON.stringify(o,null,2),"utf-8"),await lRe.rename(r,n)},async clear(){await lRe.rm(n,{force:!0}),await lRe.rm(r,{force:!0})}}}var JNp,r8n=x(()=>{"use strict";f();JNp={schemaVersion:1,goal:null,pendingTemplate:null}});import{randomUUID as XNp}from"node:crypto";function o8n(t){return t!==null&&(t.status==="active"||t.status==="budget_limited")}function ZNp(t){return t?.timeUsedSeconds??0}function s8n(t){let e=n8n(t.projectTempDir),n=t.now??(()=>new Date),r={schemaVersion:1,goal:null,pendingTemplate:null},o=Promise.resolve(),s=!1,a=null,c=2,l=0,u=null,d=()=>{An.emitGoalStateChanged({goal:r.goal,pendingTemplate:r.pendingTemplate})},p=async()=>{let T;if(o=o.then(async()=>{try{if(r.goal===null){await e.clear();return}await e.save(r)}catch(C){T=C}}),await o,T!==void 0)throw T},h=()=>{p().catch(()=>{})},m=(T,C)=>({...T,updatedAt:C}),A=()=>{if(!r.goal)throw new Error("No active goal");return r.goal},g=async(T,C)=>(r={schemaVersion:1,goal:T,pendingTemplate:C},await p(),d(),T),_=T=>{if(!o8n(r.goal)){r.goal===null&&(a=null);return}if(a===null){a=T;return}let C=Math.max(0,Math.floor((T.getTime()-a.getTime())/1e3));a=T,!(C<=0)&&(r.goal={...r.goal,timeUsedSeconds:ZNp(r.goal)+C,updatedAt:T.toISOString()})},E=T=>T.tokenBudget!==null&&T.tokensUsed>=T.tokenBudget;return{async load(){let T=n(),C=await e.load();r={...C,goal:C.goal?{...C.goal,timeUsedSeconds:C.goal.timeUsedSeconds??0}:null},a=o8n(r.goal)?T:null},async flush(){await o},getActive(){return r.goal},shouldAutoContinue(){return r.goal?r.goal.status==="budget_limited"?r.pendingTemplate==="budget_limit":r.goal.status!=="active"||r.goal.tokenBudget===null||l>=c?!1:!E(r.goal):!1},async set(T,C){let b=n(),N=b.toISOString(),v={id:XNp(),objective:T,status:"active",tokenBudget:C,tokensUsed:0,timeUsedSeconds:0,createdAt:N,updatedAt:N};return a=b,s=!1,g(v,"continuation")},async edit(T){let C=n();_(C);let b=A(),N=m({...b,objective:T},C.toISOString());return g(N,"objective_updated")},async setBudget(T){let C=n();_(C);let b=A(),N=b.status==="budget_limited"&&(T===null||T>b.tokensUsed),v=N?"active":b.status,D=N?null:r.pendingTemplate,M=m({...b,status:v,tokenBudget:T},C.toISOString());return v!=="budget_limited"&&(s=!1),g(M,D)},async pause(){let T=n();_(T);let C=A(),b=m({...C,status:"paused"},T.toISOString());return s=!1,a=null,g(b,null)},async resume(){let T=n(),C=A(),b=m({...C,status:"active"},T.toISOString());return a=T,g(b,"continuation")},async clear(){let T=n();_(T),s=!1,a=null,r={schemaVersion:1,goal:null,pendingTemplate:null},await p(),d()},async complete(T){let C=n();_(C);let b=A(),N=m({...b,status:"complete"},C.toISOString());return s=!1,a=null,g(N,null)},buildAttachmentForThisTurn(){let T=n();if(_(T),s=!1,!r.goal)return null;if(r.goal.status==="paused"||r.goal.status==="complete")return r.pendingTemplate=null,null;if(r.goal.status==="budget_limited"&&r.pendingTemplate!=="budget_limit")return null;let b={type:"goal_context",templateKind:r.goal.status==="budget_limited"?"budget_limit":r.pendingTemplate??"continuation_short",objective:r.goal.objective,status:r.goal.status,tokenBudget:r.goal.tokenBudget,tokensUsed:r.goal.tokensUsed,timeUsedSeconds:r.goal.timeUsedSeconds};return r.goal.status==="budget_limited"&&(s=!0),r.pendingTemplate=null,h(),d(),b},noteTurnStarted(){if(!r.goal||!o8n(r.goal)){u=null;return}u=r.goal.tokensUsed,h(),d()},noteTurnEnded(){if(!r.goal||u===null)return;r.goal.tokensUsed-u>0?l=0:l+=1,u=null},noteTokens(T){let C=n();if(!r.goal||r.goal.status==="paused"||r.goal.status==="complete"||(_(C),r.goal.status==="budget_limited"&&r.pendingTemplate!=="budget_limit"&&!s))return;T>0&&(l=0);let b=r.goal.status,N=r.goal.status==="active"&&r.goal.tokenBudget!==null&&r.goal.tokensUsed+T>=r.goal.tokenBudget?"budget_limited":r.goal.status;r.goal=m({...r.goal,tokensUsed:r.goal.tokensUsed+T,status:N},C.toISOString()),r.goal.status==="budget_limited"&&b!=="budget_limited"&&(r.pendingTemplate="budget_limit"),h(),d()},noteAborted(){let T=n();if(!r.goal||r.goal.status!=="active")return;_(T);let C=m({...r.goal,status:"paused"},T.toISOString());s=!1,a=null,r.goal=C,h(),d()}}}var Msa=x(()=>{"use strict";f();r8n();N0();});var Dsa=x(()=>{"use strict";f();});var i8n=x(()=>{"use strict";f();r8n();Msa();Dsa();C4n();});import*as Hx from"fs";import*as L_ from"path";var HLt,wsa=x(()=>{"use strict";f();HLt=class{directories;initialDirectories;constructor(e,n=[]){this.directories=new Set,this.initialDirectories=new Set,this.addDirectoryInternal(e),this.addInitialDirectoryInternal(e);for(let r of n)this.addDirectoryInternal(r),this.addInitialDirectoryInternal(r)}addDirectory(e,n=process.cwd()){this.addDirectoryInternal(e,n)}addDirectoryInternal(e,n=process.cwd()){let r=L_.isAbsolute(e)?e:L_.resolve(n,e);if(!Hx.existsSync(r))throw new Error(`Directory does not exist: ${r}`);if(!Hx.statSync(r).isDirectory())throw new Error(`Path is not a directory: ${r}`);let s;try{s=Hx.realpathSync(r)}catch{throw new Error(`Failed to resolve path: ${r}`)}this.directories.add(s)}addInitialDirectoryInternal(e,n=process.cwd()){let r=L_.isAbsolute(e)?e:L_.resolve(n,e);if(!Hx.existsSync(r))throw new Error(`Directory does not exist: ${r}`);if(!Hx.statSync(r).isDirectory())throw new Error(`Path is not a directory: ${r}`);let s;try{s=Hx.realpathSync(r)}catch{throw new Error(`Failed to resolve path: ${r}`)}this.initialDirectories.add(s)}getDirectories(){return Array.from(this.directories)}getInitialDirectories(){return Array.from(this.initialDirectories)}setDirectories(e){this.directories.clear();for(let n of e)this.addDirectoryInternal(n)}isPathWithinWorkspace(e){try{let n=L_.resolve(e),r=n;if(Hx.existsSync(n))try{r=Hx.realpathSync(n)}catch{return!1}else r=this.resolveViaAncestor(n);for(let o of this.directories)if(this.isPathWithinRoot(r,o))return!0;return!1}catch{return!1}}resolveViaAncestor(e){let n=e,r=[];for(;n!==L_.dirname(n);){let o=L_.dirname(n);if(r.push(L_.basename(n)),Hx.existsSync(o))try{let s=Hx.realpathSync(o);return L_.join(s,...r.reverse())}catch{return e}n=o}return e}isPathWithinRoot(e,n){let r=L_.relative(n,e);return!r.startsWith(`..${L_.sep}`)&&r!==".."&&!L_.isAbsolute(r)}}});import*as RK from"node:fs/promises";import*as qLt from"node:path";function uRe(){return process.env.CLI_EMBED_ASSET_HASH||"1.0.0-rc.54"}function eOp(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function dRe(){let t=globalThis.__CODELY_EMBEDDED_ASSETS;if(!eOp(t))return null;for(let[e,n]of Object.entries(t))if(typeof e!="string"||typeof n!="string")return null;return t}function QLt(){return dRe()!==null}function qG(t){let e=dRe();return e?e[t]??null:null}function R1(t=""){let e=dRe();if(!e)return[];let n=Object.keys(e);return t?n.filter(r=>r.startsWith(t)):n}function i3e(t="policies/"){let e=dRe();return e?Object.entries(e).filter(([n,r])=>n.startsWith(t)&&n.endsWith(".toml")&&r.length>0).map(([n,r])=>({fileName:n.slice(t.length),filePath:r})).sort((n,r)=>n.fileName.localeCompare(r.fileName)):[]}async function Lsa(t){let e=qG(t);if(!e)throw new Error(`Embedded asset not found: ${t}`);return RK.readFile(e,"utf8")}async function Usa(t){let e=qG(t);if(!e)throw new Error(`Embedded asset not found: ${t}`);let n=await RK.readFile(e);return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}async function a3e(t,e){let n=qG(t);if(!n)throw new Error(`Embedded asset not found: ${t}`);await RK.mkdir(qLt.dirname(e),{recursive:!0});let r=await RK.readFile(n);await RK.writeFile(e,r)}async function bK(t){let{prefix:e,outDir:n,filter:r}=t,o=R1(e),s=0,a=0,c=e.endsWith("/")?e:`${e}/`;for(let l of o){if(!l.startsWith(c))continue;if(r&&!r(l)){a+=1;continue}let u=l.slice(c.length);if(!u)continue;let d=qLt.join(n,u);await a3e(l,d),s+=1}return{written:s,skipped:a}}var fRe=x(()=>{"use strict";f();});function b1(){return globalThis.__CODELY_PACKAGED_EXECUTABLE===!0}var pRe=x(()=>{"use strict";f();});import Fsa from"node:fs/promises";import x3 from"node:path";import{fileURLToPath as tOp}from"node:url";function Gsa(t){return t===c3e?"user":t===l3e?"admin":"default"}function lOp(t){return t.issues.map(e=>` - Field "${e.path.join(".")}": ${e.message}`).join(`
|
|
2986
2986
|
`)}function a8n(t){if(t.length!==0)return t.sort((e,n)=>e.tier!==n.tier?e.tier-n.tier:uw(e.source,n.source)),t[t.length-1].value}async function dOp(t,e){let n=Gsa(e);if(b1()&&e===Hie){let s=i3e("loop-detection-policies/");if(s.length>0)return{files:s}}try{return{files:(await Fsa.readdir(t,{withFileTypes:!0})).filter(c=>c.isFile()&&c.name.endsWith(".toml")).map(c=>({fileName:c.name,filePath:x3.join(t,c.name)})).sort((c,l)=>uw(c.fileName,l.fileName))}}catch(s){let a=s;return a.code==="ENOENT"?{files:[]}:{files:[],error:{filePath:t,fileName:x3.basename(t),tier:n,errorType:"file_read",message:"Failed to read loop-detection policy directory",details:a.message}}}}async function YLt(t){let e=[],n=[],r=[],o=[],s=[],a={tool_cycle_max_period:[],tool_cycle_repeat_count:[],content_probe_repeat_threshold:[],content_probe_min_period_chars:[],tool_call_threshold:[],read_only_tool_call_threshold:[],content_repeat_threshold:[],strike_threshold:[]};for(let{dir:T,tier:C}of t){let b=Gsa(C),N=await dOp(T,C);if(N.error){n.push(N.error);continue}for(let v of N.files){let D=v.filePath,M=v.fileName,w;try{w=await Fsa.readFile(D,"utf-8")}catch(V){let Q=V;n.push({filePath:D,fileName:M,tier:b,errorType:"file_read",message:"Failed to read loop-detection policy file",details:Q.message});continue}let U;try{U=$sa.parse(w)}catch(V){let Q=V;n.push({filePath:D,fileName:M,tier:b,errorType:"toml_parse",message:"TOML parsing failed",details:Q.message});continue}let L=cOp.safeParse(U);if(!L.success){n.push({filePath:D,fileName:M,tier:b,errorType:"schema_validation",message:"Schema validation failed",details:lOp(L.error)});continue}let $=L.data;$.enable_cycle_detection!==void 0&&r.push({tier:C,source:x3.resolve(D),value:$.enable_cycle_detection}),$.judge_system_prompt!==void 0&&o.push({tier:C,source:x3.resolve(D),value:$.judge_system_prompt.trim()}),$.loop_detection_exempt_model!==void 0&&s.push({tier:C,source:x3.resolve(D),value:$.loop_detection_exempt_model});let H=x3.resolve(D);for(let V of Bsa){let Q=$[V];Q!==void 0&&a[V].push({tier:C,source:H,value:Q})}let F=$.loop_detection_rule??[];for(let V=0;V<F.length;V++){let Q=F[V],se=Array.isArray(Q.toolName)?Q.toolName:[Q.toolName];for(let ie of se)e.push({name:Q.name,toolName:ie,action:Q.action,priority:Q.priority,source:x3.resolve(D),tier:C,declarationIndex:V})}}}let c=e,l=!0;r.length>0&&(r.sort((T,C)=>T.tier!==C.tier?T.tier-C.tier:uw(T.source,C.source)),l=r[r.length-1].value);let u=N0e;o.length>0&&(o.sort((T,C)=>T.tier!==C.tier?T.tier-C.tier:uw(T.source,C.source)),u=o[o.length-1].value);let d;s.length>0?(s.sort((T,C)=>T.tier!==C.tier?T.tier-C.tier:uw(T.source,C.source)),d=s[s.length-1].value):d=vPt;let p={};for(let T of Bsa){let C=a8n(a[T]);if(C===void 0)continue;let b=uOp[T];p[b]=C}let h=p.contentProbeMinPeriodChars??vy.contentProbeMinPeriodChars,m=p.contentProbeRepeatThreshold??vy.contentProbeRepeatThreshold;KHe(h,m)||(n.push({filePath:"<merged>",fileName:"content_probe_thresholds",tier:"admin",errorType:"schema_validation",message:`Merged content_probe thresholds exceed probe buffer ${Zq}`,details:`${h} \xD7 ${m} = ${h*m} > ${Zq}`}),delete p.contentProbeMinPeriodChars,delete p.contentProbeRepeatThreshold);let A=a8n(a.tool_cycle_max_period.filter(T=>T.tier>Hie)),g=a8n(a.tool_cycle_repeat_count.filter(T=>T.tier>Hie));A!==void 0&&g!==void 0&&g!==null&&A*g>zb&&(n.push({filePath:"<merged>",fileName:"tool_cycle_thresholds",tier:"admin",errorType:"schema_validation",message:`Merged tool cycle thresholds exceed retained history ${zb}`,details:`${A} \xD7 ${g} = ${A*g} > ${zb}`}),delete p.toolCycleMaxPeriod,delete p.toolCycleRepeatCount);let _=p.toolCycleMaxPeriod??vy.toolCycleMaxPeriod,E=p.toolCycleRepeatCount??vy.toolCycleRepeatCount;if(E!=null&&_*E>zb){let T=Math.floor(zb/E);n.push({filePath:"<merged>",fileName:"tool_cycle_thresholds",tier:"admin",errorType:"schema_validation",message:`Effective tool_cycle_max_period converged to ${T}`,details:`${_} \xD7 ${E} = ${_*E} exceeds the retained history ${zb}; periods above ${T} can never be detected (floor(${zb} / ${E}))`}),p.toolCycleMaxPeriod=T}return{policy:xPt({rules:c,enableCycleDetection:l,judgeSystemPromptTemplate:u,cycleThresholdConfig:p,exemptModels:d}),errors:n}}var $sa,Hie,c3e,l3e,nOp,rOp,oOp,sOp,WLt,ksa,iOp,aOp,cOp,Bsa,uOp,c8n=x(()=>{"use strict";f();$sa=be(xse(),1);_y();O0e();fRe();pRe();Hie=1,c3e=2,l3e=3,nOp=16e3,rOp=/^[a-zA-Z0-9_.-]+\*?$/,oOp=/^[a-zA-Z0-9_.:/-]+\*?$/,sOp=x3.dirname(tOp(import.meta.url)),WLt=x3.join(sOp,"loop-detection-policies"),ksa=he.string().refine(t=>rOp.test(t)?(t.endsWith("*")?t.slice(0,-1):t).length<=63:!1,{message:"Must be a project tool name used as an exact match or with one trailing * wildcard"}),iOp=he.string().refine(t=>{if(!oOp.test(t))return!1;let e=(t.match(/\*/g)??[]).length;if(e>1||e===1&&!t.endsWith("*"))return!1;let n=t.endsWith("*")?t.slice(0,-1):t;return n.length>=1&&n.length<=128},{message:"Must be a model id used as an exact match or with one trailing * wildcard"}),aOp=he.object({name:he.string().optional(),toolName:he.union([ksa,he.array(ksa).min(1)]),action:he.enum(["detect","ignore_as_evidence"]),priority:he.number().int().min(0).max(999)}).strict(),cOp=he.object({version:he.literal(1),enable_cycle_detection:he.boolean().optional(),tool_cycle_max_period:he.number().int().min(2).max(32).optional(),tool_cycle_repeat_count:he.number().int().min(2).max(20).optional(),content_probe_repeat_threshold:he.number().int().min(2).max(20).optional(),content_probe_min_period_chars:he.number().int().min(31).max(2e3).optional(),tool_call_threshold:he.number().int().min(2).max(20).optional(),read_only_tool_call_threshold:he.number().int().min(2).max(20).optional(),content_repeat_threshold:he.number().int().min(2).max(50).optional(),strike_threshold:he.number().int().min(1).max(10).optional(),loop_detection_exempt_model:he.array(iOp).optional(),judge_system_prompt:he.string().trim().min(1).max(nOp).optional(),loop_detection_rule:he.array(aOp).optional()}).strict().superRefine((t,e)=>{if(t.tool_cycle_max_period!==void 0&&t.tool_cycle_repeat_count!==void 0&&t.tool_cycle_max_period*t.tool_cycle_repeat_count>zb&&e.addIssue({code:he.ZodIssueCode.custom,message:`tool_cycle_max_period \xD7 tool_cycle_repeat_count must be \u2264 ${zb} (got ${t.tool_cycle_max_period} \xD7 ${t.tool_cycle_repeat_count} = ${t.tool_cycle_max_period*t.tool_cycle_repeat_count})`,path:["tool_cycle_max_period"]}),t.content_probe_min_period_chars===void 0&&t.content_probe_repeat_threshold===void 0)return;let n=t.content_probe_min_period_chars??vy.contentProbeMinPeriodChars,r=t.content_probe_repeat_threshold??vy.contentProbeRepeatThreshold;KHe(n,r)||e.addIssue({code:he.ZodIssueCode.custom,message:`content_probe_min_period_chars \xD7 content_probe_repeat_threshold must be \u2264 ${Zq} (got ${n} \xD7 ${r} = ${n*r})`,path:["content_probe_min_period_chars"]})});Bsa=["tool_cycle_max_period","tool_cycle_repeat_count","content_probe_repeat_threshold","content_probe_min_period_chars","tool_call_threshold","read_only_tool_call_threshold","content_repeat_threshold","strike_threshold"],uOp={tool_cycle_max_period:"toolCycleMaxPeriod",tool_cycle_repeat_count:"toolCycleRepeatCount",content_probe_repeat_threshold:"contentProbeRepeatThreshold",content_probe_min_period_chars:"contentProbeMinPeriodChars",tool_call_threshold:"toolCallThreshold",read_only_tool_call_threshold:"readOnlyToolCallThreshold",content_repeat_threshold:"contentRepeatThreshold",strike_threshold:"strikeThreshold"}});function hOp(t){return typeof t=="string"?t.trim().length>0:Array.isArray(t)?t.length>0:t&&typeof t=="object"&&"parts"in t?Array.isArray(t.parts)?t.parts.length>0:!0:!!t}function mOp(t){return t===ot.USE_OPENAI||t===ot.QWEN_OAUTH||t===ot.CODELY_OAUTH}var fOp,jsa,pOp,zLt,Vsa=x(()=>{"use strict";f();Rh();q4();yPe();od();LSe();xF();eGe();D9();fOp="respond_in_schema",jsa=128,pOp={temperature:0,maxOutputTokens:jsa,max_completion_tokens:jsa,thinkingConfig:{thinkingBudget:0},reasoning_effort:"minimal",chat_template_kwargs:{enable_thinking:!1,enable_reasoning:!1}};zLt=class{contentGenerator;config;defaultUtilityConfig=pOp;constructor(e,n){this.contentGenerator=e,this.config=n}async generateJson(e){let{contents:n,schema:r,model:o,abortSignal:s,systemInstruction:a,promptId:c,responseToolName:l=fOp,retryOptions:u}=e;if(!hOp(a))throw new Error("generateJson requires an explicit non-empty systemInstruction.");if(!l.trim())throw new Error("generateJson requires a non-empty responseToolName.");let d=e.slotKey??"flashModel",p=this.getUtilityAuthType(d),h=BN(this.config,d,{abortSignal:s,...this.defaultUtilityConfig,...e.config,codely_generate_json:!0,...a&&{systemInstruction:a}});h.tools=this.buildJsonResponseTools(r,l),this.applyJsonToolSelection(h,p,l),Fk(h,this.config.getLitellmConversationId());try{let A=await a_(async()=>(await this.getUtilityContentGenerator(d)).generateContent({model:o,config:h,contents:n},c),{authType:p,abortSignal:s,...u}),g=_U(A),_=g?.find(b=>b.name===l);if(_?.args&&typeof _.args=="object"&&!Array.isArray(_.args))return _.args;let E=lM(A),T=kRt(E);if(T)return T;let C=new Error(`API did not return required ${l} tool call for generateJson.`);throw await EU(C,"Failed to receive required tool call from generateJson.",{originalRequestContents:n,functionCalls:g,responseCandidates:A.candidates},"generateJson-missing-tool-call"),C}catch(m){throw s.aborted?m:(m instanceof Error&&m.message===`API did not return required ${l} tool call for generateJson.`||await EU(m,"Error generating JSON content via API.",n,"generateJson-api"),new Error(`Failed to generate JSON content: ${Ct(m)}`))}}async generateEmbedding(e){if(!e||e.length===0)return[];let n={model:this.config.getEmbeddingModel(),contents:e},r=await this.contentGenerator.embedContent(n);if(!r.embeddings||r.embeddings.length===0)throw new Error("No embeddings found in API response.");if(r.embeddings.length!==e.length)throw new Error(`API returned a mismatched number of embeddings. Expected ${e.length}, got ${r.embeddings.length}.`);return r.embeddings.map((o,s)=>{let a=o.values;if(!a||a.length===0)throw new Error(`API returned an empty embedding for input text at index ${s}: "${e[s]}"`);return a})}applyJsonToolSelection(e,n,r){if(this.shouldUseOpenAICompatibleToolChoice(n)){e.toolChoice="auto";return}e.toolConfig={functionCallingConfig:{mode:"ANY",allowedFunctionNames:[r]}}}shouldUseOpenAICompatibleToolChoice(e){return e!==void 0&&mOp(e)}getUtilityAuthType(e){return this.config.getContentGeneratorSlotAuthType(e)??this.config.getContentGeneratorConfig()?.authType}async getUtilityContentGenerator(e){return this.config.getModelSlotContentGenerator(e)}buildJsonResponseTools(e,n){return[{functionDeclarations:[{name:n,description:"Provide the response in provided schema",parameters:e}]}]}}});function AOp(t,e,n,r,o){if(t.modes&&t.modes.length>0&&!t.modes.includes(o))return!1;if(t.toolName){if(t.toolName.endsWith("__*")){let s=t.toolName.slice(0,-3);if(r!==void 0&&r!==s||!e.name||!e.name.startsWith(s+"__"))return!1}else if(e.name!==t.toolName)return!1}return!(t.argsPattern&&(!e.args||n===void 0||!t.argsPattern.test(n)))}var Hsa,hRe,l8n=x(()=>{"use strict";f();r1();zHe();C9();oq();Hsa=["run_shell_command","ShellTool"];hRe=class{rules;defaultDecision;nonInteractive;approvalMode;enablePermanentToolApproval;constructor(e={}){this.rules=(e.rules??[]).sort((n,r)=>(r.priority??0)-(n.priority??0)),this.defaultDecision=e.defaultDecision??Kr.ASK_USER,this.nonInteractive=e.nonInteractive??!1,this.approvalMode=e.approvalMode??PS.DEFAULT,this.enablePermanentToolApproval=e.enablePermanentToolApproval??!1}setApprovalMode(e){this.approvalMode=e}setDefaultDecision(e){this.defaultDecision=e}getApprovalMode(){return this.approvalMode}shouldPersistToolApproval(){return this.enablePermanentToolApproval}shouldDowngradeForRedirection(e,n){return!n&&hMn(e)&&this.approvalMode!==PS.AUTO_EDIT&&this.approvalMode!==PS.YOLO}shouldDowngradeForCommandSubstitution(e,n){return!n&&!Fre()&&dMn(e)&&this.approvalMode!==PS.AUTO_EDIT&&this.approvalMode!==PS.YOLO}checkShellCommand(e,n,r,o,s,a,c){if(!n)return{decision:this.applyNonInteractiveMode(r),rule:c};let l=xbt(n);if(l.length===0)return r===Kr.DENY?{decision:Kr.DENY,rule:c}:this.approvalMode===PS.YOLO?{decision:Kr.ALLOW,rule:c}:{decision:this.applyNonInteractiveMode(Kr.ASK_USER),rule:c};if(r===Kr.DENY)return{decision:Kr.DENY,rule:c};let u=Obt(n);for(let h of u.denyCandidates){let m=this.check({name:e,args:{command:h}},o);if(m.decision===Kr.DENY&&m.rule?.decision===Kr.DENY)return m}let d=Kr.ALLOW,p;this.shouldDowngradeForRedirection(n,s)&&(d=Kr.ASK_USER,p=void 0),this.shouldDowngradeForCommandSubstitution(n,a)&&(d=Kr.ASK_USER,p=void 0);for(let h of l){let m=h.trim();if(m===n){this.shouldDowngradeForRedirection(m,s)?d===Kr.ALLOW&&(d=Kr.ASK_USER,p=void 0):this.shouldDowngradeForCommandSubstitution(m,a)?d===Kr.ALLOW&&(d=Kr.ASK_USER,p=void 0):r===Kr.ASK_USER&&d===Kr.ALLOW&&(d=Kr.ASK_USER,p=c);continue}let A=this.check({name:e,args:{command:m}},o),g=A.decision;if(g===Kr.DENY)return{decision:Kr.DENY,rule:A.rule};g===Kr.ASK_USER&&(d=Kr.ASK_USER,p||(p=A.rule)),g===Kr.ALLOW&&this.shouldDowngradeForRedirection(m,s)&&d===Kr.ALLOW&&(d=Kr.ASK_USER,p=void 0),g===Kr.ALLOW&&this.shouldDowngradeForCommandSubstitution(m,a)&&d===Kr.ALLOW&&(d=Kr.ASK_USER,p=void 0)}return{decision:this.applyNonInteractiveMode(d),rule:d===r?c:p}}check(e,n){let r;e.args&&this.rules.some(p=>p.argsPattern)&&(r=Xq(e.args));let o=!1,s,a=e.name;a&&Hsa.includes(a)&&(o=!0,s=e.args?.command);let c,l,u=e.name?LRt(e.name):[],d=[];for(let p of u)d.push({...e,name:p}),n&&!p.includes("__")&&d.push({...e,name:`${n}__${p}`});for(let p of this.rules)if(d.some(m=>AOp(p,m,r,n,this.approvalMode)))if(o&&a){let m=this.checkShellCommand(a,s,p.decision,n,p.allowRedirection,p.allowCommandSubstitution,p);l=m.decision,c=m.rule;break}else{l=this.applyNonInteractiveMode(p.decision),c=p;break}if(l===void 0)if(a&&Hsa.includes(a)){let p=this.checkShellCommand(a,s,this.defaultDecision,n);l=p.decision,c=p.rule}else l=this.applyNonInteractiveMode(this.defaultDecision);return{decision:this.applyNonInteractiveMode(l),rule:c}}addRule(e){this.rules.push(e),this.rules.sort((n,r)=>(r.priority??0)-(n.priority??0))}removeRulesForTool(e,n){this.rules=this.rules.filter(r=>r.toolName!==e||n!==void 0&&r.source!==n)}getRules(){return this.rules}hasRuleForTool(e,n=!1){return this.rules.some(r=>r.toolName===e&&(!n||r.source!=="Dynamic (Confirmed)"))}applyNonInteractiveMode(e){return this.nonInteractive&&e===Kr.ASK_USER?Kr.DENY:e}}});import{createHash as gOp,randomUUID as u3e}from"node:crypto";import tf from"node:fs/promises";import nf from"node:path";var mRe,qsa,nI,_Op,u8n,Qsa,d3e,d8n=x(()=>{"use strict";f();Tm();DTe();rGe();mRe=t=>/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(t),qsa=t=>typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>typeof e=="string"?e:e&&typeof e=="object"&&"text"in e&&typeof e.text=="string"?e.text:"").join(`
|
|
2987
2987
|
`).trim():"",nI=t=>{let e=nf.posix.normalize(t.replace(/\\/g,"/"));if(!e||e.startsWith("../")||e===".."||e.startsWith("/"))throw new Error(`Unsafe relative path: ${t}`);return e},_Op=32,u8n=t=>`${gOp("sha256").update(t,"utf8").digest("hex").slice(0,_Op)}.bak`,Qsa=t=>t.replace(/\r\n/g,`
|
|
2988
2988
|
`).replace(/\r/g,`
|
|
@@ -4125,7 +4125,7 @@ ${mi}Configuration:${en}
|
|
|
4125
4125
|
}
|
|
4126
4126
|
}${en}
|
|
4127
4127
|
|
|
4128
|
-
${Vs}\u{1F4A1} Tip: Built-in agents are pre-configured and cannot be modified. Create custom agents using /agents create${en}`})};GIa={name:"agents",description:"Manage and use specialized AI agents for code analysis",kind:"built-in",subCommands:[Ker,pYp,hYp,mYp,fYp,AYp,{name:"enable",description:"Enable a disabled agent. Usage: /agents enable <name>",kind:"built-in",action:gYp},{name:"disable",description:"Disable an agent. Usage: /agents disable <name>",kind:"built-in",action:_Yp},{name:"delete",description:"Delete a custom agent. Usage: /agents delete <name>",kind:"built-in",action:SYp}],action:async t=>{if(Ker.action){let e=await Ker.action(t,"");if(e)return e}return{type:"message",messageType:"info",content:"Use /agents help for available commands"}}}});function Zer(t){return t?.trim()||void 0}async function TYp(t){let e=[];try{let n=await rf(t);for(let r of n)if(!(!r.agents||r.agents.length===0))for(let o of r.agents)e.push({name:o.name,filePath:r.path,rootDir:"",source:`extension:${r.config.name}`,...Zer(o.description)?{description:o.description}:{}})}catch{}return e}function yYp(t){let e=[];for(let n of t)n.metadata?.scope==="builtin"&&e.push({name:n.name,filePath:n.metadata?.source??"",rootDir:"",source:"builtin",...Zer(n.description)?{description:n.description}:{}});return e}async function CYp(t,e){try{return await new gO(t).loadAllAgents({includeBuiltin:e})}catch{return[]}}function RYp(t,e){let n=new Map(e.map(r=>[r.name,r]));for(let r of t){let o=Zer(n.get(r.name)?.description);o&&(r.description=o)}}function bYp(t){return t.replace(/\s+/g," ").trim()}function IYp(t,e){let r=e.has(t.name)?"[disabled]":"[enabled]";console.log(`- ${t.name} ${r} (${t.source})`),console.log(` Path: ${t.filePath}`),t.description&&console.log(` Description: ${bYp(t.description)}`),console.log("")}function NYp(t){let e=new Set,n=[];for(let r of t)for(let o of r)e.has(o.name)||(n.push(o),e.add(o.name));return n}async function OYp(t){let e=process.cwd(),n=qi(e),r=new Set(n.merged.agents?.disabled??[]),o=await oce(e,void 0),s=!!t["in-agents-dir"],a=await CYp(e,!s);RYp(o,a);let c=s?o:NYp([o,await TYp(e),yYp(a)]);if(c.length===0){console.log("No agents discovered."),process.exit(0);return}console.log("Discovered agents:");for(let l of c)IYp(l,r);process.exit(0)}var jIa,VIa=x(()=>{"use strict";f();Gs();$$t();hA();zt();jIa={command:"list",describe:"Lists all discovered agents (file, extension, and builtin agents).",builder:t=>t.option("all",{type:"boolean",description:"Show all agents (reserved for future use).",default:!1}).option("in-agents-dir",{type:"boolean",description:"Only list agents from TOML files in agents directories (excludes extension and builtin agents).",default:!1}),handler:async t=>{await OYp({all:t.all,"in-agents-dir":t["in-agents-dir"]})}}});async function vYp(t){let{name:e,scope:n}=t,r=process.cwd(),o=qi(r),s=n==="User"||n==="Workspace"?[n]:["Workspace","User"],a=!1;for(let l of s){let u=o.forScope(l).settings,d=u.agents?.disabled??[];if(!d.includes(e))continue;let p=d.filter(m=>m!==e),h={...u.agents??{},disabled:p};o.setValue(l,"agents",h),a=!0}a||(console.log(`Agent "${e}" is already enabled.`),process.exit(0)),console.log(`Enabled agent "${e}" in ${n||"all scopes"}.`),process.exit(0)}var HIa,qIa=x(()=>{"use strict";f();Gs();HIa={command:"enable <name> [--scope]",describe:"Enables an agent.",builder:t=>t.positional("name",{describe:"The name of the agent to enable.",type:"string",demandOption:!0}).option("scope",{alias:"s",describe:"The scope to enable the agent in (user or workspace). Default: both.",type:"string",choices:["user","workspace"]}),handler:async t=>{let e=t.scope==="workspace"?"Workspace":t.scope==="user"?"User":void 0;await vYp({name:t.name,scope:e})}}});async function xYp(t){let{name:e,scope:n}=t,r=process.cwd(),o=qi(r),s=o.forScope(n).settings,a=s.agents?.disabled??[];a.includes(e)&&(console.log(`Agent "${e}" is already disabled in ${n} scope.`),process.exit(0));let c=[...a,e],l={...s.agents??{},disabled:c};o.setValue(n,"agents",l),console.log(`Disabled agent "${e}" in ${n} scope.`),process.exit(0)}var QIa,WIa=x(()=>{"use strict";f();Gs();QIa={command:"disable <name> [--scope]",describe:"Disables an agent.",builder:t=>t.positional("name",{describe:"The name of the agent to disable.",type:"string",demandOption:!0}).option("scope",{alias:"s",describe:"The scope to disable the agent in (user or workspace).",type:"string",default:"workspace",choices:["user","workspace"]}),handler:async t=>{let e=t.scope==="workspace"?"Workspace":"User";await xYp({name:t.name,scope:e})}}});async function PYp(t,e){try{let n=await rf(t);for(let r of n)if(!(!r.agents||r.agents.length===0)){for(let o of r.agents)if(o.name===e)return r.config.name}}catch{}return null}async function MYp(t){try{return(await new gO(process.cwd()).loadAllAgents({includeBuiltin:!0})).some(r=>r.name===t&&r.metadata?.scope==="builtin")}catch{return!1}}async function DYp(t){let e=process.cwd(),n=t.name,r=await oce(e,void 0),o=t.path?.trim(),s;if(o){let a=r.find(c=>c.filePath===o);a||(console.error(`Path "${o}" does not match any discovered agent file. Use "codely agents list" to see valid paths.`),process.exit(1)),s=a.rootDir}else{let a=r.filter(c=>c.name===n);if(a.length===0){let c=await PYp(e,n);c?console.error(`Agent "${n}" belongs to extension "${c}" and cannot be deleted directly. Use "codely extensions uninstall ${c}" to remove the extension, or "codely agents disable ${n}" to disable it.`):await MYp(n)?console.error(`Agent "${n}" is a builtin agent and cannot be deleted. Use "codely agents disable ${n}" to disable it.`):console.error(`Agent "${n}" not found.`),process.exit(1)}a.length>1&&(console.error(`Multiple agents named "${n}" found. Please pass --path to disambiguate.`),process.exit(1)),o=a[0].filePath,s=a[0].rootDir}try{if(s)await ZK(o,s);else{let{promises:a}=await import("node:fs");await a.unlink(o)}console.log(`Deleted agent "${n}" at ${o}.`),process.exit(0)}catch(a){console.error(`Failed to delete agent "${n}" at ${o}: ${a instanceof Error?a.message:String(a)}`),process.exit(1)}}var YIa,zIa=x(()=>{"use strict";f();$$t();hA();zt();l4e();YIa={command:"delete <name> [--path]",describe:"Deletes an agent TOML file from agents directories.",builder:t=>t.positional("name",{describe:"The name of the agent to delete.",type:"string",demandOption:!0}).option("path",{describe:"The full file path of the agent to delete (useful if names collide).",type:"string"}),handler:async t=>{await DYp({name:t.name,path:t.path})}}});var KIa,JIa=x(()=>{"use strict";f();VIa();qIa();WIa();zIa();KIa={command:"agents <command>",aliases:["agent"],describe:"Manage agents.",builder:t=>t.command(jIa).command(HIa).command(QIa).command(YIa).demandCommand(1,"You need at least one command before continuing.").version(!1),handler:()=>{}}});import{fileURLToPath as wYp}from"url";import*as vIe from"path";import*as XIa from"fs";function UYp(t){if(!t||typeof t!="object")return!1;let e=t.bin;if(!e)return!1;if(typeof e=="string")return!0;if(typeof e=="object"){let n=e.codely;return typeof n=="string"&&n.length>0}return!1}function kYp(t){if(!t||typeof t!="object")return!1;let{name:e,version:n}=t;return typeof e=="string"&&new Set(["@codely/cli","@codely/codely-cli","@unity-china/codely-cli","@unity-china/cli"]).has(e)||UYp(t)?!0:typeof e=="string"&&typeof n=="string"}async function BYp(t){try{let e=await XIa.promises.readFile(t,"utf-8"),n=JSON.parse(e);return kYp(n)?n:null}catch{return null}}async function tB(){if(OIe)return OIe;let t=[vIe.resolve(etr,"../../package.json"),vIe.resolve(etr,"../package.json"),vIe.resolve(etr,"../../../../package.json")];for(let e of t){let n=await BYp(e);if(n)return OIe=n,OIe}return OIe={name:"@codely/codely-cli",version:"1.0.0-rc.53"},OIe}var LYp,etr,OIe,sce=x(()=>{"use strict";f();LYp=wYp(import.meta.url),etr=vIe.dirname(LYp)});async function nB(){let t=await tB();return"1.0.0-rc.53"}var xIe=x(()=>{"use strict";f();sce();});var oNa=I((m8g,rtr)=>{"use strict";f();var eNa=ge("child_process").exec,tNa=ge("child_process").execSync,G$t=ge("fs"),ZIa=ge("path"),nNa=G$t.access,rNa=G$t.accessSync,PIe=G$t.constants||G$t,ttr=process.platform=="win32",FYp=function(t,e){nNa(t,PIe.F_OK,function(n){e(!n)})},$Yp=function(t){try{return rNa(t,PIe.F_OK),!1}catch{return!0}},GYp=function(t,e){nNa(t,PIe.F_OK|PIe.X_OK,function(n){e(null,!n)})},jYp=function(t){try{return rNa(t,PIe.F_OK|PIe.X_OK),!0}catch{return!1}},VYp=function(t,e,n){FYp(t,function(r){if(!r){var o=eNa("command -v "+e+" 2>/dev/null && { echo >&1 "+e+"; exit 0; }",function(s,a,c){n(null,!!a)});return}GYp(t,n)})},HYp=function(t,e,n){if(!/^(?!(?:.*\s|.*\.|\W+)$)(?:[a-zA-Z]:)?(?:(?:[^<>:"\|\?\*\n])+(?:\/\/|\/|\\\\|\\)?)+$/m.test(t)){n(null,!1);return}var r=eNa("where "+e,function(o){o!==null?n(null,!1):n(null,!0)})},qYp=function(t,e){if($Yp(t))try{var n=tNa("command -v "+e+" 2>/dev/null && { echo >&1 "+e+"; exit 0; }");return!!n}catch{return!1}return jYp(t)},QYp=function(t,e,n){if(!/^(?!(?:.*\s|.*\.|\W+)$)(?:[a-zA-Z]:)?(?:(?:[^<>:"\|\?\*\n])+(?:\/\/|\/|\\\\|\\)?)+$/m.test(t))return!1;try{var r=tNa("where "+e,{stdio:[]});return!!r}catch{return!1}},ntr=function(t){return/[^A-Za-z0-9_\/:=-]/.test(t)&&(t="'"+t.replace(/'/g,"'\\''")+"'",t=t.replace(/^(?:'')+/g,"").replace(/\\'''/g,"\\'")),t};ttr&&(ntr=function(t){var e=/[\\]/.test(t);if(e){var n='"'+ZIa.dirname(t)+'"',r='"'+ZIa.basename(t)+'"';return n+":"+r}return'"'+t+'"'});rtr.exports=function t(e,n){var r=ntr(e);if(!n&&typeof Promise<"u")return new Promise(function(o,s){t(e,function(a,c){c?o(e):s(a)})});ttr?HYp(e,r,n):VYp(e,r,n)};rtr.exports.sync=function(t){var e=ntr(t);return ttr?QYp(t,e):qYp(t,e)}});var iNa=I((g8g,sNa)=>{f();sNa.exports=oNa()});import*as aNa from"node:os";function WYp(t){return cNa.includes(t)}function YYp(t){if(process.env.SANDBOX)return"";let e=process.env.GEMINI_SANDBOX?.toLowerCase().trim()??"";if(t=e?.length>0?e:t,t==="1"||t==="true"?t=!0:(t==="0"||t==="false"||!t)&&(t=!1),t===!1)return"";if(typeof t=="string"&&t){if(WYp(t)||(console.error(`ERROR: invalid sandbox command '${t}'. Must be one of ${cNa.join(", ")}`),process.exit(1)),uWe.default.sync(t))return t;console.error(`ERROR: missing sandbox command '${t}' (from GEMINI_SANDBOX)`),process.exit(1)}return aNa.platform()==="darwin"&&uWe.default.sync("sandbox-exec")?"sandbox-exec":uWe.default.sync("docker")&&t===!0?"docker":uWe.default.sync("podman")&&t===!0?"podman":(t===!0&&(console.error("ERROR: GEMINI_SANDBOX is true but failed to determine command for sandbox; install docker or podman or specify command in GEMINI_SANDBOX"),process.exit(1)),"")}async function lNa(t,e){let n=e.sandbox??t.sandbox,r=YYp(n),o=await tB(),s=e.sandboxImage??process.env.GEMINI_SANDBOX_IMAGE??o?.config?.sandboxImageUri;return r&&s?{command:r,image:s}:void 0}var uWe,cNa,uNa=x(()=>{"use strict";f();uWe=be(iNa(),1);sce();cNa=["docker","podman","sandbox-exec"]});import*as otr from"os";import*as dNa from"path";function str(t){if(!t)return"";let e=t;return t.toLowerCase().startsWith("%userprofile%")?e=otr.homedir()+t.substring(13):(t==="~"||t.startsWith("~/"))&&(e=otr.homedir()+t.substring(1)),dNa.normalize(e)}var fNa=x(()=>{"use strict";f();});import*as ice from"node:fs";import{promises as pNa}from"node:fs";import*as y7 from"node:path";import{fileURLToPath as zYp}from"node:url";function atr(){let t=globalThis.__dirname;if(t)return y7.join(t,"example-prompts");let e=CBt(),n=y7.join(e,"bundle","example-prompts");return ice.existsSync(n)?n:y7.join(JYp,"../../example-prompts")}function XYp(){return R1("example-prompts/").filter(t=>t.endsWith(".toml"))}function j$t(){let t=XYp();if(t.length>0)return t.map(n=>n.slice(16).replace(/\.toml$/,"")).filter(Boolean).sort();let e=atr();try{return ice.readdirSync(e).filter(r=>r.endsWith(".toml")).map(r=>r.replace(/\.toml$/,"")).filter(Boolean).sort()}catch{return[]}}async function ZYp(t){let e=`example-prompts/${t}.toml`,n=qG(e);if(n)return pNa.readFile(n,"utf8");let r=atr(),o=y7.join(r,`${t}.toml`);return pNa.readFile(o,"utf8")}function e5p(t){let e=`example-prompts/${t}.toml`,n=qG(e);if(n)return ice.readFileSync(n,"utf8");let r=atr(),o=y7.join(r,`${t}.toml`);return ice.readFileSync(o,"utf8")}async function MIe(t){let e=await ZYp(t);return itr.default.parse(e)}function hNa(t){let e=e5p(t);return itr.default.parse(e)}async function V$t(){let t=j$t(),e=[];for(let n of t)try{let r=await MIe(n);e.push({name:n,description:r.description||"No description available"})}catch{e.push({name:n,description:"Example prompt"})}return e}var itr,KYp,JYp,H$t=x(()=>{"use strict";f();itr=be(xse(),1);dj();s4e();KYp=zYp(import.meta.url),JYp=y7.dirname(KYp)});function q$t(t=process.env){let e=t[t5p];return e==="1"||e?.toLowerCase()==="true"}function ctr(t){let e=t.trim().toLowerCase();return n5p.includes(e)||e.startsWith("codely-unity-")}var t5p,n5p,ltr=x(()=>{"use strict";f();t5p="CODELY_CLI_DISABLE_UNITY_INTEGRATION",n5p=["codely-unity-lsp-server"]});import*as dQ from"fs";import*as uQ from"path";import{homedir as r5p}from"os";function dtr(){let t=[],e={},n=a5p;try{if(dQ.existsSync(n)){let r=dQ.readFileSync(n,"utf-8"),o=JSON.parse((0,mNa.default)(r));o&&Object.assign(e,o)}}catch(r){t.push({message:Ct(r),path:n})}return new utr({path:n,config:e},t)}function c5p(t){try{let e=uQ.dirname(t.path);dQ.existsSync(e)||dQ.mkdirSync(e,{recursive:!0}),dQ.writeFileSync(t.path,JSON.stringify(t.config,null,2),"utf-8")}catch(e){console.error("Error saving trusted folders file:",e)}}function ANa(){let{rules:t,errors:e}=dtr();if(e.length>0)for(let s of e)console.error(`Error loading trusted folders config from ${s.path}: ${s.message}`);let n=[],r=[];for(let s of t)switch(s.trustLevel){case"TRUST_FOLDER":n.push(s.path);break;case"TRUST_PARENT":n.push(uQ.dirname(s.path));break;case"DO_NOT_TRUST":r.push(s.path);break;default:break}let o=process.cwd();for(let s of n)if(aPe(o,s))return!0;for(let s of r)if(uQ.normalize(o)===uQ.normalize(s))return!1}var mNa,o5p,s5p,i5p,a5p,utr,ftr=x(()=>{"use strict";f();zt();mNa=be(lzn(),1);o5p="trustedFolders.json",s5p=".codely-cli",i5p=uQ.join(r5p(),s5p),a5p=uQ.join(i5p,o5p),utr=class{constructor(e,n){this.user=e;this.errors=n}get rules(){return Object.entries(this.user.config).map(([e,n])=>({path:e,trustLevel:n}))}setValue(e,n){this.user.config[e]=n,c5p(this.user)}}});function vj(){return process.env[l5p]==="1"}function Q$t(){return u5p}var l5p,u5p,DIe=x(()=>{"use strict";f();l5p="CODELY_CLI_INTERNAL_DISABLE_AUTO_UPDATE",u5p="Update disabled: CODELY_CLI_INTERNAL_DISABLE_AUTO_UPDATE=1 is set. Unset it to check for updates."});function gNa(){return process.env.CODELY_CLI_ENV==="dev"?"http://localhost:8000":"https://codely.tuanjie.cn"}var _Na=x(()=>{"use strict";f()});import ptr from"os";function d5p(t){if(!t)return null;let e=t.trim().toLowerCase();return e==="api"||e==="server"?"api":e==="npm"||e==="registry"?"npm":null}function f5p(t){if(t.startsWith("@")){let e=t.split("/");if(e.length===2&&e[0]&&e[1])return`${e[0]}%2F${e[1]}`}return t}async function p5p(t){try{let n=`https://registry.npmjs.org/${f5p(t)}/latest`,r=new AbortController,o=setTimeout(()=>r.abort(),ENa),s=await fetch(n,{method:"GET",headers:{accept:"application/json"},signal:r.signal});return clearTimeout(o),s.ok&&(await s.json()).version||null}catch(e){return console.warn("Failed to fetch latest version from npm registry:",e),null}}async function h5p(){try{let t=ptr.platform()==="win32"?"win32":ptr.platform(),e=ptr.arch(),o=`${gNa()}/api/plugin/version?platform=${t}&architecture=${e}&plugin_name=codely-cli&is_binary=${q1()}`,s=new AbortController,a=setTimeout(()=>s.abort(),ENa),c=await fetch(o,{method:"GET",headers:{accept:"application/json"},signal:s.signal});return clearTimeout(a),c.ok?await c.json():null}catch(t){return console.warn("Failed to fetch version from API:",t),null}}async function wIe(){try{if(process.env.DEV==="true"||vj())return null;let t=await nB();if(!t||t==="unknown")return null;let n=(await tB())?.name;if((d5p(process.env.CODELY_CLI_UPDATE_SOURCE)||(n&&n.startsWith("@unity-china/")?"npm":"api"))==="npm"){if(!n)return null;let c=await p5p(n);if(!c)return null;if(W$t.default.gt(c,t)){let l=W$t.default.diff(t,c)||"major";return{message:`Codely Cli update available! ${t} \u2192 ${c}`,update:{current:t,latest:c,type:l,name:n}}}return null}let s=await h5p();if(!s||!s.active)return null;let a=s.version;if(W$t.default.gt(a,t)){let c=`Codely Cli update available! ${t} \u2192 ${a}`,l={current:t,latest:a,type:"major",name:n??s.name,downloadUrl:s.download_url};return{message:c,update:l}}return null}catch(t){return console.warn("Failed to check for updates: "+t),null}}var W$t,ENa,Y$t=x(()=>{"use strict";f();W$t=be(vZ(),1);DIe();sce();dj();xIe();_Na();ENa=2e3});var C7=x(()=>{"use strict";f();_s();});var YC,TNa,SNa,htr,lP,yNa=x(()=>{"use strict";f();YC=be(sn(),1);zt();TNa=be(st(),1);SNa=(0,YC.createContext)(void 0),htr=({children:t})=>{let[e,n]=(0,YC.useState)(()=>({sessionStartTime:new Date,metrics:Rs.getMetrics(),totalRequestTokens:Rs.getTotalRequestTokens(),modelTokenLimit:Rs.getModelTokenLimit(),promptCount:0})),r=(0,YC.useRef)(null);if(r.current===null){let l=({metrics:u,totalRequestTokens:d,modelTokenLimit:p})=>{n(h=>({...h,metrics:u??h.metrics,totalRequestTokens:d??h.totalRequestTokens,modelTokenLimit:p??h.modelTokenLimit}))};r.current=l,Rs.on("update",l)}(0,YC.useEffect)(()=>(n(l=>({...l,metrics:Rs.getMetrics(),totalRequestTokens:Rs.getTotalRequestTokens(),modelTokenLimit:Rs.getModelTokenLimit()})),()=>{r.current&&(Rs.off("update",r.current),r.current=null)}),[]);let o=(0,YC.useCallback)(()=>{n(l=>({...l,promptCount:l.promptCount+1}))},[]),s=(0,YC.useCallback)(()=>e.promptCount,[e.promptCount]),a=(0,YC.useCallback)(()=>{n({sessionStartTime:new Date,metrics:Rs.getMetrics(),totalRequestTokens:Rs.getTotalRequestTokens(),modelTokenLimit:Rs.getModelTokenLimit(),promptCount:0})},[]),c=(0,YC.useMemo)(()=>({stats:e,startNewPrompt:o,getPromptCount:s,resetSession:a}),[e,o,s,a]);return(0,TNa.jsx)(SNa.Provider,{value:c,children:t})},lP=()=>{let t=(0,YC.useContext)(SNa);if(t===void 0)throw new Error("useSessionStats must be used within a SessionStatsProvider");return t}});var MO,mtr,CNa,RNa,Atr,gtr,_tr,dWe=x(()=>{"use strict";f();MO=be(sn(),1),mtr=be(st(),1);CNa=(0,MO.createContext)(void 0),RNa=(0,MO.createContext)(void 0),Atr=()=>(0,MO.useContext)(CNa),gtr=()=>(0,MO.useContext)(RNa),_tr=({children:t})=>{let[e,n]=(0,MO.useState)(new Set),r=(0,MO.useCallback)(c=>{n(l=>{if(l.has(c))return l;let u=new Set(l);return u.add(c),u})},[]),o=(0,MO.useCallback)(c=>{n(l=>{if(!l.has(c))return l;let u=new Set(l);return u.delete(c),u})},[]),s=(0,MO.useMemo)(()=>({overflowingIds:e}),[e]),a=(0,MO.useMemo)(()=>({addOverflowingId:r,removeOverflowingId:o}),[r,o]);return(0,mtr.jsx)(CNa.Provider,{value:s,children:(0,mtr.jsx)(RNa.Provider,{value:a,children:t})})}});var z$t,K$t,Etr,J$t=x(()=>{"use strict";f();z$t=be(sn(),1);K$t=z$t.default.createContext(void 0),Etr=()=>{let t=(0,z$t.useContext)(K$t);if(t===void 0)throw new Error("useSettings must be used within a SettingsProvider");return t}});var X$t,fWe,fQ,ace=x(()=>{"use strict";f();X$t=be(sn(),1);fWe=(0,X$t.createContext)(void 0),fQ=()=>{let t=X$t.default.useContext(fWe);if(t===void 0)throw new Error("useStreamingContext must be used within a StreamingContextProvider");return t}});var rB,INa,bNa,Str,cce,pWe=x(()=>{"use strict";f();rB=be(sn(),1);Gs();INa=be(st(),1);bNa=(0,rB.createContext)(void 0),Str=({children:t,settings:e})=>{let n=e.merged.vimMode??!1,[r,o]=(0,rB.useState)(n),[s,a]=(0,rB.useState)(n?"NORMAL":"INSERT");(0,rB.useEffect)(()=>{let u=e.merged.vimMode??!1;o(u),u&&a("NORMAL")},[e.merged.vimMode]);let c=(0,rB.useCallback)(async()=>{let u=!r;return o(u),u&&a("NORMAL"),await e.setValue("User","vimMode",u),u},[r,e]),l={vimEnabled:r,vimMode:s,toggleVimEnabled:c,setVimMode:a};return(0,INa.jsx)(bNa.Provider,{value:l,children:t})},cce=()=>{let t=(0,rB.useContext)(bNa);if(t===void 0)throw new Error("useVimMode must be used within a VimModeProvider");return t}});var R7=x(()=>{"use strict";f();yNa();dWe();J$t();ace();pWe();});function Ttr(){let[t,e]=(0,oB.useState)([]),n=(0,oB.useRef)(0),r=(0,oB.useCallback)(u=>(n.current+=1,u+n.current),[]),o=(0,oB.useCallback)(u=>{e(u)},[]),s=(0,oB.useCallback)((u,d)=>{let p=r(d),h={...u,id:p};return e(m=>{if(m.length>0){let A=m[m.length-1];if(A.type==="user"&&h.type==="user"&&A.text===h.text)return m}return[...m,h]}),p},[r]),a=(0,oB.useCallback)((u,d)=>{e(p=>p.map(h=>{if(h.id===u){let m=typeof d=="function"?d(h):d;return{...h,...m}}return h}))},[]),c=(0,oB.useCallback)(u=>{if(u.length===0)return;let d=new Set(u);e(p=>p.filter(h=>!d.has(h.id)))},[]),l=(0,oB.useCallback)(()=>{e([]),n.current=0},[]);return{history:t,addItem:s,updateItem:a,removeItems:c,clearItems:l,loadHistory:o}}var oB,NNa=x(()=>{"use strict";f();oB=be(sn(),1);});var LIe,ytr,Ctr=x(()=>{"use strict";f();LIe=be(sn(),1);ca();zt();ytr=(t,e,n)=>{let[r,o]=(0,LIe.useState)(!1),s=(0,LIe.useCallback)(()=>{o(!0)},[]),a=(0,LIe.useCallback)((l,u)=>{if(!(l&&(!h0e(l)||!m0e(l))))try{t.setValue(u,"preferredEditor",l),n({type:"info",text:`Editor preference ${l?`set to "${l}"`:"cleared"} in ${u} settings.`},Date.now()),e(null),o(!1)}catch(d){e(`Failed to set editor preference: ${d}`)}},[t,e,n]),c=(0,LIe.useCallback)(()=>{o(!1)},[]);return{isEditorDialogOpen:r,openEditorDialog:s,handleEditorSelect:a,exitEditorDialog:c}}});function ONa(t){let e=t.getGeminiClient().getContentGenerator();if(e instanceof ZV){if(!e.projectId)throw new Error("Oauth not being used")}else throw new Error("Oauth not being used");return e}async function m5p(t){let e=await t.loadCodeAssist({cloudaicompanionProject:t.projectId,metadata:{ideType:"IDE_UNSPECIFIED",platform:"PLATFORM_UNSPECIFIED",pluginType:"GEMINI",duetProject:t.projectId}});if(!e.currentTier)throw new Error("User does not have a current tier");return e.currentTier.id}async function A5p(t){try{return(await t.getCodeAssistGlobalUserSetting()).freeTierDataCollectionOptin}catch(e){if(e&&typeof e=="object"&&"response"in e&&e.response?.status===404)return!0;throw e}}async function g5p(t,e){return(await t.setCodeAssistGlobalUserSetting({cloudaicompanionProject:t.projectId,freeTierDataCollectionOptin:e})).freeTierDataCollectionOptin}var UIe,Rtr,btr=x(()=>{"use strict";f();UIe=be(sn(),1);zt();Rtr=t=>{let[e,n]=(0,UIe.useState)({isLoading:!0});(0,UIe.useEffect)(()=>{(async()=>{n({isLoading:!0});try{let s=ONa(t);if(await m5p(s)!==b0.FREE){n({isLoading:!1,isFreeTier:!1});return}let c=await A5p(s);n({isLoading:!1,isFreeTier:!0,dataCollectionOptIn:c})}catch(s){n({isLoading:!1,error:s instanceof Error?s.message:String(s)})}})()},[t]);let r=(0,UIe.useCallback)(async o=>{try{let s=ONa(t),a=await g5p(s,o);n({isLoading:!1,isFreeTier:!0,dataCollectionOptIn:a})}catch(s){n({isLoading:!1,error:s instanceof Error?s.message:String(s)})}},[t]);return{privacyState:e,updateDataCollectionOptIn:r}}});var Itr=x(()=>{"use strict";f();});function xNa(t){return t>=32&&t!==127&&t<=1114111&&(t<57344||t>63743)}function y5p(t){return t.name==="enter"?{...t,name:"return"}:!t.name&&(t.sequence===`
|
|
4128
|
+
${Vs}\u{1F4A1} Tip: Built-in agents are pre-configured and cannot be modified. Create custom agents using /agents create${en}`})};GIa={name:"agents",description:"Manage and use specialized AI agents for code analysis",kind:"built-in",subCommands:[Ker,pYp,hYp,mYp,fYp,AYp,{name:"enable",description:"Enable a disabled agent. Usage: /agents enable <name>",kind:"built-in",action:gYp},{name:"disable",description:"Disable an agent. Usage: /agents disable <name>",kind:"built-in",action:_Yp},{name:"delete",description:"Delete a custom agent. Usage: /agents delete <name>",kind:"built-in",action:SYp}],action:async t=>{if(Ker.action){let e=await Ker.action(t,"");if(e)return e}return{type:"message",messageType:"info",content:"Use /agents help for available commands"}}}});function Zer(t){return t?.trim()||void 0}async function TYp(t){let e=[];try{let n=await rf(t);for(let r of n)if(!(!r.agents||r.agents.length===0))for(let o of r.agents)e.push({name:o.name,filePath:r.path,rootDir:"",source:`extension:${r.config.name}`,...Zer(o.description)?{description:o.description}:{}})}catch{}return e}function yYp(t){let e=[];for(let n of t)n.metadata?.scope==="builtin"&&e.push({name:n.name,filePath:n.metadata?.source??"",rootDir:"",source:"builtin",...Zer(n.description)?{description:n.description}:{}});return e}async function CYp(t,e){try{return await new gO(t).loadAllAgents({includeBuiltin:e})}catch{return[]}}function RYp(t,e){let n=new Map(e.map(r=>[r.name,r]));for(let r of t){let o=Zer(n.get(r.name)?.description);o&&(r.description=o)}}function bYp(t){return t.replace(/\s+/g," ").trim()}function IYp(t,e){let r=e.has(t.name)?"[disabled]":"[enabled]";console.log(`- ${t.name} ${r} (${t.source})`),console.log(` Path: ${t.filePath}`),t.description&&console.log(` Description: ${bYp(t.description)}`),console.log("")}function NYp(t){let e=new Set,n=[];for(let r of t)for(let o of r)e.has(o.name)||(n.push(o),e.add(o.name));return n}async function OYp(t){let e=process.cwd(),n=qi(e),r=new Set(n.merged.agents?.disabled??[]),o=await oce(e,void 0),s=!!t["in-agents-dir"],a=await CYp(e,!s);RYp(o,a);let c=s?o:NYp([o,await TYp(e),yYp(a)]);if(c.length===0){console.log("No agents discovered."),process.exit(0);return}console.log("Discovered agents:");for(let l of c)IYp(l,r);process.exit(0)}var jIa,VIa=x(()=>{"use strict";f();Gs();$$t();hA();zt();jIa={command:"list",describe:"Lists all discovered agents (file, extension, and builtin agents).",builder:t=>t.option("all",{type:"boolean",description:"Show all agents (reserved for future use).",default:!1}).option("in-agents-dir",{type:"boolean",description:"Only list agents from TOML files in agents directories (excludes extension and builtin agents).",default:!1}),handler:async t=>{await OYp({all:t.all,"in-agents-dir":t["in-agents-dir"]})}}});async function vYp(t){let{name:e,scope:n}=t,r=process.cwd(),o=qi(r),s=n==="User"||n==="Workspace"?[n]:["Workspace","User"],a=!1;for(let l of s){let u=o.forScope(l).settings,d=u.agents?.disabled??[];if(!d.includes(e))continue;let p=d.filter(m=>m!==e),h={...u.agents??{},disabled:p};o.setValue(l,"agents",h),a=!0}a||(console.log(`Agent "${e}" is already enabled.`),process.exit(0)),console.log(`Enabled agent "${e}" in ${n||"all scopes"}.`),process.exit(0)}var HIa,qIa=x(()=>{"use strict";f();Gs();HIa={command:"enable <name> [--scope]",describe:"Enables an agent.",builder:t=>t.positional("name",{describe:"The name of the agent to enable.",type:"string",demandOption:!0}).option("scope",{alias:"s",describe:"The scope to enable the agent in (user or workspace). Default: both.",type:"string",choices:["user","workspace"]}),handler:async t=>{let e=t.scope==="workspace"?"Workspace":t.scope==="user"?"User":void 0;await vYp({name:t.name,scope:e})}}});async function xYp(t){let{name:e,scope:n}=t,r=process.cwd(),o=qi(r),s=o.forScope(n).settings,a=s.agents?.disabled??[];a.includes(e)&&(console.log(`Agent "${e}" is already disabled in ${n} scope.`),process.exit(0));let c=[...a,e],l={...s.agents??{},disabled:c};o.setValue(n,"agents",l),console.log(`Disabled agent "${e}" in ${n} scope.`),process.exit(0)}var QIa,WIa=x(()=>{"use strict";f();Gs();QIa={command:"disable <name> [--scope]",describe:"Disables an agent.",builder:t=>t.positional("name",{describe:"The name of the agent to disable.",type:"string",demandOption:!0}).option("scope",{alias:"s",describe:"The scope to disable the agent in (user or workspace).",type:"string",default:"workspace",choices:["user","workspace"]}),handler:async t=>{let e=t.scope==="workspace"?"Workspace":"User";await xYp({name:t.name,scope:e})}}});async function PYp(t,e){try{let n=await rf(t);for(let r of n)if(!(!r.agents||r.agents.length===0)){for(let o of r.agents)if(o.name===e)return r.config.name}}catch{}return null}async function MYp(t){try{return(await new gO(process.cwd()).loadAllAgents({includeBuiltin:!0})).some(r=>r.name===t&&r.metadata?.scope==="builtin")}catch{return!1}}async function DYp(t){let e=process.cwd(),n=t.name,r=await oce(e,void 0),o=t.path?.trim(),s;if(o){let a=r.find(c=>c.filePath===o);a||(console.error(`Path "${o}" does not match any discovered agent file. Use "codely agents list" to see valid paths.`),process.exit(1)),s=a.rootDir}else{let a=r.filter(c=>c.name===n);if(a.length===0){let c=await PYp(e,n);c?console.error(`Agent "${n}" belongs to extension "${c}" and cannot be deleted directly. Use "codely extensions uninstall ${c}" to remove the extension, or "codely agents disable ${n}" to disable it.`):await MYp(n)?console.error(`Agent "${n}" is a builtin agent and cannot be deleted. Use "codely agents disable ${n}" to disable it.`):console.error(`Agent "${n}" not found.`),process.exit(1)}a.length>1&&(console.error(`Multiple agents named "${n}" found. Please pass --path to disambiguate.`),process.exit(1)),o=a[0].filePath,s=a[0].rootDir}try{if(s)await ZK(o,s);else{let{promises:a}=await import("node:fs");await a.unlink(o)}console.log(`Deleted agent "${n}" at ${o}.`),process.exit(0)}catch(a){console.error(`Failed to delete agent "${n}" at ${o}: ${a instanceof Error?a.message:String(a)}`),process.exit(1)}}var YIa,zIa=x(()=>{"use strict";f();$$t();hA();zt();l4e();YIa={command:"delete <name> [--path]",describe:"Deletes an agent TOML file from agents directories.",builder:t=>t.positional("name",{describe:"The name of the agent to delete.",type:"string",demandOption:!0}).option("path",{describe:"The full file path of the agent to delete (useful if names collide).",type:"string"}),handler:async t=>{await DYp({name:t.name,path:t.path})}}});var KIa,JIa=x(()=>{"use strict";f();VIa();qIa();WIa();zIa();KIa={command:"agents <command>",aliases:["agent"],describe:"Manage agents.",builder:t=>t.command(jIa).command(HIa).command(QIa).command(YIa).demandCommand(1,"You need at least one command before continuing.").version(!1),handler:()=>{}}});import{fileURLToPath as wYp}from"url";import*as vIe from"path";import*as XIa from"fs";function UYp(t){if(!t||typeof t!="object")return!1;let e=t.bin;if(!e)return!1;if(typeof e=="string")return!0;if(typeof e=="object"){let n=e.codely;return typeof n=="string"&&n.length>0}return!1}function kYp(t){if(!t||typeof t!="object")return!1;let{name:e,version:n}=t;return typeof e=="string"&&new Set(["@codely/cli","@codely/codely-cli","@unity-china/codely-cli","@unity-china/cli"]).has(e)||UYp(t)?!0:typeof e=="string"&&typeof n=="string"}async function BYp(t){try{let e=await XIa.promises.readFile(t,"utf-8"),n=JSON.parse(e);return kYp(n)?n:null}catch{return null}}async function tB(){if(OIe)return OIe;let t=[vIe.resolve(etr,"../../package.json"),vIe.resolve(etr,"../package.json"),vIe.resolve(etr,"../../../../package.json")];for(let e of t){let n=await BYp(e);if(n)return OIe=n,OIe}return OIe={name:"@codely/codely-cli",version:"1.0.0-rc.54"},OIe}var LYp,etr,OIe,sce=x(()=>{"use strict";f();LYp=wYp(import.meta.url),etr=vIe.dirname(LYp)});async function nB(){let t=await tB();return"1.0.0-rc.54"}var xIe=x(()=>{"use strict";f();sce();});var oNa=I((m8g,rtr)=>{"use strict";f();var eNa=ge("child_process").exec,tNa=ge("child_process").execSync,G$t=ge("fs"),ZIa=ge("path"),nNa=G$t.access,rNa=G$t.accessSync,PIe=G$t.constants||G$t,ttr=process.platform=="win32",FYp=function(t,e){nNa(t,PIe.F_OK,function(n){e(!n)})},$Yp=function(t){try{return rNa(t,PIe.F_OK),!1}catch{return!0}},GYp=function(t,e){nNa(t,PIe.F_OK|PIe.X_OK,function(n){e(null,!n)})},jYp=function(t){try{return rNa(t,PIe.F_OK|PIe.X_OK),!0}catch{return!1}},VYp=function(t,e,n){FYp(t,function(r){if(!r){var o=eNa("command -v "+e+" 2>/dev/null && { echo >&1 "+e+"; exit 0; }",function(s,a,c){n(null,!!a)});return}GYp(t,n)})},HYp=function(t,e,n){if(!/^(?!(?:.*\s|.*\.|\W+)$)(?:[a-zA-Z]:)?(?:(?:[^<>:"\|\?\*\n])+(?:\/\/|\/|\\\\|\\)?)+$/m.test(t)){n(null,!1);return}var r=eNa("where "+e,function(o){o!==null?n(null,!1):n(null,!0)})},qYp=function(t,e){if($Yp(t))try{var n=tNa("command -v "+e+" 2>/dev/null && { echo >&1 "+e+"; exit 0; }");return!!n}catch{return!1}return jYp(t)},QYp=function(t,e,n){if(!/^(?!(?:.*\s|.*\.|\W+)$)(?:[a-zA-Z]:)?(?:(?:[^<>:"\|\?\*\n])+(?:\/\/|\/|\\\\|\\)?)+$/m.test(t))return!1;try{var r=tNa("where "+e,{stdio:[]});return!!r}catch{return!1}},ntr=function(t){return/[^A-Za-z0-9_\/:=-]/.test(t)&&(t="'"+t.replace(/'/g,"'\\''")+"'",t=t.replace(/^(?:'')+/g,"").replace(/\\'''/g,"\\'")),t};ttr&&(ntr=function(t){var e=/[\\]/.test(t);if(e){var n='"'+ZIa.dirname(t)+'"',r='"'+ZIa.basename(t)+'"';return n+":"+r}return'"'+t+'"'});rtr.exports=function t(e,n){var r=ntr(e);if(!n&&typeof Promise<"u")return new Promise(function(o,s){t(e,function(a,c){c?o(e):s(a)})});ttr?HYp(e,r,n):VYp(e,r,n)};rtr.exports.sync=function(t){var e=ntr(t);return ttr?QYp(t,e):qYp(t,e)}});var iNa=I((g8g,sNa)=>{f();sNa.exports=oNa()});import*as aNa from"node:os";function WYp(t){return cNa.includes(t)}function YYp(t){if(process.env.SANDBOX)return"";let e=process.env.GEMINI_SANDBOX?.toLowerCase().trim()??"";if(t=e?.length>0?e:t,t==="1"||t==="true"?t=!0:(t==="0"||t==="false"||!t)&&(t=!1),t===!1)return"";if(typeof t=="string"&&t){if(WYp(t)||(console.error(`ERROR: invalid sandbox command '${t}'. Must be one of ${cNa.join(", ")}`),process.exit(1)),uWe.default.sync(t))return t;console.error(`ERROR: missing sandbox command '${t}' (from GEMINI_SANDBOX)`),process.exit(1)}return aNa.platform()==="darwin"&&uWe.default.sync("sandbox-exec")?"sandbox-exec":uWe.default.sync("docker")&&t===!0?"docker":uWe.default.sync("podman")&&t===!0?"podman":(t===!0&&(console.error("ERROR: GEMINI_SANDBOX is true but failed to determine command for sandbox; install docker or podman or specify command in GEMINI_SANDBOX"),process.exit(1)),"")}async function lNa(t,e){let n=e.sandbox??t.sandbox,r=YYp(n),o=await tB(),s=e.sandboxImage??process.env.GEMINI_SANDBOX_IMAGE??o?.config?.sandboxImageUri;return r&&s?{command:r,image:s}:void 0}var uWe,cNa,uNa=x(()=>{"use strict";f();uWe=be(iNa(),1);sce();cNa=["docker","podman","sandbox-exec"]});import*as otr from"os";import*as dNa from"path";function str(t){if(!t)return"";let e=t;return t.toLowerCase().startsWith("%userprofile%")?e=otr.homedir()+t.substring(13):(t==="~"||t.startsWith("~/"))&&(e=otr.homedir()+t.substring(1)),dNa.normalize(e)}var fNa=x(()=>{"use strict";f();});import*as ice from"node:fs";import{promises as pNa}from"node:fs";import*as y7 from"node:path";import{fileURLToPath as zYp}from"node:url";function atr(){let t=globalThis.__dirname;if(t)return y7.join(t,"example-prompts");let e=CBt(),n=y7.join(e,"bundle","example-prompts");return ice.existsSync(n)?n:y7.join(JYp,"../../example-prompts")}function XYp(){return R1("example-prompts/").filter(t=>t.endsWith(".toml"))}function j$t(){let t=XYp();if(t.length>0)return t.map(n=>n.slice(16).replace(/\.toml$/,"")).filter(Boolean).sort();let e=atr();try{return ice.readdirSync(e).filter(r=>r.endsWith(".toml")).map(r=>r.replace(/\.toml$/,"")).filter(Boolean).sort()}catch{return[]}}async function ZYp(t){let e=`example-prompts/${t}.toml`,n=qG(e);if(n)return pNa.readFile(n,"utf8");let r=atr(),o=y7.join(r,`${t}.toml`);return pNa.readFile(o,"utf8")}function e5p(t){let e=`example-prompts/${t}.toml`,n=qG(e);if(n)return ice.readFileSync(n,"utf8");let r=atr(),o=y7.join(r,`${t}.toml`);return ice.readFileSync(o,"utf8")}async function MIe(t){let e=await ZYp(t);return itr.default.parse(e)}function hNa(t){let e=e5p(t);return itr.default.parse(e)}async function V$t(){let t=j$t(),e=[];for(let n of t)try{let r=await MIe(n);e.push({name:n,description:r.description||"No description available"})}catch{e.push({name:n,description:"Example prompt"})}return e}var itr,KYp,JYp,H$t=x(()=>{"use strict";f();itr=be(xse(),1);dj();s4e();KYp=zYp(import.meta.url),JYp=y7.dirname(KYp)});function q$t(t=process.env){let e=t[t5p];return e==="1"||e?.toLowerCase()==="true"}function ctr(t){let e=t.trim().toLowerCase();return n5p.includes(e)||e.startsWith("codely-unity-")}var t5p,n5p,ltr=x(()=>{"use strict";f();t5p="CODELY_CLI_DISABLE_UNITY_INTEGRATION",n5p=["codely-unity-lsp-server"]});import*as dQ from"fs";import*as uQ from"path";import{homedir as r5p}from"os";function dtr(){let t=[],e={},n=a5p;try{if(dQ.existsSync(n)){let r=dQ.readFileSync(n,"utf-8"),o=JSON.parse((0,mNa.default)(r));o&&Object.assign(e,o)}}catch(r){t.push({message:Ct(r),path:n})}return new utr({path:n,config:e},t)}function c5p(t){try{let e=uQ.dirname(t.path);dQ.existsSync(e)||dQ.mkdirSync(e,{recursive:!0}),dQ.writeFileSync(t.path,JSON.stringify(t.config,null,2),"utf-8")}catch(e){console.error("Error saving trusted folders file:",e)}}function ANa(){let{rules:t,errors:e}=dtr();if(e.length>0)for(let s of e)console.error(`Error loading trusted folders config from ${s.path}: ${s.message}`);let n=[],r=[];for(let s of t)switch(s.trustLevel){case"TRUST_FOLDER":n.push(s.path);break;case"TRUST_PARENT":n.push(uQ.dirname(s.path));break;case"DO_NOT_TRUST":r.push(s.path);break;default:break}let o=process.cwd();for(let s of n)if(aPe(o,s))return!0;for(let s of r)if(uQ.normalize(o)===uQ.normalize(s))return!1}var mNa,o5p,s5p,i5p,a5p,utr,ftr=x(()=>{"use strict";f();zt();mNa=be(lzn(),1);o5p="trustedFolders.json",s5p=".codely-cli",i5p=uQ.join(r5p(),s5p),a5p=uQ.join(i5p,o5p),utr=class{constructor(e,n){this.user=e;this.errors=n}get rules(){return Object.entries(this.user.config).map(([e,n])=>({path:e,trustLevel:n}))}setValue(e,n){this.user.config[e]=n,c5p(this.user)}}});function vj(){return process.env[l5p]==="1"}function Q$t(){return u5p}var l5p,u5p,DIe=x(()=>{"use strict";f();l5p="CODELY_CLI_INTERNAL_DISABLE_AUTO_UPDATE",u5p="Update disabled: CODELY_CLI_INTERNAL_DISABLE_AUTO_UPDATE=1 is set. Unset it to check for updates."});function gNa(){return process.env.CODELY_CLI_ENV==="dev"?"http://localhost:8000":"https://codely.tuanjie.cn"}var _Na=x(()=>{"use strict";f()});import ptr from"os";function d5p(t){if(!t)return null;let e=t.trim().toLowerCase();return e==="api"||e==="server"?"api":e==="npm"||e==="registry"?"npm":null}function f5p(t){if(t.startsWith("@")){let e=t.split("/");if(e.length===2&&e[0]&&e[1])return`${e[0]}%2F${e[1]}`}return t}async function p5p(t){try{let n=`https://registry.npmjs.org/${f5p(t)}/latest`,r=new AbortController,o=setTimeout(()=>r.abort(),ENa),s=await fetch(n,{method:"GET",headers:{accept:"application/json"},signal:r.signal});return clearTimeout(o),s.ok&&(await s.json()).version||null}catch(e){return console.warn("Failed to fetch latest version from npm registry:",e),null}}async function h5p(){try{let t=ptr.platform()==="win32"?"win32":ptr.platform(),e=ptr.arch(),o=`${gNa()}/api/plugin/version?platform=${t}&architecture=${e}&plugin_name=codely-cli&is_binary=${q1()}`,s=new AbortController,a=setTimeout(()=>s.abort(),ENa),c=await fetch(o,{method:"GET",headers:{accept:"application/json"},signal:s.signal});return clearTimeout(a),c.ok?await c.json():null}catch(t){return console.warn("Failed to fetch version from API:",t),null}}async function wIe(){try{if(process.env.DEV==="true"||vj())return null;let t=await nB();if(!t||t==="unknown")return null;let n=(await tB())?.name;if((d5p(process.env.CODELY_CLI_UPDATE_SOURCE)||(n&&n.startsWith("@unity-china/")?"npm":"api"))==="npm"){if(!n)return null;let c=await p5p(n);if(!c)return null;if(W$t.default.gt(c,t)){let l=W$t.default.diff(t,c)||"major";return{message:`Codely Cli update available! ${t} \u2192 ${c}`,update:{current:t,latest:c,type:l,name:n}}}return null}let s=await h5p();if(!s||!s.active)return null;let a=s.version;if(W$t.default.gt(a,t)){let c=`Codely Cli update available! ${t} \u2192 ${a}`,l={current:t,latest:a,type:"major",name:n??s.name,downloadUrl:s.download_url};return{message:c,update:l}}return null}catch(t){return console.warn("Failed to check for updates: "+t),null}}var W$t,ENa,Y$t=x(()=>{"use strict";f();W$t=be(vZ(),1);DIe();sce();dj();xIe();_Na();ENa=2e3});var C7=x(()=>{"use strict";f();_s();});var YC,TNa,SNa,htr,lP,yNa=x(()=>{"use strict";f();YC=be(sn(),1);zt();TNa=be(st(),1);SNa=(0,YC.createContext)(void 0),htr=({children:t})=>{let[e,n]=(0,YC.useState)(()=>({sessionStartTime:new Date,metrics:Rs.getMetrics(),totalRequestTokens:Rs.getTotalRequestTokens(),modelTokenLimit:Rs.getModelTokenLimit(),promptCount:0})),r=(0,YC.useRef)(null);if(r.current===null){let l=({metrics:u,totalRequestTokens:d,modelTokenLimit:p})=>{n(h=>({...h,metrics:u??h.metrics,totalRequestTokens:d??h.totalRequestTokens,modelTokenLimit:p??h.modelTokenLimit}))};r.current=l,Rs.on("update",l)}(0,YC.useEffect)(()=>(n(l=>({...l,metrics:Rs.getMetrics(),totalRequestTokens:Rs.getTotalRequestTokens(),modelTokenLimit:Rs.getModelTokenLimit()})),()=>{r.current&&(Rs.off("update",r.current),r.current=null)}),[]);let o=(0,YC.useCallback)(()=>{n(l=>({...l,promptCount:l.promptCount+1}))},[]),s=(0,YC.useCallback)(()=>e.promptCount,[e.promptCount]),a=(0,YC.useCallback)(()=>{n({sessionStartTime:new Date,metrics:Rs.getMetrics(),totalRequestTokens:Rs.getTotalRequestTokens(),modelTokenLimit:Rs.getModelTokenLimit(),promptCount:0})},[]),c=(0,YC.useMemo)(()=>({stats:e,startNewPrompt:o,getPromptCount:s,resetSession:a}),[e,o,s,a]);return(0,TNa.jsx)(SNa.Provider,{value:c,children:t})},lP=()=>{let t=(0,YC.useContext)(SNa);if(t===void 0)throw new Error("useSessionStats must be used within a SessionStatsProvider");return t}});var MO,mtr,CNa,RNa,Atr,gtr,_tr,dWe=x(()=>{"use strict";f();MO=be(sn(),1),mtr=be(st(),1);CNa=(0,MO.createContext)(void 0),RNa=(0,MO.createContext)(void 0),Atr=()=>(0,MO.useContext)(CNa),gtr=()=>(0,MO.useContext)(RNa),_tr=({children:t})=>{let[e,n]=(0,MO.useState)(new Set),r=(0,MO.useCallback)(c=>{n(l=>{if(l.has(c))return l;let u=new Set(l);return u.add(c),u})},[]),o=(0,MO.useCallback)(c=>{n(l=>{if(!l.has(c))return l;let u=new Set(l);return u.delete(c),u})},[]),s=(0,MO.useMemo)(()=>({overflowingIds:e}),[e]),a=(0,MO.useMemo)(()=>({addOverflowingId:r,removeOverflowingId:o}),[r,o]);return(0,mtr.jsx)(CNa.Provider,{value:s,children:(0,mtr.jsx)(RNa.Provider,{value:a,children:t})})}});var z$t,K$t,Etr,J$t=x(()=>{"use strict";f();z$t=be(sn(),1);K$t=z$t.default.createContext(void 0),Etr=()=>{let t=(0,z$t.useContext)(K$t);if(t===void 0)throw new Error("useSettings must be used within a SettingsProvider");return t}});var X$t,fWe,fQ,ace=x(()=>{"use strict";f();X$t=be(sn(),1);fWe=(0,X$t.createContext)(void 0),fQ=()=>{let t=X$t.default.useContext(fWe);if(t===void 0)throw new Error("useStreamingContext must be used within a StreamingContextProvider");return t}});var rB,INa,bNa,Str,cce,pWe=x(()=>{"use strict";f();rB=be(sn(),1);Gs();INa=be(st(),1);bNa=(0,rB.createContext)(void 0),Str=({children:t,settings:e})=>{let n=e.merged.vimMode??!1,[r,o]=(0,rB.useState)(n),[s,a]=(0,rB.useState)(n?"NORMAL":"INSERT");(0,rB.useEffect)(()=>{let u=e.merged.vimMode??!1;o(u),u&&a("NORMAL")},[e.merged.vimMode]);let c=(0,rB.useCallback)(async()=>{let u=!r;return o(u),u&&a("NORMAL"),await e.setValue("User","vimMode",u),u},[r,e]),l={vimEnabled:r,vimMode:s,toggleVimEnabled:c,setVimMode:a};return(0,INa.jsx)(bNa.Provider,{value:l,children:t})},cce=()=>{let t=(0,rB.useContext)(bNa);if(t===void 0)throw new Error("useVimMode must be used within a VimModeProvider");return t}});var R7=x(()=>{"use strict";f();yNa();dWe();J$t();ace();pWe();});function Ttr(){let[t,e]=(0,oB.useState)([]),n=(0,oB.useRef)(0),r=(0,oB.useCallback)(u=>(n.current+=1,u+n.current),[]),o=(0,oB.useCallback)(u=>{e(u)},[]),s=(0,oB.useCallback)((u,d)=>{let p=r(d),h={...u,id:p};return e(m=>{if(m.length>0){let A=m[m.length-1];if(A.type==="user"&&h.type==="user"&&A.text===h.text)return m}return[...m,h]}),p},[r]),a=(0,oB.useCallback)((u,d)=>{e(p=>p.map(h=>{if(h.id===u){let m=typeof d=="function"?d(h):d;return{...h,...m}}return h}))},[]),c=(0,oB.useCallback)(u=>{if(u.length===0)return;let d=new Set(u);e(p=>p.filter(h=>!d.has(h.id)))},[]),l=(0,oB.useCallback)(()=>{e([]),n.current=0},[]);return{history:t,addItem:s,updateItem:a,removeItems:c,clearItems:l,loadHistory:o}}var oB,NNa=x(()=>{"use strict";f();oB=be(sn(),1);});var LIe,ytr,Ctr=x(()=>{"use strict";f();LIe=be(sn(),1);ca();zt();ytr=(t,e,n)=>{let[r,o]=(0,LIe.useState)(!1),s=(0,LIe.useCallback)(()=>{o(!0)},[]),a=(0,LIe.useCallback)((l,u)=>{if(!(l&&(!h0e(l)||!m0e(l))))try{t.setValue(u,"preferredEditor",l),n({type:"info",text:`Editor preference ${l?`set to "${l}"`:"cleared"} in ${u} settings.`},Date.now()),e(null),o(!1)}catch(d){e(`Failed to set editor preference: ${d}`)}},[t,e,n]),c=(0,LIe.useCallback)(()=>{o(!1)},[]);return{isEditorDialogOpen:r,openEditorDialog:s,handleEditorSelect:a,exitEditorDialog:c}}});function ONa(t){let e=t.getGeminiClient().getContentGenerator();if(e instanceof ZV){if(!e.projectId)throw new Error("Oauth not being used")}else throw new Error("Oauth not being used");return e}async function m5p(t){let e=await t.loadCodeAssist({cloudaicompanionProject:t.projectId,metadata:{ideType:"IDE_UNSPECIFIED",platform:"PLATFORM_UNSPECIFIED",pluginType:"GEMINI",duetProject:t.projectId}});if(!e.currentTier)throw new Error("User does not have a current tier");return e.currentTier.id}async function A5p(t){try{return(await t.getCodeAssistGlobalUserSetting()).freeTierDataCollectionOptin}catch(e){if(e&&typeof e=="object"&&"response"in e&&e.response?.status===404)return!0;throw e}}async function g5p(t,e){return(await t.setCodeAssistGlobalUserSetting({cloudaicompanionProject:t.projectId,freeTierDataCollectionOptin:e})).freeTierDataCollectionOptin}var UIe,Rtr,btr=x(()=>{"use strict";f();UIe=be(sn(),1);zt();Rtr=t=>{let[e,n]=(0,UIe.useState)({isLoading:!0});(0,UIe.useEffect)(()=>{(async()=>{n({isLoading:!0});try{let s=ONa(t);if(await m5p(s)!==b0.FREE){n({isLoading:!1,isFreeTier:!1});return}let c=await A5p(s);n({isLoading:!1,isFreeTier:!0,dataCollectionOptIn:c})}catch(s){n({isLoading:!1,error:s instanceof Error?s.message:String(s)})}})()},[t]);let r=(0,UIe.useCallback)(async o=>{try{let s=ONa(t),a=await g5p(s,o);n({isLoading:!1,isFreeTier:!0,dataCollectionOptIn:a})}catch(s){n({isLoading:!1,error:s instanceof Error?s.message:String(s)})}},[t]);return{privacyState:e,updateDataCollectionOptIn:r}}});var Itr=x(()=>{"use strict";f();});function xNa(t){return t>=32&&t!==127&&t<=1114111&&(t<57344||t>63743)}function y5p(t){return t.name==="enter"?{...t,name:"return"}:!t.name&&(t.sequence===`
|
|
4129
4129
|
`||t.sequence==="\r")?{...t,name:"return"}:!t.name&&(t.sequence==="\x7F"||t.sequence==="\b")?{...t,name:"backspace"}:t}function PNa(t){let e=Array.from(t);if(e.length!==1)return"";let n=e[0],r=n.codePointAt(0);return xNa(r)?n===" "?"space":n>="A"&&n<="Z"?n.toLowerCase():n:""}function C5p(t){return!t.keypress.isPasted&&!t.keypress.ctrl&&t.input.length>0&&!t.input.startsWith("\x1B")&&PNa(t.input)!==""}function R5p(t){return t==="wheelup"||t==="wheeldown"||t==="mouse"}function b5p(t){let e=t.keypress.name??"",n=t.keypress.sequence??"";return!e&&!t.keypress.isPasted&&!t.keypress.ctrl&&t.input.length===0&&(n.startsWith("\x1B")||T5p.test(n))}function I5p(t){if(!t)return null;let e=E5p.exec(t)??S5p.exec(t);if(!e)return null;let n=Number.parseInt(e[1],10);return xNa(n)?String.fromCodePoint(n):null}function N5p(t){let e=t.keypress,n=R5p(e.name)||b5p(t)?"":!e.ctrl&&!e.isPasted?I5p(e.sequence)??(C5p(t)?t.input:e.sequence??""):e.sequence??"";return y5p({name:e.name||PNa(t.input),ctrl:e.ctrl,meta:e.meta||e.option,shift:e.shift,paste:e.isPasted,sequence:n})}function _r(t,e={}){let n=e.isActive??!0,r=(0,kIe.useRef)(t);r.current=t;let o=(0,kIe.useRef)(n);o.current=n;let s=(0,kIe.useRef)({waitingForEnterAfterBackslash:!1,backslashTimeout:null,swallowNextLfAfterBackslashEnter:!1,swallowNextLfTimeout:null,lastForwardedKeyTime:0}),a=()=>{let c=s.current;c.waitingForEnterAfterBackslash=!1,c.swallowNextLfAfterBackslashEnter=!1,c.backslashTimeout&&(clearTimeout(c.backslashTimeout),c.backslashTimeout=null),c.swallowNextLfTimeout&&(clearTimeout(c.swallowNextLfTimeout),c.swallowNextLfTimeout=null)};(0,kIe.useEffect)(()=>(o.current=n,n||a(),()=>{o.current=!1,a()}),[n]),rce((c,l,u)=>{let d=s.current,p=N5p(u),h=Date.now(),m=A=>{o.current&&(r.current(A),d.lastForwardedKeyTime=Date.now())};if(!p.paste){if(p.name==="return"&&d.waitingForEnterAfterBackslash){d.backslashTimeout&&(clearTimeout(d.backslashTimeout),d.backslashTimeout=null),d.waitingForEnterAfterBackslash=!1,d.swallowNextLfAfterBackslashEnter=!0,d.swallowNextLfTimeout&&clearTimeout(d.swallowNextLfTimeout),d.swallowNextLfTimeout=setTimeout(()=>{d.swallowNextLfAfterBackslashEnter=!1,d.swallowNextLfTimeout=null},5),m({...p,shift:!0,sequence:"\\\r"});return}if(process.platform==="win32"&&d.swallowNextLfAfterBackslashEnter&&p.sequence===`
|
|
4130
4130
|
`&&!p.ctrl&&!p.meta){d.swallowNextLfAfterBackslashEnter=!1,d.swallowNextLfTimeout&&(clearTimeout(d.swallowNextLfTimeout),d.swallowNextLfTimeout=null);return}if(p.sequence==="\\"&&!p.ctrl&&!p.meta&&!p.shift&&!p.paste){d.waitingForEnterAfterBackslash=!0,d.backslashTimeout=setTimeout(()=>{d.waitingForEnterAfterBackslash=!1,d.backslashTimeout=null,m(p)},5);return}if(d.waitingForEnterAfterBackslash&&p.name!=="return"&&(d.backslashTimeout&&(clearTimeout(d.backslashTimeout),d.backslashTimeout=null),d.waitingForEnterAfterBackslash=!1,m({name:"",sequence:"\\",ctrl:!1,meta:!1,shift:!1,paste:!1})),p.name==="return"&&(p.sequence==="\r"||p.sequence===`
|
|
4131
4131
|
`)&&!p.ctrl&&!p.meta&&!p.shift&&h-d.lastForwardedKeyTime<=30){m({...p,paste:!0});return}}m(p)},{isActive:n})}var kIe,E5p,S5p,T5p,Va=x(()=>{"use strict";f();kIe=be(sn(),1);Bn();Itr();E5p=/^\x1b\[(\d+)(?:;\d+)?u$/,S5p=/^\x1b\[27;\d+;(\d+)~$/,T5p=/^\[<\d+;\d+;\d+[Mm]$/});function yu(){let t=(0,MNa.useContext)(Ij);return t||{columns:process.stdout.columns||60,rows:process.stdout.rows||20}}var MNa,zC=x(()=>{"use strict";f();MNa=be(sn(),1);Bn();});async function Z$t(t){let{geminiClient:e,config:n,resetSession:r,clearUi:o,clearQueues:s,setDebugMessage:a}=t,c=n?.getHookSystem?.();if(c)try{await c.fireSessionEndEvent(b_.Clear)}catch{}e?(a?.("Clearing terminal and resetting chat."),await e.resetChat()):a?.("Clearing terminal."),n?.getRewindService?.()?.clear(),Rs.resetLastPromptTokenCount(),r?.(),o?.(),s?.();let l;if(c)try{let u=await c.fireSessionStartEvent(Uh.Clear);u&&(l=u.getAdditionalContext(),l&&n&&n.enqueueAttachment(cx({source:"clear",additionalContext:l,visibility:"model_visible"})))}catch{}return{additionalContext:l}}var Ntr=x(()=>{"use strict";f();zt();});import{spawn as Otr}from"child_process";import{stat as O5p}from"node:fs/promises";function v5p(t,e){let r=e.trim().substring(1).trim().split(/\s+/),o=r.filter(u=>u),s=t,a,c=0,l=[];for(let u of o){let d=s.find(p=>p.name===u);if(d||(d=s.find(p=>p.altNames?.includes(u))),!d)break;if(a=d,l.push(d.name),c++,d.subCommands)s=d.subCommands;else break}if(a)return{command:a,args:r.slice(c).join(" "),canonicalPath:l}}function e2t(t,e,n=[]){let r=e.trim();if(!r)return;let o=t.flatMap(s=>[s.name,...s.altNames??[]].map(a=>({command:s,name:a,isAlias:a!==s.name}))).filter(({name:s})=>r===s||r.startsWith(`${s} `)).sort((s,a)=>{let c=a.name.length-s.name.length;return c!==0?c:s.isAlias!==a.isAlias?s.isAlias?1:-1:s.command.name.localeCompare(a.command.name)});for(let s of o){let a=r.slice(s.name.length).trimStart();if(a&&s.command.subCommands){let c=e2t(s.command.subCommands,a,[...n,s.command.name]);if(c)return c}return{command:s.command,args:a,canonicalPath:[...n,s.command.name]}}}function LNa(t,e){let n=e.trim();if(!(!n.startsWith("/")&&!n.startsWith("?")))return v5p(t,n)??e2t(t,n.substring(1).trim())}async function BIe(t,e){let n=t.trim(),r=n.substring(1).trim(),o=r.split(/\s+/)[0]??"",s=r&&e?.commands?e2t(e.commands,r):void 0;if(s)return{kind:"matched-command",match:s};try{return await(e?.stat??O5p)(n),{kind:"path-like",raw:n}}catch{}return o&&!x5p(o)?{kind:"path-like",raw:n}:{kind:"unknown-command",raw:n,firstToken:o}}var DNa,wNa,hWe,x5p,UNa,kNa,pQ=x(()=>{"use strict";f();DNa=t=>t.startsWith("@")||/\s@/.test(t),wNa=t=>t.startsWith("#")||/\s#/.test(t),hWe=t=>t.startsWith("/");x5p=(t,e)=>e&&e2t(e,t)?!0:!/[^a-zA-Z0-9:_-]/.test(t);UNa=async t=>{if(process.platform==="win32")try{await new Promise((n,r)=>{let s=`$text = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String('${Buffer.from(t,"utf-8").toString("base64")}')); Set-Clipboard -Value $text`,a=Otr("powershell",["-NoProfile","-ExecutionPolicy","Bypass","-Command",s],{shell:!1,windowsHide:!0}),c="";a.stderr.on("data",l=>c+=l.toString()),a.on("error",r),a.on("close",l=>{if(l===0)return n();let u=c.trim();r(new Error(`PowerShell Set-Clipboard exited with code ${l}${u?`: ${u}`:""}`))})});return}catch(n){return console.debug("PowerShell Set-Clipboard failed, falling back to clip.exe:",n),new Promise((r,o)=>{let s=Otr("clip",[],{shell:!1,windowsHide:!0}),a="";s.stderr.on("data",c=>a+=c.toString()),s.on("error",o),s.on("close",c=>{if(c===0)return r();let l=a.trim();o(new Error(`clip.exe exited with code ${c}${l?`: ${l}`:""}`))}),s.stdin.on("error",o),s.stdin.write(t),s.stdin.end()})}let e=(n,r)=>new Promise((o,s)=>{let a=Otr(n,r),c="";a.stderr.on("data",l=>c+=l.toString()),a.on("error",s),a.on("close",l=>{if(l===0)return o();let u=c.trim();s(new Error(`'${n}' exited with code ${l}${u?`: ${u}`:""}`))}),a.stdin.on("error",s),a.stdin.write(t),a.stdin.end()});switch(process.platform){case"darwin":return e("pbcopy",[]);case"linux":try{await e("xclip",["-selection","clipboard"])}catch(n){try{await e("xsel",["--clipboard","--input"])}catch(r){let o=n instanceof Error?n.message:String(n),s=r instanceof Error?r.message:String(r);throw new Error(`All copy commands failed. xclip: "${o}", xsel: "${s}". Please ensure xclip or xsel is installed and configured.`)}}return;default:throw new Error(`Unsupported platform: ${process.platform}`)}},kNa=()=>{let t;switch(process.platform){case"darwin":t="open";break;case"win32":t="start";break;case"linux":t="xdg-open";break;default:t="xdg-open",console.warn(`Unknown platform: ${process.platform}. Attempting to open URLs with: ${t}.`);break}return t}});function t2t(t){let e=t?.detector??"unknown",n=t?.message??"",r=t?.strikeCount,o=["System: A repeating loop was detected multiple times and the automatic recovery attempts did not help.",`Detector: ${e}.${r!==void 0?` Strike ${r}.`:""}`];n&&o.push(`Last signal: ${n}`);let s=["You MUST stop calling tools immediately and finalize your response to the user.","","Your final response MUST include the following sections in order, each no more than 3 sentences:","","1. **Progress so far**: List the concrete steps you completed and what you verified works.","2. **Where you got stuck**: Explain what specifically caused you to loop (e.g., a tool returning unexpected output, a missing piece of information, or conflicting signals).","3. **Recommended next step for the user**: Suggest 1-2 concrete actions the user can take manually or by opening a fresh prompt.","","Do NOT attempt to solve the original task further in this response. Do NOT call any more tools."].join(`
|