@vibeapi/api-helper 0.0.196 → 0.0.197

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.
@@ -979,8 +979,8 @@
979
979
  "context_window": 1000000,
980
980
  "description": "100 万上下文 | 均衡档",
981
981
  "endpoint_types": [
982
- "anthropic",
983
- "openai"
982
+ "openai",
983
+ "anthropic"
984
984
  ],
985
985
  "group": "",
986
986
  "group_name": "",
@@ -1950,8 +1950,8 @@
1950
1950
  "context_window": 1000000,
1951
1951
  "description": "100 万上下文 | 均衡档",
1952
1952
  "endpoint_types": [
1953
- "anthropic",
1954
- "openai"
1953
+ "openai",
1954
+ "anthropic"
1955
1955
  ],
1956
1956
  "group": "",
1957
1957
  "group_name": "",
@@ -2427,7 +2427,7 @@
2427
2427
  "tool": "gemini"
2428
2428
  }
2429
2429
  ],
2430
- "revision": "2026-11-24T09:56:12Z-14",
2430
+ "revision": "2026-12-01T08:09:27Z-15",
2431
2431
  "schema": 1,
2432
2432
  "tools": {
2433
2433
  "claude": {
@@ -2526,6 +2526,24 @@
2526
2526
  "openclaw": "gpt-6.1-sol",
2527
2527
  "opencode": "gpt-6.1-sol"
2528
2528
  },
2529
+ "tool_menu_models": {
2530
+ "codebuddy": [
2531
+ "gpt-6.2-sol",
2532
+ "gpt-6.2-astra",
2533
+ "claude-sonnet-5-5"
2534
+ ],
2535
+ "dsh": [
2536
+ "deepseek-v4.1-flash-1017",
2537
+ "gpt-6.2-sol",
2538
+ "gpt-6.2-astra",
2539
+ "claude-sonnet-5-5"
2540
+ ],
2541
+ "workbuddy": [
2542
+ "gpt-6.2-sol",
2543
+ "gpt-6.2-astra",
2544
+ "claude-sonnet-5-5"
2545
+ ]
2546
+ },
2529
2547
  "tool_min_versions": {
2530
2548
  "agy": "1.3.5",
2531
2549
  "claude-code": "2.1.321",
@@ -979,8 +979,8 @@
979
979
  "context_window": 1000000,
980
980
  "description": "100 万上下文 | 均衡档",
981
981
  "endpoint_types": [
982
- "anthropic",
983
- "openai"
982
+ "openai",
983
+ "anthropic"
984
984
  ],
985
985
  "group": "",
986
986
  "group_name": "",
@@ -1950,8 +1950,8 @@
1950
1950
  "context_window": 1000000,
1951
1951
  "description": "100 万上下文 | 均衡档",
1952
1952
  "endpoint_types": [
1953
- "anthropic",
1954
- "openai"
1953
+ "openai",
1954
+ "anthropic"
1955
1955
  ],
1956
1956
  "group": "",
1957
1957
  "group_name": "",
@@ -2427,7 +2427,7 @@
2427
2427
  "tool": "gemini"
2428
2428
  }
2429
2429
  ],
2430
- "revision": "2026-11-24T09:56:12Z-14",
2430
+ "revision": "2026-12-01T08:09:27Z-15",
2431
2431
  "schema": 1,
