Skip to content

feat(models): manage team and local model profiles - #675

Merged
jeff-r2026 merged 1 commit into
Tencent:mainfrom
laolaoPlayer:feature/model-profile-manager
Sep 24, 2026
Merged

jeff-r2026 merged 1 commit into
Tencent:mainfrom
laolaoPlayer:feature/model-profile-manager

Conversation

@laolaoPlayer

@laolaoPlayer laolaoPlayer commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Add teamai models commands for local and team model profiles; applying a profile always requires models switch.
  • Define gateway catalogs with model_groups, so each model ID appears once alongside the protocols it supports. Team and personal catalogs share the same format; API keys stay local.
  • Switch Claude Code, Codex, OpenCode, CodeBuddy, and WorkBuddy while preserving unrelated settings and supporting guarded restoration.
  • Validate team catalogs on pull and push. Unknown catalog fields, duplicate model IDs, and literal api_key values are rejected.
  • Guard Buddy ownership using only TeamAI-written fields, including availableModels; detect Codex provider-name and inline-table collisions; serialize model operations with an ownership lock.

Type of Change

  • Bug fix (non-breaking change that fixes an issue)
  • New feature (non-breaking change that adds functionality)
  • Breaking change (fix or feature causing existing behavior to change)
  • Documentation only
  • Refactor / internal cleanup

Test Plan

  • npm run build and npx tsc --noEmit pass after rebasing onto origin/main.

  • npx vitest run --silent and Linux-style XDG_CONFIG_HOME=/tmp/teamai-inherited-test npx vitest run --coverage --silent: 290 files, 4313 passed, 1 skipped in both runs.

  • Built CLI model E2E: grouped team catalogs, all five Agent switch/restore paths, preservation of unrelated settings, and rejection of unknown catalog fields by push.

  • Regression tests: Buddy-added metadata and owned-field edits; Codex quoted, inline, and invalid parent TOML provider definitions; unknown fields at catalog/profile/group levels.

  • Final built-CLI E2E: 17/17 passed, including model switching/restoration for Claude, Codex, OpenCode, CodeBuddy and WorkBuddy; Git, GitLab and GitHub each exercised with Claude, Codex, CodeBuddy and OpenCode.

  • Full npm run test:e2e -- --silent on macOS: 209 passed, 8 GitHub fixture tests failed because a login shell resolved the system gh instead of the test's fake gh. Those exact 8 tests passed when rerun with a PATH-preserving test shim; the model E2E also passed again on the final build. Three live-provider tests were skipped because their credentials were not configured.

  • Earlier manual acceptance exercised Claude Code CLI, Codex CLI, OpenCode, CodeBuddy CLI, and WorkBuddy IDE with real model services.

  • New regressions: incomplete uninstall retains managed.json; Claude auth/header conflicts; Buddy allowlists; URL query credentials; inline Codex parent table; post-refresh push validation; non-interactive secret prompt; concurrent switches; dry-run read-only behavior.

Related Issues

Closes #632
Supersedes the implicit-apply direction proposed in #403.

Notes for Reviewers

  • Pull discovers and validates a team catalog; it does not write Agent model settings.
  • Gateway profiles use the given root URL for Anthropic and derive <root>/v1 for OpenAI protocols. Explicit endpoint mappings use their configured URL exactly.
  • Team catalogs contain ${API_KEY} only; the actual secret is entered locally through a hidden prompt, environment reference, or stdin.
  • TeamAI does not add a temperature field.

@jeff-r2026 jeff-r2026 self-assigned this Sep 20, 2026
@github-actions

Copy link
Copy Markdown

Findings

  • [P1 blocking] src/models/profile.ts:260 uses readJson(), which returns null for both missing and malformed JSON. A corrupted values.json is therefore treated as empty, and the next add/configure/remove operation overwrites it, silently deleting every stored credential. Parsing failures must abort rather than return {}.
  • [P1 blocking] src/models/switch.ts:494 restores Buddy profiles through writeSnapshot(state.previous). After switching CodeBuddy/WorkBuddy from model ID A to B, previous.id remains A, so restore removes A rather than B and leaves the TeamAI-managed B entry installed. Restore must replace/remove state.lastWritten.id while restoring state.previous.
  • [P1 blocking] src/models/switch.ts:156 only snapshots double-quoted Codex TOML strings. Valid settings such as model = 'personal-model' are recorded as absent, overwritten during switching, and deleted rather than restored. Use a TOML parser or preserve the original assignment syntax.
  • [P1 blocking] src/models/profile.ts:37 accepts URLs containing plaintext credentials, such as https://user:[email protected]. This contradicts the secret-free team-catalog guarantee and allows secrets to be committed and displayed by models show; reject URL userinfo at minimum.
  • [P1 blocking] src/index.ts:629 adds a major public command while every README*.md remains unchanged; README.md:193 still explicitly says models are not implemented. The repository rules require all affected README language variants to be updated consistently.

Testing

  • The PR description includes a test plan and explicit real-CLI/end-to-end records, so that review requirement is satisfied.

@daoiqi

daoiqi commented Sep 20, 2026 •

Copy link
Copy Markdown
Collaborator

The model configuration file is somewhat difficult to work with. too many config item

@jeff-r2026
jeff-r2026 requested a review from daoiqi September 20, 2026 06:26
@laolaoPlayer
laolaoPlayer force-pushed the feature/model-profile-manager branch from bfcc1fa to 60c88c3 Compare September 20, 2026 06:34
@laolaoPlayer

