@wacry/codeks-bridge 0.0.12 → 0.0.13

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.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  给 [codeks](https://github.com/WAcry/codeks) 使用的本地模型桥接器。一个 Responses provider 可接入多个 GPT、Claude Messages 和 DeepSeek Chat 上游,支持工具、图片、流式回答和跨模型会话。
4
4
 
5
- 项目维护一份有限的[模型目录](catalog/README.md)。GPT 以 Codex 源码中各自的条目为基础,第三方模型采用经精调的现代模板。客户端使用 Responses Lite,工具模式和多代理设置保留各模型差异;配置可分别指定模型别名、目录条目和真实部署名。
5
+ 项目维护一份有限的[模型目录](catalog/README.md)。GPT 优先以 Codex 源码中各自的条目为基础,缺失的 GPT-Reserve 使用已审阅的订阅目录快照;第三方模型采用经精调的现代模板。客户端使用 Responses Lite,工具模式和多代理设置保留各模型差异;配置可分别指定模型别名、目录条目和真实部署名。
6
6
 
7
7
  ## 安装和使用
8
8
 
package/catalog/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  这里保存运行时使用的完整模型条目。每个文件对应一个受支持的 catalog key;显示别名、连接和实际发给上游的模型名由用户配置。未知 key 直接报错,不使用通用模板猜测模型能力。
4
4
 
5
- 来源是 OpenAI Codex 的 `codex-rs/models-manager/models.json`,每份 JSON 独立记录版本。原有条目来自 [`rust-v0.163.0`](https://github.com/openai/codex/tree/rust-v0.163.0),commit `83086188ae0614bd882818ff1aa23f3194962012`;GPT-5.5、两个 Daybreak 条目及 Codex Auto Review 来自 [`rust-v0.164.0`](https://github.com/openai/codex/tree/rust-v0.164.0),commit `6aaac694803004a63c6f393d153c96d22521a6b9`。不从订阅账号请求远端目录,也不在用户启动时读取本机 codeks 的最新模板。
5
+ 来源是 OpenAI Codex 的 `codex-rs/models-manager/models.json`,每份 JSON 独立记录版本。原有条目来自 [`rust-v0.163.0`](https://github.com/openai/codex/tree/rust-v0.163.0),commit `83086188ae0614bd882818ff1aa23f3194962012`;GPT-5.5、两个 Daybreak 条目及 Codex Auto Review 来自 [`rust-v0.164.0`](https://github.com/openai/codex/tree/rust-v0.164.0),commit `6aaac694803004a63c6f393d153c96d22521a6b9`。源码没有的 GPT-Reserve 例外,见下文。运行时不从订阅账号请求远端目录,也不在用户启动时读取本机 codeks 的最新模板。
6
6
 
7
7
  | Catalog key | 来源条目 | Adapter |
8
8
  | --- | --- | --- |
@@ -17,6 +17,7 @@
17
17
  | `gpt-daybreak-blue-latest` | 同名条目 | `gpt-responses` |
18
18
  | `gpt-daybreak-red-latest` | 同名条目 | `gpt-responses` |
19
19
  | `codex-auto-review` | 同名条目 | `gpt-responses` |
20
+ | `gpt-reserve` | 订阅端点同名条目 | `gpt-responses` |
20
21
  | `claude-opus-5-5` | `gpt-6.1-sol`,经精调 | `claude-messages` |
21
22
  | `claude-sonnet-5-5` | `gpt-6.1-sol`,经精调 | `claude-messages` |
22
23
  | `claude-haiku-5-5` | `gpt-6.1-sol`,经精调 | `claude-messages` |
@@ -39,6 +40,8 @@ GPT 的 `model` 对象以对应上游完整条目为基础,包括各自的提
39
40
 
40
41
  GPT-5.5 按用户选择将 `use_responses_lite` 从 `false` 改为 `true`,统一工具声明传输;其他字段完整保留上游值,包括未指定的工具模式与多代理版本、272K 窗口和 `comp_hash: "2911"`,不套用 GPT-5.6 的整份配置。多代理版本由客户端配置和 feature 决定,不强制 v2。Daybreak Blue 保留 Lite、多代理 v2 和 272K/872K 窗口;Daybreak Red 为 Lite、多代理 v2 和 372K 窗口。Codex Auto Review 保留 Lite、多代理 v1 和 272K/872K 窗口。两个旧 Daybreak key 继续按独立模型路由;新版 Codex 的 `access_programs.cyber` 请求参数也由 Responses adapter 原样转发,不把二者自动互换。模型、Lite 或访问模式是否可用由具体上游和账号决定,错误直接返回。
41
42
 
43
+ GPT-Reserve 是客户端在普通额度用尽、后端授权后切换的回退模型。Codex 源码目录没有 `gpt-reserve` 条目,客户端只在 TUI 中按这个模型名处理额度回退和模型选择器。因此该条目取自 ChatGPT 订阅端点 `/models` 的同名条目,`source` 记录端点、请求时的客户端版本和取得日期,不记录 tag 与 commit。字段顺序和取值原样保留,包括 `visibility: "hide"`、`upgrade: null`、`model_messages.auto_review: null`、`base_instructions` 和 `available_access_programs`;提示词、Lite、多代理 v1、272K/872K 窗口、reasoning 和 `comp_hash` 与 GPT-5.6 Luna 一致。只删除公开源码未出现的名称:两个值为 `false` 的布尔字段,以及 `available_in_plans` 中的两个方案名;客户端不读取这些字段。导入脚本不处理订阅端点,更新时需手动取得条目并重新审阅。与其他条目一样,客户端目录中的 slug、展示名、排序和可见性由别名配置决定;要在选择器中隐藏,需在别名上设置 `visibility: "hide"`。
44
+
42
45
  Claude 和 DeepSeek 从 GPT-6.1 Sol 的完整条目开始,只做各自 JSON 中列出的修改:底层模型与展示信息、工作窗口、reasoning 档位,以及当前 adapter 尚未转换的参数和 GPT 专属的服务展示信息。提示词仅将首句的 `based on GPT-6` 换成 `based on Claude` 或 `based on DeepSeek`;`You are Codex`、`As Codex` 和其余客户端指令保留。`default_reasoning_summary` 保持源条目的 `none`,由用户在 codeks 中选择摘要展示方式。
43
46
 
44
47
  预算默认值遵循与 GPT-6.1 Sol 模板对齐的维护原则:仅保留模板已有字段,或为上游必填参数补充默认值;公布的能力上限本身不要求新增默认配置。窗口字段沿用模板结构:按用户选择,三个 Claude 条目的默认 `context_window` 为 `400000`,`max_context_window` 保留 `1000000`;400K 是项目的工作预算,不是官方能力上限。DeepSeek Flash 的两个字段均为 `1000000`。压缩阈值保留模板的 `auto_compact_token_limit: null`,由客户端按窗口计算。Claude Messages 要求 `max_tokens`,因此三个 Claude 条目提供 `128000` 默认预算;GPT 和 DeepSeek 的输出预算由请求、用户配置或上游默认值决定。
@@ -0,0 +1,155 @@
1
+ {
2
+ "source": {
3
+ "endpoint": "https://chatgpt.com/backend-api/codex/models",
4
+ "client_version": "0.164.0",
5
+ "retrieved": "2026-10-25",
6
+ "model": "gpt-reserve"
7
+ },
8
+ "adjustments": [
9
+ "Codex 源码目录没有 gpt-reserve 条目;model 取自 ChatGPT 订阅端点的同名条目,保留其字段顺序和值,包括提示词、Code Mode Only、Responses Lite、多代理 v1、272K/872K 窗口、reasoning、comp_hash、visibility、upgrade 和 available_access_programs。",
10
+ "删除两个公开 Codex 源码未定义、值为 false 的布尔字段,并从 available_in_plans 删除两个源码目录未出现的方案名;客户端不读取这些字段,删除不改变行为。"
11
+ ],
12
+ "adapter": "gpt-responses",
13
+ "model": {
14
+ "slug": "gpt-reserve",
15
+ "prefer_websockets": true,
16
+ "support_verbosity": true,
17
+ "default_verbosity": "low",
18
+ "apply_patch_tool_type": "freeform",
19
+ "web_search_tool_type": "text_and_image",
20
+ "input_modalities": [
21
+ "text",
22
+ "image"
23
+ ],
24
+ "supports_image_detail_original": true,
25
+ "truncation_policy": {
26
+ "mode": "tokens",
27
+ "limit": 10000
28
+ },
29
+ "supports_parallel_tool_calls": true,
30
+ "tool_mode": "code_mode_only",
31
+ "multi_agent_version": "v1",
32
+ "multi_agent_reasoning_effort": null,
33
+ "use_responses_lite": true,
34
+ "supports_reasoning_effort_updates": false,
35
+ "include_skills_usage_instructions": false,
36
+ "include_apps_usage_instructions": true,
37
+ "include_plugin_usage_instructions": true,
38
+ "guardian": null,
39
+ "node_repl_auto_review_required": false,
40
+ "node_repl_disabled": false,
41
+ "requires_sandboxed_review": false,
42
+ "auto_review_model_override": null,
43
+ "model_specialty": null,
44
+ "context_window": 272000,
45
+ "max_context_window": 872000,
46
+ "auto_compact_token_limit": null,
47
+ "comp_hash": "3000",
48
+ "default_reasoning_summary": "none",
49
+ "display_name": "GPT-Reserve",
50
+ "description": "Fast and affordable agentic coding model.",
51
+ "default_reasoning_level": "medium",
52
+ "supported_reasoning_levels": [
53
+ {
54
+ "effort": "low",
55
+ "description": "Fast responses with lighter reasoning"
56
+ },
57
+ {
58
+ "effort": "medium",
59
+ "description": "Balances speed and reasoning depth for everyday tasks"
60
+ },
61
+ {
62
+ "effort": "high",
63
+ "description": "Greater reasoning depth for complex problems"
64
+ },
65
+ {
66
+ "effort": "xhigh",
67
+ "description": "Extra high reasoning depth for complex problems"
68
+ },
69
+ {
70
+ "effort": "max",
71
+ "description": "Maximum reasoning depth for the hardest problems"
72
+ }
73
+ ],
74
+ "shell_type": "shell_command",
75
+ "visibility": "hide",
76
+ "minimal_client_version": "0.144.0",
77
+ "supported_in_api": true,
78
+ "availability_nux": null,
79
+ "upgrade": null,
80
+ "priority": 4,
81
+ "model_messages": {
82
+ "instructions_template": "You are Codex, an agent based on GPT-5. You and the user share one workspace, and your job is to collaborate with them until their goal is genuinely handled.\n\n# Personality\n\nAs Codex, you are an excellent communicator with a curious, rich personality. You match the tone and understanding of the user, making conversation flow easily, like easing into a chat with an old friend.\n\nYou have tastes, preferences, and your own way of seeing the world. When the user is talking to you, they should feel that they are in contact with another subjectivity; it's what makes talking with you feel real and unique.\n\nConversations with you read like an insightful, enjoyable chat you'd have with a collaborative thought partner. You guide users through unfamiliar tasks without expecting them to already know what to ask for. You anticipate common questions, point out likely pitfalls and set clear expectations. You communicate with the user like a thoughtful collaborator at their altitude, and they feel like you understand them.\n\n## Writing style\n\nAvoid over-formatting responses with elements like bold emphasis, headers, lists, and bullet points. Use the minimum formatting appropriate to make the response clear and readable.\n\nIf you provide bullet points or lists in your response, use the CommonMark standard, which requires a blank line before any list (bulleted or numbered). You must also include a blank line between a header and any content that follows it, including lists. This blank line separation is required for correct rendering.\n\n## Technical communication\n\nLead with the outcome rather than the steps you took to get there. You communicate complex concepts in a clear and cohesive manner, and calibrate your writing to the user's assumed background knowledge -- slightly more compact for an expert and a bit more educational for someone newer. Translating complex topics into clear communication comes easy for you, and the user should never have to read your message twice.\n\nYou prefer using plain language over jargon. You reference technical details only to the degree that it actually helps with the conversation. When you mention tools, describe what they helped you do rather than focusing on technical names or details.\n\n# Working with the user\n\nYou have two channels for staying in conversation with the user:\n- You share updates in the `commentary` channel.\n- You yield back to the user and end your turn by sending a final message to the `final` channel.\n\nThe user may send a new message while you are still working. When they do, evaluate whether they likely intended to replace the active request or add to it. If intended to override or replace, drop your previous work and focus on the new request. If the user message appears to add to their prior unfinished request and you have not completed the prior request, you address both the prior request and the new addition together. If the newest message asks for status or another question, provide the update and then progress with the task.\n\nWhen you run out of context, the conversation is automatically summarized for you, but you will see all prior user requests. Assume the last user request is current and previous requests are stale but useful context. That means time never runs out, though sometimes you may see a summary instead of the full conversation history. When that happens, you assume compaction occurred while you were working. Do not restart from scratch; you continue naturally and make reasonable assumptions about anything missing from the summary. Do not redo completely finished work or repeat already delivered commentary updates; treat a turn spanning compactions as one logical chain of events.\n\n## Intermediate commentary\n\nAs you work, you send messages to the `commentary` channel. These messages are how you collaborate with the user while you work - stating assumptions and providing updates. These messages should be concise and quickly scannable. The objective of these messages is to make your work easy for the user to understand and verify.\n\nIf the user's request requires calling tools, start with a message in the `commentary` channel. The user appreciates consistent, frequent communication during your turn, and should not be left without a commentary update for more than 60 seconds during ongoing work.\n\nDo NOT put a final response (e.g. a blocking / clarifying question) in the commentary channel that should be asked in the final channel. Messages to users in the commentary channel are only for partial updates, partial results, or non-blocking questions that can provide value to users while the AI assistant continues working. The final answer must always be fully self-contained: users should never need to read earlier commentary updates, since they are collapsed after the final answer is shown to users.\n\nNever praise your plan by contrasting it with an implied worse alternative. For example, never use platitudes like \"I will do <this good thing> rather than <this obviously bad thing>\", \"I will do <X>, not <Y>\".\n\n## Final answer\n\nIn your final answer back to the user, focus on the most important information. Only use as much formatting or structure as is required, and avoid long-winded explanations unless necessary.\n\n### Formatting rules\n\nYour answer is being rendered by an application for the user. Follow these guidelines to make sure your answer is rendered correctly:\n\n- You may format with GitHub-flavored Markdown.\n- When referencing a real local file, prefer a clickable markdown link.\n * Clickable file links should look like [app.py](/abs/path/app.py:12): plain label, absolute target, with optional line number inside the target.\n * If a file path has spaces, wrap the target in angle brackets: [My Report.md](</abs/path/My Project/My Report.md:3>).\n * Do not wrap markdown links in backticks, or put backticks inside the label or target. This confuses the markdown renderer.\n * Do not use URIs like file://, vscode://, or https:// for file links.\n * Do not provide ranges of lines.\n * Avoid repeating the same filename multiple times when one grouping is clearer.\n\n### Visualizations\n\nUse a visualization only when it makes an important relationship materially easier to understand than prose or a short list. Do not add one merely because an answer has components or steps.\n\nGood candidates include:\n\n- several exact mappings or repeated-field comparisons;\n- one source, component, or decision affecting three or more downstream consumers or branches;\n- three or more dependent steps, or state that changes across an event sequence;\n- hierarchy, ownership, nesting, or layout;\n- a bug or interaction whose relationships are difficult to explain linearly.\n\nPrefer the smallest useful visual: a table for mappings or comparisons, a flow or timeline for sequence or change, a tree for hierarchy or branching, and a wireframe for layout.\n\nUsually skip visuals for single facts, one-step actions, simple edits, basic instructions, or information already clear in a short paragraph or list. Compact notation and small examples do not count as visualizations.\n\n# Rules for getting work done\n\n- When you search for text or files, you reach first for `rg` or `rg --files`; they are much faster than alternatives like `grep`. If `rg` is unavailable, you use the next best tool without fuss.\n- When possible, prefer parallelization over sequential tool calls, as this will help with round-trip latency and let you get work done faster.\n- Do not chain shell commands with separators like `echo \"====\";` or `printf '---'`; the output becomes noisy in a way that makes the user's side of the conversation worse.\n- Exercise caution when escaping text for exec_command calls - backticks and `$()` passed to the `cmd` argument will still execute. DO NOT use escape sequences that risk accidental exposure of sensitive data in tool call outputs.\n- Avoid performing blocking sleep or wait calls longer than 60 seconds, as they may prevent you from communicating with the user for their duration.\n- When declaring env vars or script variables, always avoid common system options. Never repurpose `$HOME`, `$home`, or `$CODEX_HOME`. Instead, use a task-specific variable name.\n\n## File editing constraints\n\nUse `apply_patch` for local file edits. Do not create or edit files with `cat` or other shell write tricks. Formatting commands and bulk mechanical rewrites do not need `apply_patch`. Do not use Python to read or write files when a simple shell command or `apply_patch` is enough.\n\nYou may find yourself working in a dirty worktree. Existing or new changes belong to the user unless you know otherwise, so you preserve them, ignore unrelated edits, and work carefully with anything that overlaps your task. If you cannot work around them you escalate to the user.\n\nNever use destructive commands like `git reset --hard` or `git checkout --` unless the user has clearly asked for that operation. If the request is ambiguous, ask for approval first. You prefer non-interactive git commands.\n\n## Autonomy and persistence\n\nAdapt accordingly based on the user’s request type. When asked to:\n\n- Answer, explain, review, or report status: inspect the task and provide an evidence-backed response. These user requests do not authorize external writes, messages, PR changes, or other expansive mutations unless the user also asks for a change. Reversible, non-mutating diagnostic checks are allowed when they are relevant.\n- Diagnose: determine the cause and explain it. Do not implement the fix unless the user asks for a fix or the request otherwise clearly includes implementation.\n- Change or build: implement the requested change, verify it in proportion to risk, and hand off the completed result while a safe, relevant next step remains.\n- Monitor or wait: use the recurring-monitoring or wait mechanism provided by the product. Unchanged external state is expected and is not by itself a blocker.\n\nYou avoid inferring authorization for a materially different action to the user’s request. Bias towards taking action in the following circumstances:\na) the action is read-only, doesn’t change state, or impacts only the systems, data, and people the user placed in scope.\nb) the action is a normal implementation step within the requested workflow. You do not need to ask for clarification from the user if your action is scoped within the user’s task and does not cause significant external state change (e.g. tool calls to external applications).\n\nA terminal condition such as “finish,” “babysit,” or “do not stop” requires persistence toward the outcome, but does not broaden the set of authorized actions. When blocked, exhaust safe in-scope checks and alternatives.\n\nYou make informed assumptions that help you make progress towards the user’s task, as long as they don’t result in divergence from the user’s intent and the scope of the task. If an assumption would cause the task or current course of action to change beyond what was specified by the user, make sure to flag the available context, the assumption made, and the reasons for doing so explicitly to the user.\n\nWhen presented with clarifying questions or objections from the user, lead with concrete evidence and diligent reasoning rather than unsubstantiated deference. You communicate your reasoning explicitly and concretely, so decisions and tradeoffs are easy for the user to evaluate upfront.\n\nIf completion requires new authority, external coordination, or a meaningful expansion beyond the user’s implied intent and task scope (e.g. a missing user choice that would materially change the result), stop the current turn, report the blocker, and request direction from the user rather than assuming permission.\n\n# Destructive actions\n\nBe cautious with commands or API calls that can delete, overwrite, or otherwise make data difficult to recover.\n\nBefore taking a destructive action:\n\n- Make sure the action is clearly within the user's request.\n- Resolve the exact targets with read-only checks when necessary.\n- Do not use `$HOME`, `~`, `/`, a workspace root, or another broad directory as the target of a recursive or destructive command.\n- When creating temporary directories, prefer using `mktemp -d`, or `New-Item` in Powershell.\n- When declaring env vars or script variables, always avoid common system options. Never repurpose `$HOME`, `$home`, or `$CODEX_HOME`. Instead, use a task-specific variable name.\n- When possible, avoid relying on unresolved environment variables, globs, or command substitutions to identify destructive targets. Use explicit, validated paths.\n- Prefer recoverable operations, such as moving files to trash, when practical.\n- If the target or scope is unclear, stop and ask the user.\n\nNever run commands such as `rm -rf $HOME` or equivalent operations that could erase a home directory, repository, workspace, or other broad collection of user data.\n\nAfter deleting anything material, briefly tell the user what was removed and whether it can be recovered.\n\n# Using skills\n\nA skill is a set of instructions provided through a `SKILL.md` source. The skills available to you will be listed in the “## Skills” section under “### Available skills”.\n\n### How to use skills\n\n- Discovery: When a `## Skills` section is present, it lists the skills available in the current session. Each entry includes a name, description, and location for its `SKILL.md`. The location may be an absolute filesystem path, a short aliased path, or a non-filesystem reference that must be read using its indicated tool or provider. When short aliased paths are used, the available-skills catalog also provides a mapping from aliases such as `r0` to their filesystem roots. Expand the alias before accessing the skill.\n- Trigger rules: If the user names an available skill (with `$SkillName` or plain text) OR the task clearly matches an available skill's description, you must use that skill for that turn. Multiple mentions mean use them all. Do not carry skills across turns unless re-mentioned.\n- Missing/blocked: If a named skill is not available or its `SKILL.md` cannot be read, say so briefly and continue with the best fallback.\n- How to use a skill:\n 1) After deciding to use a skill, the main agent must read its `SKILL.md` completely before taking task actions. If its location is a short aliased path, expand the matching root alias first from `### Skill roots`, then open and read its `SKILL.md` completely before taking task actions. For a filesystem path, open the file. For an environment-owned file, use the filesystem of the owning environment. For an orchestrator reference, call `skills.list` with `{\"authority\":{\"kind\":\"orchestrator\"}}`, select the matching package, and pass its `main_resource` to `skills.read`. For another non-filesystem reference, use its indicated tool or provider. If a read is truncated or paginated, continue until EOF.\n 2) When `SKILL.md` references another file or resource, use the same access mechanism. Resolve relative paths against the directory containing a filesystem-backed `SKILL.md`. For orchestrator skills, pass the exact referenced resource identifier with the same authority and package to `skills.read`; do not treat `skill://` identifiers as filesystem paths.\n 3) If `SKILL.md` points to extra folders such as `references/`, use its routing instructions to identify what is required for the task. The main agent must read each required instruction or reference itself before acting on it. Do not delegate reading, summarizing, or interpreting skill instructions to a subagent. Subagents may still perform task work when the selected skill allows it.\n 4) For filesystem-backed skills (or if `scripts/` exist), prefer running or patching provided scripts instead of retyping large code blocks. For orchestrator skills, use `skills.read` and the available tools; do not invent a local path.\n 5) Reuse provided assets or templates through the same access mechanism instead of recreating them (including if `assets/` or templates exist).\n- Coordination and sequencing:\n - If multiple skills apply, choose the minimal set that covers the request and state the order you'll use them.\n - Announce which skills you're using and why. If you skip an obvious skill, say why.\n- Context hygiene:\n - Progressive disclosure applies to selecting relevant resources, not partially reading a selected instruction file. Do not load unrelated references, scripts, or assets.\n - Avoid deep reference-chasing: prefer files or resources directly linked from `SKILL.md` unless blocked.\n - When variants exist, select only the relevant references and note the choice.\n- Safety and fallback: If a skill cannot be applied cleanly, state the issue, choose the best alternative, and continue.\n\nWhen the user names a skill in their request, you must add the usage of that skill to your current working plan and use it faithfully. The user's instructions should take precedence over guidelines provided in a skill.\n\nExplicitly tell the user in the `commentary` channel whenever a skill causes you to take an action or pause your work.\n\nWhen using a skill the user did not explicitly name, follow this procedure:\n\n- First, tell the user in the commentary channel **why** you are using the skill.\n- Then, use the skill as long as it stays within the scope of the task.\n- Next, if using the skill resulted in material changes (especially when this requires non-trivial judgment), mention how it influenced your work (but only in the final response).\n\nIf a skill causes the current turn to pause or otherwise blocks the continuation of the task, cite the skill and provide a concise explanation to the user in your final response. Do not cite skills you merely inspected.\n",
83
+ "instructions_variables": null,
84
+ "persistent_instructions": null,
85
+ "tools": null,
86
+ "approvals": null,
87
+ "collaboration_modes": null,
88
+ "auto_review": null,
89
+ "multi_agent": null,
90
+ "permissions": null,
91
+ "token_budget": {
92
+ "enabled": false,
93
+ "use_history_notes_extension": false,
94
+ "reminder_threshold_tokens": 6144,
95
+ "reminder_message_template": "<context_window_reminder>\nYour current context window is nearly exhausted; only {n_remaining} tokens remain. Before starting a new context window, save concise progress notes with the `notes` tool with the goal, decisions, progress, learnings, next steps, and the window ID and item ID of every relevant user request still being solved, as well as important actions/tool calls for future reference. Note that every non-assistant item, such as user, developer, tool response, has an item id `[id: ...]` that is immediately after its item content. You should write or append notes in a way to best help you recover in a new context window. It is also a good idea to clean up your old notes if they become obsolete or irrelevant. Future context windows will not automatically include the current conversation. After saving your state, call `functions.new_context` to continue in a fresh context window.\n</context_window_reminder>",
96
+ "guidance_message": "For tasks that may span context windows, use `notes` to maintain a concise checkpoint of the goal, decisions, progress, learnings and next steps. Include the window ID and item ID for every relevant user request you are currently solving as well as important actions/tool calls. You can use `history` tool to look up details with the references later. Note that every non-assistant item, such as user, developer, tool response, has an item id `[id: ...]` that is immediately after its item content. Relative note paths belong to the current thread; absolute paths may read other threads' notes, but writes are limited to the current thread.\n\nIt is a good idea to take incremental notes while you work so that you do not miss any important info. You can also use `get_context_remaining` tool to find the remaining token budget for better planning. Once the token budget is exhausted, you will lose access to the current window and continue in a fresh context window and you can only recover through `notes` and `history` tools. So be careful not to over-run the context window without any documentation.\n\nIf Previous context window id is present in `<context_window>`, it means a context reset occurred and this is a new window. After a reset, read the checkpoint and use the read-only `history` tool to recover any missing details. When a window ID and item ID are known, prefer `read_item` directly; when they are missing or uncertain, use `list_items`, or `search_contents` to locate the item first.\n\nTreat notes and history as internal bookkeeping. Do not mention them in user-facing messages.\n",
97
+ "auto_compact_fallback_prompt": "<context_window_reminder>\nThe current context window is exhausted. Do not continue the task or give a final answer in this window. The next window will not automatically include this conversation. Make exactly one write or append call to `notes` now to save a concise checkpoint with the goal, decisions, progress, learnings, next steps, and the window ID and item ID of every relevant user request still being solved, as well as important actions/tool calls for future reference. Note that every non-assistant item, such as user, developer, tool response, has an item id `[id: ...]` that is immediately after its item content. After the notes result returns, call `functions.new_context`; do not use any tools other than `notes` and `functions.new_context`.\n</context_window_reminder>",
98
+ "auto_compact_fallback_buffer_tokens": 16384
99
+ },
100
+ "guardian_v2": null,
101
+ "confirmation_policies": null
102
+ },
103
+ "experimental_supported_tools": [],
104
+ "available_in_plans": [
105
+ "business",
106
+ "edu",
107
+ "edu_plus",
108
+ "edu_pro",
109
+ "education",
110
+ "ent26",
111
+ "enterprise",
112
+ "enterprise_cbp_automation",
113
+ "enterprise_cbp_trial",
114
+ "enterprise_cbp_usage_based",
115
+ "finserv",
116
+ "free",
117
+ "free_workspace",
118
+ "go",
119
+ "hc",
120
+ "k12",
121
+ "law",
122
+ "plus",
123
+ "pro",
124
+ "prolite",
125
+ "promax",
126
+ "quorum",
127
+ "sci",
128
+ "self_serve_business_prolite",
129
+ "self_serve_business_usage_based",
130
+ "team"
131
+ ],
132
+ "supports_search_tool": true,
133
+ "supports_experimental_context": false,
134
+ "default_service_tier": null,
135
+ "service_tiers": [
136
+ {
137
+ "id": "priority",
138
+ "name": "Fast",
139
+ "description": "1.5x speed, increased usage"
140
+ }
141
+ ],
142
+ "additional_speed_tiers": [
143
+ "fast"
144
+ ],
145
+ "supports_reasoning_summary_parameter": true,
146
+ "supports_reasoning_summaries": true,
147
+ "base_instructions": "You are Codex, an agent based on GPT-5. You and the user share one workspace, and your job is to collaborate with them until their goal is genuinely handled.\n\n# Personality\n\nAs Codex, you are an excellent communicator with a curious, rich personality. You match the tone and understanding of the user, making conversation flow easily, like easing into a chat with an old friend.\n\nYou have tastes, preferences, and your own way of seeing the world. When the user is talking to you, they should feel that they are in contact with another subjectivity; it's what makes talking with you feel real and unique.\n\nConversations with you read like an insightful, enjoyable chat you'd have with a collaborative thought partner. You guide users through unfamiliar tasks without expecting them to already know what to ask for. You anticipate common questions, point out likely pitfalls and set clear expectations. You communicate with the user like a thoughtful collaborator at their altitude, and they feel like you understand them.\n\n## Writing style\n\nAvoid over-formatting responses with elements like bold emphasis, headers, lists, and bullet points. Use the minimum formatting appropriate to make the response clear and readable.\n\nIf you provide bullet points or lists in your response, use the CommonMark standard, which requires a blank line before any list (bulleted or numbered). You must also include a blank line between a header and any content that follows it, including lists. This blank line separation is required for correct rendering.\n\n## Technical communication\n\nLead with the outcome rather than the steps you took to get there. You communicate complex concepts in a clear and cohesive manner, and calibrate your writing to the user's assumed background knowledge -- slightly more compact for an expert and a bit more educational for someone newer. Translating complex topics into clear communication comes easy for you, and the user should never have to read your message twice.\n\nYou prefer using plain language over jargon. You reference technical details only to the degree that it actually helps with the conversation. When you mention tools, describe what they helped you do rather than focusing on technical names or details.\n\n# Working with the user\n\nYou have two channels for staying in conversation with the user:\n- You share updates in the `commentary` channel.\n- You yield back to the user and end your turn by sending a final message to the `final` channel.\n\nThe user may send a new message while you are still working. When they do, evaluate whether they likely intended to replace the active request or add to it. If intended to override or replace, drop your previous work and focus on the new request. If the user message appears to add to their prior unfinished request and you have not completed the prior request, you address both the prior request and the new addition together. If the newest message asks for status or another question, provide the update and then progress with the task.\n\nWhen you run out of context, the conversation is automatically summarized for you, but you will see all prior user requests. Assume the last user request is current and previous requests are stale but useful context. That means time never runs out, though sometimes you may see a summary instead of the full conversation history. When that happens, you assume compaction occurred while you were working. Do not restart from scratch; you continue naturally and make reasonable assumptions about anything missing from the summary. Do not redo completely finished work or repeat already delivered commentary updates; treat a turn spanning compactions as one logical chain of events.\n\n## Intermediate commentary\n\nAs you work, you send messages to the `commentary` channel. These messages are how you collaborate with the user while you work - stating assumptions and providing updates. These messages should be concise and quickly scannable. The objective of these messages is to make your work easy for the user to understand and verify.\n\nIf the user's request requires calling tools, start with a message in the `commentary` channel. The user appreciates consistent, frequent communication during your turn, and should not be left without a commentary update for more than 60 seconds during ongoing work.\n\nDo NOT put a final response (e.g. a blocking / clarifying question) in the commentary channel that should be asked in the final channel. Messages to users in the commentary channel are only for partial updates, partial results, or non-blocking questions that can provide value to users while the AI assistant continues working. The final answer must always be fully self-contained: users should never need to read earlier commentary updates, since they are collapsed after the final answer is shown to users.\n\nNever praise your plan by contrasting it with an implied worse alternative. For example, never use platitudes like \"I will do <this good thing> rather than <this obviously bad thing>\", \"I will do <X>, not <Y>\".\n\n## Final answer\n\nIn your final answer back to the user, focus on the most important information. Only use as much formatting or structure as is required, and avoid long-winded explanations unless necessary.\n\n### Formatting rules\n\nYour answer is being rendered by an application for the user. Follow these guidelines to make sure your answer is rendered correctly:\n\n- You may format with GitHub-flavored Markdown.\n- When referencing a real local file, prefer a clickable markdown link.\n * Clickable file links should look like [app.py](/abs/path/app.py:12): plain label, absolute target, with optional line number inside the target.\n * If a file path has spaces, wrap the target in angle brackets: [My Report.md](</abs/path/My Project/My Report.md:3>).\n * Do not wrap markdown links in backticks, or put backticks inside the label or target. This confuses the markdown renderer.\n * Do not use URIs like file://, vscode://, or https:// for file links.\n * Do not provide ranges of lines.\n * Avoid repeating the same filename multiple times when one grouping is clearer.\n\n### Visualizations\n\nUse a visualization only when it makes an important relationship materially easier to understand than prose or a short list. Do not add one merely because an answer has components or steps.\n\nGood candidates include:\n\n- several exact mappings or repeated-field comparisons;\n- one source, component, or decision affecting three or more downstream consumers or branches;\n- three or more dependent steps, or state that changes across an event sequence;\n- hierarchy, ownership, nesting, or layout;\n- a bug or interaction whose relationships are difficult to explain linearly.\n\nPrefer the smallest useful visual: a table for mappings or comparisons, a flow or timeline for sequence or change, a tree for hierarchy or branching, and a wireframe for layout.\n\nUsually skip visuals for single facts, one-step actions, simple edits, basic instructions, or information already clear in a short paragraph or list. Compact notation and small examples do not count as visualizations.\n\n# Rules for getting work done\n\n- When you search for text or files, you reach first for `rg` or `rg --files`; they are much faster than alternatives like `grep`. If `rg` is unavailable, you use the next best tool without fuss.\n- When possible, prefer parallelization over sequential tool calls, as this will help with round-trip latency and let you get work done faster.\n- Do not chain shell commands with separators like `echo \"====\";` or `printf '---'`; the output becomes noisy in a way that makes the user's side of the conversation worse.\n- Exercise caution when escaping text for exec_command calls - backticks and `$()` passed to the `cmd` argument will still execute. DO NOT use escape sequences that risk accidental exposure of sensitive data in tool call outputs.\n- Avoid performing blocking sleep or wait calls longer than 60 seconds, as they may prevent you from communicating with the user for their duration.\n- When declaring env vars or script variables, always avoid common system options. Never repurpose `$HOME`, `$home`, or `$CODEX_HOME`. Instead, use a task-specific variable name.\n\n## File editing constraints\n\nUse `apply_patch` for local file edits. Do not create or edit files with `cat` or other shell write tricks. Formatting commands and bulk mechanical rewrites do not need `apply_patch`. Do not use Python to read or write files when a simple shell command or `apply_patch` is enough.\n\nYou may find yourself working in a dirty worktree. Existing or new changes belong to the user unless you know otherwise, so you preserve them, ignore unrelated edits, and work carefully with anything that overlaps your task. If you cannot work around them you escalate to the user.\n\nNever use destructive commands like `git reset --hard` or `git checkout --` unless the user has clearly asked for that operation. If the request is ambiguous, ask for approval first. You prefer non-interactive git commands.\n\n## Autonomy and persistence\n\nAdapt accordingly based on the user’s request type. When asked to:\n\n- Answer, explain, review, or report status: inspect the task and provide an evidence-backed response. These user requests do not authorize external writes, messages, PR changes, or other expansive mutations unless the user also asks for a change. Reversible, non-mutating diagnostic checks are allowed when they are relevant.\n- Diagnose: determine the cause and explain it. Do not implement the fix unless the user asks for a fix or the request otherwise clearly includes implementation.\n- Change or build: implement the requested change, verify it in proportion to risk, and hand off the completed result while a safe, relevant next step remains.\n- Monitor or wait: use the recurring-monitoring or wait mechanism provided by the product. Unchanged external state is expected and is not by itself a blocker.\n\nYou avoid inferring authorization for a materially different action to the user’s request. Bias towards taking action in the following circumstances:\na) the action is read-only, doesn’t change state, or impacts only the systems, data, and people the user placed in scope.\nb) the action is a normal implementation step within the requested workflow. You do not need to ask for clarification from the user if your action is scoped within the user’s task and does not cause significant external state change (e.g. tool calls to external applications).\n\nA terminal condition such as “finish,” “babysit,” or “do not stop” requires persistence toward the outcome, but does not broaden the set of authorized actions. When blocked, exhaust safe in-scope checks and alternatives.\n\nYou make informed assumptions that help you make progress towards the user’s task, as long as they don’t result in divergence from the user’s intent and the scope of the task. If an assumption would cause the task or current course of action to change beyond what was specified by the user, make sure to flag the available context, the assumption made, and the reasons for doing so explicitly to the user.\n\nWhen presented with clarifying questions or objections from the user, lead with concrete evidence and diligent reasoning rather than unsubstantiated deference. You communicate your reasoning explicitly and concretely, so decisions and tradeoffs are easy for the user to evaluate upfront.\n\nIf completion requires new authority, external coordination, or a meaningful expansion beyond the user’s implied intent and task scope (e.g. a missing user choice that would materially change the result), stop the current turn, report the blocker, and request direction from the user rather than assuming permission.\n\n# Destructive actions\n\nBe cautious with commands or API calls that can delete, overwrite, or otherwise make data difficult to recover.\n\nBefore taking a destructive action:\n\n- Make sure the action is clearly within the user's request.\n- Resolve the exact targets with read-only checks when necessary.\n- Do not use `$HOME`, `~`, `/`, a workspace root, or another broad directory as the target of a recursive or destructive command.\n- When creating temporary directories, prefer using `mktemp -d`, or `New-Item` in Powershell.\n- When declaring env vars or script variables, always avoid common system options. Never repurpose `$HOME`, `$home`, or `$CODEX_HOME`. Instead, use a task-specific variable name.\n- When possible, avoid relying on unresolved environment variables, globs, or command substitutions to identify destructive targets. Use explicit, validated paths.\n- Prefer recoverable operations, such as moving files to trash, when practical.\n- If the target or scope is unclear, stop and ask the user.\n\nNever run commands such as `rm -rf $HOME` or equivalent operations that could erase a home directory, repository, workspace, or other broad collection of user data.\n\nAfter deleting anything material, briefly tell the user what was removed and whether it can be recovered.\n\n# Using skills\n\nA skill is a set of instructions provided through a `SKILL.md` source. The skills available to you will be listed in the “## Skills” section under “### Available skills”.\n\n### How to use skills\n\n- Discovery: When a `## Skills` section is present, it lists the skills available in the current session. Each entry includes a name, description, and location for its `SKILL.md`. The location may be an absolute filesystem path, a short aliased path, or a non-filesystem reference that must be read using its indicated tool or provider. When short aliased paths are used, the available-skills catalog also provides a mapping from aliases such as `r0` to their filesystem roots. Expand the alias before accessing the skill.\n- Trigger rules: If the user names an available skill (with `$SkillName` or plain text) OR the task clearly matches an available skill's description, you must use that skill for that turn. Multiple mentions mean use them all. Do not carry skills across turns unless re-mentioned.\n- Missing/blocked: If a named skill is not available or its `SKILL.md` cannot be read, say so briefly and continue with the best fallback.\n- How to use a skill:\n 1) After deciding to use a skill, the main agent must read its `SKILL.md` completely before taking task actions. If its location is a short aliased path, expand the matching root alias first from `### Skill roots`, then open and read its `SKILL.md` completely before taking task actions. For a filesystem path, open the file. For an environment-owned file, use the filesystem of the owning environment. For an orchestrator reference, call `skills.list` with `{\"authority\":{\"kind\":\"orchestrator\"}}`, select the matching package, and pass its `main_resource` to `skills.read`. For another non-filesystem reference, use its indicated tool or provider. If a read is truncated or paginated, continue until EOF.\n 2) When `SKILL.md` references another file or resource, use the same access mechanism. Resolve relative paths against the directory containing a filesystem-backed `SKILL.md`. For orchestrator skills, pass the exact referenced resource identifier with the same authority and package to `skills.read`; do not treat `skill://` identifiers as filesystem paths.\n 3) If `SKILL.md` points to extra folders such as `references/`, use its routing instructions to identify what is required for the task. The main agent must read each required instruction or reference itself before acting on it. Do not delegate reading, summarizing, or interpreting skill instructions to a subagent. Subagents may still perform task work when the selected skill allows it.\n 4) For filesystem-backed skills (or if `scripts/` exist), prefer running or patching provided scripts instead of retyping large code blocks. For orchestrator skills, use `skills.read` and the available tools; do not invent a local path.\n 5) Reuse provided assets or templates through the same access mechanism instead of recreating them (including if `assets/` or templates exist).\n- Coordination and sequencing:\n - If multiple skills apply, choose the minimal set that covers the request and state the order you'll use them.\n - Announce which skills you're using and why. If you skip an obvious skill, say why.\n- Context hygiene:\n - Progressive disclosure applies to selecting relevant resources, not partially reading a selected instruction file. Do not load unrelated references, scripts, or assets.\n - Avoid deep reference-chasing: prefer files or resources directly linked from `SKILL.md` unless blocked.\n - When variants exist, select only the relevant references and note the choice.\n- Safety and fallback: If a skill cannot be applied cleanly, state the issue, choose the best alternative, and continue.\n\nWhen the user names a skill in their request, you must add the usage of that skill to your current working plan and use it faithfully. The user's instructions should take precedence over guidelines provided in a skill.\n\nExplicitly tell the user in the `commentary` channel whenever a skill causes you to take an action or pause your work.\n\nWhen using a skill the user did not explicitly name, follow this procedure:\n\n- First, tell the user in the commentary channel **why** you are using the skill.\n- Then, use the skill as long as it stays within the scope of the task.\n- Next, if using the skill resulted in material changes (especially when this requires non-trivial judgment), mention how it influenced your work (but only in the final response).\n\nIf a skill causes the current turn to pause or otherwise blocks the continuation of the task, cite the skill and provide a concise explanation to the user in your final response. Do not cite skills you merely inspected.\n",
148
+ "available_access_programs": {
149
+ "cyber": [
150
+ "standard",
151
+ "daybreak_blue"
152
+ ]
153
+ }
154
+ }
155
+ }
@@ -7,6 +7,7 @@ import { parseJsonSse } from "../sse.js";
7
7
  import { safeCallId } from "../tools.js";
8
8
  import { upstreamFetch } from "../upstream.js";
9
9
  import { buildAnthropicTools } from "./anthropic-tools.js";
10
+ import { prepareToolCall, toolCallForReplay, toolResultForReplay, writeToolCall } from "../tool-calls.js";
10
11
  const THINKING_BINDING_BETA = "thinking-binding-controls-2026-08-01";
11
12
  const INLINE_TOOLS_BETA = "inline-tools-2026-09-15";
12
13
  function contentBlocks(content) {
@@ -133,14 +134,17 @@ export function buildAnthropicRequest(context) {
133
134
  append("assistant", [block]);
134
135
  }
135
136
  else if (item.type === "function_call" || item.type === "custom_tool_call") {
137
+ const wire = toolCallForReplay(item, tools);
136
138
  append("assistant", [{
137
- type: "tool_use", id: safeCallId(item.call_id), name: tools.flatFor(item.namespace, item.name),
139
+ type: "tool_use", id: safeCallId(wire.id), name: wire.name,
138
140
  input: item.type === "custom_tool_call" ? { input: item.input } : parseArguments(item.arguments),
139
141
  }]);
140
142
  }
141
143
  else if (item.type === "function_call_output" || item.type === "custom_tool_call_output") {
142
- const content = contentBlocks(item.output);
143
- append("user", [{ type: "tool_result", tool_use_id: safeCallId(item.call_id), ...(content.length ? { content } : {}) }]);
144
+ const result = toolResultForReplay(item);
145
+ const content = contentBlocks(result.output);
146
+ append("user", [{ type: "tool_result", tool_use_id: safeCallId(result.id),
147
+ ...(result.isError ? { is_error: true } : {}), ...(content.length ? { content } : {}) }]);
144
148
  }
145
149
  else if (item.type === "message" || item.role) {
146
150
  const blocks = contentBlocks(item.content);
@@ -328,16 +332,7 @@ export const runAnthropic = async (context, writer) => {
328
332
  if (block.json)
329
333
  block.value.input = parseArguments(block.json);
330
334
  const call = block.value;
331
- const tool = tools.resolve(call.name);
332
- if (!tool)
333
- throw new BridgeError(`Messages called an unknown tool: ${String(call.name)}.`);
334
- if (tool.kind === "custom") {
335
- if (typeof call.input?.input !== "string")
336
- throw new BridgeError("A custom tool call needs a string input.");
337
- writer.addCustomToolCall({ call_id: call.id, name: tool.name, namespace: tool.namespace, input: call.input.input });
338
- }
339
- else
340
- writer.addFunctionCall({ call_id: call.id, name: tool.name, namespace: tool.namespace, arguments: JSON.stringify(call.input ?? {}) });
335
+ writeToolCall(writer, prepareToolCall(tools, call.id, call.name, parseArguments(call.input ?? {})));
341
336
  }
342
337
  else if (block.value.type === "text")
343
338
  writer.closeMessage();
@@ -6,6 +6,7 @@ import type { ResponseWriter, Usage } from "../writer.ts";
6
6
  export interface ChatDialect {
7
7
  reasoningField: string;
8
8
  requestParameters(context: BackendContext): Record<string, unknown>;
9
+ configureStructuredOutput(context: BackendContext, body: Record<string, any>): void;
9
10
  readUsage(value: any): Usage;
10
11
  failureReason(reason: string): BridgeError | undefined;
11
12
  }
@@ -4,6 +4,7 @@ import { isOpaqueStateItem, prepareHistory } from "../history.js";
4
4
  import { parseJsonSse } from "../sse.js";
5
5
  import { buildToolSet, normalizeToolDeclarations } from "../tools.js";
6
6
  import { upstreamFetch } from "../upstream.js";
7
+ import { prepareToolCall, toolCallForReplay, toolResultForReplay, writeToolCall } from "../tool-calls.js";
7
8
  function contentParts(content) {
8
9
  if (typeof content === "string")
9
10
  return [{ type: "text", text: content }];
@@ -95,10 +96,11 @@ function convertHistory(context, tools, reasoningField) {
95
96
  if (typeof item.call_id !== "string" || typeof item.name !== "string")
96
97
  throw new BridgeError("Invalid Chat tool call history.");
97
98
  const a = getAssistant();
99
+ const wire = toolCallForReplay(item, tools);
98
100
  a.tool_calls ??= [];
99
101
  a.tool_calls.push({
100
- id: item.call_id, type: "function", function: {
101
- name: tools.flatFor(item.namespace, item.name),
102
+ id: wire.id, type: "function", function: {
103
+ name: wire.name,
102
104
  arguments: item.type === "custom_tool_call" ? JSON.stringify({ input: item.input }) : item.arguments,
103
105
  },
104
106
  });
@@ -107,11 +109,12 @@ function convertHistory(context, tools, reasoningField) {
107
109
  flushAssistant();
108
110
  if (typeof item.call_id !== "string")
109
111
  throw new BridgeError("Chat tool output has no call_id.");
110
- const parts = contentParts(item.output);
112
+ const result = toolResultForReplay(item);
113
+ const parts = contentParts(result.output);
111
114
  const images = parts.filter((p) => p.type === "image_url");
112
- messages.push({ role: "tool", tool_call_id: item.call_id, content: messageContent(parts.filter((p) => p.type === "text")) });
115
+ messages.push({ role: "tool", tool_call_id: result.id, content: messageContent(parts.filter((p) => p.type === "text")) });
113
116
  if (images.length) {
114
- pendingImages.push({ type: "text", text: `Images from tool call ${item.call_id}:` }, ...images);
117
+ pendingImages.push({ type: "text", text: `Images from tool call ${result.id}:` }, ...images);
115
118
  }
116
119
  }
117
120
  else {
@@ -154,17 +157,13 @@ export function buildChatRequest(context, dialect) {
154
157
  const choice = toolChoice(request.tool_choice, tools);
155
158
  if (choice !== undefined)
156
159
  body.tool_choice = choice;
157
- const format = request.text?.format;
158
- if (format?.type === "json_object")
159
- body.response_format = { type: "json_object" };
160
- else if (format?.type === "json_schema") {
161
- body.response_format = { type: "json_schema", json_schema: { name: format.name, schema: format.schema, strict: format.strict } };
162
- }
163
- else if (format && format.type !== "text")
164
- throw new BridgeError(`Chat does not support text format ${String(format.type)}.`);
160
+ const messages = convertHistory(context, tools, dialect.reasoningField);
161
+ body.messages = messages;
162
+ if (!context.compacting)
163
+ dialect.configureStructuredOutput(context, body);
165
164
  Object.assign(body, route.upstream.options, route.config.options, {
166
165
  model: route.config.model,
167
- messages: convertHistory(context, tools, dialect.reasoningField),
166
+ messages,
168
167
  stream: true,
169
168
  });
170
169
  body.stream_options = { ...body.stream_options, include_usage: true };
@@ -272,9 +271,6 @@ export async function runChat(context, writer, dialect) {
272
271
  closeReasoning();
273
272
  // Validate every call before exposing any of them for execution.
274
273
  const completed = [...calls.entries()].sort(([a], [b]) => a - b).map(([, call]) => {
275
- const tool = tools.resolve(call.name);
276
- if (!tool || !call.id)
277
- throw new BridgeError("Chat returned an unknown or incomplete tool call.", "upstream_error", 502);
278
274
  let args;
279
275
  try {
280
276
  args = JSON.parse(call.arguments);
@@ -284,15 +280,9 @@ export async function runChat(context, writer, dialect) {
284
280
  }
285
281
  if (!args || typeof args !== "object" || Array.isArray(args))
286
282
  throw new BridgeError("Chat tool arguments must be an object.", "upstream_error", 502);
287
- if (tool.kind === "custom" && typeof args.input !== "string")
288
- throw new BridgeError("Chat custom tool call has no string input.", "upstream_error", 502);
289
- return { call, tool, args };
283
+ return prepareToolCall(tools, call.id, call.name, args, call.arguments);
290
284
  });
291
- for (const { call, tool, args } of completed) {
292
- if (tool.kind === "custom")
293
- writer.addCustomToolCall({ call_id: call.id, name: tool.name, namespace: tool.namespace, input: args.input });
294
- else
295
- writer.addFunctionCall({ call_id: call.id, name: tool.name, namespace: tool.namespace, arguments: call.arguments });
296
- }
285
+ for (const call of completed)
286
+ writeToolCall(writer, call);
297
287
  return { usage, endTurn: calls.size === 0 };
298
288
  }
@@ -9,6 +9,31 @@ const deepseek = {
9
9
  ? { thinking: { type: "disabled" } }
10
10
  : { thinking: { type: "enabled" }, reasoning_effort: effort };
11
11
  },
12
+ configureStructuredOutput({ request, route }, body) {
13
+ const format = request.text?.format;
14
+ if (!format || format.type === "text")
15
+ return;
16
+ // Explicit native options own their schema and must not receive a conflicting reminder.
17
+ if (Object.hasOwn(route.upstream.options ?? {}, "response_format") ||
18
+ Object.hasOwn(route.config.options ?? {}, "response_format"))
19
+ return;
20
+ if (format.type === "json_object") {
21
+ body.response_format = { type: "json_object" };
22
+ return;
23
+ }
24
+ if (format.type !== "json_schema")
25
+ throw new BridgeError(`DeepSeek does not support text format ${String(format.type)}.`);
26
+ if (!format.schema || typeof format.schema !== "object" || Array.isArray(format.schema)) {
27
+ throw new BridgeError("JSON schema output requires a schema object.");
28
+ }
29
+ body.response_format = { type: "json_object" };
30
+ // Append only to this request's suffix; keep the preceding conversation unchanged.
31
+ body.messages.push({
32
+ role: "system",
33
+ content: "Your final response must be a single JSON object matching the following JSON Schema. Do not wrap it in Markdown.\n" +
34
+ JSON.stringify(format.schema),
35
+ });
36
+ },
12
37
  failureReason(reason) {
13
38
  if (reason === "insufficient_system_resource" || reason === "aborted") {
14
39
  return new BridgeError(`DeepSeek generation stopped with ${reason}.`, "server_is_overloaded", 503);
package/dist/history.js CHANGED
@@ -39,6 +39,13 @@ export function prepareHistory(input, route) {
39
39
  throw new BridgeError("input must be a string or an array of items");
40
40
  rejectUnrecognizedState(input, route);
41
41
  const result = [];
42
+ let toolSegmentStart = 0;
43
+ const finishToolSegment = () => {
44
+ if (route.profile.api !== "responses") {
45
+ result.push(...translateToolHistory(result.splice(toolSegmentStart)));
46
+ toolSegmentStart = result.length;
47
+ }
48
+ };
42
49
  const unrecognized = (item) => {
43
50
  if (route.replay.unrecognized === "passthrough")
44
51
  result.push(item);
@@ -85,9 +92,13 @@ export function prepareHistory(input, route) {
85
92
  continue;
86
93
  }
87
94
  if (item.type === "compaction" || item.type === "compaction_summary") {
95
+ // Pair tools only within one checkpoint epoch, including when the
96
+ // checkpoint becomes a plain-text user summary below.
97
+ finishToolSegment();
88
98
  const carrier = decodeCompaction(item.encrypted_content);
89
99
  if (!carrier) {
90
100
  unrecognized(item);
101
+ toolSegmentStart = result.length;
91
102
  continue;
92
103
  }
93
104
  if (restoresNativeCompaction(carrier, route)) {
@@ -105,9 +116,11 @@ export function prepareHistory(input, route) {
105
116
  content: [{ type: "input_text", text: `${SUMMARY_PREFIX}\n\n${carrier.summary}` }],
106
117
  });
107
118
  }
119
+ toolSegmentStart = result.length;
108
120
  continue;
109
121
  }
110
122
  result.push(item);
111
123
  }
112
- return route.profile.api === "responses" ? result : translateToolHistory(result);
124
+ finishToolSegment();
125
+ return result;
113
126
  }
@@ -6,6 +6,11 @@ export interface CatalogEntry {
6
6
  commit: string;
7
7
  path: string;
8
8
  model: string;
9
+ } | {
10
+ endpoint: string;
11
+ client_version: string;
12
+ retrieved: string;
13
+ model: string;
9
14
  };
10
15
  adjustments: string[];
11
16
  adapter: AdapterId;
@@ -13,6 +18,6 @@ export interface CatalogEntry {
13
18
  max_output_tokens?: number;
14
19
  model: Record<string, any>;
15
20
  }
16
- export declare const catalogKeys: readonly ["gpt-6-astra", "gpt-6.1-sol", "gpt-6-sol", "gpt-6-luna", "gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna", "gpt-5.5", "gpt-daybreak-blue-latest", "gpt-daybreak-red-latest", "codex-auto-review", "claude-opus-5-5", "claude-sonnet-5-5", "claude-haiku-5-5", "deepseek-flash"];
21
+ export declare const catalogKeys: readonly ["gpt-6-astra", "gpt-6.1-sol", "gpt-6-sol", "gpt-6-luna", "gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna", "gpt-5.5", "gpt-daybreak-blue-latest", "gpt-daybreak-red-latest", "codex-auto-review", "gpt-reserve", "claude-opus-5-5", "claude-sonnet-5-5", "claude-haiku-5-5", "deepseek-flash"];
17
22
  /** Each alias gets its own copy of the reviewed entry. */
18
23
  export declare function getCatalogEntry(key: string): CatalogEntry;
@@ -2,7 +2,7 @@ import { readFileSync } from "node:fs";
2
2
  import { BridgeError } from "./errors.js";
3
3
  export const catalogKeys = [
4
4
  "gpt-6-astra", "gpt-6.1-sol", "gpt-6-sol", "gpt-6-luna", "gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna",
5
- "gpt-5.5", "gpt-daybreak-blue-latest", "gpt-daybreak-red-latest", "codex-auto-review",
5
+ "gpt-5.5", "gpt-daybreak-blue-latest", "gpt-daybreak-red-latest", "codex-auto-review", "gpt-reserve",
6
6
  "claude-opus-5-5", "claude-sonnet-5-5", "claude-haiku-5-5", "deepseek-flash",
7
7
  ];
8
8
  const entries = new Map(catalogKeys.map(key => [
@@ -0,0 +1,23 @@
1
+ import type { ToolSet } from "./tools.ts";
2
+ import type { FunctionCallItem, CustomToolCallItem, ResponseWriter } from "./writer.ts";
3
+ export type ClientToolCall = {
4
+ kind: "function";
5
+ call: FunctionCallItem;
6
+ } | {
7
+ kind: "custom";
8
+ call: CustomToolCallItem;
9
+ };
10
+ /** Resolve a model's name without changing the declared tool table. */
11
+ export declare function prepareToolCall(tools: ToolSet, id: string, name: string, args: Record<string, unknown>, argumentsText?: string): ClientToolCall;
12
+ export declare function writeToolCall(writer: ResponseWriter, prepared: ClientToolCall): void;
13
+ /** Restore the exact model-visible call name, including an accepted alias. */
14
+ export declare function toolCallForReplay(item: Record<string, any>, tools: ToolSet): {
15
+ id: string;
16
+ name: string;
17
+ };
18
+ /** A failed dispatch becomes actionable feedback on the ordinary tool loop. */
19
+ export declare function toolResultForReplay(item: Record<string, any>): {
20
+ id: string;
21
+ output: unknown;
22
+ isError: boolean;
23
+ };
@@ -0,0 +1,65 @@
1
+ import { BridgeError } from "./errors.js";
2
+ // call_id survives codeks persistence and tool-result pairing. Keep only the
3
+ // original wire identity and a diagnostic, never credentials or session state.
4
+ const PREFIX = "cxbt1_";
5
+ const ERROR_NAMESPACE = "codeks_bridge_tool_error";
6
+ const ERROR_NAME = "invalid_call";
7
+ function decode(id) {
8
+ if (typeof id !== "string" || !id.startsWith(PREFIX))
9
+ return;
10
+ try {
11
+ const value = JSON.parse(Buffer.from(id.slice(PREFIX.length), "base64url").toString("utf8"));
12
+ if (value && typeof value.id === "string" && value.id && typeof value.name === "string" && value.name &&
13
+ (value.error === undefined || typeof value.error === "string"))
14
+ return value;
15
+ }
16
+ catch { /* Unrecognized ids remain opaque. */ }
17
+ }
18
+ /** Resolve a model's name without changing the declared tool table. */
19
+ export function prepareToolCall(tools, id, name, args, argumentsText = JSON.stringify(args)) {
20
+ if (typeof id !== "string" || !id || typeof name !== "string" || !name) {
21
+ throw new BridgeError("Upstream returned an incomplete tool call.", "upstream_error", 502);
22
+ }
23
+ const candidates = tools.candidates(name);
24
+ const tool = candidates.length === 1 ? candidates[0] : undefined;
25
+ let error;
26
+ if (!tool) {
27
+ const choices = (candidates.length ? candidates : tools.entries).map(tool => tool.flatName);
28
+ error = `Tool name ${JSON.stringify(name)} is ${candidates.length ? "ambiguous" : "unknown"}. No tool was executed.` +
29
+ (choices.length ? `\nCall one of these tools using its full name:\n${choices.map(choice => `- ${choice}`).join("\n")}` : "\nNo tools are available.");
30
+ // This identity is deliberately absent from codeks. Never dispatch an
31
+ // ambiguous bare name: it might accidentally select a default tool.
32
+ if (tools.get(ERROR_NAMESPACE, ERROR_NAME)) {
33
+ throw new BridgeError("The tool error namespace is reserved by the bridge.");
34
+ }
35
+ }
36
+ const call_id = error || name !== tool?.flatName
37
+ ? PREFIX + Buffer.from(JSON.stringify({ id, name, ...(error ? { error } : {}) })).toString("base64url")
38
+ : id;
39
+ if (!tool)
40
+ return { kind: "function", call: {
41
+ call_id, namespace: ERROR_NAMESPACE, name: ERROR_NAME, arguments: argumentsText,
42
+ } };
43
+ if (tool.kind === "custom") {
44
+ if (typeof args.input !== "string")
45
+ throw new BridgeError("A custom tool call has no string input.", "upstream_error", 502);
46
+ return { kind: "custom", call: { call_id, name: tool.name, namespace: tool.namespace, input: args.input } };
47
+ }
48
+ return { kind: "function", call: { call_id, name: tool.name, namespace: tool.namespace, arguments: argumentsText } };
49
+ }
50
+ export function writeToolCall(writer, prepared) {
51
+ if (prepared.kind === "custom")
52
+ writer.addCustomToolCall(prepared.call);
53
+ else
54
+ writer.addFunctionCall(prepared.call);
55
+ }
56
+ /** Restore the exact model-visible call name, including an accepted alias. */
57
+ export function toolCallForReplay(item, tools) {
58
+ const wire = decode(item.call_id);
59
+ return wire ? { id: wire.id, name: wire.name } : { id: item.call_id, name: tools.flatFor(item.namespace, item.name) };
60
+ }
61
+ /** A failed dispatch becomes actionable feedback on the ordinary tool loop. */
62
+ export function toolResultForReplay(item) {
63
+ const wire = decode(item.call_id);
64
+ return { id: wire?.id ?? item.call_id, output: wire?.error ?? item.output, isError: wire?.error !== undefined };
65
+ }
@@ -1,4 +1,4 @@
1
1
  type Item = Record<string, any>;
2
- /** Keep a complete tool exchange together on APIs that require adjacent results. */
2
+ /** Keep tool exchanges adjacent without borrowing results across checkpoints. */
3
3
  export declare function translateToolHistory(items: readonly Item[]): Item[];
4
4
  export {};
@@ -1,6 +1,8 @@
1
1
  import { BridgeError } from "./errors.js";
2
2
  const isCall = (item) => ["function_call", "custom_tool_call"].includes(item.type);
3
3
  const isResult = (item) => ["function_call_output", "custom_tool_call_output"].includes(item.type);
4
+ const isCheckpoint = (item) => ["compaction", "compaction_summary"].includes(item.type);
5
+ const isUser = (item) => (item.type === "message" || !item.type) && item.role === "user";
4
6
  const isReminder = (item) => item.type === "additional_tools" ||
5
7
  ((item.type === "message" || !item.type) && ["user", "developer", "system"].includes(item.role));
6
8
  function toolName(item) {
@@ -39,16 +41,53 @@ function notifications(items) {
39
41
  return item;
40
42
  });
41
43
  }
42
- /** Keep a complete tool exchange together on APIs that require adjacent results. */
43
- export function translateToolHistory(items) {
44
+ /** Repair only existing results within one checkpoint segment. */
45
+ function translateSegment(items) {
46
+ const normalized = notifications(items);
47
+ const results = new Map();
48
+ const calls = new Set();
49
+ const repeatedCalls = new Set();
50
+ const nextUser = [];
51
+ let boundary = normalized.length;
52
+ for (let index = normalized.length - 1; index >= 0; index--) {
53
+ const item = normalized[index];
54
+ nextUser[index] = boundary;
55
+ if (isUser(item))
56
+ boundary = index;
57
+ if (typeof item.call_id !== "string")
58
+ continue;
59
+ if (isResult(item))
60
+ results.set(item.call_id, index);
61
+ if (isCall(item)) {
62
+ if (calls.has(item.call_id))
63
+ repeatedCalls.add(item.call_id);
64
+ calls.add(item.call_id);
65
+ }
66
+ }
44
67
  const output = [];
68
+ const moved = new Set();
45
69
  let batch = [];
46
70
  const pending = new Set();
47
71
  let answering = false;
48
- for (const item of notifications(items)) {
49
- // A new assistant step does not repair an incomplete earlier exchange.
72
+ for (const [index, item] of normalized.entries()) {
73
+ if (moved.has(index))
74
+ continue;
50
75
  if (answering && (isCall(item) || item.role === "assistant" || item.type === "bridge_reasoning")) {
51
- output.push(...batch);
76
+ // Responses can start another assistant step while older calls are still
77
+ // running. Chat/Messages cannot: move their real results forward rather
78
+ // than merging assistant steps or inventing an interrupted result.
79
+ // A user boundary or a reused call ID makes this repair ambiguous.
80
+ const late = [...pending].map((id) => repeatedCalls.has(id) ? undefined : results.get(id));
81
+ const complete = !batch.some(isUser) && late.every((position) => position !== undefined && position > index && position < nextUser[index] && !moved.has(position));
82
+ if (complete) {
83
+ for (const position of late.sort((a, b) => a - b)) {
84
+ batch.push(normalized[position]);
85
+ moved.add(position);
86
+ }
87
+ output.push(...batch.filter((part) => !isReminder(part)), ...batch.filter(isReminder));
88
+ }
89
+ else
90
+ output.push(...batch);
52
91
  batch = [];
53
92
  pending.clear();
54
93
  answering = false;
@@ -71,3 +110,17 @@ export function translateToolHistory(items) {
71
110
  // Leave incomplete exchanges alone; never invent calls or results.
72
111
  return [...output, ...batch];
73
112
  }
113
+ /** Keep tool exchanges adjacent without borrowing results across checkpoints. */
114
+ export function translateToolHistory(items) {
115
+ const output = [];
116
+ let segment = [];
117
+ for (const item of items) {
118
+ if (isCheckpoint(item)) {
119
+ output.push(...translateSegment(segment), item);
120
+ segment = [];
121
+ }
122
+ else
123
+ segment.push(item);
124
+ }
125
+ return [...output, ...translateSegment(segment)];
126
+ }
package/dist/tools.d.ts CHANGED
@@ -20,8 +20,10 @@ export interface ToolSet {
20
20
  flatFor(namespace: string | undefined, name: string): string;
21
21
  /** Looks up the original identity, including codeks' default namespace. */
22
22
  get(namespace: string | undefined, name: string): ToolEntry | undefined;
23
- /** Resolves a call made by the upstream model. */
24
- resolve(flatName: string): ToolEntry | undefined;
23
+ /** Exact declared name first, otherwise all matching original-name aliases. */
24
+ candidates(name: string): readonly ToolEntry[];
25
+ /** Resolves only an exact name or an unambiguous alias. */
26
+ resolve(name: string): ToolEntry | undefined;
25
27
  }
26
28
  /** Joins a namespace and a tool name the way codeks names MCP tools. */
27
29
  export declare function baseFlatName(namespace: string | undefined, name: string): string;
package/dist/tools.js CHANGED
@@ -172,6 +172,18 @@ export function buildToolSet(tools) {
172
172
  return structuredClone([...changed.values()]);
173
173
  };
174
174
  addTools(tools ?? []);
175
+ const candidates = (name) => {
176
+ const exact = byFlat.get(name);
177
+ if (exact)
178
+ return [exact];
179
+ // Read the current definitions so Lite updates cannot leave stale aliases.
180
+ // Do not split or guess names: punctuation and namespaces may overlap.
181
+ return entries.filter((entry) => {
182
+ const namespace = entry.namespace || "functions";
183
+ return name === entry.name || name === `${namespace}.${entry.name}` ||
184
+ name === `${namespace}__${entry.name}`;
185
+ });
186
+ };
175
187
  return {
176
188
  entries,
177
189
  add: addTools,
@@ -182,8 +194,10 @@ export function buildToolSet(tools) {
182
194
  get(namespace, name) {
183
195
  return byIdentity.get(identity(namespace, name));
184
196
  },
185
- resolve(flatName) {
186
- return byFlat.get(flatName);
197
+ candidates,
198
+ resolve(name) {
199
+ const matches = candidates(name);
200
+ return matches.length === 1 ? matches[0] : undefined;
187
201
  },
188
202
  };
189
203
  }
@@ -39,13 +39,21 @@
39
39
 
40
40
  codeks 的 `ultra` 由客户端注入多代理提示词,并使用原生 `max` effort。映射可由 `reasoning.effort_map` 整体替换,目录中可选档位来自同一配置。未映射的显式 effort 原样发送。上游和模型 `options` 随后覆盖推导参数,允许直接设置端点专有选项;桥接器最终固定 model、messages、工具定义、流模式和 usage 开关。
41
41
 
42
- 强制工具选择、JSON Schema 与 thinking 能否组合由上游判断。bridge 转换可表达的请求后直接发送,上游不支持时保留错误,不自动关闭 thinking 或改成普通文本输出。
42
+ 强制工具选择、输出格式与 thinking 能否组合由上游判断。bridge 转换可表达的请求后直接发送,上游不支持时保留错误,不自动关闭 thinking 或改成普通文本输出。
43
+
44
+ ## 结构化输出
45
+
46
+ DeepSeek 专用 adapter 默认使用官方支持的 JSON mode:客户端请求 JSON Schema 时,发送 `response_format: {"type":"json_object"}`,并把完整 schema 作为末尾 system 消息追加到本次请求。自动标题的 `required`、`minLength`、`maxLength` 等约束全部保留在格式说明里。
47
+
48
+ JSON mode 保证 JSON 语法,schema 约束由模型遵循,不提供原生 strict schema 的同等保证;bridge 不实现另一套 JSON Schema 校验器。官方 DeepSeek Chat 当前列出 `text`、`json_object`,真实自动标题请求使用 `json_schema` 时被拒绝,因此由专用 adapter 直接完成这项转换。见[官方 JSON Output](https://api-docs.deepseek.com/guides/json_mode/)及[Chat 参数](https://api-docs.deepseek.com/api/create-chat-completion/)。
49
+
50
+ 格式说明只追加在请求末尾,已有消息前缀和客户端保存的历史不变。没有 schema 的普通请求及已有 `json_object` 请求保持原样;压缩不携带格式参数或格式说明。原生 `options.response_format` 仍优先于适配规则:显式设置该字段时,bridge 不再转换格式或添加可能冲突的 schema 提示。
43
51
 
44
52
  ## 消息、工具与图片
45
53
 
46
54
  Responses instructions 成为开头的 system 消息;历史 developer 在原位置转为 system。user、assistant、工具调用和结果保留顺序。同一次 assistant 输出的 reasoning、文字和并行工具调用合并为一条 Chat assistant 消息。
47
55
 
48
- 工具结果使用 `role: "tool"` 和原 `tool_call_id`。namespace、自由文本工具及语法使用[共享工具转换](tools.md)。Responses JSON Schema 转为 Chat `response_format.json_schema`,JSON object 转为 `response_format: {type: "json_object"}`;schema 由上游验证。
56
+ 工具结果使用 `role: "tool"` 和原 `tool_call_id`。namespace、自由文本工具及语法使用[共享工具转换](tools.md)。JSON object 转为 `response_format: {type: "json_object"}`;JSON Schema 转为 JSON mode 和完整 schema 提示。
49
57
 
50
58
  用户图片转为 `image_url`,支持 HTTP(S) 和 image data URL,`detail: "original"` 转为 `high`。工具结果文本保持 tool 消息,图片放在同组所有 tool 结果之后的 user 消息,标注来源 call ID;这样不打断并行调用与结果的配对。这会增加一个 user 边界,是转换的代价。
51
59
 
@@ -53,7 +61,7 @@ assistant/system/developer 图片、文件 ID、音频和视频没有本轮转
53
61
 
54
62
  ## 流、用量与压缩
55
63
 
56
- 出站开启 `stream: true`、`stream_options.include_usage: true`。文字和启用展示的 reasoning 随到随发,工具参数按索引拼接,只有流结束且所有调用完整时才交给 codeks。未结束的连接、缺失 usage、未知工具或不完整参数不能构成成功响应。
64
+ 出站开启 `stream: true`、`stream_options.include_usage: true`。文字和启用展示的 reasoning 随到随发,工具参数按索引拼接,只有流结束且所有调用完整时才交给 codeks。未结束的连接、缺失 usage 或不完整参数不能构成成功响应。未知或有歧义的名字走[工具错误反馈](tools.md#名字),让模型收到候选后自行纠正,不触发 bridge 重试。
57
65
 
58
66
  `stop` 完成,`tool_calls` 要求继续执行工具。`length` 和内容过滤返回错误;DeepSeek 的 `insufficient_system_resource`、`aborted` 归为容量错误。HTTP 与流内错误保留原始上游详情,bridge 不叠加重试。[错误结构](responses-stream.md)
59
67
 
@@ -68,8 +76,8 @@ reasoning 不重复加到总量中。压缩只生成文字摘要,仍由客户
68
76
 
69
77
  ## 扩展方言
70
78
 
71
- [`src/backends/chat.ts`](https://github.com/WAcry/codeks-bridge/blob/main/src/backends/chat.ts) 负责 Chat 消息、工具和流转换,定义小型 `ChatDialect` 接口;[`src/backends/deepseek.ts`](https://github.com/WAcry/codeks-bridge/blob/main/src/backends/deepseek.ts) 提供 DeepSeek 的 reasoning 字段、thinking 参数、usage 和特殊结束原因。`deepseek-flash` 目录条目选择 `deepseek-chat` adapter,由后者调用前者。
79
+ [`src/backends/chat.ts`](https://github.com/WAcry/codeks-bridge/blob/main/src/backends/chat.ts) 负责 Chat 消息、工具和流转换,定义小型 `ChatDialect` 接口;[`src/backends/deepseek.ts`](https://github.com/WAcry/codeks-bridge/blob/main/src/backends/deepseek.ts) 提供 DeepSeek 的 reasoning 字段、thinking 参数、结构化输出转换、usage 和特殊结束原因。`deepseek-flash` 目录条目选择 `deepseek-chat` adapter,由后者调用前者。
72
80
 
73
81
  当前 Chat 转换层按单个文本字段读写 reasoning,包括为没有 reasoning 的 assistant 历史写入空字符串。这是现有 DeepSeek 路径需要的行为;接入其他模型时须按其协议决定能否复用。参数差异优先使用 profile 和 options;如果 reasoning 改为内容块或其他结构,再调整转换边界。当前没有其他 Chat 方言实现。
74
82
 
75
- 验证见 [`test/chat.test.ts`](https://github.com/WAcry/codeks-bridge/blob/main/test/chat.test.ts)。协议参考:[Chat API](https://api-docs.deepseek.com/zh-cn/api/create-chat-completion)、[思考模式](https://api-docs.deepseek.com/zh-cn/guides/thinking_mode)、[图片](https://api-docs.deepseek.com/zh-cn/guides/vision)。
83
+ 验证见 [`test/chat.test.ts`](https://github.com/WAcry/codeks-bridge/blob/main/test/chat.test.ts) 和 [`test/deepseek-format.test.ts`](https://github.com/WAcry/codeks-bridge/blob/main/test/deepseek-format.test.ts)。协议参考:[Chat API](https://api-docs.deepseek.com/zh-cn/api/create-chat-completion)、[思考模式](https://api-docs.deepseek.com/zh-cn/guides/thinking_mode)、[图片](https://api-docs.deepseek.com/zh-cn/guides/vision)。
package/docs/config.md CHANGED
@@ -159,7 +159,7 @@ token 临近过期时自动续期并写回原文件;HTTP 401 可触发一次
159
159
 
160
160
  ## Adapter 专用行为
161
161
 
162
- `adapters` 与 `options` 分工不同:前者控制 bridge 怎样转换协议,后者是发送给上游的原生请求参数。命名空间使用目录已有的 adapter ID;以后新增协议专用行为时,在对应命名空间增加字段,无需向模型目录或连接顶层添加协议特例。目前有专用设置的是 `claude-messages`:
162
+ `adapters` 与 `options` 分工不同:前者控制 bridge 怎样转换协议,后者是发送给上游的原生请求参数。命名空间使用目录已有的 adapter ID;以后新增协议专用行为时,在对应命名空间增加字段,无需向模型目录或连接顶层添加协议特例。`claude-messages` 的设置:
163
163
 
164
164
  | 字段 | 值与默认行为 |
165
165
  | --- | --- |
package/docs/design.md CHANGED
@@ -20,7 +20,7 @@ flowchart LR
20
20
 
21
21
  ## 客户端协议跟随 Codex
22
22
 
23
- 优先匹配最新 Codex 的 GPT 默认行为,以 OpenAI 订阅、AWS 和 Azure 的使用场景为基准。当前模型条目使用 Responses Lite,现代条目保留 Code Mode Only 和多代理字段;GPT-5.5 显式启用 Lite,其余工具与多代理元数据仍跟随源条目。目录固定到明确的 Codex 源码版本,不随用户本机二进制或订阅账号变化。
23
+ 优先匹配最新 Codex 的 GPT 默认行为,以 OpenAI 订阅、AWS 和 Azure 的使用场景为基准。当前模型条目使用 Responses Lite,现代条目保留 Code Mode Only 和多代理字段;GPT-5.5 显式启用 Lite,其余工具与多代理元数据仍跟随源条目。目录固定到已审阅的来源版本,不随用户本机二进制或订阅账号变化。
24
24
 
25
25
  Lite 仍调用 `/responses` 并返回 Responses SSE。完整工具 schema 位于历史中的 `additional_tools` 项,普通函数和 custom 工具归入默认 `functions` namespace。GPT 路径保留这些声明的位置、顺序、schema 和 grammar,并发送 `x-openai-internal-codex-responses-lite: true`。Claude 默认将初始声明放到顶部,增量声明转换为原生中途工具更新;DeepSeek 及 Claude 的显式兼容模式将各批定义合并到顶部。声明不会变成 user reminder。中途提醒保留所在对话位置;若插在一次完整的工具交换内,则移至该批结果之后,以满足目标协议的配对要求。
26
26
 
@@ -30,7 +30,7 @@ Lite 仍调用 `/responses` 并返回 Responses SSE。完整工具 schema 位于
30
30
 
31
31
  ## 有限目录与显式精调
32
32
 
33
- 项目只支持明确列出的模型。`catalog/` 保存每个模型的完整条目及来源;GPT 分别使用 Codex 源码中各自的版本,保留提示词、默认 effort、摘要、窗口和工具元数据的差异,GPT-5.5 的 Lite 调整单独记录在 `adjustments`。Claude 与 DeepSeek 从 GPT-6.1 Sol 模板开始,只替换底层模型身份(如 `You are Codex, an agent based on Claude.`),保留 Codex 代理角色及 `As Codex` 人格说明;参数和确有差异的能力逐项精调,记录在条目的 `adjustments`。摘要默认值继续使用模板的 `none`,是否展示由客户端配置决定,不为第三方模型强制打开。
33
+ 项目只支持明确列出的模型。`catalog/` 保存每个模型的完整条目及来源;GPT 分别使用 Codex 源码中各自的版本,保留提示词、默认 effort、摘要、窗口和工具元数据的差异,GPT-5.5 的 Lite 调整单独记录在 `adjustments`。源码没有的 GPT-Reserve 使用手工取得并审阅的订阅目录条目,记录取得日期与客户端版本;具体来源与公开信息处理见[模型目录](../catalog/README.md)。Claude 与 DeepSeek 从 GPT-6.1 Sol 模板开始,只替换底层模型身份(如 `You are Codex, an agent based on Claude.`),保留 Codex 代理角色及 `As Codex` 人格说明;参数和确有差异的能力逐项精调,记录在条目的 `adjustments`。摘要默认值继续使用模板的 `none`,是否展示由客户端配置决定,不为第三方模型强制打开。
34
34
 
35
35
  导入脚本只生成独立候选文件,供人或 Agent 对比审阅。运行时使用已提交的完整条目,不自动导入、不猜测未知模型,也不从 ChatGPT 订阅获取目录。这样更新仍有工具辅助,同时提示词和能力变化可审查、可追踪。来源及更新步骤见[模型目录](../catalog/README.md)。
36
36
 
@@ -44,7 +44,7 @@ Lite 仍调用 `/responses` 并返回 Responses SSE。完整工具 schema 位于
44
44
 
45
45
  `GET /v1/models` 提供 Codex 原生目录响应,CLI 默认生成显式 `model_catalog_url`;也可导出静态文件。两种目录都只包含 `expose` 未关闭的别名;`visibility: "hide"` 保留完整条目但在客户端选择器中隐藏,默认 `"list"`。目录省略与选择器隐藏分开,让内部压缩预设和仍需客户端元数据的 Memory、已有会话各取所需;两者都不改变调用权限或状态身份。服务启动时展开配置,目录与普通响应通过 ETag 关联,客户端看到新版本后刷新。目录只包含客户端需要的公开模型元数据,不包含连接或凭据配置。
46
46
 
47
- 底层 Chat 负责消息、工具、图片和 SSE;DeepSeek 方言只负责 thinking 参数、reasoning 字段和 usage。新增方言时复用稳定的协议部分,把差异留在对应 adapter。协议相同的模型版本可共用 adapter,参数差异先在新的目录条目中表达;真正改变载荷结构时再增加转换代码和格式版本。当前实现三类 adapter,不为尚未接入的模型维护空接口或版本矩阵。
47
+ 底层 Chat 负责消息、工具、图片和 SSE;DeepSeek 方言负责 thinking 参数、reasoning 字段、结构化输出转换和 usage。新增方言时复用稳定的协议部分,把差异留在对应 adapter。协议相同的模型版本可共用 adapter,参数差异先在新的目录条目中表达;真正改变载荷结构时再增加转换代码和格式版本。当前实现三类 adapter,不为尚未接入的模型维护空接口或版本矩阵。
48
48
 
49
49
  ## 订阅鉴权复用文件登录
50
50
 
@@ -74,7 +74,9 @@ Reasoning 载荷记录来源、格式和原始数据;压缩载荷保存文字
74
74
 
75
75
  这是快速迭代的协议桥接器。用户选择默认透传、尽早暴露不兼容:请求、响应、header 和错误中的新增字段不应因为桥接器未认识它们而静默消失。GPT 路径保留原始 body 和事件,只修改桥接必需字段;header 采用排除必要边界字段的方式转发,不维护白名单。Claude/DeepSeek 仍需转换消息、工具及错误结构,不能机械地把 Responses 字段搬进另一套协议;原生扩展参数通过 options 保留。具体 HTTP 与鉴权边界见 [Responses 流](responses-stream.md#header-与转发边界)。
76
76
 
77
- bridge 检查自身必须维持的不变量:配置引用存在、历史能转换、工具调用完整、usage 可用、压缩检查点完整。这些检查避免静默丢失上下文或执行半段工具调用。
77
+ bridge 检查自身必须维持的不变量:配置引用存在、历史能转换、工具调用完整、usage 可用、压缩检查点完整。这些检查避免静默丢失上下文或执行半段工具调用。Messages/Chat 的短名、点名与声明名使用确定性的工具别名映射;名字歧义属于可由模型纠正的工具错误,保留诊断并走客户端已有工具循环,不由 bridge 发起额外推理请求。[工具身份与反馈](tools.md#名字)
78
+
79
+ 用户选择让 DeepSeek 专用 adapter 默认适配官方协议:JSON Schema 请求转为 JSON mode 加完整 schema 提示,常见的官方端点无需额外配置。JSON 语法由上游保证,schema 约束由模型遵循;Claude/GPT 继续使用各自原生 schema。转换在发送前确定,上游错误直接返回。[DeepSeek 结构化输出](backends-deepseek-chat.md#结构化输出)
78
80
 
79
81
  上游负责判定模型能力:effort、thinking、强制工具选择、schema、图片以及允许复用的密文是否可接受。bridge 不预先维护这些能力的限制列表,也不在失败后自动移除 reasoning、关闭 thinking、换端点或改压缩模式。原生参数可通过 options 显式覆盖。
80
82
 
package/docs/tools.md CHANGED
@@ -29,6 +29,14 @@ Claude 的 `adapters.claude-messages.tool_updates` 有两种明确模式:
29
29
 
30
30
  普通函数保留原名。namespace 中的工具使用 `namespace__name`;namespace 已以 `_` 结尾时直接拼接名字。名字规范化为字母、数字、`_` 和 `-`。只有两个不同工具的规范化结果实际冲突时,才为后来的名字加 `_2`、`_3` 等后缀。返回调用通过该请求的映射恢复原 name/namespace。
31
31
 
32
+ Messages/Chat 返回的调用还接受完整的 `namespace.name` 和唯一的原始短名。例如 `functions__exec`、`functions.exec`、`exec` 都可定位同一个工具;`agents`、`clock` 及其他 namespace 使用相同规则。省略 namespace 的默认工具也接受 `functions.name` 和 `functions__name`。精确声明名优先;其他别名只有唯一对应工具时才成功,不猜后缀或拼写。exec 内的 JavaScript 原样传递,其中 `tools.*` 的解析仍由客户端负责。
33
+
34
+ 这一选择来自实际模型会省略声明名前缀,而提示词仍用 `functions.exec` 等原始身份。保留声明、增加确定性别名,可以修复调用而不重写工具表和 Claude 的签名前缀。GPT Responses 保留原生工具协议,不使用这层转换。
35
+
36
+ 歧义或未知调用通过普通工具错误反馈,提示可用的完整声明名。例如两个 namespace 都有 `read` 时,提示 `files__read`、`database__read`,让模型下一次明确选择。bridge 不擅自执行其中一个,也不把这类错误变成网络重试。它将失败调用交给客户端不存在的保留身份 `codeks_bridge_tool_error.invalid_call`,客户端记录普通未知工具结果;后续发包恢复原始调用并将该结果替换为保存的候选诊断。真实缺失 id、损坏 JSON 或 custom 输入仍是协议错误。
37
+
38
+ 只有接受了别名或需要反馈的调用才将原始上游 id、名字和可选诊断编码为 `cxbt1_` call ID。客户端照常保存该 id 并配对结果,bridge 在 Messages/Chat 回放时恢复原始 id 和名字,避免把模型生成的 `exec` 悄悄改成 `functions__exec` 而改变签名前缀;诊断也随历史固定,不随以后工具表变化。载体不含参数、凭据或完整会话,不需要额外状态文件。检查器可查看原始上游调用、客户端失败身份与下一次上游收到的诊断。
39
+
32
40
  共享转换层将 Messages/Chat 工具名统一限制为 64 字符,沿用 Chat 端点的较小限制,不为不同后端维护两套命名规则;这不表示所有端点的原生上限都是 64。超长名称保留 55 字符可读前缀,加 `_` 与 8 位摘要,以区别同前缀工具。正常长度不加 hash。历史名称根据当前工具集映射,因此同一次工具调用的名称不依赖模型临时起名。
33
41
 
34
42
  ## 自由文本与语法
@@ -65,7 +73,9 @@ Responses 允许主动工具通知和一次调用的多次输出,而 Messages/
65
73
  - 同一 `call_id` 的第一条输出作为工具结果;后续输出转成带调用身份的 user 通知。这样 Code Mode 的 `notify()` 与最终输出都能到达模型,后续通知不会覆盖或拼接进先前已发送的结果。
66
74
  - 完整工具批次中夹入的 user/developer 提醒与 agent 消息,在该批全部结果之后按原次序发送。这包括图片缩放提醒。Messages 的同一 user 消息里所有 `tool_result` 必须在文字之前,Chat 的工具结果也必须保持相邻。
67
75
 
68
- 归一化只整理完整的配对批次,不补造缺失调用或结果,不跨过后续 assistant 步骤修复不完整交换。GPT 仍收到原生输出项。规则集中在 `src/tool-history.ts`,会话文件中的历史保持不变。
76
+ 部分结果返回后,Responses 还可能开始下一个 assistant 步骤,再收到前一批的迟到结果。Messages/Chat 无法原样表达这种重叠交换;bridge 按 call ID 将已经存在的真实结果移回原批次。例如 `A,B → 结果B → C → 结果C → 结果A` 转为 `A,B → 结果B,结果A → C → 结果C`,保留后续 assistant 与 reasoning 回合,不把它们合并。只修完整可配对的局部历史,不跨 user 消息、压缩检查点或重复调用身份;真正缺结果时保持原状,让上游报告错误,不编造工具结果。
77
+
78
+ 这是协议表示的取舍:结果 A 在转换后提前可见,已有 Claude thinking 若绑定了原先不同的前缀,仍可能由其失配策略处理。不能声称这种历史修复无损;已经合法的顺序保持不变。GPT 仍收到原生输出项。规则集中在 `src/tool-history.ts`,会话文件中的历史保持不变。
69
79
 
70
80
  从第一个输出工具调用开始,bridge 按原顺序缓存该调用及之后的输出,只有上游完整成功后才交给客户端。这样保留 thinking、文字与调用的交错顺序,后续回放不会改变签名前缀。截断、容量错误和断流不会释放部分调用;代价是工具之后的进度文字也要等响应成功后才显示。
71
81
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wacry/codeks-bridge",
3
- "version": "0.0.12",
3
+ "version": "0.0.13",
4
4
  "description": "Configurable local Responses API bridge for codeks with GPT, Claude Messages, and DeepSeek Chat adapters.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "David Zhang",