diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..1c3debc --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +internal/tui/codexprompt/* -text diff --git a/internal/models/models.go b/internal/models/models.go index 8a77e7a..f1e4a19 100644 --- a/internal/models/models.go +++ b/internal/models/models.go @@ -74,10 +74,13 @@ var All = []Model{ Reasoning: true, }, { - ID: "qwen3.8-flash", - Kind: Chat, - Name: "Qwen 3.8 Flash", - Context: 262_144, + ID: "qwen3.8-flash", + Kind: Chat, + Name: "Qwen 3.8 Flash", + // Served at 1,048,576 since 2026-09-29 (nan.builders/docs/models). It + // said 262,144 here, the model's native window, so every tool compacted + // it at a quarter of what the API takes. + Context: 1_048_576, Output: 32_768, Inputs: []string{InputText, InputImage}, Reasoning: true, @@ -151,6 +154,13 @@ var Retired = []string{ "mimo-v2.5", // replaced by mimo-v2.6-flash on 2026-10 } +// StaleContexts are windows this CLI once wrote for a model and has since +// corrected. opencode keeps a `limit` that is already there, since it may be +// the member's own, but one that matches a figure we wrote is ours to fix. +var StaleContexts = map[string][]int{ + "qwen3.8-flash": {262_144}, +} + func IsRetired(id string) bool { for _, r := range Retired { if r == id { diff --git a/internal/tui/codex_catalog.go b/internal/tui/codex_catalog.go new file mode 100644 index 0000000..9f96a0f --- /dev/null +++ b/internal/tui/codex_catalog.go @@ -0,0 +1,98 @@ +package tui + +import ( + _ "embed" + "encoding/json" + "path/filepath" + + catalog "github.com/nxssie/nan-cli/internal/models" +) + +// Codex fills its /model picker from a catalogue of OpenAI's models, and the +// cluster's /v1/models answers in a shape Codex does not read as one. So a +// session on the nan provider offered only gpt-* models in /model, every one +// of which the cluster answers with a 401, and the only way to another NaN +// model was to quit and relaunch with another --profile. +// +// model_catalog_json replaces that catalogue. Pointed at this file from the +// nan-* profiles - and only from them, so the member's OpenAI sessions keep +// OpenAI's list - /model lists the cluster's chat models, each with the +// window it is served at, and the "Model metadata ... not found" warning goes +// away because now there is metadata. +// +// It cannot mix providers: model_provider is per session and a catalogue entry +// has no provider of its own. Going between gpt-* and NaN is still a relaunch. +const codexCatalogFile = "nan-models.json" + +// Every catalogue entry has to carry the agent's system prompt in full: Codex +// refuses an entry without one, and an empty one goes out as no prompt at all. +// This is the prompt Codex sends a model it has no metadata for - which is what +// every NaN model got before the catalogue existed - so the catalogue changes +// the picker and the windows and leaves what the model is told exactly as it +// was. It is openai/codex's +// codex-rs/protocol/src/prompts/base_instructions/default.md at rust-v0.162.1 +// with the "Planning" and "`update_plan`" sections taken out, the way Codex +// itself takes them out when that tool is not offered; compared byte for byte +// against a request Codex 0.162.1 sent. Apache-2.0, see codexprompt/LICENSE +// and codexprompt/NOTICE. +// +//go:embed codexprompt/base_instructions.md +var codexBaseInstructions string + +type codexCatalogEntry struct { + Slug string `json:"slug"` + DisplayName string `json:"display_name"` + Description string `json:"description"` + SupportedReasoningLevels []any `json:"supported_reasoning_levels"` + ShellType string `json:"shell_type"` + Visibility string `json:"visibility"` + SupportedInAPI bool `json:"supported_in_api"` + Priority int `json:"priority"` + SupportVerbosity bool `json:"support_verbosity"` + TruncationPolicy map[string]any `json:"truncation_policy"` + ExperimentalSupportedTools []string `json:"experimental_supported_tools"` + BaseInstructions string `json:"base_instructions"` + ContextWindow int `json:"context_window"` + MaxContextWindow int `json:"max_context_window"` + InputModalities []string `json:"input_modalities"` + // Left to its default, an entry adds an "Apps (Connectors)" block to the + // prompt that a model without metadata never got. + IncludeAppsUsageInstructions bool `json:"include_apps_usage_instructions"` +} + +func codexCatalog() ([]byte, error) { + models := catalog.ChatModels() + entries := make([]codexCatalogEntry, 0, len(models)) + for i, m := range models { + entries = append(entries, codexCatalogEntry{ + Slug: m.ID, + // No " (NaN)" as droid has: in a session on the nan provider + // every model in the picker is one. + DisplayName: m.Name, + Description: "Served by the NaN cluster.", + // What a model without metadata gets, so the request is the one + // Codex was already sending. + SupportedReasoningLevels: []any{}, + ShellType: "unified_exec", + Visibility: "list", + SupportedInAPI: true, + Priority: i + 1, + TruncationPolicy: map[string]any{"mode": "tokens", "limit": 10000}, + ExperimentalSupportedTools: []string{}, + BaseInstructions: codexBaseInstructions, + ContextWindow: m.Context, + MaxContextWindow: m.Context, + // Codex takes text and image here and nothing else; audio and + // video are not modalities it can send. + InputModalities: piInputs(m), + }) + } + return json.MarshalIndent(map[string]any{"models": entries}, "", " ") +} + +// Forward slashes, because the path goes into a TOML basic string in the +// profiles and a Windows backslash there is an escape. Codex resolves +// C:/Users/... the same as C:\Users\.... +func codexCatalogPath(codexHome string) string { + return filepath.ToSlash(filepath.Join(codexHome, codexCatalogFile)) +} diff --git a/internal/tui/codexprompt/LICENSE b/internal/tui/codexprompt/LICENSE new file mode 100644 index 0000000..4606e72 --- /dev/null +++ b/internal/tui/codexprompt/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright 2025 OpenAI + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/internal/tui/codexprompt/NOTICE b/internal/tui/codexprompt/NOTICE new file mode 100644 index 0000000..2805899 --- /dev/null +++ b/internal/tui/codexprompt/NOTICE @@ -0,0 +1,6 @@ +OpenAI Codex +Copyright 2025 OpenAI + +This project includes code derived from [Ratatui](https://github.com/ratatui/ratatui), licensed under the MIT license. +Copyright (c) 2016-2022 Florian Dehau +Copyright (c) 2023-2025 The Ratatui Developers diff --git a/internal/tui/codexprompt/base_instructions.md b/internal/tui/codexprompt/base_instructions.md new file mode 100644 index 0000000..9c4c00f --- /dev/null +++ b/internal/tui/codexprompt/base_instructions.md @@ -0,0 +1,195 @@ +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.” + +## 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. + diff --git a/internal/tui/config_test.go b/internal/tui/config_test.go index 3ff5c76..0f56b83 100644 --- a/internal/tui/config_test.go +++ b/internal/tui/config_test.go @@ -2564,3 +2564,133 @@ func TestARefusedKeyOpensTheFieldAgain(t *testing.T) { t.Errorf("the refusal is gone: %q", after.keyCheck) } } + +func TestCodexProfilesPointAtACatalogOfTheClustersModels(t *testing.T) { + path := tempConfig(t, "config.toml") + if err := writeCodexConfig(path, testKey); err != nil { + t.Fatal(err) + } + home := filepath.Dir(path) + + var cat struct { + Models []map[string]any `json:"models"` + } + data, err := os.ReadFile(filepath.Join(home, codexCatalogFile)) + if err != nil { + t.Fatalf("no catalogue, so /model offers only gpt-* models the cluster answers with a 401: %v", err) + } + if err := json.Unmarshal(data, &cat); err != nil { + t.Fatal(err) + } + bySlug := map[string]map[string]any{} + for _, e := range cat.Models { + bySlug[e["slug"].(string)] = e + } + for _, m := range catalog.ChatModels() { + e, ok := bySlug[m.ID] + if !ok { + t.Errorf("%s is not in the catalogue, so /model cannot reach it", m.ID) + continue + } + if got := int(e["context_window"].(float64)); got != m.Context { + t.Errorf("%s: context_window %d, want %d", m.ID, got, m.Context) + } + if e["base_instructions"] != codexBaseInstructions { + t.Errorf("%s: the entry does not carry Codex's own prompt", m.ID) + } + // Codex refuses the whole file over a field it cannot parse, so the + // modalities it does not know must not get in. + for _, in := range e["input_modalities"].([]any) { + if in != "text" && in != "image" { + t.Errorf("%s: input_modalities has %q", m.ID, in) + } + } + + body := readFile(t, filepath.Join(home, codexProfileName(m.ID)+".config.toml")) + want := fmt.Sprintf("model_catalog_json = %q", codexCatalogPath(home)) + at := strings.Index(body, want) + if at < 0 { + t.Errorf("%s: the profile does not point at the catalogue:\n%s", m.ID, body) + continue + } + // A key under [features] belongs to that table and Codex would not + // read it as the catalogue. + if features := strings.Index(body, "[features]"); features >= 0 && at > features { + t.Errorf("%s: model_catalog_json landed inside [features]:\n%s", m.ID, body) + } + if strings.Contains(want, `\`) { + t.Errorf("%s: a backslash in a TOML basic string is an escape: %s", m.ID, want) + } + } + // Only the profiles point at it. In config.toml it would take OpenAI's + // models out of the member's own sessions. + if strings.Contains(readFile(t, path), "model_catalog_json") { + t.Error("config.toml points at the catalogue, so OpenAI sessions lose their models") + } +} + +// What a NaN model is told must not change because a picker appeared: the +// prompt is the one Codex sends a model it has no metadata for. +func TestCodexCatalogPromptIsTheOneCodexAlreadySent(t *testing.T) { + if !strings.HasPrefix(codexBaseInstructions, "You are a coding agent running in the Codex CLI") { + t.Errorf("not Codex's default prompt: %.80q", codexBaseInstructions) + } + // Codex drops these when update_plan is not offered, and it is not. + for _, section := range []string{"## Planning", "## `update_plan`"} { + if strings.Contains(codexBaseInstructions, section) { + t.Errorf("the prompt still has %q, which Codex leaves out", section) + } + } + // A checkout that turned the file to CRLF would change every byte of the + // prompt on that machine's builds. + if strings.Contains(codexBaseInstructions, "\r") { + t.Error("the embedded prompt has carriage returns") + } +} + +func TestCodexRemovalTakesTheCatalog(t *testing.T) { + path := tempConfig(t, "config.toml") + if err := writeCodexConfig(path, testKey); err != nil { + t.Fatal(err) + } + if err := removeCodexConfig(path); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(filepath.Join(filepath.Dir(path), codexCatalogFile)); !os.IsNotExist(err) { + t.Error("the catalogue outlived the disconnect") + } +} + +// qwen3.8-flash went out at 262,144 when it is served at 1,048,576. An +// existing opencode entry with that exact figure is one this CLI wrote. +func TestOpencodeConfigCorrectsAWindowWeGotWrong(t *testing.T) { + path := tempConfig(t, "opencode.json") + old := `{ + "provider": { + "nan": { + "npm": "@ai-sdk/openai-compatible", + "options": { "baseURL": "https://api.nan.builders/v1", "apiKey": "sk-old" }, + "models": { + "qwen3.8-flash": { "name": "Qwen 3.8 Flash", "limit": { "context": 262144, "output": 32768 } }, + "gemma4": { "name": "Gemma 4", "limit": { "context": 100000, "output": 65536 } } + } + } + } + }` + if err := os.WriteFile(path, []byte(old), 0o600); err != nil { + t.Fatal(err) + } + if err := writeOpencodeConfig(path, testKey); err != nil { + t.Fatal(err) + } + models := readJSON(t, path)["provider"].(map[string]any)["nan"].(map[string]any)["models"].(map[string]any) + limit := func(id string) int { + return int(models[id].(map[string]any)["limit"].(map[string]any)["context"].(float64)) + } + if got := limit("qwen3.8-flash"); got != 1_048_576 { + t.Errorf("qwen3.8-flash context %d, still compacting at a quarter of the window", got) + } + if got := limit("gemma4"); got != 100_000 { + t.Errorf("gemma4 context %d, a window the member set was overwritten", got) + } +} diff --git a/internal/tui/tui.go b/internal/tui/tui.go index 664a2ce..4f6f428 100644 --- a/internal/tui/tui.go +++ b/internal/tui/tui.go @@ -2419,6 +2419,16 @@ func writeOpencodeConfig(cfgPath, apiKey string) error { changed = true } } + if limit, ok := found["limit"].(map[string]any); ok { + if ctx, ok := limit["context"].(float64); ok { + for _, stale := range catalog.StaleContexts[id] { + if int(ctx) == stale { + limit["context"] = m.(map[string]any)["limit"].(map[string]any)["context"] + changed = true + } + } + } + } } if !changed { return nil @@ -2712,16 +2722,24 @@ func writeCodexProfiles(codexHome string) error { if err := removeCodexProfiles(codexHome); err != nil { return err } + models, err := codexCatalog() + if err != nil { + return err + } + if err := writeConfigFile(filepath.Join(codexHome, codexCatalogFile), models); err != nil { + return err + } for _, m := range catalog.ChatModels() { body := fmt.Sprintf(`# Written by the NaN CLI. Disconnecting Codex removes it. model = %q model_provider = "nan" model_context_window = %d +model_catalog_json = %q web_search = "disabled" [features] multi_agent = false -`, m.ID, m.Context) +`, m.ID, m.Context, codexCatalogPath(codexHome)) path := filepath.Join(codexHome, codexProfileName(m.ID)+".config.toml") if err := writeConfigFile(path, []byte(body)); err != nil { return err @@ -2739,7 +2757,8 @@ func codexProfileName(id string) string { return "nan-" + strings.ReplaceAll(id, ".", "") } -// Takes back only the files this CLI wrote, by the prefix it wrote them under. +// Takes back only the files this CLI wrote: the profiles, by the prefix it +// wrote them under, and the catalogue they point at. func removeCodexProfiles(codexHome string) error { entries, err := os.ReadDir(codexHome) if err != nil { @@ -2747,7 +2766,8 @@ func removeCodexProfiles(codexHome string) error { } for _, e := range entries { name := e.Name() - if !e.IsDir() && strings.HasPrefix(name, "nan-") && strings.HasSuffix(name, ".config.toml") { + ours := strings.HasPrefix(name, "nan-") && strings.HasSuffix(name, ".config.toml") + if !e.IsDir() && (ours || name == codexCatalogFile) { if err := os.Remove(filepath.Join(codexHome, name)); err != nil && !os.IsNotExist(err) { return err } @@ -3641,7 +3661,7 @@ func (m model) renderSetup(l layout) string { // ── about renderer ─────────────────────────────────────────────────────────── -const Version = "0.1.30" +const Version = "0.1.31" func renderAbout(l layout) string { var b strings.Builder