⏳ This skill is pending AI review.

Scores will appear once the review pipeline completes.

v2.0.1

codex-multi-profile

hung2124@hung2124⭐ 94 stars· last commit 18d ago· 5 open issues

>-

Choose how to use this skill

You do not need every option. Choose the path your AI client supports. The stable page stays the same; versioned files are immutable.

1. Native installer

This listing has no registered native installer command. Use the complete package or source fallback below, depending on what your client supports.

Do not guess an installer command or replace an existing version without reviewing the diff.

2. Complete package recommended

Download the ZIP when available. It includes SKILL.md plus the references, security notes and version metadata.

No complete ProSkills package is published for this listing yet.

3. Prompt-only

Copy the prompt above when the agent can read the stable page or when you want to adopt the workflow without installing a skill.

Need only the instruction file?

Download SKILL.md only if your client requires a single file. The complete ZIP is safer for a full installation because it preserves the references and release context.

No path installs or executes anything by itself. Your agent still needs access to the project files. Before updating, compare the installed version and review the diff.

—/10

// RATINGS

⭐GitHub Stars
⭐⭐ 94 on GitHubGitHub ↗

Growing

🟢ProSkills Score
—
📍

Not yet listed on ClawHub or SkillsMP

// README

Codex Multi-Profile

Built for developers, open-source maintainers, and consulting engineers who work across separate authorized Enterprise SSO, Client, and Personal workspaces in Claude Code and OpenAI Codex.

Core Capabilities (v2.0)

ModuleWhat it solves
Claude Code & Codex Profile Store (WorkspaceProfileStore)Isolate ~/.claude/settings.json, ~/.codex, and workspace .mcp.json profiles (enterprise, oss-maintainer, research) with atomic file swaps
MCP Security & Isolation Auditor (mcp-audit)Statically audits .mcp.json and claude_desktop_config.json for hardcoded credentials (sk-ant-*, ghp_*), non-loopback HTTP/SSE endpoints, and unsafe shell wrappers
Instruction Bridge (sync-docs)Deterministically synchronizes shared engineering rules between CLAUDE.md (Claude Code) and AGENTS.md (OpenAI Codex) across polyglot repositories
Windows Store Codex Workspace SwitcherHot-switches authorized Enterprise, Team, and Personal workspaces in 2–3 seconds directly from the Microsoft Store Codex avatar menu

Cross-Platform CLI & Node.js SDK (Claude Code, MCP & Codex)

Requires Node.js 18+ on macOS, Linux, or Windows:

# Install globally or invoke via npx
npm install -g codex-multi-profile

# 1. Audit .mcp.json for secret leakage and non-loopback MCP transports
npx codex-multi-profile mcp-audit .mcp.json

# 2. Synchronize CLAUDE.md <-> AGENTS.md instructions in a repository
npx codex-multi-profile sync-docs .

# 3. List isolated Claude Code (~/.claude) or Codex (~/.codex) profiles
npx codex-multi-profile profiles claude

Programmatic SDK Usage (Node.js / TypeScript)

const {
  WorkspaceProfileStore,
  auditMcpConfig,
  syncWorkspaceInstructions
} = require("codex-multi-profile");

// 1. Audit an MCP configuration before activating a workspace profile
const audit = auditMcpConfig({
  mcpServers: {
    github: {
      command: "npx",
      args: ["-y", "@modelcontextprotocol/server-github"],
      env: { GITHUB_PERSONAL_ACCESS_TOKEN: "${GITHUB_PERSONAL_ACCESS_TOKEN}" }
    }
  }
});
if (!audit.valid) throw new Error("MCP security audit failed");

// 2. Save and activate an isolated Claude Code profile
const store = new WorkspaceProfileStore();
store.saveProfile("oss-maintainer", {
  agent: "claude",
  settings: { model: "claude-sonnet-4-5" }
});
store.activateProfile("oss-maintainer", { agent: "claude", workspaceDir: process.cwd() });

// 3. Keep CLAUDE.md and AGENTS.md aligned
syncWorkspaceInstructions(process.cwd(), { direction: "claude-to-codex" });

Native Windows Desktop Integration (Microsoft Store Codex App)

Click your avatar at the bottom-left of the Windows Store Codex app. Under your identity row there is an Accounts workspace section:

In the menuDoes
Click a workspace profileSwitches to that workspace in 2-3 seconds; the Codex window stays open (from a sign-in screen Codex restarts, ~10 s)
Add accountCodex restarts on its sign-in screen; sign in with your other authorized workspace and save it under a profile label
Pencil / trash (hover a row)Rename / remove a saved workspace profile (the active profile cannot be removed)
1-9 while the menu is openActivate the workspace profile with that number
Ctrl+Alt+AOpen the workspace switcher from anywhere in Codex
Telemetry barsDisplays remaining session quota windows (5h and weekly windows) per workspace; hover for reset timestamp

The menu follows the application's language (Vietnamese or English) and its light / dark theme.

Screenshots use synthetic profiles; rendered from switcher-inject.js with node tools/screenshots/capture.mjs.

Install (Windows Desktop Helper)

Requires Windows 10/11 and Codex from the Microsoft Store:

irm https://raw.githubusercontent.com/Hung2124/codex-multi-profile/main/install.ps1 | iex

Or via npm / npx (Node.js 18+):

npx codex-multi-profile install

This registers the currently signed-in workspace as main, places a Codex shortcut on the Desktop and Start menu, and starts a lightweight background watcher at sign-in (~25 MB, no window). -NoAutoStart skips the startup watcher.

Upgrading from the legacy 0.1–0.2 clone-based layout:

$env:CODEX_MP_REMOVE_LEGACY = '1'; irm https://raw.githubusercontent.com/Hung2124/codex-multi-profile/main/install.ps1 | iex

Good to know

  • Use the profile menu instead of "Log out" when switching workspaces. Logging out inside the app revokes the active refresh token on the server.
  • A saved session that expired shows the sign-in screen after switching; signing in again refreshes the stored profile automatically.
  • Active streaming generations are stopped cleanly before swapping credentials.
  • The local helper runs only while the app is open (~130 MB, near-zero CPU).

Command line (CI, agents, scripts)

# Cross-platform MCP & instruction tooling:
codex-multi-profile mcp-audit .mcp.json --json
codex-multi-profile sync-docs .
codex-multi-profile profiles claude --json

# Windows Desktop workspace profile management:
codex-multi-profile list --json
codex-multi-profile status
codex-multi-profile switch enterprise

# Or directly via PowerShell:
$cli = "$env:LOCALAPPDATA\CodexMultiProfile\CodexAccounts.ps1"
powershell -NoProfile -ExecutionPolicy Bypass -File $cli list      # or: status | save -Name x | switch -Name x | rename -Name x -NewName y | remove -Name x | lang -Name vi

Uninstall

powershell -NoProfile -ExecutionPolicy Bypass -File "$env:LOCALAPPDATA\CodexMultiProfile\Uninstall-CodexMultiProfile.ps1"   # add -RemoveAccounts to delete saved profiles

~\.codex and ~\.claude (conversations, project memory, and active settings) are never deleted.

