Fix agent workspace isolation and Hermes one-shot resume (#7103)
* Fix coding agent workspace and resume handling * Handle attached Hermes flags and OpenClaw paths * Add Codex model metadata catalog * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Fix Codex reasoning summary metadata * Preserve Hermes hook approval on resumed one-shots --------- Co-authored-by: Lee Jackson <130007945+Imagineer99@users.noreply.github.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
This commit is contained in:
parent
815f242970
commit
1bf3509fea
4 changed files with 686 additions and 13 deletions
|
|
@ -42,6 +42,7 @@ version = {attr = "unsloth.models._utils.__version__"}
|
|||
include-package-data = true
|
||||
|
||||
[tool.setuptools.package-data]
|
||||
unsloth_cli = ["codex_fallback_prompt.md"]
|
||||
studio = [
|
||||
"*.sh",
|
||||
"*.ps1",
|
||||
|
|
|
|||
275
unsloth_cli/codex_fallback_prompt.md
Normal file
275
unsloth_cli/codex_fallback_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`.
|
||||
|
|
@ -170,6 +170,43 @@ def _hermes_install_hint() -> str:
|
|||
return _HERMES_WINDOWS_INSTALL_HINT if os.name == "nt" else _HERMES_POSIX_INSTALL_HINT
|
||||
|
||||
|
||||
def _hermes_resume_oneshot_args(args: list[str]) -> list[str]:
|
||||
"""Route resumed one-shot prompts through Hermes' session-aware chat command."""
|
||||
has_resume = any(
|
||||
arg in ("--resume", "-r", "--continue", "-c")
|
||||
or arg.startswith(("--resume=", "--continue="))
|
||||
or (len(arg) > 2 and arg.startswith(("-r", "-c")))
|
||||
for arg in args
|
||||
)
|
||||
if not has_resume:
|
||||
return args
|
||||
|
||||
rewritten = list(args)
|
||||
for index, arg in enumerate(rewritten):
|
||||
if arg in ("-z", "--oneshot"):
|
||||
rewritten[index] = "-q"
|
||||
elif len(arg) > 2 and arg.startswith("-z"):
|
||||
# argparse accepts attached short-option values (`-zPROMPT` and
|
||||
# `-z=PROMPT`); preserve the value byte-for-byte when switching to -q.
|
||||
rewritten[index] = f"-q{arg[2:]}"
|
||||
elif arg.startswith("--oneshot="):
|
||||
rewritten[index] = f"--query={arg.partition('=')[2]}"
|
||||
else:
|
||||
continue
|
||||
if any(item == "--usage-file" or item.startswith("--usage-file=") for item in args):
|
||||
raise typer.BadParameter(
|
||||
"Hermes cannot resume a one-shot session with --usage-file; remove that option."
|
||||
)
|
||||
prefix = ["chat", "-Q"]
|
||||
if "--yolo" not in rewritten:
|
||||
prefix.append("--yolo")
|
||||
if "--accept-hooks" not in rewritten:
|
||||
prefix.append("--accept-hooks")
|
||||
rewritten = prefix + rewritten
|
||||
return rewritten
|
||||
return args
|
||||
|
||||
|
||||
class LoadOptions(NamedTuple):
|
||||
"""Model-load knobs forwarded to /api/inference/load when --model triggers a load."""
|
||||
|
||||
|
|
@ -840,6 +877,60 @@ def _merge_codex_config(existing: str, base: str) -> str:
|
|||
)
|
||||
|
||||
|
||||
# Keep custom-model behavior aligned with Codex's own unknown-model fallback. This
|
||||
# Apache-2.0 prompt is copied from openai/codex rust-v0.144.0 models-manager/prompt.md.
|
||||
_CODEX_FALLBACK_PROMPT = Path(__file__).parent.parent / "codex_fallback_prompt.md"
|
||||
_CODEX_MODEL_CATALOG_MIN_VERSION = (0, 110, 0)
|
||||
|
||||
|
||||
def _codex_supports_model_catalog() -> bool:
|
||||
executable = shutil.which("codex")
|
||||
if executable is None:
|
||||
# A --no-launch recipe may be copied to another machine; assume a current Codex.
|
||||
return True
|
||||
try:
|
||||
output = subprocess.check_output(
|
||||
[executable, "--version"], text = True, timeout = 10, stderr = subprocess.DEVNULL
|
||||
)
|
||||
except Exception:
|
||||
return False
|
||||
match = re.search(r"(\d+)\.(\d+)\.(\d+)", output)
|
||||
return bool(match) and tuple(int(part) for part in match.groups()) >= (
|
||||
_CODEX_MODEL_CATALOG_MIN_VERSION
|
||||
)
|
||||
|
||||
|
||||
def _codex_model_catalog(model: dict) -> dict:
|
||||
"""Return conservative metadata for a Studio model unknown to Codex's built-in catalog."""
|
||||
model_id = model["id"]
|
||||
window = model.get("context_length") or model.get("max_context_length")
|
||||
entry = {
|
||||
"slug": model_id,
|
||||
"display_name": model_id,
|
||||
"description": "Model served by Unsloth Studio",
|
||||
"supported_reasoning_levels": [],
|
||||
"shell_type": "default",
|
||||
"visibility": "none",
|
||||
"supported_in_api": True,
|
||||
"priority": 99,
|
||||
"availability_nux": None,
|
||||
"upgrade": None,
|
||||
"base_instructions": _CODEX_FALLBACK_PROMPT.read_text(encoding = "utf-8"),
|
||||
"supports_reasoning_summaries": False,
|
||||
"supports_reasoning_summary_parameter": False,
|
||||
"support_verbosity": False,
|
||||
"default_verbosity": None,
|
||||
"apply_patch_tool_type": None,
|
||||
"truncation_policy": {"mode": "bytes", "limit": 10_000},
|
||||
"supports_parallel_tool_calls": False,
|
||||
"experimental_supported_tools": [],
|
||||
}
|
||||
if window:
|
||||
entry["context_window"] = int(window)
|
||||
entry["max_context_window"] = int(window)
|
||||
return {"models": [entry]}
|
||||
|
||||
|
||||
def write_codex_config(base: str, model: dict, home: Path) -> None:
|
||||
home.mkdir(parents = True, exist_ok = True)
|
||||
|
||||
|
|
@ -857,6 +948,16 @@ def write_codex_config(base: str, model: dict, home: Path) -> None:
|
|||
f'model_provider = "{_CODEX_PROFILE}"\n'
|
||||
f"model = {json.dumps(model['id'])}\n"
|
||||
)
|
||||
if _codex_supports_model_catalog() and _CODEX_FALLBACK_PROMPT.is_file():
|
||||
catalog = home / "model-catalog.json"
|
||||
catalog_text = json.dumps(_codex_model_catalog(model), indent = 2) + "\n"
|
||||
if not catalog.exists() or catalog.read_text(encoding = "utf-8") != catalog_text:
|
||||
catalog.write_text(catalog_text, encoding = "utf-8")
|
||||
typer.echo(f"Updated {catalog}")
|
||||
# Resolve relative to the profile file. This also survives WSL launching a Windows
|
||||
# Codex binary, where a Linux absolute path inside TOML would not be usable.
|
||||
profile_text += f"model_catalog_json = {json.dumps(catalog.name)}\n"
|
||||
|
||||
window = model.get("context_length") or model.get("max_context_length")
|
||||
if window:
|
||||
profile_text += f"model_context_window = {int(window)}\n"
|
||||
|
|
@ -875,6 +976,16 @@ def _wsl_windows_executable(command: list) -> Optional[str]:
|
|||
return None
|
||||
|
||||
|
||||
def _wsl_windows_path(path: Path) -> str:
|
||||
try:
|
||||
translated = subprocess.check_output(["wslpath", "-w", str(path)], text = True).strip()
|
||||
except (OSError, subprocess.CalledProcessError) as exc:
|
||||
_fail(f"Could not translate WSL path {path}: {exc}")
|
||||
if not translated:
|
||||
_fail(f"Could not translate WSL path {path}")
|
||||
return translated
|
||||
|
||||
|
||||
def _looks_like_path(value: str) -> bool:
|
||||
# A var only wants the WSLENV /p flag if its value is a filesystem path: an
|
||||
# absolute POSIX path (/...), a UNC path (\\...), or a drive-qualified Windows
|
||||
|
|
@ -1184,6 +1295,7 @@ def write_openclaw_config(
|
|||
model: dict,
|
||||
path: Path,
|
||||
yolo: bool = False,
|
||||
workspace_path: Optional[str] = None,
|
||||
) -> None:
|
||||
config = _read_json_object(path)
|
||||
if config is None:
|
||||
|
|
@ -1208,8 +1320,23 @@ def write_openclaw_config(
|
|||
"models": [provider_model],
|
||||
}
|
||||
# Pin a default model, else OpenClaw drops into its setup agent ("no models available").
|
||||
defaults = _subdict(_subdict(config, "agents"), "defaults")
|
||||
agents = _subdict(config, "agents")
|
||||
defaults = _subdict(agents, "defaults")
|
||||
_subdict(defaults, "model")["primary"] = f"unsloth/{model['id']}"
|
||||
# OPENCLAW_STATE_DIR does not relocate the workspace. Keep it beside the managed
|
||||
# config so ephemeral launches avoid ~/.openclaw and persisted sessions retain it.
|
||||
workspace = path.parent / "workspace"
|
||||
workspace.mkdir(parents = True, exist_ok = True, mode = 0o700)
|
||||
defaults["workspace"] = workspace_path or str(workspace)
|
||||
# Per-agent paths override agents.defaults.workspace and OPENCLAW_STATE_DIR. This
|
||||
# config is itself an isolated Unsloth copy, so remove stale explicit paths and let
|
||||
# OpenClaw resolve every listed agent beneath the managed defaults/state directory.
|
||||
agent_list = agents.get("list")
|
||||
if isinstance(agent_list, list):
|
||||
for agent_config in agent_list:
|
||||
if isinstance(agent_config, dict):
|
||||
agent_config.pop("workspace", None)
|
||||
agent_config.pop("agentDir", None)
|
||||
# Unauthenticated loopback gateway: without auth.mode=none the client won't open
|
||||
# the websocket. The daemon must still be started separately (`openclaw gateway`).
|
||||
gateway = _subdict(config, "gateway")
|
||||
|
|
@ -1339,9 +1466,11 @@ def write_opencode_config(
|
|||
tools = ("edit", "bash", "webfetch")
|
||||
if yolo:
|
||||
# OpenCode has no --yolo flag; auto-approve is the config `permission` block
|
||||
# (singular). Allow the prompting tools so tool calls don't block on the TUI. This
|
||||
# rides inline (OPENCODE_CONFIG_CONTENT) so --yolo works even over a project config.
|
||||
# (singular). Allow the prompting tools and paths outside the launch directory so
|
||||
# tool calls don't block on the TUI. This rides inline (OPENCODE_CONFIG_CONTENT) so
|
||||
# --yolo works even over a project config.
|
||||
session_permission = {t: "allow" for t in tools}
|
||||
session_permission["external_directory"] = {"*": "allow"}
|
||||
config["permission"] = dict(session_permission)
|
||||
else:
|
||||
# Undo only what --yolo wrote: our yolo sets an explicit per-tool "allow" for these
|
||||
|
|
@ -1358,6 +1487,8 @@ def write_opencode_config(
|
|||
for tool in tools:
|
||||
if permission.get(tool) == "allow":
|
||||
permission[tool] = "ask"
|
||||
if permission.get("external_directory") == {"*": "allow"}:
|
||||
permission["external_directory"] = {"*": "ask"}
|
||||
if json.dumps(config, sort_keys = True) != before:
|
||||
_write_private_json(path, config)
|
||||
typer.echo(f"Updated {path}")
|
||||
|
|
@ -1629,8 +1760,18 @@ def openclaw(
|
|||
)
|
||||
with _session_config("openclaw", launch, persist = persist) as cfg:
|
||||
config_path = cfg / "openclaw.json"
|
||||
workspace_path = None
|
||||
if _wsl_windows_executable(command):
|
||||
workspace_path = _wsl_windows_path(cfg / "workspace")
|
||||
# key lives in the config, not the env; --yolo writes the exec policy here too.
|
||||
write_openclaw_config(base, key, entry, config_path, yolo = yolo)
|
||||
write_openclaw_config(
|
||||
base,
|
||||
key,
|
||||
entry,
|
||||
config_path,
|
||||
yolo = yolo,
|
||||
workspace_path = workspace_path,
|
||||
)
|
||||
# Scope both config and state so OpenClaw never touches the user's ~/.openclaw.
|
||||
env = {"OPENCLAW_CONFIG_PATH": str(config_path), "OPENCLAW_STATE_DIR": str(cfg)}
|
||||
_run(base, entry, env, command, launch = launch, install_hint = install_hint)
|
||||
|
|
@ -1729,6 +1870,8 @@ def hermes(
|
|||
persist: bool = _PERSIST_OPTION,
|
||||
):
|
||||
"""Point Hermes (Nous Research) at the running Studio server and start it."""
|
||||
native_args = [*_yolo_command_flags("hermes", yolo), *ctx.args]
|
||||
command = ["hermes", *_hermes_resume_oneshot_args(native_args)]
|
||||
base, key, entry = _connect(
|
||||
api_key,
|
||||
model,
|
||||
|
|
@ -1736,7 +1879,6 @@ def hermes(
|
|||
serve = serve,
|
||||
launch = launch,
|
||||
)
|
||||
command = ["hermes", *_yolo_command_flags("hermes", yolo), *ctx.args]
|
||||
install_hint = _hermes_install_hint()
|
||||
with _session_config("hermes", launch, persist = persist) as home:
|
||||
# HERMES_HOME relocates hermes' whole home dir (config.yaml, sessions, state)
|
||||
|
|
|
|||
|
|
@ -294,17 +294,58 @@ def test_merge_codex_config_keeps_user_oss_provider():
|
|||
assert _parse_toml(merged)["oss_provider"] == "ollama"
|
||||
|
||||
|
||||
def test_write_codex_config_profile(tmp_path):
|
||||
def test_write_codex_config_profile(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(start, "_codex_supports_model_catalog", lambda: True)
|
||||
start.write_codex_config(BASE, MODEL, tmp_path)
|
||||
profile = _parse_toml((tmp_path / "unsloth_api.config.toml").read_text())
|
||||
assert profile["oss_provider"] == "unsloth_api"
|
||||
assert profile["model_provider"] == "unsloth_api"
|
||||
assert profile["model"] == MODEL["id"]
|
||||
assert profile["model_context_window"] == 131072
|
||||
|
||||
catalog_path = Path(profile["model_catalog_json"])
|
||||
assert catalog_path == Path("model-catalog.json")
|
||||
catalog = json.loads((tmp_path / catalog_path).read_text())
|
||||
assert catalog["models"][0]["slug"] == MODEL["id"]
|
||||
assert catalog["models"][0]["context_window"] == 131072
|
||||
assert catalog["models"][0]["max_context_window"] == 131072
|
||||
assert catalog["models"][0]["supports_reasoning_summary_parameter"] is False
|
||||
assert catalog["models"][0]["supports_parallel_tool_calls"] is False
|
||||
|
||||
assert catalog["models"][0]["base_instructions"] == start._CODEX_FALLBACK_PROMPT.read_text()
|
||||
config = _parse_toml((tmp_path / "config.toml").read_text())
|
||||
assert config["model_providers"]["unsloth_api"]["env_key"] == "UNSLOTH_STUDIO_AUTH_TOKEN"
|
||||
|
||||
|
||||
def test_write_codex_config_catalog_without_context_length(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(start, "_codex_supports_model_catalog", lambda: True)
|
||||
start.write_codex_config(BASE, {"id": "unsloth/no-window"}, tmp_path)
|
||||
profile = _parse_toml((tmp_path / "unsloth_api.config.toml").read_text())
|
||||
catalog = json.loads((tmp_path / profile["model_catalog_json"]).read_text())
|
||||
entry = catalog["models"][0]
|
||||
assert entry["slug"] == "unsloth/no-window"
|
||||
assert "context_window" not in entry
|
||||
assert "max_context_window" not in entry
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("version", "expected"),
|
||||
[("codex-cli 0.109.0", False), ("codex-cli 0.110.0", True), ("codex-cli 0.144.4", True)],
|
||||
)
|
||||
def test_codex_model_catalog_version_gate(monkeypatch, version, expected):
|
||||
monkeypatch.setattr(start.shutil, "which", lambda _: "/usr/local/bin/codex")
|
||||
monkeypatch.setattr(start.subprocess, "check_output", lambda *args, **kwargs: version)
|
||||
assert start._codex_supports_model_catalog() is expected
|
||||
|
||||
|
||||
def test_write_codex_config_omits_catalog_for_old_codex(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(start, "_codex_supports_model_catalog", lambda: False)
|
||||
start.write_codex_config(BASE, MODEL, tmp_path)
|
||||
profile = _parse_toml((tmp_path / "unsloth_api.config.toml").read_text())
|
||||
assert "model_catalog_json" not in profile
|
||||
assert not (tmp_path / "model-catalog.json").exists()
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def fake_studio(tmp_path, monkeypatch):
|
||||
calls = []
|
||||
|
|
@ -742,7 +783,12 @@ def test_opencode_inline_config_beats_project_config(fake_studio):
|
|||
assert result.exit_code == 0, result.output
|
||||
inline = _opencode_inline_config(result.output)
|
||||
assert inline["model"] == f"{start._OPENCODE_PROVIDER}/{MODEL['id']}"
|
||||
assert inline["permission"] == {"edit": "allow", "bash": "allow", "webfetch": "allow"}
|
||||
assert inline["permission"] == {
|
||||
"edit": "allow",
|
||||
"bash": "allow",
|
||||
"webfetch": "allow",
|
||||
"external_directory": {"*": "allow"},
|
||||
}
|
||||
assert "sk-unsloth" not in result.output # key stays in the private file, not the env
|
||||
|
||||
|
||||
|
|
@ -1611,12 +1657,50 @@ def test_write_openclaw_config_fresh(tmp_path):
|
|||
]
|
||||
# The default model must be pinned or OpenClaw has nothing active.
|
||||
assert config["agents"]["defaults"]["model"]["primary"] == f"unsloth/{MODEL['id']}"
|
||||
assert config["agents"]["defaults"]["workspace"] == str(tmp_path / "workspace")
|
||||
assert (tmp_path / "workspace").is_dir()
|
||||
assert config["gateway"]["mode"] == "local"
|
||||
assert config["gateway"]["auth"]["mode"] == "none" # unauth loopback gateway
|
||||
if os.name != "nt": # the file holds an API key
|
||||
assert path.stat().st_mode & 0o777 == 0o600
|
||||
|
||||
|
||||
def test_write_openclaw_config_clears_per_agent_path_overrides(tmp_path):
|
||||
path = tmp_path / "openclaw.json"
|
||||
path.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"agents": {
|
||||
"defaults": {"workspace": "/old/default"},
|
||||
"list": [
|
||||
{
|
||||
"id": "main",
|
||||
"default": True,
|
||||
"workspace": "/old/main-workspace",
|
||||
"agentDir": "/old/main-agent",
|
||||
"model": "keep/me",
|
||||
},
|
||||
{
|
||||
"id": "reviewer",
|
||||
"workspace": "/old/reviewer-workspace",
|
||||
"agentDir": "/old/reviewer-agent",
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
)
|
||||
)
|
||||
|
||||
start.write_openclaw_config(BASE, "sk-unsloth-abc", MODEL, path)
|
||||
|
||||
agents = json.loads(path.read_text())["agents"]
|
||||
assert agents["defaults"]["workspace"] == str(tmp_path / "workspace")
|
||||
assert agents["list"] == [
|
||||
{"id": "main", "default": True, "model": "keep/me"},
|
||||
{"id": "reviewer"},
|
||||
]
|
||||
|
||||
|
||||
def test_write_openclaw_config_preserves_and_idempotent(tmp_path):
|
||||
path = tmp_path / "openclaw.json"
|
||||
path.write_text(
|
||||
|
|
@ -1660,11 +1744,32 @@ def test_connect_openclaw_no_launch(fake_studio, tmp_path):
|
|||
config = json.loads(config_path.read_text())
|
||||
assert config["models"]["providers"]["unsloth"]["apiKey"] == "sk-unsloth-feedfacefeedface"
|
||||
assert config["agents"]["defaults"]["model"]["primary"] == f"unsloth/{MODEL['id']}"
|
||||
assert config["agents"]["defaults"]["workspace"] == str(
|
||||
tmp_path / "agents" / "openclaw" / "workspace"
|
||||
)
|
||||
assert _launch_command(result.output) == ["openclaw", "tui", "--local"]
|
||||
# OpenAI /v1/chat/completions works on either backend — no GGUF gate.
|
||||
assert not any(c[1].endswith("/api/inference/status") for c in fake_studio)
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name == "nt", reason = "WSL scenario")
|
||||
def test_connect_openclaw_wsl_windows_shim_translates_workspace(fake_studio, tmp_path, monkeypatch):
|
||||
windows_workspace = r"\\wsl.localhost\Ubuntu\tmp\openclaw\workspace"
|
||||
monkeypatch.setenv("WSL_DISTRO_NAME", "Ubuntu")
|
||||
monkeypatch.setattr(
|
||||
start.shutil, "which", lambda _: "/mnt/c/Users/x/AppData/Roaming/npm/openclaw"
|
||||
)
|
||||
monkeypatch.setattr(start.subprocess, "check_output", lambda *args, **kwargs: windows_workspace)
|
||||
|
||||
result = CliRunner().invoke(start.start_app, ["openclaw", "--no-launch"])
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
config_path = tmp_path / "agents" / "openclaw" / "openclaw.json"
|
||||
config = json.loads(config_path.read_text())
|
||||
assert config["agents"]["defaults"]["workspace"] == windows_workspace
|
||||
assert (config_path.parent / "workspace").is_dir()
|
||||
|
||||
|
||||
def test_connect_openclaw_no_launch_keeps_explicit_subcommand(fake_studio):
|
||||
result = CliRunner().invoke(start.start_app, ["openclaw", "--no-launch", "crestodian"])
|
||||
assert result.exit_code == 0, result.output
|
||||
|
|
@ -2090,7 +2195,12 @@ def test_yolo_opencode_writes_permission_block(fake_studio, tmp_path):
|
|||
result = CliRunner().invoke(start.start_app, ["opencode", "--yolo", "--no-launch"])
|
||||
assert result.exit_code == 0, result.output
|
||||
config = json.loads((tmp_path / "agents" / "opencode" / "opencode.json").read_text())
|
||||
assert config["permission"] == {"edit": "allow", "bash": "allow", "webfetch": "allow"}
|
||||
assert config["permission"] == {
|
||||
"edit": "allow",
|
||||
"bash": "allow",
|
||||
"webfetch": "allow",
|
||||
"external_directory": {"*": "allow"},
|
||||
}
|
||||
|
||||
|
||||
def test_no_yolo_opencode_has_no_permission_block(fake_studio, tmp_path):
|
||||
|
|
@ -2112,6 +2222,7 @@ def test_no_yolo_opencode_flips_prior_yolo_allow_to_ask(fake_studio, tmp_path):
|
|||
"edit": "allow",
|
||||
"bash": "allow",
|
||||
"webfetch": "allow",
|
||||
"external_directory": {"*": "allow"},
|
||||
}
|
||||
plain = CliRunner().invoke(start.start_app, ["opencode", "--no-launch"])
|
||||
assert plain.exit_code == 0, plain.output
|
||||
|
|
@ -2119,6 +2230,7 @@ def test_no_yolo_opencode_flips_prior_yolo_allow_to_ask(fake_studio, tmp_path):
|
|||
"edit": "ask",
|
||||
"bash": "ask",
|
||||
"webfetch": "ask",
|
||||
"external_directory": {"*": "ask"},
|
||||
}
|
||||
|
||||
|
||||
|
|
@ -2152,7 +2264,12 @@ def test_write_opencode_config_yolo_unit(tmp_path):
|
|||
path = tmp_path / "opencode.json"
|
||||
start.write_opencode_config(BASE, "sk-unsloth-abc", MODEL, path, yolo = True)
|
||||
config = json.loads(path.read_text())
|
||||
assert config["permission"] == {"edit": "allow", "bash": "allow", "webfetch": "allow"}
|
||||
assert config["permission"] == {
|
||||
"edit": "allow",
|
||||
"bash": "allow",
|
||||
"webfetch": "allow",
|
||||
"external_directory": {"*": "allow"},
|
||||
}
|
||||
|
||||
|
||||
def test_write_openclaw_config_yolo_unit(tmp_path):
|
||||
|
|
@ -2180,7 +2297,12 @@ def test_no_launch_rerun_clears_stale_opencode_yolo_permissions(fake_studio, tmp
|
|||
config = json.loads(config_path.read_text())
|
||||
# The yolo allow policy is replaced by a prompting one, not deleted (which would
|
||||
# revert to OpenCode's permissive "allow" default).
|
||||
assert config["permission"] == {"edit": "ask", "bash": "ask", "webfetch": "ask"}
|
||||
assert config["permission"] == {
|
||||
"edit": "ask",
|
||||
"bash": "ask",
|
||||
"webfetch": "ask",
|
||||
"external_directory": {"*": "ask"},
|
||||
}
|
||||
# The session provider survives the cleanup.
|
||||
assert start._OPENCODE_PROVIDER in config["provider"]
|
||||
|
||||
|
|
@ -2218,7 +2340,12 @@ def test_write_opencode_config_yolo_then_plain_unit(tmp_path):
|
|||
start.write_opencode_config(BASE, "sk-unsloth-abc", MODEL, path, yolo = False)
|
||||
config = json.loads(path.read_text())
|
||||
# A plain rerun replaces the yolo allow policy with a prompting one.
|
||||
assert config["permission"] == {"edit": "ask", "bash": "ask", "webfetch": "ask"}
|
||||
assert config["permission"] == {
|
||||
"edit": "ask",
|
||||
"bash": "ask",
|
||||
"webfetch": "ask",
|
||||
"external_directory": {"*": "ask"},
|
||||
}
|
||||
|
||||
|
||||
def test_openclaw_non_yolo_keeps_runtime_approvals(tmp_path):
|
||||
|
|
@ -2670,8 +2797,7 @@ def test_default_launch_has_no_resume_token(fake_studio, monkeypatch):
|
|||
|
||||
|
||||
def test_resume_persist_only_agents_have_no_resume_token(fake_studio, monkeypatch):
|
||||
# openclaw/hermes persist their session dir but have no non-interactive resume
|
||||
# selector, so --persist must not append a token; their own picker resumes.
|
||||
# Persistence alone must not select a session.
|
||||
for agent in ("openclaw", "hermes"):
|
||||
monkeypatch.setattr(start.shutil, "which", lambda _, a = agent: f"/usr/local/bin/{a}")
|
||||
captured = _capture_launch(monkeypatch, [agent, "--persist"])
|
||||
|
|
@ -2679,6 +2805,135 @@ def test_resume_persist_only_agents_have_no_resume_token(fake_studio, monkeypatc
|
|||
assert "--continue" not in captured["command"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("args", "expected"),
|
||||
[
|
||||
(
|
||||
["--resume", "session-id", "-z", "follow up"],
|
||||
[
|
||||
"chat",
|
||||
"-Q",
|
||||
"--yolo",
|
||||
"--accept-hooks",
|
||||
"--resume",
|
||||
"session-id",
|
||||
"-q",
|
||||
"follow up",
|
||||
],
|
||||
),
|
||||
(
|
||||
["-rsession-id", "-zfollow up"],
|
||||
["chat", "-Q", "--yolo", "--accept-hooks", "-rsession-id", "-qfollow up"],
|
||||
),
|
||||
(
|
||||
["-c=project", "-z=follow up"],
|
||||
["chat", "-Q", "--yolo", "--accept-hooks", "-c=project", "-q=follow up"],
|
||||
),
|
||||
(
|
||||
["-r", "session-id", "--oneshot=follow up"],
|
||||
[
|
||||
"chat",
|
||||
"-Q",
|
||||
"--yolo",
|
||||
"--accept-hooks",
|
||||
"-r",
|
||||
"session-id",
|
||||
"--query=follow up",
|
||||
],
|
||||
),
|
||||
(
|
||||
["--continue", "project", "--oneshot", "follow up"],
|
||||
[
|
||||
"chat",
|
||||
"-Q",
|
||||
"--yolo",
|
||||
"--accept-hooks",
|
||||
"--continue",
|
||||
"project",
|
||||
"-q",
|
||||
"follow up",
|
||||
],
|
||||
),
|
||||
(
|
||||
["--yolo", "--resume", "session-id", "-z", "follow up"],
|
||||
[
|
||||
"chat",
|
||||
"-Q",
|
||||
"--accept-hooks",
|
||||
"--yolo",
|
||||
"--resume",
|
||||
"session-id",
|
||||
"-q",
|
||||
"follow up",
|
||||
],
|
||||
),
|
||||
(
|
||||
["--accept-hooks", "--resume", "session-id", "-z", "follow up"],
|
||||
[
|
||||
"chat",
|
||||
"-Q",
|
||||
"--yolo",
|
||||
"--accept-hooks",
|
||||
"--resume",
|
||||
"session-id",
|
||||
"-q",
|
||||
"follow up",
|
||||
],
|
||||
),
|
||||
(
|
||||
["--resume", "chat", "-z", "follow up"],
|
||||
[
|
||||
"chat",
|
||||
"-Q",
|
||||
"--yolo",
|
||||
"--accept-hooks",
|
||||
"--resume",
|
||||
"chat",
|
||||
"-q",
|
||||
"follow up",
|
||||
],
|
||||
),
|
||||
(["--resume", "session-id"], ["--resume", "session-id"]),
|
||||
(["-z", "new session"], ["-z", "new session"]),
|
||||
],
|
||||
)
|
||||
def test_hermes_resume_oneshot_args(args, expected):
|
||||
assert start._hermes_resume_oneshot_args(args) == expected
|
||||
|
||||
|
||||
def test_hermes_resume_oneshot_uses_session_aware_chat(fake_studio, monkeypatch):
|
||||
monkeypatch.setattr(start.shutil, "which", lambda _: "/usr/local/bin/hermes")
|
||||
captured = _capture_launch(
|
||||
monkeypatch,
|
||||
["hermes", "--persist", "--resume", "session-id", "-z", "follow up"],
|
||||
)
|
||||
assert captured["command"][1:] == [
|
||||
"chat",
|
||||
"-Q",
|
||||
"--yolo",
|
||||
"--accept-hooks",
|
||||
"--resume",
|
||||
"session-id",
|
||||
"-q",
|
||||
"follow up",
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("usage_arg", ["--usage-file", "--usage-file=usage.json"])
|
||||
def test_hermes_resume_oneshot_rejects_usage_file(monkeypatch, usage_arg):
|
||||
monkeypatch.setattr(
|
||||
start,
|
||||
"_connect",
|
||||
lambda *args, **kwargs: pytest.fail("argument validation must run before connect"),
|
||||
)
|
||||
argv = ["hermes", "--resume", "session-id", "-z", "follow up", usage_arg]
|
||||
if usage_arg == "--usage-file":
|
||||
argv.append("usage.json")
|
||||
result = CliRunner().invoke(start.start_app, argv)
|
||||
assert result.exit_code == 2
|
||||
assert "cannot resume a one-shot session with --usage-file" in result.output
|
||||
|
||||
|
||||
def test_native_resume_flag_passes_through_unchanged(fake_studio, monkeypatch):
|
||||
# The persistence flag is --persist, NOT --resume, so an agent's own
|
||||
# `--resume <id>` (e.g. `unsloth start claude --resume <guid>`) still flows
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue