@vibeapi/api-helper 0.0.198 → 0.0.199

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.
@@ -105,6 +105,10 @@ export interface SetupCommandOptions extends Partial<Record<DedicatedKeyOption,
105
105
  * write, and it promises not to stop halfway, so the interactive file list is not asked again.
106
106
  */
107
107
  fromInstaller?: boolean;
108
+ /** `--ccswitch`: put this gateway into CC Switch as a card per tool and leave the tools' own config alone. */
109
+ ccswitch?: boolean;
110
+ /** `--ccswitch-use`: the same, then make the card current and write the tool's config the way setup does. */
111
+ ccswitchUse?: boolean;
108
112
  }
109
113
  /** `--claude-official on|off` (also true/false, show/hide, 1/0, yes/no); undefined when unrecognized. */
110
114
  export declare function parseOnOff(raw: string | undefined): boolean | undefined;
@@ -1 +1 @@
1
- import e from"chalk";import{getAdapter as o}from"../lib/tools/registry.js";import{postApplyPrompts as t}from"../lib/post-apply.js";import{ensureReachableGatewayAddress as l,moveOtherToolsAfterFallback as i,saveGatewayFallback as s,toolsWeConfigured as a}from"./base.js";import{i18n as n}from"../lib/i18n.js";import{configManager as r}from"../lib/config.js";import{toolManager as p,SUPPORTED_TOOLS as d}from"../lib/tool-manager.js";import{validateApiKey as c,fetchModels as u}from"../lib/api-validator.js";import{CODEX_ONE_MILLION_CONTEXT_SETTING as f,setCodexOneMillionContext as m}from"../lib/tools/codex.js";import{resolveModelCatalog as g}from"../lib/model-catalog.js";import{CLAUDE_DESKTOP_FORCE_REGISTRY_SETTING as y,CLAUDE_DESKTOP_HIDE_OFFICIAL_LOGIN_SETTING as k}from"../lib/tools/claude-desktop.js";import{operationError as h,authenticationError as _,networkError as b,EXIT_CODES as w}from"../lib/errors.js";import{canPrompt as v,emitJson as x,hasExplicitYes as C,isColorEnabled as j,isDryRun as T,isJsonMode as K,isNonInteractive as $,shouldAutoConfirm as I}from"../lib/runtime-options.js";import{appsForTools as M,appUpgradeCommand as G,getApp as N}from"../lib/app-update.js";import{join as S}from"path";import{confirmAction as A}from"../lib/confirm.js";import{asksBeforeWriting as O,confirmWritePlan as E,printWritePlan as B,toolWritePlan as D}from"../lib/write-plan.js";import F from"inquirer";import{logger as L}from"../utils/logger.js";import{forgetInstalls as R}from"../lib/tools/tool-installs.js";import{CLI_NAME as q,brandEnv as P}from"../lib/brand.js";import{unsupportedUpgradeTargets as Y,upgradeCommand as V}from"./upgrade.js";export const DEDICATED_KEYS=[{option:"claudekey",tool:"claude-code",need:"claude"},{option:"codexkey",tool:"codex",need:"gpt"},{option:"grokkey",tool:"grok",need:"grok"},{option:"desktopkey",tool:"claude-desktop",need:"claude"},{option:"agykey",tool:"agy",need:"gemini"},{option:"openclawkey",tool:"openclaw",need:"any",hidden:!0},{option:"hermeskey",tool:"hermes",need:"any",hidden:!0},{option:"atomcodekey",tool:"atomcode",need:"any",hidden:!0},{option:"codebuddykey",tool:"codebuddy",need:"any"},{option:"workbuddykey",tool:"workbuddy",need:"any"},{option:"dshkey",tool:"dsh",need:"any"}];async function z(e){const o=await u(e);if(!o.ok)return{hasClaude:!0,hasGpt:!0,hasGrok:!0,hasGemini:!0,probed:!1};const t=o.models.map(e=>e.toLowerCase());return{hasClaude:t.some(e=>e.includes("claude")),hasGpt:t.some(e=>e.startsWith("gpt")||e.includes("gpt-")||/^o\d/.test(e)),hasGrok:t.some(e=>e.includes("grok")),hasGemini:t.some(e=>e.startsWith("gemini")),probed:!0}}function H(e,o){switch(o){case"claude":return e.hasClaude;case"gpt":return e.hasGpt;case"grok":return e.hasGrok;case"gemini":return e.hasGemini;default:return!0}}export function parseOnOff(e){const o=(e??"").trim().toLowerCase();return!!["on","true","show","1","yes","y"].includes(o)||!["off","false","hide","0","no","n"].includes(o)&&void 0}function U(o){console.log(e.green(o))}function W(o){console.log(e.yellow(o))}function J(o){console.error(e.red(o))}let Q=null;function X(e){const o={operation:1,authentication:2,network:3};(!Q||o[e]>o[Q])&&(Q=e)}async function Z(o,t){K()||console.log(e.gray(n.t("setup.validating",{label:o})));const l=await c(t);if(l.valid)return!0;const i=n.t("errors.key_placeholder"),s="--key"===o?`${q} setup --key ${i}`:`${q} setup ${o} ${i}`;let a;if("network_error"===l.error?(X("network"),a=b(n.t("setup.unreachable",{url:r.getBaseUrl(),reason:l.message||"network error"}),`${q} base auto`,"network_error")):"invalid_api_key"===l.error?(X("authentication"),a=_(n.t("setup.invalid_key",{label:o,reason:l.message||"invalid"}),s,"invalid_api_key")):(X("operation"),a=h(n.t("setup.validate_failed",{label:o,reason:l.message||l.error||"unknown"}),s,l.error)),K())throw a;return J(a.message),console.log(e.gray(n.t("errors.next_step",{command:a.hint}))),!1}async function ee(t,l,i={}){const{oneMillion:s,officialLogin:a,desktopRegistry:c,force:u,takeOver:m}=i,g=d[t];try{"claude-desktop"===t&&void 0!==c&&r.setToolSetting("claude-desktop",y,c),"codex"===t&&void 0!==s&&r.setToolSetting("codex",f,s),"claude-desktop"===t&&void 0!==a&&r.setToolSetting("claude-desktop",k,!a),await p.applyPrivateConfig(t,l,r.getModelsForTool(t),{force:u,takeOver:m})}catch(e){if(K())throw h(e instanceof Error?e.message:String(e),`${q} setup --key ${n.t("errors.key_placeholder")}`,"config_write_failed");const o=(e instanceof Error?e.message:String(e)).replace(/\s+/g," ").trim();return J("× "+n.t("setup.apply_failed",{tool:g.displayName,reason:o})),!1}return p.printApplied(t),u&&console.log(e.gray(" "+n.t("config.force_done",{tool:g.displayName,name:t}))),"codex"===t&&void 0!==s&&console.log(e.gray(" "+n.t(s?"setup.codex_1m_enabled":"setup.codex_1m_disabled"))),o(t)?.isInstalled&&!p.isToolInstalled(t)&&console.log(e.yellow(" ! "+n.t("setup.gui_preconfigured",{tool:g.displayName,install:g.installCommand}))),!0}function oe(e){return!o(e)?.isInstalled&&!p.isToolInstalled(e)}async function te(e){if(C())return!0;const o=d[e]?.displayName??e;return v()?A({message:n.t("setup.ask_detected_tool",{tool:o}),defaultValue:!0}):(W(n.t("setup.detected_tool_hint",{tool:o,name:e})),!1)}export async function installMissingApps(o,t,l){const i=M(o).filter(e=>{if(l&&!l.includes(e))return!1;const o=N(e)?.appInstaller;try{return Boolean(o&&!o.blocker()&&!o.installedPath())}catch(o){return L.logError(`setup: app installed? ${e}`,o),!1}});if(0===i.length)return!1;const s=e=>N(e)?.displayName??e;let a=t;if(void 0===a&&!K())if(I())a=!$();else if(v()){const e=i.map(s).join(n.t("setup.list_separator")),o=i.reduce((e,o)=>e+(N(o)?.appInstaller.sizeMb()??0),0);console.log(""),a=(await F.prompt([{type:"confirm",name:"go",message:n.t("setup.install_app_confirm",{tools:e,size:String(o)}),default:!0}])).go}if(!a&&!K())for(const o of i)console.log(e.gray(n.t("setup.install_app_hint",{tool:s(o),command:G(o)})));return Boolean(a)}function le(e){W(n.t("setup.still_missing",{tools:e.map(e=>d[e].displayName).join(n.t("setup.list_separator")),commands:e.map(e=>`${q} config ${e} --yes`).join(n.t("setup.list_separator"))}))}function ie(o,t,l=[]){const i=D(o),s=S(r.getConfigDir(),"config.yaml");if(K())x({dry_run:!0,tools:i,install_first:l,key_file:t?s:null});else{if(0===i.length&&0===l.length){const o=(j()?e.cyan:e=>e)(n.t("runtime.dry_run_label"));return void console.log(`${o} ${n.t("setup.dry_run_none")}`)}B(i,{label:n.t("runtime.dry_run_label"),keyFile:t?s:void 0,installFirst:l})}}function se(e){return Boolean(o(e)?.installSpec||N(e)?.appInstaller)}function ae(e){return M(e).filter(e=>{const o=N(e);if(!o||o.tool===e)return!1;try{return!o.appInstaller.blocker()}catch(o){return L.logError(`setup: app blocker ${e}`,o),!1}})}function ne(e){const o=N(e);let t,l;if(o&&o.tool!==e){try{t=Boolean(o.appInstaller.installedPath())}catch(o){L.logError(`setup: app installed? ${e}`,o),t=!1}l=t?o.installedVersion?.():null}else t=p.isToolInstalled(e),l=t?p.installedVersion(e):null;return t?l?n.t("setup.pick_installed",{version:l}):n.t("setup.pick_installed_plain"):n.t("setup.pick_not_installed")}function re(o,t){return{name:`${N(o)?.displayName??d[o]?.displayName??o} ${e.gray(ne(o))}`,value:o,checked:t}}export function parseUpgradeList(e){const o=(Array.isArray(e)?e:void 0===e?[]:[e]).flatMap(e=>e.split(/[\s,]+/));return[...new Set(o.map(e=>e.trim()).filter(Boolean))]}function pe(){return"darwin"===process.platform||"win32"===process.platform||p.isToolInstalled("claude-desktop")}export async function setupCommand(c){Q=null;const u=DEDICATED_KEYS.map(e=>({...e,apiKey:c[e.option]?.trim()})).filter(e=>Boolean(e.apiKey)),y=void 0!==c.oneMillion||void 0!==c.claudeOfficial||void 0!==c.desktopRegistry;let k=c.key?.trim();const h=c.upgrade??[],_=Y(h);if(_.length>0)return J(n.t("upgrade.unsupported",{tool:_.join(", ")})),void(process.exitCode=w.usage);if(h.length>0&&(T()?console.log(n.t("setup.dry_run_upgrade",{tools:h.join(", ")})):(await V(h),R()),!k&&0===u.length&&!y))return;k||0!==u.length||y||!O()||(k=(await F.prompt([{type:"password",name:"key",mask:"*",message:n.t("setup.ask_key")}])).key?.trim()||void 0);const b=void 0!==c.oneMillion,v=void 0!==c.claudeOfficial;let x;if(v&&(x=parseOnOff(c.claudeOfficial),void 0===x))return J(n.t("setup.claude_official_invalid",{value:String(c.claudeOfficial)})),void(process.exitCode=1);const C=void 0!==c.desktopRegistry;let j;if(C&&(j=parseOnOff(c.desktopRegistry),void 0===j))return J(n.t("setup.desktop_registry_invalid",{value:String(c.desktopRegistry)})),void(process.exitCode=1);const M=v||C,G=Boolean(k||u.length>0),A={oneMillion:c.oneMillion,officialLogin:x,desktopRegistry:j,force:c.force};if(!G&&(b||M)&&T())return void ie([...b?["codex"]:[],...M?["claude-desktop"]:[]],!1);if(!G&&(b||M)){if(b){const e=r.getApiKeyForTool("codex");if(e)try{const o=!0===c.oneMillion;r.setToolSetting("codex",f,o);const t=await g(e);m(o,t??void 0),U(n.t(o?"setup.codex_1m_enabled":"setup.codex_1m_disabled"))}catch(e){J(n.t("setup.apply_failed",{tool:d.codex.displayName,reason:e instanceof Error?e.message:String(e)})),process.exitCode=1}else J(n.t("setup.codex_1m_missing_key")),process.exitCode=1}if(M){const e=r.getApiKeyForTool("claude-desktop");e?await ee("claude-desktop",e,{...A,oneMillion:void 0,takeOver:!0})?await t(["claude-desktop"],{apps:{install:!1}}):process.exitCode=1:(J(n.t("setup.desktop_official_login_missing_key")),process.exitCode=1)}return}if(!G)return J(n.t("setup.usage")),void(process.exitCode=1);const B=T(),D=B?null:await l(k||u[0].apiKey,{save:!1}),X=[],ne=[];let de,ce=0,ue=0;const fe=new Set,me=u.map(e=>({tool:e.tool,label:`--${e.option}`,apiKey:e.apiKey,need:e.need}));for(const e of me){if(!await Z(e.label,e.apiKey)){ue+=1;continue}const o=await z(e.apiKey);!o.probed||H(o,e.need)?(o.probed||W(n.t("setup.probe_failed",{label:e.label})),X.push({tool:e.tool,apiKey:e.apiKey,dedicated:!0}),fe.add(e.tool)):(J(n.t(`setup.key_no_${e.need}`,{label:e.label,tool:d[e.tool].displayName})),ue+=1)}const ge=!!k&&await Z("--key",k);k&&!ge&&(de=w[Q??"operation"]);const ye=k&&ge?await z(k):void 0;k&&ye&&!ye.probed&&W(n.t("setup.probe_failed",{label:"--key"})),!(k&&ye&&ye.probed)||ye.hasClaude||ye.hasGpt||ye.hasGrok||ye.hasGemini||(J(n.t("setup.key_no_family")),de=1);const ke=Boolean(k)&&0===u.length&&!c.fromInstaller&&O();if(k&&ye&&void 0===de){const e=ye.hasClaude||ye.hasGpt||ye.hasGrok||ye.hasGemini,o=[{tool:"claude-code",capable:ye.hasClaude,skipMsg:n.t(pe()?"setup.skip_no_claude_desktop":"setup.skip_no_claude")},{tool:"codex",capable:ye.hasGpt,skipMsg:n.t("setup.skip_no_gpt")},{tool:"grok",capable:ye.hasGrok,skipMsg:n.t("setup.skip_no_grok")},{tool:"claude-desktop",capable:ye.hasClaude&&pe(),skipMsg:"",quiet:!0},{tool:"agy",capable:ye.hasGemini,skipMsg:n.t("setup.skip_no_gemini")},{tool:"codebuddy",capable:e&&p.isToolInstalled("codebuddy"),skipMsg:"",quiet:!0},{tool:"workbuddy",capable:e&&p.isToolInstalled("workbuddy"),skipMsg:"",quiet:!0},{tool:"dsh",capable:e&&p.isToolInstalled("dsh"),skipMsg:"",quiet:!0,ask:!0}];for(const e of o)fe.has(e.tool)||(e.capable?(!e.ask||B||ke||await te(e.tool))&&(X.push({tool:e.tool,apiKey:k,dedicated:!1}),fe.add(e.tool)):e.quiet||W(e.skipMsg))}let he,_e=c.install,be=[];if(ke&&void 0===de&&X.length>0){const e=await async function(e,o){console.log("");const{configure:t}=await F.prompt([{type:"checkbox",name:"configure",message:n.t("setup.pick_configure"),choices:e.map(e=>re(e,!0))}]);let l=[];const i=[...e.filter(se),...ae(e)];if(o&&i.length>0){const e=e=>N(e)?.tool??e;l=(await F.prompt([{type:"checkbox",name:"upgrade",message:n.t("setup.pick_upgrade"),choices:i.map(o=>re(o,t.includes(e(o))))}])).upgrade}return 0===t.length&&0===l.length?(console.log(n.t("setup.pick_none")),null):{configure:t,upgrade:l}}(X.map(e=>e.tool),void 0===c.upgrade);if(!e)return void(process.exitCode=w.cancelled);if(0===e.configure.length)return void await V(e.upgrade);be=e.upgrade,he=[],!0!==_e&&(_e=!1);const o=e.configure.filter(e=>oe(e)&&!be.includes(e)&&!_e);if(o.length>0&&W(n.t("setup.pick_configure_skip",{tools:o.map(e=>d[e].displayName).join(n.t("setup.list_separator"))})),X.splice(0,X.length,...X.filter(t=>e.configure.includes(t.tool)&&!o.includes(t.tool))),0===X.length)return void(be.length>0&&await V(be))}const we=Boolean(k&&ge&&void 0===de);if(B)return ie(X.filter(e=>!oe(e.tool)).map(e=>e.tool),X.length>0,X.filter(e=>oe(e.tool)).map(e=>e.tool)),void((ue>0||void 0!==de)&&(process.exitCode=de??w[Q??"operation"]));const ve=X.filter(e=>!oe(e.tool)),xe=we||X.some(e=>e.dedicated),Ce=D?a().filter(e=>!X.some(o=>o.tool===e.tool)):[],je=!c.fromInstaller&&O();if((X.length>0||xe)&&!c.fromInstaller&&!await E([...ve.map(e=>e.tool),...Ce.map(e=>e.tool)],{keyFile:xe?S(r.getConfigDir(),"config.yaml"):void 0,installFirst:X.filter(e=>oe(e.tool)).map(e=>e.tool)}))return void(process.exitCode=w.cancelled);be.length>0&&(await V(be),R()),(X.length>0||xe)&&s(),we&&k&&r.setApiKey(k);for(const e of X)oe(e.tool)?(e.dedicated&&r.setToolApiKey(e.tool,e.apiKey),ne.push({tool:e.tool,apiKey:e.apiKey,dedicated:e.dedicated})):await ee(e.tool,e.apiKey,{...A,takeOver:e.dedicated||je})?(e.dedicated?r.setToolApiKey(e.tool,e.apiKey):r.clearToolApiKey(e.tool),ce+=1):(ue+=1,fe.delete(e.tool));const Te=X.length>0||xe?await i(Ce):[];if(void 0!==de)return ne.length>0&&le(ne.map(e=>e.tool)),void(process.exitCode=de);let Ke=[];if(ne.length>0){const o=await async function(o,t,l){const i=o.map(e=>e.tool);if(0===i.length)return{still:[],applied:[],failed:[]};const s=i.map(e=>d[e].displayName).join(n.t("setup.list_separator"));let a=t;if(void 0!==a||K()||(I()?a=!$():process.stdin.isTTY&&(console.log(""),a=(await F.prompt([{type:"confirm",name:"go",message:n.t("setup.install_confirm",{tools:s}),default:!0}])).go)),!a){console.log("");for(const o of i)console.log(e.yellow("! "+n.t("setup.install_hint",{tool:d[o].displayName,install:d[o].installCommand})));return K()||console.log(e.gray(n.t("setup.install_all_hint",{cli:q}))),{still:i,applied:[],failed:[]}}const c=[];for(const o of i){console.log(e.bold(`\n${d[o].displayName}`));try{await p.installTool(o)}catch(e){L.logError(`setup: install ${o}`,e)}R(),p.isToolInstalled(o)||c.push(o)}const u=i.filter(e=>!c.includes(e));u.length>0&&console.log("");const f=[],m=[];for(const{tool:e,apiKey:t,dedicated:i}of o.filter(e=>u.includes(e.tool)))await ee(e,t,l)?(f.push(e),i||r.clearToolApiKey(e)):m.push(e);return{still:c,applied:f,failed:m}}(ne,_e,A);Ke=o.still,ce+=o.applied.length,ue+=o.failed.length;for(const e of[...Ke,...o.failed])fe.delete(e)}if(ce>0){const t=[...fe].filter(e=>!o(e)?.isInstalled&&!Ke.includes(e)),l=t.map(e=>d[e]?.command).filter(Boolean).join(" / "),i=n.t("setup.done",{count:String(ce)});U("\n"+(l?`${i}${n.t("setup.done_commands",{commands:l})}`:i)),Ke.length>0&&le(Ke);for(const e of t){const o=p.ensureNativeOnPath(e);o&&U(n.t("setup.path_added",{tool:d[e].displayName,dir:o}))}const s=t.filter(e=>!p.isOnPath(e));if(s.length>0&&!K()&&"1"!==P("PATH_HINT_BY_CALLER")){const o=s.map(e=>d[e].command).join(" / ");console.log(e.yellow(" ! "+n.t("win32"===process.platform?"setup.path_reload_windows":"setup.path_reload",{commands:o})))}}0===ce&&Ke.length>0&&le(Ke),ue>0&&(J(n.t("setup.failed_summary",{count:String(ue)})),K()||console.error(`${q} setup --key ${n.t("errors.key_placeholder")}`)),await t([...fe,...Te],{apps:{install:await installMissingApps([...fe],_e,he)}}),(ue>0||0===ce&&0===Ke.length)&&(process.exitCode=w[Q??"operation"])}
1
+ import e from"chalk";import{getAdapter as o}from"../lib/tools/registry.js";import{postApplyPrompts as t}from"../lib/post-apply.js";import{ensureReachableGatewayAddress as l,moveOtherToolsAfterFallback as i,saveGatewayFallback as s,toolsWeConfigured as a}from"./base.js";import{i18n as n}from"../lib/i18n.js";import{configManager as r}from"../lib/config.js";import{toolManager as c,SUPPORTED_TOOLS as p}from"../lib/tool-manager.js";import{validateApiKey as d,fetchModels as u}from"../lib/api-validator.js";import{CODEX_ONE_MILLION_CONTEXT_SETTING as f,setCodexOneMillionContext as m}from"../lib/tools/codex.js";import{resolveModelCatalog as g}from"../lib/model-catalog.js";import{CLAUDE_DESKTOP_FORCE_REGISTRY_SETTING as h,CLAUDE_DESKTOP_HIDE_OFFICIAL_LOGIN_SETTING as y}from"../lib/tools/claude-desktop.js";import{operationError as k,authenticationError as _,networkError as w,EXIT_CODES as b}from"../lib/errors.js";import{canPrompt as v,emitJson as x,hasExplicitYes as C,isColorEnabled as j,isDryRun as K,isJsonMode as T,isNonInteractive as $,shouldAutoConfirm as M}from"../lib/runtime-options.js";import{appsForTools as I,appUpgradeCommand as S,getApp as N}from"../lib/app-update.js";import{join as A}from"path";import{confirmAction as G}from"../lib/confirm.js";import{asksBeforeWriting as E,confirmWritePlan as O,printWritePlan as B,toolWritePlan as D}from"../lib/write-plan.js";import F from"inquirer";import{logger as P}from"../utils/logger.js";import{forgetInstalls as q}from"../lib/tools/tool-installs.js";import{CLI_NAME as L,brandEnv as R}from"../lib/brand.js";import{unsupportedUpgradeTargets as V,upgradeCommand as Y}from"./upgrade.js";import{track as U}from"../lib/telemetry.js";import{CCSWITCH_SETTING as z,buildCcSwitchCard as H,inspectCcSwitch as W,quitCcSwitch as J,writeCcSwitchCards as Q}from"../lib/ccswitch.js";export const DEDICATED_KEYS=[{option:"claudekey",tool:"claude-code",need:"claude"},{option:"codexkey",tool:"codex",need:"gpt"},{option:"grokkey",tool:"grok",need:"grok"},{option:"desktopkey",tool:"claude-desktop",need:"claude"},{option:"agykey",tool:"agy",need:"gemini"},{option:"openclawkey",tool:"openclaw",need:"any",hidden:!0},{option:"hermeskey",tool:"hermes",need:"any",hidden:!0},{option:"atomcodekey",tool:"atomcode",need:"any",hidden:!0},{option:"codebuddykey",tool:"codebuddy",need:"any"},{option:"workbuddykey",tool:"workbuddy",need:"any"},{option:"dshkey",tool:"dsh",need:"any"}];async function X(e){const o=await u(e);if(!o.ok)return{hasClaude:!0,hasGpt:!0,hasGrok:!0,hasGemini:!0,probed:!1};const t=o.models.map(e=>e.toLowerCase());return{hasClaude:t.some(e=>e.includes("claude")),hasGpt:t.some(e=>e.startsWith("gpt")||e.includes("gpt-")||/^o\d/.test(e)),hasGrok:t.some(e=>e.includes("grok")),hasGemini:t.some(e=>e.startsWith("gemini")),probed:!0}}function Z(e,o){switch(o){case"claude":return e.hasClaude;case"gpt":return e.hasGpt;case"grok":return e.hasGrok;case"gemini":return e.hasGemini;default:return!0}}export function parseOnOff(e){const o=(e??"").trim().toLowerCase();return!!["on","true","show","1","yes","y"].includes(o)||!["off","false","hide","0","no","n"].includes(o)&&void 0}function ee(o){console.log(e.green(o))}function oe(o){console.log(e.yellow(o))}function te(o){console.error(e.red(o))}let le=null;function ie(e){const o={operation:1,authentication:2,network:3};(!le||o[e]>o[le])&&(le=e)}async function se(o,t){T()||console.log(e.gray(n.t("setup.validating",{label:o})));const l=await d(t);if(l.valid)return!0;const i=n.t("errors.key_placeholder"),s="--key"===o?`${L} setup --key ${i}`:`${L} setup ${o} ${i}`;let a;if("network_error"===l.error?(ie("network"),a=w(n.t("setup.unreachable",{url:r.getBaseUrl(),reason:l.message||"network error"}),`${L} base auto`,"network_error")):"invalid_api_key"===l.error?(ie("authentication"),a=_(n.t("setup.invalid_key",{label:o,reason:l.message||"invalid"}),s,"invalid_api_key")):(ie("operation"),a=k(n.t("setup.validate_failed",{label:o,reason:l.message||l.error||"unknown"}),s,l.error)),T())throw a;return te(a.message),console.log(e.gray(n.t("errors.next_step",{command:a.hint}))),!1}async function ae(t,l,i={}){const{oneMillion:s,officialLogin:a,desktopRegistry:d,force:u,takeOver:m}=i,g=p[t];try{"claude-desktop"===t&&void 0!==d&&r.setToolSetting("claude-desktop",h,d),"codex"===t&&void 0!==s&&r.setToolSetting("codex",f,s),"claude-desktop"===t&&void 0!==a&&r.setToolSetting("claude-desktop",y,!a),await c.applyPrivateConfig(t,l,r.getModelsForTool(t),{force:u,takeOver:m})}catch(e){if(T())throw k(e instanceof Error?e.message:String(e),`${L} setup --key ${n.t("errors.key_placeholder")}`,"config_write_failed");const o=(e instanceof Error?e.message:String(e)).replace(/\s+/g," ").trim();return te("× "+n.t("setup.apply_failed",{tool:g.displayName,reason:o})),!1}return c.printApplied(t),u&&console.log(e.gray(" "+n.t("config.force_done",{tool:g.displayName,name:t}))),"codex"===t&&void 0!==s&&console.log(e.gray(" "+n.t(s?"setup.codex_1m_enabled":"setup.codex_1m_disabled"))),o(t)?.isInstalled&&!c.isToolInstalled(t)&&console.log(e.yellow(" ! "+n.t("setup.gui_preconfigured",{tool:g.displayName,install:g.installCommand}))),!0}function ne(e){return!o(e)?.isInstalled&&!c.isToolInstalled(e)}async function re(e){if(C())return!0;const o=p[e]?.displayName??e;return v()?G({message:n.t("setup.ask_detected_tool",{tool:o}),defaultValue:!0}):(oe(n.t("setup.detected_tool_hint",{tool:o,name:e})),!1)}export async function installMissingApps(o,t,l){const i=I(o).filter(e=>{if(l&&!l.includes(e))return!1;const o=N(e)?.appInstaller;try{return Boolean(o&&!o.blocker()&&!o.installedPath())}catch(o){return P.logError(`setup: app installed? ${e}`,o),!1}});if(0===i.length)return!1;const s=e=>N(e)?.displayName??e;let a=t;if(void 0===a&&!T())if(M())a=!$();else if(v()){const e=i.map(s).join(n.t("setup.list_separator")),o=i.reduce((e,o)=>e+(N(o)?.appInstaller.sizeMb()??0),0);console.log(""),a=(await F.prompt([{type:"confirm",name:"go",message:n.t("setup.install_app_confirm",{tools:e,size:String(o)}),default:!0}])).go}if(!a&&!T())for(const o of i)console.log(e.gray(n.t("setup.install_app_hint",{tool:s(o),command:S(o)})));return Boolean(a)}function ce(e){oe(n.t("setup.still_missing",{tools:e.map(e=>p[e].displayName).join(n.t("setup.list_separator")),commands:e.map(e=>`${L} config ${e} --yes`).join(n.t("setup.list_separator"))}))}function pe(o,t,l=[]){const i=D(o),s=A(r.getConfigDir(),"config.yaml");if(T())x({dry_run:!0,tools:i,install_first:l,key_file:t?s:null});else{if(0===i.length&&0===l.length){const o=(j()?e.cyan:e=>e)(n.t("runtime.dry_run_label"));return void console.log(`${o} ${n.t("setup.dry_run_none")}`)}B(i,{label:n.t("runtime.dry_run_label"),keyFile:t?s:void 0,installFirst:l})}}function de(e){return Boolean(o(e)?.installSpec||N(e)?.appInstaller)}function ue(e){return I(e).filter(e=>{const o=N(e);if(!o||o.tool===e)return!1;try{return!o.appInstaller.blocker()}catch(o){return P.logError(`setup: app blocker ${e}`,o),!1}})}function fe(e){const o=N(e);let t,l;if(o&&o.tool!==e){try{t=Boolean(o.appInstaller.installedPath())}catch(o){P.logError(`setup: app installed? ${e}`,o),t=!1}l=t?o.installedVersion?.():null}else t=c.isToolInstalled(e),l=t?c.installedVersion(e):null;return t?l?n.t("setup.pick_installed",{version:l}):n.t("setup.pick_installed_plain"):n.t("setup.pick_not_installed")}function me(o,t){return{name:`${N(o)?.displayName??p[o]?.displayName??o} ${e.gray(fe(o))}`,value:o,checked:t}}export function parseUpgradeList(e){const o=(Array.isArray(e)?e:void 0===e?[]:[e]).flatMap(e=>e.split(/[\s,]+/));return[...new Set(o.map(e=>e.trim()).filter(Boolean))]}function ge(){return"darwin"===process.platform||"win32"===process.platform||c.isToolInstalled("claude-desktop")}export async function setupCommand(d){le=null;const u=DEDICATED_KEYS.map(e=>({...e,apiKey:d[e.option]?.trim()})).filter(e=>Boolean(e.apiKey)),h=void 0!==d.oneMillion||void 0!==d.claudeOfficial||void 0!==d.desktopRegistry;let y=d.key?.trim();const _=d.upgrade??[],w=V(_);if(w.length>0)return te(n.t("upgrade.unsupported",{tool:w.join(", ")})),void(process.exitCode=b.usage);if(_.length>0&&(K()?console.log(n.t("setup.dry_run_upgrade",{tools:_.join(", ")})):(await Y(_),q()),!y&&0===u.length&&!h))return;y||0!==u.length||h||!E()||(y=(await F.prompt([{type:"password",name:"key",mask:"*",message:n.t("setup.ask_key")}])).key?.trim()||void 0);const x=void 0!==d.oneMillion,j=void 0!==d.claudeOfficial;let I;if(j&&(I=parseOnOff(d.claudeOfficial),void 0===I))return te(n.t("setup.claude_official_invalid",{value:String(d.claudeOfficial)})),void(process.exitCode=1);const S=void 0!==d.desktopRegistry;let B;if(S&&(B=parseOnOff(d.desktopRegistry),void 0===B))return te(n.t("setup.desktop_registry_invalid",{value:String(d.desktopRegistry)})),void(process.exitCode=1);const D=j||S,ie=Boolean(y||u.length>0),fe={oneMillion:d.oneMillion,officialLogin:I,desktopRegistry:B,force:d.force};if(!ie&&(x||D)&&K())return void pe([...x?["codex"]:[],...D?["claude-desktop"]:[]],!1);if(!ie&&(x||D)){if(x){const e=r.getApiKeyForTool("codex");if(e)try{const o=!0===d.oneMillion;r.setToolSetting("codex",f,o);const t=await g(e);m(o,t??void 0),ee(n.t(o?"setup.codex_1m_enabled":"setup.codex_1m_disabled"))}catch(e){te(n.t("setup.apply_failed",{tool:p.codex.displayName,reason:e instanceof Error?e.message:String(e)})),process.exitCode=1}else te(n.t("setup.codex_1m_missing_key")),process.exitCode=1}if(D){const e=r.getApiKeyForTool("claude-desktop");e?await ae("claude-desktop",e,{...fe,oneMillion:void 0,takeOver:!0})?await t(["claude-desktop"],{apps:{install:!1}}):process.exitCode=1:(te(n.t("setup.desktop_official_login_missing_key")),process.exitCode=1)}return}if(!ie)return te(n.t("setup.usage")),void(process.exitCode=1);const he=d.ccswitchUse?"use":d.ccswitch?"add":null,ye=he?await async function(){let e,o=await W();if("running"===o.problem&&!K()&&(C()||v())&&(C()||await G({message:n.t("ccswitch.ask_quit"),defaultValue:!0}))){const t=J();t&&(e=t.reopen,o=await W())}if(o.ok||K()&&"running"===o.problem)return{state:o,reopen:e};const t=n.t(`ccswitch.problem_${o.problem}`,{path:o.dbPath,schema:String(o.schema??"?"),node:process.versions.node});if(U("ccswitch","unsupported_schema"===o.problem||"unexpected_tables"===o.problem||"unreadable"===o.problem?"fail":"skip",{detail:{problem:o.problem,schema:o.schema,detail:o.detail,platform:process.platform}}),T())throw k(t,`${L} setup --key ${n.t("errors.key_placeholder")}`,`ccswitch_${o.problem}`);return te(t),e?.(),null}():null;if(he&&!ye)return void(process.exitCode=1);const ke=K(),_e=ke?null:await l(y||u[0].apiKey,{save:!1}),we=[],be=[];let ve,xe=0,Ce=0;const je=new Set,Ke=u.map(e=>({tool:e.tool,label:`--${e.option}`,apiKey:e.apiKey,need:e.need}));for(const e of Ke){if(!await se(e.label,e.apiKey)){Ce+=1;continue}const o=await X(e.apiKey);!o.probed||Z(o,e.need)?(o.probed||oe(n.t("setup.probe_failed",{label:e.label})),we.push({tool:e.tool,apiKey:e.apiKey,dedicated:!0}),je.add(e.tool)):(te(n.t(`setup.key_no_${e.need}`,{label:e.label,tool:p[e.tool].displayName})),Ce+=1)}const Te=!!y&&await se("--key",y);y&&!Te&&(ve=b[le??"operation"]);const $e=y&&Te?await X(y):void 0;y&&$e&&!$e.probed&&oe(n.t("setup.probe_failed",{label:"--key"})),!(y&&$e&&$e.probed)||$e.hasClaude||$e.hasGpt||$e.hasGrok||$e.hasGemini||(te(n.t("setup.key_no_family")),ve=1);const Me=Boolean(y)&&0===u.length&&!d.fromInstaller&&E()&&!he;if(y&&$e&&void 0===ve){const e=$e.hasClaude||$e.hasGpt||$e.hasGrok||$e.hasGemini,o=[{tool:"claude-code",capable:$e.hasClaude,skipMsg:n.t(ge()?"setup.skip_no_claude_desktop":"setup.skip_no_claude")},{tool:"codex",capable:$e.hasGpt,skipMsg:n.t("setup.skip_no_gpt")},{tool:"grok",capable:$e.hasGrok,skipMsg:n.t("setup.skip_no_grok")},{tool:"claude-desktop",capable:$e.hasClaude&&ge(),skipMsg:"",quiet:!0},{tool:"agy",capable:$e.hasGemini,skipMsg:n.t("setup.skip_no_gemini")},{tool:"codebuddy",capable:e&&c.isToolInstalled("codebuddy"),skipMsg:"",quiet:!0},{tool:"workbuddy",capable:e&&c.isToolInstalled("workbuddy"),skipMsg:"",quiet:!0},{tool:"dsh",capable:e&&c.isToolInstalled("dsh"),skipMsg:"",quiet:!0,ask:!0}];for(const e of o)je.has(e.tool)||(e.capable?(!e.ask||ke||Me||await re(e.tool))&&(we.push({tool:e.tool,apiKey:y,dedicated:!1}),je.add(e.tool)):e.quiet||oe(e.skipMsg))}let Ie,Se=d.install,Ne=[];if(Me&&void 0===ve&&we.length>0){const e=await async function(e,o){console.log("");const{configure:t}=await F.prompt([{type:"checkbox",name:"configure",message:n.t("setup.pick_configure"),choices:e.map(e=>me(e,!0))}]);let l=[];const i=[...e.filter(de),...ue(e)];if(o&&i.length>0){const e=e=>N(e)?.tool??e;l=(await F.prompt([{type:"checkbox",name:"upgrade",message:n.t("setup.pick_upgrade"),choices:i.map(o=>me(o,t.includes(e(o))))}])).upgrade}return 0===t.length&&0===l.length?(console.log(n.t("setup.pick_none")),null):{configure:t,upgrade:l}}(we.map(e=>e.tool),void 0===d.upgrade);if(!e)return void(process.exitCode=b.cancelled);if(0===e.configure.length)return void await Y(e.upgrade);Ne=e.upgrade,Ie=[],!0!==Se&&(Se=!1);const o=e.configure.filter(e=>ne(e)&&!Ne.includes(e)&&!Se);if(o.length>0&&oe(n.t("setup.pick_configure_skip",{tools:o.map(e=>p[e].displayName).join(n.t("setup.list_separator"))})),we.splice(0,we.length,...we.filter(t=>e.configure.includes(t.tool)&&!o.includes(t.tool))),0===we.length)return void(Ne.length>0&&await Y(Ne))}const Ae=Boolean(y&&Te&&void 0===ve);if(he&&ye)return void 0!==ve&&0===we.length?(ye.reopen?.(),void(process.exitCode=ve)):(await async function(o,l,i,a,d,u){const f=o.filter(e=>c.supportsCcSwitch(e.tool)),m=o.filter(e=>!c.supportsCcSwitch(e.tool)),g=e=>e.map(e=>p[e.tool].displayName).join(n.t("setup.list_separator"));if(m.length>0&&oe(n.t("ccswitch.not_supported",{tools:g(m)})),0===f.length)return te(n.t("ccswitch.nothing")),i.reopen?.(),void(process.exitCode=1);const h=n.t(l?"ccswitch.plan_use":"ccswitch.plan_add",{tools:g(f),path:i.state.dbPath});if(K())return void console.log(h);if(!u&&E()&&(console.log(h),!await G({message:n.t("ccswitch.confirm"),defaultValue:!0})))return i.reopen?.(),void(process.exitCode=b.cancelled);s(),a();const y=[],k=[];for(const e of f){if(l&&ne(e.tool))oe(n.t("ccswitch.not_installed_card_only",{tool:p[e.tool].displayName}));else{if(l&&!await ae(e.tool,e.apiKey,{...d,takeOver:!0}))continue;l&&y.push(e.tool)}k.push(e)}const _=[];for(const e of k)try{const o=await H(e.tool,e.apiKey,r.getModelsForTool(e.tool));o&&_.push({tool:e.tool,card:{...o,current:y.includes(e.tool)}})}catch(o){te("× "+n.t("ccswitch.card_failed",{tool:p[e.tool].displayName,reason:o instanceof Error?o.message:String(o)}))}try{const o=_.length>0?await Q(_.map(e=>e.card)):[];o.forEach((e,o)=>{const t=_[o].tool,l=p[t].displayName;r.setMachineSetting(t,z,y.includes(t)?"use":"add");const i=e.current?"ccswitch.done_use":y.includes(t)&&e.proxyMode?"ccswitch.done_proxy":"ccswitch.done_add";ee(n.t(i,{tool:l}))}),U("ccswitch","ok",{detail:{mode:l?"use":"add",schema:i.state.schema,tools:_.map(e=>e.tool)}}),o.some(e=>!e.current)&&console.log(e.gray(" "+n.t("ccswitch.switch_hint")))}catch(e){U("ccswitch","fail",{error:e,detail:{mode:l?"use":"add",schema:i.state.schema}}),te("× "+n.t("ccswitch.write_failed",{reason:e instanceof Error?e.message:String(e)})),process.exitCode=1}i.reopen?.(),y.length>0&&await t(y,{apps:{install:!1}}),_.length<f.length&&(process.exitCode=1)}(we,"use"===he,ye,()=>{Ae&&y&&r.setApiKey(y);for(const e of we)e.dedicated?r.setToolApiKey(e.tool,e.apiKey):r.clearToolApiKey(e.tool)},fe,Boolean(d.fromInstaller)),void(void 0!==ve&&(process.exitCode=ve)));if(ke)return pe(we.filter(e=>!ne(e.tool)).map(e=>e.tool),we.length>0,we.filter(e=>ne(e.tool)).map(e=>e.tool)),void((Ce>0||void 0!==ve)&&(process.exitCode=ve??b[le??"operation"]));const Ge=we.filter(e=>!ne(e.tool)),Ee=Ae||we.some(e=>e.dedicated),Oe=_e?a().filter(e=>!we.some(o=>o.tool===e.tool)):[],Be=!d.fromInstaller&&E();if((we.length>0||Ee)&&!d.fromInstaller&&!await O([...Ge.map(e=>e.tool),...Oe.map(e=>e.tool)],{keyFile:Ee?A(r.getConfigDir(),"config.yaml"):void 0,installFirst:we.filter(e=>ne(e.tool)).map(e=>e.tool)}))return void(process.exitCode=b.cancelled);Ne.length>0&&(await Y(Ne),q()),(we.length>0||Ee)&&s(),Ae&&y&&r.setApiKey(y);for(const e of we)ne(e.tool)?(e.dedicated&&r.setToolApiKey(e.tool,e.apiKey),be.push({tool:e.tool,apiKey:e.apiKey,dedicated:e.dedicated})):await ae(e.tool,e.apiKey,{...fe,takeOver:e.dedicated||Be})?(e.dedicated?r.setToolApiKey(e.tool,e.apiKey):r.clearToolApiKey(e.tool),xe+=1):(Ce+=1,je.delete(e.tool));const De=we.length>0||Ee?await i(Oe):[];if(void 0!==ve)return be.length>0&&ce(be.map(e=>e.tool)),void(process.exitCode=ve);let Fe=[];if(be.length>0){const o=await async function(o,t,l){const i=o.map(e=>e.tool);if(0===i.length)return{still:[],applied:[],failed:[]};const s=i.map(e=>p[e].displayName).join(n.t("setup.list_separator"));let a=t;if(void 0!==a||T()||(M()?a=!$():process.stdin.isTTY&&(console.log(""),a=(await F.prompt([{type:"confirm",name:"go",message:n.t("setup.install_confirm",{tools:s}),default:!0}])).go)),!a){console.log("");for(const o of i)console.log(e.yellow("! "+n.t("setup.install_hint",{tool:p[o].displayName,install:p[o].installCommand})));return T()||console.log(e.gray(n.t("setup.install_all_hint",{cli:L}))),{still:i,applied:[],failed:[]}}const d=[];for(const o of i){console.log(e.bold(`\n${p[o].displayName}`));try{await c.installTool(o)}catch(e){P.logError(`setup: install ${o}`,e)}q(),c.isToolInstalled(o)||d.push(o)}const u=i.filter(e=>!d.includes(e));u.length>0&&console.log("");const f=[],m=[];for(const{tool:e,apiKey:t,dedicated:i}of o.filter(e=>u.includes(e.tool)))await ae(e,t,l)?(f.push(e),i||r.clearToolApiKey(e)):m.push(e);return{still:d,applied:f,failed:m}}(be,Se,fe);Fe=o.still,xe+=o.applied.length,Ce+=o.failed.length;for(const e of[...Fe,...o.failed])je.delete(e)}if(xe>0){const t=[...je].filter(e=>!o(e)?.isInstalled&&!Fe.includes(e)),l=t.map(e=>p[e]?.command).filter(Boolean).join(" / "),i=n.t("setup.done",{count:String(xe)});ee("\n"+(l?`${i}${n.t("setup.done_commands",{commands:l})}`:i)),Fe.length>0&&ce(Fe);for(const e of t){const o=c.ensureNativeOnPath(e);o&&ee(n.t("setup.path_added",{tool:p[e].displayName,dir:o}))}const s=t.filter(e=>!c.isOnPath(e));if(s.length>0&&!T()&&"1"!==R("PATH_HINT_BY_CALLER")){const o=s.map(e=>p[e].command).join(" / ");console.log(e.yellow(" ! "+n.t("win32"===process.platform?"setup.path_reload_windows":"setup.path_reload",{commands:o})))}}0===xe&&Fe.length>0&&ce(Fe),Ce>0&&(te(n.t("setup.failed_summary",{count:String(Ce)})),T()||console.error(`${L} setup --key ${n.t("errors.key_placeholder")}`)),await t([...je,...De],{apps:{install:await installMissingApps([...je],Se,Ie)}}),(Ce>0||0===xe&&0===Fe.length)&&(process.exitCode=b[le??"operation"])}
@@ -0,0 +1,79 @@
1
+ import type { VibecliModels } from './config.js';
2
+ /** Machine setting (per tool) recording that CC Switch has the tool: `add` (card only) or `use` (card, current). */
3
+ export declare const CCSWITCH_SETTING = "ccswitch";
4
+ /** Database versions whose `providers` / `provider_endpoints` tables were checked against CC Switch's source. */
5
+ export declare const CCSWITCH_SCHEMAS: number[];
6
+ /** CC Switch's app ids for the tools we hand over (`AppType::as_str`). */
7
+ export type CcSwitchApp = 'claude' | 'codex';
8
+ /** One card: what CC Switch stores in `settings_config`, plus the other gateway addresses for its endpoint list. */
9
+ export interface CcSwitchCard {
10
+ app: CcSwitchApp;
11
+ settingsConfig: Record<string, unknown>;
12
+ /** Primary address first; the rest go to `provider_endpoints`. */
13
+ endpoints: string[];
14
+ }
15
+ export type CcSwitchProblem = 'not_installed' | 'no_sqlite' | 'unsupported_schema' | 'unexpected_tables' | 'running' | 'unreadable';
16
+ export interface CcSwitchState {
17
+ ok: boolean;
18
+ problem?: CcSwitchProblem;
19
+ /** `PRAGMA user_version` when the database could be read. */
20
+ schema?: number;
21
+ dbPath: string;
22
+ detail?: string;
23
+ }
24
+ export interface CcSwitchWriteResult {
25
+ app: CcSwitchApp;
26
+ added: boolean;
27
+ /** Made the current card (`--ccswitch-use`). False when asked but CC Switch routes this app through its proxy. */
28
+ current: boolean;
29
+ proxyMode: boolean;
30
+ }
31
+ /** The card id: fixed, so a rerun updates the same card instead of adding another. */
32
+ export declare function ccSwitchCardId(): string;
33
+ /** `~/.cc-switch`: the device's own state (`settings.json`, `live-state.json`) stays here even when the data dir moved. */
34
+ export declare function ccSwitchDeviceDir(): string;
35
+ /** The data dir CC Switch uses: the override from `app_paths.json` when it exists, else `~/.cc-switch`. */
36
+ export declare function ccSwitchDataDir(): string;
37
+ export declare function ccSwitchDbPath(): string;
38
+ type Runner = (command: string, args: string[]) => {
39
+ status: number | null;
40
+ stdout: string;
41
+ };
42
+ /** Tests: fake the process check (null restores it). */
43
+ export declare function setCcSwitchRunningForTests(running: boolean | null): void;
44
+ /** Tests: replace the process runner. */
45
+ export declare function setCcSwitchRunnerForTests(fake: Runner | null): void;
46
+ /** The CC Switch app (binary `cc-switch`) is running. */
47
+ export declare function isCcSwitchRunning(): boolean;
48
+ /**
49
+ * Quit CC Switch so it can't overwrite or miss what we write (it caches its database in memory). Returns how
50
+ * to start it again (`reopen()`), or null when it is still running after ten seconds. macOS asks the app to
51
+ * quit; Windows and Linux end the process (its tray keeps it alive when the window closes; SQLite in WAL mode
52
+ * survives that).
53
+ */
54
+ export declare function quitCcSwitch(): {
55
+ reopen(): void;
56
+ } | null;
57
+ /**
58
+ * Whether we may write: installed (database there), node:sqlite available, a database version we checked,
59
+ * the two tables with the columns we write, and the app closed. Read-only; the database is not migrated.
60
+ */
61
+ export declare function inspectCcSwitch(): Promise<CcSwitchState>;
62
+ /**
63
+ * Add or update our card for each app in one transaction (after a snapshot of the database); a card with
64
+ * `current` is also made the app's current card (both in the database and the device's settings.json),
65
+ * except where CC Switch routes the app through its local proxy: switching there means changing its
66
+ * route, which only CC Switch can do. Call `inspectCcSwitch()` first.
67
+ */
68
+ export declare function writeCcSwitchCards(cards: Array<CcSwitchCard & {
69
+ current?: boolean;
70
+ }>): Promise<CcSwitchWriteResult[]>;
71
+ /**
72
+ * The card for `toolName` (null when its adapter has none): the adapter's `settings_config` built from the same
73
+ * context a normal apply gets (incl. the key's model catalog), and every gateway address with the tool's path,
74
+ * the configured one first.
75
+ */
76
+ export declare function buildCcSwitchCard(toolName: string, apiKey: string, models: VibecliModels): Promise<CcSwitchCard | null>;
77
+ /** Whether our card is in CC Switch's list for `app` (read-only; false when it can't be read). */
78
+ export declare function hasCcSwitchCard(app: CcSwitchApp): Promise<boolean>;
79
+ export {};
@@ -0,0 +1 @@
1
+ import{existsSync as t,mkdirSync as e,readFileSync as r,readdirSync as n,rmSync as i}from"fs";import{join as o}from"path";import{spawn as s,spawnSync as c}from"child_process";import{BRAND_NAME as a,CLI_NAME as p,PROVIDER_KEY as u,brandEnv as l}from"./brand.js";import{toolHome as d}from"./tools/types.js";import{atomicWriteFile as f,backupBeforeWrite as h}from"./tools/backup.js";import{columnsOf as m,openSqlite as w,rollback as g}from"./sqlite.js";import{KEY_INFO_PATH as S}from"./gateway-protocol.js";import{configManager as _}from"./config.js";import{logger as y}from"../utils/logger.js";import{getAdapter as E}from"./tools/registry.js";import{resolveModelCatalog as b}from"./model-catalog.js";import{gatewayAddresses as C}from"./gateway-addresses.js";export const CCSWITCH_SETTING="ccswitch";export const CCSWITCH_SCHEMAS=[29,30];const v=["id","app_type","name","settings_config","website_url","category","created_at","sort_index","notes","icon","meta","is_current","in_failover_queue"],A=["provider_id","app_type","url","added_at"],D={claude:"currentProviderClaude",codex:"currentProviderCodex"};export function ccSwitchCardId(){return`${u}-${p}`}function x(){return Boolean(l("TEST_HOME")?.trim())}export function ccSwitchDeviceDir(){return o(d(),".cc-switch")}export function ccSwitchDataDir(){try{const e=JSON.parse(r(function(){const t=d(),e="com.ccswitch.desktop";if("darwin"===process.platform)return o(t,"Library","Application Support",e,"app_paths.json");if("win32"===process.platform){const r=!x()&&process.env.APPDATA?process.env.APPDATA:o(t,"AppData","Roaming");return o(r,e,"app_paths.json")}const r=!x()&&process.env.XDG_DATA_HOME?process.env.XDG_DATA_HOME:o(t,".local","share");return o(r,e,"app_paths.json")}(),"utf-8")).app_config_dir_override;if("string"==typeof e&&e.trim()){const r=e.trim(),n="~"===r?d():r.startsWith("~/")||r.startsWith("~\\")?o(d(),r.slice(2)):r;if(t(n))return n}}catch{}return ccSwitchDeviceDir()}export function ccSwitchDbPath(){return o(ccSwitchDataDir(),"cc-switch.db")}function T(t){try{const e=JSON.parse(r(o(ccSwitchDeviceDir(),"live-state.json"),"utf-8")),n=e.apps?.[t]?.mode;return"string"==typeof n?n:"direct"}catch{return"direct"}}const N=(t,e)=>{const r=c(t,e,{encoding:"utf-8",timeout:1e4,windowsHide:!0,stdio:["ignore","pipe","ignore"]});return{status:r.status,stdout:`${r.stdout??""}`}};let P=N,M=null;export function setCcSwitchRunningForTests(t){M=t}export function setCcSwitchRunnerForTests(t){P=t??N}export function isCcSwitchRunning(){return null!==M?M:!x()&&("win32"===process.platform?/cc-switch\.exe/i.test(P("tasklist",["/FI","IMAGENAME eq cc-switch.exe","/NH"]).stdout):0===P("pgrep",["-x","cc-switch"]).status)}function O(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}export function quitCcSwitch(){const t=function(){if("darwin"===process.platform)return null;if("win32"===process.platform)return P("powershell.exe",["-NoProfile","-NonInteractive","-Command","(Get-Process -Name cc-switch -ErrorAction SilentlyContinue | Select-Object -First 1).Path"]).stdout.trim()||null;const t=P("pgrep",["-x","cc-switch"]).stdout.trim().split(/\s+/)[0];return t&&P("readlink",[`/proc/${t}/exe`]).stdout.trim()||null}();"darwin"===process.platform?P("osascript",["-e",'tell application id "com.ccswitch.desktop" to quit']):"win32"===process.platform?P("taskkill",["/IM","cc-switch.exe","/F"]):P("pkill",["-TERM","-x","cc-switch"]);for(let t=0;t<20&&isCcSwitchRunning();t++)O(500);return isCcSwitchRunning()?null:{reopen(){try{"darwin"===process.platform?c("open",["-b","com.ccswitch.desktop"],{stdio:"ignore",timeout:1e4}):t&&s(t,[],{detached:!0,stdio:"ignore",windowsHide:!1}).unref()}catch(t){y.logError("ccswitch.reopen",t)}}}}export async function inspectCcSwitch(){const e=ccSwitchDbPath();if(!t(e))return{ok:!1,problem:"not_installed",dbPath:e};const r=await w(e);if("string"==typeof r)return{ok:!1,problem:"no_sqlite",dbPath:e,detail:r};try{const t=Number(r.prepare("PRAGMA user_version").all()[0]?.user_version);if(!CCSWITCH_SCHEMAS.includes(t))return{ok:!1,problem:"unsupported_schema",schema:t,dbPath:e};const n=m(r,"providers"),i=m(r,"provider_endpoints"),o=[...v.filter(t=>!n.has(t)),...A.filter(t=>!i.has(t)).map(t=>`provider_endpoints.${t}`)];return o.length>0?{ok:!1,problem:"unexpected_tables",schema:t,dbPath:e,detail:o.join(",")}:isCcSwitchRunning()?{ok:!1,problem:"running",schema:t,dbPath:e}:{ok:!0,schema:t,dbPath:e}}catch(t){return{ok:!1,problem:"unreadable",dbPath:e,detail:t instanceof Error?t.message:String(t)}}finally{r.close()}}function R(){return`({\n request: {\n url: "{{baseUrl}}".replace(/\\/+$/, "").replace(/\\/v1(beta)?$/, "") + "${S}",\n method: "GET",\n headers: { "Authorization": "Bearer {{apiKey}}" }\n },\n extractor: function (response) {\n if (!response || response.success !== true || !response.data) {\n var msg = response && (response.message || (response.error && response.error.message));\n return { isValid: false, invalidMessage: msg || "Query failed" };\n }\n var b = response.data.balance;\n var result = { isValid: true, planName: response.data.group };\n if (b && typeof b.remaining === "number") {\n result.remaining = b.remaining;\n result.unit = b.unit === "TOKENS" ? "tokens" : (b.unit === "CUSTOM" ? b.symbol : b.unit);\n }\n return result;\n }\n})`}function I(e,n){const i=o(ccSwitchDeviceDir(),"settings.json");let s={};try{s=JSON.parse(r(i,"utf-8"))}catch{}s[D[e]]!==n&&(t(i)&&h(i),f(i,JSON.stringify({...s,[D[e]]:n},null,2)+"\n",384))}export async function writeCcSwitchCards(t){const r=await w(ccSwitchDbPath());if("string"==typeof r)throw new Error(r);const s=r,c=ccSwitchCardId(),p=Date.now(),u=[];try{s.exec("PRAGMA busy_timeout = 5000"),function(t){const r=o(_.getConfigDir(),"backups"),s=o(r,`cc-switch-${Date.now()}.db`);try{e(r,{recursive:!0,mode:448}),t.exec(`VACUUM INTO '${s.replace(/'/g,"''")}'`);const c=n(r).filter(t=>/^cc-switch-\d+\.db$/.test(t)).sort().reverse().slice(5);for(const t of c)i(o(r,t),{force:!0})}catch(t){y.logError("ccswitch.snapshotDb",t)}}(s),s.exec("BEGIN IMMEDIATE");for(const e of t){const t=s.prepare("SELECT meta FROM providers WHERE id = ? AND app_type = ?").all(c,e.app);let r={};try{r=t[0]&&"string"==typeof t[0].meta?JSON.parse(t[0].meta):{}}catch{r={}}r.usage_script={enabled:!0,language:"javascript",code:R(),timeout:10};const n=JSON.stringify(e.settingsConfig),i=e.endpoints[0]?.replace(/\/v1$/,"")??_.getBaseUrl();if(t.length>0)s.prepare("UPDATE providers SET name = ?, settings_config = ?, website_url = ?, meta = ? WHERE id = ? AND app_type = ?").run(a,n,i,JSON.stringify(r),c,e.app);else{const t=s.prepare("SELECT COALESCE(MAX(sort_index), -1) + 1 AS next FROM providers WHERE app_type = ?").all(e.app)[0];s.prepare("INSERT INTO providers (id, app_type, name, settings_config, website_url, category, created_at, sort_index, notes, icon, meta, is_current, in_failover_queue)\n VALUES (?, ?, ?, ?, ?, NULL, ?, ?, NULL, NULL, ?, 0, 0)").run(c,e.app,a,n,i,p,Number(t.next),JSON.stringify(r))}s.prepare("DELETE FROM provider_endpoints WHERE provider_id = ? AND app_type = ?").run(c,e.app);for(const t of e.endpoints.slice(1))s.prepare("INSERT INTO provider_endpoints (provider_id, app_type, url, added_at) VALUES (?, ?, ?, ?)").run(c,e.app,t,p);const o="proxy"===T(e.app),l=Boolean(e.current)&&!o;l&&(s.prepare("UPDATE providers SET is_current = 0 WHERE app_type = ? AND id <> ?").run(e.app,c),s.prepare("UPDATE providers SET is_current = 1 WHERE app_type = ? AND id = ?").run(e.app,c)),u.push({app:e.app,added:0===t.length,current:l,proxyMode:o})}s.exec("COMMIT")}catch(t){throw g(s),t}finally{s.close()}for(const t of u)t.current&&I(t.app,c);return u}export async function buildCcSwitchCard(t,e,r){const n=E(t);if(!n?.ccSwitch)return null;const i=n.wantsModelCatalog?await b(e):null,o=_.getBaseUrl(),s=n.ccSwitch.card({apiKey:e,baseUrl:o,models:r,settings:_.getToolSettings(t),...i?{catalog:i}:{}}),c=o.replace(/\/+$/,"").replace(/\/v1$/,""),a=[c,...C().map(t=>t.url.replace(/\/+$/,"")).filter(t=>t!==c)];return{app:n.ccSwitch.app,settingsConfig:s,endpoints:a.map(t=>t+n.ccSwitch.endpointPath)}}export async function hasCcSwitchCard(e){if(!t(ccSwitchDbPath()))return!1;const r=await w(ccSwitchDbPath());if("string"==typeof r)return!1;try{return r.prepare("SELECT 1 FROM providers WHERE id = ? AND app_type = ?").all(ccSwitchCardId(),e).length>0}catch{return!1}finally{r.close()}}
@@ -59,6 +59,13 @@ export interface ClaudeCodeMCPConfig {
59
59
  hasCompletedOnboarding?: boolean;
60
60
  [key: string]: any;
61
61
  }
