# ============================================================ # QCode.cc — Codex 一键配置脚本 (Windows PowerShell) # QCode.cc — Codex one-click setup (Windows PowerShell) # # PowerShell: irm https://qcode.cc/install/codex.ps1 | iex # English: $env:QCODE_LANG='en'; irm https://qcode.cc/install/codex.ps1 | iex # CMD / 没有 irm: # powershell -NoProfile -ExecutionPolicy Bypass -Command "irm https://qcode.cc/install/codex.ps1 | iex" # 非交互 / unattended: # & ([scriptblock]::Create((irm https://qcode.cc/install/codex.ps1))) -Key cr_xxx -Yes # 环境变量 / 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/codex.ps1))) -DryRun # 卸载 / uninstall(只删本脚本写过且值仍匹配的项,不卸载 Node / CLI): # & ([scriptblock]::Create((irm https://qcode.cc/install/codex.ps1))) -Uninstall -Yes # # 写入 %USERPROFILE%\.codex 配置,不需要管理员权限。旧文件自动备份。 # Writes config into %USERPROFILE%\.codex; no admin rights needed. Old files are backed up. # 文档 / docs: https://docs.qcode.cc/docs/getting-started/one-click-install # ============================================================ param( [string]$Key = "", [ValidateSet("", "api", "asia", "us", "eu")][string]$Domain = "", [string]$Model = "", [string]$Lang = "", # zh / en;明确给了别的值(ar / fa / xx …)⇒ 英文(2026-11-13 起不再因 ValidateSet 直接报错退出) [ValidateSet("", "auto", "cn", "off")][string]$Mirror = "", [ValidateSet("", "app", "cli")][string]$Target = "", [switch]$Yes, [switch]$NoInstall, [switch]$NoVerify, [switch]$DryRun, [switch]$Uninstall ) $__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 = "@openai/codex" $CliName = "codex" $MinNodeMajor = 20 $DefaultModel = "gpt-6.2-sol" $FallbackModels = @("gpt-6.2-sol", "gpt-6.2-astra", "gpt-6.1-sol", "gpt-6.1-terra", "gpt-6-sol", "gpt-6-astra", "gpt-5.6-sol", "gpt-5.6-terra") $DocsUrl = "https://docs.qcode.cc/docs/getting-started/one-click-install" $ProbeUrl = "https://probe.qcode.cc/" $DashboardUrl = "https://qcode.cc/dashboard" 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 · Codex 一键配置 v{0}' banner_sub = ' 无需管理员权限 · 旧配置自动备份 · 配置后自动验证' dom_api = '按地区自动分流(北美 / 欧洲→美国,其余→亚洲节点)'; dom_asia = '亚洲(韩国 / 台湾 / 香港)' dom_us = '北美 / 欧洲'; dom_eu = '欧洲' s1_probing = '[1/6] 正在对 3 个接入域测速...' timeout = '超时' pick_domain = '请选择接入域 [回车 = {0}(最快: {1})]' bad_choice = '无效选择,使用最快项 {0}' domain_ok = '接入域: {0} -> base_url={1}' s2_key = '[2/6] 请输入 QCode.cc API 密钥({0} 复制)' key_prompt = 'API 密钥' key_need = '非交互模式必须提供 -Key(或先设环境变量 QCODE_API_KEY)。用法:& ([scriptblock]::Create((irm https://qcode.cc/install/codex.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 = '配置已写入,但验证未通过 —— 请按上面的提示处理后重跑本脚本。' cfg_load_fail = 'Codex 读不了写入后的 config.toml(多半是原文件里本来就有格式错误,合并时原样保留了):' cfg_load_bak = '原文件备份: {0} —— 修正上面提示的那一行;或删掉 config.toml 后重跑本脚本,生成干净的配置' s3_target = '[3/6] 你要在哪个 Codex 客户端里使用?' target_1 = ' 1) Codex 桌面版 App —— 只写配置文件,不安装 Node.js / CLI(推荐)' target_2 = ' 2) Codex CLI —— 同时对 App 生效,会按需安装 Node.js 与 Codex CLI' target_ask = '请输入序号 [回车 = 1]' target_bad = '无效选择,按 1(桌面版 App)处理。' s4_model = '[4/6] 正在获取可用模型列表...' model_offline = '在线获取失败,使用内置推荐清单。' model_pick = '请选择默认模型 [回车 = 1]' model_reco = ' <- 推荐' model_bad = '无效选择,使用推荐模型 {0}' model_ok = '默认模型: {0}(之后可在 ~\.codex\config.toml 或 codex 内 /model 切换)' s5_write = '[5/6] 写入配置 -> {0}' backed_up = '已备份原文件: {0}' cfg_overwrite = '注意:原 config.toml 无法安全合并(多半是格式有误),这次改为整体覆盖写入。你原有的 MCP server、profile、approval_policy 等自定义配置没有被保留,' cfg_merged = '已合并进原 config.toml:只更新 model_provider / model / review_model / model_reasoning_effort 与 [model_providers.qcode],其余配置(MCP server、profile 等)原样保留' cfg_renamed = '已把本脚本以前写的 [model_providers.crs] 改名为 [model_providers.qcode],并把 model_provider 指向它(用户自己写的 crs 表不会动)' cfg_profile = 'config.toml 顶层的 profile = {0} 已注释掉:新版 Codex 不再支持这种写法(会直接报配置错误),它也会盖过本脚本的配置。要继续用这个 profile:把 [profiles.{0}] 的内容移到 ~\.codex\{0}.config.toml、删掉原表,再运行 codex --profile {0}' cfg_overwrite2 = ' 请从上面的 .bak 备份里手动合并回来。' auth_overwrite = '注意:原 auth.json 已被替换(若其中是 ChatGPT 登录态,现已切换为 API 密钥模式)。' cfg_ok = '已写入 config.toml + auth.json' app_hint = ' 提示: Codex 桌面 App 与 CLI 共用该配置,App 需完全退出后重启生效。' s6_env = '[6/6] 检查运行环境' cli_installed = 'Codex CLI 已安装: {0}' no_install = '-NoInstall:跳过安装。请自行安装后运行: npm install -g {0}' ask_install = '未检测到 Codex CLI,使用 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 = 'Codex CLI 安装完成' cli_notfound = '安装完成但当前会话未找到 codex,请重开 PowerShell。' node_notready = 'Node.js 未就绪,配置已写好;装好 Node 后运行: npm install -g {0}' verify_start = '正在验证接入(发送一条最小测试请求,费用可忽略)...' verify_ok = '接入验证通过!模型 {0} 响应正常。' 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://{{域}}/openai 且末尾不带斜杠。当前: {0}' verify_429 = '配置正确(HTTP 429 = 已到达服务但被限流),稍后即可正常使用。' verify_net = '网络或节点异常({0})。建议重跑脚本换一个接入域(-Domain asia),各域状态见 {1}' skip_verify = '-NoVerify:已跳过验证。' done_title = '配置完成!摘要:' sum_domain = ' 接入域 {0}' sum_model = ' 默认模型 {0}' sum_file = ' 配置文件 {0} + auth.json' sum_verified = ' 连通性 [OK] 已验证' app_restart = ' Codex 桌面 App:完全退出后重新打开即生效。' cli_later = ' 以后需要 Codex CLI 时,重跑本脚本并选择 2 即可。' policy_hint = ' 提示: 当前执行策略是 {0},新开的 PowerShell 里运行 codex 可能报「无法加载文件」。' policy_fix = ' 免管理员修法(只影响你自己): Set-ExecutionPolicy -Scope CurrentUser RemoteSigned(或改输 codex.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' docs_hint = ' 文档与排错: {0}' ask_launch = '是否立即启动 Codex?' uninstall_conflict = '-Uninstall 不能与 -Key / -Domain / -Model / -Mirror / -Target / -NoInstall / -NoVerify 同时使用。' uninstall_usage = '用法: -Uninstall [-Yes] [-DryRun] [-Lang zh|en];-DryRun [-Key] [-Domain api|asia|us] [-Model] [-Target app|cli] [-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_auth_keep = 'auth.json 的密钥保留:config.toml 当前使用的不是本脚本的 provider' 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_exists = '文件已存在' dry_missing = '文件尚不存在' dry_merge = '将按安装路径合并' dry_create = '将新建' dry_cfg = 'config.toml {0}:{1};{2}' dry_auth_target = 'auth.json {0}:{1};将整文件覆盖写入 OPENAI_API_KEY(与安装路径相同)' dry_toml = 'config.toml 将合并这些顶层键,并写入 [model_providers.qcode]:' dry_pick = 'dry-run 不询问,使用最快接入域 {0}。' dry_will_install = '将安装: {0}' enjoy = '随时运行 codex 开始使用。enjoy!' failed = '配置未完成: {0}' } en = @{ banner = ' QCode.cc - Codex one-click setup v{0}' banner_sub = ' No admin rights needed | old config 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/6] 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} -> base_url={1}' s2_key = '[2/6] 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/codex.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.' cfg_load_fail = 'Codex cannot load the resulting config.toml (most likely a syntax error that was already in your file and was kept as-is by the merge):' cfg_load_bak = 'Backup of the original: {0} - fix the line reported above, or delete config.toml and re-run this script for a clean config' s3_target = '[3/6] Which Codex client will you use?' target_1 = ' 1) Codex desktop App - only writes config files, no Node.js / CLI install (recommended)' target_2 = ' 2) Codex CLI - also applies to the App; installs Node.js and the Codex CLI as needed' target_ask = 'Enter a number [Enter = 1]' target_bad = 'Invalid choice; treating it as 1 (desktop App).' s4_model = '[4/6] Fetching the list of available models...' model_offline = 'Could not fetch the list; using the built-in recommended set.' model_pick = 'Choose a default model [Enter = 1]' model_reco = ' <- recommended' model_bad = 'Invalid choice; using the recommended model {0}' model_ok = 'Default model: {0} (change it later in ~\.codex\config.toml or with /model inside codex)' s5_write = '[5/6] Writing config -> {0}' backed_up = 'Backed up the original file: {0}' cfg_overwrite = 'Note: the existing config.toml could not be merged safely (it is probably malformed), so it was overwritten as a whole. Your MCP servers, profiles, approval_policy and other customisations were NOT preserved;' cfg_merged = 'Merged into the existing config.toml: only model_provider / model / review_model / model_reasoning_effort and [model_providers.qcode] were updated; everything else (MCP servers, profiles, ...) is kept' cfg_renamed = 'Renamed the [model_providers.crs] table written by an earlier run of this script to [model_providers.qcode] and pointed model_provider at it (a crs table you wrote yourself is left alone)' cfg_profile = 'Commented out profile = {0} at the top of config.toml: current Codex no longer supports it (it refuses to load the config) and it would override this setup. To keep using that profile, move the [profiles.{0}] table into ~\.codex\{0}.config.toml, delete the original table, then run codex --profile {0}' cfg_overwrite2 = ' please merge them back manually from the .bak backup listed above.' auth_overwrite = 'Note: the previous auth.json was replaced (if it held a ChatGPT login, you are now on API-key mode).' cfg_ok = 'Wrote config.toml + auth.json' app_hint = ' Note: the Codex desktop App and CLI share this config; quit the App completely and reopen it to apply.' s6_env = '[6/6] Checking the runtime environment' cli_installed = 'Codex CLI is already installed: {0}' no_install = '-NoInstall: skipping install. Install it yourself with: npm install -g {0}' ask_install = 'Codex CLI 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 = 'Codex CLI installed' cli_notfound = 'Install finished but codex 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}' verify_start = 'Verifying access (sending one minimal test request; cost is negligible)...' verify_ok = 'Access verified - model {0} 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 model {0} is currently unavailable (HTTP 400). Re-run and pick another model.' verify_400 = 'Request rejected (HTTP 400): {0}' verify_404 = 'Wrong endpoint address (HTTP 404). base_url should be https://{{domain}}/openai 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_model = ' Model {0}' sum_file = ' Config {0} + auth.json' sum_verified = ' Connectivity [OK] verified' app_restart = ' Codex desktop App: quit it completely and reopen to apply.' cli_later = ' When you later want the Codex CLI, re-run this script and choose 2.' policy_hint = ' Note: your execution policy is {0}; running codex 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 codex.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' docs_hint = ' Docs and troubleshooting: {0}' ask_launch = 'Launch Codex now?' uninstall_conflict = '-Uninstall cannot be combined with -Key / -Domain / -Model / -Mirror / -Target / -NoInstall / -NoVerify.' uninstall_usage = 'Usage: -Uninstall [-Yes] [-DryRun] [-Lang zh|en]; -DryRun [-Key] [-Domain api|asia|us] [-Model] [-Target app|cli] [-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_auth_keep = 'auth.json key kept: config.toml is not using a provider written by this script' 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_exists = 'file exists' dry_missing = 'file does not exist yet' dry_merge = 'will be merged the same way install does' dry_create = 'will be created' dry_cfg = 'config.toml {0}: {1}; {2}' dry_auth_target = 'auth.json {0}: {1}; OPENAI_API_KEY will replace the whole file (same as install)' 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 codex any time to get started. Enjoy!' 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 ---- 公共段(与 claude-code.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 按值匹配做手术式删除:不 ConvertTo-Json 重排,其余字节保持原样。 # 本段不修改安装用的环境变量写入逻辑。 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 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 Get-QcUserHome { if ($env:USERPROFILE) { return $env:USERPROFILE } return $HOME } function Get-QcCodexHome { if ($env:CODEX_HOME) { return $env:CODEX_HOME } if ($env:USERPROFILE) { return (Join-Path $env:USERPROFILE '.codex') } return (Join-Path $HOME '.codex') } function Get-QcAuthEdit([string]$Body, [bool]$DropKey) { $notes = New-Object System.Collections.Generic.List[string] if ($Body.Trim() -eq '{}') { return @{ Text = $Body; Changed = $false; Notes = $notes } } 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; Changed = $false; Notes = $notes } } if ($data -isnot [System.Management.Automation.PSCustomObject]) { throw 'not-object' } $prop = Get-QcProp $data 'OPENAI_API_KEY' if (-not $prop) { return @{ Text = $Body; Changed = $false; Notes = $notes } } if ($prop.Value -isnot [string] -or -not ([string]$prop.Value).StartsWith('cr_', [System.StringComparison]::Ordinal)) { [void]$notes.Add((TF 'uninstall_kept' 'OPENAI_API_KEY not-cr')) return @{ Text = $Body; Changed = $false; Notes = $notes } } if (-not $DropKey) { [void]$notes.Add((T 'uninstall_auth_keep')) return @{ Text = $Body; Changed = $false; Notes = $notes } } [void]$data.PSObject.Properties.Remove('OPENAI_API_KEY') if (@($data.PSObject.Properties).Count -eq 0) { return @{ Text = ('{}' + "`n"); Changed = $true; Notes = $notes } } $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"); Changed = $true; Notes = $notes } } function Update-QcUninstScan([hashtable]$St, [string]$S) { $nn = $S.Length; $i = 0 $sq = [string]([char]39) $sq3 = $sq + $sq + $sq while ($i -lt $nn) { $c = [string]$S[$i] if ($St.mls) { if (($i + 3) -le $nn -and $S.Substring($i, 3) -ceq $St.mls) { $St.mls = ''; $i += 3; continue } if ($St.mls -ceq '"""' -and $c -ceq '\') { $i += 2; continue } $i++; continue } if ($St.q) { if ($St.q -ceq '"' -and $c -ceq '\') { $i += 2; continue } if ($c -ceq $St.q) { $St.q = '' } $i++; continue } if (($i + 3) -le $nn) { $t3 = $S.Substring($i, 3) if ($t3 -ceq '"""' -or $t3 -ceq $sq3) { $St.mls = $t3; $i += 3; continue } } if ($c -ceq '"' -or $c -ceq $sq) { $St.q = $c; $i++; continue } if ($c -ceq '#') { break } if ($c -ceq '[' -or $c -ceq '{') { $St.depth++ } elseif ($c -ceq ']' -or $c -ceq '}') { $St.depth-- } $i++ } if ($St.depth -lt 0) { $St.depth = 0 } } function Get-QcHeaderName([string]$Line) { $h = $Line -replace '^[ \t]*\[+', '' $h = $h -replace '\][ \t]*(#.*)?$', '' $sq = [string]([char]39) $h = $h.Replace(' ', '').Replace("`t", '').Replace('"', '').Replace($sq, '') $h = $h.Replace('[', '').Replace(']', '') return $h } function Get-QcBareKey([string]$Line) { $k = $Line -replace '^[ \t]*', '' if ($k.Length -eq 0) { return '' } $q = $k.Substring(0, 1) $sq = [string]([char]39) if ($q -eq '"' -or $q -eq $sq) { $k = $k.Substring(1) $p = $k.IndexOf($q, [System.StringComparison]::Ordinal) if ($p -lt 0) { return '' } return $k.Substring(0, $p) } return ($k -replace '[ \t]*=.*', '') } function Get-QcSimpleVal([string]$Line) { $v = $Line -replace '^[^=]*=[ \t]*', '' if ($v -eq '') { return @{ Ok = $false; V = '' } } $sq = [string]([char]39) if ($v.StartsWith('"""', [System.StringComparison]::Ordinal) -or $v.StartsWith($sq + $sq + $sq, [System.StringComparison]::Ordinal)) { return @{ Ok = $false; V = '' } } $c0 = $v.Substring(0, 1) if ($c0 -eq '"' -or $c0 -eq $sq) { $out = New-Object System.Text.StringBuilder $i = 1 while ($i -lt $v.Length) { $ch = $v.Substring($i, 1) if ($c0 -eq '"' -and $ch -eq '\') { return @{ Ok = $false; V = '' } } if ($ch -eq $c0) { $rest = $v.Substring($i + 1) -replace '^[ \t]*', '' if ($rest -ne '' -and -not $rest.StartsWith('#', [System.StringComparison]::Ordinal)) { return @{ Ok = $false; V = '' } } return @{ Ok = $true; V = $out.ToString() } } [void]$out.Append($ch) $i++ } return @{ Ok = $false; V = '' } } $v = $v -replace '[ \t]*#.*$', '' $v = $v -replace '[ \t]*$', '' if ($v -cmatch '^[A-Za-z0-9._+-]+$') { return @{ Ok = $true; V = $v } } return @{ Ok = $false; V = '' } } function Test-QcOwnedCrs($Lines) { $in = $false; $hasName = $false; $hasBase = $false foreach ($raw in $Lines) { $one = ([string]$raw).TrimEnd("`r") if ($one -match '^[ \t]*\[') { if ($in -and $hasName -and $hasBase) { return $true } $h = ((($one -replace '^[ \t]*\[', '') -replace '\][ \t]*(#.*)?$', '') -replace "[ \t""']", '') -replace '[\[\]]', '' $in = ($h -ceq 'model_providers.crs'); $hasName = $false; $hasBase = $false continue } if ($in) { if ($one -cmatch '^[ \t]*name[ \t]*=[ \t]*"QCode"[ \t]*(#.*)?$') { $hasName = $true } if ($one -cmatch '^[ \t]*base_url[ \t]*=[ \t]*"https://[A-Za-z0-9.-]*\.qcode\.cc/openai"[ \t]*(#.*)?$') { $hasBase = $true } } } return ($in -and $hasName -and $hasBase) } function Split-QcLines([string]$Text) { $ended = $Text.EndsWith("`n", [System.StringComparison]::Ordinal) $bits = $Text.Split([char]10) $list = New-Object System.Collections.Generic.List[string] $limit = $bits.Length if ($ended -and $limit -gt 0) { $limit-- } for ($i = 0; $i -lt $limit; $i++) { [void]$list.Add([string]$bits[$i]) } return $list } function Get-QcTomlUninstall($RawList) { $notes = New-Object System.Collections.Generic.List[string] $n = $RawList.Count if ($n -eq 0) { return @{ Changed = $false; Text = ''; Notes = $notes; DelProv = $false; ProvN = 0 } } $line = New-Object System.Collections.Generic.List[string] for ($i = 0; $i -lt $n; $i++) { $s = [string]$RawList[$i] if ($s.EndsWith("`r", [System.StringComparison]::Ordinal)) { $s = $s.Substring(0, $s.Length - 1) } [void]$line.Add($s) } $dropCrs = Test-QcOwnedCrs $line $ownedRe = '^[ \t]*[''"]?(model_provider|model|review_model|model_reasoning_effort|windows_wsl_setup_acknowledged)[''"]?[ \t]*=' $mpQ = '^[ \t]*[''"]?model_providers[''"]?[ \t]*\.[ \t]*[''"]?qcode[''"]?[ \t]*[.=]' $mpC = '^[ \t]*[''"]?model_providers[''"]?[ \t]*\.[ \t]*[''"]?crs[''"]?[ \t]*[.=]' $inQ = '^[ \t]*[''"]?qcode[''"]?[ \t]*[.=]' $inC = '^[ \t]*[''"]?crs[''"]?[ \t]*[.=]' $commentRe = '^# (由 qcode\.cc 一键配置脚本写入|written by the qcode\.cc setup script)' $st = @{ depth = 0; mls = ''; q = '' } $root = $true; $skip = $false; $drop = $false; $tbl = '' $hasQcode = $false; $hasComment = $false $box = @{ model = @{ n = 0; ok = $true; v = '' } review = @{ n = 0; ok = $true; v = '' } effort = @{ n = 0; ok = $true; v = '' } prov = @{ n = 0; ok = $true; v = '' } wsl = @{ n = 0; ok = $true; v = '' } } for ($i = 0; $i -lt $n; $i++) { $s = [string]$line[$i] if ($drop) { Update-QcUninstScan $st $s if ($st.depth -eq 0 -and -not $st.mls) { $drop = $false } continue } $top = ($st.depth -eq 0 -and -not $st.mls) if ($top -and $s -cmatch '^[ \t]*\[') { $root = $false $h = Get-QcHeaderName $s $tbl = $h if ($h -ceq 'model_providers.qcode' -or $h.StartsWith('model_providers.qcode.', [System.StringComparison]::Ordinal)) { $hasQcode = $true } $skip = (($h -ceq 'model_providers.qcode' -or $h.StartsWith('model_providers.qcode.', [System.StringComparison]::Ordinal)) -or ($dropCrs -and ($h -ceq 'model_providers.crs' -or $h.StartsWith('model_providers.crs.', [System.StringComparison]::Ordinal)))) continue } if ($skip) { if (-not ($top -and $s -cmatch '^[ \t]*(#.*)?$')) { Update-QcUninstScan $st $s } continue } if ($top -and $s -cmatch $commentRe) { $hasComment = $true; continue } if ($top -and $root -and $s -cmatch $mpQ) { $hasQcode = $true Update-QcUninstScan $st $s if ($st.depth -gt 0 -or $st.mls) { $drop = $true } continue } if ($top -and $root -and $dropCrs -and $s -cmatch $mpC) { Update-QcUninstScan $st $s if ($st.depth -gt 0 -or $st.mls) { $drop = $true } continue } if ($top -and -not $root -and $tbl -ceq 'model_providers' -and $s -cmatch $inQ) { $hasQcode = $true Update-QcUninstScan $st $s if ($st.depth -gt 0 -or $st.mls) { $drop = $true } continue } if ($top -and $root -and $s -cmatch $ownedRe) { $k = Get-QcBareKey $s $parsed = Get-QcSimpleVal $s $slot = $null if ($k -ceq 'model_provider') { $slot = $box.prov } elseif ($k -ceq 'model') { $slot = $box.model } elseif ($k -ceq 'review_model') { $slot = $box.review } elseif ($k -ceq 'model_reasoning_effort') { $slot = $box.effort } elseif ($k -ceq 'windows_wsl_setup_acknowledged') { $slot = $box.wsl } if ($slot) { $slot.n++ if (-not $parsed.Ok -or ($slot.n -gt 1 -and $parsed.V -cne $slot.v)) { $slot.ok = $false } if ($slot.n -eq 1) { $slot.v = [string]$parsed.V } } Update-QcUninstScan $st $s if ($st.depth -gt 0 -or $st.mls) { $drop = $true } continue } if ($top) { Update-QcUninstScan $st $s } else { Update-QcUninstScan $st $s } } $ours = ($hasQcode -or $hasComment -or $box.prov.v -ceq 'qcode' -or ($dropCrs -and $box.prov.v -ceq 'crs')) $delProv = ($box.prov.ok -and ($box.prov.v -ceq 'qcode' -or ($dropCrs -and $box.prov.v -ceq 'crs'))) $modelId = ($box.model.v -cmatch '^[A-Za-z0-9._-]+$') $delModels = ($ours -and $box.model.ok -and $box.review.ok -and $box.model.n -gt 0 -and $box.review.n -gt 0 -and $box.model.v -ceq $box.review.v -and $modelId) $delEffort = ($ours -and $box.effort.ok -and $box.effort.n -gt 0 -and $box.effort.v -ceq 'high') $delWsl = ($ours -and $box.wsl.ok -and $box.wsl.n -gt 0 -and $box.wsl.v -ceq 'true') if ($ours -and $box.prov.n -gt 0 -and -not $delProv) { [void]$notes.Add((TF 'uninstall_kept' 'model_provider value-not-ours')) } if ($ours -and ($box.model.n -gt 0 -or $box.review.n -gt 0) -and -not $delModels) { [void]$notes.Add((TF 'uninstall_kept' 'model unconfirmed')) } if ($ours -and $box.effort.n -gt 0 -and -not $delEffort) { [void]$notes.Add((TF 'uninstall_kept' 'model_reasoning_effort value-not-high')) } if ($ours -and $box.wsl.n -gt 0 -and -not $delWsl) { [void]$notes.Add((TF 'uninstall_kept' 'windows_wsl_setup_acknowledged value-not-true')) } $st = @{ depth = 0; mls = ''; q = '' } $root = $true; $skip = $false; $drop = $false; $tbl = '' $buf = New-Object System.Collections.Generic.List[int] $del = New-Object 'bool[]' $n $notedProf = $false for ($i = 0; $i -lt $n; $i++) { $s = [string]$line[$i] if ($drop) { $del[$i] = $true Update-QcUninstScan $st $s if ($st.depth -eq 0 -and -not $st.mls) { $drop = $false } continue } $top = ($st.depth -eq 0 -and -not $st.mls) if ($top -and $s -cmatch '^[ \t]*\[') { $root = $false $h = Get-QcHeaderName $s $tbl = $h $skip = (($h -ceq 'model_providers.qcode' -or $h.StartsWith('model_providers.qcode.', [System.StringComparison]::Ordinal)) -or ($dropCrs -and ($h -ceq 'model_providers.crs' -or $h.StartsWith('model_providers.crs.', [System.StringComparison]::Ordinal)))) if ($skip) { $del[$i] = $true if ($h -ceq 'model_providers.qcode' -and $i -gt 0 -and $line[$i - 1] -cmatch '^[ \t]*$') { $del[$i - 1] = $true } $buf.Clear() } else { foreach ($b in $buf) { $del[$b] = $false } $buf.Clear() } continue } if ($skip) { if ($top -and $s -cmatch '^[ \t]*(#.*)?$') { [void]$buf.Add($i); $del[$i] = $true } else { $buf.Clear(); $del[$i] = $true; Update-QcUninstScan $st $s } continue } if ($top -and $root -and $s -cmatch $commentRe) { $del[$i] = $true; continue } if ($top -and $s -cmatch 'qcode\.cc:' -and $s -cmatch 'profile') { $notedProf = $true } if ($top -and $root -and ($s -cmatch $mpQ -or ($dropCrs -and $s -cmatch $mpC))) { $del[$i] = $true Update-QcUninstScan $st $s if ($st.depth -gt 0 -or $st.mls) { $drop = $true } continue } if ($top -and -not $root -and $tbl -ceq 'model_providers' -and ($s -cmatch $inQ -or ($dropCrs -and $s -cmatch $inC))) { $del[$i] = $true Update-QcUninstScan $st $s if ($st.depth -gt 0 -or $st.mls) { $drop = $true } continue } if ($top -and $root -and $s -cmatch $ownedRe) { $k = Get-QcBareKey $s $kill = $false if ($k -ceq 'model_provider' -and $delProv) { $kill = $true } elseif (($k -ceq 'model' -or $k -ceq 'review_model') -and $delModels) { $kill = $true } elseif ($k -ceq 'model_reasoning_effort' -and $delEffort) { $kill = $true } elseif ($k -ceq 'windows_wsl_setup_acknowledged' -and $delWsl) { $kill = $true } if ($kill) { $del[$i] = $true Update-QcUninstScan $st $s if ($st.depth -gt 0 -or $st.mls) { $drop = $true } continue } } Update-QcUninstScan $st $s } foreach ($b in $buf) { $del[$b] = $false } if ($notedProf) { [void]$notes.Add((TF 'uninstall_kept' 'profile commented-by-script-left-in-place')) } $any = $false for ($i = 0; $i -lt $n; $i++) { if ($del[$i]) { $any = $true } } if (-not $any) { return @{ Changed = $false; Text = $null; Notes = $notes; DelProv = [bool]$delProv; ProvN = [int]$box.prov.n } } $sb = New-Object System.Text.StringBuilder $first = $true for ($i = 0; $i -lt $n; $i++) { if ($del[$i]) { continue } if (-not $first) { [void]$sb.Append("`n") } [void]$sb.Append([string]$RawList[$i]) $first = $false } if (-not $first) { [void]$sb.Append("`n") } return @{ Changed = $true; Text = $sb.ToString(); Notes = $notes; DelProv = [bool]$delProv; ProvN = [int]$box.prov.n } } function Invoke-QcUninstall { try { if ($DryRun) { Info (T 'dry_uninstall') } $codexHome = Get-QcCodexHome $notes = New-Object System.Collections.Generic.List[string] $plan = New-Object System.Collections.Generic.List[string] $cfgPath = Join-Path $codexHome 'config.toml' $authPath = Join-Path $codexHome 'auth.json' $cfgNew = $null $authNew = $null $authBom = '' $dropAuth = $true if (Test-Path -LiteralPath $cfgPath) { $loadedCfg = Read-QcJsonFile $cfgPath $bits = Split-QcLines $loadedCfg.Body $ed = Get-QcTomlUninstall $bits foreach ($nt in $ed.Notes) { [void]$notes.Add($nt) } $dropAuth = (($ed.ProvN -eq 0) -or [bool]$ed.DelProv) if ($ed.Changed) { $cfgNew = $loadedCfg.Bom + [string]$ed.Text [void]$plan.Add('config.toml([model_providers.qcode] / 值仍属于本脚本的顶层键 / 本脚本写的说明行)') } } if (Test-Path -LiteralPath $authPath) { $loaded = Read-QcJsonFile $authPath $authBom = $loaded.Bom try { $ad = Get-QcAuthEdit $loaded.Body ([bool]$dropAuth) } catch { Fail (TF 'uninstall_badjson' $authPath) return 1 } foreach ($nt in $ad.Notes) { [void]$notes.Add($nt) } if ($ad.Changed) { $authNew = $authBom + [string]$ad.Text [void]$plan.Add('auth.json OPENAI_API_KEY') } } 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 ($null -ne $cfgNew) { $bak = $cfgPath + '.bak.' + $stamp Copy-Item -LiteralPath $cfgPath -Destination $bak Ok (TF 'backed_up' $bak) } if ($null -ne $authNew) { $bak = $authPath + '.bak.' + $stamp Copy-Item -LiteralPath $authPath -Destination $bak Ok (TF 'backed_up' $bak) } } catch { Fail (T 'uninstall_backup_fail') return 1 } $utf8 = New-Object System.Text.UTF8Encoding $false if ($null -ne $cfgNew) { [System.IO.File]::WriteAllText($cfgPath, $cfgNew, $utf8) } if ($null -ne $authNew) { [System.IO.File]::WriteAllText($authPath, $authNew, $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-QcDryRun { try { Say '' Say (TF 'banner' $ScriptVersion) Say (T 'dry_header') $selected = Invoke-QcPickHost $base = 'https://' + $selected + '/openai' 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) $cfgPath = Join-Path (Get-QcCodexHome) 'config.toml' $authPath = Join-Path (Get-QcCodexHome) 'auth.json' if (Test-Path -LiteralPath $cfgPath) { Say (TF 'dry_cfg' $cfgPath (T 'dry_exists') (T 'dry_merge')) } else { Say (TF 'dry_cfg' $cfgPath (T 'dry_missing') (T 'dry_create')) } if (Test-Path -LiteralPath $authPath) { Say (TF 'dry_auth_target' $authPath (T 'dry_exists')) } else { Say (TF 'dry_auth_target' $authPath (T 'dry_missing')) } $selectedModel = $DefaultModel if ($Model) { $selectedModel = $Model } elseif ($key -ne 'cr_<未提供>') { $models = @() try { $resp = Invoke-RestMethod -Uri ("https://$selected/v1/models") -Method GET -TimeoutSec 15 -Headers @{ Authorization = ('Bearer ' + $key) } $models = @($resp.data | ForEach-Object { $_.id } | Where-Object { $_ -like 'gpt-*' -and $_ -notlike '*image*' } | Select-Object -Unique) } catch { } if ($models.Count -eq 0) { $models = $FallbackModels } if ($models -contains $DefaultModel) { $models = @($DefaultModel) + @($models | Where-Object { $_ -ne $DefaultModel }) } $selectedModel = [string]$models[0] } Say (T 'dry_toml') Say 'model_provider = "qcode"' Say ('model = "' + $selectedModel + '"') Say ('review_model = "' + $selectedModel + '"') Say 'model_reasoning_effort = "high"' Say 'windows_wsl_setup_acknowledged = true' Say '[model_providers.qcode]' Say ('base_url = "' + $base + '"') Say (TF 'dry_auth' $masked) $dryTarget = 'app' if ($NoInstall) { $dryTarget = 'app' } elseif ($Target -eq 'cli') { $dryTarget = 'cli' } Say ('target=' + $dryTarget) if ($NoInstall -or $dryTarget -ne 'cli') { 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 + '/responses') $selectedModel) } return 0 } catch { Fail (TF 'failed' $_.Exception.Message) return 1 } } $ApiKey = "" $VerifyOk = $true $Failed = $false $CfgLoadOk = $true $PolicyResult = $null $QcExitSet = $false $QcExit = 0 try { if ($Uninstall) { foreach ($n in @('Key','Domain','Model','Mirror','Target','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/6] 接入域 ---------- $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 { 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 } } $CodexBaseUrl = "https://$SelectedHost/openai" Ok (TF 'domain_ok' $SelectedHost $CodexBaseUrl) # ---------- [2/6] 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/6] 目标客户端 ---------- # 大量用户只用 Codex 桌面 App,根本不需要 Node/CLI。默认只写配置。 $UseTarget = "" if ($Target -eq 'app') { $UseTarget = "1" } elseif ($Target -eq 'cli') { $UseTarget = "2" } if ($UseTarget -eq "") { Info (T 's3_target') Say (T 'target_1') Say (T 'target_2') if ($Yes) { $UseTarget = "1" } else { $t = Read-Host (T 'target_ask') if ([string]::IsNullOrWhiteSpace($t)) { $UseTarget = "1" } elseif (@("1", "2") -contains $t.Trim()) { $UseTarget = $t.Trim() } else { Warn2 (T 'target_bad'); $UseTarget = "1" } } } if ($NoInstall) { Warn2 (TF 'no_install' $NpmPkg); $UseTarget = "1" } # ---------- [4/6] 默认模型 ---------- $SelectedModel = $Model if ([string]::IsNullOrWhiteSpace($SelectedModel)) { Info (T 's4_model') $models = @() try { $resp = Invoke-RestMethod -Uri "https://$SelectedHost/v1/models" -Method GET -TimeoutSec 15 ` -Headers @{ "Authorization" = "Bearer $ApiKey" } $models = @($resp.data | ForEach-Object { $_.id } | Where-Object { $_ -like "gpt-*" -and $_ -notlike "*image*" } | Select-Object -Unique) } catch { Warn2 (T 'model_offline') } if ($models.Count -eq 0) { $models = $FallbackModels } if ($models -contains $DefaultModel) { $models = @($DefaultModel) + @($models | Where-Object { $_ -ne $DefaultModel }) } Say "" $i = 0 foreach ($m in $models) { $i++ if ($m -eq $DefaultModel) { Say "$i) $m$(T 'model_reco')" } else { Say "$i) $m" } } Say "" $choice = if ($Yes) { "1" } else { Read-Host (T 'model_pick') } if ([string]::IsNullOrWhiteSpace($choice)) { $choice = "1" } if ($choice -match '^\d+$' -and [int]$choice -ge 1 -and [int]$choice -le $models.Count) { $SelectedModel = $models[[int]$choice - 1] } else { Warn2 (TF 'model_bad' $DefaultModel) $SelectedModel = $DefaultModel } } Ok (TF 'model_ok' $SelectedModel) # ---------- [5/6] 写配置 ---------- # Codex CLI 在 Windows 上用 %USERPROFILE%;PowerShell 的 $HOME 在启用了主目录 # 重定向(HOMESHARE)的域环境里可能是网络盘,写过去 codex 永远读不到。 $CodexHome = if ($env:CODEX_HOME) { $env:CODEX_HOME } elseif ($env:USERPROFILE) { Join-Path $env:USERPROFILE ".codex" } else { Join-Path $HOME ".codex" } $ConfigFile = Join-Path $CodexHome "config.toml" $AuthFile = Join-Path $CodexHome "auth.json" Info (TF 's5_write' $CodexHome) if (-not (Test-Path $CodexHome)) { New-Item -ItemType Directory -Path $CodexHome -Force | Out-Null } $stamp = Get-Date -Format "yyyyMMddHHmmss" $hadConfig = Test-Path $ConfigFile $hadAuth = Test-Path $AuthFile foreach ($f in @($ConfigFile, $AuthFile)) { if (Test-Path $f) { Copy-Item -LiteralPath $f -Destination "$f.bak.$stamp" Ok (TF 'backed_up' "$f.bak.$stamp") } } $header = if ($UiLang -eq 'en') { "# written by the qcode.cc setup script at $stamp (docs: $DocsUrl)" } else { "# 由 qcode.cc 一键配置脚本写入 $stamp(文档: $DocsUrl)" } $rootBlock = @( $header 'model_provider = "qcode"' "model = `"$SelectedModel`"" "review_model = `"$SelectedModel`"" 'model_reasoning_effort = "high"' 'windows_wsl_setup_acknowledged = true' ) $tableBlock = @( '' '[model_providers.qcode]' 'name = "qcode"' "base_url = `"$CodexBaseUrl`"" 'wire_api = "responses"' 'requires_openai_auth = true' ) $profileNote = if ($UiLang -eq 'en') { '# qcode.cc: commented out - current Codex no longer supports a top-level profile (see the setup output)' } else { '# qcode.cc: 新版 Codex 不再支持顶层 profile,已注释(见一键脚本的提示)' } # 与 codex.sh 同一套规则:从原 config.toml 去掉本脚本负责的几项,其余原样保留—— # 顶层 model_provider / model / review_model / model_reasoning_effort / windows_wsl_setup_acknowledged(键名带不带引号都算)、 # 以前写的说明行;整张 [model_providers.qcode](含子表)、顶层 model_providers.qcode.* 点号键 / 内联表、[model_providers] 表里的 qcode = …。 # 旧版本脚本写的表名是 crs:只有 Test-QcManagedCrs 认出是本脚本写的那张 [model_providers.crs] # (name = "QCode" 且 base_url 指向 *.qcode.cc/openai)才一并去掉,等于原地改名为 qcode;用户自己写的 crs 表原样保留。 # 逐字符跟踪方括号 / 花括号深度与多行字符串,多行数组、多行内联表、多行字符串里的行不会被误认成表头或键。 # 顶层 profile = … 新版 Codex 已不支持(直接报配置错误),也会盖过我们的 provider ⇒ 原地注释掉并提示。 function Update-QcTomlState([hashtable]$St, [string]$S) { $n = $S.Length; $i = 0; $q = '' while ($i -lt $n) { $c = [string]$S[$i] if ($St.mls) { if ($i + 3 -le $n -and $S.Substring($i, 3) -ceq $St.mls) { $St.mls = ''; $i += 3; continue } if ($St.mls -ceq '"""' -and $c -ceq '\') { $i += 2; continue } $i++; continue } if ($q) { if ($q -ceq '"' -and $c -ceq '\') { $i += 2; continue } if ($c -ceq $q) { $q = '' } $i++; continue } if ($i + 3 -le $n) { $t3 = $S.Substring($i, 3) if ($t3 -ceq '"""' -or $t3 -ceq "'''") { $St.mls = $t3; $i += 3; continue } } if ($c -ceq '"' -or $c -ceq "'") { $q = $c; $i++; continue } if ($c -ceq '#') { break } if ($c -ceq '[' -or $c -ceq '{') { $St.depth++ } elseif ($c -ceq ']' -or $c -ceq '}') { $St.depth-- } $i++ } if ($St.depth -lt 0) { $St.depth = 0 } } function Test-QcManagedCrs([string[]]$Lines) { $in = $false; $hasName = $false; $hasBase = $false foreach ($raw in $Lines) { $line = $raw.TrimEnd("`r") if ($line -match '^[ \t]*\[') { if ($in -and $hasName -and $hasBase) { return $true } $h = ((($line -replace '^[ \t]*\[', '') -replace '\][ \t]*(#.*)?$', '') -replace "[ \t""']", '') -replace '[\[\]]', '' $in = ($h -ceq 'model_providers.crs'); $hasName = $false; $hasBase = $false continue } if ($in) { if ($line -cmatch '^[ \t]*name[ \t]*=[ \t]*"QCode"[ \t]*(#.*)?$') { $hasName = $true } if ($line -cmatch '^[ \t]*base_url[ \t]*=[ \t]*"https://[A-Za-z0-9.-]+\.qcode\.cc/openai/?"[ \t]*(#.*)?$') { $hasBase = $true } } } return ($in -and $hasName -and $hasBase) } function Get-QcTomlStripped([string[]]$Lines, [string]$Note, [bool]$DropCrs = $false) { $Q = '["'']?' # 我们负责的 provider 名:qcode 永远是;旧托管 crs 只在 $DropCrs 时算 $pn = if ($DropCrs) { '(qcode|crs)' } else { 'qcode' } $ownedRe = '^[ \t]*' + $Q + '(model_provider|model|review_model|model_reasoning_effort|windows_wsl_setup_acknowledged)' + $Q + '[ \t]*=' $mpOwnRe = '^[ \t]*' + $Q + 'model_providers' + $Q + '[ \t]*\.[ \t]*' + $Q + $pn + $Q + '[ \t]*[.=]' $mpAllRe = '^[ \t]*' + $Q + 'model_providers' + $Q + '[ \t]*=' $ownPRe = '^[ \t]*' + $Q + $pn + $Q + '[ \t]*[.=]' $profRe = '^[ \t]*' + $Q + 'profile' + $Q + '[ \t]*=' $st = @{ depth = 0; mls = '' } $res = @{ Lines = New-Object System.Collections.Generic.List[string]; Profile = ''; Invalid = $false } $root = $true; $skip = $false; $drop = $false; $tbl = '' $buf = New-Object System.Collections.Generic.List[string] foreach ($raw in $Lines) { $line = $raw.TrimEnd("`r") if ($drop) { Update-QcTomlState $st $line; if ($st.depth -eq 0 -and -not $st.mls) { $drop = $false }; continue } $top = ($st.depth -eq 0 -and -not $st.mls) # 行级语法检查(只看不在多行值里的行):空行 / 注释 / 表头 / key = value,其余视为格式错误 if ($top -and $line -notmatch '^[ \t]*(#.*)?$') { if ($line -match '^[ \t]*\[') { if ($line -notmatch '\][ \t]*(#.*)?$') { $res.Invalid = $true } } elseif ($line -notmatch '^[ \t]*[^ \t=#][^=]*=') { $res.Invalid = $true } } if ($top -and $line -match '^[ \t]*\[') { $root = $false # 数组表头 [[model_providers.qcode.x]] 多一层方括号,一并去掉 $h = ((($line -replace '^[ \t]*\[', '') -replace '\][ \t]*(#.*)?$', '') -replace "[ \t""']", '') -replace '[\[\]]', '' $tbl = $h $skip = (($h -ceq 'model_providers.qcode') -or $h.StartsWith('model_providers.qcode.', [System.StringComparison]::Ordinal) -or ($DropCrs -and (($h -ceq 'model_providers.crs') -or $h.StartsWith('model_providers.crs.', [System.StringComparison]::Ordinal)))) # 被删掉的 provider 表末尾、紧挨下一个表头的注释 / 空行归下一节,原样保留 if (-not $skip) { foreach ($b in $buf) { $res.Lines.Add($b) }; $res.Lines.Add($line) } $buf.Clear() continue } if ($skip) { if ($top -and $line -match '^[ \t]*(#.*)?$') { $buf.Add($line) } else { $buf.Clear(); Update-QcTomlState $st $line } continue } if ($top) { if (($root -and ($line -cmatch $ownedRe -or $line -cmatch $mpOwnRe)) -or (-not $root -and $tbl -ceq 'model_providers' -and $line -cmatch $ownPRe)) { Update-QcTomlState $st $line if ($st.depth -gt 0 -or $st.mls) { $drop = $true } continue } # 顶层 model_providers = { … } 内联表:可能还装着别的 provider,没法只改 qcode ⇒ 交给整体覆盖 if ($root -and $line -cmatch $mpAllRe) { $res.Invalid = $true } if ($root -and $line -cmatch '^# (由 qcode\.cc 一键配置脚本写入|written by the qcode\.cc setup script)') { continue } if ($root -and $line -cmatch $profRe) { if (-not $res.Profile) { $res.Profile = (($line -replace '^[^=]*=[ \t]*', '') -replace '[ \t]*#.*$', '') -replace "[ \t""']", '' } Update-QcTomlState $st $line $res.Lines.Add("# $line $Note") continue } } Update-QcTomlState $st $line $res.Lines.Add($line) } foreach ($b in $buf) { $res.Lines.Add($b) } return $res } function Get-QcTrimmed($Lines) { $a = @($Lines) $first = 0; while ($first -lt $a.Count -and [string]::IsNullOrWhiteSpace($a[$first])) { $first++ } $last = $a.Count - 1; while ($last -ge $first -and [string]::IsNullOrWhiteSpace($a[$last])) { $last-- } if ($first -gt $last) { return ,@() } return ,@($a[$first..$last]) } $cfgMode = 'new' $cfgProfile = '' $dropCrs = $false if ($hadConfig -and (Get-Item -LiteralPath $ConfigFile).Length -gt 0) { $cfgMode = 'merge' try { # ReadAllText 会识别并去掉 BOM(顺带修好 PS 5.1 Out-File 写出的带 BOM 文件) $origLines = [System.IO.File]::ReadAllText($ConfigFile) -split "`n" $dropCrs = Test-QcManagedCrs $origLines $stripped = Get-QcTomlStripped $origLines $profileNote $dropCrs $userLines = Get-QcTrimmed $stripped.Lines $mergedLines = @($rootBlock) + @($userLines) + @($tableBlock) # 没有 TOML 解析器 ⇒ 自洽检查:对合并结果再过滤一遍,必须正好剩下用户原有的内容 $recheck = Get-QcTrimmed (Get-QcTomlStripped $mergedLines $profileNote $dropCrs).Lines if ($stripped.Invalid -or (($recheck -join "`n") -cne ($userLines -join "`n"))) { $cfgMode = 'fallback' } else { $cfgProfile = $stripped.Profile } } catch { $cfgMode = 'fallback' } } if ($cfgMode -ne 'merge') { $mergedLines = @($rootBlock) + @($tableBlock) } # 必须写 UTF-8 无 BOM:PowerShell 5.1 的 Out-File -Encoding utf8 会带 BOM, # config.toml 开头多出的 EF BB BF 会让 codex 解析 TOML 直接报错。 $utf8NoBom = New-Object System.Text.UTF8Encoding($false) [System.IO.File]::WriteAllText($ConfigFile, (($mergedLines -join "`n") + "`n"), $utf8NoBom) $authJson = @{ OPENAI_API_KEY = $ApiKey } | ConvertTo-Json [System.IO.File]::WriteAllText($AuthFile, $authJson + "`n", $utf8NoBom) Ok (T 'cfg_ok') if ($cfgMode -eq 'merge') { Ok (T 'cfg_merged'); if ($dropCrs) { Ok (T 'cfg_renamed') } } elseif ($cfgMode -eq 'fallback') { # 合并不了(原文件格式有误等)才整体覆盖 —— 必须让用户知道自己的 MCP server / profile 没被保留 Warn2 (T 'cfg_overwrite') Say (T 'cfg_overwrite2') } if ($cfgProfile) { Warn2 (TF 'cfg_profile' $cfgProfile) } if ($hadAuth) { Warn2 (T 'auth_overwrite') } Say (T 'app_hint') # ---------- [6/6] Node.js / Codex CLI ---------- 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 } $CliReady = $false if ($UseTarget -eq "2") { Info (T 's6_env') # 安装段单独兜异常:config.toml/auth.json 此时已写好,装 Node/CLI 失败 # 不该让用户看到「配置未完成」并跳过验证与摘要。 try { $cliPath = Resolve-CliCommand $CliName if ($cliPath) { Ok (TF 'cli_installed' $cliPath) $CliReady = $true } 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 } try { $qcHome = $env:USERPROFILE; if (-not $qcHome) { $qcHome = $HOME } $qcBkDir = Join-Path $qcHome ".qcode" $PolicyResult = Invoke-QcEnsureExecutionPolicy -BackupDir $qcBkDir -Stamp $stamp } catch { } } # ---------- config.toml 能否被 Codex 读取 ---------- # 自洽检查看不出原文件本来就坏(重复键、缺值等,合并时会原样保留)⇒ 本机有 codex 命令时让它自己加载一次。 # 只用桌面 App 的用户多半没有 codex 命令,跳过。 $CfgLoadOk = $true try { $codexCmd = Resolve-CliCommand $CliName if ($codexCmd) { $cfgErr = @(Invoke-Native { & $codexCmd login status 2>&1 }) | ForEach-Object { "$_" } | Where-Object { $_ -match 'Error loading configuration' } | Select-Object -First 1 if ($cfgErr) { $CfgLoadOk = $false Fail (T 'cfg_load_fail') Say (" " + $cfgErr.Substring(0, [Math]::Min(300, $cfgErr.Length))) if ($hadConfig) { Say (" " + (TF 'cfg_load_bak' "$ConfigFile.bak.$stamp")) } } } } catch { } # ---------- 端到端验证 ---------- if ($NoVerify) { Warn2 (T 'skip_verify') } else { Info (T 'verify_start') $body = @{ model = $SelectedModel; input = "ping"; max_output_tokens = 32 } | ConvertTo-Json try { Invoke-RestMethod -Uri "$CodexBaseUrl/responses" -Method POST -TimeoutSec 60 ` -Headers @{ "Authorization" = "Bearer $ApiKey" } ` -ContentType "application/json" -Body $body | Out-Null Ok (TF 'verify_ok' $SelectedModel) Say (TF 'verify_usage' $ProbeUrl) } catch { # switch 体内 $_ 会被重绑定成被测试的值,必须先存下 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 { if ($bodyText -match 'not a supported model|not available on this endpoint') { # 400 恰恰证明密钥有效、地址正确、网络通畅,不该判成配置失败。 Warn2 (TF 'verify_model' $SelectedModel); $VerifyOk = $true } else { Fail (TF 'verify_400' $bodyText) } } 404 { Fail (TF 'verify_404' $CodexBaseUrl) } 429 { Ok (T 'verify_429'); $VerifyOk = $true } default { Fail (TF 'verify_net' $err.Exception.Message $ProbeUrl) } } } } # ---------- 收尾 ---------- Say "" Say "----------------------------------------" # 验证明确失败时绝不能打绿色的「配置完成」——那是在谎报成功。 if (($VerifyOk -or $NoVerify) -and $CfgLoadOk) { Ok (T 'done_title') } else { Warn2 (T 'done_partial') } Say (TF 'sum_domain' $SelectedHost) Say (TF 'sum_model' $SelectedModel) Say (TF 'sum_file' $ConfigFile) if ($PolicyResult -and $PolicyResult.Updated) { Say (T 'sum_policy') } if ($VerifyOk -and -not $NoVerify -and $CfgLoadOk) { Say (T 'sum_verified') } Say "" Say (T 'app_restart') if ($UseTarget -eq "1") { Say (T 'cli_later') } if ($UseTarget -eq "2") { 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') } } elseif ($UseTarget -eq "2") { 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 -not $CfgLoadOk) { $global:LASTEXITCODE = 1 } else { $global:LASTEXITCODE = 0 } $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','authJson','header','rootBlock','tableBlock','cfgMode','cfgProfile','origLines','stripped','userLines','mergedLines','recheck','profileNote','codexCmd','cfgErr','__qcPrevEAP','__qcPrevPP','mirrorWhy','__qcPrevNpmReg','__qcMirrorSet','dropCrs','QcExit','QcExitSet','PolicyResult','qcBkDir','qcHome')) { Remove-Variable -Name $v -ErrorAction SilentlyContinue } }