Skip to content

feat: 为 DeepTutor 添加独立 Codex OAuth 与动态模型目录 - #690

Closed
TyrionH-is-coding wants to merge 21 commits into
HKUDS:mainfrom
TyrionH-is-coding:feat/codex-oauth-provider
Closed

TyrionH-is-coding wants to merge 21 commits into
HKUDS:mainfrom
TyrionH-is-coding:feat/codex-oauth-provider

Conversation

@TyrionH-is-coding

@TyrionH-is-coding TyrionH-is-coding commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

背景

DeepTutor 原有 openai_codex 路径仍要求手工填写 ChatGPT backend URL 与 API Key,并不等同于独立 Codex OAuth。本 PR 将它改为 DeepTutor 自己管理的浏览器 OAuth、账户动态模型目录和 Responses Provider,不接入或复用本机 Codex CLI 登录。

主要改动

  • 新增独立 PKCE + loopback OAuth 服务,回调仅绑定 127.0.0.1,校验 state,并支持取消、超时、刷新与尽力撤销。
  • 凭据只写入 <user-root>/private/openai-codex/;实现文件锁、原子写入、generation 竞态保护和 symlink/reparse 防护。
  • 不读取、复制、修改或删除 ~/.codex。
  • 从当前 Codex 账号动态读取模型目录,按账号与 generation 隔离缓存。
  • 仅当 source == live 且目录包含完全匹配的原始 ID gpt-5.6-sol 时,自动切换到 Codex / GPT-5.6-Sol;不做别名、大小写或 Terra/Luna 替代。
  • Web Settings 只显示 OAuth 跳转、连接状态、刷新模型和退出登录,不显示 API Key/Base URL/Extra Headers;模型切换留在 DeepTutor Web 内。
  • CLI 的 deeptutor provider login openai-codex 与 Web 共用同一服务和私有凭据。
  • 401 只为下一次请求刷新 token,不重放当前推理;429、网络错误和目录失败均不会回退到 OPENAI_API_KEY 或其他付费 Provider。
  • 登出期间阻止新推理,活动推理存在时拒绝登出;退出后移除受管理目录,并且不覆盖用户后来主动选择的其他 Provider。
  • 多用户部署中,普通用户使用管理员托管的 Codex Provider 凭据,与现有管理员模型目录所有权一致。

审查修复

medium 深度审查额外发现并修复:

  • 模型刷新与登出竞态可能让迟到刷新重新写回已删除的 Codex Profile;
  • 损坏凭据中的 None/布尔值会被宽松转换;
  • 异步请求后才打开 OAuth 窗口可能被浏览器弹窗策略拦截;
  • i18next 禁用点号层级解析时,嵌套 codex.oauth.* 文案会显示原始键名;
  • 实机验收发现首次登录前没有 Profile 时,登出会残留已删除的 Codex 活动 ID;已补回归测试并在无有效备份时清空选择。

来源与安全边界

  • OAuth 与缓存设计借鉴 CSSwitch:
    SuperJJ007/CSSwitch@4e0af6ba7909dca22f1257b168172ecbe4af4836。
  • THIRD_PARTY_NOTICES.md 已附固定来源、MIT 版权与许可证全文。
  • OpenAI Codex 源码只用于协议核对,没有复制其源码。
  • Codex backend 兼容路径明确标注为实验性,上游接口可能变化。

自动验证

  • pytest 聚焦套件:129 passed, 2 skipped
  • 登出回归修复后的 Codex 聚焦套件:111 passed, 2 skipped
  • ruff check:通过
  • ruff format --check:通过
  • pip check:通过
  • Web Node tests:220 passed
  • Web ESLint:0 errors(仓库原有 91 warnings)
  • i18n parity:通过(audit 仅报告仓库原有潜在 literal)
  • tsc --noEmit:通过
  • Next.js production build:通过
  • git diff --check origin/main...HEAD:通过
  • Linux CI:Lint、Web、Python 3.11–3.14 Import Check 与完整 Python Tests 全部通过

Windows 全量 pytest -q 结果为 2786 passed, 10 skipped, 24 failed。24 个失败均位于本 PR 未改动的 Partners 可选依赖或现有 POSIX 路径、resource、sleep、symlink 权限测试;Linux PR CI 已全绿。

