@caishenai/cli 0.0.173 → 0.0.175
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +1 -1
- package/dist/commands/base.js +1 -1
- package/dist/commands/codex-sessions.js +1 -1
- package/dist/commands/components.js +1 -1
- package/dist/commands/doctor.js +1 -1
- package/dist/commands/sessions.js +1 -1
- package/dist/commands/setup.js +1 -1
- package/dist/commands/upgrade.js +1 -1
- package/dist/lib/app-update.js +1 -1
- package/dist/lib/auto-update.js +1 -1
- package/dist/lib/claude-code-manager.js +1 -1
- package/dist/lib/client-config-sync.js +1 -1
- package/dist/lib/codex-sessions.js +1 -1
- package/dist/lib/command.js +1 -1
- package/dist/lib/components.js +1 -1
- package/dist/lib/config.js +1 -1
- package/dist/lib/env-cleanup.js +1 -1
- package/dist/lib/gateway-addresses.js +1 -1
- package/dist/lib/install-script.js +1 -0
- package/dist/lib/model-refresh.js +1 -1
- package/dist/lib/persistent-env.js +1 -1
- package/dist/lib/post-apply.js +1 -1
- package/dist/lib/signals.js +1 -0
- package/dist/lib/system-report.js +1 -0
- package/dist/lib/telemetry.js +1 -1
- package/dist/lib/tool-manager.js +1 -1
- package/dist/lib/tool-upgrade.js +1 -1
- package/dist/lib/tools/backup.js +1 -1
- package/dist/lib/tools/claude-code.js +1 -1
- package/dist/lib/tools/claude-desktop-cli.js +1 -1
- package/dist/lib/tools/claude-desktop.js +1 -1
- package/dist/lib/tools/claude-plugins.js +1 -1
- package/dist/lib/tools/codex.js +1 -1
- package/dist/lib/tools/desktop-app-installer.js +1 -1
- package/dist/lib/tools/elevated-reg.js +1 -1
- package/dist/lib/tools/tool-installs.js +1 -1
- package/dist/lib/windows-security.js +1 -0
- package/dist/lib/written-values.js +1 -1
- package/dist/locales/en_US.json +12 -3
- package/dist/locales/zh_CN.json +12 -3
- package/dist/utils/process-alive.js +1 -0
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{execFileSync as e}from"child_process";import{createHash as r}from"crypto";import{createReadStream as t,createWriteStream as
|
|
1
|
+
import{execFileSync as e}from"child_process";import{createHash as r}from"crypto";import{createReadStream as t,createWriteStream as o,existsSync as s,readdirSync as n,readFileSync as i}from"fs";import{copyFile as a,mkdir as l,readFile as c,rename as u,rm as f,writeFile as p}from"fs/promises";import{isAbsolute as d,join as m,normalize as h,sep as w}from"path";import{Readable as g,Writable as b}from"stream";import{pipeline as v}from"stream/promises";import*as D from"zlib";import{logger as y}from"../../utils/logger.js";import{brand as k,brandEnv as $}from"../brand.js";import{downloadNativeBinary as C,nativeLayout as S,nativePlatformKey as x}from"./claude-native-mirror.js";import{WINDOWS_PACKAGE_FAMILIES as N}from"./desktop-process.js";import{toolHome as A}from"./types.js";import{mirrorFileUrl as P,withDownloadFallback as L}from"../mirror-url.js";import{powerShellEnv as O}from"../powershell-env.js";export function readDesktopCliPin(e,r,t=!1){const o=e.indexOf('claude-code-releases","sdkWrapperVersion"');if(o<0)return null;const s=e.lastIndexOf("JSON.parse('",o),n=e.indexOf("')",o);if(s<0||n<0)return null;try{const o=JSON.parse(e.subarray(s+12,n).toString("utf-8")),i="string"==typeof o.version?o.version:"",a=o.manifest?.platforms?.[r],l=t?a?.bundle?.checksum:a?.checksum;return/^\d+\.\d+\.\d+$/.test(i)&&"string"==typeof l&&/^[0-9a-f]{64}$/.test(l)?{version:i,checksum:l}:null}catch{return null}}function E(){const r=m(process.env.LOCALAPPDATA||"","AnthropicClaude");if(process.env.LOCALAPPDATA&&s(r)){const e=n(r).filter(e=>/^app-\d+\.\d+\.\d+$/.test(e)).sort((e,r)=>r.localeCompare(e,void 0,{numeric:!0}));for(const t of e){const e=m(r,t,"resources","app.asar");if(s(e))return e}}try{const r=e("powershell.exe",["-NoProfile","-Command",`Get-AppxPackage | Where-Object { @(${N.map(e=>`'${e}'`).join(",")}) -contains $_.PackageFamilyName } | ForEach-Object { $_.InstallLocation }`],{encoding:"utf-8",timeout:15e3,windowsHide:!0,stdio:["ignore","pipe","ignore"],env:O()});for(const e of r.split(/\r?\n/).map(e=>e.trim()).filter(Boolean)){const r=m(e,"app","resources","app.asar");if(s(r))return r}}catch(e){y.logError("claude-desktop-cli.windowsAsarPath",e)}return null}function j(){if($("TEST_HOME")?.trim())return null;for(const e of["/usr/lib/claude-desktop","/opt/Claude"]){const r=m(e,"resources","app.asar");if(s(r))return r}return null}function F(){for(const e of["/Applications/Claude.app",m(A(),"Applications","Claude.app")]){const r=m(e,"Contents","Resources","app.asar");if(s(r))return r}return null}export function installedDesktopAsarPath(){return"win32"===process.platform?E():"darwin"===process.platform?F():"linux"===process.platform?j():null}class T extends b{dest;buffer=Buffer.alloc(0);remaining=0;padding=0;file=null;longName=null;collectingLongName=null;constructor(e){super(),this.dest=e}_write(e,r,t){this.buffer=this.buffer.length?Buffer.concat([this.buffer,e]):e,this.drain().then(()=>t()).catch(t)}_final(e){this.remaining>0?e(new Error("archive ends inside an entry")):e()}target(e){const r=h(e);if(!r||d(r)||".."===r||r.startsWith(`..${w}`))throw new Error(`unsafe path in archive: ${e}`);return m(this.dest,r)}async closeFile(){const e=this.file;this.file=null,e&&await new Promise((r,t)=>e.end(e=>e?t(e):r()))}async drain(){for(;;){if(this.remaining>0){if(0===this.buffer.length)return;const e=this.buffer.subarray(0,Math.min(this.remaining,this.buffer.length));this.buffer=this.buffer.subarray(e.length),this.remaining-=e.length,this.collectingLongName?this.collectingLongName.push(e):this.file&&!this.file.write(e)&&await new Promise(e=>this.file.once("drain",()=>e())),0===this.remaining&&(this.collectingLongName&&(this.longName=Buffer.concat(this.collectingLongName).toString("utf-8").replace(/\0.*$/s,""),this.collectingLongName=null),await this.closeFile());continue}if(this.padding>0){if(this.buffer.length<this.padding)return;this.buffer=this.buffer.subarray(this.padding),this.padding=0}if(this.buffer.length<512)return;const e=this.buffer.subarray(0,512);if(this.buffer=this.buffer.subarray(512),e.every(e=>0===e))continue;const r=(r,t)=>e.subarray(r,r+t).toString("utf-8").replace(/\0.*$/s,""),t=r(345,155);let s=t?`${t}/${r(0,100)}`:r(0,100);null!==this.longName&&(s=this.longName,this.longName=null);const n=parseInt(r(124,12).trim()||"0",8),i=511&parseInt(r(100,8).trim()||"644",8),a=r(156,1)||"0";if(this.remaining=n,this.padding=(512-n%512)%512,"L"===a)this.collectingLongName=[];else if("x"===a||"g"===a);else if("5"===a)await l(this.target(s),{recursive:!0});else{if("0"!==a)throw new Error(`unexpected entry type ${a} in archive: ${s}`);{const e=this.target(s);await l(m(e,".."),{recursive:!0}),this.file=o(e,{mode:i||420}),0===n&&await this.closeFile()}}}}}export async function installDesktopCli(e){const o=readDesktopCliPin(e.asar,e.platformKey,e.bundle);if(!o)return{status:"skipped",reason:"unknown app layout"};if(e.bundle&&!e.download)return{status:"skipped",reason:"no bundle mirror"};const n=e.platformKey.startsWith("win32")?"claude.exe":"claude",i=m(e.userDataDir,"claude-code",o.version),d=m(i,o.checksum.slice(0,12)),h=e.bundle?m(d,"claude.app","Contents","MacOS","claude"):m(d,n),w=m(d,".verified");try{if(s(h)&&(await c(w,"utf-8")).trim()===o.checksum)return{status:"present",version:o.version}}catch{}await l(i,{recursive:!0});const g=m(i,`.partial-${o.checksum.slice(0,12)}`),y=`${g}.download`;try{await f(w,{force:!0}),await f(g,{recursive:!0,force:!0});let n="mirror";if(e.bundle){if(e.onStart?.(o.version,"mirror"),e.onDownload?.(o.version),await e.download(o.version,y),await async function(e,o,s){const n=r("sha256");if(await v(t(e),new b({write(e,r,t){n.update(e),t()}})),n.digest("hex")!==o)throw new Error("downloaded bundle does not match the app's checksum");const i=D.createZstdDecompress;if(!i)throw new Error(`Node ${process.version} cannot decompress zstd (needs 22.15 or newer)`);await v(t(e),i(),new T(s))}(y,o.checksum,g),!s(m(g,"claude.app","Contents","MacOS","claude")))throw new Error("bundle has no claude.app");await f(d,{recursive:!0,force:!0}),await u(g,d)}else{const r=e.localVersionsDir?m(e.localVersionsDir,o.version):null;if(r&&s(r))e.onStart?.(o.version,"local"),await a(r,g),n="local";else{e.onStart?.(o.version,"mirror"),e.onDownload?.(o.version);const r=e.download??((r,t)=>C(e.platformKey,r,t));await r(o.version,g)}await l(d,{recursive:!0}),await u(g,h)}return await p(w,o.checksum),{status:"installed",version:o.version,source:n}}finally{await f(g,{recursive:!0,force:!0}),await f(y,{force:!0}),await f(`${g}.download`,{force:!0})}}let K=(...e)=>fetch(...e);export function setDesktopCliFetchForTests(e){K=e}export async function ensureDesktopCli(e){const r=x();if(!r)return{status:"skipped",reason:"unsupported architecture"};if("win32"===process.platform){const t=E();return t?installDesktopCli({userDataDir:e.userDataDir,asar:i(t),platformKey:r,localVersionsDir:S().versionsDir,onDownload:e.onDownload,onStart:e.onStart}):{status:"skipped",reason:"app.asar not found"}}if("darwin"===process.platform){const t=F();if(!t)return{status:"skipped",reason:"app.asar not found"};const{mirror:s,desktopVersion:n}=e;return installDesktopCli({userDataDir:e.userDataDir,asar:i(t),platformKey:r,bundle:!0,onDownload:e.onDownload,onStart:e.onStart,download:s&&n?(e,t)=>L(P(s,`claude-code-${e}-${r}.app.tar.zst`,`v${n}`),k().installMirror?.downloadCounter,e=>async function(e,r){const t=await K(e,{signal:AbortSignal.timeout(9e5)});if(!t.ok||!t.body)throw new Error(`${e}: HTTP ${t.status}`);await v(g.fromWeb(t.body),o(r))}(e,t)):void 0})}if("linux"===process.platform){const t=j();return t?installDesktopCli({userDataDir:e.userDataDir,asar:i(t),platformKey:r.replace(/-musl$/,""),localVersionsDir:r.endsWith("-musl")?void 0:S().versionsDir,onDownload:e.onDownload,onStart:e.onStart}):{status:"skipped",reason:"app.asar not found"}}return{status:"skipped",reason:"unsupported platform"}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{chmodSync as e,existsSync as t,mkdirSync as o,readdirSync as n,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 D,atomicWriteFile as A}from"./backup.js";import{toolHome as C}from"./types.js";import{canRestartDesktop as v,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 $}from"./elevated-reg.js";import{UserActionNeeded as G}from"./types.js";import{savedApiKeys as N}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 V}from"../powershell-env.js";const W=h;export const CLAUDE_DESKTOP_HIDE_OFFICIAL_LOGIN_SETTING="hide_official_login";export const CLAUDE_DESKTOP_FORCE_REGISTRY_SETTING="force_registry";const z=/^[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 o=C(),n=Boolean(_("TEST_HOME")?.trim());switch(process.platform){case"darwin":return l(o,"Library","Application Support","Claude-3p");case"win32":{const e=!n&&process.env.LOCALAPPDATA?process.env.LOCALAPPDATA:l(o,"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=!n&&process.env.XDG_CONFIG_HOME?process.env.XDG_CONFIG_HOME:l(o,".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 o=r(e,"utf-8");if(!o.trim())return null;try{const e=JSON.parse(o);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(n,r){const s=i(n);t(s)||o(s,{recursive:!0,mode:448}),D(n),A(n,JSON.stringify(r,null,2)+"\n");try{e(n,384)}catch(e){p.logError("claude-desktop.writeJson.chmod",e)}}function oe(){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 ne(e){return e?.entries.find(e=>e.name===W&&z.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:o,bySlot:n}=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 o=(e[t]||"").trim(),n=R(o);n&&(i.includes(n)||i.push(n),/\[1m\]/i.test(o)&&r.add(n))}}const l=e=>re[ie(e)??""]??9;i.sort((e,t)=>{if(e===o)return-1;if(t===o)return 1;const n=l(e)-l(t);if(0!==n)return n;const r=se(e),s=se(t);return r&&s?function(e,t){const o=Math.max(e.length,t.length);for(let n=0;n<o;n++){const o=(t[n]??0)-(e[n]??0);if(0!==o)return o}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 n){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),o={name:e,labelOverride:s[e]||humanizeModelId(e)};if(r.has(e)&&(o.supports1m=!0,o.prefer1m=!0),t){o.anthropicFamilyTier=t;const n=c.get(t);n&&n!==e||a.has(t)||(o.isFamilyDefault=!0,a.add(t))}return o})}let le=null,ae=null,ce=null,de=null,ue=null;function pe(e){return{inferenceProvider:"gateway",inferenceCredentialKind:"static",inferenceGatewayBaseUrl:(e.baseUrl||"").trim().replace(/\/+$/,""),inferenceGatewayApiKey:e.apiKey,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 fe={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}},me=()=>{if(_("TEST_HOME")?.trim())return null;const e=g();return e?r(e):null};let ge=me,ye=null;export function setDesktopAsarForTests(e){ge=void 0===e?me:()=>e,ye=null}function he(){if(ye)return ye;let e=null;try{e=ge()}catch(e){p.logError("claude-desktop.unsupportedDefaults",e)}return ye=new Set(e?Object.keys(fe).filter(t=>!e.includes(t)):[]),ye}function ke(e){const t=he();return Object.fromEntries(Object.entries(fe).filter(([o])=>!e(o)&&!t.has(o)))}function _e(e){const t={...ke(t=>t in e),...e};for(const e of he())e in t&&JSON.stringify(t[e])===JSON.stringify(fe[e])&&delete t[e];return t}const we="SOFTWARE\\Policies\\Claude",be=`HKCU\\${we}`,De="HKLM\\SOFTWARE\\Policies\\Claude",Ae=`${w}-claude-policy.reg`,Ce=e=>c("reg",e,{stdio:["ignore","pipe","pipe"]}).toString();let ve=Ce;export function setRegRunnerForTests(e){ve=e??Ce}function Ee(){return"win32"===process.platform}function Me(e){let t;try{t=ve(["query",e])}catch{return null}const o=new Map;for(const e of t.split(/\r?\n/)){const t=/^\s{2,}(\S+)\s+(REG_[A-Z_]+)\s*(.*)$/.exec(e);t&&o.set(t[1],t[3])}return o}function Oe(){if(null===Me(be))return;const e=l(claudeDesktopUserDataDir(),Ae);try{t(i(e))||o(i(e),{recursive:!0,mode:448}),D(e),ve(["export",be,e,"/y"])}catch(e){p.logError("claude-desktop.snapshotPolicy",e)}}function Se(e){Oe();for(const[t,o]of Object.entries(e)){const[e,n]="boolean"==typeof o?["REG_DWORD",o?"1":"0"]:"number"==typeof o?["REG_DWORD",String(o)]:"string"==typeof o?["REG_SZ",o]:["REG_SZ",JSON.stringify(o)];ve(["add",be,"/v",t,"/t",e,"/d",n,"/f"])}}function xe(e){const t=Me(be);if(!t)return;Oe();let o=t.size;for(const n of e)t.has(n)&&(ve(["delete",be,"/v",n,"/f"]),o-=1);o<=0&&ve(["delete",be,"/f"])}function je(){const e=!Boolean(_("TEST_HOME")?.trim())&&process.env.LOCALAPPDATA?process.env.LOCALAPPDATA:l(C(),"AppData","Local");return!!t(l(e,"AnthropicClaude"))||j.some(o=>t(l(e,"Packages",o,"LocalCache","Local","Claude-3p")))}const Pe=[...Object.keys(pe({apiKey:"",baseUrl:"",models:{haiku:"",sonnet:"",opus:"",reasoning:""}})),...Object.keys(fe)];function Ie(e){if(!e||!Pe.some(t=>e.has(t)))return"none";const t=e.get("inferenceGatewayApiKey")?.trim();return U(e.get("inferenceGatewayBaseUrl"))||t&&N().includes(t)?"ours":"foreign"}function Le(){const e=ee(Q())?.deploymentMode;if(void 0!==e&&"3p"!==e)return{kind:"mode"};const t=oe(),o=t?.entries.find(e=>e.id===t.appliedId);if(!o||o.id===ne(t)?.id)return null;const n=ee(Y(o.id));return n&&(n.inferenceProvider||n.inferenceGatewayBaseUrl)?{kind:"entry",name:o.name}:null}function Te(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,Ge=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 Me(De)?De: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 Ne(){const e=C();let o;switch(process.platform){case"darwin":o=["/Applications/Claude.app",l(e,"Applications","Claude.app")];break;case"win32":{const t=process.env.LOCALAPPDATA||l(e,"AppData","Local");o=[l(t,"AnthropicClaude"),l(t,"Programs","Claude"),...j.map(e=>l(t,"Packages",e))];break}default:o=["/usr/lib/claude-desktop","/opt/Claude","/usr/bin/claude-desktop",l(e,".local","bin","claude-desktop")]}return o.push(claudeDesktopUserDataDir(),l(claudeDesktopUserDataDir(),"..","Claude")),o.some(e=>t(e))}const Ue=/\d+\.\d+\.\d+/;function Ke(e){const t=e=>e.split(".").map(Number);return e.sort((e,o)=>{const[n,r]=[t(e),t(o)];for(let e=0;e<3;e++)if(n[e]!==r[e])return r[e]-n[e];return 0})[0]??null}function Re(){if("darwin"===process.platform){for(const e of["/Applications/Claude.app",l(C(),"Applications","Claude.app")]){const o=l(e,"Contents","Info.plist");if(!t(o))continue;const n=/<key>CFBundleShortVersionString<\/key>\s*<string>([^<]+)<\/string>/.exec(r(o,"utf-8")),s=n?Ue.exec(n[1])?.[0]:void 0;if(s)return s}return null}if("win32"===process.platform){const e=l(process.env.LOCALAPPDATA||l(C(),"AppData","Local"),"AnthropicClaude");if(t(e)){const t=n(e).map(e=>/^app-(\d+\.\d+\.\d+)$/.exec(e)?.[1]).filter(e=>!!e);if(t.length>0)return Ke(t)}const o=j.map(e=>`'${e}'`).join(",");return Ke(c("powershell.exe",["-NoProfile","-Command",`Get-AppxPackage | Where-Object { @(${o}) -contains $_.PackageFamilyName } | ForEach-Object { $_.Version.ToString() }`],{encoding:"utf-8",timeout:15e3,windowsHide:!0,stdio:["ignore","pipe","ignore"],env:V()}).split(/\r?\n/).flatMap(e=>Ue.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 Ue.exec(e)?.[0]??null}catch{return null}return null}const Fe="darwin"===process.platform?"open -a Claude":"win32"===process.platform?"Claude":"claude-desktop",Be="darwin"!==process.platform&&"win32"!==process.platform||!k().installMirror?.claudeDesktop?"https://claude.ai/download":b(k().installMirror.claudeDesktop),He="darwin"===process.platform?`open ${Be}`:"win32"===process.platform?`start ${Be}`:`xdg-open ${Be}`;export const claudeDesktopAdapter={name:"claude-desktop",displayName:"Claude Desktop",command:Fe,installCommand:He,configPath:Z(),sessions:{format:H,files:()=>J(l(claudeDesktopUserDataDir(),"local-agent-mode-sessions"))},isInstalled:Ne,installedVersion:Re,prepareRuntime:async function(){if(!["win32","darwin","linux"].includes(process.platform)||!Ne())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}))),desktopVersion:"darwin"===process.platform?Re():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:v()?{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 Re()?"MSIX":null}catch(e){return p.logError("claude-desktop.installedPath",e),null}},install:e=>T(e)},wantsModelCatalog:!0,loadPrivateConfig(e){const t=oe()??{appliedId:"",entries:[]};let o=ne(t);o||(o={id:a(),name:W},t.entries.push(o));const n=pe(e);K(String(n.inferenceGatewayBaseUrl)),ae=!0===n.disableDeploymentModeChooser,le={models:n.inferenceModels,source:e.catalog?e.catalog.oneMillionSource:"slots",groups:e.catalog?.matchedGroups??[]};const r=ee(Y(o.id))??{};te(Y(o.id),{..._e(r),...n});const s=Le();$e=s&&!e.takeOver?Te(s):null,$e||(t.appliedId=o.id),te(Z(),t);const i=ee(Q())??{};$e||"3p"===i.deploymentMode||te(Q(),{...i,deploymentMode:"3p"}),de=null,ue=null,ce=null,Ge=null;const l=!0===e.settings?.force_registry,c=Ee()?Me(be):null;if(Ee()&&"foreign"===Ie(c)&&!l)Ge=c?.get("inferenceGatewayBaseUrl")||be;else if(Ee()){const t=Me(be),o=Pe.filter(e=>t?.has(e)),r={...ke(e=>t?.has(e)??!1),...n},s=!0===e.settings?.force_registry,i=!s&&je();try{i?xe(Pe):Se(r),ce=i?"removed":"written"}catch(e){p.logError("claude-desktop.policy",e),de=e instanceof Error?e.message.trim():String(e),(o.length>0||s)&&(ue=i?{action:"remove",values:Object.fromEntries(o.map(e=>[e,null])),deleteKey:o.length===t.size}:{action:"write",values:r,deleteKey:!1})}}},pendingElevation(){const e=ue;return e?{prompt:y.t(`tools.claude_desktop.elevate_${e.action}`),run:()=>{if(!$(we,e.values,e.deleteKey))return!1;const t=Me(be),o="remove"===e.action?Object.keys(e.values).every(e=>!t?.has(e)):Object.keys(e.values).every(e=>t?.has(e));return o&&(ue=null,de=null),o}}:null},unloadPrivateConfig(){if(Ee()&&"ours"===Ie(Me(be)))try{xe(Pe)}catch(e){p.logError("claude-desktop.removePolicy",e)}const e=oe(),t=ne(e);if(!e||!t)return;D(Y(t.id)),s(Y(t.id),{force:!0});const o=e.entries.filter(e=>e.id!==t.id);0===o.length?(D(Z()),s(Z(),{force:!0})):te(Z(),{...e,entries:o,appliedId:e.appliedId===t.id?o[0].id:e.appliedId})},listedModels(){const e=oe(),t=ne(e);if(!t||e?.appliedId!==t.id)return null;const o=ee(Y(t.id))?.inferenceModels;return Array.isArray(o)?o.map(e=>String(e.name)):null},refreshModelMenu(e){const t=oe(),o=ne(t);if(!o||t?.appliedId!==o.id)return;const n=ee(Y(o.id));if(!n)return;const r=buildInferenceModels(e.models,e.catalog),s=JSON.stringify(n.inferenceModels)!==JSON.stringify(r),i={..._e(n),inferenceModels:r},l=JSON.stringify(i)!==JSON.stringify(n);ue=null;const a=Ee()?Me(be):null,c="foreign"===Ie(a)&&!0!==e.settings?.force_registry;if(!a?.has("inferenceModels")||c)return void(l&&te(Y(o.id),i));const d=Pe.filter(e=>a.has(e)),u=!0!==e.settings?.force_registry&&je();if(l&&te(Y(o.id),i),u||s)try{u?xe(Pe):Se({inferenceModels:r})}catch(e){throw p.logError("claude-desktop.refreshModelMenu registry",e),ue=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"))}},detectCurrentConfig(){try{if(Ee()){const e=Me(be)?.get("inferenceGatewayApiKey");if(e)return{apiKey:e}}const e=ne(oe());if(!e)return{apiKey:null};const t=ee(Y(e.id)),o=t?.inferenceGatewayApiKey;return{apiKey:"string"==typeof o&&o?o:null}}catch(e){return p.logError("claude-desktop.detectCurrentConfig",e),{apiKey:null}}},getConfig(){try{const e=oe(),t=ne(e);return{meta:e,applied:t?ee(Y(t.id)):null,desktop:ee(Q()),...Ee()?{policy:Object.fromEntries(Me(be)??[])}:{}}}catch(e){return p.logError("claude-desktop.getConfig",e),null}},clearPinnedModels(){let e=!1;Ee()&&Me(be)?.has("inferenceModels")&&(Oe(),ve(["delete",be,"/v","inferenceModels","/f"]),e=!0);const t=ne(oe()),o=t?ee(Y(t.id)):null;if(t&&o&&void 0!==o.inferenceModels){const{inferenceModels:n,...r}=o;te(Y(t.id),r),e=!0}return e?["inferenceModels"]:[]},applyNotes(){const e=[];if(le&&le.models.length>0){const{models:t,source:o,groups:n}=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_${o}`,{count:String(t.length),list:t.map(e=>`${e.labelOverride}${e.supports1m?" (1M)":""}`).join(", "),groups:n.join(" / ")})})}null!==ae&&e.push({kind:"detail",text:y.t(ae?"tools.claude_desktop.official_login_hidden":"tools.claude_desktop.official_login_shown")}),v()&&!M()||e.push({kind:"action",text:y.t("tools.claude_desktop.restart_hint")}),ue?(e.push({kind:"action",text:y.t(`tools.claude_desktop.policy_stale_${ue.action}`)}),e.push({kind:"detail",text:de??""})):de?(e.push({kind:"detail",text:y.t("tools.claude_desktop.registry_denied")}),e.push({kind:"detail",text:de})):Ee()&&ce&&e.push({kind:"detail",text:y.t(`tools.claude_desktop.registry_${ce}`,{key:be})}),$e&&e.push({kind:"action",text:y.t("tools.claude_desktop.not_switched",{current:$e})}),Ge&&e.push({kind:"action",text:y.t("tools.claude_desktop.foreign_policy",{key:be,url:Ge})});const t=detectManagedConfig();return t&&e.push({kind:"action",text:y.t("tools.claude_desktop.managed_conflict",{path:t})}),e},planNotes(){const e=[],t=Le();if(t&&e.push(y.t("tools.claude_desktop.plan_switch",{current:Te(t)})),Ee()){const t=Me(be);"foreign"===Ie(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=ne(oe());t&&e.push(Y(t.id))}catch{}return e},backupPaths(){const e=[Z(),Q()];Ee()&&e.push(l(claudeDesktopUserDataDir(),Ae));try{const t=ne(oe());t&&e.push(Y(t.id))}catch{}return e}};
|
|
1
|
+
import{chmodSync as e,existsSync as t,mkdirSync as o,readdirSync as n,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 D,atomicWriteFile as A}from"./backup.js";import{toolHome as C}from"./types.js";import{canRestartDesktop as v,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 $}from"./elevated-reg.js";import{UserActionNeeded as G}from"./types.js";import{savedApiKeys as N}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 V}from"../powershell-env.js";const W=h;export const CLAUDE_DESKTOP_HIDE_OFFICIAL_LOGIN_SETTING="hide_official_login";export const CLAUDE_DESKTOP_FORCE_REGISTRY_SETTING="force_registry";const z=/^[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 o=C(),n=Boolean(_("TEST_HOME")?.trim());switch(process.platform){case"darwin":return l(o,"Library","Application Support","Claude-3p");case"win32":{const e=!n&&process.env.LOCALAPPDATA?process.env.LOCALAPPDATA:l(o,"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=!n&&process.env.XDG_CONFIG_HOME?process.env.XDG_CONFIG_HOME:l(o,".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 o=r(e,"utf-8");if(!o.trim())return null;try{const e=JSON.parse(o);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(n,r){const s=i(n);t(s)||o(s,{recursive:!0,mode:448}),D(n),A(n,JSON.stringify(r,null,2)+"\n");try{e(n,384)}catch(e){p.logError("claude-desktop.writeJson.chmod",e)}}function oe(){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 ne(e){return e?.entries.find(e=>e.name===W&&z.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:o,bySlot:n}=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 o=(e[t]||"").trim(),n=R(o);n&&(i.includes(n)||i.push(n),/\[1m\]/i.test(o)&&r.add(n))}}const l=e=>re[ie(e)??""]??9;i.sort((e,t)=>{if(e===o)return-1;if(t===o)return 1;const n=l(e)-l(t);if(0!==n)return n;const r=se(e),s=se(t);return r&&s?function(e,t){const o=Math.max(e.length,t.length);for(let n=0;n<o;n++){const o=(t[n]??0)-(e[n]??0);if(0!==o)return o}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 n){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),o={name:e,labelOverride:s[e]||humanizeModelId(e)};if(r.has(e)&&(o.supports1m=!0,o.prefer1m=!0),t){o.anthropicFamilyTier=t;const n=c.get(t);n&&n!==e||a.has(t)||(o.isFamilyDefault=!0,a.add(t))}return o})}let le=null,ae=null,ce=null,de=null,ue=null;function pe(e){return{inferenceProvider:"gateway",inferenceCredentialKind:"static",inferenceGatewayBaseUrl:(e.baseUrl||"").trim().replace(/\/+$/,""),inferenceGatewayApiKey:e.apiKey,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 fe={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}},me=()=>{if(_("TEST_HOME")?.trim())return null;const e=g();return e?r(e):null};let ge=me,ye=null;export function setDesktopAsarForTests(e){ge=void 0===e?me:()=>e,ye=null}function he(){if(ye)return ye;let e=null;try{e=ge()}catch(e){p.logError("claude-desktop.unsupportedDefaults",e)}return ye=new Set(e?Object.keys(fe).filter(t=>!e.includes(t)):[]),ye}function ke(e){const t=he();return Object.fromEntries(Object.entries(fe).filter(([o])=>!e(o)&&!t.has(o)))}function _e(e){const t={...ke(t=>t in e),...e};for(const e of he())e in t&&JSON.stringify(t[e])===JSON.stringify(fe[e])&&delete t[e];return t}const we="SOFTWARE\\Policies\\Claude",be=`HKCU\\${we}`,De="HKLM\\SOFTWARE\\Policies\\Claude",Ae=`${w}-claude-policy.reg`,Ce=e=>c("reg",e,{stdio:["ignore","pipe","pipe"]}).toString();let ve=Ce;export function setRegRunnerForTests(e){ve=e??Ce}function Ee(){return"win32"===process.platform}function Me(e){let t;try{t=ve(["query",e])}catch{return null}const o=new Map;for(const e of t.split(/\r?\n/)){const t=/^\s{2,}(\S+)\s+(REG_[A-Z_]+)\s*(.*)$/.exec(e);t&&o.set(t[1],t[3])}return o}function Oe(){if(null===Me(be))return;const e=l(claudeDesktopUserDataDir(),Ae);try{t(i(e))||o(i(e),{recursive:!0,mode:448}),D(e),ve(["export",be,e,"/y"])}catch(e){p.logError("claude-desktop.snapshotPolicy",e)}}function Se(e){Oe();for(const[t,o]of Object.entries(e)){const[e,n]="boolean"==typeof o?["REG_DWORD",o?"1":"0"]:"number"==typeof o?["REG_DWORD",String(o)]:"string"==typeof o?["REG_SZ",o]:["REG_SZ",JSON.stringify(o)];ve(["add",be,"/v",t,"/t",e,"/d",n,"/f"])}}function xe(e){const t=Me(be);if(!t)return;Oe();let o=t.size;for(const n of e)t.has(n)&&(ve(["delete",be,"/v",n,"/f"]),o-=1);o<=0&&ve(["delete",be,"/f"])}function je(){const e=!Boolean(_("TEST_HOME")?.trim())&&process.env.LOCALAPPDATA?process.env.LOCALAPPDATA:l(C(),"AppData","Local");return!!t(l(e,"AnthropicClaude"))||j.some(o=>t(l(e,"Packages",o,"LocalCache","Local","Claude-3p")))}const Pe=[...Object.keys(pe({apiKey:"",baseUrl:"",models:{haiku:"",sonnet:"",opus:"",reasoning:""}})),...Object.keys(fe)];function Ie(e){if(!e||!Pe.some(t=>e.has(t)))return"none";const t=e.get("inferenceGatewayApiKey")?.trim();return U(e.get("inferenceGatewayBaseUrl"))||t&&N().includes(t)?"ours":"foreign"}function Le(){const e=ee(Q())?.deploymentMode;if(void 0!==e&&"3p"!==e)return{kind:"mode"};const t=oe(),o=t?.entries.find(e=>e.id===t.appliedId);if(!o||o.id===ne(t)?.id)return null;const n=ee(Y(o.id));return n&&(n.inferenceProvider||n.inferenceGatewayBaseUrl)?{kind:"entry",name:o.name}:null}function Te(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,Ge=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 Me(De)?De: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 Ne(){const e=C();let o;switch(process.platform){case"darwin":o=["/Applications/Claude.app",l(e,"Applications","Claude.app")];break;case"win32":{const t=process.env.LOCALAPPDATA||l(e,"AppData","Local");o=[l(t,"AnthropicClaude"),l(t,"Programs","Claude"),...j.map(e=>l(t,"Packages",e))];break}default:o=["/usr/lib/claude-desktop","/opt/Claude","/usr/bin/claude-desktop",l(e,".local","bin","claude-desktop")]}return o.push(claudeDesktopUserDataDir(),l(claudeDesktopUserDataDir(),"..","Claude")),o.some(e=>t(e))}const Ue=/\d+\.\d+\.\d+/;function Ke(e){const t=e=>e.split(".").map(Number);return e.sort((e,o)=>{const[n,r]=[t(e),t(o)];for(let e=0;e<3;e++)if(n[e]!==r[e])return r[e]-n[e];return 0})[0]??null}function Re(){if("darwin"===process.platform){for(const e of["/Applications/Claude.app",l(C(),"Applications","Claude.app")]){const o=l(e,"Contents","Info.plist");if(!t(o))continue;const n=/<key>CFBundleShortVersionString<\/key>\s*<string>([^<]+)<\/string>/.exec(r(o,"utf-8")),s=n?Ue.exec(n[1])?.[0]:void 0;if(s)return s}return null}if("win32"===process.platform){const e=l(process.env.LOCALAPPDATA||l(C(),"AppData","Local"),"AnthropicClaude");if(t(e)){const t=n(e).map(e=>/^app-(\d+\.\d+\.\d+)$/.exec(e)?.[1]).filter(e=>!!e);if(t.length>0)return Ke(t)}const o=j.map(e=>`'${e}'`).join(",");return Ke(c("powershell.exe",["-NoProfile","-Command",`Get-AppxPackage | Where-Object { @(${o}) -contains $_.PackageFamilyName } | ForEach-Object { $_.Version.ToString() }`],{encoding:"utf-8",timeout:15e3,windowsHide:!0,stdio:["ignore","pipe","ignore"],env:V()}).split(/\r?\n/).flatMap(e=>Ue.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 Ue.exec(e)?.[0]??null}catch{return null}return null}const Fe="darwin"===process.platform?"open -a Claude":"win32"===process.platform?"Claude":"claude-desktop",Be="darwin"!==process.platform&&"win32"!==process.platform||!k().installMirror?.claudeDesktop?"https://claude.ai/download":b(k().installMirror.claudeDesktop),He="darwin"===process.platform?`open ${Be}`:"win32"===process.platform?`start ${Be}`:`xdg-open ${Be}`;export const claudeDesktopAdapter={name:"claude-desktop",displayName:"Claude Desktop",command:Fe,installCommand:He,configPath:Z(),sessions:{format:H,files:()=>J(l(claudeDesktopUserDataDir(),"local-agent-mode-sessions"))},isInstalled:Ne,installedVersion:Re,prepareRuntime:async function(){if(!["win32","darwin","linux"].includes(process.platform)||!Ne())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?Re():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:v()?{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 Re()?"MSIX":null}catch(e){return p.logError("claude-desktop.installedPath",e),null}},install:e=>T(e)},wantsModelCatalog:!0,loadPrivateConfig(e){const t=oe()??{appliedId:"",entries:[]};let o=ne(t);o||(o={id:a(),name:W},t.entries.push(o));const n=pe(e);K(String(n.inferenceGatewayBaseUrl)),ae=!0===n.disableDeploymentModeChooser,le={models:n.inferenceModels,source:e.catalog?e.catalog.oneMillionSource:"slots",groups:e.catalog?.matchedGroups??[]};const r=ee(Y(o.id))??{};te(Y(o.id),{..._e(r),...n});const s=Le();$e=s&&!e.takeOver?Te(s):null,$e||(t.appliedId=o.id),te(Z(),t);const i=ee(Q())??{};$e||"3p"===i.deploymentMode||te(Q(),{...i,deploymentMode:"3p"}),de=null,ue=null,ce=null,Ge=null;const l=!0===e.settings?.force_registry,c=Ee()?Me(be):null;if(Ee()&&"foreign"===Ie(c)&&!l)Ge=c?.get("inferenceGatewayBaseUrl")||be;else if(Ee()){const t=Me(be),o=Pe.filter(e=>t?.has(e)),r={...ke(e=>t?.has(e)??!1),...n},s=!0===e.settings?.force_registry,i=!s&&je();try{i?xe(Pe):Se(r),ce=i?"removed":"written"}catch(e){p.logError("claude-desktop.policy",e),de=e instanceof Error?e.message.trim():String(e),(o.length>0||s)&&(ue=i?{action:"remove",values:Object.fromEntries(o.map(e=>[e,null])),deleteKey:o.length===t.size}:{action:"write",values:r,deleteKey:!1})}}},pendingElevation(){const e=ue;return e?{prompt:y.t(`tools.claude_desktop.elevate_${e.action}`),run:()=>{if(!$(we,e.values,e.deleteKey))return!1;const t=Me(be),o="remove"===e.action?Object.keys(e.values).every(e=>!t?.has(e)):Object.keys(e.values).every(e=>t?.has(e));return o&&(ue=null,de=null),o}}:null},unloadPrivateConfig(){if(Ee()&&"ours"===Ie(Me(be)))try{xe(Pe)}catch(e){p.logError("claude-desktop.removePolicy",e)}const e=oe(),t=ne(e);if(!e||!t)return;D(Y(t.id)),s(Y(t.id),{force:!0});const o=e.entries.filter(e=>e.id!==t.id);0===o.length?(D(Z()),s(Z(),{force:!0})):te(Z(),{...e,entries:o,appliedId:e.appliedId===t.id?o[0].id:e.appliedId})},listedModels(){const e=oe(),t=ne(e);if(!t||e?.appliedId!==t.id)return null;const o=ee(Y(t.id))?.inferenceModels;return Array.isArray(o)?o.map(e=>String(e.name)):null},refreshModelMenu(e){const t=oe(),o=ne(t);if(!o||t?.appliedId!==o.id)return;const n=ee(Y(o.id));if(!n)return;const r=buildInferenceModels(e.models,e.catalog),s=JSON.stringify(n.inferenceModels)!==JSON.stringify(r),i={..._e(n),inferenceModels:r},l=JSON.stringify(i)!==JSON.stringify(n);ue=null;const a=Ee()?Me(be):null,c="foreign"===Ie(a)&&!0!==e.settings?.force_registry;if(!a?.has("inferenceModels")||c)return void(l&&te(Y(o.id),i));const d=Pe.filter(e=>a.has(e)),u=!0!==e.settings?.force_registry&&je();if(l&&te(Y(o.id),i),u||s)try{u?xe(Pe):Se({inferenceModels:r})}catch(e){throw p.logError("claude-desktop.refreshModelMenu registry",e),ue=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"))}},detectCurrentConfig(){try{if(Ee()){const e=Me(be)?.get("inferenceGatewayApiKey");if(e)return{apiKey:e}}const e=ne(oe());if(!e)return{apiKey:null};const t=ee(Y(e.id)),o=t?.inferenceGatewayApiKey;return{apiKey:"string"==typeof o&&o?o:null}}catch(e){return p.logError("claude-desktop.detectCurrentConfig",e),{apiKey:null}}},getConfig(){try{const e=oe(),t=ne(e);return{meta:e,applied:t?ee(Y(t.id)):null,desktop:ee(Q()),...Ee()?{policy:Object.fromEntries(Me(be)??[])}:{}}}catch(e){return p.logError("claude-desktop.getConfig",e),null}},clearPinnedModels(){let e=!1;Ee()&&Me(be)?.has("inferenceModels")&&(Oe(),ve(["delete",be,"/v","inferenceModels","/f"]),e=!0);const t=ne(oe()),o=t?ee(Y(t.id)):null;if(t&&o&&void 0!==o.inferenceModels){const{inferenceModels:n,...r}=o;te(Y(t.id),r),e=!0}return e?["inferenceModels"]:[]},applyNotes(){const e=[];if(le&&le.models.length>0){const{models:t,source:o,groups:n}=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_${o}`,{count:String(t.length),list:t.map(e=>`${e.labelOverride}${e.supports1m?" (1M)":""}`).join(", "),groups:n.join(" / ")})})}null!==ae&&e.push({kind:"detail",text:y.t(ae?"tools.claude_desktop.official_login_hidden":"tools.claude_desktop.official_login_shown")}),v()&&!M()||e.push({kind:"action",text:y.t("tools.claude_desktop.restart_hint")}),ue?(e.push({kind:"action",text:y.t(`tools.claude_desktop.policy_stale_${ue.action}`)}),e.push({kind:"detail",text:de??""})):de?(e.push({kind:"detail",text:y.t("tools.claude_desktop.registry_denied")}),e.push({kind:"detail",text:de})):Ee()&&ce&&e.push({kind:"detail",text:y.t(`tools.claude_desktop.registry_${ce}`,{key:be})}),$e&&e.push({kind:"action",text:y.t("tools.claude_desktop.not_switched",{current:$e})}),Ge&&e.push({kind:"action",text:y.t("tools.claude_desktop.foreign_policy",{key:be,url:Ge})});const t=detectManagedConfig();return t&&e.push({kind:"action",text:y.t("tools.claude_desktop.managed_conflict",{path:t})}),e},planNotes(){const e=[],t=Le();if(t&&e.push(y.t("tools.claude_desktop.plan_switch",{current:Te(t)})),Ee()){const t=Me(be);"foreign"===Ie(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=ne(oe());t&&e.push(Y(t.id))}catch{}return e},backupPaths(){const e=[Z(),Q()];Ee()&&e.push(l(claudeDesktopUserDataDir(),Ae));try{const t=ne(oe());t&&e.push(Y(t.id))}catch{}return e}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{spawnSync as e}from"child_process";import{existsSync as t,readFileSync as i}from"fs";import{join as
|
|
1
|
+
import{spawnSync as e}from"child_process";import{existsSync as t,readFileSync as i}from"fs";import{join as s}from"path";import{logger as n}from"../../utils/logger.js";import{configManager as o}from"../config.js";import{toolHome as l}from"./types.js";import{brandEnv as r,brand as a}from"../brand.js";import{track as d}from"../telemetry.js";export const PLUGIN_SOURCES=[...a().pluginMarketplaces,{name:"claude-plugins-official",add:"anthropics/claude-plugins-official",probe:"https://github.com/anthropics/claude-plugins-official.git"}];export const OFFICIAL_PLUGINS=["code-review","feature-dev","frontend-design","pr-review-toolkit","commit-commands","security-guidance","code-simplifier","skill-creator","claude-md-management","claude-code-setup"];const c="official_plugins_offered",p="official_plugins_failed_at",u=12e4;export const PLUGIN_ROUND_LIMIT_MS=24e4;export const PLUGIN_RETRY_AFTER_MS=864e5;let f=(t,i,o=12e4)=>{const a=e(t,i,{env:r("TEST_HOME")?{...process.env,CLAUDE_CONFIG_DIR:s(l(),".claude")}:process.env,encoding:"utf-8",timeout:o,windowsHide:!0,stdio:["ignore","pipe","pipe"],shell:"win32"===process.platform&&/\.cmd$/i.test(t)});return 0!==a.status&&n.logError(`claude ${i.join(" ")}`,new Error(`${a.stderr??""}${a.stdout??""}`.trim())),0===a.status},m=t=>0===e("git",["ls-remote","--heads",t],{timeout:8e3,windowsHide:!0,stdio:"ignore"}).status;export function setClaudePluginRunnerForTests(e){f=e}export function setPluginSourceProbeForTests(e){m=e}function g(e,t){try{o.setMachineSetting("claude-code",e,t)}catch(t){n.logError(`claudePlugins.saveMark(${e})`,t)}}export function installOfficialPlugins(n,a={}){if("1"===r("SKIP_CLAUDE_PLUGINS"))return{installed:[],failed:[],skipped:"disabled"};const h=a.now??Date.now,_=new Set(o.machineSettingValues("claude-code",c).flatMap(e=>"string"==typeof e?e.split(",").filter(Boolean):[])),k=function(){try{const e=JSON.parse(i(s(l(),".claude","plugins","installed_plugins.json"),"utf-8"));return new Set(Object.keys(e.plugins??{}).map(e=>e.replace(/@[^@]*$/,"")))}catch{return new Set}}(),S=e=>k.has(e),I=OFFICIAL_PLUGINS.filter(e=>!_.has(e)&&!S(e));if(0===I.length)return{installed:[],failed:[],skipped:null};const w=o.getMachineSetting("claude-code",p),L="number"==typeof w&&w>0?h()-w:1/0;if(!a.retry&&L>=0&&L<864e5)return{installed:[],failed:[],skipped:"recent_failure"};const P=h(),U=(e,t)=>(e.failed.length>0||"marketplace"===e.skipped?g(p,h()):e.skipped||"number"!=typeof w||0===w||g(p,0),d("plugins",e.skipped?"skip":e.failed.length>0?"fail":"ok",{duration_ms:h()-P,detail:{installed:e.installed.length,failed:e.failed.length,...t?{reason:t}:{},...e.source?{source:e.source}:{}}}),e);if("darwin"===process.platform&&0!==e("xcode-select",["-p"],{stdio:"ignore"}).status&&!["/opt/homebrew/bin/git","/usr/local/bin/git"].some(e=>t(e))||0!==e("git",["--version"],{timeout:8e3,windowsHide:!0,stdio:"ignore"}).status)return U({installed:[],failed:[],skipped:"git"},"git");const b=PLUGIN_SOURCES.find(e=>m(e.probe));if(!b)return U({installed:[],failed:[],skipped:"marketplace"},"marketplace");const M=()=>24e4-(h()-P);f(n,["plugin","marketplace","add",b.add],Math.min(u,Math.max(M(),1)));const E={installed:[],failed:[],skipped:null,source:b.name};let N=!1;for(const e of I){const t=M();t<=0?(N=!0,E.failed.push(e)):f(n,["plugin","install",`${e}@${b.name}`],Math.min(u,t))?(E.installed.push(e),_.add(e)):E.failed.push(e)}for(const e of OFFICIAL_PLUGINS)S(e)&&_.add(e);return g(c,[..._].join(",")),U(E,N?"time_limit":E.failed.length>0?"install_failed":void 0)}
|
package/dist/lib/tools/codex.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash as e}from"crypto";import{existsSync as t,mkdirSync as o,readdirSync as n,readFileSync as r,rmSync as i,statSync as s,writeFileSync as l}from"fs";import{join as d}from"path";import*as a from"@iarna/toml";import{logger as c}from"../../utils/logger.js";import{i18n as u}from"../i18n.js";import{backupBeforeWrite as p,atomicWriteFile as m}from"./backup.js";import{codexHome as f,pickModel as _,toolHome as g,withV1 as x}from"./types.js";import{moveSessionsToProvider as h,NO_STATE_DB as y,runningCodexPids as k}from"../codex-sessions.js";import{codexFormat as b,codexRolloutFiles as v}from"../sessions/formats.js";import{getGatewayModelRules as w,getToolDefaultModel as j}from"../model-registry.js";import{ownsValue as S,takeField as C}from"../written-values.js";import{configManager as O}from"../config.js";import{maskHome as M,track as A}from"../telemetry.js";import{buildCodexCatalog as E,catalogRejections as P,codexCatalogPath as N,fillFromOlderEntries as T,installedCodexBinaries as D,loadBundledCodexModels as $,loadPreviousCodexModels as I,previousGatewayModelIds as L}from"./codex-catalog.js";import{gatewayModelSpecs as J,modelFamily as G}from"../gateway-models.js";import{isOurGatewayUrl as R,noteWrittenGatewayUrl as K}from"../gateway-addresses.js";import{findInstalls as X,mirrorInstallCommand as B,brandInstallScripts as U}from"./tool-installs.js";import{chatgptDesktopApp as W}from"./chatgpt-desktop.js";const q=()=>f(),z=()=>d(q(),"config.toml"),Y="sessions_move_declined",F=["browser_use","browser_use_external","computer_use"],H="desktop_features_restored";function Q(e){if(!0===O.getToolSetting("codex",H))return!1;const t=e.features,o=ae(t)&&F.every(e=>!1===t[e]);if(O.setToolSetting("codex",H,!0),!o)return!1;for(const e of F)delete t[e];return!0}export function codexWorkModeOn(){try{const e=ue();return e.model_provider===te&&ae(e.desktop)&&"STEPS_PROSE"===e.desktop.conversationDetailMode}catch{return!1}}function V(){try{if(ae(ue().desktop))return!0}catch{}if("darwin"===process.platform)return["/Applications",d(g(),"Applications")].some(e=>["ChatGPT.app","Codex.app"].some(o=>t(d(e,o))));if("win32"===process.platform){const e=d(process.env.LOCALAPPDATA||d(g(),"AppData","Local"),"Packages");try{return n(e).some(e=>/^OpenAI\.(Codex|ChatGPT)/i.test(e))}catch{return!1}}return t("/usr/lib/chatgpt/ChatGPT")}export function codexConfigPath(){return z()}const Z=()=>d(q(),"auth.json"),ee="OPENAI_API_KEY",te="custom",oe="high",ne=["gpt-5.5","gpt-5.6-sol","gpt-6-astra"],re=["high","xhigh"],ie={goals:!0,js_repl:!1};let se=[];const le=1e6,de=9e5;export const CODEX_ONE_MILLION_CONTEXT_SETTING="one_million_context";function ae(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}function ce(e,t){return ae(e[t])||(e[t]={}),e[t]}function ue(){if(!t(z()))return{};const e=r(z(),"utf-8");if(!e.trim())return{};try{const t=a.parse(e);if(!ae(t))throw new Error("config.toml root must be a TOML table");return t}catch(e){throw new Error(`Existing ~/.codex/config.toml cannot be parsed; back it up and fix it first: ${e instanceof Error?e.message:String(e)}`)}}function pe(){if(!t(Z()))return{};try{const e=JSON.parse(r(Z(),"utf-8"));return ae(e)?e:{}}catch{return{}}}let me=null;function fe(e){const t=e.profiles;if(ae(t)){for(const[e,o]of Object.entries(t))ae(o)&&2===Object.keys(o).length&&o.model_provider===te&&o.model===e&&delete t[e];0===Object.keys(t).length&&delete e.profiles}}let _e=null;const ge=()=>d(O.getConfigDir(),"codex-catalog-check.json");function xe(e){const o=N();t(o)&&r(o,"utf-8")===e||(p(o),m(o,e))}function he(t,n){if(0===n.length)return[];const i=function(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")}(t,n);if(function(e){try{return JSON.parse(r(ge(),"utf-8")).signature===e}catch{return!1}}(i))return[];const d=P(N(),n);return 0===d.length&&function(e){try{o(O.getConfigDir(),{recursive:!0}),l(ge(),JSON.stringify({signature:e})+"\n")}catch(e){c.logError("codexAdapter.rememberAccepted",e)}}(i),d}function ye(e,t,o){const n=!1!==t.settings?.one_million_context;!function(e){e.model_context_window===le&&delete e.model_context_window,e.model_auto_compact_token_limit===de&&delete e.model_auto_compact_token_limit}(e);const r=()=>{e.model_catalog_json===N()&&delete e.model_catalog_json,n&&(e.model_context_window=le,e.model_auto_compact_token_limit=de)},s=$()??I();if(!s)return c.logError("codexAdapter.writeModelCatalog",new Error("no Codex binary found; model catalog skipped")),_e="skipped",void r();const l=t.catalog,d=e=>E({bundled:e,specs:J("codex",l?.clientModels,l?.clientPersonal),...l?.clientPersonal?.includes("codex")?{chosenGpt:(l.clientModels?.codex??[]).filter(e=>!e.hidden).map(e=>e.id)}:{},...l?{keyModels:l.models}:{},gatewayAvailable:l?.models??L(),oneMillion:n,selectedModel:o,..."gateway"===l?.oneMillionSource?{claudeOneMillion:l.oneMillion}:{}}),a=e=>JSON.stringify(e,null,2)+"\n";let u=d(s);xe(a(u));const p=D(),m=he(a(u),p);if(m.length>0){const e=Date.now();let t=!1;for(const e of m){const o=$(e.bin);if(o){for(const e of[{models:T(u.models,o)},{models:T(d(o).models,o)}])if(xe(a(e)),0===he(a(e),p).length){u=e,t=!0;break}if(t)break}}if(A("codex-catalog",t?"fallback":"fail",{duration_ms:Date.now()-e,error:m[0].error,detail:{rejected_by:m.map(e=>({version:e.version,path:M(e.bin)}))}}),!t)return _e={rejectedBy:m[0]},i(N(),{force:!0}),void r()}_e={listed:u.models.filter(e=>"list"===e.visibility).map(e=>({id:String(e.slug),name:String(e.display_name??e.slug)}))},e.model_catalog_json=N()}export function codexCatalogRejection(){let e;try{e=ue()}catch{return null}return e.model_catalog_json===N()&&t(N())?P(N())[0]??null:null}export function setCodexOneMillionContext(e,t){const o=ue(),n=a.stringify(o),r="string"==typeof o.model?o.model:j("codex");ye(o,{settings:{[CODEX_ONE_MILLION_CONTEXT_SETTING]:e},catalog:t},r);const i=a.stringify(o);i!==n&&(p(z()),m(z(),i))}const ke={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:U("codex"),brew:"codex"};function be(e){const t=ae(e.model_providers)?e.model_providers[te]:void 0;if(!ae(t))return null;const o="string"==typeof t.base_url?t.base_url.trim():"";return o&&!R(o)?o:null}let ve=null;function we(){if("skipped"===_e)return 0===X(ke).length?[]:[{kind:"action",text:u.t("tools.codex.catalog_skipped")}];if(!_e)return[];if("rejectedBy"in _e){const{bin:e,version:t}=_e.rejectedBy;return[{kind:"action",text:u.t("tools.codex.catalog_rejected",{path:e,version:t??"?"})}]}const e=new Map;for(const t of _e.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=>`${u.t(`tools.model_family.${t}`)} ${e.get(t)}`).join(" · ");return[{kind:"summary",text:u.t("tools.codex.catalog_written",{count:String(_e.listed.length),breakdown:t})},{kind:"detail",text:_e.listed.map(e=>e.name).join(", ")},...codexWorkModeOn()||V()?[{kind:"action",text:u.t(codexWorkModeOn()?"tools.codex.work_mode_on":"tools.codex.work_mode_hint")}]:[]]}export const codexAdapter={name:"codex",companionApps:[W],displayName:"Codex",command:"codex",installCommand:B(ke),installSpec:ke,configPath:z(),sessions:{format:b,files:()=>[...v(d(f(),"sessions")),...v(d(f(),"archived_sessions"))],resumeCommand:e=>({command:"codex",args:["resume",e]})},wantsModelCatalog:!0,listedModels(){if(ue().model_catalog_json!==N())return null;try{return(JSON.parse(r(N(),"utf-8")).models??[]).filter(e=>"list"===e.visibility).map(e=>String(e.slug))}catch{return null}},refreshModelMenu(e){if(ue().model_catalog_json!==N())return;setCodexOneMillionContext(!1!==e.settings?.one_million_context,e.catalog);const t=ue(),o=function(e,t){const o=ae(e.model_providers)?e.model_providers[te]:void 0;return!(!ae(o)||o.base_url!==t||!0===o.supports_standalone_web_search||(o.supports_standalone_web_search=!0,0))}(t,x(e.baseUrl));(Q(t)||o)&&(p(z()),m(z(),a.stringify(t)))},async followUp(){if(ue().model_provider!==te)return null;const e=await h(te,{dryRun:!0}),t=Math.max(e.moved.length,e.dbRows);if(0===t)return null;const o=O.getToolSettings("codex")[Y];if("number"==typeof o&&t<=o)return null;const n={count:String(t)};return k().length>0?{hint:u.t("tools.codex.sessions_hidden_running",n)}:{prompt:u.t("tools.codex.sessions_offer",n),hint:u.t("tools.codex.sessions_hidden",n),async run(){const e=await h(te),t=[...new Set(e.moved.map(e=>e.from))].join("、")||"-",o=String(Math.max(e.moved.length,e.dbRows)),n=[{kind:"summary",text:u.t("codex_sessions.moved",{count:o,from:t,target:te})},{kind:"summary",text:u.t("codex_sessions.backup",{dir:e.backupDir??""})}];return e.dbSkipped&&e.dbSkipped!==y&&n.push({kind:"action",text:u.t("codex_sessions.db_skipped",{reason:e.dbSkipped})}),n},decline(){O.setToolSetting("codex",Y,t)}}},applyNotes(){const e=[];return ve&&e.push({kind:"summary",text:u.t("tools.codex.provider_replaced",{url:ve})}),se.length>0&&e.push({kind:"summary",text:u.t("tools.codex.replaced_user_settings",{values:se.join(", ")})}),[...e,...we()]},planNotes(){let e;try{e=ue()}catch{return[]}const t=[],o=be(e);return o?t.push(u.t("tools.codex.plan_replace_provider",{url:o})):"string"==typeof e.model_provider&&e.model_provider!==te&&t.push(u.t("tools.codex.plan_switch_provider",{provider:e.model_provider})),t},loadPrivateConfig(e){const t=j("codex"),o=_(e.models,t),n=function(e){return/(?:^|\/)claude(?:-|$)/i.test(e)}(o)?t:o,r=x(e.baseUrl),i=ue();se=[];const s=w().retired,l=(e,t,o,n,r)=>{void 0===t||t===o||"string"==typeof t&&s.includes(t)||S(e,t,n)||se.push(`${r} = ${String(t)}`),C(e,o)};l("codex.model",i.model,n,ne,"model"),i.model=n,i.model_provider=te,l("codex.model_reasoning_effort",i.model_reasoning_effort,oe,re,"model_reasoning_effort"),i.model_reasoning_effort=oe;const d="string"==typeof i.model?i.model:n;ye(i,e,d);const c=ce(i,"model_providers");ve=be(i),K(r);const u=ae(c[te])?{...c[te]}:{};delete u.env_key;const{experimental_bearer_token:f,...g}=u;c[te]={...g,name:"custom",wire_api:"responses",requires_openai_auth:!0,supports_standalone_web_search:!0,base_url:r},fe(i),ce(ce(i,"tui"),"model_availability_nux")[d]=4;const h=ce(i,"features");for(const[e,t]of Object.entries(ie))l(`codex.features.${e}`,void 0===h[e]?void 0:String(h[e]),String(t),[String(t)],`features.${e}`),h[e]=t;Q(i),p(z()),m(z(),a.stringify(i)),function(e){const t=e.trim();if(!t)return;const o={...pe(),auth_mode:"apikey",[ee]:t};p(Z()),m(Z(),JSON.stringify(o,null,2)+"\n",384)}(e.apiKey)},holdsOurConfig(e){const t=pe()[ee];return"string"==typeof t&&e.includes(t.trim())},unloadPrivateConfig(e){if(me=function(e){const t=pe(),o="string"==typeof t[ee]?t[ee].trim():"";if(!o)return ae(t.tokens)?"chatgpt":null;if(!e.includes(o))return"other_key";const{[ee]:n,auth_mode:r,...s}=t;return p(Z()),ae(s.tokens)?(m(Z(),JSON.stringify({...s,auth_mode:"chatgpt"},null,2)+"\n",384),"chatgpt"):(i(Z(),{force:!0}),"signed_out")}(e?.savedKeys??[]),!t(z()))return;let o;try{o=ue()}catch(e){return void c.logError("codexAdapter.unloadPrivateConfig",e)}const n=o.model_providers;ae(n)&&ae(n[te])&&R(n[te].base_url)&&ae(n)&&(delete n[te],0===Object.keys(n).length&&delete o.model_providers,o.model_provider===te&&delete o.model_provider),o.model_catalog_json===N()&&delete o.model_catalog_json,Q(o),fe(o),p(z()),m(z(),a.stringify(o))},unloadNotes(){switch(me){case"chatgpt":return[{kind:"action",text:u.t("tools.codex.unload_chatgpt_restored")}];case"other_key":return[{kind:"action",text:u.t("tools.codex.unload_other_key")}];default:return[{kind:"action",text:u.t("tools.codex.unload_sign_in")}]}},detectCurrentConfig(){const e=pe()[ee];return{apiKey:"string"==typeof e&&e.trim()?e.trim():null}},getConfig(){try{return ue()}catch(e){return c.logError("codexAdapter.getConfig",e),null}},backupPaths:()=>[z(),Z(),N()]};export function codexAuthProblem(){try{const e=ue(),t=e.model_providers?.[te];if(e.model_provider!==te||!t)return null;if("string"==typeof t.experimental_bearer_token&&t.experimental_bearer_token)return"stale_bearer";const o=pe();return!0===t.requires_openai_auth&&"chatgpt"===o.auth_mode?"chatgpt_login":null}catch{return null}}
|
|
1
|
+
import{createHash as e}from"crypto";import{existsSync as t,readdirSync as o,readFileSync as n,rmSync as r,statSync as i}from"fs";import{join as s}from"path";import*as c from"@iarna/toml";import{logger as d}from"../../utils/logger.js";import{i18n as l}from"../i18n.js";import{backupBeforeWrite as a,atomicWriteFile as u}from"./backup.js";import{codexHome as p,pickModel as m,toolHome as f,withV1 as _}from"./types.js";import{moveSessionsToProvider as g,NO_STATE_DB as x,runningCodexPids as h,SessionMoveError as y}from"../codex-sessions.js";import{codexFormat as k,codexRolloutFiles as b}from"../sessions/formats.js";import{getGatewayModelRules as v,getToolDefaultModel as w}from"../model-registry.js";import{ownsValue as j,recordAfterWrite as S,takeField as C}from"../written-values.js";import{configManager as M}from"../config.js";import{maskHome as O,track as A}from"../telemetry.js";import{buildCodexCatalog as E,catalogRejections as P,codexCatalogPath as N,fillFromOlderEntries as D,installedCodexBinaries as T,loadBundledCodexModels as $,loadPreviousCodexModels as I,previousGatewayModelIds as L}from"./codex-catalog.js";import{gatewayModelSpecs as J,modelFamily as R}from"../gateway-models.js";import{isOurGatewayUrl as G,noteWrittenGatewayUrl as B}from"../gateway-addresses.js";import{findInstalls as K,mirrorInstallCommand as U,brandInstallScripts as X}from"./tool-installs.js";import{chatgptDesktopApp as W}from"./chatgpt-desktop.js";const q=()=>p(),z=()=>s(q(),"config.toml"),F="sessions_move_declined",Y=["browser_use","browser_use_external","computer_use"],H="desktop_features_restored";function Q(e){if(!0===M.getMachineSetting("codex",H))return!1;const t=e.features;if(!ae(t)||!Y.every(e=>!1===t[e]))return!1;for(const e of Y)delete t[e];return!0}function V(){try{M.setMachineSetting("codex",H,!0)}catch(e){d.logError("codexAdapter.noteFeaturesRestored",e)}}export function forgetDeclinedSessions(){try{const e=M.getMachineSetting("codex",F);"number"==typeof e&&0!==e&&M.setMachineSetting("codex",F,0)}catch(e){d.logError("codexAdapter.forgetDeclinedSessions",e)}}export function codexWorkModeOn(){try{const e=pe();return e.model_provider===oe&&ae(e.desktop)&&"STEPS_PROSE"===e.desktop.conversationDetailMode}catch{return!1}}function Z(){try{if(ae(pe().desktop))return!0}catch{}if("darwin"===process.platform)return["/Applications",s(f(),"Applications")].some(e=>["ChatGPT.app","Codex.app"].some(o=>t(s(e,o))));if("win32"===process.platform){const e=s(process.env.LOCALAPPDATA||s(f(),"AppData","Local"),"Packages");try{return o(e).some(e=>/^OpenAI\.(Codex|ChatGPT)/i.test(e))}catch{return!1}}return t("/usr/lib/chatgpt/ChatGPT")}export function codexConfigPath(){return z()}const ee=()=>s(q(),"auth.json"),te="OPENAI_API_KEY",oe="custom",ne="high",re=["gpt-5.5","gpt-5.6-sol","gpt-6-astra"],ie=["high","xhigh"],se={goals:!0,js_repl:!1};let ce=[];const de=1e6,le=9e5;export const CODEX_ONE_MILLION_CONTEXT_SETTING="one_million_context";function ae(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}function ue(e,t){return ae(e[t])||(e[t]={}),e[t]}function pe(){if(!t(z()))return{};const e=n(z(),"utf-8");if(!e.trim())return{};try{const t=c.parse(e);if(!ae(t))throw new Error("config.toml root must be a TOML table");return t}catch(e){throw new Error(`Existing ~/.codex/config.toml cannot be parsed; back it up and fix it first: ${e instanceof Error?e.message:String(e)}`)}}function me(){if(!t(ee()))return{};try{const e=JSON.parse(n(ee(),"utf-8"));return ae(e)?e:{}}catch{return{}}}let fe=null;function _e(e){const t=e.profiles;if(ae(t)){for(const[e,o]of Object.entries(t))ae(o)&&2===Object.keys(o).length&&o.model_provider===oe&&o.model===e&&delete t[e];0===Object.keys(t).length&&delete e.profiles}}let ge=null;const xe=()=>s(M.getConfigDir(),"codex-catalog-check.json");function he(t,o){const n=e("sha256").update(t);for(const e of o)try{const t=i(e);n.update(`\0${e}\0${t.size}\0${t.mtimeMs}`)}catch{n.update(`\0${e}`)}return n.digest("hex")}function ye(){try{const e=JSON.parse(n(xe(),"utf-8"));return e&&"object"==typeof e?e:{}}catch{return{}}}function ke(e){try{u(xe(),JSON.stringify(e)+"\n")}catch(e){d.logError("codexAdapter.writeCheckState",e)}}function be(e){ke({wanted:he("",e)})}function ve(){const e=ye();void 0!==e.wanted&&(delete e.wanted,ke(e))}function we(){const e=ye().wanted;return void 0!==e&&e!==he("",T())}function je(e){const o=N();t(o)&&n(o,"utf-8")===e||(a(o),u(o,e))}function Se(e,t){if(0===t.length)return[];const o=he(e,t);if(function(e){return ye().signature===e}(o))return[];const n=P(N(),t);return 0===n.length&&function(e){ke({signature:e})}(o),n}function Ce(e,t,o){const n=!1!==t.settings?.one_million_context;!function(e){e.model_context_window===de&&delete e.model_context_window,e.model_auto_compact_token_limit===le&&delete e.model_auto_compact_token_limit}(e);const i=()=>{e.model_catalog_json===N()&&delete e.model_catalog_json,n&&(e.model_context_window=de,e.model_auto_compact_token_limit=le)},s=$()??I();if(!s)return d.logError("codexAdapter.writeModelCatalog",new Error("no Codex binary found; model catalog skipped")),ge="skipped",A("codex-catalog","skip",{detail:{reason:"no_codex_binary"}}),be(T()),void i();const c=t.catalog,l=e=>E({bundled:e,specs:J("codex",c?.clientModels,c?.clientPersonal),...c?.clientPersonal?.includes("codex")?{chosenGpt:(c.clientModels?.codex??[]).filter(e=>!e.hidden).map(e=>e.id)}:{},...c?{keyModels:c.models}:{},gatewayAvailable:c?.models??L(),oneMillion:n,selectedModel:o,..."gateway"===c?.oneMillionSource?{claudeOneMillion:c.oneMillion}:{}}),a=e=>JSON.stringify(e,null,2)+"\n";let u=l(s);je(a(u));const p=T(),m=Se(a(u),p);if(m.length>0){const e=Date.now();let t=!1;for(const e of m){const o=$(e.bin);if(o){for(const e of[{models:D(u.models,o)},{models:D(l(o).models,o)}])if(je(a(e)),0===Se(a(e),p).length){u=e,t=!0;break}if(t)break}}if(A("codex-catalog",t?"fallback":"fail",{duration_ms:Date.now()-e,error:m[0].error,detail:{rejected_by:m.map(e=>({version:e.version,path:O(e.bin)}))}}),!t)return ge={rejectedBy:m[0]},r(N(),{force:!0}),be(p),void i()}ge={listed:u.models.filter(e=>"list"===e.visibility).map(e=>({id:String(e.slug),name:String(e.display_name??e.slug)}))},e.model_catalog_json=N(),ve()}export function codexCatalogRejection(){let e;try{e=pe()}catch{return null}return e.model_catalog_json===N()&&t(N())?P(N())[0]??null:null}export function setCodexOneMillionContext(e,t){const o=pe(),n=c.stringify(o),r="string"==typeof o.model?o.model:w("codex");Ce(o,{settings:{[CODEX_ONE_MILLION_CONTEXT_SETTING]:e},catalog:t},r);const i=c.stringify(o);i!==n&&(a(z()),u(z(),i))}const Me={command:"codex",npmPackage:"@openai/codex",native:{binDir:"win32"===process.platform?["AppData","Local","Programs","OpenAI","Codex","bin"]:[".local","bin"],updateArgs:["update"],updateTimeoutMs:12e4,dataDirs:[[".codex","packages","standalone"]]},mirrorScript:X("codex"),brew:"codex"};function Oe(e){const t=ae(e.model_providers)?e.model_providers[oe]:void 0;if(!ae(t))return null;const o="string"==typeof t.base_url?t.base_url.trim():"";return o&&!G(o)?o:null}let Ae=null;function Ee(){if("skipped"===ge)return 0===K(Me).length?[]:[{kind:"action",text:l.t("tools.codex.catalog_skipped")}];if(!ge)return[];if("rejectedBy"in ge){const{bin:e,version:t}=ge.rejectedBy;return[{kind:"action",text:l.t("tools.codex.catalog_rejected",{path:e,version:t??"?"})}]}const e=new Map;for(const t of ge.listed)e.set(R(t.id),(e.get(R(t.id))??0)+1);const t=["gpt","claude","gemini","other","grok"].filter(t=>e.has(t)).map(t=>`${l.t(`tools.model_family.${t}`)} ${e.get(t)}`).join(" · ");return[{kind:"summary",text:l.t("tools.codex.catalog_written",{count:String(ge.listed.length),breakdown:t})},{kind:"detail",text:ge.listed.map(e=>e.name).join(", ")},...codexWorkModeOn()||Z()?[{kind:"action",text:l.t(codexWorkModeOn()?"tools.codex.work_mode_on":"tools.codex.work_mode_hint")}]:[]]}export const codexAdapter={name:"codex",companionApps:[W],displayName:"Codex",command:"codex",installCommand:U(Me),installSpec:Me,configPath:z(),sessions:{format:k,files:()=>[...b(s(p(),"sessions")),...b(s(p(),"archived_sessions"))],resumeCommand:e=>({command:"codex",args:["resume",e]})},wantsModelCatalog:!0,listedModels(){const e=pe();if(e.model_catalog_json!==N())return e.model_provider===oe&&we()?[]:null;try{return(JSON.parse(n(N(),"utf-8")).models??[]).filter(e=>"list"===e.visibility).map(e=>String(e.slug))}catch{return null}},refreshModelMenu(e){const t=pe();if(t.model_catalog_json!==N()&&(t.model_provider!==oe||!we()))return;setCodexOneMillionContext(!1!==e.settings?.one_million_context,e.catalog);const o=pe(),n=function(e,t){const o=ae(e.model_providers)?e.model_providers[oe]:void 0;return!(!ae(o)||o.base_url!==t||!0===o.supports_standalone_web_search||(o.supports_standalone_web_search=!0,0))}(o,_(e.baseUrl));(Q(o)||n)&&(a(z()),u(z(),c.stringify(o))),V()},async followUp(){if(pe().model_provider!==oe)return null;const e=await g(oe,{dryRun:!0}),t=Math.max(e.moved.length,e.dbRows);if(0===t)return forgetDeclinedSessions(),null;const o=M.getMachineSetting("codex",F);if("number"==typeof o&&t<=o)return null;const n={count:String(t)};return h().length>0?{hint:l.t("tools.codex.sessions_hidden_running",n)}:{prompt:l.t("tools.codex.sessions_offer",n),hint:l.t("tools.codex.sessions_hidden",n),async run(){if(h().length>0)return[{kind:"action",text:l.t("tools.codex.sessions_hidden_running",n)}];let e;try{e=await g(oe)}catch(e){d.logError("codexAdapter.followUp.run",e);const o=e instanceof y?e.backupDir:null;A("codex-sessions","fail",{error:e,detail:{count:t,backup:Boolean(o)}});const n=O(e instanceof Error?e.message:String(e)).replace(/\s+/g," ").trim();return[{kind:"action",text:l.t("codex_sessions.move_failed",{reason:n})},...o?[{kind:"action",text:l.t("codex_sessions.move_failed_undo",{dir:o})}]:[]]}forgetDeclinedSessions(),A("codex-sessions","ok",{detail:{files:e.moved.length,db_rows:e.dbRows}});const o=[...new Set(e.moved.map(e=>e.from))].join("、")||"-",r=String(Math.max(e.moved.length,e.dbRows)),i=[{kind:"summary",text:l.t("codex_sessions.moved",{count:r,from:o,target:oe})},{kind:"summary",text:l.t("codex_sessions.backup",{dir:e.backupDir??""})}];return e.dbSkipped&&e.dbSkipped!==x&&i.push({kind:"action",text:l.t("codex_sessions.db_skipped",{reason:e.dbSkipped})}),i},decline(){M.setMachineSetting("codex",F,t)}}},applyNotes(){const e=[];return Ae&&e.push({kind:"summary",text:l.t("tools.codex.provider_replaced",{url:Ae})}),ce.length>0&&e.push({kind:"summary",text:l.t("tools.codex.replaced_user_settings",{values:ce.join(", ")})}),[...e,...Ee()]},planNotes(){let e;try{e=pe()}catch{return[]}const t=[],o=Oe(e);return o?t.push(l.t("tools.codex.plan_replace_provider",{url:o})):"string"==typeof e.model_provider&&e.model_provider!==oe&&t.push(l.t("tools.codex.plan_switch_provider",{provider:e.model_provider})),t},loadPrivateConfig(e){S(()=>{const t=w("codex"),o=m(e.models,t),n=function(e){return/(?:^|\/)claude(?:-|$)/i.test(e)}(o)?t:o,r=_(e.baseUrl),i=pe();ce=[];const s=v().retired,d=(e,t,o,n,r)=>{void 0===t||t===o||"string"==typeof t&&s.includes(t)||j(e,t,n)||ce.push(`${r} = ${String(t)}`),C(e,o)};d("codex.model",i.model,n,re,"model"),i.model=n,i.model_provider=oe,d("codex.model_reasoning_effort",i.model_reasoning_effort,ne,ie,"model_reasoning_effort"),i.model_reasoning_effort=ne;const l="string"==typeof i.model?i.model:n;Ce(i,e,l);const p=ue(i,"model_providers");Ae=Oe(i),B(r);const f=ae(p[oe])?{...p[oe]}:{};delete f.env_key;const{experimental_bearer_token:g,...x}=f;p[oe]={...x,name:"custom",wire_api:"responses",requires_openai_auth:!0,supports_standalone_web_search:!0,base_url:r},_e(i),ue(ue(i,"tui"),"model_availability_nux")[l]=4;const h=ue(i,"features");for(const[e,t]of Object.entries(se))d(`codex.features.${e}`,void 0===h[e]?void 0:String(h[e]),String(t),[String(t)],`features.${e}`),h[e]=t;Q(i),a(z()),u(z(),c.stringify(i))}),V(),function(e){const t=e.trim();if(!t)return;const o={...me(),auth_mode:"apikey",[te]:t};a(ee()),u(ee(),JSON.stringify(o,null,2)+"\n",384)}(e.apiKey)},holdsOurConfig(e){const t=me()[te];return"string"==typeof t&&e.includes(t.trim())},unloadPrivateConfig(e){if(fe=function(e){const t=me(),o="string"==typeof t[te]?t[te].trim():"";if(!o)return ae(t.tokens)?"chatgpt":null;if(!e.includes(o))return"other_key";const{[te]:n,auth_mode:i,...s}=t;return a(ee()),ae(s.tokens)?(u(ee(),JSON.stringify({...s,auth_mode:"chatgpt"},null,2)+"\n",384),"chatgpt"):(r(ee(),{force:!0}),"signed_out")}(e?.savedKeys??[]),!t(z()))return;let o;try{o=pe()}catch(e){return void d.logError("codexAdapter.unloadPrivateConfig",e)}const n=o.model_providers;ae(n)&&ae(n[oe])&&G(n[oe].base_url)&&ae(n)&&(delete n[oe],0===Object.keys(n).length&&delete o.model_providers,o.model_provider===oe&&delete o.model_provider),o.model_catalog_json===N()&&delete o.model_catalog_json,Q(o),_e(o),a(z()),u(z(),c.stringify(o)),V(),ve()},unloadNotes(){switch(fe){case"chatgpt":return[{kind:"action",text:l.t("tools.codex.unload_chatgpt_restored")}];case"other_key":return[{kind:"action",text:l.t("tools.codex.unload_other_key")}];default:return[{kind:"action",text:l.t("tools.codex.unload_sign_in")}]}},detectCurrentConfig(){const e=me()[te];return{apiKey:"string"==typeof e&&e.trim()?e.trim():null}},getConfig(){try{return pe()}catch(e){return d.logError("codexAdapter.getConfig",e),null}},backupPaths:()=>[z(),ee(),N()]};export function codexAuthProblem(){try{const e=pe(),t=e.model_providers?.[oe];if(e.model_provider!==oe||!t)return null;if("string"==typeof t.experimental_bearer_token&&t.experimental_bearer_token)return"stale_bearer";const o=me();return!0===t.requires_openai_auth&&"chatgpt"===o.auth_mode?"chatgpt_login":null}catch{return null}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{spawnSync as t}from"child_process";import{createHash as e}from"crypto";import{accessSync as r,constants as o,copyFileSync as n,createReadStream as s,createWriteStream as i,existsSync as a,mkdirSync as c,mkdtempSync as l,readFileSync as p,renameSync as u,rmSync as d}from"fs";import{cpus as f,tmpdir as m}from"os";import{basename as g,dirname as h,join as w}from"path";import{Readable as S,Transform as A}from"stream";import{pipeline as x}from"stream/promises";import{logger as y}from"../../utils/logger.js";import{i18n as E}from"../i18n.js";import{powerShellEnv as $}from"../powershell-env.js";import{toolHome as v}from"./types.js";import{configManager as k}from"../config.js";import{brand as _}from"../brand.js";import{mirrorFileUrl as P,withDownloadFallback as I}from"../mirror-url.js";const b=(e,r,o={})=>{const n=t(e,r,{encoding:"utf-8",timeout:o.timeout??12e4,windowsHide:!0,input:o.input,stdio:[void 0===o.input?"ignore":"pipe","pipe","pipe"],maxBuffer:16777216,env:$()});return n.error&&y.logError(`desktop-app: ${e}`,n.error),{status:n.status,stdout:`${n.stdout??""}`,stderr:`${n.stderr??""}`}};let C=b,T=(...t)=>fetch(...t),M=null,j=null,F=null,R=null;export function setDesktopAppDepsForTests(t){void 0!==t.run&&(C=t.run??b),void 0!==t.fetch&&(T=t.fetch??((...t)=>fetch(...t))),void 0!==t.platform&&(M=t.platform),void 0!==t.arm64&&(j=t.arm64),void 0!==t.privileged&&(F=t.privileged),void 0!==t.remote&&(R=t.remote)}export function appPlatform(){return M??process.platform}export function isArm64Machine(){return null!==j?j:"arm64"===process.arch||("win32"===appPlatform()?"ARM64"===process.env.PROCESSOR_ARCHITECTURE||"ARM64"===process.env.PROCESSOR_ARCHITEW6432:"darwin"===appPlatform()&&/\bApple\b/.test(f()[0]?.model??""))}export class DesktopInstallError extends Error{key;constructor(t,e){super(t),this.name="DesktopInstallError",this.key=e}}export const fail=(t,e={})=>{const r={};for(const[t,o]of Object.entries(e))r[t]=o.trim()||E.t("app_update.reason_unknown");throw new DesktopInstallError(E.t(`app_update.error_${t}`,r),t)};export function parseSha256Sums(t){const e=new Map;for(const r of t.split(/\r?\n/)){const t=/^([0-9a-f]{64})\s+\*?(\S.*)$/i.exec(r.trim());t&&e.set(t[2].trim(),t[1].toLowerCase())}return e}async function O(t){const r=e("sha256");for await(const e of s(t))r.update(e);return r.digest("hex")}async function N(t,e){const r=await T(t,{signal:AbortSignal.timeout(e)});if(!r.ok)throw new Error(`${t}: HTTP ${r.status}`);return(await r.text()).trim()}function B(t,e){try{const r=p(w(t,"Contents","Info.plist"),"utf-8");return new RegExp(`<key>${e}</key>\\s*<string>([^<]*)</string>`).exec(r)?.[1]??null}catch{return null}}export function macBundleId(t){return B(t,"CFBundleIdentifier")}export function macAppVersion(t){return/^\d+\.\d+\.\d+/.exec(B(t,"CFBundleShortVersionString")??"")?.[0]??null}function D(t){try{return r(t,o.W_OK),!0}catch{return!1}}const H=t=>`'${t.replace(/'/g,"''")}'`;function W(t,e=12e4){return C("powershell.exe",["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command","[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; "+t],{timeout:e})}export function powerShellError(t){return t.replace(/#< CLIXML/g,"").replace(/_x000D__x000A_/g,"\n").replace(/<\/S>/g,"\n").replace(/<[^>]+>/g,"").replace(/_x[0-9A-F]{4}_/g,"").replace(/'/g,"'").replace(/"/g,'"').replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&").split(/\r?\n/).map(t=>t.trim()).find(t=>t&&!/^(At line|At char|所在位置|\+|~|CategoryInfo|FullyQualifiedErrorId)/i.test(t))??""}export function createDesktopAppInstaller(t){const e=()=>t.mirror()||null,r=()=>t.asset(appPlatform(),isArm64Machine()),o=()=>{const o=appPlatform();return"darwin"!==o&&"win32"!==o?"unsupported_platform":r()?e()?"darwin"===o&&(F??0===process.getuid?.())?"root":"win32"===o&&(null!==F?F:/\\system32\\config\\systemprofile/i.test(process.env.USERPROFILE??"")||!0===process.env.USERNAME?.endsWith("$"))?"system_account":"win32"===o&&(null!==R?R:Boolean(process.env.SSH_CONNECTION||process.env.SSH_CLIENT))?"remote_session":t.extraBlocker?.(o)??null:"no_mirror":"darwin"===o?"unsupported_arch":"unsupported_platform"},s=async(r=8e3)=>{const o=e();if(!o)throw new Error("no mirror");const n=t.versionFile(appPlatform(),isArm64Machine()),s=await N(P(o,n),r),i=/^(\d+\.\d+\.\d+)(\.\d+)?$/.exec(s)?.[1];if(!i)throw new Error(`unexpected ${n}: ${s.slice(0,40)}`);return i},f=()=>{for(const e of["/Applications",w(v(),"Applications")])for(const r of t.macApp.installedNames){const o=w(e,r);if(!a(w(o,"Contents","Info.plist")))continue;const n=macBundleId(o);if(null===n||n===t.macApp.bundleId)return o}return null},$=e=>{const r=C("codesign",["--verify","--deep","--strict",e],{timeout:6e5});0!==r.status&&fail("signature",{reason:(r.stderr||r.stdout).trim().split("\n")[0]||`codesign ${r.status}`});const o=C("codesign",["-dv",e]),n=`${o.stdout}\n${o.stderr}`,s=/^TeamIdentifier=(\S+)/m.exec(n)?.[1],i=/^Identifier=(\S+)/m.exec(n)?.[1];s===t.macApp.teamId&&i===t.macApp.bundleId||fail("signature",{reason:`TeamIdentifier=${s??"?"} Identifier=${i??"?"}`});const a=C("spctl",["-a","-t","exec","-vv",e],{timeout:3e5});0!==a.status&&fail("signature",{reason:(a.stderr||a.stdout).trim().split("\n")[0]||`spctl ${a.status}`})},b=()=>{const e=f();let r=e;if(!r){const e=D("/Applications")?"/Applications":w(v(),"Applications");r=w(e,t.macApp.installedNames[0])}const o=h(r);return(a(o)&&!D(o)||e&&!D(e))&&fail("no_permission",{path:r}),{target:r,existing:e}},M=e=>{const r=W(`$s = Get-AuthenticodeSignature -LiteralPath ${H(e)}; [pscustomobject]@{ status = [string]$s.Status; subject = [string]$s.SignerCertificate.Subject } | ConvertTo-Json -Compress`);let o={};try{o=JSON.parse(r.stdout.trim()||"{}")}catch{}if("Valid"!==o.status||!t.windows.signer.test(o.subject??"")){const t=o.status?`${o.status} ${o.subject??""}`:powerShellError(r.stderr)||powerShellError(r.stdout.trim().startsWith("{")?"":r.stdout)||`exit ${r.status}`;fail("signature",{reason:t.trim()})}},j=()=>{const e=W(`Get-AppxPackage | Where-Object { ${t.windows.packageFilter} } | ForEach-Object { $_.Version.ToString() }`,3e4);return/\d+\.\d+\.\d+/.exec(e.stdout)?.[0]??null};return{assetName:r,blocker:o,latestVersion:s,installedMacApp:f,windowsPackageVersion:j,verifyMacApp:$,verifyWindowsPackage:M,install:async(f={})=>{const v=o();v&&fail("blocked",{reason:E.t(`app_update.reason_${v}`)});const F=e(),R=r();let B;try{B=await s(15e3)}catch(t){fail("download",{reason:t instanceof Error?t.message:String(t)})}const D=e=>P(F,e,t.releaseTag?.(B)),V=_().installMirror?.downloadCounter;let L;try{L=parseSha256Sums(await I(D("SHA256SUMS"),V,t=>N(t,15e3))).get(R)}catch(e){y.logError(`${t.id}: SHA256SUMS`,e)}L||fail("no_checksum",{file:R}),"darwin"===appPlatform()&&b();const U=w(k.getConfigDir(),"downloads",t.id),G=w(U,R),J=l(w(m(),`${t.id}-`));let X=w(J,R),q=!1;try{a(G)&&await O(G)===L?(X=G,f.reusing?.(B)):(f.downloading?.(B),await I(D(R),V,t=>async function(t,e,r){let o;try{o=await T(t,{signal:AbortSignal.timeout(18e5)})}catch(t){fail("download",{reason:t instanceof Error?t.message:String(t)})}o.ok&&o.body||fail("download",{reason:`HTTP ${o.status}`});const n=Number(o.headers.get("content-length"))||0;let s=0,a=-1;const c=new A({transform(t,e,o){s+=t.length;const i=n?Math.floor(100*s/n):-1;i>=0&&i!==a&&(a=i,r?.(i)),o(null,t)}});try{await x(S.fromWeb(o.body),c,i(e))}catch(t){d(e,{force:!0}),fail("download",{reason:t instanceof Error?t.message:String(t)})}}(t,X,f.percent))),f.verifying?.();const e=await O(X);e!==L&&fail("checksum",{file:R,expected:L.slice(0,12),actual:e.slice(0,12)}),f.installing?.();const r="darwin"===appPlatform()?await(async(e,r)=>{const o=w(r,"mnt");c(o,{recursive:!0});const n=C("hdiutil",["attach","-nobrowse","-readonly","-noautoopen","-mountpoint",o,e],{timeout:3e5,input:"Y\n"});0!==n.status&&fail("mount",{reason:(n.stderr||n.stdout).trim().split("\n").pop()??""});let s=null;try{const e=w(o,t.macApp.source);a(e)||fail("bad_package",{reason:t.macApp.source});const{target:r,existing:n}=b(),i=h(r),l=g(r);c(i,{recursive:!0}),s=w(i,`.${l}.${process.pid}.new`),d(s,{recursive:!0,force:!0});const p=C("ditto",[e,s],{timeout:9e5});0!==p.status&&fail("copy",{reason:(p.stderr||p.stdout).trim().split("\n")[0]??""}),$(s);const f=macAppVersion(s);f||fail("bad_package",{reason:"Info.plist"});const m=w(i,`.${l}.${process.pid}.old`);try{n&&u(n,m)}catch(t){throw["EPERM","EACCES"].includes(t.code??"")&&fail("app_management",{path:n}),t}try{u(s,r)}catch(t){throw n&&u(m,n),t}return s=null,d(m,{recursive:!0,force:!0}),{version:f,location:r}}finally{s&&d(s,{recursive:!0,force:!0}),C("hdiutil",["detach",o,"-force"],{timeout:6e4})}})(X,J):await(async(t,e)=>{M(t);const r=W(`$ErrorActionPreference = 'Stop'; Add-AppxPackage -Path ${H(t)} -ForceApplicationShutdown`,9e5);if(0!==r.status){const o=powerShellError(r.stderr)||powerShellError(r.stdout)||`Add-AppxPackage ${r.status}`;/0x80073D28/i.test(`${r.stderr}\n${r.stdout}`)||fail("install",{reason:o}),await(e.elevate?.())||fail("needs_admin");const n=(t=>{const e=w(h(t),"elevated-install.log"),r=`$ErrorActionPreference = 'Stop'; try { Add-AppxPackage -Path ${H(t)} -ForceApplicationShutdown; exit 0 } catch { [IO.File]::WriteAllText(${H(e)}, $_.Exception.Message, [Text.Encoding]::UTF8); exit 1 }`,o=W(`$ErrorActionPreference = 'Stop'; $p = Start-Process -FilePath 'powershell.exe' -ArgumentList @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-EncodedCommand', '${Buffer.from(r,"utf16le").toString("base64")}') -Verb RunAs -Wait -PassThru -WindowStyle Hidden; exit $p.ExitCode`,12e5);if(0===o.status)return null;let n="";try{n=p(e,"utf-8").trim()}catch{}return n||powerShellError(o.stderr)||powerShellError(o.stdout)||`exit ${o.status}`})(t);n&&fail("install",{reason:n}),j()||fail("other_account")}const o=j();return o||fail("install",{reason:"Get-AppxPackage"}),{version:o,location:"MSIX"}})(X,f);return q=!0,r}catch(t){const e=t instanceof DesktopInstallError?t.key:void 0;throw X!==G&&a(X)&&!["checksum","signature","bad_package","mount"].includes(e??"")&&function(t,e,r){try{d(e,{recursive:!0,force:!0}),c(e,{recursive:!0});try{u(t,r)}catch{n(t,r)}}catch(t){y.logError("desktop-app: keep package",t),d(e,{recursive:!0,force:!0})}}(X,U,G),X===G&&["signature","bad_package","mount"].includes(e??"")&&d(U,{recursive:!0,force:!0}),t}finally{q&&d(U,{recursive:!0,force:!0}),d(J,{recursive:!0,force:!0})}}}}
|
|
1
|
+
import{spawnSync as t}from"child_process";import{createHash as e}from"crypto";import{accessSync as r,constants as o,copyFileSync as n,createReadStream as s,createWriteStream as i,existsSync as a,mkdirSync as c,mkdtempSync as l,readdirSync as p,readFileSync as u,renameSync as d,rmSync as f,statSync as m}from"fs";import{cpus as g,tmpdir as h}from"os";import{basename as w,dirname as $,join as y}from"path";import{Readable as S,Transform as A}from"stream";import{pipeline as x}from"stream/promises";import{logger as E}from"../../utils/logger.js";import{i18n as v}from"../i18n.js";import{powerShellEnv as k}from"../powershell-env.js";import{toolHome as P}from"./types.js";import{configManager as _}from"../config.js";import{brand as b}from"../brand.js";import{mirrorFileUrl as I,withDownloadFallback as C}from"../mirror-url.js";import{processAlive as T}from"../../utils/process-alive.js";const M=(e,r,o={})=>{const n=t(e,r,{encoding:"utf-8",timeout:o.timeout??12e4,windowsHide:!0,input:o.input,stdio:[void 0===o.input?"ignore":"pipe","pipe","pipe"],maxBuffer:16777216,env:k()});return n.error&&E.logError(`desktop-app: ${e}`,n.error),{status:n.status,stdout:`${n.stdout??""}`,stderr:`${n.stderr??""}`}};let j=M,R=(...t)=>fetch(...t),F=null,N=null,O=null,D=null;export function setDesktopAppDepsForTests(t){void 0!==t.run&&(j=t.run??M),void 0!==t.fetch&&(R=t.fetch??((...t)=>fetch(...t))),void 0!==t.platform&&(F=t.platform),void 0!==t.arm64&&(N=t.arm64),void 0!==t.privileged&&(O=t.privileged),void 0!==t.remote&&(D=t.remote)}export function appPlatform(){return F??process.platform}export function isArm64Machine(){return null!==N?N:"arm64"===process.arch||("win32"===appPlatform()?"ARM64"===process.env.PROCESSOR_ARCHITECTURE||"ARM64"===process.env.PROCESSOR_ARCHITEW6432:"darwin"===appPlatform()&&/\bApple\b/.test(g()[0]?.model??""))}export class DesktopInstallError extends Error{key;constructor(t,e){super(t),this.name="DesktopInstallError",this.key=e}}export const fail=(t,e={})=>{const r={};for(const[t,o]of Object.entries(e))r[t]=o.trim()||v.t("app_update.reason_unknown");throw new DesktopInstallError(v.t(`app_update.error_${t}`,r),t)};export function parseSha256Sums(t){const e=new Map;for(const r of t.split(/\r?\n/)){const t=/^([0-9a-f]{64})\s+\*?(\S.*)$/i.exec(r.trim());t&&e.set(t[2].trim(),t[1].toLowerCase())}return e}async function W(t){const r=e("sha256");for await(const e of s(t))r.update(e);return r.digest("hex")}async function B(t,e){const r=await R(t,{signal:AbortSignal.timeout(e)});if(!r.ok)throw new Error(`${t}: HTTP ${r.status}`);return(await r.text()).trim()}function H(t,e){try{const r=u(y(t,"Contents","Info.plist"),"utf-8");return new RegExp(`<key>${e}</key>\\s*<string>([^<]*)</string>`).exec(r)?.[1]??null}catch{return null}}export function macBundleId(t){return H(t,"CFBundleIdentifier")}export function macAppVersion(t){return/^\d+\.\d+\.\d+/.exec(H(t,"CFBundleShortVersionString")??"")?.[0]??null}function V(t){try{return r(t,o.W_OK),!0}catch{return!1}}const L=t=>`'${t.replace(/'/g,"''")}'`;function U(t,e=12e4){return j("powershell.exe",["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command","[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; "+t],{timeout:e})}export function powerShellError(t){return t.replace(/#< CLIXML/g,"").replace(/_x000D__x000A_/g,"\n").replace(/<\/S>/g,"\n").replace(/<[^>]+>/g,"").replace(/_x[0-9A-F]{4}_/g,"").replace(/'/g,"'").replace(/"/g,'"').replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&").split(/\r?\n/).map(t=>t.trim()).find(t=>t&&!/^(At line|At char|所在位置|\+|~|CategoryInfo|FullyQualifiedErrorId)/i.test(t))??""}export function createDesktopAppInstaller(t){const e=()=>t.mirror()||null,r=()=>t.asset(appPlatform(),isArm64Machine()),o=()=>["/Applications",y(P(),"Applications")],s=()=>{const e=[];for(const r of o()){let o;try{o=p(r)}catch{continue}for(const n of t.macApp.installedNames)for(const t of o){if(!t.startsWith(`.${n}.`))continue;const o=/^(\d+)\.(new|old)$/.exec(t.slice(n.length+2));o&&!T(Number(o[1]))&&e.push({path:y(r,t),target:y(r,n),kind:o[2]})}}return e},g=()=>{if("darwin"===appPlatform())for(const e of s())if("old"===e.kind&&!a(e.target)&&a(y(e.path,"Contents","Info.plist")))try{d(e.path,e.target),E.debug(`${t.id}: restored ${e.target} from an interrupted install`)}catch(e){E.logError(`${t.id}: restore interrupted install`,e)}},k=()=>{const o=appPlatform();return"darwin"!==o&&"win32"!==o?"unsupported_platform":r()?e()?"darwin"===o&&(O??0===process.getuid?.())?"root":"win32"===o&&(null!==O?O:/\\system32\\config\\systemprofile/i.test(process.env.USERPROFILE??"")||!0===process.env.USERNAME?.endsWith("$"))?"system_account":"win32"===o&&(null!==D?D:Boolean(process.env.SSH_CONNECTION||process.env.SSH_CLIENT))?"remote_session":t.extraBlocker?.(o)??null:"no_mirror":"darwin"===o?"unsupported_arch":"unsupported_platform"},M=async(r=8e3)=>{const o=e();if(!o)throw new Error("no mirror");const n=t.versionFile(appPlatform(),isArm64Machine()),s=await B(I(o,n),r),i=/^(\d+\.\d+\.\d+)(\.\d+)?$/.exec(s)?.[1];if(!i)throw new Error(`unexpected ${n}: ${s.slice(0,40)}`);return i},F=()=>{g();for(const e of o())for(const r of t.macApp.installedNames){const o=y(e,r);if(!a(y(o,"Contents","Info.plist")))continue;const n=macBundleId(o);if(null===n||n===t.macApp.bundleId)return o}return null},N=e=>{const r=j("codesign",["--verify","--deep","--strict",e],{timeout:6e5});0!==r.status&&fail("signature",{reason:(r.stderr||r.stdout).trim().split("\n")[0]||`codesign ${r.status}`});const o=j("codesign",["-dv",e]),n=`${o.stdout}\n${o.stderr}`,s=/^TeamIdentifier=(\S+)/m.exec(n)?.[1],i=/^Identifier=(\S+)/m.exec(n)?.[1];s===t.macApp.teamId&&i===t.macApp.bundleId||fail("signature",{reason:`TeamIdentifier=${s??"?"} Identifier=${i??"?"}`});const a=j("spctl",["-a","-t","exec","-vv",e],{timeout:3e5});0!==a.status&&fail("signature",{reason:(a.stderr||a.stdout).trim().split("\n")[0]||`spctl ${a.status}`})},H=()=>{const e=F();let r=e;if(!r){const e=V("/Applications")?"/Applications":y(P(),"Applications");r=y(e,t.macApp.installedNames[0])}const o=$(r);return(a(o)&&!V(o)||e&&!V(e))&&fail("no_permission",{path:r}),{target:r,existing:e}},G=e=>{const r=U(`$s = Get-AuthenticodeSignature -LiteralPath ${L(e)}; [pscustomobject]@{ status = [string]$s.Status; subject = [string]$s.SignerCertificate.Subject } | ConvertTo-Json -Compress`);let o={};try{o=JSON.parse(r.stdout.trim()||"{}")}catch{}if("Valid"!==o.status||!t.windows.signer.test(o.subject??"")){const t=o.status?`${o.status} ${o.subject??""}`:powerShellError(r.stderr)||powerShellError(r.stdout.trim().startsWith("{")?"":r.stdout)||`exit ${r.status}`;fail("signature",{reason:t.trim()})}},J=()=>{const e=U(`Get-AppxPackage | Where-Object { ${t.windows.packageFilter} } | ForEach-Object { $_.Version.ToString() }`,3e4);return/\d+\.\d+\.\d+/.exec(e.stdout)?.[0]??null};return{assetName:r,blocker:k,latestVersion:M,installedMacApp:F,windowsPackageVersion:J,verifyMacApp:N,verifyWindowsPackage:G,install:async(o={})=>{const P=k();P&&fail("blocked",{reason:v.t(`app_update.reason_${P}`)}),(()=>{if("darwin"===appPlatform()){g();for(const e of s())try{f(e.path,{recursive:!0,force:!0})}catch(e){E.logError(`${t.id}: remove leftover`,e)}}const e=new Set(["mnt"]);for(const r of["darwin","win32"])for(const o of[!0,!1]){const n=t.asset(r,o);n&&e.add(n)}const r=new RegExp(`^${t.id.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}-[A-Za-z0-9]{6}$`);let o=[];try{o=p(h())}catch{}for(const n of o){if(!r.test(n))continue;const o=y(h(),n);try{if(!m(o).isDirectory())continue;const t=p(o);if(0===t.length||!t.every(t=>e.has(t)))continue;const r=Math.max(...[o,...t.map(t=>y(o,t))].map(t=>m(t).mtimeMs));if(Date.now()-r<864e5)continue;const n=y(o,"mnt");if("darwin"===appPlatform()&&a(n)&&(j("hdiutil",["detach",n,"-force"],{timeout:6e4}),p(n).length>0))continue;f(o,{recursive:!0,force:!0})}catch(e){E.logError(`${t.id}: remove stale work folder`,e)}}})();const T=e(),F=r();let O;try{O=await M(15e3)}catch(t){fail("download",{reason:t instanceof Error?t.message:String(t)})}const D=e=>I(T,e,t.releaseTag?.(O)),V=b().installMirror?.downloadCounter;let X;try{X=parseSha256Sums(await C(D("SHA256SUMS"),V,t=>B(t,15e3))).get(F)}catch(e){E.logError(`${t.id}: SHA256SUMS`,e)}X||fail("no_checksum",{file:F}),"darwin"===appPlatform()&&H();const q=y(_.getConfigDir(),"downloads",t.id),z=y(q,F),K=l(y(h(),`${t.id}-`));let Q=y(K,F),Y=!1;try{a(z)&&await W(z)===X?(Q=z,o.reusing?.(O)):(o.downloading?.(O),await C(D(F),V,t=>async function(t,e,r){let o;try{o=await R(t,{signal:AbortSignal.timeout(18e5)})}catch(t){fail("download",{reason:t instanceof Error?t.message:String(t)})}o.ok&&o.body||fail("download",{reason:`HTTP ${o.status}`});const n=Number(o.headers.get("content-length"))||0;let s=0,a=-1;const c=new A({transform(t,e,o){s+=t.length;const i=n?Math.floor(100*s/n):-1;i>=0&&i!==a&&(a=i,r?.(i)),o(null,t)}});try{await x(S.fromWeb(o.body),c,i(e))}catch(t){f(e,{force:!0}),fail("download",{reason:t instanceof Error?t.message:String(t)})}}(t,Q,o.percent))),o.verifying?.();const e=await W(Q);e!==X&&fail("checksum",{file:F,expected:X.slice(0,12),actual:e.slice(0,12)}),o.installing?.();const r="darwin"===appPlatform()?await(async(e,r)=>{const o=y(r,"mnt");c(o,{recursive:!0});const n=j("hdiutil",["attach","-nobrowse","-readonly","-noautoopen","-mountpoint",o,e],{timeout:3e5,input:"Y\n"});0!==n.status&&fail("mount",{reason:(n.stderr||n.stdout).trim().split("\n").pop()??""});let s=null;try{const e=y(o,t.macApp.source);a(e)||fail("bad_package",{reason:t.macApp.source});const{target:r,existing:n}=H(),i=$(r),l=w(r);c(i,{recursive:!0}),s=y(i,`.${l}.${process.pid}.new`),f(s,{recursive:!0,force:!0});const p=j("ditto",[e,s],{timeout:9e5});0!==p.status&&fail("copy",{reason:(p.stderr||p.stdout).trim().split("\n")[0]??""}),N(s);const u=macAppVersion(s);u||fail("bad_package",{reason:"Info.plist"});const m=y(i,`.${l}.${process.pid}.old`);try{n&&d(n,m)}catch(t){throw["EPERM","EACCES"].includes(t.code??"")&&fail("app_management",{path:n}),t}try{d(s,r)}catch(t){throw n&&d(m,n),t}return s=null,f(m,{recursive:!0,force:!0}),{version:u,location:r}}finally{s&&f(s,{recursive:!0,force:!0}),j("hdiutil",["detach",o,"-force"],{timeout:6e4})}})(Q,K):await(async(t,e)=>{G(t);const r=U(`$ErrorActionPreference = 'Stop'; Add-AppxPackage -Path ${L(t)} -ForceApplicationShutdown`,9e5);if(0!==r.status){const o=powerShellError(r.stderr)||powerShellError(r.stdout)||`Add-AppxPackage ${r.status}`;/0x80073D28/i.test(`${r.stderr}\n${r.stdout}`)||fail("install",{reason:o}),await(e.elevate?.())||fail("needs_admin");const n=(t=>{const e=y($(t),"elevated-install.log");f(e,{force:!0});const r=`$ErrorActionPreference = 'Stop'; try { Add-AppxPackage -Path ${L(t)} -ForceApplicationShutdown; exit 0 } catch { [IO.File]::WriteAllText(${L(e)}, $_.Exception.Message, [Text.Encoding]::UTF8); exit 1 }`,o=U(`$ErrorActionPreference = 'Stop'; $p = Start-Process -FilePath 'powershell.exe' -ArgumentList @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-EncodedCommand', '${Buffer.from(r,"utf16le").toString("base64")}') -Verb RunAs -Wait -PassThru -WindowStyle Hidden; exit $p.ExitCode`,12e5);if(0===o.status)return null;let n="";try{n=u(e,"utf-8").trim()}catch{}return n||powerShellError(o.stderr)||powerShellError(o.stdout)||`exit ${o.status}`})(t);n&&fail("install",{reason:n}),J()||fail("other_account")}const o=J();return o||fail("install",{reason:"Get-AppxPackage"}),{version:o,location:"MSIX"}})(Q,o);return Y=!0,r}catch(t){const e=t instanceof DesktopInstallError?t.key:void 0;throw Q!==z&&a(Q)&&!["checksum","signature","bad_package","mount"].includes(e??"")&&function(t,e,r){try{f(e,{recursive:!0,force:!0}),c(e,{recursive:!0});try{d(t,r)}catch{n(t,r)}}catch(t){E.logError("desktop-app: keep package",t),f(e,{recursive:!0,force:!0})}}(Q,q,z),Q===z&&["signature","bad_package","mount"].includes(e??"")&&f(q,{recursive:!0,force:!0}),t}finally{Y&&f(q,{recursive:!0,force:!0}),f(K,{recursive:!0,force:!0})}}}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{spawnSync as
|
|
1
|
+
import{spawnSync as e}from"child_process";import{mkdtempSync as r,readdirSync as t,rmSync as o,statSync as n,writeFileSync as i}from"fs";import{tmpdir as s}from"os";import{join as c}from"path";import{logger as f}from"../../utils/logger.js";import{CLI_NAME as u}from"../brand.js";import{powerShellEnv as l}from"../powershell-env.js";function m(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}export function buildRegFile(e,r,t,o=!1){const n=`HKEY_USERS\\${e}\\${r}`;return o?`Windows Registry Editor Version 5.00\r\n\r\n[-${n}]\r\n`:`Windows Registry Editor Version 5.00\r\n\r\n[${n}]\r\n${Object.entries(t).map(([e,r])=>`${m(e)}=${null===r?"-":function(e){return"boolean"==typeof e?"dword:"+(e?"00000001":"00000000"):"number"==typeof e?`dword:${(e>>>0).toString(16).padStart(8,"0")}`:m("string"==typeof e?e:JSON.stringify(e))}(r)}`).join("\r\n")}\r\n`}let a=()=>{const r=e("whoami",["/user","/fo","csv","/nh"],{encoding:"utf-8",windowsHide:!0});return/"(S-1-[\d-]+)"/.exec(`${r.stdout??""}`)?.[1]??null},d=r=>{const t=e("powershell.exe",["-NoProfile","-NonInteractive","-Command",`$p = Start-Process -FilePath 'reg.exe' -ArgumentList @('import', '"${r}"') -Verb RunAs -Wait -PassThru -WindowStyle Hidden; exit $p.ExitCode`],{encoding:"utf-8",windowsHide:!0,timeout:3e5,env:l()});return 0!==t.status&&f.logError("elevatedImport",new Error(`${t.stderr??""}`.trim()||`exit ${t.status}`)),0===t.status};export function setElevationForTests(e,r){a=e,d=r}const p=`${u}-reg-`,g=`${u}.reg`;export function removeStaleRegFiles(e=Date.now()){let r=[];try{r=t(s())}catch{return}for(const i of r){if(!i.startsWith(p)||i.length!==p.length+6)continue;const r=c(s(),i);try{const i=n(r);if(!i.isDirectory()||e-i.mtimeMs<6e5)continue;if(!t(r).every(e=>e===g))continue;o(r,{recursive:!0,force:!0})}catch(e){f.logError("elevatedReg.removeStale",e)}}}export function setUserRegistryElevated(e,t,n=!1){const f=a();if(!f)return!1;removeStaleRegFiles();const u=r(c(s(),p)),l=c(u,g);try{return i(l,Buffer.concat([Buffer.from([255,254]),Buffer.from(buildRegFile(f,e,t,n),"utf16le")]),{mode:384}),d(l)}finally{o(u,{recursive:!0,force:!0})}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{spawnSync as t}from"child_process";import{existsSync as n,realpathSync as r,statSync as e}from"fs";import{delimiter as o,dirname as s,isAbsolute as i,join as a}from"path";import{i18n as c}from"../i18n.js";import{toolHome as p}from"./types.js";import{brand as
|
|
1
|
+
import{spawnSync as t}from"child_process";import{existsSync as n,realpathSync as r,statSync as e}from"fs";import{delimiter as o,dirname as s,isAbsolute as i,join as a}from"path";import{i18n as c}from"../i18n.js";import{toolHome as p}from"./types.js";import{brand as l}from"../brand.js";export const NPM_MIRROR="https://registry.npmmirror.com";export function brandInstallScripts(t){const n=l().installMirror?.scripts;return n?{sh:`${n}/${t}.sh`,ps1:`${n}/${t}.ps1`}:void 0}export function npmMirrorInstallCommand(t,n="latest"){return`npm install -g ${t.npmPackage}@${n} --registry=${NPM_MIRROR}`}const m=/^(\d+)\.(\d+)\.(\d+)$/;function u(t,n){const r=m.exec(t).slice(1).map(Number),e=m.exec(n).slice(1).map(Number);for(let o=0;o<3;o++)if(r[o]!==e[o])return r[o]>e[o]?t:n;return t}async function f(t,n,r){const e=await fetch(t,{signal:AbortSignal.timeout(n),headers:r});if(!e.ok)throw new Error(`HTTP ${e.status}`);return e.json()}export async function npmMirrorVersion(t){if(!t.npmPackage||!t.npmMirrorTagStale)return"latest";let n=d.get(t.npmPackage);return n||d.set(t.npmPackage,n=async function(t){try{const{version:n}=await f(`https://registry.npmjs.org/${t}/latest`,1e4);if("string"==typeof n&&m.test(n))return n}catch{}try{const n=await f(`${NPM_MIRROR}/${t}`,2e4,{accept:"application/vnd.npm.install-v1+json"}),r=Object.keys(n.versions??{}).filter(t=>m.test(t));if(r.length)return r.reduce(u)}catch{}return"latest"}(t.npmPackage)),n}const d=new Map;export function mirrorInstallCommand(t){if(t.mirrorScript){if("win32"!==process.platform)return`curl -fsSL ${t.mirrorScript.sh} | sh`;const n=`$env:TEMP\\${t.command}-install.ps1`;return`irm ${t.mirrorScript.ps1} -OutFile "${n}"; powershell -NoProfile -ExecutionPolicy Bypass -File "${n}"`}return t.npmPackage?npmMirrorInstallCommand(t):""}export function npmUninstallCommand(t){return`npm uninstall -g ${t.npmPackage}`}export function installLabel(t){return c.t("upgrade.install_label",{kind:c.t(`upgrade.kind.${t.kind}`),version:t.version??"?",path:t.path})}let h=n=>{const r={encoding:"utf-8",timeout:1e4,windowsHide:!0,stdio:["ignore","pipe","pipe"]};return`${(/\.cmd$/i.test(n)?t(`"${n}" --version`,{...r,shell:!0}):t(n,["--version"],r)).stdout??""}`};const g=new Map;export function setVersionRunnerForTests(t){h=t,g.clear(),d.clear()}export function forgetInstalls(){g.clear()}function $(t,n){return"win32"===process.platform?t.toLowerCase()===n.toLowerCase():t===n}function v(t){try{return e(t).isFile()}catch{return!1}}function w(t,e){if(t.native&&$(s(e),a(p(),...t.native.binDir)))return"native";const o=t.npmPackage?a("node_modules",...t.npmPackage.split("/")):null;if(o&&n(a(s(e),o)))return"npm";let i=e;try{i=r(e)}catch{return"other"}return o&&i.includes(o)?"npm":/[\\/](Cellar|Caskroom)[\\/]/.test(i)?"brew":"other"}export function findInstalls(t){const n=g.get(t.command);if(n)return n;const e="win32"===process.platform?[`${t.command}.exe`,`${t.command}.cmd`]:[t.command],s=new Set,c=[];for(const n of(process.env.PATH??"").split(o))if(n&&i(n))for(const o of e){const e=a(n,o);if(!v(e))continue;let i=e;try{i=r(e)}catch{}const p="win32"===process.platform?i.toLowerCase():i;if(s.has(p))continue;s.add(p);const l=h(e).match(/(\d+)\.(\d+)\.(\d+)/);c.push({path:e,kind:w(t,e),version:l?l[0]:null})}return g.set(t.command,c),c}export function findInstallsIncludingNative(t){const n=findInstalls(t).map(t=>({...t,onPath:!0}));if(!t.native)return n;const r=a(p(),...t.native.binDir),e="win32"===process.platform?[`${t.command}.exe`]:[t.command];for(const t of e){const e=a(r,t);if(!v(e)||n.some(t=>$(t.path,e)))continue;const o=h(e).match(/(\d+)\.(\d+)\.(\d+)/);n.push({path:e,kind:"native",version:o?o[0]:null,onPath:!1})}return n}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{spawnSync as e}from"child_process";import{powerShellEnv as t}from"./powershell-env.js";let o;export function windowsSecurityProducts(){if("win32"!==process.platform)return[];if(o)return o;o=[];try{const r=e("powershell.exe",["-NoProfile","-NonInteractive","-Command","[Console]::OutputEncoding = [Text.Encoding]::UTF8; Get-CimInstance -Namespace root/SecurityCenter2 -ClassName AntivirusProduct | ForEach-Object { $_.displayName }"],{encoding:"utf-8",timeout:8e3,env:t(),windowsHide:!0});o=String(r.stdout??"").split(/\r?\n/).map(e=>e.trim()).filter(Boolean).slice(0,10)}catch{}return o}export function resetWindowsSecurityForTests(){o=void 0}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{readFileSync as t}from"fs";import{join as e}from"path";import{configManager as n}from"./config.js";import{atomicWriteFile as r}from"./tools/backup.js";import{logger as i}from"../utils/logger.js";function o(){return e(n.getConfigDir(),"written-values.json")}let l=null;function s(){if(l)return l;try{const e=JSON.parse(t(o(),"utf-8"));return e.values&&"object"==typeof e.values?e.values:{}}catch{return{}}}function u(t){if(l)l=t;else try{r(o(),JSON.stringify({version:1,values:t},null,2)+"\n",384)}catch(t){i.logError("writtenValues.save",t)}}export function recordAfterWrite(t){if(l)return t();l=s();const e=JSON.stringify(l);let n;try{const r=t();return n=l,l=null,JSON.stringify(n)!==e&&u(n),r}finally{l=null}}export function ownsValue(t,e,n=[]){if("string"!=typeof e)return!1;const r=s()[t];return r?r.written===e:n.includes(e)}export function claimField(t,e,n,r={}){const i=s(),o=i[t];let l;return l=null==e||""===e||e===n||"string"==typeof e&&(o?o.written===e||Boolean(r.explicit)&&o.desired!==n:Boolean(r.explicit)||(r.legacy??[]).includes(e)),i[t]=l?{written:n,desired:n}:{desired:n},u(i),l}export function takeField(t,e){const n=s();n[t]={written:e,desired:e},u(n)}export function forgetField(t){const e=s();t in e&&(delete e[t],u(e))}const c="gateway_urls";export function noteGatewayUrl(t){const e=s(),n=(e[c]?.desired??"").split("\n").filter(Boolean);n.includes(t)||(e[c]={desired:[...n,t].join("\n")},u(e))}export function wroteGatewayUrl(t){return(s()[c]?.desired??"").split("\n").includes(t)}
|
package/dist/locales/en_US.json
CHANGED
|
@@ -356,6 +356,7 @@
|
|
|
356
356
|
"elevation_running": "Click Yes in the Windows prompt…",
|
|
357
357
|
"elevation_done": "{{tool}} registry updated",
|
|
358
358
|
"elevation_failed": "Couldn't update {{tool}}'s registry (prompt declined, or this account is not an administrator): open PowerShell as administrator and run {{cli}} setup --desktopkey <your API key>",
|
|
359
|
+
"elevation_skipped": "{{tool}}'s registry was not updated: it needs one administrator confirmation. Run {{cli}} refresh in a terminal",
|
|
359
360
|
"desktop_registry_invalid": "--desktop-registry expects on or off, got: {{value}}",
|
|
360
361
|
"install_confirm": "Install {{tools}} from the China mirrors? They aren't installed yet.",
|
|
361
362
|
"install_all_hint": "Or run {{cli}} setup --key <your API key> --install to install them all",
|
|
@@ -432,6 +433,7 @@
|
|
|
432
433
|
"env_foreign": "Found the environment variables {{vars}} in {{location}}; they override Claude Code's settings. To use {{brand}} reliably, remove them and open a new terminal",
|
|
433
434
|
"env_foreign_found": "Found the environment variables {{vars}} in {{location}}; they override Claude Code's settings",
|
|
434
435
|
"env_foreign_offer": "Found the environment variables {{where}}; they override Claude Code's settings, and {{brand}} only works reliably without them. Remove them (backed up first)?",
|
|
436
|
+
"env_not_backed_up": "{{vars}} in {{location}} were not removed: their values could not be backed up first (check that ~/{{configDir}} is writable). They override Claude Code's config; remove them by hand and open a new terminal",
|
|
435
437
|
"env_removed_foreign": "Removed {{vars}} from {{location}} (backed up); open a new terminal for it to take effect",
|
|
436
438
|
"plan_replace_provider": "Replace Claude Code's current endpoint {{url}} (not written by {{product}})",
|
|
437
439
|
"provider_replaced": "Replaced the previous endpoint {{url}}; the old file is backed up",
|
|
@@ -593,7 +595,12 @@
|
|
|
593
595
|
"script_stalled_npm": "The install script made no progress for {{minutes}} minutes (the download server is unreachable); installing with npm from the China mirror instead",
|
|
594
596
|
"script_timeout_npm": "The install script was still running after an hour; installing with npm from the China mirror instead",
|
|
595
597
|
"manual_command": "{{tool}} was not installed; when the network is better, run: {{command}}",
|
|
596
|
-
"manual_npm": "or install with npm: {{command}}"
|
|
598
|
+
"manual_npm": "or install with npm: {{command}}",
|
|
599
|
+
"missing_removed_by": "Can't use {{tool}}: the install script put it at {{path}}, but the file is gone again, most likely quarantined by security software ({{security}}). Restore it from quarantine and trust it, then run {{cli}} install {{tool}} --force",
|
|
600
|
+
"missing_removed": "Can't use {{tool}}: the install script put it at {{path}}, but the file is gone again, most likely quarantined by security software. Restore it from quarantine and trust it, then run {{cli}} install {{tool}} --force",
|
|
601
|
+
"missing_not_on_path": "{{tool}} is installed at {{path}}, but this terminal cannot find it. Open a new terminal and try again; if it is still missing, add its directory to PATH",
|
|
602
|
+
"missing_not_downloaded": "Can't install {{tool}}: the install script ended before it downloaded the program; see above. Check the network and run {{cli}} install {{tool}}; if it still fails, run {{cli}} doctor --report and give support the diagnostic code",
|
|
603
|
+
"missing_unknown": "Can't use {{tool}}: the install script reported success, but the command is not there. Open a new terminal and try again; if it is still missing, run {{cli}} doctor --report and give support the diagnostic code"
|
|
597
604
|
},
|
|
598
605
|
"model_refresh": {
|
|
599
606
|
"changed": "{{tool}} model menu synced with {{brand}}: {{changes}}",
|
|
@@ -607,7 +614,9 @@
|
|
|
607
614
|
"moved": "Moved {{count}} sessions from \"{{from}}\" to \"{{target}}\"; reopen Codex to see them (archived ones in the archive). Run {{cli}} codex sessions again after switching login back",
|
|
608
615
|
"db_skipped": "Session files were updated, but Codex's database wasn't ({{reason}}). Upgrade Node.js to 22.13+ and run {{cli}} codex sessions again",
|
|
609
616
|
"backup": "Backup and undo record in {{dir}}; undo with {{cli}} codex sessions --undo <that dir>",
|
|
610
|
-
"undone": "Restored {{files}} session files and {{rows}} database rows"
|
|
617
|
+
"undone": "Restored {{files}} session files and {{rows}} database rows",
|
|
618
|
+
"move_failed": "Cannot move Codex sessions: {{reason}}",
|
|
619
|
+
"move_failed_undo": "Sessions already changed can be restored; the backup is in {{dir}}. Undo with {{cli}} codex sessions --undo \"{{dir}}\""
|
|
611
620
|
},
|
|
612
621
|
"plan": {
|
|
613
622
|
"title": "About to change (backed up first):",
|
|
@@ -671,7 +680,7 @@
|
|
|
671
680
|
"error_network": "couldn't connect",
|
|
672
681
|
"error_not_gateway": "the answer is not from {{brand}}",
|
|
673
682
|
"tools_moved": "These tools now use it:",
|
|
674
|
-
"setup_fallback": "{{from}} cannot be reached: {{reason}}. Using {{url}} from
|
|
683
|
+
"setup_fallback": "{{from}} cannot be reached: {{reason}}. Using {{url}} for this run, and from then on once the configuration is written; run {{cli}} base default to go back to the main site once the network is fine",
|
|
675
684
|
"models_count": "{{count}} models",
|
|
676
685
|
"fastest": "fastest",
|
|
677
686
|
"error_key_rejected": "API key rejected (invalid or expired)",
|
package/dist/locales/zh_CN.json
CHANGED
|
@@ -356,6 +356,7 @@
|
|
|
356
356
|
"elevation_running": "请在弹出的系统窗口里点击「是」…",
|
|
357
357
|
"elevation_done": "已更新 {{tool}} 的注册表",
|
|
358
358
|
"elevation_failed": "无法更新 {{tool}} 的注册表:系统确认被取消,或这个账号不是管理员。请以管理员身份打开 PowerShell,再运行 {{cli}} setup --desktopkey <你的令牌>",
|
|
359
|
+
"elevation_skipped": "未更新 {{tool}} 的注册表:需要在系统弹出的窗口里确认一次。请在终端里运行 {{cli}} refresh",
|
|
359
360
|
"desktop_registry_invalid": "--desktop-registry 的值应为 on 或 off,收到:{{value}}",
|
|
360
361
|
"install_confirm": "现在从国内镜像安装 {{tools}}?",
|
|
361
362
|
"install_all_hint": "也可以运行 {{cli}} setup --key <你的令牌> --install 一次安装完成",
|
|
@@ -432,6 +433,7 @@
|
|
|
432
433
|
"env_foreign": "检测到 {{location}} 里已有环境变量 {{vars}},它会盖过 Claude Code 的配置;要稳定使用 {{brand}},请删掉后重新打开终端",
|
|
433
434
|
"env_foreign_found": "检测到 {{location}} 里已有环境变量 {{vars}},它会盖过 Claude Code 的配置",
|
|
434
435
|
"env_foreign_offer": "检测到环境变量 {{where}},它会盖过 Claude Code 的配置,删掉后才能稳定使用 {{brand}}。删除这些环境变量(会先备份)?",
|
|
436
|
+
"env_not_backed_up": "未删除 {{location}} 里的 {{vars}}:无法先备份原值,请检查 ~/{{configDir}} 能否写入。它们会盖过 Claude Code 的配置,请手动删除后重新打开终端",
|
|
435
437
|
"env_removed_foreign": "已删除 {{location}} 里的 {{vars}}(已备份),重新打开终端后生效",
|
|
436
438
|
"plan_replace_provider": "替换 Claude Code 现在的接入地址 {{url}}(不是 {{product}} 写的)",
|
|
437
439
|
"provider_replaced": "已替换原来的接入地址 {{url}},修改前的文件已备份",
|
|
@@ -593,7 +595,12 @@
|
|
|
593
595
|
"script_stalled_npm": "安装脚本 {{minutes}} 分钟没有任何进展,无法连接下载地址,改为用 npm 从国内镜像安装",
|
|
594
596
|
"script_timeout_npm": "安装脚本运行 1 小时仍未完成,改为用 npm 从国内镜像安装",
|
|
595
597
|
"manual_command": "{{tool}} 未安装。网络正常时可以手动运行:{{command}}",
|
|
596
|
-
"manual_npm": "或者用 npm 安装:{{command}}"
|
|
598
|
+
"manual_npm": "或者用 npm 安装:{{command}}",
|
|
599
|
+
"missing_removed_by": "无法使用 {{tool}}:安装脚本已把它放到 {{path}},但文件随后不见了,多半被安全软件({{security}})隔离。请在安全软件的隔离区恢复这个文件并加入信任,然后运行 {{cli}} install {{tool}} --force",
|
|
600
|
+
"missing_removed": "无法使用 {{tool}}:安装脚本已把它放到 {{path}},但文件随后不见了,多半被安全软件隔离。请在安全软件的隔离区恢复这个文件并加入信任,然后运行 {{cli}} install {{tool}} --force",
|
|
601
|
+
"missing_not_on_path": "{{tool}} 已安装到 {{path}},但这个终端找不到它。新开一个终端窗口再试;仍然找不到时,把它所在的目录加进 PATH",
|
|
602
|
+
"missing_not_downloaded": "无法安装 {{tool}}:安装脚本没有下载到程序就结束了,原因见上方。检查网络后运行 {{cli}} install {{tool}};仍然失败时运行 {{cli}} doctor --report,把诊断码发给客服",
|
|
603
|
+
"missing_unknown": "无法使用 {{tool}}:安装脚本显示成功,但找不到这个命令。新开一个终端窗口再试;仍然找不到时运行 {{cli}} doctor --report,把诊断码发给客服"
|
|
597
604
|
},
|
|
598
605
|
"model_refresh": {
|
|
599
606
|
"changed": "已按 {{brand}} 最新模型清单更新 {{tool}}:{{changes}}",
|
|
@@ -607,7 +614,9 @@
|
|
|
607
614
|
"moved": "已把 {{count}} 个会话从「{{from}}」移到「{{target}}」,重新打开 Codex 后即可看到(已归档的在归档里)。以后换回另一种登录方式时,再运行 {{cli}} codex sessions",
|
|
608
615
|
"db_skipped": "会话文件已修改,但无法更新 Codex 的数据库({{reason}})。请把 Node.js 升级到 22.13 或更高版本,再运行 {{cli}} codex sessions",
|
|
609
616
|
"backup": "备份和还原记录保存在 {{dir}},还原请运行 {{cli}} codex sessions --undo <这个目录>",
|
|
610
|
-
"undone": "已还原 {{files}} 个会话文件、{{rows}} 条数据库记录"
|
|
617
|
+
"undone": "已还原 {{files}} 个会话文件、{{rows}} 条数据库记录",
|
|
618
|
+
"move_failed": "无法移动 Codex 会话:{{reason}}",
|
|
619
|
+
"move_failed_undo": "已经改动的会话可以还原,备份在 {{dir}}。还原请运行 {{cli}} codex sessions --undo \"{{dir}}\""
|
|
611
620
|
},
|
|
612
621
|
"plan": {
|
|
613
622
|
"title": "将要修改(修改前自动备份):",
|
|
@@ -671,7 +680,7 @@
|
|
|
671
680
|
"error_network": "无法连接",
|
|
672
681
|
"error_not_gateway": "返回的不是 {{brand}}",
|
|
673
682
|
"tools_moved": "以下工具已改用这个地址:",
|
|
674
|
-
"setup_fallback": "无法连接 {{from}}:{{reason}}
|
|
683
|
+
"setup_fallback": "无法连接 {{from}}:{{reason}}。这次改用 {{url}},写入配置后会一直使用这个地址;网络恢复后可以运行 {{cli}} base default 换回主站",
|
|
675
684
|
"models_count": "{{count}} 个模型",
|
|
676
685
|
"fastest": "最快",
|
|
677
686
|
"error_key_rejected": "令牌被拒绝(无效或已过期)",
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export function processAlive(r){if(!Number.isInteger(r)||r<=0)return!1;if(r===process.pid)return!0;try{return process.kill(r,0),!0}catch(r){return"EPERM"===r.code}}
|