# ============================================================ # QCode.cc — Claude Code 一键配置脚本 (Windows PowerShell) # QCode.cc — Claude Code one-click setup (Windows PowerShell) # # PowerShell: irm https://qcode.cc/install/claude-code.ps1 | iex # English: $env:QCODE_LANG='en'; irm https://qcode.cc/install/claude-code.ps1 | iex # CMD / 没有 irm: # powershell -NoProfile -ExecutionPolicy Bypass -Command "irm https://qcode.cc/install/claude-code.ps1 | iex" # 非交互 / unattended: # & ([scriptblock]::Create((irm https://qcode.cc/install/claude-code.ps1))) -Key cr_xxx -Yes # (可选 -Model claude-opus-5-5 固定默认模型;不传则沿用 Claude Code 自带默认) # 环境变量 / env vars(irm | iex 无法传参时用;-Key / -Mirror 参数优先): # $env:QCODE_API_KEY = 'cr_xxx' API 密钥,不必出现在命令行参数里 / the API key, kept off the command line # $env:QCODE_MIRROR = 'cn' 强制用国内 npm 镜像 npmmirror;'off' = 从不切换(缺省 auto:registry.npmjs.org 5 秒连不上才切) # force the China npm mirror; 'off' = never switch (default auto: switch only if registry.npmjs.org is unreachable for 5 s) # # 预览 / preview(只打印计划,不写文件、不安装、不发验证请求): # & ([scriptblock]::Create((irm https://qcode.cc/install/claude-code.ps1))) -DryRun # 卸载 / uninstall(只删本脚本写过且值仍匹配的项,不卸载 Node / CLI): # & ([scriptblock]::Create((irm https://qcode.cc/install/claude-code.ps1))) -Uninstall -Yes # # 写入用户级环境变量,不需要管理员权限。旧值自动备份。 # Writes user-level environment variables; no admin rights needed. Old values are backed up. # 文档 / docs: https://docs.qcode.cc/docs/getting-started/one-click-install # ============================================================ param( [string]$Key = "", [ValidateSet("", "api", "asia", "us", "eu")][string]$Domain = "", [ValidatePattern('^$|^[A-Za-z0-9._\[\]-]+$')][string]$Model = "", [string]$Lang = "", # zh / en;明确给了别的值(ar / fa / xx …)⇒ 英文(2026-11-13 起不再因 ValidateSet 直接报错退出) [ValidateSet("", "auto", "cn", "off")][string]$Mirror = "", [switch]$Yes, [switch]$NoInstall, [switch]$NoVerify, [switch]$DryRun, [switch]$Uninstall ) # irm|iex 是在调用者作用域里执行的,脚本改动的偏好设置会永久留在用户会话里。 # 记下原值,最后在 finally 里恢复。 $__qcPrevEAP = $ErrorActionPreference $ErrorActionPreference = "Stop" # PS 5.1 的 Invoke-WebRequest/RestMethod 默认画进度条,会反复闪并冲掉已打印的测速结果。 $__qcPrevPP = $ProgressPreference $ProgressPreference = "SilentlyContinue" # 国内镜像只改本进程的 npm_config_registry;irm|iex 下 $env: 会留在用户会话里 ⇒ 记下原值,finally 里还原。 $__qcPrevNpmReg = $env:npm_config_registry $__qcMirrorSet = $false $ScriptVersion = "2026.11.23.1" $NpmPkg = "@anthropic-ai/claude-code" $CliName = "claude" $MinNodeMajor = 22 # 与 @anthropic-ai/claude-code 的 engines(>=22.0.0,11-05 npm view 实测)一致 $DocsUrl = "https://docs.qcode.cc/docs/getting-started/one-click-install" $ProbeUrl = "https://probe.qcode.cc/" $DashboardUrl = "https://qcode.cc/dashboard" $ProbeModel = "claude-haiku-5-5" # ---------- 语言 ---------- # 优先级: -Lang > $env:QCODE_LANG > 系统区域 > zh function Resolve-UiLang { if ($Lang -in @('zh', 'en')) { return $Lang.ToLowerInvariant() } if ($Lang) { return 'en' } # 明确指定了不认识的语言 ⇒ 英文(不是中文) if ($env:QCODE_LANG -in @('zh', 'en')) { return $env:QCODE_LANG.ToLowerInvariant() } if ($env:QCODE_LANG) { return 'en' } # 用显示语言(UICulture)判断,Culture 是区域格式 —— 把区域设成 en-US 的中文用户 # 不该因此拿到英文界面;UICulture 取不到再退回 Culture。 try { if ((Get-UICulture).Name -like 'zh*') { return 'zh' } if ((Get-Culture).Name -like 'zh*') { return 'zh' } return 'en' } catch { return 'zh' } } $UiLang = Resolve-UiLang $MSG = @{ zh = @{ banner = ' QCode.cc · Claude Code 一键配置 v{0}' banner_sub = ' 无需管理员权限 · 旧值自动备份 · 配置后自动验证' dom_api = '按地区自动分流(北美 / 欧洲→美国,其余→亚洲节点)'; dom_asia = '亚洲(韩国 / 台湾 / 香港)' dom_us = '北美 / 欧洲'; dom_eu = '欧洲' s1_probing = '[1/5] 正在对 3 个接入域测速...' timeout = '超时' pick_domain = '请选择接入域 [回车 = {0}(最快: {1})]' bad_choice = '无效选择,使用最快项 {0}' domain_ok = '接入域: {0} -> ANTHROPIC_BASE_URL={1}' s2_key = '[2/5] 请输入 QCode.cc API 密钥({0} 复制)' key_prompt = 'API 密钥' key_need = '非交互模式必须提供 -Key(或先设环境变量 QCODE_API_KEY)。用法:& ([scriptblock]::Create((irm https://qcode.cc/install/claude-code.ps1))) -Key cr_xxx -Yes' key_env = '已从环境变量 QCODE_API_KEY 读取密钥' mirror_cn = 'npm 源已切到国内镜像 https://registry.npmmirror.com(-Mirror cn / QCODE_MIRROR=cn;仅本次安装生效)' mirror_auto = 'registry.npmjs.org 5 秒内连不上,npm 源已切到国内镜像 https://registry.npmmirror.com(仅本次安装生效;不想切换可设 QCODE_MIRROR=off)' key_empty = 'API 密钥不能为空。' key_badchar = 'API 密钥含有非法字符。常见原因:把引号、空格或中文标点一起粘贴进来了。请到控制台重新复制。' key_cleaned = '已自动去掉密钥首尾的引号/空白字符。' key_ok = '已读取密钥: cr_****{0}' key_noprefix = '密钥通常以 cr_ 开头,当前输入不是。' still_go = '仍然继续?' cancelled = '已取消:用户未确认继续。' done_partial = '配置已写入,但验证未通过 —— 请按上面的提示处理后重跑本脚本。' s3_write = '[3/5] 写入用户级环境变量' backed_up = '旧环境变量已备份: {0}' written = '已写入 ANTHROPIC_BASE_URL / ANTHROPIC_AUTH_TOKEN / CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC / CLAUDE_CODE_AUTO_MODE_SERVER' model_ok = '已固定默认模型: {0}(ANTHROPIC_MODEL;想改回跟随 Claude Code 默认,删除该用户环境变量即可)' apikey_conflict = '检测到用户级 ANTHROPIC_API_KEY 也有值,可能与本配置冲突,建议手动清理。' settings_conflict = '{0} 的 env 里配置了另一套接入。它的优先级高于环境变量,不改的话 Claude Code 实际不会连到 QCode。' settings_other = '那里的 ANTHROPIC_BASE_URL: {0}' settings_keys = '不一致的项: {0}' settings_ask = '把这几项改成 QCode 的配置?(先备份原文件;只改上面这几项,ANTHROPIC_API_KEY 换成 ANTHROPIC_AUTH_TOKEN,其余设置不动)' settings_ours = '{0} 里是之前写入的 QCode 配置,与本次选择不同,已按本次同步(先备份)。' settings_restore = '写入 {0} 失败,已尝试用备份还原(备份: {1})。' settings_model_note = 'settings.json 里的 ANTHROPIC_MODEL 也已改为 {0};以后想跟随 Claude Code 默认,需删掉那一项。' settings_left_title = '配置已写入,但 {0} 仍指向别处,Claude Code 实际不会走 QCode(见上方提示)。' settings_done = '已更新 settings.json 的接入配置(原文件备份: {0})' settings_kept = '已保留原样:Claude Code 仍会按 settings.json 连接;以后要用 QCode,重跑本脚本或手动删掉上面这几项。' settings_failed = '没能安全地改写 {0},原文件未动。请手动把 env 里的 ANTHROPIC_BASE_URL / ANTHROPIC_AUTH_TOKEN 改成 QCode 的值,并删掉 ANTHROPIC_API_KEY。' settings_pins = '{0} 的 env 里还固定了下面这些模型(优先级同样高于环境变量);如果是别家的模型名,在 QCode 上会报「not a supported model」:' settings_unparsable = '{0} 不是合法 JSON,已跳过自动检查。请确认其中没有别家的 ANTHROPIC_BASE_URL / ANTHROPIC_AUTH_TOKEN / ANTHROPIC_API_KEY。' s4_env = '[4/5] 检查运行环境' cli_installed = 'Claude Code 已安装: {0}' no_install = '-NoInstall:跳过安装。请自行安装后运行: npm install -g {0}' ask_install = '未检测到 Claude Code,使用 npm 安装?' node_none = '未检测到 Node.js' node_low = '当前 Node.js {0} 低于 v{1}' ask_winget = '使用 winget 安装 Node.js LTS?' no_winget = '未找到 winget。请到 https://nodejs.org 安装 LTS 版后重跑本脚本。' winget_fail = 'winget 安装 Node.js 失败(退出码 {0})。请到 https://nodejs.org 手动安装后重跑。' npm_missing = '未找到 npm,请先安装 Node.js,再执行: npm install -g {0}' npm_fail = 'npm 安装失败(退出码 {0})。可手动执行: npm.cmd install -g {1}' cli_done = 'Claude Code 安装完成' cli_notfound = '安装完成但当前会话未找到 claude,请重开 PowerShell。' node_notready = 'Node.js 未就绪,配置已写好;装好 Node 后运行: npm install -g {0}' s5_verify = '[5/5] 正在验证接入(发送一条最小测试请求,费用可忽略)...' verify_ok = '接入验证通过!模型响应正常。' verify_usage = ' > 用量与请求明细可在 {0} 输入你的密钥查看' verify_401 = '密钥无效或已过期(HTTP {0})。到 {1} 核对后重跑本脚本。' verify_model = '配置正确,但验证用的探针模型 {0} 当前不可用(HTTP 400)。这不影响你正常使用。' verify_400 = '请求被拒绝(HTTP 400): {0}' verify_404 = '接入地址错误(HTTP 404)。BASE_URL 应为 https://{{域}}/api 且末尾不带斜杠。当前: {0}' verify_429 = '配置正确(HTTP 429 = 已到达服务但被限流),稍后即可正常使用。' verify_net = '网络或节点异常({0})。建议重跑脚本换一个接入域(-Domain asia),各域状态见 {1}' skip_verify = '-NoVerify:已跳过验证。' done_title = '配置完成!摘要:' sum_domain = ' 接入域 {0}' sum_way = ' 配置方式 用户级环境变量(备份在 {0})' sum_settings = ' settings.json 接入相关的几项已改为 QCode({0})' sum_verified = ' 连通性 [OK] 已验证' reload_hint = ' 新开的 PowerShell / 终端会自动生效;VS Code 等编辑器需重启。' policy_hint = ' 提示: 当前执行策略是 {0},新开的 PowerShell 里运行 claude 可能报「无法加载文件」。' policy_fix = ' 免管理员修法(只影响你自己): Set-ExecutionPolicy -Scope CurrentUser RemoteSigned(或改输 claude.cmd)' policy_set = 'PowerShell 执行策略已设为 RemoteSigned(当前用户,原为 {0};免管理员、仅影响当前账号)' sum_policy = ' 执行策略 CurrentUser RemoteSigned(已自动放行 .ps1 脚本)' policy_gp_hint = ' 提示: 组策略({0}={1})限制运行 .ps1 脚本,当前用户设置无法覆盖组策略。' policy_gp_fix = ' 免改策略直接用: 在 PowerShell 里输入 {0}.cmd(或在 CMD 里直接输入 {0})即可正常启动。' policy_signed_hint = ' 提示: 当前用户执行策略为 AllSigned(已原样保留);在 PowerShell 中可改输 {0}.cmd 启动,或自行执行 Set-ExecutionPolicy -Scope CurrentUser RemoteSigned' update_hint = ' 以后升级 Claude Code: claude update(本配置关闭了后台自动更新)' docs_hint = ' 文档与排错: {0}' ask_launch = '是否立即启动 Claude Code?' uninstall_conflict = '-Uninstall 不能与 -Key / -Domain / -Model / -Mirror / -NoInstall / -NoVerify 同时使用。' uninstall_usage = '用法: -Uninstall [-Yes] [-DryRun] [-Lang zh|en];-DryRun [-Key] [-Domain api|asia|us] [-Model] [-NoInstall] [-NoVerify] [-Yes] [-Lang zh|en]。只删除本脚本写过且值仍匹配的配置,不卸载 Node / CLI。' uninstall_none = '没有发现本脚本写入的配置' uninstall_plan = '将移除本脚本写入的以下配置:' uninstall_ask = '确认删除以上配置?[y/N]: ' uninstall_cancel = '已取消,未修改任何文件。' uninstall_need_yes = '没有终端可确认。若确实要卸载,请加上 -Yes。' uninstall_done = '已移除本脚本写入的配置。' uninstall_reload = '当前终端里的环境变量去不掉,请新开一个终端生效。' uninstall_cli = '本脚本不卸载 CLI。若要卸载,执行: npm uninstall -g {0}' uninstall_kept = '保留 {0}' uninstall_badjson = '{0} 不是合法 JSON 或无法处理,未修改任何文件。' uninstall_other_base = 'ANTHROPIC_BASE_URL 不是 qcode.cc({0}),已保留。' uninstall_backup_fail = '备份失败,未修改任何文件。' uninstall_model_keep = '用户级 ANTHROPIC_MODEL 没有可核对的写入记录(只有当时带了 -Model 才会写,而 -Model 不能与 -Uninstall 同时使用),未删除。若要去掉请手动删除该用户环境变量。' dry_header = 'dry-run:只打印计划,不写文件、不安装、不发验证请求。' dry_key_missing = '未提供密钥,计划里用占位符(不会真正发送)。' dry_settings_skip = 'settings.json 不存在,不会创建。' dry_settings_sync = 'settings.json 计划({0}):' dry_settings_ask = 'settings.json 指向别的接入,交互时会询问(默认 Y)。' dry_install_skip = '-NoInstall:不安装 Node.js / CLI。' dry_node = 'Node.js: {0}' dry_cli = 'CLI {0}: {1}' dry_mirror = '镜像: {0}' dry_policy_set = '执行策略(CurrentUser): {0} -> RemoteSigned' dry_policy_keep = '执行策略(CurrentUser): {0}(保持不变)' dry_policy_gp = '执行策略: 受组策略 {0}={1} 管控(保持不变;PowerShell 中可改输 {2}.cmd)' dry_verify = '将验证(本次不发送): {0} {1} model={2}' dry_verify_skip = '-NoVerify:跳过验证。' dry_uninstall = 'dry-run + uninstall:只列出将删除的内容,不修改文件。' dry_env = '将写入用户级环境变量(密钥已打码):' dry_win_note = 'Windows 不写 shell 托管块,上面这些用户级环境变量就是对应的写入内容。' dry_auth = 'auth.json 将写入 OPENAI_API_KEY={0}' dry_toml = 'config.toml 将合并这些顶层键,并写入 [model_providers.qcode]:' dry_pick = 'dry-run 不询问,使用最快接入域 {0}。' dry_will_install = '将安装: {0}' enjoy = '随时运行 claude 开始使用。enjoy!' ack = '配置完成,按回车键关闭此窗口...' failed = '配置未完成: {0}' } en = @{ banner = ' QCode.cc - Claude Code one-click setup v{0}' banner_sub = ' No admin rights needed | old values backed up | verified after setup' dom_api = 'Auto by region (North America / Europe -> US, elsewhere -> Asia)'; dom_asia = 'Asia (Korea / Taiwan / Hong Kong)' dom_us = 'North America / Europe'; dom_eu = 'Europe' s1_probing = '[1/5] Measuring latency to the 3 endpoints...' timeout = 'timeout' pick_domain = 'Choose an endpoint [Enter = {0} (fastest: {1})]' bad_choice = 'Invalid choice; using the fastest one: {0}' domain_ok = 'Endpoint: {0} -> ANTHROPIC_BASE_URL={1}' s2_key = '[2/5] Enter your QCode.cc API key (copy it from {0})' key_prompt = 'API key' key_need = 'Unattended mode requires -Key (or set the QCODE_API_KEY environment variable first). Usage: & ([scriptblock]::Create((irm https://qcode.cc/install/claude-code.ps1))) -Key cr_xxx -Yes' key_env = 'Read the API key from the QCODE_API_KEY environment variable' mirror_cn = 'npm registry switched to the China mirror https://registry.npmmirror.com (-Mirror cn / QCODE_MIRROR=cn; this install only)' mirror_auto = 'registry.npmjs.org did not respond within 5 seconds; npm registry switched to the China mirror https://registry.npmmirror.com (this install only; set QCODE_MIRROR=off to disable)' key_empty = 'API key must not be empty.' key_badchar = 'The API key contains invalid characters. Usually quotes, spaces or smart punctuation were pasted along with it. Please copy it again.' key_cleaned = 'Stripped surrounding quotes/whitespace from the key automatically.' key_ok = 'Key accepted: cr_****{0}' key_noprefix = 'Keys normally start with cr_ ; this one does not.' still_go = 'Continue anyway?' cancelled = 'Cancelled: not confirmed by the user.' done_partial = 'Config was written, but verification did not pass - follow the hint above and re-run this script.' s3_write = '[3/5] Writing user-level environment variables' backed_up = 'Previous environment variables backed up: {0}' written = 'Wrote ANTHROPIC_BASE_URL / ANTHROPIC_AUTH_TOKEN / CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC / CLAUDE_CODE_AUTO_MODE_SERVER' model_ok = 'Pinned default model: {0} (ANTHROPIC_MODEL; delete that user env var to follow Claude Code defaults again)' apikey_conflict = 'A user-level ANTHROPIC_API_KEY is also set and may conflict with this config; consider removing it.' settings_conflict = 'The env block in {0} points Claude Code at a different endpoint. It takes precedence over environment variables, so without a change Claude Code will not actually use QCode.' settings_other = 'ANTHROPIC_BASE_URL there: {0}' settings_keys = 'Mismatched keys: {0}' settings_ask = 'Switch these keys to QCode? (backs up the file first; only these keys change, ANTHROPIC_API_KEY becomes ANTHROPIC_AUTH_TOKEN, everything else is kept)' settings_ours = '{0} holds an earlier QCode setup that differs from this run; synced it to this run (backed up first).' settings_restore = 'Failed to write {0}; tried to restore it from the backup ({1}).' settings_model_note = 'ANTHROPIC_MODEL in settings.json was also set to {0}; delete that key there to follow Claude Code defaults again.' settings_left_title = 'Config was written, but {0} still points elsewhere, so Claude Code will not actually use QCode (see above).' settings_done = 'Updated the endpoint settings in settings.json (backup: {0})' settings_kept = 'Left unchanged: Claude Code will keep following settings.json. To use QCode later, re-run this script or delete the keys above.' settings_failed = 'Could not rewrite {0} safely; the file was left untouched. Set ANTHROPIC_BASE_URL / ANTHROPIC_AUTH_TOKEN in its env block to the QCode values and delete ANTHROPIC_API_KEY by hand.' settings_pins = 'The env block in {0} also pins these models (they also take precedence over environment variables). If they are another provider''s model names, QCode will answer "not a supported model":' settings_unparsable = '{0} is not valid JSON, so the automatic check was skipped. Make sure it does not set another provider''s ANTHROPIC_BASE_URL / ANTHROPIC_AUTH_TOKEN / ANTHROPIC_API_KEY.' s4_env = '[4/5] Checking the runtime environment' cli_installed = 'Claude Code is already installed: {0}' no_install = '-NoInstall: skipping install. Install it yourself with: npm install -g {0}' ask_install = 'Claude Code was not found. Install it with npm?' node_none = 'Node.js not found' node_low = 'Node.js {0} is older than v{1}' ask_winget = 'Install Node.js LTS with winget?' no_winget = 'winget not found. Install the LTS build from https://nodejs.org and re-run this script.' winget_fail = 'winget failed to install Node.js (exit code {0}). Install it manually from https://nodejs.org and re-run.' npm_missing = 'npm not found. Install Node.js first, then run: npm install -g {0}' npm_fail = 'npm install failed (exit code {0}). You can run it manually: npm.cmd install -g {1}' cli_done = 'Claude Code installed' cli_notfound = 'Install finished but claude is not on PATH in this session; please reopen PowerShell.' node_notready = 'Node.js is not ready. Your config is written; once Node is installed run: npm install -g {0}' s5_verify = '[5/5] Verifying access (sending one minimal test request; cost is negligible)...' verify_ok = 'Access verified - the model responded normally.' verify_usage = ' > Usage and request details: enter your key at {0}' verify_401 = 'The key is invalid or expired (HTTP {0}). Check it at {1} and re-run this script.' verify_model = 'Setup is correct, but the probe model {0} is currently unavailable (HTTP 400). This does not affect normal use.' verify_400 = 'Request rejected (HTTP 400): {0}' verify_404 = 'Wrong endpoint address (HTTP 404). BASE_URL should be https://{{domain}}/api with no trailing slash. Currently: {0}' verify_429 = 'Setup is correct (HTTP 429 = reached the service but rate-limited); it will work shortly.' verify_net = 'Network or node problem ({0}). Try another endpoint (-Domain asia); per-endpoint status: {1}' skip_verify = '-NoVerify: verification skipped.' done_title = 'All set! Summary:' sum_domain = ' Endpoint {0}' sum_way = ' Method user-level environment variables (backup in {0})' sum_settings = ' settings.json endpoint keys switched to QCode ({0})' sum_verified = ' Connectivity [OK] verified' reload_hint = ' New PowerShell / terminal sessions pick this up automatically; restart editors such as VS Code.' policy_hint = ' Note: your execution policy is {0}; running claude in a new PowerShell may fail with "cannot be loaded".' policy_fix = ' Fix without admin rights (affects only you): Set-ExecutionPolicy -Scope CurrentUser RemoteSigned (or run claude.cmd)' policy_set = 'Set CurrentUser PowerShell execution policy to RemoteSigned (was {0}; no admin rights, affects only your account)' sum_policy = ' Exec policy CurrentUser RemoteSigned (enabled for .ps1 scripts)' policy_gp_hint = ' Note: Group Policy ({0}={1}) blocks .ps1 scripts and overrides per-user settings.' policy_gp_fix = ' Workaround: run {0}.cmd in PowerShell (or {0} in CMD) to start without .ps1 scripts.' policy_signed_hint = ' Note: CurrentUser execution policy is AllSigned (kept as-is); run {0}.cmd in PowerShell, or run Set-ExecutionPolicy -Scope CurrentUser RemoteSigned' update_hint = ' To upgrade Claude Code later: claude update (this setup turns off background auto-update)' docs_hint = ' Docs and troubleshooting: {0}' ask_launch = 'Launch Claude Code now?' uninstall_conflict = '-Uninstall cannot be combined with -Key / -Domain / -Model / -Mirror / -NoInstall / -NoVerify.' uninstall_usage = 'Usage: -Uninstall [-Yes] [-DryRun] [-Lang zh|en]; -DryRun [-Key] [-Domain api|asia|us] [-Model] [-NoInstall] [-NoVerify] [-Yes] [-Lang zh|en]. -Uninstall removes only values this script wrote, not Node or the CLI.' uninstall_none = 'No settings written by this script were found.' uninstall_plan = 'Will remove the settings this script wrote:' uninstall_ask = 'Delete the settings above? [y/N]: ' uninstall_cancel = 'Cancelled. No files were changed.' uninstall_need_yes = 'No terminal to confirm. Re-run with -Yes to uninstall.' uninstall_done = 'Removed the settings this script wrote.' uninstall_reload = 'Open a new terminal for the change to take effect.' uninstall_cli = 'This script does not uninstall the CLI. To remove it: npm uninstall -g {0}' uninstall_kept = 'kept {0}' uninstall_badjson = '{0} is not valid JSON (or could not be edited). Nothing was modified.' uninstall_other_base = 'ANTHROPIC_BASE_URL is not qcode.cc ({0}); left in place.' uninstall_backup_fail = 'Backup failed; nothing was modified.' uninstall_model_keep = 'The user-level ANTHROPIC_MODEL has no recorded value from this script (it is written only with -Model, which cannot be combined with -Uninstall), so it was kept. Delete that user environment variable yourself if you want it gone.' dry_header = 'dry-run: printing the plan only. No files, no install, no verify request.' dry_key_missing = 'No key was provided; the plan uses a placeholder and will not send it.' dry_settings_skip = 'settings.json does not exist and will not be created.' dry_settings_sync = 'settings.json plan ({0}):' dry_settings_ask = 'settings.json points elsewhere; an interactive run would ask (default Y).' dry_install_skip = '-NoInstall: Node.js / CLI will not be installed.' dry_node = 'Node.js: {0}' dry_cli = 'CLI {0}: {1}' dry_mirror = 'mirror: {0}' dry_policy_set = 'ExecutionPolicy (CurrentUser): {0} -> RemoteSigned' dry_policy_keep = 'ExecutionPolicy (CurrentUser): {0} (keep)' dry_policy_gp = 'ExecutionPolicy: controlled by {0}={1} (keep; use {2}.cmd in PowerShell)' dry_verify = 'Would verify (not sent): {0} {1} model={2}' dry_verify_skip = '-NoVerify: verification skipped.' dry_uninstall = 'dry-run + uninstall: listing deletions only. No files will change.' dry_env = 'User-level environment variables to write (key masked):' dry_win_note = 'Windows does not write a shell block; the variables above are what would be written.' dry_auth = 'auth.json would set OPENAI_API_KEY={0}' dry_toml = 'config.toml would merge these top-level keys and write [model_providers.qcode]:' dry_pick = 'dry-run does not ask; using the fastest endpoint {0}.' dry_will_install = 'Would install: {0}' enjoy = 'Run claude any time to get started. Enjoy!' ack = 'Done - press Enter to close this window...' failed = 'Setup did not complete: {0}' } } function T([string]$Key) { $tbl = $MSG[$UiLang] if (-not $tbl.ContainsKey($Key)) { return $Key } return $tbl[$Key] } function TF([string]$Key) { $fmt = T $Key # 零参数时也要把 {{ }} 反转义,否则同一条文案走两条路会渲染出不同结果。 if ($args.Count -eq 0) { return $fmt.Replace('{{', '{').Replace('}}', '}') } # 显式 [object[]]:杜绝将来某个实参是数组时误绑到 Format(string,object) 重载。 return [string]::Format($fmt, [object[]]$args) } function Say([string]$m) { Write-Host $m } function Info([string]$m) { Write-Host "==> $m" -ForegroundColor Blue } function Ok([string]$m) { Write-Host " [OK] $m" -ForegroundColor Green } function Warn2([string]$m){ Write-Host " [! ] $m" -ForegroundColor Yellow } function Fail([string]$m) { Write-Host " [X ] $m" -ForegroundColor Red } #region ---- 公共段(与 codex.ps1 同源,见 _ps_common.ps1)---- try { Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass -Force -ErrorAction Stop } catch { } function Resolve-CliCommand([string]$Name) { foreach ($candidate in @("$Name.cmd", "$Name.exe", "$Name.bat")) { $command = Get-Command $candidate -ErrorAction SilentlyContinue if ($command -and $command.Source) { return $command.Source } } $fallback = Get-Command $Name -ErrorAction SilentlyContinue if (-not $fallback) { return $null } if ($fallback.Source -and $fallback.Source.ToLowerInvariant().EndsWith(".ps1", [System.StringComparison]::Ordinal)) { $cmdPath = [System.IO.Path]::ChangeExtension($fallback.Source, ".cmd") if (Test-Path $cmdPath) { return $cmdPath } } return $fallback.Source } function Update-EnvPath { $parts = @(); $seen = @{} $groups = @( $env:Path, [System.Environment]::GetEnvironmentVariable("Path", "Machine"), [System.Environment]::GetEnvironmentVariable("Path", "User") ) foreach ($group in $groups) { if ([string]::IsNullOrWhiteSpace($group)) { continue } foreach ($item in ($group -split ";")) { $entry = $item.Trim() if ([string]::IsNullOrWhiteSpace($entry)) { continue } $key = $entry.TrimEnd("\").ToLowerInvariant() if (-not $seen.ContainsKey($key)) { $seen[$key] = $true; $parts += $entry } } } $env:Path = ($parts -join ";") } $script:KeyTrimChars = [char[]]@( ' ', "`t", "`r", "`n", '"', "'", '`', [char]0x201C, [char]0x201D, [char]0x2018, [char]0x2019, [char]0xFF02, [char]0xFF07, [char]0x3000 ) function Get-CleanApiKey([string]$Value) { if ($null -eq $Value) { return "" } $key = $Value while ($true) { $trimmed = $key.Trim($script:KeyTrimChars) if ($trimmed -eq $key) { break } $key = $trimmed } return $key } function Assert-ApiKey([string]$Key) { if ([string]::IsNullOrWhiteSpace($Key)) { throw (T 'key_empty') } if ($Key -notmatch '^[A-Za-z0-9._\-]+$') { throw (T 'key_badchar') } } function Format-KeyTail([string]$Key) { if ($Key.Length -le 4) { return "****" } return $Key.Substring($Key.Length - 4) } # 国内镜像:只在真正要 npm install 时决定。优先级 -Mirror > $env:QCODE_MIRROR > auto。 # auto:用户自己配过 npm 源(环境变量 npm_config_registry / %USERPROFILE%\.npmrc 里的 registry=)就尊重,不动; # 否则 registry.npmjs.org 5 秒内连不上才切。返回提示文案的键(mirror_cn / mirror_auto),不切返回 $null。 # Node.js 本身走 winget 安装(源由 winget 决定),这里管不到。 function Get-NpmMirrorReason { $m = if ($Mirror) { $Mirror } else { "$env:QCODE_MIRROR".Trim().ToLowerInvariant() } if ($m -eq 'off') { return $null } if ($m -eq 'cn') { return 'mirror_cn' } if (-not [string]::IsNullOrWhiteSpace($env:npm_config_registry)) { return $null } try { $npmrcHome = if ($env:USERPROFILE) { $env:USERPROFILE } else { $HOME } $npmrc = Join-Path $npmrcHome '.npmrc' if ((Test-Path -LiteralPath $npmrc) -and (Select-String -LiteralPath $npmrc -Pattern '^\s*registry\s*=' -Quiet)) { return $null } } catch { } try { $null = Invoke-WebRequest -Uri 'https://registry.npmjs.org/' -TimeoutSec 5 -UseBasicParsing return $null } catch { } return 'mirror_auto' } # 注意:本函数**不返回**退出码,调用点读 $LASTEXITCODE。 # 若写成 `& $Script; return $LASTEXITCODE`,原生命令的 stdout 会一并成为函数的 # 管道输出,调用点拿到的是 [输出行..., 退出码] 的数组,`$rc -ne 0` 于是恒为真 # —— 每次 npm 安装成功都会被误报成失败。 function Invoke-Native { param([scriptblock]$Script) $prev = $null $hasVar = Get-Variable -Name PSNativeCommandUseErrorActionPreference -Scope Global -ErrorAction SilentlyContinue if ($hasVar) { $prev = $global:PSNativeCommandUseErrorActionPreference; $global:PSNativeCommandUseErrorActionPreference = $false } # npm 几乎必然往 stderr 写 warn/notice;EAP=Stop 叠加原生命令 stderr 在 Windows # PowerShell 上有变成 NativeCommandError 终止错误的已知风险,这里临时降级。 $prevEap = $ErrorActionPreference $ErrorActionPreference = 'Continue' try { & $Script } finally { $ErrorActionPreference = $prevEap if ($hasVar) { $global:PSNativeCommandUseErrorActionPreference = $prev } } } # ---- 执行策略:只读当前状态,绝不使用无 -Scope 的 Get-ExecutionPolicy ---- function Get-QcPolicyState { $mp = [string](Get-ExecutionPolicy -Scope MachinePolicy -ErrorAction SilentlyContinue) $up = [string](Get-ExecutionPolicy -Scope UserPolicy -ErrorAction SilentlyContinue) $cu = [string](Get-ExecutionPolicy -Scope CurrentUser -ErrorAction SilentlyContinue) $lm = [string](Get-ExecutionPolicy -Scope LocalMachine -ErrorAction SilentlyContinue) if ([string]::IsNullOrWhiteSpace($mp)) { $mp = 'Undefined' } if ([string]::IsNullOrWhiteSpace($up)) { $up = 'Undefined' } if ([string]::IsNullOrWhiteSpace($cu)) { $cu = 'Undefined' } if ([string]::IsNullOrWhiteSpace($lm)) { $lm = 'Undefined' } $gpScope = '' $gpPolicy = '' if ($mp -ne 'Undefined') { $gpScope = 'MachinePolicy'; $gpPolicy = $mp } elseif ($up -ne 'Undefined') { $gpScope = 'UserPolicy'; $gpPolicy = $up } $allow = @('RemoteSigned', 'Unrestricted', 'Bypass') if ($gpScope) { if ($allow -contains $gpPolicy) { $action = 'gp-ok' } else { $action = 'gp-blocked' } } elseif ($allow -contains $cu) { $action = 'keep-ok' } elseif ($cu -eq 'AllSigned') { $action = 'keep-signed' } elseif ($cu -eq 'Undefined' -and ($allow -contains $lm)) { $action = 'keep-ok' } else { $action = 'set' } if ($cu -ne 'Undefined') { $effNew = $cu } elseif ($lm -ne 'Undefined') { $effNew = $lm } else { $effNew = 'Restricted' } return @{ Action = $action GpScope = $gpScope GpPolicy = $gpPolicy Current = $cu Machine = $lm EffectiveNewWindow = $effNew } } # ---- PS 7 -> Windows PowerShell 5.1 跨壳同步(仅 Windows)---- function Invoke-QcWinPs51Sync { try { if ($PSVersionTable.PSVersion.Major -lt 6) { return @{ Updated = $false; Previous = '' } } if ([System.Environment]::OSVersion.Platform -ne 'Win32NT') { return @{ Updated = $false; Previous = '' } } if ([string]::IsNullOrWhiteSpace($env:SystemRoot)) { return @{ Updated = $false; Previous = '' } } $winPs = Join-Path $env:SystemRoot 'System32\WindowsPowerShell\v1.0\powershell.exe' if (-not (Test-Path -LiteralPath $winPs)) { return @{ Updated = $false; Previous = '' } } $ps51Code = @' $ErrorActionPreference = 'SilentlyContinue' $WarningPreference = 'SilentlyContinue' $mp = [string](Get-ExecutionPolicy -Scope MachinePolicy) $up = [string](Get-ExecutionPolicy -Scope UserPolicy) if (($mp -and $mp -ne 'Undefined') -or ($up -and $up -ne 'Undefined')) { exit 0 } $cu = [string](Get-ExecutionPolicy -Scope CurrentUser) $lm = [string](Get-ExecutionPolicy -Scope LocalMachine) if (-not $cu) { $cu = 'Undefined' } if (-not $lm) { $lm = 'Undefined' } $allow = @('RemoteSigned', 'Unrestricted', 'Bypass') if ($allow -contains $cu) { exit 0 } if ($cu -eq 'AllSigned') { exit 0 } if ($cu -eq 'Undefined' -and ($allow -contains $lm)) { exit 0 } Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned -Force $now = [string](Get-ExecutionPolicy -Scope CurrentUser) if ($allow -contains $now) { Write-Output ('SET:' + $cu) } '@ $b64 = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($ps51Code)) $psi = New-Object System.Diagnostics.ProcessStartInfo $psi.FileName = $winPs $psi.Arguments = '-NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -EncodedCommand ' + $b64 $psi.UseShellExecute = $false $psi.CreateNoWindow = $true $psi.RedirectStandardOutput = $true $psi.RedirectStandardError = $true $proc = New-Object System.Diagnostics.Process $proc.StartInfo = $psi try { [void]$proc.Start() $outTask = $proc.StandardOutput.ReadToEndAsync() $errTask = $proc.StandardError.ReadToEndAsync() if (-not $proc.WaitForExit(5000)) { try { $proc.Kill() } catch { } return @{ Updated = $false; Previous = '' } } $out = [string]$outTask.Result $null = $errTask.Result foreach ($line in ($out -split "`r?`n")) { if ($line -match '^SET:(\S+)$') { return @{ Updated = $true; Previous = $Matches[1] } } } return @{ Updated = $false; Previous = '' } } finally { try { $proc.Dispose() } catch { } } } catch { return @{ Updated = $false; Previous = '' } } } # ---- 设置 CurrentUser 执行策略(PS 5.1 的 ExecutionPolicyOverride 不得中断脚本)---- function Invoke-QcEnsureExecutionPolicy([string]$BackupDir, [string]$Stamp) { $st = Get-QcPolicyState $updated = $false $prev = $st.Current if ($st.Action -eq 'set') { try { Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned -Force -ErrorAction SilentlyContinue -WarningAction SilentlyContinue } catch { } $after = [string](Get-ExecutionPolicy -Scope CurrentUser -ErrorAction SilentlyContinue) if (@('RemoteSigned', 'Unrestricted', 'Bypass') -contains $after) { $updated = $true } } if ($st.Action -in @('set', 'keep-ok')) { $ps51 = Invoke-QcWinPs51Sync if ($ps51.Updated -and -not $updated) { $updated = $true $prev = $ps51.Previous } } if ($updated) { try { if ($BackupDir) { if (-not (Test-Path -LiteralPath $BackupDir)) { $null = New-Item -ItemType Directory -Path $BackupDir -Force } $polBak = Join-Path $BackupDir ("backup-execution-policy-$Stamp.json") $rec = [ordered]@{ Scope = 'CurrentUser' Previous = $prev UpdatedTo = 'RemoteSigned' RestoreCommand = "Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy $prev -Force" } $utf8NoBom = New-Object System.Text.UTF8Encoding($false) [System.IO.File]::WriteAllText($polBak, (($rec | ConvertTo-Json) + "`n"), $utf8NoBom) } } catch { } Ok (TF 'policy_set' $prev) } $finalSt = Get-QcPolicyState return @{ Updated = $updated Previous = $prev State = $finalSt } } # ---- 收尾:按最终状态给出准确提示 ---- function Write-QcPolicySummaryHint($EnsureResult, [string]$Cli) { $st = if ($EnsureResult -and $EnsureResult.State) { $EnsureResult.State } else { Get-QcPolicyState } if ($st.Action -eq 'gp-blocked') { Warn2 (TF 'policy_gp_hint' $st.GpScope $st.GpPolicy) Say (TF 'policy_gp_fix' $Cli) } elseif ($st.Action -eq 'keep-signed') { Warn2 (TF 'policy_signed_hint' $Cli) } elseif ($st.Action -eq 'set') { Warn2 (TF 'policy_hint' $st.EffectiveNewWindow) Say (T 'policy_fix') } } #endregion function Confirm-Default([string]$Prompt, [bool]$DefaultYes) { if ($Yes) { return $DefaultYes } $suffix = if ($DefaultYes) { "[Y/n]" } else { "[y/N]" } $ans = Read-Host "$Prompt $suffix" if ([string]::IsNullOrWhiteSpace($ans)) { return $DefaultYes } return @("y", "yes") -contains $ans.Trim().ToLowerInvariant() } # ---------- -DryRun / -Uninstall(任何写盘、任何密钥询问之前返回)---------- # 正常安装路径不经过这里。不调用 exit(irm|iex 会关掉窗口),退出码交给 $QcExit。 # settings.json 与安装路径相同:严格 JSON 校验后 ConvertFrom-Json,删值匹配的键,ConvertTo-Json -Depth 100 写回。 # 没有要删的键则不改文件。PS 5.1 下 Trim 为 `{}` 时不解析(那个版本会得到 $null)。 # 本段不修改安装用的环境变量写入逻辑。 function Format-QcSecret([string]$Value) { if ($Value -eq 'cr_<未提供>') { return 'cr_****<未提供>' } if ($Value.Length -le 4) { return '****' } $tail = $Value.Substring($Value.Length - 4) if ($Value.StartsWith('cr_', [System.StringComparison]::Ordinal)) { return ('cr_****' + $tail) } return ('****' + $tail) } function Test-QcConsole { try { if ([Console]::IsInputRedirected) { return $false } if (-not [Environment]::UserInteractive) { return $false } return $true } catch { return $false } } function Test-QcQcodeHost([string]$Url) { if ([string]::IsNullOrEmpty($Url)) { return $false } $u = $Url.Trim() $p = $u.ToLowerInvariant().IndexOf('://', [System.StringComparison]::Ordinal) if ($p -ge 0) { $u = $u.Substring($p + 3) } $u = ($u -split '/')[0] if ($u.IndexOf('@', [System.StringComparison]::Ordinal) -ge 0) { $parts = $u.Split('@'); $u = $parts[$parts.Length - 1] } $u = ($u -split ':')[0].ToLowerInvariant() if ($u -eq 'qcode.cc') { return $true } if ($u.EndsWith('.qcode.cc', [System.StringComparison]::Ordinal)) { return $true } return $false } function Test-QcSwitch([object]$Value, [string]$Want) { if ($null -eq $Value) { return $false } if ($Value -is [string]) { return ($Value -ceq $Want) } # JSON 数字 1 / 0。字符串分支已用 -ceq,避免 "01" 被当成 1。 if ($Value -is [int] -or $Value -is [long] -or $Value -is [decimal]) { return ([string]$Value -ceq $Want) } if ($Value -is [double]) { if ($Want -ceq '1') { return ($Value -eq 1.0) } if ($Want -ceq '0') { return ($Value -eq 0.0) } } return $false } function Read-QcJsonFile([string]$Path) { $bytes = [System.IO.File]::ReadAllBytes($Path) $utf8 = New-Object System.Text.UTF8Encoding $false $text = $utf8.GetString($bytes) $bom = '' if ($text.Length -gt 0 -and $text[0] -eq [char]0xFEFF) { $bom = [string]([char]0xFEFF); $text = $text.Substring(1) } return @{ Bom = $bom; Body = $text } } function Get-QcProp($Obj, [string]$Name) { if ($null -eq $Obj) { return $null } $p = $Obj.PSObject.Properties[$Name] if (-not $p) { return $null } return $p } # 决定删哪些 env 键(最后一次出现的值说了算,与 ConvertFrom-Json 一致),再按原文摘掉每一次出现。 function Get-QcClaudeSettingsEdit([string]$Body) { $notes = New-Object System.Collections.Generic.List[string] $remove = New-Object System.Collections.Generic.List[string] # PS 5.1 把 `{}` 解析成 $null。整段只有空对象时直接当未改动返回,不写文件。 if ($Body.Trim() -eq '{}') { return @{ Text = $Body; Removed = $remove; Notes = $notes; Changed = $false } } if ($PSVersionTable.PSVersion.Major -ge 6) { ([System.Text.Json.JsonDocument]::Parse($Body)).Dispose() } $data = ConvertFrom-Json -InputObject $Body if ($null -eq $data) { return @{ Text = $Body; Removed = $remove; Notes = $notes; Changed = $false } } if ($data -isnot [System.Management.Automation.PSCustomObject]) { throw 'not-object' } $envProp = Get-QcProp $data 'env' if (-not $envProp -or $envProp.Value -isnot [System.Management.Automation.PSCustomObject]) { return @{ Text = $Body; Removed = $remove; Notes = $notes; Changed = $false } } $envObj = $envProp.Value $baseForeign = $false $base = Get-QcProp $envObj 'ANTHROPIC_BASE_URL' if ($base) { if ($base.Value -is [string] -and (Test-QcQcodeHost ([string]$base.Value))) { [void]$remove.Add('ANTHROPIC_BASE_URL') } else { $baseForeign = $true [void]$notes.Add(('KEEP ANTHROPIC_BASE_URL ' + [string]$base.Value)) } } $tok = Get-QcProp $envObj 'ANTHROPIC_AUTH_TOKEN' if ($tok) { $cr = ($tok.Value -is [string] -and ([string]$tok.Value).StartsWith('cr_', [System.StringComparison]::Ordinal)) if ($cr -and -not $baseForeign) { [void]$remove.Add('ANTHROPIC_AUTH_TOKEN') } elseif (-not $cr) { [void]$notes.Add('KEEP ANTHROPIC_AUTH_TOKEN not-cr') } } # Windows 没有 rc 可核对模型名,settings 里的 ANTHROPIC_MODEL 一律保留。 if (Get-QcProp $envObj 'ANTHROPIC_MODEL') { [void]$notes.Add('KEEP ANTHROPIC_MODEL unconfirmed') } if ($remove.Count -eq 0) { return @{ Text = $Body; Removed = $remove; Notes = $notes; Changed = $false } } foreach ($k in @($remove)) { [void]$envObj.PSObject.Properties.Remove($k) } $newJson = ConvertTo-Json -InputObject $data -Depth 100 $back = ConvertFrom-Json -InputObject $newJson $left = ConvertTo-Json -InputObject $back -Depth 100 -Compress $right = ConvertTo-Json -InputObject $data -Depth 100 -Compress if ($left -cne $right) { throw 'round-trip mismatch' } return @{ Text = ($newJson + "`n"); Removed = $remove; Notes = $notes; Changed = $true } } function Get-QcUserHome { if ($env:USERPROFILE) { return $env:USERPROFILE } return $HOME } function Invoke-QcUninstall { try { if ($DryRun) { Info (T 'dry_uninstall') } $userHome = Get-QcUserHome $notes = New-Object System.Collections.Generic.List[string] $plan = New-Object System.Collections.Generic.List[string] $envDeletes = New-Object System.Collections.Generic.List[string] $envOld = @{} $baseCur = [Environment]::GetEnvironmentVariable('ANTHROPIC_BASE_URL', 'User') $baseForeign = (-not [string]::IsNullOrEmpty($baseCur)) -and -not (Test-QcQcodeHost $baseCur) $names = @( 'ANTHROPIC_BASE_URL', 'ANTHROPIC_AUTH_TOKEN', 'CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC', 'CLAUDE_CODE_AUTO_MODE_SERVER' ) foreach ($name in $names) { $cur = [Environment]::GetEnvironmentVariable($name, 'User') if ([string]::IsNullOrEmpty($cur)) { continue } $take = $false if ($name -eq 'ANTHROPIC_BASE_URL' -and -not $baseForeign -and (Test-QcQcodeHost $cur)) { $take = $true } elseif ($name -eq 'ANTHROPIC_AUTH_TOKEN' -and -not $baseForeign -and $cur.StartsWith('cr_', [System.StringComparison]::Ordinal)) { $take = $true } elseif ($name -eq 'CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC' -and $cur -ceq '1') { $take = $true } elseif ($name -eq 'CLAUDE_CODE_AUTO_MODE_SERVER' -and $cur -ceq '0') { $take = $true } if ($take) { [void]$envDeletes.Add($name) $envOld[$name] = $cur [void]$plan.Add(('用户环境变量 ' + $name)) } elseif ($name -eq 'ANTHROPIC_BASE_URL') { [void]$notes.Add((TF 'uninstall_other_base' $cur)) } elseif ($name -eq 'ANTHROPIC_AUTH_TOKEN' -and $baseForeign -and $cur.StartsWith('cr_', [System.StringComparison]::Ordinal)) { # 别家地址已经提示过;cr_ 不是 QCode 专属,不再加第二条。 } else { [void]$notes.Add((TF 'uninstall_kept' ($name + ' value-mismatch'))) } } $modelCur = [Environment]::GetEnvironmentVariable('ANTHROPIC_MODEL', 'User') if (-not [string]::IsNullOrEmpty($modelCur)) { [void]$notes.Add((T 'uninstall_model_keep')) } $claudeDir = if ($env:CLAUDE_CONFIG_DIR) { $env:CLAUDE_CONFIG_DIR } else { Join-Path $userHome '.claude' } $settingsPath = Join-Path $claudeDir 'settings.json' $settingsNew = $null $settingsBom = '' if (Test-Path -LiteralPath $settingsPath) { $loaded = Read-QcJsonFile $settingsPath $settingsBom = $loaded.Bom try { $ed = Get-QcClaudeSettingsEdit $loaded.Body } catch { Fail (TF 'uninstall_badjson' $settingsPath) return 1 } foreach ($nt in $ed.Notes) { if ($nt.StartsWith('KEEP ANTHROPIC_BASE_URL ', [System.StringComparison]::Ordinal)) { $shown = $nt.Substring('KEEP ANTHROPIC_BASE_URL '.Length) [void]$notes.Add((TF 'uninstall_other_base' $shown)) } else { [void]$notes.Add((TF 'uninstall_kept' $nt)) } } if ($ed.Changed) { $settingsNew = $settingsBom + [string]$ed.Text foreach ($k in $ed.Removed) { [void]$plan.Add(('settings.json env.' + $k)) } } } foreach ($nt in $notes) { Warn2 $nt } if ($plan.Count -eq 0) { Say (T 'uninstall_none') return 0 } Say (T 'uninstall_plan') foreach ($item in $plan) { Say (' ' + $item) } if ($DryRun) { return 0 } if (-not $Yes) { if (-not (Test-QcConsole)) { Fail (T 'uninstall_need_yes'); return 2 } $ans = Read-Host (T 'uninstall_ask') if ([string]::IsNullOrWhiteSpace($ans) -or (@('y', 'yes') -notcontains $ans.Trim().ToLowerInvariant())) { Say (T 'uninstall_cancel') return 1 } } $stamp = Get-Date -Format 'yyyyMMddHHmmss' try { if ($envDeletes.Count -gt 0) { $backupDir = Join-Path $userHome '.qcode' if (-not (Test-Path -LiteralPath $backupDir)) { New-Item -ItemType Directory -Path $backupDir -Force | Out-Null } $backupFile = Join-Path $backupDir ('backup-claude-code-' + $stamp + '.json') $bag = [ordered]@{} foreach ($name in $envDeletes) { $bag[$name] = $envOld[$name] } $bag | ConvertTo-Json | Set-Content -Path $backupFile -Encoding UTF8 Ok (TF 'backed_up' $backupFile) } if ($null -ne $settingsNew) { $settingsBak = $settingsPath + '.bak.' + $stamp Copy-Item -LiteralPath $settingsPath -Destination $settingsBak Ok (TF 'backed_up' $settingsBak) } } catch { Fail (T 'uninstall_backup_fail') return 1 } foreach ($name in $envDeletes) { [Environment]::SetEnvironmentVariable($name, $null, 'User') } if ($null -ne $settingsNew) { $utf8 = New-Object System.Text.UTF8Encoding $false [System.IO.File]::WriteAllText($settingsPath, $settingsNew, $utf8) } Ok (T 'uninstall_done') Say (T 'uninstall_reload') Say (TF 'uninstall_cli' $NpmPkg) return 0 } catch { Fail (TF 'failed' $_.Exception.Message) return 1 } } function Invoke-QcPickHost { $dom = $Domain if ($dom -eq 'eu') { $dom = 'us' } if (-not [string]::IsNullOrEmpty($dom)) { return ($dom + '.qcode.cc') } $hosts = [ordered]@{ 'api.qcode.cc' = (T 'dom_api') 'asia.qcode.cc' = (T 'dom_asia') 'us.qcode.cc' = (T 'dom_us') } Info (T 's1_probing') $best = 'api.qcode.cc' $bestMs = [int]::MaxValue $found = $false $i = 0 foreach ($h in $hosts.Keys) { $i++ $ms = $null $sw = [System.Diagnostics.Stopwatch]::StartNew() try { Invoke-WebRequest -Uri "https://$h/v1/models" -Method GET -TimeoutSec 6 -UseBasicParsing | Out-Null $sw.Stop(); $ms = [int]$sw.ElapsedMilliseconds } catch { if ($_.Exception.Response) { $sw.Stop(); $ms = [int]$sw.ElapsedMilliseconds } } $disp = if ($null -ne $ms) { "$ms ms" } else { (T 'timeout') } Say (" $i) $h - $($hosts[$h]) [$disp]") if ($null -ne $ms -and $ms -lt $bestMs) { $bestMs = $ms; $best = $h; $found = $true } } Say (TF 'dry_pick' $best) return $best } function Invoke-QcDryRun { try { Say '' Say (TF 'banner' $ScriptVersion) Say (T 'dry_header') $selected = Invoke-QcPickHost $base = 'https://' + $selected + '/api' Ok (TF 'domain_ok' $selected $base) $key = $Key if ([string]::IsNullOrWhiteSpace($key) -and -not [string]::IsNullOrWhiteSpace($env:QCODE_API_KEY)) { $key = $env:QCODE_API_KEY Info (T 'key_env') } if ([string]::IsNullOrWhiteSpace($key)) { $key = 'cr_<未提供>' Say (T 'dry_key_missing') } else { $raw = $key $key = Get-CleanApiKey $key if ($key -ne $raw) { Warn2 (T 'key_cleaned') } Assert-ApiKey $key if (-not $key.StartsWith('cr_', [System.StringComparison]::Ordinal)) { Warn2 (T 'key_noprefix') } } $masked = Format-QcSecret $key Say (' key=' + $masked) Say (T 'dry_env') Say ('ANTHROPIC_BASE_URL=' + $base) Say ('ANTHROPIC_AUTH_TOKEN=' + $masked) Say 'CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1' Say 'CLAUDE_CODE_AUTO_MODE_SERVER=0' if ($Model) { Say ('ANTHROPIC_MODEL=' + $Model) } Say (T 'dry_win_note') $userHome = Get-QcUserHome $claudeDir = if ($env:CLAUDE_CONFIG_DIR) { $env:CLAUDE_CONFIG_DIR } else { Join-Path $userHome '.claude' } $settingsPath = Join-Path $claudeDir 'settings.json' if (-not (Test-Path -LiteralPath $settingsPath)) { Say (T 'dry_settings_skip') } else { Say (TF 'dry_settings_sync' $settingsPath) try { $rawText = (Read-QcJsonFile $settingsPath).Body $sj = ConvertFrom-Json -InputObject $rawText $envProp = Get-QcProp $sj 'env' if (-not $envProp -or $envProp.Value -isnot [System.Management.Automation.PSCustomObject]) { Say ' settings: NOENV' } else { $ep = $envProp.Value.PSObject.Properties $conf = New-Object System.Collections.Generic.List[string] $otherBase = if ($ep['ANTHROPIC_BASE_URL']) { [string]$ep['ANTHROPIC_BASE_URL'].Value } else { '' } if ($ep['ANTHROPIC_BASE_URL'] -and $otherBase.TrimEnd('/') -cne $base) { [void]$conf.Add('ANTHROPIC_BASE_URL') } if ($ep['ANTHROPIC_AUTH_TOKEN'] -and ([string]$ep['ANTHROPIC_AUTH_TOKEN'].Value) -cne $key) { [void]$conf.Add('ANTHROPIC_AUTH_TOKEN') } if ($ep['ANTHROPIC_API_KEY']) { [void]$conf.Add('ANTHROPIC_API_KEY') } if ($Model -and $ep['ANTHROPIC_MODEL'] -and ([string]$ep['ANTHROPIC_MODEL'].Value) -cne $Model) { [void]$conf.Add('ANTHROPIC_MODEL') } if ($conf.Count -eq 0) { Say ' settings: NOCHANGE' } else { $own = $true if ($conf.Contains('ANTHROPIC_API_KEY')) { $own = $false } else { $hostOnly = '' if ($otherBase) { try { $hostOnly = ([System.Uri]$otherBase).Host } catch { $hostOnly = '?' } } if (-not ($hostOnly -eq '' -or $hostOnly -eq 'qcode.cc' -or $hostOnly.EndsWith('.qcode.cc', [System.StringComparison]::Ordinal))) { $own = $false } } if (-not $own) { Say (T 'dry_settings_ask') } foreach ($ck in $conf) { if ($ck -eq 'ANTHROPIC_API_KEY') { Say ' DEL ANTHROPIC_API_KEY'; continue } $ov = [string]$ep[$ck].Value $nv = $base if ($ck -eq 'ANTHROPIC_AUTH_TOKEN') { $nv = $key; $ov = Format-QcSecret $ov; $nv = Format-QcSecret $nv } elseif ($ck -eq 'ANTHROPIC_MODEL') { $nv = $Model } Say (' SYNC ' + $ck + ' ' + $ov + ' => ' + $nv) } } } } catch { Warn2 (TF 'settings_unparsable' $settingsPath) } } if ($NoInstall) { Say (T 'dry_install_skip') } else { $nv = 'none' $nodePath = Resolve-CliCommand 'node' if ($nodePath) { try { $nv = [string](& $nodePath -v 2>$null) } catch { $nv = 'unknown' } } $cv = 'none' $cliPath = Resolve-CliCommand $CliName if ($cliPath) { try { $cv = ([string](& $cliPath --version 2>$null)).Trim() } catch { $cv = 'unknown' } } Say (TF 'dry_node' $nv) Say (TF 'dry_cli' $CliName $cv) $major = $null if ($nv -match '^v?(\d+)\.') { $major = [int]$Matches[1] } $nodeOk = ($null -ne $major -and $major -ge $MinNodeMajor) if ($nodeOk -and $cliPath) { Say (TF 'dry_mirror' 'skip') } else { Say (TF 'dry_will_install' ('Node.js LTS via winget if missing or older than v' + $MinNodeMajor + '; npm install -g ' + $NpmPkg)) $mirrorMode = if ($Mirror) { $Mirror } else { "$env:QCODE_MIRROR".Trim().ToLowerInvariant() } if ($mirrorMode -eq 'off') { Say (TF 'dry_mirror' 'off') } elseif ($mirrorMode -eq 'cn') { Say (TF 'dry_mirror' 'cn https://registry.npmmirror.com') } else { $why = Get-NpmMirrorReason if ($why -eq 'mirror_auto') { Say (TF 'dry_mirror' 'auto-cn') } elseif ($why -eq 'mirror_cn') { Say (TF 'dry_mirror' 'cn https://registry.npmmirror.com') } else { Say (TF 'dry_mirror' 'auto-off') } } } $polSt = Get-QcPolicyState if ($polSt.Action -eq 'set') { Say (TF 'dry_policy_set' $polSt.Current) } elseif ($polSt.Action -eq 'gp-blocked') { Say (TF 'dry_policy_gp' $polSt.GpScope $polSt.GpPolicy $CliName) } else { Say (TF 'dry_policy_keep' $polSt.Current) } } if ($NoVerify) { Say (T 'dry_verify_skip') } else { Say (TF 'dry_verify' 'POST' ($base + '/v1/messages') $ProbeModel) } return 0 } catch { Fail (TF 'failed' $_.Exception.Message) return 1 } } $ApiKey = "" $VerifyOk = $true $Failed = $false $SettingsLeft = $false $PolicyResult = $null # 整个主体包在 try 里:错误路径一律 throw 而不是 exit。 # irm|iex 与 [scriptblock]::Create 都不构成"脚本文件帧",exit 会穿透到宿主 # 把用户的 PowerShell 窗口直接关掉,刚打印的错误信息一眼都看不到。 $QcExitSet = $false $QcExit = 0 try { if ($Uninstall) { foreach ($n in @('Key','Domain','Model','Mirror','NoInstall','NoVerify')) { if ($PSBoundParameters.ContainsKey($n)) { Fail (T 'uninstall_conflict') Say (T 'uninstall_usage') $QcExit = 2 $QcExitSet = $true return } } $QcExit = Invoke-QcUninstall if ($QcExit -is [System.Array]) { $QcExit = $QcExit[-1] } $QcExitSet = $true return } if ($DryRun) { $QcExit = Invoke-QcDryRun if ($QcExit -is [System.Array]) { $QcExit = $QcExit[-1] } $QcExitSet = $true return } $DomainHosts = [ordered]@{ "api.qcode.cc" = (T 'dom_api') "asia.qcode.cc" = (T 'dom_asia') "us.qcode.cc" = (T 'dom_us') } Say "" Say (TF 'banner' $ScriptVersion) Say (T 'banner_sub') Say "" # ---------- [1/5] 接入域 ---------- $SelectedHost = "" if ($Domain -eq "eu") { $Domain = "us" } # 09-25 EU 节点退役:eu 作 us 的别名,兼容老命令 if ($Domain -ne "") { $SelectedHost = "$Domain.qcode.cc" } if ($SelectedHost -eq "") { Info (T 's1_probing') $results = @() foreach ($h in $DomainHosts.Keys) { $ms = $null $sw = [System.Diagnostics.Stopwatch]::StartNew() try { Invoke-WebRequest -Uri "https://$h/v1/models" -Method GET -TimeoutSec 6 -UseBasicParsing | Out-Null $sw.Stop(); $ms = [int]$sw.ElapsedMilliseconds } catch { # 有响应体的错误(4xx)也算通,只有连接类异常才算超时 if ($_.Exception.Response) { $sw.Stop(); $ms = [int]$sw.ElapsedMilliseconds } } $results += [pscustomobject]@{ Host = $h; Label = $DomainHosts[$h]; Ms = $ms } } $alive = $results | Where-Object { $null -ne $_.Ms } | Sort-Object Ms $best = if ($alive) { $alive[0].Host } else { "api.qcode.cc" } Say "" $i = 0 foreach ($r in $results) { $i++ $disp = if ($null -ne $r.Ms) { "$($r.Ms)ms" } else { (T 'timeout') } Say "$i) $($r.Host) - $($r.Label) [$disp]" } Say "" $defIdx = 1 + [array]::IndexOf(@($DomainHosts.Keys), $best) $choice = if ($Yes) { "$defIdx" } else { Read-Host (TF 'pick_domain' $defIdx $best) } if ([string]::IsNullOrWhiteSpace($choice)) { $choice = "$defIdx" } $keys = @($DomainHosts.Keys) if ($choice -match '^\d{1,2}$' -and [int]$choice -ge 1 -and [int]$choice -le $keys.Count) { $SelectedHost = $keys[[int]$choice - 1] } else { Warn2 (TF 'bad_choice' $best) $SelectedHost = $best } } $BaseUrl = "https://$SelectedHost/api" Ok (TF 'domain_ok' $SelectedHost $BaseUrl) # ---------- [2/5] API 密钥 ---------- $ApiKey = $Key if ([string]::IsNullOrWhiteSpace($ApiKey) -and -not [string]::IsNullOrWhiteSpace($env:QCODE_API_KEY)) { $ApiKey = $env:QCODE_API_KEY Info (T 'key_env') } if ([string]::IsNullOrWhiteSpace($ApiKey)) { if ($Yes) { throw (T 'key_need') } Info (TF 's2_key' $DashboardUrl) $sec = Read-Host (T 'key_prompt') -AsSecureString $ApiKey = [System.Net.NetworkCredential]::new("", $sec).Password } $rawKey = $ApiKey $ApiKey = Get-CleanApiKey $ApiKey if ($ApiKey -ne $rawKey) { Warn2 (T 'key_cleaned') } Assert-ApiKey $ApiKey if (-not $ApiKey.StartsWith("cr_", [System.StringComparison]::Ordinal)) { Warn2 (T 'key_noprefix') if (-not (Confirm-Default (T 'still_go') $false)) { throw (T 'cancelled') } } else { Ok (TF 'key_ok' (Format-KeyTail $ApiKey)) } # ---------- [3/5] 写用户级环境变量 ---------- Info (T 's3_write') $stamp = Get-Date -Format "yyyyMMddHHmmss" # 域环境启用主目录重定向(HOMESHARE)时 $HOME 可能指向网络盘,与 CLI 实际读的 # %USERPROFILE% 不是同一处。与 codex.ps1 保持一致。 $userHome = if ($env:USERPROFILE) { $env:USERPROFILE } else { $HOME } $backupDir = Join-Path $userHome ".qcode" if (-not (Test-Path $backupDir)) { New-Item -ItemType Directory -Path $backupDir -Force | Out-Null } $old = [ordered]@{ ANTHROPIC_BASE_URL = [Environment]::GetEnvironmentVariable("ANTHROPIC_BASE_URL", "User") ANTHROPIC_AUTH_TOKEN = [Environment]::GetEnvironmentVariable("ANTHROPIC_AUTH_TOKEN", "User") CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC = [Environment]::GetEnvironmentVariable("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC", "User") CLAUDE_CODE_AUTO_MODE_SERVER = [Environment]::GetEnvironmentVariable("CLAUDE_CODE_AUTO_MODE_SERVER", "User") ANTHROPIC_MODEL = [Environment]::GetEnvironmentVariable("ANTHROPIC_MODEL", "User") } if (($old.Values | Where-Object { $_ }).Count -gt 0) { $backupFile = Join-Path $backupDir "backup-claude-code-$stamp.json" $old | ConvertTo-Json | Set-Content -Path $backupFile -Encoding UTF8 Ok (TF 'backed_up' $backupFile) } [Environment]::SetEnvironmentVariable("ANTHROPIC_BASE_URL", $BaseUrl, "User") [Environment]::SetEnvironmentVariable("ANTHROPIC_AUTH_TOKEN", $ApiKey, "User") [Environment]::SetEnvironmentVariable("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC", "1", "User") # auto mode: our gateway does not return safeguard_results, so server-side review is unavailable; # use the client-side classifier directly instead of the "isn't compatible" notice and the paused first action [Environment]::SetEnvironmentVariable("CLAUDE_CODE_AUTO_MODE_SERVER", "0", "User") $env:ANTHROPIC_BASE_URL = $BaseUrl $env:ANTHROPIC_AUTH_TOKEN = $ApiKey $env:CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC = "1" $env:CLAUDE_CODE_AUTO_MODE_SERVER = "0" Ok (T 'written') # 只在显式 -Model 时写;不传就不碰用户已有的 ANTHROPIC_MODEL(沿用 Claude Code 自带默认) if ($Model) { [Environment]::SetEnvironmentVariable("ANTHROPIC_MODEL", $Model, "User") $env:ANTHROPIC_MODEL = $Model Ok (TF 'model_ok' $Model) } # 与 sh 版对齐:别家中转脚本常留下 ANTHROPIC_API_KEY 或 settings.json 的 env 块, # 它们可能让 CLI 实际打到旧供应商,而我们自己发的验证请求却是通的(假阳性)。 if ([Environment]::GetEnvironmentVariable("ANTHROPIC_API_KEY", "User")) { Warn2 (T 'apikey_conflict') } # settings.json 的 env 优先级高于环境变量(官方文档原话,10-18 实测:留着别家中转的 ANTHROPIC_BASE_URL 时, # 请求全部打到别家,而下面的验证照样通过)。只在那里配了「另一套接入」时才动它:先备份,只改接入相关的几个键。 # 认 CLAUDE_CONFIG_DIR(Claude Code 自己也按它找配置目录)。 $claudeDir = if ($env:CLAUDE_CONFIG_DIR) { $env:CLAUDE_CONFIG_DIR } else { Join-Path $userHome ".claude" } $claudeSettings = Join-Path $claudeDir "settings.json" $SettingsSynced = $false $SettingsLeft = $false # settings.json 仍指向别处(用户拒绝或写入失败),Claude Code 实际不会走 QCode if ((Test-Path -LiteralPath $claudeSettings) -and (Select-String -LiteralPath $claudeSettings -Pattern '"env"' -Quiet -ErrorAction SilentlyContinue)) { $sj = $null try { $raw = [System.IO.File]::ReadAllText($claudeSettings) # PowerShell 7 的 ConvertFrom-Json 能吃注释和尾逗号,改写时会把注释丢掉;先按严格 JSON 校验,与 sh 版、PS 5.1 行为一致 if ($PSVersionTable.PSVersion.Major -ge 6) { ([System.Text.Json.JsonDocument]::Parse($raw)).Dispose() } $sj = ConvertFrom-Json -InputObject $raw } catch { $sj = $null } if ($sj -isnot [System.Management.Automation.PSCustomObject]) { Warn2 (TF 'settings_unparsable' $claudeSettings) } else { $envProp = $sj.PSObject.Properties['env'] $envObj = if ($envProp -and $envProp.Value -is [System.Management.Automation.PSCustomObject]) { $envProp.Value } else { $null } if ($envObj) { $ep = $envObj.PSObject.Properties $otherBase = if ($ep['ANTHROPIC_BASE_URL']) { [string]$ep['ANTHROPIC_BASE_URL'].Value } else { $null } $conflict = @() if ($null -ne $otherBase -and $otherBase.TrimEnd('/') -ne $BaseUrl) { $conflict += 'ANTHROPIC_BASE_URL' } if ($ep['ANTHROPIC_AUTH_TOKEN'] -and ([string]$ep['ANTHROPIC_AUTH_TOKEN'].Value) -cne $ApiKey) { $conflict += 'ANTHROPIC_AUTH_TOKEN' } if ($ep['ANTHROPIC_API_KEY']) { $conflict += 'ANTHROPIC_API_KEY' } if ($Model -and $ep['ANTHROPIC_MODEL'] -and ([string]$ep['ANTHROPIC_MODEL'].Value) -cne $Model) { $conflict += 'ANTHROPIC_MODEL' } if ($conflict.Count -gt 0) { # 本脚本以前写进去的 QCode 配置(换接入域 / 换 key 后重跑):没有 API_KEY,地址缺省或是 qcode.cc ⇒ 直接同步,不问 $otherHost = "" if ($otherBase) { try { $otherHost = ([System.Uri]$otherBase).Host } catch { $otherHost = "?" } } $own = ($conflict -notcontains 'ANTHROPIC_API_KEY') -and ($otherHost -eq "" -or $otherHost -eq "qcode.cc" -or $otherHost.EndsWith(".qcode.cc", [System.StringComparison]::Ordinal)) if ($own) { Say (" " + (TF 'settings_ours' $claudeSettings)) } else { Warn2 (TF 'settings_conflict' $claudeSettings) if ($otherBase) { Say (" " + (TF 'settings_other' $otherBase)) } Say (" " + (TF 'settings_keys' ($conflict -join ', '))) } if ($own -or (Confirm-Default (T 'settings_ask') $true)) { $settingsBak = "$claudeSettings.bak.$stamp" $writing = $false try { $hadCred = [bool]($ep['ANTHROPIC_AUTH_TOKEN'] -or $ep['ANTHROPIC_API_KEY']) if ($ep['ANTHROPIC_BASE_URL']) { $ep['ANTHROPIC_BASE_URL'].Value = $BaseUrl } if ($hadCred) { if ($ep['ANTHROPIC_AUTH_TOKEN']) { $ep['ANTHROPIC_AUTH_TOKEN'].Value = $ApiKey } else { $envObj | Add-Member -NotePropertyName 'ANTHROPIC_AUTH_TOKEN' -NotePropertyValue $ApiKey } } if ($ep['ANTHROPIC_API_KEY']) { $ep.Remove('ANTHROPIC_API_KEY') } if ($Model -and $ep['ANTHROPIC_MODEL']) { $ep['ANTHROPIC_MODEL'].Value = $Model } $newJson = ConvertTo-Json -InputObject $sj -Depth 100 # Windows PowerShell 5.1 的 ConvertTo-Json 在某些环境下会把数组写成 {"value":[...],"Count":n}。 # 写盘前把结果再解析、再序列化,与内存里目标对象的序列化结果比对;这类会层层叠加的变形会被拦下,不一致就不写。 $back = ConvertFrom-Json -InputObject $newJson if ((ConvertTo-Json -InputObject $back -Depth 100 -Compress) -cne (ConvertTo-Json -InputObject $sj -Depth 100 -Compress)) { throw "round-trip mismatch" } Copy-Item -LiteralPath $claudeSettings -Destination $settingsBak $writing = $true [System.IO.File]::WriteAllText($claudeSettings, $newJson + "`n", (New-Object System.Text.UTF8Encoding($false))) $SettingsSynced = $true Ok (TF 'settings_done' $settingsBak) if ($conflict -contains 'ANTHROPIC_MODEL') { Say (" " + (TF 'settings_model_note' $Model)) } } catch { $SettingsLeft = $true if ($writing) { try { Copy-Item -LiteralPath $settingsBak -Destination $claudeSettings -Force } catch { } Fail (TF 'settings_restore' $claudeSettings $settingsBak) } else { Fail (TF 'settings_failed' $claudeSettings) } } } else { Warn2 (T 'settings_kept'); $SettingsLeft = $true } } $pins = @() foreach ($k in @('ANTHROPIC_MODEL', 'ANTHROPIC_DEFAULT_OPUS_MODEL', 'ANTHROPIC_DEFAULT_SONNET_MODEL', 'ANTHROPIC_DEFAULT_HAIKU_MODEL', 'ANTHROPIC_SMALL_FAST_MODEL', 'CLAUDE_CODE_SUBAGENT_MODEL')) { if ($ep[$k] -and -not ($Model -and $k -eq 'ANTHROPIC_MODEL')) { $pins += " $k=$([string]$ep[$k].Value)" } } if ($pins.Count -gt 0) { Warn2 (TF 'settings_pins' $claudeSettings); foreach ($pl in $pins) { Say $pl } } } } } # ---------- [4/5] Node.js / Claude Code ---------- function Get-NodeMajor { $nodePath = Resolve-CliCommand "node" if (-not $nodePath) { return $null } $v = (& $nodePath -v 2>$null) if ($v -match '^v?(\d+)\.') { return [int]$Matches[1] } return $null } Info (T 's4_env') $CliReady = $false # 安装段单独兜异常:环境变量此时已写好,装 Node/CLI 失败不该让用户看到 # 「配置未完成」并跳过验证与摘要。 try { $cliPath = Resolve-CliCommand $CliName if ($cliPath) { Ok (TF 'cli_installed' $cliPath) $CliReady = $true } elseif ($NoInstall) { Warn2 (TF 'no_install' $NpmPkg) } elseif (Confirm-Default (T 'ask_install') $true) { $major = Get-NodeMajor if ($null -eq $major -or $major -lt $MinNodeMajor) { if ($null -eq $major) { Warn2 (T 'node_none') } else { Warn2 (TF 'node_low' $major $MinNodeMajor) } $winget = Resolve-CliCommand "winget" if ($winget) { if (Confirm-Default (T 'ask_winget') $true) { Invoke-Native { & $winget install OpenJS.NodeJS.LTS --accept-package-agreements --accept-source-agreements } $rc = $LASTEXITCODE Update-EnvPath $major = Get-NodeMajor if (($null -eq $major -or $major -lt $MinNodeMajor) -and $rc -ne 0) { Warn2 (TF 'winget_fail' $rc) } } } else { Warn2 (T 'no_winget') } } if ($null -ne $major -and $major -ge $MinNodeMajor) { $npmPath = Resolve-CliCommand "npm" if (-not $npmPath) { Warn2 (TF 'npm_missing' $NpmPkg) } else { $mirrorWhy = Get-NpmMirrorReason if ($mirrorWhy) { $env:npm_config_registry = 'https://registry.npmmirror.com'; $__qcMirrorSet = $true; Info (T $mirrorWhy) } Invoke-Native { & $npmPath install -g $NpmPkg } $rc = $LASTEXITCODE Update-EnvPath if ($rc -ne 0) { Warn2 (TF 'npm_fail' $rc $NpmPkg) } $cliPath = Resolve-CliCommand $CliName if ($cliPath) { Ok (T 'cli_done'); $CliReady = $true } else { Warn2 (T 'cli_notfound') } } } else { Warn2 (TF 'node_notready' $NpmPkg) } } } catch { Warn2 $_.Exception.Message } if (-not $NoInstall) { try { $PolicyResult = Invoke-QcEnsureExecutionPolicy -BackupDir $backupDir -Stamp $stamp } catch { } } # ---------- [5/5] 端到端验证 ---------- if ($NoVerify) { Warn2 (T 'skip_verify') } else { Info (T 's5_verify') $body = "{`"model`":`"$ProbeModel`",`"max_tokens`":16,`"messages`":[{`"role`":`"user`",`"content`":`"ping`"}]}" try { Invoke-RestMethod -Uri "$BaseUrl/v1/messages" -Method POST -TimeoutSec 40 ` -Headers @{ "Authorization" = "Bearer $ApiKey"; "anthropic-version" = "2023-06-01" } ` -ContentType "application/json" -Body $body | Out-Null Ok (T 'verify_ok') Say (TF 'verify_usage' $ProbeUrl) } catch { # switch 语句体内 $_ 会被重绑定成"当前被测试的值",不再是这里的 ErrorRecord。 # 必须先把 ErrorRecord 存下来,否则 default 分支里的 $_.Exception.Message 恒为空。 $err = $_ $VerifyOk = $false # 用 0 而不是 $null:0 不匹配任何 clause,必进 default,语义无歧义。 $code = 0 $bodyText = "" if ($err.Exception.Response) { try { $code = [int]$err.Exception.Response.StatusCode } catch { } try { $t = $err.ErrorDetails.Message; if ($t) { $bodyText = $t } } catch { } # PS 5.1 的 Invoke-RestMethod 抛 WebException 时 ErrorDetails 未必被填充, # 需要自己读响应流,否则 400 的降级判断在主力平台上失效。 if (-not $bodyText) { try { $st = $err.Exception.Response.GetResponseStream() if ($st) { $rd = New-Object System.IO.StreamReader($st); $bodyText = $rd.ReadToEnd() } } catch { } } } switch ($code) { { $_ -in 401, 403 } { Fail (TF 'verify_401' $code $DashboardUrl) } 400 { # 400 恰恰证明密钥有效、地址正确、网络通畅 —— 不该报成配置失败。 if ($bodyText -match 'not a supported model|not available on this endpoint') { Warn2 (TF 'verify_model' $ProbeModel); $VerifyOk = $true } else { Fail (TF 'verify_400' $bodyText) } } 404 { Fail (TF 'verify_404' $BaseUrl) } 429 { Ok (T 'verify_429'); $VerifyOk = $true } default { Fail (TF 'verify_net' $err.Exception.Message $ProbeUrl) } } } } # ---------- 收尾 ---------- Say "" Say "----------------------------------------" # 验证明确失败时绝不能打绿色的「配置完成」——那是在谎报成功。 if (-not ($VerifyOk -or $NoVerify)) { Warn2 (T 'done_partial') } elseif ($SettingsLeft) { Warn2 (TF 'settings_left_title' $claudeSettings) } else { Ok (T 'done_title') } Say (TF 'sum_domain' $SelectedHost) Say (TF 'sum_way' $backupDir) if ($SettingsSynced) { Say (TF 'sum_settings' $claudeSettings) } if ($PolicyResult -and $PolicyResult.Updated) { Say (T 'sum_policy') } # 验证请求绕过 settings.json:settings 仍指向别处时,「已验证」会误导 if ($VerifyOk -and -not $NoVerify -and -not $SettingsLeft) { Say (T 'sum_verified') } Say "" Say (T 'reload_hint') if ($CliReady) { Say (T 'update_hint') } # -Scope Process 的 Bypass 只救本次会话。按最终持久化状态准确提示。 try { Write-QcPolicySummaryHint -EnsureResult $PolicyResult -Cli $CliName } catch { } Say (TF 'docs_hint' $DocsUrl) Say "----------------------------------------" if ($CliReady -and -not $Yes) { if (Confirm-Default (T 'ask_launch') $false) { $p = Resolve-CliCommand $CliName if ($p) { & $p } else { Say (T 'enjoy') } } else { Say (T 'enjoy') } } else { Say (T 'enjoy') } } catch { $Failed = $true Fail (TF 'failed' $_.Exception.Message) } finally { # 供 .cmd 包装器读取:脚本内不能调 exit(irm|iex 下 exit 会关掉用户窗口), # 改为设置 $LASTEXITCODE,由 .cmd 里的 `exit $LASTEXITCODE` 传出去。 if ($QcExitSet) { $global:LASTEXITCODE = $QcExit } elseif ($Failed -or -not $VerifyOk -or $SettingsLeft) { $global:LASTEXITCODE = 1 } else { $global:LASTEXITCODE = 0 } # 恢复用户会话状态:irm|iex 是在调用者作用域执行的,不恢复会永久污染。 $ErrorActionPreference = $__qcPrevEAP $ProgressPreference = $__qcPrevPP if ($__qcMirrorSet) { $env:npm_config_registry = $__qcPrevNpmReg } # iex 是点源执行,脚本变量会留在用户交互会话里;通用名会覆盖用户自己的同名变量。 foreach ($v in @('ApiKey','rawKey','sec','MSG','err','code','bodyText','old','results','alive','best','i','r','choice','keys','body','sj','envProp','envObj','ep','otherBase','conflict','hadCred','newJson','back','settingsBak','pins','pl','k','claudeSettings','claudeDir','SettingsSynced','SettingsLeft','raw','otherHost','own','writing','__qcPrevEAP','__qcPrevPP','mirrorWhy','__qcPrevNpmReg','__qcMirrorSet','QcExit','QcExitSet','PolicyResult')) { Remove-Variable -Name $v -ErrorAction SilentlyContinue } }