人工验收

  • Settings 选择 OpenAI Codex 后不显示 API Key/Base URL,仅显示 OAuth 卡片。
  • 中英文 OAuth 文案在真实页面正确渲染。
  • 在 OpenAI 页面完成真实账号授权,状态为 connected。
  • 实时账号目录返回 7 个模型,精确包含 gpt-5.6-sol 并自动设为活动模型。
  • 普通聊天返回 DT_CODEX_OK;reasoning_effort=medium 请求成功;强制工具调用返回 acceptance_echo({"value":"codex-oauth-ok"})。
  • 受管理 Profile 为只读、API Key 为空;凭据只落在 DeepTutor 私有目录。
  • 登出清除凭据与模型缓存,移除受管理 Profile,并恢复空目录选择为 null。
  • ~/.codex 源码零引用;受控登出窗口元数据 0 项变化。真实调用窗口只观测到 Codex Desktop 自身的全局状态/进程列表变化,没有认证、凭据或模型文件变化。

真实账号验收与 Linux CI 已完成,PR 可进入正式审查。

@TyrionH-is-coding
TyrionH-is-coding marked this pull request as ready for review July 24, 2026 11:16
@pancacake

Copy link
Copy Markdown
Collaborator

close as merged into dev

@pancacake pancacake closed this Jul 26, 2026
pancacake pushed a commit that referenced this pull request Jul 26, 2026
Replaces the oauth_cli_kit indirection with DeepTutor's own PKCE loopback
sign-in, an account-scoped live model catalog, and a Settings card that exposes
only the OAuth surface. Credentials live in `<user-root>/private/openai-codex/`
with owner-only permissions, atomic writes, and a generation guard that stops a
late refresh from resurrecting a signed-out session; `~/.codex` is never read or
modified. A CLI path shares the same service.

A Codex token authorizes one person's ChatGPT plan, so credentials anchor to the
signing-in account's own root and the managed profile is marked `owner_bound`:
`redacted_model_access` drops it for every caller, and it is not offered as an
assignable model. Signing in publishes the profile but only activates it when no
LLM is configured yet, so it never repoints a deployment that already has one.

Also from review: reschedule the status poll so one dropped response cannot
strand the card on "waiting"; defer the catalog reload when the operator has
unsaved edits instead of discarding them; log the real cause behind the generic
provider error; stop promising a retry when the token refresh actually failed;
bind both loopback stacks since `localhost` may resolve to either; and drop the
provider metadata fields nothing consumed.
pancacake added a commit that referenced this pull request Jul 26, 2026
Maintenance release on top of v1.5.4, with two new ways to bring a model.