Privacy and security

  • Saved workspace profiles stay on disk (%LOCALAPPDATA%\CodexMultiProfile on Windows or `~/.config/codex-multi-profil

// HOW IT'S BUILT

// FILES

52 files shipped with this skill. Inline text is the catalog copy. The upstream link is the source repository.

  • SKILL.md3.1 KBdb3efec26ae3upstream ↗
    ---
    name: codex-multi-profile
    description: >-
      Multi-workspace profile router, MCP server (.mcp.json) security auditor, and CLAUDE.md <-> AGENTS.md
      instruction bridge for Claude Code and OpenAI Codex. Isolates Enterprise, Open-Source Maintainer, and
      Personal profiles across ~/.claude and ~/.codex, and provides a native workspace switcher for the
      Microsoft Store Codex app on Windows.
    ---
    
    # Codex Multi-Profile (Claude Code, MCP & OpenAI Codex)
    
    Open-source developer toolkit for isolating **authorized** Enterprise SSO, Client, and Open-Source Maintainer workspaces across **Claude Code** (`~/.claude`), **Model Context Protocol (`.mcp.json`)**, and **OpenAI Codex** (`~/.codex`).
    
    ## Cross-Platform CLI & SDK (`v2.0+`)
    
    ```bash
    # Audit .mcp.json for hardcoded tokens and non-loopback endpoints
    npx codex-multi-profile mcp-audit .mcp.json
    
    # Synchronize CLAUDE.md and AGENTS.md instructions
    npx codex-multi-profile sync-docs .
    
    # Inspect saved Claude Code or Codex profiles
    npx codex-multi-profile profiles claude --json
    ```
    
    ## Windows Store Codex Integration
    
    - Each workspace profile is stored as an isolated snapshot in `%LOCALAPPDATA%\CodexMultiProfile\accounts\<name>\auth.json`.
    - The **Codex** shortcut runs `Start-CodexAccounts.ps1` (hidden): it launches the Store Codex inside its
      package with DevTools bound to `127.0.0.1:9333`, injects `switcher-inject.js`, and bridges workspace switches.
    - Avatar menu (bottom-left) → **Accounts**: click = switch (2-3 s: only the `codex.exe app-server` child restarts, the window
      stays open), **Add account** (restarts on the sign-in screen to register another authorized workspace),
      pencil = rename, trash = remove. `Ctrl+Alt+A` opens the menu, `1`-`9` pick a workspace profile.
    - While Codex runs, rotated refresh tokens in the live `auth.json` are synced back into the active workspace profile.
    
    ## CLI (agents)
    
    ```powershell
    $cli = "$env:LOCALAPPDATA\CodexMultiProfile\CodexAccounts.ps1"
    powershell -NoProfile -ExecutionPolicy Bypass -File $cli list            # -Json for machine output
    powershell -NoProfile -ExecutionPolicy Bypass -File $cli status
    powershell -NoProfile -ExecutionPolicy Bypass -File $cli save -Name work # save the login in use
    powershell -NoProfile -ExecutionPolicy Bypass -File $cli switch -Name work
    powershell -NoProfile -ExecutionPolicy Bypass -File $cli rename -Name work -NewName job
    powershell -NoProfile -ExecutionPolicy Bypass -File $cli remove -Name old
    ```
    
    `switch` restarts only Codex's app-server (2-3 s, the window stays) and stops a reply in progress; tell the user first.
    
    ## Rules
    
    - Never print or copy tokens; emails are shown masked (`ab***@domain`).
    - Do not use Codex's own **Log out** to change accounts: it can invalidate that login's saved copy. Use the menu.
    - A watcher (`CodexAccountsWatcher.exe`, HKCU Run) starts the helper whenever the Store Codex runs without it; from the
      original icon Codex restarts once to get the menu. `status` says whether the menu is attached.
    - Usage bars come from `chatgpt.com/backend-api/wham/usage` with each saved account's own token (numbers only reach
      the page).
    - Log: `%LOCALAPPDATA%\CodexMultiProfile\codex-accounts.log` (masked).
    
  • examples/README.md301 Bd2b75a70b343upstream ↗
    # SDK & CI Examples
    
    - `audit-mcp-ci.mjs`: Validate `.mcp.json` manifests in CI pipelines before deployment.
    - `sync-claude-codex-docs.mjs`: Keep `CLAUDE.md` and `AGENTS.md` synchronized across workspaces.
    - `isolate-claude-profiles.mjs`: Inspect and activate isolated `~/.claude` workspace profiles.
    
  • README.md8.2 KB7bda692c7192upstream ↗
    # Codex Multi-Profile
    
    <p align="center">
      <a href="https://github.com/Hung2124/codex-multi-profile/actions/workflows/ci.yml"><img src="https://github.com/Hung2124/codex-multi-profile/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
      <a href="https://www.npmjs.com/package/codex-multi-profile"><img src="https://img.shields.io/npm/v/codex-multi-profile?color=cb3837&label=npm" alt="npm version"></a>
      <a href="https://github.com/Hung2124/codex-multi-profile/stargazers"><img src="https://img.shields.io/github/stars/Hung2124/codex-multi-profile?color=blue&label=stars" alt="GitHub stars"></a>
      <a href="https://github.com/Hung2124/codex-multi-profile/releases"><img src="https://img.shields.io/github/v/release/Hung2124/codex-multi-profile?label=release" alt="Release"></a>
      <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-yellow.svg" alt="MIT"></a>
      <img src="https://img.shields.io/badge/Claude_Code_%26_MCP-Ready-D97757.svg" alt="Claude Code & MCP">
      <img src="https://img.shields.io/badge/OpenAI_Codex-Supported-10A37F.svg" alt="OpenAI Codex">
    </p>
    
    <p align="center">
      <strong>Multi-workspace profile router, MCP server security auditor, and <code>CLAUDE.md</code> &harr; <code>AGENTS.md</code> instruction bridge for Claude Code and OpenAI Codex.</strong><br>
      Isolate Enterprise, Open-Source Maintainer, and Personal agent environments across repositories.
    </p>
    
    <p align="center">
      <a href="README.vi.md">Tiếng Việt</a> &middot;
      <a href="docs/architecture.md">How it works</a> &middot;
      <a href="docs/troubleshooting.md">Troubleshooting</a> &middot;
      <a href="SUPPORT.md">Support</a>
    </p>
    
    <p align="center">
      <img src="docs/images/accounts-menu.png" alt="Workspace profiles in the avatar menu with telemetry and environment isolation" width="366">
    </p>
    
    > Built for developers, open-source maintainers, and consulting engineers who work across separate **authorized** Enterprise SSO, Client, and Personal workspaces in **Claude Code** and **OpenAI Codex**.
    
    ## Core Capabilities (v2.0)
    
    | Module | What it solves |
    |:---|:---|
    | **Claude Code & Codex Profile Store** (`WorkspaceProfileStore`) | Isolate `~/.claude/settings.json`, `~/.codex`, and workspace `.mcp.json` profiles (`enterprise`, `oss-maintainer`, `research`) with atomic file swaps |
    | **MCP Security & Isolation Auditor** (`mcp-audit`) | Statically audits `.mcp.json` and `claude_desktop_config.json` for hardcoded credentials (`sk-ant-*`, `ghp_*`), non-loopback HTTP/SSE endpoints, and unsafe shell wrappers |
    | **Instruction Bridge** (`sync-docs`) | Deterministically synchronizes shared engineering rules between `CLAUDE.md` (Claude Code) and `AGENTS.md` (OpenAI Codex) across polyglot repositories |
    | **Windows Store Codex Workspace Switcher** | Hot-switches authorized Enterprise, Team, and Personal workspaces in 2–3 seconds directly from the Microsoft Store Codex avatar menu |
    
    ## Cross-Platform CLI & Node.js SDK (Claude Code, MCP & Codex)
    
    Requires Node.js 18+ on macOS, Linux, or Windows:
    
    ```bash
    # Install globally or invoke via npx
    npm install -g codex-multi-profile
    
    # 1. Audit .mcp.json for secret leakage and non-loopback MCP transports
    npx codex-multi-profile mcp-audit .mcp.json
    
    # 2. Synchronize CLAUDE.md <-> AGENTS.md instructions in a repository
    npx codex-multi-profile sync-docs .
    
    # 3. List isolated Claude Code (~/.claude) or Codex (~/.codex) profiles
    npx codex-multi-profile profiles claude
    ```
    
    ### Programmatic SDK Usage (Node.js / TypeScript)
    
    ```javascript
    const {
      WorkspaceProfileStore,
      auditMcpConfig,
      syncWorkspaceInstructions
    } = require("codex-multi-profile");
    
    // 1. Audit an MCP configuration before activating a workspace profile
    const audit = auditMcpConfig({
      mcpServers: {
        github: {
          command: "npx",
          args: ["-y", "@modelcontextprotocol/server-github"],
          env: { GITHUB_PERSONAL_ACCESS_TOKEN: "${GITHUB_PERSONAL_ACCESS_TOKEN}" }
        }
      }
    });
    if (!audit.valid) throw new Error("MCP security audit failed");
    
    // 2. Save and activate an isolated Claude Code profile
    const store = new WorkspaceProfileStore();
    store.saveProfile("oss-maintainer", {
      agent: "claude",
      settings: { model: "claude-sonnet-4-5" }
    });
    store.activateProfile("oss-maintainer", { agent: "claude", workspaceDir: process.cwd() });
    
    // 3. Keep CLAUDE.md and AGENTS.md aligned
    syncWorkspaceInstructions(process.cwd(), { direction: "claude-to-codex" });
    ```
    
    ---
    
    ## Native Windows Desktop Integration (Microsoft Store Codex App)
    
    Click your avatar at the bottom-left of the Windows Store Codex app. Under your identity row there is an **Accounts** workspace section:
    
    | In the menu | Does |
    |:---|:---|
    | Click a workspace profile | Switches to that workspace in 2-3 seconds; the Codex window stays open (from a sign-in screen Codex restarts, ~10 s) |
    | **Add account** | Codex restarts on its sign-in screen; sign in with your other authorized workspace and save it under a profile label |
    | Pencil / trash (hover a row) | Rename / remove a saved workspace profile (the active profile cannot be removed) |
    | `1`-`9` while the menu is open | Activate the workspace profile with that number |
    | `Ctrl+Alt+A` | Open the workspace switcher from anywhere in Codex |
    | Telemetry bars | Displays remaining session quota windows (5h and weekly windows) per workspace; hover for reset timestamp |
    
    The menu follows the application's language (Vietnamese or English) and its light / dark theme.
    
    <p align="center">
      <img src="docs/images/add-account.png" alt="Add workspace profile dialog" width="560">
    </p>
    
    <sub>Screenshots use synthetic profiles; rendered from <code>switcher-inject.js</code> with
    <code>node tools/screenshots/capture.mjs</code>.</sub>
    
    ## Install (Windows Desktop Helper)
    
    Requires Windows 10/11 and [Codex](https://chatgpt.com/codex) from the Microsoft Store:
    
    ```powershell
    irm https://raw.githubusercontent.com/Hung2124/codex-multi-profile/main/install.ps1 | iex
    ```
    
    Or via **npm / npx** (Node.js 18+):
    
    ```powershell
    npx codex-multi-profile install
    ```
    
    This registers the currently signed-in workspace as `main`, places a **Codex** shortcut on the Desktop and Start menu, and starts a lightweight background watcher at sign-in (~25 MB, no window). `-NoAutoStart` skips the startup watcher.
    
    Upgrading from the legacy 0.1–0.2 clone-based layout:
    
    ```powershell
    $env:CODEX_MP_REMOVE_LEGACY = '1'; irm https://raw.githubusercontent.com/Hung2124/codex-multi-profile/main/install.ps1 | iex
    ```
    
    ## Good to know
    
    - **Use the profile menu instead of "Log out" when switching workspaces.** Logging out inside the app revokes the active refresh token on the server.
    - A saved session that expired shows the sign-in screen after switching; signing in again refreshes the stored profile automatically.
    - Active streaming generations are stopped cleanly before swapping credentials.
    - The local helper runs only while the app is open (~130 MB, near-zero CPU).
    
    ## Command line (CI, agents, scripts)
    
    ```powershell
    # Cross-platform MCP & instruction tooling:
    codex-multi-profile mcp-audit .mcp.json --json
    codex-multi-profile sync-docs .
    codex-multi-profile profiles claude --json
    
    # Windows Desktop workspace profile management:
    codex-multi-profile list --json
    codex-multi-profile status
    codex-multi-profile switch enterprise
    
    # Or directly via PowerShell:
    $cli = "$env:LOCALAPPDATA\CodexMultiProfile\CodexAccounts.ps1"
    powershell -NoProfile -ExecutionPolicy Bypass -File $cli list      # or: status | save -Name x | switch -Name x | rename -Name x -NewName y | remove -Name x | lang -Name vi
    ```
    
    ## Uninstall
    
    ```powershell
    powershell -NoProfile -ExecutionPolicy Bypass -File "$env:LOCALAPPDATA\CodexMultiProfile\Uninstall-CodexMultiProfile.ps1"   # add -RemoveAccounts to delete saved profiles
    ```
    
    `~\.codex` and `~\.claude` (conversations, project memory, and active settings) are never deleted.
    
    ## Privacy and security
    
    - Saved workspace profiles stay on disk (`%LOCALAPPDATA%\CodexMultiProfile` on Windows or `~/.config/codex-multi-profile` on macOS/Linux). Nothing is transmitted externally.
    - The UI layer only ever receives masked emails (`ab***@example.com`), never raw tokens.
    - The `mcp-audit` command flags plaintext secrets in `.mcp.json` before they can be committed or loaded into an untrusted workspace.
    - Application binaries are never modified. See [docs/architecture.md](docs/architecture.md) and [SECURITY.md](SECURITY.md).
    
    ## License
    
    MIT
    
  • scripts/CodexAccounts.ps15.0 KB1bddcc6931dcupstream ↗
    #Requires -Version 5.1
    <#
    .SYNOPSIS
      Command line for the saved Codex accounts (same store as the avatar menu).
    
    .EXAMPLE
      CodexAccounts.ps1 list
      CodexAccounts.ps1 save -Name work        # save the login Codex uses now
      CodexAccounts.ps1 switch -Name work      # close Codex, switch, reopen with the account menu
      CodexAccounts.ps1 rename -Name work -NewName cong-viec
      CodexAccounts.ps1 remove -Name old
      CodexAccounts.ps1 lang -Name vi          # menu language: auto | vi | en
      CodexAccounts.ps1 status
    #>
    [CmdletBinding()]
    param(
        [Parameter(Position = 0)] [ValidateSet('list', 'save', 'switch', 'rename', 'remove', 'lang', 'status')] [string]$Action = 'list',
        [string]$Name,
        [string]$NewName,
        [switch]$Json,
        [string]$Root = (Join-Path $env:LOCALAPPDATA 'CodexMultiProfile'),
        [string]$CodexHome = $(if ($env:CODEX_HOME) { $env:CODEX_HOME } else { Join-Path $env:USERPROFILE '.codex' })
    )
    
    $ErrorActionPreference = 'Stop'
    Import-Module (Join-Path $PSScriptRoot 'CodexAccounts.psm1') -Force
    
    function Get-Rows {
        $active = Get-CodexActiveAccount -Root $Root -CodexHome $CodexHome
        return @(Get-CodexAccounts -Root $Root | ForEach-Object {
                [pscustomobject]@{
                    Name     = $_.Name
                    Account  = (Hide-AuthEmail -Email $_.Email)
                    Plan     = $_.Plan
                    Active   = [bool]($active -and $active.Name -eq $_.Name)
                    Depleted = $_.Depleted
                    LastUsed = $_.LastUsed
                }
            })
    }
    
    switch ($Action) {
        'list' {
            $rows = Get-Rows
            if ($Json) { ConvertTo-Json -InputObject @($rows) -Depth 3 }
            elseif ($rows.Count -eq 0) { 'No saved accounts. Open Codex from the Codex shortcut, or run: CodexAccounts.ps1 save -Name <name>' }
            else { $rows | Format-Table -AutoSize | Out-String -Width 200 }
        }
        'save' {
            $saved = Save-CodexAccount -Name $Name -Root $Root -CodexHome $CodexHome
            "Saved the current login as $saved."
        }
        'switch' {
            if (-not $Name) { throw 'Use -Name <account>.' }
            $key = ConvertTo-AccountKey -Name $Name
            if (-not (Get-AuthIdentity -Path (Join-Path $Root "accounts\$key\auth.json"))) { throw "Unknown account '$key'." }
            # Same fast path as the menu: only the app-server restarts, the Codex window stays.
            if (Restart-CodexAppServer -Swap { Set-CodexLiveAuth -Name $key -Root $Root -CodexHome $CodexHome }) {
                Write-CodexLog -Message "[cli] switched to $key (fast)" -Root $Root
                "Switched to $key."
                break
            }
            Stop-CodexStore
            if (@(Get-CodexStoreProcesses).Count) { throw 'Codex did not close; nothing was changed.' }
            Set-CodexLiveAuth -Name $key -Root $Root -CodexHome $CodexHome
            Write-CodexLog -Message "[cli] switched to $key" -Root $Root
            $launch = Get-CodexLauncherCommand -Root $Root
            Start-Process -FilePath $launch.FilePath -ArgumentList $launch.Arguments -WindowStyle Hidden
            "Switched to $key. Codex is reopening."
        }
        'rename' {
            if (-not $Name -or -not $NewName) { throw 'Use -Name <account> -NewName <new name>.' }
            $new = Rename-CodexAccount -Name (ConvertTo-AccountKey -Name $Name) -NewName $NewName -Root $Root
            "Renamed to $new."
        }
        'remove' {
            if (-not $Name) { throw 'Use -Name <account>.' }
            Remove-CodexAccount -Name (ConvertTo-AccountKey -Name $Name) -Root $Root -CodexHome $CodexHome
            "Removed $Name."
        }
        'lang' {
            if ($Name -notin @('auto', 'vi', 'en')) { throw 'Use -Name auto, vi or en.' }
            $settings = Get-CodexAccountsSettings -Root $Root
            Write-Utf8NoBom -Path (Join-Path $Root 'settings.json') -Text ((([ordered]@{ cdpPort = $settings.CdpPort; lang = $Name }) | ConvertTo-Json) + "`n")
            "Menu language: $Name (applies the next time the menu opens)."
        }
        'status' {
            $settings = Get-CodexAccountsSettings -Root $Root
            $live = Get-AuthIdentity -Path (Join-Path $CodexHome 'auth.json')
            $active = Get-CodexActiveAccount -Root $Root -CodexHome $CodexHome
            $procs = @(Get-CodexStoreProcesses)
            $hostUp = @(Get-CimInstance Win32_Process -Filter "Name='powershell.exe'" -ErrorAction SilentlyContinue | Where-Object { [string]$_.CommandLine -like '*Start-CodexAccounts.ps1*' }).Count -gt 0
            "Version:        $(Get-CodexMultiProfileVersion)"
            "Codex (Store):  $(try { (Get-CodexStorePackage).Version } catch { 'NOT INSTALLED' })"
            "Signed in as:   $(if ($live) { Hide-AuthEmail -Email $live.Email } else { '(signed out)' })"
            "Active account: $(if ($active) { $active.Name } else { '(not saved)' })"
            "Codex running:  $(if ($procs.Count) { 'yes' + $(if (Test-CodexStoreHasCdp -Port $settings.CdpPort) { ', with the account menu' } else { ', WITHOUT the account menu (opened from the original icon)' }) } else { 'no' })"
            "Menu helper:    $(if ($hostUp) { 'running' } else { 'not running' }) (127.0.0.1:$($settings.CdpPort), language $($settings.Lang))"
            "Accounts:       $(@(Get-CodexAccounts -Root $Root).Count)"
        }
    }
    
  • scripts/CodexAccounts.psm130 KB4718413e48bdupstream ↗
    #Requires -Version 5.1
    <#
      Codex Multi-Profile core: several ChatGPT logins for the Microsoft Store Codex app.
    
      One account = one saved copy of ~/.codex/auth.json under
      %LOCALAPPDATA%\CodexMultiProfile\accounts\<name>\auth.json.
      Switching = sync the live auth.json back into the account in use, copy the chosen
      account's auth.json in place, restart the Store Codex. Chats, projects, skills and
      settings in ~/.codex are shared by every account.
    #>
    Set-StrictMode -Version Latest
    
    $script:ModuleVersion = '0.4.0'
    
    function Get-CodexMultiProfileVersion {
        foreach ($path in @((Join-Path $PSScriptRoot 'VERSION'), (Join-Path (Split-Path -Parent $PSScriptRoot) 'VERSION'))) {
            if (Test-Path -LiteralPath $path) { return ((Get-Content -LiteralPath $path -Raw).Trim()) }
        }
        return $script:ModuleVersion
    }
    
    function Get-CodexAccountsRoot {
        return (Join-Path $env:LOCALAPPDATA 'CodexMultiProfile')
    }
    
    function Get-CodexHome {
        if ($env:CODEX_HOME) { return $env:CODEX_HOME }
        return (Join-Path $env:USERPROFILE '.codex')
    }
    
    function Write-CodexLog {
        param([Parameter(Mandatory)] [string]$Message, [string]$Root = (Get-CodexAccountsRoot))
        $log = Join-Path $Root 'codex-accounts.log'
        try {
            if ((Test-Path -LiteralPath $log) -and (Get-Item -LiteralPath $log).Length -gt 512KB) {
                Move-Item -LiteralPath $log -Destination "$log.1" -Force
            }
            Add-Content -LiteralPath $log -Value ("{0} {1}" -f (Get-Date -Format 'yyyy-MM-dd HH:mm:ss.fff'), $Message)
        }
        catch { }
    }
    
    function Write-Utf8NoBom {
        param([Parameter(Mandatory)] [string]$Path, [Parameter(Mandatory)] [AllowEmptyString()] [string]$Text)
        $dir = Split-Path -Parent $Path
        if ($dir -and -not (Test-Path -LiteralPath $dir)) { New-Item -ItemType Directory -Force -Path $dir | Out-Null }
        [System.IO.File]::WriteAllText($Path, $Text, (New-Object System.Text.UTF8Encoding($false)))
    }
    
    function Copy-FileAtomic {
        # Write next to the target, then rename over it: Codex never sees a half-written auth.json.
        param([Parameter(Mandatory)] [string]$Source, [Parameter(Mandatory)] [string]$Destination)
        $dir = Split-Path -Parent $Destination
        if (-not (Test-Path -LiteralPath $dir)) { New-Item -ItemType Directory -Force -Path $dir | Out-Null }
        $tmp = "$Destination.tmp-$PID"
        Copy-Item -LiteralPath $Source -Destination $tmp -Force
        Move-Item -LiteralPath $tmp -Destination $Destination -Force
    }
    
    function Remove-CodexTreeNoFollow {
        <#
        .SYNOPSIS
          Delete a folder without ever following a junction or symlink inside it (the old
          clone profiles linked memories / skills / plugins to ~/.codex). Long paths are fine.
        #>
        param([Parameter(Mandatory)] [string]$Path)
        $full = [IO.Path]::GetFullPath($Path)
        if (-not $full.StartsWith('\\?\')) { $full = '\\?\' + $full }
        if (-not [IO.Directory]::Exists($full)) { return }
        foreach ($dir in [IO.Directory]::GetDirectories($full)) {
            if (([IO.File]::GetAttributes($dir) -band [IO.FileAttributes]::ReparsePoint) -ne 0) { [IO.Directory]::Delete($dir, $false) }
            else { Remove-CodexTreeNoFollow -Path $dir }
        }
        foreach ($file in [IO.Directory]::GetFiles($full)) {
            [IO.File]::SetAttributes($file, [IO.FileAttributes]::Normal)
            [IO.File]::Delete($file)
        }
        [IO.Directory]::Delete($full, $false)
    }
    
    function ConvertTo-AccountKey {
        <#
        .SYNOPSIS
          Folder-safe account name: lower-case a-z 0-9 and dashes, accents dropped ("Cong viec" -> cong-viec).
        #>
        param([Parameter(Mandatory)] [AllowEmptyString()] [string]$Name)
        $s = $Name.Normalize([Text.NormalizationForm]::FormD)
        $s = [regex]::Replace($s, '\p{Mn}', '')
        $s = $s.Replace([string][char]0x0111, 'd').Replace([string][char]0x0110, 'D')
        $s = [regex]::Replace($s.ToLowerInvariant(), '[^a-z0-9]+', '-').Trim('-')
        if ($s.Length -gt 64) { $s = $s.Substring(0, 64).Trim('-') }
        if (-not $s) { throw "Invalid account name: '$Name'" }
        return $s
    }
    
    function ConvertFrom-JwtPayload {
        param([Parameter(Mandatory)] [string]$Jwt)
        $parts = $Jwt.Split('.')
        if ($parts.Count -lt 2) { throw 'JWT missing payload' }
        $payload = $parts[1].Replace('-', '+').Replace('_', '/')
        while ($payload.Length % 4) { $payload += '=' }
        return ([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($payload)) | ConvertFrom-Json)
    }
    
    function Get-AuthIdentity {
        <#
        .SYNOPSIS
          Who a Codex auth.json belongs to: email, ChatGPT account id, plan. $null if unreadable.
        #>
        param([Parameter(Mandatory)] [string]$Path)
        if (-not (Test-Path -LiteralPath $Path)) { return $null }
        try {
            $j = Get-Content -LiteralPath $Path -Raw -Encoding UTF8 | ConvertFrom-Json
            if (-not $j.PSObject.Properties['tokens'] -or -not $j.tokens) { return $null }
            $claims = ConvertFrom-JwtPayload -Jwt ([string]$j.tokens.id_token)
            $email = [string]$claims.email
            if ([string]::IsNullOrWhiteSpace($email)) { return $null }
            $accountId = ''
            $plan = ''
            $auth = $claims.PSObject.Properties['https://api.openai.com/auth']
            if ($auth -and $auth.Value) {
                if ($auth.Value.PSObject.Properties['chatgpt_account_id']) { $accountId = [string]$auth.Value.chatgpt_account_id }
                if ($auth.Value.PSObject.Properties['chatgpt_plan_type']) { $plan = [string]$auth.Value.chatgpt_plan_type }
            }
            if (-not $accountId -and $j.tokens.PSObject.Properties['account_id']) { $accountId = [string]$j.tokens.account_id }
            return [pscustomobject]@{ Email = $email; AccountId = $accountId; Plan = $plan }
        }
        catch { return $null }
    }
    
    function Test-SameIdentity($A, $B) {
        if (-not $A -or -not $B) { return $false }
        if ($A.Email -ne $B.Email) { return $false }
        # Same email in two ChatGPT workspaces = two accounts.
        if ($A.AccountId -and $B.AccountId) { return ($A.AccountId -eq $B.AccountId) }
        return $true
    }
    
    function Hide-AuthEmail {
        <#
        .SYNOPSIS
          ab***@domain.com. The local part is never shown in full.
        #>
        param([Parameter(Mandatory)] [AllowEmptyString()] [string]$Email)
        $at = $Email.IndexOf('@')
        if ($at -lt 1) { return '' }
        return ($Email.Substring(0, [Math]::Min(2, $at)) + '***' + $Email.Substring($at))
    }
    
    function Test-CodexTextHasFullEmail {
        param([Parameter(Mandatory)] [AllowEmptyString()] [string]$Text)
        foreach ($m in [regex]::Matches($Text, '[A-Za-z0-9._%+\-*]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}')) {
            if ($m.Value -notmatch '^[^@]{0,2}\*\*\*@') { return $true }
        }
        return $false
    }
    
    # ---------------------------------------------------------------- account store
    
    function Get-CodexAccountsMeta {
        param([string]$Root = (Get-CodexAccountsRoot))
        $meta = @{}
        $path = Join-Path $Root 'accounts.json'
        if (Test-Path -LiteralPath $path) {
            try {
                $obj = Get-Content -LiteralPath $path -Raw -Encoding UTF8 | ConvertFrom-Json
                foreach ($p in $obj.PSObject.Properties) {
                    $meta[$p.Name] = @{
                        depleted = [bool]($p.Value.PSObject.Properties['depleted'] -and $p.Value.depleted)
                        lastUsed = $(if ($p.Value.PSObject.Properties['lastUsed']) { [string]$p.Value.lastUsed } else { '' })
                    }
                }
            }
            catch { }
        }
        return $meta
    }
    
    function Save-CodexAccountsMeta {
        param([Parameter(Mandatory)] [hashtable]$Meta, [string]$Root = (Get-CodexAccountsRoot))
        $ordered = [ordered]@{}
        foreach ($k in ($Meta.Keys | Sort-Object)) { $ordered[$k] = $Meta[$k] }
        Write-Utf8NoBom -Path (Join-Path $Root 'accounts.json') -Text (($ordered | ConvertTo-Json -Depth 4) + "`n")
    }
    
    function Set-CodexAccountMeta {
        param(
            [Parameter(Mandatory)] [string]$Name,
            [string]$Root = (Get-CodexAccountsRoot),
            [object]$Depleted = $null,
            [switch]$Used
        )
        $meta = Get-CodexAccountsMeta -Root $Root
        if (-not $meta.ContainsKey($Name)) { $meta[$Name] = @{ depleted = $false; lastUsed = '' } }
        if ($null -ne $Depleted) { $meta[$Name].depleted = [bool]$Depleted }
        if ($Used) { $meta[$Name].lastUsed = (Get-Date).ToUniversalTime().ToString('o'); $meta[$Name].depleted = $false }
        Save-CodexAccountsMeta -Meta $meta -Root $Root
    }
    
    function Get-CodexAccounts {
        <#
        .SYNOPSIS
          Saved accounts, oldest first: Name, Email, AccountId, Plan, Depleted, LastUsed, AuthPath.
        #>
        param([string]$Root = (Get-CodexAccountsRoot))
        $dir = Join-Path $Root 'accounts'
        if (-not (Test-Path -LiteralPath $dir)) { return @() }
        $meta = Get-CodexAccountsMeta -Root $Root
        $rows = foreach ($d in (Get-ChildItem -LiteralPath $dir -Directory | Sort-Object CreationTimeUtc, Name)) {
            if ($d.Name -notmatch '^[a-z0-9][a-z0-9\-]{0,63}$') { continue }
            $authPath = Join-Path $d.FullName 'auth.json'
            $id = Get-AuthIdentity -Path $authPath
            $m = $meta[$d.Name]
            [pscustomobject]@{
                Name      = $d.Name
                Email     = $(if ($id) { $id.Email } else { '' })
                AccountId = $(if ($id) { $id.AccountId } else { '' })
                Plan      = $(if ($id) { $id.Plan } else { '' })
                Depleted  = [bool]($m -and $m.depleted)
                LastUsed  = $(if ($m) { $m.lastUsed } else { '' })
                AuthPath  = $authPath
            }
        }
        return @($rows)
    }
    
    function Find-CodexAccountByIdentity {
        param($Identity, [string]$Root = (Get-CodexAccountsRoot))
        if (-not $Identity) { return $null }
        foreach ($a in (Get-CodexAccounts -Root $Root)) {
            if (Test-SameIdentity $Identity ([pscustomobject]@{ Email = $a.Email; AccountId = $a.AccountId })) { return $a }
        }
        return $null
    }
    
    function Get-CodexActiveAccount {
        <#
        .SYNOPSIS
          The saved account whose login is in ~/.codex/auth.json right now, or $null.
        #>
        param([string]$Root = (Get-CodexAccountsRoot), [string]$CodexHome = (Get-CodexHome))
        return (Find-CodexAccountByIdentity -Identity (Get-AuthIdentity -Path (Join-Path $CodexHome 'auth.json')) -Root $Root)
    }
    
    function Sync-CodexActiveAccount {
        <#
        .SYNOPSIS
          Copy the live auth.json into the account it belongs to when it changed.
          Codex refreshes (and rotates) tokens in place; a stale saved copy stops working.
        #>
        param([string]$Root = (Get-CodexAccountsRoot), [string]$CodexHome = (Get-CodexHome))
        $live = Join-Path $CodexHome 'auth.json'
        $active = Get-CodexActiveAccount -Root $Root -CodexHome $CodexHome
        if (-not $active) { return $null }
        $same = (Test-Path -LiteralPath $active.AuthPath) -and
            ((Get-FileHash -LiteralPath $live -Algorithm SHA256).Hash -eq (Get-FileHash -LiteralPath $active.AuthPath -Algorithm SHA256).Hash)
        if (-not $same) { Copy-FileAtomic -Source $live -Destination $active.AuthPath }
        return $active.Name
    }
    
    function Get-CodexNextAccountName {
        param([string]$Root = (Get-CodexAccountsRoot))
        $names = @(Get-CodexAccounts -Root $Root | ForEach-Object { $_.Name })
        if ($names -notcontains 'main') { return 'main' }
        $i = 2
        while ($names -contains "account-$i") { $i++ }
        return "account-$i"
    }
    
    function Save-CodexAccount {
        <#
        .SYNOPSIS
          Save the login in ~/.codex/auth.json as a named account.
        #>
        param(
            [string]$Name,
            [string]$Root = (Get-CodexAccountsRoot),
            [string]$CodexHome = (Get-CodexHome)
        )
        $live = Join-Path $CodexHome 'auth.json'
        $id = Get-AuthIdentity -Path $live
        if (-not $id) { throw 'Codex is not signed in (no readable ~/.codex/auth.json).' }
        $existing = Find-CodexAccountByIdentity -Identity $id -Root $Root
        if ($existing) { throw "This login is already saved as '$($existing.Name)'." }
        if (-not $Name) { $Name = Get-CodexNextAccountName -Root $Root }
        $key = ConvertTo-AccountKey -Name $Name
        $target = Join-Path $Root "accounts\$key"
        if (Test-Path -LiteralPath $target) { throw "An account named '$key' already exists." }
        Copy-FileAtomic -Source $live -Destination (Join-Path $target 'auth.json')
        Set-CodexAccountMeta -Name $key -Root $Root -Used
        return $key
    }
    
    function Remove-CodexAccount {
        param(
            [Parameter(Mandatory)] [string]$Name,
            [string]$Root = (Get-CodexAccountsRoot),
            [string]$CodexHome = (Get-CodexHome)
        )
        $active = Get-CodexActiveAccount -Root $Root -CodexHome $CodexHome
        if ($active -and $active.Name -eq $Name) { throw "'$Name' is the account in use. Switch to another one first." }
        $dir = Join-Path $Root "accounts\$Name"
        if (-not (Test-Path -LiteralPath $dir)) { throw "Unknown account '$Name'." }
        Remove-Item -LiteralPath $dir -Recurse -Force
        $meta = Get-CodexAccountsMeta -Root $Root
        if ($meta.ContainsKey($Name)) { $meta.Remove($Name); Save-CodexAccountsMeta -Meta $meta -Root $Root }
    }
    
    function Rename-CodexAccount {
        param(
            [Parameter(Mandatory)] [string]$Name,
            [Parameter(Mandatory)] [string]$NewName,
            [string]$Root = (Get-CodexAccountsRoot)
        )
        $key = ConvertTo-AccountKey -Name $NewName
        $dir = Join-Path $Root "accounts\$Name"
        if (-not (Test-Path -LiteralPath $dir)) { throw "Unknown account '$Name'." }
        if ($key -eq $Name) { return $key }
        if (Test-Path -LiteralPath (Join-Path $Root "accounts\$key")) { throw "An account named '$key' already exists." }
        Rename-Item -LiteralPath $dir -NewName $key
        $meta = Get-CodexAccountsMeta -Root $Root
        if ($meta.ContainsKey($Name)) { $meta[$key] = $meta[$Name]; $meta.Remove($Name); Save-CodexAccountsMeta -Meta $meta -Root $Root }
        return $key
    }
    
    function Set-CodexLiveAuth {
        <#
        .SYNOPSIS
          Put account <Name> into ~/.codex/auth.json (Codex must be closed).
          The outgoing login is synced into its own account first.
        #>
        param(
            [Parameter(Mandatory)] [string]$Name,
            [string]$Root = (Get-CodexAccountsRoot),
            [string]$CodexHome = (Get-CodexHome)
        )
        $src = Join-Path $Root "accounts\$Name\auth.json"
        if (-not (Get-AuthIdentity -Path $src)) { throw "Account '$Name' has no usable saved login." }
        $null = Sync-CodexActiveAccount -Root $Root -CodexHome $CodexHome
        Copy-FileAtomic -Source $src -Destination (Join-Path $CodexHome 'auth.json')
        Set-CodexAccountMeta -Name $Name -Root $Root -Used
    }
    
    function Clear-CodexLiveAuth {
        <#
        .SYNOPSIS
          Sign-in screen for a new account (Codex must be closed). Refuses to drop a login
          that is not saved anywhere.
        #>
        param([string]$Root = (Get-CodexAccountsRoot), [string]$CodexHome = (Get-CodexHome))
        $live = Join-Path $CodexHome 'auth.json'
        if (-not (Test-Path -LiteralPath $live)) { return }
        if (Get-AuthIdentity -Path $live) {
            if (-not (Sync-CodexActiveAccount -Root $Root -CodexHome $CodexHome)) { throw 'The current login is not saved; save it before adding another.' }
        }
        Remove-Item -LiteralPath $live -Force
    }
    
    # ---------------------------------------------------------------- Store Codex process
    
    function Get-CodexStorePackage {
        $pkg = Get-AppxPackage -Name 'OpenAI.Codex' -ErrorAction SilentlyContinue | Sort-Object Version -Descending | Select-Object -First 1
        if (-not $pkg) { throw 'Codex from the Microsoft Store is not installed.' }
        return $pkg
    }
    
    function Get-CodexStoreProcesses {
        <#
        .SYNOPSIS
          Browser (main) processes of the Store Codex: ChatGPT.exe under WindowsApps\OpenAI.Codex_*, no --type=.
        #>
        return @(Get-CimInstance Win32_Process -Filter "Name='ChatGPT.exe'" -ErrorAction SilentlyContinue | Where-Object {
                ([string]$_.ExecutablePath -like '*\WindowsApps\OpenAI.Codex_*') -and ([string]$_.CommandLine -notmatch '--type=')
            })
    }
    
    function Test-CodexStoreHasCdp {
        param([Parameter(Mandatory)] [int]$Port)
        return (@(Get-CodexStoreProcesses | Where-Object { [string]$_.CommandLine -match ("--remote-debugging-port={0}(\s|`"|$)" -f $Port) }).Count -gt 0)
    }
    
    function Get-CodexStoreProcessTree {
        <#
        .SYNOPSIS
          Ids of the Store Codex and everything it started (renderers, GPU, the codex.exe app-server,
          computer-use helpers), from one process snapshot.
        #>
        $all = @(Get-CimInstance Win32_Process -ErrorAction SilentlyContinue)
        $ids = New-Object System.Collections.Generic.List[int]
        $todo = New-Object System.Collections.Generic.List[int]
        foreach ($p in $all) {
            if ($p.Name -eq 'ChatGPT.exe' -and [string]$p.ExecutablePath -like '*\WindowsApps\OpenAI.Codex_*') { $todo.Add([int]$p.ProcessId) }
        }
        while ($todo.Count -gt 0) {
            $id = $todo[0]
            $todo.RemoveAt(0)
            if ($ids.Contains($id)) { continue }
            $ids.Add($id)
            foreach ($c in $all) { if ([int]$c.ParentProcessId -eq $id -and -not $ids.Contains([int]$c.ProcessId)) { $todo.Add([int]$c.ProcessId) } }
        }
        return , $ids.ToArray()
    }
    
    function Get-CodexAppServer {
        <#
        .SYNOPSIS
          The codex.exe app-server(s) the Store Codex window talks to (ProcessId, CreationDate).
          It holds the ChatGPT login; the window itself does not.
        #>
        $mains = @(Get-CodexStoreProcesses | ForEach-Object { [int]$_.ProcessId })
        if ($mains.Count -eq 0) { return @() }
        return @(Get-CimInstance Win32_Process -Filter "Name='codex.exe'" -ErrorAction SilentlyContinue | Where-Object {
                $mains -contains [int]$_.ParentProcessId -and [string]$_.CommandLine -match '\sapp-server(\s|$)'
            })
    }
    
    function Restart-CodexAppServer {
        <#
        .SYNOPSIS
          Fast account switch: end only the app-server, run $Swap (auth.json changes) and let the Codex
          window start a new app-server on the new login. The window stays open and picks the account
          up by itself (a few seconds, no restart). Returns $false when Codex did not bring a new
          app-server up; the caller then restarts Codex. Errors from $Swap are rethrown.
        #>
        param([Parameter(Mandatory)] [scriptblock]$Swap, [int]$TimeoutSec = 10)
        $old = @(Get-CodexAppServer)
        if ($old.Count -eq 0) { return $false }
        $gone = New-Object System.Collections.Generic.List[int]
        foreach ($p in $old) { $gone.Add([int]$p.ProcessId) }
        Stop-Process -Id $gone.ToArray() -Force -ErrorAction SilentlyContinue
        $deadline = (Get-Date).AddSeconds(3)
        while ((Get-Date) -lt $deadline -and @(Get-Process -Id $gone.ToArray() -ErrorAction SilentlyContinue).Count -gt 0) { Start-Sleep -Milliseconds 50 }
        & $Swap
        $swapped = Get-Date
        $deadline = $swapped.AddSeconds($TimeoutSec)
        while ((Get-Date) -lt $deadline) {
            $fresh = @(Get-CodexAppServer | Where-Object { -not $gone.Contains([int]$_.ProcessId) })
            foreach ($p in $fresh) {
                if ($p.CreationDate -ge $swapped.AddMilliseconds(-50)) { return $true }
                # Codex was quicker than the swap: this one may have read the old login. Once more.
                $gone.Add([int]$p.ProcessId)
                Stop-Process -Id $p.ProcessId -Force -ErrorAction SilentlyContinue
            }
            Start-Sleep -Milliseconds 200
        }
        return $false
    }
    
    function Stop-CodexStore {
        <#
        .SYNOPSIS
          End the Store Codex and its whole process tree, and wait until it is really gone: a new
          instance started while the old one is still exiting hangs on "The application is exiting".
          (Closing the window only hides Codex, so there is nothing to wait for there.) Never throws.
        #>
        $ids = Get-CodexStoreProcessTree
        if ($ids.Count -eq 0) { return }
        Stop-Process -Id $ids -Force -ErrorAction SilentlyContinue
        $deadline = (Get-Date).AddSeconds(10)
        while ((Get-Date) -lt $deadline -and @(Get-Process -Id $ids -ErrorAction SilentlyContinue).Count -gt 0) {
            Start-Sleep -Milliseconds 100
        }
    }
    
    function Start-CodexStore {
        <#
        .SYNOPSIS
          Start the Store Codex through Windows app activation (it refuses to run without package
          identity), with the DevTools protocol on 127.0.0.1:<Port> for the account menu. Returns the pid.
          Invoke-CommandInDesktopPackage and shell:AppsFolder were tried: from a normal process both
          leave a hung ChatGPT.exe with no window and no port.
        #>
        param([Parameter(Mandatory)] [int]$Port)
        if (-not ('CodexMultiProfile.AppActivation' -as [type]) -or -not [CodexMultiProfile.AppActivation].GetMethod('ActivateWithTimeout')) {
            Add-Type -TypeDefinition @'
    using System;
    using System.Runtime.InteropServices;
    namespace CodexMultiProfile {
        [ComImport, Guid("2e941141-7f97-4756-ba1d-9decde894a3d"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
        interface IApplicationActivationManager {
            int ActivateApplication([MarshalAs(UnmanagedType.LPWStr)] string appUserModelId, [MarshalAs(UnmanagedType.LPWStr)] string arguments, int options, out uint processId);
        }
        [ComImport, Guid("45BA127D-10A8-46EA-8AB7-56EA9078943C")]
        class ApplicationActivationManager { }
        public static class AppActivation {
            public static uint Activate(string appUserModelId, string arguments) {
                uint pid;
                int hr = ((IApplicationActivationManager)new ApplicationActivationManager()).ActivateApplication(appUserModelId, arguments, 0, out pid);
                if (hr != 0) { Marshal.ThrowExceptionForHR(hr); }
                return pid;
            }
            // ActivateApplication waits for the app to come up; never let that freeze the caller.
            public static uint ActivateWithTimeout(string appUserModelId, string arguments, int timeoutMs) {
                var task = System.Threading.Tasks.Task.Run(() => Activate(appUserModelId, arguments));
                return task.Wait(timeoutMs) ? task.Result : 0;
            }
        }
    }
    '@
        }
        $pkg = Get-CodexStorePackage
        $cdpArgs = "--remote-debugging-address=127.0.0.1 --remote-debugging-port=$Port"
        return [CodexMultiProfile.AppActivation]::ActivateWithTimeout("$($pkg.PackageFamilyName)!App", $cdpArgs, 15000)
    }
    
    function Get-CodexLauncherCommand {
        <#
        .SYNOPSIS
          What the Codex shortcut runs: the host in a hidden PowerShell. conhost --headless keeps
          it windowless without VBScript (Windows is phasing VBScript / wscript out).
        #>
        param([string]$Root = (Get-CodexAccountsRoot))
        return [pscustomobject]@{
            FilePath  = Join-Path $env:WINDIR 'System32\conhost.exe'
            Arguments = '--headless powershell.exe -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File "{0}"' -f (Join-Path $Root 'Start-CodexAccounts.ps1')
        }
    }
    
    # ---------------------------------------------------------------- page <-> host
    
    function Get-CodexSwitcherBindingName { return 'cmpSwitcherBridge' }
    
    function Get-CodexAccountsSettings {
        param([string]$Root = (Get-CodexAccountsRoot))
        $port = 9333
        $lang = 'auto'
        $path = Join-Path $Root 'settings.json'
        if (Test-Path -LiteralPath $path) {
            try {
                $obj = Get-Content -LiteralPath $path -Raw -Encoding UTF8 | ConvertFrom-Json
                if ($obj.PSObject.Properties['cdpPort'] -and [int]$obj.cdpPort -gt 1023) { $port = [int]$obj.cdpPort }
                if ($obj.PSObject.Properties['lang'] -and ([string]$obj.lang) -in @('auto', 'vi', 'en')) { $lang = [string]$obj.lang }
            }
            catch { }
        }
        return [pscustomobject]@{ CdpPort = $port; Lang = $lang }
    }
    
    function ConvertFrom-CodexUsageJson {
        <#
        .SYNOPSIS
          Usage windows from chatgpt.com/backend-api/wham/usage: label (5h / week / month / Nd / Nh),
          percent used, reset time (unix seconds), and whether a limit is reached. Numbers only.
        #>
        param([Parameter(Mandatory)] [string]$Json)
        $u = ConvertFrom-Json -InputObject $Json
        $rl = $null
        if ($u.PSObject.Properties['rate_limit']) { $rl = $u.rate_limit }
        $windows = @()
        if ($rl) {
            foreach ($name in @('primary_window', 'secondary_window')) {
                if (-not $rl.PSObject.Properties[$name] -or -not $rl.$name) { continue }
                $w = $rl.$name
                $secs = [int64]$w.limit_window_seconds
                # if/elseif, not switch: a PowerShell switch returns every matching branch (604800 -> week AND 7d).
                if ($secs -eq 18000) { $label = '5h' }
                elseif ($secs -eq 604800) { $label = 'week' }
                elseif ($secs -ge 2419200 -and $secs -le 2678400) { $label = 'month' }
                elseif ($secs -ge 86400) { $label = '{0}d' -f [int]($secs / 86400) }
                else { $label = '{0}h' -f [Math]::Max(1, [int]($secs / 3600)) }
                $used = [int][Math]::Round([double]$w.used_percent)
                $windows += [ordered]@{
                    label   = $label
                    used    = [Math]::Min(100, [Math]::Max(0, $used))
                    resetAt = $(if ($w.PSObject.Properties['reset_at']) { [int64]$w.reset_at } else { $null })
                }
            }
        }
        $reached = [bool]($rl -and $rl.PSObject.Properties['limit_reached'] -and $rl.limit_reached)
        return [ordered]@{ windows = $windows; limitReached = $reached }
    }
    
    function New-CodexUsageRequest {
        <#
        .SYNOPSIS
          HTTP request for one saved account's usage (sent only to chatgpt.com, like Codex itself does).
        #>
        param([Parameter(Mandatory)] [string]$AuthPath)
        Add-Type -AssemblyName System.Net.Http
        $j = Get-Content -LiteralPath $AuthPath -Raw -Encoding UTF8 | ConvertFrom-Json
        $token = [string]$j.tokens.access_token
        if (-not $token) { return $null }
        $id = Get-AuthIdentity -Path $AuthPath
        $req = New-Object System.Net.Http.HttpRequestMessage([System.Net.Http.HttpMethod]::Get, 'https://chatgpt.com/backend-api/wham/usage')
        $req.Headers.Authorization = New-Object System.Net.Http.Headers.AuthenticationHeaderValue('Bearer', $token)
        if ($id -and $id.AccountId) { [void]$req.Headers.TryAddWithoutValidation('ChatGPT-Account-Id', $id.AccountId) }
        [void]$req.Headers.TryAddWithoutValidation('User-Agent', 'codex-multi-profile')
        return $req
    }
    
    function Get-CodexSwitcherSnapshot {
        <#
        .SYNOPSIS
          State pushed into the Codex window. Masked emails only; no tokens, no paths.
        #>
        param(
            [string]$Root = (Get-CodexAccountsRoot),
            [string]$CodexHome = (Get-CodexHome),
            [string]$Pending = '',
            # name -> ConvertFrom-CodexUsageJson result (optional)
            [hashtable]$Usage = @{}
        )
        $accounts = @(Get-CodexAccounts -Root $Root)
        $active = Get-CodexActiveAccount -Root $Root -CodexHome $CodexHome
        $activeName = $(if ($active) { $active.Name } else { $null })
        $out = @{}
        $profiles = @(foreach ($a in $accounts) {
                $u = $Usage[$a.Name]
                # Via a variable: $( @(x) ) would unroll a one-window list (free plan: month only) into a plain object.
                $windows = $null
                if ($u) { $windows = [object[]]@($u.windows) }
                $isOut = [bool]$a.Depleted -or [bool]($u -and $u.limitReached)
                $out[$a.Name] = $isOut
                [ordered]@{
                    name       = $a.Name
                    account    = (Hide-AuthEmail -Email $a.Email)
                    plan       = $a.Plan
                    depleted   = $isOut
                    needsLogin = (-not $a.Email)
                    active     = ($a.Name -eq $activeName)
                    usage      = $windows
                }
            })
        # Usage-limit hint: least recently used saved account that is not out of quota.
        $next = @($accounts | Where-Object { $_.Name -ne $activeName -and -not $out[$_.Name] -and $_.Email } | Sort-Object LastUsed | Select-Object -First 1)
        $settings = Get-CodexAccountsSettings -Root $Root
        return [ordered]@{
            version    = (Get-CodexMultiProfileVersion)
            active     = $activeName
            signedIn   = [bool](Get-AuthIdentity -Path (Join-Path $CodexHome 'auth.json'))
            pending    = $(if ($Pending) { $Pending } else { $null })
            suggestion = $(if ($next.Count) { $next[0].Name } else { $null })
            hotkey     = 'Ctrl+Alt+A'
            lang       = $settings.Lang
            profiles   = $profiles
        }
    }
    
    function ConvertFrom-CodexSwitcherMessage {
        <#
        .SYNOPSIS
          Validate one message from the page (CDP binding). Never trusts page input.
          Returns Type / Profile / Name / Value, or Error.
        #>
        param(
            [Parameter(Mandatory)] [AllowEmptyString()] [string]$Payload,
            [string[]]$KnownProfiles = @()
        )
        function New-Result([string]$Type, [string]$ProfileName, [string]$Name, $Value, [string]$ErrorText) {
            return [pscustomobject]@{ Type = $Type; Profile = $ProfileName; Name = $Name; Value = $Value; Error = $ErrorText }
        }
        if ([string]::IsNullOrWhiteSpace($Payload)) { return (New-Result '' '' '' $null 'empty') }
        if ($Payload.Length -gt 4096) { return (New-Result '' '' '' $null 'too-large') }
        try { $msg = $Payload | ConvertFrom-Json } catch { return (New-Result '' '' '' $null 'bad-json') }
        if ($null -eq $msg -or -not $msg.PSObject -or -not $msg.PSObject.Properties['type']) { return (New-Result '' '' '' $null 'no-type') }
        $type = [string]$msg.type
        if (@('hello', 'refresh', 'switch', 'add', 'remove', 'rename', 'depleted', 'cancel-add') -notcontains $type) {
            return (New-Result $type '' '' $null 'unknown-type')
        }
        $target = ''
        if ($type -in @('switch', 'remove', 'rename', 'depleted')) {
            if (-not $msg.PSObject.Properties['profile']) { return (New-Result $type '' '' $null 'no-profile') }
            $target = [string]$msg.profile
            if ($target -notmatch '^[a-z0-9][a-z0-9\-]{0,63}$') { return (New-Result $type '' '' $null 'bad-profile') }
            if ($KnownProfiles -notcontains $target) { return (New-Result $type $target '' $null 'unknown-profile') }
        }
        $name = ''
        if ($type -in @('add', 'rename')) {
            $raw = ''
            if ($msg.PSObject.Properties['name']) { $raw = [string]$msg.name }
            if ($raw.Length -gt 64) { return (New-Result $type $target '' $null 'bad-name') }
            try { $name = ConvertTo-AccountKey -Name $raw } catch { return (New-Result $type $target '' $null 'bad-name') }
            if ($KnownProfiles -contains $name -and $name -ne $target) { return (New-Result $type $target $name $null 'exists') }
        }
        $value = $null
        if ($type -eq 'depleted') {
            $value = $true
            if ($msg.PSObject.Properties['value'] -and $msg.value -is [bool]) { $value = [bool]$msg.value }
        }
        if ($type -eq 'switch') {
            # Page says the normal signed-in UI is up, so a fast switch (same window) can be tried.
            $value = [bool]($msg.PSObject.Properties['fast'] -and $msg.fast -is [bool] -and $msg.fast)
        }
        return (New-Result $type $target $name $value '')
    }
    
    Export-ModuleMember -Function *
    
  • scripts/CodexAccountsWatcher.cs3.9 KB0039fb451840upstream ↗
    // Codex Multi-Profile watcher: tiny background program started at sign-in (HKCU Run).
    // Whenever the Microsoft Store Codex is running without the account-menu helper (opened from the taskbar,
    // the Start menu, after the helper exited, ...), it starts Start-CodexAccounts.ps1, which reopens Codex
    // with the menu if needed and serves it. No window, a few MB, one process list every 1.5 s.
    // Built by Install-CodexMultiProfile.ps1 with the C# compiler that ships with .NET Framework.
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.IO;
    using System.Threading;
    
    static class CodexAccountsWatcher
    {
        const string HostMutex = @"Local\CodexMultiProfileHost";
        const string SelfMutex = @"Local\CodexMultiProfileWatcher";
        static readonly Dictionary<int, bool> isCodex = new Dictionary<int, bool>();
    
        static bool StoreCodexRunning()
        {
            var alive = new HashSet<int>();
            bool found = false;
            foreach (var p in Process.GetProcessesByName("ChatGPT"))
            {
                using (p)
                {
                    alive.Add(p.Id);
                    bool codex;
                    if (!isCodex.TryGetValue(p.Id, out codex))
                    {
                        codex = false;
                        try { codex = p.MainModule.FileName.IndexOf(@"\WindowsApps\OpenAI.Codex_", StringComparison.OrdinalIgnoreCase) >= 0; }
                        catch { }
                        isCodex[p.Id] = codex;
                    }
                    if (codex) { found = true; }
                }
            }
            foreach (var id in new List<int>(isCodex.Keys)) { if (!alive.Contains(id)) { isCodex.Remove(id); } }
            return found;
        }
    
        static bool HostRunning()
        {
            Mutex m;
            if (!Mutex.TryOpenExisting(HostMutex, out m)) { return false; }
            m.Dispose();
            return true;
        }
    
        static void StartHost(string hostScript)
        {
            var psi = new ProcessStartInfo("powershell.exe",
                "-NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File \"" + hostScript + "\"");
            psi.UseShellExecute = false;
            psi.CreateNoWindow = true;
            psi.WorkingDirectory = Path.GetDirectoryName(hostScript);
            using (Process.Start(psi)) { }
        }
    
        static void Main()
        {
            bool first;
            using (var self = new Mutex(true, SelfMutex, out first))
            {
                if (!first) { return; }
                string root = AppDomain.CurrentDomain.BaseDirectory;
                string hostScript = Path.Combine(root, "Start-CodexAccounts.ps1");
                DateTime lastStart = DateTime.MinValue, hostSeen = DateTime.MinValue;
                int quickExits = 0;
                bool judged = true;
                while (File.Exists(hostScript))
                {
                    try
                    {
                        DateTime now = DateTime.UtcNow;
                        if (HostRunning())
                        {
                            hostSeen = now;
                            if ((now - lastStart).TotalMinutes > 2) { quickExits = 0; }
                        }
                        else if (StoreCodexRunning())
                        {
                            // A helper that ended within a minute of its start did not manage (port taken, ...):
                            // wait longer each time, up to 10 minutes, instead of retrying every 20 s forever.
                            if (!judged && (hostSeen - lastStart).TotalSeconds < 60) { quickExits++; }
                            judged = true;
                            double wait = Math.Min(600, 20 * Math.Pow(2, Math.Min(quickExits, 5)));
                            if ((now - lastStart).TotalSeconds > wait)
                            {
                                lastStart = now;
                                hostSeen = now;
                                judged = false;
                                StartHost(hostScript);
                            }
                        }
                    }
                    catch { }
                    Thread.Sleep(1500);
                }
            }
        }
    }
    
  • scripts/Install-CodexMultiProfile.ps18.6 KB1f2fa8da4ebeupstream ↗
    #Requires -Version 5.1
    <#
    .SYNOPSIS
      Install Codex Multi-Profile: the account list inside the Microsoft Store Codex avatar menu.
    
    .DESCRIPTION
      Copies the scripts to %LOCALAPPDATA%\CodexMultiProfile, saves the login Codex is using
      now as the first account, and creates a "Codex" shortcut (Desktop + Start menu) that opens
      Codex with the account menu. Pin that shortcut instead of the original Codex icon.
    
      -RemoveLegacy also imports the logins saved by the old clone-based versions (0.1-0.3,
      %LOCALAPPDATA%\CodexParallelDesktop) and then deletes that folder, its cloned ChatGPT.exe
      copies and the old Codex1 / Codex Main / Codex Accounts / Codex Profiles shortcuts.
    
    .EXAMPLE
      powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\Install-CodexMultiProfile.ps1 -RemoveLegacy
    #>
    [CmdletBinding()]
    param(
        [switch]$RemoveLegacy,
        [switch]$SkipShortcuts,
        [switch]$NoAutoStart,
        [string]$Root = (Join-Path $env:LOCALAPPDATA 'CodexMultiProfile'),
        [string]$CodexHome = $(if ($env:CODEX_HOME) { $env:CODEX_HOME } else { Join-Path $env:USERPROFILE '.codex' })
    )
    
    $ErrorActionPreference = 'Stop'
    $RepoRoot = Split-Path -Parent $PSScriptRoot
    Import-Module (Join-Path $PSScriptRoot 'CodexAccounts.psm1') -Force
    
    $files = @('CodexAccounts.psm1', 'Start-CodexAccounts.ps1', 'switcher-inject.js', 'CodexAccounts.ps1', 'Uninstall-CodexMultiProfile.ps1')
    $legacyRoot = Join-Path $env:LOCALAPPDATA 'CodexParallelDesktop'
    $desktop = [Environment]::GetFolderPath('Desktop')
    $startMenu = Join-Path ([Environment]::GetFolderPath('Programs')) 'Codex (accounts).lnk'
    
    function Import-LegacyLogins {
        # Old versions kept a login per profile, plus the main login in auth.json.__main__ during a swap.
        $candidates = @()
        $mainBak = Join-Path $CodexHome 'auth.json.__main__'
        if (Test-Path -LiteralPath $mainBak) { $candidates += [pscustomobject]@{ Name = 'main'; Path = $mainBak } }
        $profilesDir = Join-Path $legacyRoot 'profiles'
        if (Test-Path -LiteralPath $profilesDir) {
            foreach ($d in (Get-ChildItem -LiteralPath $profilesDir -Directory)) {
                foreach ($rel in @('auth.json', 'auth.json.secondary.bak', '.codex\auth.json')) {
                    $p = Join-Path $d.FullName $rel
                    if (Get-AuthIdentity -Path $p) { $candidates += [pscustomobject]@{ Name = $d.Name; Path = $p }; break }
                }
            }
        }
        foreach ($c in $candidates) {
            $id = Get-AuthIdentity -Path $c.Path
            if (-not $id) { continue }
            $existing = Find-CodexAccountByIdentity -Identity $id -Root $Root
            if ($existing) { Write-Output ("Old login {0} ({1}) is already saved as {2}." -f $c.Name, (Hide-AuthEmail -Email $id.Email), $existing.Name); continue }
            $key = ConvertTo-AccountKey -Name $c.Name
            if (Test-Path -LiteralPath (Join-Path $Root "accounts\$key")) { $key = Get-CodexNextAccountName -Root $Root }
            Copy-FileAtomic -Source $c.Path -Destination (Join-Path $Root "accounts\$key\auth.json")
            Set-CodexAccountMeta -Name $key -Root $Root
            Write-Output ("Imported old login {0} as {1} ({2})." -f $c.Name, $key, (Hide-AuthEmail -Email $id.Email))
        }
        if (Test-Path -LiteralPath $mainBak) {
            # A swap was left half done: ~/.codex/auth.json may hold the secondary login. Both are saved now.
            Remove-Item -LiteralPath $mainBak -Force
        }
    }
    
    function New-Shortcut([string]$Path, [string]$Icon) {
        $launch = Get-CodexLauncherCommand -Root $Root
        # Start from an empty file: CreateShortcut() on an existing .lnk keeps its old extra data blocks.
        Remove-Item -LiteralPath $Path -Force -ErrorAction SilentlyContinue
        $shell = New-Object -ComObject WScript.Shell
        $lnk = $shell.CreateShortcut($Path)
        $lnk.TargetPath = $launch.FilePath
        $lnk.Arguments = $launch.Arguments
        $lnk.WindowStyle = 7
        $lnk.WorkingDirectory = $Root
        $lnk.Description = 'Codex with the account list in the avatar menu'
        if ($Icon -and (Test-Path -LiteralPath $Icon)) { $lnk.IconLocation = $Icon }
        $lnk.Save()
    }
    
    $pkg = Get-CodexStorePackage
    New-Item -ItemType Directory -Force -Path $Root | Out-Null
    foreach ($name in $files) {
        Copy-Item -LiteralPath (Join-Path $PSScriptRoot $name) -Destination (Join-Path $Root $name) -Force
        Unblock-File -LiteralPath (Join-Path $Root $name) -ErrorAction SilentlyContinue
    }
    Copy-Item -LiteralPath (Join-Path $RepoRoot 'VERSION') -Destination (Join-Path $Root 'VERSION') -Force
    
    # Accounts: the login in use first, then anything the old versions saved.
    $live = Get-AuthIdentity -Path (Join-Path $CodexHome 'auth.json')
    if ($live -and -not (Find-CodexAccountByIdentity -Identity $live -Root $Root)) {
        $saved = Save-CodexAccount -Root $Root -CodexHome $CodexHome
        Write-Output ("Saved the current Codex login as {0} ({1})." -f $saved, (Hide-AuthEmail -Email $live.Email))
    }
    if (Test-Path -LiteralPath $legacyRoot) { Import-LegacyLogins }
    
    # Icon copied so the shortcut survives Store updates that move the package folder.
    $icon = Join-Path $Root 'codex.ico'
    try {
        Add-Type -AssemblyName System.Drawing
        $ico = [System.Drawing.Icon]::ExtractAssociatedIcon((Join-Path $pkg.InstallLocation 'app\ChatGPT.exe'))
        $fs = [IO.File]::Create($icon)
        try { $ico.Save($fs) } finally { $fs.Dispose() }
    }
    catch { $icon = $null }
    
    if (-not $SkipShortcuts) {
        New-Shortcut -Path (Join-Path $desktop 'Codex.lnk') -Icon $icon
        New-Shortcut -Path $startMenu -Icon $icon
    }
    
    # Watcher: the menu also shows up when Codex is opened from its own taskbar / Start icon.
    $watcherExe = Join-Path $Root 'CodexAccountsWatcher.exe'
    $runKey = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Run'
    Get-Process -Name 'CodexAccountsWatcher' -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue
    if ($NoAutoStart) {
        Remove-ItemProperty -Path $runKey -Name 'CodexMultiProfile' -ErrorAction SilentlyContinue
    }
    else {
        Start-Sleep -Milliseconds 300
        Add-Type -TypeDefinition (Get-Content -LiteralPath (Join-Path $PSScriptRoot 'CodexAccountsWatcher.cs') -Raw) `
            -OutputAssembly $watcherExe -OutputType WindowsApplication
        Set-ItemProperty -Path $runKey -Name 'CodexMultiProfile' -Value ('"' + $watcherExe + '"')
        Start-Process -FilePath $watcherExe
        Write-Output 'Watcher on: the account menu also appears when Codex is opened from its own icon.'
    }
    
    if ($RemoveLegacy) {
        $legacyRunning = @(Get-CimInstance Win32_Process -Filter "Name='ChatGPT.exe'" -ErrorAction SilentlyContinue | Where-Object { [string]$_.ExecutablePath -like '*CodexParallelDesktop*' })
        if ($legacyRunning.Count) { throw 'A cloned Codex from the old version is running. Close it, then run this again.' }
        Get-CimInstance Win32_Process -Filter "Name='powershell.exe'" -ErrorAction SilentlyContinue |
            Where-Object { [string]$_.CommandLine -match 'CodexParallelDesktop\\(watch-authswap-restore|Start-CodexSwitcherHost|Start-CodexLayer)' } |
            ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }
        if (Test-Path -LiteralPath $legacyRoot) {
            Remove-CodexTreeNoFollow -Path $legacyRoot
            Write-Output "Removed the old clone-based install ($legacyRoot)."
        }
        foreach ($n in @('Codex1.lnk', 'Codex Main.lnk', 'Codex Accounts.lnk', 'Codex Profiles.lnk')) {
            $lnk = Join-Path $desktop $n
            if (Test-Path -LiteralPath $lnk) {
                $target = (New-Object -ComObject WScript.Shell).CreateShortcut($lnk).Arguments
                if ($target -like '*CodexParallelDesktop*') { Remove-Item -LiteralPath $lnk -Force; Write-Output "Removed old shortcut $n." }
            }
        }
        foreach ($dir in @((Join-Path $env:USERPROFILE '.cursor\skills\codex-multi-profile\scripts'), (Join-Path $CodexHome 'skills\codex-multi-profile\scripts'))) {
            if (Test-Path -LiteralPath $dir) { Remove-CodexTreeNoFollow -Path $dir }
        }
    }
    
    # Agent skill: the CLI lives in the install folder, the skill only describes it.
    foreach ($dir in @((Join-Path $CodexHome 'skills\codex-multi-profile'), (Join-Path $env:USERPROFILE '.cursor\skills\codex-multi-profile'))) {
        if (Test-Path -LiteralPath (Split-Path -Parent $dir)) {
            New-Item -ItemType Directory -Force -Path $dir | Out-Null
            Copy-Item -LiteralPath (Join-Path $RepoRoot 'SKILL.md') -Destination (Join-Path $dir 'SKILL.md') -Force
        }
    }
    
    Write-Output ("Installed {0} to {1}" -f (Get-CodexMultiProfileVersion), $Root)
    Write-Output ("Accounts: {0}" -f ((@(Get-CodexAccounts -Root $Root) | ForEach-Object { $_.Name }) -join ', '))
    Write-Output 'Open Codex from the new "Codex" shortcut (pin it to the taskbar instead of the original icon),'
    Write-Output 'then click your avatar at the bottom-left: your accounts are listed under your name.'
    
  • scripts/Start-CodexAccounts.ps128 KB120816a60c3fupstream ↗
    #Requires -Version 5.1
    <#
    .SYNOPSIS
      Open the Microsoft Store Codex with the account list in its avatar menu.
    
    .DESCRIPTION
      What the "Codex" shortcut runs (hidden). It starts the Store Codex inside its package
      with the DevTools protocol on 127.0.0.1, injects switcher-inject.js into the main
      window and stays in the background as the bridge for that menu:
    
        switch  -> close Codex, sync the outgoing login, put the chosen auth.json in place, reopen
        add     -> close Codex, reopen on the sign-in screen, save the new login under the chosen name
        remove / rename / out-of-quota flag
    
      While Codex runs it keeps each saved account in sync with the live ~/.codex/auth.json
      (Codex rotates refresh tokens). It exits when Codex is closed.
    
      No HTTP listener, no token sent to the page (masked emails only), Codex files are not patched.
    #>
    [CmdletBinding()]
    param(
        [int]$Port = 0,
        [string]$Root = (Join-Path $env:LOCALAPPDATA 'CodexMultiProfile'),
        [string]$CodexHome = $(if ($env:CODEX_HOME) { $env:CODEX_HOME } else { Join-Path $env:USERPROFILE '.codex' })
    )
    
    $ErrorActionPreference = 'Stop'
    Import-Module (Join-Path $PSScriptRoot 'CodexAccounts.psm1') -Force
    
    $script:NextId = 1
    $script:Pending = ''        # name for the account being added (sign-in screen is up)
    $script:PendingReturn = ''  # account to go back to if the add is cancelled
    $script:QueuedToast = $null # toast to show once the reopened window says hello
    $script:LastAction = [datetime]::MinValue
    
    # Usage bars in the menu: /wham/usage per saved account, fetched without blocking the loop.
    Add-Type -AssemblyName System.Net.Http
    [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
    $script:Http = New-Object System.Net.Http.HttpClient
    $script:Http.Timeout = [TimeSpan]::FromSeconds(15)
    $script:Usage = @{}       # name -> ConvertFrom-CodexUsageJson result
    $script:UsageAt = @{}     # name -> last fetch start
    $script:UsageTasks = @{}  # name -> pending Task<HttpResponseMessage>
    
    function Write-HostLog([string]$Message) { Write-CodexLog -Message "[host] $Message" -Root $Root }
    
    # ---------------------------------------------------------------- CDP plumbing
    
    function Test-CdpOwnerIsStoreCodex {
        # Only attach when the port belongs to the Store Codex, never a browser or anything else.
        $owners = @(Get-NetTCPConnection -LocalPort $Port -State Listen -ErrorAction SilentlyContinue | ForEach-Object { $_.OwningProcess } | Select-Object -Unique)
        if ($owners.Count -eq 0) { return $false }
        foreach ($ownerPid in $owners) {
            $p = Get-CimInstance Win32_Process -Filter ("ProcessId={0}" -f [int]$ownerPid) -ErrorAction SilentlyContinue
            if (-not $p -or $p.Name -ne 'ChatGPT.exe' -or [string]$p.ExecutablePath -notlike '*\WindowsApps\OpenAI.Codex_*') { return $false }
        }
        return $true
    }
    
    function Get-CdpTargets {
        $client = New-Object System.Net.WebClient
        $client.Proxy = $null
        $client.Encoding = [Text.Encoding]::UTF8
        try { $json = $client.DownloadString("http://127.0.0.1:$Port/json/list") } finally { $client.Dispose() }
        return (Select-CdpMainPages -Json $json -CdpPort $Port)
    }
    
    function Select-CdpMainPages {
        # Codex main window only (not the Mini, detached or avatar-overlay windows), loopback websocket only.
        param([Parameter(Mandatory)] [string]$Json, [Parameter(Mandatory)] [int]$CdpPort)
        # Assign first: Windows PowerShell 5.1 emits a JSON array as ONE object in a pipeline.
        $items = ConvertFrom-Json -InputObject $Json
        return @($items | Where-Object {
                [string]$_.type -eq 'page' -and ([string]$_.url).StartsWith('app://-/index.html') -and
                ([string]$_.url) -notmatch 'initialRoute=' -and
                ([string]$_.webSocketDebuggerUrl).StartsWith("ws://127.0.0.1:$CdpPort/")
            })
    }
    
    function Send-CdpMessage {
        param([Parameter(Mandatory)] $Conn, [Parameter(Mandatory)] [string]$Method, [hashtable]$Params = @{})
        $id = $script:NextId
        $script:NextId++
        if ($Params.ContainsKey('expression')) { $Params['expression'] = [string]$Params['expression'] }  # plain string, see Invoke-AccountsHost
        $bytes = [Text.Encoding]::UTF8.GetBytes((@{ id = $id; method = $Method; params = $Params } | ConvertTo-Json -Depth 8 -Compress))
        $seg = New-Object System.ArraySegment[byte] -ArgumentList @(, $bytes)
        $cts = New-Object System.Threading.CancellationTokenSource
        $cts.CancelAfter(10000)
        try { $Conn.Ws.SendAsync($seg, [System.Net.WebSockets.WebSocketMessageType]::Text, $true, $cts.Token).Wait() }
        finally { $cts.Dispose() }
    }
    
    function Start-CdpReceive($Conn) {
        $Conn.Task = $Conn.Ws.ReceiveAsync($Conn.Segment, [System.Threading.CancellationToken]::None)
    }
    
    function Connect-CdpTarget {
        param([Parameter(Mandatory)] $Target, [Parameter(Mandatory)] [string]$Source)
        $ws = New-Object System.Net.WebSockets.ClientWebSocket
        try { $ws.Options.Proxy = $null } catch { }
        $cts = New-Object System.Threading.CancellationTokenSource
        $cts.CancelAfter(10000)
        try { $ws.ConnectAsync([Uri][string]$Target.webSocketDebuggerUrl, $cts.Token).Wait() }
        finally { $cts.Dispose() }
        $buffer = New-Object byte[] 65536
        $conn = [pscustomobject]@{
            TargetId = [string]$Target.id
            Ws       = $ws
            Buffer   = $buffer
            Segment  = (New-Object System.ArraySegment[byte] -ArgumentList @(, $buffer))
            Stream   = (New-Object System.IO.MemoryStream)
            Task     = $null
        }
        # No Runtime.enable: bindingCalled arrives without it, and it would stream every Codex console
        # message through this PowerShell process. Page.enable is needed (and cheap: a few events per
        # navigation) for the new-document script to run again when Codex reloads its window.
        Send-CdpMessage -Conn $conn -Method 'Runtime.addBinding' -Params @{ name = (Get-CodexSwitcherBindingName) }
        Send-CdpMessage -Conn $conn -Method 'Page.enable'
        Send-CdpMessage -Conn $conn -Method 'Page.addScriptToEvaluateOnNewDocument' -Params @{ source = $Source }
        Send-CdpMessage -Conn $conn -Method 'Runtime.evaluate' -Params @{ expression = $Source; returnByValue = $true }
        Start-CdpReceive $conn
        return $conn
    }
    
    function Close-CdpConn($Conn) {
        try {
            if ($Conn.Ws.State -eq [System.Net.WebSockets.WebSocketState]::Open) {
                $cts = New-Object System.Threading.CancellationTokenSource
                $cts.CancelAfter(2000)
                $Conn.Ws.CloseAsync([System.Net.WebSockets.WebSocketCloseStatus]::NormalClosure, 'bye', $cts.Token).Wait()
            }
        }
        catch { }
        try { $Conn.Ws.Dispose() } catch { }
        try { $Conn.Stream.Dispose() } catch { }
    }
    
    function Receive-CdpMessage($Conn) {
        # Whole message text, '' while more frames are due, $null when the socket closed.
        $result = $Conn.Task.Result
        if ($result.MessageType -eq [System.Net.WebSockets.WebSocketMessageType]::Close) { return $null }
        $Conn.Stream.Write($Conn.Buffer, 0, $result.Count)
        if (-not $result.EndOfMessage) { Start-CdpReceive $Conn; return '' }
        $text = [Text.Encoding]::UTF8.GetString($Conn.Stream.ToArray())
        $Conn.Stream.SetLength(0)
        Start-CdpReceive $Conn
        return $text
    }
    
    # ---------------------------------------------------------------- page events
    
    function Send-PageEvent([object[]]$Conns, [hashtable]$Event) {
        $json = $Event | ConvertTo-Json -Depth 8 -Compress
        if (Test-CodexTextHasFullEmail -Text $json) { Write-HostLog 'BLOCKED an event with an unmasked email'; return }
        $expr = "if (window.__cmpSwitcher) { window.__cmpSwitcher.receive($json); }"
        foreach ($c in $Conns) {
            try { Send-CdpMessage -Conn $c -Method 'Runtime.evaluate' -Params @{ expression = $expr; returnByValue = $true } } catch { }
        }
    }
    
    function Test-CodexStoreRunning {
        # Cheap check (no WMI): any Store Codex process left.
        return [bool](Get-Process -Name 'ChatGPT' -ErrorAction SilentlyContinue | Where-Object { [string]$_.Path -like '*\WindowsApps\OpenAI.Codex_*' } | Select-Object -First 1)
    }
    
    function Get-StoreFingerprint {
        $parts = foreach ($p in @((Join-Path $CodexHome 'auth.json'), (Join-Path $Root 'accounts'), (Join-Path $Root 'accounts.json'))) {
            $i = Get-Item -LiteralPath $p -ErrorAction SilentlyContinue
            if ($i) { $i.LastWriteTimeUtc.Ticks } else { 0 }
        }
        return (($parts -join '|') + '|' + $script:Pending)
    }
    
    function Start-UsageFetch([int]$MaxAgeSec = 60) {
        foreach ($a in @(Get-CodexAccounts -Root $Root)) {
            if ($script:UsageTasks.ContainsKey($a.Name)) { continue }
            $at = $script:UsageAt[$a.Name]
            if ($at -and ((Get-Date) - $at).TotalSeconds -lt $MaxAgeSec) { continue }
            $script:UsageAt[$a.Name] = Get-Date
            try {
                $req = New-CodexUsageRequest -AuthPath $a.AuthPath
                if ($req) { $script:UsageTasks[$a.Name] = $script:Http.SendAsync($req) }
            }
            catch { }
        }
    }
    
    function Complete-UsageFetches {
        # Collect finished requests; $true when a bar changed. A login the server rejects shows no bar.
        $changed = $false
        foreach ($name in @($script:UsageTasks.Keys)) {
            $task = $script:UsageTasks[$name]
            if (-not $task.IsCompleted) { continue }
            $script:UsageTasks.Remove($name)
            if ($task.IsFaulted -or $task.IsCanceled) { continue }
            $resp = $task.Result
            try {
                if ($resp.IsSuccessStatusCode) {
                    $script:Usage[$name] = ConvertFrom-CodexUsageJson -Json ($resp.Content.ReadAsStringAsync().Result)
                    $changed = $true
                }
                elseif ([int]$resp.StatusCode -in @(401, 403) -and $script:Usage.ContainsKey($name)) {
                    $script:Usage.Remove($name)
                    $changed = $true
                }
            }
            catch { }
            finally { $resp.Dispose() }
        }
        return $changed
    }
    
    function Move-UsageEntry([string]$From, [string]$To) {
        foreach ($map in @($script:Usage, $script:UsageAt)) {
            if ($map.ContainsKey($From)) {
                if ($To) { $map[$To] = $map[$From] }
                $map.Remove($From)
            }
        }
    }
    
    function Send-PageState([object[]]$Conns) {
        $snap = Get-CodexSwitcherSnapshot -Root $Root -CodexHome $CodexHome -Pending $script:Pending -Usage $script:Usage
        Send-PageEvent $Conns @{ kind = 'state'; state = $snap }
    }
    
    function Send-PageToast([object[]]$Conns, [string]$Level, [string]$Code, [string]$Detail = '') {
        Send-PageEvent $Conns @{ kind = 'toast'; level = $Level; code = $Code; detail = $Detail }
    }
    
    # ---------------------------------------------------------------- actions
    
    function Restart-Codex {
        <#
        .SYNOPSIS
          Close Codex, run $Swap (auth.json changes happen while Codex is closed), reopen with CDP.
          Codex is always reopened, whatever failed, on whatever login is in place.
        #>
        param([Parameter(Mandatory)] [scriptblock]$Swap)
        $t0 = Get-Date
        $closed = 0
        try {
            Stop-CodexStore
            $closed = ((Get-Date) - $t0).TotalSeconds
            if (Test-CodexStoreRunning) { throw 'Codex did not close; the login was left as it was.' }
            & $Swap
        }
        finally {
            $codexPid = Start-CodexStore -Port $Port
            Write-HostLog ("restart: closed in {0:n1}s, reopened pid={1} after {2:n1}s" -f $closed, $codexPid, ((Get-Date) - $t0).TotalSeconds)
        }
    }
    
    function Invoke-LoginChange {
        <#
        .SYNOPSIS
          Change the login Codex uses. Fast path: restart only the app-server, the window stays (2-3 s).
          Fallback: restart Codex. $Swap must be safe to run twice. Returns $true when Codex was restarted
          (the page is gone and must be attached again).
        #>
        param([Parameter(Mandatory)] [scriptblock]$Swap, [switch]$Full)
        $t0 = Get-Date
        if (-not $Full -and (Restart-CodexAppServer -Swap $Swap)) {
            Write-HostLog ("fast switch: new app-server after {0:n1}s" -f ((Get-Date) - $t0).TotalSeconds)
            return $false
        }
        if (-not $Full) { Write-HostLog 'fast switch unavailable; restarting Codex' }
        Restart-Codex -Swap $Swap
        return $true
    }
    
    function Complete-LoginChange {
        <#
        .SYNOPSIS
          Run a login change for the page and report the outcome to it. Returns $true when Codex was
          restarted (attach again).
        #>
        param([object[]]$Conns, [string]$Profile, [scriptblock]$Swap, [switch]$Add, [switch]$Full)
        try { $restarted = Invoke-LoginChange -Swap $Swap -Full:$Full }
        catch {
            $script:LastAction = Get-Date
            $what = $(if ($Add) { 'add' } else { 'switch' })
            Write-HostLog ("{0} {1} failed: {2}" -f $what, $Profile, $_.Exception.Message)
            if ($Add) { $script:Pending = ''; $script:PendingReturn = '' }
            # The page may still be there (fast path) or come back after a restart: tell it both ways.
            Send-PageToast $Conns 'error' "$what-failed" $Profile
            $script:QueuedToast = @{ Level = 'error'; Code = "$what-failed"; Detail = $Profile }
            return $false
        }
        # The double-click guard counts from the end of a change: a click queued while it ran is not a new request.
        $script:LastAction = Get-Date
        if (-not $restarted) {
            Send-PageState $Conns
            Send-PageEvent $Conns @{ kind = 'switched'; profile = $Profile; add = [bool]$Add }
        }
        return $restarted
    }
    
    function Invoke-PageRequest {
        param([Parameter(Mandatory)] [string]$Payload, [Parameter(Mandatory)] [AllowEmptyCollection()] [object[]]$Conns)
        $known = @(Get-CodexAccounts -Root $Root | ForEach-Object { $_.Name })
        $req = ConvertFrom-CodexSwitcherMessage -Payload $Payload -KnownProfiles $known
        if ($req.Error) {
            Write-HostLog ("rejected {0}: {1}" -f $req.Type, $req.Error)
            Send-PageToast $Conns 'error' $req.Error $req.Name
            return $false
        }
        # Double-click guard. The page shows a waiting card, so always answer instead of ignoring.
        $busy = ((Get-Date) - $script:LastAction).TotalSeconds -lt 1.5
        switch ($req.Type) {
            { $_ -in @('hello', 'refresh') } {
                # The menu was opened: refresh usage bars older than a minute (they arrive a moment later).
                Start-UsageFetch -MaxAgeSec 60
                Send-PageState $Conns
                if ($_ -eq 'hello' -and $script:QueuedToast) {
                    $q = $script:QueuedToast
                    $script:QueuedToast = $null
                    Send-PageToast $Conns $q.Level $q.Code $q.Detail
                }
            }
            'switch' {
                $active = Get-CodexActiveAccount -Root $Root -CodexHome $CodexHome
                if ($active -and $active.Name -eq $req.Profile) { Send-PageToast $Conns 'info' 'already-active' $req.Profile; return $false }
                if ($busy) { Send-PageToast $Conns 'info' 'busy'; return $false }
                $script:LastAction = Get-Date
                Write-HostLog ("switch {0} -> {1}" -f $(if ($active) { $active.Name } else { '(none)' }), $req.Profile)
                Send-PageEvent $Conns @{ kind = 'switching'; profile = $req.Profile }
                $target = $req.Profile
                $script:Pending = ''
                $script:PendingReturn = ''
                return (Complete-LoginChange -Conns $Conns -Profile $target -Full:(-not $req.Value) -Swap { Set-CodexLiveAuth -Name $target -Root $Root -CodexHome $CodexHome })
            }
            'add' {
                if ($busy) { Send-PageToast $Conns 'info' 'busy'; return $false }
                $script:LastAction = Get-Date
                $active = Get-CodexActiveAccount -Root $Root -CodexHome $CodexHome
                Write-HostLog ("add {0}: opening the sign-in screen" -f $req.Name)
                Send-PageEvent $Conns @{ kind = 'switching'; profile = $req.Name; add = $true }
                $script:Pending = $req.Name
                $script:PendingReturn = $(if ($active) { $active.Name } else { '' })
                # The sign-in screen only appears when Codex starts without a login: full restart.
                return (Complete-LoginChange -Conns $Conns -Profile $req.Name -Add -Full -Swap { Clear-CodexLiveAuth -Root $Root -CodexHome $CodexHome })
            }
            'cancel-add' {
                if (-not $script:Pending) { return $false }
                $back = $script:PendingReturn
                Write-HostLog ("add {0} cancelled, back to {1}" -f $script:Pending, $back)
                $script:Pending = ''
                $script:PendingReturn = ''
                if (-not $back -or (Get-AuthIdentity -Path (Join-Path $CodexHome 'auth.json'))) { Send-PageState $Conns; return $false }
                $script:LastAction = Get-Date
                Send-PageEvent $Conns @{ kind = 'switching'; profile = $back }
                # Leaving the sign-in screen needs a restart as well.
                return (Complete-LoginChange -Conns $Conns -Profile $back -Full -Swap { Set-CodexLiveAuth -Name $back -Root $Root -CodexHome $CodexHome })
            }
            'remove' {
                try { Remove-CodexAccount -Name $req.Profile -Root $Root -CodexHome $CodexHome }
                catch {
                    Write-HostLog ("remove {0} failed: {1}" -f $req.Profile, $_.Exception.Message)
                    Send-PageState $Conns
                    Send-PageToast $Conns 'error' 'remove-failed' $req.Profile
                    return $false
                }
                Write-HostLog ("removed {0}" -f $req.Profile)
                Move-UsageEntry -From $req.Profile -To ''
                Send-PageState $Conns
                Send-PageToast $Conns 'success' 'removed' $req.Profile
            }
            'rename' {
                try { $new = Rename-CodexAccount -Name $req.Profile -NewName $req.Name -Root $Root }
                catch {
                    Write-HostLog ("rename {0} failed: {1}" -f $req.Profile, $_.Exception.Message)
                    Send-PageToast $Conns 'error' 'rename-failed' $req.Profile
                    return $false
                }
                Write-HostLog ("renamed {0} -> {1}" -f $req.Profile, $new)
                Move-UsageEntry -From $req.Profile -To $new
                Send-PageState $Conns
                Send-PageToast $Conns 'success' 'renamed' $new
            }
            'depleted' {
                Set-CodexAccountMeta -Name $req.Profile -Root $Root -Depleted ([bool]$req.Value)
                Send-PageState $Conns
            }
        }
        return $false
    }
    
    function Update-FromLiveAuth([object[]]$Conns) {
        <#
        .SYNOPSIS
          Keep the account in use in sync; finish a pending add once Codex has signed in.
        #>
        try { $null = Sync-CodexActiveAccount -Root $Root -CodexHome $CodexHome } catch { Write-HostLog ("sync failed: " + $_.Exception.Message) }
        $id = Get-AuthIdentity -Path (Join-Path $CodexHome 'auth.json')
        if (-not $id) { return }
        if (-not $script:Pending) {
            # Signed in to a login that is not saved (e.g. another account on a sign-in screen): keep it.
            if (Find-CodexAccountByIdentity -Identity $id -Root $Root) { return }
            try { $saved = Save-CodexAccount -Root $Root -CodexHome $CodexHome } catch { Write-HostLog ("auto-save failed: " + $_.Exception.Message); return }
            Write-HostLog ("saved a new login as {0} ({1})" -f $saved, (Hide-AuthEmail -Email $id.Email))
            Send-PageState $Conns
            Send-PageToast $Conns 'success' 'added' $saved
            return
        }
        $name = $script:Pending
        $script:Pending = ''
        $script:PendingReturn = ''
        $existing = Find-CodexAccountByIdentity -Identity $id -Root $Root
        if ($existing) {
            Write-HostLog ("add {0}: that login is already saved as {1}" -f $name, $existing.Name)
            Send-PageState $Conns
            Send-PageToast $Conns 'info' 'exists-as' $existing.Name
            return
        }
        try { $saved = Save-CodexAccount -Name $name -Root $Root -CodexHome $CodexHome }
        catch {
            Write-HostLog ("add {0} failed: {1}" -f $name, $_.Exception.Message)
            Send-PageToast $Conns 'error' 'add-failed' $name
            return
        }
        Write-HostLog ("added {0} ({1})" -f $saved, (Hide-AuthEmail -Email $id.Email))
        Send-PageState $Conns
        Send-PageToast $Conns 'success' 'added' $saved
    }
    
    # ---------------------------------------------------------------- main loop
    
    function Invoke-AccountsHost {
        # ReadAllText, not Get-Content: on Windows PowerShell 5.1 a Get-Content string carries PSPath / PSProvider /
        # PSDrive note properties, and ConvertTo-Json then serializes those object graphs (GBs, minutes of CPU).
        $source = [System.IO.File]::ReadAllText((Join-Path $PSScriptRoot 'switcher-inject.js'), [System.Text.Encoding]::UTF8)
        $binding = Get-CodexSwitcherBindingName
        $conns = New-Object System.Collections.ArrayList
        $lastDiscover = [datetime]::MinValue
        $lastSync = [datetime]::MinValue
        $lastFingerprint = ''
        $goneSince = $null
        Write-HostLog ("host start port={0}" -f $Port)
    
        while ($true) {
          try {
            $now = Get-Date
            # Attached: the socket closing tells us when the window goes, so look around rarely.
            if (($now - $lastDiscover).TotalSeconds -ge $(if ($conns.Count) { 15 } else { 1 })) {
                $lastDiscover = $now
                if (-not (Test-CodexStoreRunning)) {
                    if (-not $goneSince) { $goneSince = $now }
                    if (($now - $goneSince).TotalSeconds -ge 8) { break }
                }
                else { $goneSince = $null }
                $targets = @()
                try { $targets = @(Get-CdpTargets) } catch { $targets = @() }
                $fresh = @($targets | Where-Object { $id = [string]$_.id; -not @($conns | Where-Object { $_.TargetId -eq $id }).Count })
                if ($fresh.Count -gt 0) {
                    if (-not (Test-CdpOwnerIsStoreCodex)) { Write-HostLog 'REFUSED: the CDP port is not owned by the Store Codex'; break }
                    foreach ($t in $fresh) {
                        try {
                            $c = Connect-CdpTarget -Target $t -Source $source
                            [void]$conns.Add($c)
                            Write-HostLog ("attached {0}" -f $t.id)
                            # A reopen that gave Codex its menu port worked: clear the no-loop mark.
                            Remove-Item -LiteralPath (Join-Path $Root 'last-reopen.txt') -ErrorAction SilentlyContinue
                            Send-PageState @($c)
                        }
                        catch { Write-HostLog ("attach failed: " + $_.Exception.Message) }
                    }
                }
            }
    
            # Only when auth.json or the account store changed (token refresh, sign-in, CLI edits).
            if (($now - $lastSync).TotalSeconds -ge 3) {
                $lastSync = $now
                # Safety net: normal use stays around 150 MB. Whatever went wrong, never weigh on the PC.
                $mem = [System.Diagnostics.Process]::GetCurrentProcess().WorkingSet64
                if ($mem -gt 500MB) { Write-HostLog ("helper memory {0} MB, exiting to stay light" -f [int]($mem / 1MB)); break }
                $fingerprint = Get-StoreFingerprint
                $push = $false
                if ($fingerprint -ne $lastFingerprint) {
                    $lastFingerprint = $fingerprint
                    Update-FromLiveAuth @($conns)
                    $push = $true
                }
                # Usage bars: keep them at most 10 minutes old, and show new numbers as soon as they arrive.
                if ($conns.Count) { Start-UsageFetch -MaxAgeSec 600 }
                if (Complete-UsageFetches) { $push = $true }
                if ($push) { try { Send-PageState @($conns) } catch { } }
            }
    
            if ($conns.Count -eq 0) { Start-Sleep -Milliseconds 500; continue }
    
            $idx = [System.Threading.Tasks.Task]::WaitAny([System.Threading.Tasks.Task[]]@($conns | ForEach-Object { $_.Task }), 1000)
            if ($idx -lt 0) { continue }
            $conn = $conns[$idx]
            $text = $null
            try { if (-not ($conn.Task.IsFaulted -or $conn.Task.IsCanceled)) { $text = Receive-CdpMessage $conn } } catch { $text = $null }
            if ($null -eq $text) {
                Write-HostLog ("detached {0}" -f $conn.TargetId)
                Close-CdpConn $conn
                $conns.RemoveAt($idx)
                continue
            }
            if (-not $text) { continue }
            if ($text.Contains('"Page.domContentEventFired"')) {
                # Codex reloaded its window. Without Runtime.enable the binding is not carried into the new
                # page by itself; re-adding it does (the script itself comes back via addScriptToEvaluateOnNewDocument).
                # The new-document script is sometimes missing after the first reload; evaluate it too (it guards
                # against running twice), so the menu is always back.
                try {
                    Send-CdpMessage -Conn $conn -Method 'Runtime.removeBinding' -Params @{ name = $binding }
                    Send-CdpMessage -Conn $conn -Method 'Runtime.addBinding' -Params @{ name = $binding }
                    Send-CdpMessage -Conn $conn -Method 'Runtime.evaluate' -Params @{ expression = $source; returnByValue = $true }
                }
                catch { }
                # Do not wait for the page's hello: a hidden window runs its timers very late.
                try { Send-PageState @($conn) } catch { }
                continue
            }
            # Replies to our own commands are skipped without parsing; only the page's requests matter.
            if (-not $text.Contains('"Runtime.bindingCalled"')) { continue }
            $msg = $null
            try { $msg = ConvertFrom-Json -InputObject $text } catch { continue }
            if ([string]$msg.params.name -eq $binding) {
                $restarted = $false
                try { $restarted = Invoke-PageRequest -Payload ([string]$msg.params.payload) -Conns @($conns) }
                catch {
                    Write-HostLog ("request failed: " + $_.Exception.Message)
                    Send-PageToast @($conns) 'error' 'host-error'
                }
                if ($restarted) {
                    # Codex was closed and reopened: drop the dead sockets, attach to the new window.
                    foreach ($c in @($conns)) { Close-CdpConn $c }
                    $conns.Clear()
                    $lastFingerprint = ''
                    $goneSince = $null
                }
            }
          }
          catch {
            # Keep serving: one unexpected error must not leave the menu without its helper.
            Write-HostLog ("loop error: " + $_.Exception.Message)
            Start-Sleep -Milliseconds 500
          }
        }
    
        foreach ($c in @($conns)) { Close-CdpConn $c }
        try { $null = Sync-CodexActiveAccount -Root $Root -CodexHome $CodexHome } catch { }
        Write-HostLog 'host exit (Codex closed)'
    }
    
    function Start-CodexWithAccounts {
        New-Item -ItemType Directory -Force -Path $Root | Out-Null
        if ($Port -le 0) { $script:Port = (Get-CodexAccountsSettings -Root $Root).CdpPort }
    
        $mutex = New-Object System.Threading.Mutex($false, 'Local\CodexMultiProfileHost')
        $owned = $false
        try { $owned = $mutex.WaitOne(0) }
        catch {
            # A killed host leaves the mutex abandoned; WaitOne still hands it over.
            $ex = $_.Exception
            if ($ex -is [System.Threading.AbandonedMutexException] -or $ex.InnerException -is [System.Threading.AbandonedMutexException]) { $owned = $true }
            else { throw }
        }
        if (-not $owned) {
            # A host is already serving Codex: just bring Codex up / to the front.
            $null = Start-CodexStore -Port $Port
            return
        }
        try {
            # The login in use is always saved, so switching away can never lose it.
            $live = Get-AuthIdentity -Path (Join-Path $CodexHome 'auth.json')
            if ($live -and -not (Find-CodexAccountByIdentity -Identity $live -Root $Root)) {
                $name = Save-CodexAccount -Root $Root -CodexHome $CodexHome
                Write-HostLog ("saved the current login as {0} ({1})" -f $name, (Hide-AuthEmail -Email $live.Email))
            }
            if (-not (Test-CodexStoreHasCdp -Port $Port)) {
                if (@(Get-CodexStoreProcesses).Count -gt 0) {
                    # Never a restart loop: if the last reopen did not give Codex its menu port, leave Codex alone
                    # for a while (port taken by another program, a Codex build that ignores the argument, ...).
                    $mark = Join-Path $Root 'last-reopen.txt'
                    $last = Get-Item -LiteralPath $mark -ErrorAction SilentlyContinue
                    if ($last -and ((Get-Date) - $last.LastWriteTime).TotalMinutes -lt 10) {
                        Write-HostLog 'Codex is still without the account menu after a reopen; not reopening again for 10 minutes'
                        return
                    }
                    Set-Content -LiteralPath $mark -Value (Get-Date -Format o)
                    Write-HostLog 'Codex was opened without the account menu; reopening it'
                    Stop-CodexStore
                }
                $null = Start-CodexStore -Port $Port
            }
            Invoke-AccountsHost
        }
        finally {
            $mutex.ReleaseMutex()
            $mutex.Dispose()
        }
    }
    
    # Dot-sourcing loads the functions only (tests); running the file starts Codex + the host.
    if ($MyInvocation.InvocationName -ne '.') {
        try { Start-CodexWithAccounts }
        catch {
            Write-HostLog ("ERROR: " + $_.Exception.Message)
            exit 1
        }
    }
    
  • scripts/switcher-inject.js61 KB8530ed463ed3upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • scripts/Uninstall-CodexMultiProfile.ps12.0 KB6502e6ddec18upstream ↗
    #Requires -Version 5.1
    <#
    .SYNOPSIS
      Remove the Codex shortcut, the menu helper and the scripts. Saved accounts are kept unless -RemoveAccounts.
      ~/.codex (chats, settings, the login in use) is never touched.
    #>
    [CmdletBinding()]
    param(
        [switch]$RemoveAccounts,
        [string]$Root = (Join-Path $env:LOCALAPPDATA 'CodexMultiProfile')
    )
    
    $ErrorActionPreference = 'Stop'
    Remove-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Run' -Name 'CodexMultiProfile' -ErrorAction SilentlyContinue
    Get-Process -Name 'CodexAccountsWatcher' -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue
    Get-CimInstance Win32_Process -Filter "Name='powershell.exe'" -ErrorAction SilentlyContinue |
        Where-Object { [string]$_.CommandLine -like '*Start-CodexAccounts.ps1*' -and $_.ProcessId -ne $PID } |
        ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }
    
    $hostScript = Join-Path $Root 'Start-CodexAccounts.ps1'
    foreach ($lnk in @((Join-Path ([Environment]::GetFolderPath('Desktop')) 'Codex.lnk'), (Join-Path ([Environment]::GetFolderPath('Programs')) 'Codex (accounts).lnk'))) {
        if ((Test-Path -LiteralPath $lnk) -and (New-Object -ComObject WScript.Shell).CreateShortcut($lnk).Arguments -like "*$hostScript*") {
            Remove-Item -LiteralPath $lnk -Force
        }
    }
    foreach ($name in @('CodexAccounts.psm1', 'Start-CodexAccounts.ps1', 'switcher-inject.js', 'CodexAccounts.ps1', 'CodexAccountsWatcher.exe', 'codex.ico', 'VERSION', 'settings.json')) {
        Remove-Item -LiteralPath (Join-Path $Root $name) -Force -ErrorAction SilentlyContinue
    }
    if ($RemoveAccounts) {
        Remove-Item -LiteralPath (Join-Path $Root 'accounts') -Recurse -Force -ErrorAction SilentlyContinue
        Remove-Item -LiteralPath (Join-Path $Root 'accounts.json') -Force -ErrorAction SilentlyContinue
    }
    Write-Output ("Uninstalled. Saved accounts {0}. Uninstall script left in {1}." -f $(if ($RemoveAccounts) { 'removed' } else { "kept in $Root\accounts" }), $Root)
    
  • .gitattributes97 B4002c75bfca4upstream ↗
    * text=auto
    *.png binary
    *.ps1 text eol=crlf
    *.psm1 text eol=crlf
    *.cmd text eol=crlf
    *.svg text
    
  • .github/CODEOWNERS25 B26a2aea184caupstream ↗
    * @Hung2124 @nicnqaccoin
    
  • .github/dependabot.yml113 B3a626c3a7f27upstream ↗
    version: 2
    updates:
      - package-ecosystem: github-actions
        directory: /
        schedule:
          interval: monthly
    
  • .github/ISSUE_TEMPLATE/bug.yml1.2 KB066e662d16feupstream ↗
    name: Bug report
    description: Something broke while opening Codex or switching accounts
    labels: [bug]
    body:
      - type: textarea
        id: what
        attributes:
          label: What happened
          description: Wrong account on screen, crash, Access Denied, poisoned auth, etc.
        validations:
          required: true
      - type: textarea
        id: expected
        attributes:
          label: Expected
        validations:
          required: true
      - type: input
        id: version
        attributes:
          label: codex-multi-profile version
          description: Output of CodexAccounts.ps1 status (Version line) or the VERSION file
          placeholder: 0.1.2
      - type: input
        id: app
        attributes:
          label: Codex Desktop version
          placeholder: "e.g. 26.924.2738.0 (Codex (Store) line of CodexAccounts.ps1 status)"
      - type: textarea
        id: doctor
        attributes:
          label: doctor output
          description: Run CodexAccounts.ps1 status and paste here (emails are already masked).
          render: text
      - type: textarea
        id: log
        attributes:
          label: Relevant lines of codex-accounts.log
          description: From %LOCALAPPDATA%\CodexMultiProfile\codex-accounts.log (emails are masked). Do not paste auth.json or tokens.
          render: text
    
  • .github/ISSUE_TEMPLATE/config.yml202 B1197bb78831aupstream ↗
    blank_issues_enabled: true
    contact_links:
      - name: OpenAI Codex
        url: https://github.com/openai/codex
        about: Official Codex CLI / app issues (this repo is unofficial Windows multi-profile only)
    
  • .github/ISSUE_TEMPLATE/feature.yml660 B5acd462841d6upstream ↗
    name: Feature request
    description: A verified Windows Codex Desktop behavior this repo should encode
    labels: [enhancement]
    body:
      - type: textarea
        id: problem
        attributes:
          label: What went wrong or is missing
          description: Prefer a launch log excerpt with emails redacted.
        validations:
          required: true
      - type: textarea
        id: expected
        attributes:
          label: Expected behavior
        validations:
          required: true
      - type: checkboxes
        id: verified
        attributes:
          label: Verified on a real machine
          options:
            - label: I reproduced this on Windows Codex Desktop (not only CLI)
              required: true
    
  • .github/workflows/ci.yml578 B03ce783d1dcbupstream ↗
    name: ci
    
    on:
      push:
        branches: [main]
      pull_request:
    
    jobs:
      test:
        runs-on: windows-latest
        steps:
          - uses: actions/checkout@v7
          - name: Show VERSION
            shell: powershell
            run: Get-Content .\VERSION
          - name: Parse and unit tests
            shell: powershell
            run: powershell -NoProfile -ExecutionPolicy Bypass -File .\tests\Run-All.ps1
          - name: Verify npm CLI wrapper and SDK unit tests
            shell: powershell
            run: |
              node .\tests\sdk.test.js
              node .\cli.js --version
              node .\cli.js --help
    
  • .gitignore168 Be2836743f456upstream ↗
    auth.json
    auth.json.*
    *.bak
    .authswap-active
    launch-trace.log
    launch-*-env.cmd
    .env
    .DS_Store
    Thumbs.db
    profiles/
    versions/
    accounts/
    accounts.json
    codex-accounts.log*
    
  • AGENTS.md1.3 KB22f835e2dd91upstream ↗
    # AGENTS.md
    
    Windows-only helper: several ChatGPT logins for the **Microsoft Store Codex**, switched from the Codex avatar menu.
    
    - Read `SKILL.md` and `docs/architecture.md` before changing launch or switch behavior.
    - Start the Store Codex only through `Start-CodexStore` (IApplicationActivationManager). Do not copy / clone
      `ChatGPT.exe` (26.9xx needs package identity), do not use `Invoke-CommandInDesktopPackage` or `shell:AppsFolder`
      (both hang from a normal process), do not patch Codex files.
    - Keep the helper cheap: no `Runtime.enable` (console flood), no JSON parsing of CDP replies, no WMI in the loop.
      `Page.enable` stays: without it the injected script is not re-added after Codex reloads its window.
    - Page input goes through `ConvertFrom-CodexSwitcherMessage`. Only masked emails reach the page. The injected
      script builds DOM with `createElement` only (tests enforce this).
    - Never drop a login that is not saved (`Clear-CodexLiveAuth` refuses). Sync the live `auth.json` into its account
      before replacing it.
    - `.ps1` / `.psm1` files stay ASCII (Windows PowerShell 5.1 reads BOM-less UTF-8 as ANSI). Remember that
      `ConvertFrom-Json` on 5.1 emits a JSON array as one object in a pipeline: assign it first.
    - Never commit `auth.json`, the `accounts` folder or logs. Run `tests/Run-All.ps1` after edits.
    
  • CHANGELOG.md8.8 KBca69e9e447aaupstream ↗
    # Changelog
    
    All notable changes to this project are documented here.
    
    ## 2.0.0 — 2026-10-23
    
    ### Added
    - **Cross-Platform Claude Code & Codex Profile Store (`WorkspaceProfileStore`)**: Programmatic Node.js SDK (`src/profile-manager.js`) and TypeScript definitions (`index.d.ts`) to save, list, and atomically activate isolated `~/.claude/settings.json`, `~/.codex`, and workspace `.mcp.json` profiles across macOS, Linux, and Windows
    - **MCP Server Security & Isolation Auditor (`npx codex-multi-profile mcp-audit`)**: Static analyzer (`src/mcp-auditor.js`) for `.mcp.json` and `claude_desktop_config.json` that detects hardcoded API tokens (`sk-ant-*`, `ghp_*`), non-loopback HTTP/SSE endpoints, and unsafe shell wrapper invocations before switching workspaces
    - **`CLAUDE.md` <-> `AGENTS.md` Instruction Bridge (`npx codex-multi-profile sync-docs`)**: Deterministic Markdown parser and synchronizer (`src/instruction-bridge.js`) keeping repository guidelines aligned across Claude Code and OpenAI Codex workflows
    - Added `docs/claude-code-mcp.md` and `tests/sdk.test.js` covering MCP auditing, instruction synchronization, and profile isolation
    
    ## 1.0.4 — 2026-10-20
    
    ### Added
    - Official npm CLI wrapper (`codex-multi-profile` on npm) supporting `npx codex-multi-profile install`, `list [--json]`, `status`, `save`, `switch`, `rename`, `remove`, and `lang`
    - Automated GitHub Actions release verification and npm package smoke tests in CI
    
    ### Changed
    - Unified repository `VERSION` and `package.json` to `1.0.4` with zero-dependency Node.js >=18 launcher delegating to `%LOCALAPPDATA%\CodexMultiProfile\CodexAccounts.ps1`
    
    ## 1.0.3 — 2026-10-19
    
    ### Added
    - Published `codex-multi-profile` CLI distribution to the public npm registry (`https://www.npmjs.com/package/codex-multi-profile`)
    - Normalized `bin` entry in `package.json` for cross-shell compatibility on Windows (`pwsh`, Windows PowerShell 5.1, Git Bash)
    
    ## 1.0.0 — 2026-10-05
    
    ### Added
    - Promoted the Microsoft Store Codex avatar-menu switcher architecture (0.4.0) to stable 1.0.0 release after production validation across multi-workspace Plus, Pro, and Team accounts
    
    ## 0.4.0 — 2026-09-28
    
    Rebuilt around the Microsoft Store Codex. Codex 26.9xx refuses to run outside its package ("The process has no
    package identity"), so the cloned `ChatGPT.exe` the earlier versions launched no longer starts. This release
    replaces the unreleased 0.3.0 clone-based in-app switcher.
    
    ### Added
    - **Accounts in the Codex avatar menu** of the Store app: click an account to switch in 2-3 s (only the codex.exe
      app-server restarts, the window stays; full restart from a sign-in screen), **Add account** (Codex reopens on its sign-in screen, the new login is saved under the chosen name),
      rename (pencil) and remove (trash) on hover, `1`-`9`, `Ctrl+Alt+A`, usage-limit suggestion card
    - One **Codex** shortcut (Desktop + Start menu) that starts the Store Codex through `IApplicationActivationManager`
      with DevTools on `127.0.0.1` and runs the hidden helper (`Start-CodexAccounts.ps1`) while Codex is open
    - Live token sync: the `auth.json` Codex refreshes is copied back into the account in use, so saved logins do not go stale
    - Any new login seen while Codex runs is saved automatically; a login that is not saved is never removed
    - Menu language follows Codex (`<html lang>`), Vietnamese or English
    - **Usage bars** under every account (5h / week on paid plans, month on free), from `/wham/usage` with that
      account's own token, non-blocking; hover shows the reset time
    - **Watcher** at sign-in (`CodexAccountsWatcher.exe`, ~25 MB): the menu also appears when Codex is opened from its
      own taskbar / Start icon (Codex restarts once); `-NoAutoStart` to skip
    - While switching, an opaque veil hides the error screen Codex shows for a second, until its UI is back
    - `CodexAccounts.ps1` CLI: `list`, `status`, `save`, `switch`, `rename`, `remove`, `lang`
    - `Install-CodexMultiProfile.ps1 -RemoveLegacy` / `CODEX_MP_REMOVE_LEGACY=1`: imports the logins saved by 0.1-0.2 and
      removes `%LOCALAPPDATA%\CodexParallelDesktop` (junctions into `~\.codex` are unlinked, never followed)
    
    ### Changed
    - Helper cost: no `Runtime.enable`, no JSON parsing of CDP replies, no WMI polling, work only when
      `auth.json` or the store changes (~130 MB, ~1 s CPU per minute)
    - Shortcut runs through `conhost --headless` (no VBScript)
    - Page script is event-driven: observes only `<body>`'s direct children (Codex menus are portals) and scans right after
      the avatar click; the usage-limit watcher batches small nodes once a second (no work per streamed token)
    - Never a restart loop: Codex is reopened for its menu port at most once per 10 minutes unless the last reopen
      worked, and the watcher waits longer after each helper that ends within a minute (20 s doubling up to 10 min)
    - Closing Codex ends its whole process tree with `Stop-Process` from one snapshot and never throws; Codex is always
      started again after a failed switch
    
    ### Removed
    - Cloned `ChatGPT.exe`, Codex1 / Codex Main launchers, AuthSwap watcher, Codex Accounts WPF app, router
      (`pool` / `stick` / `route`), layer, ChatGPT Web model block, doctor / repair / diagnostics
    
    ### Fixed
    - The helper hung with GBs of memory after Codex reloaded its window: a `Get-Content` string carries PSProvider /
      PSDrive note properties that `ConvertTo-Json -Depth 8` serialized; the page script is now read with `ReadAllText`
    - The helper found no Codex window on Windows PowerShell 5.1 (`ConvertFrom-Json` emits a JSON array as one object),
      so the menu was never injected
    
    ## 0.2.0 — 2026-08-20
    
    ### Added
    - **Codex Accounts** desktop app (`Show-CodexAccountApp.ps1`): WPF account picker (masked email, last-used, depleted, sticky). Click / Enter closes the open Codex window then AuthSwap-launches the saved account
    - Desktop shortcut **Codex Accounts** next to Codex1 / Codex Main
    - One-command Windows install stays `irm .../install.ps1 | iex` (counterpart of b-nnett/codex-subscription-router curl|bash)
    - Subscription router (AuthSwap, one window): `pool`, `stick`, `route`, `depleted` on CodexProfile.ps1
    - Sticky git-repo/workspace -> profile; new work picks least-recently-used non-depleted profile; depleted owner fails over; all-depleted prints one combined message
    - Combined pool view with masked emails, last-used, depleted flag, sticky paths
    - Optional clone-only desktop layer (`layer` / `layer -Disable`)
    - Optional ChatGPT Web model block in `~/.codex/config.toml` (`models` / `models -Disable`)
    - `docs/router.md`, `docs/layer.md`, `tests/LayerAndRouter.Tests.ps1`
    
    ### Changed
    - VERSION 0.2.0; installer packages `CodexRouter.psm1`, `Start-CodexLayer.ps1`, `layer-inject.js`, `Show-CodexAccountApp.ps1`
    - Existing Codex1 / Codex Main / doctor / verify / AuthSwap launch unchanged until you opt in
    
    ## 0.1.4 — 2026-08-14
    
    ### Added
    - `repair` clears a stale AuthSwap lock and restores main auth from backup
    - `sync-check` SHA256-compares packaged scripts vs LocalAppData install
    - `diagnostics` / `Export-CodexDiagnostics.ps1` for redacted support bundles
    - `install.ps1` tag/`vX.Y.Z` Ref support and temp cleanup
    - Recipe cards for stale lock + diagnostics; CODEOWNERS; SUPPORT.md
    
    ### Changed
    - Installer copies every name from `Get-CodexPackagedScriptNames`
    - Menu, FAQ, SKILL, and doctor hint point at `repair` / `diagnostics`
    
    ## 0.1.3 — 2026-08-14
    
    ### Added
    - `doctor` health checks (stale lock, dual-window, BOM, poisoned profile)
    - `processes` to list Store vs clone ChatGPT.exe
    - `Redact-LaunchTrace.ps1` for safe bug-report logs
    - SUPPORT, recipe cards, contributor invariants
    
    ### Changed
    - Bug template asks for doctor output and redacted logs
    
    ## 0.1.2 — 2026-08-13
    
    ### Added
    - `status -AsJson` for scripts (emails still masked)
    - `remove -Force` to delete one profile folder, never `~\.codex`
    
    ### Fixed
    - `launch-trace.log` no longer writes full ChatGPT emails
    - CI uses `actions/checkout@v7`
    
    ### Changed
    - Installer imports `CodexMultiProfile.psm1` instead of duplicating helpers
    
    ## 0.1.1 — 2026-08-13
    
    ### Added
    - `CodexProfile.ps1 -Action status` (masked emails) and `-Action verify`
    - `Update-CodexMultiProfile.ps1` to pull and reinstall
    - FAQ, feature-request template, Dependabot for GitHub Actions
    
    ### Fixed
    - Uninstall now removes every Desktop shortcut whose target is CodexParallelDesktop
    - CI uses `actions/checkout@v5` and `tests/Run-All.ps1`
    
    ### Security
    - Status/list never print a full ChatGPT email
    
    ## 0.1.0 — 2026-08-13
    
    ### Added
    - AuthSwap launchers for a secondary ChatGPT login while keeping `~\.codex` shared
    - Restore-main shortcut that refuses to copy the main token into a profile
    - Shared PowerShell module with JWT email parse, bootstrap detection, and UTF-8 (no BOM) writes
    - Installer, uninstall, Desktop shortcuts, and Codex/Cursor skill copy
    - Tests for poison-guard, JWT parse, profile keys, and script parse
    - Windows CI
    
    ### Security
    - `auth.json` stays on disk only. Nothing is uploaded. Do not commit logs or tokens.
    
  • cli.js5.0 KB170941854103upstream ↗
    #!/usr/bin/env node
    "use strict";
    
    const path = require("path");
    const { spawnSync } = require("child_process");
    const {
      getInstallRoot,
      getAccountsScriptPath,
      runCodexAccounts,
      auditMcpFile,
      syncWorkspaceInstructions,
      WorkspaceProfileStore
    } = require("./index");
    
    const rawArgs = process.argv.slice(2);
    
    if (rawArgs.includes("--help") || rawArgs.includes("-h")) {
      console.log([
        "codex-multi-profile — Multi-Workspace Profile Router & MCP Isolation Toolkit for Claude Code and OpenAI Codex",
        "",
        "Cross-Platform Commands (Claude Code, MCP & Codex):",
        "  npx codex-multi-profile mcp-audit [path]         Audit .mcp.json / Claude Code MCP server security & token exposure",
        "  npx codex-multi-profile sync-docs [dir]          Synchronize CLAUDE.md <-> AGENTS.md instructions across a repo",
        "  npx codex-multi-profile profiles [claude|codex]  List isolated Claude Code (~/.claude) or Codex (~/.codex) profiles",
        "",
        "Windows Desktop Commands (Microsoft Store Codex App):",
        "  npx codex-multi-profile install                  Install or update the Windows Store Codex workspace helper",
        "  npx codex-multi-profile list [--json]            List saved workspace profiles and active status",
        "  npx codex-multi-profile status                   Show Store app, local CDP bridge, and active workspace status",
        "  npx codex-multi-profile save <name>              Save the currently active workspace profile",
        "  npx codex-multi-profile switch <name>            Switch active workspace profile (2-3s hot reload)",
        "  npx codex-multi-profile rename <old> <new>       Rename a saved workspace profile",
        "  npx codex-multi-profile remove <name>            Remove a saved workspace profile",
        "  npx codex-multi-profile lang <auto|vi|en>        Set workspace menu language",
        "",
        `Profile store root: ${getInstallRoot()}`
      ].join("\n"));
      process.exit(0);
    }
    
    if (rawArgs.includes("--version") || rawArgs.includes("-v")) {
      const pkg = require("./package.json");
      console.log(pkg.version);
      process.exit(0);
    }
    
    const cmd = (rawArgs[0] || "list").toLowerCase();
    
    if (cmd === "mcp-audit") {
      const targetFile = path.resolve(rawArgs[1] || ".mcp.json");
      try {
        const res = auditMcpFile(targetFile, { allowRemoteHttp: rawArgs.includes("--allow-remote") });
        if (rawArgs.includes("--json")) {
          console.log(JSON.stringify(res, null, 2));
        } else {
          console.log(`Audited ${res.serverCount} MCP server(s) in ${targetFile}: ${res.valid ? "PASS" : "FAIL"}`);
          for (const f of res.findings) {
            console.log(`  [${f.severity.toUpperCase()}] (${f.code}) ${f.server}: ${f.message}`);
          }
        }
        process.exit(res.valid ? 0 : 1);
      } catch (err) {
        console.error(`Error auditing MCP config at ${targetFile}: ${err.message}`);
        process.exit(1);
      }
    }
    
    if (cmd === "sync-docs") {
      const dir = path.resolve(rawArgs[1] || ".");
      const dryRun = rawArgs.includes("--dry-run");
      const res = syncWorkspaceInstructions(dir, { dryRun });
      if (rawArgs.includes("--json")) {
        console.log(JSON.stringify(res, null, 2));
      } else if (res.action === "none") {
        console.log(`No CLAUDE.md or AGENTS.md found in ${dir}.`);
      } else {
        console.log(
          `${dryRun ? "[DRY-RUN] " : ""}Synced (${res.action}): ${res.sectionCount} section(s) -> ${path.basename(res.targetFile)} (updated=${res.updated})`
        );
      }
      process.exit(0);
    }
    
    if (cmd === "profiles") {
      const agent = (rawArgs[1] || "claude").toLowerCase() === "codex" ? "codex" : "claude";
      const store = new WorkspaceProfileStore();
      const list = store.listProfiles(agent);
      if (rawArgs.includes("--json")) {
        console.log(JSON.stringify(list, null, 2));
      } else if (list.length === 0) {
        console.log(`No saved ${agent} configuration profiles in ${store.getProfilesDir(agent)}.`);
      } else {
        for (const p of list) {
          console.log(`${p.slug}\tagent=${p.agent}\tmcp=${p.hasMcpConfig}\thash=${p.settingsHash || "none"}`);
        }
      }
      process.exit(0);
    }
    
    if (cmd === "install" || cmd === "setup") {
      const installCmd = "irm https://raw.githubusercontent.com/Hung2124/codex-multi-profile/main/install.ps1 | iex";
      const res = spawnSync("powershell.exe", ["-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", installCmd], {
        stdio: "inherit"
      });
      process.exit(res.status ?? 0);
    }
    
    const mapped = [];
    if (cmd === "list") {
      mapped.push("list");
      if (rawArgs.includes("--json")) mapped.push("-Json");
    } else if (cmd === "status") {
      mapped.push("status");
    } else if (cmd === "save" && rawArgs[1]) {
      mapped.push("save", "-Name", rawArgs[1]);
    } else if (cmd === "switch" && rawArgs[1]) {
      mapped.push("switch", "-Name", rawArgs[1]);
    } else if (cmd === "rename" && rawArgs[1] && rawArgs[2]) {
      mapped.push("rename", "-Name", rawArgs[1], "-NewName", rawArgs[2]);
    } else if (cmd === "remove" && rawArgs[1]) {
      mapped.push("remove", "-Name", rawArgs[1]);
    } else if (cmd === "lang" && rawArgs[1]) {
      mapped.push("lang", "-Name", rawArgs[1]);
    } else {
      mapped.push(...rawArgs);
    }
    
    process.exit(runCodexAccounts(mapped));
    
  • CONTRIBUTING.md1.2 KB62fc17898237upstream ↗
    # Contributing
    
    PRs that encode a **verified Windows Codex Desktop** behavior are welcome. Keep changes small.
    
    ## Rules
    
    1. Do not add API keys, `auth.json`, or account emails to the repo or to fixtures. Tests use fake JWTs (`[email protected]`).
    2. Write files Codex will parse with UTF-8 **without BOM** (`Write-Utf8NoBom`).
    3. Keep `SKILL.md` under ~500 lines. Put long explanations in `docs/`.
    4. Start the Store Codex only through `Start-CodexStore`; never clone or patch `ChatGPT.exe`.
    5. Keep `.ps1` / `.psm1` files ASCII (Windows PowerShell 5.1 reads BOM-less UTF-8 as ANSI).
    6. Read [AGENTS.md](AGENTS.md) and [docs/architecture.md](docs/architecture.md) for the rules that keep switching safe.
    7. Run:
    
    ```powershell
    powershell -NoProfile -ExecutionPolicy Bypass -File .\tests\Run-All.ps1
    ```
    
    8. Changed how the menu looks? Regenerate the README screenshots (made-up accounts, headless Edge):
    
    ```powershell
    node tools/screenshots/capture.mjs
    ```
    
    ## Scope
    
    In scope: the account store, the avatar-menu switcher, starting the Store Codex, the installer and shortcuts, the CLI and agent skill, and their tests.
    
    Out of scope: unofficial API proxies, automating ChatGPT sign-in, shipping tokens, a Go mux, asar/ChatGPT.exe patchers, or quota-bypass features.
    
  • docs/architecture.md6.8 KBd83fd2ac0c03upstream ↗
    # How it works
    
    ## 1. Cross-Platform Node.js SDK & CLI (`src/`)
    
    ```
    codex-multi-profile (Node.js 18+ CLI & SDK)
      ├─ src/mcp-auditor.js        Static security analyzer for .mcp.json & claude_desktop_config.json
      │                            (flags plaintext tokens sk-ant-*/ghp_*, non-loopback HTTP/SSE, shell wrappers)
      ├─ src/mcp-presets.js        Hardened MCP server templates enforcing ${ENV_VAR} interpolation
      ├─ src/instruction-bridge.js Deterministic parser & two-way sync between CLAUDE.md and AGENTS.md
      └─ src/profile-manager.js    WorkspaceProfileStore: atomic profile snapshots for ~/.claude & ~/.codex
    ```
    
    ## 2. Windows Store Codex Helper (`scripts/`)
    
    ```
    Codex shortcut
      └─ conhost --headless powershell Start-CodexAccounts.ps1        (hidden, one per Windows session)
           ├─ saves the login in ~/.codex/auth.json as an account if it is new
           ├─ starts the Store Codex through IApplicationActivationManager
           │    with --remote-debugging-address=127.0.0.1 --remote-debugging-port=9333
           ├─ CDP on the main window (app://-/index.html only):
           │    Runtime.addBinding('cmpSwitcherBridge') + inject switcher-inject.js (survives reloads)
           ├─ page: when Codex's avatar menu (role=menu) opens, add the Accounts section under the identity row
           ├─ every 3 s: if auth.json or the account store changed -> sync + push masked state to the page
           └─ exits when Codex is closed
    ```
    
    ## Watcher
    
    `CodexAccountsWatcher.exe` (compiled at install from `scripts/CodexAccountsWatcher.cs`, started at sign-in from
    HKCU `Run`): every 1.5 s it lists `ChatGPT.exe` processes; when the Store Codex runs and the helper's mutex
    (`Local\CodexMultiProfileHost`) is free it starts the helper, which reopens Codex with the DevTools port if needed.
    ~25 MB, near-zero CPU. It exits by itself once the install folder is gone. A helper that ends within a minute
    while Codex runs makes it wait longer before the next try (20 s doubling up to 10 min), and the helper reopens
    Codex for the port at most once per 10 minutes unless the last reopen worked: never a restart loop.
    
    ## Usage bars
    
    The helper asks `https://chatgpt.com/backend-api/wham/usage` for every saved account with that account's own access
    token (the endpoint Codex itself uses), without blocking: one shared `HttpClient`, tasks checked in the main loop.
    When the menu opens (at most once a minute per account) and every 10 minutes. The page gets label / percent used /
    reset time only. A limit reached counts as out of quota; a login the server rejects shows no bar.
    
    ## Accounts
    
    - `%LOCALAPPDATA%\CodexMultiProfile\accounts\<name>\auth.json`: one saved copy of `~\.codex\auth.json` per account,
      identified by the id_token email + ChatGPT account id (same email in two workspaces = two accounts).
    - `accounts.json`: last used / out-of-quota flags. `settings.json` (optional): `cdpPort`, `lang`.
    - **Sync.** Codex refreshes and rotates its tokens in `auth.json`. The helper copies the live file back into the account
      in use whenever it changes, and once more right before a switch. A saved copy that fell behind would stop working.
    - **Switch (fast, 2-3 s).** The login lives in the `codex.exe app-server` child, not in the window. End only the
      app-server → sync the outgoing account → copy the chosen `auth.json` in place (write + rename) → Codex starts a new
      app-server by itself and the open window picks the new account up (name, plan, limits) without a reload. If Codex
      was quicker than the copy, that app-server is ended once more. Used when the page reports the normal signed-in UI.
    - **Switch (full).** From a sign-in screen, or when no new app-server shows up within 10 s: end Codex and its whole
      process tree (one snapshot, `Stop-Process`, wait until every process is gone) → swap → start Codex. Codex is always
      started again, whatever failed.
    - **Add.** Full restart (only a fresh start shows the sign-in screen): sync → remove `~\.codex\auth.json` → start Codex → when a new login appears,
      save it under the chosen name. A login that is not saved anywhere is never removed, and any new login seen while
      Codex runs is saved automatically.
    
    ## Starting the Store Codex
    
    Codex 26.9xx refuses to run without package identity, so it cannot be copied out of `WindowsApps`.
    `IApplicationActivationManager.ActivateApplication("OpenAI.Codex_2p2nqsd0c76g0!App", args)` starts it inside its
    package and passes the DevTools arguments. Tried and rejected: `Invoke-CommandInDesktopPackage` and `shell:AppsFolder`
    leave a hung `ChatGPT.exe` (no window, no port) when called from a normal process.
    
    Before starting again the helper waits until every `ChatGPT.exe` of the package has exited; starting while the old
    instance is still exiting hangs on "The application is exiting and cannot service this request".
    
    ## Page side (`switcher-inject.js`)
    
    - Closed shadow roots inside Codex's own menu; built with `createElement` only (no HTML strings, Trusted Types and
      CSP safe), no network calls. React keeps rendering its own rows.
    - Finds the avatar button by position / `aria-haspopup=menu` / image, and looks again only when it went away or the
      window became visible. If it cannot be found (sign-in screen, a future Codex layout) a same-looking account button
      appears at the bottom-left instead.
    - Light on Codex: menus are Radix portals appended to `<body>`, so only `<body>`'s direct children are observed, plus a
      scan right after the avatar is clicked. The usage-limit watcher only queues small new nodes and checks them once a
      second, so streaming replies do not cost anything noticeable.
    - Codex sends printable keys typed outside an editable element to its composer; the layer carries
      `data-codex-character-input-boundary` (Codex's own opt-out) so typing in our dialogs stays there.
    - Talks to the helper only through the binding. Messages: `hello`, `refresh`, `switch`, `add`, `cancel-add`, `rename`,
      `remove`, `depleted`. The helper validates each one (`ConvertFrom-CodexSwitcherMessage`): fixed types, names
      `^[a-z0-9][a-z0-9-]{0,63}$` that must exist, 4 KB max.
    
    ## Helper cost
    
    No `Runtime.enable`: the binding works without it, and it would stream every Codex console message through PowerShell.
    `Page.enable` is kept (a few events per navigation): the new-document script needs it to run again after a reload. Replies are skipped without JSON parsing. Idle cost: ~130 MB, ~1 s CPU per minute.
    
    ## Security notes
    
    - The DevTools port is bound to `127.0.0.1`. The helper attaches only when the port belongs to the Store Codex
      `ChatGPT.exe`, and only to `ws://127.0.0.1:<port>/` sockets. Any program running as you can reach the port as well.
    - Events sent to the page are checked for unmasked emails and dropped if one slips through.
    - Logs (`codex-accounts.log`, rotated at 512 KB) contain account names and masked emails only.
    
  • docs/claude-code-mcp.md2.6 KB807bcd5da0c1upstream ↗
    # Claude Code & MCP Workspace Isolation Guide
    
    `codex-multi-profile` v2.0 provides programmatic and CLI primitives for developers and open-source maintainers who work across multiple **Claude Code** (`~/.claude`), **Model Context Protocol (`.mcp.json`)**, and **OpenAI Codex** (`~/.codex`) environments.
    
    ## 1. Auditing `.mcp.json` Before Switching Profiles
    
    When switching between an Enterprise SSO repository and a public Open-Source repository, `.mcp.json` files can inadvertently expose plaintext API keys or bind to non-loopback HTTP/SSE endpoints.
    
    Run the static auditor in CI or pre-commit hooks:
    
    ```bash
    npx codex-multi-profile mcp-audit .mcp.json
    ```
    
    ### Checks Performed
    - **`HARDCODED_SECRET_ENV` (`error`)**: Detects plaintext tokens (`sk-ant-*`, `ghp_*`, `xoxb-*`, or sensitive `*_KEY` / `*_TOKEN` values) that are not using `${VAR}` environment variable interpolation.
    - **`INSECURE_REMOTE_MCP_ENDPOINT` (`error`)**: Flags unencrypted `http://` MCP server URLs bound to non-loopback hosts.
    - **`REMOTE_MCP_ENDPOINT` (`warning`)**: Highlights external `https://` MCP endpoints unless `--allow-remote` is passed.
    - **`SHELL_WRAPPER_COMMAND` (`warning`)**: Warns when an MCP server spawns `bash -c`, `sh -c`, or `powershell -Command` instead of a direct binary or package entrypoint.
    
    ## 2. Managing Isolated `~/.claude` and `~/.codex` Profiles
    
    Use `WorkspaceProfileStore` to snapshot and activate isolated agent settings (`model`, `permissions`, `.mcp.json`) without cross-contaminating credentials:
    
    ```javascript
    const { WorkspaceProfileStore } = require("codex-multi-profile");
    
    const store = new WorkspaceProfileStore();
    
    // Save an Open-Source Maintainer profile for Claude Code
    store.saveProfile("oss-maintainer", {
      agent: "claude",
      settings: {
        model: "claude-sonnet-4-5",
        permissions: {
          allow: ["Read", "Edit", "Bash(npm test)", "Bash(git status)"]
        }
      }
    });
    
    // Activate the profile atomically
    store.activateProfile("oss-maintainer", {
      agent: "claude",
      workspaceDir: process.cwd()
    });
    ```
    
    ## 3. Synchronizing `CLAUDE.md` and `AGENTS.md`
    
    Maintainers who use both **Claude Code** and **OpenAI Codex** can keep their repository instructions aligned from a single source of truth:
    
    ```bash
    npx codex-multi-profile sync-docs .
    ```
    
    ## 4. Generating Hardened `.mcp.json` Manifests
    
    Use `composeMcpConfig` to scaffold a clean `.mcp.json` manifest that enforces `${VAR}` secret interpolation:
    
    ```javascript
    const { composeMcpConfig, auditMcpConfig } = require("codex-multi-profile");
    
    const manifest = composeMcpConfig(["github", "filesystem", "postgres"]);
    console.assert(auditMcpConfig(manifest).valid === true);
    ```
    
  • docs/images/accounts-menu-vi.png81 KB781e5419f60cupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • docs/images/accounts-menu.png80 KB951ecdc49082upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • docs/images/add-account.png74 KB51a8a5a5ca26upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • docs/troubleshooting.md1.4 KB382f6d9cc62eupstream ↗
    # Troubleshooting
    
    Start with:
    
    ```powershell
    powershell -NoProfile -ExecutionPolicy Bypass -File "$env:LOCALAPPDATA\CodexMultiProfile\CodexAccounts.ps1" status
    ```
    
    Log: `%LOCALAPPDATA%\CodexMultiProfile\codex-accounts.log` (masked, safe to paste after a look).
    
    | Symptom | Try |
    |:---|:---|
    | No **Accounts** section in the avatar menu | The watcher should fix this within seconds (Codex restarts once). If not: is `CodexAccountsWatcher.exe` running? Re-run the installer, or open Codex from the **Codex** shortcut |
    | "The account helper is not running" in the menu | The helper exited. Open Codex again from the **Codex** shortcut (it attaches without restarting Codex) |
    | After switching, Codex shows its sign-in screen | That account's saved login expired. Sign in with the same account; it is saved automatically. Or use the account button at the bottom-left to go back |
    | "That login is already saved as ..." after Add account | You signed in with an account that is already in the list; nothing was added |
    | The switch card stays for more than ~25 s | See the log: `restart:` lines show how long closing and reopening took. Open Codex from the shortcut again |
    | Port 9333 is used by something else | `settings.json` in the install folder: `{ "cdpPort": 9444 }`, then reopen Codex from the shortcut |
    | Menu language | `CodexAccounts.ps1 lang -Name vi` (or `en`, `auto` = follow Codex) |
    
    Never paste `auth.json` or anything from the `accounts` folder into an issue.
    
  • examples/audit-mcp-ci.mjs353 B0288f299e2bdupstream ↗
    import { composeMcpConfig, auditMcpConfig } from '../index.js';
    
    const manifest = composeMcpConfig(['github', 'filesystem', 'postgres']);
    const report = auditMcpConfig(manifest);
    if (!report.valid) {
      console.error('MCP Audit Failed:', report.findings);
      process.exit(1);
    }
    console.log('Verified', report.serverCount, 'MCP servers with 0 findings.');
    
  • examples/isolate-claude-profiles.mjs171 Be3ee13c2c8b0upstream ↗
    import { WorkspaceProfileStore } from '../index.js';
    
    const store = new WorkspaceProfileStore();
    console.log('Saved Claude Code profiles:', store.listProfiles('claude'));
    
  • examples/mcp.example.json230 B4eee0f05d45eupstream ↗
    {
      "mcpServers": {
        "github": {
          "command": "npx",
          "args": ["-y", "@modelcontextprotocol/server-github"],
          "env": {
            "GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_PERSONAL_ACCESS_TOKEN}"
          }
        }
      }
    }
    
  • examples/sync-claude-codex-docs.mjs175 B4d0b6a2839c2upstream ↗
    import { syncWorkspaceInstructions } from '../index.js';
    
    const res = syncWorkspaceInstructions(process.cwd(), { dryRun: true });
    console.log('Instruction sync check:', res);
    
  • index.d.ts2.8 KB650a9f5897b9upstream ↗
    export interface McpAuditFinding {
      server: string;
      severity: "error" | "warning";
      code: string;
      message: string;
    }
    
    export interface McpAuditResult {
      valid: boolean;
      serverCount: number;
      findings: McpAuditFinding[];
    }
    
    export interface McpAuditOptions {
      allowRemoteHttp?: boolean;
    }
    
    export interface AgentSection {
      heading: string;
      level: number;
      body: string;
    }
    
    export interface ParsedAgentMarkdown {
      title: string | null;
      preamble: string;
      sections: AgentSection[];
    }
    
    export interface SyncInstructionOptions {
      direction?: "claude-to-codex" | "codex-to-claude" | "auto";
      dryRun?: boolean;
    }
    
    export interface SyncInstructionResult {
      action: string;
      sourceFile: string | null;
      targetFile: string | null;
      sectionCount: number;
      updated: boolean;
    }
    
    export interface ProfileSummary {
      slug: string;
      agent: string;
      updatedAt: string;
      hasMcpConfig: boolean;
      settingsHash: string | null;
    }
    
    export declare class WorkspaceProfileStore {
      storeRoot: string;
      claudeHome: string;
      codexHome: string;
      constructor(options?: { storeRoot?: string; claudeHome?: string; codexHome?: string });
      getProfilesDir(agent?: "claude" | "codex"): string;
      listProfiles(agent?: "claude" | "codex"): ProfileSummary[];
      saveProfile(
        name: string,
        payload?: { agent?: "claude" | "codex"; settings?: Record<string, unknown>; mcpConfig?: Record<string, unknown> }
      ): { slug: string; agent: string; path: string };
      activateProfile(
        name: string,
        options?: { agent?: "claude" | "codex"; workspaceDir?: string }
      ): { slug: string; agent: string; copiedSettings: boolean; copiedMcp: boolean };
    }
    
    export declare function getInstallRoot(): string;
    export declare function getAccountsScriptPath(): string;
    export declare function runCodexAccounts(args?: string[]): number;
    export declare function auditMcpConfig(config: Record<string, unknown>, options?: McpAuditOptions): McpAuditResult;
    export declare function auditMcpFile(filePath: string, options?: McpAuditOptions): McpAuditResult;
    export declare function parseAgentMarkdown(markdown: string): ParsedAgentMarkdown;
    export declare function renderAgentMarkdown(
      doc: ParsedAgentMarkdown,
      options?: { target?: "claude" | "codex"; includeSyncBanner?: boolean }
    ): string;
    export declare function syncWorkspaceInstructions(workspaceDir: string, options?: SyncInstructionOptions): SyncInstructionResult;
    export declare function normalizeProfileSlug(name: string): string;
    export declare function maskEmailAddress(email: string): string;
    
    export declare const MCP_PRESETS: Record<string, Record<string, unknown>>;
    export declare function getMcpPreset(name: string): Record<string, unknown> | null;
    export declare function listMcpPresets(): string[];
    export declare function composeMcpConfig(presetNames?: string[]): { mcpServers: Record<string, unknown> };
    
  • index.js2.1 KB5da9561b4e1eupstream ↗
    "use strict";
    
    const { spawnSync } = require("child_process");
    const path = require("path");
    const os = require("os");
    const fs = require("fs");
    
    const { auditMcpConfig, auditMcpFile } = require("./src/mcp-auditor");
    const { MCP_PRESETS, getMcpPreset, listMcpPresets, composeMcpConfig } = require("./src/mcp-presets");
    const { parseAgentMarkdown, renderAgentMarkdown, syncWorkspaceInstructions } = require("./src/instruction-bridge");
    const { normalizeProfileSlug, maskEmailAddress, WorkspaceProfileStore } = require("./src/profile-manager");
    
    function getInstallRoot() {
      if (process.platform === "win32") {
        const localAppData = process.env.LOCALAPPDATA || path.join(os.homedir(), "AppData", "Local");
        return path.join(localAppData, "CodexMultiProfile");
      }
      return path.join(process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config"), "codex-multi-profile");
    }
    
    function getAccountsScriptPath() {
      return path.join(getInstallRoot(), "CodexAccounts.ps1");
    }
    
    function runCodexAccounts(args = ["list"]) {
      if (process.platform !== "win32") {
        throw new Error("Native Windows Store Codex app integration requires Windows 10/11. Use `profiles`, `mcp-audit`, or `sync-docs` on macOS/Linux.");
      }
      const scriptPath = getAccountsScriptPath();
      if (!fs.existsSync(scriptPath)) {
        const installCmd = "irm https://raw.githubusercontent.com/Hung2124/codex-multi-profile/main/install.ps1 | iex";
        const res = spawnSync("powershell.exe", ["-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", installCmd], {
          stdio: "inherit"
        });
        return res.status ?? 0;
      }
      const res = spawnSync(
        "powershell.exe",
        ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", scriptPath, ...args],
        { stdio: "inherit" }
      );
      return res.status ?? 0;
    }
    
    module.exports = {
      getInstallRoot,
      getAccountsScriptPath,
      runCodexAccounts,
      auditMcpConfig,
      auditMcpFile,
      parseAgentMarkdown,
      renderAgentMarkdown,
      syncWorkspaceInstructions,
      normalizeProfileSlug,
      maskEmailAddress,
      WorkspaceProfileStore,
      MCP_PRESETS,
      getMcpPreset,
      listMcpPresets,
      composeMcpConfig
    };
    
  • install.ps12.4 KB8644847db652upstream ↗
    #Requires -Version 5.1
    <#
    .SYNOPSIS
      Download this repo and run the Windows installer.
    
    .EXAMPLE
      irm https://raw.githubusercontent.com/Hung2124/codex-multi-profile/main/install.ps1 | iex
    
    .EXAMPLE
      powershell -NoProfile -ExecutionPolicy Bypass -File .\install.ps1 -Ref v0.4.0
    
    .EXAMPLE
      # Upgrading from the old clone-based version: import its logins and remove it
      $env:CODEX_MP_REMOVE_LEGACY = '1'; irm https://raw.githubusercontent.com/Hung2124/codex-multi-profile/main/install.ps1 | iex
    #>
    [CmdletBinding()]
    param(
        [string]$Repo = 'Hung2124/codex-multi-profile',
        [string]$Ref = 'main',
        [switch]$KeepDownload,
        [switch]$RemoveLegacy
    )
    
    $ErrorActionPreference = 'Stop'
    if (-not $PSBoundParameters.ContainsKey('Ref') -and $env:CODEX_MP_REF) {
        $Ref = $env:CODEX_MP_REF
    }
    if (-not $PSBoundParameters.ContainsKey('RemoveLegacy') -and $env:CODEX_MP_REMOVE_LEGACY -in @('1', 'true', 'yes', 'on')) {
        $RemoveLegacy = $true
    }
    $tmp = Join-Path $env:TEMP ("codex-multi-profile-" + [guid]::NewGuid().ToString('n'))
    New-Item -ItemType Directory -Force -Path $tmp | Out-Null
    
    try {
        $zip = Join-Path $tmp 'src.zip'
        if ($Ref -match '^(refs/)?tags/') {
            $tag = $Ref -replace '^(refs/)?tags/', ''
            $url = "https://github.com/$Repo/archive/refs/tags/$tag.zip"
        }
        elseif ($Ref -match '^v?\d+\.\d+') {
            $url = "https://github.com/$Repo/archive/refs/tags/$Ref.zip"
        }
        else {
            $url = "https://github.com/$Repo/archive/refs/heads/$Ref.zip"
        }
    
        Write-Host "Downloading $url"
        Invoke-WebRequest -Uri $url -OutFile $zip -UseBasicParsing
        Expand-Archive -LiteralPath $zip -DestinationPath $tmp -Force
        $inner = Get-ChildItem -LiteralPath $tmp -Directory |
            Where-Object { $_.Name -like 'codex-multi-profile-*' } |
            Select-Object -First 1
        if (-not $inner) { throw "Unzipped repo folder not found under $tmp" }
    
        $installer = Join-Path $inner.FullName 'scripts\Install-CodexMultiProfile.ps1'
        if (-not (Test-Path -LiteralPath $installer)) { throw "Installer missing: $installer" }
    
        $installArgs = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', $installer)
        if ($RemoveLegacy) { $installArgs += '-RemoveLegacy' }
        & powershell.exe @installArgs
    }
    
    finally {
        if (-not $KeepDownload -and (Test-Path -LiteralPath $tmp)) {
            Remove-Item -LiteralPath $tmp -Recurse -Force -ErrorAction SilentlyContinue
        }
        elseif ($KeepDownload) {
            Write-Host "Kept download at $tmp"
        }
    }
    
  • LICENSE1.0 KB0e145d07461fupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • package.json1.4 KB3c37742d7e64upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • README.vi.md6.7 KBd411883c2fdbupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • SECURITY.md963 B155eeb41fe2bupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • src/instruction-bridge.js4.9 KBf58c4bbf9831upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • src/mcp-auditor.js4.9 KB27aef69f8587upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • src/mcp-presets.js1.8 KB1a2419dd9f72upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • src/profile-manager.js6.0 KBedfa0f535b4aupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • SUPPORT.md471 B1c6b02492ce8upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/Accounts.Tests.ps111 KB4b8681b8645eupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/Invoke-ParseCheck.ps11.0 KB73ca55060912upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/Run-All.ps1277 Bbb61ef268b23upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/sdk.test.js4.8 KB681d22cf664eupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/Switcher.Tests.ps14.1 KBd27b695f6c1eupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tools/screenshots/capture.mjs3.9 KB5d99ec3ae055upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tools/screenshots/mock.html6.7 KB50a2f2a95735upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • VERSION6 B38f77a65b301upstream ↗
    2.0.1
    

Plain-text copy, no login: /skill-bundles/hung2124-codex-multi-profile.md

// REPO STATS

94 stars
5 open issues
Last commit: 18d ago