62
+ /**
63
+ * The CC Switch card for Claude Code (`settings_config`): address, token and model variables in `env`,
64
+ * top-level `model`, and our `/model` menu (`modelPicker`, `modelSettings`, `CLAUDE_CODE_MAX_CONTEXT_TOKENS`).
65
+ * CC Switch owns `env` address / token / models, `model` and `modelPicker`: it writes them when switching
66
+ * to this card and clears them when switching away, so the menu never stays behind for another provider.
67
+ */
68
+ export declare function ccSwitchClaudeSettings(apiKey: string, baseUrl: string, models: typeof DEFAULT_MODELS, availableModels?: string[], gatewayModels?: GatewayModelSpec[]): ClaudeCodeSettingsConfig;
62
69
  export declare class ClaudeCodeManager {
63
70
  private static instance;
64
71
  private settingsPath;
@@ -1 +1 @@
1
- import{existsSync as e,mkdirSync as t,readFileSync as n,writeFileSync as o,renameSync as i,unlinkSync as s}from"fs";import{join as r,dirname as a}from"path";import{toolHome as l}from"./tools/types.js";import{logger as c}from"../utils/logger.js";import{configManager as d,DEFAULT_MODELS as g}from"./config.js";import{loadSettingsTemplate as f}from"./settings-template.js";import{cleanupAnthropicEnvVars as u}from"./env-cleanup.js";import{getClaudeCodeTierChains as m,getGatewayModelRules as C,getRetiredDefaultModelIds as O}from"./model-registry.js";import{claimField as h,forgetField as p,ownsValue as _,recordAfterWrite as E,takeField as A}from"./written-values.js";import{atomicWriteFile as v}from"./tools/backup.js";import{noteWrittenGatewayUrl as T}from"./gateway-addresses.js";import{autoCompactTokens as P,modelBlurb as S,prettyModelName as N}from"./gateway-models.js";import{baseModelId as M}from"./model-catalog.js";export const MODEL_ENV_VARS=["ANTHROPIC_DEFAULT_HAIKU_MODEL","ANTHROPIC_DEFAULT_SONNET_MODEL","ANTHROPIC_DEFAULT_OPUS_MODEL","ANTHROPIC_DEFAULT_FABLE_MODEL","ANTHROPIC_MODEL","ANTHROPIC_REASONING_MODEL"];const D="claude-code.model",L=e=>`claude-code.env.${e}`;function R(e){const t=Object.values(m()).flat(),n=[...Object.values(g),...Object.values(e)].filter(e=>"string"==typeof e&&""!==e);return[...new Set(["opus[1m]",...n,...O(),...t])]}const y={opus:"ANTHROPIC_DEFAULT_OPUS_MODEL",sonnet:"ANTHROPIC_DEFAULT_SONNET_MODEL",haiku:"ANTHROPIC_DEFAULT_HAIKU_MODEL",fable:"ANTHROPIC_DEFAULT_FABLE_MODEL"},I="CLAUDE_CODE_MAX_CONTEXT_TOKENS";function U(){return r(d.getConfigDir(),"claude-code-picker.json")}function H(){try{const e=JSON.parse(n(U(),"utf-8")).ids;return Array.isArray(e)?e.map(String):[]}catch{return[]}}function b(e){try{v(U(),JSON.stringify({ids:e})+"\n")}catch(e){c.logError("claudeCode.recordWrittenPickerIds",e)}}let F=null;function j(e,t=[]){if(!e||"object"!=typeof e)return!1;const{options:n,replaceBuiltInOptions:o}=e;if(!Array.isArray(n)||o)return!1;const i=C(),s=new Set([...i.models.map(e=>e.id),...i.retired,...H(),...t]);return n.every(e=>e&&"object"==typeof e&&s.has(M(String(e.model))))}export function applyGatewayModels(e,t){if(void 0===t)return e;const n={...e};if(void 0!==n.modelPicker&&!j(n.modelPicker,t.map(e=>e.id)))return n;const o=j(n.modelPicker)?n.modelPicker.options.map(e=>M(e.model)):[],i={...n.env||{}},s={...n.modelSettings||{}};for(const e of o){if(!s[e])continue;const{autoCompactWindow:t,...n}=s[e];Object.keys(n).length>0?s[e]=n:delete s[e]}const r=e=>(e.contextWindow??0)>=1e6,a=t.filter(e=>!r(e)).map(e=>e.contextWindow).filter(e=>"number"==typeof e&&e>0);!function(e){const t=H(),n=[...new Set([...t,...e])];n.length!==t.length&&b(n),F=e}(t.map(e=>e.id));const l=e=>S(e.description,{millionContext:r(e)});if(0===t.length)delete n.modelPicker,delete i[I];else{n.modelPicker={options:t.map(e=>({model:r(e)?`${e.id}[1m]`:e.id,label:e.name||N(e.id),...l(e)?{description:l(e)}:{}}))},a.length>0?i[I]=String(Math.min(...a)):delete i[I];for(const e of t){if(!e.contextWindow)continue;const t=P(e.contextWindow,e.autoCompactTokens);s[e.id]={...s[e.id],autoCompactWindow:Math.min(Math.max(t,1e5),1e6)}}}return Object.keys(s).length>0?n.modelSettings=s:delete n.modelSettings,Object.keys(i).length>0?n.env=i:delete n.env,n}export function resolveTierFallbacks(e){if(!e||0===e.length)return[];const t=new Set(e.map(M)),n=[];for(const[e,o]of Object.entries(m())){const i=y[e],[s,...r]=o;if(!i||!s||t.has(s))continue;const a=r.find(e=>t.has(e));a&&n.push({tier:e,envVar:i,from:s,to:a})}return n}export class ClaudeCodeManager{static instance;settingsPath;mcpConfigPath;lastTierFallbacks=[];lastReplaced=[];constructor(){this.settingsPath=r(l(),".claude","settings.json"),this.mcpConfigPath=r(l(),".claude.json")}static getInstance(){return ClaudeCodeManager.instance||(ClaudeCodeManager.instance=new ClaudeCodeManager),ClaudeCodeManager.instance}ensureConfigDir(n){const o=a(n);e(o)||t(o,{recursive:!0})}atomicWrite(t,n){const r=`${t}.tmp`;try{o(r,n,"utf-8"),i(r,t)}catch(t){if(e(r))try{s(r)}catch{}throw t}}getSettings(){try{if(e(this.settingsPath)){const e=n(this.settingsPath,"utf-8");return JSON.parse(e)}}catch(e){c.warn("Failed to read Claude Code settings:",e),c.logError("ClaudeCodeManager.getSettings",e)}return{}}saveSettings(e){try{this.ensureConfigDir(this.settingsPath),this.atomicWrite(this.settingsPath,JSON.stringify(e,null,2))}catch(e){throw new Error(`Failed to save Claude Code settings: ${e}`)}!function(){if(!F)return;const e=F;F=null;const t=H();(t.length!==e.length||t.some(t=>!e.includes(t)))&&b(e)}()}getMCPConfig(){try{if(e(this.mcpConfigPath)){const e=n(this.mcpConfigPath,"utf-8");return JSON.parse(e)}}catch(e){c.warn("Failed to read Claude Code MCP config:",e),c.logError("ClaudeCodeManager.getMCPConfig",e)}return{}}saveMCPConfig(e){try{this.ensureConfigDir(this.mcpConfigPath),this.atomicWrite(this.mcpConfigPath,JSON.stringify(e,null,2))}catch(e){throw new Error(`Failed to save Claude Code MCP config: ${e}`)}}loadPrivateConfig(e,t,n,o){E(()=>this.writePrivateConfig(e,t,n,o))}writePrivateConfig(e,t,n,o){this.ensureOnboardingCompleted(),u();const i=f(),s=i.env||{},{env:r,...a}=i,l=this.getSettings(),{ANTHROPIC_API_KEY:c,...m}=l.env||{},C={...m},O={},h=e=>{const n=(t[e]||"").trim();return n&&n!==g[e]?n:null},E=h("haiku"),v=h("sonnet"),P=h("opus"),S=new Set([E&&"haiku",v&&"sonnet",P&&"opus"].filter(Boolean)),N=resolveTierFallbacks(n).filter(e=>!S.has(e.tier));for(const e of N)O[e.envVar]=e.to;const M=new Set;E&&(O.ANTHROPIC_DEFAULT_HAIKU_MODEL=E),v&&(O.ANTHROPIC_DEFAULT_SONNET_MODEL=v),P&&(O.ANTHROPIC_DEFAULT_OPUS_MODEL=P,O.ANTHROPIC_MODEL=P),E&&M.add("ANTHROPIC_DEFAULT_HAIKU_MODEL"),v&&M.add("ANTHROPIC_DEFAULT_SONNET_MODEL"),P&&["ANTHROPIC_DEFAULT_OPUS_MODEL","ANTHROPIC_MODEL"].forEach(e=>M.add(e));const y=R(t);this.lastReplaced=[];for(const e of MODEL_ENV_VARS){const t=C[e],n=O[e];if(void 0!==n)void 0===t||t===n||_(L(e),t,y)||this.lastReplaced.push(`${e}=${t}`),C[e]=n,A(L(e),n);else{if(void 0===t)continue;_(L(e),t,y)||this.lastReplaced.push(`${e}=${t}`),delete C[e],p(L(e))}}this.lastTierFallbacks=N.filter(e=>C[e.envVar]===e.to);const I={...l};for(const[e,t]of Object.entries(a))"model"!==e&&(e in I||(I[e]=t));I.showThinkingSummaries=!0;const U={...I,env:{...C,...Object.fromEntries(Object.entries(s).filter(([e])=>!(e in C))),ANTHROPIC_AUTH_TOKEN:e,ANTHROPIC_BASE_URL:d.getBaseUrl()}};T(d.getBaseUrl());const H=P??("string"==typeof a.model?a.model:void 0),b=l.model,F=void 0!==b&&b!==H&&!_(D,b,y);void 0===H?(delete U.model,p(D)):(U.model=H,A(D,H)),F&&this.lastReplaced.push(`model=${String(b)}`),this.saveSettings(applyGatewayModels(U,o))}ensureOnboardingCompleted(){try{const e=this.getMCPConfig();e.hasCompletedOnboarding||this.saveMCPConfig({...e,hasCompletedOnboarding:!0})}catch(e){c.warn("Failed to ensure onboarding completed:",e),c.logError("ClaudeCodeManager.ensureOnboardingCompleted",e)}}unloadPrivateConfig(){E(()=>this.removePrivateConfig())}removePrivateConfig(){const e=this.getSettings(),t=R(d.getModelsForTool("claude-code")),n=void 0!==e.model&&_(D,e.model,t);if(p(D),!e.env){if(n){const{model:t,...n}=e;this.saveSettings(n)}return}const{ANTHROPIC_AUTH_TOKEN:o,ANTHROPIC_BASE_URL:i,API_TIMEOUT_MS:s,CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:r,CLAUDE_CODE_AUTO_MODE_SERVER:a,...l}=e.env,c={...l};for(const e of MODEL_ENV_VARS)e in c&&_(L(e),c[e],t)&&delete c[e],p(L(e));const g={...applyGatewayModels({...e,env:c},[])};g.env=g.env||{},n&&delete g.model,g.env&&0===Object.keys(g.env).length&&delete g.env,this.saveSettings(g)}clearPinnedModels(e){const t=this.getSettings(),n=t.env,o=n?.ANTHROPIC_AUTH_TOKEN?Object.fromEntries(resolveTierFallbacks(e).map(e=>[e.envVar,e.to])):{},i=[];for(const e of MODEL_ENV_VARS)n&&e in n&&n[e]!==o[e]&&i.push(e);void 0!==t.model&&i.push("model");const s=Object.entries(o).some(([e,t])=>n?.[e]!==t);if(0===i.length&&!s)return[];const r={...t};if(delete r.model,n){const e={...n};for(const t of MODEL_ENV_VARS)delete e[t];Object.assign(e,o),0===Object.keys(e).length?delete r.env:r.env=e}this.saveSettings(r),p(D);for(const e of MODEL_ENV_VARS)o[e]?h(L(e),o[e],o[e]):p(L(e));return i}getLastReplaced(){return[...this.lastReplaced]}getLastTierFallbacks(){return[...this.lastTierFallbacks]}detectCurrentConfig(){try{const e=this.getSettings();return e.env&&e.env.ANTHROPIC_AUTH_TOKEN?{apiKey:e.env.ANTHROPIC_AUTH_TOKEN}:{apiKey:null}}catch{return{apiKey:null}}}getExperimentalFeature(e){const t=this.getSettings();return t.env?.[e]}setExperimentalFeature(e,t){const n=this.getSettings(),o=n.env||{},i={...n,env:{...o,[e]:t}};this.saveSettings(i)}removeExperimentalFeature(e){const t=this.getSettings();if(!t.env)return;const{[e]:n,...o}=t.env,i={...t,env:o};this.saveSettings(i)}}export const claudeCodeManager=ClaudeCodeManager.getInstance();
1
+ import{existsSync as e,mkdirSync as t,readFileSync as n,writeFileSync as o,renameSync as i,unlinkSync as s}from"fs";import{join as r,dirname as a}from"path";import{toolHome as l}from"./tools/types.js";import{logger as c}from"../utils/logger.js";import{configManager as d,DEFAULT_MODELS as g}from"./config.js";import{loadSettingsTemplate as u}from"./settings-template.js";import{cleanupAnthropicEnvVars as f}from"./env-cleanup.js";import{getClaudeCodeTierChains as m,getGatewayModelRules as p,getRetiredDefaultModelIds as C}from"./model-registry.js";import{claimField as h,forgetField as O,ownsValue as _,recordAfterWrite as E,takeField as v}from"./written-values.js";import{atomicWriteFile as A}from"./tools/backup.js";import{noteWrittenGatewayUrl as T}from"./gateway-addresses.js";import{autoCompactTokens as P,modelBlurb as S,prettyModelName as N}from"./gateway-models.js";import{baseModelId as M}from"./model-catalog.js";export const MODEL_ENV_VARS=["ANTHROPIC_DEFAULT_HAIKU_MODEL","ANTHROPIC_DEFAULT_SONNET_MODEL","ANTHROPIC_DEFAULT_OPUS_MODEL","ANTHROPIC_DEFAULT_FABLE_MODEL","ANTHROPIC_MODEL","ANTHROPIC_REASONING_MODEL"];const y="claude-code.model",R=e=>`claude-code.env.${e}`;function D(e){const t=Object.values(m()).flat(),n=[...Object.values(g),...Object.values(e)].filter(e=>"string"==typeof e&&""!==e);return[...new Set(["opus[1m]",...n,...C(),...t])]}const L={opus:"ANTHROPIC_DEFAULT_OPUS_MODEL",sonnet:"ANTHROPIC_DEFAULT_SONNET_MODEL",haiku:"ANTHROPIC_DEFAULT_HAIKU_MODEL",fable:"ANTHROPIC_DEFAULT_FABLE_MODEL"},I="CLAUDE_CODE_MAX_CONTEXT_TOKENS";function b(){return r(d.getConfigDir(),"claude-code-picker.json")}function H(){try{const e=JSON.parse(n(b(),"utf-8")).ids;return Array.isArray(e)?e.map(String):[]}catch{return[]}}function U(e){try{A(b(),JSON.stringify({ids:e})+"\n")}catch(e){c.logError("claudeCode.recordWrittenPickerIds",e)}}let j=null;function w(e,t=[]){if(!e||"object"!=typeof e)return!1;const{options:n,replaceBuiltInOptions:o}=e;if(!Array.isArray(n)||o)return!1;const i=p(),s=new Set([...i.models.map(e=>e.id),...i.retired,...H(),...t]);return n.every(e=>e&&"object"==typeof e&&s.has(M(String(e.model))))}export function applyGatewayModels(e,t){if(void 0===t)return e;const n={...e};if(void 0!==n.modelPicker&&!w(n.modelPicker,t.map(e=>e.id)))return n;const o=w(n.modelPicker)?n.modelPicker.options.map(e=>M(e.model)):[],i={...n.env||{}},s={...n.modelSettings||{}};for(const e of o){if(!s[e])continue;const{autoCompactWindow:t,...n}=s[e];Object.keys(n).length>0?s[e]=n:delete s[e]}const r=e=>(e.contextWindow??0)>=1e6,a=t.filter(e=>!r(e)).map(e=>e.contextWindow).filter(e=>"number"==typeof e&&e>0);!function(e){const t=H(),n=[...new Set([...t,...e])];n.length!==t.length&&U(n),j=e}(t.map(e=>e.id));const l=e=>S(e.description,{millionContext:r(e)});if(0===t.length)delete n.modelPicker,delete i[I];else{n.modelPicker={options:t.map(e=>({model:r(e)?`${e.id}[1m]`:e.id,label:e.name||N(e.id),...l(e)?{description:l(e)}:{}}))},a.length>0?i[I]=String(Math.min(...a)):delete i[I];for(const e of t){if(!e.contextWindow)continue;const t=P(e.contextWindow,e.autoCompactTokens);s[e.id]={...s[e.id],autoCompactWindow:Math.min(Math.max(t,1e5),1e6)}}}return Object.keys(s).length>0?n.modelSettings=s:delete n.modelSettings,Object.keys(i).length>0?n.env=i:delete n.env,n}export function resolveTierFallbacks(e){if(!e||0===e.length)return[];const t=new Set(e.map(M)),n=[];for(const[e,o]of Object.entries(m())){const i=L[e],[s,...r]=o;if(!i||!s||t.has(s))continue;const a=r.find(e=>t.has(e));a&&n.push({tier:e,envVar:i,from:s,to:a})}return n}function F(e,t){const n={},o=t=>{const n=(e[t]||"").trim();return n&&n!==g[t]?n:null},i=o("haiku"),s=o("sonnet"),r=o("opus"),a=new Set([i&&"haiku",s&&"sonnet",r&&"opus"].filter(Boolean)),l=resolveTierFallbacks(t).filter(e=>!a.has(e.tier));for(const e of l)n[e.envVar]=e.to;return i&&(n.ANTHROPIC_DEFAULT_HAIKU_MODEL=i),s&&(n.ANTHROPIC_DEFAULT_SONNET_MODEL=s),r&&(n.ANTHROPIC_DEFAULT_OPUS_MODEL=r,n.ANTHROPIC_MODEL=r),{modelEnv:n,opus:r,fallbacks:l}}export function ccSwitchClaudeSettings(e,t,n,o,i){const{modelEnv:s,opus:r}=F(n,o),a=u(),l=r??("string"==typeof a.model?a.model:void 0);return applyGatewayModels({env:{ANTHROPIC_BASE_URL:t,ANTHROPIC_AUTH_TOKEN:e,...s},...l?{model:l}:{}},i??[])}export class ClaudeCodeManager{static instance;settingsPath;mcpConfigPath;lastTierFallbacks=[];lastReplaced=[];constructor(){this.settingsPath=r(l(),".claude","settings.json"),this.mcpConfigPath=r(l(),".claude.json")}static getInstance(){return ClaudeCodeManager.instance||(ClaudeCodeManager.instance=new ClaudeCodeManager),ClaudeCodeManager.instance}ensureConfigDir(n){const o=a(n);e(o)||t(o,{recursive:!0})}atomicWrite(t,n){const r=`${t}.tmp`;try{o(r,n,"utf-8"),i(r,t)}catch(t){if(e(r))try{s(r)}catch{}throw t}}getSettings(){try{if(e(this.settingsPath)){const e=n(this.settingsPath,"utf-8");return JSON.parse(e)}}catch(e){c.warn("Failed to read Claude Code settings:",e),c.logError("ClaudeCodeManager.getSettings",e)}return{}}saveSettings(e){try{this.ensureConfigDir(this.settingsPath),this.atomicWrite(this.settingsPath,JSON.stringify(e,null,2))}catch(e){throw new Error(`Failed to save Claude Code settings: ${e}`)}!function(){if(!j)return;const e=j;j=null;const t=H();(t.length!==e.length||t.some(t=>!e.includes(t)))&&U(e)}()}getMCPConfig(){try{if(e(this.mcpConfigPath)){const e=n(this.mcpConfigPath,"utf-8");return JSON.parse(e)}}catch(e){c.warn("Failed to read Claude Code MCP config:",e),c.logError("ClaudeCodeManager.getMCPConfig",e)}return{}}saveMCPConfig(e){try{this.ensureConfigDir(this.mcpConfigPath),this.atomicWrite(this.mcpConfigPath,JSON.stringify(e,null,2))}catch(e){throw new Error(`Failed to save Claude Code MCP config: ${e}`)}}loadPrivateConfig(e,t,n,o){E(()=>this.writePrivateConfig(e,t,n,o))}writePrivateConfig(e,t,n,o){this.ensureOnboardingCompleted(),f();const i=u(),s=i.env||{},{env:r,...a}=i,l=this.getSettings(),{ANTHROPIC_API_KEY:c,...g}=l.env||{},m={...g},{modelEnv:p,opus:C,fallbacks:h}=F(t,n),E=D(t);this.lastReplaced=[];for(const e of MODEL_ENV_VARS){const t=m[e],n=p[e];if(void 0!==n)void 0===t||t===n||_(R(e),t,E)||this.lastReplaced.push(`${e}=${t}`),m[e]=n,v(R(e),n);else{if(void 0===t)continue;_(R(e),t,E)||this.lastReplaced.push(`${e}=${t}`),delete m[e],O(R(e))}}this.lastTierFallbacks=h.filter(e=>m[e.envVar]===e.to);const A={...l};for(const[e,t]of Object.entries(a))"model"!==e&&(e in A||(A[e]=t));A.showThinkingSummaries=!0;const P={...A,env:{...m,...Object.fromEntries(Object.entries(s).filter(([e])=>!(e in m))),ANTHROPIC_AUTH_TOKEN:e,ANTHROPIC_BASE_URL:d.getBaseUrl()}};T(d.getBaseUrl());const S=C??("string"==typeof a.model?a.model:void 0),N=l.model,M=void 0!==N&&N!==S&&!_(y,N,E);void 0===S?(delete P.model,O(y)):(P.model=S,v(y,S)),M&&this.lastReplaced.push(`model=${String(N)}`),this.saveSettings(applyGatewayModels(P,o))}ensureOnboardingCompleted(){try{const e=this.getMCPConfig();e.hasCompletedOnboarding||this.saveMCPConfig({...e,hasCompletedOnboarding:!0})}catch(e){c.warn("Failed to ensure onboarding completed:",e),c.logError("ClaudeCodeManager.ensureOnboardingCompleted",e)}}unloadPrivateConfig(){E(()=>this.removePrivateConfig())}removePrivateConfig(){const e=this.getSettings(),t=D(d.getModelsForTool("claude-code")),n=void 0!==e.model&&_(y,e.model,t);if(O(y),!e.env){if(n){const{model:t,...n}=e;this.saveSettings(n)}return}const{ANTHROPIC_AUTH_TOKEN:o,ANTHROPIC_BASE_URL:i,API_TIMEOUT_MS:s,CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:r,CLAUDE_CODE_AUTO_MODE_SERVER:a,...l}=e.env,c={...l};for(const e of MODEL_ENV_VARS)e in c&&_(R(e),c[e],t)&&delete c[e],O(R(e));const g={...applyGatewayModels({...e,env:c},[])};g.env=g.env||{},n&&delete g.model,g.env&&0===Object.keys(g.env).length&&delete g.env,this.saveSettings(g)}clearPinnedModels(e){const t=this.getSettings(),n=t.env,o=n?.ANTHROPIC_AUTH_TOKEN?Object.fromEntries(resolveTierFallbacks(e).map(e=>[e.envVar,e.to])):{},i=[];for(const e of MODEL_ENV_VARS)n&&e in n&&n[e]!==o[e]&&i.push(e);void 0!==t.model&&i.push("model");const s=Object.entries(o).some(([e,t])=>n?.[e]!==t);if(0===i.length&&!s)return[];const r={...t};if(delete r.model,n){const e={...n};for(const t of MODEL_ENV_VARS)delete e[t];Object.assign(e,o),0===Object.keys(e).length?delete r.env:r.env=e}this.saveSettings(r),O(y);for(const e of MODEL_ENV_VARS)o[e]?h(R(e),o[e],o[e]):O(R(e));return i}getLastReplaced(){return[...this.lastReplaced]}getLastTierFallbacks(){return[...this.lastTierFallbacks]}detectCurrentConfig(){try{const e=this.getSettings();return e.env&&e.env.ANTHROPIC_AUTH_TOKEN?{apiKey:e.env.ANTHROPIC_AUTH_TOKEN}:{apiKey:null}}catch{return{apiKey:null}}}getExperimentalFeature(e){const t=this.getSettings();return t.env?.[e]}setExperimentalFeature(e,t){const n=this.getSettings(),o=n.env||{},i={...n,env:{...o,[e]:t}};this.saveSettings(i)}removeExperimentalFeature(e){const t=this.getSettings();if(!t.env)return;const{[e]:n,...o}=t.env,i={...t,env:o};this.saveSettings(i)}}export const claudeCodeManager=ClaudeCodeManager.getInstance();
@@ -1 +1 @@
1
- import{spawnSync as t}from"child_process";import{closeSync as e,copyFileSync as r,createReadStream as o,createWriteStream as n,existsSync as s,mkdirSync as i,openSync as c,readFileSync as a,readSync as f,readdirSync as l,realpathSync as p,renameSync as u,statSync as d,utimesSync as m}from"fs";import{basename as h,join as g,resolve as b}from"path";import{pipeline as y}from"stream/promises";import*as E from"@iarna/toml";import{codexHome as S,toolHome as v}from"./tools/types.js";import{atomicWriteFile as x}from"./tools/backup.js";import{CLI_NAME as _}from"./brand.js";import{powerShellEnv as w}from"./powershell-env.js";export{S as codexHome};export function currentCodexProvider(){try{const t=E.parse(a(g(S(),"config.toml"),"utf-8"));return"string"==typeof t.model_provider&&t.model_provider.trim()?t.model_provider.trim():"openai"}catch{return"openai"}}let O=()=>{if("win32"===process.platform)return`${t("powershell.exe",["-NoProfile","-NonInteractive","-Command","(Get-Process -Name codex -ErrorAction SilentlyContinue).Id"],{encoding:"utf-8",windowsHide:!0,env:w()}).stdout??""}`.split(/\s+/).filter(Boolean).map(Number);const e=process.getuid?.(),r=`${t("pgrep",["-x","-i",...void 0===e?[]:["-u",String(e)],"codex"],{encoding:"utf-8"}).stdout??""}`.split(/\s+/).filter(Boolean).map(Number);if("linux"!==process.platform)return r;const o=N(S());return r.filter(t=>{let e;try{e=a(`/proc/${t}/environ`,"utf-8")}catch{return!0}const r=new Map(e.split("\0").map(t=>[t.slice(0,t.indexOf("=")),t.slice(t.indexOf("=")+1)])),n=r.get("CODEX_HOME")?.trim()||(r.get("HOME")?g(r.get("HOME"),".codex"):null);return null===n||N(n)===o})};function N(t){try{return p(t)}catch{return t}}export function setCodexProcessCheckForTests(t){O=t}export function runningCodexPids(){try{return O()}catch{return[]}}function $(t){const r=c(t,"r");try{const t=[],e=Buffer.alloc(65536);for(;;){const o=f(r,e,0,e.length,null);if(o<=0)break;const n=e.subarray(0,o).indexOf(10);if(n>=0){t.push(Buffer.from(e.subarray(0,n)));break}t.push(Buffer.from(e.subarray(0,o)))}return Buffer.concat(t).toString("utf-8")}finally{e(r)}}async function M(t,e,r){const{atime:s,mtime:i}=d(t),c=`${t}.${_}-tmp`,a=n(c);a.write(e),await y(o(t,{start:r}),a),u(c,t),m(t,s,i)}export function codexSqliteHome(){const t=S();try{const e=E.parse(a(g(t,"config.toml"),"utf-8")),r="string"==typeof e.sqlite_home?e.sqlite_home.trim():"";if(r)return"~"===r||r.startsWith("~/")?g(v(),r.slice(1)):b(t,r)}catch{}const e=process.env.CODEX_SQLITE_HOME?.trim();return e?b(e):t}function D(){const t=codexSqliteHome();if(!s(t))return null;const e=l(t).map(t=>/^state_(\d+)\.sqlite$/.exec(t)).filter(t=>!!t).sort((t,e)=>Number(e[1])-Number(t[1]));return e.length>0?g(t,e[0][0]):null}const T={threads:"id",local_thread_catalog:"thread_id"};function A(){const t=g(codexSqliteHome(),"sqlite");return s(t)?l(t).filter(t=>/\.(db|sqlite3?)$/.test(t)).map(e=>g(t,e)).sort():[]}function q(t,e,r){const o=function(t,e){return new Set(t.prepare(`PRAGMA table_info(${e})`).all().map(t=>String(t.name)))}(t,e),n=T[e];if(!o.has(n)||!o.has("model_provider"))return null;const s=o.has("host_id")?" AND host_id = 'local'":"";return t.prepare(`SELECT ${n} AS id, model_provider AS "from" FROM ${e} WHERE COALESCE(model_provider, '') NOT IN ('', ?)${s}`).all(r).map(t=>({id:String(t.id),from:String(t.from)}))}export class SessionMoveError extends Error{backupDir;constructor(t,e){super(t instanceof Error?t.message:String(t)),this.name="SessionMoveError",this.backupDir=e}}function B(t){try{t.exec("ROLLBACK")}catch{}}async function C(t){try{return function(){const t=process.emitWarning.bind(process);if(process.emitWarning.quietSqlite)return;const e=(e,...r)=>{const o=e instanceof Error?e.message:String(e);"ExperimentalWarning"===(e instanceof Error?e.name:"string"==typeof r[0]?r[0]:r[0]?.type)&&/SQLite/i.test(o)||t(e,...r)};e.quietSqlite=!0,process.emitWarning=e}(),new((await import("node:sqlite")).DatabaseSync)(t)}catch(t){return`node:sqlite unavailable (Node ${process.versions.node}; needs 22.13+): ${t instanceof Error?t.message:String(t)}`}}export const NO_STATE_DB="no state DB";export async function moveSessionsToProvider(t,e={}){const o=function(){const t=[],e=r=>{if(s(r))for(const o of l(r,{withFileTypes:!0})){const n=g(r,o.name);o.isDirectory()?e(n):o.isFile()&&o.name.endsWith(".jsonl")&&t.push(n)}};return e(g(S(),"sessions")),e(g(S(),"archived_sessions")),t}(),n=[];for(const e of o){let r,o;try{r=$(e)}catch{continue}try{o=JSON.parse(r)}catch{continue}const s=o.payload?.model_provider;"session_meta"===o.type&&"string"==typeof s&&s!==t&&(o.payload.model_provider=t,n.push({file:e,from:s,line:JSON.stringify(o),length:Buffer.byteLength(r,"utf-8")}))}const c=[D(),...A()].filter(t=>!!t);let a=c.length>0?null:NO_STATE_DB;const f=[];for(const e of c){const r=await C(e);if("string"==typeof r){a=r;break}const o=[];try{for(const n of Object.keys(T)){const s=q(r,n,t);s&&s.length>0&&o.push({db:e,table:n,rows:s})}}catch{}f.push({path:e,db:r,tables:o})}const p=f.flatMap(t=>t.tables),u=new Set(p.flatMap(t=>t.rows.map(t=>t.id))),d={target:t,scanned:o.length,moved:n.map(({file:t,from:e})=>({file:t,from:e})),dbRows:u.size,dbSkipped:a,backupDir:null},m=()=>f.forEach(t=>t.db.close());if(e.dryRun||0===n.length&&0===p.length)return m(),d;const b=g(S(),"backups",`${_}-sessions-${(new Date).toISOString().replace(/[:.]/g,"-")}`);i(b,{recursive:!0}),f.forEach(({path:t,tables:e},o)=>{if(0!==e.length)for(const e of["","-wal","-shm"])s(t+e)&&r(t+e,g(b,`${o}-${h(t)}${e}`))});const y={target:t,moved:d.moved,tables:p};x(g(b,"manifest.json"),JSON.stringify(y,null,2)+"\n");const E=f.filter(t=>t.tables.length>0),v=[];try{for(const{db:t}of E)t.exec("BEGIN IMMEDIATE"),v.push(t);for(const t of n)await M(t.file,t.line,t.length);for(const{db:e,tables:r}of E)for(const{table:o,rows:n}of r){const r=e.prepare(`UPDATE ${o} SET model_provider = ? WHERE ${T[o]} = ? AND model_provider = ?`);for(const{id:e,from:o}of n)r.run(t,e,o)}for(;v.length>0;)v.shift().exec("COMMIT")}catch(t){throw v.forEach(B),m(),new SessionMoveError(t,b)}return m(),d.backupDir=b,d}export async function undoSessionMove(t){const e=JSON.parse(a(g(t,"manifest.json"),"utf-8"));let r=0;for(const{file:t,from:o}of e.moved){if(!s(t))continue;const e=$(t),n=JSON.parse(e);n.payload&&(n.payload.model_provider=o,await M(t,JSON.stringify(n),Buffer.byteLength(e,"utf-8")),r+=1)}const o=e.tables??(e.db&&e.threads?[{db:e.db,table:"threads",rows:e.threads}]:[]),n=new Set;for(const{db:t,table:r,rows:i}of o){if(!s(t)||0===i.length||!T[r])continue;const o=await C(t);if("string"==typeof o)continue;const c=[];try{o.exec("BEGIN IMMEDIATE");const t=o.prepare(`UPDATE ${r} SET model_provider = ? WHERE ${T[r]} = ? AND model_provider = ?`);for(const{id:r,from:o}of i)Number(t.run(o,r,e.target).changes)>0&&c.push(r);o.exec("COMMIT")}catch(t){throw B(o),o.close(),t}o.close(),c.forEach(t=>n.add(t))}return{files:r,dbRows:n.size}}
1
+ import{spawnSync as t}from"child_process";import{closeSync as e,copyFileSync as o,createReadStream as r,createWriteStream as n,existsSync as s,mkdirSync as i,openSync as c,readFileSync as a,readSync as f,readdirSync as l,realpathSync as p,renameSync as u,statSync as d,utimesSync as m}from"fs";import{basename as h,join as g,resolve as b}from"path";import{pipeline as y}from"stream/promises";import*as E from"@iarna/toml";import{codexHome as S,toolHome as v}from"./tools/types.js";import{atomicWriteFile as _}from"./tools/backup.js";import{CLI_NAME as x}from"./brand.js";import{powerShellEnv as w}from"./powershell-env.js";import{columnsOf as O,openSqlite as N,rollback as M}from"./sqlite.js";export{S as codexHome};export function currentCodexProvider(){try{const t=E.parse(a(g(S(),"config.toml"),"utf-8"));return"string"==typeof t.model_provider&&t.model_provider.trim()?t.model_provider.trim():"openai"}catch{return"openai"}}let $=()=>{if("win32"===process.platform)return`${t("powershell.exe",["-NoProfile","-NonInteractive","-Command","(Get-Process -Name codex -ErrorAction SilentlyContinue).Id"],{encoding:"utf-8",windowsHide:!0,env:w()}).stdout??""}`.split(/\s+/).filter(Boolean).map(Number);const e=process.getuid?.(),o=`${t("pgrep",["-x","-i",...void 0===e?[]:["-u",String(e)],"codex"],{encoding:"utf-8"}).stdout??""}`.split(/\s+/).filter(Boolean).map(Number);if("linux"!==process.platform)return o;const r=D(S());return o.filter(t=>{let e;try{e=a(`/proc/${t}/environ`,"utf-8")}catch{return!0}const o=new Map(e.split("\0").map(t=>[t.slice(0,t.indexOf("=")),t.slice(t.indexOf("=")+1)])),n=o.get("CODEX_HOME")?.trim()||(o.get("HOME")?g(o.get("HOME"),".codex"):null);return null===n||D(n)===r})};function D(t){try{return p(t)}catch{return t}}export function setCodexProcessCheckForTests(t){$=t}export function runningCodexPids(){try{return $()}catch{return[]}}function T(t){const o=c(t,"r");try{const t=[],e=Buffer.alloc(65536);for(;;){const r=f(o,e,0,e.length,null);if(r<=0)break;const n=e.subarray(0,r).indexOf(10);if(n>=0){t.push(Buffer.from(e.subarray(0,n)));break}t.push(Buffer.from(e.subarray(0,r)))}return Buffer.concat(t).toString("utf-8")}finally{e(o)}}async function A(t,e,o){const{atime:s,mtime:i}=d(t),c=`${t}.${x}-tmp`,a=n(c);a.write(e),await y(r(t,{start:o}),a),u(c,t),m(t,s,i)}export function codexSqliteHome(){const t=S();try{const e=E.parse(a(g(t,"config.toml"),"utf-8")),o="string"==typeof e.sqlite_home?e.sqlite_home.trim():"";if(o)return"~"===o||o.startsWith("~/")?g(v(),o.slice(1)):b(t,o)}catch{}const e=process.env.CODEX_SQLITE_HOME?.trim();return e?b(e):t}function B(){const t=codexSqliteHome();if(!s(t))return null;const e=l(t).map(t=>/^state_(\d+)\.sqlite$/.exec(t)).filter(t=>!!t).sort((t,e)=>Number(e[1])-Number(t[1]));return e.length>0?g(t,e[0][0]):null}const C={threads:"id",local_thread_catalog:"thread_id"};function I(){const t=g(codexSqliteHome(),"sqlite");return s(t)?l(t).filter(t=>/\.(db|sqlite3?)$/.test(t)).map(e=>g(t,e)).sort():[]}function k(t,e,o){const r=O(t,e),n=C[e];if(!r.has(n)||!r.has("model_provider"))return null;const s=r.has("host_id")?" AND host_id = 'local'":"";return t.prepare(`SELECT ${n} AS id, model_provider AS "from" FROM ${e} WHERE COALESCE(model_provider, '') NOT IN ('', ?)${s}`).all(o).map(t=>({id:String(t.id),from:String(t.from)}))}export class SessionMoveError extends Error{backupDir;constructor(t,e){super(t instanceof Error?t.message:String(t)),this.name="SessionMoveError",this.backupDir=e}}export const NO_STATE_DB="no state DB";export async function moveSessionsToProvider(t,e={}){const r=function(){const t=[],e=o=>{if(s(o))for(const r of l(o,{withFileTypes:!0})){const n=g(o,r.name);r.isDirectory()?e(n):r.isFile()&&r.name.endsWith(".jsonl")&&t.push(n)}};return e(g(S(),"sessions")),e(g(S(),"archived_sessions")),t}(),n=[];for(const e of r){let o,r;try{o=T(e)}catch{continue}try{r=JSON.parse(o)}catch{continue}const s=r.payload?.model_provider;"session_meta"===r.type&&"string"==typeof s&&s!==t&&(r.payload.model_provider=t,n.push({file:e,from:s,line:JSON.stringify(r),length:Buffer.byteLength(o,"utf-8")}))}const c=[B(),...I()].filter(t=>!!t);let a=c.length>0?null:NO_STATE_DB;const f=[];for(const e of c){const o=await N(e);if("string"==typeof o){a=o;break}const r=[];try{for(const n of Object.keys(C)){const s=k(o,n,t);s&&s.length>0&&r.push({db:e,table:n,rows:s})}}catch{}f.push({path:e,db:o,tables:r})}const p=f.flatMap(t=>t.tables),u=new Set(p.flatMap(t=>t.rows.map(t=>t.id))),d={target:t,scanned:r.length,moved:n.map(({file:t,from:e})=>({file:t,from:e})),dbRows:u.size,dbSkipped:a,backupDir:null},m=()=>f.forEach(t=>t.db.close());if(e.dryRun||0===n.length&&0===p.length)return m(),d;const b=g(S(),"backups",`${x}-sessions-${(new Date).toISOString().replace(/[:.]/g,"-")}`);i(b,{recursive:!0}),f.forEach(({path:t,tables:e},r)=>{if(0!==e.length)for(const e of["","-wal","-shm"])s(t+e)&&o(t+e,g(b,`${r}-${h(t)}${e}`))});const y={target:t,moved:d.moved,tables:p};_(g(b,"manifest.json"),JSON.stringify(y,null,2)+"\n");const E=f.filter(t=>t.tables.length>0),v=[];try{for(const{db:t}of E)t.exec("BEGIN IMMEDIATE"),v.push(t);for(const t of n)await A(t.file,t.line,t.length);for(const{db:e,tables:o}of E)for(const{table:r,rows:n}of o){const o=e.prepare(`UPDATE ${r} SET model_provider = ? WHERE ${C[r]} = ? AND model_provider = ?`);for(const{id:e,from:r}of n)o.run(t,e,r)}for(;v.length>0;)v.shift().exec("COMMIT")}catch(t){throw v.forEach(M),m(),new SessionMoveError(t,b)}return m(),d.backupDir=b,d}export async function undoSessionMove(t){const e=JSON.parse(a(g(t,"manifest.json"),"utf-8"));let o=0;for(const{file:t,from:r}of e.moved){if(!s(t))continue;const e=T(t),n=JSON.parse(e);n.payload&&(n.payload.model_provider=r,await A(t,JSON.stringify(n),Buffer.byteLength(e,"utf-8")),o+=1)}const r=e.tables??(e.db&&e.threads?[{db:e.db,table:"threads",rows:e.threads}]:[]),n=new Set;for(const{db:t,table:o,rows:i}of r){if(!s(t)||0===i.length||!C[o])continue;const r=await N(t);if("string"==typeof r)continue;const c=[];try{r.exec("BEGIN IMMEDIATE");const t=r.prepare(`UPDATE ${o} SET model_provider = ? WHERE ${C[o]} = ? AND model_provider = ?`);for(const{id:o,from:r}of i)Number(t.run(r,o,e.target).changes)>0&&c.push(o);r.exec("COMMIT")}catch(t){throw M(r),r.close(),t}r.close(),c.forEach(t=>n.add(t))}return{files:o,dbRows:n.size}}
@@ -28,8 +28,9 @@ interface RefreshOutcome {
28
28
  * because their key differs from the saved one.
29
29
  */
30
30
  export declare function lastModelRefreshOutcome(): RefreshOutcome;
31
- /** Rewrites the menus that differ from the gateway's current list; returns what changed per tool. */
32
- export declare function refreshModelMenus(): Promise<ModelMenuChange[]>;
31
+ export declare function refreshModelMenus(options?: {
32
+ explicit?: boolean;
33
+ }): Promise<ModelMenuChange[]>;
33
34
  /** Startup hook: at most once an hour, never fails the command it rides along with. */
34
35
  export declare function runModelRefresh(args: string[], options?: {
35
36
  env?: NodeJS.ProcessEnv;
@@ -1 +1 @@
1
- import{readFileSync as e}from"fs";import{dirname as o,join as t}from"path";import r from"chalk";import{configManager as n}from"./config.js";import{i18n as s}from"./i18n.js";import{resolveModelCatalog as i}from"./model-catalog.js";import{listAdapters as l}from"./tools/registry.js";import{UserActionNeeded as f}from"./tools/types.js";import{logger as a}from"../utils/logger.js";import{resolveUpdateCachePath as c}from"./auto-update.js";import{isHelpRequest as d}from"./cli-help.js";import{brandEnvName as m}from"./brand.js";import{atomicWriteFile as u}from"./tools/backup.js";import{track as h}from"./telemetry.js";export const MODEL_REFRESH_INTERVAL_MS=36e5;export const MODEL_REFRESH_OFFLINE_RETRY_MS=6e5;const p=new Set(["setup","init","config","auth","enter","completion","update","lang","logs","refresh"]),g=["--json","--dry-run","--help","-h","--version","-v"],y=[];export function shouldSkipModelRefresh(e,o=process.env){if("1"===o[m("DISABLE_MODEL_REFRESH")])return!0;if(g.some(o=>e.includes(o))||d(e))return!0;const t=e.find(e=>!e.startsWith("-"));return void 0!==t&&p.has(t)}let M={checked:0,failed:0,offline:0,keyMismatch:[]};export function lastModelRefreshOutcome(){return{...M,keyMismatch:[...M.keyMismatch]}}export async function refreshModelMenus(){const e=new Map,o=[];y.length=0,M={checked:0,failed:0,offline:0,keyMismatch:[]};for(const t of l())if(t.refreshModelMenu&&t.listedModels)try{let r=n.getApiKeyForTool(t.name);if(!r)continue;const s=t.detectCurrentConfig().apiKey;if(s&&s!==r&&s===n.getApiKey()&&(n.clearToolApiKey(t.name),r=s),s!==r){s&&(M.keyMismatch.push(t.displayName),h(`menu-sync:${t.name}`,"skip",{detail:{reason:"key_mismatch"}}));continue}const l=t.listedModels();if(null===l)continue;e.has(r)||e.set(r,await i(r));const f=e.get(r);if(!f){M.offline++;continue}t.refreshModelMenu({apiKey:r,baseUrl:n.getBaseUrl(),models:n.getModelsForTool(t.name),settings:n.getToolSettings(t.name),catalog:f}),M.checked++;const a=t.listedModels();if(null===a){o.push({tool:t.displayName,added:[],removed:[],fromGateway:!0});continue}const c=a,d=c.filter(e=>!l.includes(e)),m=l.filter(e=>!c.includes(e));(d.length>0||m.length>0)&&o.push({tool:t.displayName,added:d,removed:m})}catch(e){M.failed++,a.logError(`modelRefresh(${t.name})`,e),h(`menu-sync:${t.name}`,e instanceof f?"skip":"fail",{error:e}),e instanceof f&&y.push(e.message)}return o}export async function runModelRefresh(n,i={}){const l=i.env??process.env,f=i.now??Date.now(),d=function(e){return t(o(c(e)),"model-refresh.json")}(l);if(!i.force){if(shouldSkipModelRefresh(n,l))return[];if(f-function(o){try{const t=JSON.parse(e(o,"utf-8")).refreshed_at;return"number"==typeof t?t:0}catch{return 0}}(d)<36e5)return[]}let m=[];try{m=await refreshModelMenus();const e=M.offline>0&&0===M.checked&&0===M.failed,o=e?f-36e5+6e5:f;e&&h("menu-sync","skip",{detail:{reason:"offline",tools:M.offline}}),u(d,JSON.stringify({refreshed_at:o})+"\n")}catch(e){a.logError("runModelRefresh",e)}const p=i.output??(e=>console.log(r.gray(e)));for(const e of y)p(e);for(const e of m){if(e.fromGateway){p(s.t("model_refresh.from_gateway",{tool:e.tool}));continue}const o=[e.added.length>0?s.t("model_refresh.added",{models:e.added.join(", ")}):"",e.removed.length>0?s.t("model_refresh.removed",{models:e.removed.join(", ")}):""].filter(Boolean);p(s.t("model_refresh.changed",{tool:e.tool,changes:o.join(";")}))}return m}
1
+ import{readFileSync as e}from"fs";import{dirname as o,join as t}from"path";import n from"chalk";import{configManager as r}from"./config.js";import{i18n as s}from"./i18n.js";import{resolveModelCatalog as i}from"./model-catalog.js";import{listAdapters as a}from"./tools/registry.js";import{UserActionNeeded as c}from"./tools/types.js";import{logger as l}from"../utils/logger.js";import{resolveUpdateCachePath as f}from"./auto-update.js";import{isHelpRequest as m}from"./cli-help.js";import{brandEnvName as d}from"./brand.js";import{atomicWriteFile as h}from"./tools/backup.js";import{track as p}from"./telemetry.js";import{CCSWITCH_SETTING as u,buildCcSwitchCard as g,hasCcSwitchCard as y,inspectCcSwitch as M,writeCcSwitchCards as w}from"./ccswitch.js";export const MODEL_REFRESH_INTERVAL_MS=36e5;export const MODEL_REFRESH_OFFLINE_RETRY_MS=6e5;const k=new Set(["setup","init","config","auth","enter","completion","update","lang","logs","refresh"]),_=["--json","--dry-run","--help","-h","--version","-v"],j=[];export function shouldSkipModelRefresh(e,o=process.env){if("1"===o[d("DISABLE_MODEL_REFRESH")])return!0;if(_.some(o=>e.includes(o))||m(e))return!0;const t=e.find(e=>!e.startsWith("-"));return void 0!==t&&k.has(t)}let E={checked:0,failed:0,offline:0,keyMismatch:[]};export function lastModelRefreshOutcome(){return{...E,keyMismatch:[...E.keyMismatch]}}export async function refreshModelMenus(e={}){const o=[],t=new Map,n=[];j.length=0,E={checked:0,failed:0,offline:0,keyMismatch:[]};for(const e of a())if(e.refreshModelMenu&&e.listedModels)try{let s=r.getApiKeyForTool(e.name);if(!s)continue;const a=e.detectCurrentConfig().apiKey;if(a&&a!==s&&a===r.getApiKey()&&(r.clearToolApiKey(e.name),s=a),e.ccSwitch&&r.getMachineSetting(e.name,u)&&(o.push({name:e.name,apiKey:s}),a!==s))continue;if(a!==s){a&&(E.keyMismatch.push(e.displayName),p(`menu-sync:${e.name}`,"skip",{detail:{reason:"key_mismatch"}}));continue}const c=e.listedModels();if(null===c)continue;t.has(s)||t.set(s,await i(s));const l=t.get(s);if(!l){E.offline++;continue}e.refreshModelMenu({apiKey:s,baseUrl:r.getBaseUrl(),models:r.getModelsForTool(e.name),settings:r.getToolSettings(e.name),catalog:l}),E.checked++;const f=e.listedModels();if(null===f){n.push({tool:e.displayName,added:[],removed:[],fromGateway:!0});continue}const m=f,d=m.filter(e=>!c.includes(e)),h=c.filter(e=>!m.includes(e));(d.length>0||h.length>0)&&n.push({tool:e.displayName,added:d,removed:h})}catch(o){E.failed++,l.logError(`modelRefresh(${e.name})`,o),p(`menu-sync:${e.name}`,o instanceof c?"skip":"fail",{error:o}),o instanceof c&&j.push(o.message)}return await async function(e,o){if(0===e.length)return;const t=await M();if(!t.ok)return void("running"===t.problem&&o&&j.push(s.t("ccswitch.refresh_running")));const n=[];for(const o of e){const e=await g(o.name,o.apiKey,r.getModelsForTool(o.name));e&&await y(e.app)&&n.push(e)}if(0!==n.length)try{await w(n),p("menu-sync:ccswitch","ok",{detail:{apps:n.map(e=>e.app),schema:t.schema}})}catch(e){l.logError("modelRefresh(ccswitch)",e),p("menu-sync:ccswitch","fail",{error:e})}}(o,Boolean(e.explicit)),n}export async function runModelRefresh(r,i={}){const a=i.env??process.env,c=i.now??Date.now(),m=function(e){return t(o(f(e)),"model-refresh.json")}(a);if(!i.force){if(shouldSkipModelRefresh(r,a))return[];if(c-function(o){try{const t=JSON.parse(e(o,"utf-8")).refreshed_at;return"number"==typeof t?t:0}catch{return 0}}(m)<36e5)return[]}let d=[];try{d=await refreshModelMenus({explicit:Boolean(i.force)});const e=E.offline>0&&0===E.checked&&0===E.failed,o=e?c-36e5+6e5:c;e&&p("menu-sync","skip",{detail:{reason:"offline",tools:E.offline}}),h(m,JSON.stringify({refreshed_at:o})+"\n")}catch(e){l.logError("runModelRefresh",e)}const u=i.output??(e=>console.log(n.gray(e)));for(const e of j)u(e);for(const e of d){if(e.fromGateway){u(s.t("model_refresh.from_gateway",{tool:e.tool}));continue}const o=[e.added.length>0?s.t("model_refresh.added",{models:e.added.join(", ")}):"",e.removed.length>0?s.t("model_refresh.removed",{models:e.removed.join(", ")}):""].filter(Boolean);u(s.t("model_refresh.changed",{tool:e.tool,changes:o.join(";")}))}return d}
@@ -1 +1 @@
1
- import{Command as e,Option as o}from"commander";import{readFileSync as s}from"fs";import{join as t,dirname as n}from"path";import{fileURLToPath as a}from"url";import{i18n as i}from"./i18n.js";import{wizard as r}from"./wizard.js";import{SUPPORTED_TOOLS as c}from"./tool-manager.js";import{DEFAULT_BASE_URL as l}from"./config.js";import{attachCommandHelp as p,helpConfiguration as m}from"./cli-help.js";import{langCommand as d,authCommand as u,doctorCommand as f,configCommand as g,statusCommand as x,refreshCommand as h}from"../commands/index.js";import{logsCommand as y}from"../commands/logs.js";import{completionCommand as $}from"../commands/completion.js";import{benchCommand as b}from"../commands/bench.js";import{updateCommand as k}from"../commands/update.js";import{upgradeCommand as _}from"../commands/upgrade.js";import{installCommand as w,listCommand as v}from"../commands/components.js";import{codexSessionsCommand as j}from"../commands/codex-sessions.js";import{sessionsExportCommand as O,sessionsListCommand as S,sessionsResumeCommand as A,sessionsShowCommand as E}from"../commands/sessions.js";import{setupCommand as G,parseUpgradeList as z,DEDICATED_KEYS as C}from"../commands/setup.js";import{baseCommand as R}from"../commands/base.js";import{usageError as B}from"./errors.js";import{requireTerminal as I}from"./confirm.js";import{brand as L,brandEnv as N,CLI_NAME as P}from"./brand.js";import{asksBeforeWriting as T}from"./write-plan.js";const U=(L().gatewayAddresses[1]??L().gatewayAddresses[0]).url,H=(L().gatewayAddresses[2]??L().gatewayAddresses[0]).url;function K(e,o){return i.t(`help.${e}`,o)}function M(e,o){return{command:e,note:K(o)}}function q(e){const o=K(e);return o===`help.${e}`?"":o}function D(e,o=[]){return{when:q(`${e}.when`),prerequisites:q(`${e}.needs`).split("\n").filter(Boolean),alternatives:o.map(([e,o])=>M(e,o))}}function F(e){return e.helpCommand("help [command]",K("help_command"))}export function buildProgram(){const L=new e;L.name(`${P}`).summary(K("root.summary")).description(K("root.description")).configureHelp(m()).allowExcessArguments(!0).optionsGroup(K("group.global_options")).helpOption("-h, --help",K("global.help")).version(function(){try{const e=n(a(import.meta.url));return JSON.parse(s(t(e,"../../package.json"),"utf-8")).version}catch{return"1.0.0"}}(),"-v, --version",K("global.version")).option("--base <url>",K("global.base")).option("--non-interactive",K("global.non_interactive")).option("--json",K("global.json")).option("-y, --yes",K("global.yes")).option("--dry-run",K("global.dry_run")).option("--no-color",K("global.no_color")),L.configureOutput({writeErr:()=>{},outputError:()=>{}}),L.showSuggestionAfterError(),L.exitOverride(e=>{throw e}),L.commandsGroup(K("group.configure"));const q=L.command("setup").summary(K("setup.summary")).description(K("setup.description")).option("--key <key>",K("setup.opt.key"));for(const e of C){const s=new o(`--${e.option} <key>`,K(`setup.opt.${e.option}`));e.hidden&&s.hideHelp(),q.addOption(s)}q.option("--1m",K("setup.opt.one_m")).option("--no-1m",K("setup.opt.no_one_m")).option("--claude-official <on|off>",K("setup.opt.claude_official")).option("--desktop-registry <on|off>",K("setup.opt.desktop_registry")).option("--force",K("setup.opt.force")).option("--install",K("setup.opt.install")).option("--no-install",K("setup.opt.no_install")).option("--upgrade <ids>",K("setup.opt.upgrade"),(e,o=[])=>[...o,e]).option("--all",K("setup.opt.all")).action(async e=>{e.key||C.some(o=>e[o.option])||(e.key=N("SETUP_KEY")?.trim()||void 0,e.fromInstaller=Boolean(e.key));const o=Boolean(e.key||C.some(o=>e[o.option])),s=void 0!==e["1m"]||void 0!==e.claudeOfficial||void 0!==e.desktopRegistry,t=i.t("errors.key_placeholder"),n=void 0===e.upgrade?void 0:z(e.upgrade);if(!(o||s||n?.length||T()))throw B(i.t("setup.usage"),`${P} setup --key ${t}`,"missing_key");if(void 0!==e.claudeOfficial&&!["on","off"].includes(String(e.claudeOfficial).toLowerCase()))throw B(i.t("setup.claude_official_invalid",{value:String(e.claudeOfficial)}),`${P} setup --claude-official on|off`,"invalid_value");if(void 0!==e.desktopRegistry&&!["on","off"].includes(String(e.desktopRegistry).toLowerCase()))throw B(i.t("setup.desktop_registry_invalid",{value:String(e.desktopRegistry)}),`${P} setup --desktop-registry on|off`,"invalid_value");await G({key:e.key,...Object.fromEntries(C.map(o=>[o.option,e[o.option]])),all:e.all,oneMillion:e["1m"],claudeOfficial:e.claudeOfficial,desktopRegistry:e.desktopRegistry,force:e.force,install:e.install,upgrade:n,fromInstaller:e.fromInstaller})}),p(q,{...D("setup",[[`${P} init`,"setup.alt.init"],[`${P} config <tool>`,"setup.alt.config"],[`${P} auth <key>`,"setup.alt.auth"]]),sections:[{title:K("setup.autodetect_title"),rows:[["Claude",K("setup.autodetect.claude")],["GPT",K("setup.autodetect.gpt")],["Grok",K("setup.autodetect.grok")],["Gemini",K("setup.autodetect.gemini")],[K("setup.autodetect.any_label"),K("setup.autodetect.any")]]}],examples:[M(`${P} setup --key sk-xxx`,"setup.ex.key"),M(`${P} setup --install --key sk-xxx`,"setup.ex.install"),M(`${P} setup --claudekey sk-a --codexkey sk-b --agykey sk-g`,"setup.ex.split"),M(`${P} setup --claudekey sk-xxx --no-install --upgrade claude-code,grok`,"setup.ex.upgrade"),M(`${P} setup --base ${U} --key sk-xxx`,"setup.ex.base")]});const J=L.command("init").summary(K("init.summary")).description(K("init.description")).action(async()=>{I(),await r.runFirstTimeSetup()});p(J,{...D("init",[[`${P} setup --key <key>`,"init.alt.setup"],[`${P}`,"init.alt.menu"]]),examples:[M(`${P} init`,"init.ex.run"),M(`${P} init --base ${U}`,"init.ex.base"),M(`${P}`,"init.ex.menu")]});const Y=L.command("auth").summary(K("auth.summary")).description(K("auth.description")).argument("[token]",K("auth.arg.token")).action(async e=>{const o=[];e&&o.push(e),await u(o)});F(Y);const Q=Y.command("revoke").description(K("auth.revoke")).action(async()=>{await u(["revoke"])});p(Q,{examples:[M(`${P} auth revoke`,"auth.ex.revoke_ask"),M(`${P} auth revoke --yes`,"auth.ex.revoke")]});const V=Y.command("reload <tool>").description(K("auth.reload")).action(async e=>{await u(["reload",e])});p(V,{examples:[M(`${P} auth reload claude-code`,"auth.ex.reload"),M(`${P} auth reload claude-code --json`,"auth.ex.reload_json")]}),p(Y,{...D("auth",[[`${P} setup --key <key>`,"auth.alt.setup"]]),examples:[M(`${P} auth`,"auth.ex.prompt"),M(`${P} auth sk-xxx --non-interactive`,"auth.ex.save"),M(`${P} auth revoke --yes`,"auth.ex.revoke"),M(`${P} auth reload claude-code`,"auth.ex.reload")]});const W=L.command("config").summary(K("config.summary")).description(K("config.description")).argument("[args...]",K("config.arg.args")).option("-f, --force",K("config.opt.force")).allowUnknownOption(!0).action(async(e=[],o={})=>{await g(o.force?[...e,"--force"]:e)});p(W,{...D("config",[[`${P} setup --force --key <key>`,"config.alt.setup"],[`${P} status`,"config.alt.status"]]),sections:[{title:K("config.subcommands_title"),rows:[["<tool>",K("config.sub.tool")],["<tool> --force",K("config.sub.tool_force")],["<tool> --non-interactive",K("config.sub.tool_non_interactive")],["<tool> remove",K("config.sub.tool_remove")],["<tool> restore",K("config.sub.tool_restore")],["<tool> backups",K("config.sub.tool_backups")],["<tool> clear-model",K("config.sub.tool_clear_model")],["tool-model list",K("config.sub.tool_model_list")],["tool-model set <tool> [slot] <model>",K("config.sub.tool_model_set")],["tool-model clear <tool>",K("config.sub.tool_model_clear")],["profile list",K("config.sub.profile_list")],["profile create <name>",K("config.sub.profile_create")],["profile use <name>",K("config.sub.profile_use")],["profile delete <name>",K("config.sub.profile_delete")],["preset list",K("config.sub.preset_list")],["preset save <name>",K("config.sub.preset_save")],["preset use <name>",K("config.sub.preset_use")],["preset delete <name>",K("config.sub.preset_delete")],["backup list",K("config.sub.backup_list")],["backup create [label]",K("config.sub.backup_create")],["backup restore <name>",K("config.sub.backup_restore")]]},{title:K("config.tools_title"),rows:Object.values(c).filter(e=>!e.hidden).map(e=>[e.name,e.displayName])}],examples:[M(`${P} config codex`,"config.ex.menu"),M(`${P} config claude-code --force`,"config.ex.force"),M(`${P} config tool-model set codex gpt-6-astra`,"config.ex.tool_model"),M(`${P} config profile create work`,"config.ex.profile"),M(`${P} config codex remove`,"config.ex.remove")]});const X=L.command("base").summary(K("base.summary")).description(K("base.description")).argument("[target]",K("base.arg.target")).action(async e=>{await R(e)});p(X,{...D("base",[[`${P} doctor`,"base.alt.doctor"],[`${P} bench`,"base.alt.bench"]]),sections:[{title:K("base.targets_title"),rows:[[K("base.target.none_term"),K("base.target.none")],[K("base.target.index_term"),K("base.target.index")],[K("base.target.url_term"),K("base.target.url")],["auto",K("base.target.auto")],["default",K("base.target.default",{url:l})]]}],examples:[M(`${P} base`,"base.ex.list"),M(`${P} base auto`,"base.ex.auto"),M(`${P} base 2`,"base.ex.index"),M(`${P} base ${U}`,"base.ex.url"),M(`${P} base default`,"base.ex.default")]}),L.commandsGroup(K("group.diagnose"));const Z=L.command("status").summary(K("status.summary")).description(K("status.description")).action(async()=>{await x()});p(Z,{...D("status",[[`${P} doctor`,"status.alt.doctor"]]),examples:[M(`${P} status`,"status.ex.show"),M(`${P} status --json`,"status.ex.json")]});const ee=L.command("doctor").summary(K("doctor.summary")).description(K("doctor.description")).option("--deep",K("doctor.opt.deep")).option("--report",K("doctor.opt.report")).action(async e=>{await f({deep:e.deep,report:e.report})});p(ee,{...D("doctor",[[`${P} base auto`,"doctor.alt.base"],[`${P} logs tail`,"doctor.alt.logs"]]),examples:[M(`${P} doctor`,"doctor.ex.run"),M(`${P} doctor --deep`,"doctor.ex.deep"),M(`${P} doctor --report`,"doctor.ex.report")]});const oe=L.command("bench").summary(K("bench.summary")).description(K("bench.description")).option("--samples <n>",K("bench.opt.samples"),"5").option("--stream",K("bench.opt.stream")).option("--model <model>",K("bench.opt.model")).action(async e=>{const o=[];e.samples&&o.push("--samples",e.samples),e.stream&&o.push("--stream"),e.model&&o.push("--model",e.model),await b(o)});p(oe,{...D("bench",[[`${P} base`,"bench.alt.base"]]),examples:[M(`${P} bench`,"bench.ex.run"),M(`${P} bench --samples 3`,"bench.ex.samples"),M(`${P} bench --stream`,"bench.ex.stream"),M(`${P} bench --stream --model gpt-6-astra`,"bench.ex.stream_model"),M(`${P} bench --json`,"bench.ex.json")]});const se=L.command("logs").summary(K("logs.summary")).description(K("logs.description")).argument("[action]",K("logs.arg.action")).argument("[file]",K("logs.arg.file")).action(async(e,o)=>{const s=[];e&&s.push(e),o&&s.push(o),await y(s)});p(se,{...D("logs",[[`${P} doctor`,"logs.alt.doctor"]]),sections:[{title:K("logs.actions_title"),rows:[["list",K("logs.action.list")],["tail [file]",K("logs.action.tail")],["path",K("logs.action.path")]]}],examples:[M(`${P} logs`,"logs.ex.list"),M(`${P} logs tail`,"logs.ex.tail"),M(`${P} logs path`,"logs.ex.path")]}),L.commandsGroup(K("group.maintain"));const te=L.command("list").summary(K("list.summary")).description(K("list.description")).option("--refresh",K("list.opt.refresh")).action(async(e={})=>{await v({refresh:e.refresh})});p(te,{...D("list",[[`${P} doctor`,"list.alt.doctor"]]),examples:[M(`${P} list`,"list.ex.all"),M(`${P} list --refresh`,"list.ex.refresh"),M(`${P} list --json`,"list.ex.json")]});const ne=L.command("install").summary(K("install.summary")).description(K("install.description")).argument("<components...>",K("install.arg.components")).option("--force",K("install.opt.force")).action(async(e,o={})=>{await w(e,{force:o.force})});p(ne,{...D("install",[[`${P} upgrade`,"install.alt.upgrade"],[`${P} setup --key ${i.t("errors.key_placeholder")}`,"install.alt.setup"]]),examples:[M(`${P} install node uv`,"install.ex.runtimes"),M(`${P} install claude-code codex`,"install.ex.clis"),M(`${P} install chatgpt`,"install.ex.app"),M(`${P} install uv --force`,"install.ex.force"),M(`${P} install node uv --yes --json`,"install.ex.json")]});const ae=L.command("upgrade").summary(K("upgrade.summary")).description(K("upgrade.description")).argument("[tools...]",K("upgrade.arg.tools")).option("--force",K("upgrade.opt.force")).action(async(e=[],o={})=>{await _(e,{force:o.force})});p(ae,{...D("upgrade",[[`${P} update`,"upgrade.alt.update"]]),examples:[M(`${P} upgrade`,"upgrade.ex.all"),M(`${P} upgrade codex agy`,"upgrade.ex.many"),M(`${P} upgrade claude-desktop`,"upgrade.ex.desktop"),M(`${P} upgrade chatgpt --force`,"upgrade.ex.force"),M(`${P} upgrade node`,"upgrade.ex.runtime")]});const ie=L.command("refresh").summary(K("refresh.summary")).description(K("refresh.description")).action(async()=>{await h()});p(ie,{...D("refresh",[[`${P} setup --key ${i.t("errors.key_placeholder")}`,"refresh.alt.setup"]]),examples:[M(`${P} refresh`,"refresh.ex.run"),M(`${P} refresh --base ${H}`,"refresh.ex.base")]});const re=L.command("update").summary(K("update.summary")).description(K("update.description")).action(async()=>{await k()});p(re,{...D("update",[[`${P} upgrade`,"update.alt.upgrade"]]),examples:[M(`${P} update`,"update.ex.check"),M(`${P} update --json`,"update.ex.json")]});const ce=L.command("codex").summary(K("codex.summary")).description(K("codex.description"));F(ce);const le=ce.command("sessions").summary(K("codex_sessions.summary")).description(K("codex_sessions.description")).option("--to <provider>",K("codex_sessions.opt.to")).option("--undo <dir>",K("codex_sessions.opt.undo")).action(async e=>{await j(e)});p(ce,{...D("codex"),examples:[M(`${P} codex sessions`,"codex_sessions.ex.move"),M(`${P} codex sessions --undo <dir>`,"codex_sessions.ex.undo")]}),p(le,{...D("codex_sessions",[[`${P} codex sessions --undo <dir>`,"codex_sessions.alt.undo"]]),examples:[M(`${P} codex sessions`,"codex_sessions.ex.move"),M(`${P} codex sessions --to custom`,"codex_sessions.ex.to"),M(`${P} codex sessions --undo <dir>`,"codex_sessions.ex.undo")]});const pe=L.command("sessions").summary(K("sessions.summary")).description(K("sessions.description"));F(pe);const me=pe.command("list",{isDefault:!0}).description(K("sessions.list")).option("--tool <tool>",K("sessions.opt.tool")).option("--dir <path>",K("sessions.opt.dir")).option("--here",K("sessions.opt.here")).option("-n, --limit <count>",K("sessions.opt.limit")).option("--all",K("sessions.opt.all")).action(async e=>{await S(e)}),de=pe.command("show <id>").description(K("sessions.show")).option("-m, --messages <count>",K("sessions.opt.messages")).action(async(e,o)=>{await E(e,o)}),ue=pe.command("resume <id>").description(K("sessions.resume")).option("--run",K("sessions.opt.run")).action(async(e,o)=>{await A(e,o)}),fe=pe.command("export <ids...>").description(K("sessions.export")).option("-o, --output <dir>",K("sessions.opt.output")).option("--tools",K("sessions.opt.tools")).action(async(e,o)=>{await O(e,o)});p(me,{examples:[M(`${P} sessions list`,"sessions.ex.list"),M(`${P} sessions list --tool codex`,"sessions.ex.codex"),M(`${P} sessions list --here --all`,"sessions.ex.here"),M(`${P} sessions list --json`,"sessions.ex.json")]}),p(de,{examples:[M(`${P} sessions show 01a0f5fe`,"sessions.ex.show"),M(`${P} sessions show 01a0f5fe -m 20`,"sessions.ex.show_more")]}),p(ue,{examples:[M(`${P} sessions resume 01a0f5fe`,"sessions.ex.resume_print"),M(`${P} sessions resume 01a0f5fe --run`,"sessions.ex.resume")]}),p(fe,{examples:[M(`${P} sessions export 01a0f5fe 7c2e9d41 -o ./sessions`,"sessions.ex.export"),M(`${P} sessions export 01a0f5fe -o ./sessions --tools`,"sessions.ex.export_tools")]}),p(pe,{...D("sessions",[[`${P} codex sessions`,"sessions.alt.codex_sessions"]]),examples:[M(`${P} sessions`,"sessions.ex.list"),M(`${P} sessions --tool codex --here`,"sessions.ex.here"),M(`${P} sessions show 01a0f5fe`,"sessions.ex.show"),M(`${P} sessions resume 01a0f5fe --run`,"sessions.ex.resume"),M(`${P} sessions export 01a0f5fe 7c2e9d41 -o ./sessions`,"sessions.ex.export")]});const ge=L.command("lang").summary(K("lang.summary")).description(K("lang.description"));F(ge);const xe=ge.command("show").description(K("lang.show")).action(async()=>{await d(["show"])}),he=ge.command("set <locale>").description(K("lang.set")).action(async e=>{await d(["set",e])}),ye=[M(`${P} lang show`,"lang.ex.show"),M(`${P} lang set en_US`,"lang.ex.set_en"),M(`${P} lang set zh_CN`,"lang.ex.set_zh")];p(ge,{...D("lang",[[`${P} enter lang`,"lang.alt.enter"]]),examples:ye}),p(xe,{examples:[ye[0],M(`${P} lang show --json`,"lang.ex.show_json")]}),p(he,{examples:ye.slice(1)});const $e=L.command("completion").summary(K("completion.summary")).description(K("completion.description")).argument("<shell>",K("completion.arg.shell")).action(async e=>{await $([e])});p($e,{...D("completion"),examples:[M(`${P} completion bash > ~/.${P}-completion.bash`,"completion.ex.bash"),M(`${P} completion zsh > ~/.${P}-completion.zsh`,"completion.ex.zsh"),M(`${P} completion fish > ~/.config/fish/completions/${P}.fish`,"completion.ex.fish")]});const be=L.command("enter").summary(K("enter.summary")).description(K("enter.description")).argument("[option]",K("enter.arg.option")).action(async e=>{if(e&&!["lang","language","apikey","api-key","models"].includes(e)||I(),e)switch(e){case"lang":case"language":await r.configLanguage();break;case"apikey":case"api-key":await r.configApiKey();break;case"models":await r.configModels();break;default:await g([e])}else await r.run()});p(be,{...D("enter",[[`${P}`,"enter.alt.menu"],[`${P} config <tool>`,"enter.alt.config"]]),sections:[{title:K("enter.options_title"),rows:[[K("enter.option.none_term"),K("enter.option.none")],["lang",K("enter.option.lang")],["apikey",K("enter.option.apikey")],["models",K("enter.option.models")],["<tool>",K("enter.option.tool")]]}],examples:[M(`${P} enter`,"enter.ex.menu"),M(`${P} enter models`,"enter.ex.models"),M(`${P} enter codex`,"enter.ex.tool")]}),F(L),L.action(async()=>{I(),await r.run()}),p(L,{examples:[M(`${P}`,"root.ex.menu"),M(`${P} setup --key sk-xxx`,"root.ex.setup"),M(`${P} doctor`,"root.ex.doctor"),M(`${P} base auto`,"root.ex.base"),M(`${P} config codex`,"root.ex.config")]});const ke=e=>{for(const o of e.commands)o.helpOption("-h, --help",K("global.help")),ke(o)};return ke(L),L}
1
+ import{Command as e,Option as o}from"commander";import{readFileSync as s}from"fs";import{join as t,dirname as n}from"path";import{fileURLToPath as a}from"url";import{i18n as i}from"./i18n.js";import{wizard as r}from"./wizard.js";import{SUPPORTED_TOOLS as c}from"./tool-manager.js";import{DEFAULT_BASE_URL as l}from"./config.js";import{attachCommandHelp as p,helpConfiguration as m}from"./cli-help.js";import{langCommand as u,authCommand as d,doctorCommand as f,configCommand as g,statusCommand as x,refreshCommand as h}from"../commands/index.js";import{logsCommand as y}from"../commands/logs.js";import{completionCommand as $}from"../commands/completion.js";import{benchCommand as b}from"../commands/bench.js";import{updateCommand as k}from"../commands/update.js";import{upgradeCommand as w}from"../commands/upgrade.js";import{installCommand as _,listCommand as v}from"../commands/components.js";import{codexSessionsCommand as j}from"../commands/codex-sessions.js";import{sessionsExportCommand as O,sessionsListCommand as S,sessionsResumeCommand as A,sessionsShowCommand as E}from"../commands/sessions.js";import{setupCommand as G,parseUpgradeList as z,DEDICATED_KEYS as C}from"../commands/setup.js";import{baseCommand as R}from"../commands/base.js";import{usageError as U}from"./errors.js";import{requireTerminal as B}from"./confirm.js";import{brand as I,brandEnv as L,CLI_NAME as N}from"./brand.js";import{asksBeforeWriting as P}from"./write-plan.js";const T=(I().gatewayAddresses[1]??I().gatewayAddresses[0]).url,H=(I().gatewayAddresses[2]??I().gatewayAddresses[0]).url;function K(e,o){return i.t(`help.${e}`,o)}function M(e,o){return{command:e,note:K(o)}}function q(e){const o=K(e);return o===`help.${e}`?"":o}function D(e,o=[]){return{when:q(`${e}.when`),prerequisites:q(`${e}.needs`).split("\n").filter(Boolean),alternatives:o.map(([e,o])=>M(e,o))}}function F(e){return e.helpCommand("help [command]",K("help_command"))}export function buildProgram(){const I=new e;I.name(`${N}`).summary(K("root.summary")).description(K("root.description")).configureHelp(m()).allowExcessArguments(!0).optionsGroup(K("group.global_options")).helpOption("-h, --help",K("global.help")).version(function(){try{const e=n(a(import.meta.url));return JSON.parse(s(t(e,"../../package.json"),"utf-8")).version}catch{return"1.0.0"}}(),"-v, --version",K("global.version")).option("--base <url>",K("global.base")).option("--non-interactive",K("global.non_interactive")).option("--json",K("global.json")).option("-y, --yes",K("global.yes")).option("--dry-run",K("global.dry_run")).option("--no-color",K("global.no_color")),I.configureOutput({writeErr:()=>{},outputError:()=>{}}),I.showSuggestionAfterError(),I.exitOverride(e=>{throw e}),I.commandsGroup(K("group.configure"));const q=I.command("setup").summary(K("setup.summary")).description(K("setup.description")).option("--key <key>",K("setup.opt.key"));for(const e of C){const s=new o(`--${e.option} <key>`,K(`setup.opt.${e.option}`));e.hidden&&s.hideHelp(),q.addOption(s)}q.option("--1m",K("setup.opt.one_m")).option("--no-1m",K("setup.opt.no_one_m")).option("--claude-official <on|off>",K("setup.opt.claude_official")).option("--desktop-registry <on|off>",K("setup.opt.desktop_registry")).option("--force",K("setup.opt.force")).option("--install",K("setup.opt.install")).option("--no-install",K("setup.opt.no_install")).option("--ccswitch",K("setup.opt.ccswitch")).option("--ccswitch-use",K("setup.opt.ccswitch_use")).option("--upgrade <ids>",K("setup.opt.upgrade"),(e,o=[])=>[...o,e]).option("--all",K("setup.opt.all")).action(async e=>{e.key||C.some(o=>e[o.option])||(e.key=L("SETUP_KEY")?.trim()||void 0,e.fromInstaller=Boolean(e.key));const o=Boolean(e.key||C.some(o=>e[o.option])),s=void 0!==e["1m"]||void 0!==e.claudeOfficial||void 0!==e.desktopRegistry,t=i.t("errors.key_placeholder"),n=void 0===e.upgrade?void 0:z(e.upgrade);if(!(o||s||n?.length||P()))throw U(i.t("setup.usage"),`${N} setup --key ${t}`,"missing_key");if(void 0!==e.claudeOfficial&&!["on","off"].includes(String(e.claudeOfficial).toLowerCase()))throw U(i.t("setup.claude_official_invalid",{value:String(e.claudeOfficial)}),`${N} setup --claude-official on|off`,"invalid_value");if(void 0!==e.desktopRegistry&&!["on","off"].includes(String(e.desktopRegistry).toLowerCase()))throw U(i.t("setup.desktop_registry_invalid",{value:String(e.desktopRegistry)}),`${N} setup --desktop-registry on|off`,"invalid_value");await G({key:e.key,...Object.fromEntries(C.map(o=>[o.option,e[o.option]])),all:e.all,oneMillion:e["1m"],claudeOfficial:e.claudeOfficial,desktopRegistry:e.desktopRegistry,force:e.force,install:e.install,upgrade:n,fromInstaller:e.fromInstaller,ccswitch:e.ccswitch,ccswitchUse:e.ccswitchUse})}),p(q,{...D("setup",[[`${N} init`,"setup.alt.init"],[`${N} config <tool>`,"setup.alt.config"],[`${N} auth <key>`,"setup.alt.auth"]]),sections:[{title:K("setup.autodetect_title"),rows:[["Claude",K("setup.autodetect.claude")],["GPT",K("setup.autodetect.gpt")],["Grok",K("setup.autodetect.grok")],["Gemini",K("setup.autodetect.gemini")],[K("setup.autodetect.any_label"),K("setup.autodetect.any")]]}],examples:[M(`${N} setup --key sk-xxx`,"setup.ex.key"),M(`${N} setup --install --key sk-xxx`,"setup.ex.install"),M(`${N} setup --claudekey sk-a --codexkey sk-b --agykey sk-g`,"setup.ex.split"),M(`${N} setup --claudekey sk-xxx --no-install --upgrade claude-code,grok`,"setup.ex.upgrade"),M(`${N} setup --base ${T} --key sk-xxx`,"setup.ex.base")]});const J=I.command("init").summary(K("init.summary")).description(K("init.description")).action(async()=>{B(),await r.runFirstTimeSetup()});p(J,{...D("init",[[`${N} setup --key <key>`,"init.alt.setup"],[`${N}`,"init.alt.menu"]]),examples:[M(`${N} init`,"init.ex.run"),M(`${N} init --base ${T}`,"init.ex.base"),M(`${N}`,"init.ex.menu")]});const Y=I.command("auth").summary(K("auth.summary")).description(K("auth.description")).argument("[token]",K("auth.arg.token")).action(async e=>{const o=[];e&&o.push(e),await d(o)});F(Y);const Q=Y.command("revoke").description(K("auth.revoke")).action(async()=>{await d(["revoke"])});p(Q,{examples:[M(`${N} auth revoke`,"auth.ex.revoke_ask"),M(`${N} auth revoke --yes`,"auth.ex.revoke")]});const V=Y.command("reload <tool>").description(K("auth.reload")).action(async e=>{await d(["reload",e])});p(V,{examples:[M(`${N} auth reload claude-code`,"auth.ex.reload"),M(`${N} auth reload claude-code --json`,"auth.ex.reload_json")]}),p(Y,{...D("auth",[[`${N} setup --key <key>`,"auth.alt.setup"]]),examples:[M(`${N} auth`,"auth.ex.prompt"),M(`${N} auth sk-xxx --non-interactive`,"auth.ex.save"),M(`${N} auth revoke --yes`,"auth.ex.revoke"),M(`${N} auth reload claude-code`,"auth.ex.reload")]});const W=I.command("config").summary(K("config.summary")).description(K("config.description")).argument("[args...]",K("config.arg.args")).option("-f, --force",K("config.opt.force")).allowUnknownOption(!0).action(async(e=[],o={})=>{await g(o.force?[...e,"--force"]:e)});p(W,{...D("config",[[`${N} setup --force --key <key>`,"config.alt.setup"],[`${N} status`,"config.alt.status"]]),sections:[{title:K("config.subcommands_title"),rows:[["<tool>",K("config.sub.tool")],["<tool> --force",K("config.sub.tool_force")],["<tool> --non-interactive",K("config.sub.tool_non_interactive")],["<tool> remove",K("config.sub.tool_remove")],["<tool> restore",K("config.sub.tool_restore")],["<tool> backups",K("config.sub.tool_backups")],["<tool> clear-model",K("config.sub.tool_clear_model")],["tool-model list",K("config.sub.tool_model_list")],["tool-model set <tool> [slot] <model>",K("config.sub.tool_model_set")],["tool-model clear <tool>",K("config.sub.tool_model_clear")],["profile list",K("config.sub.profile_list")],["profile create <name>",K("config.sub.profile_create")],["profile use <name>",K("config.sub.profile_use")],["profile delete <name>",K("config.sub.profile_delete")],["preset list",K("config.sub.preset_list")],["preset save <name>",K("config.sub.preset_save")],["preset use <name>",K("config.sub.preset_use")],["preset delete <name>",K("config.sub.preset_delete")],["backup list",K("config.sub.backup_list")],["backup create [label]",K("config.sub.backup_create")],["backup restore <name>",K("config.sub.backup_restore")]]},{title:K("config.tools_title"),rows:Object.values(c).filter(e=>!e.hidden).map(e=>[e.name,e.displayName])}],examples:[M(`${N} config codex`,"config.ex.menu"),M(`${N} config claude-code --force`,"config.ex.force"),M(`${N} config tool-model set codex gpt-6-astra`,"config.ex.tool_model"),M(`${N} config profile create work`,"config.ex.profile"),M(`${N} config codex remove`,"config.ex.remove")]});const X=I.command("base").summary(K("base.summary")).description(K("base.description")).argument("[target]",K("base.arg.target")).action(async e=>{await R(e)});p(X,{...D("base",[[`${N} doctor`,"base.alt.doctor"],[`${N} bench`,"base.alt.bench"]]),sections:[{title:K("base.targets_title"),rows:[[K("base.target.none_term"),K("base.target.none")],[K("base.target.index_term"),K("base.target.index")],[K("base.target.url_term"),K("base.target.url")],["auto",K("base.target.auto")],["default",K("base.target.default",{url:l})]]}],examples:[M(`${N} base`,"base.ex.list"),M(`${N} base auto`,"base.ex.auto"),M(`${N} base 2`,"base.ex.index"),M(`${N} base ${T}`,"base.ex.url"),M(`${N} base default`,"base.ex.default")]}),I.commandsGroup(K("group.diagnose"));const Z=I.command("status").summary(K("status.summary")).description(K("status.description")).action(async()=>{await x()});p(Z,{...D("status",[[`${N} doctor`,"status.alt.doctor"]]),examples:[M(`${N} status`,"status.ex.show"),M(`${N} status --json`,"status.ex.json")]});const ee=I.command("doctor").summary(K("doctor.summary")).description(K("doctor.description")).option("--deep",K("doctor.opt.deep")).option("--report",K("doctor.opt.report")).action(async e=>{await f({deep:e.deep,report:e.report})});p(ee,{...D("doctor",[[`${N} base auto`,"doctor.alt.base"],[`${N} logs tail`,"doctor.alt.logs"]]),examples:[M(`${N} doctor`,"doctor.ex.run"),M(`${N} doctor --deep`,"doctor.ex.deep"),M(`${N} doctor --report`,"doctor.ex.report")]});const oe=I.command("bench").summary(K("bench.summary")).description(K("bench.description")).option("--samples <n>",K("bench.opt.samples"),"5").option("--stream",K("bench.opt.stream")).option("--model <model>",K("bench.opt.model")).action(async e=>{const o=[];e.samples&&o.push("--samples",e.samples),e.stream&&o.push("--stream"),e.model&&o.push("--model",e.model),await b(o)});p(oe,{...D("bench",[[`${N} base`,"bench.alt.base"]]),examples:[M(`${N} bench`,"bench.ex.run"),M(`${N} bench --samples 3`,"bench.ex.samples"),M(`${N} bench --stream`,"bench.ex.stream"),M(`${N} bench --stream --model gpt-6-astra`,"bench.ex.stream_model"),M(`${N} bench --json`,"bench.ex.json")]});const se=I.command("logs").summary(K("logs.summary")).description(K("logs.description")).argument("[action]",K("logs.arg.action")).argument("[file]",K("logs.arg.file")).action(async(e,o)=>{const s=[];e&&s.push(e),o&&s.push(o),await y(s)});p(se,{...D("logs",[[`${N} doctor`,"logs.alt.doctor"]]),sections:[{title:K("logs.actions_title"),rows:[["list",K("logs.action.list")],["tail [file]",K("logs.action.tail")],["path",K("logs.action.path")]]}],examples:[M(`${N} logs`,"logs.ex.list"),M(`${N} logs tail`,"logs.ex.tail"),M(`${N} logs path`,"logs.ex.path")]}),I.commandsGroup(K("group.maintain"));const te=I.command("list").summary(K("list.summary")).description(K("list.description")).option("--refresh",K("list.opt.refresh")).action(async(e={})=>{await v({refresh:e.refresh})});p(te,{...D("list",[[`${N} doctor`,"list.alt.doctor"]]),examples:[M(`${N} list`,"list.ex.all"),M(`${N} list --refresh`,"list.ex.refresh"),M(`${N} list --json`,"list.ex.json")]});const ne=I.command("install").summary(K("install.summary")).description(K("install.description")).argument("<components...>",K("install.arg.components")).option("--force",K("install.opt.force")).action(async(e,o={})=>{await _(e,{force:o.force})});p(ne,{...D("install",[[`${N} upgrade`,"install.alt.upgrade"],[`${N} setup --key ${i.t("errors.key_placeholder")}`,"install.alt.setup"]]),examples:[M(`${N} install node uv`,"install.ex.runtimes"),M(`${N} install claude-code codex`,"install.ex.clis"),M(`${N} install chatgpt`,"install.ex.app"),M(`${N} install uv --force`,"install.ex.force"),M(`${N} install node uv --yes --json`,"install.ex.json")]});const ae=I.command("upgrade").summary(K("upgrade.summary")).description(K("upgrade.description")).argument("[tools...]",K("upgrade.arg.tools")).option("--force",K("upgrade.opt.force")).action(async(e=[],o={})=>{await w(e,{force:o.force})});p(ae,{...D("upgrade",[[`${N} update`,"upgrade.alt.update"]]),examples:[M(`${N} upgrade`,"upgrade.ex.all"),M(`${N} upgrade codex agy`,"upgrade.ex.many"),M(`${N} upgrade claude-desktop`,"upgrade.ex.desktop"),M(`${N} upgrade chatgpt --force`,"upgrade.ex.force"),M(`${N} upgrade node`,"upgrade.ex.runtime")]});const ie=I.command("refresh").summary(K("refresh.summary")).description(K("refresh.description")).action(async()=>{await h()});p(ie,{...D("refresh",[[`${N} setup --key ${i.t("errors.key_placeholder")}`,"refresh.alt.setup"]]),examples:[M(`${N} refresh`,"refresh.ex.run"),M(`${N} refresh --base ${H}`,"refresh.ex.base")]});const re=I.command("update").summary(K("update.summary")).description(K("update.description")).action(async()=>{await k()});p(re,{...D("update",[[`${N} upgrade`,"update.alt.upgrade"]]),examples:[M(`${N} update`,"update.ex.check"),M(`${N} update --json`,"update.ex.json")]});const ce=I.command("codex").summary(K("codex.summary")).description(K("codex.description"));F(ce);const le=ce.command("sessions").summary(K("codex_sessions.summary")).description(K("codex_sessions.description")).option("--to <provider>",K("codex_sessions.opt.to")).option("--undo <dir>",K("codex_sessions.opt.undo")).action(async e=>{await j(e)});p(ce,{...D("codex"),examples:[M(`${N} codex sessions`,"codex_sessions.ex.move"),M(`${N} codex sessions --undo <dir>`,"codex_sessions.ex.undo")]}),p(le,{...D("codex_sessions",[[`${N} codex sessions --undo <dir>`,"codex_sessions.alt.undo"]]),examples:[M(`${N} codex sessions`,"codex_sessions.ex.move"),M(`${N} codex sessions --to custom`,"codex_sessions.ex.to"),M(`${N} codex sessions --undo <dir>`,"codex_sessions.ex.undo")]});const pe=I.command("sessions").summary(K("sessions.summary")).description(K("sessions.description"));F(pe);const me=pe.command("list",{isDefault:!0}).description(K("sessions.list")).option("--tool <tool>",K("sessions.opt.tool")).option("--dir <path>",K("sessions.opt.dir")).option("--here",K("sessions.opt.here")).option("-n, --limit <count>",K("sessions.opt.limit")).option("--all",K("sessions.opt.all")).action(async e=>{await S(e)}),ue=pe.command("show <id>").description(K("sessions.show")).option("-m, --messages <count>",K("sessions.opt.messages")).action(async(e,o)=>{await E(e,o)}),de=pe.command("resume <id>").description(K("sessions.resume")).option("--run",K("sessions.opt.run")).action(async(e,o)=>{await A(e,o)}),fe=pe.command("export <ids...>").description(K("sessions.export")).option("-o, --output <dir>",K("sessions.opt.output")).option("--tools",K("sessions.opt.tools")).action(async(e,o)=>{await O(e,o)});p(me,{examples:[M(`${N} sessions list`,"sessions.ex.list"),M(`${N} sessions list --tool codex`,"sessions.ex.codex"),M(`${N} sessions list --here --all`,"sessions.ex.here"),M(`${N} sessions list --json`,"sessions.ex.json")]}),p(ue,{examples:[M(`${N} sessions show 01a0f5fe`,"sessions.ex.show"),M(`${N} sessions show 01a0f5fe -m 20`,"sessions.ex.show_more")]}),p(de,{examples:[M(`${N} sessions resume 01a0f5fe`,"sessions.ex.resume_print"),M(`${N} sessions resume 01a0f5fe --run`,"sessions.ex.resume")]}),p(fe,{examples:[M(`${N} sessions export 01a0f5fe 7c2e9d41 -o ./sessions`,"sessions.ex.export"),M(`${N} sessions export 01a0f5fe -o ./sessions --tools`,"sessions.ex.export_tools")]}),p(pe,{...D("sessions",[[`${N} codex sessions`,"sessions.alt.codex_sessions"]]),examples:[M(`${N} sessions`,"sessions.ex.list"),M(`${N} sessions --tool codex --here`,"sessions.ex.here"),M(`${N} sessions show 01a0f5fe`,"sessions.ex.show"),M(`${N} sessions resume 01a0f5fe --run`,"sessions.ex.resume"),M(`${N} sessions export 01a0f5fe 7c2e9d41 -o ./sessions`,"sessions.ex.export")]});const ge=I.command("lang").summary(K("lang.summary")).description(K("lang.description"));F(ge);const xe=ge.command("show").description(K("lang.show")).action(async()=>{await u(["show"])}),he=ge.command("set <locale>").description(K("lang.set")).action(async e=>{await u(["set",e])}),ye=[M(`${N} lang show`,"lang.ex.show"),M(`${N} lang set en_US`,"lang.ex.set_en"),M(`${N} lang set zh_CN`,"lang.ex.set_zh")];p(ge,{...D("lang",[[`${N} enter lang`,"lang.alt.enter"]]),examples:ye}),p(xe,{examples:[ye[0],M(`${N} lang show --json`,"lang.ex.show_json")]}),p(he,{examples:ye.slice(1)});const $e=I.command("completion").summary(K("completion.summary")).description(K("completion.description")).argument("<shell>",K("completion.arg.shell")).action(async e=>{await $([e])});p($e,{...D("completion"),examples:[M(`${N} completion bash > ~/.${N}-completion.bash`,"completion.ex.bash"),M(`${N} completion zsh > ~/.${N}-completion.zsh`,"completion.ex.zsh"),M(`${N} completion fish > ~/.config/fish/completions/${N}.fish`,"completion.ex.fish")]});const be=I.command("enter").summary(K("enter.summary")).description(K("enter.description")).argument("[option]",K("enter.arg.option")).action(async e=>{if(e&&!["lang","language","apikey","api-key","models"].includes(e)||B(),e)switch(e){case"lang":case"language":await r.configLanguage();break;case"apikey":case"api-key":await r.configApiKey();break;case"models":await r.configModels();break;default:await g([e])}else await r.run()});p(be,{...D("enter",[[`${N}`,"enter.alt.menu"],[`${N} config <tool>`,"enter.alt.config"]]),sections:[{title:K("enter.options_title"),rows:[[K("enter.option.none_term"),K("enter.option.none")],["lang",K("enter.option.lang")],["apikey",K("enter.option.apikey")],["models",K("enter.option.models")],["<tool>",K("enter.option.tool")]]}],examples:[M(`${N} enter`,"enter.ex.menu"),M(`${N} enter models`,"enter.ex.models"),M(`${N} enter codex`,"enter.ex.tool")]}),F(I),I.action(async()=>{B(),await r.run()}),p(I,{examples:[M(`${N}`,"root.ex.menu"),M(`${N} setup --key sk-xxx`,"root.ex.setup"),M(`${N} doctor`,"root.ex.doctor"),M(`${N} base auto`,"root.ex.base"),M(`${N} config codex`,"root.ex.config")]});const ke=e=>{for(const o of e.commands)o.helpOption("-h, --help",K("global.help")),ke(o)};return ke(I),I}
@@ -0,0 +1,21 @@
1
+ /**
2
+ * node:sqlite (Node 22.13+ without a flag) for the few places that edit another app's
3
+ * SQLite database in place: Codex's state DB (codex-sessions.ts) and CC Switch's
4
+ * provider list (ccswitch.ts). Node 20 has no node:sqlite: callers get the reason back
5
+ * and skip, they never fall back to rewriting the file themselves (WAL databases).
6
+ */
7
+ export type SqliteDb = {
8
+ prepare(sql: string): {
9
+ all(...p: unknown[]): unknown[];
10
+ run(...p: unknown[]): {
11
+ changes: number | bigint;
12
+ };
13
+ };
14
+ exec(sql: string): void;
15
+ close(): void;
16
+ };
17
+ /** Open `path`, or say why node:sqlite can't be used here (a string). */
18
+ export declare function openSqlite(path: string): Promise<SqliteDb | string>;
19
+ /** Column names of `table` (empty when it doesn't exist). */
20
+ export declare function columnsOf(db: SqliteDb, table: string): Set<string>;
21
+ export declare function rollback(db: SqliteDb): void;
@@ -0,0 +1 @@
1
+ export async function openSqlite(e){try{return function(){const e=process.emitWarning.bind(process);if(process.emitWarning.quietSqlite)return;const n=(n,...t)=>{const r=n instanceof Error?n.message:String(n);"ExperimentalWarning"===(n instanceof Error?n.name:"string"==typeof t[0]?t[0]:t[0]?.type)&&/SQLite/i.test(r)||e(n,...t)};n.quietSqlite=!0,process.emitWarning=n}(),new((await import("node:sqlite")).DatabaseSync)(e)}catch(e){return`node:sqlite unavailable (Node ${process.versions.node}; needs 22.13+): ${e instanceof Error?e.message:String(e)}`}}export function columnsOf(e,n){return new Set(e.prepare(`PRAGMA table_info(${n})`).all().map(e=>e.name))}export function rollback(e){try{e.exec("ROLLBACK")}catch{}}
@@ -77,6 +77,8 @@ export declare class ToolManager {
77
77
  takeOver?: boolean;
78
78
  }): Promise<void>;
79
79
  private applyPrivateConfigNow;
80
+ /** Tools that can go into CC Switch as a card (adapters with `ccSwitch`). */
81
+ supportsCcSwitch(toolName: string): boolean;
80
82
  /** Post-apply follow-ups the adapter wants shown to the user (may be empty). */
81
83
  applyNotes(toolName: string): ApplyNote[];
82
84
  /**
@@ -1 +1 @@
1
- import{execSync as t,spawnSync as o}from"child_process";import{i18n as n}from"./i18n.js";import e from"inquirer";import r from"chalk";import{canPrompt as i,shouldAutoConfirm as l}from"./runtime-options.js";import{logger as a}from"../utils/logger.js";import{configManager as s,savedApiKeys as c}from"./config.js";import{getAdapter as d,listAdapters as p,TOOL_ADAPTERS as u}from"./tools/registry.js";import{backupBeforeWrite as m,listBackups as f,restoreBackup as h}from"./tools/backup.js";import{existsSync as g,rmSync as w}from"fs";import{dirname as P,join as y}from"path";import{toolHome as v}from"./tools/types.js";import{stringWidth as $}from"../utils/string-width.js";import{resolveModelCatalog as T}from"./model-catalog.js";import{compareVersions as k,getToolMinVersion as C}from"./model-registry.js";import{findInstalls as E,forgetInstalls as O,installLabel as _,mirrorInstallCommand as S,npmMirrorInstallCommand as N,npmMirrorVersion as j}from"./tools/tool-installs.js";import{mirrorInstall as M}from"./tool-upgrade.js";import{upgradeApp as U}from"./app-update.js";import{CLI_NAME as b}from"./brand.js";import{track as x,trackStep as I}from"./telemetry.js";import{addUserPathDir as R,broadcastEnvChange as F}from"./windows-env.js";export{k as compareVersions};function L(t){const o=u[t];return{name:o.name,command:o.command,installCommand:o.installCommand,configPath:o.configPath,displayName:o.displayName,...o.hidden?{hidden:!0}:{},...o.isInstalled?{gui:!0}:{}}}export const SUPPORTED_TOOLS=Object.fromEntries(Object.keys(u).map(t=>[t,L(t)]));export class ToolManager{static instance;constructor(){}static getInstance(){return ToolManager.instance||(ToolManager.instance=new ToolManager),ToolManager.instance}isToolInstalled(t){if(!SUPPORTED_TOOLS[t])return!1;const o=d(t);if(o?.isInstalled)try{return o.isInstalled()}catch{return!1}return this.isOnPath(t)||null!==this.nativeLauncher(t)}isOnPath(o){const n=SUPPORTED_TOOLS[o];if(!n)return!1;try{const o="win32"===process.platform?`where ${n.command}`:`which ${n.command}`;return t(o,{stdio:"pipe"}),!0}catch{return!1}}nativeLauncher(t){const o=d(t),n=o?.installSpec?.native?.binDir;if(!o||!n)return null;const e="win32"===process.platform?`${o.command}.exe`:o.command,r=y(v(),...n,e);return g(r)?r:null}ensureNativeOnPath(t){if("win32"!==process.platform||this.isOnPath(t))return null;const o=this.nativeLauncher(t);if(!o)return null;const n=P(o);try{if(!R(n))return null}catch(o){return a.logError(`ensureNativeOnPath: ${t}`,o),null}return F(),process.env.Path=`${process.env.Path??""};${n}`,n}addToPath(t){try{if("win32"===process.platform){if(!R(t))return!1;F(),process.env.Path=`${process.env.Path??""};${t}`}else process.env.PATH=`${process.env.PATH??""}:${t}`;return!0}catch(o){return a.logError(`addToPath: ${t}`,o),!1}}async installTool(t){return I(`install:${t}`,()=>this.installToolNow(t))}async installToolNow(o){const a=SUPPORTED_TOOLS[o];if(!a)throw new Error(`Unknown tool: ${o}`);const s=d(o)?.appInstaller;if(s&&!s.blocker()){const t=await U(o,{install:!0});if("failed"===t.result||"unavailable"===t.result)throw new Error(`Failed to install ${a.displayName}`);return}const c=d(o)?.installSpec;if(c&&(c.mirrorScript||c.npmPackage)){const t=S(c),e={installed:()=>this.isToolInstalled(o),expectedPaths:c.native?[y(v(),...c.native.binDir,"win32"===process.platform?`${c.command}.exe`:c.command)]:[],addToPath:t=>this.addToPath(t)};if(await M(c,e))return O(),void console.log(r.green("√ "+n.t("wizard.tool_installed")));throw console.log(r.red("× "+n.t("wizard.install_failed"))),console.log(r.yellow(" ! "+n.t("install.manual_command",{tool:a.displayName,command:t}))),c.mirrorScript&&c.npmPackage&&console.log(r.yellow(" ! "+n.t("install.manual_npm",{command:N(c,await j(c))}))),new Error(`Failed to install ${a.displayName}`)}const p=a.installCommand;console.log(r.gray("$ ")+r.white(p));try{return t(p,{stdio:"inherit"}),O(),void console.log(r.green("√ "+n.t("wizard.tool_installed")))}catch(t){if(console.log(r.red("× "+n.t("wizard.install_failed"))),!/EACCES|EPERM|permission denied/i.test(`${t?.message??""}${t?.stderr??""}`)&&243!==t?.status&&!p.startsWith("npm "))throw new Error(`Failed to install ${a.displayName}: ${t}`);console.log(r.yellow(" ! "+("win32"===process.platform?n.t("install.permission_windows",{command:p}):n.t("install.permission_unix",{command:p}))))}const{action:u}=!i()||l()?{action:"continue"}:await e.prompt([{type:"list",name:"action",message:n.t("install.what_next"),choices:[{name:n.t("install.installed_continue"),value:"continue"},{name:n.t("install.cancel_install"),value:"cancel"}]}]);if("cancel"===u)throw new Error(n.t("install.user_cancelled"));if(O(),!this.isToolInstalled(o))throw console.log(r.red("× "+n.t("install.still_not_installed",{tool:a.displayName}))),new Error(`${a.displayName} is not installed`);console.log(r.green("√ "+n.t("install.verified_success",{tool:a.displayName})))}getToolConfig(t){const o=d(t);if(!o)throw new Error(`Unknown tool: ${t}`);try{return o.getConfig()}catch(o){return a.warn(`Failed to read config for ${t}:`,o),a.logError(`ToolManager.getToolConfig(${t})`,o),null}}updateToolConfig(t,o){const n=d(t);if(!n)throw new Error(`Unknown tool: ${t}`);if(!n.updateConfig)throw new Error(`Tool ${t} does not support raw config updates`);n.updateConfig(o)}forceResetConfig(t){const o=d(t);if(!o)throw new Error(`Unknown tool: ${t}`);const n=o.forceResetPaths?o.forceResetPaths():this.backupPathsFor(o),e=[];for(const t of n)g(t)&&(m(t),w(t,{force:!0}),e.push(t));return e}loadPrivateConfig(t,o,n,e,r={}){const i=d(t);if(!i)throw new Error(`Unknown tool: ${t}`);r.force&&this.forceResetConfig(t),i.loadPrivateConfig({apiKey:o,baseUrl:s.getBaseUrl(),models:n,settings:s.getToolSettings(t),...e?{catalog:e}:{},...r.takeOver?{takeOver:!0}:{}})}async applyPrivateConfig(t,o,n,e={}){const r=this.installedVersion(t);return I(`apply:${t}`,()=>this.applyPrivateConfigNow(t,o,n,e),{...r?{tool_version:r}:{},...e.force?{force:!0}:{}})}async applyPrivateConfigNow(t,o,n,e){const r=d(t);if(!r)throw new Error(`Unknown tool: ${t}`);const i=r.wantsModelCatalog?await T(o):null,{force:l,takeOver:a}=e;l||a?this.loadPrivateConfig(t,o,n,i??void 0,{force:l,takeOver:a}):i?this.loadPrivateConfig(t,o,n,i):this.loadPrivateConfig(t,o,n)}applyNotes(t){const o=d(t);if(!o)return[];const e=[];try{o.applyNotes&&e.push(...o.applyNotes())}catch(o){a.logError(`ToolManager.applyNotes(${t})`,o)}const r=this.outdatedVersion(t);if(r){e.push({kind:"action",text:n.t("tools.version_outdated",{current:r.current,min:r.min,upgrade:o.installSpec?`${b} upgrade ${t}`:o.upgradeCommand||o.installCommand})});for(const t of o.upgradeHints?.(r.min)??[])e.push({kind:"action",text:t})}const i=o.installSpec?E(o.installSpec):[];return i.length>1&&e.push({kind:"action",text:n.t("upgrade.duplicates_note",{count:String(i.length),active:_(i[0]),others:i.slice(1).map(_).join("、"),tool:t})}),e}printApplied(t,o=16){const n=SUPPORTED_TOOLS[t]?.displayName??t,e=this.applyNotes(t);for(const t of e.filter(t=>"detail"===t.kind))a.record(`${n}: ${t.text}`);const i=e.filter(t=>"summary"===t.kind).map(t=>t.text).join(";"),l=" ".repeat(Math.max(1,o-$(n)));console.log(r.green("√ "+n)+(i?l+i:""));for(const t of e.filter(t=>"action"===t.kind))console.log(r.yellow(" ! "+t.text))}installedVersion(t){const n=d(t);if(!n)return null;if(n.installSpec)return E(n.installSpec)[0]?.version??null;if(n.installedVersion)try{return n.installedVersion()}catch(o){return a.logError(`ToolManager.installedVersion(${t})`,o),null}if(n.isInstalled)return null;try{const t={encoding:"utf-8",timeout:1e4,windowsHide:!0,stdio:["ignore","pipe","pipe"]},e=`${("win32"===process.platform?o(`${n.command} --version`,{...t,shell:!0}):o(n.command,["--version"],t)).stdout??""}`.match(/(\d+)\.(\d+)\.(\d+)/);return e?e[0]:null}catch{return null}}outdatedVersion(t){const o=C(t);if(!o)return null;const n=this.installedVersion(t);return n&&k(n,o)<0?{current:n,min:o}:null}unloadPrivateConfig(t){const o=d(t);if(!o)throw new Error(`Unknown tool: ${t}`);try{o.unloadPrivateConfig({savedKeys:c()}),x(`remove:${t}`,"ok")}catch(o){throw x(`remove:${t}`,"fail",{error:o}),o}let e=[];try{e=o.unloadNotes?.()??[]}catch(o){a.logError(`ToolManager.unloadNotes(${t})`,o)}return e.length>0?e:[{kind:"action",text:n.t("config.reopen_hint",{tool:o.displayName})}]}async clearPinnedModels(t){const o=d(t);if(!o)throw new Error(`Unknown tool: ${t}`);if(s.setToolModel(t,null),!o.clearPinnedModels)return[];const n=s.getApiKeyForTool(t),e=o.wantsModelCatalog&&n?await T(n):null;return o.clearPinnedModels(e??void 0)}supportsClearPinnedModels(t){return Boolean(d(t)?.clearPinnedModels)}hasPendingElevation(t){return Boolean(d(t)?.pendingElevation?.())}holdsOurConfig(t){const o=d(t);if(!o)return!1;const n=c();return o.holdsOurConfig?o.holdsOurConfig(n):Boolean(o.detectCurrentConfig().apiKey)}detectCurrentConfig(t){const o=d(t);if(!o)throw new Error(`Unknown tool: ${t}`);return o.detectCurrentConfig()}backupPathsFor(t){return t.backupPaths?t.backupPaths():[t.configPath]}listToolBackups(t){const o=d(t);if(!o)throw new Error(`Unknown tool: ${t}`);return this.backupPathsFor(o).map(t=>({file:t,backups:f(t)}))}restorePrivateConfig(t){const o=d(t);if(!o)throw new Error(`Unknown tool: ${t}`);return this.backupPathsFor(o).map(t=>({file:t,result:h(t)}))}getInstalledTools(){return Object.keys(SUPPORTED_TOOLS).filter(t=>this.isToolInstalled(t))}getSupportedTools(){return p().filter(t=>!t.hidden).map(t=>L(t.name))}isGitInstalled(){try{const o="win32"===process.platform?"where git":"which git";return t(o,{stdio:"pipe"}),!0}catch{return!1}}}export const toolManager=ToolManager.getInstance();
1
+ import{execSync as t,spawnSync as o}from"child_process";import{i18n as n}from"./i18n.js";import e from"inquirer";import r from"chalk";import{canPrompt as i,shouldAutoConfirm as l}from"./runtime-options.js";import{logger as a}from"../utils/logger.js";import{configManager as s,savedApiKeys as c}from"./config.js";import{getAdapter as d,listAdapters as p,TOOL_ADAPTERS as u}from"./tools/registry.js";import{backupBeforeWrite as m,listBackups as f,restoreBackup as h}from"./tools/backup.js";import{existsSync as g,rmSync as w}from"fs";import{dirname as P,join as y}from"path";import{toolHome as v}from"./tools/types.js";import{stringWidth as $}from"../utils/string-width.js";import{resolveModelCatalog as T}from"./model-catalog.js";import{compareVersions as C,getToolMinVersion as k}from"./model-registry.js";import{findInstalls as E,forgetInstalls as O,installLabel as S,mirrorInstallCommand as _,npmMirrorInstallCommand as N,npmMirrorVersion as j}from"./tools/tool-installs.js";import{mirrorInstall as M}from"./tool-upgrade.js";import{upgradeApp as U}from"./app-update.js";import{CLI_NAME as b}from"./brand.js";import{track as x,trackStep as I}from"./telemetry.js";import{addUserPathDir as R,broadcastEnvChange as F}from"./windows-env.js";export{C as compareVersions};function L(t){const o=u[t];return{name:o.name,command:o.command,installCommand:o.installCommand,configPath:o.configPath,displayName:o.displayName,...o.hidden?{hidden:!0}:{},...o.isInstalled?{gui:!0}:{}}}export const SUPPORTED_TOOLS=Object.fromEntries(Object.keys(u).map(t=>[t,L(t)]));export class ToolManager{static instance;constructor(){}static getInstance(){return ToolManager.instance||(ToolManager.instance=new ToolManager),ToolManager.instance}isToolInstalled(t){if(!SUPPORTED_TOOLS[t])return!1;const o=d(t);if(o?.isInstalled)try{return o.isInstalled()}catch{return!1}return this.isOnPath(t)||null!==this.nativeLauncher(t)}isOnPath(o){const n=SUPPORTED_TOOLS[o];if(!n)return!1;try{const o="win32"===process.platform?`where ${n.command}`:`which ${n.command}`;return t(o,{stdio:"pipe"}),!0}catch{return!1}}nativeLauncher(t){const o=d(t),n=o?.installSpec?.native?.binDir;if(!o||!n)return null;const e="win32"===process.platform?`${o.command}.exe`:o.command,r=y(v(),...n,e);return g(r)?r:null}ensureNativeOnPath(t){if("win32"!==process.platform||this.isOnPath(t))return null;const o=this.nativeLauncher(t);if(!o)return null;const n=P(o);try{if(!R(n))return null}catch(o){return a.logError(`ensureNativeOnPath: ${t}`,o),null}return F(),process.env.Path=`${process.env.Path??""};${n}`,n}addToPath(t){try{if("win32"===process.platform){if(!R(t))return!1;F(),process.env.Path=`${process.env.Path??""};${t}`}else process.env.PATH=`${process.env.PATH??""}:${t}`;return!0}catch(o){return a.logError(`addToPath: ${t}`,o),!1}}async installTool(t){return I(`install:${t}`,()=>this.installToolNow(t))}async installToolNow(o){const a=SUPPORTED_TOOLS[o];if(!a)throw new Error(`Unknown tool: ${o}`);const s=d(o)?.appInstaller;if(s&&!s.blocker()){const t=await U(o,{install:!0});if("failed"===t.result||"unavailable"===t.result)throw new Error(`Failed to install ${a.displayName}`);return}const c=d(o)?.installSpec;if(c&&(c.mirrorScript||c.npmPackage)){const t=_(c),e={installed:()=>this.isToolInstalled(o),expectedPaths:c.native?[y(v(),...c.native.binDir,"win32"===process.platform?`${c.command}.exe`:c.command)]:[],addToPath:t=>this.addToPath(t)};if(await M(c,e))return O(),void console.log(r.green("√ "+n.t("wizard.tool_installed")));throw console.log(r.red("× "+n.t("wizard.install_failed"))),console.log(r.yellow(" ! "+n.t("install.manual_command",{tool:a.displayName,command:t}))),c.mirrorScript&&c.npmPackage&&console.log(r.yellow(" ! "+n.t("install.manual_npm",{command:N(c,await j(c))}))),new Error(`Failed to install ${a.displayName}`)}const p=a.installCommand;console.log(r.gray("$ ")+r.white(p));try{return t(p,{stdio:"inherit"}),O(),void console.log(r.green("√ "+n.t("wizard.tool_installed")))}catch(t){if(console.log(r.red("× "+n.t("wizard.install_failed"))),!/EACCES|EPERM|permission denied/i.test(`${t?.message??""}${t?.stderr??""}`)&&243!==t?.status&&!p.startsWith("npm "))throw new Error(`Failed to install ${a.displayName}: ${t}`);console.log(r.yellow(" ! "+("win32"===process.platform?n.t("install.permission_windows",{command:p}):n.t("install.permission_unix",{command:p}))))}const{action:u}=!i()||l()?{action:"continue"}:await e.prompt([{type:"list",name:"action",message:n.t("install.what_next"),choices:[{name:n.t("install.installed_continue"),value:"continue"},{name:n.t("install.cancel_install"),value:"cancel"}]}]);if("cancel"===u)throw new Error(n.t("install.user_cancelled"));if(O(),!this.isToolInstalled(o))throw console.log(r.red("× "+n.t("install.still_not_installed",{tool:a.displayName}))),new Error(`${a.displayName} is not installed`);console.log(r.green("√ "+n.t("install.verified_success",{tool:a.displayName})))}getToolConfig(t){const o=d(t);if(!o)throw new Error(`Unknown tool: ${t}`);try{return o.getConfig()}catch(o){return a.warn(`Failed to read config for ${t}:`,o),a.logError(`ToolManager.getToolConfig(${t})`,o),null}}updateToolConfig(t,o){const n=d(t);if(!n)throw new Error(`Unknown tool: ${t}`);if(!n.updateConfig)throw new Error(`Tool ${t} does not support raw config updates`);n.updateConfig(o)}forceResetConfig(t){const o=d(t);if(!o)throw new Error(`Unknown tool: ${t}`);const n=o.forceResetPaths?o.forceResetPaths():this.backupPathsFor(o),e=[];for(const t of n)g(t)&&(m(t),w(t,{force:!0}),e.push(t));return e}loadPrivateConfig(t,o,n,e,r={}){const i=d(t);if(!i)throw new Error(`Unknown tool: ${t}`);r.force&&this.forceResetConfig(t),i.loadPrivateConfig({apiKey:o,baseUrl:s.getBaseUrl(),models:n,settings:s.getToolSettings(t),...e?{catalog:e}:{},...r.takeOver?{takeOver:!0}:{}})}async applyPrivateConfig(t,o,n,e={}){const r=this.installedVersion(t);return I(`apply:${t}`,()=>this.applyPrivateConfigNow(t,o,n,e),{...r?{tool_version:r}:{},...e.force?{force:!0}:{}})}async applyPrivateConfigNow(t,o,n,e){const r=d(t);if(!r)throw new Error(`Unknown tool: ${t}`);const i=r.wantsModelCatalog?await T(o):null,{force:l,takeOver:a}=e;l||a?this.loadPrivateConfig(t,o,n,i??void 0,{force:l,takeOver:a}):i?this.loadPrivateConfig(t,o,n,i):this.loadPrivateConfig(t,o,n)}supportsCcSwitch(t){return Boolean(d(t)?.ccSwitch)}applyNotes(t){const o=d(t);if(!o)return[];const e=[];try{o.applyNotes&&e.push(...o.applyNotes())}catch(o){a.logError(`ToolManager.applyNotes(${t})`,o)}const r=this.outdatedVersion(t);if(r){e.push({kind:"action",text:n.t("tools.version_outdated",{current:r.current,min:r.min,upgrade:o.installSpec?`${b} upgrade ${t}`:o.upgradeCommand||o.installCommand})});for(const t of o.upgradeHints?.(r.min)??[])e.push({kind:"action",text:t})}const i=o.installSpec?E(o.installSpec):[];return i.length>1&&e.push({kind:"action",text:n.t("upgrade.duplicates_note",{count:String(i.length),active:S(i[0]),others:i.slice(1).map(S).join("、"),tool:t})}),e}printApplied(t,o=16){const n=SUPPORTED_TOOLS[t]?.displayName??t,e=this.applyNotes(t);for(const t of e.filter(t=>"detail"===t.kind))a.record(`${n}: ${t.text}`);const i=e.filter(t=>"summary"===t.kind).map(t=>t.text).join(";"),l=" ".repeat(Math.max(1,o-$(n)));console.log(r.green("√ "+n)+(i?l+i:""));for(const t of e.filter(t=>"action"===t.kind))console.log(r.yellow(" ! "+t.text))}installedVersion(t){const n=d(t);if(!n)return null;if(n.installSpec)return E(n.installSpec)[0]?.version??null;if(n.installedVersion)try{return n.installedVersion()}catch(o){return a.logError(`ToolManager.installedVersion(${t})`,o),null}if(n.isInstalled)return null;try{const t={encoding:"utf-8",timeout:1e4,windowsHide:!0,stdio:["ignore","pipe","pipe"]},e=`${("win32"===process.platform?o(`${n.command} --version`,{...t,shell:!0}):o(n.command,["--version"],t)).stdout??""}`.match(/(\d+)\.(\d+)\.(\d+)/);return e?e[0]:null}catch{return null}}outdatedVersion(t){const o=k(t);if(!o)return null;const n=this.installedVersion(t);return n&&C(n,o)<0?{current:n,min:o}:null}unloadPrivateConfig(t){const o=d(t);if(!o)throw new Error(`Unknown tool: ${t}`);try{o.unloadPrivateConfig({savedKeys:c()}),x(`remove:${t}`,"ok")}catch(o){throw x(`remove:${t}`,"fail",{error:o}),o}let e=[];try{e=o.unloadNotes?.()??[]}catch(o){a.logError(`ToolManager.unloadNotes(${t})`,o)}return e.length>0?e:[{kind:"action",text:n.t("config.reopen_hint",{tool:o.displayName})}]}async clearPinnedModels(t){const o=d(t);if(!o)throw new Error(`Unknown tool: ${t}`);if(s.setToolModel(t,null),!o.clearPinnedModels)return[];const n=s.getApiKeyForTool(t),e=o.wantsModelCatalog&&n?await T(n):null;return o.clearPinnedModels(e??void 0)}supportsClearPinnedModels(t){return Boolean(d(t)?.clearPinnedModels)}hasPendingElevation(t){return Boolean(d(t)?.pendingElevation?.())}holdsOurConfig(t){const o=d(t);if(!o)return!1;const n=c();return o.holdsOurConfig?o.holdsOurConfig(n):Boolean(o.detectCurrentConfig().apiKey)}detectCurrentConfig(t){const o=d(t);if(!o)throw new Error(`Unknown tool: ${t}`);return o.detectCurrentConfig()}backupPathsFor(t){return t.backupPaths?t.backupPaths():[t.configPath]}listToolBackups(t){const o=d(t);if(!o)throw new Error(`Unknown tool: ${t}`);return this.backupPathsFor(o).map(t=>({file:t,backups:f(t)}))}restorePrivateConfig(t){const o=d(t);if(!o)throw new Error(`Unknown tool: ${t}`);return this.backupPathsFor(o).map(t=>({file:t,result:h(t)}))}getInstalledTools(){return Object.keys(SUPPORTED_TOOLS).filter(t=>this.isToolInstalled(t))}getSupportedTools(){return p().filter(t=>!t.hidden).map(t=>L(t.name))}isGitInstalled(){try{const o="win32"===process.platform?"where git":"which git";return t(o,{stdio:"pipe"}),!0}catch{return!1}}}export const toolManager=ToolManager.getInstance();
@@ -1 +1 @@
1
- import{join as e}from"path";import{applyGatewayModels as t,claudeCodeManager as o}from"../claude-code-manager.js";import{backupBeforeWrite as n}from"./backup.js";import{i18n as s}from"../i18n.js";import{baseModelId as a}from"../model-catalog.js";import{gatewayModelSpecs as r,prettyModelName as i,vendorNames as l}from"../gateway-models.js";import{toolHome as c}from"./types.js";import{gatewayAddresses as d,normalizeBaseUrl as u}from"../gateway-addresses.js";import{configManager as p,savedApiKeys as m}from"../config.js";import{envCleanupPlan as f,lastEnvCleanup as g,removeEnvSources as _}from"../env-cleanup.js";import{canPrompt as v,hasExplicitYes as h}from"../runtime-options.js";import{maskHome as j}from"../telemetry.js";import{spawnSync as k}from"child_process";import{existsSync as C,readFileSync as y}from"fs";import{detectManagedOverrides as O}from"./claude-managed.js";import{installOfficialPlugins as A}from"./claude-plugins.js";import{findInstalls as P,mirrorInstallCommand as S,brandInstallScripts as x}from"./tool-installs.js";import{updateNativeFromMirror as b}from"./claude-native-mirror.js";import{brandEnv as T}from"../brand.js";import{claudeFormat as N,claudeProjectFiles as U}from"../sessions/formats.js";const w=e(c(),".claude","settings.json"),H=e(c(),".claude.json");let L,R=null,E=()=>0===k("security",["find-generic-password","-s","Claude Code-credentials"],{stdio:"ignore"}).status;export function setClaudeKeychainProbeForTests(e){E=e}export function claudeAccountLoginPresent(){const t=process.env.CLAUDE_CONFIG_DIR?.trim()||e(c(),".claude");if(C(e(t,".credentials.json")))return!0;if("darwin"!==process.platform||T("TEST_HOME"))return!1;try{return E()}catch{return!1}}function I(){try{const t=JSON.parse(y(e(c(),".claude","settings.json"),"utf-8"));return"string"==typeof t.autoUpdatesChannel?t.autoUpdatesChannel:"latest"}catch{return"latest"}}function M(e){if(!e)return;const t=new Set(e.models);return r("claude-code",e.clientModels,e.clientPersonal).filter(e=>t.has(e.id))}function B(){const e=o.getSettings().env?.ANTHROPIC_BASE_URL;return"string"==typeof e&&e.trim()?claudeCodeAdapter.holdsOurConfig(m())?null:e.trim():null}let D=null;const K={command:"claude",npmPackage:"@anthropic-ai/claude-code",native:{binDir:[".local","bin"],updateArgs:["update"],dataDirs:[[".local","share","claude"]],mirrorUpdate:()=>b(I())},mirrorScript:x("claude-code"),brew:"claude-code"};function F(){return v()&&!h()}export const claudeCodeAdapter={name:"claude-code",displayName:"Claude Code",command:"claude",installCommand:S(K),upgradeCommand:"claude update",installSpec:K,upgradeHints:e=>"stable"===I()?[s.t("tools.claude_code.stable_channel",{min:e})]:[],configPath:w,sessions:{format:N,files:()=>U(e(process.env.CLAUDE_CONFIG_DIR?.trim()||e(c(),".claude"),"projects")),resumeCommand:e=>({command:"claude",args:["--resume",e]})},wantsModelCatalog:!0,loadPrivateConfig(t){D=B(),n(w),n(H),L=M(t.catalog),o.loadPrivateConfig(t.apiKey,t.models,t.catalog?.models,L);const s=e(c(),".local","bin","win32"===process.platform?"claude.exe":"claude"),a=P(claudeCodeAdapter.installSpec)[0]?.path??(C(s)?s:null);R=a?A(a,{retry:Boolean(t.takeOver)}):null},holdsOurConfig(e){const t=o.getSettings().env??{},n="string"==typeof t.ANTHROPIC_AUTH_TOKEN?t.ANTHROPIC_AUTH_TOKEN.trim():"",s="string"==typeof t.ANTHROPIC_BASE_URL?u(t.ANTHROPIC_BASE_URL):null;return!(!n||!e.includes(n))||null!==s&&(d().some(e=>e.url===s)||s===u(p.getBaseUrl()))},planNotes(){const e=[],t=B();t&&e.push(s.t("tools.claude_code.plan_replace_provider",{url:t}));for(const t of f())e.push(s.t("tools.claude_code.plan_env_remove",{location:j(t.location),vars:Object.keys(t.vars).join(", ")}));return e},unloadPrivateConfig(e){const t=o.getSettings().env??{};Boolean(t.ANTHROPIC_AUTH_TOKEN||t.ANTHROPIC_BASE_URL)&&!claudeCodeAdapter.holdsOurConfig(e?.savedKeys??[])||(n(w),o.unloadPrivateConfig())},detectCurrentConfig:()=>o.detectCurrentConfig(),getConfig:()=>({settings:o.getSettings(),mcp:o.getMCPConfig()}),updateConfig(e){const t=e||{};t.settings&&o.saveSettings(t.settings),t.mcp&&o.saveMCPConfig(t.mcp)},clearPinnedModels:e=>(n(w),o.clearPinnedModels(e?.models)),listedModels(){const e=o.getSettings().modelPicker;return Array.isArray(e?.options)?e.options.map(e=>a(String(e.model))):null},refreshModelMenu(e){const s=o.getSettings(),a=t(s,M(e.catalog));JSON.stringify(a)!==JSON.stringify(s)&&(n(w),o.saveSettings(a))},async followUp(){const e=g().foreign;if(0===e.length||!F())return null;const t=e.map(e=>`${j(e.location)}(${Object.keys(e.vars).join(", ")})`).join("、");return{prompt:s.t("tools.claude_code.env_foreign_offer",{where:t}),hint:s.t("tools.claude_code.env_foreign",{location:e.map(e=>j(e.location)).join("、"),vars:[...new Set(e.flatMap(e=>Object.keys(e.vars)))].join(", ")}),async run(){const t=_(e),o=t.removed.map(e=>({kind:"summary",text:s.t("tools.claude_code.env_removed_foreign",{location:j(e.location),vars:Object.keys(e.vars).join(", ")})}));t.machineLeft.length>0&&o.push({kind:"action",text:s.t("messages.env_vars_machine_left",{vars:t.machineLeft.join(", ")})});for(const e of t.notBackedUp)o.push({kind:"action",text:s.t("tools.claude_code.env_not_backed_up",{location:j(e.location),vars:Object.keys(e.vars).join(", ")})});return o},decline(){}}},applyNotes(){const e=[];R?.installed.length&&(e.push({kind:"summary",text:s.t("tools.claude_code.plugins_installed",{count:String(R.installed.length)})}),e.push({kind:"detail",text:R.installed.join(", ")})),"git"===R?.skipped?e.push({kind:"action",text:s.t("tools.claude_code.plugins_need_git")}):("marketplace"===R?.skipped||"recent_failure"===R?.skipped||R?.failed.length)&&e.push({kind:"action",text:s.t("tools.claude_code.plugins_failed")}),L&&L.length>0&&(e.push({kind:"summary",text:s.t("tools.claude_code.gateway_models",{count:String(L.length),vendors:l(L.map(e=>e.id)).join(" / ")})}),e.push({kind:"detail",text:L.map(e=>e.name||i(e.id)).join(", ")})),D&&e.push({kind:"summary",text:s.t("tools.claude_code.provider_replaced",{url:D})});const t=g();for(const o of t.removed)e.push({kind:"summary",text:s.t("tools.claude_code.env_removed",{location:j(o.location),vars:Object.keys(o.vars).join(", ")})});for(const o of t.foreign){const t={location:j(o.location),vars:Object.keys(o.vars).join(", ")};e.push(F()?{kind:"detail",text:s.t("tools.claude_code.env_foreign_found",t)}:{kind:"action",text:s.t("tools.claude_code.env_foreign",t)})}t.machineLeft.length>0&&e.push({kind:"action",text:s.t("messages.env_vars_machine_left",{vars:t.machineLeft.join(", ")})});for(const o of t.notBackedUp)e.push({kind:"action",text:s.t("tools.claude_code.env_not_backed_up",{location:j(o.location),vars:Object.keys(o.vars).join(", ")})});const n=o.getLastReplaced();n.length>0&&e.push({kind:"summary",text:s.t("tools.claude_code.replaced_user_models",{values:n.join(", ")})}),"win32"!==process.platform||process.env.CLAUDE_CODE_GIT_BASH_PATH||0===k("where",["git"],{windowsHide:!0,stdio:"ignore"}).status||e.push({kind:"action",text:s.t("tools.claude_code.no_git_bash")}),claudeAccountLoginPresent()&&e.push({kind:"detail",text:s.t("tools.claude_code.account_login_overridden")});for(const t of O())e.push({kind:"action",text:s.t("tools.claude_code.managed_override",{source:t.source,keys:t.keys.join(", ")})});for(const t of o.getLastTierFallbacks())e.push({kind:"detail",text:s.t("tools.claude_code.tier_fallback",{tier:t.tier,from:t.from,to:t.to})});return e},backupPaths:()=>[w,H],forceResetPaths:()=>[w]};
1
+ import{join as e}from"path";import{applyGatewayModels as t,ccSwitchClaudeSettings as o,claudeCodeManager as n}from"../claude-code-manager.js";import{backupBeforeWrite as s}from"./backup.js";import{i18n as a}from"../i18n.js";import{baseModelId as r}from"../model-catalog.js";import{gatewayModelSpecs as i,prettyModelName as l,vendorNames as c}from"../gateway-models.js";import{toolHome as d}from"./types.js";import{gatewayAddresses as u,normalizeBaseUrl as p}from"../gateway-addresses.js";import{configManager as m,savedApiKeys as f}from"../config.js";import{envCleanupPlan as g,lastEnvCleanup as _,removeEnvSources as h}from"../env-cleanup.js";import{canPrompt as v,hasExplicitYes as j}from"../runtime-options.js";import{maskHome as k}from"../telemetry.js";import{spawnSync as C}from"child_process";import{existsSync as y,readFileSync as O}from"fs";import{detectManagedOverrides as A}from"./claude-managed.js";import{installOfficialPlugins as P}from"./claude-plugins.js";import{findInstalls as S,mirrorInstallCommand as b,brandInstallScripts as x}from"./tool-installs.js";import{updateNativeFromMirror as T}from"./claude-native-mirror.js";import{brandEnv as N}from"../brand.js";import{claudeFormat as U,claudeProjectFiles as w}from"../sessions/formats.js";const H=e(d(),".claude","settings.json"),L=e(d(),".claude.json");let R,E=null,I=()=>0===C("security",["find-generic-password","-s","Claude Code-credentials"],{stdio:"ignore"}).status;export function setClaudeKeychainProbeForTests(e){I=e}export function claudeAccountLoginPresent(){const t=process.env.CLAUDE_CONFIG_DIR?.trim()||e(d(),".claude");if(y(e(t,".credentials.json")))return!0;if("darwin"!==process.platform||N("TEST_HOME"))return!1;try{return I()}catch{return!1}}function M(){try{const t=JSON.parse(O(e(d(),".claude","settings.json"),"utf-8"));return"string"==typeof t.autoUpdatesChannel?t.autoUpdatesChannel:"latest"}catch{return"latest"}}function B(e){if(!e)return;const t=new Set(e.models);return i("claude-code",e.clientModels,e.clientPersonal).filter(e=>t.has(e.id))}function D(){const e=n.getSettings().env?.ANTHROPIC_BASE_URL;return"string"==typeof e&&e.trim()?claudeCodeAdapter.holdsOurConfig(f())?null:e.trim():null}let K=null;const F={command:"claude",npmPackage:"@anthropic-ai/claude-code",native:{binDir:[".local","bin"],updateArgs:["update"],dataDirs:[[".local","share","claude"]],mirrorUpdate:()=>T(M())},mirrorScript:x("claude-code"),brew:"claude-code"};function G(){return v()&&!j()}export const claudeCodeAdapter={name:"claude-code",displayName:"Claude Code",command:"claude",installCommand:b(F),upgradeCommand:"claude update",installSpec:F,upgradeHints:e=>"stable"===M()?[a.t("tools.claude_code.stable_channel",{min:e})]:[],configPath:H,sessions:{format:U,files:()=>w(e(process.env.CLAUDE_CONFIG_DIR?.trim()||e(d(),".claude"),"projects")),resumeCommand:e=>({command:"claude",args:["--resume",e]})},wantsModelCatalog:!0,ccSwitch:{app:"claude",endpointPath:"",card:e=>o(e.apiKey,e.baseUrl,e.models,e.catalog?.models,B(e.catalog))},loadPrivateConfig(t){K=D(),s(H),s(L),R=B(t.catalog),n.loadPrivateConfig(t.apiKey,t.models,t.catalog?.models,R);const o=e(d(),".local","bin","win32"===process.platform?"claude.exe":"claude"),a=S(claudeCodeAdapter.installSpec)[0]?.path??(y(o)?o:null);E=a?P(a,{retry:Boolean(t.takeOver)}):null},holdsOurConfig(e){const t=n.getSettings().env??{},o="string"==typeof t.ANTHROPIC_AUTH_TOKEN?t.ANTHROPIC_AUTH_TOKEN.trim():"",s="string"==typeof t.ANTHROPIC_BASE_URL?p(t.ANTHROPIC_BASE_URL):null;return!(!o||!e.includes(o))||null!==s&&(u().some(e=>e.url===s)||s===p(m.getBaseUrl()))},planNotes(){const e=[],t=D();t&&e.push(a.t("tools.claude_code.plan_replace_provider",{url:t}));for(const t of g())e.push(a.t("tools.claude_code.plan_env_remove",{location:k(t.location),vars:Object.keys(t.vars).join(", ")}));return e},unloadPrivateConfig(e){const t=n.getSettings().env??{};Boolean(t.ANTHROPIC_AUTH_TOKEN||t.ANTHROPIC_BASE_URL)&&!claudeCodeAdapter.holdsOurConfig(e?.savedKeys??[])||(s(H),n.unloadPrivateConfig())},detectCurrentConfig:()=>n.detectCurrentConfig(),getConfig:()=>({settings:n.getSettings(),mcp:n.getMCPConfig()}),updateConfig(e){const t=e||{};t.settings&&n.saveSettings(t.settings),t.mcp&&n.saveMCPConfig(t.mcp)},clearPinnedModels:e=>(s(H),n.clearPinnedModels(e?.models)),listedModels(){const e=n.getSettings().modelPicker;return Array.isArray(e?.options)?e.options.map(e=>r(String(e.model))):null},refreshModelMenu(e){const o=n.getSettings(),a=t(o,B(e.catalog));JSON.stringify(a)!==JSON.stringify(o)&&(s(H),n.saveSettings(a))},async followUp(){const e=_().foreign;if(0===e.length||!G())return null;const t=e.map(e=>`${k(e.location)}(${Object.keys(e.vars).join(", ")})`).join("、");return{prompt:a.t("tools.claude_code.env_foreign_offer",{where:t}),hint:a.t("tools.claude_code.env_foreign",{location:e.map(e=>k(e.location)).join("、"),vars:[...new Set(e.flatMap(e=>Object.keys(e.vars)))].join(", ")}),async run(){const t=h(e),o=t.removed.map(e=>({kind:"summary",text:a.t("tools.claude_code.env_removed_foreign",{location:k(e.location),vars:Object.keys(e.vars).join(", ")})}));t.machineLeft.length>0&&o.push({kind:"action",text:a.t("messages.env_vars_machine_left",{vars:t.machineLeft.join(", ")})});for(const e of t.notBackedUp)o.push({kind:"action",text:a.t("tools.claude_code.env_not_backed_up",{location:k(e.location),vars:Object.keys(e.vars).join(", ")})});return o},decline(){}}},applyNotes(){const e=[];E?.installed.length&&(e.push({kind:"summary",text:a.t("tools.claude_code.plugins_installed",{count:String(E.installed.length)})}),e.push({kind:"detail",text:E.installed.join(", ")})),"git"===E?.skipped?e.push({kind:"action",text:a.t("tools.claude_code.plugins_need_git")}):("marketplace"===E?.skipped||"recent_failure"===E?.skipped||E?.failed.length)&&e.push({kind:"action",text:a.t("tools.claude_code.plugins_failed")}),R&&R.length>0&&(e.push({kind:"summary",text:a.t("tools.claude_code.gateway_models",{count:String(R.length),vendors:c(R.map(e=>e.id)).join(" / ")})}),e.push({kind:"detail",text:R.map(e=>e.name||l(e.id)).join(", ")})),K&&e.push({kind:"summary",text:a.t("tools.claude_code.provider_replaced",{url:K})});const t=_();for(const o of t.removed)e.push({kind:"summary",text:a.t("tools.claude_code.env_removed",{location:k(o.location),vars:Object.keys(o.vars).join(", ")})});for(const o of t.foreign){const t={location:k(o.location),vars:Object.keys(o.vars).join(", ")};e.push(G()?{kind:"detail",text:a.t("tools.claude_code.env_foreign_found",t)}:{kind:"action",text:a.t("tools.claude_code.env_foreign",t)})}t.machineLeft.length>0&&e.push({kind:"action",text:a.t("messages.env_vars_machine_left",{vars:t.machineLeft.join(", ")})});for(const o of t.notBackedUp)e.push({kind:"action",text:a.t("tools.claude_code.env_not_backed_up",{location:k(o.location),vars:Object.keys(o.vars).join(", ")})});const o=n.getLastReplaced();o.length>0&&e.push({kind:"summary",text:a.t("tools.claude_code.replaced_user_models",{values:o.join(", ")})}),"win32"!==process.platform||process.env.CLAUDE_CODE_GIT_BASH_PATH||0===C("where",["git"],{windowsHide:!0,stdio:"ignore"}).status||e.push({kind:"action",text:a.t("tools.claude_code.no_git_bash")}),claudeAccountLoginPresent()&&e.push({kind:"detail",text:a.t("tools.claude_code.account_login_overridden")});for(const t of A())e.push({kind:"action",text:a.t("tools.claude_code.managed_override",{source:t.source,keys:t.keys.join(", ")})});for(const t of n.getLastTierFallbacks())e.push({kind:"detail",text:a.t("tools.claude_code.tier_fallback",{tier:t.tier,from:t.from,to:t.to})});return e},backupPaths:()=>[H,L],forceResetPaths:()=>[H]};
@@ -1 +1 @@
1
- import{createHash as e}from"crypto";import{existsSync as t,readdirSync as o,readFileSync as n,rmSync as r,statSync as i}from"fs";import{join as s}from"path";import*as c from"@iarna/toml";import{logger as d}from"../../utils/logger.js";import{i18n as l}from"../i18n.js";import{backupBeforeWrite as a,atomicWriteFile as u}from"./backup.js";import{codexHome as p,pickModel as m,toolHome as f,withV1 as _}from"./types.js";import{moveSessionsToProvider as g,NO_STATE_DB as x,runningCodexPids as h,SessionMoveError as y}from"../codex-sessions.js";import{codexFormat as k,codexRolloutFiles as b}from"../sessions/formats.js";import{getGatewayModelRules as v,getToolDefaultModel as w}from"../model-registry.js";import{ownsValue as j,recordAfterWrite as S,takeField as C}from"../written-values.js";import{configManager as M}from"../config.js";import{maskHome as O,track as A}from"../telemetry.js";import{buildCodexCatalog as E,catalogRejections as P,codexCatalogPath as N,fillFromOlderEntries as D,installedCodexBinaries as T,loadBundledCodexModels as $,loadPreviousCodexModels as I,previousGatewayModelIds as L}from"./codex-catalog.js";import{gatewayModelSpecs as J,modelFamily as R}from"../gateway-models.js";import{isOurGatewayUrl as G,noteWrittenGatewayUrl as B}from"../gateway-addresses.js";import{findInstalls as K,mirrorInstallCommand as U,brandInstallScripts as X}from"./tool-installs.js";import{chatgptDesktopApp as W}from"./chatgpt-desktop.js";const q=()=>p(),z=()=>s(q(),"config.toml"),F="sessions_move_declined",Y=["browser_use","browser_use_external","computer_use"],H="desktop_features_restored";function Q(e){if(!0===M.getMachineSetting("codex",H))return!1;const t=e.features;if(!ae(t)||!Y.every(e=>!1===t[e]))return!1;for(const e of Y)delete t[e];return!0}function V(){try{M.setMachineSetting("codex",H,!0)}catch(e){d.logError("codexAdapter.noteFeaturesRestored",e)}}export function forgetDeclinedSessions(){try{const e=M.getMachineSetting("codex",F);"number"==typeof e&&0!==e&&M.setMachineSetting("codex",F,0)}catch(e){d.logError("codexAdapter.forgetDeclinedSessions",e)}}export function codexWorkModeOn(){try{const e=pe();return e.model_provider===oe&&ae(e.desktop)&&"STEPS_PROSE"===e.desktop.conversationDetailMode}catch{return!1}}function Z(){try{if(ae(pe().desktop))return!0}catch{}if("darwin"===process.platform)return["/Applications",s(f(),"Applications")].some(e=>["ChatGPT.app","Codex.app"].some(o=>t(s(e,o))));if("win32"===process.platform){const e=s(process.env.LOCALAPPDATA||s(f(),"AppData","Local"),"Packages");try{return o(e).some(e=>/^OpenAI\.(Codex|ChatGPT)/i.test(e))}catch{return!1}}return t("/usr/lib/chatgpt/ChatGPT")}export function codexConfigPath(){return z()}const ee=()=>s(q(),"auth.json"),te="OPENAI_API_KEY",oe="custom",ne="high",re=["gpt-5.5","gpt-5.6-sol","gpt-6-astra"],ie=["high","xhigh"],se={goals:!0,js_repl:!1};let ce=[];const de=1e6,le=9e5;export const CODEX_ONE_MILLION_CONTEXT_SETTING="one_million_context";function ae(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}function ue(e,t){return ae(e[t])||(e[t]={}),e[t]}function pe(){if(!t(z()))return{};const e=n(z(),"utf-8");if(!e.trim())return{};try{const t=c.parse(e);if(!ae(t))throw new Error("config.toml root must be a TOML table");return t}catch(e){throw new Error(`Existing ~/.codex/config.toml cannot be parsed; back it up and fix it first: ${e instanceof Error?e.message:String(e)}`)}}function me(){if(!t(ee()))return{};try{const e=JSON.parse(n(ee(),"utf-8"));return ae(e)?e:{}}catch{return{}}}let fe=null;function _e(e){const t=e.profiles;if(ae(t)){for(const[e,o]of Object.entries(t))ae(o)&&2===Object.keys(o).length&&o.model_provider===oe&&o.model===e&&delete t[e];0===Object.keys(t).length&&delete e.profiles}}let ge=null;const xe=()=>s(M.getConfigDir(),"codex-catalog-check.json");function he(t,o){const n=e("sha256").update(t);for(const e of o)try{const t=i(e);n.update(`\0${e}\0${t.size}\0${t.mtimeMs}`)}catch{n.update(`\0${e}`)}return n.digest("hex")}function ye(){try{const e=JSON.parse(n(xe(),"utf-8"));return e&&"object"==typeof e?e:{}}catch{return{}}}function ke(e){try{u(xe(),JSON.stringify(e)+"\n")}catch(e){d.logError("codexAdapter.writeCheckState",e)}}function be(e){ke({wanted:he("",e)})}function ve(){const e=ye();void 0!==e.wanted&&(delete e.wanted,ke(e))}function we(){const e=ye().wanted;return void 0!==e&&e!==he("",T())}function je(e){const o=N();t(o)&&n(o,"utf-8")===e||(a(o),u(o,e))}function Se(e,t){if(0===t.length)return[];const o=he(e,t);if(function(e){return ye().signature===e}(o))return[];const n=P(N(),t);return 0===n.length&&function(e){ke({signature:e})}(o),n}function Ce(e,t,o){const n=!1!==t.settings?.one_million_context;!function(e){e.model_context_window===de&&delete e.model_context_window,e.model_auto_compact_token_limit===le&&delete e.model_auto_compact_token_limit}(e);const i=()=>{e.model_catalog_json===N()&&delete e.model_catalog_json,n&&(e.model_context_window=de,e.model_auto_compact_token_limit=le)},s=$()??I();if(!s)return d.logError("codexAdapter.writeModelCatalog",new Error("no Codex binary found; model catalog skipped")),ge="skipped",A("codex-catalog","skip",{detail:{reason:"no_codex_binary"}}),be(T()),void i();const c=t.catalog,l=e=>E({bundled:e,specs:J("codex",c?.clientModels,c?.clientPersonal),...c?.clientPersonal?.includes("codex")?{chosenGpt:(c.clientModels?.codex??[]).filter(e=>!e.hidden).map(e=>e.id)}:{},...c?{keyModels:c.models}:{},gatewayAvailable:c?.models??L(),oneMillion:n,selectedModel:o,..."gateway"===c?.oneMillionSource?{claudeOneMillion:c.oneMillion}:{}}),a=e=>JSON.stringify(e,null,2)+"\n";let u=l(s);je(a(u));const p=T(),m=Se(a(u),p);if(m.length>0){const e=Date.now();let t=!1;for(const e of m){const o=$(e.bin);if(o){for(const e of[{models:D(u.models,o)},{models:D(l(o).models,o)}])if(je(a(e)),0===Se(a(e),p).length){u=e,t=!0;break}if(t)break}}if(A("codex-catalog",t?"fallback":"fail",{duration_ms:Date.now()-e,error:m[0].error,detail:{rejected_by:m.map(e=>({version:e.version,path:O(e.bin)}))}}),!t)return ge={rejectedBy:m[0]},r(N(),{force:!0}),be(p),void i()}ge={listed:u.models.filter(e=>"list"===e.visibility).map(e=>({id:String(e.slug),name:String(e.display_name??e.slug)}))},e.model_catalog_json=N(),ve()}export function codexCatalogRejection(){let e;try{e=pe()}catch{return null}return e.model_catalog_json===N()&&t(N())?P(N())[0]??null:null}export function setCodexOneMillionContext(e,t){const o=pe(),n=c.stringify(o),r="string"==typeof o.model?o.model:w("codex");Ce(o,{settings:{[CODEX_ONE_MILLION_CONTEXT_SETTING]:e},catalog:t},r);const i=c.stringify(o);i!==n&&(a(z()),u(z(),i))}const Me={command:"codex",npmPackage:"@openai/codex",native:{binDir:"win32"===process.platform?["AppData","Local","Programs","OpenAI","Codex","bin"]:[".local","bin"],updateArgs:["update"],updateTimeoutMs:12e4,dataDirs:[[".codex","packages","standalone"]]},mirrorScript:X("codex"),brew:"codex"};function Oe(e){const t=ae(e.model_providers)?e.model_providers[oe]:void 0;if(!ae(t))return null;const o="string"==typeof t.base_url?t.base_url.trim():"";return o&&!G(o)?o:null}let Ae=null;function Ee(){if("skipped"===ge)return 0===K(Me).length?[]:[{kind:"action",text:l.t("tools.codex.catalog_skipped")}];if(!ge)return[];if("rejectedBy"in ge){const{bin:e,version:t}=ge.rejectedBy;return[{kind:"action",text:l.t("tools.codex.catalog_rejected",{path:e,version:t??"?"})}]}const e=new Map;for(const t of ge.listed)e.set(R(t.id),(e.get(R(t.id))??0)+1);const t=["gpt","claude","gemini","other","grok"].filter(t=>e.has(t)).map(t=>`${l.t(`tools.model_family.${t}`)} ${e.get(t)}`).join(" · ");return[{kind:"summary",text:l.t("tools.codex.catalog_written",{count:String(ge.listed.length),breakdown:t})},{kind:"detail",text:ge.listed.map(e=>e.name).join(", ")},...codexWorkModeOn()||Z()?[{kind:"action",text:l.t(codexWorkModeOn()?"tools.codex.work_mode_on":"tools.codex.work_mode_hint")}]:[]]}export const codexAdapter={name:"codex",companionApps:[W],displayName:"Codex",command:"codex",installCommand:U(Me),installSpec:Me,configPath:z(),sessions:{format:k,files:()=>[...b(s(p(),"sessions")),...b(s(p(),"archived_sessions"))],resumeCommand:e=>({command:"codex",args:["resume",e]})},wantsModelCatalog:!0,listedModels(){const e=pe();if(e.model_catalog_json!==N())return e.model_provider===oe&&we()?[]:null;try{return(JSON.parse(n(N(),"utf-8")).models??[]).filter(e=>"list"===e.visibility).map(e=>String(e.slug))}catch{return null}},refreshModelMenu(e){const t=pe();if(t.model_catalog_json!==N()&&(t.model_provider!==oe||!we()))return;setCodexOneMillionContext(!1!==e.settings?.one_million_context,e.catalog);const o=pe(),n=function(e,t){const o=ae(e.model_providers)?e.model_providers[oe]:void 0;return!(!ae(o)||o.base_url!==t||!0===o.supports_standalone_web_search||(o.supports_standalone_web_search=!0,0))}(o,_(e.baseUrl));(Q(o)||n)&&(a(z()),u(z(),c.stringify(o))),V()},async followUp(){if(pe().model_provider!==oe)return null;const e=await g(oe,{dryRun:!0}),t=Math.max(e.moved.length,e.dbRows);if(0===t)return forgetDeclinedSessions(),null;const o=M.getMachineSetting("codex",F);if("number"==typeof o&&t<=o)return null;const n={count:String(t)};return h().length>0?{hint:l.t("tools.codex.sessions_hidden_running",n)}:{prompt:l.t("tools.codex.sessions_offer",n),hint:l.t("tools.codex.sessions_hidden",n),async run(){if(h().length>0)return[{kind:"action",text:l.t("tools.codex.sessions_hidden_running",n)}];let e;try{e=await g(oe)}catch(e){d.logError("codexAdapter.followUp.run",e);const o=e instanceof y?e.backupDir:null;A("codex-sessions","fail",{error:e,detail:{count:t,backup:Boolean(o)}});const n=O(e instanceof Error?e.message:String(e)).replace(/\s+/g," ").trim();return[{kind:"action",text:l.t("codex_sessions.move_failed",{reason:n})},...o?[{kind:"action",text:l.t("codex_sessions.move_failed_undo",{dir:o})}]:[]]}forgetDeclinedSessions(),A("codex-sessions","ok",{detail:{files:e.moved.length,db_rows:e.dbRows}});const o=[...new Set(e.moved.map(e=>e.from))].join("、")||"-",r=String(Math.max(e.moved.length,e.dbRows)),i=[{kind:"summary",text:l.t("codex_sessions.moved",{count:r,from:o,target:oe})},{kind:"summary",text:l.t("codex_sessions.backup",{dir:e.backupDir??""})}];return e.dbSkipped&&e.dbSkipped!==x&&i.push({kind:"action",text:l.t("codex_sessions.db_skipped",{reason:e.dbSkipped})}),i},decline(){M.setMachineSetting("codex",F,t)}}},applyNotes(){const e=[];return Ae&&e.push({kind:"summary",text:l.t("tools.codex.provider_replaced",{url:Ae})}),ce.length>0&&e.push({kind:"summary",text:l.t("tools.codex.replaced_user_settings",{values:ce.join(", ")})}),[...e,...Ee()]},planNotes(){let e;try{e=pe()}catch{return[]}const t=[],o=Oe(e);return o?t.push(l.t("tools.codex.plan_replace_provider",{url:o})):"string"==typeof e.model_provider&&e.model_provider!==oe&&t.push(l.t("tools.codex.plan_switch_provider",{provider:e.model_provider})),t},loadPrivateConfig(e){S(()=>{const t=w("codex"),o=m(e.models,t),n=function(e){return/(?:^|\/)claude(?:-|$)/i.test(e)}(o)?t:o,r=_(e.baseUrl),i=pe();ce=[];const s=v().retired,d=(e,t,o,n,r)=>{void 0===t||t===o||"string"==typeof t&&s.includes(t)||j(e,t,n)||ce.push(`${r} = ${String(t)}`),C(e,o)};d("codex.model",i.model,n,re,"model"),i.model=n,i.model_provider=oe,d("codex.model_reasoning_effort",i.model_reasoning_effort,ne,ie,"model_reasoning_effort"),i.model_reasoning_effort=ne;const l="string"==typeof i.model?i.model:n;Ce(i,e,l);const p=ue(i,"model_providers");Ae=Oe(i),B(r);const f=ae(p[oe])?{...p[oe]}:{};delete f.env_key;const{experimental_bearer_token:g,...x}=f;p[oe]={...x,name:"custom",wire_api:"responses",requires_openai_auth:!0,supports_standalone_web_search:!0,base_url:r},_e(i),ue(ue(i,"tui"),"model_availability_nux")[l]=4;const h=ue(i,"features");for(const[e,t]of Object.entries(se))d(`codex.features.${e}`,void 0===h[e]?void 0:String(h[e]),String(t),[String(t)],`features.${e}`),h[e]=t;Q(i),a(z()),u(z(),c.stringify(i))}),V(),function(e){const t=e.trim();if(!t)return;const o={...me(),auth_mode:"apikey",[te]:t};a(ee()),u(ee(),JSON.stringify(o,null,2)+"\n",384)}(e.apiKey)},holdsOurConfig(e){const t=me()[te];return"string"==typeof t&&e.includes(t.trim())},unloadPrivateConfig(e){if(fe=function(e){const t=me(),o="string"==typeof t[te]?t[te].trim():"";if(!o)return ae(t.tokens)?"chatgpt":null;if(!e.includes(o))return"other_key";const{[te]:n,auth_mode:i,...s}=t;return a(ee()),ae(s.tokens)?(u(ee(),JSON.stringify({...s,auth_mode:"chatgpt"},null,2)+"\n",384),"chatgpt"):(r(ee(),{force:!0}),"signed_out")}(e?.savedKeys??[]),!t(z()))return;let o;try{o=pe()}catch(e){return void d.logError("codexAdapter.unloadPrivateConfig",e)}const n=o.model_providers;ae(n)&&ae(n[oe])&&G(n[oe].base_url)&&ae(n)&&(delete n[oe],0===Object.keys(n).length&&delete o.model_providers,o.model_provider===oe&&delete o.model_provider),o.model_catalog_json===N()&&delete o.model_catalog_json,Q(o),_e(o),a(z()),u(z(),c.stringify(o)),V(),ve()},unloadNotes(){switch(fe){case"chatgpt":return[{kind:"action",text:l.t("tools.codex.unload_chatgpt_restored")}];case"other_key":return[{kind:"action",text:l.t("tools.codex.unload_other_key")}];default:return[{kind:"action",text:l.t("tools.codex.unload_sign_in")}]}},detectCurrentConfig(){const e=me()[te];return{apiKey:"string"==typeof e&&e.trim()?e.trim():null}},getConfig(){try{return pe()}catch(e){return d.logError("codexAdapter.getConfig",e),null}},backupPaths:()=>[z(),ee(),N()]};export function codexAuthProblem(){try{const e=pe(),t=e.model_providers?.[oe];if(e.model_provider!==oe||!t)return null;if("string"==typeof t.experimental_bearer_token&&t.experimental_bearer_token)return"stale_bearer";const o=me();return!0===t.requires_openai_auth&&"chatgpt"===o.auth_mode?"chatgpt_login":null}catch{return null}}
1
+ import{createHash as e}from"crypto";import{existsSync as t,readdirSync as o,readFileSync as n,rmSync as r,statSync as s}from"fs";import{join as i}from"path";import*as c from"@iarna/toml";import{logger as d}from"../../utils/logger.js";import{i18n as l}from"../i18n.js";import{backupBeforeWrite as a,atomicWriteFile as u}from"./backup.js";import{codexHome as p,pickModel as m,toolHome as f,withV1 as _}from"./types.js";import{moveSessionsToProvider as g,NO_STATE_DB as x,runningCodexPids as h,SessionMoveError as y}from"../codex-sessions.js";import{codexFormat as k,codexRolloutFiles as b}from"../sessions/formats.js";import{getGatewayModelRules as v,getToolDefaultModel as w}from"../model-registry.js";import{ownsValue as j,recordAfterWrite as S,takeField as C}from"../written-values.js";import{configManager as M,savedApiKeys as O}from"../config.js";import{maskHome as A,track as E}from"../telemetry.js";import{buildCodexCatalog as P,catalogRejections as N,codexCatalogPath as D,fillFromOlderEntries as T,installedCodexBinaries as $,loadBundledCodexModels as I,loadPreviousCodexModels as L,previousGatewayModelIds as J}from"./codex-catalog.js";import{gatewayModelSpecs as R,modelFamily as G}from"../gateway-models.js";import{isOurGatewayUrl as K,noteWrittenGatewayUrl as U}from"../gateway-addresses.js";import{findInstalls as B,mirrorInstallCommand as X,brandInstallScripts as q}from"./tool-installs.js";import{chatgptDesktopApp as W}from"./chatgpt-desktop.js";const z=()=>p(),F=()=>i(z(),"config.toml"),Y="sessions_move_declined",H=["browser_use","browser_use_external","computer_use"],Q="desktop_features_restored";function V(e){if(!0===M.getMachineSetting("codex",Q))return!1;const t=e.features;if(!me(t)||!H.every(e=>!1===t[e]))return!1;for(const e of H)delete t[e];return!0}function Z(){try{M.setMachineSetting("codex",Q,!0)}catch(e){d.logError("codexAdapter.noteFeaturesRestored",e)}}export function forgetDeclinedSessions(){try{const e=M.getMachineSetting("codex",Y);"number"==typeof e&&0!==e&&M.setMachineSetting("codex",Y,0)}catch(e){d.logError("codexAdapter.forgetDeclinedSessions",e)}}export function codexWorkModeOn(){try{const e=_e();return e.model_provider===ne&&me(e.desktop)&&"STEPS_PROSE"===e.desktop.conversationDetailMode}catch{return!1}}function ee(){try{if(me(_e().desktop))return!0}catch{}if("darwin"===process.platform)return["/Applications",i(f(),"Applications")].some(e=>["ChatGPT.app","Codex.app"].some(o=>t(i(e,o))));if("win32"===process.platform){const e=i(process.env.LOCALAPPDATA||i(f(),"AppData","Local"),"Packages");try{return o(e).some(e=>/^OpenAI\.(Codex|ChatGPT)/i.test(e))}catch{return!1}}return t("/usr/lib/chatgpt/ChatGPT")}export function codexConfigPath(){return F()}const te=()=>i(z(),"auth.json"),oe="OPENAI_API_KEY",ne="custom",re="custom",se="high",ie=["gpt-5.5","gpt-5.6-sol","gpt-6-astra"],ce=["high","xhigh"],de={goals:!0,js_repl:!1};let le=[];const ae=1e6,ue=9e5;export const CODEX_ONE_MILLION_CONTEXT_SETTING="one_million_context";function pe(e){return/(?:^|\/)claude(?:-|$)/i.test(e)}function me(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}function fe(e,t){return me(e[t])||(e[t]={}),e[t]}function _e(){if(!t(F()))return{};const e=n(F(),"utf-8");if(!e.trim())return{};try{const t=c.parse(e);if(!me(t))throw new Error("config.toml root must be a TOML table");return t}catch(e){throw new Error(`Existing ~/.codex/config.toml cannot be parsed; back it up and fix it first: ${e instanceof Error?e.message:String(e)}`)}}function ge(){if(!t(te()))return{};try{const e=JSON.parse(n(te(),"utf-8"));return me(e)?e:{}}catch{return{}}}let xe=null;function he(e){const t=e.profiles;if(me(t)){for(const[e,o]of Object.entries(t))me(o)&&2===Object.keys(o).length&&o.model_provider===ne&&o.model===e&&delete t[e];0===Object.keys(t).length&&delete e.profiles}}let ye=null;const ke=()=>i(M.getConfigDir(),"codex-catalog-check.json");function be(t,o){const n=e("sha256").update(t);for(const e of o)try{const t=s(e);n.update(`\0${e}\0${t.size}\0${t.mtimeMs}`)}catch{n.update(`\0${e}`)}return n.digest("hex")}function ve(){try{const e=JSON.parse(n(ke(),"utf-8"));return e&&"object"==typeof e?e:{}}catch{return{}}}function we(e){try{u(ke(),JSON.stringify(e)+"\n")}catch(e){d.logError("codexAdapter.writeCheckState",e)}}function je(e){we({wanted:be("",e)})}function Se(){const e=ve();void 0!==e.wanted&&(delete e.wanted,we(e))}function Ce(){const e=ve().wanted;return void 0!==e&&e!==be("",$())}function Me(e){const o=D();t(o)&&n(o,"utf-8")===e||(a(o),u(o,e))}function Oe(e,t){if(0===t.length)return[];const o=be(e,t);if(function(e){return ve().signature===e}(o))return[];const n=N(D(),t);return 0===n.length&&function(e){we({signature:e})}(o),n}function Ae(e,t,o){const n=!1!==t.settings?.one_million_context;!function(e){e.model_context_window===ae&&delete e.model_context_window,e.model_auto_compact_token_limit===ue&&delete e.model_auto_compact_token_limit}(e);const s=()=>{e.model_catalog_json===D()&&delete e.model_catalog_json,n&&(e.model_context_window=ae,e.model_auto_compact_token_limit=ue)},i=I()??L();if(!i)return d.logError("codexAdapter.writeModelCatalog",new Error("no Codex binary found; model catalog skipped")),ye="skipped",E("codex-catalog","skip",{detail:{reason:"no_codex_binary"}}),je($()),void s();const c=t.catalog,l=e=>P({bundled:e,specs:R("codex",c?.clientModels,c?.clientPersonal),...c?.clientPersonal?.includes("codex")?{chosenGpt:(c.clientModels?.codex??[]).filter(e=>!e.hidden).map(e=>e.id)}:{},...c?{keyModels:c.models}:{},gatewayAvailable:c?.models??J(),oneMillion:n,selectedModel:o,..."gateway"===c?.oneMillionSource?{claudeOneMillion:c.oneMillion}:{}}),a=e=>JSON.stringify(e,null,2)+"\n";let u=l(i);Me(a(u));const p=$(),m=Oe(a(u),p);if(m.length>0){const e=Date.now();let t=!1;for(const e of m){const o=I(e.bin);if(o){for(const e of[{models:T(u.models,o)},{models:T(l(o).models,o)}])if(Me(a(e)),0===Oe(a(e),p).length){u=e,t=!0;break}if(t)break}}if(E("codex-catalog",t?"fallback":"fail",{duration_ms:Date.now()-e,error:m[0].error,detail:{rejected_by:m.map(e=>({version:e.version,path:A(e.bin)}))}}),!t)return ye={rejectedBy:m[0]},r(D(),{force:!0}),je(p),void s()}ye={listed:u.models.filter(e=>"list"===e.visibility).map(e=>({id:String(e.slug),name:String(e.display_name??e.slug)}))},e.model_catalog_json=D(),Se()}export function codexCatalogRejection(){let e;try{e=_e()}catch{return null}return e.model_catalog_json===D()&&t(D())?N(D())[0]??null:null}export function setCodexOneMillionContext(e,t){const o=_e(),n=c.stringify(o),r="string"==typeof o.model?o.model:w("codex");Ae(o,{settings:{[CODEX_ONE_MILLION_CONTEXT_SETTING]:e},catalog:t},r);const s=c.stringify(o);s!==n&&(a(F()),u(F(),s))}const Ee={command:"codex",npmPackage:"@openai/codex",native:{binDir:"win32"===process.platform?["AppData","Local","Programs","OpenAI","Codex","bin"]:[".local","bin"],updateArgs:["update"],updateTimeoutMs:12e4,dataDirs:[[".codex","packages","standalone"]]},mirrorScript:q("codex"),brew:"codex"};function Pe(e){const t=me(e.model_providers)?e.model_providers[ne]:void 0;if(!me(t))return null;const o="string"==typeof t.base_url?t.base_url.trim():"";return o&&!K(o)?o:null}let Ne=null;function De(){if("skipped"===ye)return 0===B(Ee).length?[]:[{kind:"action",text:l.t("tools.codex.catalog_skipped")}];if(!ye)return[];if("rejectedBy"in ye){const{bin:e,version:t}=ye.rejectedBy;return[{kind:"action",text:l.t("tools.codex.catalog_rejected",{path:e,version:t??"?"})}]}const e=new Map;for(const t of ye.listed)e.set(G(t.id),(e.get(G(t.id))??0)+1);const t=["gpt","claude","gemini","other","grok"].filter(t=>e.has(t)).map(t=>`${l.t(`tools.model_family.${t}`)} ${e.get(t)}`).join(" · ");return[{kind:"summary",text:l.t("tools.codex.catalog_written",{count:String(ye.listed.length),breakdown:t})},{kind:"detail",text:ye.listed.map(e=>e.name).join(", ")},...codexWorkModeOn()||ee()?[{kind:"action",text:l.t(codexWorkModeOn()?"tools.codex.work_mode_on":"tools.codex.work_mode_hint")}]:[]]}export const codexAdapter={name:"codex",companionApps:[W],displayName:"Codex",command:"codex",installCommand:X(Ee),installSpec:Ee,configPath:F(),sessions:{format:k,files:()=>[...b(i(p(),"sessions")),...b(i(p(),"archived_sessions"))],resumeCommand:e=>({command:"codex",args:["resume",e]})},wantsModelCatalog:!0,listedModels(){const e=_e();if(e.model_catalog_json!==D())return e.model_provider===ne&&Ce()?[]:null;try{return(JSON.parse(n(D(),"utf-8")).models??[]).filter(e=>"list"===e.visibility).map(e=>String(e.slug))}catch{return null}},refreshModelMenu(e){const t=_e();if(t.model_catalog_json!==D()&&(t.model_provider!==ne||!Ce()))return;setCodexOneMillionContext(!1!==e.settings?.one_million_context,e.catalog);const o=_e(),n=function(e,t){const o=me(e.model_providers)?e.model_providers[ne]:void 0;return!(!me(o)||o.base_url!==t||!0===o.supports_standalone_web_search||(o.supports_standalone_web_search=!0,0))}(o,_(e.baseUrl));(V(o)||n)&&(a(F()),u(F(),c.stringify(o))),Z()},async followUp(){if(_e().model_provider!==ne)return null;const e=await g(ne,{dryRun:!0}),t=Math.max(e.moved.length,e.dbRows);if(0===t)return forgetDeclinedSessions(),null;const o=M.getMachineSetting("codex",Y);if("number"==typeof o&&t<=o)return null;const n={count:String(t)};return h().length>0?{hint:l.t("tools.codex.sessions_hidden_running",n)}:{prompt:l.t("tools.codex.sessions_offer",n),hint:l.t("tools.codex.sessions_hidden",n),async run(){if(h().length>0)return[{kind:"action",text:l.t("tools.codex.sessions_hidden_running",n)}];let e;try{e=await g(ne)}catch(e){d.logError("codexAdapter.followUp.run",e);const o=e instanceof y?e.backupDir:null;E("codex-sessions","fail",{error:e,detail:{count:t,backup:Boolean(o)}});const n=A(e instanceof Error?e.message:String(e)).replace(/\s+/g," ").trim();return[{kind:"action",text:l.t("codex_sessions.move_failed",{reason:n})},...o?[{kind:"action",text:l.t("codex_sessions.move_failed_undo",{dir:o})}]:[]]}forgetDeclinedSessions(),E("codex-sessions","ok",{detail:{files:e.moved.length,db_rows:e.dbRows}});const o=[...new Set(e.moved.map(e=>e.from))].join("、")||"-",r=String(Math.max(e.moved.length,e.dbRows)),s=[{kind:"summary",text:l.t("codex_sessions.moved",{count:r,from:o,target:ne})},{kind:"summary",text:l.t("codex_sessions.backup",{dir:e.backupDir??""})}];return e.dbSkipped&&e.dbSkipped!==x&&s.push({kind:"action",text:l.t("codex_sessions.db_skipped",{reason:e.dbSkipped})}),s},decline(){M.setMachineSetting("codex",Y,t)}}},applyNotes(){const e=[];return Ne&&e.push({kind:"summary",text:l.t("tools.codex.provider_replaced",{url:Ne})}),le.length>0&&e.push({kind:"summary",text:l.t("tools.codex.replaced_user_settings",{values:le.join(", ")})}),[...e,...De()]},planNotes(){let e;try{e=_e()}catch{return[]}const t=[],o=Pe(e);return o?t.push(l.t("tools.codex.plan_replace_provider",{url:o})):"string"==typeof e.model_provider&&e.model_provider!==ne&&t.push(l.t("tools.codex.plan_switch_provider",{provider:e.model_provider})),t},ccSwitch:{app:"codex",endpointPath:"/v1",card(e){const t=w("codex"),o=m(e.models,t),n=pe(o)?t:o,r={};Ae(r,e,n);const s={model_provider:ne,model:n,model_reasoning_effort:se,..."string"==typeof r.model_catalog_json?{model_catalog_json:r.model_catalog_json}:{},model_providers:{[ne]:{name:re,base_url:_(e.baseUrl),wire_api:"responses",requires_openai_auth:!0,supports_standalone_web_search:!0}}};return{auth:{[oe]:e.apiKey},config:c.stringify(s)}}},loadPrivateConfig(e){S(()=>{const t=w("codex"),o=m(e.models,t),n=pe(o)?t:o,r=_(e.baseUrl),s=_e();le=[];const i=v().retired,d=(e,t,o,n,r)=>{void 0===t||t===o||"string"==typeof t&&i.includes(t)||j(e,t,n)||le.push(`${r} = ${String(t)}`),C(e,o)};d("codex.model",s.model,n,ie,"model"),s.model=n,s.model_provider=ne,d("codex.model_reasoning_effort",s.model_reasoning_effort,se,ce,"model_reasoning_effort"),s.model_reasoning_effort=se;const l="string"==typeof s.model?s.model:n;Ae(s,e,l);const p=fe(s,"model_providers");Ne=Pe(s),U(r);const f=me(p[ne])?{...p[ne]}:{};delete f.env_key;const{experimental_bearer_token:g,...x}=f;p[ne]={...x,name:re,wire_api:"responses",requires_openai_auth:!0,supports_standalone_web_search:!0,base_url:r},he(s),fe(fe(s,"tui"),"model_availability_nux")[l]=4;const h=fe(s,"features");for(const[e,t]of Object.entries(de))d(`codex.features.${e}`,void 0===h[e]?void 0:String(h[e]),String(t),[String(t)],`features.${e}`),h[e]=t;V(s),a(F()),u(F(),c.stringify(s))}),Z(),function(e){const t=e.trim();if(!t)return;const o={...ge(),auth_mode:"apikey",[oe]:t};a(te()),u(te(),JSON.stringify(o,null,2)+"\n",384)}(e.apiKey)},holdsOurConfig(e){const t=ge()[oe];return"string"==typeof t&&e.includes(t.trim())},unloadPrivateConfig(e){if(xe=function(e){const t=ge(),o="string"==typeof t[oe]?t[oe].trim():"";if(!o)return me(t.tokens)?"chatgpt":null;if(!e.includes(o))return"other_key";const{[oe]:n,auth_mode:s,...i}=t;return a(te()),me(i.tokens)?(u(te(),JSON.stringify({...i,auth_mode:"chatgpt"},null,2)+"\n",384),"chatgpt"):(r(te(),{force:!0}),"signed_out")}(e?.savedKeys??[]),!t(F()))return;let o;try{o=_e()}catch(e){return void d.logError("codexAdapter.unloadPrivateConfig",e)}const n=o.model_providers;me(n)&&me(n[ne])&&K(n[ne].base_url)&&me(n)&&(delete n[ne],0===Object.keys(n).length&&delete o.model_providers,o.model_provider===ne&&delete o.model_provider),o.model_catalog_json===D()&&delete o.model_catalog_json,V(o),he(o),a(F()),u(F(),c.stringify(o)),Z(),Se()},unloadNotes(){switch(xe){case"chatgpt":return[{kind:"action",text:l.t("tools.codex.unload_chatgpt_restored")}];case"other_key":return[{kind:"action",text:l.t("tools.codex.unload_other_key")}];default:return[{kind:"action",text:l.t("tools.codex.unload_sign_in")}]}},detectCurrentConfig(){const e=ge()[oe];return{apiKey:"string"==typeof e&&e.trim()?e.trim():null}},getConfig(){try{return _e()}catch(e){return d.logError("codexAdapter.getConfig",e),null}},backupPaths:()=>[F(),te(),D()]};export function codexAuthProblem(){try{const e=_e(),t=e.model_providers?.[ne];if(e.model_provider!==ne||!t)return null;const o="string"==typeof t.experimental_bearer_token?t.experimental_bearer_token.trim():"";if(o&&!O().includes(o))return"stale_bearer";const n=ge();return!0===t.requires_openai_auth&&"chatgpt"===n.auth_mode?"chatgpt_login":null}catch{return null}}
@@ -164,6 +164,16 @@ export interface ToolAdapter {
164
164
  * prompt fixes it); setup, the wizard and `config <tool> remove` offer to run it. Null when none.
165
165
  * `failedHint` / `skippedHint` replace the generic next step when it is not "rerun setup / refresh".
166
166
  */
167
+ /**
168
+ * How this tool goes into CC Switch as a card (`setup --ccswitch` / `--ccswitch-use`, `src/lib/ccswitch.ts`):
169
+ * CC Switch's app id, the path its endpoints carry (`/v1` for OpenAI-style tools) and the card's
170
+ * `settings_config`. Tools without it are not handed to CC Switch.
171
+ */
172
+ ccSwitch?: {
173
+ app: 'claude' | 'codex';
174
+ endpointPath: string;
175
+ card(ctx: ToolApplyContext): Record<string, unknown>;
176
+ };
167
177
  pendingElevation?(): {
168
178
  prompt: string;
169
179
  failedHint?: string;
@@ -321,6 +321,28 @@
321
321
  "needs_terminal": "This command asks questions and needs a terminal; none is attached",
322
322
  "non_interactive_required_token": "An API key is required in non-interactive mode"
323
323
  },
324
+ "ccswitch": {
325
+ "ask_quit": "Quit CC Switch now and reopen it when done? (It doesn't see changes made while it runs)",
326
+ "problem_not_installed": "Couldn't write to CC Switch: its data wasn't found ({{path}}). Install CC Switch, open it once, then run the same command again",
327
+ "problem_no_sqlite": "Couldn't write to CC Switch: this needs Node.js 22.13 or newer (now {{node}}). Run {{cli}} upgrade node, then try again",
328
+ "problem_unsupported_schema": "Couldn't write to CC Switch: {{cli}} doesn't support this CC Switch version yet (database version {{schema}}), so nothing was written; this was reported. Use \"Import to CC Switch\" on the console's API keys page for now, or run {{cli}} update and try again",
329
+ "problem_unexpected_tables": "Couldn't write to CC Switch: {{cli}} doesn't support this CC Switch version yet (database version {{schema}}, different tables), so nothing was written; this was reported. Use \"Import to CC Switch\" on the console's API keys page for now, or run {{cli}} update and try again",
330
+ "problem_running": "Couldn't write to CC Switch: it is running. Quit CC Switch from the tray or menu bar, then run the same command again",
331
+ "problem_unreadable": "Couldn't read CC Switch's data ({{path}}). Quit CC Switch completely, then run the same command again",
332
+ "not_supported": "{{tools}}: not set up through CC Switch, nothing changed; to configure directly, run again without --ccswitch",
333
+ "nothing": "Couldn't write to CC Switch: none of the tools this key can set up goes through CC Switch (Claude Code, Codex)",
334
+ "plan_add": "Will add or update the {{brand}} card in CC Switch for {{tools}} ({{path}}), without changing these tools' own config",
335
+ "plan_use": "Will add or update the {{brand}} card in CC Switch for {{tools}} ({{path}}) and switch to it, also writing these tools' config",
336
+ "confirm": "Write to CC Switch?",
337
+ "card_failed": "Couldn't build the CC Switch card for {{tool}}: {{reason}}",
338
+ "write_failed": "Couldn't write to CC Switch: {{reason}}",
339
+ "done_add": "Added the {{brand}} card for {{tool}} to CC Switch",
340
+ "done_use": "Switched {{tool}} to the {{brand}} card in CC Switch",
341
+ "done_proxy": "Wrote {{tool}}'s config and added the {{brand}} card to CC Switch; CC Switch routes it locally, so switch to {{brand}} in CC Switch",
342
+ "switch_hint": "Takes effect once you switch to {{brand}} in CC Switch",
343
+ "not_installed_card_only": "{{tool}} isn't installed: only the card went into CC Switch; after installing it, switch to {{brand}} in CC Switch",
344
+ "refresh_running": "CC Switch is running, so the {{brand}} card's model menu wasn't updated. Quit CC Switch, then run {{cli}} refresh"
345
+ },
324
346
  "setup": {
325
347
  "dry_run_tool": "Would configure {{tool}}, writing:",
326
348
  "dry_run_key": "The API key would be saved to {{file}}",
@@ -783,6 +805,8 @@
783
805
  "all": "Configure every tool the API key can serve (the default)",
784
806
  "install": "Install missing tools from the China mirrors without asking",
785
807
  "no_install": "Only print install commands for missing tools",
808
+ "ccswitch": "Only add {{brand}} to CC Switch (a card each for Claude Code and Codex), leaving the tools' own config alone",
809
+ "ccswitch_use": "Add to CC Switch and switch to it, also writing the tools' config",
786
810
  "upgrade": "Install or update these components first (comma separated, e.g. claude-code,grok; same as the upgrade command), then configure as the other options say",
787
811
  "codebuddykey": "API key just for CodeBuddy Code",
788
812
  "workbuddykey": "API key just for WorkBuddy",
@@ -321,6 +321,28 @@
321
321
  "needs_terminal": "这个命令要在终端里回答问题,当前没有可以输入的终端",
322
322
  "non_interactive_required_token": "非交互模式下必须提供令牌"
323
323
  },
324
+ "ccswitch": {
325
+ "ask_quit": "先退出 CC Switch,写完再自动打开?(它运行时读不到外面写进去的配置)",
326
+ "problem_not_installed": "无法写入 CC Switch:没有找到它的数据({{path}})。先安装并打开一次 CC Switch,再运行一次刚才的命令",
327
+ "problem_no_sqlite": "无法写入 CC Switch:需要 Node.js 22.13 或更新版本(当前 {{node}})。运行 {{cli}} upgrade node 后再试",
328
+ "problem_unsupported_schema": "无法写入 CC Switch:{{cli}} 还没有适配这个版本的 CC Switch(数据库版本 {{schema}}),这次没有写入,已上报。可以先用控制台「令牌」页的「导入到 CC Switch」,或运行 {{cli}} update 后再试",
329
+ "problem_unexpected_tables": "无法写入 CC Switch:{{cli}} 还没有适配这个版本的 CC Switch(数据库版本 {{schema}},表结构不同),这次没有写入,已上报。可以先用控制台「令牌」页的「导入到 CC Switch」,或运行 {{cli}} update 后再试",
330
+ "problem_running": "无法写入 CC Switch:它正在运行。先在托盘或菜单栏里退出 CC Switch,再运行一次刚才的命令",
331
+ "problem_unreadable": "无法读取 CC Switch 的数据({{path}})。完全退出 CC Switch 后再运行一次刚才的命令",
332
+ "not_supported": "{{tools}} 不经 CC Switch 配置,这次没有改动;要直接配置,去掉 --ccswitch 再运行",
333
+ "nothing": "无法写入 CC Switch:这个令牌能配的工具里没有经 CC Switch 配置的(Claude Code、Codex)",
334
+ "plan_add": "将在 CC Switch 里添加或更新 {{brand}} 卡片:{{tools}}({{path}}),不改这些工具自己的配置",
335
+ "plan_use": "将在 CC Switch 里添加或更新 {{brand}} 卡片并切换过去:{{tools}}({{path}}),同时写好这些工具的配置",
336
+ "confirm": "写入 CC Switch?",
337
+ "card_failed": "无法生成 {{tool}} 的 CC Switch 卡片:{{reason}}",
338
+ "write_failed": "无法写入 CC Switch:{{reason}}",
339
+ "done_add": "已把 {{tool}} 的 {{brand}} 卡片加进 CC Switch",
340
+ "done_use": "已把 {{tool}} 切换到 CC Switch 里的 {{brand}} 卡片",
341
+ "done_proxy": "已写好 {{tool}} 的配置并把 {{brand}} 卡片加进 CC Switch;CC Switch 对它开着本地路由,请在 CC Switch 里切换到 {{brand}}",
342
+ "switch_hint": "在 CC Switch 里切换到 {{brand}} 后生效",
343
+ "not_installed_card_only": "{{tool}} 还没有安装:只把卡片加进 CC Switch,安装后在 CC Switch 里切换到 {{brand}}",
344
+ "refresh_running": "CC Switch 正在运行,{{brand}} 卡片的模型菜单没有更新。退出 CC Switch 后运行 {{cli}} refresh"
345
+ },
324
346
  "setup": {
325
347
  "dry_run_tool": "将配置 {{tool}},写入:",
326
348
  "dry_run_key": "令牌将保存到 {{file}}",
@@ -783,6 +805,8 @@
783
805
  "all": "配置令牌能用的全部工具(默认行为)",
784
806
  "install": "未安装的工具直接从国内镜像安装,不再询问",
785
807
  "no_install": "未安装的工具只给出安装命令,不安装",
808
+ "ccswitch": "只把 {{brand}} 加进 CC Switch(Claude Code、Codex 各一张卡片),不改工具自己的配置",
809
+ "ccswitch_use": "加进 CC Switch 并切换过去,同时写好工具的配置",
786
810
  "upgrade": "先安装或更新这些组件(逗号分隔,如 claude-code,grok;和 upgrade 命令相同),再按其他参数配置",
787
811
  "codebuddykey": "CodeBuddy Code 专属令牌",
788
812
  "workbuddykey": "WorkBuddy 专属令牌",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vibeapi/api-helper",
3
- "version": "0.0.198",
3
+ "version": "0.0.199",
4
4
  "description": "CLI tool for managing AI coding assistants (Claude Code, Codex, OpenClaw, Hermes, AtomCode, Grok Build) with one unified config",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",