laolaoPlayer commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor Author

Addressed all five automated P1 findings in the current single commit:

  • malformed local model-input JSON now fails closed instead of being treated as an empty store;
  • Buddy restore removes the latest TeamAI-managed model ID before restoring the original entry;
  • Codex snapshots now parse valid TOML strings, including single-quoted values;
  • endpoint URLs containing userinfo are rejected both in templates and after local interpolation;
  • the model catalog/explicit teamai models workflow is now reflected in every README translation.

Validation: npm run build, npx tsc --noEmit, and all 3545 tests pass. Real CLI dry-runs also pass for Claude, Codex, OpenCode, CodeBuddy, and WorkBuddy without changing the active local configurations.

@laolaoPlayer
laolaoPlayer force-pushed the feature/model-profile-manager branch from 60c88c3 to 9c24ddf Compare September 20, 2026 06:37
@github-actions

Copy link
Copy Markdown

Findings

  • [P1 blocking] src/models/switch.ts:132 — Claude switching overwrites gateway/model fields while preserving conflicting ANTHROPIC_API_KEY and ANTHROPIC_CUSTOM_HEADERS. These settings can override authentication or send user-owned headers to the newly selected endpoint. Treat them as ownership conflicts or manage and restore them.
  • [P1 blocking] src/models/switch.ts:274 — CodeBuddy/WorkBuddy writes only models and leaves a non-empty availableModels allowlist unchanged. The newly switched model therefore remains unavailable in configurations using that supported format; switching and restoration must update the allowlist too.
  • [P1 blocking] src/uninstall.ts:969 — Full uninstall continues deleting ~/.teamai, including models/managed.json, when restoration returns failed or skipped. This permanently discards the saved original configuration while managed credentials/settings may remain in agent files. Preserve the manifest or abort shared removal until restoration succeeds.
  • [P1 blocking] src/models/profile.ts:38 — The “secret-free” catalog validation accepts credentials embedded in URL query parameters, such as https://host/v1?api_key=sk-...; teamai push then permits committing them and models show prints them. Credential-bearing URL parameters must be rejected or required to use declared secret placeholders outside base_url.

The PR description includes a concrete test plan and real-CLI/end-to-end verification, so it satisfies the review requirement for testing notes.

Comment thread docs/usage-guide.zh-CN.md Outdated
在团队仓库中创建 `models/models.yaml`:

```yaml
version: 1

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

version 不要了

Comment thread docs/usage-guide.zh-CN.md Outdated
protocol: anthropic
base_url: ${COMPANY_GATEWAY_URL}
api_key: ${API_KEY}
agents:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

不用区分 agents , 统一下发所有 agents,先支持: claude , codex, codebuddy ,workbuddy, opencode

Comment thread docs/usage-guide.zh-CN.md Outdated
profiles:
- id: company-anthropic
name: Company Anthropic gateway
inputs:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

配置放到 teamai.yaml 顶层,参考 packages , 没有项目级,模型下发只有 user 级别。
models:

  • name1
    url
    api key, 可从环境变量读取
    protocol
  • name2 ....

@github-actions

Copy link
Copy Markdown
  • [P1 blocking] src/models/profile.ts:76 — ModelProfileBaseSchema and the outer file schema are not .strict(), so unknown fields are silently discarded during validation. A catalog containing apiKey: sk-secret or credentials: ... therefore passes pull/push validation while the plaintext remains committed, violating the advertised secret-free catalog guarantee.
  • [P1 blocking] src/models/switch.ts:420 — Buddy ownership compares the complete model entry byte-for-byte. CodeBuddy/WorkBuddy may normalize entries by adding capability metadata, so merely launching the agent can make the snapshot differ; subsequent switches/restores then report an external edit and permanently leave TeamAI’s model entries behind. Compare only the fields TeamAI owns.
  • [P1 blocking] src/models/switch.ts:237 — Codex collision detection recognizes only the literal [model_providers.teamai] spelling. Valid TOML forms such as [model_providers."teamai"] or model_providers.teamai = {...} are missed, after which TeamAI appends another definition for the same table and can leave config.toml invalid. Detect collisions from the parsed TOML structure before editing.
  • The PR description includes both a test plan and explicit real-CLI/end-to-end verification records, so it satisfies the review requirement.

@jeff-r2026

Copy link
Copy Markdown
Collaborator

This PR currently has merge conflicts with main. Please rebase and resolve them so review can continue.

@laolaoPlayer
laolaoPlayer force-pushed the feature/model-profile-manager branch from ee68ea0 to fdd6ae5 Compare September 23, 2026 07:52
@github-actions

Copy link
Copy Markdown

Findings

  • [P1 blocking] src/uninstall.ts:1024 still proceeds to executeRemoval() when model restoration returns skipped or failed. A full uninstall then deletes ~/.teamai/models/managed.json, permanently losing the snapshot required to restore settings that TeamAI left installed.
  • [P1 blocking] src/models/switch.ts:9 still overwrites Claude’s gateway/token fields while leaving conflicting ANTHROPIC_API_KEY and ANTHROPIC_CUSTOM_HEADERS intact. Those values can override authentication or forward user-owned headers to the selected endpoint; shell-level ANTHROPIC_* conflicts are also not checked.
  • [P1 blocking] src/models/switch.ts:383 updates only Buddy’s models array. When a non-empty availableModels allowlist exists, newly switched CodeBuddy/WorkBuddy models remain unavailable, and later restoration does not reconcile that allowlist.
  • [P1 blocking] src/models/profile.ts:38 still permits credentials in URL query parameters such as ?api_key=sk-secret. Such secrets remain commit-able in team catalogs and are printed by models show.
  • [P1 blocking] src/models/switch.ts:783 permits an existing inline parent table such as model_providers = { personal = {...} } because it lacks a teamai property. Appending [model_providers.teamai] then attempts to extend an immutable TOML inline table and corrupts config.toml.
  • [P1 blocking] src/push.ts:635 validates the model catalog before pushCore() resets and pulls the latest repository state. An invalid catalog received at src/push.ts:808 therefore bypasses validation and the push continues against it; validation must occur after the refresh.
  • [P1 blocking] src/utils/prompt.ts:104 bypasses isInteractive() and checks only TTY state. In CI or with TEAMAI_NONINTERACTIVE under a pseudo-terminal, models add/configure can wait indefinitely for a secret instead of failing non-interactively.
  • [P1 blocking] src/index.ts:695 adds a major public command while none of README.md, README.ja.md, README.ko.md, README.th.md, or README.zh-CN.md is updated. Repository rules require every README language variant to document affected behavior consistently.
  • [P2 non-blocking] src/models/switch.ts:675 performs an unlocked read-modify-write of the shared ownership manifest. Concurrent switches for different agents can each load the same manifest and overwrite one another, leaving one agent modified without restoration state.

Resolved Earlier Findings

  • Malformed local input JSON now fails closed.
  • Buddy restoration now removes the latest managed IDs.
  • Single-quoted Codex model settings are captured semantically.
  • URL userinfo is rejected.
  • Catalog schemas now reject unknown fields.
  • Buddy ownership ignores agent-added metadata.
  • Alternate Codex declarations of the teamai provider are detected.

The PR description includes a test plan and explicit real-CLI/end-to-end verification records, so the review-description testing requirement is satisfied.

@laolaoPlayer
laolaoPlayer force-pushed the feature/model-profile-manager branch from 3767b9d to aebac8d Compare September 23, 2026 08:36
@github-actions

Copy link
Copy Markdown

Findings

  • [P1 blocking] src/models/switch.ts:776 treats every inherited ANTHROPIC_* value as a shell override. Claude injects settings.json.env into its subprocesses, so running teamai models switch from a Claude session incorrectly skips Claude even when those values came from the settings TeamAI intends to replace.
  • [P1 blocking] src/models/switch.ts:10 does not own or restore ANTHROPIC_CUSTOM_MODEL_OPTION{,_NAME} and does not reconcile the existing local-agent model manifest. Switching over a server-delivered Claude model leaves its old model selection active; the next local-agent sync sees changed hashes, drops ownership, and can no longer update or clean up those fields.
  • [P1 blocking] src/models/switch.ts:278 only recognizes bare TOML keys. A valid Codex config using "model" = "personal" or 'model_provider' = "custom" gets an additional bare assignment appended, producing duplicate keys and an invalid config.toml.
  • [P1 blocking] src/uninstall.ts:1199 restores machine-global model state during every full project-scope uninstall because plan.includeShared is scoped to that project. Uninstalling one project—or its last configured tool—can therefore restore Claude, Codex, and other global settings still used by another TeamAI project.
  • [P2 non-blocking] src/uninstall.ts:1192 performs the model-restoration gate only after removing managed MCP servers. If restoration is skipped or fails, uninstall returns with an error but has already partially removed integrations from the current and sibling worktrees.
  • [P2 non-blocking] src/models/switch.ts:278 replaces the complete model and model_provider lines. Inline comments attached to those user settings are permanently discarded and cannot be recovered by models restore.

Review Status

  • All nine findings from the earlier review are resolved in the current diff.
  • The PR description contains a test plan and explicit real-CLI/end-to-end verification records, so the testing-description requirement is satisfied.

@laolaoPlayer
laolaoPlayer force-pushed the feature/model-profile-manager branch from 4f3233f to e68acb3 Compare September 23, 2026 09:26
@laolaoPlayer

Copy link
Copy Markdown
Contributor Author

Follow-up on the latest automated review: all six findings were reproducible against the previous revision and are addressed in e68acb3. Claude now distinguishes re-injected settings env from independent shell overrides, owns/restores server-delivered custom-model fields, and pauses local-agent model sync while an explicit profile is active. Codex quoted top-level keys and inline comments survive switch/restore. Project-scope uninstall leaves machine-global model state alone; user-scope model restoration gates MCP cleanup. Public docs and test fixtures no longer contain the internal gateway URL. Verification after rebase onto origin/main: npm run build, npx tsc --noEmit, 290 Vitest files (4317 passed, 1 skipped), and built-CLI isolated E2E for git/gitlab/github across Claude, Codex, OpenCode, CodeBuddy, and WorkBuddy, including Claude env injection and quoted Codex keys. No live gateway calls or real credentials were used in these tests.

@github-actions

Copy link
Copy Markdown

Findings

  • [P1 blocking] src/models/switch.ts:802 allows Claude provider-selection flags inherited from settings.json.env—such as CLAUDE_CODE_USE_BEDROCK, CLAUDE_CODE_USE_VERTEX, or CLAUDE_CODE_USE_FOUNDRY—but writeClaude() neither removes nor owns them. The command therefore reports a successful gateway switch while Claude can continue using the previous provider.
  • [P1 blocking] src/models/switch.ts:687 persists the resolved plaintext credential for explicit CodeBuddy/WorkBuddy mappings even when the profile was configured with --from-env. Because both api_key_value and api_key_env are populated, the value always wins; use the environment reference first as the grouped-profile path does.
  • [P1 blocking] src/models/switch.ts:897 treats every existing Buddy model ID as user-owned. Models previously installed by TeamAI’s local-agent delivery are therefore reported as collisions, so an explicit profile cannot switch CodeBuddy/WorkBuddy to a different endpoint using the same model ID.
  • [P1 blocking] src/models/profile.ts:442 revalidates interpolated URLs for protocol and userinfo only. A declared URL input can resolve to a URL containing a query or fragment, bypassing the catalog’s prohibition and allowing credentials such as ?api_key=... into agent configuration and restore state.
  • [P2 non-blocking] src/models/switch.ts:313 collapses every run of three or more newlines across the entire Codex configuration whenever the TeamAI provider block is replaced or restored. This unnecessarily rewrites unrelated user-owned formatting; limit normalization to the edited block boundary.
  • [P2 non-blocking] src/models-cmd.ts:266 and src/models-cmd.ts:314 persist profile edits before loading and validating the corresponding input file. If values.json is malformed or required inputs remain missing, models configure exits with an error after already modifying models.yaml.

Review Status

  • The findings from the earlier review passes are otherwise resolved in the current diff.
  • The PR description includes a test plan and explicit built-CLI/end-to-end verification records, so the review-description testing requirement is satisfied.
  • Per request, I only inspected the diff and did not run or install PR code.

@laolaoPlayer

Copy link
Copy Markdown
Contributor Author

Follow-up on the latest automated review: I reproduced all six findings against the previous revision and addressed them in 940b55b. Claude now skips an active Bedrock/Vertex/Foundry selection; explicit Buddy mappings prefer environment references; TeamAI local-agent-owned Buddy IDs can be replaced by an explicit switch; resolved URLs reject query/fragment injection; Codex provider edits preserve unrelated blank lines; and failed configure validation leaves models.yaml unchanged. Regression tests cover each case.

Public documentation examples now use the officially documented DeepSeek models deepseek-flash and deepseek-v4-pro. DeepSeek uses a separate /anthropic base URL, so the shared-root example intentionally covers OpenAI-compatible agents and shows an explicit Claude mapping. Internal TokenHub model IDs and endpoints were removed from the current documentation and E2E examples.

Verification: npm run build; npx tsc --noEmit; npx vitest run --silent --reporter=dot (290 files, 4329 passed, 1 skipped); node scripts/model-routes-e2e.mjs (git, gitlab, github, built CLI); git diff --check. All passed. The CLI E2E uses isolated temporary homes and does not touch real Agent settings.

@github-actions

Copy link
Copy Markdown

Findings

  • [P1 blocking] src/models-cmd.ts:301 rewrites every existing agent mapping to endpointId during any legacy-profile edit. For a multi-endpoint profile, even models configure ... --name New redirects all agents to the first endpoint—or fails validation when protocols differ—instead of preserving each mapping’s existing endpoint.
  • [P1 blocking] src/uninstall.ts:1162 releases the model-operation lock immediately after restoration, before executeRemoval() deletes the TeamAI home. A concurrent models switch can run in that window, write new agent settings and a new managed.json, then have uninstall delete the only restoration record. The fallback uninstall path has the same race.
  • [P1 blocking] src/models/switch.ts:484 preserves Buddy-added metadata when restoring a model previously owned by local-agent delivery, but does not update that delivery manifest’s full-entry hash. The next local-agent sync treats the restored entry as user-owned, drops ownership, and can no longer update or remove it.
  • [P1 blocking] src/models/switch.ts:283 edits Codex TOML using single-line regular expressions. Valid multiline values such as model = """...""", or a multiline string containing [model_providers.teamai], leave trailing string content behind or replace text inside the string, corrupting config.toml.
  • [P1 blocking] src/models/switch.ts:819 assumes a process environment value equal to settings.json.env was injected by Claude. If the user independently exports the same current value, switching is allowed, but that shell value continues overriding the newly written settings; TeamAI reports success while Claude still uses the old endpoint or credentials.
  • [P2 non-blocking] src/models-cmd.ts:214 performs unlocked read-modify-write operations across shared models.yaml and values.json files. Concurrent add, configure, or remove commands can overwrite one another and can leave profiles and credentials out of sync.
  • [P2 non-blocking] src/utils/prompt.ts:128 listens only for data; EOF/Ctrl-D and stream errors never settle the promise or restore terminal mode, so an interrupted secret prompt can hang or leave the terminal in raw mode.
  • [P2 non-blocking] src/models-cmd.ts:428 adds modelProfileSummary explicitly “for future dashboard use,” but it has no caller in the repository and pulls in redactEndpoint solely for that speculative API. This violates the repository rule against unused future abstractions.

Review Status

  • The other findings from earlier passes appear resolved in the current diff.
  • The PR description includes a test plan and explicit built-CLI/end-to-end verification records, so the testing-description requirement is satisfied.
  • Per request, I only read the specified diff and did not run, build, or install PR code.

@jeff-r2026 jeff-r2026 assigned jeff-r2026 and unassigned jeff-r2026 Sep 23, 2026
@github-actions

Copy link
Copy Markdown

Findings

  • [P1 blocking] src/models-cmd.ts:301 rewrites every selected agent mapping to endpointId. Without --agent, even a name-only edit redirects all mappings in a multi-endpoint profile to the first endpoint.
  • [P1 blocking] src/uninstall.ts:1162 releases the model lock after restoration and before executeRemoval() deletes ~/.teamai. A concurrent switch can create new settings and managed.json, then uninstall deletes their only restoration state. The fallback path at src/uninstall.ts:1279 has the same race.
  • [P1 blocking] src/models/switch.ts:484 restores metadata onto a model owned by local-agent delivery without updating that delivery manifest’s full-entry hash. The next sync treats it as user-owned and loses update/removal ownership.
  • [P1 blocking] src/models/switch.ts:283 still edits TOML with line-based regular expressions. Valid multiline model values, or [model_providers.teamai] text inside multiline strings, can leave fragments or remove string content and corrupt config.toml.
  • [P1 blocking] src/models/switch.ts:819 assumes a process environment value matching settings.json.env was injected by Claude. An independently exported equal value passes the guard and continues overriding the new configuration after the switch reports success.
  • [P1 blocking] src/local-agent.ts:2477 checks profile ownership separately from the switch lock. A concurrent server-delivered model update can pass the check, race with models switch, and overwrite the explicitly selected profile or leave both ownership manifests inconsistent.
  • [P2 non-blocking] src/models-cmd.ts:214 performs unlocked read-modify-write operations across shared models.yaml and values.json. Concurrent add/configure/remove commands can lose updates or leave definitions and credentials out of sync.
  • [P2 non-blocking] src/utils/prompt.ts:117 handles only data. EOF/Ctrl-D and stream errors never settle the secret prompt or restore terminal mode, potentially hanging the command or leaving the terminal raw.
  • [P2 non-blocking] src/models-cmd.ts:428 retains the unused modelProfileSummary helper explicitly for “future dashboard use,” adding speculative API and dependency surface contrary to the repository’s anti-over-engineering rule.

Review Status

  • The earlier findings marked resolved remain resolved; the eight findings from the latest prior pass remain present and are listed again.
  • The PR description includes a test plan and explicit real-CLI/end-to-end records, so the testing-description requirement is satisfied.
  • Review was limited to the specified diff; no PR code was run, built, or installed.

@laolaoPlayer
laolaoPlayer force-pushed the feature/model-profile-manager branch from 940b55b to 8f66b8a Compare September 23, 2026 12:18
@laolaoPlayer

Copy link
Copy Markdown
Contributor Author

Squashed into one commit (8f66b8a), rebased onto main. This revision simplifies the design rather than adding more fixes on top of it.

Simplification

  • Removed the explicit-mapping schema (inputs / endpoints / per-agent agents) and its CLI flags (--agent on add, --opus/--sonnet/--haiku-model, --set, --endpoint, --secret-stdin), plus the compatibility code for unpublished manifests. The catalog is now only id, name, base_url, api_key: ${API_KEY} (kept as a placeholder), and model_groups.
  • switch now defaults to every installed, compatible agent (--agent narrows it, --model picks the default), and asks once for a missing key. --all is gone.
  • teamai pull re-applies the team's latest catalog to agents already switched to one of its profiles (scoped to that team), and stays silent when nothing changed. models list shows where each profile is active.
  • Docs use a public TokenHub example (glm-5.3, deepseek-v4-flash). Anthropic runs at the root and OpenAI at /v1, which fits the URL rule.

Bugs fixed in this revision

  • CodeBuddy / WorkBuddy env keys were written as OpenCode's {env:VAR}. CodeBuddy only expands ${VAR} (resolveEnvVariables), so --from-env sent the literal string. They now use ${VAR}.
  • Claude /model pick was treated as a takeover. Claude Code persists /model choices to settings.json model, so after one pick every later switch, restore, and pull skipped Claude. The top-level model is now excluded from the ownership check; a re-apply keeps the pick while the catalog still offers it, and restore keeps a model TeamAI never offered.
  • Claude was always skipped when switch ran inside Claude Code, because the host injects ANTHROPIC_BASE_URL. Shell overrides now produce a warning instead of a skip; a Bedrock/Vertex/Foundry flag in settings.json still refuses. The unit tests also failed in that environment and are now hermetic.
  • Claude family aliases were cleared, so background work and subagents could ask the gateway for claude-haiku-*. ANTHROPIC_DEFAULT_{OPUS,SONNET,HAIKU}_MODEL now map to a matching gateway model, otherwise to the default.
  • Adding a protocol to a model could silently change the default model; group order is now kept stable.
  • Model commands printed raw stack traces; they now print one error line and exit 1.

Latest review findings

Finding Status
Legacy configure remaps every agent to the first endpoint Gone with the legacy schema
Codex multiline TOML corrupts config.toml Fixed: the edited TOML is parsed and compared with the intended values before writing; otherwise the switch fails and the file is untouched. A failed write also drops its pending ownership record.
Shell value equal to settings.json goes unreported Moot: shell overrides are now warnings, not a gate
askSecret hangs on EOF / Ctrl-D Fixed
modelProfileSummary unused Removed
Uninstall lock window, local-agent hash after restore, unlocked models.yaml writes Not changed: narrow concurrency/restore edge cases, left for a follow-up if wanted

Known limits

  • Claude cannot read an env reference in settings.json, so with --from-env Claude still receives the resolved key; the docs say so.
  • TokenHub answers /v1/responses (401 without a key), but per-model Responses support is unverified, so the example does not declare it and Codex is not switched.

Test report

  • npm run build, npx tsc --noEmit: pass
  • npx vitest run: 293 files, 4365 passed, 1 skipped (run inside a Claude Code session to confirm hermeticity)
  • vitest -c vitest.e2e.config.ts src/__tests__/e2e/model-cli-switch.test.ts: pass
  • node scripts/model-routes-e2e.mjs (built CLI, isolated homes): pass for git, gitlab, github
  • Manual built-CLI checks in isolated homes: switch/restore across Claude, Codex, OpenCode, CodeBuddy, and WorkBuddy; pull after an upstream catalog change updated the switched agents, skipped a hand-edited Claude, and printed nothing on an unchanged pull.

No live gateway calls or real credentials were used.

@github-actions

Copy link
Copy Markdown

Findings

  • [P1 blocking] src/uninstall.ts:1161 releases the model-operation lock after restoration, before executeRemoval() deletes ~/.teamai. A concurrent models switch can create new settings and managed.json in that window, after which uninstall deletes the only restoration record. The fallback path at src/uninstall.ts:1278 has the same race.
  • [P1 blocking] src/models/switch.ts:276 treats a process environment value equal to settings.json.env as Claude-injected. If the user independently exported that same old value, no warning is emitted and it continues overriding the newly written gateway after the switch reports success.
  • [P1 blocking] src/models/switch.ts:488 restores app-added Buddy metadata onto an entry previously owned by local-agent delivery without updating that delivery manifest’s full-entry hash. The next server sync treats the restored entry as user-owned and permanently loses update/removal ownership.
  • [P1 blocking] src/local-agent.ts:2501 checks explicit-profile ownership outside the model-operation lock. A concurrent server-delivered update can pass the check, race with models switch, and overwrite the selected profile or leave the two ownership manifests inconsistent.
  • [P1 blocking] src/models-cmd.ts:357 snapshots active team profiles before acquiring the switch lock. If a user switches an agent to a local profile before the pull re-apply reaches switchModelProfile(), the stale pull decision silently switches it back to the old team profile.
  • [P2 non-blocking] src/models-cmd.ts:210 performs unlocked read-modify-write operations across shared models.yaml and values.json. Concurrent add, configure, or remove commands can lose updates or leave profile definitions and credentials out of sync.
  • [P2 non-blocking] src/models/switch.ts:317 still edits Codex settings with single-line regular expressions. The new semantic check prevents corruption, but valid multiline top-level model or model_provider strings now cause every switch to fail instead of being updated safely.

Resolved Earlier Findings

  • Multi-endpoint profile edits now preserve existing agent mappings.
  • Secret prompts now handle EOF and stream errors.
  • The unused future-dashboard helper was removed.
  • Unsafe Codex edits are validated before writing, preventing the previously reported file corruption.
  • The other findings marked resolved in earlier passes remain resolved.

Review Status

  • The PR description contains a test plan and explicit real-CLI/end-to-end verification records, so the testing-description requirement is satisfied.
  • Review was limited to the specified diff; no PR code was run, built, or installed.

@laolaoPlayer
laolaoPlayer force-pushed the feature/model-profile-manager branch from 8f66b8a to 2bf91cc Compare September 23, 2026 14:21
@laolaoPlayer

Copy link
Copy Markdown
Contributor Author

Follow-up on the latest automated review. I checked each finding against the code. Three were reproducible and are fixed in 2bf91cc, still a single commit, rebased onto main. The other four are left as they are, for the reasons below.

Fixed

Finding Change
Shell value equal to the old settings.json value is not reported The warning now compares the shell with the values TeamAI writes, so an exported value that still overrides the new gateway is always reported. This also drops the "injected by Claude" heuristic.
Buddy restore keeps app-added metadata on an entry owned by local-agent delivery A restore now puts the original entry back exactly, so its local-agent hash still matches. App metadata is kept only when one TeamAI entry replaces another.
pull decides what to re-apply before taking the lock switchModelProfile takes an onlyIfActive guard that pull passes. Under the lock, an agent that has moved to another profile (or another --model) since then is left alone.

Each fix has a regression test, and the usage and design docs are updated in both languages.

Not changed

Finding Reason
Uninstall lock window before ~/.teamai is removed Requires the user to run models switch during their own teamai uninstall.
local-agent ownership check outside the lock The window is milliseconds. A collision leaves managed fields different from the recorded ones, so the next switch or restore skips the agent instead of overwriting. Nothing is corrupted.
Unlocked models.yaml / values.json read-modify-write (P2) Needs two concurrent add/configure/remove commands from the same user.
Multiline Codex model strings make switch fail (P2) That is the intended outcome of the new verification: the switch fails and leaves the file unchanged, instead of corrupting it. Model IDs are not written as multiline strings in practice.

Test report

  • npm run build, npx tsc --noEmit: pass
  • npx vitest run: 294 files, 4381 passed, 1 skipped
  • vitest -c vitest.e2e.config.ts src/__tests__/e2e/model-cli-switch.test.ts: pass
  • node scripts/model-routes-e2e.mjs (built CLI, isolated homes): pass for git, gitlab, github

@github-actions

Copy link
Copy Markdown

Findings

  • [P1 blocking] src/uninstall.ts:1162 releases the model-operation lock before executeRemoval() deletes ~/.teamai. A concurrent models switch can create new agent settings and managed.json during MCP cleanup, after which uninstall deletes their only restoration record. The fallback path at src/uninstall.ts:1279 has the same race.
  • [P1 blocking] src/local-agent.ts:2501 still checks explicit-profile ownership outside the model-operation lock. Server delivery can pass the check, race with models switch, and overwrite the selected profile while leaving the two ownership manifests inconsistent.
  • [P1 blocking] src/models/switch.ts:773 carries historical Buddy IDs only in previous.entries, not lastWritten.entries. After switching from model A to model B, a user can create their own model A without triggering the ownership check; models restore then treats A as historical managed state and deletes or overwrites that user entry.
  • [P1 blocking] src/models/switch.ts:814 records the lexical configuration path, while writes resolve the current symlink target at src/models/switch.ts:183. Retargeting a settings-file or parent-directory symlink is therefore not detected as a path change, allowing later switches or restoration to modify a different file when its managed fields happen to match.
  • [P2 non-blocking] src/models-cmd.ts:210 performs unlocked read-modify-write operations across shared models.yaml and values.json. Concurrent add, configure, or remove commands can lose updates or leave profile definitions and credentials out of sync.
  • [P2 non-blocking] src/models/switch.ts:317 still edits Codex settings with single-line regular expressions. Valid multiline top-level model or model_provider strings cannot be updated and make every switch fail, despite the resulting TOML now being checked before writing.

Review Status

  • Earlier Claude shell-override detection, Buddy local-agent restoration hashing, pull re-apply staleness, and secret-prompt cleanup findings are resolved.
  • The PR description includes a test plan and explicit real-CLI/end-to-end records, so the testing-description requirement is satisfied.
  • Review was limited to the specified diff; no PR code was run, built, or installed.

@laolaoPlayer
laolaoPlayer force-pushed the feature/model-profile-manager branch from 2bf91cc to ef52d84 Compare September 23, 2026 14:41
@laolaoPlayer

Copy link
Copy Markdown
Contributor Author

Follow-up on the latest automated review. ef52d84 is still a single commit on current main.

Fixed: historical Buddy IDs during restore

Reproduced: switch to model A, then to model B, then add your own model A. models restore deleted that entry. If A was also in availableModels, restore was blocked instead. This becomes more likely now that pull follows catalog changes.

When a switch drops a model from the catalog, TeamAI now puts that ID's original entry and allowlist state back right away (or removes the entry if there was none) and stops tracking the ID. Restore only touches IDs TeamAI still writes, so a user entry that reuses a dropped ID is left alone. As a side effect, an entry owned by local-agent delivery comes back as soon as the catalog stops using its ID. Regression tests cover both cases for CodeBuddy and WorkBuddy.

Not changed: symlink retargeting

The recorded path is lexical by design. For the reported scenario to do harm, the new target must hold exactly the fields TeamAI last wrote, including the token, so it is effectively a copy of the same config. The common real case is a dotfiles checkout that moved: the symlink now points at the user's same config, and continuing to manage it is expected. Pinning the resolved path would instead refuse to switch or restore there.

Repeated findings

The uninstall lock window, the local-agent check outside the lock, unlocked models.yaml writes, and multiline Codex model strings are unchanged. The reasons are in the previous reply.

Test report

  • npm run build, npx tsc --noEmit: pass
  • npx vitest run: 294 files, 4385 passed, 1 skipped
  • vitest -c vitest.e2e.config.ts src/__tests__/e2e/model-cli-switch.test.ts: pass
  • node scripts/model-routes-e2e.mjs (built CLI, isolated homes): pass for git, gitlab, github

@github-actions

Copy link
Copy Markdown

Findings

  • [P1 blocking] src/uninstall.ts:1162 releases the model-operation lock before MCP cleanup and executeRemoval() delete ~/.teamai. A concurrent models switch can write new settings and managed.json during that window, after which uninstall deletes the only restoration state. The fallback path at src/uninstall.ts:1279 has the same race.
  • [P1 blocking] src/local-agent.ts:2501 checks explicit-profile ownership outside the model-operation lock. Server delivery can pass the check immediately before models switch, then overwrite the selected profile and leave the delivery and switch manifests inconsistent.
  • [P1 blocking] src/models/switch.ts:95 compares only lexical configuration paths, while writes follow the current symlink target. Retargeting a settings-file or parent-directory symlink is not detected, so later switches or restoration can modify a different file when its managed fields happen to match.
  • [P1 blocking] src/models/profile.ts:299 accepts --model when the model exists anywhere in the profile, but only reorders protocol routes containing it. With protocol-specific groups, selecting an Anthropic-only model still switches Codex or Buddy to another route’s first model while recording the requested model in managed.json, so the command reports success for a model it did not apply.
  • [P2 non-blocking] src/models-cmd.ts:210 performs unlocked read-modify-write operations across shared models.yaml and values.json. Concurrent add, configure, or remove commands can lose updates or leave profiles and credentials out of sync.
  • [P2 non-blocking] src/models-cmd.ts:231 updates profile definitions and credentials as separate writes without rollback. A failure during the second write can leave orphaned credentials, a profile without its credentials, or a credential change applied despite a failed profile edit; configure and remove have equivalent partial-update windows.
  • [P2 non-blocking] src/models/switch.ts:317 still edits Codex settings with single-line regular expressions. Valid multiline top-level model or model_provider strings cause every switch to fail rather than being updated safely.

Resolved Earlier Findings

  • Historical Buddy IDs are now released from both ownership snapshots, so reused user entries survive restoration.
  • Claude shell overrides matching the old settings are now warned about correctly.
  • Pull reapplication now rechecks the active profile while holding the switch lock.
  • The other findings previously marked resolved remain resolved.

Review Status

  • The PR description includes a test plan and explicit real-CLI/end-to-end verification records, so the testing-description requirement is satisfied.
  • Review was limited to the specified diff; no PR code was run, built, or installed.

Add `teamai models` to point Claude Code, Codex, OpenCode, CodeBuddy, and
WorkBuddy at a team or personal model gateway.

- A team publishes `models/models.yaml` (id, name, base_url, api_key
  placeholder, model_groups by protocol); each member keeps the API key
  locally or as an environment-variable reference.
- `models switch` updates every installed, compatible agent (or `--agent`),
  asks for a missing key once, and accepts `--model` for the default.
- `teamai pull` re-applies the team's latest catalog to agents already
  switched to it; agents never switched are left alone.
- TeamAI records the managed fields before its first switch, skips agents
  whose managed fields changed outside TeamAI, and `models restore` puts
  the originals back. Claude's `/model` pick is not treated as a takeover.
- Claude family aliases map to matching gateway models or the default;
  Buddy entries use `${VAR}` key references; Codex edits are parsed and
  verified before writing.
- Push rejects an invalid catalog; user-scope uninstall restores model
  settings first.
@laolaoPlayer
laolaoPlayer force-pushed the feature/model-profile-manager branch from ef52d84 to dbc2166 Compare September 24, 2026 03:40
@jeff-r2026
jeff-r2026 merged commit da13c11 into Tencent:main Sep 24, 2026
11 checks passed
@github-actions

Copy link
Copy Markdown

Findings

  • [P1 blocking] src/uninstall.ts:1166 releases the model-operation lock before MCP cleanup and executeRemoval() delete ~/.teamai. A concurrent models switch can write new settings and managed.json during that window, after which uninstall deletes the only restoration state. The fallback path at src/uninstall.ts:1283 has the same race.
  • [P1 blocking] src/local-agent.ts:2549 checks explicit-profile ownership outside the model-operation lock. Server delivery can pass the check immediately before models switch, then overwrite the selected profile and leave the delivery and switch manifests inconsistent.
  • [P1 blocking] src/models/switch.ts:95 records and compares only lexical configuration paths while writes follow the current symlink target. Retargeting the settings file or a parent-directory symlink can make later switches or restoration modify a different file.
  • [P1 blocking] src/models/profile.ts:299 accepts --model when the model exists anywhere in the profile, but only reorders routes containing it. Selecting a protocol-specific model can switch other agents to a different model while reporting and recording the requested model as applied.
  • [P1 blocking] src/index.ts:730 adds a new model-management workflow, but the diff only updates the generated command reference. It adds neither a workflow under skill-data/ nor routing in skills/teamai/SKILL.md, contrary to the repository’s explicit workflow-deployment rule, so deployed agents cannot discover or follow this feature.
  • [P2 non-blocking] src/models-cmd.ts:210 performs unlocked read-modify-write operations across shared models.yaml and values.json. Concurrent add, configure, or remove commands can lose updates or leave profiles and credentials inconsistent.
  • [P2 non-blocking] src/models-cmd.ts:231 updates profile definitions and credentials as separate writes without rollback. A second-write failure can leave orphaned credentials, missing credentials, or an edit partially applied despite the command reporting failure.
  • [P2 non-blocking] src/models/switch.ts:317 edits Codex settings with single-line regular expressions. Valid multiline top-level model or model_provider strings cannot be updated and cause every switch to fail.

Review Status

  • All seven findings from the latest prior pass remain present; previously resolved findings remain resolved.
  • The PR description includes a test plan and explicit real-CLI/end-to-end verification records, so the testing-description requirement is satisfied.
  • Review was limited to the specified diff; no PR code was run, built, or installed.

Walternater pushed a commit to Walternater/teamai-cli that referenced this pull request Nov 2, 2026
Add `teamai models` to point Claude Code, Codex, OpenCode, CodeBuddy, and
WorkBuddy at a team or personal model gateway.

- A team publishes `models/models.yaml` (id, name, base_url, api_key
  placeholder, model_groups by protocol); each member keeps the API key
  locally or as an environment-variable reference.
- `models switch` updates every installed, compatible agent (or `--agent`),
  asks for a missing key once, and accepts `--model` for the default.
- `teamai pull` re-applies the team's latest catalog to agents already
  switched to it; agents never switched are left alone.
- TeamAI records the managed fields before its first switch, skips agents
  whose managed fields changed outside TeamAI, and `models restore` puts
  the originals back. Claude's `/model` pick is not treated as a takeover.
- Claude family aliases map to matching gateway models or the default;
  Buddy entries use `${VAR}` key references; Codex edits are parsed and
  verified before writing.
- Push rejects an invalid catalog; user-scope uninstall restores model
  settings first.
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.

feat(models): manage team and local model profiles with explicit agent switching

3 participants