2432
2432
  "tools": {
2433
2433
  "claude": {
@@ -2526,6 +2526,24 @@
2526
2526
  "openclaw": "gpt-6.1-sol",
2527
2527
  "opencode": "gpt-6.1-sol"
2528
2528
  },
2529
+ "tool_menu_models": {
2530
+ "codebuddy": [
2531
+ "gpt-6.2-sol",
2532
+ "gpt-6.2-astra",
2533
+ "claude-sonnet-5-5"
2534
+ ],
2535
+ "dsh": [
2536
+ "deepseek-v4.1-flash-1017",
2537
+ "gpt-6.2-sol",
2538
+ "gpt-6.2-astra",
2539
+ "claude-sonnet-5-5"
2540
+ ],
2541
+ "workbuddy": [
2542
+ "gpt-6.2-sol",
2543
+ "gpt-6.2-astra",
2544
+ "claude-sonnet-5-5"
2545
+ ]
2546
+ },
2529
2547
  "tool_min_versions": {
2530
2548
  "agy": "1.3.5",
2531
2549
  "claude-code": "2.1.321",
@@ -1 +1 @@
1
- import o from"inquirer";import e from"chalk";import{wizard as t}from"../lib/wizard.js";import{runFollowUps as n}from"../lib/post-apply.js";import{toolManager as l,SUPPORTED_TOOLS as i}from"../lib/tool-manager.js";import{i18n as r}from"../lib/i18n.js";import{configManager as a,DEFAULT_PROFILE_NAME as s}from"../lib/config.js";import{confirmAction as c,applyOrDryRun as d,requireTerminal as f}from"../lib/confirm.js";import{canPrompt as g,isDryRun as p,isNonInteractive as m,shouldAutoConfirm as _}from"../lib/runtime-options.js";const u=/^[a-zA-Z0-9._-]+$/;function y(o,e){const t=(o||"").trim();if(!t||!u.test(t))throw new Error(r.t(`config.${e}_invalid_name`,{name:t||"<empty>"}));return t}function v(o,t){console.log("\n"+e.bold(o)),0!==t.length?t.forEach(o=>console.log(" "+o)):console.log(e.gray(" ("+r.t("config.empty_list")+")"))}function w(o,t){if("backups"===t){const t=l.listToolBackups(o).flatMap(o=>{const t=o.file.replace(/^.*[/\\]/,"");return o.backups.length?o.backups.map(o=>`${e.cyan(t)} ${e.gray(o.name.split(".bak-")[1]||o.name)}`):[`${e.cyan(t)} ${e.gray("("+r.t("config.empty_list")+")")}`]});return void v(r.t("config.tool_backups_title",{tool:i[o].displayName}),t)}const n=l.restorePrivateConfig(o).filter(o=>o.result.restored);0!==n.length?(console.log(e.green(r.t("config.config_restored",{tool:i[o].displayName}))),n.forEach(o=>console.log(e.gray(` ${o.file} ← ${o.result.from}`))),console.log(e.yellow(" ! "+r.t("config.reopen_hint",{tool:i[o].displayName})))):console.log(e.yellow(r.t("config.restore_no_backup",{tool:i[o].displayName})))}async function b(s,m,_){if(!i[s])return void console.log(e.red(r.t("config.unknown_tool",{tool:s})));const u=(m[0]||"").toLowerCase();if("backups"!==u&&"list-backups"!==u)if("restore"!==u){if("remove"===u||"unload"===u){const o=i[s].displayName;return void await d({description:r.t("config.remove_dry_run",{tool:o}),json:{action:"remove",tool:s},apply:async()=>{if(!await c({message:r.t("config.confirm_remove",{tool:o,name:s}),defaultValue:!0}))return;const t=l.holdsOurConfig(s),n=l.unloadPrivateConfig(s);t?(console.log(e.green(r.t("config.remove_done",{tool:o}))),n.forEach(o=>console.log(e.yellow(" ! "+o.text)))):console.log(e.gray(r.t("config.remove_nothing",{tool:o})))}})}if("clear-model"===u||"clear-models"===u){const o=i[s].displayName;return l.supportsClearPinnedModels(s)?void await d({description:r.t("config.clear_model_dry_run",{tool:o}),json:{action:"clear_model",tool:s},apply:async()=>{const t=await l.clearPinnedModels(s);0!==t.length?(console.log(e.green(r.t("config.clear_model_done",{tool:o}))),t.forEach(o=>console.log(e.gray(` - ${o}`))),console.log(e.gray(r.t("config.clear_model_restart_hint",{tool:o})))):console.log(e.yellow(r.t("config.clear_model_none",{tool:o})))}}):void console.log(e.yellow(r.t("config.clear_model_unsupported",{tool:o})))}if(p())await d({description:r.t("config.tool_apply_dry_run",{tool:i[s].displayName}),json:{action:"apply",tool:s,force:Boolean(_.force)},apply:()=>{}});else{if(!l.isToolInstalled(s)){if(_.nonInteractive)return void console.log(e.yellow(r.t("wizard.tool_not_installed",{tool:i[s].displayName})));if(console.log(e.yellow(r.t("wizard.tool_not_installed",{tool:i[s].displayName}))),!g())return;const{shouldInstall:t}=await o.prompt([{type:"confirm",name:"shouldInstall",message:r.t("wizard.install_tool_confirm"),default:!0}]);if(!t)return void console.log(e.yellow(r.t("wizard.install_skipped")));try{await l.installTool(s)}catch(o){return console.error(e.red(r.t("install.install_failed_detail"))),void(o instanceof Error&&o.message&&console.error(e.gray(o.message)))}}if(_.nonInteractive||_.force){const o=a.getApiKeyForTool(s);if(!o)return void console.log(e.red(r.t("auth.reload_missing_config")));if(_.force&&!_.nonInteractive&&!await c({message:r.t("config.confirm_force",{tool:i[s].displayName}),defaultValue:!1}))return;return await l.applyPrivateConfig(s,o,a.getModelsForTool(s),{force:_.force,takeOver:!0}),_.force&&console.log(e.yellow(r.t("config.force_done",{tool:i[s].displayName,name:s}))),l.printApplied(s),void await n([s])}f(),await t.showToolMenu(s)}}else await d({description:r.t("config.tool_restore_dry_run",{tool:i[s].displayName}),json:{action:"tool_restore",tool:s},apply:async()=>{await c({message:r.t("config.confirm_restore",{tool:i[s].displayName}),defaultValue:!1})&&w(s,"restore")}});else w(s,"backups")}export async function configCommand(t){const{positional:n,options:l}=function(o){const e=[],t={};(m()||_())&&(t.nonInteractive=!0);for(const n of o)"--non-interactive"===n||"-y"===n?t.nonInteractive=!0:"--force"===n||"-f"===n?t.force=!0:e.push(n);return{positional:e,options:t}}(t),f=n[0],p=n.slice(1);if(f){switch(f){case"profile":return void await async function(o){const t=o[0],n=o[1];if(!t||"list"===t){const o=a.getActiveProfileName(),t=a.listProfiles().map(t=>{const n=t===o;return`${n?e.green("●"):e.gray("○")} ${t}${n?e.gray(" ("+r.t("config.profile_active_label")+")"):""}`});return void v(r.t("config.profile_list_title"),t)}if("create"===t){const o=y(n,"profile");return a.listProfiles().includes(o)?void console.log(e.yellow(r.t("config.profile_exists",{name:o}))):void await d({description:r.t("config.profile_create_dry_run",{name:o}),json:{action:"profile_create",name:o},apply:()=>{a.createProfile(o),console.log(e.green(r.t("config.profile_created",{name:o})))}})}if("use"===t){const o=y(n,"profile");return void await d({description:r.t("config.profile_use_dry_run",{name:o}),json:{action:"profile_use",name:o},apply:()=>{a.setActiveProfile(o),console.log(e.green(r.t("config.profile_activated",{name:o})))}})}if("delete"===t||"remove"===t){const o=y(n,"profile");return o===s&&1===a.listProfiles().length?void console.log(e.yellow(r.t("config.profile_cannot_delete_last"))):void await d({description:r.t("config.profile_delete_dry_run",{name:o}),json:{action:"profile_delete",name:o},apply:async()=>{await c({message:r.t("config.profile_delete_confirm",{name:o}),defaultValue:!1})?(a.deleteProfile(o),console.log(e.green(r.t("config.profile_deleted",{name:o})))):console.log(e.yellow(r.t("config.profile_delete_aborted")))}})}console.log(e.red(r.t("config.unknown_action",{action:t})))}(p);case"preset":return void await async function(o){const t=o[0],n=o[1];if(!t||"list"===t){const o=Object.entries(a.getCustomPresets()).map(([o,t])=>`${e.cyan(o)} ${e.gray(`H:${t.models.haiku} S:${t.models.sonnet} O:${t.models.opus}`)}`);return void v(r.t("config.preset_list_title"),o)}if("save"===t){const o=y(n,"preset");return void await d({description:r.t("config.preset_save_dry_run",{name:o}),json:{action:"preset_save",name:o},apply:()=>{a.saveCustomPreset(o,a.getModels()),console.log(e.green(r.t("config.preset_saved",{name:o})))}})}if("use"===t||"apply"===t){const o=y(n,"preset"),t=a.getCustomPresets()[o];return t?void await d({description:r.t("config.preset_use_dry_run",{name:o}),json:{action:"preset_use",name:o},apply:()=>{a.setModels(t.models),console.log(e.green(r.t("config.preset_applied",{name:o})))}}):void console.log(e.red(r.t("config.preset_not_found",{name:o})))}if("delete"===t||"remove"===t){const o=y(n,"preset");return void await d({description:r.t("config.preset_delete_dry_run",{name:o}),json:{action:"preset_delete",name:o},apply:()=>{a.deleteCustomPreset(o),console.log(e.green(r.t("config.preset_deleted",{name:o})))}})}console.log(e.red(r.t("config.unknown_action",{action:t})))}(p);case"tool-model":return void await async function(o){const t=o[0];if(!t||"list"===t){const o=a.getProfile().tool_models||{},t=Object.entries(o).map(([o,t])=>{const n=Object.entries(t).map(([o,e])=>`${o}=${e}`).join(" ");return`${e.cyan(o)} ${e.gray(n)}`});return void v(r.t("config.tool_model_list_title"),t)}if("set"===t){const t=(o[1]||"").trim(),n=o.length>=4?(o[2]||"").trim():"opus",l=(o.length>=4?o[3]:o[2]||"").trim();return i[t]?l&&u.test(n)?void await d({description:r.t("config.tool_model_set_dry_run",{tool:t,slot:n,model:l}),json:{action:"tool_model_set",tool:t,slot:n,model:l},apply:()=>{a.setToolModel(t,{[n]:l}),console.log(e.green(r.t("config.tool_model_set",{tool:t,slot:n,model:l})))}}):void console.log(e.red(r.t("config.tool_model_usage"))):void console.log(e.red(t?r.t("config.unknown_tool",{tool:t}):r.t("config.tool_model_usage")))}if("clear"===t||"remove"===t){const t=(o[1]||"").trim();return i[t]?void await d({description:r.t("config.tool_model_clear_dry_run",{tool:t}),json:{action:"tool_model_clear",tool:t},apply:()=>{a.setToolModel(t,null),console.log(e.green(r.t("config.tool_model_cleared",{tool:t})))}}):void console.log(e.red(t?r.t("config.unknown_tool",{tool:t}):r.t("config.tool_model_usage")))}console.log(e.red(r.t("config.unknown_action",{action:t})))}(p);case"backup":return void await function(o){return async function(o){const t=o[0],n=o[1];if(!t||"list"===t){const o=a.listBackups().map(o=>{const t=new Date(o.mtimeMs).toISOString();return`${e.cyan(o.name)} ${e.gray(t)}`});return void v(r.t("config.backup_list_title"),o)}if("create"!==t&&"snapshot"!==t)return"restore"===t?n?void await d({description:r.t("config.backup_restore_dry_run",{name:n}),json:{action:"backup_restore",name:n},apply:async()=>{await c({message:r.t("config.backup_restore_confirm",{name:n}),defaultValue:!1})?(a.restoreBackup(n),console.log(e.green(r.t("config.backup_restored",{name:n})))):console.log(e.yellow(r.t("config.backup_restore_aborted")))}}):void console.log(e.red(r.t("config.backup_restore_missing_name"))):void console.log(e.red(r.t("config.unknown_action",{action:t})));await d({description:r.t("config.backup_create_dry_run"),json:{action:"backup_create",name:n??null},apply:()=>{const o=a.createBackup(n);console.log(e.green(r.t("config.backup_created",{path:o})))}})}(o)}(p)}"claude-code"!==f&&"claude-code"!==p[0]?i[f]?await b(f,p,l):(console.error(e.red(r.t("config.unknown_command",{command:f}))),console.log(e.gray(r.t("config.usage_hint"))),Object.values(i).filter(o=>!o.hidden).forEach(o=>{console.log(e.gray(` - ${o.name}: ${o.displayName}`))})):await b("claude-code",p,l)}else await async function(t){if(t.nonInteractive||!g())return void console.log(e.red(r.t("config.requires_argument")));const{selectedTool:n}=await o.prompt([{type:"list",name:"selectedTool",message:r.t("wizard.select_tool"),choices:Object.values(i).filter(o=>!o.hidden).map(o=>({name:`${o.displayName} (${o.name})`,value:o.name}))}]);await b(n,[],t)}(l)}
1
+ import o from"inquirer";import e from"chalk";import{wizard as t}from"../lib/wizard.js";import{runFollowUps as n,runPendingElevations as l}from"../lib/post-apply.js";import{toolManager as i,SUPPORTED_TOOLS as r}from"../lib/tool-manager.js";import{i18n as a}from"../lib/i18n.js";import{configManager as s,DEFAULT_PROFILE_NAME as c}from"../lib/config.js";import{confirmAction as d,applyOrDryRun as f,requireTerminal as g}from"../lib/confirm.js";import{canPrompt as p,isDryRun as m,isNonInteractive as _,shouldAutoConfirm as u}from"../lib/runtime-options.js";const y=/^[a-zA-Z0-9._-]+$/;function v(o,e){const t=(o||"").trim();if(!t||!y.test(t))throw new Error(a.t(`config.${e}_invalid_name`,{name:t||"<empty>"}));return t}function w(o,t){console.log("\n"+e.bold(o)),0!==t.length?t.forEach(o=>console.log(" "+o)):console.log(e.gray(" ("+a.t("config.empty_list")+")"))}function b(o,t){if("backups"===t){const t=i.listToolBackups(o).flatMap(o=>{const t=o.file.replace(/^.*[/\\]/,"");return o.backups.length?o.backups.map(o=>`${e.cyan(t)} ${e.gray(o.name.split(".bak-")[1]||o.name)}`):[`${e.cyan(t)} ${e.gray("("+a.t("config.empty_list")+")")}`]});return void w(a.t("config.tool_backups_title",{tool:r[o].displayName}),t)}const n=i.restorePrivateConfig(o).filter(o=>o.result.restored);0!==n.length?(console.log(e.green(a.t("config.config_restored",{tool:r[o].displayName}))),n.forEach(o=>console.log(e.gray(` ${o.file} ← ${o.result.from}`))),console.log(e.yellow(" ! "+a.t("config.reopen_hint",{tool:r[o].displayName})))):console.log(e.yellow(a.t("config.restore_no_backup",{tool:r[o].displayName})))}async function k(c,_,u){if(!r[c])return void console.log(e.red(a.t("config.unknown_tool",{tool:c})));const y=(_[0]||"").toLowerCase();if("backups"!==y&&"list-backups"!==y)if("restore"!==y){if("remove"===y||"unload"===y){const o=r[c].displayName;return void await f({description:a.t("config.remove_dry_run",{tool:o}),json:{action:"remove",tool:c},apply:async()=>{if(!await d({message:a.t("config.confirm_remove",{tool:o,name:c}),defaultValue:!0}))return;const t=i.holdsOurConfig(c),n=i.unloadPrivateConfig(c);(await l([c])).length>0?process.exitCode=1:t?(console.log(e.green(a.t("config.remove_done",{tool:o}))),n.forEach(o=>console.log(e.yellow(" ! "+o.text)))):console.log(e.gray(a.t("config.remove_nothing",{tool:o})))}})}if("clear-model"===y||"clear-models"===y){const o=r[c].displayName;return i.supportsClearPinnedModels(c)?void await f({description:a.t("config.clear_model_dry_run",{tool:o}),json:{action:"clear_model",tool:c},apply:async()=>{const t=await i.clearPinnedModels(c);0!==t.length?(console.log(e.green(a.t("config.clear_model_done",{tool:o}))),t.forEach(o=>console.log(e.gray(` - ${o}`))),console.log(e.gray(a.t("config.clear_model_restart_hint",{tool:o})))):console.log(e.yellow(a.t("config.clear_model_none",{tool:o})))}}):void console.log(e.yellow(a.t("config.clear_model_unsupported",{tool:o})))}if(m())await f({description:a.t("config.tool_apply_dry_run",{tool:r[c].displayName}),json:{action:"apply",tool:c,force:Boolean(u.force)},apply:()=>{}});else{if(!i.isToolInstalled(c)){if(u.nonInteractive)return void console.log(e.yellow(a.t("wizard.tool_not_installed",{tool:r[c].displayName})));if(console.log(e.yellow(a.t("wizard.tool_not_installed",{tool:r[c].displayName}))),!p())return;const{shouldInstall:t}=await o.prompt([{type:"confirm",name:"shouldInstall",message:a.t("wizard.install_tool_confirm"),default:!0}]);if(!t)return void console.log(e.yellow(a.t("wizard.install_skipped")));try{await i.installTool(c)}catch(o){return console.error(e.red(a.t("install.install_failed_detail"))),void(o instanceof Error&&o.message&&console.error(e.gray(o.message)))}}if(u.nonInteractive||u.force){const o=s.getApiKeyForTool(c);if(!o)return void console.log(e.red(a.t("auth.reload_missing_config")));if(u.force&&!u.nonInteractive&&!await d({message:a.t("config.confirm_force",{tool:r[c].displayName}),defaultValue:!1}))return;return await i.applyPrivateConfig(c,o,s.getModelsForTool(c),{force:u.force,takeOver:!0}),u.force&&console.log(e.yellow(a.t("config.force_done",{tool:r[c].displayName,name:c}))),i.printApplied(c),void await n([c])}g(),await t.showToolMenu(c)}}else await f({description:a.t("config.tool_restore_dry_run",{tool:r[c].displayName}),json:{action:"tool_restore",tool:c},apply:async()=>{await d({message:a.t("config.confirm_restore",{tool:r[c].displayName}),defaultValue:!1})&&b(c,"restore")}});else b(c,"backups")}export async function configCommand(t){const{positional:n,options:l}=function(o){const e=[],t={};(_()||u())&&(t.nonInteractive=!0);for(const n of o)"--non-interactive"===n||"-y"===n?t.nonInteractive=!0:"--force"===n||"-f"===n?t.force=!0:e.push(n);return{positional:e,options:t}}(t),i=n[0],g=n.slice(1);if(i){switch(i){case"profile":return void await async function(o){const t=o[0],n=o[1];if(!t||"list"===t){const o=s.getActiveProfileName(),t=s.listProfiles().map(t=>{const n=t===o;return`${n?e.green("●"):e.gray("○")} ${t}${n?e.gray(" ("+a.t("config.profile_active_label")+")"):""}`});return void w(a.t("config.profile_list_title"),t)}if("create"===t){const o=v(n,"profile");return s.listProfiles().includes(o)?void console.log(e.yellow(a.t("config.profile_exists",{name:o}))):void await f({description:a.t("config.profile_create_dry_run",{name:o}),json:{action:"profile_create",name:o},apply:()=>{s.createProfile(o),console.log(e.green(a.t("config.profile_created",{name:o})))}})}if("use"===t){const o=v(n,"profile");return void await f({description:a.t("config.profile_use_dry_run",{name:o}),json:{action:"profile_use",name:o},apply:()=>{s.setActiveProfile(o),console.log(e.green(a.t("config.profile_activated",{name:o})))}})}if("delete"===t||"remove"===t){const o=v(n,"profile");return o===c&&1===s.listProfiles().length?void console.log(e.yellow(a.t("config.profile_cannot_delete_last"))):void await f({description:a.t("config.profile_delete_dry_run",{name:o}),json:{action:"profile_delete",name:o},apply:async()=>{await d({message:a.t("config.profile_delete_confirm",{name:o}),defaultValue:!1})?(s.deleteProfile(o),console.log(e.green(a.t("config.profile_deleted",{name:o})))):console.log(e.yellow(a.t("config.profile_delete_aborted")))}})}console.log(e.red(a.t("config.unknown_action",{action:t})))}(g);case"preset":return void await async function(o){const t=o[0],n=o[1];if(!t||"list"===t){const o=Object.entries(s.getCustomPresets()).map(([o,t])=>`${e.cyan(o)} ${e.gray(`H:${t.models.haiku} S:${t.models.sonnet} O:${t.models.opus}`)}`);return void w(a.t("config.preset_list_title"),o)}if("save"===t){const o=v(n,"preset");return void await f({description:a.t("config.preset_save_dry_run",{name:o}),json:{action:"preset_save",name:o},apply:()=>{s.saveCustomPreset(o,s.getModels()),console.log(e.green(a.t("config.preset_saved",{name:o})))}})}if("use"===t||"apply"===t){const o=v(n,"preset"),t=s.getCustomPresets()[o];return t?void await f({description:a.t("config.preset_use_dry_run",{name:o}),json:{action:"preset_use",name:o},apply:()=>{s.setModels(t.models),console.log(e.green(a.t("config.preset_applied",{name:o})))}}):void console.log(e.red(a.t("config.preset_not_found",{name:o})))}if("delete"===t||"remove"===t){const o=v(n,"preset");return void await f({description:a.t("config.preset_delete_dry_run",{name:o}),json:{action:"preset_delete",name:o},apply:()=>{s.deleteCustomPreset(o),console.log(e.green(a.t("config.preset_deleted",{name:o})))}})}console.log(e.red(a.t("config.unknown_action",{action:t})))}(g);case"tool-model":return void await async function(o){const t=o[0];if(!t||"list"===t){const o=s.getProfile().tool_models||{},t=Object.entries(o).map(([o,t])=>{const n=Object.entries(t).map(([o,e])=>`${o}=${e}`).join(" ");return`${e.cyan(o)} ${e.gray(n)}`});return void w(a.t("config.tool_model_list_title"),t)}if("set"===t){const t=(o[1]||"").trim(),n=o.length>=4?(o[2]||"").trim():"opus",l=(o.length>=4?o[3]:o[2]||"").trim();return r[t]?l&&y.test(n)?void await f({description:a.t("config.tool_model_set_dry_run",{tool:t,slot:n,model:l}),json:{action:"tool_model_set",tool:t,slot:n,model:l},apply:()=>{s.setToolModel(t,{[n]:l}),console.log(e.green(a.t("config.tool_model_set",{tool:t,slot:n,model:l})))}}):void console.log(e.red(a.t("config.tool_model_usage"))):void console.log(e.red(t?a.t("config.unknown_tool",{tool:t}):a.t("config.tool_model_usage")))}if("clear"===t||"remove"===t){const t=(o[1]||"").trim();return r[t]?void await f({description:a.t("config.tool_model_clear_dry_run",{tool:t}),json:{action:"tool_model_clear",tool:t},apply:()=>{s.setToolModel(t,null),console.log(e.green(a.t("config.tool_model_cleared",{tool:t})))}}):void console.log(e.red(t?a.t("config.unknown_tool",{tool:t}):a.t("config.tool_model_usage")))}console.log(e.red(a.t("config.unknown_action",{action:t})))}(g);case"backup":return void await function(o){return async function(o){const t=o[0],n=o[1];if(!t||"list"===t){const o=s.listBackups().map(o=>{const t=new Date(o.mtimeMs).toISOString();return`${e.cyan(o.name)} ${e.gray(t)}`});return void w(a.t("config.backup_list_title"),o)}if("create"!==t&&"snapshot"!==t)return"restore"===t?n?void await f({description:a.t("config.backup_restore_dry_run",{name:n}),json:{action:"backup_restore",name:n},apply:async()=>{await d({message:a.t("config.backup_restore_confirm",{name:n}),defaultValue:!1})?(s.restoreBackup(n),console.log(e.green(a.t("config.backup_restored",{name:n})))):console.log(e.yellow(a.t("config.backup_restore_aborted")))}}):void console.log(e.red(a.t("config.backup_restore_missing_name"))):void console.log(e.red(a.t("config.unknown_action",{action:t})));await f({description:a.t("config.backup_create_dry_run"),json:{action:"backup_create",name:n??null},apply:()=>{const o=s.createBackup(n);console.log(e.green(a.t("config.backup_created",{path:o})))}})}(o)}(g)}"claude-code"!==i&&"claude-code"!==g[0]?r[i]?await k(i,g,l):(console.error(e.red(a.t("config.unknown_command",{command:i}))),console.log(e.gray(a.t("config.usage_hint"))),Object.values(r).filter(o=>!o.hidden).forEach(o=>{console.log(e.gray(` - ${o.name}: ${o.displayName}`))})):await k("claude-code",g,l)}else await async function(t){if(t.nonInteractive||!p())return void console.log(e.red(a.t("config.requires_argument")));const{selectedTool:n}=await o.prompt([{type:"list",name:"selectedTool",message:a.t("wizard.select_tool"),choices:Object.values(r).filter(o=>!o.hidden).map(o=>({name:`${o.displayName} (${o.name})`,value:o.name}))}]);await k(n,[],t)}(l)}
@@ -4,7 +4,7 @@
4
4
  * terminal) only the command is shown: a UAC prompt nobody is there to answer would hold the command for
5
5
  * minutes. Same rule as the adapters' follow-ups below.
6
6
  */
7
- export declare function runPendingElevations(tools: string[]): Promise<void>;
7
+ export declare function runPendingElevations(tools: string[]): Promise<string[]>;
8
8
  /**
9
9
  * The adapters' `followUp()` offers (Codex sessions, another service's ANTHROPIC_* variables): asked in a
10
10
  * terminal with default yes, done under `--yes`, otherwise only the hint is printed. Also after `config <tool>`.
@@ -1 +1 @@
1
- import o from"chalk";import t from"inquirer";import{i18n as e}from"./i18n.js";import{canPrompt as n,hasExplicitYes as r}from"./runtime-options.js";import{flushTelemetry as l,track as i}from"./telemetry.js";import{toolManager as a}from"./tool-manager.js";import{getAdapter as s}from"./tools/registry.js";import{upgradeTool as p}from"./tool-upgrade.js";import{appsForTools as c,upgradeApp as f}from"./app-update.js";import{offerLatestUpgrades as u}from"./latest-upgrade.js";import{logger as m}from"../utils/logger.js";async function g(o){const{ok:e}=await t.prompt([{type:"confirm",name:"ok",message:o,default:!0}]);return e}export async function runPendingElevations(t){const a=n(),p=r();for(const n of t){const t=s(n)?.pendingElevation?.();if(!t)continue;const r=s(n)?.displayName??n;if(!p&&!a){console.log(o.yellow(" ! "+e.t("setup.elevation_skipped",{tool:r}))),i("elevate-registry","skip",{detail:{tool:n,reason:"no_terminal"}});continue}if(!p&&!await g(t.prompt)){i("elevate-registry","cancel",{detail:{tool:n,reason:"declined"}});continue}console.log(o.gray(" "+e.t("setup.elevation_running")));const c=Date.now();i("elevate-registry","start",{detail:{tool:n,asked:!p}}),await l();const f=t.run();i("elevate-registry",f?"ok":"fail",{duration_ms:Date.now()-c,detail:{tool:n,asked:!p}}),console.log(f?o.green(" √ "+e.t("setup.elevation_done",{tool:r})):o.yellow(" ! "+e.t("setup.elevation_failed",{tool:r})))}}export async function runFollowUps(t){const e=n();for(const n of t){let t,l;try{t=await(s(n)?.followUp?.())}catch(o){m.logError(`postApplyPrompts.followUp(${n})`,o);continue}if(t)if("run"in t&&(r()||e))if(r()||await g(t.prompt)){try{l=await t.run()}catch(e){m.logError(`postApplyPrompts.followUp.run(${n})`,e),i(`follow-up:${n}`,"fail",{error:e}),console.log(o.yellow(" ! "+t.hint));continue}for(const t of l)console.log("action"===t.kind?o.yellow(" ! "+t.text):o.green(" √ "+t.text))}else t.decline();else console.log(o.yellow(" ! "+t.hint))}}export async function postApplyPrompts(t,l={}){const i=new Set;for(const o of l.apps?c(t):[])try{const t=await f(o,{install:l.apps.install,quiet:!0,askBeforeUpgrade:!0});t.upgraded&&t.running&&i.add(o)}catch(t){m.logError(`postApplyPrompts.upgradeApp(${o})`,t)}for(const e of t){const t=await(s(e)?.prepareRuntime?.())??[];for(const e of t)console.log("action"===e.kind?o.yellow(" ! "+e.text):o.green(" √ "+e.text))}await runPendingElevations(t),await runFollowUps(t);const d=n(),y=r(),w=d||y?t.filter(o=>s(o)?.installSpec&&a.outdatedVersion(o)):[];if(w.length>0){const o=w.map(o=>s(o)?.displayName??o).join("、");if(y||await g(e.t("setup.offer_upgrade",{tools:o})))for(const o of w)await p(o)}await u(t.filter(o=>s(o)?.installSpec),new Set(w));for(const n of t){const t=s(n);if(i.has(n)||!t?.runningApp?.isRunning())continue;if(y||!d){console.log(o.yellow(" ! "+e.t("setup.reopen_hint",{tool:t.displayName})));continue}if(!await g(e.t("setup.offer_restart",{tool:t.displayName})))continue;const r=t.runningApp.restart();console.log(r?o.green(" √ "+e.t("setup.restarted",{tool:t.displayName})):o.yellow(" ! "+e.t("setup.restart_failed",{tool:t.displayName})))}}
1
+ import o from"chalk";import t from"inquirer";import{i18n as e}from"./i18n.js";import{canPrompt as n,hasExplicitYes as l}from"./runtime-options.js";import{flushTelemetry as i,track as r}from"./telemetry.js";import{toolManager as a}from"./tool-manager.js";import{getAdapter as s}from"./tools/registry.js";import{upgradeTool as p}from"./tool-upgrade.js";import{appsForTools as c,upgradeApp as f}from"./app-update.js";import{offerLatestUpgrades as u}from"./latest-upgrade.js";import{logger as m}from"../utils/logger.js";async function d(o){const{ok:e}=await t.prompt([{type:"confirm",name:"ok",message:o,default:!0}]);return e}export async function runPendingElevations(t){const a=n(),p=l(),c=[];for(const n of t){const t=s(n)?.pendingElevation?.();if(!t)continue;const l=s(n)?.displayName??n;if(!p&&!a){console.log(o.yellow(" ! "+(t.skippedHint??e.t("setup.elevation_skipped",{tool:l})))),r("elevate-registry","skip",{detail:{tool:n,reason:"no_terminal"}}),c.push(n);continue}if(!p&&!await d(t.prompt)){r("elevate-registry","cancel",{detail:{tool:n,reason:"declined"}}),t.failedHint&&console.log(o.yellow(" ! "+t.failedHint)),c.push(n);continue}console.log(o.gray(" "+e.t("setup.elevation_running")));const f=Date.now();r("elevate-registry","start",{detail:{tool:n,asked:!p}}),await i();const u=t.run();r("elevate-registry",u?"ok":"fail",{duration_ms:Date.now()-f,detail:{tool:n,asked:!p}}),console.log(u?o.green(" √ "+e.t("setup.elevation_done",{tool:l})):o.yellow(" ! "+(t.failedHint??e.t("setup.elevation_failed",{tool:l})))),u||c.push(n)}return c}export async function runFollowUps(t){const e=n();for(const n of t){let t,i;try{t=await(s(n)?.followUp?.())}catch(o){m.logError(`postApplyPrompts.followUp(${n})`,o);continue}if(t)if("run"in t&&(l()||e))if(l()||await d(t.prompt)){try{i=await t.run()}catch(e){m.logError(`postApplyPrompts.followUp.run(${n})`,e),r(`follow-up:${n}`,"fail",{error:e}),console.log(o.yellow(" ! "+t.hint));continue}for(const t of i)console.log("action"===t.kind?o.yellow(" ! "+t.text):o.green(" √ "+t.text))}else t.decline();else console.log(o.yellow(" ! "+t.hint))}}export async function postApplyPrompts(t,i={}){const r=new Set;for(const o of i.apps?c(t):[])try{const t=await f(o,{install:i.apps.install,quiet:!0,askBeforeUpgrade:!0});t.upgraded&&t.running&&r.add(o)}catch(t){m.logError(`postApplyPrompts.upgradeApp(${o})`,t)}for(const e of t){const t=await(s(e)?.prepareRuntime?.())??[];for(const e of t)console.log("action"===e.kind?o.yellow(" ! "+e.text):o.green(" √ "+e.text))}await runPendingElevations(t),await runFollowUps(t);const g=n(),y=l(),w=g||y?t.filter(o=>s(o)?.installSpec&&a.outdatedVersion(o)):[];if(w.length>0){const o=w.map(o=>s(o)?.displayName??o).join("、");if(y||await d(e.t("setup.offer_upgrade",{tools:o})))for(const o of w)await p(o)}await u(t.filter(o=>s(o)?.installSpec),new Set(w));for(const n of t){const t=s(n);if(r.has(n)||!t?.runningApp?.isRunning())continue;if(y||!g){console.log(o.yellow(" ! "+e.t("setup.reopen_hint",{tool:t.displayName})));continue}if(!await d(e.t("setup.offer_restart",{tool:t.displayName})))continue;const l=t.runningApp.restart();console.log(l?o.green(" √ "+e.t("setup.restarted",{tool:t.displayName})):o.yellow(" ! "+e.t("setup.restart_failed",{tool:t.displayName})))}}
@@ -102,6 +102,8 @@ export declare class ToolManager {
102
102
  /** Whether this tool supports clearing a pinned model. */
103
103
  supportsClearPinnedModels(toolName: string): boolean;
104
104
  /** The tool currently holds our provider settings (what `remove` would take out). */
105
+ /** Whether the last write / removal left a change that needs one administrator prompt. */
106
+ hasPendingElevation(toolName: string): boolean;
105
107
  holdsOurConfig(toolName: string): boolean;
106
108
  detectCurrentConfig(toolName: string): {
107
109
  apiKey: string | null;
@@ -1 +1 @@
1
- import{execSync as t,spawnSync as o}from"child_process";import{i18n as n}from"./i18n.js";import e from"inquirer";import r from"chalk";import{canPrompt as i,shouldAutoConfirm as l}from"./runtime-options.js";import{logger as a}from"../utils/logger.js";import{configManager as s,savedApiKeys as c}from"./config.js";import{getAdapter as d,listAdapters as p,TOOL_ADAPTERS as u}from"./tools/registry.js";import{backupBeforeWrite as m,listBackups as f,restoreBackup as h}from"./tools/backup.js";import{existsSync as g,rmSync as w}from"fs";import{dirname as P,join as y}from"path";import{toolHome as v}from"./tools/types.js";import{stringWidth as $}from"../utils/string-width.js";import{resolveModelCatalog as T}from"./model-catalog.js";import{compareVersions as k,getToolMinVersion as C}from"./model-registry.js";import{findInstalls as E,forgetInstalls as O,installLabel as _,mirrorInstallCommand as S,npmMirrorInstallCommand as N,npmMirrorVersion as j}from"./tools/tool-installs.js";import{mirrorInstall as M}from"./tool-upgrade.js";import{upgradeApp as U}from"./app-update.js";import{CLI_NAME as b}from"./brand.js";import{track as x,trackStep as I}from"./telemetry.js";import{addUserPathDir as R,broadcastEnvChange as F}from"./windows-env.js";export{k as compareVersions};function L(t){const o=u[t];return{name:o.name,command:o.command,installCommand:o.installCommand,configPath:o.configPath,displayName:o.displayName,...o.hidden?{hidden:!0}:{},...o.isInstalled?{gui:!0}:{}}}export const SUPPORTED_TOOLS=Object.fromEntries(Object.keys(u).map(t=>[t,L(t)]));export class ToolManager{static instance;constructor(){}static getInstance(){return ToolManager.instance||(ToolManager.instance=new ToolManager),ToolManager.instance}isToolInstalled(t){if(!SUPPORTED_TOOLS[t])return!1;const o=d(t);if(o?.isInstalled)try{return o.isInstalled()}catch{return!1}return this.isOnPath(t)||null!==this.nativeLauncher(t)}isOnPath(o){const n=SUPPORTED_TOOLS[o];if(!n)return!1;try{const o="win32"===process.platform?`where ${n.command}`:`which ${n.command}`;return t(o,{stdio:"pipe"}),!0}catch{return!1}}nativeLauncher(t){const o=d(t),n=o?.installSpec?.native?.binDir;if(!o||!n)return null;const e="win32"===process.platform?`${o.command}.exe`:o.command,r=y(v(),...n,e);return g(r)?r:null}ensureNativeOnPath(t){if("win32"!==process.platform||this.isOnPath(t))return null;const o=this.nativeLauncher(t);if(!o)return null;const n=P(o);try{if(!R(n))return null}catch(o){return a.logError(`ensureNativeOnPath: ${t}`,o),null}return F(),process.env.Path=`${process.env.Path??""};${n}`,n}addToPath(t){try{if("win32"===process.platform){if(!R(t))return!1;F(),process.env.Path=`${process.env.Path??""};${t}`}else process.env.PATH=`${process.env.PATH??""}:${t}`;return!0}catch(o){return a.logError(`addToPath: ${t}`,o),!1}}async installTool(t){return I(`install:${t}`,()=>this.installToolNow(t))}async installToolNow(o){const a=SUPPORTED_TOOLS[o];if(!a)throw new Error(`Unknown tool: ${o}`);const s=d(o)?.appInstaller;if(s&&!s.blocker()){const t=await U(o,{install:!0});if("failed"===t.result||"unavailable"===t.result)throw new Error(`Failed to install ${a.displayName}`);return}const c=d(o)?.installSpec;if(c&&(c.mirrorScript||c.npmPackage)){const t=S(c),e={installed:()=>this.isToolInstalled(o),expectedPaths:c.native?[y(v(),...c.native.binDir,"win32"===process.platform?`${c.command}.exe`:c.command)]:[],addToPath:t=>this.addToPath(t)};if(await M(c,e))return O(),void console.log(r.green("√ "+n.t("wizard.tool_installed")));throw console.log(r.red("× "+n.t("wizard.install_failed"))),console.log(r.yellow(" ! "+n.t("install.manual_command",{tool:a.displayName,command:t}))),c.mirrorScript&&c.npmPackage&&console.log(r.yellow(" ! "+n.t("install.manual_npm",{command:N(c,await j(c))}))),new Error(`Failed to install ${a.displayName}`)}const p=a.installCommand;console.log(r.gray("$ ")+r.white(p));try{return t(p,{stdio:"inherit"}),O(),void console.log(r.green("√ "+n.t("wizard.tool_installed")))}catch(t){if(console.log(r.red("× "+n.t("wizard.install_failed"))),!/EACCES|EPERM|permission denied/i.test(`${t?.message??""}${t?.stderr??""}`)&&243!==t?.status&&!p.startsWith("npm "))throw new Error(`Failed to install ${a.displayName}: ${t}`);console.log(r.yellow(" ! "+("win32"===process.platform?n.t("install.permission_windows",{command:p}):n.t("install.permission_unix",{command:p}))))}const{action:u}=!i()||l()?{action:"continue"}:await e.prompt([{type:"list",name:"action",message:n.t("install.what_next"),choices:[{name:n.t("install.installed_continue"),value:"continue"},{name:n.t("install.cancel_install"),value:"cancel"}]}]);if("cancel"===u)throw new Error(n.t("install.user_cancelled"));if(O(),!this.isToolInstalled(o))throw console.log(r.red("× "+n.t("install.still_not_installed",{tool:a.displayName}))),new Error(`${a.displayName} is not installed`);console.log(r.green("√ "+n.t("install.verified_success",{tool:a.displayName})))}getToolConfig(t){const o=d(t);if(!o)throw new Error(`Unknown tool: ${t}`);try{return o.getConfig()}catch(o){return a.warn(`Failed to read config for ${t}:`,o),a.logError(`ToolManager.getToolConfig(${t})`,o),null}}updateToolConfig(t,o){const n=d(t);if(!n)throw new Error(`Unknown tool: ${t}`);if(!n.updateConfig)throw new Error(`Tool ${t} does not support raw config updates`);n.updateConfig(o)}forceResetConfig(t){const o=d(t);if(!o)throw new Error(`Unknown tool: ${t}`);const n=o.forceResetPaths?o.forceResetPaths():this.backupPathsFor(o),e=[];for(const t of n)g(t)&&(m(t),w(t,{force:!0}),e.push(t));return e}loadPrivateConfig(t,o,n,e,r={}){const i=d(t);if(!i)throw new Error(`Unknown tool: ${t}`);r.force&&this.forceResetConfig(t),i.loadPrivateConfig({apiKey:o,baseUrl:s.getBaseUrl(),models:n,settings:s.getToolSettings(t),...e?{catalog:e}:{},...r.takeOver?{takeOver:!0}:{}})}async applyPrivateConfig(t,o,n,e={}){const r=this.installedVersion(t);return I(`apply:${t}`,()=>this.applyPrivateConfigNow(t,o,n,e),{...r?{tool_version:r}:{},...e.force?{force:!0}:{}})}async applyPrivateConfigNow(t,o,n,e){const r=d(t);if(!r)throw new Error(`Unknown tool: ${t}`);const i=r.wantsModelCatalog?await T(o):null,{force:l,takeOver:a}=e;l||a?this.loadPrivateConfig(t,o,n,i??void 0,{force:l,takeOver:a}):i?this.loadPrivateConfig(t,o,n,i):this.loadPrivateConfig(t,o,n)}applyNotes(t){const o=d(t);if(!o)return[];const e=[];try{o.applyNotes&&e.push(...o.applyNotes())}catch(o){a.logError(`ToolManager.applyNotes(${t})`,o)}const r=this.outdatedVersion(t);if(r){e.push({kind:"action",text:n.t("tools.version_outdated",{current:r.current,min:r.min,upgrade:o.installSpec?`${b} upgrade ${t}`:o.upgradeCommand||o.installCommand})});for(const t of o.upgradeHints?.(r.min)??[])e.push({kind:"action",text:t})}const i=o.installSpec?E(o.installSpec):[];return i.length>1&&e.push({kind:"action",text:n.t("upgrade.duplicates_note",{count:String(i.length),active:_(i[0]),others:i.slice(1).map(_).join("、"),tool:t})}),e}printApplied(t,o=16){const n=SUPPORTED_TOOLS[t]?.displayName??t,e=this.applyNotes(t);for(const t of e.filter(t=>"detail"===t.kind))a.record(`${n}: ${t.text}`);const i=e.filter(t=>"summary"===t.kind).map(t=>t.text).join(";"),l=" ".repeat(Math.max(1,o-$(n)));console.log(r.green("√ "+n)+(i?l+i:""));for(const t of e.filter(t=>"action"===t.kind))console.log(r.yellow(" ! "+t.text))}installedVersion(t){const n=d(t);if(!n)return null;if(n.installSpec)return E(n.installSpec)[0]?.version??null;if(n.installedVersion)try{return n.installedVersion()}catch(o){return a.logError(`ToolManager.installedVersion(${t})`,o),null}if(n.isInstalled)return null;try{const t={encoding:"utf-8",timeout:1e4,windowsHide:!0,stdio:["ignore","pipe","pipe"]},e=`${("win32"===process.platform?o(`${n.command} --version`,{...t,shell:!0}):o(n.command,["--version"],t)).stdout??""}`.match(/(\d+)\.(\d+)\.(\d+)/);return e?e[0]:null}catch{return null}}outdatedVersion(t){const o=C(t);if(!o)return null;const n=this.installedVersion(t);return n&&k(n,o)<0?{current:n,min:o}:null}unloadPrivateConfig(t){const o=d(t);if(!o)throw new Error(`Unknown tool: ${t}`);try{o.unloadPrivateConfig({savedKeys:c()}),x(`remove:${t}`,"ok")}catch(o){throw x(`remove:${t}`,"fail",{error:o}),o}let e=[];try{e=o.unloadNotes?.()??[]}catch(o){a.logError(`ToolManager.unloadNotes(${t})`,o)}return e.length>0?e:[{kind:"action",text:n.t("config.reopen_hint",{tool:o.displayName})}]}async clearPinnedModels(t){const o=d(t);if(!o)throw new Error(`Unknown tool: ${t}`);if(s.setToolModel(t,null),!o.clearPinnedModels)return[];const n=s.getApiKeyForTool(t),e=o.wantsModelCatalog&&n?await T(n):null;return o.clearPinnedModels(e??void 0)}supportsClearPinnedModels(t){return Boolean(d(t)?.clearPinnedModels)}holdsOurConfig(t){const o=d(t);if(!o)return!1;const n=c();return o.holdsOurConfig?o.holdsOurConfig(n):Boolean(o.detectCurrentConfig().apiKey)}detectCurrentConfig(t){const o=d(t);if(!o)throw new Error(`Unknown tool: ${t}`);return o.detectCurrentConfig()}backupPathsFor(t){return t.backupPaths?t.backupPaths():[t.configPath]}listToolBackups(t){const o=d(t);if(!o)throw new Error(`Unknown tool: ${t}`);return this.backupPathsFor(o).map(t=>({file:t,backups:f(t)}))}restorePrivateConfig(t){const o=d(t);if(!o)throw new Error(`Unknown tool: ${t}`);return this.backupPathsFor(o).map(t=>({file:t,result:h(t)}))}getInstalledTools(){return Object.keys(SUPPORTED_TOOLS).filter(t=>this.isToolInstalled(t))}getSupportedTools(){return p().filter(t=>!t.hidden).map(t=>L(t.name))}isGitInstalled(){try{const o="win32"===process.platform?"where git":"which git";return t(o,{stdio:"pipe"}),!0}catch{return!1}}}export const toolManager=ToolManager.getInstance();
1
+ import{execSync as t,spawnSync as o}from"child_process";import{i18n as n}from"./i18n.js";import e from"inquirer";import r from"chalk";import{canPrompt as i,shouldAutoConfirm as l}from"./runtime-options.js";import{logger as a}from"../utils/logger.js";import{configManager as s,savedApiKeys as c}from"./config.js";import{getAdapter as d,listAdapters as p,TOOL_ADAPTERS as u}from"./tools/registry.js";import{backupBeforeWrite as m,listBackups as f,restoreBackup as h}from"./tools/backup.js";import{existsSync as g,rmSync as w}from"fs";import{dirname as P,join as y}from"path";import{toolHome as v}from"./tools/types.js";import{stringWidth as $}from"../utils/string-width.js";import{resolveModelCatalog as T}from"./model-catalog.js";import{compareVersions as k,getToolMinVersion as C}from"./model-registry.js";import{findInstalls as E,forgetInstalls as O,installLabel as _,mirrorInstallCommand as S,npmMirrorInstallCommand as N,npmMirrorVersion as j}from"./tools/tool-installs.js";import{mirrorInstall as M}from"./tool-upgrade.js";import{upgradeApp as U}from"./app-update.js";import{CLI_NAME as b}from"./brand.js";import{track as x,trackStep as I}from"./telemetry.js";import{addUserPathDir as R,broadcastEnvChange as F}from"./windows-env.js";export{k as compareVersions};function L(t){const o=u[t];return{name:o.name,command:o.command,installCommand:o.installCommand,configPath:o.configPath,displayName:o.displayName,...o.hidden?{hidden:!0}:{},...o.isInstalled?{gui:!0}:{}}}export const SUPPORTED_TOOLS=Object.fromEntries(Object.keys(u).map(t=>[t,L(t)]));export class ToolManager{static instance;constructor(){}static getInstance(){return ToolManager.instance||(ToolManager.instance=new ToolManager),ToolManager.instance}isToolInstalled(t){if(!SUPPORTED_TOOLS[t])return!1;const o=d(t);if(o?.isInstalled)try{return o.isInstalled()}catch{return!1}return this.isOnPath(t)||null!==this.nativeLauncher(t)}isOnPath(o){const n=SUPPORTED_TOOLS[o];if(!n)return!1;try{const o="win32"===process.platform?`where ${n.command}`:`which ${n.command}`;return t(o,{stdio:"pipe"}),!0}catch{return!1}}nativeLauncher(t){const o=d(t),n=o?.installSpec?.native?.binDir;if(!o||!n)return null;const e="win32"===process.platform?`${o.command}.exe`:o.command,r=y(v(),...n,e);return g(r)?r:null}ensureNativeOnPath(t){if("win32"!==process.platform||this.isOnPath(t))return null;const o=this.nativeLauncher(t);if(!o)return null;const n=P(o);try{if(!R(n))return null}catch(o){return a.logError(`ensureNativeOnPath: ${t}`,o),null}return F(),process.env.Path=`${process.env.Path??""};${n}`,n}addToPath(t){try{if("win32"===process.platform){if(!R(t))return!1;F(),process.env.Path=`${process.env.Path??""};${t}`}else process.env.PATH=`${process.env.PATH??""}:${t}`;return!0}catch(o){return a.logError(`addToPath: ${t}`,o),!1}}async installTool(t){return I(`install:${t}`,()=>this.installToolNow(t))}async installToolNow(o){const a=SUPPORTED_TOOLS[o];if(!a)throw new Error(`Unknown tool: ${o}`);const s=d(o)?.appInstaller;if(s&&!s.blocker()){const t=await U(o,{install:!0});if("failed"===t.result||"unavailable"===t.result)throw new Error(`Failed to install ${a.displayName}`);return}const c=d(o)?.installSpec;if(c&&(c.mirrorScript||c.npmPackage)){const t=S(c),e={installed:()=>this.isToolInstalled(o),expectedPaths:c.native?[y(v(),...c.native.binDir,"win32"===process.platform?`${c.command}.exe`:c.command)]:[],addToPath:t=>this.addToPath(t)};if(await M(c,e))return O(),void console.log(r.green("√ "+n.t("wizard.tool_installed")));throw console.log(r.red("× "+n.t("wizard.install_failed"))),console.log(r.yellow(" ! "+n.t("install.manual_command",{tool:a.displayName,command:t}))),c.mirrorScript&&c.npmPackage&&console.log(r.yellow(" ! "+n.t("install.manual_npm",{command:N(c,await j(c))}))),new Error(`Failed to install ${a.displayName}`)}const p=a.installCommand;console.log(r.gray("$ ")+r.white(p));try{return t(p,{stdio:"inherit"}),O(),void console.log(r.green("√ "+n.t("wizard.tool_installed")))}catch(t){if(console.log(r.red("× "+n.t("wizard.install_failed"))),!/EACCES|EPERM|permission denied/i.test(`${t?.message??""}${t?.stderr??""}`)&&243!==t?.status&&!p.startsWith("npm "))throw new Error(`Failed to install ${a.displayName}: ${t}`);console.log(r.yellow(" ! "+("win32"===process.platform?n.t("install.permission_windows",{command:p}):n.t("install.permission_unix",{command:p}))))}const{action:u}=!i()||l()?{action:"continue"}:await e.prompt([{type:"list",name:"action",message:n.t("install.what_next"),choices:[{name:n.t("install.installed_continue"),value:"continue"},{name:n.t("install.cancel_install"),value:"cancel"}]}]);if("cancel"===u)throw new Error(n.t("install.user_cancelled"));if(O(),!this.isToolInstalled(o))throw console.log(r.red("× "+n.t("install.still_not_installed",{tool:a.displayName}))),new Error(`${a.displayName} is not installed`);console.log(r.green("√ "+n.t("install.verified_success",{tool:a.displayName})))}getToolConfig(t){const o=d(t);if(!o)throw new Error(`Unknown tool: ${t}`);try{return o.getConfig()}catch(o){return a.warn(`Failed to read config for ${t}:`,o),a.logError(`ToolManager.getToolConfig(${t})`,o),null}}updateToolConfig(t,o){const n=d(t);if(!n)throw new Error(`Unknown tool: ${t}`);if(!n.updateConfig)throw new Error(`Tool ${t} does not support raw config updates`);n.updateConfig(o)}forceResetConfig(t){const o=d(t);if(!o)throw new Error(`Unknown tool: ${t}`);const n=o.forceResetPaths?o.forceResetPaths():this.backupPathsFor(o),e=[];for(const t of n)g(t)&&(m(t),w(t,{force:!0}),e.push(t));return e}loadPrivateConfig(t,o,n,e,r={}){const i=d(t);if(!i)throw new Error(`Unknown tool: ${t}`);r.force&&this.forceResetConfig(t),i.loadPrivateConfig({apiKey:o,baseUrl:s.getBaseUrl(),models:n,settings:s.getToolSettings(t),...e?{catalog:e}:{},...r.takeOver?{takeOver:!0}:{}})}async applyPrivateConfig(t,o,n,e={}){const r=this.installedVersion(t);return I(`apply:${t}`,()=>this.applyPrivateConfigNow(t,o,n,e),{...r?{tool_version:r}:{},...e.force?{force:!0}:{}})}async applyPrivateConfigNow(t,o,n,e){const r=d(t);if(!r)throw new Error(`Unknown tool: ${t}`);const i=r.wantsModelCatalog?await T(o):null,{force:l,takeOver:a}=e;l||a?this.loadPrivateConfig(t,o,n,i??void 0,{force:l,takeOver:a}):i?this.loadPrivateConfig(t,o,n,i):this.loadPrivateConfig(t,o,n)}applyNotes(t){const o=d(t);if(!o)return[];const e=[];try{o.applyNotes&&e.push(...o.applyNotes())}catch(o){a.logError(`ToolManager.applyNotes(${t})`,o)}const r=this.outdatedVersion(t);if(r){e.push({kind:"action",text:n.t("tools.version_outdated",{current:r.current,min:r.min,upgrade:o.installSpec?`${b} upgrade ${t}`:o.upgradeCommand||o.installCommand})});for(const t of o.upgradeHints?.(r.min)??[])e.push({kind:"action",text:t})}const i=o.installSpec?E(o.installSpec):[];return i.length>1&&e.push({kind:"action",text:n.t("upgrade.duplicates_note",{count:String(i.length),active:_(i[0]),others:i.slice(1).map(_).join("、"),tool:t})}),e}printApplied(t,o=16){const n=SUPPORTED_TOOLS[t]?.displayName??t,e=this.applyNotes(t);for(const t of e.filter(t=>"detail"===t.kind))a.record(`${n}: ${t.text}`);const i=e.filter(t=>"summary"===t.kind).map(t=>t.text).join(";"),l=" ".repeat(Math.max(1,o-$(n)));console.log(r.green("√ "+n)+(i?l+i:""));for(const t of e.filter(t=>"action"===t.kind))console.log(r.yellow(" ! "+t.text))}installedVersion(t){const n=d(t);if(!n)return null;if(n.installSpec)return E(n.installSpec)[0]?.version??null;if(n.installedVersion)try{return n.installedVersion()}catch(o){return a.logError(`ToolManager.installedVersion(${t})`,o),null}if(n.isInstalled)return null;try{const t={encoding:"utf-8",timeout:1e4,windowsHide:!0,stdio:["ignore","pipe","pipe"]},e=`${("win32"===process.platform?o(`${n.command} --version`,{...t,shell:!0}):o(n.command,["--version"],t)).stdout??""}`.match(/(\d+)\.(\d+)\.(\d+)/);return e?e[0]:null}catch{return null}}outdatedVersion(t){const o=C(t);if(!o)return null;const n=this.installedVersion(t);return n&&k(n,o)<0?{current:n,min:o}:null}unloadPrivateConfig(t){const o=d(t);if(!o)throw new Error(`Unknown tool: ${t}`);try{o.unloadPrivateConfig({savedKeys:c()}),x(`remove:${t}`,"ok")}catch(o){throw x(`remove:${t}`,"fail",{error:o}),o}let e=[];try{e=o.unloadNotes?.()??[]}catch(o){a.logError(`ToolManager.unloadNotes(${t})`,o)}return e.length>0?e:[{kind:"action",text:n.t("config.reopen_hint",{tool:o.displayName})}]}async clearPinnedModels(t){const o=d(t);if(!o)throw new Error(`Unknown tool: ${t}`);if(s.setToolModel(t,null),!o.clearPinnedModels)return[];const n=s.getApiKeyForTool(t),e=o.wantsModelCatalog&&n?await T(n):null;return o.clearPinnedModels(e??void 0)}supportsClearPinnedModels(t){return Boolean(d(t)?.clearPinnedModels)}hasPendingElevation(t){return Boolean(d(t)?.pendingElevation?.())}holdsOurConfig(t){const o=d(t);if(!o)return!1;const n=c();return o.holdsOurConfig?o.holdsOurConfig(n):Boolean(o.detectCurrentConfig().apiKey)}detectCurrentConfig(t){const o=d(t);if(!o)throw new Error(`Unknown tool: ${t}`);return o.detectCurrentConfig()}backupPathsFor(t){return t.backupPaths?t.backupPaths():[t.configPath]}listToolBackups(t){const o=d(t);if(!o)throw new Error(`Unknown tool: ${t}`);return this.backupPathsFor(o).map(t=>({file:t,backups:f(t)}))}restorePrivateConfig(t){const o=d(t);if(!o)throw new Error(`Unknown tool: ${t}`);return this.backupPathsFor(o).map(t=>({file:t,result:h(t)}))}getInstalledTools(){return Object.keys(SUPPORTED_TOOLS).filter(t=>this.isToolInstalled(t))}getSupportedTools(){return p().filter(t=>!t.hidden).map(t=>L(t.name))}isGitInstalled(){try{const o="win32"===process.platform?"where git":"which git";return t(o,{stdio:"pipe"}),!0}catch{return!1}}}export const toolManager=ToolManager.getInstance();
@@ -1 +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 D}from"../mirror-url.js";import{backupBeforeWrite as b,atomicWriteFile as v}from"./backup.js";import{toolHome as A}from"./types.js";import{canRestartDesktop as M,desktopQuitRefused as C,isDesktopRunning as E,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 N}from"./elevated-reg.js";import{UserActionNeeded as $}from"./types.js";import{savedApiKeys as G}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 z=h;export const CLAUDE_DESKTOP_HIDE_OFFICIAL_LOGIN_SETTING="hide_official_login";export const CLAUDE_DESKTOP_FORCE_REGISTRY_SETTING="force_registry";const W=/^[a-f0-9-]{36}$/;function q(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}export function claudeDesktopUserDataDir(){const e=process.env.CLAUDE_USER_DATA_DIR?.trim();if(e)return e;const o=A(),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}),b(n),v(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===z&&W.test(e.id))}const re={opus:0,fable:1,sonnet:2,haiku:3};function se(e){let t=/^claude-(opus|sonnet|haiku|fable)-(\d+(?:-\d+)*)/i.exec(e);return t?{family:t[1].toLowerCase(),version:t[2].split("-").map(Number)}:(t=/^claude-(\d+(?:-\d+)*)-(opus|sonnet|haiku)/i.exec(e),t?{family:t[2].toLowerCase(),version:t[1].split("-").map(Number)}:null)}export function humanizeModelId(e){const t=se(e);return t?`${t.family[0].toUpperCase()+t.family.slice(1)} ${t.version.filter(e=>e<1e7).slice(0,2).join(".")}`:e}function ie(e){return se(e)?.family}export function buildInferenceModels(e,t){const{primary: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=!1,de=null,ue=null,pe=null;function fe(e){return{inferenceProvider:"gateway",inferenceCredentialKind:"static",inferenceGatewayBaseUrl:(e.baseUrl||"").trim().replace(/\/+$/,""),inferenceGatewayApiKey:e.apiKey,...e.catalog?.desktopDiscovery?{}:{inferenceModels:buildInferenceModels(e.models,e.catalog)},disableDeploymentModeChooser:!1!==e.settings?.hide_official_login,chatTabEnabled:!0,chatAdvancedFileAnalysisEnabled:!0,autoModeEnabled:!0,coworkEgressAllowedHosts:["*"],disableEssentialTelemetry:!0,disableNonessentialTelemetry:!0,disableNonessentialServices:!1}}const me={defaultModelEffort:"medium",modelPrefer1mContext:!0,skipWebFetchPreflight:!0,toolSearchEnabled:!0,builtinBrowserEnabled:!0,isDesktopExtensionEnabled:!0,sshHostAllowlist:["*"],claudeAiImport:{enabled:!0,automatic3pImport:!0,exportEnabled:!0},coworkVmIpv6Enabled:!0,mcpToolTimeoutSec:3600,updateViaUpdatesHost:!0,banner:{enabled:!1}},ge=()=>{if(_("TEST_HOME")?.trim())return null;const e=g();return e?r(e):null};let ye=ge,he=null;export function setDesktopAsarForTests(e){ye=void 0===e?ge:()=>e,he=null}function ke(){if(he)return he;let e=null;try{e=ye()}catch(e){p.logError("claude-desktop.unsupportedDefaults",e)}return he=new Set(e?Object.keys(me).filter(t=>!e.includes(t)):[]),he}function _e(e){const t=ke();return Object.fromEntries(Object.entries(me).filter(([o])=>!e(o)&&!t.has(o)))}function we(e){const t={..._e(t=>t in e),...e};for(const e of ke())e in t&&JSON.stringify(t[e])===JSON.stringify(me[e])&&delete t[e];return t}const De="SOFTWARE\\Policies\\Claude",be=`HKCU\\${De}`,ve="HKLM\\SOFTWARE\\Policies\\Claude",Ae=`${w}-claude-policy.reg`,Me=e=>c("reg",e,{stdio:["ignore","pipe","pipe"]}).toString();let Ce=Me;export function setRegRunnerForTests(e){Ce=e??Me}function Ee(){return"win32"===process.platform}function Oe(e){let t;try{t=Ce(["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 Se(){if(null===Oe(be))return;const e=l(claudeDesktopUserDataDir(),Ae);try{t(i(e))||o(i(e),{recursive:!0,mode:448}),b(e),Ce(["export",be,e,"/y"])}catch(e){p.logError("claude-desktop.snapshotPolicy",e)}}function xe(e){Se();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)];Ce(["add",be,"/v",t,"/t",e,"/d",n,"/f"])}}function je(e){const t=Oe(be);if(!t)return;Se();let o=t.size;for(const n of e)t.has(n)&&(Ce(["delete",be,"/v",n,"/f"]),o-=1);o<=0&&Ce(["delete",be,"/f"])}function Pe(){const e=!Boolean(_("TEST_HOME")?.trim())&&process.env.LOCALAPPDATA?process.env.LOCALAPPDATA:l(A(),"AppData","Local");return!!t(l(e,"AnthropicClaude"))||j.some(o=>t(l(e,"Packages",o,"LocalCache","Local","Claude-3p")))}const Ie=[...Object.keys(fe({apiKey:"",baseUrl:"",models:{haiku:"",sonnet:"",opus:"",reasoning:""}})),...Object.keys(me)];function Le(e){const{inferenceModels:t,...o}=e;return o}function Te(e){if(!e||!Ie.some(t=>e.has(t)))return"none";const t=e.get("inferenceGatewayApiKey")?.trim();return U(e.get("inferenceGatewayBaseUrl"))||t&&G().includes(t)?"ours":"foreign"}function Ne(){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 $e(e){return"mode"===e.kind?y.t("tools.claude_desktop.current_official"):y.t("tools.claude_desktop.current_entry",{name:e.name})}let Ge=null,Ue=null;export function detectManagedConfig(){try{if("darwin"===process.platform){let e="";try{e=d().username}catch{}return[e?`/Library/Managed Preferences/${e}/com.anthropic.claudefordesktop.plist`:"","/Library/Managed Preferences/com.anthropic.claudefordesktop.plist"].filter(Boolean).find(e=>t(e))??null}if("win32"===process.platform)return Oe(ve)?ve:null;const e="/etc/claude-desktop/managed-settings.json";return t(e)?e:null}catch(e){return p.logError("claude-desktop.detectManagedConfig",e),null}}function Ke(){const e=A();let 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 Re=/\d+\.\d+\.\d+/;function Fe(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 Be(){if("darwin"===process.platform){for(const e of["/Applications/Claude.app",l(A(),"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?Re.exec(n[1])?.[0]:void 0;if(s)return s}return null}if("win32"===process.platform){const e=l(process.env.LOCALAPPDATA||l(A(),"AppData","Local"),"AnthropicClaude");if(t(e)){const t=n(e).map(e=>/^app-(\d+\.\d+\.\d+)$/.exec(e)?.[1]).filter(e=>!!e);if(t.length>0)return Fe(t)}const o=j.map(e=>`'${e}'`).join(",");return Fe(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=>Re.exec(e)?.[0]??[]))}if("linux"===process.platform)try{const e=c("dpkg-query",["-W","-f=${Version}","claude-desktop"],{encoding:"utf-8",timeout:5e3,stdio:["ignore","pipe","ignore"]});return Re.exec(e)?.[0]??null}catch{return null}return null}const He="darwin"===process.platform?"open -a Claude":"win32"===process.platform?"Claude":"claude-desktop",Je="darwin"!==process.platform&&"win32"!==process.platform||!k().installMirror?.claudeDesktop?"https://claude.ai/download":D(k().installMirror.claudeDesktop),Ve="darwin"===process.platform?`open ${Je}`:"win32"===process.platform?`start ${Je}`:`xdg-open ${Je}`;export const claudeDesktopAdapter={name:"claude-desktop",displayName:"Claude Desktop",command:He,installCommand:Ve,configPath:Z(),sessions:{format:H,files:()=>J(l(claudeDesktopUserDataDir(),"local-agent-mode-sessions"))},isInstalled:Ke,installedVersion:Be,prepareRuntime:async function(){if(!["win32","darwin","linux"].includes(process.platform)||!Ke())return[];const e=Date.now();try{const t=await m({userDataDir:claudeDesktopUserDataDir(),onDownload:e=>console.log(u.gray(" "+y.t("tools.claude_desktop.code_cli_downloading",{version:e}))),onStart:(e,t)=>f("desktop-code-cli","start",{detail:{version:e,source:t}}),desktopVersion:"darwin"===process.platform?Be():null,mirror:k().installMirror?.claudeDesktop??null});return f("desktop-code-cli","skipped"===t.status?"skip":"ok",{duration_ms:Date.now()-e,detail:{...t}}),"installed"!==t.status?[]:[{kind:"summary",text:y.t("tools.claude_desktop.code_cli_installed",{version:t.version})}]}catch(t){return p.logError("claude-desktop.prepareCodeTabCli",t),f("desktop-code-cli","fail",{duration_ms:Date.now()-e,error:t}),[{kind:"action",text:y.t("tools.claude_desktop.code_cli_failed",{reason:t instanceof Error?t.message:String(t)})}]}},runningApp:M()?{isRunning:E,restart:x,quit:S,quitRefused:C,launch:O}:void 0,appInstaller:{vendor:"Anthropic",sizeMb:()=>300,downloadPage:"https://claude.ai/download",blocker:P,latestVersion:()=>I(),installedPath(){if("darwin"===process.platform)return L();if("win32"!==process.platform)return null;try{return Be()?"MSIX":null}catch(e){return p.logError("claude-desktop.installedPath",e),null}},install:e=>T(e)},wantsModelCatalog:!0,loadPrivateConfig(e){const t=oe()??{appliedId:"",entries:[]};let o=ne(t);o||(o={id:a(),name:z},t.entries.push(o));const n=fe(e);K(String(n.inferenceGatewayBaseUrl)),ae=!0===n.disableDeploymentModeChooser;const r=!0===e.catalog?.desktopDiscovery;le=r?null:{models:n.inferenceModels,source:e.catalog?e.catalog.oneMillionSource:"slots",groups:e.catalog?.matchedGroups??[]},ce=r;const s={...we(ee(Y(o.id))??{}),...n};te(Y(o.id),r?Le(s):s);const i=Ne();Ge=i&&!e.takeOver?$e(i):null,Ge||(t.appliedId=o.id),te(Z(),t);const l=ee(Q())??{};Ge||"3p"===l.deploymentMode||te(Q(),{...l,deploymentMode:"3p"}),ue=null,pe=null,de=null,Ue=null;const c=!0===e.settings?.force_registry,d=Ee()?Oe(be):null;if(Ee()&&"foreign"===Te(d)&&!c)Ue=d?.get("inferenceGatewayBaseUrl")||be;else if(Ee()){const t=Oe(be),o=Ie.filter(e=>t?.has(e)),s={..._e(e=>t?.has(e)??!1),...n},i=!0===e.settings?.force_registry,l=!i&&Pe(),a=r&&!l&&(t?.has("inferenceModels")??!1);try{l?je(Ie):xe(s),a&&je(["inferenceModels"]),de=l?"removed":"written"}catch(e){p.logError("claude-desktop.policy",e),ue=e instanceof Error?e.message.trim():String(e),(o.length>0||i)&&(pe=l?{action:"remove",values:Object.fromEntries(o.map(e=>[e,null])),deleteKey:o.length===t.size}:{action:"write",values:{...s,...a?{inferenceModels:null}:{}},deleteKey:!1})}}},pendingElevation(){const e=pe;return e?{prompt:y.t(`tools.claude_desktop.elevate_${e.action}`),run:()=>{if(!N(De,e.values,e.deleteKey))return!1;const t=Oe(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&&(pe=null,ue=null),o}}:null},unloadPrivateConfig(){if(Ee()&&"ours"===Te(Oe(be)))try{je(Ie)}catch(e){p.logError("claude-desktop.removePolicy",e)}const e=oe(),t=ne(e);if(!e||!t)return;b(Y(t.id)),s(Y(t.id),{force:!0});const o=e.entries.filter(e=>e.id!==t.id);0===o.length?(b(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;if(e.catalog?.desktopDiscovery)return void function(e,t,o){const n=Le(we(e));JSON.stringify(n)!==JSON.stringify(e)&&te(Y(t),n),pe=null;const r=Ee()?Oe(be):null,s=!0===o.settings?.force_registry;if(!r?.has("inferenceModels")||"foreign"===Te(r)&&!s)return;const i=!s&&Pe()?Ie.filter(e=>r.has(e)):["inferenceModels"];try{je(i)}catch(e){throw p.logError("claude-desktop.unpinModelMenu registry",e),pe={action:"remove",values:Object.fromEntries(i.map(e=>[e,null])),deleteKey:i.length===r.size},new $(y.t("tools.claude_desktop.refresh_needs_admin"))}}(n,o.id,e);const r=buildInferenceModels(e.models,e.catalog),s=JSON.stringify(n.inferenceModels)!==JSON.stringify(r),i={...we(n),inferenceModels:r},l=JSON.stringify(i)!==JSON.stringify(n);pe=null;const a=Ee()?Oe(be):null,c="foreign"===Te(a)&&!0!==e.settings?.force_registry;if(!a?.has("inferenceModels")||c)return void(l&&te(Y(o.id),i));const d=Ie.filter(e=>a.has(e)),u=!0!==e.settings?.force_registry&&Pe();if(l&&te(Y(o.id),i),u||s)try{u?je(Ie):xe({inferenceModels:r})}catch(e){throw p.logError("claude-desktop.refreshModelMenu registry",e),pe=u?{action:"remove",values:Object.fromEntries(d.map(e=>[e,null])),deleteKey:d.length===a.size}:{action:"write",values:{inferenceModels:r},deleteKey:!1},new $(y.t("tools.claude_desktop.refresh_needs_admin"))}},detectCurrentConfig(){try{if(Ee()){const e=Oe(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(Oe(be)??[])}:{}}}catch(e){return p.logError("claude-desktop.getConfig",e),null}},clearPinnedModels(){let e=!1;Ee()&&Oe(be)?.has("inferenceModels")&&(Se(),Ce(["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(" / ")})})}ce&&e.push({kind:"summary",text:y.t("tools.claude_desktop.models_from_gateway")}),null!==ae&&e.push({kind:"detail",text:y.t(ae?"tools.claude_desktop.official_login_hidden":"tools.claude_desktop.official_login_shown")}),M()&&!E()||e.push({kind:"action",text:y.t("tools.claude_desktop.restart_hint")}),pe?(e.push({kind:"action",text:y.t(`tools.claude_desktop.policy_stale_${pe.action}`)}),e.push({kind:"detail",text:ue??""})):ue?(e.push({kind:"detail",text:y.t("tools.claude_desktop.registry_denied")}),e.push({kind:"detail",text:ue})):Ee()&&de&&e.push({kind:"detail",text:y.t(`tools.claude_desktop.registry_${de}`,{key:be})}),Ge&&e.push({kind:"action",text:y.t("tools.claude_desktop.not_switched",{current:Ge})}),Ue&&e.push({kind:"action",text:y.t("tools.claude_desktop.foreign_policy",{key:be,url:Ue})});const t=detectManagedConfig();return t&&e.push({kind:"action",text:y.t("tools.claude_desktop.managed_conflict",{path:t})}),e},planNotes(){const e=[],t=Ne();if(t&&e.push(y.t("tools.claude_desktop.plan_switch",{current:$e(t)})),Ee()){const t=Oe(be);"foreign"===Te(t)&&e.push(y.t("tools.claude_desktop.plan_foreign_policy",{key:be,url:t?.get("inferenceGatewayBaseUrl")||"-"}))}return e},forceResetPaths(){const e=[Z(),Q()];try{const t=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 v}from"./backup.js";import{toolHome as A}from"./types.js";import{canRestartDesktop as E,desktopQuitRefused as M,isDesktopRunning as C,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 N}from"./elevated-reg.js";import{UserActionNeeded as $}from"./types.js";import{savedApiKeys as G}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 H}from"../model-registry.js";import{claudeFormat as B,nestedClaudeProjectFiles as J}from"../sessions/formats.js";import{powerShellEnv as z}from"../powershell-env.js";const V=h;export const CLAUDE_DESKTOP_HIDE_OFFICIAL_LOGIN_SETTING="hide_official_login";export const CLAUDE_DESKTOP_FORCE_REGISTRY_SETTING="force_registry";const W=/^[a-f0-9-]{36}$/;function q(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}export function claudeDesktopUserDataDir(){const e=process.env.CLAUDE_USER_DATA_DIR?.trim();if(e)return e;const o=A(),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),v(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===V&&W.test(e.id))}const re={opus:0,fable:1,sonnet:2,haiku:3};function se(e){let t=/^claude-(opus|sonnet|haiku|fable)-(\d+(?:-\d+)*)/i.exec(e);return t?{family:t[1].toLowerCase(),version:t[2].split("-").map(Number)}:(t=/^claude-(\d+(?:-\d+)*)-(opus|sonnet|haiku)/i.exec(e),t?{family:t[2].toLowerCase(),version:t[1].split("-").map(Number)}:null)}export function humanizeModelId(e){const t=se(e);return t?`${t.family[0].toUpperCase()+t.family.slice(1)} ${t.version.filter(e=>e<1e7).slice(0,2).join(".")}`:e}function ie(e){return se(e)?.family}export function buildInferenceModels(e,t){const{primary: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(H()).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=!1,de=null,ue=null,pe=null;function fe(e){return{inferenceProvider:"gateway",inferenceCredentialKind:"static",inferenceGatewayBaseUrl:(e.baseUrl||"").trim().replace(/\/+$/,""),inferenceGatewayApiKey:e.apiKey,...e.catalog?.desktopDiscovery?{}:{inferenceModels:buildInferenceModels(e.models,e.catalog)},disableDeploymentModeChooser:!1!==e.settings?.hide_official_login,chatTabEnabled:!0,chatAdvancedFileAnalysisEnabled:!0,autoModeEnabled:!0,coworkEgressAllowedHosts:["*"],disableEssentialTelemetry:!0,disableNonessentialTelemetry:!0,disableNonessentialServices:!1}}const me={defaultModelEffort:"medium",modelPrefer1mContext:!0,skipWebFetchPreflight:!0,toolSearchEnabled:!0,builtinBrowserEnabled:!0,isDesktopExtensionEnabled:!0,sshHostAllowlist:["*"],claudeAiImport:{enabled:!0,automatic3pImport:!0,exportEnabled:!0},coworkVmIpv6Enabled:!0,mcpToolTimeoutSec:3600,updateViaUpdatesHost:!0,banner:{enabled:!1}},ge=()=>{if(_("TEST_HOME")?.trim())return null;const e=g();return e?r(e):null};let ye=ge,he=null;export function setDesktopAsarForTests(e){ye=void 0===e?ge:()=>e,he=null}function ke(){if(he)return he;let e=null;try{e=ye()}catch(e){p.logError("claude-desktop.unsupportedDefaults",e)}return he=new Set(e?Object.keys(me).filter(t=>!e.includes(t)):[]),he}function _e(e){const t=ke();return Object.fromEntries(Object.entries(me).filter(([o])=>!e(o)&&!t.has(o)))}function we(e){const t={..._e(t=>t in e),...e};for(const e of ke())e in t&&JSON.stringify(t[e])===JSON.stringify(me[e])&&delete t[e];return t}const be="SOFTWARE\\Policies\\Claude",De=`HKCU\\${be}`,ve="HKLM\\SOFTWARE\\Policies\\Claude",Ae=`${w}-claude-policy.reg`,Ee=e=>c("reg",e,{stdio:["ignore","pipe","pipe"]}).toString();let Me=Ee;export function setRegRunnerForTests(e){Me=e??Ee}function Ce(){return"win32"===process.platform}function Oe(e){let t;try{t=Me(["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 Se(){if(null===Oe(De))return;const e=l(claudeDesktopUserDataDir(),Ae);try{t(i(e))||o(i(e),{recursive:!0,mode:448}),D(e),Me(["export",De,e,"/y"])}catch(e){p.logError("claude-desktop.snapshotPolicy",e)}}function xe(e){Se();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)];Me(["add",De,"/v",t,"/t",e,"/d",n,"/f"])}}function je(e){const t=Oe(De);if(!t)return;Se();let o=t.size;for(const n of e)t.has(n)&&(Me(["delete",De,"/v",n,"/f"]),o-=1);o<=0&&Me(["delete",De,"/f"])}function Pe(){const e=!Boolean(_("TEST_HOME")?.trim())&&process.env.LOCALAPPDATA?process.env.LOCALAPPDATA:l(A(),"AppData","Local");return!!t(l(e,"AnthropicClaude"))||j.some(o=>t(l(e,"Packages",o,"LocalCache","Local","Claude-3p")))}const Ie=[...Object.keys(fe({apiKey:"",baseUrl:"",models:{haiku:"",sonnet:"",opus:"",reasoning:""}})),...Object.keys(me)];function Le(e){const{inferenceModels:t,...o}=e;return o}function Te(e){if(!e||!Ie.some(t=>e.has(t)))return"none";const t=e.get("inferenceGatewayApiKey")?.trim();return U(e.get("inferenceGatewayBaseUrl"))||t&&G().includes(t)?"ours":"foreign"}function Ne(){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 $e(e){return"mode"===e.kind?y.t("tools.claude_desktop.current_official"):y.t("tools.claude_desktop.current_entry",{name:e.name})}let Ge=null,Ue=null;export function detectManagedConfig(){try{if("darwin"===process.platform){let e="";try{e=d().username}catch{}return[e?`/Library/Managed Preferences/${e}/com.anthropic.claudefordesktop.plist`:"","/Library/Managed Preferences/com.anthropic.claudefordesktop.plist"].filter(Boolean).find(e=>t(e))??null}if("win32"===process.platform)return Oe(ve)?ve:null;const e="/etc/claude-desktop/managed-settings.json";return t(e)?e:null}catch(e){return p.logError("claude-desktop.detectManagedConfig",e),null}}function Ke(){const e=A();let 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 Re=/\d+\.\d+\.\d+/;function Fe(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 He(){if("darwin"===process.platform){for(const e of["/Applications/Claude.app",l(A(),"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?Re.exec(n[1])?.[0]:void 0;if(s)return s}return null}if("win32"===process.platform){const e=l(process.env.LOCALAPPDATA||l(A(),"AppData","Local"),"AnthropicClaude");if(t(e)){const t=n(e).map(e=>/^app-(\d+\.\d+\.\d+)$/.exec(e)?.[1]).filter(e=>!!e);if(t.length>0)return Fe(t)}const o=j.map(e=>`'${e}'`).join(",");return Fe(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:z()}).split(/\r?\n/).flatMap(e=>Re.exec(e)?.[0]??[]))}if("linux"===process.platform)try{const e=c("dpkg-query",["-W","-f=${Version}","claude-desktop"],{encoding:"utf-8",timeout:5e3,stdio:["ignore","pipe","ignore"]});return Re.exec(e)?.[0]??null}catch{return null}return null}const Be="darwin"===process.platform?"open -a Claude":"win32"===process.platform?"Claude":"claude-desktop",Je="darwin"!==process.platform&&"win32"!==process.platform||!k().installMirror?.claudeDesktop?"https://claude.ai/download":b(k().installMirror.claudeDesktop),ze="darwin"===process.platform?`open ${Je}`:"win32"===process.platform?`start ${Je}`:`xdg-open ${Je}`;export const claudeDesktopAdapter={name:"claude-desktop",displayName:"Claude Desktop",command:Be,installCommand:ze,configPath:Z(),sessions:{format:B,files:()=>J(l(claudeDesktopUserDataDir(),"local-agent-mode-sessions"))},isInstalled:Ke,installedVersion:He,prepareRuntime:async function(){if(!["win32","darwin","linux"].includes(process.platform)||!Ke())return[];const e=Date.now();try{const t=await m({userDataDir:claudeDesktopUserDataDir(),onDownload:e=>console.log(u.gray(" "+y.t("tools.claude_desktop.code_cli_downloading",{version:e}))),onStart:(e,t)=>f("desktop-code-cli","start",{detail:{version:e,source:t}}),desktopVersion:"darwin"===process.platform?He():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:E()?{isRunning:C,restart:x,quit:S,quitRefused:M,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 He()?"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:V},t.entries.push(o));const n=fe(e);K(String(n.inferenceGatewayBaseUrl)),ae=!0===n.disableDeploymentModeChooser;const r=!0===e.catalog?.desktopDiscovery;le=r?null:{models:n.inferenceModels,source:e.catalog?e.catalog.oneMillionSource:"slots",groups:e.catalog?.matchedGroups??[]},ce=r;const s={...we(ee(Y(o.id))??{}),...n};te(Y(o.id),r?Le(s):s);const i=Ne();Ge=i&&!e.takeOver?$e(i):null,Ge||(t.appliedId=o.id),te(Z(),t);const l=ee(Q())??{};Ge||"3p"===l.deploymentMode||te(Q(),{...l,deploymentMode:"3p"}),ue=null,pe=null,de=null,Ue=null;const c=!0===e.settings?.force_registry,d=Ce()?Oe(De):null;if(Ce()&&"foreign"===Te(d)&&!c)Ue=d?.get("inferenceGatewayBaseUrl")||De;else if(Ce()){const t=Oe(De),o=Ie.filter(e=>t?.has(e)),s={..._e(e=>t?.has(e)??!1),...n},i=!0===e.settings?.force_registry,l=!i&&Pe(),a=r&&!l&&(t?.has("inferenceModels")??!1);try{l?je(Ie):xe(s),a&&je(["inferenceModels"]),de=l?"removed":"written"}catch(e){p.logError("claude-desktop.policy",e),ue=e instanceof Error?e.message.trim():String(e),(o.length>0||i)&&(pe=l?{action:"remove",values:Object.fromEntries(o.map(e=>[e,null])),deleteKey:o.length===t.size}:{action:"write",values:{...s,...a?{inferenceModels:null}:{}},deleteKey:!1})}}},pendingElevation(){const e=pe;if(!e)return null;const t="unload"===e.action;return{prompt:y.t(`tools.claude_desktop.elevate_${e.action}`),...t?{failedHint:y.t("tools.claude_desktop.unload_elevation_failed"),skippedHint:y.t("tools.claude_desktop.unload_elevation_skipped")}:{},run:()=>{if(!N(be,e.values,e.deleteKey))return!1;const t=Oe(De),o="write"!==e.action?Object.keys(e.values).every(e=>!t?.has(e)):Object.keys(e.values).every(e=>t?.has(e));return o&&(pe=null,ue=null),o}}},unloadPrivateConfig(){pe=null;const e=Ce()?Oe(De):null;if(e&&"ours"===Te(e))try{je(Ie)}catch(t){p.logError("claude-desktop.removePolicy",t);const o=Ie.filter(t=>e.has(t));pe={action:"unload",values:Object.fromEntries(o.map(e=>[e,null])),deleteKey:o.length===e.size}}const t=oe(),o=ne(t);if(!t||!o)return;D(Y(o.id)),s(Y(o.id),{force:!0});const n=t.entries.filter(e=>e.id!==o.id);0===n.length?(D(Z()),s(Z(),{force:!0})):te(Z(),{...t,entries:n,appliedId:t.appliedId===o.id?n[0].id:t.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;if(e.catalog?.desktopDiscovery)return void function(e,t,o){const n=Le(we(e));JSON.stringify(n)!==JSON.stringify(e)&&te(Y(t),n),pe=null;const r=Ce()?Oe(De):null,s=!0===o.settings?.force_registry;if(!r?.has("inferenceModels")||"foreign"===Te(r)&&!s)return;const i=!s&&Pe()?Ie.filter(e=>r.has(e)):["inferenceModels"];try{je(i)}catch(e){throw p.logError("claude-desktop.unpinModelMenu registry",e),pe={action:"remove",values:Object.fromEntries(i.map(e=>[e,null])),deleteKey:i.length===r.size},new $(y.t("tools.claude_desktop.refresh_needs_admin"))}}(n,o.id,e);const r=buildInferenceModels(e.models,e.catalog),s=JSON.stringify(n.inferenceModels)!==JSON.stringify(r),i={...we(n),inferenceModels:r},l=JSON.stringify(i)!==JSON.stringify(n);pe=null;const a=Ce()?Oe(De):null,c="foreign"===Te(a)&&!0!==e.settings?.force_registry;if(!a?.has("inferenceModels")||c)return void(l&&te(Y(o.id),i));const d=Ie.filter(e=>a.has(e)),u=!0!==e.settings?.force_registry&&Pe();if(l&&te(Y(o.id),i),u||s)try{u?je(Ie):xe({inferenceModels:r})}catch(e){throw p.logError("claude-desktop.refreshModelMenu registry",e),pe=u?{action:"remove",values:Object.fromEntries(d.map(e=>[e,null])),deleteKey:d.length===a.size}:{action:"write",values:{inferenceModels:r},deleteKey:!1},new $(y.t("tools.claude_desktop.refresh_needs_admin"))}},detectCurrentConfig(){try{if(Ce()){const e=Oe(De)?.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()),...Ce()?{policy:Object.fromEntries(Oe(De)??[])}:{}}}catch(e){return p.logError("claude-desktop.getConfig",e),null}},clearPinnedModels(){let e=!1;Ce()&&Oe(De)?.has("inferenceModels")&&(Se(),Me(["delete",De,"/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(" / ")})})}ce&&e.push({kind:"summary",text:y.t("tools.claude_desktop.models_from_gateway")}),null!==ae&&e.push({kind:"detail",text:y.t(ae?"tools.claude_desktop.official_login_hidden":"tools.claude_desktop.official_login_shown")}),E()&&!C()||e.push({kind:"action",text:y.t("tools.claude_desktop.restart_hint")}),pe?(e.push({kind:"action",text:y.t(`tools.claude_desktop.policy_stale_${pe.action}`)}),e.push({kind:"detail",text:ue??""})):ue?(e.push({kind:"detail",text:y.t("tools.claude_desktop.registry_denied")}),e.push({kind:"detail",text:ue})):Ce()&&de&&e.push({kind:"detail",text:y.t(`tools.claude_desktop.registry_${de}`,{key:De})}),Ge&&e.push({kind:"action",text:y.t("tools.claude_desktop.not_switched",{current:Ge})}),Ue&&e.push({kind:"action",text:y.t("tools.claude_desktop.foreign_policy",{key:De,url:Ue})});const t=detectManagedConfig();return t&&e.push({kind:"action",text:y.t("tools.claude_desktop.managed_conflict",{path:t})}),e},planNotes(){const e=[],t=Ne();if(t&&e.push(y.t("tools.claude_desktop.plan_switch",{current:$e(t)})),Ce()){const t=Oe(De);"foreign"===Te(t)&&e.push(y.t("tools.claude_desktop.plan_foreign_policy",{key:De,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()];Ce()&&e.push(l(claudeDesktopUserDataDir(),Ae));try{const t=ne(oe());t&&e.push(Y(t.id))}catch{}return e}};
@@ -161,10 +161,13 @@ export interface ToolAdapter {
161
161
  }): void;
162
162
  /**
163
163
  * A change the last apply could not make without an administrator (one UAC
164
- * prompt fixes it); setup and the wizard offer to run it. Null when none.
164
+ * prompt fixes it); setup, the wizard and `config <tool> remove` offer to run it. Null when none.
165
+ * `failedHint` / `skippedHint` replace the generic next step when it is not "rerun setup / refresh".
165
166
  */
166
167
  pendingElevation?(): {
167
168
  prompt: string;
169
+ failedHint?: string;
170
+ skippedHint?: string;
168
171
  run(): boolean;
169
172
  } | null;
170
173
  /**
@@ -1 +1 @@
1
- import e from"inquirer";import t from"chalk";import a from"ora";import{configManager as o,DEFAULT_MODELS as i}from"./config.js";import{getPresets as n,resolvePreset as r,getToolDefaultModel as s}from"./model-registry.js";import{toolManager as l,SUPPORTED_TOOLS as c}from"./tool-manager.js";import{confirmWritePlan as d}from"./write-plan.js";import{postApplyPrompts as p}from"./post-apply.js";import{appStatus as m,appStatusText as u,appTools as _,appsForTools as g,cachedAppStatus as w,upgradeApp as f}from"./app-update.js";import{i18n as y,detectSystemLang as h}from"./i18n.js";import{createBorderLine as z,createContentLine as v}from"../utils/string-width.js";import{validateApiKey as k,fetchModels as x}from"./api-validator.js";import{CODEX_ONE_MILLION_CONTEXT_SETTING as b}from"./tools/codex.js";import{CLAUDE_DESKTOP_HIDE_OFFICIAL_LOGIN_SETTING as S}from"./tools/claude-desktop.js";import{addressesWithCurrent as C,ensureReachableGatewayAddress as M,moveOtherToolsAfterFallback as T,toolsWeConfigured as A,fastestIndex as K,probeAll as N,probeSummary as B,reasonText as O,savedApiKey as P,switchGatewayAddress as W}from"../commands/base.js";import{readFileSync as j}from"fs";import{dirname as H,join as L}from"path";import{fileURLToPath as $}from"url";import{brand as F}from"./brand.js";const I=H($(import.meta.url)),E=t.hex("#FF8700");export class Wizard{static instance;BOX_WIDTH=63;validatedApiKeys=new Set;constructor(){}static getInstance(){return Wizard.instance||(Wizard.instance=new Wizard),Wizard.instance}createBox(e){console.log(E.bold("\n"+z("╔","╗","═",this.BOX_WIDTH))),console.log(E.bold(v(e,"║","║",this.BOX_WIDTH,"center"))),console.log(E.bold(z("╚","╝","═",this.BOX_WIDTH))),console.log("")}showOperationHints(){const e=[t.gray(y.t("wizard.hint_navigate")),t.gray(y.t("wizard.hint_confirm"))];console.log(t.gray("💡 ")+e.join(t.gray(" | "))+"\n")}async promptWithHints(t){this.showOperationHints();const a=t.map(e=>"list"!==e.type||e.pageSize?e:{...e,pageSize:20});return e.prompt(a)}printBanner(){const e=60,t=y.t("wizard.banner_subtitle"),a=v(t,"║","║",e,"center"),o=v("","║","║",e,"center"),i=v(`${F().productName} v${function(){try{return JSON.parse(j(L(I,"..","..","package.json"),"utf-8")).version}catch{return"0.0.0"}}()}`,"║","║",e,"center"),n=[String.raw`__ ___ _ ____ _ ___ `,String.raw`\ \ / (_) |__ ___ / ___| | |_ _|`,String.raw` \ \ / /| | '_ \ / _ \ | | | | | `,String.raw` \ V / | | |_) | __/ |___| |___ | | `,String.raw` \_/ |_|_.__/ \___|\____|_____|___|`],r=Math.max(...n.map(e=>e.length)),s=" ".repeat(Math.floor((58-r)/2)),l=n.map(t=>v(s+t,"║","║",e,"left")),c=[z("╔","╗","═",e),o,...l,o,i,a,z("╚","╝","═",e)];console.log(E.bold("\n"+c.join("\n")))}resetScreen(){console.clear(),this.printBanner()}printGoodbye(){const e=l.getSupportedTools().filter(e=>{if(e.gui)return!1;try{return Boolean(l.detectCurrentConfig(e.name).apiKey)&&l.isToolInstalled(e.name)}catch{return!1}});let a;if(e.length>0){const t=e.map(e=>e.command).join(" / ");a=y.t("wizard.goodbye_message_tools",{commands:t}),e.some(e=>"claude-code"===e.name)&&(a+=" "+y.t("wizard.goodbye_claude_hint"))}else a=y.t("wizard.goodbye_message");console.log(t.green("\n👋 "+a)),this.printPathReloadHint(e.map(e=>e.name))}printPathReloadHint(e){const a=e.filter(e=>!l.isOnPath(e));if(0===a.length)return;const o=a.map(e=>c[e].command).join(" / ");console.log(t.yellow(" ! "+y.t("win32"===process.platform?"setup.path_reload_windows":"setup.path_reload",{commands:o})))}async runFirstTimeSetup(){const e="zh_CN"===h();if(e&&(o.setLang("zh_CN"),y.setLocale("zh_CN")),this.resetScreen(),console.log(E.bold("\n"+y.t("wizard.welcome"))),console.log(t.gray(y.t("wizard.privacy_note")+"\n")),e?console.log(t.gray(y.t("wizard.lang_auto_zh")+"\n")):await this.configLanguage(),await M()){const e=A();e.length>0&&await d(e.map(e=>e.tool))&&await p(await T(e))}await this.configApiKey()&&await this.selectAndConfigureTool(!0)}async configLanguage(){for(;;){this.resetScreen(),this.createBox(y.t("wizard.select_language"));const a=y.getLocale(),{language:i}=await this.promptWithHints([{type:"list",name:"language",message:"✨ "+y.t("wizard.select_language"),choices:[{name:"[EN] English"+("en_US"===a?t.green(" ✓ ("+y.t("wizard.current_active")+")"):""),value:"en_US"},{name:"[CN] 中文"+("zh_CN"===a?t.green(" ✓ ("+y.t("wizard.current_active")+")"):""),value:"zh_CN"},new e.Separator,{name:"<- "+y.t("wizard.nav_return"),value:"back"},{name:"x "+y.t("wizard.nav_exit"),value:"exit"}],default:"zh_CN"}]);if("exit"===i)this.printGoodbye(),process.exit(0);else if("back"===i)return;return o.setLang(i),void y.setLocale(i)}}buildPresetChoices(){const a=n(),o=a.filter(e=>e.recommended),i=a.filter(e=>!e.recommended),r=e=>({name:(y.t(e.name)!==e.name?y.t(e.name):e.name)+(e.models?t.gray(` [H:${e.models.haiku} S:${e.models.sonnet} O:${e.models.opus}]`):""),value:{type:"preset",preset:e}}),s=[];return o.length>0&&(s.push(new e.Separator(t.hex("#FF8700")("── "+y.t("wizard.recommended")+" ──"))),s.push(...o.map(r))),i.length>0&&(s.push(new e.Separator(t.gray("── "+y.t("wizard.other_models")+" ──"))),s.push(...i.map(r))),s}async handleCustomModelInput(){const a=o.getModels(),{customMode:n}=await e.prompt([{type:"list",name:"customMode",message:y.t("wizard.custom_model_mode"),choices:[{name:y.t("wizard.custom_model_single"),value:"single"},{name:y.t("wizard.custom_model_per_role"),value:"per_role"}]}]);if("single"===n){const{customModel:t}=await e.prompt([{type:"input",name:"customModel",message:y.t("wizard.input_custom_model"),default:i.sonnet}]);o.setModels({haiku:t,sonnet:t,opus:t,reasoning:t})}else{const t=await e.prompt([{type:"input",name:"haiku",message:y.t("wizard.model_haiku"),default:a.haiku},{type:"input",name:"sonnet",message:y.t("wizard.model_sonnet"),default:a.sonnet},{type:"input",name:"opus",message:y.t("wizard.model_opus"),default:a.opus},{type:"input",name:"reasoning",message:y.t("wizard.model_reasoning"),default:a.reasoning}]);o.setModels(t)}console.log(t.green("\n✓ "+y.t("wizard.models_saved")))}async configModels(a){const i=o.getApiKey();if(await this.validatedKeyForConfiguration(i))for(;;){this.resetScreen(),this.createBox(y.t("wizard.config_models"));const i=[...this.buildPresetChoices()];i.push(new e.Separator),i.push({name:"✏️ "+y.t("wizard.custom_model_input"),value:{type:"custom_input"}}),i.push(new e.Separator),i.push({name:"<- "+y.t("wizard.nav_return"),value:{type:"back"}}),i.push({name:"x "+y.t("wizard.nav_exit"),value:{type:"exit"}});const{modelChoice:n}=await this.promptWithHints([{type:"list",name:"modelChoice",message:y.t("wizard.select_model_config"),choices:i}]);if("exit"===n.type)this.printGoodbye(),process.exit(0);else{if("back"===n.type)return;if("custom_input"===n.type)return await this.handleCustomModelInput(),void(a?.skipLoadPrompt||await this.promptLoadAfterModelConfig());if("preset"===n.type){const e=r(n.preset);return o.setModels(e),console.log(t.green("\n✓ "+y.t("wizard.models_saved"))),void(a?.skipLoadPrompt||await this.promptLoadAfterModelConfig())}}}else await e.prompt([{type:"input",name:"continue",message:y.t("wizard.press_enter")}])}async promptLoadAfterModelConfig(){const{shouldLoad:t}=await e.prompt([{type:"list",name:"shouldLoad",message:y.t("wizard.load_config_now"),choices:[{name:y.t("wizard.load_config_yes"),value:!0},{name:y.t("wizard.load_config_later"),value:!1}]}]);t&&await this.selectAndConfigureTool()}async configBaseUrl(){const i=o.getBaseUrl(),n=C(),r=a(y.t("wizard.base_testing")).start(),s=await N(n,{apiKey:P(),samples:3});r.stop();const l=K(s),c=n.map((e,a)=>{const o=e.url===i?t.cyan(` ← ${y.t("base.current_mark")}`):"";return{name:`${e.url} ${t.gray(e.label)} ${B(s[a],a===l)}${o}`,value:e.url}});c.push(new e.Separator,{name:"<- "+y.t("wizard.nav_return"),value:"__back__"});const{url:d}=await this.promptWithHints([{type:"list",name:"url",message:y.t("wizard.base_select"),choices:c,default:i}]);if("__back__"===d)return;const p=s[n.findIndex(e=>e.url===d)];p.ok?await W(d):console.log(t.red(y.t("base.unreachable",{url:d,reason:O(p)}))),await e.prompt([{type:"input",name:"continue",message:y.t("wizard.press_enter")}])}async configApiKey(){for(;;){this.resetScreen(),this.createBox(y.t("wizard.input_api_key")),console.log(t.gray("\n💡 "+y.t("wizard.api_key_input_hint"))),console.log(t.gray(" "+y.t("wizard.api_key_get_hint",{url:F().links.tokenPage}))),console.log();const{apiKey:i}=await e.prompt([{type:"password",name:"apiKey",message:y.t("wizard.input_your_api_key"),mask:"*"}]);if(!i||""===i.trim()){const{action:t}=await e.prompt([{type:"list",name:"action",message:y.t("wizard.select_action"),choices:[{name:y.t("wizard.retry_input"),value:"retry"},{name:"<- "+y.t("wizard.nav_return"),value:"back"}]}]);if("back"===t)return!1;continue}const n=a(y.t("wizard.validating_api_key")).start(),r=await k(i.trim());if(n.stop(),r.valid)return o.setApiKey(i.trim()),this.validatedApiKeys.add(i.trim()),console.log(t.green("\n✓ "+y.t("wizard.api_key_valid"))),!0;{this.validatedApiKeys.delete(i.trim()),"invalid_api_key"===r.error?console.log(t.red("\n✗ "+y.t("wizard.api_key_invalid"))):console.log(t.red("\n✗ "+y.t("wizard.api_key_network_error")));const{action:a}=await e.prompt([{type:"list",name:"action",message:y.t("wizard.select_action"),choices:[{name:y.t("wizard.retry_input"),value:"retry"},{name:"<- "+y.t("wizard.nav_return"),value:"back"}]}]);if("back"===a)return!1}}}async selectAndConfigureTool(a=!1){for(const e of _())await m(e).catch(()=>{});for(;;){this.resetScreen(),this.createBox(y.t("wizard.select_tool"));const o=l.getSupportedTools().map(e=>{const a=g([e.name]).map(e=>w(e)).find(e=>e.outdated);return{name:e.displayName+(a?t.yellow(" "+(a.tool===e.name?"":`${a.name} `)+u(a)):""),value:e.name}}),{tool:i}=await this.promptWithHints([{type:"list",name:"tool",message:"🛠️ "+y.t("wizard.select_tool"),choices:[...o,new e.Separator,{name:"<- "+y.t("wizard.nav_return"),value:"back"},{name:"x "+y.t("wizard.nav_exit"),value:"exit"}]}]);if("exit"===i)this.printGoodbye(),process.exit(0);else if("back"===i)return;await this.configureTool(i,a)}}async configureTool(a,o=!1){const i=c[a];if(i){if(!l.isToolInstalled(a)){console.log(t.yellow("\n"+y.t("wizard.tool_not_installed",{tool:i.displayName})));const{install:o}=await e.prompt([{type:"confirm",name:"install",message:y.t("wizard.install_tool_confirm"),default:!0}]);if(!o)return;try{await l.installTool(a)}catch{return void console.log(t.red(y.t("wizard.install_failed")))}}o?await this.configureToolModel(a)&&await this.loadConfig(a):await this.showToolMenu(a)}}async showToolMenu(t){for(;;){this.resetScreen();const a=c[t];if(!a)return;this.createBox(a.displayName+" "+y.t("wizard.menu_title"));const o=[{name:"📥 "+y.t("wizard.action_load_config",{tool:a.displayName}),value:"load"},{name:"📤 "+y.t("wizard.action_unload_config",{tool:a.displayName}),value:"unload"}];l.supportsClearPinnedModels(t)&&o.push({name:"🧹 "+y.t("wizard.action_clear_model",{tool:a.displayName}),value:"clear-model"});for(const e of g([t]).map(e=>w(e)).reverse()){if(e.blocker||!e.latest||!e.outdated&&e.installed)continue;const t=e.installed?y.t("wizard.action_upgrade_app",{tool:e.name,current:e.current??"?",latest:e.latest}):y.t("wizard.action_install_app",{tool:e.name,latest:e.latest});o.unshift({name:"↑ "+t,value:`upgrade-app:${e.tool}`})}o.push({name:"🧨 "+y.t("wizard.action_force_config",{tool:a.displayName}),value:"force"},{name:"↩️ "+y.t("wizard.action_restore_config",{tool:a.displayName}),value:"restore"},new e.Separator,{name:"<- "+y.t("wizard.nav_return"),value:"back"},{name:"x "+y.t("wizard.nav_exit"),value:"exit"});const{action:i}=await this.promptWithHints([{type:"list",name:"action",message:"⚙️ "+y.t("wizard.select_action"),choices:o}]);if("exit"===i)this.printGoodbye(),process.exit(0);else{if("back"===i)return;"load"===i?await this.configureToolModel(t)&&await this.loadConfig(t):"force"===i?await this.forceConfig(t):"unload"===i?await this.unloadConfig(t):"string"==typeof i&&i.startsWith("upgrade-app:")?(await f(i.slice(12),{install:!0}),await e.prompt([{type:"input",name:"continue",message:y.t("wizard.press_enter")}])):"clear-model"===i?await this.clearPinnedModels(t):"restore"===i&&await this.restoreConfig(t)}}}singleModelOverride(e){const t=e.trim();return/claude/i.test(t)?{opus:t}:{haiku:t,sonnet:t,opus:t,reasoning:t}}hasConfiguredApiKey(){return!!o.getApiKey()?.trim()||o.listToolApiKeys().some(e=>Boolean(o.getApiKeyForTool(e)?.trim()))}async validatedKeyForConfiguration(e){const o=e?.trim();if(!o)return console.log(t.red("\n"+y.t("wizard.api_key_required"))),console.log(t.yellow(y.t("wizard.please_config_api_key_first"))),null;if(this.validatedApiKeys.has(o))return o;const i=a(y.t("wizard.validating_api_key")).start(),n=await k(o);if(n.valid)return this.validatedApiKeys.add(o),i.succeed(y.t("wizard.api_key_valid")),o;this.validatedApiKeys.delete(o);const r="invalid_api_key"===n.error?y.t("wizard.api_key_invalid"):y.t("wizard.api_key_network_error");return i.fail(r),console.log(t.red("\n"+y.t("wizard.please_reconfig_api_key"))),null}async configureToolModel(i){const n=c[i];if(!n)return!1;const l=await this.validatedKeyForConfiguration(o.getApiKeyForTool(i));if(!l)return await e.prompt([{type:"input",name:"continue",message:y.t("wizard.press_enter")}]),!1;const d="claude-code"===i,p=d||"claude-desktop"===i||"agy"===i,m=s(i),u=p||!m?y.t("wizard.model_builtin_default"):m;this.resetScreen(),this.createBox(n.displayName+" · "+y.t("wizard.config_models"));const _=[{name:"✅ "+y.t("wizard.use_default_model",{model:u}),value:{type:"default"}},{name:"🌐 "+y.t("wizard.fetch_models_from_api"),value:{type:"fetch"}},...this.buildPresetChoices(),new e.Separator,{name:"✏️ "+y.t("wizard.input_custom_model"),value:{type:"custom"}},new e.Separator,{name:"<- "+y.t("wizard.nav_return"),value:{type:"back"}}],{choice:g}=await this.promptWithHints([{type:"list",name:"choice",message:y.t("wizard.select_tool_model",{tool:n.displayName}),choices:_}]);if("back"===g.type)return!1;if("default"===g.type)o.setToolModel(i,null);else if("preset"===g.type)o.setToolModel(i,r(g.preset));else if("custom"===g.type){const{model:t}=await e.prompt([{type:"input",name:"model",message:y.t("wizard.input_custom_model"),default:!p&&m?m:void 0}]),a=(t||"").trim();o.setToolModel(i,a?this.singleModelOverride(a):null)}else if("fetch"===g.type){const n=a(y.t("wizard.fetching_models")).start(),r=await x(l);let s;if(n.stop(),r.ok&&r.models.length>0){const{model:t}=await e.prompt([{type:"list",name:"model",message:y.t("wizard.select_fetched_model"),pageSize:20,choices:[...r.models,new e.Separator,{name:"<- "+y.t("wizard.nav_return"),value:"__back__"}]}]);if("__back__"===t)return!1;s=t}else{console.log(t.yellow("\n"+y.t("wizard.fetch_models_failed")));const{model:a}=await e.prompt([{type:"input",name:"model",message:y.t("wizard.input_custom_model"),default:!p&&m?m:void 0}]);s=(a||"").trim()}o.setToolModel(i,s?this.singleModelOverride(s):null)}if("codex"===i){const t=o.getToolSetting(i,b),{enableOneMillionContext:a}=await e.prompt([{type:"confirm",name:"enableOneMillionContext",message:y.t("wizard.codex_enable_1m_context"),default:!1!==t}]);o.setToolSetting(i,b,Boolean(a))}if("claude-desktop"===i){const t=o.getToolSetting(i,S),{hideOfficialLogin:a}=await e.prompt([{type:"confirm",name:"hideOfficialLogin",message:y.t("wizard.desktop_hide_official_login"),default:!1!==t}]);o.setToolSetting(i,S,Boolean(a))}return console.log(t.green("\n✓ "+y.t("wizard.models_saved"))),d&&console.log(t.gray("💡 "+y.t("wizard.claude_model_hint"))),!0}async forceConfig(t){const a=c[t]?.displayName||t,{confirm:o}=await e.prompt([{type:"confirm",name:"confirm",message:y.t("config.confirm_force",{tool:a}),default:!1}]);o&&await this.loadConfig(t,{force:!0})}async loadConfig(i,n={}){const r=o.getModelsForTool(i),s=await this.validatedKeyForConfiguration(o.getApiKeyForTool(i));if(!s)return void await e.prompt([{type:"input",name:"continue",message:y.t("wizard.press_enter")}]);if(!n.force&&!await d([i]))return;const m=a(y.t("wizard.loading_config")).start();try{await l.applyPrivateConfig(i,s,r,{...n,takeOver:!0}),m.stop(),l.printApplied(i),await p([i],{apps:{install:!1}}),n.force&&console.log(t.yellow(y.t("config.force_done",{tool:c[i]?.displayName||i,name:i})));const a=c[i];a&&!a.gui&&(l.isOnPath(i)&&console.log(t.green("\n"+y.t("wizard.run_tool_hint",{command:a.command}))),this.printPathReloadHint([i]));const{nextAction:o}=await e.prompt([{type:"list",name:"nextAction",message:y.t("wizard.what_next"),choices:[{name:y.t("wizard.exit_and_start"),value:"exit"},{name:y.t("wizard.continue_config"),value:"continue"}]}]);"exit"===o&&(this.printGoodbye(),process.exit(0))}catch(a){m.fail(y.t("wizard.config_failed")),console.log(t.red(a instanceof Error?a.message:String(a))),await e.prompt([{type:"input",name:"continue",message:y.t("wizard.press_enter")}])}}async clearPinnedModels(a){const o=c[a]?.displayName||a,{confirm:i}=await e.prompt([{type:"confirm",name:"confirm",message:y.t("wizard.confirm_clear_model",{tool:o}),default:!1}]);if(i){try{const e=await l.clearPinnedModels(a);0===e.length?console.log(t.yellow("\n"+y.t("config.clear_model_none",{tool:o}))):(console.log(t.green("\n✓ "+y.t("config.clear_model_done",{tool:o}))),e.forEach(e=>console.log(t.gray(` - ${e}`))),console.log(t.gray(y.t("config.clear_model_restart_hint",{tool:o}))))}catch(e){console.log(t.red("\n"+(e instanceof Error?e.message:String(e))))}await e.prompt([{type:"input",name:"continue",message:y.t("wizard.press_enter")}])}}async unloadConfig(o){const{confirm:i}=await e.prompt([{type:"confirm",name:"confirm",message:y.t("wizard.confirm_unload_config",{tool:c[o]?.displayName||o}),default:!1}]);if(!i)return;const n=a(y.t("wizard.unloading_config")).start();try{const a=l.holdsOurConfig(o),i=l.unloadPrivateConfig(o);if(!a)return void n.info(y.t("config.remove_nothing",{tool:c[o]?.displayName||o}));n.succeed(y.t("wizard.config_unloaded")),i.forEach(e=>console.log(t.yellow(" ! "+e.text)));const{nextAction:r}=await e.prompt([{type:"list",name:"nextAction",message:y.t("wizard.what_next"),choices:[{name:y.t("wizard.nav_exit"),value:"exit"},{name:y.t("wizard.continue_config"),value:"continue"}]}]);"exit"===r&&(this.printGoodbye(),process.exit(0))}catch(a){n.fail(y.t("wizard.config_unload_failed")),console.log(t.red(a instanceof Error?a.message:String(a))),await e.prompt([{type:"input",name:"continue",message:y.t("wizard.press_enter")}])}}async restoreConfig(o){const i=c[o]?.displayName||o,{confirm:n}=await e.prompt([{type:"confirm",name:"confirm",message:y.t("wizard.confirm_restore_config",{tool:i}),default:!1}]);if(!n)return;const r=a(y.t("wizard.restoring_config")).start();try{const e=l.restorePrivateConfig(o).filter(e=>e.result.restored);0===e.length?r.warn(y.t("wizard.restore_no_backup")):(r.succeed(y.t("wizard.config_restored",{tool:i})),e.forEach(e=>console.log(t.gray(` ${e.file} ← ${e.result.from}`))),console.log(t.yellow(" ! "+y.t("config.reopen_hint",{tool:i}))))}catch(e){r.fail(y.t("wizard.config_restore_failed")),console.log(t.red(e instanceof Error?e.message:String(e)))}await e.prompt([{type:"input",name:"continue",message:y.t("wizard.press_enter")}])}async run(){await this.showMainMenu()}async showMainMenu(){if(this.hasConfiguredApiKey())for(;;){this.resetScreen();const a=o.getApiKey()||"",i=a.length>4?"sk-****"+a.slice(-4):"****";console.log(t.gray(` 🔑 API Key: ${i}`)+t.green(" ✓")),console.log("");const n=l.getSupportedTools().map(e=>({name:"🛠️ "+e.displayName,value:{type:"tool",tool:e.name}})),r=[new e.Separator(E("── "+y.t("wizard.select_tool")+" ──")),...n,new e.Separator(t.gray("── "+y.t("wizard.settings")+" ──")),{name:"🔑 "+y.t("wizard.menu_change_api_key"),value:{type:"apikey"}},{name:"🔗 "+y.t("wizard.menu_base_url",{url:o.getBaseUrl()}),value:{type:"base"}},{name:"🌐 "+y.t("wizard.menu_config_language"),value:{type:"language"}},new e.Separator,{name:"x "+y.t("wizard.nav_exit"),value:{type:"exit"}}],{action:s}=await this.promptWithHints([{type:"list",name:"action",message:"🛠️ "+y.t("wizard.select_tool"),choices:r}]);"exit"===s.type?(this.printGoodbye(),process.exit(0)):"tool"===s.type?await this.configureTool(s.tool):"apikey"===s.type?await this.configApiKey():"base"===s.type?await this.configBaseUrl():"language"===s.type&&await this.configLanguage()}else await this.runFirstTimeSetup()}}export const wizard=Wizard.getInstance();
1
+ import e from"inquirer";import t from"chalk";import a from"ora";import{configManager as o,DEFAULT_MODELS as i}from"./config.js";import{getPresets as n,resolvePreset as r,getToolDefaultModel as s}from"./model-registry.js";import{toolManager as l,SUPPORTED_TOOLS as c}from"./tool-manager.js";import{confirmWritePlan as d}from"./write-plan.js";import{postApplyPrompts as p,runPendingElevations as m}from"./post-apply.js";import{appStatus as u,appStatusText as _,appTools as g,appsForTools as w,cachedAppStatus as f,upgradeApp as y}from"./app-update.js";import{i18n as h,detectSystemLang as z}from"./i18n.js";import{createBorderLine as v,createContentLine as k}from"../utils/string-width.js";import{validateApiKey as x,fetchModels as b}from"./api-validator.js";import{CODEX_ONE_MILLION_CONTEXT_SETTING as S}from"./tools/codex.js";import{CLAUDE_DESKTOP_HIDE_OFFICIAL_LOGIN_SETTING as C}from"./tools/claude-desktop.js";import{addressesWithCurrent as M,ensureReachableGatewayAddress as T,moveOtherToolsAfterFallback as A,toolsWeConfigured as K,fastestIndex as N,probeAll as B,probeSummary as P,reasonText as O,savedApiKey as W,switchGatewayAddress as j}from"../commands/base.js";import{readFileSync as H}from"fs";import{dirname as L,join as $}from"path";import{fileURLToPath as F}from"url";import{brand as I}from"./brand.js";const E=L(F(import.meta.url)),G=t.hex("#FF8700");export class Wizard{static instance;BOX_WIDTH=63;validatedApiKeys=new Set;constructor(){}static getInstance(){return Wizard.instance||(Wizard.instance=new Wizard),Wizard.instance}createBox(e){console.log(G.bold("\n"+v("╔","╗","═",this.BOX_WIDTH))),console.log(G.bold(k(e,"║","║",this.BOX_WIDTH,"center"))),console.log(G.bold(v("╚","╝","═",this.BOX_WIDTH))),console.log("")}showOperationHints(){const e=[t.gray(h.t("wizard.hint_navigate")),t.gray(h.t("wizard.hint_confirm"))];console.log(t.gray("💡 ")+e.join(t.gray(" | "))+"\n")}async promptWithHints(t){this.showOperationHints();const a=t.map(e=>"list"!==e.type||e.pageSize?e:{...e,pageSize:20});return e.prompt(a)}printBanner(){const e=60,t=h.t("wizard.banner_subtitle"),a=k(t,"║","║",e,"center"),o=k("","║","║",e,"center"),i=k(`${I().productName} v${function(){try{return JSON.parse(H($(E,"..","..","package.json"),"utf-8")).version}catch{return"0.0.0"}}()}`,"║","║",e,"center"),n=[String.raw`__ ___ _ ____ _ ___ `,String.raw`\ \ / (_) |__ ___ / ___| | |_ _|`,String.raw` \ \ / /| | '_ \ / _ \ | | | | | `,String.raw` \ V / | | |_) | __/ |___| |___ | | `,String.raw` \_/ |_|_.__/ \___|\____|_____|___|`],r=Math.max(...n.map(e=>e.length)),s=" ".repeat(Math.floor((58-r)/2)),l=n.map(t=>k(s+t,"║","║",e,"left")),c=[v("╔","╗","═",e),o,...l,o,i,a,v("╚","╝","═",e)];console.log(G.bold("\n"+c.join("\n")))}resetScreen(){console.clear(),this.printBanner()}printGoodbye(){const e=l.getSupportedTools().filter(e=>{if(e.gui)return!1;try{return Boolean(l.detectCurrentConfig(e.name).apiKey)&&l.isToolInstalled(e.name)}catch{return!1}});let a;if(e.length>0){const t=e.map(e=>e.command).join(" / ");a=h.t("wizard.goodbye_message_tools",{commands:t}),e.some(e=>"claude-code"===e.name)&&(a+=" "+h.t("wizard.goodbye_claude_hint"))}else a=h.t("wizard.goodbye_message");console.log(t.green("\n👋 "+a)),this.printPathReloadHint(e.map(e=>e.name))}printPathReloadHint(e){const a=e.filter(e=>!l.isOnPath(e));if(0===a.length)return;const o=a.map(e=>c[e].command).join(" / ");console.log(t.yellow(" ! "+h.t("win32"===process.platform?"setup.path_reload_windows":"setup.path_reload",{commands:o})))}async runFirstTimeSetup(){const e="zh_CN"===z();if(e&&(o.setLang("zh_CN"),h.setLocale("zh_CN")),this.resetScreen(),console.log(G.bold("\n"+h.t("wizard.welcome"))),console.log(t.gray(h.t("wizard.privacy_note")+"\n")),e?console.log(t.gray(h.t("wizard.lang_auto_zh")+"\n")):await this.configLanguage(),await T()){const e=K();e.length>0&&await d(e.map(e=>e.tool))&&await p(await A(e))}await this.configApiKey()&&await this.selectAndConfigureTool(!0)}async configLanguage(){for(;;){this.resetScreen(),this.createBox(h.t("wizard.select_language"));const a=h.getLocale(),{language:i}=await this.promptWithHints([{type:"list",name:"language",message:"✨ "+h.t("wizard.select_language"),choices:[{name:"[EN] English"+("en_US"===a?t.green(" ✓ ("+h.t("wizard.current_active")+")"):""),value:"en_US"},{name:"[CN] 中文"+("zh_CN"===a?t.green(" ✓ ("+h.t("wizard.current_active")+")"):""),value:"zh_CN"},new e.Separator,{name:"<- "+h.t("wizard.nav_return"),value:"back"},{name:"x "+h.t("wizard.nav_exit"),value:"exit"}],default:"zh_CN"}]);if("exit"===i)this.printGoodbye(),process.exit(0);else if("back"===i)return;return o.setLang(i),void h.setLocale(i)}}buildPresetChoices(){const a=n(),o=a.filter(e=>e.recommended),i=a.filter(e=>!e.recommended),r=e=>({name:(h.t(e.name)!==e.name?h.t(e.name):e.name)+(e.models?t.gray(` [H:${e.models.haiku} S:${e.models.sonnet} O:${e.models.opus}]`):""),value:{type:"preset",preset:e}}),s=[];return o.length>0&&(s.push(new e.Separator(t.hex("#FF8700")("── "+h.t("wizard.recommended")+" ──"))),s.push(...o.map(r))),i.length>0&&(s.push(new e.Separator(t.gray("── "+h.t("wizard.other_models")+" ──"))),s.push(...i.map(r))),s}async handleCustomModelInput(){const a=o.getModels(),{customMode:n}=await e.prompt([{type:"list",name:"customMode",message:h.t("wizard.custom_model_mode"),choices:[{name:h.t("wizard.custom_model_single"),value:"single"},{name:h.t("wizard.custom_model_per_role"),value:"per_role"}]}]);if("single"===n){const{customModel:t}=await e.prompt([{type:"input",name:"customModel",message:h.t("wizard.input_custom_model"),default:i.sonnet}]);o.setModels({haiku:t,sonnet:t,opus:t,reasoning:t})}else{const t=await e.prompt([{type:"input",name:"haiku",message:h.t("wizard.model_haiku"),default:a.haiku},{type:"input",name:"sonnet",message:h.t("wizard.model_sonnet"),default:a.sonnet},{type:"input",name:"opus",message:h.t("wizard.model_opus"),default:a.opus},{type:"input",name:"reasoning",message:h.t("wizard.model_reasoning"),default:a.reasoning}]);o.setModels(t)}console.log(t.green("\n✓ "+h.t("wizard.models_saved")))}async configModels(a){const i=o.getApiKey();if(await this.validatedKeyForConfiguration(i))for(;;){this.resetScreen(),this.createBox(h.t("wizard.config_models"));const i=[...this.buildPresetChoices()];i.push(new e.Separator),i.push({name:"✏️ "+h.t("wizard.custom_model_input"),value:{type:"custom_input"}}),i.push(new e.Separator),i.push({name:"<- "+h.t("wizard.nav_return"),value:{type:"back"}}),i.push({name:"x "+h.t("wizard.nav_exit"),value:{type:"exit"}});const{modelChoice:n}=await this.promptWithHints([{type:"list",name:"modelChoice",message:h.t("wizard.select_model_config"),choices:i}]);if("exit"===n.type)this.printGoodbye(),process.exit(0);else{if("back"===n.type)return;if("custom_input"===n.type)return await this.handleCustomModelInput(),void(a?.skipLoadPrompt||await this.promptLoadAfterModelConfig());if("preset"===n.type){const e=r(n.preset);return o.setModels(e),console.log(t.green("\n✓ "+h.t("wizard.models_saved"))),void(a?.skipLoadPrompt||await this.promptLoadAfterModelConfig())}}}else await e.prompt([{type:"input",name:"continue",message:h.t("wizard.press_enter")}])}async promptLoadAfterModelConfig(){const{shouldLoad:t}=await e.prompt([{type:"list",name:"shouldLoad",message:h.t("wizard.load_config_now"),choices:[{name:h.t("wizard.load_config_yes"),value:!0},{name:h.t("wizard.load_config_later"),value:!1}]}]);t&&await this.selectAndConfigureTool()}async configBaseUrl(){const i=o.getBaseUrl(),n=M(),r=a(h.t("wizard.base_testing")).start(),s=await B(n,{apiKey:W(),samples:3});r.stop();const l=N(s),c=n.map((e,a)=>{const o=e.url===i?t.cyan(` ← ${h.t("base.current_mark")}`):"";return{name:`${e.url} ${t.gray(e.label)} ${P(s[a],a===l)}${o}`,value:e.url}});c.push(new e.Separator,{name:"<- "+h.t("wizard.nav_return"),value:"__back__"});const{url:d}=await this.promptWithHints([{type:"list",name:"url",message:h.t("wizard.base_select"),choices:c,default:i}]);if("__back__"===d)return;const p=s[n.findIndex(e=>e.url===d)];p.ok?await j(d):console.log(t.red(h.t("base.unreachable",{url:d,reason:O(p)}))),await e.prompt([{type:"input",name:"continue",message:h.t("wizard.press_enter")}])}async configApiKey(){for(;;){this.resetScreen(),this.createBox(h.t("wizard.input_api_key")),console.log(t.gray("\n💡 "+h.t("wizard.api_key_input_hint"))),console.log(t.gray(" "+h.t("wizard.api_key_get_hint",{url:I().links.tokenPage}))),console.log();const{apiKey:i}=await e.prompt([{type:"password",name:"apiKey",message:h.t("wizard.input_your_api_key"),mask:"*"}]);if(!i||""===i.trim()){const{action:t}=await e.prompt([{type:"list",name:"action",message:h.t("wizard.select_action"),choices:[{name:h.t("wizard.retry_input"),value:"retry"},{name:"<- "+h.t("wizard.nav_return"),value:"back"}]}]);if("back"===t)return!1;continue}const n=a(h.t("wizard.validating_api_key")).start(),r=await x(i.trim());if(n.stop(),r.valid)return o.setApiKey(i.trim()),this.validatedApiKeys.add(i.trim()),console.log(t.green("\n✓ "+h.t("wizard.api_key_valid"))),!0;{this.validatedApiKeys.delete(i.trim()),"invalid_api_key"===r.error?console.log(t.red("\n✗ "+h.t("wizard.api_key_invalid"))):console.log(t.red("\n✗ "+h.t("wizard.api_key_network_error")));const{action:a}=await e.prompt([{type:"list",name:"action",message:h.t("wizard.select_action"),choices:[{name:h.t("wizard.retry_input"),value:"retry"},{name:"<- "+h.t("wizard.nav_return"),value:"back"}]}]);if("back"===a)return!1}}}async selectAndConfigureTool(a=!1){for(const e of g())await u(e).catch(()=>{});for(;;){this.resetScreen(),this.createBox(h.t("wizard.select_tool"));const o=l.getSupportedTools().map(e=>{const a=w([e.name]).map(e=>f(e)).find(e=>e.outdated);return{name:e.displayName+(a?t.yellow(" "+(a.tool===e.name?"":`${a.name} `)+_(a)):""),value:e.name}}),{tool:i}=await this.promptWithHints([{type:"list",name:"tool",message:"🛠️ "+h.t("wizard.select_tool"),choices:[...o,new e.Separator,{name:"<- "+h.t("wizard.nav_return"),value:"back"},{name:"x "+h.t("wizard.nav_exit"),value:"exit"}]}]);if("exit"===i)this.printGoodbye(),process.exit(0);else if("back"===i)return;await this.configureTool(i,a)}}async configureTool(a,o=!1){const i=c[a];if(i){if(!l.isToolInstalled(a)){console.log(t.yellow("\n"+h.t("wizard.tool_not_installed",{tool:i.displayName})));const{install:o}=await e.prompt([{type:"confirm",name:"install",message:h.t("wizard.install_tool_confirm"),default:!0}]);if(!o)return;try{await l.installTool(a)}catch{return void console.log(t.red(h.t("wizard.install_failed")))}}o?await this.configureToolModel(a)&&await this.loadConfig(a):await this.showToolMenu(a)}}async showToolMenu(t){for(;;){this.resetScreen();const a=c[t];if(!a)return;this.createBox(a.displayName+" "+h.t("wizard.menu_title"));const o=[{name:"📥 "+h.t("wizard.action_load_config",{tool:a.displayName}),value:"load"},{name:"📤 "+h.t("wizard.action_unload_config",{tool:a.displayName}),value:"unload"}];l.supportsClearPinnedModels(t)&&o.push({name:"🧹 "+h.t("wizard.action_clear_model",{tool:a.displayName}),value:"clear-model"});for(const e of w([t]).map(e=>f(e)).reverse()){if(e.blocker||!e.latest||!e.outdated&&e.installed)continue;const t=e.installed?h.t("wizard.action_upgrade_app",{tool:e.name,current:e.current??"?",latest:e.latest}):h.t("wizard.action_install_app",{tool:e.name,latest:e.latest});o.unshift({name:"↑ "+t,value:`upgrade-app:${e.tool}`})}o.push({name:"🧨 "+h.t("wizard.action_force_config",{tool:a.displayName}),value:"force"},{name:"↩️ "+h.t("wizard.action_restore_config",{tool:a.displayName}),value:"restore"},new e.Separator,{name:"<- "+h.t("wizard.nav_return"),value:"back"},{name:"x "+h.t("wizard.nav_exit"),value:"exit"});const{action:i}=await this.promptWithHints([{type:"list",name:"action",message:"⚙️ "+h.t("wizard.select_action"),choices:o}]);if("exit"===i)this.printGoodbye(),process.exit(0);else{if("back"===i)return;"load"===i?await this.configureToolModel(t)&&await this.loadConfig(t):"force"===i?await this.forceConfig(t):"unload"===i?await this.unloadConfig(t):"string"==typeof i&&i.startsWith("upgrade-app:")?(await y(i.slice(12),{install:!0}),await e.prompt([{type:"input",name:"continue",message:h.t("wizard.press_enter")}])):"clear-model"===i?await this.clearPinnedModels(t):"restore"===i&&await this.restoreConfig(t)}}}singleModelOverride(e){const t=e.trim();return/claude/i.test(t)?{opus:t}:{haiku:t,sonnet:t,opus:t,reasoning:t}}hasConfiguredApiKey(){return!!o.getApiKey()?.trim()||o.listToolApiKeys().some(e=>Boolean(o.getApiKeyForTool(e)?.trim()))}async validatedKeyForConfiguration(e){const o=e?.trim();if(!o)return console.log(t.red("\n"+h.t("wizard.api_key_required"))),console.log(t.yellow(h.t("wizard.please_config_api_key_first"))),null;if(this.validatedApiKeys.has(o))return o;const i=a(h.t("wizard.validating_api_key")).start(),n=await x(o);if(n.valid)return this.validatedApiKeys.add(o),i.succeed(h.t("wizard.api_key_valid")),o;this.validatedApiKeys.delete(o);const r="invalid_api_key"===n.error?h.t("wizard.api_key_invalid"):h.t("wizard.api_key_network_error");return i.fail(r),console.log(t.red("\n"+h.t("wizard.please_reconfig_api_key"))),null}async configureToolModel(i){const n=c[i];if(!n)return!1;const l=await this.validatedKeyForConfiguration(o.getApiKeyForTool(i));if(!l)return await e.prompt([{type:"input",name:"continue",message:h.t("wizard.press_enter")}]),!1;const d="claude-code"===i,p=d||"claude-desktop"===i||"agy"===i,m=s(i),u=p||!m?h.t("wizard.model_builtin_default"):m;this.resetScreen(),this.createBox(n.displayName+" · "+h.t("wizard.config_models"));const _=[{name:"✅ "+h.t("wizard.use_default_model",{model:u}),value:{type:"default"}},{name:"🌐 "+h.t("wizard.fetch_models_from_api"),value:{type:"fetch"}},...this.buildPresetChoices(),new e.Separator,{name:"✏️ "+h.t("wizard.input_custom_model"),value:{type:"custom"}},new e.Separator,{name:"<- "+h.t("wizard.nav_return"),value:{type:"back"}}],{choice:g}=await this.promptWithHints([{type:"list",name:"choice",message:h.t("wizard.select_tool_model",{tool:n.displayName}),choices:_}]);if("back"===g.type)return!1;if("default"===g.type)o.setToolModel(i,null);else if("preset"===g.type)o.setToolModel(i,r(g.preset));else if("custom"===g.type){const{model:t}=await e.prompt([{type:"input",name:"model",message:h.t("wizard.input_custom_model"),default:!p&&m?m:void 0}]),a=(t||"").trim();o.setToolModel(i,a?this.singleModelOverride(a):null)}else if("fetch"===g.type){const n=a(h.t("wizard.fetching_models")).start(),r=await b(l);let s;if(n.stop(),r.ok&&r.models.length>0){const{model:t}=await e.prompt([{type:"list",name:"model",message:h.t("wizard.select_fetched_model"),pageSize:20,choices:[...r.models,new e.Separator,{name:"<- "+h.t("wizard.nav_return"),value:"__back__"}]}]);if("__back__"===t)return!1;s=t}else{console.log(t.yellow("\n"+h.t("wizard.fetch_models_failed")));const{model:a}=await e.prompt([{type:"input",name:"model",message:h.t("wizard.input_custom_model"),default:!p&&m?m:void 0}]);s=(a||"").trim()}o.setToolModel(i,s?this.singleModelOverride(s):null)}if("codex"===i){const t=o.getToolSetting(i,S),{enableOneMillionContext:a}=await e.prompt([{type:"confirm",name:"enableOneMillionContext",message:h.t("wizard.codex_enable_1m_context"),default:!1!==t}]);o.setToolSetting(i,S,Boolean(a))}if("claude-desktop"===i){const t=o.getToolSetting(i,C),{hideOfficialLogin:a}=await e.prompt([{type:"confirm",name:"hideOfficialLogin",message:h.t("wizard.desktop_hide_official_login"),default:!1!==t}]);o.setToolSetting(i,C,Boolean(a))}return console.log(t.green("\n✓ "+h.t("wizard.models_saved"))),d&&console.log(t.gray("💡 "+h.t("wizard.claude_model_hint"))),!0}async forceConfig(t){const a=c[t]?.displayName||t,{confirm:o}=await e.prompt([{type:"confirm",name:"confirm",message:h.t("config.confirm_force",{tool:a}),default:!1}]);o&&await this.loadConfig(t,{force:!0})}async loadConfig(i,n={}){const r=o.getModelsForTool(i),s=await this.validatedKeyForConfiguration(o.getApiKeyForTool(i));if(!s)return void await e.prompt([{type:"input",name:"continue",message:h.t("wizard.press_enter")}]);if(!n.force&&!await d([i]))return;const m=a(h.t("wizard.loading_config")).start();try{await l.applyPrivateConfig(i,s,r,{...n,takeOver:!0}),m.stop(),l.printApplied(i),await p([i],{apps:{install:!1}}),n.force&&console.log(t.yellow(h.t("config.force_done",{tool:c[i]?.displayName||i,name:i})));const a=c[i];a&&!a.gui&&(l.isOnPath(i)&&console.log(t.green("\n"+h.t("wizard.run_tool_hint",{command:a.command}))),this.printPathReloadHint([i]));const{nextAction:o}=await e.prompt([{type:"list",name:"nextAction",message:h.t("wizard.what_next"),choices:[{name:h.t("wizard.exit_and_start"),value:"exit"},{name:h.t("wizard.continue_config"),value:"continue"}]}]);"exit"===o&&(this.printGoodbye(),process.exit(0))}catch(a){m.fail(h.t("wizard.config_failed")),console.log(t.red(a instanceof Error?a.message:String(a))),await e.prompt([{type:"input",name:"continue",message:h.t("wizard.press_enter")}])}}async clearPinnedModels(a){const o=c[a]?.displayName||a,{confirm:i}=await e.prompt([{type:"confirm",name:"confirm",message:h.t("wizard.confirm_clear_model",{tool:o}),default:!1}]);if(i){try{const e=await l.clearPinnedModels(a);0===e.length?console.log(t.yellow("\n"+h.t("config.clear_model_none",{tool:o}))):(console.log(t.green("\n✓ "+h.t("config.clear_model_done",{tool:o}))),e.forEach(e=>console.log(t.gray(` - ${e}`))),console.log(t.gray(h.t("config.clear_model_restart_hint",{tool:o}))))}catch(e){console.log(t.red("\n"+(e instanceof Error?e.message:String(e))))}await e.prompt([{type:"input",name:"continue",message:h.t("wizard.press_enter")}])}}async unloadConfig(o){const{confirm:i}=await e.prompt([{type:"confirm",name:"confirm",message:h.t("wizard.confirm_unload_config",{tool:c[o]?.displayName||o}),default:!1}]);if(!i)return;const n=a(h.t("wizard.unloading_config")).start();try{const a=l.holdsOurConfig(o),i=l.unloadPrivateConfig(o);if(l.hasPendingElevation(o)&&(n.stop(),(await m([o])).length>0))return;if(!a)return void n.info(h.t("config.remove_nothing",{tool:c[o]?.displayName||o}));n.succeed(h.t("wizard.config_unloaded")),i.forEach(e=>console.log(t.yellow(" ! "+e.text)));const{nextAction:r}=await e.prompt([{type:"list",name:"nextAction",message:h.t("wizard.what_next"),choices:[{name:h.t("wizard.nav_exit"),value:"exit"},{name:h.t("wizard.continue_config"),value:"continue"}]}]);"exit"===r&&(this.printGoodbye(),process.exit(0))}catch(a){n.fail(h.t("wizard.config_unload_failed")),console.log(t.red(a instanceof Error?a.message:String(a))),await e.prompt([{type:"input",name:"continue",message:h.t("wizard.press_enter")}])}}async restoreConfig(o){const i=c[o]?.displayName||o,{confirm:n}=await e.prompt([{type:"confirm",name:"confirm",message:h.t("wizard.confirm_restore_config",{tool:i}),default:!1}]);if(!n)return;const r=a(h.t("wizard.restoring_config")).start();try{const e=l.restorePrivateConfig(o).filter(e=>e.result.restored);0===e.length?r.warn(h.t("wizard.restore_no_backup")):(r.succeed(h.t("wizard.config_restored",{tool:i})),e.forEach(e=>console.log(t.gray(` ${e.file} ← ${e.result.from}`))),console.log(t.yellow(" ! "+h.t("config.reopen_hint",{tool:i}))))}catch(e){r.fail(h.t("wizard.config_restore_failed")),console.log(t.red(e instanceof Error?e.message:String(e)))}await e.prompt([{type:"input",name:"continue",message:h.t("wizard.press_enter")}])}async run(){await this.showMainMenu()}async showMainMenu(){if(this.hasConfiguredApiKey())for(;;){this.resetScreen();const a=o.getApiKey()||"",i=a.length>4?"sk-****"+a.slice(-4):"****";console.log(t.gray(` 🔑 API Key: ${i}`)+t.green(" ✓")),console.log("");const n=l.getSupportedTools().map(e=>({name:"🛠️ "+e.displayName,value:{type:"tool",tool:e.name}})),r=[new e.Separator(G("── "+h.t("wizard.select_tool")+" ──")),...n,new e.Separator(t.gray("── "+h.t("wizard.settings")+" ──")),{name:"🔑 "+h.t("wizard.menu_change_api_key"),value:{type:"apikey"}},{name:"🔗 "+h.t("wizard.menu_base_url",{url:o.getBaseUrl()}),value:{type:"base"}},{name:"🌐 "+h.t("wizard.menu_config_language"),value:{type:"language"}},new e.Separator,{name:"x "+h.t("wizard.nav_exit"),value:{type:"exit"}}],{action:s}=await this.promptWithHints([{type:"list",name:"action",message:"🛠️ "+h.t("wizard.select_tool"),choices:r}]);"exit"===s.type?(this.printGoodbye(),process.exit(0)):"tool"===s.type?await this.configureTool(s.tool):"apikey"===s.type?await this.configApiKey():"base"===s.type?await this.configBaseUrl():"language"===s.type&&await this.configLanguage()}else await this.runFirstTimeSetup()}}export const wizard=Wizard.getInstance();
@@ -437,6 +437,9 @@
437
437
  "policy_stale_write": "Claude Desktop still uses old registry settings (most likely from the .reg file downloaded from the gateway page); writing the new config there needs one administrator confirmation",
438
438
  "elevate_remove": "Remove the old registry settings? Windows asks for administrator confirmation once; later updates won't need it",
439
439
  "elevate_write": "Write the new config to the registry? Windows asks for administrator confirmation once",
440
+ "elevate_unload": "Remove the {{brand}} config from the registry? Windows asks for administrator confirmation once. Otherwise Claude Desktop keeps using it",
441
+ "unload_elevation_failed": "Couldn't remove the {{brand}} config from the registry (prompt declined, or this account is not an administrator), so Claude Desktop keeps using it. Run {{cli}} config claude-desktop remove and click Yes in the Windows prompt",
442
+ "unload_elevation_skipped": "The {{brand}} config in the registry was not removed: it needs one confirmation in a Windows prompt, and until then Claude Desktop keeps using it. Run {{cli}} config claude-desktop remove in a terminal",
440
443
  "refresh_needs_admin": "Claude Desktop's model menu was not updated: an old model list is still in the registry, and changing it needs administrator confirmation. Run {{cli}} refresh and click Yes in the Windows prompt",
441
444
  "registry_removed": "Removed the old values under {{key}}; Claude Desktop now reads the local config"
442
445
  },
@@ -437,6 +437,9 @@
437
437
  "policy_stale_write": "Claude Desktop 还在使用注册表里的旧配置(多半是以前从网关页面下载 .reg 写入的);把新配置写进注册表需要管理员确认一次",
438
438
  "elevate_remove": "删除注册表里的旧配置?系统会弹出一次管理员确认,之后更新 Claude Desktop 不再需要管理员。",
439
439
  "elevate_write": "把新配置写进注册表?系统会弹出一次管理员确认。",
440
+ "elevate_unload": "删除注册表里的 {{brand}} 配置?系统会弹出一次管理员确认。不删的话 Claude Desktop 会继续使用这份配置",
441
+ "unload_elevation_failed": "无法删除注册表里的 {{brand}} 配置:系统确认被取消,或这个账号不是管理员,Claude Desktop 会继续使用它。请运行 {{cli}} config claude-desktop remove,在系统弹出的窗口里点「是」",
442
+ "unload_elevation_skipped": "未删除注册表里的 {{brand}} 配置:需要在系统弹出的窗口里确认一次,Claude Desktop 会继续使用它。请在终端里运行 {{cli}} config claude-desktop remove",
440
443
  "refresh_needs_admin": "Claude Desktop 的模型菜单没有更新:注册表里还留着旧的模型列表,改它需要管理员确认。运行 {{cli}} refresh,在弹出的系统窗口里点击「是」",
441
444
  "registry_removed": "已删除注册表 {{key}} 里的旧配置,Claude Desktop 改为读取本地配置"
442
445
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vibeapi/api-helper",
3
- "version": "0.0.196",
3
+ "version": "0.0.197",
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",