forked from unslothai/unsloth
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstart.py
More file actions
3715 lines (3435 loc) · 156 KB
/
Copy pathstart.py
File metadata and controls
3715 lines (3435 loc) · 156 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
"""`unsloth start` — launch a coding agent against a running Unsloth server."""
import atexit
import base64
import contextlib
import json
import os
import re
import shlex
import shutil
import signal
import subprocess
import sys
import tempfile
import threading
import time
import urllib.error
import urllib.request
from pathlib import Path
from typing import Literal, NamedTuple, NoReturn, Optional
from urllib.parse import urlencode, urlparse
import click
import typer
from typer.core import TyperCommand
from unsloth_cli._inference import (
_USER_AGENT,
_studio_token,
ensure_studio_backend_path,
find_studio_server,
is_loopback_url,
urlopen_no_redirect,
verify_studio_identity,
)
start_app = typer.Typer(
help = "Start a coding agent against a running Unsloth server.",
no_args_is_help = True,
context_settings = {"help_option_names": ["-h", "--help"]},
)
_CODEX_PROFILE = "unsloth_api"
_CODEX_ENV_KEY = "UNSLOTH_STUDIO_AUTH_TOKEN"
_HERMES_ENV_KEY = "UNSLOTH_API_KEY"
_HERMES_PROVIDER = "unsloth"
# Skip the installer's interactive setup wizard: `unsloth start hermes` runs
# this hint unattended and then writes its own session-scoped Hermes config, so
# the wizard's global API-key/model prompts would block the launch and point the
# user at a different (global) provider than the one Unsloth just configured.
# Both installers expose a skip flag: `-SkipSetup` (PowerShell) and
# `--skip-setup` (POSIX; passed to the piped script via `bash -s --`). Pin both
# the fetched script and the repository checkout it performs to the same full
# commit so a later change to either upstream branch cannot silently replace
# code that Unsloth executes with the user's privileges.
_HERMES_INSTALL_COMMIT = "f1af945f6c576eccb126fa955edc9be258b33020"
_HERMES_INSTALL_BASE = (
"https://raw.githubusercontent.com/NousResearch/hermes-agent/"
f"{_HERMES_INSTALL_COMMIT}/scripts"
)
_HERMES_WINDOWS_INSTALL_HINT = (
f"& ([scriptblock]::Create((irm {_HERMES_INSTALL_BASE}/install.ps1)))"
f" -SkipSetup -Commit {_HERMES_INSTALL_COMMIT}"
)
_HERMES_POSIX_INSTALL_HINT = (
f"curl -fsSL {_HERMES_INSTALL_BASE}/install.sh | bash -s --"
f" --skip-setup --commit {_HERMES_INSTALL_COMMIT}"
)
# Hermes refuses to initialize when the model window is under 64,000 tokens; its
# error message points at the model.context_length / auxiliary.compression
# overrides in config.yaml. write_hermes_config claims this value for smaller
# windows and scales the compaction threshold back down to the real window.
_HERMES_MIN_CONTEXT = 65536
_PI_PROVIDER = "unsloth"
_SUBAGENT_NAME = "unsloth"
_SUBAGENT_DESCRIPTION = (
"Local coding subagent powered by Unsloth for debugging, implementation, and codebase "
"research. Use when the user asks to spawn an Unsloth or local agent."
)
_SUBAGENT_INSTRUCTIONS = (
"You are a local coding subagent powered by Unsloth. Complete the assigned task directly, "
"use the available tools when useful, verify your work, and return a concise result to the "
"parent agent."
)
_SUBAGENT_PLAN_DESCRIPTION = (
"Read-only local coding subagent powered by Unsloth for planning and codebase research. "
"Use this local agent when Claude is in plan mode."
)
_SUBAGENT_PLAN_INSTRUCTIONS = (
"You are a read-only local coding subagent powered by Unsloth. Investigate the assigned "
"task with read-only tools, produce a concrete plan or answer, and return a concise result "
"to the parent agent. Do not modify files."
)
_CLAUDE_SUBAGENT_MCP_MODULE = "unsloth_cli.claude_subagent_mcp"
_CLAUDE_SUBAGENT_TOOL = "mcp__plugin_unsloth-local-agent_unsloth__unsloth_agent"
_CLAUDE_SUBAGENT_PLAN_TOOL = "mcp__plugin_unsloth-local-agent_unsloth__unsloth_plan_agent"
_CODEX_SUBAGENT_MCP_MODULE = "unsloth_cli.codex_subagent_mcp"
_CODEX_SUBAGENT_MCP_SERVER = "unsloth_local_agent"
_CODEX_SUBAGENT_MCP_TOOL = "spawn_local_agent"
_CODEX_SUBAGENT_CONFIG_ENV = "UNSLOTH_CODEX_SUBAGENT_CONFIG"
_CODEX_PARENT_OVERLAY_MANIFEST = ".unsloth-parent-overlay.json"
_CODEX_SUBAGENT_TOOL_DESCRIPTION = (
f"{_SUBAGENT_DESCRIPTION} Use this tool instead of the built-in spawn_agent tool for those "
"requests. Other subagent requests may use the built-in tools normally."
)
_CODEX_SUBAGENT_ROUTING_INSTRUCTIONS = (
"When the user asks to spawn an Unsloth agent or local agent, you must call the "
"spawn_local_agent MCP tool once with the complete task. Do not answer, simulate the "
"result, call wait, or use a built-in subagent before calling the tool. Use built-in "
"subagents for other delegation requests."
)
_PI_SUBAGENT_EXTENSION = Path(__file__).parent.parent / "pi_subagent.ts"
# OpenCode selects a model by "<providerID>/<modelID>". Use a dedicated id to avoid
# colliding with a user's providers; provider filters are set in the launch-time overlay.
_OPENCODE_PROVIDER = "unsloth-studio"
_PROVIDER_HEADER = f"[model_providers.{_CODEX_PROFILE}]"
_PASSTHROUGH = {"allow_extra_args": True, "ignore_unknown_options": True}
class _PassthroughCommand(TyperCommand):
"""Preserve the option separator when forwarding arguments to an agent."""
def parse_args(self, ctx: click.Context, args: list[str]) -> list[str]:
raw_args = list(args)
try:
separator = raw_args.index("--")
except ValueError:
return super().parse_args(ctx, args)
trailing_count = len(raw_args) - separator - 1
remaining = super().parse_args(ctx, args)
insert_at = max(0, len(remaining) - trailing_count)
if insert_at >= len(remaining) or remaining[insert_at] != "--":
remaining.insert(insert_at, "--")
ctx.args = remaining
return remaining
_CLAUDE_ENV_UNSET = ("ANTHROPIC_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN")
_CODEX_ENV_UNSET = ("OPENAI_API_KEY", "CODEX_API_KEY", "CODEX_ACCESS_TOKEN")
# Shared by every agent command; only the config/env/command differ.
# Help is grouped into rich panels so `--help` reads as Model / Server / Session
# instead of one long unaligned list.
_PANEL_MODEL = "Model"
_PANEL_SERVER = "Server"
_PANEL_SAMPLING = "Sampling"
_PANEL_SESSION = "Agent session"
_MODEL_OPTION = typer.Option(
None,
"--model",
"-m",
rich_help_panel = _PANEL_MODEL,
help = "Model for the agent, or a bare `org/name(:variant)` positional. "
"Defaults to the one loaded in Unsloth.",
)
_GGUF_VARIANT_OPTION = typer.Option(
None,
"--gguf-variant",
rich_help_panel = _PANEL_MODEL,
help = "GGUF quant variant to load (e.g. UD-Q4_K_XL). Defaults to UD-Q4_K_XL for "
"unsloth/* GGUF repos, else Q4_K_M.",
)
_CONTEXT_OPTION = typer.Option(
0,
"--max-seq-length",
"--context-length",
rich_help_panel = _PANEL_MODEL,
help = "Context length in tokens for the load (0 = model default).",
)
_LOAD_4BIT_OPTION = typer.Option(
True,
"--load-in-4bit/--no-load-in-4bit",
rich_help_panel = _PANEL_MODEL,
help = "Load hub models in 4-bit (ignored for GGUF).",
)
_TENSOR_PARALLEL_OPTION = typer.Option(
False,
"--tensor-parallel/--no-tensor-parallel",
rich_help_panel = _PANEL_MODEL,
help = "Split a GGUF across GPUs by tensor instead of by layer (multi-GPU only).",
)
_GPU_MEMORY_MODE_OPTION = typer.Option(
None,
"--gpu-memory-mode",
rich_help_panel = _PANEL_MODEL,
help = (
"GPU memory strategy for GGUF models loaded by this command. Auto lets "
"Unsloth manage placement. Manual with default layers and context delegates "
"placement and sizing to llama.cpp --fit. Omit when attaching to preserve "
"the running model's mode."
),
)
# Server knobs. Only used when `unsloth start` auto-starts the server (--serve);
# they have no effect when attaching to a server someone else already started.
_SERVE_OPTION = typer.Option(
True,
"--serve/--no-serve",
rich_help_panel = _PANEL_SERVER,
help = "If no Unsloth server is running, auto-start one for --model and keep it "
"available after the agent exits. --no-serve errors out instead.",
)
_ENABLE_TOOLS_OPTION = typer.Option(
False,
"--enable-tools/--disable-tools",
rich_help_panel = _PANEL_SERVER,
help = "Server-side tools (web search, code execution) for the auto-started server. "
"Default off so the agent's own tools are relayed unchanged.",
)
_TOOL_CALL_HEALING_OPTION = typer.Option(
None,
"--enable-tool-call-healing/--disable-tool-call-healing",
rich_help_panel = _PANEL_SERVER,
help = "Promote text-form tool calls from small GGUFs back into structured calls. On by "
"default; when the flag is omitted an inherited UNSLOTH_DISABLE_TOOL_CALL_HEALING is kept.",
)
_TOOL_CALL_NUDGING_OPTION = typer.Option(
None,
"--enable-tool-call-nudging/--disable-tool-call-nudging",
rich_help_panel = _PANEL_SERVER,
help = "Retry once with a nudge when a non-streaming passthrough tool call can't be healed. "
"On by default; when the flag is omitted an inherited UNSLOTH_TOOL_CALL_NUDGE is kept.",
)
_REASONING_OPTION = typer.Option(
None,
"--reasoning",
rich_help_panel = _PANEL_SERVER,
help = (
"llama-server reasoning mode for an auto-started coding-agent server. "
"Defaults to off so tool calls stay in the structured tool channel; use "
"'auto' or 'on' to opt back into model reasoning."
),
)
# Sampling overrides pin a value on the auto-started server (winning over the client and the
# per-model recommendation). Default unset -> the model's recommended sampling is used.
_TEMPERATURE_OPTION = typer.Option(
None,
"--temperature",
min = 0.0,
max = 2.0,
rich_help_panel = _PANEL_SAMPLING,
help = "Pin the sampling temperature. Default: unset (per-model recommendation).",
)
_TOP_P_OPTION = typer.Option(
None,
"--top-p",
min = 0.0,
max = 1.0,
rich_help_panel = _PANEL_SAMPLING,
help = "Pin top-p (nucleus) sampling. Default: unset (per-model recommendation).",
)
_TOP_K_OPTION = typer.Option(
None,
"--top-k",
min = -1,
max = 100,
rich_help_panel = _PANEL_SAMPLING,
help = "Pin top-k sampling. Default: unset (per-model recommendation).",
)
_MIN_P_OPTION = typer.Option(
None,
"--min-p",
min = 0.0,
max = 1.0,
rich_help_panel = _PANEL_SAMPLING,
help = "Pin min-p sampling threshold. Default: unset (per-model recommendation).",
)
_REPETITION_PENALTY_OPTION = typer.Option(
None,
"--repetition-penalty",
min = 1.0,
max = 2.0,
rich_help_panel = _PANEL_SAMPLING,
help = "Pin the repetition penalty. Default: unset (per-model recommendation).",
)
_PRESENCE_PENALTY_OPTION = typer.Option(
None,
"--presence-penalty",
min = 0.0,
max = 2.0,
rich_help_panel = _PANEL_SAMPLING,
help = "Pin the presence penalty. Default: unset (per-model recommendation).",
)
# Agent-session knobs.
_KEY_OPTION = typer.Option(
None,
"--api-key",
envvar = "UNSLOTH_API_KEY",
rich_help_panel = _PANEL_SESSION,
help = "Unsloth API key. For a local Unsloth it is minted automatically and "
"remembered per server. For a remote server, pass one with --api-key "
"(or UNSLOTH_API_KEY); it is remembered for next time.",
)
_LAUNCH_OPTION = typer.Option(
True,
"--launch/--no-launch",
rich_help_panel = _PANEL_SESSION,
help = "--no-launch prints the env and command instead (remote shells, WSL).",
)
# One normalized "run tools without prompting" switch. Each agent spells this
# differently and it's easy to forget which is which, so accept every spelling and
# route to the agent's own mechanism in _yolo_command_flags / the config writers.
_YOLO_OPTION = typer.Option(
False,
"--yolo",
"--dangerously-skip-permissions",
"--dangerously-bypass-approvals-and-sandbox",
rich_help_panel = _PANEL_SESSION,
help = "Auto-approve all tool actions for this session; routed to the agent's own "
"flag/config. Any of the three spellings works for any agent.",
)
_PERSIST_OPTION = typer.Option(
False,
"--persist/--no-persist",
rich_help_panel = _PANEL_SESSION,
help = (
"Keep this agent's Unsloth-managed session dir so you can resume it later. "
"codex/openclaw/hermes/pi have their whole home relocated into an Unsloth dir "
"that is a throwaway temp dir (wiped on exit) by default; with --persist it "
"lives under the Unsloth agents dir and survives, so their own resume can reopen "
"it. claude and opencode keep sessions in your own stores (~/.claude, "
"~/.local/share/opencode), so they already resume regardless. To reopen a "
"session, pass the agent's own resume command through, e.g. "
"`unsloth start codex --persist resume` or `claude --resume <id>`; those flow to "
"the agent unchanged."
),
)
_AS_SUBAGENT_OPTION = typer.Option(
False,
"--as-subagent",
rich_help_panel = _PANEL_SESSION,
help = "Keep the coding agent's current model and add Unsloth as a local subagent.",
)
# Per-agent CLI flag for "run tools without prompting". OpenCode (native --auto is
# command-scoped, handled below) and OpenClaw (config-only) are absent from this prefix map.
_YOLO_COMMAND_FLAGS = {
"claude": ["--dangerously-skip-permissions"],
"codex": ["--dangerously-bypass-approvals-and-sandbox"],
"hermes": ["--yolo"],
# Pi never prompts per tool call; its only approval gate is project trust, so -a
# (trust project resources) is the closest "don't ask me" equivalent.
"pi": ["--approve"],
}
def _yolo_command_flags(agent: str, yolo: bool) -> list:
# .get so a config-based agent (or a typo) yields no flag instead of a KeyError.
return _YOLO_COMMAND_FLAGS.get(agent, []) if yolo else []
# Subcommands that reject --auto (OpenCode exposes it only on the default TUI and `run`),
# so `opencode serve --auto` is never emitted. Includes console/generate, hidden from
# `opencode --help` but still registered. Unknown first positionals are TUI paths -> --auto.
_OPENCODE_NON_AUTO_SUBCOMMANDS = frozenset(
"completion acp mcp attach debug providers auth agent upgrade uninstall serve web "
"models stats export import github pr session plugin plug db console generate".split()
)
_OPENCODE_GLOBAL_BOOLEAN_OPTIONS = frozenset(
"-h --help -v --version --print-logs --pure --mdns".split()
)
_OPENCODE_GLOBAL_VALUE_OPTIONS = frozenset(
"--log-level --port --hostname --mdns-domain --cors".split()
)
_OPENCODE_NATIVE_AUTO_MIN_VERSION = (1, 17, 12)
def _opencode_supports_native_auto() -> bool:
executable = _which_with_install_dirs("opencode")
if executable is None:
# No local binary: a --no-launch recipe may run elsewhere, and _run installs the
# current release on launch -- either way assume native --auto is available.
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()) >= (
_OPENCODE_NATIVE_AUTO_MIN_VERSION
)
def _opencode_subcommand(args: list[str]) -> Optional[str]:
"""Return an explicit OpenCode subcommand after supported global options."""
index = 0
while index < len(args):
arg = args[index]
if arg == "--":
return None
if arg in _OPENCODE_GLOBAL_BOOLEAN_OPTIONS:
index += 1
continue
if arg in _OPENCODE_GLOBAL_VALUE_OPTIONS:
index += 2
continue
if any(arg.startswith(f"{option}=") for option in _OPENCODE_GLOBAL_VALUE_OPTIONS):
index += 1
continue
# A non-global option (e.g. --session) is a TUI flag; stop before its value is
# mistaken for a subcommand.
if arg.startswith("-"):
return None
return arg
return None
def _opencode_native_auto_args(args: list[str], yolo: bool) -> tuple[list[str], bool]:
"""Add OpenCode's native --auto when the selected command supports it."""
routed = list(args)
if not yolo:
return routed, False
if _opencode_subcommand(routed) in _OPENCODE_NON_AUTO_SUBCOMMANDS:
return routed, False
separator = routed.index("--") if "--" in routed else len(routed)
# --mini's runMini TUI forces auto=false and never forwards --auto, so appending it is
# useless; fall back to the config permission block so --yolo still auto-approves.
if any(arg == "--mini" or arg.startswith("--mini=") for arg in routed[:separator]):
return routed, False
if "--auto" not in routed[:separator]:
routed.insert(separator, "--auto")
return routed, True
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."""
gguf_variant: Optional[str] = None
max_seq_length: int = 0
load_in_4bit: bool = True
tensor_parallel: bool = False
gpu_memory_mode: Optional[Literal["auto", "manual"]] = None
class ServerOptions(NamedTuple):
"""Tool-call knobs forwarded to an auto-started `unsloth run` server."""
enable_tools: bool = False
tool_call_healing: Optional[bool] = None
tool_call_nudging: Optional[bool] = None
reasoning: Optional[Literal["on", "off", "auto"]] = None
temperature: Optional[float] = None
top_p: Optional[float] = None
top_k: Optional[int] = None
min_p: Optional[float] = None
repetition_penalty: Optional[float] = None
presence_penalty: Optional[float] = None
def _split_repo_variant(model: str) -> tuple:
"""Split ``org/name:QUANT`` into ``(repo, variant)`` -> ``("org/name", "QUANT")``.
``unsloth run`` and llama.cpp accept ``--model org/name:QUANT`` as shorthand for
``--model org/name --gguf-variant QUANT``. Mirror that here so a ``:variant`` suffix
resolves against the already-loaded ``org/name`` (which /v1/models lists without the
suffix) instead of trying to load a repo id containing ``:`` -- which Hugging Face
rejects, and which would evict a model another session is using. Local paths, Windows
drive letters, and ids without a ``:`` pass through unchanged.
"""
s = (model or "").strip()
if not s or s.startswith(("/", "./", "../", "~")) or s == ".":
return s, None
if len(s) >= 2 and s[1] == ":" and s[0].isalpha(): # Windows drive, e.g. C:\models\x
return s, None
if ":" not in s:
return s, None
repo, _, variant = s.rpartition(":")
if not repo or not variant or "/" in variant:
return s, None
return repo, variant
def _looks_like_model(token: str) -> bool:
"""True for a bare `org/name(:variant)` hub id that is not a flag or a local path.
Reuses `_is_hub_model_id`, so a relative dir like `owner/repo` that actually exists
is left for the agent (e.g. OpenCode opens it as a project) instead of being taken
as a model; a non-existent `org/name` is treated as a hub id.
"""
if not token or token.startswith("-") or " " in token:
return False
repo, _ = _split_repo_variant(token)
return _is_hub_model_id(repo)
def _consume_positional_model(model: Optional[str], args: list) -> tuple:
"""Route a leading `org/name` positional to --model when --model was not given.
Only the FIRST token is considered so an option value like `--profile owner/repo`
is never stolen, and only when --model is absent so an explicit --model always wins.
Returns (model, remaining_args) with the consumed token removed from the passthrough.
"""
args = list(args)
if model or not args or not _looks_like_model(args[0]):
return model, args
return args[0], args[1:]
def _display_model_spec(model: str, variant: Optional[str]) -> str:
"""Return a user-facing model name that includes the selected GGUF variant."""
repo, inline_variant = _split_repo_variant(model)
selected_variant = variant or inline_variant
return f"{repo}:{selected_variant}" if selected_variant else model
def _subagent_model_id(
base: str,
key: str,
entry: dict,
requested_model: Optional[str],
requested_variant: Optional[str],
) -> str:
"""Return an API model id that preserves the selected GGUF variant.
Coding-agent model definitions outlive the initial load. If Unsloth later
unloads the model, a bare repository id may resolve to a different cached
quant. Include the explicit or currently loaded variant so an automatic
reload selects the same weights.
"""
model_id = str(entry["id"])
_, inline_variant = _split_repo_variant(requested_model or "")
variant = requested_variant or inline_variant
if not variant:
try:
status = _http_json("GET", f"{base}/api/inference/status", key)
except Exception:
status = {}
typer.echo(
"Warning: could not verify the loaded GGUF variant; a later reload "
"may pick a different cached quant. Pass :variant to pin it.",
err = True,
)
if status.get("is_gguf"):
variant = status.get("gguf_variant")
if variant and _is_hub_model_id(model_id):
return _display_model_spec(model_id, str(variant))
if variant:
# A path load is advertised as a bare basename with no ":variant" channel,
# so the quant cannot be recorded and a later reload picks for itself.
typer.echo(
f"Warning: {model_id} loaded from a path, so the subagent config cannot "
f"pin the {variant} quant; a reload may choose a different one. Load the "
"model by repository id to pin it.",
err = True,
)
return model_id
def _fail(message: str) -> NoReturn:
typer.echo(message, err = True)
raise typer.Exit(code = 1)
def _reject_as_subagent(agent: str, args: list) -> None:
# Reject early, or the flag reaches the agent binary after Studio loaded the model.
if any(arg == "--as-subagent" or arg.startswith("--as-subagent=") for arg in args):
_fail(f"--as-subagent is not supported for {agent}.")
def _http_error_detail(exc: urllib.error.HTTPError) -> str:
try:
body = json.loads(exc.read().decode())
return body.get("detail") or body["error"]["message"]
except Exception:
return str(exc)
def _http_json(
method: str,
url: str,
token: str,
payload = None,
timeout = 30,
error = None,
):
"""On HTTPError: raise if `error` is None, else fail with `error` plus the server's detail."""
request = urllib.request.Request(
url,
data = None if payload is None else json.dumps(payload).encode(),
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json",
"User-Agent": _USER_AGENT,
},
method = method,
)
try:
# No redirects: a 3xx would leak this bearer token to an unvetted base.
with urlopen_no_redirect(request, timeout = timeout) as response:
return json.loads(response.read().decode() or "{}")
except urllib.error.HTTPError as exc:
if error is None:
raise
_fail(f"{error}: {_http_error_detail(exc)}")
except (urllib.error.URLError, TimeoutError) as exc:
if error is None:
raise
_fail(f"{error}: {getattr(exc, 'reason', None) or exc}")
# A server that WE auto-started (never one we merely found). Kept at module scope so
# failure paths and the atexit backstop can tear it down without threading a handle
# through all six agent commands. Only one agent runs per process, so one slot is enough.
_auto_served_server: Optional[subprocess.Popen] = None
# Model download + load can be slow; give the auto-started server room before giving up.
_SERVER_START_TIMEOUT_S = 900
_DOWNLOAD_POLL_INTERVAL_S = 1.0
_START_API_KEY_PREFIX = "UNSLOTH_START_API_KEY: "
_START_API_KEY_MARKER_ENV = "_UNSLOTH_START_API_KEY_MARKER"
def _format_download_bytes(value: int) -> str:
value = max(0, int(value))
for unit in ("B", "KiB", "MiB", "GiB", "TiB"):
if value < 1024 or unit == "TiB":
precision = 0 if unit in ("B", "KiB") else 1
return f"{value:.{precision}f} {unit}"
value /= 1024
return "0 B"
def _format_download_eta(seconds: float) -> str:
seconds = max(0, int(seconds))
if seconds < 60:
return f"{seconds}s"
minutes, seconds = divmod(seconds, 60)
if minutes < 60:
return f"{minutes}m {seconds:02d}s"
hours, minutes = divmod(minutes, 60)
return f"{hours}h {minutes:02d}m"
class _DownloadProgressDisplay:
"""Render download progress without making redirected output noisy."""
def __init__(self) -> None:
self._samples: list[tuple[float, int]] = []
self._shown = False
self._last_bucket = -1
self._last_line_length = 0
self._last_expected = 0
self._interactive = bool(getattr(sys.stdout, "isatty", lambda: False)())
def update(self, progress: dict) -> None:
downloaded = max(0, int(progress.get("downloaded_bytes") or 0))
completed = max(0, int(progress.get("completed_bytes") or 0))
expected = max(0, int(progress.get("expected_bytes") or 0))
self._last_expected = max(self._last_expected, expected)
fraction = float(progress.get("progress") or 0)
if downloaded <= 0:
return
# A fully cached snapshot can report 99% with no incomplete bytes; that is
# not a transfer, so don't show it as a download.
if completed >= downloaded > 0:
return
now = time.monotonic()
if self._samples and downloaded < self._samples[-1][1]:
self._samples.clear()
self._samples.append((now, downloaded))
cutoff = now - 15.0
while len(self._samples) > 2 and self._samples[0][0] < cutoff:
self._samples.pop(0)
rate = 0.0
if len(self._samples) >= 2:
elapsed = self._samples[-1][0] - self._samples[0][0]
delta = self._samples[-1][1] - self._samples[0][1]
if elapsed >= 1.0 and delta > 0:
rate = delta / elapsed
if expected > 0:
# The endpoint caps at 99% while bytes remain in an incomplete file; trust it.
fraction = min(1.0, max(0.0, fraction))
percent = min(100, max(0, int(fraction * 100)))
filled = min(24, int(fraction * 24))
bar = "=" * filled + ">" + "." * max(0, 23 - filled) if filled < 24 else "=" * 24
line = (
f"Downloading model [{bar}] {percent:3d}% "
f"{_format_download_bytes(downloaded)} / {_format_download_bytes(expected)}"
)
bucket = percent // 10
if rate > 0:
line += f" | {_format_download_bytes(rate)}/s"
if downloaded < expected:
line += f" | ETA {_format_download_eta((expected - downloaded) / rate)}"
else:
line = f"Downloading model: {_format_download_bytes(downloaded)}"
bucket = downloaded // (1024**3)
if rate > 0:
line += f" | {_format_download_bytes(rate)}/s"
if self._interactive:
padding = " " * max(0, self._last_line_length - len(line))
typer.echo(f"\r{line}{padding}", nl = False)
sys.stdout.flush()
self._last_line_length = len(line)
elif not self._shown or bucket > self._last_bucket:
typer.echo(line)
self._last_bucket = bucket
self._shown = True
def close(self) -> None:
if self._interactive and self._shown:
typer.echo()
self._last_line_length = 0
def complete(self) -> None:
"""Finish a displayed transfer after the model load confirms success."""
if not self._shown:
return
downloaded = self._samples[-1][1] if self._samples else 0
expected = max(downloaded, getattr(self, "_last_expected", 0))
self.update(
{
"downloaded_bytes": expected,
"expected_bytes": expected,
"progress": 1.0,
}
)
def _normalized_variant(value: object) -> str:
return re.sub(r"[^a-z0-9]", "", str(value or "").lower())
class _ModelDownloadProgress:
"""Best-effort polling of the model download endpoints."""
def __init__(self, base: str, key: str, model: str, variant: Optional[str]) -> None:
self._base = base
self._key = key
self._model = model
self._variant = variant or ""
self._expected_bytes = 0
self._display = _DownloadProgressDisplay()
self._configured = False
self._disabled = not _is_hub_model_id(model)
self._progress_prefix = "/api/hub"
def _configure(self) -> None:
self._configured = True
if self._disabled:
return
# GGUF repos need the selected quant's size; the repo endpoint totals every
# quant. Resolve the variant first, otherwise show bytes only.
if self._variant or "gguf" in self._model.lower():
try:
params = urlencode({"repo_id": self._model})
try:
info = _http_json(
"GET",
f"{self._base}/api/hub/gguf-variants?{params}",
self._key,
timeout = 10,
)
except urllib.error.HTTPError as exc:
if exc.code != 404:
raise
self._progress_prefix = "/api/models"
info = _http_json(
"GET",
f"{self._base}/api/models/gguf-variants?{params}",
self._key,
timeout = 10,
)
self._variant = self._variant or str(info.get("default_variant") or "")
wanted = _normalized_variant(self._variant)
for item in info.get("variants") or []:
quant = _normalized_variant(item.get("quant"))
filename = _normalized_variant(item.get("filename"))
if wanted and (wanted == quant or wanted in filename):
self._expected_bytes = int(
item.get("download_size_bytes") or item.get("size_bytes") or 0
)
break
except Exception:
# Older servers lack this endpoint; byte progress is still useful.
pass
def poll(self) -> None:
if not self._configured:
self._configure()
if self._disabled:
return
try:
if self._variant or "gguf" in self._model.lower():
params = urlencode(
{
"repo_id": self._model,
"variant": self._variant,
"expected_bytes": self._expected_bytes,
}
)
url = f"{self._base}{self._progress_prefix}/gguf-download-progress?{params}"
else:
url = (
f"{self._base}{self._progress_prefix}/download-progress?"
f"{urlencode({'repo_id': self._model})}"
)
try:
reading = _http_json("GET", url, self._key, timeout = 10)
except urllib.error.HTTPError as exc:
if exc.code != 404 or self._progress_prefix == "/api/models":
raise
self._progress_prefix = "/api/models"
self.poll()
return
self._display.update(reading)
except Exception:
# Progress is best-effort; never fail the load over a polling error.
self._disabled = True
def close(self) -> None:
self._display.close()
def complete(self) -> None:
self._display.complete()
def _load_model_with_progress(
base: str, key: str, model: str, load: LoadOptions, payload: dict
) -> dict:
"""Run the blocking load request while polling its download progress."""
result: list[tuple[bool, object]] = []
done = threading.Event()
def _load() -> None:
try:
value = _http_json(
"POST",
f"{base}/api/inference/load",
key,
payload,
timeout = 3600,
error = "Model load failed",
)
result.append((True, value))
except BaseException as exc:
result.append((False, exc))
finally:
done.set()
threading.Thread(target = _load, name = "unsloth-model-load", daemon = True).start()
progress = _ModelDownloadProgress(base, key, model, load.gguf_variant)
loading_announced = False
try:
while not done.wait(_DOWNLOAD_POLL_INTERVAL_S):
if not loading_announced:
typer.echo(f"Loading model: {_display_model_spec(model, load.gguf_variant)}")
loading_announced = True
progress.poll()
ok, value = result[0]
if not ok:
assert isinstance(value, BaseException)
raise value
progress.complete()
return value if isinstance(value, dict) else {}
finally:
progress.close()
def _studio_healthy(base: str, timeout: float = 3.0) -> bool:
request = urllib.request.Request(f"{base}/api/health", headers = {"User-Agent": _USER_AGENT})
try:
with urllib.request.urlopen(request, timeout = timeout) as response:
return json.loads(response.read(65536).decode() or "{}").get("status") == "healthy"
except Exception:
return False
def _log_tail(path: Path, lines: int = 20) -> str:
try:
return "\n".join(path.read_text(encoding = "utf-8", errors = "replace").splitlines()[-lines:])
except OSError:
return "(no server log)"
def _redacted_log_tail(path: Path, lines: int = 20) -> str:
"""Tail with minted keys removed; only for tails shown on the terminal."""
return re.sub(r"sk-unsloth-\S+", "sk-unsloth-[redacted]", _log_tail(path, lines))
def _shutdown_server(server: Optional[subprocess.Popen]) -> None:
# Idempotent teardown of a server WE started, plus its own children (llama-server,
# cloudflared). A no-op once the process is already gone.
if server is None or server.poll() is not None:
return
if os.name == "nt":
# terminate()/kill() reach only the parent `unsloth run`; taskkill /T walks the
# whole tree so the llama-server child doesn't keep the port and GPU (matches the
# taskkill /T /F pattern already used in unsloth/dataprep/synthetic.py).
try:
subprocess.run(
["taskkill", "/PID", str(server.pid), "/T", "/F"],
capture_output = True,
timeout = 15,
check = False,
)
server.wait(timeout = 5)
except Exception:
with contextlib.suppress(Exception):
server.kill()
return
try:
os.killpg(os.getpgid(server.pid), signal.SIGTERM)
except OSError:
server.terminate()
try:
server.wait(timeout = 15)
except Exception:
try:
os.killpg(os.getpgid(server.pid), signal.SIGKILL)
except OSError:
server.kill()
def _shutdown_auto_served() -> None:
global _auto_served_server
server, _auto_served_server = _auto_served_server, None
if server is not None and server.poll() is None:
typer.echo("Stopping the auto-started Unsloth server…")
_shutdown_server(server)
def _keep_auto_served() -> bool:
"""Release ownership so a successfully started server survives this CLI."""
global _auto_served_server
server, _auto_served_server = _auto_served_server, None
atexit.unregister(_shutdown_auto_served)
return server is not None and server.poll() is None
def _start_studio_server(
base: str,
model: str,
load: LoadOptions,
server: ServerOptions = ServerOptions(),
) -> subprocess.Popen:
"""Spawn `unsloth run` for `model`, wait until it is fully ready, and return it."""
global _auto_served_server
unsloth = shutil.which("unsloth") or "unsloth"
parsed = urlparse(base)
# Tools default off = passthrough mode (relay the agent's own tools); --no-cloudflare =
# loopback only, no tunnel. Mirrors .github/scripts/serve-unsloth-run.sh. Healing/nudging
# travel via the child env below (version-agnostic) rather than new run flags that an
# older re-exec'd run could mistake for llama-server args.
command = [
unsloth,