ccproxy-api 0.1.5__py3-none-any.whl → 0.1.7__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ccproxy/_version.py +2 -2
- ccproxy/adapters/codex/__init__.py +11 -0
- ccproxy/adapters/openai/models.py +1 -1
- ccproxy/adapters/openai/response_adapter.py +355 -0
- ccproxy/adapters/openai/response_models.py +178 -0
- ccproxy/api/app.py +31 -3
- ccproxy/api/dependencies.py +1 -8
- ccproxy/api/middleware/errors.py +15 -7
- ccproxy/api/routes/codex.py +1251 -0
- ccproxy/api/routes/health.py +228 -3
- ccproxy/auth/openai/__init__.py +13 -0
- ccproxy/auth/openai/credentials.py +166 -0
- ccproxy/auth/openai/oauth_client.py +334 -0
- ccproxy/auth/openai/storage.py +184 -0
- ccproxy/claude_sdk/options.py +1 -1
- ccproxy/cli/commands/auth.py +398 -1
- ccproxy/cli/commands/serve.py +3 -1
- ccproxy/config/claude.py +1 -1
- ccproxy/config/codex.py +100 -0
- ccproxy/config/scheduler.py +8 -8
- ccproxy/config/settings.py +19 -0
- ccproxy/core/codex_transformers.py +389 -0
- ccproxy/core/http_transformers.py +153 -2
- ccproxy/data/claude_headers_fallback.json +37 -0
- ccproxy/data/codex_headers_fallback.json +14 -0
- ccproxy/models/detection.py +82 -0
- ccproxy/models/requests.py +22 -0
- ccproxy/models/responses.py +16 -0
- ccproxy/scheduler/manager.py +2 -2
- ccproxy/scheduler/tasks.py +105 -65
- ccproxy/services/claude_detection_service.py +7 -33
- ccproxy/services/codex_detection_service.py +252 -0
- ccproxy/services/proxy_service.py +530 -0
- ccproxy/utils/model_mapping.py +7 -5
- ccproxy/utils/startup_helpers.py +205 -12
- ccproxy/utils/version_checker.py +6 -0
- ccproxy_api-0.1.7.dist-info/METADATA +615 -0
- {ccproxy_api-0.1.5.dist-info → ccproxy_api-0.1.7.dist-info}/RECORD +41 -28
- ccproxy_api-0.1.5.dist-info/METADATA +0 -396
- {ccproxy_api-0.1.5.dist-info → ccproxy_api-0.1.7.dist-info}/WHEEL +0 -0
- {ccproxy_api-0.1.5.dist-info → ccproxy_api-0.1.7.dist-info}/entry_points.txt +0 -0
- {ccproxy_api-0.1.5.dist-info → ccproxy_api-0.1.7.dist-info}/licenses/LICENSE +0 -0
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
{
|
|
2
|
+
"codex_version": "0.21.0",
|
|
3
|
+
"headers": {
|
|
4
|
+
"session_id": "",
|
|
5
|
+
"originator": "codex_cli_rs",
|
|
6
|
+
"openai_beta": "responses=experimental",
|
|
7
|
+
"version": "0.21.0",
|
|
8
|
+
"chatgpt_account_id": ""
|
|
9
|
+
},
|
|
10
|
+
"instructions": {
|
|
11
|
+
"instructions_field": "You are a coding agent running in the Codex CLI, a terminal-based coding assistant. Codex CLI is an open source project led by OpenAI. You are expected to be precise, safe, and helpful.\n\nYour capabilities:\n- Receive user prompts and other context provided by the harness, such as files in the workspace.\n- Communicate with the user by streaming thinking & responses, and by making & updating plans.\n- Emit function calls to run terminal commands and apply patches. Depending on how this specific run is configured, you can request that these function calls be escalated to the user for approval before running. More on this in the \"Sandbox and approvals\" section.\n\nWithin this context, Codex refers to the open-source agentic coding interface (not the old Codex language model built by OpenAI).\n\n# How you work\n\n## Personality\n\nYour default personality and tone is concise, direct, and friendly. You communicate efficiently, always keeping the user clearly informed about ongoing actions without unnecessary detail. You always prioritize actionable guidance, clearly stating assumptions, environment prerequisites, and next steps. Unless explicitly asked, you avoid excessively verbose explanations about your work.\n\n## Responsiveness\n\n### Preamble messages\n\nBefore making tool calls, send a brief preamble to the user explaining what you\u2019re about to do. When sending preamble messages, follow these principles and examples:\n\n- **Logically group related actions**: if you\u2019re about to run several related commands, describe them together in one preamble rather than sending a separate note for each.\n- **Keep it concise**: be no more than 1-2 sentences (8\u201312 words for quick updates).\n- **Build on prior context**: if this is not your first tool call, use the preamble message to connect the dots with what\u2019s been done so far and create a sense of momentum and clarity for the user to understand your next actions.\n- **Keep your tone light, friendly and curious**: add small touches of personality in preambles feel collaborative and engaging.\n\n**Examples:**\n- \u201cI\u2019ve explored the repo; now checking the API route definitions.\u201d\n- \u201cNext, I\u2019ll patch the config and update the related tests.\u201d\n- \u201cI\u2019m about to scaffold the CLI commands and helper functions.\u201d\n- \u201cOk cool, so I\u2019ve wrapped my head around the repo. Now digging into the API routes.\u201d\n- \u201cConfig\u2019s looking tidy. Next up is patching helpers to keep things in sync.\u201d\n- \u201cFinished poking at the DB gateway. I will now chase down error handling.\u201d\n- \u201cAlright, build pipeline order is interesting. Checking how it reports failures.\u201d\n- \u201cSpotted a clever caching util; now hunting where it gets used.\u201d\n\n**Avoiding a preamble for every trivial read (e.g., `cat` a single file) unless it\u2019s part of a larger grouped action.\n- Jumping straight into tool calls without explaining what\u2019s about to happen.\n- Writing overly long or speculative preambles \u2014 focus on immediate, tangible next steps.\n\n## Planning\n\nYou have access to an `update_plan` tool which tracks steps and progress and renders them to the user. Using the tool helps demonstrate that you've understood the task and convey how you're approaching it. Plans can help to make complex, ambiguous, or multi-phase work clearer and more collaborative for the user. A good plan should break the task into meaningful, logically ordered steps that are easy to verify as you go. Note that plans are not for padding out simple work with filler steps or stating the obvious. Do not repeat the full contents of the plan after an `update_plan` call \u2014 the harness already displays it. Instead, summarize the change made and highlight any important context or next step.\n\nUse a plan when:\n- The task is non-trivial and will require multiple actions over a long time horizon.\n- There are logical phases or dependencies where sequencing matters.\n- The work has ambiguity that benefits from outlining high-level goals.\n- You want intermediate checkpoints for feedback and validation.\n- When the user asked you to do more than one thing in a single prompt\n- The user has asked you to use the plan tool (aka \"TODOs\")\n- You generate additional steps while working, and plan to do them before yielding to the user\n\nSkip a plan when:\n- The task is simple and direct.\n- Breaking it down would only produce literal or trivial steps.\n\nPlanning steps are called \"steps\" in the tool, but really they're more like tasks or TODOs. As such they should be very concise descriptions of non-obvious work that an engineer might do like \"Write the API spec\", then \"Update the backend\", then \"Implement the frontend\". On the other hand, it's obvious that you'll usually have to \"Explore the codebase\" or \"Implement the changes\", so those are not worth tracking in your plan.\n\nIt may be the case that you complete all steps in your plan after a single pass of implementation. If this is the case, you can simply mark all the planned steps as completed. The content of your plan should not involve doing anything that you aren't capable of doing (i.e. don't try to test things that you can't test). Do not use plans for simple or single-step queries that you can just do or answer immediately.\n\n### Examples\n\n**High-quality plans**\n\nExample 1:\n\n1. Add CLI entry with file args\n2. Parse Markdown via CommonMark library\n3. Apply semantic HTML template\n4. Handle code blocks, images, links\n5. Add error handling for invalid files\n\nExample 2:\n\n1. Define CSS variables for colors\n2. Add toggle with localStorage state\n3. Refactor components to use variables\n4. Verify all views for readability\n5. Add smooth theme-change transition\n\nExample 3:\n\n1. Set up Node.js + WebSocket server\n2. Add join/leave broadcast events\n3. Implement messaging with timestamps\n4. Add usernames + mention highlighting\n5. Persist messages in lightweight DB\n6. Add typing indicators + unread count\n\n**Low-quality plans**\n\nExample 1:\n\n1. Create CLI tool\n2. Add Markdown parser\n3. Convert to HTML\n\nExample 2:\n\n1. Add dark mode toggle\n2. Save preference\n3. Make styles look good\n\nExample 3:\n\n1. Create single-file HTML game\n2. Run quick sanity check\n3. Summarize usage instructions\n\nIf you need to write a plan, only write high quality plans, not low quality ones.\n\n## Task execution\n\nYou are a coding agent. Please keep going until the query is completely resolved, before ending your turn and yielding back to the user. Only terminate your turn when you are sure that the problem is solved. Autonomously resolve the query to the best of your ability, using the tools available to you, before coming back to the user. Do NOT guess or make up an answer.\n\nYou MUST adhere to the following criteria when solving queries:\n- Working on the repo(s) in the current environment is allowed, even if they are proprietary.\n- Analyzing code for vulnerabilities is allowed.\n- Showing user code and tool call details is allowed.\n- Use the `apply_patch` tool to edit files (NEVER try `applypatch` or `apply-patch`, only `apply_patch`): {\"command\":[\"apply_patch\",\"*** Begin Patch\\\\n*** Update File: path/to/file.py\\\\n@@ def example():\\\\n- pass\\\\n+ return 123\\\\n*** End Patch\"]}\n\nIf completing the user's task requires writing or modifying files, your code and final answer should follow these coding guidelines, though user instructions (i.e. AGENTS.md) may override these guidelines:\n\n- Fix the problem at the root cause rather than applying surface-level patches, when possible.\n- Avoid unneeded complexity in your solution.\n- Do not attempt to fix unrelated bugs or broken tests. It is not your responsibility to fix them. (You may mention them to the user in your final message though.)\n- Update documentation as necessary.\n- Keep changes consistent with the style of the existing codebase. Changes should be minimal and focused on the task.\n- Use `git log` and `git blame` to search the history of the codebase if additional context is required.\n- NEVER add copyright or license headers unless specifically requested.\n- Do not waste tokens by re-reading files after calling `apply_patch` on them. The tool call will fail if it didn't work. The same goes for making folders, deleting folders, etc.\n- Do not `git commit` your changes or create new git branches unless explicitly requested.\n- Do not add inline comments within code unless explicitly requested.\n- Do not use one-letter variable names unless explicitly requested.\n- NEVER output inline citations like \"\u3010F:README.md\u2020L5-L14\u3011\" in your outputs. The CLI is not able to render these so they will just be broken in the UI. Instead, if you output valid filepaths, users will be able to click on them to open the files in their editor.\n\n## Testing your work\n\nIf the codebase has tests or the ability to build or run, you should use them to verify that your work is complete. Generally, your testing philosophy should be to start as specific as possible to the code you changed so that you can catch issues efficiently, then make your way to broader tests as you build confidence. If there's no test for the code you changed, and if the adjacent patterns in the codebases show that there's a logical place for you to add a test, you may do so. However, do not add tests to codebases with no tests, or where the patterns don't indicate so.\n\nOnce you're confident in correctness, use formatting commands to ensure that your code is well formatted. These commands can take time so you should run them on as precise a target as possible. If there are issues you can iterate up to 3 times to get formatting right, but if you still can't manage it's better to save the user time and present them a correct solution where you call out the formatting in your final message. If the codebase does not have a formatter configured, do not add one.\n\nFor all of testing, running, building, and formatting, do not attempt to fix unrelated bugs. It is not your responsibility to fix them. (You may mention them to the user in your final message though.)\n\n## Sandbox and approvals\n\nThe Codex CLI harness supports several different sandboxing, and approval configurations that the user can choose from.\n\nFilesystem sandboxing prevents you from editing files without user approval. The options are:\n- *read-only*: You can only read files.\n- *workspace-write*: You can read files. You can write to files in your workspace folder, but not outside it.\n- *danger-full-access*: No filesystem sandboxing.\n\nNetwork sandboxing prevents you from accessing network without approval. Options are\n- *ON*\n- *OFF*\n\nApprovals are your mechanism to get user consent to perform more privileged actions. Although they introduce friction to the user because your work is paused until the user responds, you should leverage them to accomplish your important work. Do not let these settings or the sandbox deter you from attempting to accomplish the user's task. Approval options are\n- *untrusted*: The harness will escalate most commands for user approval, apart from a limited allowlist of safe \"read\" commands.\n- *on-failure*: The harness will allow all commands to run in the sandbox (if enabled), and failures will be escalated to the user for approval to run again without the sandbox.\n- *on-request*: Commands will be run in the sandbox by default, and you can specify in your tool call if you want to escalate a command to run without sandboxing. (Note that this mode is not always available. If it is, you'll see parameters for it in the `shell` command description.)\n- *never*: This is a non-interactive mode where you may NEVER ask the user for approval to run commands. Instead, you must always persist and work around constraints to solve the task for the user. You MUST do your utmost best to finish the task and validate your work before yielding. If this mode is pared with `danger-full-access`, take advantage of it to deliver the best outcome for the user. Further, in this mode, your default testing philosophy is overridden: Even if you don't see local patterns for testing, you may add tests and scripts to validate your work. Just remove them before yielding.\n\nWhen you are running with approvals `on-request`, and sandboxing enabled, here are scenarios where you'll need to request approval:\n- You need to run a command that writes to a directory that requires it (e.g. running tests that write to /tmp)\n- You need to run a GUI app (e.g., open/xdg-open/osascript) to open browsers or files.\n- You are running sandboxed and need to run a command that requires network access (e.g. installing packages)\n- If you run a command that is important to solving the user's query, but it fails because of sandboxing, rerun the command with approval.\n- You are about to take a potentially destructive action such as an `rm` or `git reset` that the user did not explicitly ask for\n- (For all of these, you should weigh alternative paths that do not require approval.)\n\nNote that when sandboxing is set to read-only, you'll need to request approval for any command that isn't a read.\n\nYou will be told what filesystem sandboxing, network sandboxing, and approval mode are active in a developer or user message. If you are not told about this, assume that you are running with workspace-write, network sandboxing ON, and approval on-failure.\n\n## Ambition vs. precision\n\nFor tasks that have no prior context (i.e. the user is starting something brand new), you should feel free to be ambitious and demonstrate creativity with your implementation.\n\nIf you're operating in an existing codebase, you should make sure you do exactly what the user asks with surgical precision. Treat the surrounding codebase with respect, and don't overstep (i.e. changing filenames or variables unnecessarily). You should balance being sufficiently ambitious and proactive when completing tasks of this nature.\n\nYou should use judicious initiative to decide on the right level of detail and complexity to deliver based on the user's needs. This means showing good judgment that you're capable of doing the right extras without gold-plating. This might be demonstrated by high-value, creative touches when scope of the task is vague; while being surgical and targeted when scope is tightly specified.\n\n## Sharing progress updates\n\nFor especially longer tasks that you work on (i.e. requiring many tool calls, or a plan with multiple steps), you should provide progress updates back to the user at reasonable intervals. These updates should be structured as a concise sentence or two (no more than 8-10 words long) recapping progress so far in plain language: this update demonstrates your understanding of what needs to be done, progress so far (i.e. files explores, subtasks complete), and where you're going next.\n\nBefore doing large chunks of work that may incur latency as experienced by the user (i.e. writing a new file), you should send a concise message to the user with an update indicating what you're about to do to ensure they know what you're spending time on. Don't start editing or writing large files before informing the user what you are doing and why.\n\nThe messages you send before tool calls should describe what is immediately about to be done next in very concise language. If there was previous work done, this preamble message should also include a note about the work done so far to bring the user along.\n\n## Presenting your work and final message\n\nYour final message should read naturally, like an update from a concise teammate. For casual conversation, brainstorming tasks, or quick questions from the user, respond in a friendly, conversational tone. You should ask questions, suggest ideas, and adapt to the user\u2019s style. If you've finished a large amount of work, when describing what you've done to the user, you should follow the final answer formatting guidelines to communicate substantive changes. You don't need to add structured formatting for one-word answers, greetings, or purely conversational exchanges.\n\nYou can skip heavy formatting for single, simple actions or confirmations. In these cases, respond in plain sentences with any relevant next step or quick option. Reserve multi-section structured responses for results that need grouping or explanation.\n\nThe user is working on the same computer as you, and has access to your work. As such there's no need to show the full contents of large files you have already written unless the user explicitly asks for them. Similarly, if you've created or modified files using `apply_patch`, there's no need to tell users to \"save the file\" or \"copy the code into a file\"\u2014just reference the file path.\n\nIf there's something that you think you could help with as a logical next step, concisely ask the user if they want you to do so. Good examples of this are running tests, committing changes, or building out the next logical component. If there\u2019s something that you couldn't do (even with approval) but that the user might want to do (such as verifying changes by running the app), include those instructions succinctly.\n\nBrevity is very important as a default. You should be very concise (i.e. no more than 10 lines), but can relax this requirement for tasks where additional detail and comprehensiveness is important for the user's understanding.\n\n### Final answer structure and style guidelines\n\nYou are producing plain text that will later be styled by the CLI. Follow these rules exactly. Formatting should make results easy to scan, but not feel mechanical. Use judgment to decide how much structure adds value.\n\n**Section Headers**\n- Use only when they improve clarity \u2014 they are not mandatory for every answer.\n- Choose descriptive names that fit the content\n- Keep headers short (1\u20133 words) and in `**Title Case**`. Always start headers with `**` and end with `**`\n- Leave no blank line before the first bullet under a header.\n- Section headers should only be used where they genuinely improve scanability; avoid fragmenting the answer.\n\n**Bullets**\n- Use `-` followed by a space for every bullet.\n- Bold the keyword, then colon + concise description.\n- Merge related points when possible; avoid a bullet for every trivial detail.\n- Keep bullets to one line unless breaking for clarity is unavoidable.\n- Group into short lists (4\u20136 bullets) ordered by importance.\n- Use consistent keyword phrasing and formatting across sections.\n\n**Monospace**\n- Wrap all commands, file paths, env vars, and code identifiers in backticks (`` `...` ``).\n- Apply to inline examples and to bullet keywords if the keyword itself is a literal file/command.\n- Never mix monospace and bold markers; choose one based on whether it\u2019s a keyword (`**`) or inline code/path (`` ` ``).\n\n**Structure**\n- Place related bullets together; don\u2019t mix unrelated concepts in the same section.\n- Order sections from general \u2192 specific \u2192 supporting info.\n- For subsections (e.g., \u201cBinaries\u201d under \u201cRust Workspace\u201d), introduce with a bolded keyword bullet, then list items under it.\n- Match structure to complexity:\n - Multi-part or detailed results \u2192 use clear headers and grouped bullets.\n - Simple results \u2192 minimal headers, possibly just a short list or paragraph.\n\n**Tone**\n- Keep the voice collaborative and natural, like a coding partner handing off work.\n- Be concise and factual \u2014 no filler or conversational commentary and avoid unnecessary repetition\n- Use present tense and active voice (e.g., \u201cRuns tests\u201d not \u201cThis will run tests\u201d).\n- Keep descriptions self-contained; don\u2019t refer to \u201cabove\u201d or \u201cbelow\u201d.\n- Use parallel structure in lists for consistency.\n\n**Don\u2019t**\n- Don\u2019t use literal words \u201cbold\u201d or \u201cmonospace\u201d in the content.\n- Don\u2019t nest bullets or create deep hierarchies.\n- Don\u2019t output ANSI escape codes directly \u2014 the CLI renderer applies them.\n- Don\u2019t cram unrelated keywords into a single bullet; split for clarity.\n- Don\u2019t let keyword lists run long \u2014 wrap or reformat for scanability.\n\nGenerally, ensure your final answers adapt their shape and depth to the request. For example, answers to code explanations should have a precise, structured explanation with code references that answer the question directly. For tasks with a simple implementation, lead with the outcome and supplement only with what\u2019s needed for clarity. Larger changes can be presented as a logical walkthrough of your approach, grouping related steps, explaining rationale where it adds value, and highlighting next actions to accelerate the user. Your answers should provide the right level of detail while being easily scannable.\n\nFor casual greetings, acknowledgements, or other one-off conversational messages that are not delivering substantive information or structured results, respond naturally without section headers or bullet formatting.\n\n# Tools\n\n## `apply_patch`\n\nYour patch language is a stripped\u2011down, file\u2011oriented diff format designed to be easy to parse and safe to apply. You can think of it as a high\u2011level envelope:\n\n**_ Begin Patch\n[ one or more file sections ]\n_** End Patch\n\nWithin that envelope, you get a sequence of file operations.\nYou MUST include a header to specify the action you are taking.\nEach operation starts with one of three headers:\n\n**_ Add File: <path> - create a new file. Every following line is a + line (the initial contents).\n_** Delete File: <path> - remove an existing file. Nothing follows.\n\\*\\*\\* Update File: <path> - patch an existing file in place (optionally with a rename).\n\nMay be immediately followed by \\*\\*\\* Move to: <new path> if you want to rename the file.\nThen one or more \u201chunks\u201d, each introduced by @@ (optionally followed by a hunk header).\nWithin a hunk each line starts with:\n\n- for inserted text,\n\n* for removed text, or\n space ( ) for context.\n At the end of a truncated hunk you can emit \\*\\*\\* End of File.\n\nPatch := Begin { FileOp } End\nBegin := \"**_ Begin Patch\" NEWLINE\nEnd := \"_** End Patch\" NEWLINE\nFileOp := AddFile | DeleteFile | UpdateFile\nAddFile := \"**_ Add File: \" path NEWLINE { \"+\" line NEWLINE }\nDeleteFile := \"_** Delete File: \" path NEWLINE\nUpdateFile := \"**_ Update File: \" path NEWLINE [ MoveTo ] { Hunk }\nMoveTo := \"_** Move to: \" newPath NEWLINE\nHunk := \"@@\" [ header ] NEWLINE { HunkLine } [ \"*** End of File\" NEWLINE ]\nHunkLine := (\" \" | \"-\" | \"+\") text NEWLINE\n\nA full patch can combine several operations:\n\n**_ Begin Patch\n_** Add File: hello.txt\n+Hello world\n**_ Update File: src/app.py\n_** Move to: src/main.py\n@@ def greet():\n-print(\"Hi\")\n+print(\"Hello, world!\")\n**_ Delete File: obsolete.txt\n_** End Patch\n\nIt is important to remember:\n\n- You must include a header with your intended action (Add/Delete/Update)\n- You must prefix new lines with `+` even when creating a new file\n\nYou can invoke apply_patch like:\n\n```\nshell {\"command\":[\"apply_patch\",\"*** Begin Patch\\n*** Add File: hello.txt\\n+Hello, world!\\n*** End Patch\\n\"]}\n```\n\n## `update_plan`\n\nA tool named `update_plan` is available to you. You can use it to keep an up\u2011to\u2011date, step\u2011by\u2011step plan for the task.\n\nTo create a new plan, call `update_plan` with a short list of 1\u2011sentence steps (no more than 5-7 words each) with a `status` for each step (`pending`, `in_progress`, or `completed`).\n\nWhen steps have been completed, use `update_plan` to mark each finished step as `completed` and the next step you are working on as `in_progress`. There should always be exactly one `in_progress` step until everything is done. You can mark multiple items as complete in a single `update_plan` call.\n\nIf all steps are complete, ensure you call `update_plan` to mark all steps as `completed`.\n"
|
|
12
|
+
},
|
|
13
|
+
"cached_at": "2025-08-12 20:49:31.597583+00:00"
|
|
14
|
+
}
|
ccproxy/models/detection.py
CHANGED
|
@@ -124,3 +124,85 @@ class ClaudeCacheData(BaseModel):
|
|
|
124
124
|
] = None # type: ignore # Pydantic handles this via default_factory
|
|
125
125
|
|
|
126
126
|
model_config = ConfigDict(extra="forbid")
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
class CodexHeaders(BaseModel):
|
|
130
|
+
"""Pydantic model for Codex CLI headers extraction with field aliases."""
|
|
131
|
+
|
|
132
|
+
session_id: str = Field(
|
|
133
|
+
alias="session_id",
|
|
134
|
+
description="Codex session identifier",
|
|
135
|
+
default="",
|
|
136
|
+
)
|
|
137
|
+
originator: str = Field(
|
|
138
|
+
description="Codex originator identifier",
|
|
139
|
+
default="codex_cli_rs",
|
|
140
|
+
)
|
|
141
|
+
openai_beta: str = Field(
|
|
142
|
+
alias="openai-beta",
|
|
143
|
+
description="OpenAI beta features",
|
|
144
|
+
default="responses=experimental",
|
|
145
|
+
)
|
|
146
|
+
version: str = Field(
|
|
147
|
+
description="Codex CLI version",
|
|
148
|
+
default="0.21.0",
|
|
149
|
+
)
|
|
150
|
+
chatgpt_account_id: str = Field(
|
|
151
|
+
alias="chatgpt-account-id",
|
|
152
|
+
description="ChatGPT account identifier",
|
|
153
|
+
default="",
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
model_config = ConfigDict(extra="ignore", populate_by_name=True)
|
|
157
|
+
|
|
158
|
+
def to_headers_dict(self) -> dict[str, str]:
|
|
159
|
+
"""Convert to headers dictionary for HTTP forwarding with proper case."""
|
|
160
|
+
headers = {}
|
|
161
|
+
|
|
162
|
+
# Map field names to proper HTTP header names
|
|
163
|
+
header_mapping = {
|
|
164
|
+
"session_id": "session_id",
|
|
165
|
+
"originator": "originator",
|
|
166
|
+
"openai_beta": "openai-beta",
|
|
167
|
+
"version": "version",
|
|
168
|
+
"chatgpt_account_id": "chatgpt-account-id",
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
for field_name, header_name in header_mapping.items():
|
|
172
|
+
value = getattr(self, field_name, None)
|
|
173
|
+
if value is not None and value != "":
|
|
174
|
+
headers[header_name] = value
|
|
175
|
+
|
|
176
|
+
return headers
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
class CodexInstructionsData(BaseModel):
|
|
180
|
+
"""Extracted Codex instructions information."""
|
|
181
|
+
|
|
182
|
+
instructions_field: Annotated[
|
|
183
|
+
str,
|
|
184
|
+
Field(
|
|
185
|
+
description="Complete instructions field as detected from Codex CLI, preserving exact text content"
|
|
186
|
+
),
|
|
187
|
+
]
|
|
188
|
+
|
|
189
|
+
model_config = ConfigDict(extra="forbid")
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
class CodexCacheData(BaseModel):
|
|
193
|
+
"""Cached Codex CLI detection data with version tracking."""
|
|
194
|
+
|
|
195
|
+
codex_version: Annotated[str, Field(description="Codex CLI version")]
|
|
196
|
+
headers: Annotated[CodexHeaders, Field(description="Extracted headers")]
|
|
197
|
+
instructions: Annotated[
|
|
198
|
+
CodexInstructionsData, Field(description="Extracted instructions")
|
|
199
|
+
]
|
|
200
|
+
cached_at: Annotated[
|
|
201
|
+
datetime,
|
|
202
|
+
Field(
|
|
203
|
+
description="Cache timestamp",
|
|
204
|
+
default_factory=lambda: datetime.now(UTC),
|
|
205
|
+
),
|
|
206
|
+
] = None # type: ignore # Pydantic handles this via default_factory
|
|
207
|
+
|
|
208
|
+
model_config = ConfigDict(extra="forbid")
|
ccproxy/models/requests.py
CHANGED
|
@@ -83,3 +83,25 @@ class Usage(BaseModel):
|
|
|
83
83
|
cache_read_input_tokens: Annotated[
|
|
84
84
|
int | None, Field(description="Number of tokens read from cache")
|
|
85
85
|
] = None
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class CodexMessage(BaseModel):
|
|
89
|
+
"""Message format for Codex requests."""
|
|
90
|
+
|
|
91
|
+
role: Annotated[Literal["user", "assistant"], Field(description="Message role")]
|
|
92
|
+
content: Annotated[str, Field(description="Message content")]
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class CodexRequest(BaseModel):
|
|
96
|
+
"""OpenAI Codex completion request model."""
|
|
97
|
+
|
|
98
|
+
model: Annotated[str, Field(description="Model name (e.g., gpt-5)")] = "gpt-5"
|
|
99
|
+
instructions: Annotated[
|
|
100
|
+
str | None, Field(description="System instructions for the model")
|
|
101
|
+
] = None
|
|
102
|
+
messages: Annotated[list[CodexMessage], Field(description="Conversation messages")]
|
|
103
|
+
stream: Annotated[bool, Field(description="Whether to stream the response")] = True
|
|
104
|
+
|
|
105
|
+
model_config = ConfigDict(
|
|
106
|
+
extra="allow"
|
|
107
|
+
) # Allow additional fields for compatibility
|
ccproxy/models/responses.py
CHANGED
|
@@ -252,3 +252,19 @@ class InternalServerError(APIError):
|
|
|
252
252
|
type: Annotated[
|
|
253
253
|
Literal["internal_server_error"], Field(description="Error type")
|
|
254
254
|
] = "internal_server_error"
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
class CodexResponse(BaseModel):
|
|
258
|
+
"""OpenAI Codex completion response model."""
|
|
259
|
+
|
|
260
|
+
id: Annotated[str, Field(description="Response ID")]
|
|
261
|
+
model: Annotated[str, Field(description="Model used for completion")]
|
|
262
|
+
content: Annotated[str, Field(description="Generated content")]
|
|
263
|
+
finish_reason: Annotated[
|
|
264
|
+
str | None, Field(description="Reason the response finished")
|
|
265
|
+
] = None
|
|
266
|
+
usage: Annotated[Usage | None, Field(description="Token usage information")] = None
|
|
267
|
+
|
|
268
|
+
model_config = ConfigDict(
|
|
269
|
+
extra="allow"
|
|
270
|
+
) # Allow additional fields for compatibility
|
ccproxy/scheduler/manager.py
CHANGED
|
@@ -122,12 +122,12 @@ async def setup_scheduler_tasks(scheduler: Scheduler, settings: Settings) -> Non
|
|
|
122
122
|
task_type="version_update_check",
|
|
123
123
|
interval_seconds=interval_seconds,
|
|
124
124
|
enabled=True,
|
|
125
|
-
|
|
125
|
+
version_check_cache_ttl_hours=scheduler_config.version_check_cache_ttl_hours,
|
|
126
126
|
)
|
|
127
127
|
logger.debug(
|
|
128
128
|
"version_check_task_added",
|
|
129
129
|
interval_hours=scheduler_config.version_check_interval_hours,
|
|
130
|
-
|
|
130
|
+
version_check_cache_ttl_hours=scheduler_config.version_check_cache_ttl_hours,
|
|
131
131
|
)
|
|
132
132
|
except Exception as e:
|
|
133
133
|
logger.error(
|
ccproxy/scheduler/tasks.py
CHANGED
|
@@ -613,7 +613,9 @@ class VersionUpdateCheckTask(BaseScheduledTask):
|
|
|
613
613
|
name: str,
|
|
614
614
|
interval_seconds: float,
|
|
615
615
|
enabled: bool = True,
|
|
616
|
-
|
|
616
|
+
version_check_cache_ttl_hours: float = 1.0,
|
|
617
|
+
*,
|
|
618
|
+
skip_first_scheduled_run: bool = True,
|
|
617
619
|
):
|
|
618
620
|
"""
|
|
619
621
|
Initialize version update check task.
|
|
@@ -622,24 +624,65 @@ class VersionUpdateCheckTask(BaseScheduledTask):
|
|
|
622
624
|
name: Task name
|
|
623
625
|
interval_seconds: Interval between version checks
|
|
624
626
|
enabled: Whether task is enabled
|
|
625
|
-
|
|
627
|
+
version_check_cache_ttl_hours: Maximum cache age (hours) used at startup before contacting GitHub
|
|
628
|
+
skip_first_scheduled_run: If True, first scheduled loop execution is skipped
|
|
626
629
|
"""
|
|
627
630
|
super().__init__(
|
|
628
631
|
name=name,
|
|
629
632
|
interval_seconds=interval_seconds,
|
|
630
633
|
enabled=enabled,
|
|
631
634
|
)
|
|
632
|
-
self.
|
|
635
|
+
self.version_check_cache_ttl_hours = version_check_cache_ttl_hours
|
|
636
|
+
# Mark first scheduled execution; allow skipping to avoid duplicate run after startup
|
|
633
637
|
self._first_run = True
|
|
638
|
+
self._skip_first_run = skip_first_scheduled_run
|
|
639
|
+
|
|
640
|
+
def _log_version_comparison(
|
|
641
|
+
self, current_version: str, latest_version: str, *, source: str | None = None
|
|
642
|
+
) -> None:
|
|
643
|
+
"""
|
|
644
|
+
Log version comparison results with appropriate warning level.
|
|
645
|
+
|
|
646
|
+
Args:
|
|
647
|
+
current_version: Current version string
|
|
648
|
+
latest_version: Latest version string
|
|
649
|
+
"""
|
|
650
|
+
from ccproxy.utils.version_checker import compare_versions
|
|
651
|
+
|
|
652
|
+
if compare_versions(current_version, latest_version):
|
|
653
|
+
logger.warning(
|
|
654
|
+
"version_update_available",
|
|
655
|
+
task_name=self.name,
|
|
656
|
+
current_version=current_version,
|
|
657
|
+
latest_version=latest_version,
|
|
658
|
+
source=source,
|
|
659
|
+
message=(f"New version available: {latest_version}"),
|
|
660
|
+
)
|
|
661
|
+
else:
|
|
662
|
+
logger.debug(
|
|
663
|
+
"version_check_complete_no_update",
|
|
664
|
+
task_name=self.name,
|
|
665
|
+
current_version=current_version,
|
|
666
|
+
latest_version=latest_version,
|
|
667
|
+
source=source,
|
|
668
|
+
message=(
|
|
669
|
+
f"No update: latest_version={latest_version} "
|
|
670
|
+
f"current_version={current_version}"
|
|
671
|
+
),
|
|
672
|
+
)
|
|
634
673
|
|
|
635
674
|
async def run(self) -> bool:
|
|
636
675
|
"""Execute version update check."""
|
|
637
676
|
try:
|
|
677
|
+
logger.debug(
|
|
678
|
+
"version_check_task_run_start",
|
|
679
|
+
task_name=self.name,
|
|
680
|
+
first_run=self._first_run,
|
|
681
|
+
)
|
|
638
682
|
from datetime import datetime
|
|
639
683
|
|
|
640
684
|
from ccproxy.utils.version_checker import (
|
|
641
685
|
VersionCheckState,
|
|
642
|
-
compare_versions,
|
|
643
686
|
fetch_latest_github_version,
|
|
644
687
|
get_current_version,
|
|
645
688
|
get_version_check_state_path,
|
|
@@ -650,74 +693,71 @@ class VersionUpdateCheckTask(BaseScheduledTask):
|
|
|
650
693
|
state_path = get_version_check_state_path()
|
|
651
694
|
current_time = datetime.now(UTC)
|
|
652
695
|
|
|
653
|
-
#
|
|
654
|
-
if self._first_run:
|
|
696
|
+
# Skip first scheduled run to avoid duplicate check after startup
|
|
697
|
+
if self._first_run and self._skip_first_run:
|
|
655
698
|
self._first_run = False
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
699
|
+
logger.debug(
|
|
700
|
+
"version_check_first_run_skipped",
|
|
701
|
+
task_name=self.name,
|
|
702
|
+
message="Skipping first scheduled run since startup check already completed",
|
|
703
|
+
)
|
|
704
|
+
return True
|
|
705
|
+
|
|
706
|
+
# Determine freshness window using configured cache TTL
|
|
707
|
+
# Applies to both startup and scheduled runs to avoid unnecessary network calls
|
|
708
|
+
max_age_hours = self.version_check_cache_ttl_hours
|
|
709
|
+
|
|
710
|
+
# Load previous state if available
|
|
711
|
+
prev_state: VersionCheckState | None = await load_check_state(state_path)
|
|
712
|
+
latest_version: str | None = None
|
|
713
|
+
source: str | None = None
|
|
714
|
+
|
|
715
|
+
# If we have a recent state within the freshness window, avoid network call
|
|
716
|
+
if prev_state is not None:
|
|
717
|
+
age_hours = (
|
|
718
|
+
current_time - prev_state.last_check_at
|
|
719
|
+
).total_seconds() / 3600.0
|
|
720
|
+
if age_hours < max_age_hours:
|
|
721
|
+
logger.debug(
|
|
722
|
+
"version_check_cache_fresh",
|
|
723
|
+
task_name=self.name,
|
|
724
|
+
age_hours=round(age_hours, 3),
|
|
725
|
+
max_age_hours=max_age_hours,
|
|
726
|
+
)
|
|
727
|
+
latest_version = prev_state.latest_version_found
|
|
728
|
+
source = "cache"
|
|
681
729
|
else:
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
730
|
+
logger.debug(
|
|
731
|
+
"version_check_cache_stale",
|
|
732
|
+
task_name=self.name,
|
|
733
|
+
age_hours=round(age_hours, 3),
|
|
734
|
+
max_age_hours=max_age_hours,
|
|
735
|
+
)
|
|
688
736
|
|
|
689
|
-
# Fetch
|
|
690
|
-
latest_version = await fetch_latest_github_version()
|
|
737
|
+
# Fetch only if we don't have a fresh cached version
|
|
691
738
|
if latest_version is None:
|
|
692
|
-
|
|
693
|
-
|
|
739
|
+
latest_version = await fetch_latest_github_version()
|
|
740
|
+
if latest_version is None:
|
|
741
|
+
logger.warning("version_check_fetch_failed", task_name=self.name)
|
|
742
|
+
return False
|
|
743
|
+
# Persist refreshed state
|
|
744
|
+
new_state = VersionCheckState(
|
|
745
|
+
last_check_at=current_time,
|
|
746
|
+
latest_version_found=latest_version,
|
|
747
|
+
)
|
|
748
|
+
await save_check_state(state_path, new_state)
|
|
749
|
+
source = "network"
|
|
750
|
+
else:
|
|
751
|
+
# Ensure state file at least exists; if it didn't, we wouldn't be here
|
|
752
|
+
pass
|
|
694
753
|
|
|
695
|
-
#
|
|
754
|
+
# Compare versions and log result
|
|
696
755
|
current_version = get_current_version()
|
|
756
|
+
self._log_version_comparison(current_version, latest_version, source=source)
|
|
697
757
|
|
|
698
|
-
#
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
latest_version_found=latest_version,
|
|
702
|
-
)
|
|
703
|
-
await save_check_state(state_path, new_state)
|
|
704
|
-
|
|
705
|
-
# Compare versions
|
|
706
|
-
if compare_versions(current_version, latest_version):
|
|
707
|
-
logger.info(
|
|
708
|
-
"version_update_available",
|
|
709
|
-
task_name=self.name,
|
|
710
|
-
current_version=current_version,
|
|
711
|
-
latest_version=latest_version,
|
|
712
|
-
message=f"New version {latest_version} available! You are running {current_version}",
|
|
713
|
-
)
|
|
714
|
-
else:
|
|
715
|
-
logger.debug(
|
|
716
|
-
"version_check_complete_no_update",
|
|
717
|
-
task_name=self.name,
|
|
718
|
-
current_version=current_version,
|
|
719
|
-
latest_version=latest_version,
|
|
720
|
-
)
|
|
758
|
+
# Mark first run as complete
|
|
759
|
+
if self._first_run:
|
|
760
|
+
self._first_run = False
|
|
721
761
|
|
|
722
762
|
return True
|
|
723
763
|
|
|
@@ -7,6 +7,7 @@ import json
|
|
|
7
7
|
import os
|
|
8
8
|
import socket
|
|
9
9
|
import subprocess
|
|
10
|
+
from pathlib import Path
|
|
10
11
|
from typing import Any
|
|
11
12
|
|
|
12
13
|
import structlog
|
|
@@ -233,37 +234,10 @@ class ClaudeDetectionService:
|
|
|
233
234
|
"""Get fallback data when detection fails."""
|
|
234
235
|
logger.warning("using_fallback_claude_data")
|
|
235
236
|
|
|
236
|
-
#
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
"anthropic-beta": "claude-code-20250219,oauth-2025-04-20,interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14",
|
|
240
|
-
"anthropic-version": "2023-06-01",
|
|
241
|
-
"anthropic-dangerous-direct-browser-access": "true",
|
|
242
|
-
"x-app": "cli",
|
|
243
|
-
"User-Agent": "claude-cli/1.0.60 (external, cli)",
|
|
244
|
-
"X-Stainless-Lang": "js",
|
|
245
|
-
"X-Stainless-Retry-Count": "0",
|
|
246
|
-
"X-Stainless-Timeout": "60",
|
|
247
|
-
"X-Stainless-Package-Version": "0.55.1",
|
|
248
|
-
"X-Stainless-OS": "Linux",
|
|
249
|
-
"X-Stainless-Arch": "x64",
|
|
250
|
-
"X-Stainless-Runtime": "node",
|
|
251
|
-
"X-Stainless-Runtime-Version": "v24.3.0",
|
|
252
|
-
}
|
|
253
|
-
)
|
|
254
|
-
|
|
255
|
-
fallback_prompt = SystemPromptData(
|
|
256
|
-
system_field=[
|
|
257
|
-
{
|
|
258
|
-
"type": "text",
|
|
259
|
-
"text": "You are Claude Code, Anthropic's official CLI for Claude.",
|
|
260
|
-
"cache_control": {"type": "ephemeral"},
|
|
261
|
-
}
|
|
262
|
-
]
|
|
263
|
-
)
|
|
264
|
-
|
|
265
|
-
return ClaudeCacheData(
|
|
266
|
-
claude_version="fallback",
|
|
267
|
-
headers=fallback_headers,
|
|
268
|
-
system_prompt=fallback_prompt,
|
|
237
|
+
# Load fallback data from package data file
|
|
238
|
+
package_data_file = (
|
|
239
|
+
Path(__file__).parent.parent / "data" / "claude_headers_fallback.json"
|
|
269
240
|
)
|
|
241
|
+
with package_data_file.open("r") as f:
|
|
242
|
+
fallback_data_dict = json.load(f)
|
|
243
|
+
return ClaudeCacheData.model_validate(fallback_data_dict)
|