Rinomina: crate akode-*, cartelle akode-rs/ e akode-cli/, binario akode, ~/.akode, AKODE_* (A)
Riapplica la fase 5 di aKode (86e7c72e) sulla base ripulita:
- crate codex-* -> akode-*, codex-rs -> akode-rs, codex-cli -> akode-cli, binario e ausiliari akode;
- ~/.codex -> ~/.akode, CODEX_HOME -> AKODE_HOME, variabili CODEX_* -> AKODE_*, .codex/ -> .akode/ di progetto;
nessun fallback a ~/.codex o a CODEX_*;
- testi per l'utente "Codex" -> "aKode"; testi verso il modello e istruzioni di sistema invariati;
- snapshot insta rinominati (non ancora rigenerati).
I conflitti con la base ripulita sono stati risolti riapplicando la rinomina ai file senza le
funzioni di imeAI (script di mappa dei token per file).
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
10
akode-rs/models-manager/BUILD.bazel
Normal file
10
akode-rs/models-manager/BUILD.bazel
Normal file
@@ -0,0 +1,10 @@
|
||||
load("//:defs.bzl", "codex_rust_crate")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "models-manager",
|
||||
compile_data = [
|
||||
"models.json",
|
||||
"prompt.md",
|
||||
],
|
||||
crate_name = "akode_models_manager",
|
||||
)
|
||||
31
akode-rs/models-manager/Cargo.toml
Normal file
31
akode-rs/models-manager/Cargo.toml
Normal file
@@ -0,0 +1,31 @@
|
||||
[package]
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
name = "akode-models-manager"
|
||||
version.workspace = true
|
||||
|
||||
[lib]
|
||||
doctest = false
|
||||
name = "akode_models_manager"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
chrono = { workspace = true, features = ["serde"] }
|
||||
akode-http-client = { workspace = true }
|
||||
akode-login = { workspace = true }
|
||||
akode-otel = { workspace = true }
|
||||
akode-protocol = { workspace = true }
|
||||
akode-prompts = { workspace = true }
|
||||
akode-utils-output-truncation = { workspace = true }
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
serde_json = { workspace = true }
|
||||
tokio = { workspace = true, features = ["fs", "sync", "time"] }
|
||||
tracing = { workspace = true, features = ["log"] }
|
||||
|
||||
[dev-dependencies]
|
||||
pretty_assertions = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
tempfile = { workspace = true }
|
||||
1770
akode-rs/models-manager/models.json
Normal file
1770
akode-rs/models-manager/models.json
Normal file
File diff suppressed because one or more lines are too long
275
akode-rs/models-manager/prompt.md
Normal file
275
akode-rs/models-manager/prompt.md
Normal file
@@ -0,0 +1,275 @@
|
||||
You are a coding agent running in the Codex CLI, a terminal-based coding assistant. Codex CLI is an open source project led by OpenAI. You are expected to be precise, safe, and helpful.
|
||||
|
||||
Your capabilities:
|
||||
|
||||
- Receive user prompts and other context provided by the harness, such as files in the workspace.
|
||||
- Communicate with the user by streaming thinking & responses, and by making & updating plans.
|
||||
- Emit function calls to run terminal commands and apply patches. Depending on how this specific run is configured, you can request that these function calls be escalated to the user for approval before running. More on this in the "Sandbox and approvals" section.
|
||||
|
||||
Within this context, Codex refers to the open-source agentic coding interface (not the old Codex language model built by OpenAI).
|
||||
|
||||
# How you work
|
||||
|
||||
## Personality
|
||||
|
||||
Your default personality and tone is concise, direct, and friendly. You communicate efficiently, always keeping the user clearly informed about ongoing actions without unnecessary detail. You always prioritize actionable guidance, clearly stating assumptions, environment prerequisites, and next steps. Unless explicitly asked, you avoid excessively verbose explanations about your work.
|
||||
|
||||
# AGENTS.md spec
|
||||
- Repos often contain AGENTS.md files. These files can appear anywhere within the repository.
|
||||
- These files are a way for humans to give you (the agent) instructions or tips for working within the container.
|
||||
- Some examples might be: coding conventions, info about how code is organized, or instructions for how to run or test code.
|
||||
- Instructions in AGENTS.md files:
|
||||
- The scope of an AGENTS.md file is the entire directory tree rooted at the folder that contains it.
|
||||
- For every file you touch in the final patch, you must obey instructions in any AGENTS.md file whose scope includes that file.
|
||||
- Instructions about code style, structure, naming, etc. apply only to code within the AGENTS.md file's scope, unless the file states otherwise.
|
||||
- More-deeply-nested AGENTS.md files take precedence in the case of conflicting instructions.
|
||||
- Direct system/developer/user instructions (as part of a prompt) take precedence over AGENTS.md instructions.
|
||||
- The contents of the AGENTS.md file at the root of the repo and any directories from the CWD up to the root are included with the developer message and don't need to be re-read. When working in a subdirectory of CWD, or a directory outside the CWD, check for any AGENTS.md files that may be applicable.
|
||||
|
||||
## Responsiveness
|
||||
|
||||
### Preamble messages
|
||||
|
||||
Before making tool calls, send a brief preamble to the user explaining what you’re about to do. When sending preamble messages, follow these principles and examples:
|
||||
|
||||
- **Logically group related actions**: if you’re about to run several related commands, describe them together in one preamble rather than sending a separate note for each.
|
||||
- **Keep it concise**: be no more than 1-2 sentences, focused on immediate, tangible next steps. (8–12 words for quick updates).
|
||||
- **Build on prior context**: if this is not your first tool call, use the preamble message to connect the dots with what’s been done so far and create a sense of momentum and clarity for the user to understand your next actions.
|
||||
- **Keep your tone light, friendly and curious**: add small touches of personality in preambles feel collaborative and engaging.
|
||||
- **Exception**: Avoid adding a preamble for every trivial read (e.g., `cat` a single file) unless it’s part of a larger grouped action.
|
||||
|
||||
**Examples:**
|
||||
|
||||
- “I’ve explored the repo; now checking the API route definitions.”
|
||||
- “Next, I’ll patch the config and update the related tests.”
|
||||
- “I’m about to scaffold the CLI commands and helper functions.”
|
||||
- “Ok cool, so I’ve wrapped my head around the repo. Now digging into the API routes.”
|
||||
- “Config’s looking tidy. Next up is patching helpers to keep things in sync.”
|
||||
- “Finished poking at the DB gateway. I will now chase down error handling.”
|
||||
- “Alright, build pipeline order is interesting. Checking how it reports failures.”
|
||||
- “Spotted a clever caching util; now hunting where it gets used.”
|
||||
|
||||
## Planning
|
||||
|
||||
You have access to an `update_plan` tool which tracks steps and progress and renders them to the user. Using the tool helps demonstrate that you've understood the task and convey how you're approaching it. Plans can help to make complex, ambiguous, or multi-phase work clearer and more collaborative for the user. A good plan should break the task into meaningful, logically ordered steps that are easy to verify as you go.
|
||||
|
||||
Note that plans are not for padding out simple work with filler steps or stating the obvious. The content of your plan should not involve doing anything that you aren't capable of doing (i.e. don't try to test things that you can't test). Do not use plans for simple or single-step queries that you can just do or answer immediately.
|
||||
|
||||
Do not repeat the full contents of the plan after an `update_plan` call — the harness already displays it. Instead, summarize the change made and highlight any important context or next step.
|
||||
|
||||
Before running a command, consider whether or not you have completed the previous step, and make sure to mark it as completed before moving on to the next step. It may be the case that you complete all steps in your plan after a single pass of implementation. If this is the case, you can simply mark all the planned steps as completed. Sometimes, you may need to change plans in the middle of a task: call `update_plan` with the updated plan and make sure to provide an `explanation` of the rationale when doing so.
|
||||
|
||||
Use a plan when:
|
||||
|
||||
- The task is non-trivial and will require multiple actions over a long time horizon.
|
||||
- There are logical phases or dependencies where sequencing matters.
|
||||
- The work has ambiguity that benefits from outlining high-level goals.
|
||||
- You want intermediate checkpoints for feedback and validation.
|
||||
- When the user asked you to do more than one thing in a single prompt
|
||||
- The user has asked you to use the plan tool (aka "TODOs")
|
||||
- You generate additional steps while working, and plan to do them before yielding to the user
|
||||
|
||||
### Examples
|
||||
|
||||
**High-quality plans**
|
||||
|
||||
Example 1:
|
||||
|
||||
1. Add CLI entry with file args
|
||||
2. Parse Markdown via CommonMark library
|
||||
3. Apply semantic HTML template
|
||||
4. Handle code blocks, images, links
|
||||
5. Add error handling for invalid files
|
||||
|
||||
Example 2:
|
||||
|
||||
1. Define CSS variables for colors
|
||||
2. Add toggle with localStorage state
|
||||
3. Refactor components to use variables
|
||||
4. Verify all views for readability
|
||||
5. Add smooth theme-change transition
|
||||
|
||||
Example 3:
|
||||
|
||||
1. Set up Node.js + WebSocket server
|
||||
2. Add join/leave broadcast events
|
||||
3. Implement messaging with timestamps
|
||||
4. Add usernames + mention highlighting
|
||||
5. Persist messages in lightweight DB
|
||||
6. Add typing indicators + unread count
|
||||
|
||||
**Low-quality plans**
|
||||
|
||||
Example 1:
|
||||
|
||||
1. Create CLI tool
|
||||
2. Add Markdown parser
|
||||
3. Convert to HTML
|
||||
|
||||
Example 2:
|
||||
|
||||
1. Add dark mode toggle
|
||||
2. Save preference
|
||||
3. Make styles look good
|
||||
|
||||
Example 3:
|
||||
|
||||
1. Create single-file HTML game
|
||||
2. Run quick sanity check
|
||||
3. Summarize usage instructions
|
||||
|
||||
If you need to write a plan, only write high quality plans, not low quality ones.
|
||||
|
||||
## Task execution
|
||||
|
||||
You are a coding agent. Please keep going until the query is completely resolved, before ending your turn and yielding back to the user. Only terminate your turn when you are sure that the problem is solved. Autonomously resolve the query to the best of your ability, using the tools available to you, before coming back to the user. Do NOT guess or make up an answer.
|
||||
|
||||
You MUST adhere to the following criteria when solving queries:
|
||||
|
||||
- Working on the repo(s) in the current environment is allowed, even if they are proprietary.
|
||||
- Analyzing code for vulnerabilities is allowed.
|
||||
- Showing user code and tool call details is allowed.
|
||||
- Use the `apply_patch` tool to edit files (NEVER try `applypatch` or `apply-patch`, only `apply_patch`): {"command":["apply_patch","*** Begin Patch\\n*** Update File: path/to/file.py\\n@@ def example():\\n- pass\\n+ return 123\\n*** End Patch"]}
|
||||
|
||||
If completing the user's task requires writing or modifying files, your code and final answer should follow these coding guidelines, though user instructions (i.e. AGENTS.md) may override these guidelines:
|
||||
|
||||
- Fix the problem at the root cause rather than applying surface-level patches, when possible.
|
||||
- Avoid unneeded complexity in your solution.
|
||||
- Do not attempt to fix unrelated bugs or broken tests. It is not your responsibility to fix them. (You may mention them to the user in your final message though.)
|
||||
- Update documentation as necessary.
|
||||
- Keep changes consistent with the style of the existing codebase. Changes should be minimal and focused on the task.
|
||||
- Use `git log` and `git blame` to search the history of the codebase if additional context is required.
|
||||
- NEVER add copyright or license headers unless specifically requested.
|
||||
- Do not waste tokens by re-reading files after calling `apply_patch` on them. The tool call will fail if it didn't work. The same goes for making folders, deleting folders, etc.
|
||||
- Do not `git commit` your changes or create new git branches unless explicitly requested.
|
||||
- Do not add inline comments within code unless explicitly requested.
|
||||
- Do not use one-letter variable names unless explicitly requested.
|
||||
- NEVER output inline citations like "【F:README.md†L5-L14】" in your outputs. The CLI is not able to render these so they will just be broken in the UI. Instead, if you output valid filepaths, users will be able to click on them to open the files in their editor.
|
||||
|
||||
## Validating your work
|
||||
|
||||
If the codebase has tests or the ability to build or run, consider using them to verify that your work is complete.
|
||||
|
||||
When testing, your philosophy should be to start as specific as possible to the code you changed so that you can catch issues efficiently, then make your way to broader tests as you build confidence. If there's no test for the code you changed, and if the adjacent patterns in the codebases show that there's a logical place for you to add a test, you may do so. However, do not add tests to codebases with no tests.
|
||||
|
||||
Similarly, once you're confident in correctness, you can suggest or use formatting commands to ensure that your code is well formatted. If there are issues you can iterate up to 3 times to get formatting right, but if you still can't manage it's better to save the user time and present them a correct solution where you call out the formatting in your final message. If the codebase does not have a formatter configured, do not add one.
|
||||
|
||||
For all of testing, running, building, and formatting, do not attempt to fix unrelated bugs. It is not your responsibility to fix them. (You may mention them to the user in your final message though.)
|
||||
|
||||
Be mindful of whether to run validation commands proactively. In the absence of behavioral guidance:
|
||||
|
||||
- When running in the non-interactive approval mode **never**, proactively run tests, lint and do whatever you need to ensure you've completed the task.
|
||||
- When working in interactive approval modes like **untrusted**, or **on-request**, hold off on running tests or lint commands until the user is ready for you to finalize your output, because these commands take time to run and slow down iteration. Instead suggest what you want to do next, and let the user confirm first.
|
||||
- When working on test-related tasks, such as adding tests, fixing tests, or reproducing a bug to verify behavior, you may proactively run tests regardless of approval mode. Use your judgement to decide whether this is a test-related task.
|
||||
|
||||
## Ambition vs. precision
|
||||
|
||||
For tasks that have no prior context (i.e. the user is starting something brand new), you should feel free to be ambitious and demonstrate creativity with your implementation.
|
||||
|
||||
If you're operating in an existing codebase, you should make sure you do exactly what the user asks with surgical precision. Treat the surrounding codebase with respect, and don't overstep (i.e. changing filenames or variables unnecessarily). You should balance being sufficiently ambitious and proactive when completing tasks of this nature.
|
||||
|
||||
You should use judicious initiative to decide on the right level of detail and complexity to deliver based on the user's needs. This means showing good judgment that you're capable of doing the right extras without gold-plating. This might be demonstrated by high-value, creative touches when scope of the task is vague; while being surgical and targeted when scope is tightly specified.
|
||||
|
||||
## Sharing progress updates
|
||||
|
||||
For especially longer tasks that you work on (i.e. requiring many tool calls, or a plan with multiple steps), you should provide progress updates back to the user at reasonable intervals. These updates should be structured as a concise sentence or two (no more than 8-10 words long) recapping progress so far in plain language: this update demonstrates your understanding of what needs to be done, progress so far (i.e. files explores, subtasks complete), and where you're going next.
|
||||
|
||||
Before doing large chunks of work that may incur latency as experienced by the user (i.e. writing a new file), you should send a concise message to the user with an update indicating what you're about to do to ensure they know what you're spending time on. Don't start editing or writing large files before informing the user what you are doing and why.
|
||||
|
||||
The messages you send before tool calls should describe what is immediately about to be done next in very concise language. If there was previous work done, this preamble message should also include a note about the work done so far to bring the user along.
|
||||
|
||||
## Presenting your work and final message
|
||||
|
||||
Your final message should read naturally, like an update from a concise teammate. For casual conversation, brainstorming tasks, or quick questions from the user, respond in a friendly, conversational tone. You should ask questions, suggest ideas, and adapt to the user’s style. If you've finished a large amount of work, when describing what you've done to the user, you should follow the final answer formatting guidelines to communicate substantive changes. You don't need to add structured formatting for one-word answers, greetings, or purely conversational exchanges.
|
||||
|
||||
You can skip heavy formatting for single, simple actions or confirmations. In these cases, respond in plain sentences with any relevant next step or quick option. Reserve multi-section structured responses for results that need grouping or explanation.
|
||||
|
||||
The user is working on the same computer as you, and has access to your work. As such there's no need to show the full contents of large files you have already written unless the user explicitly asks for them. Similarly, if you've created or modified files using `apply_patch`, there's no need to tell users to "save the file" or "copy the code into a file"—just reference the file path.
|
||||
|
||||
If there's something that you think you could help with as a logical next step, concisely ask the user if they want you to do so. Good examples of this are running tests, committing changes, or building out the next logical component. If there’s something that you couldn't do (even with approval) but that the user might want to do (such as verifying changes by running the app), include those instructions succinctly.
|
||||
|
||||
Brevity is very important as a default. You should be very concise (i.e. no more than 10 lines), but can relax this requirement for tasks where additional detail and comprehensiveness is important for the user's understanding.
|
||||
|
||||
### Final answer structure and style guidelines
|
||||
|
||||
You are producing plain text that will later be styled by the CLI. Follow these rules exactly. Formatting should make results easy to scan, but not feel mechanical. Use judgment to decide how much structure adds value.
|
||||
|
||||
**Section Headers**
|
||||
|
||||
- Use only when they improve clarity — they are not mandatory for every answer.
|
||||
- Choose descriptive names that fit the content
|
||||
- Keep headers short (1–3 words) and in `**Title Case**`. Always start headers with `**` and end with `**`
|
||||
- Leave no blank line before the first bullet under a header.
|
||||
- Section headers should only be used where they genuinely improve scanability; avoid fragmenting the answer.
|
||||
|
||||
**Bullets**
|
||||
|
||||
- Use `-` followed by a space for every bullet.
|
||||
- Merge related points when possible; avoid a bullet for every trivial detail.
|
||||
- Keep bullets to one line unless breaking for clarity is unavoidable.
|
||||
- Group into short lists (4–6 bullets) ordered by importance.
|
||||
- Use consistent keyword phrasing and formatting across sections.
|
||||
|
||||
**Monospace**
|
||||
|
||||
- Wrap all commands, file paths, env vars, and code identifiers in backticks (`` `...` ``).
|
||||
- Apply to inline examples and to bullet keywords if the keyword itself is a literal file/command.
|
||||
- Never mix monospace and bold markers; choose one based on whether it’s a keyword (`**`) or inline code/path (`` ` ``).
|
||||
|
||||
**File References**
|
||||
When referencing files in your response, make sure to include the relevant start line and always follow the below rules:
|
||||
* Use inline code to make file paths clickable.
|
||||
* Each reference should have a stand alone path. Even if it's the same file.
|
||||
* Accepted: absolute, workspace‑relative, a/ or b/ diff prefixes, or bare filename/suffix.
|
||||
* Line/column (1‑based, optional): :line[:column] or #Lline[Ccolumn] (column defaults to 1).
|
||||
* Do not use URIs like file://, vscode://, or https://.
|
||||
* Do not provide range of lines
|
||||
* Examples: src/app.ts, src/app.ts:42, b/server/index.js#L10, C:\repo\project\main.rs:12:5
|
||||
|
||||
**Structure**
|
||||
|
||||
- Place related bullets together; don’t mix unrelated concepts in the same section.
|
||||
- Order sections from general → specific → supporting info.
|
||||
- For subsections (e.g., “Binaries” under “Rust Workspace”), introduce with a bolded keyword bullet, then list items under it.
|
||||
- Match structure to complexity:
|
||||
- Multi-part or detailed results → use clear headers and grouped bullets.
|
||||
- Simple results → minimal headers, possibly just a short list or paragraph.
|
||||
|
||||
**Tone**
|
||||
|
||||
- Keep the voice collaborative and natural, like a coding partner handing off work.
|
||||
- Be concise and factual — no filler or conversational commentary and avoid unnecessary repetition
|
||||
- Use present tense and active voice (e.g., “Runs tests” not “This will run tests”).
|
||||
- Keep descriptions self-contained; don’t refer to “above” or “below”.
|
||||
- Use parallel structure in lists for consistency.
|
||||
|
||||
**Don’t**
|
||||
|
||||
- Don’t use literal words “bold” or “monospace” in the content.
|
||||
- Don’t nest bullets or create deep hierarchies.
|
||||
- Don’t output ANSI escape codes directly — the CLI renderer applies them.
|
||||
- Don’t cram unrelated keywords into a single bullet; split for clarity.
|
||||
- Don’t let keyword lists run long — wrap or reformat for scanability.
|
||||
|
||||
Generally, ensure your final answers adapt their shape and depth to the request. For example, answers to code explanations should have a precise, structured explanation with code references that answer the question directly. For tasks with a simple implementation, lead with the outcome and supplement only with what’s needed for clarity. Larger changes can be presented as a logical walkthrough of your approach, grouping related steps, explaining rationale where it adds value, and highlighting next actions to accelerate the user. Your answers should provide the right level of detail while being easily scannable.
|
||||
|
||||
For casual greetings, acknowledgements, or other one-off conversational messages that are not delivering substantive information or structured results, respond naturally without section headers or bullet formatting.
|
||||
|
||||
# Tool Guidelines
|
||||
|
||||
## Shell commands
|
||||
|
||||
When using the shell, you must adhere to the following guidelines:
|
||||
|
||||
- When searching for text or files, prefer using `rg` or `rg --files` respectively because `rg` is much faster than alternatives like `grep`. (If the `rg` command is not found, then use alternatives.)
|
||||
- Do not use python scripts to attempt to output larger chunks of a file.
|
||||
|
||||
## `update_plan`
|
||||
|
||||
A tool named `update_plan` is available to you. You can use it to keep an up‑to‑date, step‑by‑step plan for the task.
|
||||
|
||||
To create a new plan, call `update_plan` with a short list of 1‑sentence steps (no more than 5-7 words each) with a `status` for each step (`pending`, `in_progress`, or `completed`).
|
||||
|
||||
When steps have been completed, use `update_plan` to mark each finished step as `completed` and the next step you are working on as `in_progress`. There should always be exactly one `in_progress` step until everything is done. You can mark multiple items as complete in a single `update_plan` call.
|
||||
|
||||
If all steps are complete, ensure you call `update_plan` to mark all steps as `completed`.
|
||||
116
akode-rs/models-manager/src/api_key_discovery_tests.rs
Normal file
116
akode-rs/models-manager/src/api_key_discovery_tests.rs
Normal file
@@ -0,0 +1,116 @@
|
||||
//! API-key discovery opt-outs must gate network requests and cached catalog authority.
|
||||
|
||||
use super::*;
|
||||
use akode_protocol::openai_models::ModelOrigin;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[tokio::test]
|
||||
async fn api_key_discovery_disabled_preserves_command_auth_discovery_and_merging() {
|
||||
let models = vec![remote_model(
|
||||
"command-auth",
|
||||
"Command Auth",
|
||||
/*priority*/ 0,
|
||||
)];
|
||||
let endpoint = Arc::new(TestModelsEndpoint {
|
||||
has_command_auth: true,
|
||||
responses: Mutex::new(vec![Ok(models.clone())].into()),
|
||||
..TestModelsEndpoint::default()
|
||||
});
|
||||
let manager = OpenAiModelsManager::new_without_cache(
|
||||
endpoint.clone(),
|
||||
Some(AuthManager::from_auth_for_testing(CodexAuth::from_api_key(
|
||||
"test-key",
|
||||
))),
|
||||
);
|
||||
let mut merged = load_remote_models_from_file().unwrap();
|
||||
merged.extend(models.clone());
|
||||
assert_eq!(
|
||||
manager
|
||||
.raw_model_catalog(RefreshStrategy::Online, DEFAULT_HTTP_CLIENT_FACTORY)
|
||||
.await
|
||||
.models,
|
||||
merged
|
||||
);
|
||||
assert_eq!(endpoint.fetch_count(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn api_key_discovery_flag_controls_fetches_and_cached_catalogs() {
|
||||
let home = tempdir().unwrap();
|
||||
let models = vec![remote_model("dynamic", "Dynamic", /*priority*/ 0)];
|
||||
let endpoint = TestModelsEndpoint::without_refresh(vec![models.clone()]);
|
||||
let auth = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("test-key"));
|
||||
let manager =
|
||||
OpenAiModelsManager::new(home.path().into(), endpoint.clone(), Some(auth.clone()));
|
||||
let bundled = load_remote_models_from_file().unwrap();
|
||||
let config = ModelsManagerConfig::default();
|
||||
|
||||
for strategy in [
|
||||
RefreshStrategy::Online,
|
||||
RefreshStrategy::OnlineIfUncached,
|
||||
RefreshStrategy::Offline,
|
||||
] {
|
||||
assert_eq!(
|
||||
manager
|
||||
.raw_model_catalog(strategy, DEFAULT_HTTP_CLIENT_FACTORY)
|
||||
.await
|
||||
.models,
|
||||
bundled
|
||||
);
|
||||
}
|
||||
assert_eq!(endpoint.fetch_count(), 0);
|
||||
|
||||
let manager =
|
||||
OpenAiModelsManager::new(home.path().into(), endpoint.clone(), Some(auth.clone()));
|
||||
manager.set_api_key_model_discovery_enabled(/*enabled*/ true);
|
||||
assert_eq!(
|
||||
manager
|
||||
.raw_model_catalog(RefreshStrategy::Online, DEFAULT_HTTP_CLIENT_FACTORY)
|
||||
.await
|
||||
.models,
|
||||
models
|
||||
);
|
||||
assert_eq!(endpoint.fetch_count(), 1);
|
||||
assert_eq!(
|
||||
manager.get_model_info("dynamic", &config).await,
|
||||
CatalogModel {
|
||||
model: models[0].clone().into(),
|
||||
origin: ModelOrigin::Provider
|
||||
}
|
||||
);
|
||||
|
||||
// A runtime rollback must also suppress the already-loaded catalog.
|
||||
manager.set_api_key_model_discovery_enabled(/*enabled*/ false);
|
||||
assert_eq!(
|
||||
manager
|
||||
.raw_model_catalog(RefreshStrategy::Online, DEFAULT_HTTP_CLIENT_FACTORY)
|
||||
.await
|
||||
.models,
|
||||
bundled
|
||||
);
|
||||
assert_eq!(manager.try_get_remote_models().unwrap(), bundled);
|
||||
assert_eq!(
|
||||
manager.get_model_info("dynamic", &config).await.origin,
|
||||
ModelOrigin::Synthetic
|
||||
);
|
||||
assert_eq!(endpoint.fetch_count(), 1);
|
||||
|
||||
// A new session must honor its startup flag even when a matching disk cache exists.
|
||||
for enabled in [false, true] {
|
||||
let restarted =
|
||||
OpenAiModelsManager::new(home.path().into(), endpoint.clone(), Some(auth.clone()));
|
||||
restarted.set_api_key_model_discovery_enabled(enabled);
|
||||
let expected = if enabled { &models } else { &bundled };
|
||||
for strategy in [RefreshStrategy::Offline, RefreshStrategy::OnlineIfUncached] {
|
||||
assert_eq!(
|
||||
&restarted
|
||||
.raw_model_catalog(strategy, DEFAULT_HTTP_CLIENT_FACTORY)
|
||||
.await
|
||||
.models,
|
||||
expected
|
||||
);
|
||||
}
|
||||
assert_eq!(&restarted.try_get_remote_models().unwrap(), expected);
|
||||
}
|
||||
assert_eq!(endpoint.fetch_count(), 1);
|
||||
}
|
||||
267
akode-rs/models-manager/src/cache.rs
Normal file
267
akode-rs/models-manager/src/cache.rs
Normal file
@@ -0,0 +1,267 @@
|
||||
use crate::ModelCatalogOriginator;
|
||||
use chrono::DateTime;
|
||||
use chrono::Utc;
|
||||
use akode_protocol::openai_models::ModelInfo;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use std::fmt;
|
||||
use std::future::Future;
|
||||
use std::io;
|
||||
use std::io::ErrorKind;
|
||||
use std::path::PathBuf;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use tokio::fs;
|
||||
use tracing::info;
|
||||
|
||||
/// Asynchronous storage for model catalog snapshots used by the models manager.
|
||||
///
|
||||
/// Implementations own cache freshness and lookup partitioning. [`ModelsCache::load`] must not
|
||||
/// return stale entries or entries for a different client version. A shared backend must also keep
|
||||
/// catalogs for different providers and tenants separate. The manager also validates the entry
|
||||
/// identity against the current endpoint before using it.
|
||||
///
|
||||
/// Cache failures are non-fatal. The models manager logs them and falls back to the configured
|
||||
/// models endpoint.
|
||||
pub trait ModelsCache: fmt::Debug + Send + Sync {
|
||||
/// Return a separate cache partition, or `None` to disable storage for this originator.
|
||||
/// Implementations must isolate loads, writes, and TTL renewal from the default catalog.
|
||||
fn for_originator(&self, _originator: ModelCatalogOriginator) -> Option<Arc<dyn ModelsCache>> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Loads a fresh entry for `client_version`.
|
||||
///
|
||||
/// Returns `Ok(None)` for a normal miss, including an absent, stale, or version-mismatched
|
||||
/// entry. Returns `Err` when the backend could not complete the lookup; the models manager
|
||||
/// treats that error as a miss and fetches the catalog from the models endpoint.
|
||||
fn load<'a>(
|
||||
&'a self,
|
||||
client_version: &'a str,
|
||||
) -> ModelsCacheFuture<'a, Result<Option<ModelsCacheEntry>, ModelsCacheError>>;
|
||||
|
||||
/// Stores `entry`, replacing the snapshot for this cache implementation's lookup identity.
|
||||
///
|
||||
/// The implementation derives that identity from its own configuration and the entry metadata.
|
||||
/// For example, a shared backend can capture provider and tenant identity when it is constructed.
|
||||
fn store<'a>(
|
||||
&'a self,
|
||||
entry: &'a ModelsCacheEntry,
|
||||
) -> ModelsCacheFuture<'a, Result<(), ModelsCacheError>>;
|
||||
|
||||
/// Extends freshness only if the stored version, identity, and ETag match.
|
||||
///
|
||||
/// The models manager calls this after the endpoint confirms that the cached ETag is still
|
||||
/// current. Implementations must preserve the models, identity, ETag, and client version. This operation
|
||||
/// cannot be expressed in terms of [`ModelsCache::load`], because `load` intentionally omits
|
||||
/// expired entries. File-backed implementations can read and revalidate the stored entry
|
||||
/// directly, while backends with native TTL support can extend the entry in place.
|
||||
fn refresh_ttl<'a>(
|
||||
&'a self,
|
||||
client_version: &'a str,
|
||||
identity: &'a str,
|
||||
etag: &'a str,
|
||||
) -> ModelsCacheFuture<'a, Result<(), ModelsCacheError>>;
|
||||
}
|
||||
|
||||
/// Boxed future returned by [`ModelsCache`] implementations.
|
||||
pub type ModelsCacheFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
|
||||
|
||||
/// Serialized model catalog and validation metadata stored in a [`ModelsCache`].
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct ModelsCacheEntry {
|
||||
/// Time when the catalog was fetched or last revalidated with the models endpoint.
|
||||
///
|
||||
/// `DateTime::<Utc>::MIN_UTC` marks an invalidated catalog, both in memory and in storage.
|
||||
/// The manager rejects it even if the backend uses native TTL.
|
||||
pub fetched_at: DateTime<Utc>,
|
||||
/// Endpoint ETag used to revalidate the catalog without downloading an unchanged payload.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub etag: Option<String>,
|
||||
/// Client version for which this catalog was returned.
|
||||
///
|
||||
/// The models manager rejects entries whose value is absent or differs from its current version.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub client_version: Option<String>,
|
||||
/// Opaque provider and auth identity. Unscoped legacy entries are cache misses.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub identity: Option<String>,
|
||||
/// Models returned by the catalog endpoint.
|
||||
#[serde(
|
||||
deserialize_with = "akode_protocol::openai_models::deserialize_model_infos_with_legacy_base"
|
||||
)]
|
||||
pub models: Vec<ModelInfo>,
|
||||
}
|
||||
|
||||
impl ModelsCacheEntry {
|
||||
/// Returns `true` when the cache entry has not exceeded the configured TTL.
|
||||
fn is_fresh(&self, ttl: Duration) -> bool {
|
||||
if ttl.is_zero() {
|
||||
return false;
|
||||
}
|
||||
let Ok(ttl_duration) = chrono::Duration::from_std(ttl) else {
|
||||
return false;
|
||||
};
|
||||
let age = Utc::now().signed_duration_since(self.fetched_at);
|
||||
age <= ttl_duration
|
||||
}
|
||||
}
|
||||
|
||||
/// Error returned by a [`ModelsCache`] implementation.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ModelsCacheError {
|
||||
message: String,
|
||||
}
|
||||
|
||||
impl ModelsCacheError {
|
||||
/// Create a cache error without exposing backend-specific error types.
|
||||
pub fn new(message: impl Into<String>) -> Self {
|
||||
Self {
|
||||
message: message.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for ModelsCacheError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(&self.message)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ModelsCacheError {}
|
||||
|
||||
/// Built-in file-backed model catalog cache.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct FileModelsCache {
|
||||
cache_path: PathBuf,
|
||||
cache_ttl: Duration,
|
||||
}
|
||||
|
||||
impl FileModelsCache {
|
||||
/// Create a file-backed cache with the given path and TTL.
|
||||
pub(crate) fn new(cache_path: PathBuf, cache_ttl: Duration) -> Self {
|
||||
Self {
|
||||
cache_path,
|
||||
cache_ttl,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ModelsCache for FileModelsCache {
|
||||
fn for_originator(&self, originator: ModelCatalogOriginator) -> Option<Arc<dyn ModelsCache>> {
|
||||
Some(Arc::new(Self::new(
|
||||
self.cache_path
|
||||
.with_extension(format!("{}.json", originator.as_str())),
|
||||
self.cache_ttl,
|
||||
)))
|
||||
}
|
||||
|
||||
fn load<'a>(
|
||||
&'a self,
|
||||
client_version: &'a str,
|
||||
) -> ModelsCacheFuture<'a, Result<Option<ModelsCacheEntry>, ModelsCacheError>> {
|
||||
Box::pin(
|
||||
async move { load_fresh_file(&self.cache_path, self.cache_ttl, client_version).await },
|
||||
)
|
||||
}
|
||||
|
||||
fn store<'a>(
|
||||
&'a self,
|
||||
entry: &'a ModelsCacheEntry,
|
||||
) -> ModelsCacheFuture<'a, Result<(), ModelsCacheError>> {
|
||||
Box::pin(async move { save_file(&self.cache_path, entry).await })
|
||||
}
|
||||
|
||||
fn refresh_ttl<'a>(
|
||||
&'a self,
|
||||
client_version: &'a str,
|
||||
identity: &'a str,
|
||||
etag: &'a str,
|
||||
) -> ModelsCacheFuture<'a, Result<(), ModelsCacheError>> {
|
||||
Box::pin(async move {
|
||||
let mut entry = load_file(&self.cache_path)
|
||||
.await
|
||||
.map_err(cache_error)?
|
||||
.ok_or_else(|| ModelsCacheError::new("cache not found"))?;
|
||||
if entry.client_version.as_deref() != Some(client_version)
|
||||
|| entry.identity.as_deref() != Some(identity)
|
||||
|| entry.etag.as_deref() != Some(etag)
|
||||
|| entry.is_fresh(self.cache_ttl / 2)
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
entry.fetched_at = Utc::now();
|
||||
save_file(&self.cache_path, &entry).await
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
async fn load_fresh_file(
|
||||
cache_path: &PathBuf,
|
||||
cache_ttl: Duration,
|
||||
expected_version: &str,
|
||||
) -> Result<Option<ModelsCacheEntry>, ModelsCacheError> {
|
||||
info!(
|
||||
cache_path = %cache_path.display(),
|
||||
expected_version,
|
||||
"models cache: attempting load_fresh"
|
||||
);
|
||||
let Some(cache) = load_file(cache_path).await.map_err(cache_error)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
info!(
|
||||
cache_path = %cache_path.display(),
|
||||
cached_version = ?cache.client_version,
|
||||
fetched_at = %cache.fetched_at,
|
||||
"models cache: loaded cache file"
|
||||
);
|
||||
if cache.client_version.as_deref() != Some(expected_version) {
|
||||
info!(
|
||||
cache_path = %cache_path.display(),
|
||||
expected_version,
|
||||
cached_version = ?cache.client_version,
|
||||
"models cache: cache version mismatch"
|
||||
);
|
||||
return Ok(None);
|
||||
}
|
||||
if !cache.is_fresh(cache_ttl) {
|
||||
info!(
|
||||
cache_path = %cache_path.display(),
|
||||
cache_ttl_secs = cache_ttl.as_secs(),
|
||||
fetched_at = %cache.fetched_at,
|
||||
"models cache: cache is stale"
|
||||
);
|
||||
return Ok(None);
|
||||
}
|
||||
info!(
|
||||
cache_path = %cache_path.display(),
|
||||
cache_ttl_secs = cache_ttl.as_secs(),
|
||||
"models cache: cache hit"
|
||||
);
|
||||
Ok(Some(cache))
|
||||
}
|
||||
|
||||
async fn load_file(cache_path: &PathBuf) -> io::Result<Option<ModelsCacheEntry>> {
|
||||
match fs::read(cache_path).await {
|
||||
Ok(contents) => {
|
||||
let cache = serde_json::from_slice(&contents)
|
||||
.map_err(|err| io::Error::new(ErrorKind::InvalidData, err.to_string()))?;
|
||||
Ok(Some(cache))
|
||||
}
|
||||
Err(err) if err.kind() == ErrorKind::NotFound => Ok(None),
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
|
||||
async fn save_file(cache_path: &PathBuf, cache: &ModelsCacheEntry) -> Result<(), ModelsCacheError> {
|
||||
if let Some(parent) = cache_path.parent() {
|
||||
fs::create_dir_all(parent).await.map_err(cache_error)?;
|
||||
}
|
||||
let json = serde_json::to_vec_pretty(cache).map_err(cache_error)?;
|
||||
fs::write(cache_path, json).await.map_err(cache_error)
|
||||
}
|
||||
|
||||
fn cache_error(error: impl fmt::Display) -> ModelsCacheError {
|
||||
ModelsCacheError::new(error.to_string())
|
||||
}
|
||||
84
akode-rs/models-manager/src/cache_identity_tests.rs
Normal file
84
akode-rs/models-manager/src/cache_identity_tests.rs
Normal file
@@ -0,0 +1,84 @@
|
||||
//! Coverage for cache identity validation and conditional freshness updates.
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[tokio::test]
|
||||
async fn mismatched_and_legacy_cache_entries_fetch_the_current_catalog() {
|
||||
for identity in [None, Some("other-provider-or-account".to_string())] {
|
||||
let stale = remote_model("stale", "Stale", /*priority*/ 0);
|
||||
let current = remote_model("current", "Current", /*priority*/ 0);
|
||||
let cache = TestModelsCache::with_entry(ModelsCacheEntry {
|
||||
fetched_at: Utc::now(),
|
||||
etag: Some("old-etag".into()),
|
||||
client_version: Some(crate::client_version_to_whole()),
|
||||
identity,
|
||||
models: vec![stale],
|
||||
});
|
||||
let endpoint = TestModelsEndpoint::new(vec![vec![current.clone()]]);
|
||||
let manager = OpenAiModelsManager::new_with_cache(
|
||||
cache.clone(),
|
||||
endpoint.clone(),
|
||||
Some(AuthManager::from_auth_for_testing(CodexAuth::from_api_key(
|
||||
"test-api-key",
|
||||
))),
|
||||
);
|
||||
manager.set_api_key_model_discovery_enabled(/*enabled*/ true);
|
||||
manager
|
||||
.ensure_initialized(DEFAULT_HTTP_CLIENT_FACTORY)
|
||||
.await;
|
||||
assert_eq!(
|
||||
manager
|
||||
.raw_model_catalog(RefreshStrategy::InMemory, DEFAULT_HTTP_CLIENT_FACTORY)
|
||||
.await
|
||||
.models,
|
||||
vec![current.clone()]
|
||||
);
|
||||
assert_eq!(endpoint.fetch_count(), 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn matching_etag_cannot_renew_a_different_identity_or_catalog() {
|
||||
let home = tempdir().unwrap();
|
||||
let cache = FileModelsCache::new(home.path().join(MODEL_CACHE_FILE), DEFAULT_MODEL_CACHE_TTL);
|
||||
let expected = ModelsCacheEntry {
|
||||
fetched_at: Utc::now() - chrono::Duration::hours(1),
|
||||
etag: Some("etag".into()),
|
||||
client_version: Some(crate::client_version_to_whole()),
|
||||
identity: Some("first-account".into()),
|
||||
models: vec![remote_model("model", "Model", /*priority*/ 0)],
|
||||
};
|
||||
for (key, etag, version) in [
|
||||
("other-account", "etag", crate::client_version_to_whole()),
|
||||
(
|
||||
"first-account",
|
||||
"new-etag",
|
||||
crate::client_version_to_whole(),
|
||||
),
|
||||
("first-account", "etag", "other-version".into()),
|
||||
] {
|
||||
let stored = ModelsCacheEntry {
|
||||
identity: Some(key.into()),
|
||||
etag: Some(etag.into()),
|
||||
client_version: Some(version),
|
||||
..expected.clone()
|
||||
};
|
||||
cache.store(&stored).await.unwrap();
|
||||
cache
|
||||
.refresh_ttl(
|
||||
expected.client_version.as_deref().unwrap(),
|
||||
expected.identity.as_deref().unwrap(),
|
||||
expected.etag.as_deref().unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let actual: ModelsCacheEntry = serde_json::from_slice(
|
||||
&tokio::fs::read(home.path().join(MODEL_CACHE_FILE))
|
||||
.await
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(actual, stored);
|
||||
}
|
||||
}
|
||||
81
akode-rs/models-manager/src/catalog.rs
Normal file
81
akode-rs/models-manager/src/catalog.rs
Normal file
@@ -0,0 +1,81 @@
|
||||
//! Tracks the source of model metadata without changing the catalog wire or cache formats.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::collections::HashSet;
|
||||
|
||||
use akode_protocol::openai_models::ModelInfo;
|
||||
|
||||
use crate::cache::ModelsCacheEntry;
|
||||
|
||||
pub use akode_protocol::openai_models::CatalogModel;
|
||||
pub use akode_protocol::openai_models::ModelOrigin;
|
||||
|
||||
/// Catalog authority is independent of whether its model metadata is borrowed or owned.
|
||||
pub(crate) enum SelectedCatalog<'a> {
|
||||
CurrentSnapshot(Cow<'a, [ModelInfo]>),
|
||||
Fallback(Cow<'a, [ModelInfo]>),
|
||||
}
|
||||
|
||||
impl<'a> SelectedCatalog<'a> {
|
||||
pub fn into_models(self) -> Cow<'a, [ModelInfo]> {
|
||||
match self {
|
||||
Self::CurrentSnapshot(models) | Self::Fallback(models) => models,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The effective catalog and the IDs in the unmerged provider response share one lock.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct CatalogState {
|
||||
pub entry: ModelsCacheEntry,
|
||||
pub provider_model_ids: HashSet<String>,
|
||||
// Distinguishes a successfully loaded empty catalog from the initial bundled seed.
|
||||
pub initialized: bool,
|
||||
}
|
||||
|
||||
impl CatalogState {
|
||||
pub fn bundled(entry: ModelsCacheEntry) -> Self {
|
||||
Self {
|
||||
entry,
|
||||
provider_model_ids: HashSet::new(),
|
||||
initialized: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn provider(entry: ModelsCacheEntry) -> Self {
|
||||
// Capture raw response IDs before merging, including when loading from disk cache.
|
||||
let provider_model_ids = entry
|
||||
.models
|
||||
.iter()
|
||||
.map(|model| model.slug.clone())
|
||||
.collect();
|
||||
Self {
|
||||
entry,
|
||||
provider_model_ids,
|
||||
initialized: true,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn model_origin(&self, selected: &SelectedCatalog<'_>, slug: &str) -> ModelOrigin {
|
||||
if matches!(selected, SelectedCatalog::CurrentSnapshot(_))
|
||||
&& self.provider_model_ids.contains(slug)
|
||||
{
|
||||
ModelOrigin::Provider
|
||||
} else {
|
||||
ModelOrigin::Bundled
|
||||
}
|
||||
}
|
||||
|
||||
pub fn model_catalog(&self, selected: SelectedCatalog<'_>) -> Vec<CatalogModel> {
|
||||
let models = match &selected {
|
||||
SelectedCatalog::CurrentSnapshot(models) | SelectedCatalog::Fallback(models) => models,
|
||||
};
|
||||
models
|
||||
.iter()
|
||||
.map(|model| CatalogModel {
|
||||
origin: self.model_origin(&selected, &model.slug),
|
||||
model: model.clone().into(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
184
akode-rs/models-manager/src/catalog_origin_tests.rs
Normal file
184
akode-rs/models-manager/src/catalog_origin_tests.rs
Normal file
@@ -0,0 +1,184 @@
|
||||
#![cfg(test)]
|
||||
//! Catalog origins survive merges, cache reloads, and changes of provider identity.
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[tokio::test]
|
||||
async fn catalog_origins_survive_reload_and_auth_change() {
|
||||
for (slug, reviewer_origin) in [
|
||||
("codex-auto-review", ModelOrigin::Provider),
|
||||
("gateway-model", ModelOrigin::Bundled),
|
||||
] {
|
||||
let home = tempdir().unwrap();
|
||||
let model = remote_model_with_visibility(slug, "Gateway", /*priority*/ 0, "hide");
|
||||
let auth = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("test-api-key"));
|
||||
let endpoint =
|
||||
TestAuthAwareModelsEndpoint::new(Some(auth.clone()), vec![vec![model.clone()]]);
|
||||
let manager =
|
||||
OpenAiModelsManager::new(home.path().into(), endpoint.clone(), Some(auth.clone()));
|
||||
let mut updates = manager.model_catalog_updates().unwrap();
|
||||
manager.set_api_key_model_discovery_enabled(/*enabled*/ true);
|
||||
let bundled = manager
|
||||
.model_catalog_with_origins(RefreshStrategy::Offline, DEFAULT_HTTP_CLIENT_FACTORY)
|
||||
.await;
|
||||
assert!(manager.refreshed_model_catalog().is_none());
|
||||
assert!(!updates.has_changed().unwrap());
|
||||
let catalog = manager
|
||||
.model_catalog_with_origins(RefreshStrategy::Online, DEFAULT_HTTP_CLIENT_FACTORY)
|
||||
.await;
|
||||
assert_eq!(
|
||||
manager.refreshed_model_catalog().as_deref(),
|
||||
Some([model.clone()].as_slice())
|
||||
);
|
||||
assert!(updates.has_changed().unwrap());
|
||||
updates.borrow_and_update();
|
||||
assert!(catalog.contains(&CatalogModel {
|
||||
model: model.into(),
|
||||
origin: ModelOrigin::Provider
|
||||
}));
|
||||
assert_eq!(
|
||||
catalog
|
||||
.iter()
|
||||
.find(|entry| entry.model.slug == "codex-auto-review")
|
||||
.map(|entry| entry.origin),
|
||||
Some(reviewer_origin)
|
||||
);
|
||||
|
||||
let restarted = openai_manager_for_tests(home.path().to_path_buf(), endpoint.clone());
|
||||
assert_eq!(
|
||||
restarted
|
||||
.model_catalog_with_origins(RefreshStrategy::Offline, DEFAULT_HTTP_CLIENT_FACTORY)
|
||||
.await,
|
||||
catalog
|
||||
);
|
||||
assert_eq!(endpoint.fetch_count(), 1);
|
||||
assert!(
|
||||
restarted.refreshed_model_catalog().is_none(),
|
||||
"disk cache is not a fresh provider response"
|
||||
);
|
||||
assert_eq!(
|
||||
restarted
|
||||
.get_model_info(
|
||||
&format!("gateway/{slug}-variant"),
|
||||
&ModelsManagerConfig::default()
|
||||
)
|
||||
.await
|
||||
.origin,
|
||||
ModelOrigin::Provider
|
||||
);
|
||||
|
||||
// An empty subsequent response restores bundled origins instead of retaining old IDs.
|
||||
assert_eq!(
|
||||
restarted
|
||||
.model_catalog_with_origins(RefreshStrategy::Online, DEFAULT_HTTP_CLIENT_FACTORY)
|
||||
.await,
|
||||
bundled
|
||||
);
|
||||
|
||||
// The original manager still holds provider IDs, but its identity is no longer current.
|
||||
auth.set_external_auth(Arc::new(TestExternalApiKeyAuth))
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
manager.refreshed_model_catalog().is_none(),
|
||||
"a previous identity cannot normalize settings"
|
||||
);
|
||||
assert_eq!(
|
||||
manager
|
||||
.model_catalog_with_origins(RefreshStrategy::Offline, DEFAULT_HTTP_CLIENT_FACTORY)
|
||||
.await,
|
||||
bundled
|
||||
);
|
||||
assert_eq!(endpoint.fetch_count(), 2);
|
||||
assert_eq!(
|
||||
manager
|
||||
.get_model_info("codex-auto-review", &ModelsManagerConfig::default())
|
||||
.await
|
||||
.origin,
|
||||
ModelOrigin::Bundled
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn static_catalog_records_its_supplied_origin() {
|
||||
let model = remote_model("reviewer", "Reviewer", /*priority*/ 0);
|
||||
for origin in [
|
||||
ModelOrigin::Bundled,
|
||||
ModelOrigin::Provider,
|
||||
ModelOrigin::ExplicitConfig,
|
||||
] {
|
||||
let manager = StaticModelsManager::new(
|
||||
/*auth_manager*/ None,
|
||||
ModelsResponse {
|
||||
models: vec![model.clone()],
|
||||
},
|
||||
origin,
|
||||
);
|
||||
assert_eq!(
|
||||
manager
|
||||
.get_model_info(
|
||||
"namespace/reviewer-variant",
|
||||
&ModelsManagerConfig::default()
|
||||
)
|
||||
.await,
|
||||
CatalogModel {
|
||||
model: ModelInfo {
|
||||
slug: "namespace/reviewer-variant".to_string(),
|
||||
..model.clone()
|
||||
}
|
||||
.into(),
|
||||
origin
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
manager
|
||||
.model_catalog_with_origins(RefreshStrategy::Offline, DEFAULT_HTTP_CLIENT_FACTORY)
|
||||
.await,
|
||||
vec![CatalogModel {
|
||||
model: model.clone().into(),
|
||||
origin
|
||||
}]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn refreshing_retained_originators_keeps_catalog_notifications_isolated() {
|
||||
let root_model = remote_model("root-model", "Root", /*priority*/ 0);
|
||||
let work_model = remote_model("work-model", "Work", /*priority*/ 0);
|
||||
let root_endpoint = TestModelsEndpoint::new(vec![vec![root_model.clone()]]);
|
||||
let work_endpoint = TestModelsEndpoint::new(vec![vec![work_model.clone()]]);
|
||||
let auth = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("test-api-key"));
|
||||
let root = OpenAiModelsManager::new_without_cache(root_endpoint.clone(), Some(auth.clone()));
|
||||
root.set_api_key_model_discovery_enabled(/*enabled*/ true);
|
||||
let work = Arc::new(OpenAiModelsManager::new_without_cache(
|
||||
work_endpoint.clone(),
|
||||
Some(auth),
|
||||
));
|
||||
work.set_api_key_model_discovery_enabled(/*enabled*/ true);
|
||||
root.list_models(RefreshStrategy::Online, DEFAULT_HTTP_CLIENT_FACTORY)
|
||||
.await;
|
||||
let root_updates = root.model_catalog_updates().unwrap();
|
||||
let work_updates = work.model_catalog_updates().unwrap();
|
||||
root.originator_managers
|
||||
.lock()
|
||||
.unwrap()
|
||||
.insert(ModelCatalogOriginator::WorkDesktop, work.clone());
|
||||
root.refresh_originator_catalogs(DEFAULT_HTTP_CLIENT_FACTORY)
|
||||
.await;
|
||||
assert_eq!(
|
||||
root.refreshed_model_catalog().as_deref(),
|
||||
Some([root_model].as_slice())
|
||||
);
|
||||
assert_eq!(
|
||||
work.refreshed_model_catalog().as_deref(),
|
||||
Some([work_model].as_slice())
|
||||
);
|
||||
assert!(!root_updates.has_changed().unwrap());
|
||||
assert!(work_updates.has_changed().unwrap());
|
||||
assert_eq!(root_endpoint.fetch_count(), 1);
|
||||
assert_eq!(work_endpoint.fetch_count(), 1);
|
||||
assert_eq!(root.originator_managers.lock().unwrap().len(), 1);
|
||||
}
|
||||
28
akode-rs/models-manager/src/collaboration_mode_presets.rs
Normal file
28
akode-rs/models-manager/src/collaboration_mode_presets.rs
Normal file
@@ -0,0 +1,28 @@
|
||||
use akode_prompts::ResolvedModelMessages;
|
||||
use akode_protocol::config_types::CollaborationModeMask;
|
||||
use akode_protocol::config_types::ModeKind;
|
||||
use akode_protocol::openai_models::ReasoningEffort;
|
||||
|
||||
pub fn builtin_collaboration_mode_presets() -> Vec<CollaborationModeMask> {
|
||||
let messages = ResolvedModelMessages::bundled().collaboration_modes();
|
||||
vec![
|
||||
CollaborationModeMask {
|
||||
name: ModeKind::Plan.display_name().to_string(),
|
||||
mode: Some(ModeKind::Plan),
|
||||
model: None,
|
||||
reasoning_effort: Some(Some(ReasoningEffort::Medium)),
|
||||
developer_instructions: Some(Some(messages.plan.text().to_string())),
|
||||
},
|
||||
CollaborationModeMask {
|
||||
name: ModeKind::Default.display_name().to_string(),
|
||||
mode: Some(ModeKind::Default),
|
||||
model: None,
|
||||
reasoning_effort: None,
|
||||
developer_instructions: Some(Some(messages.default.text().to_string())),
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "collaboration_mode_presets_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,34 @@
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn preset_names_use_mode_display_names() {
|
||||
let presets = builtin_collaboration_mode_presets();
|
||||
let [plan, default] = presets.as_slice() else {
|
||||
panic!("expected Plan and Default presets");
|
||||
};
|
||||
assert_eq!(plan.name, ModeKind::Plan.display_name());
|
||||
assert_eq!(default.name, ModeKind::Default.display_name());
|
||||
assert_eq!(plan.model, None);
|
||||
assert_eq!(plan.reasoning_effort, Some(Some(ReasoningEffort::Medium)));
|
||||
assert_eq!(default.model, None);
|
||||
assert_eq!(default.reasoning_effort, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_mode_instructions_follow_user_input_tool_availability() {
|
||||
let presets = builtin_collaboration_mode_presets();
|
||||
let default_instructions = presets[1]
|
||||
.developer_instructions
|
||||
.as_ref()
|
||||
.expect("default preset should include instructions")
|
||||
.as_ref()
|
||||
.expect("default instructions should be set");
|
||||
|
||||
assert!(default_instructions.contains(
|
||||
"Use the `request_user_input` tool only when it is listed in the available tools"
|
||||
));
|
||||
assert!(
|
||||
default_instructions.contains("Ask the user directly with one concise plain-text question")
|
||||
);
|
||||
}
|
||||
12
akode-rs/models-manager/src/config.rs
Normal file
12
akode-rs/models-manager/src/config.rs
Normal file
@@ -0,0 +1,12 @@
|
||||
use akode_protocol::config_types::Personality;
|
||||
use akode_protocol::openai_models::ModelsResponse;
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct ModelsManagerConfig {
|
||||
pub model_context_window: Option<i64>,
|
||||
pub model_auto_compact_token_limit: Option<i64>,
|
||||
pub tool_output_token_limit: Option<usize>,
|
||||
pub base_instructions: Option<String>,
|
||||
pub personality: Option<Personality>,
|
||||
pub model_catalog: Option<ModelsResponse>,
|
||||
}
|
||||
31
akode-rs/models-manager/src/lib.rs
Normal file
31
akode-rs/models-manager/src/lib.rs
Normal file
@@ -0,0 +1,31 @@
|
||||
pub mod cache;
|
||||
mod catalog;
|
||||
pub mod collaboration_mode_presets;
|
||||
pub(crate) mod config;
|
||||
pub mod manager;
|
||||
pub mod model_info;
|
||||
pub mod model_presets;
|
||||
mod originator;
|
||||
pub mod test_support;
|
||||
|
||||
pub use catalog::CatalogModel;
|
||||
pub use catalog::ModelOrigin;
|
||||
pub use akode_protocol::auth::AuthMode;
|
||||
pub use config::ModelsManagerConfig;
|
||||
pub use originator::ModelCatalogOriginator;
|
||||
|
||||
/// Load the bundled model catalog shipped with `akode-models-manager`.
|
||||
pub fn bundled_models_response()
|
||||
-> std::result::Result<akode_protocol::openai_models::ModelsResponse, serde_json::Error> {
|
||||
serde_json::from_str(include_str!("../models.json"))
|
||||
}
|
||||
|
||||
/// Convert the client version string to a whole version string (e.g. "1.2.3-alpha.4" -> "1.2.3").
|
||||
pub fn client_version_to_whole() -> String {
|
||||
format!(
|
||||
"{}.{}.{}",
|
||||
env!("CARGO_PKG_VERSION_MAJOR"),
|
||||
env!("CARGO_PKG_VERSION_MINOR"),
|
||||
env!("CARGO_PKG_VERSION_PATCH")
|
||||
)
|
||||
}
|
||||
1250
akode-rs/models-manager/src/manager.rs
Normal file
1250
akode-rs/models-manager/src/manager.rs
Normal file
File diff suppressed because it is too large
Load Diff
1817
akode-rs/models-manager/src/manager_tests.rs
Normal file
1817
akode-rs/models-manager/src/manager_tests.rs
Normal file
File diff suppressed because it is too large
Load Diff
159
akode-rs/models-manager/src/model_info.rs
Normal file
159
akode-rs/models-manager/src/model_info.rs
Normal file
@@ -0,0 +1,159 @@
|
||||
use akode_protocol::config_types::Personality;
|
||||
use akode_protocol::config_types::ReasoningSummary;
|
||||
use akode_protocol::openai_models::ConfigShellToolType;
|
||||
use akode_protocol::openai_models::ModelInfo;
|
||||
use akode_protocol::openai_models::ModelMessages;
|
||||
use akode_protocol::openai_models::ModelVisibility;
|
||||
use akode_protocol::openai_models::TruncationMode;
|
||||
use akode_protocol::openai_models::TruncationPolicyConfig;
|
||||
use akode_protocol::openai_models::WebSearchToolType;
|
||||
use akode_protocol::openai_models::default_input_modalities;
|
||||
|
||||
use crate::config::ModelsManagerConfig;
|
||||
use akode_utils_output_truncation::approx_bytes_for_tokens;
|
||||
use tracing::warn;
|
||||
|
||||
pub const BASE_INSTRUCTIONS: &str = include_str!("../prompt.md");
|
||||
const PERSONALITY_SECTION_HEADER: &str = "# Personality";
|
||||
|
||||
pub fn with_config_overrides(mut model: ModelInfo, config: &ModelsManagerConfig) -> ModelInfo {
|
||||
if let Some(context_window) = config.model_context_window {
|
||||
model.context_window = Some(
|
||||
model
|
||||
.max_context_window
|
||||
.map_or(context_window, |max_context_window| {
|
||||
context_window.min(max_context_window)
|
||||
}),
|
||||
);
|
||||
}
|
||||
if let Some(auto_compact_token_limit) = config.model_auto_compact_token_limit {
|
||||
model.auto_compact_token_limit = Some(auto_compact_token_limit);
|
||||
}
|
||||
if let Some(token_limit) = config.tool_output_token_limit {
|
||||
model.truncation_policy = match model.truncation_policy.mode {
|
||||
TruncationMode::Bytes => {
|
||||
let byte_limit =
|
||||
i64::try_from(approx_bytes_for_tokens(token_limit)).unwrap_or(i64::MAX);
|
||||
TruncationPolicyConfig::bytes(byte_limit)
|
||||
}
|
||||
TruncationMode::Tokens => {
|
||||
let limit = i64::try_from(token_limit).unwrap_or(i64::MAX);
|
||||
TruncationPolicyConfig::tokens(limit)
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
if let Some(base_instructions) = &config.base_instructions {
|
||||
let model_messages = model.model_messages.get_or_insert_default();
|
||||
model_messages.instructions_template = Some(base_instructions.clone());
|
||||
} else if config.personality == Some(Personality::None)
|
||||
&& let Some(instructions_template) = model
|
||||
.model_messages
|
||||
.as_mut()
|
||||
.and_then(|messages| messages.instructions_template.as_mut())
|
||||
{
|
||||
*instructions_template = strip_personality_section(std::mem::take(instructions_template));
|
||||
}
|
||||
|
||||
model
|
||||
}
|
||||
|
||||
fn strip_personality_section(mut instructions: String) -> String {
|
||||
let mut section_start = None;
|
||||
let mut section_end = None;
|
||||
let mut offset = 0;
|
||||
|
||||
for line_with_ending in instructions.split_inclusive('\n') {
|
||||
let line = match line_with_ending.strip_suffix('\n') {
|
||||
Some(line) => line.strip_suffix('\r').unwrap_or(line),
|
||||
None => line_with_ending,
|
||||
};
|
||||
if section_start.is_some() {
|
||||
if is_h1_heading(line) {
|
||||
section_end = Some(offset);
|
||||
break;
|
||||
}
|
||||
} else if line == PERSONALITY_SECTION_HEADER {
|
||||
section_start = Some(offset);
|
||||
}
|
||||
offset += line_with_ending.len();
|
||||
}
|
||||
|
||||
if let Some(section_start) = section_start {
|
||||
let section_end = section_end.unwrap_or(instructions.len());
|
||||
instructions.replace_range(section_start..section_end, "");
|
||||
}
|
||||
|
||||
instructions
|
||||
}
|
||||
|
||||
fn is_h1_heading(line: &str) -> bool {
|
||||
let Some(rest) = line.strip_prefix('#') else {
|
||||
return false;
|
||||
};
|
||||
rest.is_empty() || rest.starts_with(' ') || rest.starts_with('\t')
|
||||
}
|
||||
|
||||
/// Build a minimal fallback model descriptor for missing/unknown slugs.
|
||||
pub fn model_info_from_slug(slug: &str) -> ModelInfo {
|
||||
warn!("Unknown model {slug} is used. This will use fallback model metadata.");
|
||||
ModelInfo {
|
||||
slug: slug.to_string(),
|
||||
display_name: slug.to_string(),
|
||||
description: None,
|
||||
default_reasoning_level: None,
|
||||
supported_reasoning_levels: Vec::new(),
|
||||
shell_type: ConfigShellToolType::UnifiedExec,
|
||||
visibility: ModelVisibility::None,
|
||||
supported_in_api: true,
|
||||
priority: 99,
|
||||
additional_speed_tiers: Vec::new(),
|
||||
service_tiers: Vec::new(),
|
||||
default_service_tier: None,
|
||||
availability_nux: None,
|
||||
upgrade: None,
|
||||
model_messages: Some(local_model_messages()),
|
||||
include_skills_usage_instructions: false,
|
||||
include_plugin_usage_instructions: false,
|
||||
include_apps_usage_instructions: false,
|
||||
supports_reasoning_summary_parameter: true,
|
||||
default_reasoning_summary: ReasoningSummary::Auto,
|
||||
support_verbosity: false,
|
||||
default_verbosity: None,
|
||||
apply_patch_tool_type: None,
|
||||
web_search_tool_type: WebSearchToolType::Text,
|
||||
web_search_provider: None,
|
||||
truncation_policy: TruncationPolicyConfig::bytes(/*limit*/ 10_000),
|
||||
supports_image_detail_original: false,
|
||||
context_window: Some(272_000),
|
||||
max_context_window: Some(272_000),
|
||||
auto_compact_token_limit: None,
|
||||
comp_hash: None,
|
||||
effective_context_window_percent: 95,
|
||||
experimental_supported_tools: Vec::new(),
|
||||
input_modalities: default_input_modalities(),
|
||||
supports_search_tool: false,
|
||||
supports_experimental_context: false,
|
||||
use_responses_lite: false,
|
||||
supports_reasoning_effort_updates: false,
|
||||
guardian: None,
|
||||
node_repl_auto_review_required: false,
|
||||
node_repl_disabled: false,
|
||||
auto_review_model_override: None,
|
||||
model_specialty: None,
|
||||
tool_mode: None,
|
||||
multi_agent_version: None,
|
||||
multi_agent_reasoning_effort: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn local_model_messages() -> ModelMessages {
|
||||
ModelMessages {
|
||||
instructions_template: Some(BASE_INSTRUCTIONS.to_string()),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "model_info_tests.rs"]
|
||||
mod tests;
|
||||
45
akode-rs/models-manager/src/model_info_overrides_tests.rs
Normal file
45
akode-rs/models-manager/src/model_info_overrides_tests.rs
Normal file
@@ -0,0 +1,45 @@
|
||||
use crate::ModelsManagerConfig;
|
||||
use crate::manager::ModelsManager;
|
||||
use akode_protocol::openai_models::TruncationPolicyConfig;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::TempDir;
|
||||
|
||||
use super::TestModelsEndpoint;
|
||||
use super::openai_manager_for_tests;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn offline_model_info_without_tool_output_override() {
|
||||
let codex_home = TempDir::new().expect("create temp dir");
|
||||
let config = ModelsManagerConfig::default();
|
||||
let manager = openai_manager_for_tests(
|
||||
codex_home.path().to_path_buf(),
|
||||
TestModelsEndpoint::new(Vec::new()),
|
||||
);
|
||||
|
||||
let model_info = manager.get_model_info("unknown-model", &config).await;
|
||||
|
||||
assert_eq!(
|
||||
model_info.truncation_policy,
|
||||
TruncationPolicyConfig::bytes(/*limit*/ 10_000)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn offline_model_info_with_tool_output_override() {
|
||||
let codex_home = TempDir::new().expect("create temp dir");
|
||||
let config = ModelsManagerConfig {
|
||||
tool_output_token_limit: Some(123),
|
||||
..Default::default()
|
||||
};
|
||||
let manager = openai_manager_for_tests(
|
||||
codex_home.path().to_path_buf(),
|
||||
TestModelsEndpoint::new(Vec::new()),
|
||||
);
|
||||
|
||||
let model_info = manager.get_model_info("gpt-5.5", &config).await;
|
||||
|
||||
assert_eq!(
|
||||
model_info.truncation_policy,
|
||||
TruncationPolicyConfig::tokens(/*limit*/ 123)
|
||||
);
|
||||
}
|
||||
280
akode-rs/models-manager/src/model_info_tests.rs
Normal file
280
akode-rs/models-manager/src/model_info_tests.rs
Normal file
@@ -0,0 +1,280 @@
|
||||
use super::*;
|
||||
use crate::ModelsManagerConfig;
|
||||
use akode_prompts::render_model_instructions;
|
||||
use akode_protocol::config_types::Personality;
|
||||
use akode_protocol::openai_models::ApprovalMessages;
|
||||
use akode_protocol::openai_models::AppsMessages;
|
||||
use akode_protocol::openai_models::AutoReviewMessages;
|
||||
use akode_protocol::openai_models::CollaborationModeMessages;
|
||||
use akode_protocol::openai_models::ConfirmationPolicies;
|
||||
use akode_protocol::openai_models::GranularApprovalMessages;
|
||||
use akode_protocol::openai_models::GuardianV2ModelConfig;
|
||||
use akode_protocol::openai_models::ModelTokenBudgetConfig;
|
||||
use akode_protocol::openai_models::MultiAgentMessages;
|
||||
use akode_protocol::openai_models::MultiAgentModeMessages;
|
||||
use akode_protocol::openai_models::MultiAgentRoleMessages;
|
||||
use akode_protocol::openai_models::MultiAgentToolMessages;
|
||||
use akode_protocol::openai_models::PermissionMessages;
|
||||
use akode_protocol::openai_models::ToolMessage;
|
||||
use akode_protocol::openai_models::ToolMessages;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
fn config_with_personality(personality: Option<Personality>) -> ModelsManagerConfig {
|
||||
ModelsManagerConfig {
|
||||
personality,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn base_instruction_override_is_literal_and_preserves_catalog_messages() {
|
||||
let override_instructions = "override {{ personality }}\n# Personality\nKeep me";
|
||||
let persistent_instructions = "Follow up on the active task.";
|
||||
let async_message_description = "Catalog async message description.";
|
||||
let mut model = model_info_from_slug("unknown-model");
|
||||
let approvals = ApprovalMessages {
|
||||
on_request: Some("user approvals".to_string()),
|
||||
on_request_auto_review: Some("auto approvals".to_string()),
|
||||
never: Some("never approvals".to_string()),
|
||||
unless_trusted: Some("unless-trusted approvals".to_string()),
|
||||
granular: Some(GranularApprovalMessages {
|
||||
intro: Some("Catalog: {{ policy }}".to_string()),
|
||||
prompted_categories: Some("Allowed: {{ categories }}".to_string()),
|
||||
rejected_categories: Some("Denied: {{ categories }}".to_string()),
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
let collaboration_modes = CollaborationModeMessages {
|
||||
default: Some("default instructions".to_string()),
|
||||
plan: Some("plan instructions".to_string()),
|
||||
};
|
||||
let auto_review = AutoReviewMessages {
|
||||
policy: Some("review policy".to_string()),
|
||||
policy_template: Some("review policy template".to_string()),
|
||||
node_repl_policy: None,
|
||||
rejection_instructions: Some("rejection instructions".to_string()),
|
||||
timeout_instructions: Some(String::new()),
|
||||
};
|
||||
let permissions = PermissionMessages {
|
||||
danger_full_access: Some("danger".to_string()),
|
||||
workspace_write: Some(String::new()),
|
||||
read_only: None,
|
||||
approved_prefixes: None,
|
||||
..PermissionMessages::default()
|
||||
};
|
||||
let multi_agent = MultiAgentMessages {
|
||||
role: Some(MultiAgentRoleMessages {
|
||||
root: Some("root base".to_string()),
|
||||
subagent: Some("subagent base".to_string()),
|
||||
}),
|
||||
mode: Some(MultiAgentModeMessages {
|
||||
explicit: Some("explicit mode".to_string()),
|
||||
proactive: Some("proactive mode".to_string()),
|
||||
hint_text: Some("mode hint".to_string()),
|
||||
}),
|
||||
};
|
||||
let token_budget = ModelTokenBudgetConfig {
|
||||
enabled: false,
|
||||
reminder_threshold_tokens: 128,
|
||||
reminder_message_template: "budget reminder".to_string(),
|
||||
guidance_message: "budget guidance".to_string(),
|
||||
auto_compact_fallback_prompt: "compact prompt".to_string(),
|
||||
auto_compact_fallback_buffer_tokens: 64,
|
||||
};
|
||||
let guardian_v2 = GuardianV2ModelConfig {
|
||||
classifier_instructions: Some("Guardian experiment".to_string()),
|
||||
..Default::default()
|
||||
};
|
||||
let confirmation_policies = ConfirmationPolicies {
|
||||
browser_use: Some("# Browser policy\n\n{{literal_markdown}}\n".to_string()),
|
||||
computer_use: Some(" # Native policy\r\n\n${native_markdown}\n".to_string()),
|
||||
};
|
||||
let mut messages = ModelMessages {
|
||||
apps: Some(AppsMessages {
|
||||
usage_instructions: Some("Catalog Apps instructions.".to_string()),
|
||||
}),
|
||||
plugins: None,
|
||||
content_filter_guidance: None,
|
||||
persistent_instructions: Some(persistent_instructions.to_string()),
|
||||
tools: Some(ToolMessages {
|
||||
send_user_message_async: Some(ToolMessage {
|
||||
description: Some(async_message_description.to_string()),
|
||||
..Default::default()
|
||||
}),
|
||||
multi_agent: Some(MultiAgentToolMessages {
|
||||
spawn_agent: Some(ToolMessage {
|
||||
description: Some("Catalog spawn description.".to_string()),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
}),
|
||||
instructions_template: Some("template".to_string()),
|
||||
approvals: Some(approvals),
|
||||
collaboration_modes: Some(collaboration_modes),
|
||||
auto_review: Some(auto_review),
|
||||
permissions: Some(permissions),
|
||||
multi_agent: Some(multi_agent),
|
||||
token_budget: Some(token_budget),
|
||||
confirmation_policies: Some(confirmation_policies),
|
||||
guardian_v2: Some(guardian_v2),
|
||||
};
|
||||
model.model_messages = Some(messages.clone());
|
||||
let config = ModelsManagerConfig {
|
||||
base_instructions: Some(override_instructions.to_string()),
|
||||
personality: Some(Personality::None),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let updated = with_config_overrides(model, &config);
|
||||
|
||||
messages.instructions_template = Some(override_instructions.to_string());
|
||||
assert_eq!(updated.model_messages, Some(messages));
|
||||
assert_eq!(render_model_instructions(&updated), override_instructions);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn personality_none_strips_catalog_instruction_sources_through_the_next_h1() {
|
||||
let config = config_with_personality(Some(Personality::None));
|
||||
for (instructions, expected) in [
|
||||
(
|
||||
"Intro\n\n# Personality\n\nRemove me\n\n## Writing Style\n\nRemove me too\n\n# Safety\n\nKeep me",
|
||||
"Intro\n\n# Safety\n\nKeep me",
|
||||
),
|
||||
("Intro\n\n# Personality\n\nRemove me", "Intro\n\n"),
|
||||
(
|
||||
"Intro\n\n## Personality\n\nKeep me",
|
||||
"Intro\n\n## Personality\n\nKeep me",
|
||||
),
|
||||
(
|
||||
"Intro\n\n# Personality \n\nKeep me",
|
||||
"Intro\n\n# Personality \n\nKeep me",
|
||||
),
|
||||
(
|
||||
"Intro\r\n\r\n# Personality\r\n\r\nRemove me\r\n\r\n## Writing Style\r\n\r\nRemove me too\r\n\r\n# General\r\n\r\nKeep me",
|
||||
"Intro\r\n\r\n# General\r\n\r\nKeep me",
|
||||
),
|
||||
] {
|
||||
let mut messages = ModelMessages {
|
||||
instructions_template: Some(instructions.to_string()),
|
||||
persistent_instructions: Some(String::new()),
|
||||
tools: Some(ToolMessages {
|
||||
send_user_message_async: Some(ToolMessage {
|
||||
description: Some(String::new()),
|
||||
..Default::default()
|
||||
}),
|
||||
multi_agent: Some(MultiAgentToolMessages {
|
||||
spawn_agent: Some(ToolMessage {
|
||||
description: Some(String::new()),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
}),
|
||||
approvals: Some(ApprovalMessages {
|
||||
on_request: Some("user approvals".to_string()),
|
||||
on_request_auto_review: None,
|
||||
never: None,
|
||||
unless_trusted: None,
|
||||
granular: None,
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
let mut model = model_info_from_slug("unknown-model");
|
||||
model.model_messages = Some(messages.clone());
|
||||
|
||||
let updated = with_config_overrides(model, &config);
|
||||
|
||||
messages.instructions_template = Some(expected.to_string());
|
||||
assert_eq!(updated.model_messages, Some(messages));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn baked_personality_section_is_preserved_without_explicit_none() {
|
||||
let instructions = "Intro\n# Personality\nKeep me\n# General\nKeep me too";
|
||||
let configs = [
|
||||
config_with_personality(/*personality*/ None),
|
||||
config_with_personality(Some(Personality::Friendly)),
|
||||
config_with_personality(Some(Personality::Pragmatic)),
|
||||
];
|
||||
|
||||
for config in configs {
|
||||
let mut model = model_info_from_slug("unknown-model");
|
||||
model
|
||||
.model_messages
|
||||
.as_mut()
|
||||
.expect("fallback model messages")
|
||||
.instructions_template = Some(instructions.to_string());
|
||||
|
||||
assert_eq!(
|
||||
render_model_instructions(&with_config_overrides(model, &config)),
|
||||
instructions
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_empty_base_instructions_stay_empty_with_personality_none() {
|
||||
let mut model = model_info_from_slug("unknown-model");
|
||||
model
|
||||
.model_messages
|
||||
.as_mut()
|
||||
.expect("fallback model messages")
|
||||
.instructions_template = Some("Intro\n# Personality\nRemove me".to_string());
|
||||
let config = ModelsManagerConfig {
|
||||
base_instructions: Some(String::new()),
|
||||
personality: Some(Personality::None),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let updated = with_config_overrides(model, &config);
|
||||
|
||||
assert_eq!(
|
||||
updated
|
||||
.model_messages
|
||||
.as_ref()
|
||||
.and_then(|messages| messages.instructions_template.as_deref()),
|
||||
Some("")
|
||||
);
|
||||
assert_eq!(render_model_instructions(&updated), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_model_uses_builtin_instruction_template() {
|
||||
let model = model_info_from_slug("unknown-model");
|
||||
|
||||
assert_eq!(render_model_instructions(&model), BASE_INSTRUCTIONS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_context_window_override_clamps_to_max_context_window() {
|
||||
let mut model = model_info_from_slug("unknown-model");
|
||||
model.context_window = Some(273_000);
|
||||
model.max_context_window = Some(400_000);
|
||||
let config = ModelsManagerConfig {
|
||||
model_context_window: Some(500_000),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let updated = with_config_overrides(model.clone(), &config);
|
||||
let mut expected = model;
|
||||
expected.context_window = Some(400_000);
|
||||
|
||||
assert_eq!(updated, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_context_window_uses_model_value_without_override() {
|
||||
let mut model = model_info_from_slug("unknown-model");
|
||||
model.context_window = Some(273_000);
|
||||
model.max_context_window = Some(400_000);
|
||||
let config = ModelsManagerConfig::default();
|
||||
|
||||
let updated = with_config_overrides(model.clone(), &config);
|
||||
|
||||
assert_eq!(updated, model);
|
||||
}
|
||||
6
akode-rs/models-manager/src/model_presets.rs
Normal file
6
akode-rs/models-manager/src/model_presets.rs
Normal file
@@ -0,0 +1,6 @@
|
||||
/// Legacy notice keys kept for config compatibility with older migration prompts.
|
||||
///
|
||||
/// Hardcoded model presets were removed; model listings are now derived from the active catalog.
|
||||
pub const HIDE_GPT5_1_MIGRATION_PROMPT_CONFIG: &str = "hide_gpt5_1_migration_prompt";
|
||||
pub const HIDE_GPT_5_1_CODEX_MAX_MIGRATION_PROMPT_CONFIG: &str =
|
||||
"hide_gpt-5.1-codex-max_migration_prompt";
|
||||
33
akode-rs/models-manager/src/originator.rs
Normal file
33
akode-rs/models-manager/src/originator.rs
Normal file
@@ -0,0 +1,33 @@
|
||||
//! Bounded catalog partitions for callers migrated to CCA. Other callers keep the default catalog.
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
|
||||
pub enum ModelCatalogOriginator {
|
||||
Work,
|
||||
WorkWeb,
|
||||
WorkDesktop,
|
||||
WorkMobile,
|
||||
Chat,
|
||||
}
|
||||
|
||||
impl ModelCatalogOriginator {
|
||||
pub fn from_originator(originator: &str) -> Option<Self> {
|
||||
match originator {
|
||||
"codex_work_cca" => Some(Self::Work),
|
||||
"codex_work_web" => Some(Self::WorkWeb),
|
||||
"codex_work_desktop" => Some(Self::WorkDesktop),
|
||||
"codex_work_mobile" => Some(Self::WorkMobile),
|
||||
"chatgpt_cca" => Some(Self::Chat),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Work => "codex_work_cca",
|
||||
Self::WorkWeb => "codex_work_web",
|
||||
Self::WorkDesktop => "codex_work_desktop",
|
||||
Self::WorkMobile => "codex_work_mobile",
|
||||
Self::Chat => "chatgpt_cca",
|
||||
}
|
||||
}
|
||||
}
|
||||
40
akode-rs/models-manager/src/test_support.rs
Normal file
40
akode-rs/models-manager/src/test_support.rs
Normal file
@@ -0,0 +1,40 @@
|
||||
//! Test-only helpers exposed for dependent crate tests.
|
||||
//!
|
||||
//! Production code should not depend on this module.
|
||||
|
||||
use crate::CatalogModel;
|
||||
use crate::ModelOrigin;
|
||||
use crate::ModelsManagerConfig;
|
||||
use crate::bundled_models_response;
|
||||
use crate::manager::construct_model_info_from_candidates;
|
||||
use akode_protocol::openai_models::ModelInfo;
|
||||
use akode_protocol::openai_models::ModelPreset;
|
||||
|
||||
/// Get model identifier without consulting remote state or cache.
|
||||
pub fn get_model_offline_for_tests(model: Option<&str>) -> String {
|
||||
if let Some(model) = model {
|
||||
return model.to_string();
|
||||
}
|
||||
let mut response = bundled_models_response().unwrap_or_default();
|
||||
response.models.sort_by_key(|model| model.priority);
|
||||
let presets: Vec<ModelPreset> = response.models.into_iter().map(Into::into).collect();
|
||||
presets
|
||||
.iter()
|
||||
.find(|preset| preset.show_in_picker)
|
||||
.or_else(|| presets.first())
|
||||
.map(|preset| preset.model.clone())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Resolve metadata and its source without consulting remote state or cache.
|
||||
pub fn construct_model_info_offline_for_tests(
|
||||
model: &str,
|
||||
config: &ModelsManagerConfig,
|
||||
) -> CatalogModel {
|
||||
let candidates: &[ModelInfo] = if let Some(model_catalog) = config.model_catalog.as_ref() {
|
||||
&model_catalog.models
|
||||
} else {
|
||||
&[]
|
||||
};
|
||||
construct_model_info_from_candidates(model, candidates, ModelOrigin::ExplicitConfig, config)
|
||||
}
|
||||
Reference in New Issue
Block a user