{
  "schema": 1,
  "id": "ext.codex",
  "name": "ChatGPT Codex",
  "version": "2.2.0",
  "category": "tool",
  "description": "OpenAI Codex as a chat agent: models and effort from the Codex CLI, sandbox modes, /review, /init, /mcp and your own prompts, session fork, export and delete, context meter, profiles and quick actions. Ships executable code.",
  "author": "Lumen",
  "icon": "Cx",
  "color": "#10a37f",
  "license": "MIT",
  "minAppVersion": "0.7.0",
  "keywords": [
    "codex",
    "chatgpt",
    "openai",
    "ai",
    "agent",
    "cli"
  ],
  "readme": "# ChatGPT Codex\n\nOpenAI Codex as a chat agent in Lumen. Each message starts the installed\nCodex CLI (`codex exec`); your login, `AGENTS.md` and `~/.codex/config.toml`\napply.\n\n## Chat\n\n- **Modes** are sandbox levels: *In project* (default), *Read only* and — only\n  when enabled — *Full access*\n- **Tools** with preview: commands with their output, changed files to\n  open, MCP calls (`server.tool` with their arguments and result), web searches\n- **Plan**: Codex's to-do list as a card with progress\n- **Tokens and duration** per answer, a **context meter** (from Codex's own\n  `token_count` records, else the model cache) and **rate limits** when your\n  plan reports them; Codex prints no prices, so there is no cost estimate\n- **Notices**: how the session runs (sandbox, approvals, network), warnings\n  Codex prints, switched-off reasoning summaries, ephemeral sessions\n- **Multiple chats**, **resume earlier sessions** (from `~/.codex/sessions`,\n  named as Codex or you named them)\n- **Models** from `~/.codex/models_cache.json` or from `codex app-server`\n  (`model/list`) — ↻ next to the picker asks the CLI again\n- **Reasoning effort per model** chosen in the chat — only the levels the model\n  supports; Lumen remembers the choice per model\n- Switch **models** directly in the chat, paste or attach **images**,\n  `@` for files, send the open file and selection along\n\n## Slash commands\n\n| Command | What it does |\n| --- | --- |\n| `/review [base <branch> \\| commit <sha> [title] \\| instructions]` | `codex exec review`: uncommitted changes by default. Codex accepts either a target or custom instructions, not both. A review runs in a session of its own. |\n| `/init` | Asks Codex to create or improve `AGENTS.md` |\n| `/status` | Codex version, account, model, sandbox, approvals, profile, `AGENTS.md`, session |\n| `/mcp [list \\| get \\| add \\| remove]` | `codex mcp …`; `add` takes `codex mcp add`'s arguments, e.g. `/mcp add docs --url https://…` or `/mcp add tool -- npx -y some-server` |\n| `/profiles` | The profiles Codex finds (`[profiles.x]` in `config.toml`, `<name>.config.toml`) |\n| `/prompts:<name> [args]` | Your Codex custom prompts: `~/.codex/prompts/*.md`, and `.codex/prompts/*.md` of the project (a project prompt wins). Front matter `description` and `argument-hint`; body placeholders `$1`…`$9`, `$ARGUMENTS`, `$NAME` (filled from `NAME=value`), `$$` |\n| your own | *Customize → Slash commands* (e.g. `/explain`, `/tests`) |\n\nLumen adds `/clear`, `/new` and — for the session actions below — `/fork`,\n`/rename`, `/delete`, `/export`. The palette learns Codex's own commands when\nthe chat's first session starts.\n\n## Session actions\n\n- **Fork** — `codex exec fork <id>`: a new session with the old history\n- **Rename** — kept by the add-on (exec mode cannot rename); the history shows it\n- **Delete** — `codex delete --force <id>`\n- **Export** — the session's rollout file as Markdown (your messages and Codex's)\n\nNot offered: *compact* (exec mode has no compaction command; Codex compacts by\nitself near the context limit) and *rewind* (no checkpoints in exec mode).\n\n## Settings\n\n*Settings → Extensions → ChatGPT Codex*:\n\n- **Program** — path to `codex`, profile (`[profiles.x]` or `<x>.config.toml`)\n- **Model** — default model, list source, more models, effort (incl. `max`),\n  reasoning summary, verbosity, hide reasoning\n- **Instructions** — text added to every chat, handed to Codex as\n  `developer_instructions` (`-c`) or in front of each message; the chat's own\n  system prompt is added after it\n- **Tools** — web search, network and `/tmp` in the *In project* sandbox\n- **Permissions** — approval policy, overridable per mode; full access;\n  more writable folders (`--add-dir`); Git check\n- **Advanced** — `-c` overrides (comments allowed, bad lines reported), reply\n  schema (`--output-schema`), feature flags (`--enable` / `--disable`), local\n  model (`--oss`, `--local-provider`), ephemeral sessions (`--ephemeral`),\n  environment variables\n- **Customize** — quick actions, slash commands and profiles as one-line\n  entries (pre-filled; edit freely)\n\n```text\nQuick action   Label | prompt                         ({{selection}} {{file}} {{clipboard}})\nCommand        name | description | prompt            ($ARGUMENTS or {{args}})\nProfile        Label | mode=read-only | effort=high | anySettingKey=value\n```\n\nBuilt in: the profiles *Careful* (read only, high effort) and *Build*.\n*Full access* in a profile still needs the setting that allows it.\n\nEvery message runs with `--color never`. Exec mode has no `--search` flag, so\nweb search is the `web_search` config key.\n\n## Project\n\n- **Project type** `ChatGPT Codex` — detected by `AGENTS.md` or `.codex/`, with the\n  tasks *Start Codex*, *Resume last session*, *Sign in*,\n  *Show MCP servers* and *Install Codex*\n- **Template** `AGENTS.md` with commands and conventions, an example prompt in `.codex/prompts/` and a project `.codex/config.toml`\n\n## Requirements\n\n```sh\nnpm install -g @openai/codex\ncodex login\n```\n\nThe extension ships executable code that must be confirmed on installation.\nIt only starts the program you have installed.\n",
  "settings": [
    {
      "key": "codexPath",
      "label": "Path to codex",
      "type": "path",
      "pathKind": "file",
      "section": "Program",
      "default": "",
      "placeholder": "search automatically",
      "hint": "Leave empty to find codex on the PATH and in the usual folders."
    },
    {
      "key": "profile",
      "label": "Profile from config.toml",
      "type": "text",
      "section": "Program",
      "default": "",
      "placeholder": "none",
      "hint": "A profile that applies to every message: a [profiles.<name>] table in ~/.codex/config.toml or a ~/.codex/<name>.config.toml file. /profiles in the chat lists what Codex found."
    },
    {
      "key": "model",
      "label": "Default model",
      "type": "text",
      "section": "Model",
      "default": "",
      "placeholder": "as in config.toml",
      "hint": "Applies while \"Default\" is chosen in the chat — e.g. gpt-5-codex. The chat picker comes from Codex itself."
    },
    {
      "key": "modelSource",
      "label": "Model list from",
      "type": "select",
      "section": "Model",
      "default": "auto",
      "hint": "\"Automatic\" reads ~/.codex/models_cache.json and asks codex app-server when the file is missing or you reload.",
      "choices": [
        {
          "value": "auto",
          "label": "Automatic (cache, else CLI)"
        },
        {
          "value": "cache",
          "label": "models_cache.json only"
        },
        {
          "value": "cli",
          "label": "Always codex app-server"
        }
      ]
    },
    {
      "key": "showLegacyModels",
      "label": "Offer older and hidden models",
      "type": "toggle",
      "section": "Model",
      "default": "false",
      "hint": "Also adds models that Codex hides in its own list."
    },
    {
      "key": "modelCacheMinutes",
      "label": "CLI-Cache model list (minutes)",
      "type": "number",
      "section": "Model",
      "default": "60",
      "min": 0,
      "max": 10080,
      "when": "modelSource=cli"
    },
    {
      "key": "extraModels",
      "label": "More models",
      "type": "textarea",
      "section": "Model",
      "rows": 2,
      "default": "",
      "placeholder": "gpt-5-codex | GPT-5 Codex (pinned)",
      "hint": "In addition to the Codex list — one model ID per line, optionally with \"| Display name\"."
    },
    {
      "key": "reasoningEffort",
      "label": "Default reasoning effort",
      "type": "select",
      "section": "Model",
      "default": "auto",
      "choices": [
        {
          "value": "auto",
          "label": "As in config.toml"
        },
        {
          "value": "none",
          "label": "None"
        },
        {
          "value": "minimal",
          "label": "Minimal"
        },
        {
          "value": "low",
          "label": "Low"
        },
        {
          "value": "medium",
          "label": "Medium"
        },
        {
          "value": "high",
          "label": "High"
        },
        {
          "value": "xhigh",
          "label": "Very high"
        },
        {
          "value": "max",
          "label": "Maximum"
        }
      ],
      "hint": "Applies while no effort is chosen in the chat. In the chat it can be set per model — only the levels the model supports are offered."
    },
    {
      "key": "reasoningSummary",
      "label": "Reasoning summary",
      "type": "select",
      "section": "Model",
      "default": "default",
      "choices": [
        {
          "value": "default",
          "label": "As in config.toml"
        },
        {
          "value": "auto",
          "label": "Automatic"
        },
        {
          "value": "concise",
          "label": "Concise"
        },
        {
          "value": "detailed",
          "label": "Detailed"
        },
        {
          "value": "none",
          "label": "None"
        }
      ]
    },
    {
      "key": "verbosity",
      "label": "Answer verbosity",
      "type": "select",
      "section": "Model",
      "default": "auto",
      "choices": [
        {
          "value": "auto",
          "label": "As in config.toml"
        },
        {
          "value": "low",
          "label": "Concise"
        },
        {
          "value": "medium",
          "label": "Medium"
        },
        {
          "value": "high",
          "label": "Detailed"
        }
      ]
    },
    {
      "key": "hideReasoning",
      "label": "Hide reasoning",
      "type": "toggle",
      "section": "Model",
      "default": "false"
    },
    {
      "key": "customInstructions",
      "label": "Instructions for every chat",
      "type": "textarea",
      "section": "Instructions",
      "rows": 4,
      "default": "",
      "placeholder": "Answer briefly. Prefer small, reviewable changes.",
      "hint": "Added to AGENTS.md as developer instructions. A system prompt set for one chat is added after it."
    },
    {
      "key": "instructionsVia",
      "label": "Hand instructions to Codex",
      "type": "select",
      "section": "Instructions",
      "default": "config",
      "choices": [
        {
          "value": "config",
          "label": "As developer_instructions (-c)"
        },
        {
          "value": "prompt",
          "label": "In front of each message"
        }
      ],
      "hint": "Exec mode has no system-prompt flag. \"As developer_instructions\" uses the config key of that name; use \"In front of each message\" if your Codex version ignores it."
    },
    {
      "key": "webSearch",
      "label": "Web search",
      "type": "select",
      "section": "Tools",
      "default": "auto",
      "choices": [
        {
          "value": "auto",
          "label": "As in config.toml"
        },
        {
          "value": "live",
          "label": "Live"
        },
        {
          "value": "cached",
          "label": "From the cache"
        },
        {
          "value": "disabled",
          "label": "Off"
        }
      ],
      "hint": "Sets web_search for the session (`--search` exists only in interactive Codex)."
    },
    {
      "key": "networkAccess",
      "label": "Network in \"In project\" sandbox mode",
      "type": "select",
      "section": "Tools",
      "default": "auto",
      "hint": "Whether commands in the \"In project\" mode may access the network (npm install, curl …).",
      "choices": [
        {
          "value": "auto",
          "label": "As in config.toml"
        },
        {
          "value": "true",
          "label": "Allowed"
        },
        {
          "value": "false",
          "label": "Blocked"
        }
      ]
    },
    {
      "key": "excludeTmp",
      "label": "Keep /tmp and $TMPDIR out of the writable roots",
      "type": "toggle",
      "section": "Tools",
      "default": "false",
      "hint": "In \"In project\" mode Codex may also write to the temporary folders; this switches that off (sandbox_workspace_write.exclude_*)."
    },
    {
      "key": "approvalPolicy",
      "label": "Approval policy (all modes)",
      "type": "select",
      "section": "Permissions",
      "default": "never",
      "hint": "Codex cannot ask questions in the chat — what it may do is set by the sandbox mode. \"Never ask\" keeps Codex from waiting for an answer. The per-mode settings below override this.",
      "choices": [
        {
          "value": "never",
          "label": "Never ask"
        },
        {
          "value": "on-failure",
          "label": "On failure"
        },
        {
          "value": "on-request",
          "label": "On the model's request"
        },
        {
          "value": "untrusted",
          "label": "For untrusted commands"
        },
        {
          "value": "auto",
          "label": "As in config.toml"
        }
      ]
    },
    {
      "key": "approvalReadOnly",
      "label": "Approvals in \"Read only\"",
      "type": "select",
      "section": "Permissions",
      "default": "default",
      "choices": [
        {
          "value": "default",
          "label": "As the general policy"
        },
        {
          "value": "never",
          "label": "Never ask"
        },
        {
          "value": "on-failure",
          "label": "On failure"
        },
        {
          "value": "on-request",
          "label": "On the model's request"
        },
        {
          "value": "untrusted",
          "label": "For untrusted commands"
        }
      ]
    },
    {
      "key": "approvalWorkspace",
      "label": "Approvals in \"In project\"",
      "type": "select",
      "section": "Permissions",
      "default": "default",
      "choices": [
        {
          "value": "default",
          "label": "As the general policy"
        },
        {
          "value": "never",
          "label": "Never ask"
        },
        {
          "value": "on-failure",
          "label": "On failure"
        },
        {
          "value": "on-request",
          "label": "On the model's request"
        },
        {
          "value": "untrusted",
          "label": "For untrusted commands"
        }
      ]
    },
    {
      "key": "approvalFull",
      "label": "Approvals in \"Full access\"",
      "type": "select",
      "section": "Permissions",
      "default": "default",
      "choices": [
        {
          "value": "default",
          "label": "As the general policy"
        },
        {
          "value": "never",
          "label": "Never ask"
        },
        {
          "value": "on-failure",
          "label": "On failure"
        },
        {
          "value": "on-request",
          "label": "On the model's request"
        },
        {
          "value": "untrusted",
          "label": "For untrusted commands"
        }
      ]
    },
    {
      "key": "allowFullAccess",
      "label": "Allow \"Full access\" mode",
      "type": "toggle",
      "section": "Permissions",
      "default": "false",
      "hint": "Warning: without a sandbox Codex can change any file and run any command. Use only in isolated environments."
    },
    {
      "key": "additionalDirectories",
      "label": "More writable folders",
      "type": "textarea",
      "section": "Permissions",
      "rows": 2,
      "default": "",
      "placeholder": "~/shared-lib",
      "hint": "One per line."
    },
    {
      "key": "skipGitRepoCheck",
      "label": "Also work outside Git repositories",
      "type": "toggle",
      "section": "Permissions",
      "default": "true"
    },
    {
      "key": "configOverrides",
      "label": "More configuration (-c)",
      "type": "textarea",
      "section": "Advanced",
      "rows": 3,
      "default": "",
      "placeholder": "# model_verbosity=\"low\"\nsandbox_workspace_write.network_access=true\nshell_environment_policy.inherit=\"all\"",
      "hint": "One key=value per line in TOML format, as with `codex -c`. Lines starting with # are comments; lines that are not key=value are ignored (and reported in the chat)."
    },
    {
      "key": "env",
      "label": "Environment variables",
      "type": "textarea",
      "section": "Advanced",
      "rows": 3,
      "default": "",
      "placeholder": "OPENAI_API_KEY=…\nHTTPS_PROXY=http://proxy:3128",
      "hint": "KEY=VALUE, one per line."
    },
    {
      "key": "ephemeral",
      "label": "Ephemeral sessions",
      "type": "toggle",
      "section": "Advanced",
      "default": "false",
      "hint": "--ephemeral: Codex keeps no session file. The chat cannot be resumed later, and Fork and Export do not work."
    },
    {
      "key": "outputSchema",
      "label": "Reply schema (--output-schema)",
      "type": "path",
      "pathKind": "file",
      "section": "Advanced",
      "default": "",
      "placeholder": "none",
      "hint": "A JSON Schema file; Codex's final answer then follows that shape."
    },
    {
      "key": "features",
      "label": "Feature flags",
      "type": "textarea",
      "section": "Advanced",
      "rows": 2,
      "default": "",
      "placeholder": "unified_exec\n-web_search_request",
      "hint": "One per line: a name enables the feature (--enable), a leading - disables it (--disable). `codex features list` shows them."
    },
    {
      "key": "oss",
      "label": "Use a local model (--oss)",
      "type": "toggle",
      "section": "Advanced",
      "default": "false",
      "hint": "Runs against a local open-source provider instead of OpenAI."
    },
    {
      "key": "localProvider",
      "label": "Local provider",
      "type": "select",
      "section": "Advanced",
      "default": "default",
      "choices": [
        {
          "value": "default",
          "label": "As in config.toml"
        },
        {
          "value": "ollama",
          "label": "Ollama"
        },
        {
          "value": "lmstudio",
          "label": "LM Studio"
        }
      ],
      "when": "oss=true"
    },
    {
      "key": "quickActionsText",
      "label": "Quick actions",
      "type": "textarea",
      "section": "Customize",
      "rows": 7,
      "default": "# Label | prompt   ({{selection}}, {{file}}, {{clipboard}}; \\n is a line break)\nExplain selection | Explain {{selection}} from {{file}} step by step.\nFix this file | Find and fix bugs in {{file}}. Explain each change briefly.\nWrite tests | Write tests for {{selection}} in {{file}} following the project's conventions, then run them.\nReview changes | Review the uncommitted changes in this repository for bugs, risky changes and missing tests.\nCommit message | Read the staged changes (git diff --staged) and write a concise conventional commit message. Do not commit.",
      "hint": "Buttons above the message box. One per line: Label | prompt."
    },
    {
      "key": "customCommandsText",
      "label": "Slash commands",
      "type": "textarea",
      "section": "Customize",
      "rows": 7,
      "default": "# name | description | prompt   ($ARGUMENTS or {{args}} is what follows the command)\nexplain | Explain code or a concept | Explain $ARGUMENTS in simple terms, with an example from this project.\ntests | Write tests | Write tests for $ARGUMENTS and run them. Follow the existing test style.\nfix | Fix a problem | Find the cause of this problem and fix it: $ARGUMENTS\ndocs | Document code | Write or improve documentation comments for $ARGUMENTS.\nrefactor | Refactor | Refactor $ARGUMENTS for readability without changing behaviour; run the tests afterwards.",
      "hint": "One per line: name | description | prompt. /review, /init, /status, /mcp and your ~/.codex/prompts are offered besides."
    },
    {
      "key": "profilesText",
      "label": "Profiles",
      "type": "textarea",
      "section": "Customize",
      "rows": 5,
      "default": "# Label | mode=… | model=… | effort=… | anySettingKey=value\nQuick | mode=workspace-write | effort=low | reasoningSummary=none\nOffline | mode=workspace-write | networkAccess=false | webSearch=disabled\nFull access (needs the setting) | mode=danger-full-access | effort=medium",
      "hint": "Presets for mode, model, effort and any setting of this extension. Full access works only when it is allowed above."
    }
  ],
  "pages": [],
  "agents": [
    {
      "id": "codex",
      "name": "Codex",
      "description": "Ask Codex about your project: explain code, find bugs, make changes. What Codex may do is set by the mode.",
      "icon": "Cx",
      "location": "right",
      "images": true,
      "placeholder": "Message Codex …  (Enter to send, Shift+Enter for a new line, @ files)",
      "modelSetting": "model",
      "models": [],
      "modes": [
        {
          "id": "workspace-write",
          "label": "In project",
          "description": "Reads everything, changes and runs only in the project folder"
        },
        {
          "id": "read-only",
          "label": "Read only",
          "description": "Reads and plans, changes nothing"
        },
        {
          "id": "danger-full-access",
          "label": "Full access",
          "description": "No sandbox — must be enabled in the settings"
        }
      ],
      "suggestions": [
        "Explain the structure of this project.",
        "Find possible bugs in the open file.",
        "Write tests for the current selection.",
        "/review",
        "/init"
      ],
      "capabilities": {
        "fork": true,
        "rename": true,
        "delete": true,
        "export": true,
        "usage": true
      },
      "systemPrompt": true,
      "quickActionsSetting": "quickActionsText",
      "customCommandsSetting": "customCommandsText",
      "profilesSetting": "profilesText",
      "profiles": [
        {
          "id": "careful",
          "label": "Careful",
          "mode": "read-only",
          "effort": "high",
          "settings": {
            "approvalPolicy": "never"
          }
        },
        {
          "id": "build",
          "label": "Build",
          "mode": "workspace-write"
        }
      ]
    }
  ],
  "views": [],
  "commands": [],
  "code": {
    "main": "import { createRequire as __lumenRequire } from 'node:module'; const require = __lumenRequire(import.meta.url);\nimport{spawn as Qe}from\"node:child_process\";import rt from\"node:fs/promises\";import qe from\"node:os\";import Jt from\"node:path\";import zt from\"node:readline\";import U from\"node:fs\";import O from\"node:fs/promises\";import w from\"node:path\";import lt from\"node:readline\";import{spawn as Yt}from\"node:child_process\";import ct from\"node:fs\";import R from\"node:os\";import g from\"node:path\";var Kt=6e3,L=t=>String(t??\"\").split(/\\r?\\n/).map(e=>e.trim()).filter(Boolean),T=t=>L(t).filter(e=>!e.startsWith(\"#\")),p=t=>t===\"true\",D=t=>t.replace(/^~(?=\\/|$)/,R.homedir()),u=()=>process.env.CODEX_HOME||g.join(R.homedir(),\".codex\");function h(t){return`\"${String(t).replace(/\\\\/g,\"\\\\\\\\\").replace(/\"/g,'\\\\\"').replace(/\\r/g,\"\").replace(/\\n/g,\"\\\\n\").replace(/\\t/g,\"\\\\t\")}\"`}function S(t){let e={};for(let n of String(t??\"\").split(/\\r?\\n/)){let o=/^\\s*([A-Za-z_][A-Za-z0-9_]*)\\s*=\\s*(.*)$/.exec(n);o&&(e[o[1]]=o[2])}return e}function I(t,e=Kt){let n=String(t??\"\");return n.length<=e?n:`${n.slice(0,e)}\n\\u2026 (${n.length-e} more characters)`}function _(t){let e=process.platform===\"win32\"?\"codex.cmd\":\"codex\";if(t&&t!==\"codex\"){if(!ct.existsSync(t))throw new Error(`codex not found at ${t}`);return t}let n=R.homedir(),o=[...(process.env.PATH??\"\").split(g.delimiter),g.join(n,\".local\",\"bin\"),g.join(n,\".npm-global\",\"bin\"),g.join(n,\".bun\",\"bin\"),g.join(n,\".cargo\",\"bin\"),\"/usr/local/bin\",\"/opt/homebrew/bin\"];for(let r of o.filter(Boolean)){let s=g.join(r,e);if(ct.existsSync(s))return s}throw new Error(\"Codex is not installed. Install it (npm install -g @openai/codex), sign in with `codex login`, or set its path under Settings \\u2192 Extensions \\u2192 ChatGPT Codex.\")}function m(t,e,{cwd:n,input:o,timeout:r=3e4}={}){return new Promise((s,a)=>{let i=Yt(_(t.codexPath),e,{cwd:n,env:{...process.env,...S(t.env)},shell:process.platform===\"win32\",windowsHide:!0}),c=[],l=[],f=setTimeout(()=>i.kill(\"SIGTERM\"),r);i.stdout.on(\"data\",d=>c.push(d)),i.stderr.on(\"data\",d=>l.push(d)),i.once(\"error\",d=>{clearTimeout(f),a(d)}),i.once(\"close\",d=>{clearTimeout(f),s({code:d,stdout:Buffer.concat(c).toString(\"utf8\"),stderr:Buffer.concat(l).toString(\"utf8\")})}),i.stdin.on(\"error\",()=>{}),i.stdin.end(o??\"\")})}function x(t){let e=[],n=\"\",o=\"\",r=!1,s=String(t??\"\");for(let a=0;a<s.length;a++){let i=s[a];if(i===\"\\\\\"&&o!==\"'\"&&a+1<s.length){n+=s[++a],r=!0;continue}if(o){if(i===o){o=\"\";continue}n+=i;continue}if(i==='\"'||i===\"'\"){o=i,r=!0;continue}if(/\\s/.test(i)){r&&(e.push(n),n=\"\",r=!1);continue}n+=i,r=!0}return r&&e.push(n),e}var Qt=300,qt=512*1024,dt=\"sessionTitles\",W=null,G=new Map,ut=t=>{W=t},te=()=>w.join(u(),\"sessions\");async function ft(t,e,n){let o=await O.readdir(t,{withFileTypes:!0}).catch(()=>[]);for(let r of o){let s=w.join(t,r.name);r.isDirectory()&&e<3&&await ft(s,e+1,n),r.isFile()&&r.name.endsWith(\".jsonl\")&&n.push(s)}}async function pt(){let t=[];return await ft(te(),0,t),t.sort((e,n)=>w.basename(n).localeCompare(w.basename(e)))}async function mt(t){if(!t)return\"\";let e=G.get(t);if(e&&U.existsSync(e))return e;let n=(await pt()).find(o=>o.endsWith(`-${t}.jsonl`));return n&&G.set(t,n),n??\"\"}function C(t){try{return JSON.parse(t)}catch{return null}}function ht(t){return Array.isArray(t.content)?t.content.map(e=>e.text??\"\").join(\" \").trim():\"\"}function ee(t){let e=t?.payload??t;if(e?.type===\"user_message\"&&typeof e.message==\"string\")return e.message;if(e?.type!==\"message\"||e.role!==\"user\")return\"\";let n=ht(e);return n.startsWith(\"<\")?\"\":n}async function ne(t){let e=U.createReadStream(t,{encoding:\"utf8\",end:262144}),n=lt.createInterface({input:e,crlfDelay:1/0}),o={id:\"\",cwd:\"\",title:\"\"};try{for await(let r of n){let s=C(r),a=s?.payload??{};if(!o.id&&(s?.type===\"session_meta\"||a.id)&&typeof a.id==\"string\"&&(o.id=a.id,o.cwd=typeof a.cwd==\"string\"?a.cwd:\"\"),o.title||=ee(s),o.id&&o.title)break}}finally{n.close(),e.destroy()}return o}async function gt(){let t=await O.readFile(w.join(u(),\"session_index.jsonl\"),\"utf8\").catch(()=>\"\"),e=new Map;for(let n of t.split(`\n`)){let o=C(n);o?.id&&o.thread_name&&e.set(o.id,o.thread_name)}return e}var H=()=>W?.get(dt,{})??{},j=t=>H()[t]??\"\";function B(t,e){let n={...H()};e&&(n[t]=e),e||delete n[t],W?.set(dt,n)}function wt(t){G.delete(t),B(t,\"\")}async function xt(t){let e=(await pt()).slice(0,Qt),n=await gt(),o=H(),r=[];for(let s of e){let a=await ne(s).catch(()=>null);if(!a?.id||w.resolve(a.cwd||\"/\")!==w.resolve(t))continue;let i=await O.stat(s).catch(()=>null),c=o[a.id]||n.get(a.id)||a.title||a.id;if(r.push({id:a.id,title:c.split(`\n`)[0].slice(0,80),updatedAt:i?.mtimeMs}),r.length>=40)break}return r.sort((s,a)=>(a.updatedAt??0)-(s.updatedAt??0))}async function J(t){return j(t)?j(t):(await gt()).get(t)??\"\"}async function oe(t){let e=await O.open(t,\"r\");try{let{size:n}=await e.stat(),o=Math.max(0,n-qt),r=Buffer.alloc(n-o);await e.read(r,0,r.length,o);let s=r.toString(\"utf8\").split(`\n`);return o>0?s.slice(1):s}finally{await e.close()}}var re=t=>!!(t?.primary||t?.secondary);async function yt(t){let e=await mt(t);if(!e)return null;let n=await oe(e).catch(()=>[]),o=null;for(let r=n.length-1;r>=0;r--){let s=C(n[r])?.payload;if(!(s?.type!==\"token_count\"||!s.info)&&(o??={contextUsed:s.info.last_token_usage?.total_tokens,contextTotal:s.info.model_context_window},re(s.rate_limits)))return{...o,limits:s.rate_limits}}return o}function se(t){let e=t?.payload;if(t?.type!==\"response_item\"||e?.type!==\"message\"||e.role!==\"user\"&&e.role!==\"assistant\")return null;let n=ht(e);return!n||e.role===\"user\"&&n.startsWith(\"<\")?null:{role:e.role,text:n}}async function ie(t){let e=lt.createInterface({input:U.createReadStream(t,{encoding:\"utf8\"}),crlfDelay:1/0}),n=[];for await(let o of e){let r=se(C(o));r&&n.push(r)}return n}async function St(t,e){let n=await mt(t);if(!n)return null;let o=await ie(n),r=`# ${e||`Codex session ${t}`}`,s=o.map(a=>`## ${a.role===\"user\"?\"You\":\"Codex\"}\n\n${a.text}`);return[r,`Session \\`${t}\\``,...s].join(`\n\n`)+`\n`}import ae from\"node:fs\";import ce from\"node:path\";var le=new Set([\"read-only\",\"workspace-write\",\"danger-full-access\"]),_t=new Set([\"never\",\"on-request\",\"on-failure\",\"untrusted\"]),kt=new Set([\"none\",\"minimal\",\"low\",\"medium\",\"high\",\"xhigh\",\"max\"]),de=new Set([\"auto\",\"concise\",\"detailed\",\"none\"]),ue=new Set([\"low\",\"medium\",\"high\"]),fe=new Set([\"lmstudio\",\"ollama\"]),pe={\"read-only\":\"approvalReadOnly\",\"workspace-write\":\"approvalWorkspace\",\"danger-full-access\":\"approvalFull\"},vt=[...kt];function z(t,e){if(!le.has(t))throw new Error(`Unknown mode: ${t}`);if(t===\"danger-full-access\"&&!p(e.allowFullAccess))throw new Error(\"\\u201CFull access\\u201D is switched off. Enable it under Settings \\u2192 Extensions \\u2192 ChatGPT Codex first.\");return t}function me(t){let e=t.effort||t.settings.reasoningEffort;if(!(!e||e===\"auto\")){if(!kt.has(e))throw new Error(`Unknown reasoning effort: ${e}`);return e}}function k(t,e){let n=e[pe[t]];return _t.has(n)?n:_t.has(e.approvalPolicy)?e.approvalPolicy:\"\"}function Z(t){let e=[],n=[];for(let o of T(t)){if(/^[A-Za-z_][\\w.-]*\\s*=\\s*\\S/.test(o)){e.push(o);continue}n.push(o)}return{valid:e,invalid:n}}function V(t){return t?ae.existsSync(ce.join(u(),`${t}.config.toml`))?[\"--profile\",t]:[\"--config\",`profile=${h(t)}`]:[]}function he(t){return T(t).flatMap(e=>e.startsWith(\"-\")?[\"--disable\",e.slice(1).trim()]:[\"--enable\",e.replace(/^\\+/,\"\").trim()])}function X(t){return[t.settings.customInstructions,t.systemPrompt].map(n=>String(n??\"\").trim()).filter(Boolean).join(`\n\n`)}function ge(t,e){let{model:n,settings:o}=t,r=[],s=n||(o.model!==\"auto\"?o.model:\"\");return s&&r.push(\"--model\",s),e&&r.push(\"--config\",`model_reasoning_effort=${h(e)}`),de.has(o.reasoningSummary)&&r.push(\"--config\",`model_reasoning_summary=${h(o.reasoningSummary)}`),ue.has(o.verbosity)&&r.push(\"--config\",`model_verbosity=${h(o.verbosity)}`),p(o.hideReasoning)&&r.push(\"--config\",\"hide_agent_reasoning=true\"),p(o.oss)&&(r.push(\"--oss\"),fe.has(o.localProvider)&&r.push(\"--local-provider\",o.localProvider)),r}function we(t){let{cwd:e,mode:n,settings:o}=t,r=[\"--sandbox\",z(n,o),\"--cd\",e];for(let a of T(o.additionalDirectories))r.push(\"--add-dir\",D(a));(o.networkAccess===\"true\"||o.networkAccess===\"false\")&&r.push(\"--config\",`sandbox_workspace_write.network_access=${o.networkAccess}`),p(o.excludeTmp)&&r.push(\"--config\",\"sandbox_workspace_write.exclude_slash_tmp=true\",\"--config\",\"sandbox_workspace_write.exclude_tmpdir_env_var=true\"),o.webSearch&&o.webSearch!==\"auto\"&&r.push(\"--config\",`web_search=${h(o.webSearch)}`);let s=k(n,o);return s&&r.push(\"--config\",`approval_policy=${h(s)}`),r}function bt(t){let{settings:e}=t,n=[\"exec\",\"--experimental-json\",\"--color\",\"never\"];return n.push(...Z(e.configOverrides).valid.flatMap(o=>[\"--config\",o])),n.push(...V(e.profile)),n.push(...ge(t,me(t))),n.push(...we(t)),e.skipGitRepoCheck!==\"false\"&&n.push(\"--skip-git-repo-check\"),p(e.ephemeral)&&n.push(\"--ephemeral\"),e.outputSchema&&n.push(\"--output-schema\",D(e.outputSchema)),n.push(...he(e.features)),n}function $t(t,e,n={}){let o=bt(t),r=t.settings.instructionsVia===\"prompt\"?\"\":X(t);if(r&&o.push(\"--config\",`developer_instructions=${h(r)}`),n.kind===\"review\")return o.push(\"review\",...n.target),n.prompt?[...o,n.prompt]:o;t.sessionId&&o.push(\"resume\",t.sessionId);for(let s of e)o.push(\"--image\",s);return o}function At(t){return[...bt(t),\"fork\",t.sessionId]}function Et(t,e=[],n=\"\"){let o=e.filter(s=>s.path&&!/\\.(png|jpe?g|gif|webp)$/i.test(s.path)),r=o.length?`${t}\n\nFiles: ${o.map(s=>s.path).join(\", \")}`:t;return n?`<instructions>\n${n}\n</instructions>\n\n${r}`:r}function M(t){if(!t.sessionId)throw new Error(\"This chat has no Codex session yet \\u2014 send a message first.\");return t.sessionId}var xe=t=>t.toLowerCase().replace(/[^a-z0-9]+/g,\"-\").replace(/^-|-$/g,\"\").slice(0,40)||\"session\";async function ye(t,e){let n=M(t);e({kind:\"status\",text:\"Forking the session \\u2026\"});let o={...t.settings,ephemeral:\"false\"},r=At({...t,settings:o,mode:t.mode||\"workspace-write\",sessionId:n}),s=await m(o,r,{cwd:t.cwd,timeout:6e4}),a=s.stdout.split(`\n`).map(c=>{try{return JSON.parse(c)}catch{return null}}).find(c=>c?.type===\"thread.started\");if(!a?.thread_id)throw new Error(s.stderr.trim().split(`\n`).slice(-3).join(`\n`)||\"codex did not report the forked session\");let i=await J(n);return{sessionId:a.thread_id,title:i?`${i} (fork)`:void 0,notice:\"Continuing in a fork of the session.\"}}async function Se(t){let e=M(t),n=await m(t.settings,[\"delete\",\"--force\",e],{cwd:t.cwd});if(n.code!==0)throw new Error(`${n.stdout}${n.stderr}`.trim().split(`\n`).slice(-2).join(`\n`)||\"codex could not delete the session\");return wt(e),{deleted:!0,notice:\"Session deleted.\"}}function _e(t){let e=M(t),n=String(t.argument??\"\").trim();return B(e,n),{title:n||void 0}}async function ke(t){let e=M(t),n=await J(e),o=await St(e,n);if(o===null)throw new Error(\"Codex keeps no session file for this chat (ephemeral session, or not written yet).\");return{export:{fileName:`codex-${xe(j(e)||n||e)}.md`,text:o}}}var ve={fork:ye,delete:Se,rename:_e,export:ke};async function Tt(t,e){let n=ve[t.action];if(!n)throw new Error(`Codex does not support \\u201C${t.action}\\u201D in exec mode.`);return n(t,e)}import b from\"node:fs\";import nt from\"node:path\";var be=new Set([\"add\",\"remove\",\"get\"]);function $e(t){let e=t.transport??{},n=e.type===\"stdio\"?[e.command,...e.args??[]].join(\" \"):e.url??e.type??\"\",o=t.enabled===!1?\"off\":\"on\";return`- ${t.name} (${o}, ${e.type??\"?\"}) ${n}`.trimEnd()}async function Ae(t,e){let n=await m(t,[\"mcp\",\"list\",\"--json\"],{cwd:e});if(n.code!==0)throw new Error(n.stderr.trim()||\"codex mcp list failed\");let o=JSON.parse(n.stdout||\"[]\");return o.length?[\"MCP servers:\",...o.map($e)].join(`\n`):\"No MCP servers are configured. Add one with `/mcp add <name> -- <command> [args\\u2026]` or `/mcp add <name> --url <url>`.\"}async function It(t,e,n){let[o=\"list\",...r]=x(n);if(o===\"list\")return Ae(t,e);if(!be.has(o))return\"Usage: /mcp [list | get <name> | add <name> (--url <url> | -- <command> [args\\u2026]) | remove <name>]\";let s=await m(t,[\"mcp\",o,...r],{cwd:e,timeout:6e4}),a=`${s.stdout}${s.stderr}`.trim();if(s.code!==0)throw new Error(a||`codex mcp ${o} failed`);return a||`codex mcp ${o}: done`}import jt from\"node:fs/promises\";import Y from\"node:path\";var Ee=/^([A-Z][A-Z0-9_]*)=([\\s\\S]*)$/;function Te(t){let e=/^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\n?([\\s\\S]*)$/.exec(t);if(!e)return{meta:{},body:t};let n={};for(let o of e[1].split(/\\r?\\n/)){let r=/^([\\w-]+)\\s*:\\s*(.*)$/.exec(o.trim());r&&(n[r[1]]=r[2].replace(/^[\"']|[\"']$/g,\"\"))}return{meta:n,body:e[2]}}async function Ot(t,e){let n=await jt.readdir(t,{withFileTypes:!0}).catch(()=>[]),o=[];for(let r of n){if(!r.isFile()||!r.name.endsWith(\".md\"))continue;let s=await jt.readFile(Y.join(t,r.name),\"utf8\").catch(()=>\"\"),{meta:a,body:i}=Te(s);o.push({name:`prompts:${r.name.slice(0,-3)}`,description:a.description||void 0,argumentHint:a[\"argument-hint\"]||void 0,source:e,body:i})}return o}async function K(t){let e=await Ot(Y.join(t,\".codex\",\"prompts\"),\"project\"),n=await Ot(Y.join(u(),\"prompts\"),\"user\"),o=new Set(e.map(r=>r.name));return[...e,...n.filter(r=>!o.has(r.name))]}function Ie(t,e){let n=[],o={};for(let r of x(e)){let s=Ee.exec(r);if(s){o[s[1]]=s[2];continue}n.push(r)}return t.replace(/\\$(\\$|ARGUMENTS|[1-9]|[A-Z][A-Z0-9_]*)/g,(r,s)=>s===\"$\"?\"$\":s===\"ARGUMENTS\"?n.join(\" \"):/^[1-9]$/.test(s)?n[Number(s)-1]??\"\":o[s]??r)}async function Ct(t,e,n){let o=(await K(t)).find(r=>r.name===e);return o?Ie(o.body,n):null}import{spawn as je}from\"node:child_process\";import q from\"node:fs/promises\";import tt from\"node:path\";import Oe from\"node:readline\";var Ce=2e4,v={key:\"\",at:0,list:[]};function Me(t){if(typeof t==\"string\")return{id:t};let e=t?.effort??t?.reasoningEffort??t?.reasoning_effort??t?.id;return typeof e!=\"string\"||!e?null:{id:e,description:t.description||void 0}}var Mt=t=>Array.isArray(t)?t.map(Me).filter(Boolean):void 0;async function Q(t=!1){let e=await q.readFile(tt.join(u(),\"models_cache.json\"),\"utf8\").catch(()=>\"\");if(!e)return[];let n=JSON.parse(e);return(Array.isArray(n.models)?n.models:[]).filter(o=>o?.slug&&(t||(o.visibility??\"list\")===\"list\")).sort((o,r)=>(o.priority??1e9)-(r.priority??1e9)).map(o=>({id:o.slug,label:o.display_name||o.slug,description:[o.visibility===\"list\"||!o.visibility?\"\":\"Older model\",o.description].filter(Boolean).join(\" \\u2014 \")||void 0,efforts:Mt(o.supported_reasoning_levels),defaultEffort:o.default_reasoning_level||void 0}))}function Pe(t){let e=je(_(t.codexPath),[\"app-server\"],{env:{...process.env,...S(t.env)},shell:process.platform===\"win32\",windowsHide:!0}),n=new Map,o=0,r=i=>{for(let{reject:c}of n.values())c(i);n.clear()};e.once(\"error\",r),e.once(\"close\",i=>r(new Error(`codex app-server exited with code ${i}`))),e.stdin.on(\"error\",()=>{});let s=Oe.createInterface({input:e.stdout,crlfDelay:1/0});s.on(\"line\",i=>{let c;try{c=JSON.parse(i)}catch{return}let l=n.get(c?.id);if(l){if(n.delete(c.id),c.error){l.reject(new Error(c.error.message??\"codex app-server failed\"));return}l.resolve(c.result)}});let a=i=>e.stdin.write(`${JSON.stringify(i)}\n`);return{request(i,c){let l=++o;return new Promise((f,d)=>{n.set(l,{resolve:f,reject:d}),a({id:l,method:i,params:c})})},notify:(i,c)=>a(c?{method:i,params:c}:{method:i}),close(){s.close(),e.stdin.end(),e.kill(\"SIGTERM\")}}}async function Ne(t,e=!1){let n=Pe(t),o,r=new Promise((a,i)=>{o=setTimeout(()=>i(new Error(\"codex did not report its models in time\")),Ce)}),s=async()=>{await n.request(\"initialize\",{clientInfo:{name:\"lumen\",title:\"Lumen\",version:\"1.0.0\"}}),n.notify(\"initialized\");let a=[],i;for(let c=0;c<10;c++){let l=await n.request(\"model/list\",{...i?{cursor:i}:{},...e?{includeHidden:!0}:{}});if(a.push(...l?.data??l?.models??l?.items??[]),i=l?.nextCursor??l?.next_cursor,!i)break}return a};try{return(await Promise.race([s(),r])).filter(i=>(i?.model||i?.id||i?.slug)&&(e||!i.hidden)).map(i=>({id:i.model||i.id||i.slug,label:i.displayName||i.display_name||i.model||i.id,description:[i.hidden?\"Older model\":\"\",i.description].filter(Boolean).join(\" \\u2014 \")||void 0,efforts:Mt(i.supportedReasoningEfforts??i.supported_reasoning_levels),defaultEffort:i.defaultReasoningEffort||i.default_reasoning_level||void 0,isDefault:i.isDefault===!0}))}finally{clearTimeout(o),n.close()}}async function P(){let e=(await q.readFile(tt.join(u(),\"config.toml\"),\"utf8\").catch(()=>\"\")).split(/^\\s*\\[/m)[0];return/^\\s*model\\s*=\\s*[\"']([^\"']+)[\"']/m.exec(e)?.[1]??\"\"}function et(t){return L(t).map(e=>{let[n,o]=e.split(\"|\").map(r=>r.trim());return{id:n,label:o||n,efforts:vt.map(r=>({id:r}))}})}async function Fe(t,e){let n=t.modelSource||\"auto\",o=t.showLegacyModels===\"true\";if(n===\"cache\")return Q(o);let r=JSON.stringify([t.codexPath,t.env,o]),s=Number(t.modelCacheMinutes||60),a=v.key===r&&Date.now()-v.at<Math.max(0,s)*6e4;if(n===\"auto\"&&!e){let i=await Q(o).catch(()=>[]);if(i.length)return i}if(a&&!e&&v.list.length)return v.list;try{let i=await Ne(t,o);return v={key:r,at:Date.now(),list:i},i}catch(i){if(n===\"cli\")throw i;return console.warn(\"[codex] could not list models via codex app-server:\",i.message),Q(o)}}async function Pt({settings:t={},refresh:e=!1}={}){let n=await Fe(t,e);if(!n.some(r=>r.isDefault)){let r=await P(),s=n.find(a=>a.id===r);s&&(s.isDefault=!0)}let o=new Set(n.map(r=>r.id));return[...n,...et(t.extraModels).filter(r=>!o.has(r.id))]}async function Nt(t){let e=await q.readFile(tt.join(u(),\"models_cache.json\"),\"utf8\").catch(()=>\"\");if(!e)return 0;let n=t||await P(),o=(JSON.parse(e).models??[]).find(r=>r?.slug===n);return o?.context_window?Math.round(o.context_window*((o.effective_context_window_percent??100)/100)):0}var Ft=[\"Create an AGENTS.md file in the root of this repository: a concise contributor guide for coding agents.\",\"Inspect the project first (layout, build and test commands, code style, commit conventions) and write only what you verified.\",\"Use short sections: Project structure, Build and test commands, Coding style, Testing, Commit and PR guidelines.\",\"If AGENTS.md already exists, improve it instead of replacing what is correct.\"].join(\" \"),Re=[{name:\"review\",description:\"Review code with Codex\",argumentHint:\"[base <branch> | commit <sha> | instructions]\",source:\"builtin\"},{name:\"init\",description:\"Create or improve AGENTS.md\",source:\"builtin\"},{name:\"status\",description:\"Show model, sandbox, approvals, session and context\",source:\"builtin\"},{name:\"mcp\",description:\"List or manage MCP servers\",argumentHint:\"[list | add | remove | get]\",source:\"builtin\"},{name:\"profiles\",description:\"List the profiles of config.toml\",source:\"builtin\"}];async function Rt(t){let e=await K(t).catch(()=>[]);return[...Re,...e.map(({body:n,...o})=>o)]}function Le(t){let e=x(t),[n,o,...r]=e;return!e.length||n===\"uncommitted\"?{target:[\"--uncommitted\"]}:(n===\"base\"||n===\"--base\")&&o?{target:[\"--base\",o]}:(n===\"commit\"||n===\"--commit\")&&o?{target:[\"--commit\",o,...r.length?[\"--title\",r.join(\" \")]:[]]}:{target:[],prompt:t.trim()}}function De(){let t=new Set,e=u(),n=b.existsSync(nt.join(e,\"config.toml\"))?b.readFileSync(nt.join(e,\"config.toml\"),\"utf8\"):\"\";for(let o of n.matchAll(/^\\s*\\[profiles\\.(?:\"([^\"]+)\"|([\\w-]+))\\]/gm))t.add(o[1]??o[2]);for(let o of b.existsSync(e)?b.readdirSync(e):[]){let r=/^(.+)\\.config\\.toml$/.exec(o);r&&t.add(r[1])}return[...t].sort()}function Ge(){let t=De();return t.length?[\"Profiles (set one under Settings \\u2192 Extensions \\u2192 ChatGPT Codex \\u2192 Profile):\",...t.map(e=>`- ${e}`)].join(`\n`):\"No profiles found. Add a `[profiles.<name>]` table to ~/.codex/config.toml or a ~/.codex/<name>.config.toml file, then name it under Settings \\u2192 Extensions \\u2192 ChatGPT Codex \\u2192 Profile.\"}async function Ue(t){let{settings:e,cwd:n,mode:o,sessionId:r}=t,s=await m(e,[\"--version\"],{cwd:n}).catch(()=>null),a=await m(e,[\"login\",\"status\"],{cwd:n}).catch(()=>null),i=t.model||(e.model!==\"auto\"?e.model:\"\")||await P()||\"as in config.toml\",c=e.profile?V(e.profile).join(\" \"):\"none\";return[[\"Codex\",s?.stdout.trim()||\"unknown\"],[\"Account\",`${a?.stdout??\"\"}${a?.stderr??\"\"}`.trim().split(`\n`).pop()||\"unknown\"],[\"Model\",`${i}${t.effort?` (${t.effort})`:\"\"}`],[\"Sandbox\",z(o,e)],[\"Approvals\",k(o,e)||\"as in config.toml\"],[\"Profile\",c],[\"Folder\",n],[\"AGENTS.md\",b.existsSync(nt.join(n,\"AGENTS.md\"))?\"present\":\"missing \\u2014 /init creates it\"],[\"Session\",r||\"none yet\"]].map(([f,d])=>`${f}: ${d}`).join(`\n`)}async function Lt(t){let e=/^\\/([^\\s]+)(?:\\s+([\\s\\S]*))?$/.exec(t.text.trim());if(!e)return null;let[,n,o=\"\"]=e;if(n===\"review\")return{kind:\"review\",...Le(o)};if(n===\"init\")return{kind:\"prompt\",text:o?`${Ft}\nAlso: ${o}`:Ft};if(n===\"status\")return{kind:\"notice\",text:await Ue(t)};if(n===\"profiles\")return{kind:\"notice\",text:Ge()};if(n===\"mcp\")return{kind:\"notice\",text:await It(t.settings,t.cwd,o)};let r=n.startsWith(\"prompts:\")?await Ct(t.cwd,n,o):null;return r===null?null:{kind:\"prompt\",text:r}}import Dt from\"node:path\";var We={add:\"Write\",update:\"Edit\",delete:\"Delete\"};function He(t){return t.type===\"text\"?t.text:t.type===\"resource\"&&t.resource?.text?t.resource.text:`[${t.type??\"content\"}]`}function Be(t){if(t.error?.message)return t.error.message;let e=Array.isArray(t.result?.content)?t.result.content:[];if(e.length)return I(e.map(He).join(`\n`));let n=t.result?.structured_content??t.result?.structuredContent;return n?I(JSON.stringify(n,null,2)):\"\"}function Je(t){return t.arguments&&typeof t.arguments==\"object\"&&!Array.isArray(t.arguments)?t.arguments:t.arguments===void 0||t.arguments===null?{}:{arguments:t.arguments}}function ze(t){let e={query:t.query??t.action?.query??\"\"};return t.action?.type&&t.action.type!==\"search\"&&(e.action=t.action.type),t.action?.url&&(e.url=t.action.url),e}function ot(t){let e=Array.isArray(t.items)?t.items:[],n=e.findIndex(o=>!o.completed);return e.map((o,r)=>o.completed?{text:o.text,status:\"completed\"}:{text:o.text,status:r===n?\"in_progress\":\"pending\"})}var N=(t,e,n)=>({kind:\"assistant\",blocks:[{type:\"tool\",id:t,name:e,input:n}]});function Ze(t){return t.type===\"command_execution\"?[N(t.id,\"Shell\",{command:t.command})]:t.type===\"mcp_tool_call\"?[N(t.id,`${t.server}.${t.tool}`,Je(t))]:t.type===\"web_search\"?[N(t.id,\"WebSearch\",ze(t))]:t.type===\"todo_list\"?[{kind:\"todos\",items:ot(t)}]:[]}function Ve(t,e){return(t.changes??[]).flatMap((n,o)=>{let r=`${t.id}-${o}`,s=Dt.isAbsolute(n.path)?n.path:Dt.join(e,n.path);return[N(r,We[n.kind]??\"Edit\",{file_path:s}),{kind:\"toolResult\",toolUseId:r,text:\"\",isError:t.status===\"failed\"}]})}function Xe(t,e){if(t.type===\"agent_message\")return[{kind:\"assistant\",blocks:[{type:\"text\",text:t.text??\"\"}]}];if(t.type===\"reasoning\")return[{kind:\"assistant\",blocks:[{type:\"thinking\",text:t.text??\"\"}]}];if(t.type===\"command_execution\"){let n=t.status===\"failed\"||typeof t.exit_code==\"number\"&&t.exit_code!==0;return[{kind:\"toolResult\",toolUseId:t.id,text:I(t.aggregated_output),isError:n}]}return t.type===\"file_change\"?Ve(t,e):t.type===\"mcp_tool_call\"?[{kind:\"toolResult\",toolUseId:t.id,text:Be(t),isError:t.status===\"failed\"}]:t.type===\"web_search\"?[{kind:\"toolResult\",toolUseId:t.id,text:\"\",isError:!1}]:t.type===\"todo_list\"?[{kind:\"todos\",items:ot(t)}]:t.type===\"error\"?[{kind:\"notice\",level:\"warn\",text:t.message}]:[]}function Gt(t,e){return{inputTokens:t?.input_tokens,outputTokens:(t?.output_tokens??0)+(t?.reasoning_output_tokens??0),cacheReadTokens:t?.cached_input_tokens,cacheWriteTokens:t?.cache_write_input_tokens,durationMs:Date.now()-e}}function Ut(t,e){return t.type===\"thread.started\"?[{kind:\"session\",sessionId:t.thread_id,model:e.model,mode:e.mode,...e.sessionExtras}]:t.type===\"turn.started\"?[{kind:\"status\",text:\"\"}]:t.type===\"item.started\"?Ze(t.item):t.type===\"item.updated\"&&t.item?.type===\"todo_list\"?[{kind:\"todos\",items:ot(t.item)}]:t.type===\"item.completed\"?Xe(t.item,e.cwd):t.type===\"turn.completed\"?[{kind:\"result\",isError:!1,text:\"\",usage:Gt(t.usage,e.startedAt)}]:t.type===\"turn.failed\"?[{kind:\"result\",isError:!0,text:t.error?.message??\"The turn failed\",usage:Gt(null,e.startedAt)}]:t.type===\"error\"?[{kind:\"error\",message:t.message}]:[]}function Ye(t){return t?t%10080===0?t===10080?\"week\":`${t/10080} weeks`:t%1440===0?t===43200?\"month\":`${t/1440} d`:t%60===0?`${t/60} h`:`${t} min`:\"limit\"}function Ke(t){return[\"primary\",\"secondary\"].map(e=>t?.[e]).filter(Boolean).map(e=>({label:Ye(e.window_minutes),usedPercent:typeof e.used_percent==\"number\"?Math.min(100,Math.max(0,e.used_percent)):void 0,resetsAt:e.resets_at?e.resets_at*1e3:void 0}))}async function Wt({sessionId:t,model:e,mode:n,turn:o}){let r=t?await yt(t).catch(()=>null):null,s=r?.contextTotal||await Nt(e).catch(()=>0),a=r?.contextUsed??((o?.input_tokens??0)+(o?.output_tokens??0)||void 0),i={kind:\"usage\",model:e||void 0,mode:n};a&&(i.contextUsed=a),s&&(i.contextTotal=s);let c=Ke(r?.limits);return c.length&&(i.rateLimits=c),i}function Ht(t){let{mode:e,settings:n}=t,o=[`sandbox ${e}`],r=k(e,n);o.push(`approvals ${r||\"as in config.toml\"}`),e===\"workspace-write\"&&n.networkAccess&&n.networkAccess!==\"auto\"&&o.push(`network ${n.networkAccess===\"true\"?\"allowed\":\"blocked\"}`);let s=[{kind:\"notice\",level:\"info\",text:`Codex runs with ${o.join(\" \\xB7 \")}.`}];return e===\"danger-full-access\"&&s.push({kind:\"notice\",level:\"warn\",text:\"No sandbox: Codex can change any file and run any command.\"}),(p(n.hideReasoning)||n.reasoningSummary===\"none\")&&s.push({kind:\"notice\",level:\"info\",text:\"Reasoning summaries are switched off.\"}),p(n.ephemeral)&&s.push({kind:\"notice\",level:\"warn\",text:\"Ephemeral session: Codex keeps no session file, so it cannot be resumed later.\"}),s}function Bt(t){let e=t.replace(/^\\S+Z\\s+/,\"\").trim();return!/^WARN\\b/.test(e)||/rmcp::/.test(e)?null:{kind:\"notice\",level:\"warn\",text:e.replace(/^WARN\\s+/,\"\").slice(0,300)}}var tn={\"image/png\":\".png\",\"image/jpeg\":\".jpg\",\"image/gif\":\".gif\",\"image/webp\":\".webp\"},en=3,nn={fork:!0,rename:!0,delete:!0,export:!0,usage:!0},$=new Map;async function on(t=[]){let e=[],n=null;for(let o of t){if(o.path&&/\\.(png|jpe?g|gif|webp)$/i.test(o.path)){e.push(o.path);continue}let r=tn[o.mimeType];if(!o.data||!r)continue;n??=await rt.mkdtemp(Jt.join(qe.tmpdir(),\"lumen-codex-\"));let s=Jt.join(n,`image-${e.length+1}${r}`);await rt.writeFile(s,Buffer.from(o.data,\"base64\")),e.push(s)}return{files:e,cleanup:()=>n?rt.rm(n,{recursive:!0,force:!0}):Promise.resolve()}}function rn(t,e){let n=[],o=new Set;return zt.createInterface({input:t.stderr,crlfDelay:1/0}).on(\"line\",s=>{n.push(s);let a=o.size<en?Bt(s):null;a&&!o.has(a.text)&&(o.add(a.text),e(a))}),()=>n.slice(-12).join(`\n`).trim()}function sn(t){let{invalid:e}=Z(t.configOverrides);return e.length?{kind:\"notice\",level:\"warn\",text:`Ignored lines in \\u201CMore configuration (-c)\\u201D (use key=value): ${e.join(\", \")}`}:null}function an(t){let{cwd:e,mode:n,settings:o}=t;return{cwd:e,mode:n,model:t.model||o.model||void 0,startedAt:Date.now(),sessionId:t.sessionId,sessionExtras:{capabilities:nn}}}async function cn(t,e,n){let o=Ut(t,e),r=[];for(let s of o)r.push(s),s.kind===\"session\"&&(e.sessionId=s.sessionId,r.push(...n.sessionId?[]:Ht(n)));return t.type===\"turn.completed\"&&r.push(await Wt({sessionId:e.sessionId,model:e.model,mode:e.mode,turn:t.usage})),r}async function ln(t,e,n){let{chatId:o,attachments:r,settings:s}=t,a=_(s.codexPath),i=await on(r),c=an(t);c.sessionExtras.slashCommands=await Rt(t.cwd).catch(()=>[]);let l=Qe(a,$t(t,i.files,n.sub),{cwd:t.cwd,env:{...process.env,...S(s.env)},shell:process.platform===\"win32\",windowsHide:!0}),f={child:l,stopped:!1};$.set(o,f);let d=rn(l,e),st=new Promise((A,F)=>{l.once(\"error\",F),l.once(\"close\",(E,y)=>A({code:E,signal:y}))});st.catch(()=>{}),l.stdin?.on(\"error\",()=>{});let Zt=s.instructionsVia===\"prompt\"?X(t):\"\";l.stdin?.end(n.sub?\"\":Et(n.text,r,Zt));try{let A=sn(s);A&&e(A);let F=zt.createInterface({input:l.stdout,crlfDelay:1/0});for await(let Vt of F){let at=dn(Vt);for(let Xt of at?await cn(at,c,t):[])e(Xt)}let{code:E,signal:y}=await st;if(f.stopped||E===0&&!y)return;let it=d();throw new Error(`codex exited with ${y?`signal ${y}`:`code ${E}`}${it?`:\n${it}`:\"\"}`)}finally{$.delete(o),await i.cleanup().catch(()=>{})}}function dn(t){try{return JSON.parse(t)}catch{return null}}async function un(t,e){let n=await Lt(t);return n?n.kind===\"notice\"?(e({kind:\"notice\",level:\"info\",text:n.text}),null):n.kind===\"review\"?{sub:{kind:\"review\",target:n.target,prompt:n.prompt}}:{text:n.text}:{text:t.text}}var fn={async send(t,e){if($.has(t.chatId))throw new Error(\"Codex is still answering\");let n=await un(t,e);n&&await ln(t,e,n)},answer(){return!1},interrupt(t){let e=$.get(t);e&&(e.stopped=!0,e.child.kill(\"SIGTERM\"),setTimeout(()=>{e.child.exitCode===null&&e.child.signalCode===null&&e.child.kill(\"SIGKILL\")},3e3))},sessions:t=>xt(t),action:(t,e)=>Tt(t,e),models:t=>Pt(t).catch(e=>(console.warn(\"[codex] could not list models:\",e.message),et(t?.settings?.extraModels)))};function _o(t){return ut(t.storage),t.agents.register(\"codex\",fn),()=>{for(let e of $.values())e.stopped=!0,e.child.kill(\"SIGTERM\")}}export{_o as activate};\n"
  },
  "addon": {
    "schema": 1,
    "languages": [],
    "themes": [],
    "commands": [],
    "events": [],
    "templates": [
      {
        "id": "codex-project",
        "name": "Codex Projekt",
        "description": "AGENTS.md, an example Codex prompt and a project config.toml.",
        "kindId": "codex",
        "icon": "Cx",
        "color": "#10a37f",
        "open": "AGENTS.md",
        "next": "Start Codex from the task list; try /prompts:explain-file in the chat.",
        "fields": [
          {
            "id": "description",
            "label": "Description",
            "section": "Projekt",
            "placeholder": "What does the project do?",
            "required": false
          },
          {
            "id": "commands",
            "label": "Build and test commands",
            "section": "Projekt",
            "placeholder": "npm test",
            "required": false,
            "mono": true
          }
        ],
        "files": [
          {
            "path": "AGENTS.md",
            "content": "# {{name}}\n\n{{description}}\n\n## Commands\n\n```sh\n{{commands}}\n```\n\n## Conventions\n\n- Small, reviewable changes\n- Run the tests before finishing\n"
          },
          {
            "path": ".codex/prompts/explain-file.md",
            "content": "---\ndescription: Explain a file\nargument-hint: FILE=<path> [FOCUS=<topic>]\n---\nRead $FILE and explain what it does, how it fits into {{name}}, and anything surprising. Focus on: $FOCUS\n"
          },
          {
            "path": ".codex/config.toml",
            "content": "# Project settings for Codex (read for trusted projects).\n# model_reasoning_effort = \"medium\"\n# approval_policy = \"never\"\n\n[sandbox_workspace_write]\nnetwork_access = false\n"
          }
        ]
      }
    ],
    "projectKinds": [
      {
        "id": "codex",
        "name": "ChatGPT Codex",
        "icon": "Cx",
        "color": "#10a37f",
        "markers": [
          "AGENTS.md",
          ".codex"
        ],
        "priority": 1,
        "buildFile": "AGENTS.md",
        "tasks": [
          {
            "id": "session",
            "label": "Start Codex",
            "command": "codex",
            "args": [],
            "group": "run",
            "detail": "New session in the project folder"
          },
          {
            "id": "resume",
            "label": "Resume last session",
            "command": "codex",
            "args": [
              "resume",
              "--last"
            ],
            "group": "run"
          },
          {
            "id": "login",
            "label": "Sign in",
            "command": "codex",
            "args": [
              "login"
            ],
            "group": "other",
            "detail": "With a ChatGPT account or API key"
          },
          {
            "id": "mcp",
            "label": "Show MCP servers",
            "command": "codex",
            "args": [
              "mcp",
              "list"
            ],
            "group": "other"
          },
          {
            "id": "install",
            "label": "Install Codex",
            "command": "npm",
            "args": [
              "install",
              "-g",
              "@openai/codex"
            ],
            "group": "build",
            "detail": "Requires Node.js"
          }
        ],
        "facts": [
          {
            "label": "Instructions",
            "file": "AGENTS.md",
            "pattern": "^#\\s+(.+)$"
          }
        ]
      }
    ],
    "snippets": [],
    "id": "ext.codex",
    "name": "ChatGPT Codex",
    "version": "2.2.0",
    "description": "OpenAI Codex as a chat agent: models and effort from the Codex CLI, sandbox modes, /review, /init, /mcp and your own prompts, session fork, export and delete, context meter, profiles and quick actions. Ships executable code.",
    "author": "Lumen",
    "icon": "Cx",
    "color": "#10a37f",
    "category": "tool"
  }
}
