makecoder 2.0.95 → 2.0.97
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/dist/cc.mjs +3 -3
- package/dist/coder.js +25 -18
- package/dist/gemini/{chunk-P74ZNAQL.js → chunk-FZKV2OXC.js} +2 -2
- package/dist/gemini/{chunk-LMI44K7Z.js → chunk-RJWN4TV6.js} +2 -2
- package/dist/gemini/{chunk-DYJGCY6I.js → chunk-SZCTACC4.js} +2 -2
- package/dist/gemini/{chunk-J3OZTJAG.js → chunk-WQ23SZKZ.js} +2 -2
- package/dist/gemini/{core-IMFFRI76.js → core-6CSJEUHD.js} +1 -1
- package/dist/gemini/{devtoolsService-EHXHW6BU.js → devtoolsService-CLP7VYOP.js} +2 -2
- package/dist/gemini/{devtoolsService-V3S3BUMG.js → devtoolsService-TCAPUJWL.js} +2 -2
- package/dist/gemini/{dist-SANZLHVS.js → dist-G4EPGJS6.js} +1 -1
- package/dist/gemini/gemini.js +5 -5
- package/dist/gemini/{interactiveCli-XSAHDOTH.js → interactiveCli-BBNEBSZD.js} +2 -2
- package/dist/gemini/{interactiveCli-CZ4TLI3G.js → interactiveCli-OSI3BU7D.js} +2 -2
- package/dist/gemini/{oauth2-provider-I6XYB5WE.js → oauth2-provider-FFVQZBNR.js} +1 -1
- package/dist/gemini/{oauth2-provider-LS6G6IRO.js → oauth2-provider-R4BZ7DTI.js} +1 -1
- package/package.json +4 -4
- /package/dist/gemini/{tree-sitter-BJV5YZCI.js → tree-sitter-ONNCTZTG.js} +0 -0
- /package/dist/gemini/{tree-sitter-bash-XZVX6YWO.js → tree-sitter-bash-56AB4HVQ.js} +0 -0
package/dist/cc.mjs
CHANGED
|
@@ -20,13 +20,13 @@ import{createRequire as vP5}from"node:module";var MP5=Object.create;var{getProto
|
|
|
20
20
|
Object.assign(A, {
|
|
21
21
|
post(...args) {
|
|
22
22
|
const [url, payload, ...remainArgs] = args;
|
|
23
|
-
const patchedUrl = url + (url.includes('?') ? '&' : ':') + '&app=codev-cli' + '&version=2.0.
|
|
23
|
+
const patchedUrl = url + (url.includes('?') ? '&' : ':') + '&app=codev-cli' + '&version=2.0.97' + '&session_id=' + I8();
|
|
24
24
|
if (process.env.CODEV_AUTH_SK && process.env.CODEV_AUTH_AK) {
|
|
25
25
|
const headerValues = payload.headers.values;
|
|
26
26
|
headerValues.set('AUTHORIZATION', `Bearer ${process.env.CODEV_AUTH_AK}.${process.env.CODEV_AUTH_SK}`)
|
|
27
27
|
}
|
|
28
28
|
|
|
29
|
-
payload.headers.values.set('X-Coder-Version', '2.0.
|
|
29
|
+
payload.headers.values.set('X-Coder-Version', '2.0.97');
|
|
30
30
|
payload.headers.values.set('X-Coder-Platform', process.platform);
|
|
31
31
|
payload.headers.values.set('X-Coder-Arch', process.arch);
|
|
32
32
|
|
|
@@ -4120,7 +4120,7 @@ If called outside an EnterWorktree session, the tool is a **no-op**: it reports
|
|
|
4120
4120
|
- If a tmux session was attached to the worktree: killed on \`remove\`, left running on \`keep\` (its name is returned so the user can reattach)
|
|
4121
4121
|
- Once exited, EnterWorktree can be called again to create a fresh worktree
|
|
4122
4122
|
`}function TvK({action:q}){return q??""}function VvK(q,K,_){let z=q.action==="keep"?"Kept worktree":"Removed worktree";return ST.createElement(_1,null,ST.createElement(u,{flexDirection:"column"},ST.createElement(T,null,z,q.worktreeBranch?ST.createElement(ST.Fragment,null," ","(branch ",ST.createElement(T,{bold:!0},q.worktreeBranch),")"):null),ST.createElement(T,{dimColor:!0},"Returned to ",q.originalCwd)))}var ST;var kvK=L(()=>{GK();g6();ST=K6(P6(),1)});async function NvK(q,K){let _=await w1("git",["-C",q,"status","--porcelain"]);if(_.code!==0)return null;let z=w7(_.stdout.split(`
|
|
4123
|
-
`),(O)=>O.trim()!=="");if(!K)return null;let Y=await w1("git",["-C",q,"rev-list","--count",`${K}..HEAD`]);if(Y.code!==0)return null;let A=parseInt(Y.stdout.trim(),10)||0;return{changedFiles:z,commits:A}}function EvK(q,K){if(l$(q),dL(q),K)pB6(q),KR6();zL(null),nc(),Lk(),aO.cache.clear?.()}var IjY,xjY,yvK;var LvK=L(()=>{p7();y8();OR6();C8();gq();PM();n7();Q4();Bc();NJ();$G();g4();tD();kvK();IjY=C6(()=>y.strictObject({action:y.enum(["keep","remove"]).describe('"keep" leaves the worktree and branch on disk; "remove" deletes both.'),discard_changes:y.boolean().optional().describe('Required true when action is "remove" and the worktree has uncommitted files or unmerged commits. The tool will refuse and list them otherwise.')})),xjY=C6(()=>y.object({action:y.enum(["keep","remove"]),originalCwd:y.string(),worktreePath:y.string(),worktreeBranch:y.string().optional(),tmuxSessionName:y.string().optional(),discardedFiles:y.number().optional(),discardedCommits:y.number().optional(),message:y.string()}));yvK=Iq({name:AI8,searchHint:"exit a worktree session and return to the original directory",maxResultSizeChars:1e5,async description(){return"Exits a worktree session created by EnterWorktree and restores the original working directory"},async prompt(){return vvK()},get inputSchema(){return IjY()},get outputSchema(){return xjY()},userFacingName(){return"Exiting worktree"},shouldDefer:!0,isDestructive(q){return q.action==="remove"},toAutoClassifierInput(q){return q.action},async validateInput(q){if(Sf6())return{result:!1,message:'ExitWorktree cannot be called from a subagent with a cwd override (isolation: "worktree" or explicit cwd) — it would mutate the parent session\'s process-wide working directory. This agent is already isolated; use Bash with `cd` for directory changes within it.',errorCode:5};let K=sO();if(!K)return{result:!1,message:"No-op: there is no active EnterWorktree session to exit. This tool only operates on worktrees created by EnterWorktree in the current session — it will not touch worktrees created manually or in a previous session. No filesystem changes were made.",errorCode:1};if(q.action==="remove"&&K.enteredExisting)return{result:!1,message:`This session entered an existing worktree (${K.worktreePath}); it was not created by EnterWorktree, so this tool will not remove it. Use action: "keep" to return to ${K.originalCwd}, then remove the worktree manually with \`git worktree remove\` if desired.`,errorCode:4};if(q.action==="remove"&&!q.discard_changes){let _=await NvK(K.worktreePath,K.originalHeadCommit);if(_===null)return{result:!1,message:`Could not verify worktree state at ${K.worktreePath}. Refusing to remove without explicit confirmation. Re-invoke with discard_changes: true to proceed — or use action: "keep" to preserve the worktree.`,errorCode:3};let{changedFiles:z,commits:Y}=_;if(z>0||Y>0){let A=[];if(z>0)A.push(`${z} uncommitted ${z===1?"file":"files"}`);if(Y>0)A.push(`${Y} ${Y===1?"commit":"commits"} on ${K.worktreeBranch??"the worktree branch"}`);return{result:!1,message:`Worktree has ${A.join(" and ")}. Removing will discard this work permanently. Confirm with the user, then re-invoke with discard_changes: true — or use action: "keep" to preserve the worktree.`,errorCode:2}}}return{result:!0}},renderToolUseMessage:TvK,renderToolResultMessage:VvK,async call(q){let K=sO();if(!K)throw Error("Not in a worktree session");let{originalCwd:_,worktreePath:z,worktreeBranch:Y,tmuxSessionName:A,originalHeadCommit:O}=K,w=c9()===Y7(),{changedFiles:$,commits:j}=await NvK(z,O)??{changedFiles:0,commits:0};if(q.action==="keep"){await hM6(),EvK(_,w),d("tengu_worktree_kept",{mid_session:!0,commits:j,changed_files:$});let X=A?` Tmux session ${A} is still running; reattach with: tmux attach -t ${A}`:"";return{data:{action:"keep",originalCwd:_,worktreePath:z,worktreeBranch:Y,tmuxSessionName:A,message:`Exited worktree. Your work is preserved at ${z}${Y?` on branch ${Y}`:""}. Session is now back in ${_}.${X}`}}}if(A)await AI6(A);await OI6(),EvK(_,w),d("tengu_worktree_removed",{source:"exit_tool",mid_session:!0,commits:j,changed_files:$});let H=[];if(j>0)H.push(`${j} ${j===1?"commit":"commits"}`);if($>0)H.push(`${$} uncommitted ${$===1?"file":"files"}`);let J=H.length>0?` Discarded ${H.join(" and ")}.`:"";return{data:{action:"remove",originalCwd:_,worktreePath:z,worktreeBranch:Y,discardedFiles:$,discardedCommits:j,message:`Exited and removed worktree at ${z}.${J} Session is now back in ${_}.`}}},mapToolResultToToolResultBlockParam({message:q},K){return{type:"tool_result",content:q,tool_use_id:K}}})});var hvK="Config";function Td8(q=!1){if(i7())return{value:null,label:"Default (recommended)",description:uT6(q)};let K=!KA();return{value:null,label:K?"Default":"Default (recommended)",description:`Use the default model (currently ${Hn6(hv())})${K?"":` · ${Yf(GQ)}`}`}}function ujY(){let q=!KA(),K=process.env.ANTHROPIC_DEFAULT_SONNET_MODEL;if(q&&K){let _=DP(K);return{value:"sonnet",label:process.env.ANTHROPIC_DEFAULT_SONNET_MODEL_NAME??K,description:process.env.ANTHROPIC_DEFAULT_SONNET_MODEL_DESCRIPTION??`Custom Sonnet model${_?" (1M context)":""}`,descriptionForModel:`${process.env.ANTHROPIC_DEFAULT_SONNET_MODEL_DESCRIPTION??`Custom Sonnet model${_?" with 1M context":""}`} (${K})`}}}function mjY(){let q=!KA();return{value:q?ZO().sonnet46:"sonnet",label:"Sonnet",description:`Sonnet 4.6 · Best for everyday tasks${q?"":` · ${Yf(GQ)}`}`,descriptionForModel:"Sonnet 4.6 - best for everyday tasks. Generally recommended for most coding tasks"}}function BjY(){let q=!KA(),K=process.env.ANTHROPIC_DEFAULT_OPUS_MODEL;if(q&&K){let _=DP(K);return{value:"opus",label:process.env.ANTHROPIC_DEFAULT_OPUS_MODEL_NAME??K,description:process.env.ANTHROPIC_DEFAULT_OPUS_MODEL_DESCRIPTION??`Custom Opus model${_?" (1M context)":""}`,descriptionForModel:`${process.env.ANTHROPIC_DEFAULT_OPUS_MODEL_DESCRIPTION??`Custom Opus model${_?" with 1M context":""}`} (${K})`}}}function pjY(){return{value:"opus",label:"Opus 4.1",description:"Opus 4.1 · Legacy",descriptionForModel:"Opus 4.1 - legacy version"}}function uvK(q=!1,K=!0){return{value:!KA()?ZO().opus46:"claude-opus-4-6",label:"Opus 4.6",description:`Opus 4.6 · Most capable for complex work${K?QZ8(q):""}`,descriptionForModel:"Opus 4.6 - most capable for complex work"}}function RvK(){let q=!KA();return{value:q?ZO().opus47:"opus",label:"Opus",description:`Opus 4.7 · Most capable for complex work${q?"":` · ${Yf(jB)}`}`,descriptionForModel:"Opus 4.7 - most capable for complex work"}}function SvK(){let q=!KA();return{value:q?ZO().sonnet46+"[1m]":"sonnet[1m]",label:"Sonnet (1M context)",description:`Sonnet 4.6 for long sessions${q?"":` · ${Yf(GQ)}`}`,descriptionForModel:"Sonnet 4.6 with 1M context window - for long sessions with large codebases"}}function mvK(q=!1,K=!0){return{value:!KA()?ZO().opus46+"[1m]":"claude-opus-4-6[1m]",label:"Opus 4.6 (1M context)",description:`Opus 4.6 for long sessions${K?QZ8(q):""}`,descriptionForModel:"Opus 4.6 with 1M context window - for long sessions with large codebases"}}function CvK(){let q=!KA();return{value:q?ZO().opus47+"[1m]":"opus[1m]",label:"Opus (1M context)",description:`Opus 4.7 for long sessions${q?"":` · ${Yf(jB)}`}`,descriptionForModel:"Opus 4.7 with 1M context window - for long sessions with large codebases"}}function FjY(){let q=!KA(),K=process.env.ANTHROPIC_DEFAULT_HAIKU_MODEL;if(q&&K)return{value:"haiku",label:process.env.ANTHROPIC_DEFAULT_HAIKU_MODEL_NAME??K,description:process.env.ANTHROPIC_DEFAULT_HAIKU_MODEL_DESCRIPTION??"Custom Haiku model",descriptionForModel:`${process.env.ANTHROPIC_DEFAULT_HAIKU_MODEL_DESCRIPTION??"Custom Haiku model"} (${K})`}}function BvK(){return{value:"haiku",label:"Haiku",description:`Haiku 4.5 · Fastest for quick answers${!KA()?"":` · ${Yf(_T1)}`}`,descriptionForModel:"Haiku 4.5 - fastest for quick answers. Lower cost but less capable than Sonnet 4.6."}}function gjY(){return{value:"haiku",label:"Haiku",description:`Haiku 3.5 for simple tasks${!KA()?"":` · ${Yf(KT1)}`}`,descriptionForModel:"Haiku 3.5 - faster and lower cost, but less capable than Sonnet. Use for simple tasks."}}function UjY(){return xT6()===ZO().haiku45?BvK():gjY()}function k37(){if(MK()==="pro"&&u8("tengu_gypsum_kite",!1))return" · ~2× usage vs Sonnet";return""}function pvK(q=!1){let K=!KA();return{value:"opus",label:"Opus",description:`Opus 4.7 · Most capable for complex work${k37()}${K||!q?"":` · ${Yf(jB)}`}`}}function bvK(){let q=!KA(),K=i7()?" · Billed as extra usage":"";return{value:"sonnet[1m]",label:"Sonnet (1M context)",description:`Sonnet 4.6 with 1M context${K}${!(K!==""&&!q)?"":` · ${Yf(GQ)}`}`}}function IvK(){let q=!KA(),K=i7()?" · Billed as extra usage":"",_=K!==""&&!q;return{value:"opus[1m]",label:"Opus (1M context)",description:`Opus 4.7 with 1M context${k37()}${K}${!_?"":` · ${Yf(jB)}`}`}}function V37(q=!1){let K=!KA();return{value:K?ZO().opus47+"[1m]":"opus[1m]",label:"Opus (1M context)",description:`Opus 4.7 with 1M context · Most capable for complex work${k37()}${K||!q?"":` · ${Yf(jB)}`}`,descriptionForModel:"Opus 4.7 with 1M context - most capable for complex work"}}function djY(){return{value:"opusplan",label:"Opus Plan Mode",description:"Use Opus in plan mode, Sonnet otherwise"}}function cjY(q=!1){if(i7()){if(ch()||Yq6()){let O=[Td8(q)];if(!YX()&&Ql())O.push(IvK());if(O.push(QjY),rt())O.push(bvK());return O.push(xvK),O}let A=[Td8(q)];if(rt())A.push(bvK());if(YX())A.push(V37(!1));else if(A.push(pvK(!1)),Ql())A.push(IvK());return A.push(xvK),A}if(KA()){let A=[Td8(q)];if(rt())A.push(SvK());if(YX())A.push(V37(!0));else if(A.push(RvK()),Ql())A.push(CvK());return A.push(BvK()),A}let K=[Td8(q)],_=ujY();if(_!==void 0)K.push(_);else if(K.push(mjY()),rt())K.push(SvK());let z=BjY();if(z!==void 0)K.push(z);else{if(K.push(pjY()),K.push(RvK()),Ql())K.push(CvK());if(K.push(uvK(q,!1)),Ql())K.push(mvK(q))}let Y=FjY();if(Y!==void 0)K.push(Y);else K.push(UjY());return K}function ljY(q){let K=o5(q);if(K.includes("claude-sonnet-4-6")||K.includes("claude-sonnet-4-5")||K.includes("claude-sonnet-4-")||K.includes("claude-3-7-sonnet")||K.includes("claude-3-5-sonnet")){let _=xW(Af());if(_)return{alias:"Sonnet",currentVersionName:_}}if(K.includes("claude-opus-4")){let _=xW(LE());if(_)return{alias:"Opus",currentVersionName:_}}if(K.includes("claude-haiku")||K.includes("claude-3-5-haiku")){let _=xW(xT6());if(_)return{alias:"Haiku",currentVersionName:_}}return null}function njY(q){let K=xW(q);if(!K)return null;let _=ljY(q);if(!_)return{value:q,label:K,description:q};if(K!==_.currentVersionName)return{value:q,label:K,description:`Newer version available · select ${_.alias} for ${_.currentVersionName}`};return{value:q,label:K,description:q}}function q_6(q=!1){return [{"value":"Claude Sonnet 4.6","label":"Claude Sonnet 4.6","description":"Use the default model Claude Sonnet 4.6 · 1.5x/1.88x per Mtok"},{"value":"Claude Haiku 4.5","label":"Claude Haiku 4.5","description":"Claude Haiku 4.5 模型。0.53x~"},{"value":"Claude Opus 4.6","label":"Claude Opus 4.6","description":"Claude Opus 4.6 for complex tasks · 2.5x/3.12x per Mtok"},{"value":"GPT-5.4","label":"GPT-5.4","description":"GPT-5.4 for complex tasks · 2x/1.5x per Mtok"},{"value":"GPT o3","label":"GPT o3","description":"GPT o3 for complex tasks · 1x/1x per Mtok"},{"value":"Gemini 3 Flash","label":"Gemini 3 Flash","description":"Gemini 2.5 Flash for complex tasks · 0.4x/0.3x per Mtok"},{"value":"Gemini 3.1 Pro Preview","label":"Gemini 3.1 Pro Preview","description":"Gemini 3.1 Pro Preview for complex tasks · 1.6x/1.2x per Mtok"},{"value":"DeepSeek-V3.2","label":"DeepSeek-V3.2","description":"DeepSeek-V3.2 for complex tasks · 0.23x/0.04x per Mtok"},{"value":"DeepSeek-R1","label":"DeepSeek-R1","description":"DeepSeek-R1 for complex tasks · 0.29x/0.29x per Mtok"},{"value":"Qwen-max","label":"Qwen Max","description":"Qwen Max for complex tasks · 0.17x/0.17x per Mtok"},{"value":"Qwen3-Coder-Plus","label":"Qwen3 Coder Plus","description":"Qwen3 Coder Plus for complex tasks · 0.29x/0.29x per Mtok"},{"value":"Kimi-K2-Thinking","label":"Kimi-K2-Thinking","description":"Kimi-K2-Thinking for complex tasks · 0.29x/0.29x per Mtok"},{"value":"Kimi-K2.5","label":"Kimi K2.5","description":"Kimi-K2.5 for complex tasks · 0.36x/0.36x per Mtok"},{"value":"MiniMax-M2.5","label":"MiniMax M2.5","description":"MiniMax-M2.5 for complex tasks · 0.19x/0.19x per Mtok"},{"value":"Doubao-Seed-1.6","label":"Doubao Seed 1.6","description":"DoubanSeed-1.6 for complex tasks · 0.06x/0.04x per Mtok"},{"value":"GLM-5","label":"GLM 5","description":"GLM-5 for complex tasks · 0.46x/0.25x per Mtok"}];let K=cjY(q),_=process.env.ANTHROPIC_CUSTOM_MODEL_OPTION;if(_&&!K.some((w)=>w.value===_))K.push({value:_,label:process.env.ANTHROPIC_CUSTOM_MODEL_OPTION_NAME??_,description:process.env.ANTHROPIC_CUSTOM_MODEL_OPTION_DESCRIPTION??`Custom model (${_})`});for(let w of H8().additionalModelOptionsCache??[])if(!K.some(($)=>$.value===w.value))K.push(w);let{availableModels:z}=y7()??{};if(z)for(let w of z){let $=w.trim();if(!$.startsWith("anthropic.")||K.some((j)=>j.value===$))continue;K.push({value:$,label:$,description:"Custom model"})}let Y=null,A=Ub(),O=cB6();if(A!==void 0&&A!==null)Y=A;else if(O!==null)Y=O;if(Y===null||K.some((w)=>w.value===Y))return RM6(K);else if(Y==="opusplan")return RM6([...K,djY()]);else if(Y==="opus"&&KA())return RM6([...K,pvK(!1)]);else if(Y==="opus[1m]"&&KA())return RM6([...K,V37(!1)]);else if(Y==="claude-opus-4-6"&&KA())return RM6([...K,uvK(q,!1)]);else if(Y==="claude-opus-4-6[1m]"&&KA())return RM6([...K,mvK(q,!1)]);else{let w=njY(Y);if(w)K.push(w);else K.push({value:Y,label:Y,description:"Custom model"});return RM6(K)}}function RM6(q){if(!(y7()||{}).availableModels)return q;return q.filter((_)=>_.value===null||_.value!==null&&Kq6(_.value))}var QjY,xvK;var s58=L(()=>{y8();B1();T7();jQ();fo();a1();bg8();x9();jn6();Sq();AJ();h1();QjY={value:"sonnet",label:"Sonnet",description:"Sonnet 4.6 · Best for everyday tasks"},xvK={value:"haiku",label:"Haiku",description:"Haiku 4.5 · Fastest for quick answers"}});var N37={};h8(N37,{isVoiceModeEnabled:()=>SM6,isVoiceGrowthBookEnabled:()=>K_6,hasVoiceAuth:()=>Vd8});function K_6(){return!u8("tengu_amber_quartz_disabled",!1)}function Vd8(){if(!jX())return!1;let q=o7();return Boolean(q?.accessToken)}function SM6(){return Vd8()&&K_6()}var __6=L(()=>{B1();T7()});async function wI6(q){let K=q.trim();if(!K)return{valid:!1,error:"Model name cannot be empty"};if(!Kq6(K))return{valid:!1,error:`Model '${K}' is not in the list of available models`};let _=K.toLowerCase();if(Yw6.includes(_))return{valid:!0};if(K===process.env.ANTHROPIC_CUSTOM_MODEL_OPTION)return{valid:!0};if(FvK.has(K))return{valid:!0};try{return await dR({model:K,max_tokens:1,maxRetries:0,querySource:"model_validation",messages:[{role:"user",content:[{type:"text",text:"Hi",cache_control:{type:"ephemeral"}}]}]}),FvK.set(K,!0),{valid:!0}}catch(z){return ijY(z,K)}}function ijY(q,K){if(q instanceof fY6){let z=rjY(K),Y=z?`. Try '${z}' instead`:"";return{valid:!1,error:`Model '${K}' not found${Y}`}}if(q instanceof vq){if(q instanceof ZY6)return{valid:!1,error:"Authentication failed. Please check your API credentials."};if(q instanceof bZ)return{valid:!1,error:"Network error. Please check your internet connection."};let z=q.error;if(z&&typeof z==="object"&&"type"in z&&z.type==="not_found_error"&&"message"in z&&typeof z.message==="string"&&z.message.includes("model:"))return{valid:!1,error:`Model '${K}' not found`};return{valid:!1,error:`API error: ${q.message}`}}return{valid:!1,error:`Unable to validate model: ${q instanceof Error?q.message:String(q)}`}}function rjY(q){if(KA())return;let K=q.toLowerCase();if(K.includes("opus-4-7")||K.includes("opus_4_7"))return ZO().opus41;if(K.includes("opus-4-6")||K.includes("opus_4_6"))return ZO().opus41;if(K.includes("opus-4-5")||K.includes("opus_4_5"))return ZO().opus41;if(K.includes("sonnet-4-6")||K.includes("sonnet_4_6"))return ZO().sonnet45;if(K.includes("sonnet-4-5")||K.includes("sonnet_4_5"))return ZO().sonnet40;return}var FvK;var kd8=L(()=>{IT6();jn6();x9();tH6();eG();jQ();FvK=new Map});function gvK(q){return q in $I6}function UvK(q){return $I6[q]}function Nd8(q){let K=$I6[q];if(!K)return;if(K.options)return[...K.options];if(K.getOptions)return K.getOptions();return}function QvK(q){return $I6[q]?.path??q.split(".")}var $I6;var y37=L(()=>{h1();$b1();s58();kd8();tB();$I6={theme:{source:"global",type:"string",description:"Color theme for the UI",options:ZY4},editorMode:{source:"global",type:"string",description:"Key binding mode",options:Ck8},verbose:{source:"global",type:"boolean",description:"Show detailed debug output",appStateKey:"verbose"},preferredNotifChannel:{source:"global",type:"string",description:"Preferred notification channel",options:Sk8},autoCompactEnabled:{source:"global",type:"boolean",description:"Auto-compact when context is full"},autoScrollEnabled:{source:"global",type:"boolean",description:"Auto-scroll conversation to bottom (fullscreen mode only)"},autoMemoryEnabled:{source:"settings",type:"boolean",description:"Enable auto-memory"},autoDreamEnabled:{source:"settings",type:"boolean",description:"Enable background memory consolidation"},fileCheckpointingEnabled:{source:"global",type:"boolean",description:"Enable file checkpointing for code rewind"},showTurnDuration:{source:"global",type:"boolean",description:'Show turn duration message after responses (e.g., "Cooked for 1m 6s")'},terminalProgressBarEnabled:{source:"global",type:"boolean",description:"Show OSC 9;4 progress indicator in supported terminals"},todoFeatureEnabled:{source:"global",type:"boolean",description:"Enable todo/task tracking"},model:{source:"settings",type:"string",description:"Override the default model",appStateKey:"mainLoopModel",getOptions:()=>{try{return q_6().filter((q)=>q.value!==null).map((q)=>q.value)}catch{return["sonnet","opus","haiku"]}},validateOnWrite:(q)=>wI6(String(q)),formatOnRead:(q)=>q===null?"default":q},alwaysThinkingEnabled:{source:"settings",type:"boolean",description:"Enable extended thinking (false to disable)",appStateKey:"thinkingEnabled"},"permissions.defaultMode":{source:"settings",type:"string",description:"Default permission mode for tool usage",options:["default","plan","acceptEdits","dontAsk","auto"]},language:{source:"settings",type:"string",description:'Preferred language for Claude responses and voice dictation (e.g., "japanese", "spanish")'},teammateMode:{source:"global",type:"string",description:'How to spawn teammates: "tmux" for traditional tmux, "in-process" for same process, "auto" to choose automatically',options:Nq4},tui:{source:"settings",type:"string",description:'Terminal UI renderer: "fullscreen" for flicker-free alt-screen rendering, "default" for the classic renderer',options:["default","fullscreen"]},...!1,...{voiceEnabled:{source:"settings",type:"boolean",description:"Enable voice dictation (hold-to-talk)"}},remoteControlAtStartup:{source:"global",type:"boolean",description:"Enable Remote Control for all sessions (true | false | default)",formatOnRead:()=>zd()},...{inputNeededNotifEnabled:{source:"global",type:"boolean",description:"Push to your mobile device when a permission prompt or question is waiting (requires Remote Control)"},agentPushNotifEnabled:{source:"global",type:"boolean",description:"Allow Claude to push to your mobile device when it deems it appropriate (requires Remote Control)"}}}});function cvK(){let q=[],K=[];for(let[z,Y]of Object.entries($I6)){if(z==="model")continue;if(z==="voiceEnabled"&&!K_6())continue;let A=Nd8(z),O=`- ${z}`;if(A)O+=`: ${A.map((w)=>`"${w}"`).join(", ")}`;else if(Y.type==="boolean")O+=": true/false";if(O+=` - ${Y.description}`,Y.source==="global")q.push(O);else K.push(O)}let _=ojY();return`Get or set Claude Code configuration settings.
|
|
4123
|
+
`),(O)=>O.trim()!=="");if(!K)return null;let Y=await w1("git",["-C",q,"rev-list","--count",`${K}..HEAD`]);if(Y.code!==0)return null;let A=parseInt(Y.stdout.trim(),10)||0;return{changedFiles:z,commits:A}}function EvK(q,K){if(l$(q),dL(q),K)pB6(q),KR6();zL(null),nc(),Lk(),aO.cache.clear?.()}var IjY,xjY,yvK;var LvK=L(()=>{p7();y8();OR6();C8();gq();PM();n7();Q4();Bc();NJ();$G();g4();tD();kvK();IjY=C6(()=>y.strictObject({action:y.enum(["keep","remove"]).describe('"keep" leaves the worktree and branch on disk; "remove" deletes both.'),discard_changes:y.boolean().optional().describe('Required true when action is "remove" and the worktree has uncommitted files or unmerged commits. The tool will refuse and list them otherwise.')})),xjY=C6(()=>y.object({action:y.enum(["keep","remove"]),originalCwd:y.string(),worktreePath:y.string(),worktreeBranch:y.string().optional(),tmuxSessionName:y.string().optional(),discardedFiles:y.number().optional(),discardedCommits:y.number().optional(),message:y.string()}));yvK=Iq({name:AI8,searchHint:"exit a worktree session and return to the original directory",maxResultSizeChars:1e5,async description(){return"Exits a worktree session created by EnterWorktree and restores the original working directory"},async prompt(){return vvK()},get inputSchema(){return IjY()},get outputSchema(){return xjY()},userFacingName(){return"Exiting worktree"},shouldDefer:!0,isDestructive(q){return q.action==="remove"},toAutoClassifierInput(q){return q.action},async validateInput(q){if(Sf6())return{result:!1,message:'ExitWorktree cannot be called from a subagent with a cwd override (isolation: "worktree" or explicit cwd) — it would mutate the parent session\'s process-wide working directory. This agent is already isolated; use Bash with `cd` for directory changes within it.',errorCode:5};let K=sO();if(!K)return{result:!1,message:"No-op: there is no active EnterWorktree session to exit. This tool only operates on worktrees created by EnterWorktree in the current session — it will not touch worktrees created manually or in a previous session. No filesystem changes were made.",errorCode:1};if(q.action==="remove"&&K.enteredExisting)return{result:!1,message:`This session entered an existing worktree (${K.worktreePath}); it was not created by EnterWorktree, so this tool will not remove it. Use action: "keep" to return to ${K.originalCwd}, then remove the worktree manually with \`git worktree remove\` if desired.`,errorCode:4};if(q.action==="remove"&&!q.discard_changes){let _=await NvK(K.worktreePath,K.originalHeadCommit);if(_===null)return{result:!1,message:`Could not verify worktree state at ${K.worktreePath}. Refusing to remove without explicit confirmation. Re-invoke with discard_changes: true to proceed — or use action: "keep" to preserve the worktree.`,errorCode:3};let{changedFiles:z,commits:Y}=_;if(z>0||Y>0){let A=[];if(z>0)A.push(`${z} uncommitted ${z===1?"file":"files"}`);if(Y>0)A.push(`${Y} ${Y===1?"commit":"commits"} on ${K.worktreeBranch??"the worktree branch"}`);return{result:!1,message:`Worktree has ${A.join(" and ")}. Removing will discard this work permanently. Confirm with the user, then re-invoke with discard_changes: true — or use action: "keep" to preserve the worktree.`,errorCode:2}}}return{result:!0}},renderToolUseMessage:TvK,renderToolResultMessage:VvK,async call(q){let K=sO();if(!K)throw Error("Not in a worktree session");let{originalCwd:_,worktreePath:z,worktreeBranch:Y,tmuxSessionName:A,originalHeadCommit:O}=K,w=c9()===Y7(),{changedFiles:$,commits:j}=await NvK(z,O)??{changedFiles:0,commits:0};if(q.action==="keep"){await hM6(),EvK(_,w),d("tengu_worktree_kept",{mid_session:!0,commits:j,changed_files:$});let X=A?` Tmux session ${A} is still running; reattach with: tmux attach -t ${A}`:"";return{data:{action:"keep",originalCwd:_,worktreePath:z,worktreeBranch:Y,tmuxSessionName:A,message:`Exited worktree. Your work is preserved at ${z}${Y?` on branch ${Y}`:""}. Session is now back in ${_}.${X}`}}}if(A)await AI6(A);await OI6(),EvK(_,w),d("tengu_worktree_removed",{source:"exit_tool",mid_session:!0,commits:j,changed_files:$});let H=[];if(j>0)H.push(`${j} ${j===1?"commit":"commits"}`);if($>0)H.push(`${$} uncommitted ${$===1?"file":"files"}`);let J=H.length>0?` Discarded ${H.join(" and ")}.`:"";return{data:{action:"remove",originalCwd:_,worktreePath:z,worktreeBranch:Y,discardedFiles:$,discardedCommits:j,message:`Exited and removed worktree at ${z}.${J} Session is now back in ${_}.`}}},mapToolResultToToolResultBlockParam({message:q},K){return{type:"tool_result",content:q,tool_use_id:K}}})});var hvK="Config";function Td8(q=!1){if(i7())return{value:null,label:"Default (recommended)",description:uT6(q)};let K=!KA();return{value:null,label:K?"Default":"Default (recommended)",description:`Use the default model (currently ${Hn6(hv())})${K?"":` · ${Yf(GQ)}`}`}}function ujY(){let q=!KA(),K=process.env.ANTHROPIC_DEFAULT_SONNET_MODEL;if(q&&K){let _=DP(K);return{value:"sonnet",label:process.env.ANTHROPIC_DEFAULT_SONNET_MODEL_NAME??K,description:process.env.ANTHROPIC_DEFAULT_SONNET_MODEL_DESCRIPTION??`Custom Sonnet model${_?" (1M context)":""}`,descriptionForModel:`${process.env.ANTHROPIC_DEFAULT_SONNET_MODEL_DESCRIPTION??`Custom Sonnet model${_?" with 1M context":""}`} (${K})`}}}function mjY(){let q=!KA();return{value:q?ZO().sonnet46:"sonnet",label:"Sonnet",description:`Sonnet 4.6 · Best for everyday tasks${q?"":` · ${Yf(GQ)}`}`,descriptionForModel:"Sonnet 4.6 - best for everyday tasks. Generally recommended for most coding tasks"}}function BjY(){let q=!KA(),K=process.env.ANTHROPIC_DEFAULT_OPUS_MODEL;if(q&&K){let _=DP(K);return{value:"opus",label:process.env.ANTHROPIC_DEFAULT_OPUS_MODEL_NAME??K,description:process.env.ANTHROPIC_DEFAULT_OPUS_MODEL_DESCRIPTION??`Custom Opus model${_?" (1M context)":""}`,descriptionForModel:`${process.env.ANTHROPIC_DEFAULT_OPUS_MODEL_DESCRIPTION??`Custom Opus model${_?" with 1M context":""}`} (${K})`}}}function pjY(){return{value:"opus",label:"Opus 4.1",description:"Opus 4.1 · Legacy",descriptionForModel:"Opus 4.1 - legacy version"}}function uvK(q=!1,K=!0){return{value:!KA()?ZO().opus46:"claude-opus-4-6",label:"Opus 4.6",description:`Opus 4.6 · Most capable for complex work${K?QZ8(q):""}`,descriptionForModel:"Opus 4.6 - most capable for complex work"}}function RvK(){let q=!KA();return{value:q?ZO().opus47:"opus",label:"Opus",description:`Opus 4.7 · Most capable for complex work${q?"":` · ${Yf(jB)}`}`,descriptionForModel:"Opus 4.7 - most capable for complex work"}}function SvK(){let q=!KA();return{value:q?ZO().sonnet46+"[1m]":"sonnet[1m]",label:"Sonnet (1M context)",description:`Sonnet 4.6 for long sessions${q?"":` · ${Yf(GQ)}`}`,descriptionForModel:"Sonnet 4.6 with 1M context window - for long sessions with large codebases"}}function mvK(q=!1,K=!0){return{value:!KA()?ZO().opus46+"[1m]":"claude-opus-4-6[1m]",label:"Opus 4.6 (1M context)",description:`Opus 4.6 for long sessions${K?QZ8(q):""}`,descriptionForModel:"Opus 4.6 with 1M context window - for long sessions with large codebases"}}function CvK(){let q=!KA();return{value:q?ZO().opus47+"[1m]":"opus[1m]",label:"Opus (1M context)",description:`Opus 4.7 for long sessions${q?"":` · ${Yf(jB)}`}`,descriptionForModel:"Opus 4.7 with 1M context window - for long sessions with large codebases"}}function FjY(){let q=!KA(),K=process.env.ANTHROPIC_DEFAULT_HAIKU_MODEL;if(q&&K)return{value:"haiku",label:process.env.ANTHROPIC_DEFAULT_HAIKU_MODEL_NAME??K,description:process.env.ANTHROPIC_DEFAULT_HAIKU_MODEL_DESCRIPTION??"Custom Haiku model",descriptionForModel:`${process.env.ANTHROPIC_DEFAULT_HAIKU_MODEL_DESCRIPTION??"Custom Haiku model"} (${K})`}}function BvK(){return{value:"haiku",label:"Haiku",description:`Haiku 4.5 · Fastest for quick answers${!KA()?"":` · ${Yf(_T1)}`}`,descriptionForModel:"Haiku 4.5 - fastest for quick answers. Lower cost but less capable than Sonnet 4.6."}}function gjY(){return{value:"haiku",label:"Haiku",description:`Haiku 3.5 for simple tasks${!KA()?"":` · ${Yf(KT1)}`}`,descriptionForModel:"Haiku 3.5 - faster and lower cost, but less capable than Sonnet. Use for simple tasks."}}function UjY(){return xT6()===ZO().haiku45?BvK():gjY()}function k37(){if(MK()==="pro"&&u8("tengu_gypsum_kite",!1))return" · ~2× usage vs Sonnet";return""}function pvK(q=!1){let K=!KA();return{value:"opus",label:"Opus",description:`Opus 4.7 · Most capable for complex work${k37()}${K||!q?"":` · ${Yf(jB)}`}`}}function bvK(){let q=!KA(),K=i7()?" · Billed as extra usage":"";return{value:"sonnet[1m]",label:"Sonnet (1M context)",description:`Sonnet 4.6 with 1M context${K}${!(K!==""&&!q)?"":` · ${Yf(GQ)}`}`}}function IvK(){let q=!KA(),K=i7()?" · Billed as extra usage":"",_=K!==""&&!q;return{value:"opus[1m]",label:"Opus (1M context)",description:`Opus 4.7 with 1M context${k37()}${K}${!_?"":` · ${Yf(jB)}`}`}}function V37(q=!1){let K=!KA();return{value:K?ZO().opus47+"[1m]":"opus[1m]",label:"Opus (1M context)",description:`Opus 4.7 with 1M context · Most capable for complex work${k37()}${K||!q?"":` · ${Yf(jB)}`}`,descriptionForModel:"Opus 4.7 with 1M context - most capable for complex work"}}function djY(){return{value:"opusplan",label:"Opus Plan Mode",description:"Use Opus in plan mode, Sonnet otherwise"}}function cjY(q=!1){if(i7()){if(ch()||Yq6()){let O=[Td8(q)];if(!YX()&&Ql())O.push(IvK());if(O.push(QjY),rt())O.push(bvK());return O.push(xvK),O}let A=[Td8(q)];if(rt())A.push(bvK());if(YX())A.push(V37(!1));else if(A.push(pvK(!1)),Ql())A.push(IvK());return A.push(xvK),A}if(KA()){let A=[Td8(q)];if(rt())A.push(SvK());if(YX())A.push(V37(!0));else if(A.push(RvK()),Ql())A.push(CvK());return A.push(BvK()),A}let K=[Td8(q)],_=ujY();if(_!==void 0)K.push(_);else if(K.push(mjY()),rt())K.push(SvK());let z=BjY();if(z!==void 0)K.push(z);else{if(K.push(pjY()),K.push(RvK()),Ql())K.push(CvK());if(K.push(uvK(q,!1)),Ql())K.push(mvK(q))}let Y=FjY();if(Y!==void 0)K.push(Y);else K.push(UjY());return K}function ljY(q){let K=o5(q);if(K.includes("claude-sonnet-4-6")||K.includes("claude-sonnet-4-5")||K.includes("claude-sonnet-4-")||K.includes("claude-3-7-sonnet")||K.includes("claude-3-5-sonnet")){let _=xW(Af());if(_)return{alias:"Sonnet",currentVersionName:_}}if(K.includes("claude-opus-4")){let _=xW(LE());if(_)return{alias:"Opus",currentVersionName:_}}if(K.includes("claude-haiku")||K.includes("claude-3-5-haiku")){let _=xW(xT6());if(_)return{alias:"Haiku",currentVersionName:_}}return null}function njY(q){let K=xW(q);if(!K)return null;let _=ljY(q);if(!_)return{value:q,label:K,description:q};if(K!==_.currentVersionName)return{value:q,label:K,description:`Newer version available · select ${_.alias} for ${_.currentVersionName}`};return{value:q,label:K,description:q}}function q_6(q=!1){return [{"value":"Claude Sonnet 4.6","label":"Claude Sonnet 4.6","description":"Use the default model Claude Sonnet 4.6 · 1.5x/1.88x per Mtok"},{"value":"Claude Haiku 4.5","label":"Claude Haiku 4.5","description":"Claude Haiku 4.5 模型。0.53x~"},{"value":"Claude Opus 4.7","label":"Claude Opus 4.7","description":"Claude Opus 4.7 for complex tasks · 2.5x/3.12x per Mtok"},{"value":"GPT-5.4","label":"GPT-5.4","description":"GPT-5.4 for complex tasks · 2x/1.5x per Mtok"},{"value":"GPT o3","label":"GPT o3","description":"GPT o3 for complex tasks · 1x/1x per Mtok"},{"value":"Gemini 3 Flash","label":"Gemini 3 Flash","description":"Gemini 2.5 Flash for complex tasks · 0.4x/0.3x per Mtok"},{"value":"Gemini 3.1 Pro Preview","label":"Gemini 3.1 Pro Preview","description":"Gemini 3.1 Pro Preview for complex tasks · 1.6x/1.2x per Mtok"},{"value":"DeepSeek-V3.2","label":"DeepSeek-V3.2","description":"DeepSeek-V3.2 for complex tasks · 0.23x/0.04x per Mtok"},{"value":"DeepSeek-R1","label":"DeepSeek-R1","description":"DeepSeek-R1 for complex tasks · 0.29x/0.29x per Mtok"},{"value":"Qwen-max","label":"Qwen Max","description":"Qwen Max for complex tasks · 0.17x/0.17x per Mtok"},{"value":"Qwen3-Coder-Plus","label":"Qwen3 Coder Plus","description":"Qwen3 Coder Plus for complex tasks · 0.29x/0.29x per Mtok"},{"value":"Kimi-K2-Thinking","label":"Kimi-K2-Thinking","description":"Kimi-K2-Thinking for complex tasks · 0.29x/0.29x per Mtok"},{"value":"Kimi-K2.5","label":"Kimi K2.5","description":"Kimi-K2.5 for complex tasks · 0.36x/0.36x per Mtok"},{"value":"MiniMax-M2.5","label":"MiniMax M2.5","description":"MiniMax-M2.5 for complex tasks · 0.19x/0.19x per Mtok"},{"value":"Doubao-Seed-1.6","label":"Doubao Seed 1.6","description":"DoubanSeed-1.6 for complex tasks · 0.06x/0.04x per Mtok"},{"value":"GLM-5","label":"GLM 5","description":"GLM-5 for complex tasks · 0.46x/0.25x per Mtok"}];let K=cjY(q),_=process.env.ANTHROPIC_CUSTOM_MODEL_OPTION;if(_&&!K.some((w)=>w.value===_))K.push({value:_,label:process.env.ANTHROPIC_CUSTOM_MODEL_OPTION_NAME??_,description:process.env.ANTHROPIC_CUSTOM_MODEL_OPTION_DESCRIPTION??`Custom model (${_})`});for(let w of H8().additionalModelOptionsCache??[])if(!K.some(($)=>$.value===w.value))K.push(w);let{availableModels:z}=y7()??{};if(z)for(let w of z){let $=w.trim();if(!$.startsWith("anthropic.")||K.some((j)=>j.value===$))continue;K.push({value:$,label:$,description:"Custom model"})}let Y=null,A=Ub(),O=cB6();if(A!==void 0&&A!==null)Y=A;else if(O!==null)Y=O;if(Y===null||K.some((w)=>w.value===Y))return RM6(K);else if(Y==="opusplan")return RM6([...K,djY()]);else if(Y==="opus"&&KA())return RM6([...K,pvK(!1)]);else if(Y==="opus[1m]"&&KA())return RM6([...K,V37(!1)]);else if(Y==="claude-opus-4-6"&&KA())return RM6([...K,uvK(q,!1)]);else if(Y==="claude-opus-4-6[1m]"&&KA())return RM6([...K,mvK(q,!1)]);else{let w=njY(Y);if(w)K.push(w);else K.push({value:Y,label:Y,description:"Custom model"});return RM6(K)}}function RM6(q){if(!(y7()||{}).availableModels)return q;return q.filter((_)=>_.value===null||_.value!==null&&Kq6(_.value))}var QjY,xvK;var s58=L(()=>{y8();B1();T7();jQ();fo();a1();bg8();x9();jn6();Sq();AJ();h1();QjY={value:"sonnet",label:"Sonnet",description:"Sonnet 4.6 · Best for everyday tasks"},xvK={value:"haiku",label:"Haiku",description:"Haiku 4.5 · Fastest for quick answers"}});var N37={};h8(N37,{isVoiceModeEnabled:()=>SM6,isVoiceGrowthBookEnabled:()=>K_6,hasVoiceAuth:()=>Vd8});function K_6(){return!u8("tengu_amber_quartz_disabled",!1)}function Vd8(){if(!jX())return!1;let q=o7();return Boolean(q?.accessToken)}function SM6(){return Vd8()&&K_6()}var __6=L(()=>{B1();T7()});async function wI6(q){let K=q.trim();if(!K)return{valid:!1,error:"Model name cannot be empty"};if(!Kq6(K))return{valid:!1,error:`Model '${K}' is not in the list of available models`};let _=K.toLowerCase();if(Yw6.includes(_))return{valid:!0};if(K===process.env.ANTHROPIC_CUSTOM_MODEL_OPTION)return{valid:!0};if(FvK.has(K))return{valid:!0};try{return await dR({model:K,max_tokens:1,maxRetries:0,querySource:"model_validation",messages:[{role:"user",content:[{type:"text",text:"Hi",cache_control:{type:"ephemeral"}}]}]}),FvK.set(K,!0),{valid:!0}}catch(z){return ijY(z,K)}}function ijY(q,K){if(q instanceof fY6){let z=rjY(K),Y=z?`. Try '${z}' instead`:"";return{valid:!1,error:`Model '${K}' not found${Y}`}}if(q instanceof vq){if(q instanceof ZY6)return{valid:!1,error:"Authentication failed. Please check your API credentials."};if(q instanceof bZ)return{valid:!1,error:"Network error. Please check your internet connection."};let z=q.error;if(z&&typeof z==="object"&&"type"in z&&z.type==="not_found_error"&&"message"in z&&typeof z.message==="string"&&z.message.includes("model:"))return{valid:!1,error:`Model '${K}' not found`};return{valid:!1,error:`API error: ${q.message}`}}return{valid:!1,error:`Unable to validate model: ${q instanceof Error?q.message:String(q)}`}}function rjY(q){if(KA())return;let K=q.toLowerCase();if(K.includes("opus-4-7")||K.includes("opus_4_7"))return ZO().opus41;if(K.includes("opus-4-6")||K.includes("opus_4_6"))return ZO().opus41;if(K.includes("opus-4-5")||K.includes("opus_4_5"))return ZO().opus41;if(K.includes("sonnet-4-6")||K.includes("sonnet_4_6"))return ZO().sonnet45;if(K.includes("sonnet-4-5")||K.includes("sonnet_4_5"))return ZO().sonnet40;return}var FvK;var kd8=L(()=>{IT6();jn6();x9();tH6();eG();jQ();FvK=new Map});function gvK(q){return q in $I6}function UvK(q){return $I6[q]}function Nd8(q){let K=$I6[q];if(!K)return;if(K.options)return[...K.options];if(K.getOptions)return K.getOptions();return}function QvK(q){return $I6[q]?.path??q.split(".")}var $I6;var y37=L(()=>{h1();$b1();s58();kd8();tB();$I6={theme:{source:"global",type:"string",description:"Color theme for the UI",options:ZY4},editorMode:{source:"global",type:"string",description:"Key binding mode",options:Ck8},verbose:{source:"global",type:"boolean",description:"Show detailed debug output",appStateKey:"verbose"},preferredNotifChannel:{source:"global",type:"string",description:"Preferred notification channel",options:Sk8},autoCompactEnabled:{source:"global",type:"boolean",description:"Auto-compact when context is full"},autoScrollEnabled:{source:"global",type:"boolean",description:"Auto-scroll conversation to bottom (fullscreen mode only)"},autoMemoryEnabled:{source:"settings",type:"boolean",description:"Enable auto-memory"},autoDreamEnabled:{source:"settings",type:"boolean",description:"Enable background memory consolidation"},fileCheckpointingEnabled:{source:"global",type:"boolean",description:"Enable file checkpointing for code rewind"},showTurnDuration:{source:"global",type:"boolean",description:'Show turn duration message after responses (e.g., "Cooked for 1m 6s")'},terminalProgressBarEnabled:{source:"global",type:"boolean",description:"Show OSC 9;4 progress indicator in supported terminals"},todoFeatureEnabled:{source:"global",type:"boolean",description:"Enable todo/task tracking"},model:{source:"settings",type:"string",description:"Override the default model",appStateKey:"mainLoopModel",getOptions:()=>{try{return q_6().filter((q)=>q.value!==null).map((q)=>q.value)}catch{return["sonnet","opus","haiku"]}},validateOnWrite:(q)=>wI6(String(q)),formatOnRead:(q)=>q===null?"default":q},alwaysThinkingEnabled:{source:"settings",type:"boolean",description:"Enable extended thinking (false to disable)",appStateKey:"thinkingEnabled"},"permissions.defaultMode":{source:"settings",type:"string",description:"Default permission mode for tool usage",options:["default","plan","acceptEdits","dontAsk","auto"]},language:{source:"settings",type:"string",description:'Preferred language for Claude responses and voice dictation (e.g., "japanese", "spanish")'},teammateMode:{source:"global",type:"string",description:'How to spawn teammates: "tmux" for traditional tmux, "in-process" for same process, "auto" to choose automatically',options:Nq4},tui:{source:"settings",type:"string",description:'Terminal UI renderer: "fullscreen" for flicker-free alt-screen rendering, "default" for the classic renderer',options:["default","fullscreen"]},...!1,...{voiceEnabled:{source:"settings",type:"boolean",description:"Enable voice dictation (hold-to-talk)"}},remoteControlAtStartup:{source:"global",type:"boolean",description:"Enable Remote Control for all sessions (true | false | default)",formatOnRead:()=>zd()},...{inputNeededNotifEnabled:{source:"global",type:"boolean",description:"Push to your mobile device when a permission prompt or question is waiting (requires Remote Control)"},agentPushNotifEnabled:{source:"global",type:"boolean",description:"Allow Claude to push to your mobile device when it deems it appropriate (requires Remote Control)"}}}});function cvK(){let q=[],K=[];for(let[z,Y]of Object.entries($I6)){if(z==="model")continue;if(z==="voiceEnabled"&&!K_6())continue;let A=Nd8(z),O=`- ${z}`;if(A)O+=`: ${A.map((w)=>`"${w}"`).join(", ")}`;else if(Y.type==="boolean")O+=": true/false";if(O+=` - ${Y.description}`,Y.source==="global")q.push(O);else K.push(O)}let _=ojY();return`Get or set Claude Code configuration settings.
|
|
4124
4124
|
|
|
4125
4125
|
View or change Claude Code settings. Use when the user requests configuration changes, asks about current settings, or when adjusting a setting would benefit them.
|
|
4126
4126
|
|
package/dist/coder.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var it=Object.create;var de=Object.defineProperty;var at=Object.getOwnPropertyDescriptor;var ct=Object.getOwnPropertyNames;var lt=Object.getPrototypeOf,ut=Object.prototype.hasOwnProperty;var m=(h,e)=>()=>(e||h((e={exports:{}}).exports,e),e.exports);var dt=(h,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ct(e))!ut.call(h,o)&&o!==t&&de(h,o,{get:()=>e[o],enumerable:!(s=at(e,o))||s.enumerable});return h};var ht=(h,e,t)=>(t=h!=null?it(lt(h)):{},dt(e||!h||!h.__esModule?de(t,"default",{value:h,enumerable:!0}):t,h));var
|
|
2
|
+
var it=Object.create;var de=Object.defineProperty;var at=Object.getOwnPropertyDescriptor;var ct=Object.getOwnPropertyNames;var lt=Object.getPrototypeOf,ut=Object.prototype.hasOwnProperty;var m=(h,e)=>()=>(e||h((e={exports:{}}).exports,e),e.exports);var dt=(h,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ct(e))!ut.call(h,o)&&o!==t&&de(h,o,{get:()=>e[o],enumerable:!(s=at(e,o))||s.enumerable});return h};var ht=(h,e,t)=>(t=h!=null?it(lt(h)):{},dt(e||!h||!h.__esModule?de(t,"default",{value:h,enumerable:!0}):t,h));var pe=m((rs,he)=>{var pt=require("http"),z=class{constructor(e={}){this.port=e.port||9380,this.timeout=e.timeout||300*1e3,this.server=null,this.timeoutId=null}validateTokenFormat(e){if(!e||typeof e!="string")return!1;let t=e.split(".");if(t.length!==2)return!1;let[s,o]=t;return s&&s.length>0&&o&&o.length>0}async waitForCallback(e){return new Promise((t,s)=>{let o=!1;this.server=pt.createServer((r,n)=>{let i=new URL(r.url,`http://localhost:${this.port}`);if(i.pathname==="/callback"){let a=i.searchParams.get("token"),c=i.searchParams.get("state"),l=i.searchParams.get("error");if(l){n.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),n.end(`
|
|
3
3
|
<!DOCTYPE html>
|
|
4
4
|
<html>
|
|
5
5
|
<head>
|
|
@@ -124,7 +124,7 @@ var it=Object.create;var de=Object.defineProperty;var at=Object.getOwnPropertyDe
|
|
|
124
124
|
</script>
|
|
125
125
|
</body>
|
|
126
126
|
</html>
|
|
127
|
-
`),o||(o=!0,this.cleanup(),t({ak:u,sk:d}))}else n.writeHead(404,{"Content-Type":"text/plain"}),n.end("Not Found")}),this.server.on("error",r=>{if(r.code==="EADDRINUSE"){if(this.port++,this.port>9390){o||(o=!0,s(new Error("Could not find available port for OAuth callback server")));return}this.server.close(),this.server.listen(this.port)}else o||(o=!0,this.cleanup(),s(r))}),this.server.listen(this.port,()=>{process.env.CODEV_DEBUG&&console.log(`OAuth callback server listening on port ${this.port}`)}),this.timeoutId=setTimeout(()=>{o||(o=!0,this.cleanup(),s(new Error("OAuth login timeout - no response received within 5 minutes")))},this.timeout)})}getCallbackUrl(){return`http://localhost:${this.port}/callback`}cleanup(){this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),this.server&&(this.server.close(),this.server=null)}};he.exports=z});var
|
|
127
|
+
`),o||(o=!0,this.cleanup(),t({ak:u,sk:d}))}else n.writeHead(404,{"Content-Type":"text/plain"}),n.end("Not Found")}),this.server.on("error",r=>{if(r.code==="EADDRINUSE"){if(this.port++,this.port>9390){o||(o=!0,s(new Error("Could not find available port for OAuth callback server")));return}this.server.close(),this.server.listen(this.port)}else o||(o=!0,this.cleanup(),s(r))}),this.server.listen(this.port,()=>{process.env.CODEV_DEBUG&&console.log(`OAuth callback server listening on port ${this.port}`)}),this.timeoutId=setTimeout(()=>{o||(o=!0,this.cleanup(),s(new Error("OAuth login timeout - no response received within 5 minutes")))},this.timeout)})}getCallbackUrl(){return`http://localhost:${this.port}/callback`}cleanup(){this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),this.server&&(this.server.close(),this.server=null)}};he.exports=z});var ge=m((is,fe)=>{var ft=require("crypto"),gt=pe(),W=class{constructor(e={}){this.baseUrl=e.baseUrl||"https://makecoder.com",this.callbackServer=null}generateState(){return ft.randomBytes(16).toString("hex")}buildAuthorizationUrl(e,t){let s=new URLSearchParams({redirect_uri:e,state:t,response_type:"token"});return`${this.baseUrl}/oauth/authorize?${s.toString()}`}async login(){let e=this.generateState();this.callbackServer=new gt;try{let t=this.callbackServer.getCallbackUrl(),s=this.buildAuthorizationUrl(t,e);console.log(`
|
|
128
128
|
\u{1F510} \u5F00\u59CB OAuth \u767B\u5F55\u6D41\u7A0B...
|
|
129
129
|
`),console.log(`\u{1F4CB} \u8BF7\u5728\u6D4F\u89C8\u5668\u4E2D\u5B8C\u6210\u767B\u5F55
|
|
130
130
|
`),console.log(`\u{1F310} \u6388\u6743\u5730\u5740: ${s}
|
|
@@ -132,7 +132,7 @@ var it=Object.create;var de=Object.defineProperty;var at=Object.getOwnPropertyDe
|
|
|
132
132
|
`);try{let r=(await import("open")).default;await r(s)}catch(r){console.warn("\u26A0\uFE0F \u65E0\u6CD5\u81EA\u52A8\u6253\u5F00\u6D4F\u89C8\u5668,\u8BF7\u624B\u52A8\u590D\u5236\u4E0A\u8FF0\u94FE\u63A5\u5230\u6D4F\u89C8\u5668\u6253\u5F00"),process.env.CODEV_DEBUG&&console.error("Browser open error:",r)}let o=await this.callbackServer.waitForCallback(e);return console.log(`\u2705 API Key \u83B7\u53D6\u6210\u529F!
|
|
133
133
|
`),o}catch(t){throw console.error(`
|
|
134
134
|
\u274C OAuth \u767B\u5F55\u5931\u8D25: ${t.message}
|
|
135
|
-
`),t}finally{this.callbackServer&&this.callbackServer.cleanup()}}cleanup(){this.callbackServer&&this.callbackServer.cleanup()}};
|
|
135
|
+
`),t}finally{this.callbackServer&&this.callbackServer.cleanup()}}cleanup(){this.callbackServer&&this.callbackServer.cleanup()}};fe.exports=W});var Ce=m((as,Se)=>{var P=require("fs"),me=require("path"),mt=require("os"),ye=require("readline"),yt=ge(),wt=new Set(["login","skills","wiki"]),we=new Set(["claude","gemini","codex"]),St=new Set(["pub","login","update","skills","wiki"]),J=class{constructor(){this.configPath=me.join(mt.homedir(),".coder","config.json"),this.defaultConfig={agent:"claude",auth:{ak:null,sk:null}}}loadConfig(){let e=me.dirname(this.configPath);try{return P.existsSync(e)||P.mkdirSync(e,{recursive:!0}),P.existsSync(this.configPath)||P.writeFileSync(this.configPath,JSON.stringify(this.defaultConfig,null,2)),JSON.parse(P.readFileSync(this.configPath,"utf8"))}catch{return{...this.defaultConfig}}}saveAuthToConfig(e,t){let s=this.loadConfig();s.auth={...s.auth,ak:e,sk:t};try{return P.writeFileSync(this.configPath,JSON.stringify(s,null,2)),!0}catch{return!1}}clearAuthFromConfig(){let e=this.loadConfig();e.auth&&(e.auth={ak:null,sk:null});try{return P.writeFileSync(this.configPath,JSON.stringify(e,null,2)),!0}catch{return!1}}promptForAKSK(){let e=ye.createInterface({input:process.stdin,output:process.stdout});return new Promise((t,s)=>{console.log(`
|
|
136
136
|
\u{1F510} \u8BF7\u8F93\u5165\u60A8\u7684 API Key\uFF1A`),e.question("\u8BF7\u8F93\u5165 API Key: ",o=>{e.close();let r=o.indexOf(".");if(r<=0||r===o.length-1)return s(new Error("\u683C\u5F0F\u9519\u8BEF"));let n=o.substring(0,r).trim(),i=o.substring(r+1).trim();if(!n||!i)return s(new Error("\u683C\u5F0F\u9519\u8BEF"));t({ak:n,sk:i})})})}promptForName(){let e=ye.createInterface({input:process.stdin,output:process.stdout});return new Promise((t,s)=>{e.question("\u8BF7\u8F93\u5165\u9879\u76EE\u540D\u79F0 (name): ",o=>{e.close();let r=o.trim();if(!r)return s(new Error("\u9879\u76EE\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A"));if(!/^[a-zA-Z0-9_-]+$/.test(r))return s(new Error("\u9879\u76EE\u540D\u79F0\u53EA\u80FD\u5305\u542B\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u4E0B\u5212\u7EBF\u548C\u8FDE\u5B57\u7B26"));t(r)})})}async parse(e=process.argv.slice(2)){let t=this.loadConfig(),s={agent:t.agent||"claude",remainingArgs:[]},o=0;if(e.length>0){if(we.has(e[0]))s.agent=e[0],s.agentSetBySubcommand=!0,o=1;else if(St.has(e[0])){if(s.command=e[0],o=1,e[0]==="skills"){let n=e[1];s.skillsSubcommand=n==="--help"||n==="-h"?void 0:n,s.skillsArg=e[2],s.skillsRemainingArgs=e.slice(2),o=e.length}else if(e[0]==="wiki"){let n=e[1];s.wikiSubcommand=n==="--help"||n==="-h"?void 0:n,s.wikiArg=e[2],s.wikiRemainingArgs=e.slice(2),o=e.length}}}for(;o<e.length;){let n=e[o];if(n==="--agent"){if(s.agentSetBySubcommand)throw new Error(`\u4E0D\u80FD\u540C\u65F6\u4F7F\u7528\u5B50\u547D\u4EE4 '${s.agent}' \u548C --agent\uFF0C\u8BF7\u9009\u62E9\u5176\u4E00`);let i=e[o+1];if(!i||!we.has(i))throw new Error("--agent \u9700\u8981\u6307\u5B9A\u4EE3\u7406\u7C7B\u578B\uFF08claude|gemini|codex\uFF09");s.agent=i,o+=2}else if(n==="--apikey"||n==="--aksk"){let i=e[o+1];if(!i||i.startsWith("--"))s.needAKSKPrompt=!0,o+=1;else{let a=i.indexOf(".");if(a===-1)throw new Error("API Key \u683C\u5F0F\u9519\u8BEF\uFF0C\u5E94\u4E3A <ak>.<sk>");s.auth_ak=i.substring(0,a),s.auth_sk=i.substring(a+1),o+=2}}else if(n==="--save-auth")s.saveAuth=!0,o+=1;else if(n==="--clear-auth")s.clearAuth=!0,o+=1;else if(n==="--name"){let i=e[o+1];i&&!i.startsWith("--")?(s.pubName=i,o+=2):o+=1}else if(n==="--allow-clone")s.allowClone=!0,o+=1;else if(n==="--meta-data"){let i=e[o+1];if(!i||i.startsWith("--"))throw new Error("--meta-data \u9700\u8981\u4E00\u4E2A JSON \u5B57\u7B26\u4E32\u503C");try{JSON.parse(i)}catch(a){throw new Error(`--meta-data \u4E0D\u662F\u5408\u6CD5\u7684 JSON\uFF1A${a.message}`)}s.pubMetaData=i,o+=2}else{s.remainingArgs=e.slice(o);break}}if(s.needAKSKPrompt)try{let{ak:n,sk:i}=await this.promptForAKSK();s.auth_ak=n,s.auth_sk=i,delete s.needAKSKPrompt}catch(n){console.error(`\u274C ${n.message}`),process.exit(1)}s.clearAuth&&(console.log(this.clearAuthFromConfig()?"\u2705 API Key \u5DF2\u4ECE\u914D\u7F6E\u6587\u4EF6\u6E05\u9664":"\u274C \u6E05\u9664 API Key \u5931\u8D25"),process.exit(0)),s.saveAuth&&s.auth_ak&&s.auth_sk&&(console.log(this.saveAuthToConfig(s.auth_ak,s.auth_sk)?"\u2705 API Key \u5DF2\u4FDD\u5B58\u5230\u914D\u7F6E\u6587\u4EF6":"\u274C \u4FDD\u5B58 API Key \u5931\u8D25"),process.exit(0)),s.command!=="login"&&(s.auth_ak||=t.auth?.ak||process.env.CODEV_AUTH_AK,s.auth_sk||=t.auth?.sk||process.env.CODEV_AUTH_SK),s.codevServer=process.env.CODEV_SERVER||t.codevServer||"https://makecoder.com/bigapis/codev/v1";let r=s.remainingArgs.includes("--version")||s.remainingArgs.includes("-v")||s.remainingArgs.includes("--help")||s.remainingArgs.includes("-h");return!wt.has(s.command)&&!r&&(!s.auth_ak||!s.auth_sk)&&await this._oauthLogin(s),s}async _oauthLogin(e){console.log(`\u274C \u7F3A\u5C11\u5FC5\u8981\u7684 API Key
|
|
137
137
|
`),console.log(`\u{1F510} \u6B63\u5728\u542F\u52A8\u767B\u5F55\u6D41\u7A0B...
|
|
138
138
|
`);try{let s=await new yt({baseUrl:"https://makecoder.com",apiBaseUrl:e.codevServer}).login();e.auth_ak=s.ak,e.auth_sk=s.sk,console.log(this.saveAuthToConfig(s.ak,s.sk)?`\u2705 API Key \u5DF2\u81EA\u52A8\u4FDD\u5B58\u5230\u914D\u7F6E\u6587\u4EF6
|
|
@@ -188,13 +188,13 @@ AI \u4EE3\u7406:
|
|
|
188
188
|
coder wiki --help # \u67E5\u770B wiki \u5B50\u547D\u4EE4\u5E2E\u52A9
|
|
189
189
|
|
|
190
190
|
\u914D\u7F6E\u6587\u4EF6: ~/.coder/config.json
|
|
191
|
-
`)}};Se.exports=J});var R=m((cs,Ee)=>{function Ct(h=process.argv.slice(2)){return h.includes("--print")||h.includes("-p")}Ee.exports={isPrintMode:Ct}});var H=m((ls,Ie)=>{var{spawn:Et}=require("child_process"),M=require("path"),k=require("fs"),ve=require("os"),{isPrintMode:be}=R(),Q=class{constructor(e){this.config=e}resloveSettingFilePath(e){return M.join(e,this.config.configDir,"settings.json")}readModelFromSettingsFile(e){try{let t=this.resloveSettingFilePath(e);if(k.existsSync(t)){let s=k.readFileSync(t,"utf8"),o=JSON.parse(s);if(o&&o.model)return o.model}}catch(t){console.warn(e,t.message)}return null}getCurrentModel(e){let t=e.findIndex(o=>o==="--model");if(t!==-1&&t+1<e.length)return e[t+1];let s=this.readModelFromSettingsFile(process.cwd());return s||(s=this.readModelFromSettingsFile(ve.homedir()),s)?s:this.config.defaultModel}async ensureConfig(e=0){let t=M.join(ve.homedir(),this.config.configDir,this.config.configFile),s=M.dirname(t);if(!k.existsSync(t)){let o=this.config.defaultConfig||{};try{k.existsSync(s)||k.mkdirSync(s,{recursive:!0}),k.writeFileSync(t,JSON.stringify(o,null,2)),e>0&&await new Promise(r=>setTimeout(r,e))}catch(r){console.warn(`Failed to create ${this.config.configFile}: ${r.message}`)}}}findExecutablePath(){let e=M.dirname(require.main.filename);for(let t of this.config.executablePaths){let s=M.resolve(e,t);if(k.existsSync(s))return s}throw new Error(`Could not find executable in any of the configured paths: ${this.config.executablePaths.join(", ")}`)}handleChildMessages(e){process.env.CODEV_DEBUG&&console.log("Child process message handler initialized"),e.connected&&(e.on("message",t=>{this.onChildMessage(t)}),e.on("exit",async(t,s)=>{try{await this.handleChildProcessExit(t,s)}catch(o){console.error("Error in handleChildProcessExit:",o.message)}}),e.on("error",t=>{this.handleChildProcessError(t)}))}onChildMessage(e){process.env.CODEV_DEBUG&&console.log("Received IPC message from child:",e)}handleChildProcessExit(e,t){}handleChildProcessError(e){}async launch(e={}){let{remainingArgs:t=[],codevServer:s,auth_ak:o=null,auth_sk:r=null}=e;try{let n=this.getCurrentModel(t);be(t)||console.log(`model:\x1B[90m\x1B[3m ${n} (use /model to switch models) \x1B[0m`),await this.ensureConfig(1e3);let i=this.findExecutablePath();return process.env.CODEV_DEBUG&&console.log(`executablePath: ${i}`),new Promise((a,c)=>{let l={...process.env,...this.config.environmentVariables(s)};o&&(l.CODEV_AUTH_AK=o),r&&(l.CODEV_AUTH_SK=r);let u=["--no-warnings"];process.env.CODEV_INSPECT_BRK==="True"&&u.push("--inspect-brk"),u.push(i,...t);let d=Et("node",u,{env:l,stdio:["inherit","inherit","inherit","ipc"]});this.handleChildMessages(d),d.on("error",
|
|
191
|
+
`)}};Se.exports=J});var R=m((cs,Ee)=>{function Ct(h=process.argv.slice(2)){return h.includes("--print")||h.includes("-p")}Ee.exports={isPrintMode:Ct}});var H=m((ls,Ie)=>{var{spawn:Et}=require("child_process"),M=require("path"),k=require("fs"),ve=require("os"),{isPrintMode:be}=R(),Q=class{constructor(e){this.config=e}resloveSettingFilePath(e){return M.join(e,this.config.configDir,"settings.json")}readModelFromSettingsFile(e){try{let t=this.resloveSettingFilePath(e);if(k.existsSync(t)){let s=k.readFileSync(t,"utf8"),o=JSON.parse(s);if(o&&o.model)return o.model}}catch(t){console.warn(e,t.message)}return null}getCurrentModel(e){let t=e.findIndex(o=>o==="--model");if(t!==-1&&t+1<e.length)return e[t+1];let s=this.readModelFromSettingsFile(process.cwd());return s||(s=this.readModelFromSettingsFile(ve.homedir()),s)?s:this.config.defaultModel}async ensureConfig(e=0){let t=M.join(ve.homedir(),this.config.configDir,this.config.configFile),s=M.dirname(t);if(!k.existsSync(t)){let o=this.config.defaultConfig||{};try{k.existsSync(s)||k.mkdirSync(s,{recursive:!0}),k.writeFileSync(t,JSON.stringify(o,null,2)),e>0&&await new Promise(r=>setTimeout(r,e))}catch(r){console.warn(`Failed to create ${this.config.configFile}: ${r.message}`)}}}findExecutablePath(){let e=M.dirname(require.main.filename);for(let t of this.config.executablePaths){let s=M.resolve(e,t);if(k.existsSync(s))return s}throw new Error(`Could not find executable in any of the configured paths: ${this.config.executablePaths.join(", ")}`)}handleChildMessages(e){process.env.CODEV_DEBUG&&console.log("Child process message handler initialized"),e.connected&&(e.on("message",t=>{this.onChildMessage(t)}),e.on("exit",async(t,s)=>{try{await this.handleChildProcessExit(t,s)}catch(o){console.error("Error in handleChildProcessExit:",o.message)}}),e.on("error",t=>{this.handleChildProcessError(t)}))}onChildMessage(e){process.env.CODEV_DEBUG&&console.log("Received IPC message from child:",e)}handleChildProcessExit(e,t){}handleChildProcessError(e){}async launch(e={}){let{remainingArgs:t=[],codevServer:s,auth_ak:o=null,auth_sk:r=null}=e;try{let n=this.getCurrentModel(t);be(t)||console.log(`model:\x1B[90m\x1B[3m ${n} (use /model to switch models) \x1B[0m`),await this.ensureConfig(1e3);let i=this.findExecutablePath();return process.env.CODEV_DEBUG&&console.log(`executablePath: ${i}`),new Promise((a,c)=>{let l={...process.env,...this.config.environmentVariables(s)};o&&(l.CODEV_AUTH_AK=o),r&&(l.CODEV_AUTH_SK=r);let u=["--no-warnings"];process.env.CODEV_INSPECT_BRK==="True"&&u.push("--inspect-brk"),u.push(i,...t);let d=Et("node",u,{env:l,stdio:["inherit","inherit","inherit","ipc"]});this.handleChildMessages(d),d.on("error",p=>{console.error(`Failed to start: ${p.message}`),c(p)}),d.on("exit",async(p,C)=>{be(t)||C&&console.log(`terminated by signal: ${C}`)}),process.on("SIGINT",async()=>{console.log(`
|
|
192
192
|
Terminating ...`),d.kill("SIGTERM"),setTimeout(()=>{d.killed||d.kill("SIGKILL")},8e3)}),process.on("SIGTERM",async()=>{console.log(`
|
|
193
|
-
Terminating ...`),d.kill("SIGTERM"),setTimeout(()=>{d.killed||d.kill("SIGKILL")},8e3)})})}catch(n){throw n}}};Ie.exports=Q});var xe=m((us,$e)=>{var f=process.env.CODEV_DEBUG==="True",Y=class{constructor(e={}){this.queue=[],this.processing=!1,this.shuttingDown=!1,this.shutdownTimeout=e.shutdownTimeout||5e3,this.maxRetries=e.maxRetries||3,this.retryDelay=e.retryDelay||1e3,this.onProcessMessage=e.onProcessMessage||null,this.shutdownPromise=null,this.currentlyProcessing=null}enqueue(e){if(this.shuttingDown)return f&&console.log("Queue is shutting down, skipping new messages"),null;let t={id:Date.now()+Math.random(),data:e,timestamp:Date.now(),retryCount:0,processing:!1};return this.queue.push(t),f&&console.log(`Message enqueued, queue length: ${this.queue.length}`),this.processQueue(),t.id}dequeue(){let e=this.queue.shift();return f&&e&&console.log(`Message dequeued, remaining queue length: ${this.queue.length}`),e}removeById(e){let t=this.queue.findIndex(s=>s.id===e);return t>-1?(this.queue.splice(t,1),f&&console.log(`Message ${e} removed from queue`),!0):!1}async processQueue(){if(!(this.processing||this.queue.length===0)){this.processing=!0;try{for(;this.queue.length>0&&!this.shuttingDown;){let e=this.queue[0];e.processing=!0;try{this.onProcessMessage&&await this.onProcessMessage(e),this.dequeue()}catch(t){if(f&&console.error(`Failed to process message: ${t.message}`),e.retryCount++,f&&console.log("Start Retry:",e.retryCount,"times..."),e.retryCount>=this.maxRetries)f&&console.error("Message exceeded max retries, removing from queue"),this.dequeue();else{e.processing=!1;let s=this.shuttingDown?100:this.retryDelay*e.retryCount;await new Promise(o=>setTimeout(o,s))}}}}finally{this.processing=!1}}}getQueueSize(){return this.queue.length}clear(){this.queue=[],f&&console.log("Message queue cleared")}setMessageProcessor(e){this.onProcessMessage=e}async waitForProcessingMessages(e=5e3){let t=this.queue.filter(o=>o.processing);if(t.length===0)return;f&&console.log(`Waiting for ${t.length} processing messages to complete (timeout: ${e}ms)`);let s=Date.now();for(;Date.now()-s<e;){if(this.queue.filter(r=>r.processing).length===0){f&&console.log(`All processing messages completed in ${Date.now()-s}ms`);return}await new Promise(r=>setTimeout(r,50))}if(f){let o=this.queue.filter(r=>r.processing);console.log(`Timeout waiting for processing messages. ${o.length} messages still processing`)}}async gracefulShutdown(e={}){if(this.shutdownPromise)return this.shutdownPromise;let{timeoutMs:t=this.shutdownTimeout,batchSize:s=10,fastMode:o=!1}=e;return this.shutdownPromise=new Promise(async r=>{this.shuttingDown=!0,await this.waitForProcessingMessages(Math.min(t*.3,3e3));let n=this.queue.filter(g=>!g.processing),i=n.length;f&&(console.log(`Starting graceful shutdown with ${i} pending messages (${this.queue.length-i} already processing)`),console.log(`Mode: ${o?"fast (parallel)":"sequential"}, timeout: ${t}ms`));let a=Date.now(),c=0,l=0;try{if(o){let g=await this.processAllParallel(t-(Date.now()-a),n);c=g.processed,l=g.failed}else{let g=await this.processInBatches(s,t-(Date.now()-a),n);c=g.processed,l=g.failed}}catch(g){f&&console.error("Error during shutdown processing:",g.message)}let u=Date.now()-a,d=this.queue.length;f&&(console.log(`Shutdown completed in ${u}ms:`),console.log(` - Total: ${i} messages`),console.log(` - Processed: ${c}`),console.log(` - Failed: ${l}`),console.log(` - Remaining: ${d}`)),r({totalMessages:i,processedMessages:c,failedMessages:l,remainingMessages:d,duration:u,allMessagesSent:d===0&&l===0})}),this.shutdownPromise}async processAllParallel(e){if(this.queue.length===0)return{processed:0,failed:0};f&&console.log(`Processing ${this.queue.length} messages in parallel...`);let t=[...this.queue];this.queue=[];let s=t.map(async a=>{try{return this.onProcessMessage&&await this.onProcessMessage(a),{success:!0,messageId:a.id}}catch(c){return f&&console.warn(`Message ${a.id} processing failed: ${c.message}`),{success:!1,messageId:a.id,error:c}}}),o=new Promise(a=>{setTimeout(()=>a({timedOut:!0}),e)}),r=await Promise.race([Promise.allSettled(s).then(a=>({results:a})),o]);if(r.timedOut)return f&&console.log(`Parallel processing timed out after ${e}ms`),{processed:0,failed:t.length};let n=r.results.filter(a=>a.status==="fulfilled"&&a.value?.success).length,i=t.length-n;return{processed:n,failed:i}}async processInBatches(e,t){if(this.queue.length===0)return{processed:0,failed:0};f&&console.log(`Processing ${this.queue.length} messages in batches of ${e}...`);let s=Date.now(),o=0,r=0;for(;this.queue.length>0&&Date.now()-s<t;){let n=this.queue.splice(0,e),i=n.map(async u=>{try{return this.onProcessMessage&&await this.onProcessMessage(u),{success:!0}}catch(d){return f&&console.warn(`Batch message processing failed: ${d.message}`),{success:!1,error:d}}}),c=(await Promise.allSettled(i)).filter(u=>u.status==="fulfilled"&&u.value?.success).length,l=n.length-c;o+=c,r+=l,f&&n.length>0&&console.log(`Batch completed: ${c}/${n.length} successful`),this.queue.length>0&&await new Promise(u=>setTimeout(u,10))}return this.queue.length>0&&(r+=this.queue.length,f&&console.log(`${this.queue.length} messages not processed due to timeout`),this.queue=[]),{processed:o,failed:r}}async forceFlushAndShutdown(e=2e3){this.shuttingDown=!0,await this.waitForProcessingMessages(Math.min(e*.4,1e3));let t=this.queue.filter(a=>!a.processing);f&&console.log(`Force flush: attempting to send ${t.length} pending messages within ${e}ms (${this.queue.length-t.length} already processing)`);let s=Date.now(),o=t.map(async a=>{try{return this.onProcessMessage&&Date.now()-s<e?(await this.onProcessMessage(a),{success:!0,messageId:a.id}):{success:!1,messageId:a.id,reason:"timeout"}}catch(c){return{success:!1,messageId:a.id,error:c.message}}}),r=e-(Date.now()-s),n=new Promise(a=>{setTimeout(()=>a({timedOut:!0}),Math.max(100,r))}),i=await Promise.race([Promise.allSettled(o).then(a=>({results:a})),n]);if(t.forEach(a=>{let c=this.queue.findIndex(l=>l.id===a.id);c>-1&&this.queue.splice(c,1)}),this.processing=!1,i.timedOut)return f&&console.log(`Force flush timed out after ${e}ms`),{success:!1,reason:"timeout",attemptedCount:t.length};{let a=i.results.filter(c=>c.status==="fulfilled"&&c.value.success).length;return f&&console.log(`Force flush completed: ${a}/${t.length} messages sent`),{success:a===t.length,successCount:a,totalCount:t.length,results:i.results}}}forceShutdown(){this.shuttingDown=!0,this.queue=[],this.processing=!1,f&&console.log("Force shutdown: Queue cleared")}};$e.exports=Y});var q=m((ds,vt)=>{vt.exports={name:"makecoder",version:"2.0.95",description:"MakeCoder: Unified AI agent CLI tool integrating Claude Code, Codex and Gemini CLI",main:"./dist/coder.js",bin:{coder:"./dist/coder.js"},scripts:{test:'echo "Error: no test specified" && exit 1',start:"node ./src/coder.js",build:"node scripts/build.js","build:clean":"node scripts/build.js --clean","build:dev":"node scripts/build.js --no-minify --sourcemap",postinstall:"node scripts/postinstall.js"},keywords:["cli","ai","claude","gemini","codex","agent"],author:"makecoder",license:"MIT",repository:{type:"git",url:"https://github.com/makecoderai/coder.git"},homepage:"https://github.com/makecoderai/coder",dependencies:{"node-fetch":"^3.3.2",open:"^10.1.0",zod:"^3.25.76"},optionalDependencies:{"makecoder-codex-linux-x64":"*","makecoder-codex-darwin-arm64":"*","makecoder-codex-win32-x64":"*"},engines:{node:">=20.0.0"},devDependencies:{chokidar:"^4.0.3"},files:["dist","claude","scripts/postinstall.js"]}});var _e=m((hs,ke)=>{var bt=require("http"),It=require("https"),{URL:De}=require("url"),{version:$t}=q(),Pe=process.env.CODEV_DEBUG==="True",Z=class{constructor(e={}){this.baseUrl=e.baseUrl||"",this.timeout=e.timeout||3e4,this.defaultHeaders={"Content-Type":"application/json","User-Agent":`codev-cli/${$t}`,...e.headers}}setBaseUrl(e){this.baseUrl=e}setDefaultHeaders(e){this.defaultHeaders={...this.defaultHeaders,...e}}async post(e,t,s={}){let o=this.resolveUrl(e),r={...this.defaultHeaders,...s.headers};return new Promise((n,i)=>{this.validateRequest(o,t,i);let a=this.serializeData(t,i);if(!a)return;r["Content-Length"]=Buffer.byteLength(a);let c=this.buildRequestOptions(o,"POST",r),l=this.getHttpModule(o);Pe&&console.debug(`HTTP POST to ${o} with data length: ${a.length}`);let u=l.request(c,d=>{this.handleResponse(d,n,i)});this.attachErrorHandlers(u,o,i),u.setTimeout(this.timeout),u.write(a),u.end()})}resolveUrl(e){return e.startsWith("http")?e:`${this.baseUrl}${e.startsWith("/")?"":"/"}${e}`}validateRequest(e,t,s){return!e||typeof e!="string"?(s(new Error(`Invalid URL: ${e}`)),!1):t?!0:(s(new Error("No data provided for HTTP POST")),!1)}serializeData(e,t){try{return typeof e=="string"?e:JSON.stringify(e)}catch(s){return t(new Error(`Failed to serialize data: ${s.message}`)),null}}buildRequestOptions(e,t,s){let o=new De(e),r=o.protocol==="https:";return{hostname:o.hostname,port:o.port||(r?443:80),path:o.pathname+o.search,method:t,headers:s}}getHttpModule(e){return new De(e).protocol==="https:"?It:bt}handleResponse(e,t,s){Pe&&console.debug(`HTTP response status: ${e.statusCode}`);let o="";e.on("data",r=>{o+=r}),e.on("end",()=>{e.statusCode>=200&&e.statusCode<300?t({statusCode:e.statusCode,data:o,headers:e.headers}):s(new Error(`HTTP request returned status ${e.statusCode}: ${o}`))})}attachErrorHandlers(e,t,s){e.on("error",o=>{s(new Error(`HTTP POST request failed: ${o.message}`))}),e.on("timeout",()=>{s(new Error(`HTTP POST request timed out for URL: ${t}`)),e.destroy()})}};ke.exports=Z});var Te=m((gs,Oe)=>{var xt=require("crypto"),{URL:Dt}=require("url"),X=class{static generateSignature(e,t,s,o){try{let r=new Dt(e),n=Buffer.from(r.pathname),i=Buffer.from(n),a=t?typeof t=="string"?Buffer.from(t):Buffer.from(JSON.stringify(t)):Buffer.alloc(0),c=Buffer.concat([i,a,Buffer.from(o)]),l=xt.createHmac("sha256",s);return l.update(c),l.digest("hex")}catch(r){throw new Error(`Failed to generate signature: ${r.message}`)}}static validateSignature(e,t,s,o,r){return this.generateSignature(e,t,s,o)===r}static generateTimestamp(){return Date.now().toString()}};Oe.exports=X});var Me=m((ps,Ae)=>{var Pt=Te(),ee=class{constructor(e={}){this.accessKey=null,this.secretKey=null,this.validateCredentials=e.validateCredentials!==!1}setCredentials(e,t){if(this.validateCredentials&&(!e||!t))throw new Error("Both access key and secret key are required");this.accessKey=e,this.secretKey=t}hasCredentials(){return!!(this.accessKey&&this.secretKey)}generateAuthHeaders(e,t=null){if(!this.hasCredentials())return{};try{return{AUTHORIZATION:`Bearer ${this.accessKey}.${this.secretKey}`}}catch(s){throw new Error(`Failed to generate auth headers: ${s.message}`)}}validateAuthHeaders(e,t,s,o){if(!this.hasCredentials())throw new Error("No credentials available for validation");return Pt.validateSignature(e,t,this.secretKey,s,o)}clearCredentials(){this.accessKey=null,this.secretKey=null}getCredentials(){return{accessKey:this.accessKey,hasCredentials:this.hasCredentials()}}};Ae.exports=ee});var Fe=m((fs,qe)=>{var F=process.env.CODEV_DEBUG==="True",te=class{constructor(e={}){this.currentSessionId=null,this.previousSessionId=null,this.onSessionSwitch=e.onSessionSwitch||null,this.terminateSignal=e.terminateSignal||"CODEV_TERMINATE_SIGNAL"}handleSessionSwitch(e){if(!e)return F&&console.warn("Received empty session ID"),!1;let t=this.previousSessionId!==null&&this.previousSessionId!==e;return t&&(F&&console.log(`Session switch detected: ${this.previousSessionId} -> ${e}`),this.onSessionSwitch&&this.onSessionSwitch({type:this.terminateSignal,reason:"User switch session",agent:"claude",previousSessionId:this.previousSessionId,newSessionId:e})),this.previousSessionId=this.currentSessionId,this.currentSessionId=e,t}getCurrentSessionId(){return this.currentSessionId}getPreviousSessionId(){return this.previousSessionId}hasActiveSession(){return!!this.currentSessionId}terminateCurrentSession(e="Session terminated",t=null,s=null){if(!this.hasActiveSession())return F&&console.log("No active session to terminate"),null;let o={type:this.terminateSignal,reason:s?`terminated by signal: ${s}`:e,code:t,signal:s,timestamp:Date.now(),agent:"claude",sessionId:this.currentSessionId};return F&&console.log("Terminating session:",o),this.previousSessionId=null,this.currentSessionId=null,o}createErrorTermination(e){return this.hasActiveSession()?{type:this.terminateSignal,error:e.message,stack:e.stack,timestamp:Date.now(),agent:"claude",sessionId:this.currentSessionId}:null}reset(){F&&console.log("Resetting session manager"),this.currentSessionId=null,this.previousSessionId=null}setSessionSwitchCallback(e){this.onSessionSwitch=e}getSessionInfo(){return{currentSessionId:this.currentSessionId,previousSessionId:this.previousSessionId,hasActiveSession:this.hasActiveSession()}}};qe.exports=te});var Ne=m((ms,Ue)=>{var _=require("fs"),T=require("path"),kt=require("events"),_t=require("crypto"),S=process.env.CODEV_DEBUG==="True",se=class extends kt{constructor(e={}){super(),this.watchPaths=e.watchPaths||[],this.excludePatterns=e.excludePatterns||[/node_modules/,/\.git/,/\.DS_Store/,/\.tmp/,/\.log$/,/\.swp$/,/codev\.log/],this.includePatterns=e.includePatterns||[/\.(js|jsx|ts|tsx|py|java|c|cpp|h|hpp|go|rs|rb|php|html|css|scss|sass|less|json|xml|yaml|yml|md|txt)$/],this.watchers=new Map,this.isWatching=!1,this.debounceTimeout=e.debounceTimeout||300,this.pendingChanges=new Map,this.fileContentHashes=new Map,this.enableContentComparison=e.enableContentComparison!==!1,this.onFileChange=e.onFileChange||null}calculateFileHash(e){try{let t=_.readFileSync(e,"utf8");return _t.createHash("sha256").update(t).digest("hex")}catch{return null}}hasContentChanged(e){if(!this.enableContentComparison)return!0;let t=this.calculateFileHash(e),s=this.fileContentHashes.get(e);return t===null?s!==void 0?(this.fileContentHashes.delete(e),!0):!1:s===void 0||t!==s?(this.fileContentHashes.set(e,t),!0):!1}preloadFileHashes(e){if(!(!this.enableContentComparison||!_.existsSync(e)))try{let t=_.readdirSync(e,{withFileTypes:!0});for(let s of t){let o=T.join(e,s.name);s.isFile()&&this.shouldWatchFile(o)?(this.calculateFileHash(o),this.fileContentHashes.set(o,this.calculateFileHash(o))):s.isDirectory()&&!this.shouldExcludeDirectory(o)&&this.preloadFileHashes(o)}}catch(t){S&&console.warn(`Failed to preload hashes for ${e}:`,t.message)}}shouldExcludeDirectory(e){let t=e.replace(/\\/g,"/");for(let s of this.excludePatterns)if(s.test(t)||s.test(T.basename(e)))return!0;return!1}startWatching(e=null){if(this.isWatching){S&&console.log("FileWatchService is already watching");return}let t=e||this.watchPaths;if(t.length===0){S&&console.log("No watch paths specified");return}this.isWatching=!0;for(let s of t)this.enableContentComparison&&this.preloadFileHashes(s),this.watchDirectory(s);S&&(console.log(`FileWatchService started watching ${t.length} paths`),this.enableContentComparison&&console.log(`Preloaded hashes for ${this.fileContentHashes.size} files`))}stopWatching(){if(this.isWatching){this.isWatching=!1;for(let[e,t]of this.watchers)try{t.close(),S&&console.log(`Stopped watching: ${e}`)}catch(s){S&&console.error(`Error stopping watcher for ${e}:`,s.message)}this.watchers.clear(),this.pendingChanges.clear(),this.fileContentHashes.clear(),S&&console.log("FileWatchService stopped watching all paths")}}watchDirectory(e){if(!_.existsSync(e)){S&&console.warn(`Watch path does not exist: ${e}`);return}if(!_.statSync(e).isDirectory()){S&&console.warn(`Watch path is not a directory: ${e}`);return}try{let s=_.watch(e,{recursive:!0,persistent:!1},(o,r)=>{if(!r)return;let n=T.join(e,r);this.handleFileChange(o,n,e)});this.watchers.set(e,s),S&&console.log(`Started watching directory: ${e}`),s.on("error",o=>{S&&console.error(`Watcher error for ${e}:`,o.message),this.watchers.delete(e)})}catch(s){S&&console.error(`Failed to start watching ${e}:`,s.message)}}handleFileChange(e,t,s){if(!this.shouldWatchFile(t))return;let o=`${e}:${t}`;this.pendingChanges.has(o)&&clearTimeout(this.pendingChanges.get(o)),this.pendingChanges.set(o,setTimeout(()=>{this.pendingChanges.delete(o),this.processFileChange(e,t,s)},this.debounceTimeout))}processFileChange(e,t,s){if(!this.isWatching)return;let o="modified",r=!1;try{_.statSync(t),r=!0,e==="rename"?o="created":e==="change"&&(o="modified")}catch{e==="rename"&&(o="deleted")}if(r&&(o==="modified"||o==="created")&&!this.hasContentChanged(t)){S&&console.log(`Ignoring false change for: ${T.relative(s,t)}`);return}!r&&o==="deleted"&&this.fileContentHashes.delete(t);let n={type:"CODEV_FILE_CHANGE_DETECTTED",data:{eventType:e,changeType:o,filePath:t,relativePath:T.relative(s,t),watchPath:s,fileExists:r,timestamp:Date.now(),sessionId:process.env.SESSION_ID||"default"}};if(S&&console.log(`File ${o}: ${n.data.relativePath}`),this.emit("fileChange",n),this.onFileChange&&typeof this.onFileChange=="function")try{this.onFileChange(n)}catch(i){S&&console.error("Error in file change callback:",i.message)}}shouldWatchFile(e){let t=T.basename(e),s=e.replace(/\\/g,"/");for(let o of this.excludePatterns)if(o.test(s)||o.test(t))return!1;if(this.includePatterns.length===0)return!0;for(let o of this.includePatterns)if(o.test(s)||o.test(t))return!0;return!1}addWatchPath(e){this.watchPaths.includes(e)||(this.watchPaths.push(e),this.isWatching&&this.watchDirectory(e))}removeWatchPath(e){let t=this.watchPaths.indexOf(e);if(t>-1&&(this.watchPaths.splice(t,1),this.watchers.has(e)))try{this.watchers.get(e).close(),this.watchers.delete(e),S&&console.log(`Removed watch path: ${e}`)}catch(s){S&&console.error(`Error removing watch path ${e}:`,s.message)}}getStatus(){return{isWatching:this.isWatching,watchPaths:[...this.watchPaths],activeWatchers:this.watchers.size,pendingChanges:this.pendingChanges.size}}setFileChangeCallback(e){this.onFileChange=e}};Ue.exports=se});var Le=m((Ss,Be)=>{var Ot=H(),Tt=require("path"),ys=require("fs"),ws=require("os"),At=xe(),Mt=_e(),qt=Me(),Ft=Fe(),Ut=Ne(),w=process.env.CODEV_DEBUG==="True",oe=class extends Ot{constructor(){super({configDir:".",configFile:".claude.json",defaultModel:"Claude Sonnet 4.5",executablePaths:["cc.mjs","/tmp/claude-code/package/cc.mjs"],environmentVariables:e=>({ANTHROPIC_BASE_URL:`${e}/claude`,ANTHROPIC_API_KEY:"codev",DISABLE_TELEMETRY:!0,CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:!0,DISABLE_COST_WARNINGS:!0,DISABLE_NON_ESSENTIAL_MODEL_CALLS:!0,CODEV_SERVER:e,CLAUDE_CODE_ATTRIBUTION_HEADER:"0"}),defaultConfig:{numStartups:1,installMethod:"unknown",autoUpdates:!1,theme:"Coder Dark",customApiKeyResponses:{approved:["codev"]},shiftEnterKeyBindingInstalled:!0,hasCompletedOnboarding:!0,subscriptionNoticeCount:0,hasAvailableSubscription:!0,projects:{}}}),this.fileWatchService=null,this.shutdownInProgress=!1,this.initializeServices()}initializeServices(){this.httpClient=new Mt({timeout:1e4}),this.authService=new qt({validateCredentials:!1}),this.sessionManager=new Ft({onSessionSwitch:e=>{this.sendTerminationMessage(e)}}),this.messageQueue=new At({maxRetries:2,retryDelay:500,shutdownTimeout:3e3,onProcessMessage:e=>this.processMessage(e)}),this.initializeFileWatchService()}resloveSettingFilePath(e){return Tt.join(e,this.config.configDir,".claude","settings.json")}initializeFileWatchService(){if(!process.env.SESSION_ID){w&&console.log("FileWatchService disabled: SESSION_ID environment variable not found");return}try{this.fileWatchService=new Ut({watchPaths:this.getFileWatchPaths(),onFileChange:e=>this.handleFileChange(e),debounceTimeout:300}),w&&console.log("FileWatchService initialized with SESSION_ID:",process.env.SESSION_ID)}catch(e){w&&console.error("Failed to initialize FileWatchService:",e.message)}}getFileWatchPaths(){let e=[],t=process.cwd();e.push(t);let s=process.env.CODEV_WATCH_PATHS;if(s){let o=s.split(",").map(r=>r.trim());e.push(...o)}return e}handleFileChange(e){if(w&&console.log("File change detected:",e.data.relativePath),this.shutdownInProgress)return;let t={message:e,sessionId:e.data.sessionId||process.env.SESSION_ID};this.messageQueue.enqueue(t)}startFileWatching(){this.fileWatchService&&!this.fileWatchService.isWatching&&(this.fileWatchService.startWatching(),w&&console.log("File watching started"))}stopFileWatching(){this.fileWatchService&&this.fileWatchService.isWatching&&(this.fileWatchService.stopWatching(),w&&console.log("File watching stopped"))}onChildMessage(e){e&&e.type==="claude:send-msg"&&this.handleClaudeSendMessage(e.data),super.onChildMessage(e)}handleClaudeSendMessage(e){if(w&&console.log("Handling claude:send-msg message:",e),!e||typeof e!="object"){console.error(`handleClaudeSendMessage: Invalid message data. Expected object, got: ${typeof e}`);return}if(this.shutdownInProgress){w&&console.log("Shutdown in progress, ignoring new message");return}let t=e.sessionId||process.env.SESSION_ID;this.sessionManager.handleSessionSwitch(t),this.messageQueue.enqueue(e)}async processMessage(e){let t=e.data.message,s=e.data.sessionId||process.env.SESSION_ID;if(!s)throw new Error("No session ID available");let o;try{o=typeof t=="string"?JSON.parse(t):t}catch(i){throw new Error(`Failed to parse message data: ${i.message}`)}let r=`/conversations/${s}/@append?task_type=codev`,n=this.authService.hasCredentials()?this.authService.generateAuthHeaders(`${this.httpClient.baseUrl}${r}`,o):{};w&&(console.debug("Sending message to:",r),console.debug("Send Message: ",JSON.stringify(o))),e.type!=="CODEV_TERMINATE_SIGNAL"&&(this.sessionManager.currentSessionId=s)}sendTerminationMessage(e){let t={message:e,sessionId:e.sessionId||this.sessionManager.getCurrentSessionId()};this.messageQueue.enqueue(t)}async handleChildProcessExit(e,t){w&&console.log(`Child process exited with code: ${e}, signal: ${t}`),this.stopFileWatching();let s=this.messageQueue.getQueueSize(),o=this.sessionManager.terminateCurrentSession("process exited normally",e,t);if(o&&this.sendTerminationMessage(o),s>0||o){w&&console.log("Starting graceful shutdown of message queue...");try{let r=!t||t==="SIGTERM",n=this.messageQueue.getQueueSize(),i={timeoutMs:r?8e3:3e3,batchSize:Math.min(n,15),fastMode:!r||n>30};w&&console.log("Shutdown options:",i);let a=await this.messageQueue.gracefulShutdown(i);w&&console.log("Message queue shutdown completed:",a),a.failedMessages>0&&w&&console.warn(`Shutdown summary: ${a.processedMessages} sent, ${a.failedMessages} failed, ${a.remainingMessages} remaining`)}catch(r){w&&console.error("Error during message queue shutdown:",r.message)}}}handleChildProcessError(e){w&&console.error(`Child process error: ${e.message}`);let t=this.sessionManager.createErrorTermination(e);t&&this.sendTerminationMessage(t)}async forceFlushMessages(e=3e3){if(this.messageQueue.getQueueSize()===0)return{success:!0,message:"No messages to flush"};w&&console.log(`Force flushing ${this.messageQueue.getQueueSize()} messages...`);try{return await this.messageQueue.forceFlushAndShutdown(e)}catch(t){return w&&console.error("Force flush failed:",t.message),{success:!1,error:t.message}}}async launch(e={}){let{codevServer:t,auth_ak:s=null,auth_sk:o=null}=e;return this.httpClient.setBaseUrl(t),s&&o&&this.authService.setCredentials(s,o),this.startFileWatching(),super.launch(e)}};Be.exports=oe});var Re=m((Es,je)=>{var Nt=H(),Cs=require("path"),ne=class extends Nt{constructor(){super({configDir:".gemini",configFile:"settings.json",defaultModel:"gemini-2.5-pro",executablePaths:["gemini/gemini.js","../dist/gemini/gemini.js"],environmentVariables:e=>({GOOGLE_GEMINI_BASE_URL:`${e}/gemini`,GEMINI_API_KEY:"coder",GOOGLE_API_KEY:"coder",GOOGLE_CLOUD_PROJECT:"coder",GOOGLE_CLOUD_LOCATION:"coder",DISABLE_TELEMETRY:!0,GEMINI_CODE_DISABLE_NONESSENTIAL_TRAFFIC:!0,DISABLE_COST_WARNINGS:!0,DISABLE_NON_ESSENTIAL_MODEL_CALLS:!0,USE_VERTEX:!0}),defaultConfig:{ide:{hasSeenNudge:!0},telemetry:{enabled:!1,logPrompts:!1},privacy:{usageStatisticsEnabled:!1},general:{disableUpdateNag:!0,preferredEditor:"vscode",previewFeatures:!0},ui:{hideBanner:!0,theme:"Default"},security:{auth:{selectedType:"vertex-ai"}}}})}};je.exports=ne});var Ge=m((vs,He)=>{var Bt=H(),U=require("path"),x=require("fs"),Lt=require("os"),{spawn:jt}=require("child_process"),G=process.env.CODEV_DEBUG==="True",re=class extends Bt{constructor(){super({configDir:".codex",configFile:"config.toml",defaultModel:"o4-mini",executablePaths:["codex.mjs","../dist/codex.mjs"],environmentVariables:e=>({OPENAI_BASE_URL:`${e}/codex`,OPENAI_API_KEY:"codev-proxy-key",DEBUG:G?"true":"false",CODEX_QUIET_MODE:"0",OPENAI_DISABLE_TELEMETRY:"true",CODEX_DISABLE_PROJECT_DOC:"0",CODEV_SERVER:e}),defaultConfig:{model:"gpt-5-codex",approvalMode:"suggest",fullAutoErrorMode:"ask-user",notify:[],history:{maxSize:1e3,saveHistory:!0,sensitivePatterns:[],persistence:"save-all"}}})}checkCodexAvailability(){try{let e=this.findExecutablePath();return x.existsSync(e)}catch{return!1}}resloveSettingFilePath(e){return U.join(e,this.config.configDir,"config.toml")}async ensureConfig(e,t=0){let s=U.join(Lt.homedir(),this.config.configDir,this.config.configFile),o=U.dirname(s);try{x.existsSync(o)||x.mkdirSync(o,{recursive:!0});let r=`${e}/codex`;if(x.existsSync(s)){let n=x.readFileSync(s,"utf8"),i=`openai_base_url = "${r}"`;/^openai_base_url\s*=/m.test(n)?n=n.replace(/^openai_base_url\s*=.*/m,i):n=n.trimEnd()+`
|
|
193
|
+
Terminating ...`),d.kill("SIGTERM"),setTimeout(()=>{d.killed||d.kill("SIGKILL")},8e3)})})}catch(n){throw n}}};Ie.exports=Q});var $e=m((us,xe)=>{var g=process.env.CODEV_DEBUG==="True",Y=class{constructor(e={}){this.queue=[],this.processing=!1,this.shuttingDown=!1,this.shutdownTimeout=e.shutdownTimeout||5e3,this.maxRetries=e.maxRetries||3,this.retryDelay=e.retryDelay||1e3,this.onProcessMessage=e.onProcessMessage||null,this.shutdownPromise=null,this.currentlyProcessing=null}enqueue(e){if(this.shuttingDown)return g&&console.log("Queue is shutting down, skipping new messages"),null;let t={id:Date.now()+Math.random(),data:e,timestamp:Date.now(),retryCount:0,processing:!1};return this.queue.push(t),g&&console.log(`Message enqueued, queue length: ${this.queue.length}`),this.processQueue(),t.id}dequeue(){let e=this.queue.shift();return g&&e&&console.log(`Message dequeued, remaining queue length: ${this.queue.length}`),e}removeById(e){let t=this.queue.findIndex(s=>s.id===e);return t>-1?(this.queue.splice(t,1),g&&console.log(`Message ${e} removed from queue`),!0):!1}async processQueue(){if(!(this.processing||this.queue.length===0)){this.processing=!0;try{for(;this.queue.length>0&&!this.shuttingDown;){let e=this.queue[0];e.processing=!0;try{this.onProcessMessage&&await this.onProcessMessage(e),this.dequeue()}catch(t){if(g&&console.error(`Failed to process message: ${t.message}`),e.retryCount++,g&&console.log("Start Retry:",e.retryCount,"times..."),e.retryCount>=this.maxRetries)g&&console.error("Message exceeded max retries, removing from queue"),this.dequeue();else{e.processing=!1;let s=this.shuttingDown?100:this.retryDelay*e.retryCount;await new Promise(o=>setTimeout(o,s))}}}}finally{this.processing=!1}}}getQueueSize(){return this.queue.length}clear(){this.queue=[],g&&console.log("Message queue cleared")}setMessageProcessor(e){this.onProcessMessage=e}async waitForProcessingMessages(e=5e3){let t=this.queue.filter(o=>o.processing);if(t.length===0)return;g&&console.log(`Waiting for ${t.length} processing messages to complete (timeout: ${e}ms)`);let s=Date.now();for(;Date.now()-s<e;){if(this.queue.filter(r=>r.processing).length===0){g&&console.log(`All processing messages completed in ${Date.now()-s}ms`);return}await new Promise(r=>setTimeout(r,50))}if(g){let o=this.queue.filter(r=>r.processing);console.log(`Timeout waiting for processing messages. ${o.length} messages still processing`)}}async gracefulShutdown(e={}){if(this.shutdownPromise)return this.shutdownPromise;let{timeoutMs:t=this.shutdownTimeout,batchSize:s=10,fastMode:o=!1}=e;return this.shutdownPromise=new Promise(async r=>{this.shuttingDown=!0,await this.waitForProcessingMessages(Math.min(t*.3,3e3));let n=this.queue.filter(p=>!p.processing),i=n.length;g&&(console.log(`Starting graceful shutdown with ${i} pending messages (${this.queue.length-i} already processing)`),console.log(`Mode: ${o?"fast (parallel)":"sequential"}, timeout: ${t}ms`));let a=Date.now(),c=0,l=0;try{if(o){let p=await this.processAllParallel(t-(Date.now()-a),n);c=p.processed,l=p.failed}else{let p=await this.processInBatches(s,t-(Date.now()-a),n);c=p.processed,l=p.failed}}catch(p){g&&console.error("Error during shutdown processing:",p.message)}let u=Date.now()-a,d=this.queue.length;g&&(console.log(`Shutdown completed in ${u}ms:`),console.log(` - Total: ${i} messages`),console.log(` - Processed: ${c}`),console.log(` - Failed: ${l}`),console.log(` - Remaining: ${d}`)),r({totalMessages:i,processedMessages:c,failedMessages:l,remainingMessages:d,duration:u,allMessagesSent:d===0&&l===0})}),this.shutdownPromise}async processAllParallel(e){if(this.queue.length===0)return{processed:0,failed:0};g&&console.log(`Processing ${this.queue.length} messages in parallel...`);let t=[...this.queue];this.queue=[];let s=t.map(async a=>{try{return this.onProcessMessage&&await this.onProcessMessage(a),{success:!0,messageId:a.id}}catch(c){return g&&console.warn(`Message ${a.id} processing failed: ${c.message}`),{success:!1,messageId:a.id,error:c}}}),o=new Promise(a=>{setTimeout(()=>a({timedOut:!0}),e)}),r=await Promise.race([Promise.allSettled(s).then(a=>({results:a})),o]);if(r.timedOut)return g&&console.log(`Parallel processing timed out after ${e}ms`),{processed:0,failed:t.length};let n=r.results.filter(a=>a.status==="fulfilled"&&a.value?.success).length,i=t.length-n;return{processed:n,failed:i}}async processInBatches(e,t){if(this.queue.length===0)return{processed:0,failed:0};g&&console.log(`Processing ${this.queue.length} messages in batches of ${e}...`);let s=Date.now(),o=0,r=0;for(;this.queue.length>0&&Date.now()-s<t;){let n=this.queue.splice(0,e),i=n.map(async u=>{try{return this.onProcessMessage&&await this.onProcessMessage(u),{success:!0}}catch(d){return g&&console.warn(`Batch message processing failed: ${d.message}`),{success:!1,error:d}}}),c=(await Promise.allSettled(i)).filter(u=>u.status==="fulfilled"&&u.value?.success).length,l=n.length-c;o+=c,r+=l,g&&n.length>0&&console.log(`Batch completed: ${c}/${n.length} successful`),this.queue.length>0&&await new Promise(u=>setTimeout(u,10))}return this.queue.length>0&&(r+=this.queue.length,g&&console.log(`${this.queue.length} messages not processed due to timeout`),this.queue=[]),{processed:o,failed:r}}async forceFlushAndShutdown(e=2e3){this.shuttingDown=!0,await this.waitForProcessingMessages(Math.min(e*.4,1e3));let t=this.queue.filter(a=>!a.processing);g&&console.log(`Force flush: attempting to send ${t.length} pending messages within ${e}ms (${this.queue.length-t.length} already processing)`);let s=Date.now(),o=t.map(async a=>{try{return this.onProcessMessage&&Date.now()-s<e?(await this.onProcessMessage(a),{success:!0,messageId:a.id}):{success:!1,messageId:a.id,reason:"timeout"}}catch(c){return{success:!1,messageId:a.id,error:c.message}}}),r=e-(Date.now()-s),n=new Promise(a=>{setTimeout(()=>a({timedOut:!0}),Math.max(100,r))}),i=await Promise.race([Promise.allSettled(o).then(a=>({results:a})),n]);if(t.forEach(a=>{let c=this.queue.findIndex(l=>l.id===a.id);c>-1&&this.queue.splice(c,1)}),this.processing=!1,i.timedOut)return g&&console.log(`Force flush timed out after ${e}ms`),{success:!1,reason:"timeout",attemptedCount:t.length};{let a=i.results.filter(c=>c.status==="fulfilled"&&c.value.success).length;return g&&console.log(`Force flush completed: ${a}/${t.length} messages sent`),{success:a===t.length,successCount:a,totalCount:t.length,results:i.results}}}forceShutdown(){this.shuttingDown=!0,this.queue=[],this.processing=!1,g&&console.log("Force shutdown: Queue cleared")}};xe.exports=Y});var q=m((ds,vt)=>{vt.exports={name:"makecoder",version:"2.0.97",description:"MakeCoder: Unified AI agent CLI tool integrating Claude Code, Codex and Gemini CLI",main:"./dist/coder.js",bin:{coder:"./dist/coder.js"},scripts:{test:'echo "Error: no test specified" && exit 1',start:"node ./src/coder.js",build:"node scripts/build.js","build:clean":"node scripts/build.js --clean","build:dev":"node scripts/build.js --no-minify --sourcemap",postinstall:"node scripts/postinstall.js"},keywords:["cli","ai","claude","gemini","codex","agent"],author:"makecoder",license:"MIT",repository:{type:"git",url:"https://github.com/makecoderai/coder.git"},homepage:"https://github.com/makecoderai/coder",dependencies:{"node-fetch":"^3.3.2",open:"^10.1.0",zod:"^3.25.76"},optionalDependencies:{"makecoder-codex-linux-x64":"*","makecoder-codex-darwin-arm64":"*","makecoder-codex-win32-x64":"*"},engines:{node:">=20.0.0"},devDependencies:{chokidar:"^4.0.3"},files:["dist","claude","scripts/postinstall.js"]}});var _e=m((hs,ke)=>{var bt=require("http"),It=require("https"),{URL:De}=require("url"),{version:xt}=q(),Pe=process.env.CODEV_DEBUG==="True",Z=class{constructor(e={}){this.baseUrl=e.baseUrl||"",this.timeout=e.timeout||3e4,this.defaultHeaders={"Content-Type":"application/json","User-Agent":`codev-cli/${xt}`,...e.headers}}setBaseUrl(e){this.baseUrl=e}setDefaultHeaders(e){this.defaultHeaders={...this.defaultHeaders,...e}}async post(e,t,s={}){let o=this.resolveUrl(e),r={...this.defaultHeaders,...s.headers};return new Promise((n,i)=>{this.validateRequest(o,t,i);let a=this.serializeData(t,i);if(!a)return;r["Content-Length"]=Buffer.byteLength(a);let c=this.buildRequestOptions(o,"POST",r),l=this.getHttpModule(o);Pe&&console.debug(`HTTP POST to ${o} with data length: ${a.length}`);let u=l.request(c,d=>{this.handleResponse(d,n,i)});this.attachErrorHandlers(u,o,i),u.setTimeout(this.timeout),u.write(a),u.end()})}resolveUrl(e){return e.startsWith("http")?e:`${this.baseUrl}${e.startsWith("/")?"":"/"}${e}`}validateRequest(e,t,s){return!e||typeof e!="string"?(s(new Error(`Invalid URL: ${e}`)),!1):t?!0:(s(new Error("No data provided for HTTP POST")),!1)}serializeData(e,t){try{return typeof e=="string"?e:JSON.stringify(e)}catch(s){return t(new Error(`Failed to serialize data: ${s.message}`)),null}}buildRequestOptions(e,t,s){let o=new De(e),r=o.protocol==="https:";return{hostname:o.hostname,port:o.port||(r?443:80),path:o.pathname+o.search,method:t,headers:s}}getHttpModule(e){return new De(e).protocol==="https:"?It:bt}handleResponse(e,t,s){Pe&&console.debug(`HTTP response status: ${e.statusCode}`);let o="";e.on("data",r=>{o+=r}),e.on("end",()=>{e.statusCode>=200&&e.statusCode<300?t({statusCode:e.statusCode,data:o,headers:e.headers}):s(new Error(`HTTP request returned status ${e.statusCode}: ${o}`))})}attachErrorHandlers(e,t,s){e.on("error",o=>{s(new Error(`HTTP POST request failed: ${o.message}`))}),e.on("timeout",()=>{s(new Error(`HTTP POST request timed out for URL: ${t}`)),e.destroy()})}};ke.exports=Z});var Te=m((ps,Oe)=>{var $t=require("crypto"),{URL:Dt}=require("url"),X=class{static generateSignature(e,t,s,o){try{let r=new Dt(e),n=Buffer.from(r.pathname),i=Buffer.from(n),a=t?typeof t=="string"?Buffer.from(t):Buffer.from(JSON.stringify(t)):Buffer.alloc(0),c=Buffer.concat([i,a,Buffer.from(o)]),l=$t.createHmac("sha256",s);return l.update(c),l.digest("hex")}catch(r){throw new Error(`Failed to generate signature: ${r.message}`)}}static validateSignature(e,t,s,o,r){return this.generateSignature(e,t,s,o)===r}static generateTimestamp(){return Date.now().toString()}};Oe.exports=X});var Me=m((fs,Ae)=>{var Pt=Te(),ee=class{constructor(e={}){this.accessKey=null,this.secretKey=null,this.validateCredentials=e.validateCredentials!==!1}setCredentials(e,t){if(this.validateCredentials&&(!e||!t))throw new Error("Both access key and secret key are required");this.accessKey=e,this.secretKey=t}hasCredentials(){return!!(this.accessKey&&this.secretKey)}generateAuthHeaders(e,t=null){if(!this.hasCredentials())return{};try{return{AUTHORIZATION:`Bearer ${this.accessKey}.${this.secretKey}`}}catch(s){throw new Error(`Failed to generate auth headers: ${s.message}`)}}validateAuthHeaders(e,t,s,o){if(!this.hasCredentials())throw new Error("No credentials available for validation");return Pt.validateSignature(e,t,this.secretKey,s,o)}clearCredentials(){this.accessKey=null,this.secretKey=null}getCredentials(){return{accessKey:this.accessKey,hasCredentials:this.hasCredentials()}}};Ae.exports=ee});var Ue=m((gs,qe)=>{var U=process.env.CODEV_DEBUG==="True",te=class{constructor(e={}){this.currentSessionId=null,this.previousSessionId=null,this.onSessionSwitch=e.onSessionSwitch||null,this.terminateSignal=e.terminateSignal||"CODEV_TERMINATE_SIGNAL"}handleSessionSwitch(e){if(!e)return U&&console.warn("Received empty session ID"),!1;let t=this.previousSessionId!==null&&this.previousSessionId!==e;return t&&(U&&console.log(`Session switch detected: ${this.previousSessionId} -> ${e}`),this.onSessionSwitch&&this.onSessionSwitch({type:this.terminateSignal,reason:"User switch session",agent:"claude",previousSessionId:this.previousSessionId,newSessionId:e})),this.previousSessionId=this.currentSessionId,this.currentSessionId=e,t}getCurrentSessionId(){return this.currentSessionId}getPreviousSessionId(){return this.previousSessionId}hasActiveSession(){return!!this.currentSessionId}terminateCurrentSession(e="Session terminated",t=null,s=null){if(!this.hasActiveSession())return U&&console.log("No active session to terminate"),null;let o={type:this.terminateSignal,reason:s?`terminated by signal: ${s}`:e,code:t,signal:s,timestamp:Date.now(),agent:"claude",sessionId:this.currentSessionId};return U&&console.log("Terminating session:",o),this.previousSessionId=null,this.currentSessionId=null,o}createErrorTermination(e){return this.hasActiveSession()?{type:this.terminateSignal,error:e.message,stack:e.stack,timestamp:Date.now(),agent:"claude",sessionId:this.currentSessionId}:null}reset(){U&&console.log("Resetting session manager"),this.currentSessionId=null,this.previousSessionId=null}setSessionSwitchCallback(e){this.onSessionSwitch=e}getSessionInfo(){return{currentSessionId:this.currentSessionId,previousSessionId:this.previousSessionId,hasActiveSession:this.hasActiveSession()}}};qe.exports=te});var Ne=m((ms,Fe)=>{var _=require("fs"),T=require("path"),kt=require("events"),_t=require("crypto"),S=process.env.CODEV_DEBUG==="True",se=class extends kt{constructor(e={}){super(),this.watchPaths=e.watchPaths||[],this.excludePatterns=e.excludePatterns||[/node_modules/,/\.git/,/\.DS_Store/,/\.tmp/,/\.log$/,/\.swp$/,/codev\.log/],this.includePatterns=e.includePatterns||[/\.(js|jsx|ts|tsx|py|java|c|cpp|h|hpp|go|rs|rb|php|html|css|scss|sass|less|json|xml|yaml|yml|md|txt)$/],this.watchers=new Map,this.isWatching=!1,this.debounceTimeout=e.debounceTimeout||300,this.pendingChanges=new Map,this.fileContentHashes=new Map,this.enableContentComparison=e.enableContentComparison!==!1,this.onFileChange=e.onFileChange||null}calculateFileHash(e){try{let t=_.readFileSync(e,"utf8");return _t.createHash("sha256").update(t).digest("hex")}catch{return null}}hasContentChanged(e){if(!this.enableContentComparison)return!0;let t=this.calculateFileHash(e),s=this.fileContentHashes.get(e);return t===null?s!==void 0?(this.fileContentHashes.delete(e),!0):!1:s===void 0||t!==s?(this.fileContentHashes.set(e,t),!0):!1}preloadFileHashes(e){if(!(!this.enableContentComparison||!_.existsSync(e)))try{let t=_.readdirSync(e,{withFileTypes:!0});for(let s of t){let o=T.join(e,s.name);s.isFile()&&this.shouldWatchFile(o)?(this.calculateFileHash(o),this.fileContentHashes.set(o,this.calculateFileHash(o))):s.isDirectory()&&!this.shouldExcludeDirectory(o)&&this.preloadFileHashes(o)}}catch(t){S&&console.warn(`Failed to preload hashes for ${e}:`,t.message)}}shouldExcludeDirectory(e){let t=e.replace(/\\/g,"/");for(let s of this.excludePatterns)if(s.test(t)||s.test(T.basename(e)))return!0;return!1}startWatching(e=null){if(this.isWatching){S&&console.log("FileWatchService is already watching");return}let t=e||this.watchPaths;if(t.length===0){S&&console.log("No watch paths specified");return}this.isWatching=!0;for(let s of t)this.enableContentComparison&&this.preloadFileHashes(s),this.watchDirectory(s);S&&(console.log(`FileWatchService started watching ${t.length} paths`),this.enableContentComparison&&console.log(`Preloaded hashes for ${this.fileContentHashes.size} files`))}stopWatching(){if(this.isWatching){this.isWatching=!1;for(let[e,t]of this.watchers)try{t.close(),S&&console.log(`Stopped watching: ${e}`)}catch(s){S&&console.error(`Error stopping watcher for ${e}:`,s.message)}this.watchers.clear(),this.pendingChanges.clear(),this.fileContentHashes.clear(),S&&console.log("FileWatchService stopped watching all paths")}}watchDirectory(e){if(!_.existsSync(e)){S&&console.warn(`Watch path does not exist: ${e}`);return}if(!_.statSync(e).isDirectory()){S&&console.warn(`Watch path is not a directory: ${e}`);return}try{let s=_.watch(e,{recursive:!0,persistent:!1},(o,r)=>{if(!r)return;let n=T.join(e,r);this.handleFileChange(o,n,e)});this.watchers.set(e,s),S&&console.log(`Started watching directory: ${e}`),s.on("error",o=>{S&&console.error(`Watcher error for ${e}:`,o.message),this.watchers.delete(e)})}catch(s){S&&console.error(`Failed to start watching ${e}:`,s.message)}}handleFileChange(e,t,s){if(!this.shouldWatchFile(t))return;let o=`${e}:${t}`;this.pendingChanges.has(o)&&clearTimeout(this.pendingChanges.get(o)),this.pendingChanges.set(o,setTimeout(()=>{this.pendingChanges.delete(o),this.processFileChange(e,t,s)},this.debounceTimeout))}processFileChange(e,t,s){if(!this.isWatching)return;let o="modified",r=!1;try{_.statSync(t),r=!0,e==="rename"?o="created":e==="change"&&(o="modified")}catch{e==="rename"&&(o="deleted")}if(r&&(o==="modified"||o==="created")&&!this.hasContentChanged(t)){S&&console.log(`Ignoring false change for: ${T.relative(s,t)}`);return}!r&&o==="deleted"&&this.fileContentHashes.delete(t);let n={type:"CODEV_FILE_CHANGE_DETECTTED",data:{eventType:e,changeType:o,filePath:t,relativePath:T.relative(s,t),watchPath:s,fileExists:r,timestamp:Date.now(),sessionId:process.env.SESSION_ID||"default"}};if(S&&console.log(`File ${o}: ${n.data.relativePath}`),this.emit("fileChange",n),this.onFileChange&&typeof this.onFileChange=="function")try{this.onFileChange(n)}catch(i){S&&console.error("Error in file change callback:",i.message)}}shouldWatchFile(e){let t=T.basename(e),s=e.replace(/\\/g,"/");for(let o of this.excludePatterns)if(o.test(s)||o.test(t))return!1;if(this.includePatterns.length===0)return!0;for(let o of this.includePatterns)if(o.test(s)||o.test(t))return!0;return!1}addWatchPath(e){this.watchPaths.includes(e)||(this.watchPaths.push(e),this.isWatching&&this.watchDirectory(e))}removeWatchPath(e){let t=this.watchPaths.indexOf(e);if(t>-1&&(this.watchPaths.splice(t,1),this.watchers.has(e)))try{this.watchers.get(e).close(),this.watchers.delete(e),S&&console.log(`Removed watch path: ${e}`)}catch(s){S&&console.error(`Error removing watch path ${e}:`,s.message)}}getStatus(){return{isWatching:this.isWatching,watchPaths:[...this.watchPaths],activeWatchers:this.watchers.size,pendingChanges:this.pendingChanges.size}}setFileChangeCallback(e){this.onFileChange=e}};Fe.exports=se});var je=m((Ss,Be)=>{var Ot=H(),Tt=require("path"),ys=require("fs"),ws=require("os"),At=$e(),Mt=_e(),qt=Me(),Ut=Ue(),Ft=Ne(),w=process.env.CODEV_DEBUG==="True",oe=class extends Ot{constructor(){super({configDir:".",configFile:".claude.json",defaultModel:"Claude Sonnet 4.5",executablePaths:["cc.mjs","/tmp/claude-code/package/cc.mjs"],environmentVariables:e=>({ANTHROPIC_BASE_URL:`${e}/claude`,ANTHROPIC_API_KEY:"codev",DISABLE_TELEMETRY:!0,CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:!0,DISABLE_COST_WARNINGS:!0,DISABLE_NON_ESSENTIAL_MODEL_CALLS:!0,CODEV_SERVER:e,CLAUDE_CODE_ATTRIBUTION_HEADER:"0"}),defaultConfig:{numStartups:1,installMethod:"unknown",autoUpdates:!1,theme:"Coder Dark",customApiKeyResponses:{approved:["codev"]},shiftEnterKeyBindingInstalled:!0,hasCompletedOnboarding:!0,subscriptionNoticeCount:0,hasAvailableSubscription:!0,projects:{}}}),this.fileWatchService=null,this.shutdownInProgress=!1,this.initializeServices()}initializeServices(){this.httpClient=new Mt({timeout:1e4}),this.authService=new qt({validateCredentials:!1}),this.sessionManager=new Ut({onSessionSwitch:e=>{this.sendTerminationMessage(e)}}),this.messageQueue=new At({maxRetries:2,retryDelay:500,shutdownTimeout:3e3,onProcessMessage:e=>this.processMessage(e)}),this.initializeFileWatchService()}resloveSettingFilePath(e){return Tt.join(e,this.config.configDir,".claude","settings.json")}initializeFileWatchService(){if(!process.env.SESSION_ID){w&&console.log("FileWatchService disabled: SESSION_ID environment variable not found");return}try{this.fileWatchService=new Ft({watchPaths:this.getFileWatchPaths(),onFileChange:e=>this.handleFileChange(e),debounceTimeout:300}),w&&console.log("FileWatchService initialized with SESSION_ID:",process.env.SESSION_ID)}catch(e){w&&console.error("Failed to initialize FileWatchService:",e.message)}}getFileWatchPaths(){let e=[],t=process.cwd();e.push(t);let s=process.env.CODEV_WATCH_PATHS;if(s){let o=s.split(",").map(r=>r.trim());e.push(...o)}return e}handleFileChange(e){if(w&&console.log("File change detected:",e.data.relativePath),this.shutdownInProgress)return;let t={message:e,sessionId:e.data.sessionId||process.env.SESSION_ID};this.messageQueue.enqueue(t)}startFileWatching(){this.fileWatchService&&!this.fileWatchService.isWatching&&(this.fileWatchService.startWatching(),w&&console.log("File watching started"))}stopFileWatching(){this.fileWatchService&&this.fileWatchService.isWatching&&(this.fileWatchService.stopWatching(),w&&console.log("File watching stopped"))}onChildMessage(e){e&&e.type==="claude:send-msg"&&this.handleClaudeSendMessage(e.data),super.onChildMessage(e)}handleClaudeSendMessage(e){if(w&&console.log("Handling claude:send-msg message:",e),!e||typeof e!="object"){console.error(`handleClaudeSendMessage: Invalid message data. Expected object, got: ${typeof e}`);return}if(this.shutdownInProgress){w&&console.log("Shutdown in progress, ignoring new message");return}let t=e.sessionId||process.env.SESSION_ID;this.sessionManager.handleSessionSwitch(t),this.messageQueue.enqueue(e)}async processMessage(e){let t=e.data.message,s=e.data.sessionId||process.env.SESSION_ID;if(!s)throw new Error("No session ID available");let o;try{o=typeof t=="string"?JSON.parse(t):t}catch(i){throw new Error(`Failed to parse message data: ${i.message}`)}let r=`/conversations/${s}/@append?task_type=codev`,n=this.authService.hasCredentials()?this.authService.generateAuthHeaders(`${this.httpClient.baseUrl}${r}`,o):{};w&&(console.debug("Sending message to:",r),console.debug("Send Message: ",JSON.stringify(o))),e.type!=="CODEV_TERMINATE_SIGNAL"&&(this.sessionManager.currentSessionId=s)}sendTerminationMessage(e){let t={message:e,sessionId:e.sessionId||this.sessionManager.getCurrentSessionId()};this.messageQueue.enqueue(t)}async handleChildProcessExit(e,t){w&&console.log(`Child process exited with code: ${e}, signal: ${t}`),this.stopFileWatching();let s=this.messageQueue.getQueueSize(),o=this.sessionManager.terminateCurrentSession("process exited normally",e,t);if(o&&this.sendTerminationMessage(o),s>0||o){w&&console.log("Starting graceful shutdown of message queue...");try{let r=!t||t==="SIGTERM",n=this.messageQueue.getQueueSize(),i={timeoutMs:r?8e3:3e3,batchSize:Math.min(n,15),fastMode:!r||n>30};w&&console.log("Shutdown options:",i);let a=await this.messageQueue.gracefulShutdown(i);w&&console.log("Message queue shutdown completed:",a),a.failedMessages>0&&w&&console.warn(`Shutdown summary: ${a.processedMessages} sent, ${a.failedMessages} failed, ${a.remainingMessages} remaining`)}catch(r){w&&console.error("Error during message queue shutdown:",r.message)}}}handleChildProcessError(e){w&&console.error(`Child process error: ${e.message}`);let t=this.sessionManager.createErrorTermination(e);t&&this.sendTerminationMessage(t)}async forceFlushMessages(e=3e3){if(this.messageQueue.getQueueSize()===0)return{success:!0,message:"No messages to flush"};w&&console.log(`Force flushing ${this.messageQueue.getQueueSize()} messages...`);try{return await this.messageQueue.forceFlushAndShutdown(e)}catch(t){return w&&console.error("Force flush failed:",t.message),{success:!1,error:t.message}}}async launch(e={}){let{codevServer:t,auth_ak:s=null,auth_sk:o=null}=e;return this.httpClient.setBaseUrl(t),s&&o&&this.authService.setCredentials(s,o),this.startFileWatching(),super.launch(e)}};Be.exports=oe});var Re=m((Es,Le)=>{var Nt=H(),Cs=require("path"),ne=class extends Nt{constructor(){super({configDir:".gemini",configFile:"settings.json",defaultModel:"gemini-2.5-pro",executablePaths:["gemini/gemini.js","../dist/gemini/gemini.js"],environmentVariables:e=>({GOOGLE_GEMINI_BASE_URL:`${e}/gemini`,GEMINI_API_KEY:"coder",GOOGLE_API_KEY:"coder",GOOGLE_CLOUD_PROJECT:"coder",GOOGLE_CLOUD_LOCATION:"coder",DISABLE_TELEMETRY:!0,GEMINI_CODE_DISABLE_NONESSENTIAL_TRAFFIC:!0,DISABLE_COST_WARNINGS:!0,DISABLE_NON_ESSENTIAL_MODEL_CALLS:!0,USE_VERTEX:!0}),defaultConfig:{ide:{hasSeenNudge:!0},telemetry:{enabled:!1,logPrompts:!1},privacy:{usageStatisticsEnabled:!1},general:{disableUpdateNag:!0,preferredEditor:"vscode",previewFeatures:!0},ui:{hideBanner:!0,theme:"Default"},security:{auth:{selectedType:"vertex-ai"}}}})}};Le.exports=ne});var Ge=m((vs,He)=>{var Bt=H(),F=require("path"),$=require("fs"),jt=require("os"),{spawn:Lt}=require("child_process"),G=process.env.CODEV_DEBUG==="True",re=class extends Bt{constructor(){super({configDir:".codex",configFile:"config.toml",defaultModel:"o4-mini",executablePaths:["codex.mjs","../dist/codex.mjs"],environmentVariables:e=>({OPENAI_BASE_URL:`${e}/codex`,OPENAI_API_KEY:"codev-proxy-key",DEBUG:G?"true":"false",CODEX_QUIET_MODE:"0",OPENAI_DISABLE_TELEMETRY:"true",CODEX_DISABLE_PROJECT_DOC:"0",CODEV_SERVER:e}),defaultConfig:{model:"gpt-5-codex",approvalMode:"suggest",fullAutoErrorMode:"ask-user",notify:[],history:{maxSize:1e3,saveHistory:!0,sensitivePatterns:[],persistence:"save-all"}}})}checkCodexAvailability(){try{let e=this.findExecutablePath();return $.existsSync(e)}catch{return!1}}resloveSettingFilePath(e){return F.join(e,this.config.configDir,"config.toml")}async ensureConfig(e,t=0){let s=F.join(jt.homedir(),this.config.configDir,this.config.configFile),o=F.dirname(s);try{$.existsSync(o)||$.mkdirSync(o,{recursive:!0});let r=`${e}/codex`;if($.existsSync(s)){let n=$.readFileSync(s,"utf8"),i=`openai_base_url = "${r}"`;/^openai_base_url\s*=/m.test(n)?n=n.replace(/^openai_base_url\s*=.*/m,i):n=n.trimEnd()+`
|
|
194
194
|
`+i+`
|
|
195
|
-
|
|
195
|
+
`,$.writeFileSync(s,n),G&&console.log(`Updated openai_base_url in ${s}`)}else{let n=this.config.defaultConfig||{},i=this.generateTOMLConfig(n,r);$.writeFileSync(s,i),G&&console.log(`Created Codex config file: ${s}`)}t>0&&await new Promise(n=>setTimeout(n,t))}catch(r){console.warn(`Failed to update ${this.config.configFile}: ${r.message}`)}}generateTOMLConfig(e,t){return`model = "${e.model||"gpt-5-codex"}"
|
|
196
196
|
openai_base_url = "${t}"
|
|
197
|
-
`}findExecutablePath(){let e=
|
|
197
|
+
`}findExecutablePath(){let e=F.dirname(require.main.filename);for(let t of this.config.executablePaths){let s=F.resolve(e,t);if($.existsSync(s))return s}throw new Error(`Could not find Codex executable in any of the configured paths: ${this.config.executablePaths.join(", ")}`)}async launch(e={}){let{remainingArgs:t=[],codevServer:s,auth_ak:o=null,auth_sk:r=null}=e;try{if(!this.checkCodexAvailability())throw new Error("Codex executable not found. Please ensure makecoder is properly installed: npm install -g makecoder@latest");await this.ensureConfig(s,1e3);let n=this.findExecutablePath();return G&&console.log(`executablePath: ${n}`),new Promise((i,a)=>{let c={...process.env,...this.config.environmentVariables(s)};o&&(c.CODEV_AUTH_AK=o),r&&(c.CODEV_AUTH_SK=r);let l=["--no-warnings"];process.env.CODEV_INSPECT_BRK==="True"&&l.push("--inspect-brk"),l.push(n,...t);let u=Lt("node",l,{env:c,stdio:["inherit","inherit","inherit","ipc"]});this.handleChildMessages(u),u.on("error",d=>{console.error(`Failed to start Codex: ${d.message}`),a(d)}),u.on("exit",async(d,p)=>{console.log(p?`terminated by signal: ${p}`:"Goodbye for now! Keep building great things!")}),process.on("SIGINT",async()=>{console.log(`
|
|
198
198
|
Terminating ...`),u.kill("SIGTERM"),setTimeout(()=>{u.killed||u.kill("SIGKILL")},8e3)}),process.on("SIGTERM",async()=>{console.log(`
|
|
199
199
|
Terminating ...`),u.kill("SIGTERM"),setTimeout(()=>{u.killed||u.kill("SIGKILL")},8e3)})})}catch(n){throw n}}};He.exports=re});var We=m((bs,ze)=>{var N=require("fs"),Ve=require("path"),{spawn:Ke}=require("child_process"),ie=class{constructor(){this.extensionId="codev.codev-background";let e=require.main?Ve.dirname(require.main.filename):__dirname;this.extensionPath=Ve.resolve(e,"vendor/claude-code.vsix"),this._codeCommand=null}async resolveCodeCommand(){if(this._codeCommand)return this._codeCommand;if(process.env.IS_AISTUDIO==="True"){let e="/usr/lib/aistudio/lib/vscode/bin/remote-cli/aistudio";if(N.existsSync(e))try{return N.accessSync(e,N.constants.F_OK|N.constants.X_OK),this._codeCommand=e,process.env.CODEV_DEBUG&&console.log(`Using AI Studio VSCode path: ${e}`),this._codeCommand}catch(t){process.env.CODEV_DEBUG&&console.log(`AI Studio path exists but not executable: ${t.message}`)}else process.env.CODEV_DEBUG&&console.log(`AI Studio path not found: ${e}`)}try{let{spawn:e}=require("child_process");return new Promise(t=>{let s=e("which",["code"],{stdio:["ignore","pipe","ignore"]}),o="";s.stdout.on("data",r=>{o+=r.toString().trim()}),s.on("close",r=>{r===0&&o?(this._codeCommand=o,process.env.CODEV_DEBUG&&console.log(`Resolved code command path: ${o}`),t(this._codeCommand)):(this._codeCommand="code",t(this._codeCommand))}),s.on("error",()=>{this._codeCommand="code",t(this._codeCommand)}),setTimeout(()=>{s.kill(),this._codeCommand="code",t(this._codeCommand)},3e3)})}catch{return this._codeCommand="code",this._codeCommand}}async shouldInstallExtension(){try{return process.env.IS_AISTUDIO!=="True"?(process.env.CODEV_DEBUG&&console.log("Not in AI Studio environment (IS_AISTUDIO!=True), skipping extension installation"),!1):await this.isVSCodeAvailable()?await this.isExtensionInstalled()?(process.env.CODEV_DEBUG&&console.log(`Extension ${this.extensionId} already installed`),!1):!!N.existsSync(this.extensionPath):(process.env.CODEV_DEBUG&&console.log("VSCode not available, skipping extension installation"),!1)}catch(e){return process.env.CODEV_DEBUG&&console.error(`Error checking extension installation status: ${e.message}`),!1}}async installExtension(){try{return console.log("Installing Codev VSCode extension..."),await this.executeVSCodeCommand(["--install-extension",this.extensionPath])?(console.log("\u2705 Codev VSCode extension installed successfully"),!0):(console.warn("\u274C Failed to install Codev VSCode extension"),!1)}catch(e){return console.warn(`Error installing VSCode extension: ${e.message}`),!1}}async isVSCodeAvailable(){try{let e=process.env.IS_AISTUDIO==="True"?["--help"]:["--version"],t=await this.executeVSCodeCommand(e,{timeout:1e4});if(process.env.CODEV_DEBUG&&(console.log(`VSCode availability check (${e.join(" ")}): ${t?"available":"unavailable"}`),process.env.IS_AISTUDIO==="True")){let{spawn:s}=require("child_process");try{s("which",["code"],{stdio:["ignore","pipe","ignore"]}).stdout.on("data",r=>{console.log("which code:",r.toString().trim())})}catch(o){console.log("which command failed:",o.message)}}return t}catch(e){return process.env.CODEV_DEBUG&&console.error("VSCode availability check error:",e.message),!1}}async isExtensionInstalled(){let e=await this.resolveCodeCommand();try{return new Promise(t=>{try{let s={stdio:["ignore","pipe","ignore"],shell:!1,env:{...process.env,PATH:process.env.PATH,HOME:process.env.HOME,USER:process.env.USER}};process.env.CODEV_DEBUG&&console.log(`Spawning: ${e} --list-extensions`);let o=Ke(e,["--list-extensions"],s),r="";o.stdout.on("data",n=>{r+=n.toString()}),o.on("close",n=>{if(n===0){let i=r.split(`
|
|
200
200
|
`).map(a=>a.trim());t(i.includes(this.extensionId))}else t(!1)}),o.on("error",n=>{process.env.CODEV_DEBUG&&(console.error("VSCode list extensions error:",n.message),console.error("Error code:",n.code),console.error("Error errno:",n.errno),console.error("Error syscall:",n.syscall)),t(!1)}),setTimeout(()=>{try{o.kill()}catch{}t(!1)},1e4)}catch(s){process.env.CODEV_DEBUG&&console.error("Failed to spawn VSCode list extensions:",s.message),t(!1)}})}catch{return!1}}async executeVSCodeCommand(e,t={}){let s=await this.resolveCodeCommand();return new Promise(o=>{try{let r={stdio:"ignore",shell:!1,env:{...process.env,PATH:process.env.PATH,HOME:process.env.HOME,USER:process.env.USER}};process.env.CODEV_DEBUG&&console.log(`Spawning: ${s} ${e.join(" ")}`);let n=Ke(s,e,r);n.on("close",a=>{o(a===0)}),n.on("error",a=>{process.env.CODEV_DEBUG&&(console.error("VSCode command error:",a.message),console.error("Error code:",a.code),console.error("Error errno:",a.errno),console.error("Error syscall:",a.syscall)),o(!1)});let i=t.timeout||3e4;setTimeout(()=>{try{n.kill()}catch{}o(!1)},i)}catch(r){process.env.CODEV_DEBUG&&console.error("Failed to spawn VSCode command:",r.message),o(!1)}})}async ensureExtensionInstalled(){try{process.env.CODEV_DEBUG&&console.log("VSCode Extension Service: Checking extension status..."),await this.shouldInstallExtension()&&await this.installExtension()}catch(e){process.env.CODEV_DEBUG&&console.error("VSCode Extension Service Error:",e)}}};ze.exports=ie});var Ye=m((Is,Qe)=>{var E=require("fs"),O=require("path"),Rt=require("readline"),{execSync:V}=require("child_process"),Je=require("os"),ae=class{constructor(){this.serverUrl="https://makecoder.com/bigapis/codev/v1/coderpub"}getClaudeJsonlPath(e,t=!1){let s=e.replace(/[/_]/g,"-"),o=O.join(Je.homedir(),".claude","projects",s);if(t&&(console.log(`
|
|
@@ -207,12 +207,12 @@ Terminating ...`),u.kill("SIGTERM"),setTimeout(()=>{u.killed||u.kill("SIGKILL")}
|
|
|
207
207
|
\u{1F310} [allow-clone] \u5F00\u59CB\u4E0A\u4F20\u5230\u670D\u52A1\u5668...`);let l=await this.upload(i,n,t,s,o,r);return l.code===0?(console.log(`
|
|
208
208
|
\u2705 \u53D1\u5E03\u6210\u529F!`),console.log(`\u{1F4CC} \u7248\u672C: ${l.data.version}`),console.log(`\u{1F310} \u8BBF\u95EE\u5730\u5740: https://${n}.coder.pub/`),0):(console.error(`
|
|
209
209
|
\u274C \u53D1\u5E03\u5931\u8D25: ${l.message||l.reason}`),1)}catch(a){return console.error(`
|
|
210
|
-
\u274C ${a.message}`),1}finally{i&&this.cleanup(i)}}};Qe.exports=ae});var et=m((
|
|
211
|
-
`);for(let a of i)console.log(` ${a.slug.padEnd(20)} ${a.summary}`);s(0)}catch(n){console.error(`\u274C \u89E3\u6790\u54CD\u5E94\u5931\u8D25: ${n.message}`),s(1)}})}).on("error",o=>{console.error(`\u274C \u8BF7\u6C42\u5931\u8D25: ${o.message}`),s(1)})})}async publish(e,t,s){let{execSync:o}=require("child_process"),r=require("os"),n="global",i="PUBLIC",a=null,c=null,l=null,u=null;for(let
|
|
212
|
-
\u2705 \u53D1\u5E03\u6210\u529F!`),console.log(` ${
|
|
213
|
-
\u274C \u53D1\u5E03\u5931\u8D25: ${
|
|
214
|
-
\u274C \u53D1\u5E03\u5931\u8D25: ${I.msg||y}`),1}catch{}return console.error(`\u274C \u8BF7\u6C42\u5931\u8D25: ${
|
|
215
|
-
`);for(let l of a){let u=`${l.namespace}/${l.slug}`.padEnd(36),d=`\u2B50 ${l.starCount??0}`.padEnd(8),
|
|
210
|
+
\u274C ${a.message}`),1}finally{i&&this.cleanup(i)}}};Qe.exports=ae});var et=m((xs,Xe)=>{var Ze=require("https"),v=require("fs"),b=require("path"),Ht=require("os"),x="https://makecoder.com/skillhub",ce=class{getSkillDirs(){let e=Ht.homedir();return[b.join(e,".claude","skills"),b.join(e,".codex","skills"),b.join(e,".gemini","skills"),b.join(e,".agents","skills")]}fetchWithAuth(e,t){return new Promise((s,o)=>{let r=new URL(e),n={hostname:r.hostname,port:r.port||443,path:r.pathname+r.search,method:"GET",headers:t?{Authorization:`Bearer ${t}`}:{}};Ze.get(n,i=>{if(i.statusCode>=300&&i.statusCode<400&&i.headers.location)return this.fetchWithAuth(i.headers.location,t).then(s).catch(o);let a="";i.on("data",c=>{a+=c}),i.on("end",()=>s({status:i.statusCode,body:a}))}).on("error",o)})}async handle({skillsSubcommand:e,skillsArg:t,skillsRemainingArgs:s,auth_ak:o,auth_sk:r}){let{execFileSync:n}=require("child_process");if(!e||e==="--help"||e==="-h")return this.showHelp(),0;if(e==="publish")return await this.publish(s||[],o,r);if(e==="unpublish")return await this.unpublish(t,o,r);if(e==="list")return await this.listMySkills(o,r);if(e==="namespaces")return await this.listNamespaces(o,r);if(t&&e!=="search"&&!/^[@a-zA-Z0-9_\-/.]+$/.test(t))return console.error("\u274C skill \u540D\u79F0\u5305\u542B\u975E\u6CD5\u5B57\u7B26"),1;if(e==="search")return t?await this.search(t):(console.error("\u274C \u8BF7\u6307\u5B9A\u641C\u7D22\u5173\u952E\u8BCD"),1);if(e==="remove")return t?this.remove(t):(console.error("\u274C \u8BF7\u6307\u5B9A skill \u540D\u79F0"),1);if((e==="add"||e==="update")&&t&&o&&r)return await this.install(t,`${o}.${r}`);try{let i;if(e==="add"){if(!t)return console.error("\u274C \u8BF7\u6307\u5B9A skill \u540D\u79F0"),1;i=["skills","add",x,"--skill",t,"-g"]}else if(e==="update")i=t?["skills","update","--skill",t,"-g"]:["skills","update","-g"];else return console.error(`\u274C \u672A\u77E5\u5B50\u547D\u4EE4: ${e}`),1;return n("npx",i,{stdio:"inherit"}),0}catch(i){return console.error(`\u274C \u6267\u884C\u5931\u8D25: ${i.message}`),1}}async install(e,t){let s=x.replace(/\/$/,"");console.log(`\u{1F50D} \u6B63\u5728\u4ECE ${x} \u67E5\u627E skill...`);let o;try{let c=await this.fetchWithAuth(`${s}/.well-known/agent-skills/index.json?skill=${encodeURIComponent(e)}`,t);if(c.status===404)return console.error(`\u274C \u672A\u627E\u5230 skill: ${e}`),1;if(c.status!==200)return console.error(`\u274C \u65E0\u6CD5\u83B7\u53D6 skill \u4FE1\u606F (HTTP ${c.status})`),1;o=JSON.parse(c.body)}catch(c){return console.error(`\u274C \u8BF7\u6C42\u5931\u8D25: ${c.message}`),1}let r=(o.skills||[])[0];if(!r)return console.error(`\u274C \u672A\u627E\u5230 skill: ${e}`),1;let n=Array.from(new Set(["SKILL.md",...r.files||[]])),i=`${s}/.well-known/agent-skills/${r.name}`,a={};for(let c of n)try{let l=await this.fetchWithAuth(`${i}/${c}`,t);if(l.status!==200){console.warn(`\u26A0\uFE0F \u8DF3\u8FC7 ${c} (HTTP ${l.status})`);continue}a[c]=l.body}catch(l){console.warn(`\u26A0\uFE0F \u4E0B\u8F7D ${c} \u5931\u8D25: ${l.message}`)}console.log(`\u{1F4E6} \u6B63\u5728\u5B89\u88C5 ${r.name}...`);for(let c of this.getSkillDirs()){let l=b.join(c,r.name);v.mkdirSync(l,{recursive:!0});for(let[u,d]of Object.entries(a)){let p=b.join(l,u);v.mkdirSync(b.dirname(p),{recursive:!0}),v.writeFileSync(p,d,"utf8")}}return console.log(`\u2705 ${r.name} \u5B89\u88C5\u5B8C\u6210`),0}remove(e){let t=!1;for(let s of this.getSkillDirs()){let o=b.join(s,e);v.existsSync(o)&&(v.rmSync(o,{recursive:!0,force:!0}),console.log(` \u{1F5D1}\uFE0F ${o}`),t=!0)}return t?(console.log(`\u2705 ${e} \u5DF2\u5220\u9664`),0):(console.error(`\u274C \u672A\u627E\u5230\u5DF2\u5B89\u88C5\u7684 skill: ${e}`),1)}async search(e){let t=`${x}/api/web/skills?q=${encodeURIComponent(e)}&sort=relevance&page=0&size=12`;return new Promise(s=>{Ze.get(t,o=>{let r="";o.on("data",n=>{r+=n}),o.on("end",()=>{try{let n=JSON.parse(r);if(n.code!==0)return console.error(`\u274C \u67E5\u8BE2\u5931\u8D25: ${n.msg}`),s(1);let i=n.data.items;if(i.length===0)return console.log(`\u6CA1\u6709\u627E\u5230\u4E0E "${e}" \u76F8\u5173\u7684 skill`),s(0);console.log(`\u627E\u5230 ${n.data.total} \u4E2A\u7ED3\u679C:
|
|
211
|
+
`);for(let a of i)console.log(` ${a.slug.padEnd(20)} ${a.summary}`);s(0)}catch(n){console.error(`\u274C \u89E3\u6790\u54CD\u5E94\u5931\u8D25: ${n.message}`),s(1)}})}).on("error",o=>{console.error(`\u274C \u8BF7\u6C42\u5931\u8D25: ${o.message}`),s(1)})})}async publish(e,t,s){let{execSync:o}=require("child_process"),r=require("os"),n="global",i="PUBLIC",a=null,c=null,l=null,u=null;for(let f=0;f<e.length;f++)if(e[f]==="--namespace"||e[f]==="-n")n=e[++f];else if(e[f]==="--visibility"||e[f]==="-v")i=e[++f];else if(e[f]==="--meta-data"){let y=e[++f];try{JSON.parse(y)}catch(I){return console.error(`\u274C --meta-data \u4E0D\u662F\u5408\u6CD5\u7684 JSON\uFF1A${I.message}`),1}a=y}else if(!e[f].startsWith("-")){let y=e[f];v.existsSync(y)&&v.statSync(y).isDirectory()?u=y:c=y}if(!t||!s)return console.error("\u274C \u7F3A\u5C11 API Key\uFF0C\u8BF7\u5148\u767B\u5F55: coder login"),1;let d=n.startsWith("@")?n.slice(1):n;d==="global"||(i="NAMESPACE_ONLY");let C=["PUBLIC","NAMESPACE_ONLY","PRIVATE"];if(!C.includes(i))return console.error(`\u274C visibility \u5FC5\u987B\u662F: ${C.join(", ")}`),1;if(c){if(!v.existsSync(c))return console.error(`\u274C \u6587\u4EF6\u4E0D\u5B58\u5728: ${c}`),1}else{let f=u?b.resolve(u):process.cwd();l=b.join(r.tmpdir(),`skill-pub-${Date.now()}.zip`),console.log(`\u{1F4E6} \u6B63\u5728\u6253\u5305 ${f}...`);try{v.existsSync(b.join(f,".git"))?(o(`git archive -o "${l}" HEAD`,{cwd:f,stdio:"pipe"}),console.log(" \u4F7F\u7528 git archive\uFF08\u5DF2\u6392\u9664 .gitignore \u6587\u4EF6\uFF09")):o(`zip -r "${l}" . -x ".git/*" -x "node_modules/*" -x ".env" -x "*.log"`,{cwd:f,stdio:"pipe"})}catch(y){return console.error(`\u274C \u6253\u5305\u5931\u8D25: ${y.message}`),1}c=l}let B=`${x}/api/v1/skills/${encodeURIComponent(d)}/publish?visibility=${encodeURIComponent(i)}`,A=`${t}.${s}`;console.log(`\u{1F680} \u6B63\u5728\u53D1\u5E03\u5230 ${x}...`),console.log(` namespace: ${d}`),console.log(` visibility: ${i}`);try{let f=a?` -F "meta_data=${a.replace(/"/g,'\\"')}"`:"",y=`curl -s -X POST "${B}" -H "Authorization: Bearer ${A}" -F "file=@${c}"${f}`,I=o(y,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),j=JSON.parse(I);if(j.code===0){let L=j.data;return console.log(`
|
|
212
|
+
\u2705 \u53D1\u5E03\u6210\u529F!`),console.log(` ${L.namespace}/${L.slug}@${L.version}`),L.status==="PUBLISHED"?console.log(" \u72B6\u6001: \u5DF2\u53D1\u5E03"):console.log(" \u72B6\u6001: \u5F85\u5BA1\u6838"),0}else return console.error(`
|
|
213
|
+
\u274C \u53D1\u5E03\u5931\u8D25: ${j.msg||JSON.stringify(j)}`),1}catch(f){let y=f.stdout;if(y)try{let I=JSON.parse(y);return console.error(`
|
|
214
|
+
\u274C \u53D1\u5E03\u5931\u8D25: ${I.msg||y}`),1}catch{}return console.error(`\u274C \u8BF7\u6C42\u5931\u8D25: ${f.message}`),1}finally{l&&v.existsSync(l)&&v.unlinkSync(l)}}async unpublish(e,t,s){let{execSync:o}=require("child_process");if(!e)return console.error("\u274C \u8BF7\u6307\u5B9A skill: coder skills unpublish <namespace>/<slug>"),1;if(!t||!s)return console.error("\u274C \u7F3A\u5C11 API Key\uFF0C\u8BF7\u5148\u767B\u5F55: coder login"),1;let r=e.split("/");if(r.length!==2||!r[0]||!r[1])return console.error("\u274C \u683C\u5F0F\u9519\u8BEF\uFF0C\u5E94\u4E3A <namespace>/<slug>\uFF0C\u4F8B\u5982: global/my-skill"),1;let[n,i]=r,a=n.startsWith("@")?n.slice(1):n,c=`${x}/api/v1/skills/${encodeURIComponent(a)}/${encodeURIComponent(i)}`,l=`${t}.${s}`;console.log(`\u{1F5D1}\uFE0F \u6B63\u5728\u4E0B\u67B6 ${a}/${i}...`);try{let u=o(`curl -s -X DELETE "${c}" -H "Authorization: Bearer ${l}"`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),d=JSON.parse(u);return d.code===0?(console.log(`\u2705 \u5DF2\u4E0B\u67B6 ${a}/${i}`),0):(console.error(`\u274C \u4E0B\u67B6\u5931\u8D25: ${d.msg||JSON.stringify(d)}`),1)}catch(u){return console.error(`\u274C \u8BF7\u6C42\u5931\u8D25: ${u.message}`),1}}async listMySkills(e,t){let{execSync:s}=require("child_process");if(!e||!t)return console.error("\u274C \u7F3A\u5C11 API Key\uFF0C\u8BF7\u5148\u767B\u5F55: coder login"),1;let o=`${x}/api/v1/me/skills?size=50`,r=`${e}.${t}`;try{let n=s(`curl -s "${o}" -H "Authorization: Bearer ${r}"`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),i=JSON.parse(n);if(i.code!==0)return console.error(`\u274C \u83B7\u53D6\u5931\u8D25: ${i.msg}`),1;let a=i.data?.items||[],c=i.data?.total||0;if(a.length===0)return console.log("\u6682\u65E0\u5DF2\u53D1\u5E03\u7684 skill"),0;console.log(`\u5171 ${c} \u4E2A skill:
|
|
215
|
+
`);for(let l of a){let u=`${l.namespace}/${l.slug}`.padEnd(36),d=`\u2B50 ${l.starCount??0}`.padEnd(8),p=`\u2193 ${l.downloadCount??0}`.padEnd(10);console.log(` ${u} ${d} ${p} [${l.status}]`),l.displayName&&l.displayName!==l.slug&&console.log(` ${"".padEnd(36)} ${l.displayName}`)}return 0}catch(n){return console.error(`\u274C \u8BF7\u6C42\u5931\u8D25: ${n.message}`),1}}async listNamespaces(e,t){let{execSync:s}=require("child_process");if(!e||!t)return console.error("\u274C \u7F3A\u5C11 API Key\uFF0C\u8BF7\u5148\u767B\u5F55: coder login"),1;let o=`${x}/api/v1/me/namespaces`,r=`${e}.${t}`;try{let n=s(`curl -s "${o}" -H "Authorization: Bearer ${r}"`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),i=JSON.parse(n);if(i.code!==0)return console.error(`\u274C \u83B7\u53D6\u5931\u8D25: ${i.msg}`),1;let a=i.data||[];if(a.length===0)return console.log("\u6682\u65E0\u547D\u540D\u7A7A\u95F4"),0;console.log(`\u5171 ${a.length} \u4E2A\u547D\u540D\u7A7A\u95F4:
|
|
216
216
|
`);for(let c of a){let l=c.type==="GLOBAL"?"\u5168\u5C40":"\u56E2\u961F";console.log(` @${c.slug.padEnd(20)} ${c.displayName.padEnd(20)} [${l}] ${c.status}`)}return 0}catch(n){return console.error(`\u274C \u8BF7\u6C42\u5931\u8D25: ${n.message}`),1}}showHelp(){console.log(`
|
|
217
217
|
coder skills \u2014 \u7BA1\u7406 Claude Code skills
|
|
218
218
|
|
|
@@ -245,10 +245,10 @@ EXAMPLES:
|
|
|
245
245
|
coder skills publish --meta-data '{"category":"tool"}' ./my-skill-dir
|
|
246
246
|
coder skills unpublish global/my-skill
|
|
247
247
|
coder skills namespaces
|
|
248
|
-
`)}};Xe.exports=ce});var ot=m((
|
|
248
|
+
`)}};Xe.exports=ce});var ot=m(($s,st)=>{var Gt=require("https"),K="https://makecoder.com/wiki",Vt=`${K}/api`,D=h=>`${K}/doc/${h}`,tt=h=>`${K}/collection/${h}`,le=class{getToken(e,t){return e&&t?`${e}.${t}`:null}post(e,t,s){return new Promise((o,r)=>{let n=JSON.stringify(t),i=new URL(`${Vt}/${e}`),a={hostname:i.hostname,port:i.port||443,path:i.pathname,method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(n),Authorization:`Bearer ${s}`}},c=Gt.request(a,l=>{let u="";l.on("data",d=>u+=d),l.on("end",()=>o({status:l.statusCode,body:u}))});c.on("error",r),c.write(n),c.end()})}parseJson(e){try{return JSON.parse(e)}catch{return null}}async handle({wikiSubcommand:e,wikiArg:t,wikiRemainingArgs:s,auth_ak:o,auth_sk:r}){if(!e||e==="--help"||e==="-h")return this.showHelp(),0;let n=this.getToken(o,r);if(!n)return console.error("\u274C \u7F3A\u5C11 API Key\uFF0C\u8BF7\u5148\u767B\u5F55: coder login"),1;let i=s||[];return e==="list"?await this.list(t,i,n):e==="create-collection"?await this.createCollection(i,n):e==="update-collection"?await this.updateCollection(t,i,n):e==="delete-collection"?await this.deleteCollection(t,n):e==="get"?await this.get(t,n):e==="publish"?await this.publish(t,i,n):e==="update"?await this.update(i,n):e==="delete"?await this.delete(t,i,n):e==="move"?await this.move(i,n):e==="archive"?await this.archive(t,n):e==="restore"?await this.restore(t,n):e==="drafts"?await this.drafts(n):e==="recent"?await this.recent(n):e==="search"?t?await this.search([t,...i],n):(console.error("\u274C \u8BF7\u6307\u5B9A\u641C\u7D22\u5173\u952E\u8BCD"),1):e==="stars"?await this.stars(n):e==="star"?await this.star(t,i,n):e==="unstar"?await this.unstar(t,n):e==="pins"?await this.pins(t,n):e==="pin"?await this.pin(t,i,n):e==="unpin"?await this.unpin(t,n):e==="comments"?await this.comments(t,n):e==="comment"?await this.comment(t,i,n):(console.error(`\u274C \u672A\u77E5\u5B50\u547D\u4EE4: ${e}`),this.showHelp(),1)}async list(e,t,s){let o=t.indexOf("-d"),r=o!==-1?parseInt(t[o+1],10):null;if(!e){let c=await this.post("collections.list",{limit:100,offset:0},s),l=this.parseJson(c.body);if(!l?.data)return console.error("\u274C \u8BF7\u6C42\u5931\u8D25:",c.body),1;let u=l.data.collections||l.data||[];return u.length?(this.printTable(u.map(d=>({collectionId:d.id,\u76EE\u5F55\u540D\u79F0:d.name,URL:tt(d.urlId||d.id)}))),0):(console.log("\u6682\u65E0\u76EE\u5F55"),0)}if(r===null){let c=await this.post("documents.list",{collectionId:e,sort:"updatedAt",direction:"DESC"},s),l=this.parseJson(c.body);if(!l?.data)return console.error("\u274C \u8BF7\u6C42\u5931\u8D25:",c.body),1;let u=l.data.documents||l.data||[];return u.length?(this.printTable(u.map(d=>({docId:d.id,\u6807\u9898:d.title,URL:D(d.urlId||d.id)}))),0):(console.log("\u6682\u65E0\u6587\u6863"),0)}let n=await this.post("collections.documents",{id:e},s),i=this.parseJson(n.body);if(!i?.data)return console.error("\u274C \u8BF7\u6C42\u5931\u8D25:",n.body),1;let a=r===-1?1/0:r;return this.printTree(i.data,"",a,0),0}printTree(e,t,s,o){if(Array.isArray(e))for(let r=0;r<e.length;r++){let n=e[r],i=r===e.length-1,a=i?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",c=n.url?`${K}${n.url}`:D(n.id);console.log(`${t}${a}${n.title||n.id} \x1B[90m${c}\x1B[0m`),n.children?.length&&o+1<s&&this.printTree(n.children,t+(i?" ":"\u2502 "),s,o+1)}}printTable(e){if(!e.length)return;let t=Object.keys(e[0]),s=i=>[...String(i)].reduce((a,c)=>a+(c.charCodeAt(0)>127?2:1),0),o=(i,a)=>i+" ".repeat(Math.max(0,a-s(i))),r=t.map(i=>Math.max(s(i),...e.map(a=>s(a[i]||"")))),n=r.map(i=>"-".repeat(i)).join("-+-");console.log(t.map((i,a)=>o(i,r[a])).join(" | ")),console.log(n);for(let i of e)console.log(t.map((a,c)=>o(String(i[a]||""),r[c])).join(" | "))}async createCollection(e,t){let s=e.indexOf("--permission"),o="read_write";s!==-1&&(o=e[s+1]||"read_write",e.splice(s,2));let r=e[0];if(!r)return console.error("\u274C \u8BF7\u6307\u5B9A\u76EE\u5F55\u540D\u79F0"),1;let n=e.slice(1).join(" "),i={name:r,description:n,sharing:!0};o==="null"||o==="none"?i.permission=null:i.permission=o;let a=await this.post("collections.create",i,t),c=this.parseJson(a.body);return c?.data?(console.log(`\u2705 \u76EE\u5F55\u5DF2\u521B\u5EFA: ${c.data.id} \u2014 ${c.data.name}`),0):(console.error("\u274C \u521B\u5EFA\u5931\u8D25:",a.body),1)}async updateCollection(e,t,s){if(!e)return console.error("\u274C \u8BF7\u6307\u5B9A\u76EE\u5F55 ID"),1;let o={id:e},r=t.indexOf("--name");r!==-1&&(o.name=t[r+1]);let n=t.indexOf("--description");n!==-1&&(o.description=t[n+1]);let i=t.indexOf("--permission");if(i!==-1){let d=t[i+1];o.permission=d==="null"||d==="none"?null:d}let a=t.indexOf("--color");a!==-1&&(o.color=t[a+1]);let c=t.indexOf("--sharing");if(c!==-1&&(o.sharing=t[c+1]==="true"),Object.keys(o).length<=1)return console.error("\u274C \u8BF7\u81F3\u5C11\u6307\u5B9A\u4E00\u4E2A\u8981\u66F4\u65B0\u7684\u5B57\u6BB5\uFF08--name, --description, --permission, --color, --sharing\uFF09"),1;let l=await this.post("collections.update",o,s),u=this.parseJson(l.body);return u?.data?(console.log(`\u2705 \u76EE\u5F55\u5DF2\u66F4\u65B0: ${u.data.id} \u2014 ${u.data.name}`),0):(console.error("\u274C \u66F4\u65B0\u76EE\u5F55\u5931\u8D25:",l.body),1)}async deleteCollection(e,t){if(!e)return console.error("\u274C \u8BF7\u6307\u5B9A\u76EE\u5F55 ID"),1;let s=await this.post("collections.delete",{id:e},t);return this.parseJson(s.body)?.ok===!1||s.status>=400?(console.error("\u274C \u5220\u9664\u76EE\u5F55\u5931\u8D25:",s.body),1):(console.log("\u2705 \u76EE\u5F55\u5DF2\u5220\u9664"),0)}async get(e,t){if(!e)return console.error("\u274C \u8BF7\u6307\u5B9A\u6587\u6863 ID"),1;let s=await this.post("documents.info",{id:e},t),o=this.parseJson(s.body);if(!o?.data)return console.error("\u274C \u8BF7\u6C42\u5931\u8D25:",s.body),1;let r=o.data;return console.log(`\u6807\u9898: ${r.title}`),console.log(`ID: ${r.id}`),console.log(`\u76EE\u5F55: ${r.collectionId}`),console.log(`\u66F4\u65B0: ${r.updatedAt}`),r.text&&console.log(`
|
|
249
249
|
${r.text}`),0}async publish(e,t,s){let o=require("fs"),r=require("path");if(!e)return console.error(`\u274C \u7528\u6CD5: wiki publish <collectionId> <title> [text]
|
|
250
|
-
wiki publish <collectionId> --file <path> [--parent <parentDocId>]`),1;let n,i,a,c=t.indexOf("--file"),l=t.indexOf("--parent");if(l!==-1&&(a=t[l+1]),c!==-1){let
|
|
251
|
-
${D(A.data.urlId||C)}`),0):(console.error("\u274C \u66F4\u65B0\u5185\u5BB9\u5931\u8D25:",B.body),1)}async update(e,t){let s=require("fs"),o=require("path"),r=e[0];if(!r)return console.error("\u274C \u7528\u6CD5: wiki update <docId> <title> [text] | <docId> --file <path>"),1;let n,i,a=e.indexOf("--file");if(a!==-1){let d=e[a+1];if(!d)return console.error("\u274C \u8BF7\u6307\u5B9A --file \u8DEF\u5F84"),1;let
|
|
250
|
+
wiki publish <collectionId> --file <path> [--parent <parentDocId>]`),1;let n,i,a,c=t.indexOf("--file"),l=t.indexOf("--parent");if(l!==-1&&(a=t[l+1]),c!==-1){let f=t[c+1];if(!f)return console.error("\u274C \u8BF7\u6307\u5B9A --file \u8DEF\u5F84"),1;let y=r.resolve(f);if(!o.existsSync(y))return console.error(`\u274C \u6587\u4EF6\u4E0D\u5B58\u5728: ${y}`),1;i=o.readFileSync(y,"utf8");let I=i.match(/^#\s+(.+)/m);if(!I)return console.error("\u274C \u6587\u4EF6\u7F3A\u5C11 H1 \u6807\u9898\uFF08# \u6807\u9898\uFF09\uFF0C\u8BF7\u6DFB\u52A0\u540E\u91CD\u8BD5"),1;n=I[1].trim()}else if(n=t[0],i=t.slice(1).join(" "),!n)return console.error("\u274C \u8BF7\u6307\u5B9A\u6587\u6863\u6807\u9898"),1;let u={collectionId:e,title:n,text:"",publish:!0};a&&(u.parentDocumentId=a);let d=await this.post("documents.create",u,s),p=this.parseJson(d.body);if(!p?.data)return console.error("\u274C \u521B\u5EFA\u6587\u6863\u5931\u8D25:",d.body),1;let C=p.data.id;console.log(` \u521B\u5EFA\u6587\u6863: ${C}`);let B=await this.post("documents.update",{id:C,title:n,text:i,publish:!0},s),A=this.parseJson(B.body);return A?.data?(console.log(`\u2705 \u6587\u6863\u5DF2\u53D1\u5E03: ${A.data.title}
|
|
251
|
+
${D(A.data.urlId||C)}`),0):(console.error("\u274C \u66F4\u65B0\u5185\u5BB9\u5931\u8D25:",B.body),1)}async update(e,t){let s=require("fs"),o=require("path"),r=e[0];if(!r)return console.error("\u274C \u7528\u6CD5: wiki update <docId> <title> [text] | <docId> --file <path>"),1;let n,i,a=e.indexOf("--file");if(a!==-1){let d=e[a+1];if(!d)return console.error("\u274C \u8BF7\u6307\u5B9A --file \u8DEF\u5F84"),1;let p=o.resolve(d);if(!s.existsSync(p))return console.error(`\u274C \u6587\u4EF6\u4E0D\u5B58\u5728: ${p}`),1;i=s.readFileSync(p,"utf8");let C=i.match(/^#\s+(.+)/m);if(!C)return console.error("\u274C \u6587\u4EF6\u7F3A\u5C11 H1 \u6807\u9898\uFF08# \u6807\u9898\uFF09\uFF0C\u8BF7\u6DFB\u52A0\u540E\u91CD\u8BD5"),1;n=C[1].trim()}else if(n=e[1],i=e.slice(2).join(" "),!n)return console.error("\u274C \u8BF7\u6307\u5B9A\u6587\u6863\u6807\u9898"),1;let c={id:r,title:n,publish:!0};i&&(c.text=i);let l=await this.post("documents.update",c,t),u=this.parseJson(l.body);return u?.data?(console.log(`\u2705 \u6587\u6863\u5DF2\u66F4\u65B0: ${u.data.title}`),0):(console.error("\u274C \u66F4\u65B0\u5931\u8D25:",l.body),1)}async delete(e,t,s){if(!e)return console.error("\u274C \u8BF7\u6307\u5B9A\u6587\u6863 ID"),1;let o=t.includes("--permanent"),r=await this.post("documents.delete",{id:e,...o?{permanent:!0}:{}},s);return this.parseJson(r.body)?.ok===!1||r.status>=400?(console.error("\u274C \u5220\u9664\u5931\u8D25:",r.body),1):(console.log(`\u2705 \u6587\u6863\u5DF2${o?"\u6C38\u4E45":""}\u5220\u9664`),0)}async move(e,t){let[s,o,r]=e;if(!s||!o)return console.error("\u274C \u7528\u6CD5: wiki move <docId> <collectionId> [parentDocId]"),1;let n={id:s,collectionId:o};r&&(n.parentDocumentId=r);let i=await this.post("documents.move",n,t);return this.parseJson(i.body)?.data?(console.log("\u2705 \u6587\u6863\u5DF2\u79FB\u52A8"),0):(console.error("\u274C \u79FB\u52A8\u5931\u8D25:",i.body),1)}async archive(e,t){if(!e)return console.error("\u274C \u8BF7\u6307\u5B9A\u6587\u6863 ID"),1;let s=await this.post("documents.archive",{id:e},t);return this.parseJson(s.body)?.data?(console.log("\u2705 \u6587\u6863\u5DF2\u5F52\u6863"),0):(console.error("\u274C \u5F52\u6863\u5931\u8D25:",s.body),1)}async restore(e,t){if(!e)return console.error("\u274C \u8BF7\u6307\u5B9A\u6587\u6863 ID"),1;let s=await this.post("documents.restore",{id:e},t);return this.parseJson(s.body)?.data?(console.log("\u2705 \u6587\u6863\u5DF2\u6062\u590D"),0):(console.error("\u274C \u6062\u590D\u5931\u8D25:",s.body),1)}async drafts(e){let t=await this.post("documents.drafts",{sort:"updatedAt",direction:"DESC"},e),s=this.parseJson(t.body);if(!s?.data)return console.error("\u274C \u8BF7\u6C42\u5931\u8D25:",t.body),1;let o=s.data.documents||s.data||[];return o.length?(this.printTable(o.map(r=>({ID:r.id,\u6807\u9898:r.title,URL:D(r.urlId||r.id)}))),0):(console.log("\u6682\u65E0\u8349\u7A3F"),0)}async recent(e){let t=await this.post("documents.viewed",{sort:"updatedAt",direction:"DESC"},e),s=this.parseJson(t.body);if(!s?.data)return console.error("\u274C \u8BF7\u6C42\u5931\u8D25:",t.body),1;let o=s.data.documents||s.data||[];return o.length?(this.printTable(o.map(r=>({ID:r.id,\u6807\u9898:r.title,URL:D(r.urlId||r.id)}))),0):(console.log("\u6682\u65E0\u6D4F\u89C8\u8BB0\u5F55"),0)}async search(e,t){let s=e.join(" "),o=await this.post("documents.search",{query:s,snippetMinWords:20,snippetMaxWords:30},t),r=this.parseJson(o.body);if(!r?.data)return console.error("\u274C \u641C\u7D22\u5931\u8D25:",o.body),1;let n=r.data||[];return n.length?(console.log(`\u627E\u5230 ${n.length} \u4E2A\u7ED3\u679C:
|
|
252
252
|
`),this.printTable(n.map(i=>{let a=i.document||i;return{docId:a.id,\u6807\u9898:a.title,URL:D(a.urlId||a.id)}})),0):(console.log(`\u6CA1\u6709\u627E\u5230\u4E0E "${s}" \u76F8\u5173\u7684\u6587\u6863`),0)}async stars(e){let t=await this.post("stars.list",{},e),s=this.parseJson(t.body);if(!s?.data)return console.error("\u274C \u8BF7\u6C42\u5931\u8D25:",t.body),1;let o=s.data.stars||s.data||[];return o.length?(this.printTable(o.map(r=>({starId:r.id,\u6807\u9898:r.document?.title||r.collection?.name||"",URL:r.document?D(r.document.urlId||r.document.id):r.collection?tt(r.collection.urlId||r.collection.id):""}))),0):(console.log("\u6682\u65E0\u6536\u85CF"),0)}async star(e,t,s){if(!e)return console.error("\u274C \u8BF7\u6307\u5B9A\u6587\u6863\u6216\u76EE\u5F55 ID"),1;let r=t.includes("--collection")?{collectionId:e}:{documentId:e},n=await this.post("stars.create",r,s);return this.parseJson(n.body)?.data?(console.log("\u2705 \u5DF2\u6536\u85CF"),0):(console.error("\u274C \u6536\u85CF\u5931\u8D25:",n.body),1)}async unstar(e,t){if(!e)return console.error("\u274C \u8BF7\u6307\u5B9A\u6536\u85CF ID"),1;let s=await this.post("stars.delete",{id:e},t);return s.status>=400?(console.error("\u274C \u53D6\u6D88\u6536\u85CF\u5931\u8D25:",s.body),1):(console.log("\u2705 \u5DF2\u53D6\u6D88\u6536\u85CF"),0)}async pins(e,t){let s=e?{collectionId:e}:{},o=await this.post("pins.list",s,t),r=this.parseJson(o.body);if(!r?.data)return console.error("\u274C \u8BF7\u6C42\u5931\u8D25:",o.body),1;let n=r.data.pins||r.data||[];return n.length?(this.printTable(n.map(i=>({pinId:i.id,\u6807\u9898:i.document?.title||i.documentId,URL:D(i.document?.urlId||i.documentId)}))),0):(console.log("\u6682\u65E0\u7F6E\u9876"),0)}async pin(e,t,s){if(!e)return console.error("\u274C \u8BF7\u6307\u5B9A\u6587\u6863 ID"),1;let o={documentId:e,...t[0]?{collectionId:t[0]}:{}},r=await this.post("pins.create",o,s),n=this.parseJson(r.body);return n?.data?(console.log(`\u2705 \u5DF2\u7F6E\u9876: ${n.data.id}`),0):(console.error("\u274C \u7F6E\u9876\u5931\u8D25:",r.body),1)}async unpin(e,t){if(!e)return console.error("\u274C \u8BF7\u6307\u5B9A\u7F6E\u9876 ID"),1;let s=await this.post("pins.delete",{id:e},t);return s.status>=400?(console.error("\u274C \u53D6\u6D88\u7F6E\u9876\u5931\u8D25:",s.body),1):(console.log("\u2705 \u5DF2\u53D6\u6D88\u7F6E\u9876"),0)}async comments(e,t){if(!e)return console.error("\u274C \u8BF7\u6307\u5B9A\u6587\u6863 ID"),1;let s=await this.post("comments.list",{documentId:e,sort:"createdAt",direction:"ASC"},t),o=this.parseJson(s.body);if(!o?.data)return console.error("\u274C \u8BF7\u6C42\u5931\u8D25:",s.body),1;let r=o.data.comments||o.data||[];if(!r.length)return console.log("\u6682\u65E0\u8BC4\u8BBA"),0;for(let n of r){let i=this.extractCommentText(n.data);console.log(` [${n.id}] ${n.createdBy?.name||"?"}: ${i}`)}return 0}async comment(e,t,s){let o=t.join(" ");if(!e||!o)return console.error("\u274C \u7528\u6CD5: wiki comment <docId> <text>"),1;let r={type:"doc",content:[{type:"paragraph",content:[{type:"text",text:o}]}]},n=await this.post("comments.create",{documentId:e,data:r},s),i=this.parseJson(n.body);return i?.data?(console.log(`\u2705 \u8BC4\u8BBA\u5DF2\u53D1\u5E03: ${i.data.id}`),0):(console.error("\u274C \u8BC4\u8BBA\u5931\u8D25:",n.body),1)}extractCommentText(e){return e?.content?e.content.flatMap(t=>t.content||[]).filter(t=>t.type==="text").map(t=>t.text).join(""):""}showHelp(){console.log(`
|
|
253
253
|
coder wiki \u2014 \u7BA1\u7406 MakeCoder \u77E5\u8BC6\u5E93
|
|
254
254
|
|
|
@@ -259,7 +259,14 @@ SUBCOMMANDS:
|
|
|
259
259
|
list \u5217\u51FA\u6240\u6709\u76EE\u5F55
|
|
260
260
|
list <collectionId> \u5217\u51FA\u76EE\u5F55\u4E0B\u7684\u6839\u6587\u6863\uFF08\u8868\u683C\uFF09
|
|
261
261
|
list <collectionId> -d <depth> \u5C55\u5F00\u6587\u6863\u6811\uFF0C-d -1 \u5168\u90E8\u5C55\u5F00
|
|
262
|
-
create-collection <name> [desc]
|
|
262
|
+
create-collection <name> [desc] [--permission <perm>]
|
|
263
|
+
\u521B\u5EFA\u76EE\u5F55
|
|
264
|
+
perm: read_write (\u53EF\u8BFB\u5199\uFF0C\u9ED8\u8BA4)
|
|
265
|
+
read (\u53EA\u8BFB)
|
|
266
|
+
null (\u4EC5\u6307\u5B9A\u6210\u5458\u53EF\u8BBF\u95EE)
|
|
267
|
+
update-collection <collectionId> [--name <n>] [--description <d>] [--permission <p>] [--color <c>] [--sharing <bool>]
|
|
268
|
+
\u66F4\u65B0\u76EE\u5F55
|
|
269
|
+
delete-collection <collectionId> \u5220\u9664\u76EE\u5F55
|
|
263
270
|
get <docId> \u67E5\u770B\u6587\u6863
|
|
264
271
|
publish <collectionId> <title> [text] \u521B\u5EFA\u5E76\u53D1\u5E03\u6587\u6863
|
|
265
272
|
publish <collectionId> --file <path> [--parent <parentDocId>]
|
|
@@ -291,7 +298,7 @@ EXAMPLES:
|
|
|
291
298
|
coder wiki publish <collectionId> --file ./doc.md
|
|
292
299
|
coder wiki search "\u5173\u952E\u8BCD"
|
|
293
300
|
coder wiki comment <docId> "\u5F88\u6709\u5E2E\u52A9\uFF01"
|
|
294
|
-
`)}};st.exports=le});var rt=m((Ds,nt)=>{var Kt=Ce(),zt=
|
|
301
|
+
`)}};st.exports=le});var rt=m((Ds,nt)=>{var Kt=Ce(),zt=je(),Wt=Re(),Jt=Ge(),Qt=We(),Yt=Ye(),Zt=et(),Xt=ot(),{isPrintMode:es}=R(),ue=class{constructor(){this.argParser=new Kt,this.claudeLauncher=new zt,this.geminiLauncher=new Wt,this.codexLauncher=new Jt,this.vscodeExtensionService=new Qt,this.publishService=new Yt,this.skillsService=new Zt,this.wikiService=new Xt}async run(e=process.argv.slice(2)){try{try{await this.vscodeExtensionService.ensureExtensionInstalled()}catch(s){process.env.CODEV_DEBUG&&console.error("VSCode Extension Service Error:",s)}if(!e.includes("--agent")&&!e.includes("-a")){let s=e.length>0&&["claude","gemini","codex"].includes(e[0]),o=e.length>0&&["pub","update","skills","wiki"].includes(e[0]);if(!s&&!o&&(e.includes("--help")||e.includes("-h")))return this.argParser.showHelp(),0;if(!s&&!o&&(e.includes("--version")||e.includes("-v")))return this.showVersion(),0}let t=await this.argParser.parse(e);return t.command==="login"?await this.handleLogin(t):t.command==="update"?this.handleUpdate():t.command==="skills"?await this.skillsService.handle(t):t.command==="wiki"?await this.wikiService.handle(t):t.command==="pub"?await this.publishService.publish({name:t.pubName,ak:t.auth_ak,sk:t.auth_sk,serverBaseUrl:t.codevServer,allowClone:t.allowClone}):await this.launchAgent(t)}catch(t){return console.error(`Error: ${t.message}`),process.env.CODEV_DEBUG&&console.error("Stack trace:",t.stack),1}}async launchAgent(e){let{agent:t,remainingArgs:s}=e;return es(s)||console.log(`cwd:\x1B[90m\x1B[3m ${process.cwd()} \x1B[0m`),t==="claude"?await this.claudeLauncher.launch(e):t==="gemini"?await this.geminiLauncher.launch(e):t==="codex"?await this.codexLauncher.launch(e):1}async handleLogin(e){let t=e.auth_ak,s=e.auth_sk;if(!t||!s){console.log(`
|
|
295
302
|
\u{1F511} \u8BF7\u5148\u5728 MakeCoder \u521B\u5EFA API Key\uFF1A`),console.log(` \u{1F449} https://makecoder.com/my/apikeys
|
|
296
303
|
`);try{let r=await this.argParser.promptForAKSK();t=r.ak,s=r.sk}catch(r){return console.error(`\u274C ${r.message}`),1}}if(this.argParser.saveAuthToConfig(t,s))console.log("\u2705 API Key \u5DF2\u4FDD\u5B58\u5230 ~/.coder/config.json"),console.log(" \u73B0\u5728\u53EF\u4EE5\u76F4\u63A5\u8FD0\u884C coder \u5F00\u59CB\u4F7F\u7528\u4E86 \u{1F680}");else return console.error("\u274C \u4FDD\u5B58\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5 ~/.coder/ \u76EE\u5F55\u7684\u6587\u4EF6\u6743\u9650"),1;return 0}handleUpdate(){let{execSync:e}=require("child_process"),t=q();console.log(`\u5F53\u524D\u7248\u672C: ${t.version}`),console.log(`\u6B63\u5728\u5347\u7EA7 Coder...
|
|
297
304
|
`);try{return e("npm install -g makecoder@latest",{stdio:"inherit"}),console.log(`
|