@vibeapi/cli 0.0.155 → 0.0.156
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/lib/claude-code-manager.d.ts +3 -3
- package/dist/lib/claude-code-manager.js +1 -1
- package/dist/lib/tools/claude-code.js +1 -1
- package/dist/lib/tools/codex.js +1 -1
- package/dist/lib/written-values.d.ts +6 -0
- package/dist/lib/written-values.js +1 -1
- package/dist/locales/en_US.json +2 -2
- package/dist/locales/zh_CN.json +2 -2
- package/package.json +1 -1
|
@@ -65,7 +65,7 @@ export declare class ClaudeCodeManager {
|
|
|
65
65
|
private mcpConfigPath;
|
|
66
66
|
private lastTierFallbacks;
|
|
67
67
|
/** `NAME=value` of model settings the user chose that the last loadPrivateConfig left alone. */
|
|
68
|
-
private
|
|
68
|
+
private lastReplaced;
|
|
69
69
|
private constructor();
|
|
70
70
|
static getInstance(): ClaudeCodeManager;
|
|
71
71
|
/**
|
|
@@ -112,8 +112,8 @@ export declare class ClaudeCodeManager {
|
|
|
112
112
|
* @returns 实际被清除的键名(未改动时为空数组)
|
|
113
113
|
*/
|
|
114
114
|
clearPinnedModels(availableModels?: string[]): string[];
|
|
115
|
-
/** 最近一次 loadPrivateConfig
|
|
116
|
-
|
|
115
|
+
/** 最近一次 loadPrivateConfig 换掉的、不是 vibecli 写的模型设置(`名字=值`)。 */
|
|
116
|
+
getLastReplaced(): string[];
|
|
117
117
|
/** 最近一次 loadPrivateConfig 实际写入的档位回退(用于应用后的提示)。 */
|
|
118
118
|
getLastTierFallbacks(): TierFallback[];
|
|
119
119
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync as e,mkdirSync as t,readFileSync as n,writeFileSync as o,renameSync as s,unlinkSync as i}from"fs";import{join as r,dirname as a}from"path";import{toolHome as l}from"./tools/types.js";import{logger as c}from"../utils/logger.js";import{configManager as d,DEFAULT_MODELS as g}from"./config.js";import{loadSettingsTemplate as u}from"./settings-template.js";import{cleanupAnthropicEnvVars as f}from"./env-cleanup.js";import{getClaudeCodeTierChains as m,getGatewayModelRules as O,getRetiredDefaultModelIds as C}from"./model-registry.js";import{claimField as h,forgetField as p,ownsValue as _}from"./written-values.js";import{noteWrittenGatewayUrl as
|
|
1
|
+
import{existsSync as e,mkdirSync as t,readFileSync as n,writeFileSync as o,renameSync as s,unlinkSync as i}from"fs";import{join as r,dirname as a}from"path";import{toolHome as l}from"./tools/types.js";import{logger as c}from"../utils/logger.js";import{configManager as d,DEFAULT_MODELS as g}from"./config.js";import{loadSettingsTemplate as u}from"./settings-template.js";import{cleanupAnthropicEnvVars as f}from"./env-cleanup.js";import{getClaudeCodeTierChains as m,getGatewayModelRules as O,getRetiredDefaultModelIds as C}from"./model-registry.js";import{claimField as h,forgetField as p,ownsValue as _,takeField as E}from"./written-values.js";import{noteWrittenGatewayUrl as A}from"./gateway-addresses.js";import{autoCompactTokens as T,modelBlurb as v,prettyModelName as P}from"./gateway-models.js";import{baseModelId as N}from"./model-catalog.js";export const MODEL_ENV_VARS=["ANTHROPIC_DEFAULT_HAIKU_MODEL","ANTHROPIC_DEFAULT_SONNET_MODEL","ANTHROPIC_DEFAULT_OPUS_MODEL","ANTHROPIC_DEFAULT_FABLE_MODEL","ANTHROPIC_MODEL","ANTHROPIC_REASONING_MODEL"];const S="claude-code.model",M=e=>`claude-code.env.${e}`;function D(e){const t=Object.values(m()).flat(),n=[...Object.values(g),...Object.values(e)].filter(e=>"string"==typeof e&&""!==e);return[...new Set(["opus[1m]",...n,...C(),...t])]}const L={opus:"ANTHROPIC_DEFAULT_OPUS_MODEL",sonnet:"ANTHROPIC_DEFAULT_SONNET_MODEL",haiku:"ANTHROPIC_DEFAULT_HAIKU_MODEL",fable:"ANTHROPIC_DEFAULT_FABLE_MODEL"},R="CLAUDE_CODE_MAX_CONTEXT_TOKENS";function y(){return r(d.getConfigDir(),"claude-code-picker.json")}function I(){try{const e=JSON.parse(n(y(),"utf-8")).ids;return Array.isArray(e)?e.map(String):[]}catch{return[]}}function U(e,t=[]){if(!e||"object"!=typeof e)return!1;const{options:n,replaceBuiltInOptions:o}=e;if(!Array.isArray(n)||o)return!1;const s=O(),i=new Set([...s.models.map(e=>e.id),...s.retired,...I(),...t]);return n.every(e=>e&&"object"==typeof e&&i.has(N(String(e.model))))}export function applyGatewayModels(e,n){if(void 0===n)return e;const s={...e};if(void 0!==s.modelPicker&&!U(s.modelPicker,n.map(e=>e.id)))return s;const i=U(s.modelPicker)?s.modelPicker.options.map(e=>N(e.model)):[],r={...s.env||{}},a={...s.modelSettings||{}};for(const e of i){if(!a[e])continue;const{autoCompactWindow:t,...n}=a[e];Object.keys(n).length>0?a[e]=n:delete a[e]}const l=e=>(e.contextWindow??0)>=1e6,g=n.filter(e=>!l(e)).map(e=>e.contextWindow).filter(e=>"number"==typeof e&&e>0);!function(e){try{t(d.getConfigDir(),{recursive:!0}),o(y(),JSON.stringify({ids:e})+"\n")}catch(e){c.logError("claudeCode.recordWrittenPickerIds",e)}}(n.map(e=>e.id));const u=e=>v(e.description,{millionContext:l(e)});if(0===n.length)delete s.modelPicker,delete r[R];else{s.modelPicker={options:n.map(e=>({model:l(e)?`${e.id}[1m]`:e.id,label:e.name||P(e.id),...u(e)?{description:u(e)}:{}}))},g.length>0?r[R]=String(Math.min(...g)):delete r[R];for(const e of n){if(!e.contextWindow)continue;const t=T(e.contextWindow,e.autoCompactTokens);a[e.id]={...a[e.id],autoCompactWindow:Math.min(Math.max(t,1e5),1e6)}}}return Object.keys(a).length>0?s.modelSettings=a:delete s.modelSettings,Object.keys(r).length>0?s.env=r:delete s.env,s}export function resolveTierFallbacks(e){if(!e||0===e.length)return[];const t=new Set(e.map(N)),n=[];for(const[e,o]of Object.entries(m())){const s=L[e],[i,...r]=o;if(!s||!i||t.has(i))continue;const a=r.find(e=>t.has(e));a&&n.push({tier:e,envVar:s,from:i,to:a})}return n}export class ClaudeCodeManager{static instance;settingsPath;mcpConfigPath;lastTierFallbacks=[];lastReplaced=[];constructor(){this.settingsPath=r(l(),".claude","settings.json"),this.mcpConfigPath=r(l(),".claude.json")}static getInstance(){return ClaudeCodeManager.instance||(ClaudeCodeManager.instance=new ClaudeCodeManager),ClaudeCodeManager.instance}ensureConfigDir(n){const o=a(n);e(o)||t(o,{recursive:!0})}atomicWrite(t,n){const r=`${t}.tmp`;try{o(r,n,"utf-8"),s(r,t)}catch(t){if(e(r))try{i(r)}catch{}throw t}}getSettings(){try{if(e(this.settingsPath)){const e=n(this.settingsPath,"utf-8");return JSON.parse(e)}}catch(e){c.warn("Failed to read Claude Code settings:",e),c.logError("ClaudeCodeManager.getSettings",e)}return{}}saveSettings(e){try{this.ensureConfigDir(this.settingsPath),this.atomicWrite(this.settingsPath,JSON.stringify(e,null,2))}catch(e){throw new Error(`Failed to save Claude Code settings: ${e}`)}}getMCPConfig(){try{if(e(this.mcpConfigPath)){const e=n(this.mcpConfigPath,"utf-8");return JSON.parse(e)}}catch(e){c.warn("Failed to read Claude Code MCP config:",e),c.logError("ClaudeCodeManager.getMCPConfig",e)}return{}}saveMCPConfig(e){try{this.ensureConfigDir(this.mcpConfigPath),this.atomicWrite(this.mcpConfigPath,JSON.stringify(e,null,2))}catch(e){throw new Error(`Failed to save Claude Code MCP config: ${e}`)}}loadPrivateConfig(e,t,n,o){this.ensureOnboardingCompleted(),f();const s=u(),i=s.env||{},{env:r,...a}=s,l=this.getSettings(),{ANTHROPIC_API_KEY:c,...m}=l.env||{},O={...m},C={},h=e=>{const n=(t[e]||"").trim();return n&&n!==g[e]?n:null},T=h("haiku"),v=h("sonnet"),P=h("opus"),N=new Set([T&&"haiku",v&&"sonnet",P&&"opus"].filter(Boolean)),L=resolveTierFallbacks(n).filter(e=>!N.has(e.tier));for(const e of L)C[e.envVar]=e.to;const R=new Set;T&&(C.ANTHROPIC_DEFAULT_HAIKU_MODEL=T),v&&(C.ANTHROPIC_DEFAULT_SONNET_MODEL=v),P&&(C.ANTHROPIC_DEFAULT_OPUS_MODEL=P,C.ANTHROPIC_MODEL=P),T&&R.add("ANTHROPIC_DEFAULT_HAIKU_MODEL"),v&&R.add("ANTHROPIC_DEFAULT_SONNET_MODEL"),P&&["ANTHROPIC_DEFAULT_OPUS_MODEL","ANTHROPIC_MODEL"].forEach(e=>R.add(e));const y=D(t);this.lastReplaced=[];for(const e of MODEL_ENV_VARS){const t=O[e],n=C[e];if(void 0!==n)void 0===t||t===n||_(M(e),t,y)||this.lastReplaced.push(`${e}=${t}`),O[e]=n,E(M(e),n);else{if(void 0===t)continue;_(M(e),t,y)||this.lastReplaced.push(`${e}=${t}`),delete O[e],p(M(e))}}this.lastTierFallbacks=L.filter(e=>O[e.envVar]===e.to);const I={...l};for(const[e,t]of Object.entries(a))"model"!==e&&(e in I||(I[e]=t));I.showThinkingSummaries=!0;const U={...I,env:{...O,...Object.fromEntries(Object.entries(i).filter(([e])=>!(e in O))),ANTHROPIC_AUTH_TOKEN:e,ANTHROPIC_BASE_URL:d.getBaseUrl()}};A(d.getBaseUrl());const H=P??("string"==typeof a.model?a.model:void 0),F=l.model,b=void 0!==F&&F!==H&&!_(S,F,y);void 0===H?(delete U.model,p(S)):(U.model=H,E(S,H)),b&&this.lastReplaced.push(`model=${String(F)}`),this.saveSettings(applyGatewayModels(U,o))}ensureOnboardingCompleted(){try{const e=this.getMCPConfig();e.hasCompletedOnboarding||this.saveMCPConfig({...e,hasCompletedOnboarding:!0})}catch(e){c.warn("Failed to ensure onboarding completed:",e),c.logError("ClaudeCodeManager.ensureOnboardingCompleted",e)}}unloadPrivateConfig(){const e=this.getSettings(),t=D(d.getModelsForTool("claude-code")),n=void 0!==e.model&&_(S,e.model,t);if(p(S),!e.env){if(n){const{model:t,...n}=e;this.saveSettings(n)}return}const{ANTHROPIC_AUTH_TOKEN:o,ANTHROPIC_BASE_URL:s,API_TIMEOUT_MS:i,CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:r,CLAUDE_CODE_AUTO_MODE_SERVER:a,...l}=e.env,c={...l};for(const e of MODEL_ENV_VARS)e in c&&_(M(e),c[e],t)&&delete c[e],p(M(e));const g={...applyGatewayModels({...e,env:c},[])};g.env=g.env||{},n&&delete g.model,g.env&&0===Object.keys(g.env).length&&delete g.env,this.saveSettings(g)}clearPinnedModels(e){const t=this.getSettings(),n=t.env,o=n?.ANTHROPIC_AUTH_TOKEN?Object.fromEntries(resolveTierFallbacks(e).map(e=>[e.envVar,e.to])):{},s=[];for(const e of MODEL_ENV_VARS)n&&e in n&&n[e]!==o[e]&&s.push(e);void 0!==t.model&&s.push("model");const i=Object.entries(o).some(([e,t])=>n?.[e]!==t);if(0===s.length&&!i)return[];const r={...t};if(delete r.model,n){const e={...n};for(const t of MODEL_ENV_VARS)delete e[t];Object.assign(e,o),0===Object.keys(e).length?delete r.env:r.env=e}this.saveSettings(r),p(S);for(const e of MODEL_ENV_VARS)o[e]?h(M(e),o[e],o[e]):p(M(e));return s}getLastReplaced(){return[...this.lastReplaced]}getLastTierFallbacks(){return[...this.lastTierFallbacks]}detectCurrentConfig(){try{const e=this.getSettings();return e.env&&e.env.ANTHROPIC_AUTH_TOKEN?{apiKey:e.env.ANTHROPIC_AUTH_TOKEN}:{apiKey:null}}catch{return{apiKey:null}}}getExperimentalFeature(e){const t=this.getSettings();return t.env?.[e]}setExperimentalFeature(e,t){const n=this.getSettings(),o=n.env||{},s={...n,env:{...o,[e]:t}};this.saveSettings(s)}removeExperimentalFeature(e){const t=this.getSettings();if(!t.env)return;const{[e]:n,...o}=t.env,s={...t,env:o};this.saveSettings(s)}}export const claudeCodeManager=ClaudeCodeManager.getInstance();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{join as e}from"path";import{applyGatewayModels as t,claudeCodeManager as o}from"../claude-code-manager.js";import{backupBeforeWrite as n}from"./backup.js";import{i18n as s}from"../i18n.js";import{baseModelId as a}from"../model-catalog.js";import{gatewayModelSpecs as r,prettyModelName as i,vendorNames as l}from"../gateway-models.js";import{toolHome as c}from"./types.js";import{gatewayAddresses as d,normalizeBaseUrl as u}from"../gateway-addresses.js";import{configManager as m,savedApiKeys as p}from"../config.js";import{envCleanupPlan as f,lastEnvCleanup as g,removeEnvSources as _}from"../env-cleanup.js";import{canPrompt as h,hasExplicitYes as v}from"../runtime-options.js";import{maskHome as C}from"../telemetry.js";import{spawnSync as j}from"child_process";import{existsSync as y,readFileSync as k}from"fs";import{detectManagedOverrides as A}from"./claude-managed.js";import{installOfficialPlugins as O}from"./claude-plugins.js";import{findInstalls as S,mirrorInstallCommand as P,brandInstallScripts as x}from"./tool-installs.js";import{updateNativeFromMirror as b}from"./claude-native-mirror.js";import{brandEnv as T}from"../brand.js";import{claudeFormat as N,claudeProjectFiles as w}from"../sessions/formats.js";const H=e(c(),".claude","settings.json"),L=e(c(),".claude.json");let U
|
|
1
|
+
import{join as e}from"path";import{applyGatewayModels as t,claudeCodeManager as o}from"../claude-code-manager.js";import{backupBeforeWrite as n}from"./backup.js";import{i18n as s}from"../i18n.js";import{baseModelId as a}from"../model-catalog.js";import{gatewayModelSpecs as r,prettyModelName as i,vendorNames as l}from"../gateway-models.js";import{toolHome as c}from"./types.js";import{gatewayAddresses as d,normalizeBaseUrl as u}from"../gateway-addresses.js";import{configManager as m,savedApiKeys as p}from"../config.js";import{envCleanupPlan as f,lastEnvCleanup as g,removeEnvSources as _}from"../env-cleanup.js";import{canPrompt as h,hasExplicitYes as v}from"../runtime-options.js";import{maskHome as C}from"../telemetry.js";import{spawnSync as j}from"child_process";import{existsSync as y,readFileSync as k}from"fs";import{detectManagedOverrides as A}from"./claude-managed.js";import{installOfficialPlugins as O}from"./claude-plugins.js";import{findInstalls as S,mirrorInstallCommand as P,brandInstallScripts as x}from"./tool-installs.js";import{updateNativeFromMirror as b}from"./claude-native-mirror.js";import{brandEnv as T}from"../brand.js";import{claudeFormat as N,claudeProjectFiles as w}from"../sessions/formats.js";const H=e(c(),".claude","settings.json"),L=e(c(),".claude.json");let R,U=null,E=()=>0===j("security",["find-generic-password","-s","Claude Code-credentials"],{stdio:"ignore"}).status;export function setClaudeKeychainProbeForTests(e){E=e}export function claudeAccountLoginPresent(){const t=process.env.CLAUDE_CONFIG_DIR?.trim()||e(c(),".claude");if(y(e(t,".credentials.json")))return!0;if("darwin"!==process.platform||T("TEST_HOME"))return!1;try{return E()}catch{return!1}}function I(){try{const t=JSON.parse(k(e(c(),".claude","settings.json"),"utf-8"));return"string"==typeof t.autoUpdatesChannel?t.autoUpdatesChannel:"latest"}catch{return"latest"}}function M(e){if(!e)return;const t=new Set(e.models);return r("claude-code",e.clientModels).filter(e=>t.has(e.id))}function D(){const e=o.getSettings().env?.ANTHROPIC_BASE_URL;return"string"==typeof e&&e.trim()?claudeCodeAdapter.holdsOurConfig(p())?null:e.trim():null}let B=null;const K={command:"claude",npmPackage:"@anthropic-ai/claude-code",native:{binDir:[".local","bin"],updateArgs:["update"],dataDirs:[[".local","share","claude"]],mirrorUpdate:()=>b(I())},mirrorScript:x("claude-code"),brew:"claude-code"};function F(){return h()&&!v()}export const claudeCodeAdapter={name:"claude-code",displayName:"Claude Code",command:"claude",installCommand:P(K),upgradeCommand:"claude update",installSpec:K,upgradeHints:e=>"stable"===I()?[s.t("tools.claude_code.stable_channel",{min:e})]:[],configPath:H,sessions:{format:N,files:()=>w(e(process.env.CLAUDE_CONFIG_DIR?.trim()||e(c(),".claude"),"projects")),resumeCommand:e=>({command:"claude",args:["--resume",e]})},wantsModelCatalog:!0,loadPrivateConfig(t){B=D(),n(H),n(L),R=M(t.catalog),o.loadPrivateConfig(t.apiKey,t.models,t.catalog?.models,R);const s=e(c(),".local","bin","win32"===process.platform?"claude.exe":"claude"),a=S(claudeCodeAdapter.installSpec)[0]?.path??(y(s)?s:null);U=a?O(a):null},holdsOurConfig(e){const t=o.getSettings().env??{},n="string"==typeof t.ANTHROPIC_AUTH_TOKEN?t.ANTHROPIC_AUTH_TOKEN.trim():"",s="string"==typeof t.ANTHROPIC_BASE_URL?u(t.ANTHROPIC_BASE_URL):null;return!(!n||!e.includes(n))||null!==s&&(d().some(e=>e.url===s)||s===u(m.getBaseUrl()))},planNotes(){const e=[],t=D();t&&e.push(s.t("tools.claude_code.plan_replace_provider",{url:t}));for(const t of f())e.push(s.t("tools.claude_code.plan_env_remove",{location:C(t.location),vars:Object.keys(t.vars).join(", ")}));return e},unloadPrivateConfig(e){const t=o.getSettings().env??{};Boolean(t.ANTHROPIC_AUTH_TOKEN||t.ANTHROPIC_BASE_URL)&&!claudeCodeAdapter.holdsOurConfig(e?.savedKeys??[])||(n(H),o.unloadPrivateConfig())},detectCurrentConfig:()=>o.detectCurrentConfig(),getConfig:()=>({settings:o.getSettings(),mcp:o.getMCPConfig()}),updateConfig(e){const t=e||{};t.settings&&o.saveSettings(t.settings),t.mcp&&o.saveMCPConfig(t.mcp)},clearPinnedModels:e=>(n(H),o.clearPinnedModels(e?.models)),listedModels(){const e=o.getSettings().modelPicker;return Array.isArray(e?.options)?e.options.map(e=>a(String(e.model))):null},refreshModelMenu(e){const s=o.getSettings(),a=t(s,M(e.catalog));JSON.stringify(a)!==JSON.stringify(s)&&(n(H),o.saveSettings(a))},async followUp(){const e=g().foreign;if(0===e.length||!F())return null;const t=e.map(e=>`${C(e.location)}(${Object.keys(e.vars).join(", ")})`).join("、");return{prompt:s.t("tools.claude_code.env_foreign_offer",{where:t}),hint:s.t("tools.claude_code.env_foreign",{location:e.map(e=>C(e.location)).join("、"),vars:[...new Set(e.flatMap(e=>Object.keys(e.vars)))].join(", ")}),async run(){const t=_(e),o=t.removed.map(e=>({kind:"summary",text:s.t("tools.claude_code.env_removed_foreign",{location:C(e.location),vars:Object.keys(e.vars).join(", ")})}));return t.machineLeft.length>0&&o.push({kind:"action",text:s.t("messages.env_vars_machine_left",{vars:t.machineLeft.join(", ")})}),o},decline(){}}},applyNotes(){const e=[];U?.installed.length&&(e.push({kind:"summary",text:s.t("tools.claude_code.plugins_installed",{count:String(U.installed.length)})}),e.push({kind:"detail",text:U.installed.join(", ")})),"git"===U?.skipped?e.push({kind:"action",text:s.t("tools.claude_code.plugins_need_git")}):("marketplace"===U?.skipped||U?.failed.length)&&e.push({kind:"action",text:s.t("tools.claude_code.plugins_failed")}),R&&R.length>0&&(e.push({kind:"summary",text:s.t("tools.claude_code.gateway_models",{count:String(R.length),vendors:l(R.map(e=>e.id)).join(" / ")})}),e.push({kind:"detail",text:R.map(e=>e.name||i(e.id)).join(", ")})),B&&e.push({kind:"summary",text:s.t("tools.claude_code.provider_replaced",{url:B})});const t=g();for(const o of t.removed)e.push({kind:"summary",text:s.t("tools.claude_code.env_removed",{location:C(o.location),vars:Object.keys(o.vars).join(", ")})});for(const o of t.foreign){const t={location:C(o.location),vars:Object.keys(o.vars).join(", ")};e.push(F()?{kind:"detail",text:s.t("tools.claude_code.env_foreign_found",t)}:{kind:"action",text:s.t("tools.claude_code.env_foreign",t)})}t.machineLeft.length>0&&e.push({kind:"action",text:s.t("messages.env_vars_machine_left",{vars:t.machineLeft.join(", ")})});const n=o.getLastReplaced();n.length>0&&e.push({kind:"summary",text:s.t("tools.claude_code.replaced_user_models",{values:n.join(", ")})}),"win32"!==process.platform||process.env.CLAUDE_CODE_GIT_BASH_PATH||0===j("where",["git"],{windowsHide:!0,stdio:"ignore"}).status||e.push({kind:"action",text:s.t("tools.claude_code.no_git_bash")}),claudeAccountLoginPresent()&&e.push({kind:"detail",text:s.t("tools.claude_code.account_login_overridden")});for(const t of A())e.push({kind:"action",text:s.t("tools.claude_code.managed_override",{source:t.source,keys:t.keys.join(", ")})});for(const t of o.getLastTierFallbacks())e.push({kind:"detail",text:s.t("tools.claude_code.tier_fallback",{tier:t.tier,from:t.from,to:t.to})});return e},backupPaths:()=>[H,L],forceResetPaths:()=>[H]};
|
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 r,readFileSync as n,rmSync as s,statSync as i,writeFileSync as l}from"fs";import{join as a}from"path";import*as c from"@iarna/toml";import{logger as d}from"../../utils/logger.js";import{i18n as u}from"../i18n.js";import{backupBeforeWrite as m,atomicWriteFile as p}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{claimField as S}from"../written-values.js";import{configManager as C}from"../config.js";import{maskHome as O,track as M}from"../telemetry.js";import{buildCodexCatalog as A,catalogRejections as E,codexCatalogPath as N,fillFromOlderEntries as P,installedCodexBinaries as T,loadBundledCodexModels as D,loadPreviousCodexModels as $,previousGatewayModelIds as I}from"./codex-catalog.js";import{gatewayModelSpecs as L,modelFamily as J}from"../gateway-models.js";import{isOurGatewayUrl as G,noteWrittenGatewayUrl as R}from"../gateway-addresses.js";import{findInstalls as K,mirrorInstallCommand as X,brandInstallScripts as B}from"./tool-installs.js";import{chatgptDesktopApp as U}from"./chatgpt-desktop.js";const W=()=>f(),q=()=>a(W(),"config.toml"),z="sessions_move_declined",Y=["browser_use","browser_use_external","computer_use"],F="desktop_features_restored";function H(e){if(!0===C.getToolSetting("codex",F))return!1;const t=e.features,o=ae(t)&&Y.every(e=>!1===t[e]);if(C.setToolSetting("codex",F,!0),!o)return!1;for(const e of Y)delete t[e];return!0}export function codexWorkModeOn(){try{const e=de();return e.model_provider===ee&&ae(e.desktop)&&"STEPS_PROSE"===e.desktop.conversationDetailMode}catch{return!1}}function Q(){try{if(ae(de().desktop))return!0}catch{}if("darwin"===process.platform)return["/Applications",a(g(),"Applications")].some(e=>["ChatGPT.app","Codex.app"].some(o=>t(a(e,o))));if("win32"===process.platform){const e=a(process.env.LOCALAPPDATA||a(g(),"AppData","Local"),"Packages");try{return r(e).some(e=>/^OpenAI\.(Codex|ChatGPT)/i.test(e))}catch{return!1}}return t("/usr/lib/chatgpt/ChatGPT")}export function codexConfigPath(){return q()}const V=()=>a(W(),"auth.json"),Z="OPENAI_API_KEY",ee="custom",te="high",oe=["gpt-5.5","gpt-5.6-sol","gpt-6-astra"],re=["high","xhigh"],ne={goals:!0,js_repl:!1};let se=[];const ie=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 ce(e,t){return ae(e[t])||(e[t]={}),e[t]}function de(){if(!t(q()))return{};const e=n(q(),"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 ue(){if(!t(V()))return{};try{const e=JSON.parse(n(V(),"utf-8"));return ae(e)?e:{}}catch{return{}}}let me=null;function pe(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===ee&&o.model===e&&delete t[e];0===Object.keys(t).length&&delete e.profiles}}let fe=null;const _e=()=>a(C.getConfigDir(),"codex-catalog-check.json");function ge(e){const o=N();t(o)&&n(o,"utf-8")===e||(m(o),p(o,e))}function xe(t,r){if(0===r.length)return[];const s=function(t,o){const r=e("sha256").update(t);for(const e of o)try{const t=i(e);r.update(`\0${e}\0${t.size}\0${t.mtimeMs}`)}catch{r.update(`\0${e}`)}return r.digest("hex")}(t,r);if(function(e){try{return JSON.parse(n(_e(),"utf-8")).signature===e}catch{return!1}}(s))return[];const a=E(N(),r);return 0===a.length&&function(e){try{o(C.getConfigDir(),{recursive:!0}),l(_e(),JSON.stringify({signature:e})+"\n")}catch(e){d.logError("codexAdapter.rememberAccepted",e)}}(s),a}function he(e,t,o){const r=!1!==t.settings?.one_million_context;!function(e){e.model_context_window===ie&&delete e.model_context_window,e.model_auto_compact_token_limit===le&&delete e.model_auto_compact_token_limit}(e);const n=()=>{e.model_catalog_json===N()&&delete e.model_catalog_json,r&&(e.model_context_window=ie,e.model_auto_compact_token_limit=le)},i=D()??$();if(!i)return d.logError("codexAdapter.writeModelCatalog",new Error("no Codex binary found; model catalog skipped")),fe="skipped",void n();const l=t.catalog,a=e=>A({bundled:e,specs:L("codex",l?.clientModels),...l?{keyModels:l.models}:{},gatewayAvailable:l?.models??I(),oneMillion:r,selectedModel:o,..."gateway"===l?.oneMillionSource?{claudeOneMillion:l.oneMillion}:{}}),c=e=>JSON.stringify(e,null,2)+"\n";let u=a(i);ge(c(u));const m=T(),p=xe(c(u),m);if(p.length>0){const e=Date.now();let t=!1;for(const e of p){const o=D(e.bin);if(o){for(const e of[{models:P(u.models,o)},{models:P(a(o).models,o)}])if(ge(c(e)),0===xe(c(e),m).length){u=e,t=!0;break}if(t)break}}if(M("codex-catalog",t?"fallback":"fail",{duration_ms:Date.now()-e,error:p[0].error,detail:{rejected_by:p.map(e=>({version:e.version,path:O(e.bin)}))}}),!t)return fe={rejectedBy:p[0]},s(N(),{force:!0}),void n()}fe={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=de()}catch{return null}return e.model_catalog_json===N()&&t(N())?E(N())[0]??null:null}export function setCodexOneMillionContext(e,t){const o=de(),r=c.stringify(o),n="string"==typeof o.model?o.model:j("codex");he(o,{settings:{[CODEX_ONE_MILLION_CONTEXT_SETTING]:e},catalog:t},n);const s=c.stringify(o);s!==r&&(m(q()),p(q(),s))}const ye={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:B("codex"),brew:"codex"};function ke(e){const t=ae(e.model_providers)?e.model_providers[ee]: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 be=null;function ve(){if("skipped"===fe)return 0===K(ye).length?[]:[{kind:"action",text:u.t("tools.codex.catalog_skipped")}];if(!fe)return[];if("rejectedBy"in fe){const{bin:e,version:t}=fe.rejectedBy;return[{kind:"action",text:u.t("tools.codex.catalog_rejected",{path:e,version:t??"?"})}]}const e=new Map;for(const t of fe.listed)e.set(J(t.id),(e.get(J(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(fe.listed.length),breakdown:t})},{kind:"detail",text:fe.listed.map(e=>e.name).join(", ")},...codexWorkModeOn()||Q()?[{kind:"action",text:u.t(codexWorkModeOn()?"tools.codex.work_mode_on":"tools.codex.work_mode_hint")}]:[]]}export const codexAdapter={name:"codex",companionApps:[U],displayName:"Codex",command:"codex",installCommand:X(ye),installSpec:ye,configPath:q(),sessions:{format:b,files:()=>[...v(a(f(),"sessions")),...v(a(f(),"archived_sessions"))],resumeCommand:e=>({command:"codex",args:["resume",e]})},wantsModelCatalog:!0,listedModels(){if(de().model_catalog_json!==N())return 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){if(de().model_catalog_json!==N())return;setCodexOneMillionContext(!1!==e.settings?.one_million_context,e.catalog);const t=de(),o=function(e,t){const o=ae(e.model_providers)?e.model_providers[ee]: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));(H(t)||o)&&(m(q()),p(q(),c.stringify(t)))},async followUp(){if(de().model_provider!==ee)return null;const e=await h(ee,{dryRun:!0}),t=Math.max(e.moved.length,e.dbRows);if(0===t)return null;const o=C.getToolSettings("codex")[z];if("number"==typeof o&&t<=o)return null;const r={count:String(t)};return k().length>0?{hint:u.t("tools.codex.sessions_hidden_running",r)}:{prompt:u.t("tools.codex.sessions_offer",r),hint:u.t("tools.codex.sessions_hidden",r),async run(){const e=await h(ee),t=[...new Set(e.moved.map(e=>e.from))].join("、")||"-",o=String(Math.max(e.moved.length,e.dbRows)),r=[{kind:"summary",text:u.t("codex_sessions.moved",{count:o,from:t,target:ee})},{kind:"summary",text:u.t("codex_sessions.backup",{dir:e.backupDir??""})}];return e.dbSkipped&&e.dbSkipped!==y&&r.push({kind:"action",text:u.t("codex_sessions.db_skipped",{reason:e.dbSkipped})}),r},decline(){C.setToolSetting("codex",z,t)}}},applyNotes(){const e=[];return be&&e.push({kind:"summary",text:u.t("tools.codex.provider_replaced",{url:be})}),se.length>0&&e.push({kind:"summary",text:u.t("tools.codex.kept_user_settings",{values:se.join(", ")})}),[...e,...ve()]},planNotes(){let e;try{e=de()}catch{return[]}const t=[],o=ke(e);return o?t.push(u.t("tools.codex.plan_replace_provider",{url:o})):"string"==typeof e.model_provider&&e.model_provider!==ee&&t.push(u.t("tools.codex.plan_switch_provider",{provider:e.model_provider})),t},loadPrivateConfig(e){const t=j("codex"),o=_(e.models,t),r=function(e){return/(?:^|\/)claude(?:-|$)/i.test(e)}(o)?t:o,n=x(e.baseUrl),s=de();se=[];const i=w().retired,l="string"==typeof s.model&&i.includes(s.model)?void 0:s.model;S("codex.model",l,r,{explicit:r!==t,legacy:oe})?s.model=r:se.push(`model = ${String(s.model)}`),s.model_provider=ee,S("codex.model_reasoning_effort",s.model_reasoning_effort,te,{legacy:re})?s.model_reasoning_effort=te:se.push(`model_reasoning_effort = ${String(s.model_reasoning_effort)}`);const a="string"==typeof s.model?s.model:r;he(s,e,a);const d=ce(s,"model_providers");be=ke(s),R(n);const u=ae(d[ee])?{...d[ee]}:{};delete u.env_key;const{experimental_bearer_token:f,...g}=u;d[ee]={...g,name:"custom",wire_api:"responses",requires_openai_auth:!0,supports_standalone_web_search:!0,base_url:n},pe(s),ce(ce(s,"tui"),"model_availability_nux")[a]=4;const h=ce(s,"features");for(const[e,t]of Object.entries(ne))(S(`codex.features.${e}`,h[e],String(t),{legacy:[String(t)]})||h[e]===t)&&(h[e]=t);H(s),m(q()),p(q(),c.stringify(s)),function(e){const t=e.trim();if(!t)return;const o={...ue(),auth_mode:"apikey",[Z]:t};m(V()),p(V(),JSON.stringify(o,null,2)+"\n",384)}(e.apiKey)},holdsOurConfig(e){const t=ue()[Z];return"string"==typeof t&&e.includes(t.trim())},unloadPrivateConfig(e){if(me=function(e){const t=ue(),o="string"==typeof t[Z]?t[Z].trim():"";if(!o)return ae(t.tokens)?"chatgpt":null;if(!e.includes(o))return"other_key";const{[Z]:r,auth_mode:n,...i}=t;return m(V()),ae(i.tokens)?(p(V(),JSON.stringify({...i,auth_mode:"chatgpt"},null,2)+"\n",384),"chatgpt"):(s(V(),{force:!0}),"signed_out")}(e?.savedKeys??[]),!t(q()))return;let o;try{o=de()}catch(e){return void d.logError("codexAdapter.unloadPrivateConfig",e)}const r=o.model_providers;ae(r)&&ae(r[ee])&&G(r[ee].base_url)&&ae(r)&&(delete r[ee],0===Object.keys(r).length&&delete o.model_providers,o.model_provider===ee&&delete o.model_provider),o.model_catalog_json===N()&&delete o.model_catalog_json,H(o),pe(o),m(q()),p(q(),c.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=ue()[Z];return{apiKey:"string"==typeof e&&e.trim()?e.trim():null}},getConfig(){try{return de()}catch(e){return d.logError("codexAdapter.getConfig",e),null}},backupPaths:()=>[q(),V(),N()]};export function codexAuthProblem(){try{const e=de(),t=e.model_providers?.[ee];if(e.model_provider!==ee||!t)return null;if("string"==typeof t.experimental_bearer_token&&t.experimental_bearer_token)return"stale_bearer";const o=ue();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,mkdirSync as o,readdirSync as r,readFileSync as n,rmSync as s,statSync as i,writeFileSync as l}from"fs";import{join as a}from"path";import*as d 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 N,codexCatalogPath as P,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=()=>a(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=de(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&&de(e.desktop)&&"STEPS_PROSE"===e.desktop.conversationDetailMode}catch{return!1}}function V(){try{if(de(ue().desktop))return!0}catch{}if("darwin"===process.platform)return["/Applications",a(g(),"Applications")].some(e=>["ChatGPT.app","Codex.app"].some(o=>t(a(e,o))));if("win32"===process.platform){const e=a(process.env.LOCALAPPDATA||a(g(),"AppData","Local"),"Packages");try{return r(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=()=>a(q(),"auth.json"),ee="OPENAI_API_KEY",te="custom",oe="high",re=["gpt-5.5","gpt-5.6-sol","gpt-6-astra"],ne=["high","xhigh"],se={goals:!0,js_repl:!1};let ie=[];const le=1e6,ae=9e5;export const CODEX_ONE_MILLION_CONTEXT_SETTING="one_million_context";function de(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}function ce(e,t){return de(e[t])||(e[t]={}),e[t]}function ue(){if(!t(z()))return{};const e=n(z(),"utf-8");if(!e.trim())return{};try{const t=d.parse(e);if(!de(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(n(Z(),"utf-8"));return de(e)?e:{}}catch{return{}}}let me=null;function fe(e){const t=e.profiles;if(de(t)){for(const[e,o]of Object.entries(t))de(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=()=>a(O.getConfigDir(),"codex-catalog-check.json");function xe(e){const o=P();t(o)&&n(o,"utf-8")===e||(p(o),m(o,e))}function he(t,r){if(0===r.length)return[];const s=function(t,o){const r=e("sha256").update(t);for(const e of o)try{const t=i(e);r.update(`\0${e}\0${t.size}\0${t.mtimeMs}`)}catch{r.update(`\0${e}`)}return r.digest("hex")}(t,r);if(function(e){try{return JSON.parse(n(ge(),"utf-8")).signature===e}catch{return!1}}(s))return[];const a=N(P(),r);return 0===a.length&&function(e){try{o(O.getConfigDir(),{recursive:!0}),l(ge(),JSON.stringify({signature:e})+"\n")}catch(e){c.logError("codexAdapter.rememberAccepted",e)}}(s),a}function ye(e,t,o){const r=!1!==t.settings?.one_million_context;!function(e){e.model_context_window===le&&delete e.model_context_window,e.model_auto_compact_token_limit===ae&&delete e.model_auto_compact_token_limit}(e);const n=()=>{e.model_catalog_json===P()&&delete e.model_catalog_json,r&&(e.model_context_window=le,e.model_auto_compact_token_limit=ae)},i=$()??I();if(!i)return c.logError("codexAdapter.writeModelCatalog",new Error("no Codex binary found; model catalog skipped")),_e="skipped",void n();const l=t.catalog,a=e=>E({bundled:e,specs:J("codex",l?.clientModels),...l?{keyModels:l.models}:{},gatewayAvailable:l?.models??L(),oneMillion:r,selectedModel:o,..."gateway"===l?.oneMillionSource?{claudeOneMillion:l.oneMillion}:{}}),d=e=>JSON.stringify(e,null,2)+"\n";let u=a(i);xe(d(u));const p=D(),m=he(d(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(a(o).models,o)}])if(xe(d(e)),0===he(d(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]},s(P(),{force:!0}),void n()}_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=P()}export function codexCatalogRejection(){let e;try{e=ue()}catch{return null}return e.model_catalog_json===P()&&t(P())?N(P())[0]??null:null}export function setCodexOneMillionContext(e,t){const o=ue(),r=d.stringify(o),n="string"==typeof o.model?o.model:j("codex");ye(o,{settings:{[CODEX_ONE_MILLION_CONTEXT_SETTING]:e},catalog:t},n);const s=d.stringify(o);s!==r&&(p(z()),m(z(),s))}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=de(e.model_providers)?e.model_providers[te]:void 0;if(!de(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(a(f(),"sessions")),...v(a(f(),"archived_sessions"))],resumeCommand:e=>({command:"codex",args:["resume",e]})},wantsModelCatalog:!0,listedModels(){if(ue().model_catalog_json!==P())return null;try{return(JSON.parse(n(P(),"utf-8")).models??[]).filter(e=>"list"===e.visibility).map(e=>String(e.slug))}catch{return null}},refreshModelMenu(e){if(ue().model_catalog_json!==P())return;setCodexOneMillionContext(!1!==e.settings?.one_million_context,e.catalog);const t=ue(),o=function(e,t){const o=de(e.model_providers)?e.model_providers[te]:void 0;return!(!de(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(),d.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 r={count:String(t)};return k().length>0?{hint:u.t("tools.codex.sessions_hidden_running",r)}:{prompt:u.t("tools.codex.sessions_offer",r),hint:u.t("tools.codex.sessions_hidden",r),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)),r=[{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&&r.push({kind:"action",text:u.t("codex_sessions.db_skipped",{reason:e.dbSkipped})}),r},decline(){O.setToolSetting("codex",Y,t)}}},applyNotes(){const e=[];return ve&&e.push({kind:"summary",text:u.t("tools.codex.provider_replaced",{url:ve})}),ie.length>0&&e.push({kind:"summary",text:u.t("tools.codex.replaced_user_settings",{values:ie.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),r=function(e){return/(?:^|\/)claude(?:-|$)/i.test(e)}(o)?t:o,n=x(e.baseUrl),s=ue();ie=[];const i=w().retired,l=(e,t,o,r,n)=>{void 0===t||t===o||"string"==typeof t&&i.includes(t)||S(e,t,r)||ie.push(`${n} = ${String(t)}`),C(e,o)};l("codex.model",s.model,r,re,"model"),s.model=r,s.model_provider=te,l("codex.model_reasoning_effort",s.model_reasoning_effort,oe,ne,"model_reasoning_effort"),s.model_reasoning_effort=oe;const a="string"==typeof s.model?s.model:r;ye(s,e,a);const c=ce(s,"model_providers");ve=be(s),K(n);const u=de(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:n},fe(s),ce(ce(s,"tui"),"model_availability_nux")[a]=4;const h=ce(s,"features");for(const[e,t]of Object.entries(se))l(`codex.features.${e}`,void 0===h[e]?void 0:String(h[e]),String(t),[String(t)],`features.${e}`),h[e]=t;Q(s),p(z()),m(z(),d.stringify(s)),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 de(t.tokens)?"chatgpt":null;if(!e.includes(o))return"other_key";const{[ee]:r,auth_mode:n,...i}=t;return p(Z()),de(i.tokens)?(m(Z(),JSON.stringify({...i,auth_mode:"chatgpt"},null,2)+"\n",384),"chatgpt"):(s(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 r=o.model_providers;de(r)&&de(r[te])&&R(r[te].base_url)&&de(r)&&(delete r[te],0===Object.keys(r).length&&delete o.model_providers,o.model_provider===te&&delete o.model_provider),o.model_catalog_json===P()&&delete o.model_catalog_json,Q(o),fe(o),p(z()),m(z(),d.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(),P()]};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}}
|
|
@@ -11,6 +11,12 @@ export declare function ownsValue(key: string, current: unknown, legacy?: readon
|
|
|
11
11
|
* true → the caller writes `desired` (recorded as ours); false → the user's value stays.
|
|
12
12
|
*/
|
|
13
13
|
export declare function claimField(key: string, current: unknown, desired: string, options?: ClaimOptions): boolean;
|
|
14
|
+
/**
|
|
15
|
+
* vibecli writes `value` into the field whatever it held (setup / config: the user runs them to get
|
|
16
|
+
* a working setup in one go, user 2026-11-03; the file was backed up first). Recorded as ours so
|
|
17
|
+
* uninstall still takes out only what vibecli wrote.
|
|
18
|
+
*/
|
|
19
|
+
export declare function takeField(key: string, value: string): void;
|
|
14
20
|
/** vibecli removed its value from the field (or the user cleared it through vibecli). */
|
|
15
21
|
export declare function forgetField(key: string): void;
|
|
16
22
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{mkdirSync as e,readFileSync as t,writeFileSync as n}from"fs";import{join as r}from"path";import{configManager as i}from"./config.js";import{logger as o}from"../utils/logger.js";function s(){return r(i.getConfigDir(),"written-values.json")}function l(){try{const e=JSON.parse(t(s(),"utf-8"));return e.values&&"object"==typeof e.values?e.values:{}}catch{return{}}}function u(t){try{e(i.getConfigDir(),{recursive:!0}),n(s(),JSON.stringify({version:1,values:t},null,2)+"\n",{mode:384})}catch(e){o.logError("writtenValues.save",e)}}export function ownsValue(e,t,n=[]){if("string"!=typeof t)return!1;const r=l()[e];return r?r.written===t:n.includes(t)}export function claimField(e,t,n,r={}){const i=l(),o=i[e];let s;return s=null==t||""===t||t===n||"string"==typeof t&&(o?o.written===t||Boolean(r.explicit)&&o.desired!==n:Boolean(r.explicit)||(r.legacy??[]).includes(t)),i[e]=s?{written:n,desired:n}:{desired:n},u(i),s}export function forgetField(e){const t=l();e in t&&(delete t[e],u(t))}const c="gateway_urls";export function noteGatewayUrl(e){const t=l(),n=(t[c]?.desired??"").split("\n").filter(Boolean);n.includes(e)||(t[c]={desired:[...n,e].join("\n")},u(t))}export function wroteGatewayUrl(e){return(l()[c]?.desired??"").split("\n").includes(e)}
|
|
1
|
+
import{mkdirSync as e,readFileSync as t,writeFileSync as n}from"fs";import{join as r}from"path";import{configManager as i}from"./config.js";import{logger as o}from"../utils/logger.js";function s(){return r(i.getConfigDir(),"written-values.json")}function l(){try{const e=JSON.parse(t(s(),"utf-8"));return e.values&&"object"==typeof e.values?e.values:{}}catch{return{}}}function u(t){try{e(i.getConfigDir(),{recursive:!0}),n(s(),JSON.stringify({version:1,values:t},null,2)+"\n",{mode:384})}catch(e){o.logError("writtenValues.save",e)}}export function ownsValue(e,t,n=[]){if("string"!=typeof t)return!1;const r=l()[e];return r?r.written===t:n.includes(t)}export function claimField(e,t,n,r={}){const i=l(),o=i[e];let s;return s=null==t||""===t||t===n||"string"==typeof t&&(o?o.written===t||Boolean(r.explicit)&&o.desired!==n:Boolean(r.explicit)||(r.legacy??[]).includes(t)),i[e]=s?{written:n,desired:n}:{desired:n},u(i),s}export function takeField(e,t){const n=l();n[e]={written:t,desired:t},u(n)}export function forgetField(e){const t=l();e in t&&(delete t[e],u(t))}const c="gateway_urls";export function noteGatewayUrl(e){const t=l(),n=(t[c]?.desired??"").split("\n").filter(Boolean);n.includes(e)||(t[c]={desired:[...n,e].join("\n")},u(t))}export function wroteGatewayUrl(e){return(l()[c]?.desired??"").split("\n").includes(e)}
|
package/dist/locales/en_US.json
CHANGED
|
@@ -381,7 +381,7 @@
|
|
|
381
381
|
"list_separator": ", "
|
|
382
382
|
},
|
|
383
383
|
"codex": {
|
|
384
|
-
"
|
|
384
|
+
"replaced_user_settings": "Replaced the earlier settings: {{values}} (backed up; to restore run {{cli}} config codex restore)",
|
|
385
385
|
"plan_replace_provider": "Replace model_providers.custom (now pointing at {{url}}, not written by {{product}})",
|
|
386
386
|
"plan_switch_provider": "Codex now uses {{provider}}; it will switch to {{brand}}",
|
|
387
387
|
"provider_replaced": "Replaced the previous custom provider {{url}}; the old file is backed up",
|
|
@@ -434,7 +434,7 @@
|
|
|
434
434
|
"plan_replace_provider": "Replace Claude Code's current endpoint {{url}} (not written by {{product}})",
|
|
435
435
|
"provider_replaced": "Replaced the previous endpoint {{url}}; the old file is backed up",
|
|
436
436
|
"gateway_models": "{{count}} more models added to /model ({{vendors}})",
|
|
437
|
-
"
|
|
437
|
+
"replaced_user_models": "Replaced the earlier model settings: {{values}} (backed up; to restore run {{cli}} config claude-code restore)",
|
|
438
438
|
"tier_fallback": "This API key can't use Claude Code's default {{from}}; the {{tier}} alias now uses {{to}}",
|
|
439
439
|
"stable_channel": "Your update channel in settings.json is stable, which may not have reached {{min}} yet; set autoUpdatesChannel to latest, then upgrade",
|
|
440
440
|
"managed_override": "Claude Code managed settings found ({{source}}); {{keys}} there override what {{product}} writes, so this config won't take effect. Managed settings usually come from your company's IT; ask your administrator",
|
package/dist/locales/zh_CN.json
CHANGED
|
@@ -381,7 +381,7 @@
|
|
|
381
381
|
"list_separator": "、"
|
|
382
382
|
},
|
|
383
383
|
"codex": {
|
|
384
|
-
"
|
|
384
|
+
"replaced_user_settings": "已替换原来的设置:{{values}}(已备份,恢复运行 {{cli}} config codex restore)",
|
|
385
385
|
"plan_replace_provider": "替换 model_providers.custom(现在指向 {{url}},不是 {{product}} 写的)",
|
|
386
386
|
"plan_switch_provider": "Codex 现在用的是 {{provider}},将改用 {{brand}}",
|
|
387
387
|
"provider_replaced": "已替换原来的 custom 提供方 {{url}},修改前的文件已备份",
|
|
@@ -434,7 +434,7 @@
|
|
|
434
434
|
"plan_replace_provider": "替换 Claude Code 现在的接入地址 {{url}}(不是 {{product}} 写的)",
|
|
435
435
|
"provider_replaced": "已替换原来的接入地址 {{url}},修改前的文件已备份",
|
|
436
436
|
"gateway_models": "/model 菜单新增 {{count}} 个其他模型({{vendors}})",
|
|
437
|
-
"
|
|
437
|
+
"replaced_user_models": "已替换原来的模型设置:{{values}}(已备份,恢复运行 {{cli}} config claude-code restore)",
|
|
438
438
|
"tier_fallback": "当前令牌无法使用 Claude Code 默认的 {{from}},{{tier}} 档已改用 {{to}}",
|
|
439
439
|
"stable_channel": "settings.json 里的更新渠道是 stable,这个渠道可能还没有更新到 {{min}}。请把 autoUpdatesChannel 改成 latest 后再升级",
|
|
440
440
|
"managed_override": "发现 Claude Code 的托管配置({{source}}),其中 {{keys}} 优先于 {{product}} 写入的设置,这里的配置不会生效。托管配置通常由公司电脑统一下发,请联系公司 IT 管理员",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vibeapi/cli",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.156",
|
|
4
4
|
"description": "CLI tool for managing AI coding assistants (Claude Code, Codex, OpenClaw, Hermes, AtomCode, Grok Build) with one unified config",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|