- OpenAI Codex is a first-party OAuth provider (#690): browser sign-in
  against your own ChatGPT plan replaces the API-key fields, credentials
  stay in <user-root>/private/openai-codex/ with owner-only permissions,
  and the managed profile is owner-bound so it is never handed out through
  grants or made active over an already-configured LLM.
- Eden AI joins as the 35th LLM binding (#671), an OpenAI-compatible
  gateway addressed as <provider>/<model>.
- Knowledge bases answer from a real document inventory instead of
  guessing from retrieval hits: a per-KB inventory rides the system prompt
  and a new kb_files tool enumerates on demand with glob/substring
  filters, mounted under rag's gate and deniable per partner.
- The rag tool cites the chunks, entities, and reports retrieval actually
  returned (#694) rather than an echo of its own query; the local LightRAG
  pipeline still surfaces nothing to cite.
- GraphRAG indexing runs on a worker thread with its own asyncio loop
  (#695), so UVICORN_LOOP=asyncio is no longer needed, and two config
  faults that broke the first run are fixed (#699).
- Assorted: unique optimistic message ids (#698, a v1.5.4 regression that
  dropped the assistant reply from the visible thread), partner-chat
  manual scrolling respected (#704), claude-opus-5 recognized as
  effort-based (#703), Kimi models omit temperature outright, and
  deeptutor start keeps relaying logs on legacy Windows code pages (#702).
- Typing: narrow the loopback callback server to asyncio.Server and gate
  the msvcrt lock path on sys.platform so it type-checks off Windows.

Release notes: assets/releases/ver1-5-5.md
pancacake added a commit to SeleiXi/DeepTutor that referenced this pull request Aug 12, 2026
Merges dev and reworks this branch against what an adversarial pass found.

**The administrator's subscription was grantable.** A CodeBuddy credential
is one person's IDE-plugin login read from this host, exactly the shape
HKUDS#690 ruled must never be lent out — but ``owner_bound`` is stamped on the
*managed* profile Codex publishes, and a CodeBuddy profile is created by
hand in the settings editor with nowhere to acquire it. Binding now decides
too (``OWNER_BOUND_BINDINGS``), so the profile is never offered in the
grant editor.

**The agent sandbox failed open.** ``_build_options`` probed ten candidate
kwarg sets and returned the first the SDK accepted; six of them carry no
``permission_mode`` and no turn limit. An SDK that renamed those kwargs
would silently fall through to an unrestricted agent. Every candidate now
carries them — both spellings — and exhausting the list raises. The extra
is pinned ``<0.2`` so a minor bump cannot reintroduce the fall-through, and
dropped from ``all`` (it vendors a ~130 MB headless CLI that chat does not
need).

**A local file chose where the token was sent.** ``cached_product_endpoint``
accepted any string starting with ``http`` out of another application's
cache blob. Anything able to write under the service account's home could
point the bearer token at a host of its choosing. Restricted to https on
the two known deployments; an operator who needs another still sets
``CODEBUDDY_BASE_URL``, which is honoured first.

**Logout ended a session DeepTutor does not own.** It called the SDK's
logout against the auth file the IDE plugin and CLI share, signing the
operator out of their editor. It now drops our cached clients and reports
where the session actually lives.

**A phone number was a display label.** ``user_label`` fell back to
``phoneNumber``, returned verbatim by the status endpoint to every admin.

Also: keep the usage-extraction change from wiping real token counts when a
gateway echoes a zero-filled usage object on delta chunks (it applies to
every openai_compat provider, not just this one); replace the two
``binding == "codebuddy"`` tests in the chat loop and the explore
capability with a ``threads_session_id`` predicate, so generic code no
longer names a provider; and revert 33 files whose only change was a
Prettier reformat in the opposite direction from the 3.8.3 the repo pins —
they would have made the next contributor's ``pre-commit run --all-files``
touch 33 unrelated files.
pancacake added a commit that referenced this pull request Aug 12, 2026
An adversarial pass over #818 / #789 / #780 after merging.

**Codex sign-ins from before this week stopped working (#789).**
``validate_runtime_profile`` compared the profile's ``codex_account_binding``
for equality, but that key is written only by ``sync_codex_catalog`` — every
managed profile published by #690/#774 has none, so ``None != <hash>`` made
each of them look like another account's and locked its owner out of Codex
until they re-ran "Refresh models". Absent now reads as legacy; a binding
that is present and different is still an account switch and still refused.

**Overriding reasoning effort for one turn returned 409 (#789).** The same
function also required the request's effort to be byte-equal to the value
stored in the catalog. Effort is a per-request knob, not part of the identity
that ties a config to a token — the check now stops at model membership.
Its test asserted the old behaviour and has been rewritten around what the
function is actually for.

**The reasoning-effort endpoint left the runtime caches stale (#789).** It
writes the catalog the runtime resolves against, like every other catalog
write in this router, but skipped ``_invalidate_runtime_caches()``.

**OrcaRouter claimed Anthropic prompt caching (#818).** ``supports_prompt_caching``
makes ``_build_kwargs`` inject ``cache_control`` blocks into any ``anthropic/*``
or ``claude*`` request — an OpenRouter extension. No other gateway sets it and
nothing established the second one accepts it; a strict gateway would 400 every
Claude turn. Also fixed ``anthropic/claude-sonnet-4.6`` in the fallback list,
which the rest of the repo spells with dashes, so a user picking it from our
own menu would have got "model not found".

**OrcaRouter inserted itself into the curated menus (#818).** The featured
lists are hand-picked and rendered as a positional numbered menu, so adding an
entry shifted Ollama from [10] to [11]. The registry entry alone already makes
a provider reachable via "Show all" and the Settings dropdown; which providers
are featured is a maintainer decision. The README paragraph goes with it — no
other provider has per-provider prose there, and it would have been translated
into ten languages.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants