@xhscopy-ai/cli 0.0.199 → 0.0.200

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.
@@ -1100,8 +1100,8 @@
1100
1100
  "context_window": 1000000,
1101
1101
  "description": "100 万上下文 | Agent 工作流",
1102
1102
  "endpoint_types": [
1103
- "openai",
1104
- "gemini"
1103
+ "gemini",
1104
+ "openai"
1105
1105
  ],
1106
1106
  "group": "",
1107
1107
  "group_name": "",
@@ -2071,8 +2071,8 @@
2071
2071
  "context_window": 1000000,
2072
2072
  "description": "100 万上下文 | Agent 工作流",
2073
2073
  "endpoint_types": [
2074
- "openai",
2075
- "gemini"
2074
+ "gemini",
2075
+ "openai"
2076
2076
  ],
2077
2077
  "group": "",
2078
2078
  "group_name": "",
@@ -1100,8 +1100,8 @@
1100
1100
  "context_window": 1000000,
1101
1101
  "description": "100 万上下文 | Agent 工作流",
1102
1102
  "endpoint_types": [
1103
- "openai",
1104
- "gemini"
1103
+ "gemini",
1104
+ "openai"
1105
1105
  ],
1106
1106
  "group": "",
1107
1107
  "group_name": "",
@@ -2071,8 +2071,8 @@
2071
2071
  "context_window": 1000000,
2072
2072
  "description": "100 万上下文 | Agent 工作流",
2073
2073
  "endpoint_types": [
2074
- "openai",
2075
- "gemini"
2074
+ "gemini",
2075
+ "openai"
2076
2076
  ],
2077
2077
  "group": "",
2078
2078
  "group_name": "",
@@ -1 +1 @@
1
- import e from"chalk";import{configManager as o,DEFAULT_BASE_URL as r}from"../lib/config.js";import{i18n as t}from"../lib/i18n.js";import{toolManager as a}from"../lib/tool-manager.js";import{listAdapters as s}from"../lib/tools/registry.js";import{postApplyPrompts as l}from"../lib/post-apply.js";import{emitJson as n,isJsonMode as i}from"../lib/runtime-options.js";import{logger as u}from"../utils/logger.js";import{reportCliError as c,usageError as f,authenticationError as p,networkError as d,operationError as m}from"../lib/errors.js";import{gatewayAddresses as b,normalizeBaseUrl as y,probeGatewayAddress as g}from"../lib/gateway-addresses.js";import{CLI_NAME as _}from"../lib/brand.js";import{track as h}from"../lib/telemetry.js";import{forgetField as k,ownsValue as w,takeField as x}from"../lib/written-values.js";export async function baseCommand(a){const s=o.getBaseUrl(),l=addressesWithCurrent(),u=a?.trim().toLowerCase();if(!u)return void await async function(o,r){const a=savedApiKey(),s=await probeAll(o,{apiKey:a,samples:3});i()?n({ok:!0,current:r,addresses:o.map((e,o)=>({...e,...s[o],current:e.url===r}))}):(console.log(e.bold(t.t("base.current",{url:r}))),console.log(e.gray(t.t(a?"base.probe_with_key":"base.probe_without_key"))+"\n"),K(o,s,r),console.log("\n"+e.gray(t.t("base.usage_hint"))))}(l,s);if("auto"===u){const e=await probeAll(l,{apiKey:savedApiKey()}),o=e.find(e=>e.ok);if(!o){const o=e.every(e=>"key_rejected"===e.error);return j(o?"key_rejected":"no_reachable",t.t(o?"base.key_rejected_everywhere":"base.none_reachable")),void K(l,e,s)}return void await switchGatewayAddress(o.url,{auto:!0})}let c;if("default"===u||"reset"===u)c=r;else if(/^\d+$/.test(u)){if(c=l[Number(u)-1]?.url??null,!c)return void j("bad_index",t.t("base.bad_index",{index:u,count:String(l.length)}))}else if(c=y(a),!c)return void j("bad_url",t.t("base.bad_url",{value:a}));const f=await g(c,{apiKey:savedApiKey()});f.ok?await switchGatewayAddress(c):j("unreachable",t.t("base.unreachable",{url:c,reason:reasonText(f)}))}export async function ensureReachableGatewayAddress(a=savedApiKey(),s={}){if(o.hasRuntimeBaseUrl())return null;const l=o.getBaseUrl(),n=b(),u=await g(l,{apiKey:a});if("key_rejected"===u.error)return null;let c;if(u.ok){const e=n.findIndex(e=>e.url===l);if(e<=0||!w($(),l))return null;c=n.slice(0,e)}else c=n.filter(e=>e.url!==l);const f=(await probeAll(c,{apiKey:a})).find(e=>e.ok);if(!f)return null;if(u.ok?h("gateway-fallback","ok",{detail:{from:l,to:f.url,back:!0}}):h("gateway-fallback","fallback",{error:reasonText(u),detail:{from:l,to:f.url}}),!1===s.save?(o.setBaseUrl(f.url,!1),v=f.url):A(f.url,!0),!i())if(u.ok)console.log(e.yellow(t.t("base.setup_back",{from:l,url:f.url})));else{const o=f.url===r?"base.setup_fallback_main":"base.setup_fallback";console.log(e.yellow(t.t(o,{from:l,reason:reasonText(u),url:f.url})))}return f.url}let v=null;function $(){return`base_url_auto:${o.getActiveProfileName()}`}function A(e,t){e===r?o.resetBaseUrl():o.setBaseUrl(e,!0),t?x($(),e):k($())}export function saveGatewayFallback(){if(!v)return;const e=v;v=null,A(e,!0)}export function addressesWithCurrent(){const e=o.getBaseUrl(),r=b();return r.some(o=>o.url===e)||r.push({url:e,label:t.t("base.custom_label")}),r}export function savedApiKey(){return o.getApiKey()||s().map(e=>o.getApiKeyForTool(e.name)).find(Boolean)}export async function probeAll(e,o={}){return Promise.all(e.map(e=>g(e.url,o)))}export function probeSummary(o,r){if(!o.ok)return e.red(`× ${reasonText(o)}`);const a=[`${o.ms} ms`];return void 0!==o.models&&a.push(t.t("base.models_count",{count:String(o.models)})),r&&a.push(t.t("base.fastest")),e.green(`√ ${a.join(" · ")}`)}export function fastestIndex(e){let o=-1;return e.forEach((r,t)=>{r.ok&&(o<0||r.ms<e[o].ms)&&(o=t)}),o}export function reasonText(e){if(!e.error)return"";const o=t.t(`base.error_${e.error}`);return e.detail?`${o}(${e.detail})`:o}function j(e,o){const r="bad_index"===e||"bad_url"===e?f(o,t.t("errors.next_step",{command:`${_} base --help`}),e):"key_rejected"===e?p(o,t.t("errors.next_step",{command:`${_} setup --key ${t.t("errors.key_placeholder")}`}),e):d(o,t.t("base.next_addresses"),e);c(r)}function K(o,r,a){if(i())return;const s=r.length>1?fastestIndex(r):-1;o.forEach((o,l)=>{const n=o.url===a?e.cyan(` ← ${t.t("base.current_mark")}`):"";console.log(`${l+1}. ${o.url} ${e.gray(o.label)}\n ${probeSummary(r[l],l===s)}${n}`)})}export function toolsWeConfigured(){const e=[];for(const r of s()){const t=o.getApiKeyForTool(r.name);if(t)try{r.detectCurrentConfig().apiKey===t&&e.push({tool:r.name,apiKey:t})}catch(e){u.logError(`base.detectCurrentConfig(${r.name})`,e)}}return e}export async function moveToolsToCurrentAddress(e){const r=[],t=[];for(const{tool:s,apiKey:l}of e)try{await a.applyPrivateConfig(s,l,o.getModelsForTool(s)),r.push(s)}catch(e){t.push({tool:s,reason:e instanceof Error?e.message:String(e)})}return{applied:r,failed:t}}export async function moveOtherToolsAfterFallback(o){if(0===o.length)return[];const{applied:r,failed:s}=await moveToolsToCurrentAddress(o);if(h("gateway-fallback-tools",s.length>0?"fail":"ok",{detail:{applied:r,failed:s.map(e=>e.tool)}}),!i()){r.length>0&&console.log(t.t("base.other_tools_moved"));for(const e of r)a.printApplied(e);for(const{tool:o,reason:r}of s)console.error(e.red(`× ${t.t("setup.apply_failed",{tool:o,reason:r})}`))}return r}export async function switchGatewayAddress(r,s={}){const u=o.getBaseUrl(),f=toolsWeConfigured();A(r,Boolean(s.auto));const{applied:p,failed:d}=await moveToolsToCurrentAddress(f);if(d.length>0&&c(m(d.map(({tool:e,reason:o})=>`${e}: ${o}`).join("; "),t.t("errors.next_step",{command:`${_} setup --key ${t.t("errors.key_placeholder")}`}),"config_write_failed")),i()&&0===d.length)n({ok:0===d.length,previous:u,base_url:r,applied:p,failed:d});else{console.log(e.green(t.t(r===u?"base.kept":"base.switched",{url:r}))),p.length>0&&console.log(t.t("base.tools_moved"));for(const e of p)a.printApplied(e);for(const{tool:o,reason:r}of d)console.error(e.red(`× ${t.t("setup.apply_failed",{tool:o,reason:r})}`));0===p.length&&0===d.length&&console.log(e.yellow(t.t("base.no_tools",{url:r}))),await l(p)}}
1
+ import e from"chalk";import{configManager as o,DEFAULT_BASE_URL as r}from"../lib/config.js";import{i18n as t}from"../lib/i18n.js";import{toolManager as a}from"../lib/tool-manager.js";import{listAdapters as s}from"../lib/tools/registry.js";import{postApplyPrompts as l}from"../lib/post-apply.js";import{emitJson as n,isJsonMode as i}from"../lib/runtime-options.js";import{logger as u}from"../utils/logger.js";import{reportCliError as c,usageError as f,authenticationError as p,networkError as d,operationError as m}from"../lib/errors.js";import{gatewayAddresses as b,normalizeBaseUrl as y,probeGatewayAddress as g}from"../lib/gateway-addresses.js";import{CLI_NAME as h}from"../lib/brand.js";import{track as _}from"../lib/telemetry.js";import{forgetField as k,ownsValue as w,takeField as x}from"../lib/written-values.js";export async function baseCommand(a){const s=o.getBaseUrl(),l=addressesWithCurrent(),u=a?.trim().toLowerCase();if(!u)return void await async function(o,r){const a=savedApiKey(),s=await probeAll(o,{apiKey:a,samples:3});i()?n({ok:!0,current:r,addresses:o.map((e,o)=>({...e,...s[o],current:e.url===r}))}):(console.log(e.bold(t.t("base.current",{url:r}))),console.log(e.gray(t.t(a?"base.probe_with_key":"base.probe_without_key"))+"\n"),K(o,s,r),console.log("\n"+e.gray(t.t("base.usage_hint"))))}(l,s);if("auto"===u){const e=await probeAll(l,{apiKey:savedApiKey()}),o=e.find(e=>e.ok);if(!o){const o=e.every(e=>"key_rejected"===e.error);return j(o?"key_rejected":"no_reachable",t.t(o?"base.key_rejected_everywhere":"base.none_reachable")),void K(l,e,s)}return void await switchGatewayAddress(o.url,{auto:!0})}let c;if("default"===u||"reset"===u)c=r;else if(/^\d+$/.test(u)){if(c=l[Number(u)-1]?.url??null,!c)return void j("bad_index",t.t("base.bad_index",{index:u,count:String(l.length)}))}else if(c=y(a),!c)return void j("bad_url",t.t("base.bad_url",{value:a}));const f=await g(c,{apiKey:savedApiKey()});f.ok?await switchGatewayAddress(c):j("unreachable",t.t("base.unreachable",{url:c,reason:reasonText(f)}))}export async function ensureReachableGatewayAddress(a=savedApiKey(),s={}){if(o.hasRuntimeBaseUrl())return null;const l=o.getBaseUrl(),n=b(),u=await g(l,{apiKey:a});if("key_rejected"===u.error)return null;let c;if(u.ok){const e=n.findIndex(e=>e.url===l);if(e<=0||!w($(),l))return null;c=n.slice(0,e)}else c=n.filter(e=>e.url!==l);const f=(await probeAll(c,{apiKey:a})).find(e=>e.ok);if(!f)return null;if(u.ok?_("gateway-fallback","ok",{detail:{from:l,to:f.url,back:!0}}):_("gateway-fallback","fallback",{error:reasonText(u),detail:{from:l,to:f.url}}),!1===s.save?(o.setBaseUrl(f.url,!1),v=f.url):A(f.url,!0),!i())if(u.ok)console.log(e.yellow(t.t("base.setup_back",{from:l,url:f.url})));else{const o=f.url===r?"base.setup_fallback_main":"base.setup_fallback";console.log(e.yellow(t.t(o,{from:l,reason:reasonText(u),url:f.url})))}return f.url}let v=null;function $(){return`base_url_auto:${o.getActiveProfileName()}`}function A(e,t){e===r?o.resetBaseUrl():o.setBaseUrl(e,!0),t?x($(),e):k($())}export function saveGatewayFallback(){if(!v)return;const e=v;v=null,A(e,!0)}export function addressesWithCurrent(){const e=o.getBaseUrl(),r=b();return r.some(o=>o.url===e)||r.push({url:e,label:t.t("base.custom_label")}),r}export function savedApiKey(){return o.getApiKey()||s().map(e=>o.getApiKeyForTool(e.name)).find(Boolean)}export async function probeAll(e,o={}){return Promise.all(e.map(e=>g(e.url,o)))}export function probeSummary(o,r){if(!o.ok)return e.red(`× ${reasonText(o)}`);const a=[`${o.ms} ms`];return void 0!==o.models&&a.push(t.t("base.models_count",{count:String(o.models)})),r&&a.push(t.t("base.fastest")),e.green(`√ ${a.join(" · ")}`)}export function fastestIndex(e){let o=-1;return e.forEach((r,t)=>{r.ok&&(o<0||r.ms<e[o].ms)&&(o=t)}),o}export function reasonText(e){if(!e.error)return"";const o=t.t(`base.error_${e.error}`);return e.detail?`${o}(${e.detail})`:o}function j(e,o){const r="bad_index"===e||"bad_url"===e?f(o,t.t("errors.next_step",{command:`${h} base --help`}),e):"key_rejected"===e?p(o,t.t("errors.next_step",{command:`${h} setup --key ${t.t("errors.key_placeholder")}`}),e):d(o,t.t("base.next_addresses"),e);c(r)}function K(o,r,a){if(i())return;const s=r.length>1?fastestIndex(r):-1;o.forEach((o,l)=>{const n=o.url===a?e.cyan(` ← ${t.t("base.current_mark")}`):"";console.log(`${l+1}. ${o.url} ${e.gray(o.label)}\n ${probeSummary(r[l],l===s)}${n}`)})}export function toolsWeConfigured(){const e=[];for(const r of s()){const t=o.getApiKeyForTool(r.name);if(t&&(!r.ccSwitch?.handOver||!o.getMachineSetting(r.name,"ccswitch")))try{r.detectCurrentConfig().apiKey===t&&e.push({tool:r.name,apiKey:t})}catch(e){u.logError(`base.detectCurrentConfig(${r.name})`,e)}}return e}export async function moveToolsToCurrentAddress(e){const r=[],t=[];for(const{tool:s,apiKey:l}of e)try{await a.applyPrivateConfig(s,l,o.getModelsForTool(s)),r.push(s)}catch(e){t.push({tool:s,reason:e instanceof Error?e.message:String(e)})}return{applied:r,failed:t}}export async function moveOtherToolsAfterFallback(o){if(0===o.length)return[];const{applied:r,failed:s}=await moveToolsToCurrentAddress(o);if(_("gateway-fallback-tools",s.length>0?"fail":"ok",{detail:{applied:r,failed:s.map(e=>e.tool)}}),!i()){r.length>0&&console.log(t.t("base.other_tools_moved"));for(const e of r)a.printApplied(e);for(const{tool:o,reason:r}of s)console.error(e.red(`× ${t.t("setup.apply_failed",{tool:o,reason:r})}`))}return r}export async function switchGatewayAddress(r,s={}){const u=o.getBaseUrl(),f=toolsWeConfigured();A(r,Boolean(s.auto));const{applied:p,failed:d}=await moveToolsToCurrentAddress(f);if(d.length>0&&c(m(d.map(({tool:e,reason:o})=>`${e}: ${o}`).join("; "),t.t("errors.next_step",{command:`${h} setup --key ${t.t("errors.key_placeholder")}`}),"config_write_failed")),i()&&0===d.length)n({ok:0===d.length,previous:u,base_url:r,applied:p,failed:d});else{console.log(e.green(t.t(r===u?"base.kept":"base.switched",{url:r}))),p.length>0&&console.log(t.t("base.tools_moved"));for(const e of p)a.printApplied(e);for(const{tool:o,reason:r}of d)console.error(e.red(`× ${t.t("setup.apply_failed",{tool:o,reason:r})}`));0===p.length&&0===d.length&&console.log(e.yellow(t.t("base.no_tools",{url:r}))),await l(p)}}
@@ -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 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"])}
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 i,moveOtherToolsAfterFallback as l,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 _,authenticationError as k,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 S}from"../lib/runtime-options.js";import{appsForTools as M,appUpgradeCommand as I,getApp as O}from"../lib/app-update.js";import{join as A}from"path";import{confirmAction as N}from"../lib/confirm.js";import{asksBeforeWriting as G,confirmWritePlan as E,printWritePlan as B,toolWritePlan as P}from"../lib/write-plan.js";import D from"inquirer";import{logger as F}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,buildCcSwitchCards as H,ccSwitchContext as W,isAdditiveCcSwitchApp as J,inspectCcSwitch as Q,quitCcSwitch as X,writeCcSwitchCards as Z}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 ee(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 oe(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 te(o){console.log(e.green(o))}function ie(o){console.log(e.yellow(o))}function le(o){console.error(e.red(o))}let se=null;function ae(e){const o={operation:1,authentication:2,network:3};(!se||o[e]>o[se])&&(se=e)}async function ne(o,t){T()||console.log(e.gray(n.t("setup.validating",{label:o})));const i=await d(t);if(i.valid)return!0;const l=n.t("errors.key_placeholder"),s="--key"===o?`${L} setup --key ${l}`:`${L} setup ${o} ${l}`;let a;if("network_error"===i.error?(ae("network"),a=w(n.t("setup.unreachable",{url:r.getBaseUrl(),reason:i.message||"network error"}),`${L} base auto`,"network_error")):"invalid_api_key"===i.error?(ae("authentication"),a=k(n.t("setup.invalid_key",{label:o,reason:i.message||"invalid"}),s,"invalid_api_key")):(ae("operation"),a=_(n.t("setup.validate_failed",{label:o,reason:i.message||i.error||"unknown"}),s,i.error)),T())throw a;return le(a.message),console.log(e.gray(n.t("errors.next_step",{command:a.hint}))),!1}async function re(t,i,l={}){const{oneMillion:s,officialLogin:a,desktopRegistry:d,force:u,takeOver:m}=l,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,i,r.getModelsForTool(t),{force:u,takeOver:m})}catch(e){if(T())throw _(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 le("× "+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 ce(e){return!o(e)?.isInstalled&&!c.isToolInstalled(e)}async function pe(e){if(C())return!0;const o=p[e]?.displayName??e;return v()?N({message:n.t("setup.ask_detected_tool",{tool:o}),defaultValue:!0}):(ie(n.t("setup.detected_tool_hint",{tool:o,name:e})),!1)}export async function installMissingApps(o,t,i){const l=M(o).filter(e=>{if(i&&!i.includes(e))return!1;const o=O(e)?.appInstaller;try{return Boolean(o&&!o.blocker()&&!o.installedPath())}catch(o){return F.logError(`setup: app installed? ${e}`,o),!1}});if(0===l.length)return!1;const s=e=>O(e)?.displayName??e;let a=t;if(void 0===a&&!T())if(S())a=!$();else if(v()){const e=l.map(s).join(n.t("setup.list_separator")),o=l.reduce((e,o)=>e+(O(o)?.appInstaller.sizeMb()??0),0);console.log(""),a=(await D.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 l)console.log(e.gray(n.t("setup.install_app_hint",{tool:s(o),command:I(o)})));return Boolean(a)}function de(e){ie(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 ue(o,t,i=[]){const l=P(o),s=A(r.getConfigDir(),"config.yaml");if(T())x({dry_run:!0,tools:l,install_first:i,key_file:t?s:null});else{if(0===l.length&&0===i.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(l,{label:n.t("runtime.dry_run_label"),keyFile:t?s:void 0,installFirst:i})}}function fe(e){return Boolean(o(e)?.installSpec||O(e)?.appInstaller)}function me(e){return M(e).filter(e=>{const o=O(e);if(!o||o.tool===e)return!1;try{return!o.appInstaller.blocker()}catch(o){return F.logError(`setup: app blocker ${e}`,o),!1}})}function ge(e){const o=O(e);let t,i;if(o&&o.tool!==e){try{t=Boolean(o.appInstaller.installedPath())}catch(o){F.logError(`setup: app installed? ${e}`,o),t=!1}i=t?o.installedVersion?.():null}else t=c.isToolInstalled(e),i=t?c.installedVersion(e):null;return t?i?n.t("setup.pick_installed",{version:i}):n.t("setup.pick_installed_plain"):n.t("setup.pick_not_installed")}function he(o,t){return{name:`${O(o)?.displayName??p[o]?.displayName??o} ${e.gray(ge(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 ye(){return"darwin"===process.platform||"win32"===process.platform||c.isToolInstalled("claude-desktop")}export async function setupCommand(d){se=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 k=d.upgrade??[],w=V(k);if(w.length>0)return le(n.t("upgrade.unsupported",{tool:w.join(", ")})),void(process.exitCode=b.usage);if(k.length>0&&(K()?console.log(n.t("setup.dry_run_upgrade",{tools:k.join(", ")})):(await Y(k),q()),!y&&0===u.length&&!h))return;y||0!==u.length||h||!G()||(y=(await D.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 M;if(j&&(M=parseOnOff(d.claudeOfficial),void 0===M))return le(n.t("setup.claude_official_invalid",{value:String(d.claudeOfficial)})),void(process.exitCode=1);const I=void 0!==d.desktopRegistry;let B;if(I&&(B=parseOnOff(d.desktopRegistry),void 0===B))return le(n.t("setup.desktop_registry_invalid",{value:String(d.desktopRegistry)})),void(process.exitCode=1);const P=j||I,ae=Boolean(y||u.length>0),ge={oneMillion:d.oneMillion,officialLogin:M,desktopRegistry:B,force:d.force};if(!ae&&(x||P)&&K())return void ue([...x?["codex"]:[],...P?["claude-desktop"]:[]],!1);if(!ae&&(x||P)){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),te(n.t(o?"setup.codex_1m_enabled":"setup.codex_1m_disabled"))}catch(e){le(n.t("setup.apply_failed",{tool:p.codex.displayName,reason:e instanceof Error?e.message:String(e)})),process.exitCode=1}else le(n.t("setup.codex_1m_missing_key")),process.exitCode=1}if(P){const e=r.getApiKeyForTool("claude-desktop");e?await re("claude-desktop",e,{...ge,oneMillion:void 0,takeOver:!0})?await t(["claude-desktop"],{apps:{install:!1}}):process.exitCode=1:(le(n.t("setup.desktop_official_login_missing_key")),process.exitCode=1)}return}if(!ae)return le(n.t("setup.usage")),void(process.exitCode=1);const _e=d.ccswitchUse?"use":d.ccswitch?"add":null,ke=_e?await async function(){let e,o=await Q();if("running"===o.problem&&!K()&&(C()||v())&&(C()||await N({message:n.t("ccswitch.ask_quit"),defaultValue:!0}))){const t=X();t&&(e=t.reopen,o=await Q())}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 _(t,`${L} setup --key ${n.t("errors.key_placeholder")}`,`ccswitch_${o.problem}`);return le(t),e?.(),null}():null;if(_e&&!ke)return void(process.exitCode=1);const we=K(),be=we?null:await i(y||u[0].apiKey,{save:!1}),ve=[],xe=[];let Ce,je=0,Ke=0;const Te=new Set,$e=u.map(e=>({tool:e.tool,label:`--${e.option}`,apiKey:e.apiKey,need:e.need}));for(const e of $e){if(!await ne(e.label,e.apiKey)){Ke+=1;continue}const o=await ee(e.apiKey);!o.probed||oe(o,e.need)?(o.probed||ie(n.t("setup.probe_failed",{label:e.label})),ve.push({tool:e.tool,apiKey:e.apiKey,dedicated:!0}),Te.add(e.tool)):(le(n.t(`setup.key_no_${e.need}`,{label:e.label,tool:p[e.tool].displayName})),Ke+=1)}const Se=!!y&&await ne("--key",y);y&&!Se&&(Ce=b[se??"operation"]);const Me=y&&Se?await ee(y):void 0;y&&Me&&!Me.probed&&ie(n.t("setup.probe_failed",{label:"--key"})),!(y&&Me&&Me.probed)||Me.hasClaude||Me.hasGpt||Me.hasGrok||Me.hasGemini||(le(n.t("setup.key_no_family")),Ce=1);const Ie=Boolean(y)&&0===u.length&&!d.fromInstaller&&G()&&!_e;if(y&&Me&&void 0===Ce){const e=Me.hasClaude||Me.hasGpt||Me.hasGrok||Me.hasGemini,o=[{tool:"claude-code",capable:Me.hasClaude,skipMsg:n.t(ye()?"setup.skip_no_claude_desktop":"setup.skip_no_claude")},{tool:"codex",capable:Me.hasGpt,skipMsg:n.t("setup.skip_no_gpt")},{tool:"grok",capable:Me.hasGrok,skipMsg:n.t("setup.skip_no_grok")},{tool:"claude-desktop",capable:Me.hasClaude&&ye(),skipMsg:"",quiet:!0},{tool:"agy",capable:Me.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)Te.has(e.tool)||(e.capable?(!e.ask||we||Ie||await pe(e.tool))&&(ve.push({tool:e.tool,apiKey:y,dedicated:!1}),Te.add(e.tool)):e.quiet||ie(e.skipMsg))}let Oe,Ae=d.install,Ne=[];if(Ie&&void 0===Ce&&ve.length>0){const e=await async function(e,o){console.log("");const{configure:t}=await D.prompt([{type:"checkbox",name:"configure",message:n.t("setup.pick_configure"),choices:e.map(e=>he(e,!0))}]);let i=[];const l=[...e.filter(fe),...me(e)];if(o&&l.length>0){const e=e=>O(e)?.tool??e;i=(await D.prompt([{type:"checkbox",name:"upgrade",message:n.t("setup.pick_upgrade"),choices:l.map(o=>he(o,t.includes(e(o))))}])).upgrade}return 0===t.length&&0===i.length?(console.log(n.t("setup.pick_none")),null):{configure:t,upgrade:i}}(ve.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,Oe=[],!0!==Ae&&(Ae=!1);const o=e.configure.filter(e=>ce(e)&&!Ne.includes(e)&&!Ae);if(o.length>0&&ie(n.t("setup.pick_configure_skip",{tools:o.map(e=>p[e].displayName).join(n.t("setup.list_separator"))})),ve.splice(0,ve.length,...ve.filter(t=>e.configure.includes(t.tool)&&!o.includes(t.tool))),0===ve.length)return void(Ne.length>0&&await Y(Ne))}const Ge=Boolean(y&&Se&&void 0===Ce);if(_e&&ke)return void 0!==Ce&&0===ve.length?(ke.reopen?.(),void(process.exitCode=Ce)):(await async function(i,l,a,d,u,f){const m=i.filter(e=>c.supportsCcSwitch(e.tool)),g=i.filter(e=>!c.supportsCcSwitch(e.tool)),h=e=>e.map(e=>p[e.tool].displayName).join(n.t("setup.list_separator"));if(g.length>0&&ie(n.t("ccswitch.not_supported",{tools:h(g)})),0===m.length)return le(n.t("ccswitch.nothing")),a.reopen?.(),void(process.exitCode=1);const y=m.filter(e=>o(e.tool)?.ccSwitch?.handOver&&!r.getMachineSetting(e.tool,z)&&c.holdsOurConfig(e.tool)),_=n.t(l?"ccswitch.plan_use":"ccswitch.plan_add",{tools:h(m),path:a.state.dbPath})+(y.length>0?"\n"+n.t("ccswitch.plan_handover",{tools:h(y)}):"");if(K())return void console.log(_);if(!f&&G()&&(console.log(_),!await N({message:n.t("ccswitch.confirm"),defaultValue:!0})))return a.reopen?.(),void(process.exitCode=b.cancelled);s(),d();const k=[],w=[];for(const t of m){const i=p[t.tool].displayName,s=o(t.tool).ccSwitch;try{const o=await W(t.tool,t.apiKey,r.getModelsForTool(t.tool)),a=H(t.tool,o);if(0===a.cards.length){ie(n.t("ccswitch.no_models",{tool:i}));continue}if(s.handOver&&c.holdsOurConfig(t.tool)&&(c.unloadPrivateConfig(t.tool),r.getMachineSetting(t.tool,z)||console.log(e.gray(" "+n.t("ccswitch.handed_over",{tool:i})))),l&&ce(t.tool))ie(n.t("ccswitch.not_installed_card_only",{tool:i}));else if(l&&s.applyAsCards)s.applyAsCards({...o,takeOver:!0},a.cards),k.push(t.tool);else if(l){if(!await re(t.tool,t.apiKey,{...u,takeOver:!0}))continue;k.push(t.tool)}w.push({tool:t.tool,group:{...a,current:k.includes(t.tool)}})}catch(e){le("× "+n.t("ccswitch.card_failed",{tool:i,reason:e instanceof Error?e.message:String(e)}))}}try{const o=w.length>0?await Z(w.map(e=>e.group)):[];o.forEach((e,o)=>{const t=w[o].tool,i=p[t].displayName;r.setMachineSetting(t,z,k.includes(t)?"use":"add");const l=String(e.written),s=e.current?J(e.app)?"ccswitch.done_enabled":"ccswitch.done_use":k.includes(t)&&e.proxyMode?"ccswitch.done_proxy":e.written>1?"ccswitch.done_add_many":"ccswitch.done_add";te(n.t(s,{tool:i,count:l})),e.skipped.length>0&&ie(n.t("ccswitch.skipped_foreign",{tool:i,ids:e.skipped.join(", ")}))}),U("ccswitch","ok",{detail:{mode:l?"use":"add",schema:a.state.schema,tools:w.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:a.state.schema}}),le("× "+n.t("ccswitch.write_failed",{reason:e instanceof Error?e.message:String(e)})),process.exitCode=1}a.reopen?.(),k.length>0&&await t(k,{apps:{install:!1}}),w.length<m.length&&(process.exitCode=1)}(ve,"use"===_e,ke,()=>{Ge&&y&&r.setApiKey(y);for(const e of ve)e.dedicated?r.setToolApiKey(e.tool,e.apiKey):r.clearToolApiKey(e.tool)},ge,Boolean(d.fromInstaller)),void(void 0!==Ce&&(process.exitCode=Ce)));if(we)return ue(ve.filter(e=>!ce(e.tool)).map(e=>e.tool),ve.length>0,ve.filter(e=>ce(e.tool)).map(e=>e.tool)),void((Ke>0||void 0!==Ce)&&(process.exitCode=Ce??b[se??"operation"]));const Ee=ve.filter(e=>!ce(e.tool)),Be=Ge||ve.some(e=>e.dedicated),Pe=be?a().filter(e=>!ve.some(o=>o.tool===e.tool)):[],De=!d.fromInstaller&&G();if((ve.length>0||Be)&&!d.fromInstaller&&!await E([...Ee.map(e=>e.tool),...Pe.map(e=>e.tool)],{keyFile:Be?A(r.getConfigDir(),"config.yaml"):void 0,installFirst:ve.filter(e=>ce(e.tool)).map(e=>e.tool)}))return void(process.exitCode=b.cancelled);Ne.length>0&&(await Y(Ne),q()),(ve.length>0||Be)&&s(),Ge&&y&&r.setApiKey(y);for(const e of ve)ce(e.tool)?(e.dedicated&&r.setToolApiKey(e.tool,e.apiKey),xe.push({tool:e.tool,apiKey:e.apiKey,dedicated:e.dedicated})):await re(e.tool,e.apiKey,{...ge,takeOver:e.dedicated||De})?(e.dedicated?r.setToolApiKey(e.tool,e.apiKey):r.clearToolApiKey(e.tool),je+=1):(Ke+=1,Te.delete(e.tool));const Fe=ve.length>0||Be?await l(Pe):[];if(void 0!==Ce)return xe.length>0&&de(xe.map(e=>e.tool)),void(process.exitCode=Ce);let qe=[];if(xe.length>0){const o=await async function(o,t,i){const l=o.map(e=>e.tool);if(0===l.length)return{still:[],applied:[],failed:[]};const s=l.map(e=>p[e].displayName).join(n.t("setup.list_separator"));let a=t;if(void 0!==a||T()||(S()?a=!$():process.stdin.isTTY&&(console.log(""),a=(await D.prompt([{type:"confirm",name:"go",message:n.t("setup.install_confirm",{tools:s}),default:!0}])).go)),!a){console.log("");for(const o of l)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:l,applied:[],failed:[]}}const d=[];for(const o of l){console.log(e.bold(`\n${p[o].displayName}`));try{await c.installTool(o)}catch(e){F.logError(`setup: install ${o}`,e)}q(),c.isToolInstalled(o)||d.push(o)}const u=l.filter(e=>!d.includes(e));u.length>0&&console.log("");const f=[],m=[];for(const{tool:e,apiKey:t,dedicated:l}of o.filter(e=>u.includes(e.tool)))await re(e,t,i)?(f.push(e),l||r.clearToolApiKey(e)):m.push(e);return{still:d,applied:f,failed:m}}(xe,Ae,ge);qe=o.still,je+=o.applied.length,Ke+=o.failed.length;for(const e of[...qe,...o.failed])Te.delete(e)}if(je>0){const t=[...Te].filter(e=>!o(e)?.isInstalled&&!qe.includes(e)),i=t.map(e=>p[e]?.command).filter(Boolean).join(" / "),l=n.t("setup.done",{count:String(je)});te("\n"+(i?`${l}${n.t("setup.done_commands",{commands:i})}`:l)),qe.length>0&&de(qe);for(const e of t){const o=c.ensureNativeOnPath(e);o&&te(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===je&&qe.length>0&&de(qe),Ke>0&&(le(n.t("setup.failed_summary",{count:String(Ke)})),T()||console.error(`${L} setup --key ${n.t("errors.key_placeholder")}`)),await t([...Te,...Fe],{apps:{install:await installMissingApps([...Te],Ae,Oe)}}),(Ke>0||0===je&&0===qe.length)&&(process.exitCode=b[se??"operation"])}
@@ -1 +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()}}
1
+ import{existsSync as t,mkdirSync as e,readFileSync as r,readdirSync as n,rmSync as o}from"fs";import{join as i}from"path";import{spawn as s,spawnSync as c}from"child_process";import{BRAND_NAME as p,CLI_NAME as a,PROVIDER_KEY as u,brandEnv as d}from"./brand.js";import{toolHome as l}from"./tools/types.js";import{atomicWriteFile as f,backupBeforeWrite as h}from"./tools/backup.js";import{columnsOf as m,openSqlite as g,rollback as w}from"./sqlite.js";import{KEY_INFO_PATH as _}from"./gateway-protocol.js";import{configManager as E}from"./config.js";import{logger as S}from"../utils/logger.js";import{getAdapter as y}from"./tools/registry.js";import{resolveModelCatalog as b}from"./model-catalog.js";import{gatewayAddresses as v}from"./gateway-addresses.js";export const CCSWITCH_SETTING="ccswitch";export const CCSWITCH_SCHEMAS=[29,30];const C=["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","claude-desktop":"currentProviderClaudeDesktop",grokbuild:"currentProviderGrokbuild",agy:"currentProviderAgy"},x=new Set(["workbuddy","codebuddy","dsh"]);export function isAdditiveCcSwitchApp(t){return x.has(t)}export function ccSwitchCardId(){return`${u}-${a}`}function T(){return Boolean(d("TEST_HOME")?.trim())}export function ccSwitchDeviceDir(){return i(l(),".cc-switch")}export function ccSwitchDataDir(){try{const e=JSON.parse(r(function(){const t=l(),e="com.ccswitch.desktop";if("darwin"===process.platform)return i(t,"Library","Application Support",e,"app_paths.json");if("win32"===process.platform){const r=!T()&&process.env.APPDATA?process.env.APPDATA:i(t,"AppData","Roaming");return i(r,e,"app_paths.json")}const r=!T()&&process.env.XDG_DATA_HOME?process.env.XDG_DATA_HOME:i(t,".local","share");return i(r,e,"app_paths.json")}(),"utf-8")).app_config_dir_override;if("string"==typeof e&&e.trim()){const r=e.trim(),n="~"===r?l():r.startsWith("~/")||r.startsWith("~\\")?i(l(),r.slice(2)):r;if(t(n))return n}}catch{}return ccSwitchDeviceDir()}export function ccSwitchDbPath(){return i(ccSwitchDataDir(),"cc-switch.db")}function N(t){try{const e=JSON.parse(r(i(ccSwitchDeviceDir(),"live-state.json"),"utf-8")),n=e.apps?.[t]?.mode;return"string"==typeof n?n:"direct"}catch{return"direct"}}const P=(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 M=P,R=null;export function setCcSwitchRunningForTests(t){R=t}export function setCcSwitchRunnerForTests(t){M=t??P}export function isCcSwitchRunning(){return null!==R?R:!T()&&("win32"===process.platform?/cc-switch\.exe/i.test(M("tasklist",["/FI","IMAGENAME eq cc-switch.exe","/NH"]).stdout):0===M("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 M("powershell.exe",["-NoProfile","-NonInteractive","-Command","(Get-Process -Name cc-switch -ErrorAction SilentlyContinue | Select-Object -First 1).Path"]).stdout.trim()||null;const t=M("pgrep",["-x","cc-switch"]).stdout.trim().split(/\s+/)[0];return t&&M("readlink",[`/proc/${t}/exe`]).stdout.trim()||null}();"darwin"===process.platform?M("osascript",["-e",'tell application id "com.ccswitch.desktop" to quit']):"win32"===process.platform?M("taskkill",["/IM","cc-switch.exe","/F"]):M("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){S.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 g(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"),o=m(r,"provider_endpoints"),i=[...C.filter(t=>!n.has(t)),...A.filter(t=>!o.has(t)).map(t=>`provider_endpoints.${t}`)];return i.length>0?{ok:!1,problem:"unexpected_tables",schema:t,dbPath:e,detail:i.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 k(){return`({\n request: {\n url: "{{baseUrl}}".replace(/\\/+$/, "").replace(/\\/v1(beta)?$/, "") + "${_}",\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 H(e,n){const o=i(ccSwitchDeviceDir(),"settings.json");let s={};try{s=JSON.parse(r(o,"utf-8"))}catch{}const c=D[e];c&&s[c]!==n&&(t(o)&&h(o),f(o,JSON.stringify({...s,[c]:n},null,2)+"\n",384))}function I(t){try{const e="string"==typeof t?JSON.parse(t):null;return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}catch{return{}}}export async function writeCcSwitchCards(t){const r=await g(ccSwitchDbPath());if("string"==typeof r)throw new Error(r);const s=r,c=Date.now(),a=[],u=[];try{s.exec("PRAGMA busy_timeout = 5000"),function(t){const r=i(E.getConfigDir(),"backups"),s=i(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)o(i(r,t),{force:!0})}catch(t){S.logError("ccswitch.snapshotDb",t)}}(s),s.exec("BEGIN IMMEDIATE");for(const e of t){const t=x.has(e.app),r=!t&&"proxy"===N(e.app),n=Boolean(e.current)&&!r,o=e.endpoints[0]?.replace(/\/v1$/,"")??E.getBaseUrl(),i=[],d=[];for(const r of e.cards){const a=r.id??ccSwitchCardId(),u=s.prepare("SELECT meta, settings_config FROM providers WHERE id = ? AND app_type = ?").all(a,e.app);if(u.length>0&&e.owns&&!e.owns(a,I(u[0].settings_config))){d.push(a);continue}const l={...I(u[0]?.meta),usage_script:{enabled:!0,language:"javascript",code:k(),timeout:10},...r.meta};t&&void 0!==e.current&&(l.liveConfigManaged=n);const f=JSON.stringify(r.settingsConfig),h=r.name??p;if(u.length>0)s.prepare("UPDATE providers SET name = ?, settings_config = ?, website_url = ?, meta = ? WHERE id = ? AND app_type = ?").run(h,f,o,JSON.stringify(l),a,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(a,e.app,h,f,o,c,Number(t.next),JSON.stringify(l))}s.prepare("DELETE FROM provider_endpoints WHERE provider_id = ? AND app_type = ?").run(a,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(a,e.app,t,c);i.push(a)}if(e.owns){const t=s.prepare("SELECT id, settings_config FROM providers WHERE app_type = ?").all(e.app);for(const r of t)!i.includes(r.id)&&e.owns(r.id,I(r.settings_config))&&(s.prepare("DELETE FROM provider_endpoints WHERE provider_id = ? AND app_type = ?").run(r.id,e.app),s.prepare("DELETE FROM providers WHERE id = ? AND app_type = ?").run(r.id,e.app))}if(n&&!t&&i.length>0){const t=i[0];s.prepare("UPDATE providers SET is_current = 0 WHERE app_type = ? AND id <> ?").run(e.app,t),s.prepare("UPDATE providers SET is_current = 1 WHERE app_type = ? AND id = ?").run(e.app,t),D[e.app]&&u.push({app:e.app,id:t})}a.push({app:e.app,written:i.length,skipped:d,current:n&&i.length>0,proxyMode:r})}s.exec("COMMIT")}catch(t){throw w(s),t}finally{s.close()}for(const{app:t,id:e}of u)H(t,e);return a}export async function ccSwitchContext(t,e,r){const n=y(t),o=n?.wantsModelCatalog?await b(e):null;return{apiKey:e,baseUrl:E.getBaseUrl(),models:r,settings:E.getToolSettings(t),...o?{catalog:o}:{}}}export function buildCcSwitchCards(t,e){const r=y(t)?.ccSwitch;if(!r)return null;const n=e.baseUrl.replace(/\/+$/,"").replace(/\/v1$/,""),o=[n,...v().map(t=>t.url.replace(/\/+$/,"")).filter(t=>t!==n)];return{app:r.app,cards:r.cards(e),endpoints:o.map(t=>t+r.endpointPath),...r.owns?{owns:r.owns.bind(r)}:{}}}export async function hasCcSwitchCards(e){if(!t(ccSwitchDbPath()))return!1;const r=await g(ccSwitchDbPath());if("string"==typeof r)return!1;try{const t=r.prepare("SELECT id, settings_config FROM providers WHERE app_type = ?").all(e.app),n=new Set(e.cards.map(t=>t.id??ccSwitchCardId()));return t.some(t=>n.has(t.id)||Boolean(e.owns?.(t.id,I(t.settings_config))))}catch{return!1}finally{r.close()}}
@@ -1 +1 @@
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
+ 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 c}from"./tools/registry.js";import{UserActionNeeded as a}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 u}from"./telemetry.js";import{CCSWITCH_SETTING as p,buildCcSwitchCards as g,ccSwitchContext as y,hasCcSwitchCards as M,inspectCcSwitch as w,writeCcSwitchCards as k}from"./ccswitch.js";export const MODEL_REFRESH_INTERVAL_MS=36e5;export const MODEL_REFRESH_OFFLINE_RETRY_MS=6e5;const _=new Set(["setup","init","config","auth","enter","completion","update","lang","logs","refresh"]),j=["--json","--dry-run","--help","-h","--version","-v"],E=[];export function shouldSkipModelRefresh(e,o=process.env){if("1"===o[d("DISABLE_MODEL_REFRESH")])return!0;if(j.some(o=>e.includes(o))||m(e))return!0;const t=e.find(e=>!e.startsWith("-"));return void 0!==t&&_.has(t)}let R={checked:0,failed:0,offline:0,keyMismatch:[]};export function lastModelRefreshOutcome(){return{...R,keyMismatch:[...R.keyMismatch]}}export async function refreshModelMenus(e={}){const o=[],t=new Map,n=[];E.length=0,R={checked:0,failed:0,offline:0,keyMismatch:[]};for(const e of c())if(e.refreshModelMenu&&e.listedModels)try{let s=r.getApiKeyForTool(e.name);if(!s)continue;const c=e.detectCurrentConfig().apiKey;if(c&&c!==s&&c===r.getApiKey()&&(r.clearToolApiKey(e.name),s=c),e.ccSwitch&&r.getMachineSetting(e.name,p)&&(o.push({name:e.name,apiKey:s}),c!==s||e.ccSwitch.handOver))continue;if(c!==s){c&&(R.keyMismatch.push(e.displayName),u(`menu-sync:${e.name}`,"skip",{detail:{reason:"key_mismatch"}}));continue}const a=e.listedModels();if(null===a)continue;t.has(s)||t.set(s,await i(s));const l=t.get(s);if(!l){R.offline++;continue}e.refreshModelMenu({apiKey:s,baseUrl:r.getBaseUrl(),models:r.getModelsForTool(e.name),settings:r.getToolSettings(e.name),catalog:l}),R.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=>!a.includes(e)),h=a.filter(e=>!m.includes(e));(d.length>0||h.length>0)&&n.push({tool:e.displayName,added:d,removed:h})}catch(o){R.failed++,l.logError(`modelRefresh(${e.name})`,o),u(`menu-sync:${e.name}`,o instanceof a?"skip":"fail",{error:o}),o instanceof a&&E.push(o.message)}return await async function(e,o){if(0===e.length)return;const t=await w();if(!t.ok)return void("running"===t.problem&&o&&E.push(s.t("ccswitch.refresh_running")));const n=[];for(const o of e){const e=g(o.name,await y(o.name,o.apiKey,r.getModelsForTool(o.name)));e&&e.cards.length>0&&await M(e)&&n.push(e)}if(0!==n.length)try{await k(n),u("menu-sync:ccswitch","ok",{detail:{apps:n.map(e=>e.app),schema:t.schema}})}catch(e){l.logError("modelRefresh(ccswitch)",e),u("menu-sync:ccswitch","fail",{error:e})}}(o,Boolean(e.explicit)),n}export async function runModelRefresh(r,i={}){const c=i.env??process.env,a=i.now??Date.now(),m=function(e){return t(o(f(e)),"model-refresh.json")}(c);if(!i.force){if(shouldSkipModelRefresh(r,c))return[];if(a-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=R.offline>0&&0===R.checked&&0===R.failed,o=e?a-36e5+6e5:a;e&&u("menu-sync","skip",{detail:{reason:"offline",tools:R.offline}}),h(m,JSON.stringify({refreshed_at:o})+"\n")}catch(e){l.logError("runModelRefresh",e)}const p=i.output??(e=>console.log(n.gray(e)));for(const e of E)p(e);for(const e of d){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 d}
@@ -1 +1 @@
1
- import{chmodSync as t,existsSync as r,readFileSync as e}from"fs";import{join as n}from"path";import{i18n as o}from"../i18n.js";import{prettyModelName as i}from"../gateway-models.js";import{getAgyRules as a}from"../model-registry.js";import{logger as l}from"../../utils/logger.js";import{persistentEnvApplied as s,readPersistentEnvFile as c,removePersistentEnv as u,writePersistentEnv as p}from"../persistent-env.js";import{backupBeforeWrite as m,atomicWriteFile as d}from"./backup.js";import{findInstalls as g,mirrorInstallCommand as y}from"./tool-installs.js";import{toolHome as f}from"./types.js";import{brand as h,PROVIDER_KEY as v}from"../brand.js";const A="agy",_="AGY_LLM_GATEWAY_URL",E="AGY_LLM_GATEWAY_API_KEY",j="AGY_LLM_GATEWAY_MODELS",w=["GEMINI_API_KEY","GOOGLE_GEMINI_BASE_URL"],K="gemini",b=()=>n(f(),".gemini","antigravity-cli"),I=()=>n(b(),"settings.json"),P=()=>n(b(),`${v}.env`),M=()=>n(f(),".antigravity","settings.json"),G=h().installMirror?.agy,L={command:"agy",native:{binDir:"win32"===process.platform?["AppData","Local","agy","bin"]:[".local","bin"],updateArgs:["update"],dataDirs:[]},...G?{mirrorScript:{sh:`${G}/install.sh`,ps1:`${G}/install.ps1`}}:{}};function $(t){return!!t&&"object"==typeof t&&!Array.isArray(t)}function C(t,n){if(!r(t))return{};const o=e(t,"utf-8");if(!o.trim())return{};try{const t=JSON.parse(o);if(!$(t))throw new Error(`${n} root must be an object`);return t}catch(t){throw new Error(`Existing ${n} cannot be parsed; back it up and fix it first: ${t instanceof Error?t.message:String(t)}`)}}const N=()=>C(I(),"~/.gemini/antigravity-cli/settings.json"),S=()=>C(M(),"~/.antigravity/settings.json");function Y(r,e,n){m(r),d(r,JSON.stringify(e,null,2)+"\n",n),void 0!==n&&t(r,n)}function x(t){return(t||"").replace(/\/+$/,"").replace(/\/v1(beta)?$/,"")}const k=/-(minimal|low|medium|high|xhigh|max)$/;function O(t){const r=a().gatewayModels,e=t?r.filter(r=>t.models.includes(r)||t.models.includes(r.replace(k,""))):[];return e.length>0?e:r}function U(t){const r=t.replace(/-preview$/,""),e=k.exec(r)?.[1];return e?`${i(r.replace(k,""))} (${e[0].toUpperCase()}${e.slice(1)})`:i(r)}function D(t){const r=t.gateway;return $(r)&&!0===r.enabled&&"string"==typeof r.apiKey&&r.apiKey.trim()&&"string"==typeof r.url?{url:r.url,apiKey:r.apiKey}:null}function R(t){const r=t.models;return $(r)&&Array.isArray(r.list)?r.list.map(t=>$(t)&&"string"==typeof t.modelId?t.modelId:"").filter(Boolean):[]}function T(){try{if(N().modelProvider!==K)return null}catch{return null}const t=c(P()),r=t.GEMINI_API_KEY;return r&&r.trim()?{apiKey:r,url:t.GOOGLE_GEMINI_BASE_URL??""}:null}function B(t){const r=c(P());return r[_]===t.url&&r[E]===t.apiKey}function W(t,r,e){const n=N(),o=S();o.gateway={...$(o.gateway)?o.gateway:{},enabled:!0,url:r,apiKey:t,wireProtocol:"genai"},o.models={...$(o.models)?o.models:{},defaultModelId:e[0],list:e.map(t=>({modelId:t,displayName:U(t),supportsThinking:!0}))},Y(M(),o,384),w.some(t=>void 0!==c(P())[t])&&u(A,P(),w);const i=p(A,P(),{[_]:r,[E]:t,[j]:e.join(",")}).rcFiles;for(const t of w)delete process.env[t];return n.modelProvider===K&&(delete n.modelProvider,Y(I(),n)),i}let J=null,F=null;export const antigravityAdapter={name:"agy",displayName:"Antigravity CLI",command:"agy",installCommand:y(L),installSpec:L,configPath:M(),wantsModelCatalog:!0,loadPrivateConfig(t){N(),S();const r=O(t.catalog);J=W(t.apiKey,x(t.baseUrl),r),F=r},unloadPrivateConfig(){try{const t=S();D(t)&&(delete t.gateway,delete t.models,Y(M(),t,384))}catch(t){l.logError("antigravityAdapter.unloadPrivateConfig",t)}try{const t=N();t.modelProvider===K&&(delete t.modelProvider,Y(I(),t))}catch(t){l.logError("antigravityAdapter.unloadPrivateConfig",t)}u(A,P(),[_,E,j,...w])},detectCurrentConfig(){try{const t=D(S());if(t)return{apiKey:t.apiKey}}catch{return{apiKey:null}}return{apiKey:T()?.apiKey??null}},listedModels(){try{const t=S(),r=D(t);if(r)return B(r)?R(t):[]}catch{return null}return T()?[]:null},refreshModelMenu(t){const r=S(),e=D(r)??T();if(!e)return;const n=O(t.catalog),o=e.url||x(t.baseUrl),i=D(r);null!==i&&B(i)&&R(r).join(",")===n.join(",")&&c(P())[j]===n.join(",")&&s(P())&&null===T()||W(e.apiKey,o,n)},getConfig(){try{return S()}catch(t){return l.logError("antigravityAdapter.getConfig",t),null}},applyNotes(){const t=[];if(F&&F.length>0){const r=F.map(U);t.push({kind:"summary",text:o.t("tools.agy.menu_written",{count:String(r.length),list:r.join(o.t("tools.grok.list_separator")),default:r[0]})})}return null===J||0===g(L).length||t.push({kind:"action",text:o.t("tools.agy.open_new_terminal")}),t},backupPaths:()=>[M(),I(),P()],forceResetPaths:()=>[P()]};
1
+ import{chmodSync as t,existsSync as e,readFileSync as r}from"fs";import{join as n}from"path";import{i18n as o}from"../i18n.js";import{prettyModelName as i}from"../gateway-models.js";import{getAgyRules as a}from"../model-registry.js";import{logger as l}from"../../utils/logger.js";import{persistentEnvApplied as s,readPersistentEnvFile as c,removePersistentEnv as p,writePersistentEnv as d}from"../persistent-env.js";import{backupBeforeWrite as g,atomicWriteFile as u}from"./backup.js";import{findInstalls as m,mirrorInstallCommand as y}from"./tool-installs.js";import{toolHome as f}from"./types.js";import{brand as h,PROVIDER_KEY as _}from"../brand.js";import{noteWrittenGatewayUrl as v}from"../gateway-addresses.js";const A="agy",E="AGY_LLM_GATEWAY_URL",j="AGY_LLM_GATEWAY_API_KEY",w="AGY_LLM_GATEWAY_MODELS",I=["GEMINI_API_KEY","GOOGLE_GEMINI_BASE_URL"],K="gemini",b=()=>n(f(),".gemini","antigravity-cli"),M=()=>n(b(),"settings.json"),P=()=>n(b(),`${_}.env`),G=()=>n(f(),".antigravity","settings.json"),L=h().installMirror?.agy,C={command:"agy",native:{binDir:"win32"===process.platform?["AppData","Local","agy","bin"]:[".local","bin"],updateArgs:["update"],dataDirs:[]},...L?{mirrorScript:{sh:`${L}/install.sh`,ps1:`${L}/install.ps1`}}:{}};function N(t){return!!t&&"object"==typeof t&&!Array.isArray(t)}function $(t,n){if(!e(t))return{};const o=r(t,"utf-8");if(!o.trim())return{};try{const t=JSON.parse(o);if(!N(t))throw new Error(`${n} root must be an object`);return t}catch(t){throw new Error(`Existing ${n} cannot be parsed; back it up and fix it first: ${t instanceof Error?t.message:String(t)}`)}}const O=()=>$(M(),"~/.gemini/antigravity-cli/settings.json"),S=()=>$(G(),"~/.antigravity/settings.json");function Y(e,r,n){g(e),u(e,JSON.stringify(r,null,2)+"\n",n),void 0!==n&&t(e,n)}function x(t){return(t||"").replace(/\/+$/,"").replace(/\/v1(beta)?$/,"")}const U=/-(minimal|low|medium|high|xhigh|max)$/;function k(t){const e=a().gatewayModels,r=t?e.filter(e=>t.models.includes(e)||t.models.includes(e.replace(U,""))):[];return r.length>0?r:e}function R(t){const e=t.replace(/-preview$/,""),r=U.exec(e)?.[1];return r?`${i(e.replace(U,""))} (${r[0].toUpperCase()}${r.slice(1)})`:i(e)}function B(t){const e=t.gateway;return N(e)&&!0===e.enabled&&"string"==typeof e.apiKey&&e.apiKey.trim()&&"string"==typeof e.url?{url:e.url,apiKey:e.apiKey}:null}function D(t){const e=t.models;return N(e)&&Array.isArray(e.list)?e.list.map(t=>N(t)&&"string"==typeof t.modelId?t.modelId:"").filter(Boolean):[]}function T(){try{if(O().modelProvider!==K)return null}catch{return null}const t=c(P()),e=t.GEMINI_API_KEY;return e&&e.trim()?{apiKey:e,url:t.GOOGLE_GEMINI_BASE_URL??""}:null}function W(t){const e=c(P());return e[E]===t.url&&e[j]===t.apiKey}function J(t,e,r){const n=O(),o=S();o.gateway={...N(o.gateway)?o.gateway:{},enabled:!0,url:e,apiKey:t,wireProtocol:"genai"},o.models={...N(o.models)?o.models:{},defaultModelId:r[0],list:r.map(t=>({modelId:t,displayName:R(t),supportsThinking:!0}))},Y(G(),o,384),I.some(t=>void 0!==c(P())[t])&&p(A,P(),I);const i=d(A,P(),{[E]:e,[j]:t,[w]:r.join(",")}).rcFiles;for(const t of I)delete process.env[t];return n.modelProvider===K&&(delete n.modelProvider,Y(M(),n)),i}let F=null,H=null;export const antigravityAdapter={name:"agy",displayName:"Antigravity CLI",command:"agy",installCommand:y(C),installSpec:C,configPath:G(),wantsModelCatalog:!0,ccSwitch:{app:"agy",endpointPath:"",handOver:!0,cards(t){const e=k(t.catalog);return[{settingsConfig:{env:{GEMINI_API_KEY:t.apiKey,GOOGLE_GEMINI_BASE_URL:x(t.baseUrl)},config:{},gateway:{models:e,defaultModel:e[0],modelOptions:Object.fromEntries(e.map(t=>[t,{displayName:R(t)}]))}}}]},applyAsCards(t){const e=n(f(),".gemini","config","config.json"),r=$(e,"~/.gemini/config/config.json"),o=k(t.catalog),i=x(t.baseUrl);r.gateway={enabled:!0,url:i,apiKey:t.apiKey,wireProtocol:"genai",customHeaders:{"x-goog-api-key":t.apiKey}},r.models={defaultModelId:o[0],list:o.map(t=>({modelId:t,displayName:R(t)}))},v(i),Y(e,r,384),H=o}},loadPrivateConfig(t){O(),S();const e=k(t.catalog);F=J(t.apiKey,x(t.baseUrl),e),H=e},unloadPrivateConfig(){try{const t=S();B(t)&&(delete t.gateway,delete t.models,Y(G(),t,384))}catch(t){l.logError("antigravityAdapter.unloadPrivateConfig",t)}try{const t=O();t.modelProvider===K&&(delete t.modelProvider,Y(M(),t))}catch(t){l.logError("antigravityAdapter.unloadPrivateConfig",t)}p(A,P(),[E,j,w,...I])},detectCurrentConfig(){try{const t=B(S());if(t)return{apiKey:t.apiKey}}catch{return{apiKey:null}}return{apiKey:T()?.apiKey??null}},listedModels(){try{const t=S(),e=B(t);if(e)return W(e)?D(t):[]}catch{return null}return T()?[]:null},refreshModelMenu(t){const e=S(),r=B(e)??T();if(!r)return;const n=k(t.catalog),o=r.url||x(t.baseUrl),i=B(e);null!==i&&W(i)&&D(e).join(",")===n.join(",")&&c(P())[w]===n.join(",")&&s(P())&&null===T()||J(r.apiKey,o,n)},getConfig(){try{return S()}catch(t){return l.logError("antigravityAdapter.getConfig",t),null}},applyNotes(){const t=[];if(H&&H.length>0){const e=H.map(R);t.push({kind:"summary",text:o.t("tools.agy.menu_written",{count:String(e.length),list:e.join(o.t("tools.grok.list_separator")),default:e[0]})})}return null===F||0===m(C).length||t.push({kind:"action",text:o.t("tools.agy.open_new_terminal")}),t},backupPaths:()=>[G(),M(),P()],forceResetPaths:()=>[P()]};
@@ -1 +1 @@
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
+ 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 C}from"../telemetry.js";import{spawnSync as k}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===k("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:"",cards:e=>[{settingsConfig: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:C(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=>`${C(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=>C(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:C(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:C(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:C(o.location),vars:Object.keys(o.vars).join(", ")})});for(const o of t.foreign){const t={location:C(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:C(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===k("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{chmodSync as e,existsSync as t,mkdirSync as n,readdirSync as o,readFileSync as r,rmSync as s}from"fs";import{dirname as i}from"path";import{join as l}from"path";import{randomUUID as a}from"crypto";import{execFileSync as c}from"child_process";import{userInfo as d}from"os";import u from"chalk";import{logger as p}from"../../utils/logger.js";import{track as f}from"../telemetry.js";import{ensureDesktopCli as m,installedDesktopAsarPath as g}from"./claude-desktop-cli.js";import{i18n as y}from"../i18n.js";import{BRAND_NAME as h,brand as k,brandEnv as _,CLI_NAME as w}from"../brand.js";import{mirrorPageUrl as D}from"../mirror-url.js";import{backupBeforeWrite as b,atomicWriteFile as v}from"./backup.js";import{toolHome as A}from"./types.js";import{canRestartDesktop as C,desktopQuitRefused as E,isDesktopRunning as M,launchDesktop as O,quitDesktop as S,restartDesktop as x,WINDOWS_PACKAGE_FAMILIES as j}from"./desktop-process.js";import{desktopInstallBlocker as P,fetchLatestDesktopVersion as I,installedMacApp as L,installLatestDesktop as T}from"./claude-desktop-app.js";import{setUserRegistryElevated as G}from"./elevated-reg.js";import{UserActionNeeded as N}from"./types.js";import{savedApiKeys as $}from"../config.js";import{isOurGatewayUrl as U,noteWrittenGatewayUrl as K}from"../gateway-addresses.js";import{baseModelId as R,isClaudeModel as F}from"../model-catalog.js";import{getDefaultModels as B}from"../model-registry.js";import{claudeFormat as H,nestedClaudeProjectFiles as J}from"../sessions/formats.js";import{powerShellEnv as z}from"../powershell-env.js";const V=h;export const CLAUDE_DESKTOP_HIDE_OFFICIAL_LOGIN_SETTING="hide_official_login";export const CLAUDE_DESKTOP_FORCE_REGISTRY_SETTING="force_registry";const W=/^[a-f0-9-]{36}$/;function q(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}export function claudeDesktopUserDataDir(){const e=process.env.CLAUDE_USER_DATA_DIR?.trim();if(e)return e;const n=A(),o=Boolean(_("TEST_HOME")?.trim());switch(process.platform){case"darwin":return l(n,"Library","Application Support","Claude-3p");case"win32":{const e=!o&&process.env.LOCALAPPDATA?process.env.LOCALAPPDATA:l(n,"AppData","Local");return j.map(t=>l(e,"Packages",t,"LocalCache","Local","Claude-3p")).find(e=>t(e))??l(e,"Claude-3p")}default:{const e=!o&&process.env.XDG_CONFIG_HOME?process.env.XDG_CONFIG_HOME:l(n,".config");return l(e,"Claude-3p")}}}const X=()=>l(claudeDesktopUserDataDir(),"configLibrary"),Z=()=>l(X(),"_meta.json"),Y=e=>l(X(),`${e}.json`),Q=()=>l(claudeDesktopUserDataDir(),"claude_desktop_config.json");function ee(e){if(!t(e))return null;const n=r(e,"utf-8");if(!n.trim())return null;try{const e=JSON.parse(n);return q(e)?e:null}catch(t){throw new Error(`Existing ${e} cannot be parsed; back it up and fix it first: ${t instanceof Error?t.message:String(t)}`)}}function te(o,r){const s=i(o);t(s)||n(s,{recursive:!0,mode:448}),b(o),v(o,JSON.stringify(r,null,2)+"\n");try{e(o,384)}catch(e){p.logError("claude-desktop.writeJson.chmod",e)}}function ne(){const e=ee(Z());if(!e)return null;const t=Array.isArray(e.entries)?e.entries.filter(e=>q(e)&&"string"==typeof e.id&&"string"==typeof e.name):[];return{...e,appliedId:"string"==typeof e.appliedId?e.appliedId:"",entries:t}}function oe(e){return e?.entries.find(e=>e.name===V&&W.test(e.id))}const re={opus:0,fable:1,sonnet:2,haiku:3};function se(e){let t=/^claude-(opus|sonnet|haiku|fable)-(\d+(?:-\d+)*)/i.exec(e);return t?{family:t[1].toLowerCase(),version:t[2].split("-").map(Number)}:(t=/^claude-(\d+(?:-\d+)*)-(opus|sonnet|haiku)/i.exec(e),t?{family:t[2].toLowerCase(),version:t[1].split("-").map(Number)}:null)}export function humanizeModelId(e){const t=se(e);return t?`${t.family[0].toUpperCase()+t.family.slice(1)} ${t.version.filter(e=>e<1e7).slice(0,2).join(".")}`:e}function ie(e){return se(e)?.family}export function buildInferenceModels(e,t){const{primary:n,bySlot:o}=function(e){const t=["opus","sonnet","haiku","reasoning"].map(t=>R(e[t]||"")).filter(Boolean);return{primary:t[0]??"",bySlot:t}}(e),r=new Set,s=t?.labels??{};let i;if(t&&t.models.some(F)){i=[...new Set(t.models.filter(F).map(R))];for(const e of t.oneMillion)r.add(e)}else{i=[];for(const t of["opus","sonnet","haiku","reasoning"]){const n=(e[t]||"").trim(),o=R(n);o&&(i.includes(o)||i.push(o),/\[1m\]/i.test(n)&&r.add(o))}}const l=e=>re[ie(e)??""]??9;i.sort((e,t)=>{if(e===n)return-1;if(t===n)return 1;const o=l(e)-l(t);if(0!==o)return o;const r=se(e),s=se(t);return r&&s?function(e,t){const n=Math.max(e.length,t.length);for(let o=0;o<n;o++){const n=(t[o]??0)-(e[o]??0);if(0!==n)return n}return 0}(r.version,s.version):e.localeCompare(t)});const a=new Set,c=new Map,d=new Set(Object.values(B()).map(e=>R(e||"")));for(const e of o){const t=ie(e);t&&i.includes(e)&&!d.has(e)&&!c.has(t)&&c.set(t,e)}return i.map(e=>{const t=ie(e),n={name:e,labelOverride:s[e]||humanizeModelId(e)};if(r.has(e)&&(n.supports1m=!0,n.prefer1m=!0),t){n.anthropicFamilyTier=t;const o=c.get(t);o&&o!==e||a.has(t)||(n.isFamilyDefault=!0,a.add(t))}return n})}let le=null,ae=null,ce=!1,de=null,ue=null,pe=null;function fe(e){return{inferenceProvider:"gateway",inferenceCredentialKind:"static",inferenceGatewayBaseUrl:(e.baseUrl||"").trim().replace(/\/+$/,""),inferenceGatewayApiKey:e.apiKey,...e.catalog?.desktopDiscovery?{}:{inferenceModels:buildInferenceModels(e.models,e.catalog)},disableDeploymentModeChooser:!1!==e.settings?.hide_official_login,chatTabEnabled:!0,chatAdvancedFileAnalysisEnabled:!0,autoModeEnabled:!0,coworkEgressAllowedHosts:["*"],disableEssentialTelemetry:!0,disableNonessentialTelemetry:!0,disableNonessentialServices:!1}}const me={defaultModelEffort:"medium",modelPrefer1mContext:!0,skipWebFetchPreflight:!0,toolSearchEnabled:!0,builtinBrowserEnabled:!0,isDesktopExtensionEnabled:!0,sshHostAllowlist:["*"],claudeAiImport:{enabled:!0,automatic3pImport:!0,exportEnabled:!0},coworkVmIpv6Enabled:!0,mcpToolTimeoutSec:3600,updateViaUpdatesHost:!0,banner:{enabled:!1}},ge=()=>{if(_("TEST_HOME")?.trim())return null;const e=g();return e?r(e):null};let ye=ge,he=null;export function setDesktopAsarForTests(e){ye=void 0===e?ge:()=>e,he=null}function ke(){if(he)return he;let e=null;try{e=ye()}catch(e){p.logError("claude-desktop.unsupportedDefaults",e)}return he=new Set(e?Object.keys(me).filter(t=>!e.includes(t)):[]),he}function _e(e){const t=ke();return Object.fromEntries(Object.entries(me).filter(([n])=>!e(n)&&!t.has(n)))}function we(e){const t={..._e(t=>t in e),...e};for(const e of ke())e in t&&JSON.stringify(t[e])===JSON.stringify(me[e])&&delete t[e];return t}const De="SOFTWARE\\Policies\\Claude",be=`HKCU\\${De}`,ve="HKLM\\SOFTWARE\\Policies\\Claude",Ae=`${w}-claude-policy.reg`,Ce=e=>c("reg",e,{stdio:["ignore","pipe","pipe"]}).toString();let Ee=Ce;export function setRegRunnerForTests(e){Ee=e??Ce}function Me(){return"win32"===process.platform}function Oe(e){let t;try{t=Ee(["query",e])}catch{return null}const n=new Map;for(const e of t.split(/\r?\n/)){const t=/^\s{2,}(\S+)\s+(REG_[A-Z_]+)\s*(.*)$/.exec(e);t&&n.set(t[1],t[3])}return n}function Se(){if(null===Oe(be))return;const e=l(claudeDesktopUserDataDir(),Ae);try{t(i(e))||n(i(e),{recursive:!0,mode:448}),b(e),Ee(["export",be,e,"/y"])}catch(e){p.logError("claude-desktop.snapshotPolicy",e)}}function xe(e){Se();for(const[t,n]of Object.entries(e)){const[e,o]="boolean"==typeof n?["REG_DWORD",n?"1":"0"]:"number"==typeof n?["REG_DWORD",String(n)]:"string"==typeof n?["REG_SZ",n]:["REG_SZ",JSON.stringify(n)];Ee(["add",be,"/v",t,"/t",e,"/d",o,"/f"])}}function je(e){const t=Oe(be);if(!t)return;Se();let n=t.size;for(const o of e)t.has(o)&&(Ee(["delete",be,"/v",o,"/f"]),n-=1);n<=0&&Ee(["delete",be,"/f"])}function Pe(){const e=!Boolean(_("TEST_HOME")?.trim())&&process.env.LOCALAPPDATA?process.env.LOCALAPPDATA:l(A(),"AppData","Local");return!!t(l(e,"AnthropicClaude"))||j.some(n=>t(l(e,"Packages",n,"LocalCache","Local","Claude-3p")))}const Ie=[...Object.keys(fe({apiKey:"",baseUrl:"",models:{haiku:"",sonnet:"",opus:"",reasoning:""}})),...Object.keys(me)];function Le(e){const{inferenceModels:t,...n}=e;return n}function Te(e){if(!e||!Ie.some(t=>e.has(t)))return"none";const t=e.get("inferenceGatewayApiKey")?.trim();return U(e.get("inferenceGatewayBaseUrl"))||t&&$().includes(t)||function(e){if(e.has("inferenceGatewayBaseUrl")||e.has("inferenceGatewayApiKey"))return!1;const t=[...e.keys()];return t.length>=10&&t.every(e=>Ie.includes(e))}(e)?"ours":"foreign"}function Ge(){const e=ee(Q())?.deploymentMode;if(void 0!==e&&"3p"!==e)return{kind:"mode"};const t=ne(),n=t?.entries.find(e=>e.id===t.appliedId);if(!n||n.id===oe(t)?.id)return null;const o=ee(Y(n.id));return o&&(o.inferenceProvider||o.inferenceGatewayBaseUrl)?{kind:"entry",name:n.name}:null}function Ne(e){return"mode"===e.kind?y.t("tools.claude_desktop.current_official"):y.t("tools.claude_desktop.current_entry",{name:e.name})}let $e=null,Ue=null;export function detectManagedConfig(){try{if("darwin"===process.platform){let e="";try{e=d().username}catch{}return[e?`/Library/Managed Preferences/${e}/com.anthropic.claudefordesktop.plist`:"","/Library/Managed Preferences/com.anthropic.claudefordesktop.plist"].filter(Boolean).find(e=>t(e))??null}if("win32"===process.platform)return Oe(ve)?ve:null;const e="/etc/claude-desktop/managed-settings.json";return t(e)?e:null}catch(e){return p.logError("claude-desktop.detectManagedConfig",e),null}}function Ke(){const e=A();let n;switch(process.platform){case"darwin":n=["/Applications/Claude.app",l(e,"Applications","Claude.app")];break;case"win32":{const t=process.env.LOCALAPPDATA||l(e,"AppData","Local");n=[l(t,"AnthropicClaude"),l(t,"Programs","Claude"),...j.map(e=>l(t,"Packages",e))];break}default:n=["/usr/lib/claude-desktop","/opt/Claude","/usr/bin/claude-desktop",l(e,".local","bin","claude-desktop")]}return n.push(claudeDesktopUserDataDir(),l(claudeDesktopUserDataDir(),"..","Claude")),n.some(e=>t(e))}const Re=/\d+\.\d+\.\d+/;function Fe(e){const t=e=>e.split(".").map(Number);return e.sort((e,n)=>{const[o,r]=[t(e),t(n)];for(let e=0;e<3;e++)if(o[e]!==r[e])return r[e]-o[e];return 0})[0]??null}function Be(){if("darwin"===process.platform){for(const e of["/Applications/Claude.app",l(A(),"Applications","Claude.app")]){const n=l(e,"Contents","Info.plist");if(!t(n))continue;const o=/<key>CFBundleShortVersionString<\/key>\s*<string>([^<]+)<\/string>/.exec(r(n,"utf-8")),s=o?Re.exec(o[1])?.[0]:void 0;if(s)return s}return null}if("win32"===process.platform){const e=l(process.env.LOCALAPPDATA||l(A(),"AppData","Local"),"AnthropicClaude");if(t(e)){const t=o(e).map(e=>/^app-(\d+\.\d+\.\d+)$/.exec(e)?.[1]).filter(e=>!!e);if(t.length>0)return Fe(t)}const n=j.map(e=>`'${e}'`).join(",");return Fe(c("powershell.exe",["-NoProfile","-Command",`Get-AppxPackage | Where-Object { @(${n}) -contains $_.PackageFamilyName } | ForEach-Object { $_.Version.ToString() }`],{encoding:"utf-8",timeout:15e3,windowsHide:!0,stdio:["ignore","pipe","ignore"],env:z()}).split(/\r?\n/).flatMap(e=>Re.exec(e)?.[0]??[]))}if("linux"===process.platform)try{const e=c("dpkg-query",["-W","-f=${Version}","claude-desktop"],{encoding:"utf-8",timeout:5e3,stdio:["ignore","pipe","ignore"]});return Re.exec(e)?.[0]??null}catch{return null}return null}const He="darwin"===process.platform?"open -a Claude":"win32"===process.platform?"Claude":"claude-desktop",Je="darwin"!==process.platform&&"win32"!==process.platform||!k().installMirror?.claudeDesktop?"https://claude.ai/download":D(k().installMirror.claudeDesktop),ze="darwin"===process.platform?`open ${Je}`:"win32"===process.platform?`start ${Je}`:`xdg-open ${Je}`;export const claudeDesktopAdapter={name:"claude-desktop",displayName:"Claude Desktop",command:He,installCommand:ze,configPath:Z(),sessions:{format:H,files:()=>J(l(claudeDesktopUserDataDir(),"local-agent-mode-sessions"))},isInstalled:Ke,installedVersion:Be,prepareRuntime:async function(){if(!["win32","darwin","linux"].includes(process.platform)||!Ke())return[];const e=Date.now();try{const t=await m({userDataDir:claudeDesktopUserDataDir(),onDownload:e=>console.log(u.gray(" "+y.t("tools.claude_desktop.code_cli_downloading",{version:e}))),onStart:(e,t)=>f("desktop-code-cli","start",{detail:{version:e,source:t}}),desktopVersion:"darwin"===process.platform?Be():null,mirror:k().installMirror?.claudeDesktop??null});return f("desktop-code-cli","skipped"===t.status?"skip":"ok",{duration_ms:Date.now()-e,detail:{...t}}),"installed"!==t.status?[]:[{kind:"summary",text:y.t("tools.claude_desktop.code_cli_installed",{version:t.version})}]}catch(t){return p.logError("claude-desktop.prepareCodeTabCli",t),f("desktop-code-cli","fail",{duration_ms:Date.now()-e,error:t}),[{kind:"action",text:y.t("tools.claude_desktop.code_cli_failed",{reason:t instanceof Error?t.message:String(t)})}]}},runningApp:C()?{isRunning:M,restart:x,quit:S,quitRefused:E,launch:O}:void 0,appInstaller:{vendor:"Anthropic",sizeMb:()=>300,downloadPage:"https://claude.ai/download",blocker:P,latestVersion:()=>I(),installedPath(){if("darwin"===process.platform)return L();if("win32"!==process.platform)return null;try{return Be()?"MSIX":null}catch(e){return p.logError("claude-desktop.installedPath",e),null}},install:e=>T(e)},wantsModelCatalog:!0,loadPrivateConfig(e){const t=ne()??{appliedId:"",entries:[]};let n=oe(t);n||(n={id:a(),name:V},t.entries.push(n));const o=fe(e);K(String(o.inferenceGatewayBaseUrl)),ae=!0===o.disableDeploymentModeChooser;const r=!0===e.catalog?.desktopDiscovery;le=r?null:{models:o.inferenceModels,source:e.catalog?e.catalog.oneMillionSource:"slots",groups:e.catalog?.matchedGroups??[]},ce=r;const s={...we(ee(Y(n.id))??{}),...o};te(Y(n.id),r?Le(s):s);const i=Ge();$e=i&&!e.takeOver?Ne(i):null,$e||(t.appliedId=n.id),te(Z(),t);const l=ee(Q())??{};$e||"3p"===l.deploymentMode||te(Q(),{...l,deploymentMode:"3p"}),ue=null,pe=null,de=null,Ue=null;const c=!0===e.settings?.force_registry,d=Me()?Oe(be):null;if(Me()&&"foreign"===Te(d)&&!c)Ue=d?.get("inferenceGatewayBaseUrl")||be;else if(Me()){const t=Oe(be),n=Ie.filter(e=>t?.has(e)),s={..._e(e=>t?.has(e)??!1),...o},i=!0===e.settings?.force_registry,l=!i&&Pe(),a=r&&!l&&(t?.has("inferenceModels")??!1);try{l?je(Ie):xe(s),a&&je(["inferenceModels"]),de=l?"removed":"written"}catch(e){p.logError("claude-desktop.policy",e),ue=e instanceof Error?e.message.trim():String(e),(n.length>0||i)&&(pe=l?{action:"remove",values:Object.fromEntries(n.map(e=>[e,null])),deleteKey:n.length===t.size}:{action:"write",values:{...s,...a?{inferenceModels:null}:{}},deleteKey:!1})}}},pendingElevation(){const e=pe;if(!e)return null;const t="unload"===e.action;return{prompt:y.t(`tools.claude_desktop.elevate_${e.action}`),...t?{failedHint:y.t("tools.claude_desktop.unload_elevation_failed"),skippedHint:y.t("tools.claude_desktop.unload_elevation_skipped")}:{},run:()=>{if(!G(De,e.values,e.deleteKey))return!1;const t=Oe(be),n="write"!==e.action?Object.keys(e.values).every(e=>!t?.has(e)):Object.keys(e.values).every(e=>t?.has(e));return n&&(pe=null,ue=null),n}}},unloadPrivateConfig(){pe=null;const e=Me()?Oe(be):null;if(e&&"ours"===Te(e))try{je(Ie)}catch(t){p.logError("claude-desktop.removePolicy",t);const n=Ie.filter(t=>e.has(t));pe={action:"unload",values:Object.fromEntries(n.map(e=>[e,null])),deleteKey:n.length===e.size}}const t=ne(),n=oe(t);if(!t||!n)return;b(Y(n.id)),s(Y(n.id),{force:!0});const o=t.entries.filter(e=>e.id!==n.id);0===o.length?(b(Z()),s(Z(),{force:!0})):te(Z(),{...t,entries:o,appliedId:t.appliedId===n.id?o[0].id:t.appliedId})},listedModels(){const e=ne(),t=oe(e);if(!t||e?.appliedId!==t.id)return null;const n=ee(Y(t.id))?.inferenceModels;return Array.isArray(n)?n.map(e=>String(e.name)):null},refreshModelMenu(e){const t=ne(),n=oe(t);if(!n||t?.appliedId!==n.id)return;const o=ee(Y(n.id));if(!o)return;if(e.catalog?.desktopDiscovery)return void function(e,t,n){const o=Le(we(e));JSON.stringify(o)!==JSON.stringify(e)&&te(Y(t),o),pe=null;const r=Me()?Oe(be):null,s=!0===n.settings?.force_registry;if(!r?.has("inferenceModels")||"foreign"===Te(r)&&!s)return;const i=!s&&Pe()?Ie.filter(e=>r.has(e)):["inferenceModels"];try{je(i)}catch(e){throw p.logError("claude-desktop.unpinModelMenu registry",e),pe={action:"remove",values:Object.fromEntries(i.map(e=>[e,null])),deleteKey:i.length===r.size},new N(y.t("tools.claude_desktop.refresh_needs_admin"))}}(o,n.id,e);const r=buildInferenceModels(e.models,e.catalog),s=JSON.stringify(o.inferenceModels)!==JSON.stringify(r),i={...we(o),inferenceModels:r},l=JSON.stringify(i)!==JSON.stringify(o);pe=null;const a=Me()?Oe(be):null,c="foreign"===Te(a)&&!0!==e.settings?.force_registry;if(!a?.has("inferenceModels")||c)return void(l&&te(Y(n.id),i));const d=Ie.filter(e=>a.has(e)),u=!0!==e.settings?.force_registry&&Pe();if(l&&te(Y(n.id),i),u||s)try{u?je(Ie):xe({inferenceModels:r})}catch(e){throw p.logError("claude-desktop.refreshModelMenu registry",e),pe=u?{action:"remove",values:Object.fromEntries(d.map(e=>[e,null])),deleteKey:d.length===a.size}:{action:"write",values:{inferenceModels:r},deleteKey:!1},new N(y.t("tools.claude_desktop.refresh_needs_admin"))}},holdsOurConfig:()=>!(!Me()||"ours"!==Te(Oe(be)))||Boolean(claudeDesktopAdapter.detectCurrentConfig().apiKey),detectCurrentConfig(){try{if(Me()){const e=Oe(be)?.get("inferenceGatewayApiKey");if(e)return{apiKey:e}}const e=oe(ne());if(!e)return{apiKey:null};const t=ee(Y(e.id)),n=t?.inferenceGatewayApiKey;return{apiKey:"string"==typeof n&&n?n:null}}catch(e){return p.logError("claude-desktop.detectCurrentConfig",e),{apiKey:null}}},getConfig(){try{const e=ne(),t=oe(e);return{meta:e,applied:t?ee(Y(t.id)):null,desktop:ee(Q()),...Me()?{policy:Object.fromEntries(Oe(be)??[])}:{}}}catch(e){return p.logError("claude-desktop.getConfig",e),null}},clearPinnedModels(){let e=!1;Me()&&Oe(be)?.has("inferenceModels")&&(Se(),Ee(["delete",be,"/v","inferenceModels","/f"]),e=!0);const t=oe(ne()),n=t?ee(Y(t.id)):null;if(t&&n&&void 0!==n.inferenceModels){const{inferenceModels:o,...r}=n;te(Y(t.id),r),e=!0}return e?["inferenceModels"]:[]},applyNotes(){const e=[];if(le&&le.models.length>0){const{models:t,source:n,groups:o}=le;e.push({kind:"summary",text:y.t("tools.claude_desktop.models_summary",{count:String(t.length),default:t[0].labelOverride??t[0].name})}),e.push({kind:"detail",text:y.t(`tools.claude_desktop.models_written_${n}`,{count:String(t.length),list:t.map(e=>`${e.labelOverride}${e.supports1m?" (1M)":""}`).join(", "),groups:o.join(" / ")})})}ce&&e.push({kind:"summary",text:y.t("tools.claude_desktop.models_from_gateway")}),null!==ae&&e.push({kind:"detail",text:y.t(ae?"tools.claude_desktop.official_login_hidden":"tools.claude_desktop.official_login_shown")}),C()&&!M()||e.push({kind:"action",text:y.t("tools.claude_desktop.restart_hint")}),pe?(e.push({kind:"action",text:y.t(`tools.claude_desktop.policy_stale_${pe.action}`)}),e.push({kind:"detail",text:ue??""})):ue?(e.push({kind:"detail",text:y.t("tools.claude_desktop.registry_denied")}),e.push({kind:"detail",text:ue})):Me()&&de&&e.push({kind:"detail",text:y.t(`tools.claude_desktop.registry_${de}`,{key:be})}),$e&&e.push({kind:"action",text:y.t("tools.claude_desktop.not_switched",{current:$e})}),Ue&&e.push({kind:"action",text:y.t("tools.claude_desktop.foreign_policy",{key:be,url:Ue})});const t=detectManagedConfig();return t&&e.push({kind:"action",text:y.t("tools.claude_desktop.managed_conflict",{path:t})}),e},planNotes(){const e=[],t=Ge();if(t&&e.push(y.t("tools.claude_desktop.plan_switch",{current:Ne(t)})),Me()){const t=Oe(be);"foreign"===Te(t)&&e.push(y.t("tools.claude_desktop.plan_foreign_policy",{key:be,url:t?.get("inferenceGatewayBaseUrl")||"-"}))}return e},forceResetPaths(){const e=[Z(),Q()];try{const t=oe(ne());t&&e.push(Y(t.id))}catch{}return e},backupPaths(){const e=[Z(),Q()];Me()&&e.push(l(claudeDesktopUserDataDir(),Ae));try{const t=oe(ne());t&&e.push(Y(t.id))}catch{}return e}};
1
+ import{chmodSync as e,existsSync as t,mkdirSync as n,readdirSync as o,readFileSync as r,rmSync as s}from"fs";import{dirname as i}from"path";import{join as l}from"path";import{randomUUID as a}from"crypto";import{execFileSync as c}from"child_process";import{userInfo as d}from"os";import u from"chalk";import{logger as p}from"../../utils/logger.js";import{track as f}from"../telemetry.js";import{ensureDesktopCli as m,installedDesktopAsarPath as g}from"./claude-desktop-cli.js";import{i18n as y}from"../i18n.js";import{BRAND_NAME as h,brand as k,brandEnv as _,CLI_NAME as w}from"../brand.js";import{mirrorPageUrl as b}from"../mirror-url.js";import{backupBeforeWrite as v,atomicWriteFile as D}from"./backup.js";import{toolHome as A}from"./types.js";import{canRestartDesktop as C,desktopQuitRefused as E,isDesktopRunning as M,launchDesktop as O,quitDesktop as S,restartDesktop as j,WINDOWS_PACKAGE_FAMILIES as x}from"./desktop-process.js";import{desktopInstallBlocker as P,fetchLatestDesktopVersion as T,installedMacApp as I,installLatestDesktop as L}from"./claude-desktop-app.js";import{setUserRegistryElevated as N}from"./elevated-reg.js";import{UserActionNeeded as G}from"./types.js";import{savedApiKeys as U}from"../config.js";import{isOurGatewayUrl as K,noteWrittenGatewayUrl as $}from"../gateway-addresses.js";import{baseModelId as R,isClaudeModel as F}from"../model-catalog.js";import{getDefaultModels as H}from"../model-registry.js";import{claudeFormat as B,nestedClaudeProjectFiles as J}from"../sessions/formats.js";import{powerShellEnv as z}from"../powershell-env.js";const V=h;export const CLAUDE_DESKTOP_HIDE_OFFICIAL_LOGIN_SETTING="hide_official_login";export const CLAUDE_DESKTOP_FORCE_REGISTRY_SETTING="force_registry";const W=/^[a-f0-9-]{36}$/;function q(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}export function claudeDesktopUserDataDir(){const e=process.env.CLAUDE_USER_DATA_DIR?.trim();if(e)return e;const n=A(),o=Boolean(_("TEST_HOME")?.trim());switch(process.platform){case"darwin":return l(n,"Library","Application Support","Claude-3p");case"win32":{const e=!o&&process.env.LOCALAPPDATA?process.env.LOCALAPPDATA:l(n,"AppData","Local");return x.map(t=>l(e,"Packages",t,"LocalCache","Local","Claude-3p")).find(e=>t(e))??l(e,"Claude-3p")}default:{const e=!o&&process.env.XDG_CONFIG_HOME?process.env.XDG_CONFIG_HOME:l(n,".config");return l(e,"Claude-3p")}}}const X=()=>l(claudeDesktopUserDataDir(),"configLibrary"),Z=()=>l(X(),"_meta.json"),Y=e=>l(X(),`${e}.json`),Q=()=>l(claudeDesktopUserDataDir(),"claude_desktop_config.json");function ee(e){if(!t(e))return null;const n=r(e,"utf-8");if(!n.trim())return null;try{const e=JSON.parse(n);return q(e)?e:null}catch(t){throw new Error(`Existing ${e} cannot be parsed; back it up and fix it first: ${t instanceof Error?t.message:String(t)}`)}}function te(o,r){const s=i(o);t(s)||n(s,{recursive:!0,mode:448}),v(o),D(o,JSON.stringify(r,null,2)+"\n");try{e(o,384)}catch(e){p.logError("claude-desktop.writeJson.chmod",e)}}function ne(){const e=ee(Z());if(!e)return null;const t=Array.isArray(e.entries)?e.entries.filter(e=>q(e)&&"string"==typeof e.id&&"string"==typeof e.name):[];return{...e,appliedId:"string"==typeof e.appliedId?e.appliedId:"",entries:t}}const oe={id:"00000000-0000-4000-8000-000000157210",name:"CC Switch"};let re=null;function se(e){return re?e?.entries.find(e=>e.id===re.id):e?.entries.find(e=>e.name===V&&W.test(e.id))}const ie={opus:0,fable:1,sonnet:2,haiku:3};function le(e){let t=/^claude-(opus|sonnet|haiku|fable)-(\d+(?:-\d+)*)/i.exec(e);return t?{family:t[1].toLowerCase(),version:t[2].split("-").map(Number)}:(t=/^claude-(\d+(?:-\d+)*)-(opus|sonnet|haiku)/i.exec(e),t?{family:t[2].toLowerCase(),version:t[1].split("-").map(Number)}:null)}export function humanizeModelId(e){const t=le(e);return t?`${t.family[0].toUpperCase()+t.family.slice(1)} ${t.version.filter(e=>e<1e7).slice(0,2).join(".")}`:e}function ae(e){return le(e)?.family}export function buildInferenceModels(e,t){const{primary:n,bySlot:o}=function(e){const t=["opus","sonnet","haiku","reasoning"].map(t=>R(e[t]||"")).filter(Boolean);return{primary:t[0]??"",bySlot:t}}(e),r=new Set,s=t?.labels??{};let i;if(t&&t.models.some(F)){i=[...new Set(t.models.filter(F).map(R))];for(const e of t.oneMillion)r.add(e)}else{i=[];for(const t of["opus","sonnet","haiku","reasoning"]){const n=(e[t]||"").trim(),o=R(n);o&&(i.includes(o)||i.push(o),/\[1m\]/i.test(n)&&r.add(o))}}const l=e=>ie[ae(e)??""]??9;i.sort((e,t)=>{if(e===n)return-1;if(t===n)return 1;const o=l(e)-l(t);if(0!==o)return o;const r=le(e),s=le(t);return r&&s?function(e,t){const n=Math.max(e.length,t.length);for(let o=0;o<n;o++){const n=(t[o]??0)-(e[o]??0);if(0!==n)return n}return 0}(r.version,s.version):e.localeCompare(t)});const a=new Set,c=new Map,d=new Set(Object.values(H()).map(e=>R(e||"")));for(const e of o){const t=ae(e);t&&i.includes(e)&&!d.has(e)&&!c.has(t)&&c.set(t,e)}return i.map(e=>{const t=ae(e),n={name:e,labelOverride:s[e]||humanizeModelId(e)};if(r.has(e)&&(n.supports1m=!0,n.prefer1m=!0),t){n.anthropicFamilyTier=t;const o=c.get(t);o&&o!==e||a.has(t)||(n.isFamilyDefault=!0,a.add(t))}return n})}let ce=null,de=null,ue=!1,pe=null,fe=null,me=null;function ge(e){return{inferenceProvider:"gateway",inferenceCredentialKind:"static",inferenceGatewayBaseUrl:(e.baseUrl||"").trim().replace(/\/+$/,""),inferenceGatewayApiKey:e.apiKey,...e.catalog?.desktopDiscovery?{}:{inferenceModels:buildInferenceModels(e.models,e.catalog)},disableDeploymentModeChooser:!1!==e.settings?.hide_official_login,chatTabEnabled:!0,chatAdvancedFileAnalysisEnabled:!0,autoModeEnabled:!0,coworkEgressAllowedHosts:["*"],disableEssentialTelemetry:!0,disableNonessentialTelemetry:!0,disableNonessentialServices:!1}}const ye={defaultModelEffort:"medium",modelPrefer1mContext:!0,skipWebFetchPreflight:!0,toolSearchEnabled:!0,builtinBrowserEnabled:!0,isDesktopExtensionEnabled:!0,sshHostAllowlist:["*"],claudeAiImport:{enabled:!0,automatic3pImport:!0,exportEnabled:!0},coworkVmIpv6Enabled:!0,mcpToolTimeoutSec:3600,updateViaUpdatesHost:!0,banner:{enabled:!1}},he=()=>{if(_("TEST_HOME")?.trim())return null;const e=g();return e?r(e):null};let ke=he,_e=null;export function setDesktopAsarForTests(e){ke=void 0===e?he:()=>e,_e=null}function we(){if(_e)return _e;let e=null;try{e=ke()}catch(e){p.logError("claude-desktop.unsupportedDefaults",e)}return _e=new Set(e?Object.keys(ye).filter(t=>!e.includes(t)):[]),_e}function be(e){const t=we();return Object.fromEntries(Object.entries(ye).filter(([n])=>!e(n)&&!t.has(n)))}function ve(e){const t={...be(t=>t in e),...e};for(const e of we())e in t&&JSON.stringify(t[e])===JSON.stringify(ye[e])&&delete t[e];return t}const De="SOFTWARE\\Policies\\Claude",Ae=`HKCU\\${De}`,Ce="HKLM\\SOFTWARE\\Policies\\Claude",Ee=`${w}-claude-policy.reg`,Me=e=>c("reg",e,{stdio:["ignore","pipe","pipe"]}).toString();let Oe=Me;export function setRegRunnerForTests(e){Oe=e??Me}function Se(){return"win32"===process.platform}function je(e){let t;try{t=Oe(["query",e])}catch{return null}const n=new Map;for(const e of t.split(/\r?\n/)){const t=/^\s{2,}(\S+)\s+(REG_[A-Z_]+)\s*(.*)$/.exec(e);t&&n.set(t[1],t[3])}return n}function xe(){if(null===je(Ae))return;const e=l(claudeDesktopUserDataDir(),Ee);try{t(i(e))||n(i(e),{recursive:!0,mode:448}),v(e),Oe(["export",Ae,e,"/y"])}catch(e){p.logError("claude-desktop.snapshotPolicy",e)}}function Pe(e){xe();for(const[t,n]of Object.entries(e)){const[e,o]="boolean"==typeof n?["REG_DWORD",n?"1":"0"]:"number"==typeof n?["REG_DWORD",String(n)]:"string"==typeof n?["REG_SZ",n]:["REG_SZ",JSON.stringify(n)];Oe(["add",Ae,"/v",t,"/t",e,"/d",o,"/f"])}}function Te(e){const t=je(Ae);if(!t)return;xe();let n=t.size;for(const o of e)t.has(o)&&(Oe(["delete",Ae,"/v",o,"/f"]),n-=1);n<=0&&Oe(["delete",Ae,"/f"])}function Ie(){const e=!Boolean(_("TEST_HOME")?.trim())&&process.env.LOCALAPPDATA?process.env.LOCALAPPDATA:l(A(),"AppData","Local");return!!t(l(e,"AnthropicClaude"))||x.some(n=>t(l(e,"Packages",n,"LocalCache","Local","Claude-3p")))}const Le=[...Object.keys(ge({apiKey:"",baseUrl:"",models:{haiku:"",sonnet:"",opus:"",reasoning:""}})),...Object.keys(ye)];function Ne(e){const{inferenceModels:t,...n}=e;return n}function Ge(e){if(!e||!Le.some(t=>e.has(t)))return"none";const t=e.get("inferenceGatewayApiKey")?.trim();return K(e.get("inferenceGatewayBaseUrl"))||t&&U().includes(t)||function(e){if(e.has("inferenceGatewayBaseUrl")||e.has("inferenceGatewayApiKey"))return!1;const t=[...e.keys()];return t.length>=10&&t.every(e=>Le.includes(e))}(e)?"ours":"foreign"}function Ue(){const e=ee(Q())?.deploymentMode;if(void 0!==e&&"3p"!==e)return{kind:"mode"};const t=ne(),n=t?.entries.find(e=>e.id===t.appliedId);if(!n||n.id===se(t)?.id)return null;const o=ee(Y(n.id));return o&&(o.inferenceProvider||o.inferenceGatewayBaseUrl)?{kind:"entry",name:n.name}:null}function Ke(e){return"mode"===e.kind?y.t("tools.claude_desktop.current_official"):y.t("tools.claude_desktop.current_entry",{name:e.name})}let $e=null,Re=null;export function detectManagedConfig(){try{if("darwin"===process.platform){let e="";try{e=d().username}catch{}return[e?`/Library/Managed Preferences/${e}/com.anthropic.claudefordesktop.plist`:"","/Library/Managed Preferences/com.anthropic.claudefordesktop.plist"].filter(Boolean).find(e=>t(e))??null}if("win32"===process.platform)return je(Ce)?Ce:null;const e="/etc/claude-desktop/managed-settings.json";return t(e)?e:null}catch(e){return p.logError("claude-desktop.detectManagedConfig",e),null}}function Fe(){const e=A();let n;switch(process.platform){case"darwin":n=["/Applications/Claude.app",l(e,"Applications","Claude.app")];break;case"win32":{const t=process.env.LOCALAPPDATA||l(e,"AppData","Local");n=[l(t,"AnthropicClaude"),l(t,"Programs","Claude"),...x.map(e=>l(t,"Packages",e))];break}default:n=["/usr/lib/claude-desktop","/opt/Claude","/usr/bin/claude-desktop",l(e,".local","bin","claude-desktop")]}return n.push(claudeDesktopUserDataDir(),l(claudeDesktopUserDataDir(),"..","Claude")),n.some(e=>t(e))}const He=/\d+\.\d+\.\d+/;function Be(e){const t=e=>e.split(".").map(Number);return e.sort((e,n)=>{const[o,r]=[t(e),t(n)];for(let e=0;e<3;e++)if(o[e]!==r[e])return r[e]-o[e];return 0})[0]??null}function Je(){if("darwin"===process.platform){for(const e of["/Applications/Claude.app",l(A(),"Applications","Claude.app")]){const n=l(e,"Contents","Info.plist");if(!t(n))continue;const o=/<key>CFBundleShortVersionString<\/key>\s*<string>([^<]+)<\/string>/.exec(r(n,"utf-8")),s=o?He.exec(o[1])?.[0]:void 0;if(s)return s}return null}if("win32"===process.platform){const e=l(process.env.LOCALAPPDATA||l(A(),"AppData","Local"),"AnthropicClaude");if(t(e)){const t=o(e).map(e=>/^app-(\d+\.\d+\.\d+)$/.exec(e)?.[1]).filter(e=>!!e);if(t.length>0)return Be(t)}const n=x.map(e=>`'${e}'`).join(",");return Be(c("powershell.exe",["-NoProfile","-Command",`Get-AppxPackage | Where-Object { @(${n}) -contains $_.PackageFamilyName } | ForEach-Object { $_.Version.ToString() }`],{encoding:"utf-8",timeout:15e3,windowsHide:!0,stdio:["ignore","pipe","ignore"],env:z()}).split(/\r?\n/).flatMap(e=>He.exec(e)?.[0]??[]))}if("linux"===process.platform)try{const e=c("dpkg-query",["-W","-f=${Version}","claude-desktop"],{encoding:"utf-8",timeout:5e3,stdio:["ignore","pipe","ignore"]});return He.exec(e)?.[0]??null}catch{return null}return null}const ze="darwin"===process.platform?"open -a Claude":"win32"===process.platform?"Claude":"claude-desktop",Ve="darwin"!==process.platform&&"win32"!==process.platform||!k().installMirror?.claudeDesktop?"https://claude.ai/download":b(k().installMirror.claudeDesktop),We="darwin"===process.platform?`open ${Ve}`:"win32"===process.platform?`start ${Ve}`:`xdg-open ${Ve}`;export const claudeDesktopAdapter={name:"claude-desktop",displayName:"Claude Desktop",command:ze,installCommand:We,configPath:Z(),sessions:{format:B,files:()=>J(l(claudeDesktopUserDataDir(),"local-agent-mode-sessions"))},isInstalled:Fe,installedVersion:Je,prepareRuntime:async function(){if(!["win32","darwin","linux"].includes(process.platform)||!Fe())return[];const e=Date.now();try{const t=await m({userDataDir:claudeDesktopUserDataDir(),onDownload:e=>console.log(u.gray(" "+y.t("tools.claude_desktop.code_cli_downloading",{version:e}))),onStart:(e,t)=>f("desktop-code-cli","start",{detail:{version:e,source:t}}),desktopVersion:"darwin"===process.platform?Je():null,mirror:k().installMirror?.claudeDesktop??null});return f("desktop-code-cli","skipped"===t.status?"skip":"ok",{duration_ms:Date.now()-e,detail:{...t}}),"installed"!==t.status?[]:[{kind:"summary",text:y.t("tools.claude_desktop.code_cli_installed",{version:t.version})}]}catch(t){return p.logError("claude-desktop.prepareCodeTabCli",t),f("desktop-code-cli","fail",{duration_ms:Date.now()-e,error:t}),[{kind:"action",text:y.t("tools.claude_desktop.code_cli_failed",{reason:t instanceof Error?t.message:String(t)})}]}},runningApp:C()?{isRunning:M,restart:j,quit:S,quitRefused:E,launch:O}:void 0,appInstaller:{vendor:"Anthropic",sizeMb:()=>300,downloadPage:"https://claude.ai/download",blocker:P,latestVersion:()=>T(),installedPath(){if("darwin"===process.platform)return I();if("win32"!==process.platform)return null;try{return Je()?"MSIX":null}catch(e){return p.logError("claude-desktop.installedPath",e),null}},install:e=>L(e)},wantsModelCatalog:!0,ccSwitch:{app:"claude-desktop",endpointPath:"",handOver:!0,cards(e){const t=ge(e),n=t.inferenceModels??[],o=Object.fromEntries(n.filter(e=>/^claude-(sonnet|opus|haiku|fable)-[0-9]/.test(e.name)&&!e.name.includes("[")).map(e=>[e.name,{model:e.name,...e.labelOverride?{labelOverride:e.labelOverride}:{},...e.supports1m?{supports1m:!0}:{}}]));return[{settingsConfig:{env:{ANTHROPIC_BASE_URL:t.inferenceGatewayBaseUrl,ANTHROPIC_AUTH_TOKEN:e.apiKey}},meta:{claudeDesktopMode:"direct",apiFormat:"anthropic",...Object.keys(o).length>0?{claudeDesktopModelRoutes:o}:{}}}]},applyAsCards(e){re=oe;try{claudeDesktopAdapter.loadPrivateConfig({...e,takeOver:!0})}finally{re=null}}},loadPrivateConfig(e){const t=ne()??{appliedId:"",entries:[]};let n=se(t);n||(n=re?{...re}:{id:a(),name:V},t.entries.push(n));const o=ge(e);$(String(o.inferenceGatewayBaseUrl)),de=!0===o.disableDeploymentModeChooser;const r=!0===e.catalog?.desktopDiscovery;ce=r?null:{models:o.inferenceModels,source:e.catalog?e.catalog.oneMillionSource:"slots",groups:e.catalog?.matchedGroups??[]},ue=r;const s={...ve(ee(Y(n.id))??{}),...o};te(Y(n.id),r?Ne(s):s);const i=Ue();$e=i&&!e.takeOver?Ke(i):null,$e||(t.appliedId=n.id),te(Z(),t);const l=ee(Q())??{};$e||"3p"===l.deploymentMode||te(Q(),{...l,deploymentMode:"3p"}),fe=null,me=null,pe=null,Re=null;const c=!0===e.settings?.force_registry,d=Se()&&!re?je(Ae):null;if(re);else if(Se()&&"foreign"===Ge(d)&&!c)Re=d?.get("inferenceGatewayBaseUrl")||Ae;else if(Se()){const t=je(Ae),n=Le.filter(e=>t?.has(e)),s={...be(e=>t?.has(e)??!1),...o},i=!0===e.settings?.force_registry,l=!i&&Ie(),a=r&&!l&&(t?.has("inferenceModels")??!1);try{l?Te(Le):Pe(s),a&&Te(["inferenceModels"]),pe=l?"removed":"written"}catch(e){p.logError("claude-desktop.policy",e),fe=e instanceof Error?e.message.trim():String(e),(n.length>0||i)&&(me=l?{action:"remove",values:Object.fromEntries(n.map(e=>[e,null])),deleteKey:n.length===t.size}:{action:"write",values:{...s,...a?{inferenceModels:null}:{}},deleteKey:!1})}}},pendingElevation(){const e=me;if(!e)return null;const t="unload"===e.action;return{prompt:y.t(`tools.claude_desktop.elevate_${e.action}`),...t?{failedHint:y.t("tools.claude_desktop.unload_elevation_failed"),skippedHint:y.t("tools.claude_desktop.unload_elevation_skipped")}:{},run:()=>{if(!N(De,e.values,e.deleteKey))return!1;const t=je(Ae),n="write"!==e.action?Object.keys(e.values).every(e=>!t?.has(e)):Object.keys(e.values).every(e=>t?.has(e));return n&&(me=null,fe=null),n}}},unloadPrivateConfig(){me=null;const e=Se()?je(Ae):null;if(e&&"ours"===Ge(e))try{Te(Le)}catch(t){p.logError("claude-desktop.removePolicy",t);const n=Le.filter(t=>e.has(t));me={action:"unload",values:Object.fromEntries(n.map(e=>[e,null])),deleteKey:n.length===e.size}}const t=ne(),n=se(t);if(!t||!n)return;v(Y(n.id)),s(Y(n.id),{force:!0});const o=t.entries.filter(e=>e.id!==n.id);0===o.length?(v(Z()),s(Z(),{force:!0})):te(Z(),{...t,entries:o,appliedId:t.appliedId===n.id?o[0].id:t.appliedId})},listedModels(){const e=ne(),t=se(e);if(!t||e?.appliedId!==t.id)return null;const n=ee(Y(t.id))?.inferenceModels;return Array.isArray(n)?n.map(e=>String(e.name)):null},refreshModelMenu(e){const t=ne(),n=se(t);if(!n||t?.appliedId!==n.id)return;const o=ee(Y(n.id));if(!o)return;if(e.catalog?.desktopDiscovery)return void function(e,t,n){const o=Ne(ve(e));JSON.stringify(o)!==JSON.stringify(e)&&te(Y(t),o),me=null;const r=Se()?je(Ae):null,s=!0===n.settings?.force_registry;if(!r?.has("inferenceModels")||"foreign"===Ge(r)&&!s)return;const i=!s&&Ie()?Le.filter(e=>r.has(e)):["inferenceModels"];try{Te(i)}catch(e){throw p.logError("claude-desktop.unpinModelMenu registry",e),me={action:"remove",values:Object.fromEntries(i.map(e=>[e,null])),deleteKey:i.length===r.size},new G(y.t("tools.claude_desktop.refresh_needs_admin"))}}(o,n.id,e);const r=buildInferenceModels(e.models,e.catalog),s=JSON.stringify(o.inferenceModels)!==JSON.stringify(r),i={...ve(o),inferenceModels:r},l=JSON.stringify(i)!==JSON.stringify(o);me=null;const a=Se()?je(Ae):null,c="foreign"===Ge(a)&&!0!==e.settings?.force_registry;if(!a?.has("inferenceModels")||c)return void(l&&te(Y(n.id),i));const d=Le.filter(e=>a.has(e)),u=!0!==e.settings?.force_registry&&Ie();if(l&&te(Y(n.id),i),u||s)try{u?Te(Le):Pe({inferenceModels:r})}catch(e){throw p.logError("claude-desktop.refreshModelMenu registry",e),me=u?{action:"remove",values:Object.fromEntries(d.map(e=>[e,null])),deleteKey:d.length===a.size}:{action:"write",values:{inferenceModels:r},deleteKey:!1},new G(y.t("tools.claude_desktop.refresh_needs_admin"))}},holdsOurConfig:()=>!(!Se()||"ours"!==Ge(je(Ae)))||Boolean(claudeDesktopAdapter.detectCurrentConfig().apiKey),detectCurrentConfig(){try{if(Se()){const e=je(Ae)?.get("inferenceGatewayApiKey");if(e)return{apiKey:e}}const e=se(ne());if(!e)return{apiKey:null};const t=ee(Y(e.id)),n=t?.inferenceGatewayApiKey;return{apiKey:"string"==typeof n&&n?n:null}}catch(e){return p.logError("claude-desktop.detectCurrentConfig",e),{apiKey:null}}},getConfig(){try{const e=ne(),t=se(e);return{meta:e,applied:t?ee(Y(t.id)):null,desktop:ee(Q()),...Se()?{policy:Object.fromEntries(je(Ae)??[])}:{}}}catch(e){return p.logError("claude-desktop.getConfig",e),null}},clearPinnedModels(){let e=!1;Se()&&je(Ae)?.has("inferenceModels")&&(xe(),Oe(["delete",Ae,"/v","inferenceModels","/f"]),e=!0);const t=se(ne()),n=t?ee(Y(t.id)):null;if(t&&n&&void 0!==n.inferenceModels){const{inferenceModels:o,...r}=n;te(Y(t.id),r),e=!0}return e?["inferenceModels"]:[]},applyNotes(){const e=[];if(ce&&ce.models.length>0){const{models:t,source:n,groups:o}=ce;e.push({kind:"summary",text:y.t("tools.claude_desktop.models_summary",{count:String(t.length),default:t[0].labelOverride??t[0].name})}),e.push({kind:"detail",text:y.t(`tools.claude_desktop.models_written_${n}`,{count:String(t.length),list:t.map(e=>`${e.labelOverride}${e.supports1m?" (1M)":""}`).join(", "),groups:o.join(" / ")})})}ue&&e.push({kind:"summary",text:y.t("tools.claude_desktop.models_from_gateway")}),null!==de&&e.push({kind:"detail",text:y.t(de?"tools.claude_desktop.official_login_hidden":"tools.claude_desktop.official_login_shown")}),C()&&!M()||e.push({kind:"action",text:y.t("tools.claude_desktop.restart_hint")}),me?(e.push({kind:"action",text:y.t(`tools.claude_desktop.policy_stale_${me.action}`)}),e.push({kind:"detail",text:fe??""})):fe?(e.push({kind:"detail",text:y.t("tools.claude_desktop.registry_denied")}),e.push({kind:"detail",text:fe})):Se()&&pe&&e.push({kind:"detail",text:y.t(`tools.claude_desktop.registry_${pe}`,{key:Ae})}),$e&&e.push({kind:"action",text:y.t("tools.claude_desktop.not_switched",{current:$e})}),Re&&e.push({kind:"action",text:y.t("tools.claude_desktop.foreign_policy",{key:Ae,url:Re})});const t=detectManagedConfig();return t&&e.push({kind:"action",text:y.t("tools.claude_desktop.managed_conflict",{path:t})}),e},planNotes(){const e=[],t=Ue();if(t&&e.push(y.t("tools.claude_desktop.plan_switch",{current:Ke(t)})),Se()){const t=je(Ae);"foreign"===Ge(t)&&e.push(y.t("tools.claude_desktop.plan_foreign_policy",{key:Ae,url:t?.get("inferenceGatewayBaseUrl")||"-"}))}return e},forceResetPaths(){const e=[Z(),Q()];try{const t=se(ne());t&&e.push(Y(t.id))}catch{}return e},backupPaths(){const e=[Z(),Q()];Se()&&e.push(l(claudeDesktopUserDataDir(),Ee));try{const t=se(ne());t&&e.push(Y(t.id))}catch{}return e}};
@@ -1 +1 @@
1
- import{existsSync as e,readFileSync as t}from"fs";import{join as o}from"path";import{logger as r}from"../../utils/logger.js";import{i18n as d}from"../i18n.js";import{getToolDefaultModel as n,getToolMenuModels as i}from"../model-registry.js";import{prettyModelName as s,vendorNames as a}from"../gateway-models.js";import{backupBeforeWrite as l,atomicWriteFile as c}from"./backup.js";import{CUSTOM_MODEL_PREFIX as u,bareModelId as m,foreignIdsReplaced as p,isOurEntry as g,menuSpecs as y,mergeEntries as f,ourApiKey as b,ourEntries as h,readModelsFile as j,writeModelsFile as C}from"./codebuddy-models.js";import{pickModel as v,toolHome as S}from"./types.js";const w=()=>process.env.CODEBUDDY_CONFIG_DIR?.trim()||o(S(),".codebuddy"),E=()=>o(w(),"models.json"),N=()=>o(w(),"settings.json"),P={command:"codebuddy",npmPackage:"@tencent-ai/codebuddy-code",brew:"codebuddy-code"};function $(){if(!e(N()))return{};const o=t(N(),"utf-8");if(!o.trim())return{};let r;try{r=JSON.parse(o)}catch(e){throw new Error(`Existing ${N()} cannot be parsed; back it up and fix it first: ${e instanceof Error?e.message:String(e)}`)}if(!(d=r)||"object"!=typeof d||Array.isArray(d))throw new Error(`Existing ${N()} must hold a JSON object`);var d;return r}function _(e){l(N()),c(N(),`${JSON.stringify(e,null,2)}\n`,384)}function k(e,t){return"string"==typeof e&&e.startsWith(u)&&t.has(e.slice(u.length))}const x=e=>m(v(e.models,n("codebuddy")));function A(e,t){return e.find(e=>e.id===t)??e[0]}const O=(e,t)=>y(e,t,i("codebuddy"));let D=null;function M(e,t){const o=j(E()),{entries:r,replaced:d}=f(o.entries,t,e.baseUrl,e.apiKey);return C(E(),o,r),d}export const codebuddyAdapter={name:"codebuddy",displayName:"CodeBuddy Code",command:"codebuddy",installCommand:`npm install -g ${P.npmPackage}`,installSpec:P,get configPath(){return E()},wantsModelCatalog:!0,loadPrivateConfig(e){const t=x(e),o=O(e.catalog,t),r=$(),d=M(e,o),n=A(o,t);n&&(r.model=`${u}${n.id}`,_(r));const i=e=>e.name??s(e.id);D={names:o.map(i),vendors:a(o.map(e=>e.id)),defaultName:n?i(n):"",replaced:d}},unloadPrivateConfig(){let e;try{e=j(E())}catch(e){return void r.logError("codebuddyAdapter.unloadPrivateConfig",e)}const t=new Set(h(e.entries).map(e=>String(e.id)));t.size>0&&C(E(),e,e.entries.filter(e=>!g(e)));try{const e=$();k(e.model,t)&&(delete e.model,_(e))}catch(e){r.logError("codebuddyAdapter.unloadPrivateConfig",e)}},detectCurrentConfig(){try{return{apiKey:b(j(E()).entries)}}catch{return{apiKey:null}}},listedModels(){try{const e=h(j(E()).entries);return e.length>0?e.map(e=>String(e.id)):null}catch{return null}},refreshModelMenu(e){const t=j(E()),o=new Set(h(t.entries).map(e=>String(e.id))),r=$(),d=k(r.model,o)?String(r.model).slice(u.length):void 0,n=d&&e.catalog.models.includes(d)?d:x(e),i=O(e.catalog,n);M(e,i);const s=A(i,n);if(s&&(void 0===r.model||k(r.model,o))){const e=`${u}${s.id}`;r.model!==e&&(r.model=e,_(r))}},planNotes(){try{const e=j(E()),t=p(e.entries,O(void 0,n("codebuddy")));return t.length>0?[d.t("tools.codebuddy.replaces_models",{path:E(),list:t.join(d.t("tools.codebuddy.list_separator"))})]:[]}catch{return[]}},applyNotes(){if(!D)return[];const e=[{kind:"summary",text:d.t("tools.codebuddy.menu_written",{count:String(D.names.length),list:D.vendors.join(d.t("tools.codebuddy.list_separator")),default:D.defaultName})}];return D.replaced.length>0&&e.push({kind:"detail",text:d.t("tools.codebuddy.replaced_models",{tool:"codebuddy",list:D.replaced.join(d.t("tools.codebuddy.list_separator"))})}),e},backupPaths:()=>[E(),N()],forceResetPaths:()=>[E()],getConfig(){try{return{models:j(E()).entries,settings:$()}}catch(e){return r.logError("codebuddyAdapter.getConfig",e),null}}};
1
+ import{existsSync as e,readFileSync as t}from"fs";import{join as o}from"path";import{logger as r}from"../../utils/logger.js";import{i18n as n}from"../i18n.js";import{getToolDefaultModel as d,getToolMenuModels as i}from"../model-registry.js";import{prettyModelName as s,vendorNames as a}from"../gateway-models.js";import{backupBeforeWrite as l,atomicWriteFile as c}from"./backup.js";import{CUSTOM_MODEL_PREFIX as u,bareModelId as m,foreignIdsReplaced as p,isOurEntry as g,menuSpecs as y,mergeEntries as f,modelEntry as b,ourApiKey as h,ourEntries as j,readModelsFile as C,writeModelsFile as S}from"./codebuddy-models.js";import{pickModel as v,toolHome as w}from"./types.js";import{BRAND_NAME as P}from"../brand.js";const E=()=>process.env.CODEBUDDY_CONFIG_DIR?.trim()||o(w(),".codebuddy"),N=()=>o(E(),"models.json"),$=()=>o(E(),"settings.json"),_={command:"codebuddy",npmPackage:"@tencent-ai/codebuddy-code",brew:"codebuddy-code"};function k(){if(!e($()))return{};const o=t($(),"utf-8");if(!o.trim())return{};let r;try{r=JSON.parse(o)}catch(e){throw new Error(`Existing ${$()} cannot be parsed; back it up and fix it first: ${e instanceof Error?e.message:String(e)}`)}if(!(n=r)||"object"!=typeof n||Array.isArray(n))throw new Error(`Existing ${$()} must hold a JSON object`);var n;return r}function x(e){l($()),c($(),`${JSON.stringify(e,null,2)}\n`,384)}function A(e,t){return"string"==typeof e&&e.startsWith(u)&&t.has(e.slice(u.length))}const O=e=>m(v(e.models,d("codebuddy")));function D(e,t){return e.find(e=>e.id===t)??e[0]}const K=(e,t)=>y(e,t,i("codebuddy"));let M=null;function J(e,t){const o=C(N()),{entries:r,replaced:n}=f(o.entries,t,e.baseUrl,e.apiKey);return S(N(),o,r),n}export const codebuddyAdapter={name:"codebuddy",displayName:"CodeBuddy Code",command:"codebuddy",installCommand:`npm install -g ${_.npmPackage}`,installSpec:_,get configPath(){return N()},wantsModelCatalog:!0,ccSwitch:{app:"codebuddy",endpointPath:"/v1",cards:e=>K(e.catalog,O(e)).map(t=>{const{id:o,...r}=b(t,e.baseUrl,e.apiKey);return{id:String(o),name:String(r.name),settingsConfig:r}}),owns:(e,t)=>t.vendor===P},loadPrivateConfig(e){const t=O(e),o=K(e.catalog,t),r=k(),n=J(e,o),d=D(o,t);d&&(r.model=`${u}${d.id}`,x(r));const i=e=>e.name??s(e.id);M={names:o.map(i),vendors:a(o.map(e=>e.id)),defaultName:d?i(d):"",replaced:n}},unloadPrivateConfig(){let e;try{e=C(N())}catch(e){return void r.logError("codebuddyAdapter.unloadPrivateConfig",e)}const t=new Set(j(e.entries).map(e=>String(e.id)));t.size>0&&S(N(),e,e.entries.filter(e=>!g(e)));try{const e=k();A(e.model,t)&&(delete e.model,x(e))}catch(e){r.logError("codebuddyAdapter.unloadPrivateConfig",e)}},detectCurrentConfig(){try{return{apiKey:h(C(N()).entries)}}catch{return{apiKey:null}}},listedModels(){try{const e=j(C(N()).entries);return e.length>0?e.map(e=>String(e.id)):null}catch{return null}},refreshModelMenu(e){const t=C(N()),o=new Set(j(t.entries).map(e=>String(e.id))),r=k(),n=A(r.model,o)?String(r.model).slice(u.length):void 0,d=n&&e.catalog.models.includes(n)?n:O(e),i=K(e.catalog,d);J(e,i);const s=D(i,d);if(s&&(void 0===r.model||A(r.model,o))){const e=`${u}${s.id}`;r.model!==e&&(r.model=e,x(r))}},planNotes(){try{const e=C(N()),t=p(e.entries,K(void 0,d("codebuddy")));return t.length>0?[n.t("tools.codebuddy.replaces_models",{path:N(),list:t.join(n.t("tools.codebuddy.list_separator"))})]:[]}catch{return[]}},applyNotes(){if(!M)return[];const e=[{kind:"summary",text:n.t("tools.codebuddy.menu_written",{count:String(M.names.length),list:M.vendors.join(n.t("tools.codebuddy.list_separator")),default:M.defaultName})}];return M.replaced.length>0&&e.push({kind:"detail",text:n.t("tools.codebuddy.replaced_models",{tool:"codebuddy",list:M.replaced.join(n.t("tools.codebuddy.list_separator"))})}),e},backupPaths:()=>[N(),$()],forceResetPaths:()=>[N()],getConfig(){try{return{models:C(N()).entries,settings:k()}}catch(e){return r.logError("codebuddyAdapter.getConfig",e),null}}};
@@ -1 +1 @@
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}}
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",cards(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[{settingsConfig:{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}}
@@ -1 +1 @@
1
- import{existsSync as e,readFileSync as t}from"fs";import{join as r}from"path";import*as n from"js-yaml";import{logger as o}from"../../utils/logger.js";import{API_KEY_ENV as s,BRAND_NAME as i,PROVIDER_KEY as a}from"../brand.js";import{i18n as d}from"../i18n.js";import{modelFamily as l,prettyModelName as c,vendorNames as f}from"../gateway-models.js";import{getToolDefaultModel as p,getToolMenuModels as m}from"../model-registry.js";import{atomicWriteFile as u,backupBeforeWrite as h}from"./backup.js";import{bareModelId as g,menuSpecs as y,usesResponses as v}from"./codebuddy-models.js";import{pickModel as b,toolHome as w,withV1 as k}from"./types.js";const x=()=>process.env.DSH_HOME?.trim()||r(w(),".dsh"),A=e=>r(x(),"profiles",e,"cordis.patch.yml"),j=()=>r(x(),".credentials.yaml"),E=["web","desktop"],C="llm-pi-ai",O="agent-default-model",P=a,$=`${a}-gpt`,_=`${a}-claude`,M=["off","minimal","low","medium","high","xhigh","max"],S=e=>!!e&&"object"==typeof e&&!Array.isArray(e),D=e=>e===P||e.startsWith(`${a}-`);class L{source;constructor(e){this.source=e}}const H=n.DEFAULT_SCHEMA.extend(new n.Type("tag:yaml.org,2002:js",{kind:"scalar",construct:e=>new L(e??""),instanceOf:L,represent:e=>e.source}));function T(r){if(!e(r))return{entries:[],header:""};const o=t(r,"utf-8"),s=o.match(/^(?:#.*\r?\n)*/)?.[0]??"",i=n.load(o,{schema:H});if(null==i)return{entries:[],header:s};if(!Array.isArray(i))throw new Error(`Existing ${r} must hold a YAML list`);return{entries:i,header:s}}function W(r,o){const s=o.header+n.dump(o.entries,{schema:H,lineWidth:-1,noRefs:!0,sortKeys:!1});e(r)&&t(r,"utf-8")===s||(h(r),u(r,s))}function K(e,t){let r=e.find(e=>e.id===t);return r||(r={id:t},e.push(r)),S(r.config)||(r.config={}),r.config}function N(e){const t=e.find(e=>e.id===C&&S(e.config))?.config;return S(t?.providers)?t.providers:{}}function R(){if(!e(j()))return{version:1,refs:{}};const r=n.load(t(j(),"utf-8"));if(null==r)return{version:1,refs:{}};if(!S(r))throw new Error(`Existing ${j()} must hold a YAML mapping`);return"version"in r?S(r.refs)?r:{...r,refs:{}}:{version:1,refs:r}}function U(e){h(j()),u(j(),n.dump(e,{lineWidth:-1,sortKeys:!1}),384)}function F(e){const t=e.capabilities??{},r={id:e.id,name:e.name??c(e.id)},n=t.contextWindow??e.contextWindow;n&&(r.contextWindow=n);const o=t.maxOutput??e.maxOutputTokens;if(o&&(r.maxTokens=o),t.vision&&(r.input=["text","image"]),e.id.startsWith("deepseek-"))r.compat={thinkingFormat:"deepseek"},r.reasoningEfforts={off:null,high:"high",max:"max"};else if(t.reasoning&&t.reasoningEfforts){const e=t.reasoningEfforts.filter(e=>M.includes(e)&&"off"!==e);e.length>0&&(r.reasoningEfforts=Object.fromEntries(e.map(e=>[e,e])))}return r}function Y(e){return"claude"===l(e.id)?_:v(e)?$:P}function G(e,t){const r=k(t),n={apiKeyEnv:s},o={[P]:{displayName:i,...n,api:"openai-completions",baseURL:r,compat:{supportsDeveloperRole:!1,maxTokensField:"max_tokens"}},[$]:{displayName:`${i} GPT`,...n,api:"openai-responses",baseURL:r},[_]:{displayName:`${i} Claude`,...n,api:"anthropic-messages",baseURL:r.replace(/\/v\d+$/,"")}},a={};for(const[t,r]of Object.entries(o)){const n=e.filter(e=>Y(e)===t).map(F);n.length>0&&(a[t]={...r,models:n})}return a}const I=e=>g(b(e.models,p("dsh"))),q=(e,t)=>y(e,t,m("dsh"));function z(e,t,r,n=T(e)){const o=K(n.entries,C),s=Object.entries(S(o.providers)?o.providers:{}).filter(([e])=>!D(e));o.providers={...Object.fromEntries(s),...G(t,r)},W(e,n)}const B=e=>{const t=e.find(e=>e.id===O)?.config;return!S(t)||"string"!=typeof t.provider||D(t.provider)?null:`${t.provider}/${String(t.model)}`};let J=null;export const dshAdapter={name:"dsh",displayName:"DeepSeek Harness",command:"dsh",installCommand:"npx @deepseek-ai/dsh web",get configPath(){return A("web")},wantsModelCatalog:!0,isInstalled(){if(e(x()))return!0;if("darwin"===process.platform)return["/Applications/DeepSeek Harness.app",r(w(),"Applications","DeepSeek Harness.app")].some(t=>e(t));const t="win32"===process.platform?process.env.LOCALAPPDATA:void 0;return!!t&&e(r(t,"Programs","DeepSeek Harness"))},loadPrivateConfig(e){const t=q(e.catalog,I(e));if(0===t.length)throw new Error(d.t("tools.dsh.no_models"));const r=t.find(t=>t.id===I(e))??t[0],n=[];for(const o of E){const s=A(o),i=T(s),a=B(i.entries);a&&!n.includes(a)&&n.push(a);const d=K(i.entries,O);d.provider=Y(r),d.model=r.id,delete d.reasoningEffort,z(s,t,e.baseUrl,i)}const o=R();o.refs={...o.refs,[s]:e.apiKey},U(o),J={count:t.length,vendors:f(t.map(e=>e.id)),replaced:n}},unloadPrivateConfig(){try{for(const t of E){const r=A(t);if(!e(r))continue;const n=T(r),o=N(n.entries);for(const e of Object.keys(o))D(e)&&delete o[e];const s=n.entries.find(e=>e.id===O)?.config;S(s)&&"string"==typeof s.provider&&D(s.provider)&&(n.entries=n.entries.filter(e=>e.id!==O)),W(r,n)}const t=R(),r=t.refs;s in r&&(delete r[s],U(t))}catch(e){o.logError("dshAdapter.unloadPrivateConfig",e)}},detectCurrentConfig(){try{const e=R().refs[s];return{apiKey:"string"==typeof e&&e?e:null}}catch{return{apiKey:null}}},listedModels(){try{const e=Object.entries(N(T(A("web")).entries)).filter(([e])=>D(e));return 0===e.length?null:e.flatMap(([,e])=>S(e)&&Array.isArray(e.models)?e.models:[]).map(e=>String(e.id))}catch{return null}},refreshModelMenu(e){const t=q(e.catalog,I(e));if(0!==t.length)for(const r of E)z(A(r),t,e.baseUrl)},planNotes(){try{const e=B(T(A("web")).entries);return e?[d.t("tools.dsh.replaces_default",{model:e})]:[]}catch{return[]}},applyNotes(){if(!J)return[];const e=[{kind:"summary",text:d.t("tools.dsh.menu_written",{count:String(J.count),list:J.vendors.join(d.t("tools.codebuddy.list_separator"))})},{kind:"action",text:d.t("tools.dsh.pick_in_app")}];for(const t of J.replaced)e.push({kind:"detail",text:d.t("tools.dsh.replaced_default",{model:t})});return e},backupPaths:()=>[...E.map(A),j()],forceResetPaths:()=>E.map(A),getConfig(){try{return T(A("web")).entries}catch(e){return o.logError("dshAdapter.getConfig",e),null}}};
1
+ import{existsSync as e,readFileSync as t}from"fs";import{join as r}from"path";import*as n from"js-yaml";import{logger as o}from"../../utils/logger.js";import{API_KEY_ENV as s,BRAND_NAME as i,PROVIDER_KEY as a}from"../brand.js";import{i18n as d}from"../i18n.js";import{modelFamily as c,prettyModelName as l,vendorNames as p}from"../gateway-models.js";import{getToolDefaultModel as f,getToolMenuModels as m}from"../model-registry.js";import{atomicWriteFile as u,backupBeforeWrite as g}from"./backup.js";import{bareModelId as h,menuSpecs as y,usesResponses as b}from"./codebuddy-models.js";import{pickModel as v,toolHome as w,withV1 as x}from"./types.js";const k=()=>process.env.DSH_HOME?.trim()||r(w(),".dsh"),j=e=>r(k(),"profiles",e,"cordis.patch.yml"),E=()=>r(k(),".credentials.yaml"),A=["web","desktop"],C="llm-pi-ai",O="agent-default-model",S=a,P=`${a}-gpt`,L=`${a}-claude`,_=["off","minimal","low","medium","high","xhigh","max"],K=e=>!!e&&"object"==typeof e&&!Array.isArray(e),M=e=>e===S||e===P||e===L;class U{source;constructor(e){this.source=e}}const $=n.DEFAULT_SCHEMA.extend(new n.Type("tag:yaml.org,2002:js",{kind:"scalar",construct:e=>new U(e??""),instanceOf:U,represent:e=>e.source}));function D(r){if(!e(r))return{entries:[],header:""};const o=t(r,"utf-8"),s=o.match(/^(?:#.*\r?\n)*/)?.[0]??"",i=n.load(o,{schema:$});if(null==i)return{entries:[],header:s};if(!Array.isArray(i))throw new Error(`Existing ${r} must hold a YAML list`);return{entries:i,header:s}}function R(r,o){const s=o.header+n.dump(o.entries,{schema:$,lineWidth:-1,noRefs:!0,sortKeys:!1});e(r)&&t(r,"utf-8")===s||(g(r),u(r,s))}function T(e,t){let r=e.find(e=>e.id===t);return r||(r={id:t},e.push(r)),K(r.config)||(r.config={}),r.config}function H(e){const t=e.find(e=>e.id===C&&K(e.config))?.config;return K(t?.providers)?t.providers:{}}function N(){if(!e(E()))return{version:1,refs:{}};const r=n.load(t(E(),"utf-8"));if(null==r)return{version:1,refs:{}};if(!K(r))throw new Error(`Existing ${E()} must hold a YAML mapping`);return"version"in r?K(r.refs)?r:{...r,refs:{}}:{version:1,refs:r}}function W(e){g(E()),u(E(),n.dump(e,{lineWidth:-1,sortKeys:!1}),384)}function F(e){const t=e.capabilities??{},r={id:e.id,name:e.name??l(e.id)},n=t.contextWindow??e.contextWindow;n&&(r.contextWindow=n);const o=t.maxOutput??e.maxOutputTokens;if(o&&(r.maxTokens=o),t.vision&&(r.input=["text","image"]),e.id.startsWith("deepseek-"))r.compat={thinkingFormat:"deepseek"},r.reasoningEfforts={off:null,high:"high",max:"max"};else if(t.reasoning&&t.reasoningEfforts){const e=t.reasoningEfforts.filter(e=>_.includes(e)&&"off"!==e);e.length>0&&(r.reasoningEfforts=Object.fromEntries(e.map(e=>[e,e])))}return r}function Y(e){return"claude"===c(e.id)?L:b(e)?P:S}function G(e,t){const r=x(t),n={apiKeyEnv:s},o={[S]:{displayName:i,...n,api:"openai-completions",baseURL:r,compat:{supportsDeveloperRole:!1,maxTokensField:"max_tokens"}},[P]:{displayName:`${i} GPT`,...n,api:"openai-responses",baseURL:r},[L]:{displayName:`${i} Claude`,...n,api:"anthropic-messages",baseURL:r.replace(/\/v\d+$/,"")}},a={};for(const[t,r]of Object.entries(o)){const n=e.filter(e=>Y(e)===t).map(F);n.length>0&&(a[t]={...r,models:n})}return a}const I=e=>h(v(e.models,f("dsh"))),q=(e,t)=>y(e,t,m("dsh"));function z(e,t,r,n=D(e)){const o=T(n.entries,C),s=Object.entries(K(o.providers)?o.providers:{}).filter(([e])=>!M(e));o.providers={...Object.fromEntries(s),...G(t,r)},R(e,n)}const B=e=>{const t=e.find(e=>e.id===O)?.config;return!K(t)||"string"!=typeof t.provider||M(t.provider)?null:`${t.provider}/${String(t.model)}`};let J=null;export const dshAdapter={name:"dsh",displayName:"DeepSeek Harness",command:"dsh",installCommand:"npx @deepseek-ai/dsh web",get configPath(){return j("web")},wantsModelCatalog:!0,isInstalled(){if(e(k()))return!0;if("darwin"===process.platform)return["/Applications/DeepSeek Harness.app",r(w(),"Applications","DeepSeek Harness.app")].some(t=>e(t));const t="win32"===process.platform?process.env.LOCALAPPDATA:void 0;return!!t&&e(r(t,"Programs","DeepSeek Harness"))},ccSwitch:{app:"dsh",endpointPath:"/v1",cards(e){const t=G(q(e.catalog,I(e)),e.baseUrl);return Object.entries(t).map(([t,r])=>{const{displayName:n,baseURL:o,apiKeyEnv:s,models:i,...a}=r,d=Object.fromEntries(i.map(({id:e,contextWindow:t,maxTokens:r,input:n,...o})=>[String(e),{...o,...t||r?{limit:{...t?{context:t}:{},...r?{output:r}:{}}}:{},...n?{modalities:{input:n,output:["text"]}}:{}}]));return{id:t,name:String(n),settingsConfig:{name:n,kind:"custom",enabled:!0,...a,options:{baseURL:o,apiKey:e.apiKey},models:d}}})},owns:e=>M(e)},loadPrivateConfig(e){const t=q(e.catalog,I(e));if(0===t.length)throw new Error(d.t("tools.dsh.no_models"));const r=t.find(t=>t.id===I(e))??t[0],n=[];for(const o of A){const s=j(o),i=D(s),a=B(i.entries);a&&!n.includes(a)&&n.push(a);const d=T(i.entries,O);d.provider=Y(r),d.model=r.id,delete d.reasoningEffort,z(s,t,e.baseUrl,i)}const o=N();o.refs={...o.refs,[s]:e.apiKey},W(o),J={count:t.length,vendors:p(t.map(e=>e.id)),replaced:n}},unloadPrivateConfig(){try{for(const t of A){const r=j(t);if(!e(r))continue;const n=D(r),o=H(n.entries);for(const e of Object.keys(o))M(e)&&delete o[e];const s=n.entries.find(e=>e.id===O)?.config;K(s)&&"string"==typeof s.provider&&M(s.provider)&&(n.entries=n.entries.filter(e=>e.id!==O)),R(r,n)}const t=N(),r=t.refs;s in r&&(delete r[s],W(t))}catch(e){o.logError("dshAdapter.unloadPrivateConfig",e)}},detectCurrentConfig(){try{const e=N().refs[s];return{apiKey:"string"==typeof e&&e?e:null}}catch{return{apiKey:null}}},listedModels(){try{const e=Object.entries(H(D(j("web")).entries)).filter(([e])=>M(e));return 0===e.length?null:e.flatMap(([,e])=>K(e)&&Array.isArray(e.models)?e.models:[]).map(e=>String(e.id))}catch{return null}},refreshModelMenu(e){const t=q(e.catalog,I(e));if(0!==t.length)for(const r of A)z(j(r),t,e.baseUrl)},planNotes(){try{const e=B(D(j("web")).entries);return e?[d.t("tools.dsh.replaces_default",{model:e})]:[]}catch{return[]}},applyNotes(){if(!J)return[];const e=[{kind:"summary",text:d.t("tools.dsh.menu_written",{count:String(J.count),list:J.vendors.join(d.t("tools.codebuddy.list_separator"))})},{kind:"action",text:d.t("tools.dsh.pick_in_app")}];for(const t of J.replaced)e.push({kind:"detail",text:d.t("tools.dsh.replaced_default",{model:t})});return e},backupPaths:()=>[...A.map(j),E()],forceResetPaths:()=>A.map(j),getConfig(){try{return D(j("web")).entries}catch(e){return o.logError("dshAdapter.getConfig",e),null}}};
@@ -1 +1 @@
1
- import{existsSync as e,readFileSync as t}from"fs";import{join as o}from"path";import*as r from"@iarna/toml";import{logger as n}from"../../utils/logger.js";import{PROVIDER_KEY as i}from"../brand.js";import{backupBeforeWrite as l,atomicWriteFile as s}from"./backup.js";import{pickModel as a,toolHome as d,withV1 as m}from"./types.js";import{i18n as f}from"../i18n.js";import{getToolDefaultModel as g}from"../model-registry.js";import{gatewayModelSpecs as c,modelBlurb as u,modelFamily as p,prettyModelName as y}from"../gateway-models.js";import{brandInstallScripts as k,mirrorInstallCommand as b}from"./tool-installs.js";import{OFFICIAL_PLUGINS as h}from"./claude-plugins.js";const j=()=>o(o(d(),".grok"),"config.toml"),_=i,w=`${i}-`,A=["low","medium","high","xhigh"];let v=null;const C=e=>`${w}${e}`,M=e=>e===_||e.startsWith(w),x={command:"grok",npmPackage:"@xai-official/grok",npmMirrorTagStale:!0,mirrorScript:k("grok"),native:{binDir:[".grok","bin"],updateArgs:["update"],updateTimeoutMs:12e4,dataDirs:[[".grok","downloads"]]}};function S(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}function E(e,t){return S(e[t])||(e[t]={}),e[t]}function O(){if(!e(j()))return{};const o=t(j(),"utf-8");if(!o.trim())return{};try{const e=r.parse(o);if(!S(e))throw new Error("config.toml root must be a TOML table");return e}catch(e){throw new Error(`Existing ~/.grok/config.toml cannot be parsed; back it up and fix it first: ${e instanceof Error?e.message:String(e)}`)}}function P(e){return S(e.model)?Object.entries(e.model).filter(e=>M(e[0])&&S(e[1])):[]}function N(e,t){let o=c("grok",e.catalog?.clientModels,e.catalog?.clientPersonal);if(e.catalog){const t=new Set(e.catalog.models);o=o.filter(e=>t.has(e.id))}return o.some(e=>e.id===t)?o:[{id:t},...o]}function $(e,t,o){E(e,"endpoints").models_base_url=m(t.baseUrl);const r=E(e,"model"),n=new Map(P(e));for(const e of n.keys())delete r[e];for(const e of o){const o=C(e.id),i={...n.get(o)??{},name:e.name??y(e.id),model:e.id,base_url:m(t.baseUrl),api_key:t.apiKey,context_window:e.contextWindow??5e5,api_backend:"responses",reasoning_summary:"concise"};"grok"===p(e.id)&&(i.supports_reasoning_effort=!0,i.reasoning_efforts=A);const l=u(e.description);l?i.description=l:delete i.description,r[o]=i}}export const grokAdapter={name:"grok",displayName:"Grok Build",command:"grok",installCommand:b(x),installSpec:x,configPath:j(),wantsModelCatalog:!0,loadPrivateConfig(e){const t=O(),o=a(e.models,g("grok")),n=N(e,o);$(t,e,n);const i=e=>e.name??y(e.id);v={names:n.map(i),defaultName:i(n.find(e=>e.id===o))},E(t,"models").default=C(o),function(e){const t=E(e,"plugins"),o=e=>Array.isArray(e)?e.map(String):[],r=o(t.enabled),n=o(t.disabled),i=h.filter(e=>!r.includes(e)&&!n.includes(e));i.length>0&&(t.disabled=[...n,...i])}(t),l(j()),s(j(),r.stringify(t))},unloadPrivateConfig(){if(!e(j()))return;let t;try{t=O()}catch(e){return void n.logError("grokAdapter.unloadPrivateConfig",e)}if(S(t.model)){for(const[e]of P(t))delete t.model[e];0===Object.keys(t.model).length&&delete t.model}S(t.models)&&"string"==typeof t.models.default&&M(t.models.default)&&(delete t.models.default,0===Object.keys(t.models).length&&delete t.models),S(t.endpoints)&&(delete t.endpoints.models_base_url,0===Object.keys(t.endpoints).length&&delete t.endpoints),function(e){if(!S(e.plugins)||!Array.isArray(e.plugins.disabled))return;const t=e.plugins.disabled.filter(e=>!h.includes(e));t.length>0?e.plugins.disabled=t:delete e.plugins.disabled,0===Object.keys(e.plugins).length&&delete e.plugins}(t),l(j()),s(j(),r.stringify(t))},detectCurrentConfig(){try{const e=O(),t=P(e),o=S(e.models)?e.models.default:void 0,r=t.find(([e])=>e===o)?.[1]??t[0]?.[1],n=r?r.api_key:null;return{apiKey:"string"==typeof n&&n.trim()?n:null}}catch{return{apiKey:null}}},listedModels(){try{const e=P(O());return e.length>0?e.map(([,e])=>String(e.model)):null}catch{return null}},refreshModelMenu(e){const t=O(),o=E(t,"models"),n="string"==typeof o.default?o.default:void 0,i=n?P(t).find(([e])=>e===n)?.[1].model:void 0,d="string"==typeof i&&n!==_&&e.catalog.models.includes(i)?i:a(e.models,g("grok")),m=r.stringify(t);$(t,e,N(e,d)),(void 0===n||M(n))&&(o.default=C(d)),r.stringify(t)!==m&&(l(j()),s(j(),r.stringify(t)))},applyNotes:()=>v?[{kind:"summary",text:f.t("tools.grok.menu_written",{count:String(v.names.length),list:v.names.join(f.t("tools.grok.list_separator")),default:v.defaultName})}]:[],getConfig(){try{return O()}catch(e){return n.logError("grokAdapter.getConfig",e),null}}};
1
+ import{existsSync as e,readFileSync as t}from"fs";import{join as o}from"path";import*as r from"@iarna/toml";import{logger as n}from"../../utils/logger.js";import{BRAND_NAME as i,CLI_NAME as s,PROVIDER_KEY as l}from"../brand.js";import{backupBeforeWrite as d,atomicWriteFile as a}from"./backup.js";import{pickModel as m,toolHome as f,withV1 as g}from"./types.js";import{i18n as c}from"../i18n.js";import{getToolDefaultModel as u}from"../model-registry.js";import{gatewayModelSpecs as p,modelBlurb as y,modelFamily as k,prettyModelName as b}from"../gateway-models.js";import{brandInstallScripts as h,mirrorInstallCommand as _}from"./tool-installs.js";import{OFFICIAL_PLUGINS as j}from"./claude-plugins.js";const w=()=>o(o(f(),".grok"),"config.toml"),v=l,A=`${l}-`,C=["low","medium","high","xhigh"];function $(e){const t=P(e,"plugins"),o=e=>Array.isArray(e)?e.map(String):[],r=o(t.enabled),n=o(t.disabled),i=j.filter(e=>!r.includes(e)&&!n.includes(e));i.length>0&&(t.disabled=[...n,...i])}let M=null;const S=e=>`${A}${e}`,x=e=>e===v||e.startsWith(A),N={command:"grok",npmPackage:"@xai-official/grok",npmMirrorTagStale:!0,mirrorScript:h("grok"),native:{binDir:[".grok","bin"],updateArgs:["update"],updateTimeoutMs:12e4,dataDirs:[[".grok","downloads"]]}};function O(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}function P(e,t){return O(e[t])||(e[t]={}),e[t]}function E(){if(!e(w()))return{};const o=t(w(),"utf-8");if(!o.trim())return{};try{const e=r.parse(o);if(!O(e))throw new Error("config.toml root must be a TOML table");return e}catch(e){throw new Error(`Existing ~/.grok/config.toml cannot be parsed; back it up and fix it first: ${e instanceof Error?e.message:String(e)}`)}}function K(e){return O(e.model)?Object.entries(e.model).filter(e=>x(e[0])&&O(e[1])):[]}function T(e,t){let o=p("grok",e.catalog?.clientModels,e.catalog?.clientPersonal);if(e.catalog){const t=new Set(e.catalog.models);o=o.filter(e=>t.has(e.id))}return o.some(e=>e.id===t)?o:[{id:t},...o]}function U(e,t,o){P(e,"endpoints").models_base_url=g(t.baseUrl);const r=P(e,"model"),n=new Map(K(e));for(const e of n.keys())delete r[e];for(const e of o){const o=S(e.id);r[o]=W(e,t,n.get(o))}}function W(e,t,o={}){const r={...o,name:e.name??b(e.id),model:e.id,base_url:g(t.baseUrl),api_key:t.apiKey,context_window:e.contextWindow??5e5,api_backend:"responses",reasoning_summary:"concise"};"grok"===k(e.id)&&(r.supports_reasoning_effort=!0,r.reasoning_efforts=C);const n=y(e.description);return n?r.description=n:delete r.description,r}export const grokAdapter={name:"grok",displayName:"Grok Build",command:"grok",installCommand:_(N),installSpec:N,configPath:w(),wantsModelCatalog:!0,ccSwitch:{app:"grokbuild",endpointPath:"/v1",handOver:!0,cards(e){const t=m(e.models,u("grok"));return T(e,t).sort((e,o)=>Number(o.id===t)-Number(e.id===t)).map(t=>{return{id:(o=t.id,`${l}-${s}-${o}`),name:`${i} · ${t.name??b(t.id)}`,settingsConfig:{config:r.stringify({models:{default:S(t.id)},model:{[S(t.id)]:W(t,e)}})}};var o})},owns:e=>e.startsWith(`${l}-${s}-`),applyAsCards(e){const t=E(),o=m(e.models,u("grok")),n=T(e,o).find(e=>e.id===o),i=P(t,"model");for(const[e]of K(t))delete i[e];i[S(n.id)]=W(n,e),P(t,"models").default=S(n.id),P(t,"endpoints").models_base_url=g(e.baseUrl),$(t);const s=n.name??b(n.id);M={names:[s],defaultName:s},d(w()),a(w(),r.stringify(t))}},loadPrivateConfig(e){const t=E(),o=m(e.models,u("grok")),n=T(e,o);U(t,e,n);const i=e=>e.name??b(e.id);M={names:n.map(i),defaultName:i(n.find(e=>e.id===o))},P(t,"models").default=S(o),$(t),d(w()),a(w(),r.stringify(t))},unloadPrivateConfig(){if(!e(w()))return;let t;try{t=E()}catch(e){return void n.logError("grokAdapter.unloadPrivateConfig",e)}if(O(t.model)){for(const[e]of K(t))delete t.model[e];0===Object.keys(t.model).length&&delete t.model}O(t.models)&&"string"==typeof t.models.default&&x(t.models.default)&&(delete t.models.default,0===Object.keys(t.models).length&&delete t.models),O(t.endpoints)&&(delete t.endpoints.models_base_url,0===Object.keys(t.endpoints).length&&delete t.endpoints),function(e){if(!O(e.plugins)||!Array.isArray(e.plugins.disabled))return;const t=e.plugins.disabled.filter(e=>!j.includes(e));t.length>0?e.plugins.disabled=t:delete e.plugins.disabled,0===Object.keys(e.plugins).length&&delete e.plugins}(t),d(w()),a(w(),r.stringify(t))},detectCurrentConfig(){try{const e=E(),t=K(e),o=O(e.models)?e.models.default:void 0,r=t.find(([e])=>e===o)?.[1]??t[0]?.[1],n=r?r.api_key:null;return{apiKey:"string"==typeof n&&n.trim()?n:null}}catch{return{apiKey:null}}},listedModels(){try{const e=K(E());return e.length>0?e.map(([,e])=>String(e.model)):null}catch{return null}},refreshModelMenu(e){const t=E(),o=P(t,"models"),n="string"==typeof o.default?o.default:void 0,i=n?K(t).find(([e])=>e===n)?.[1].model:void 0,s="string"==typeof i&&n!==v&&e.catalog.models.includes(i)?i:m(e.models,u("grok")),l=r.stringify(t);U(t,e,T(e,s)),(void 0===n||x(n))&&(o.default=S(s)),r.stringify(t)!==l&&(d(w()),a(w(),r.stringify(t)))},applyNotes:()=>M?[{kind:"summary",text:c.t("tools.grok.menu_written",{count:String(M.names.length),list:M.names.join(c.t("tools.grok.list_separator")),default:M.defaultName})}]:[],getConfig(){try{return E()}catch(e){return n.logError("grokAdapter.getConfig",e),null}}};
@@ -1 +1 @@
1
- import{existsSync as t}from"fs";import{join as r}from"path";import{logger as o}from"../../utils/logger.js";import{i18n as e}from"../i18n.js";import{getToolDefaultModel as n,getToolMenuModels as d}from"../model-registry.js";import{prettyModelName as s,vendorNames as i}from"../gateway-models.js";import{bareModelId as a,foreignIdsReplaced as l,isOurEntry as p,menuSpecs as u,mergeEntries as c,ourApiKey as m,ourEntries as y,readModelsFile as g,writeModelsFile as f}from"./codebuddy-models.js";import{pickModel as b,toolHome as k}from"./types.js";const w=()=>process.env.WORKBUDDY_CONFIG_DIR?.trim()||process.env.CODEBUDDY_CONFIG_DIR?.trim()||r(k(),".workbuddy"),h=()=>r(w(),"models.json"),C="https://www.codebuddy.cn/work/";let _=null;function j(t,r){const o=g(h()),{entries:e,replaced:n}=c(o.entries,r,t.baseUrl,t.apiKey,!0);return f(h(),o,e),n}const v=t=>a(b(t.models,n("workbuddy"))),D=(t,r)=>u(t,r,d("workbuddy"));export const workbuddyAdapter={name:"workbuddy",displayName:"WorkBuddy",command:"workbuddy",installCommand:"darwin"===process.platform?`open ${C}`:C,get configPath(){return h()},wantsModelCatalog:!0,isInstalled:function(){return!!t(w())||"darwin"===process.platform&&["/Applications/WorkBuddy.app",r(k(),"Applications","WorkBuddy.app")].some(r=>t(r))},loadPrivateConfig(t){const r=D(t.catalog,v(t)),o=j(t,r);_={names:r.map(t=>t.name??s(t.id)),vendors:i(r.map(t=>t.id)),replaced:o}},unloadPrivateConfig(){try{const t=g(h());if(0===y(t.entries).length)return;f(h(),t,t.entries.filter(t=>!p(t)))}catch(t){o.logError("workbuddyAdapter.unloadPrivateConfig",t)}},detectCurrentConfig(){try{return{apiKey:m(g(h()).entries)}}catch{return{apiKey:null}}},listedModels(){try{const t=y(g(h()).entries);return t.length>0?t.map(t=>String(t.id)):null}catch{return null}},refreshModelMenu(t){j(t,D(t.catalog,v(t)))},planNotes(){try{const t=g(h()),r=l(t.entries,D(void 0,n("workbuddy")));return r.length>0?[e.t("tools.codebuddy.replaces_models",{path:h(),list:r.join(e.t("tools.codebuddy.list_separator"))})]:[]}catch{return[]}},applyNotes(){if(!_)return[];const t=[{kind:"summary",text:e.t("tools.workbuddy.menu_written",{count:String(_.names.length),list:_.vendors.join(e.t("tools.codebuddy.list_separator"))})},{kind:"action",text:e.t("tools.workbuddy.pick_in_app")}];return _.replaced.length>0&&t.push({kind:"detail",text:e.t("tools.codebuddy.replaced_models",{tool:"workbuddy",list:_.replaced.join(e.t("tools.codebuddy.list_separator"))})}),t},backupPaths:()=>[h()],getConfig(){try{return g(h()).entries}catch(t){return o.logError("workbuddyAdapter.getConfig",t),null}}};
1
+ import{existsSync as t}from"fs";import{join as r}from"path";import{logger as e}from"../../utils/logger.js";import{i18n as o}from"../i18n.js";import{getToolDefaultModel as n,getToolMenuModels as d}from"../model-registry.js";import{prettyModelName as s,vendorNames as i}from"../gateway-models.js";import{bareModelId as a,foreignIdsReplaced as l,isOurEntry as p,menuSpecs as c,mergeEntries as u,modelEntry as m,ourApiKey as y,ourEntries as g,readModelsFile as f,writeModelsFile as b}from"./codebuddy-models.js";import{pickModel as w,toolHome as h,withV1 as k}from"./types.js";import{BRAND_NAME as C,CLI_NAME as v,PROVIDER_KEY as j}from"../brand.js";const _=()=>process.env.WORKBUDDY_CONFIG_DIR?.trim()||process.env.CODEBUDDY_CONFIG_DIR?.trim()||r(h(),".workbuddy"),P=()=>r(_(),"models.json"),D="https://www.codebuddy.cn/work/";let I=null;function K(t,r){const e=f(P()),{entries:o,replaced:n}=u(e.entries,r,t.baseUrl,t.apiKey,!0);return b(P(),e,o),n}const A=t=>a(w(t.models,n("workbuddy"))),B=(t,r)=>c(t,r,d("workbuddy"));export const workbuddyAdapter={name:"workbuddy",displayName:"WorkBuddy",command:"workbuddy",installCommand:"darwin"===process.platform?`open ${D}`:D,get configPath(){return P()},wantsModelCatalog:!0,isInstalled:function(){return!!t(_())||"darwin"===process.platform&&["/Applications/WorkBuddy.app",r(h(),"Applications","WorkBuddy.app")].some(r=>t(r))},ccSwitch:{app:"workbuddy",endpointPath:"/v1",handOver:!0,cards(t){const r=B(t.catalog,A(t)).map(r=>m(r,t.baseUrl,t.apiKey,!0));return[{settingsConfig:{vendor:C,url:`${k(t.baseUrl)}/chat/completions`,apiKey:t.apiKey,models:r}}]},applyAsCards(t,r){const e=f(P()),o=`${j}-${v}`,n=(r[0]?.settingsConfig.models??[]).map(t=>({...t,ccSwitchProviderId:o})),d=e.entries.filter(t=>!(p(t)||t&&"object"==typeof t&&t.ccSwitchProviderId===o));b(P(),e,[...d,...n])}},loadPrivateConfig(t){const r=B(t.catalog,A(t)),e=K(t,r);I={names:r.map(t=>t.name??s(t.id)),vendors:i(r.map(t=>t.id)),replaced:e}},unloadPrivateConfig(){try{const t=f(P());if(0===g(t.entries).length)return;b(P(),t,t.entries.filter(t=>!p(t)))}catch(t){e.logError("workbuddyAdapter.unloadPrivateConfig",t)}},detectCurrentConfig(){try{return{apiKey:y(f(P()).entries)}}catch{return{apiKey:null}}},listedModels(){try{const t=g(f(P()).entries);return t.length>0?t.map(t=>String(t.id)):null}catch{return null}},refreshModelMenu(t){K(t,B(t.catalog,A(t)))},planNotes(){try{const t=f(P()),r=l(t.entries,B(void 0,n("workbuddy")));return r.length>0?[o.t("tools.codebuddy.replaces_models",{path:P(),list:r.join(o.t("tools.codebuddy.list_separator"))})]:[]}catch{return[]}},applyNotes(){if(!I)return[];const t=[{kind:"summary",text:o.t("tools.workbuddy.menu_written",{count:String(I.names.length),list:I.vendors.join(o.t("tools.codebuddy.list_separator"))})},{kind:"action",text:o.t("tools.workbuddy.pick_in_app")}];return I.replaced.length>0&&t.push({kind:"detail",text:o.t("tools.codebuddy.replaced_models",{tool:"workbuddy",list:I.replaced.join(o.t("tools.codebuddy.list_separator"))})}),t},backupPaths:()=>[P()],getConfig(){try{return f(P()).entries}catch(t){return e.logError("workbuddyAdapter.getConfig",t),null}}};
@@ -330,7 +330,7 @@
330
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
331
  "problem_unreadable": "Couldn't read CC Switch's data ({{path}}). Quit CC Switch completely, then run the same command again",
332
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)",
333
+ "nothing": "Couldn't write to CC Switch: none of the tools this key can set up goes through CC Switch",
334
334
  "plan_add": "Will add or update the {{brand}} card in CC Switch for {{tools}} ({{path}}), without changing these tools' own config",
335
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
336
  "confirm": "Write to CC Switch?",
@@ -339,9 +339,15 @@
339
339
  "done_add": "Added the {{brand}} card for {{tool}} to CC Switch",
340
340
  "done_use": "Switched {{tool}} to the {{brand}} card in CC Switch",
341
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",
342
+ "switch_hint": "Takes effect once you switch to (or add) the {{brand}} card in CC Switch",
343
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"
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
+ "no_models": "{{tool}}: this key has no model a CC Switch card can carry, skipped",
346
+ "handed_over": "Removed the config {{cli}} wrote into {{tool}} directly; CC Switch switches it from now on",
347
+ "plan_handover": "The config {{cli}} wrote into these tools directly is removed first, then CC Switch switches them: {{tools}}",
348
+ "done_add_many": "Added {{count}} {{brand}} cards for {{tool}} to CC Switch",
349
+ "done_enabled": "Added the {{brand}} cards for {{tool}} to CC Switch and turned them on",
350
+ "skipped_foreign": "{{tool}}: CC Switch already has other cards with these ids, left as they are: {{ids}}"
345
351
  },
346
352
  "setup": {
347
353
  "dry_run_tool": "Would configure {{tool}}, writing:",
@@ -805,8 +811,8 @@
805
811
  "all": "Configure every tool the API key can serve (the default)",
806
812
  "install": "Install missing tools from the China mirrors without asking",
807
813
  "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",
814
+ "ccswitch": "Only add {{brand}} to CC Switch as cards, leaving the tools' own config alone (Claude Code, Codex, Claude Desktop, Grok Build, Antigravity, WorkBuddy, CodeBuddy Code, DeepSeek Harness)",
815
+ "ccswitch_use": "Add to CC Switch and switch to it (or turn it on), also writing the tools' config",
810
816
  "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",
811
817
  "codebuddykey": "API key just for CodeBuddy Code",
812
818
  "workbuddykey": "API key just for WorkBuddy",
@@ -330,7 +330,7 @@
330
330
  "problem_running": "无法写入 CC Switch:它正在运行。先在托盘或菜单栏里退出 CC Switch,再运行一次刚才的命令",
331
331
  "problem_unreadable": "无法读取 CC Switch 的数据({{path}})。完全退出 CC Switch 后再运行一次刚才的命令",
332
332
  "not_supported": "{{tools}} 不经 CC Switch 配置,这次没有改动;要直接配置,去掉 --ccswitch 再运行",
333
- "nothing": "无法写入 CC Switch:这个令牌能配的工具里没有经 CC Switch 配置的(Claude Code、Codex)",
333
+ "nothing": "无法写入 CC Switch:这个令牌能配的工具里没有经 CC Switch 配置的",
334
334
  "plan_add": "将在 CC Switch 里添加或更新 {{brand}} 卡片:{{tools}}({{path}}),不改这些工具自己的配置",
335
335
  "plan_use": "将在 CC Switch 里添加或更新 {{brand}} 卡片并切换过去:{{tools}}({{path}}),同时写好这些工具的配置",
336
336
  "confirm": "写入 CC Switch?",
@@ -339,9 +339,15 @@
339
339
  "done_add": "已把 {{tool}} 的 {{brand}} 卡片加进 CC Switch",
340
340
  "done_use": "已把 {{tool}} 切换到 CC Switch 里的 {{brand}} 卡片",
341
341
  "done_proxy": "已写好 {{tool}} 的配置并把 {{brand}} 卡片加进 CC Switch;CC Switch 对它开着本地路由,请在 CC Switch 里切换到 {{brand}}",
342
- "switch_hint": "在 CC Switch 里切换到 {{brand}} 后生效",
342
+ "switch_hint": "在 CC Switch 里切换到(或添加){{brand}} 卡片后生效",
343
343
  "not_installed_card_only": "{{tool}} 还没有安装:只把卡片加进 CC Switch,安装后在 CC Switch 里切换到 {{brand}}",
344
- "refresh_running": "CC Switch 正在运行,{{brand}} 卡片的模型菜单没有更新。退出 CC Switch 后运行 {{cli}} refresh"
344
+ "refresh_running": "CC Switch 正在运行,{{brand}} 卡片的模型菜单没有更新。退出 CC Switch 后运行 {{cli}} refresh",
345
+ "no_models": "{{tool}}:这个令牌没有能放进 CC Switch 卡片的模型,跳过",
346
+ "handed_over": "已移除 {{cli}} 之前直接写进 {{tool}} 的配置,之后由 CC Switch 切换",
347
+ "plan_handover": "这些工具里 {{cli}} 之前直接写的配置会先移除,之后由 CC Switch 切换:{{tools}}",
348
+ "done_add_many": "已把 {{tool}} 的 {{count}} 张 {{brand}} 卡片加进 CC Switch",
349
+ "done_enabled": "已把 {{tool}} 的 {{brand}} 卡片加进 CC Switch 并启用",
350
+ "skipped_foreign": "{{tool}}:CC Switch 里已有同名的其他卡片,没有覆盖:{{ids}}"
345
351
  },
346
352
  "setup": {
347
353
  "dry_run_tool": "将配置 {{tool}},写入:",
@@ -805,8 +811,8 @@
805
811
  "all": "配置令牌能用的全部工具(默认行为)",
806
812
  "install": "未安装的工具直接从国内镜像安装,不再询问",
807
813
  "no_install": "未安装的工具只给出安装命令,不安装",
808
- "ccswitch": "只把 {{brand}} 加进 CC Switch(Claude Code、Codex 各一张卡片),不改工具自己的配置",
809
- "ccswitch_use": "加进 CC Switch 并切换过去,同时写好工具的配置",
814
+ "ccswitch": "只把 {{brand}} 作为卡片加进 CC Switch,不改工具自己的配置(Claude Code、Codex、Claude Desktop、Grok Build、Antigravity、WorkBuddy、CodeBuddy Code、DeepSeek Harness)",
815
+ "ccswitch_use": "加进 CC Switch 并切换过去(或启用),同时写好工具的配置",
810
816
  "upgrade": "先安装或更新这些组件(逗号分隔,如 claude-code,grok;和 upgrade 命令相同),再按其他参数配置",
811
817
  "codebuddykey": "CodeBuddy Code 专属令牌",
812
818
  "workbuddykey": "WorkBuddy 专属令牌",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xhscopy-ai/cli",
3
- "version": "0.0.199",
3
+ "version": "0.0.200",
4
4
  "description": "Configure Claude Code, Codex, Grok Build and other coding tools for Xhscopy AI with one command",
5
5
  "main": "dist/index.js",
6
6
  "bin": {