-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathminion.py
More file actions
5318 lines (4852 loc) · 240 KB
/
Copy pathminion.py
File metadata and controls
5318 lines (4852 loc) · 240 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
#!/usr/bin/env python3
"""minion — a deliberately tiny coding agent for self-hosted or remote models.
One file, one dep (`openai`), no TUI framework. Points at any OpenAI-compatible
endpoint (vLLM / llama.cpp / SGLang / Z.ai / OpenAI itself). Survives models
whose native tool-calling isn't wired up yet by falling back to parsing
<tool_call>...</tool_call> tags out of the text — the convention most open
models (Hermes/Qwen/Nemotron) emit.
pip install openai
export MINION_BASE_URL=http://localhost:8000/v1 # your served endpoint
export MINION_MODEL=your-model-name
export MINION_API_KEY=sk-noop # any string; local servers ignore it
python minion.py
Multiple sources — define named endpoints and switch between them at runtime:
MINION_SOURCES=local,zai
MINION_SOURCE_LOCAL_BASE_URL=http://localhost:8080/v1
MINION_SOURCE_ZAI_BASE_URL=https://api.z.ai/api/paas/v4
MINION_SOURCE_ZAI_API_KEY=*** # $name = key from env / ~/.env
MINION_SOURCE_ZAI_MODEL=glm-x-preview
python minion.py --source zai # start on Z.ai
Sessions — every chat is auto-saved to ~/.minion/sessions/ and resumable:
python minion.py sessions # list saved sessions (prints + exits)
python minion.py sessions --page 2 # next page of saved sessions
python minion.py sessions refactor # …filtered by a substring query
python minion.py --resume <id|short-id|prefix|title> # resume a past session
python minion.py --resume 1 # resume the most recent
/sessions # list recent sessions (with short ids)
/sessions --page 2 # next page of recent sessions
/resume <n|short-id|title> # switch to another session mid-chat
/save [title] # save the current session (title optional)
Toggles in-session: /source [name] [model] /provider [source] [a,b,…|off] /yolo /approval [level] /compress /compact /autocompress [pct|off|on] /memory save|remember|list /reset /clear /new /recover /sessions /resume /save /delete /quit
Flags: --yolo --approval <all|low|medium|high|yolo> --source <name> --resume <target> --session <id>
Env: MINION_APPROVAL=<all|low|medium|high|yolo> (persistent default approval mode; ~/.env or shell)
MINION_AUTOCOMPRESS_PERCENT=<0-100> (auto-compress threshold; 0=off; default 85)
MINION_BACKEND=vllm (disables llama.cpp-only recovery knobs like min_p /
repeat_penalty / DRY that vLLM's speculative decoder
rejects; omits them from extra_body on retries)
TOGETHER_API_KEY (auto-registers a built-in `together` source; default model zai-org/GLM-5.2)
OPENROUTER_API_KEY (auto-registers a built-in `openrouter` source; default model z-ai/glm-5.2,
routed to parasail/fp8 — override with /provider or MINION_SOURCE_OPENROUTER_EXTRA_BODY)
"""
import json
import os
import random
import re
import secrets
import select
import shlex
import unicodedata
import shutil
import subprocess
import sys
import termios
import threading
import time
import urllib.error
import urllib.request
import httpx
from openai import OpenAI, APIConnectionError, APIError
# --- env file ---------------------------------------------------------------
# Load ~/.env (or MINION_ENV_FILE) into os.environ without clobbering vars
# already set in the shell. Lets source config / API keys live in one place
# instead of being exported in every terminal.
_ENV_FILE = os.path.expanduser(os.environ.get("MINION_ENV_FILE", "~/.env"))
def _load_env_file():
try:
with open(_ENV_FILE, encoding="utf-8") as f:
for raw in f:
line = raw.strip()
if not line or line.startswith("#") or "=" not in line:
continue
k, v = line.split("=", 1)
k = k.strip()
if k.startswith("export "):
k = k[len("export "):].strip()
if not k or k in os.environ:
continue
v = v.strip()
if len(v) >= 2 and v[0] == v[-1] and v[0] in ("'", '"'):
v = v[1:-1]
os.environ[k] = v
except (OSError, IOError):
pass
_load_env_file()
# --- sessions ---------------------------------------------------------------
# Chat history persistence. Each session is one JSON file under
# ~/.minion/sessions/ (override with MINION_HOME / MINION_SESSIONS_DIR).
# The file stores the exact `messages` array the model sees (system prompt
# + every turn + tool calls/results), plus a little metadata (id, title,
# created_at, updated_at, cwd, source). Greppable, human-readable, and it
# round-trips trivially — load it back in and you have a resumable chat.
#
# Design cribbed from Hermes (hermes_state.py / SessionDB), which uses a
# SQLite store + FTS5 search because it's a multi-platform gateway (web,
# CLI, Telegram, …) with billing and compression chains. minion is a single
# local agent, so a flat directory of JSON files gives the same UX
# (auto-save per turn, /sessions, /resume, /save) without the weight.
SESSION_HOME = os.path.expanduser(
os.environ.get("MINION_HOME", "~/.minion")
)
SESSION_LIST_DEFAULT_LIMIT = 10
SESSION_LIST_MAX_LIMIT = 100
def _sessions_dir():
"""Where session files live. Honors MINION_SESSIONS_DIR, then MINION_HOME/sessions."""
return os.path.expanduser(
os.environ.get("MINION_SESSIONS_DIR",
os.path.join(SESSION_HOME, "sessions"))
)
def _memories_dir():
"""Where memory files live. Always under SESSION_HOME/memories."""
return os.path.join(SESSION_HOME, "memories")
def _new_session_id():
"""Short, unguessable, sortable-ish: YYYYMMDD-HHMMSS-<6 hex>."""
stamp = time.strftime("%Y%m%d-%H%M%S")
return f"{stamp}-{secrets.token_hex(3)}"
def _safe_title(text, maxlen=60):
"""Turn the first user message into a filesystem-safe-ish title.
Collapses whitespace, strips control chars, clamps length. We don't
scrub for path-separators beyond replacing them with spaces — the id
(not the title) is the filename, so a weird title can't break lookup.
"""
if not text:
return None
text = " ".join(str(text).split())
text = "".join(c for c in text if c.isprintable())
if len(text) > maxlen:
text = text[:maxlen - 1] + "…"
return text or None
def _is_empty_assistant_message(msg):
if msg.get("role") != "assistant" or msg.get("tool_calls"):
return False
content = msg.get("content")
if content is None:
return True
if isinstance(content, str):
return not content.strip()
if isinstance(content, list):
for part in content:
if isinstance(part, str) and part.strip():
return False
if isinstance(part, dict):
text = part.get("text")
if isinstance(text, str) and text.strip():
return False
return True
return False
def _prune_empty_assistant_messages(messages):
"""Drop assistant turns that have neither visible content nor tool calls."""
if not isinstance(messages, list):
return 0
kept = [m for m in messages if not _is_empty_assistant_message(m)]
removed = len(messages) - len(kept)
if removed:
messages[:] = kept
return removed
def _session_path(session_id):
return os.path.join(_sessions_dir(), f"{session_id}.json")
def _write_session(session_id, messages, meta=None):
"""Persist `messages` to the session file. Creates the dir if needed.
Writes atomically (temp file + rename) so a crash mid-write can't
corrupt the existing session. `meta` (title, source, cwd, …) is
merged into the stored metadata.
"""
d = _sessions_dir()
os.makedirs(d, exist_ok=True)
_prune_empty_assistant_messages(messages)
path = _session_path(session_id)
now = time.time()
existing = {}
try:
with open(path, encoding="utf-8") as f:
existing = json.load(f)
if not isinstance(existing, dict):
existing = {}
except (OSError, IOError, json.JSONDecodeError):
pass
# Start from the existing metadata so partial writes (e.g. the session
# description refresh, which only passes {"description", "desc_turns"})
# don't clobber fields a prior _save_current wrote — token totals,
# started_at, etc. Then let `meta` override on top.
data = dict(existing)
data["id"] = session_id
data["messages"] = messages
data["created_at"] = existing.get("created_at", now)
data["updated_at"] = now
if meta:
for k, v in meta.items():
if v is not None:
data[k] = v
tmp = path + ".tmp"
with open(tmp, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False)
os.replace(tmp, path)
try:
os.utime(path, (data["updated_at"], data["updated_at"]))
except (OSError, TypeError, ValueError):
pass
def _load_session(session_id):
"""Read a session file. Returns the dict (id, messages, meta…) or None."""
path = _session_path(session_id)
try:
with open(path, encoding="utf-8") as f:
data = json.load(f)
if isinstance(data, dict) and "messages" in data:
_prune_empty_assistant_messages(data.get("messages"))
return data
except (OSError, IOError, json.JSONDecodeError):
pass
return None
def _session_files_newest():
"""Return session JSON filenames newest-first using filesystem mtimes.
Listing many sessions should not require parsing every old transcript.
The session writer keeps mtime aligned with updated_at, so this is a
cheap index for recent-session browsing.
"""
d = _sessions_dir()
files = []
try:
with os.scandir(d) as entries:
for entry in entries:
if not entry.name.endswith(".json"):
continue
try:
if not entry.is_file():
continue
files.append((entry.stat().st_mtime, entry.name))
except OSError:
continue
except OSError:
return []
files.sort(key=lambda item: (item[0], item[1]), reverse=True)
return [name for _, name in files]
def _session_summary_from_file(fname):
d = _sessions_dir()
path = os.path.join(d, fname)
try:
with open(path, encoding="utf-8") as f:
data = json.load(f)
if not isinstance(data, dict) or "messages" not in data:
return None
except (OSError, IOError, json.JSONDecodeError):
return None
sid = data.get("id") or fname[:-5]
msgs = data.get("messages", [])
preview = ""
for m in msgs:
if m.get("role") == "user" and m.get("content"):
preview = _safe_title(m["content"]) or ""
break
return {
"id": sid,
"short": _short_id(sid),
"title": data.get("title") or preview or "(empty)",
"description": data.get("description"),
"preview": preview,
"updated_at": data.get("updated_at", 0),
"n": len([m for m in msgs if m.get("role") != "system"]),
"model": data.get("model"),
"source": data.get("source"),
"cwd": data.get("cwd"),
}
def _session_matches_query(summary, query):
if not query:
return True
q = query.lower()
return (
q in (summary.get("title") or "").lower()
or q in (summary.get("description") or "").lower()
or q in (summary.get("preview") or "").lower()
or q in (summary.get("id") or "").lower()
or q in (summary.get("short") or "").lower()
)
def _list_sessions(limit=20, offset=0, query=None):
"""Return sessions newest-first as dicts: id, title, description, preview, n.
`preview` is the first ~60 chars of the first user message; `description`
is an optional model-generated one-liner refreshed every N turns (richer
than the static first-message title). `n` is the turn count (non-system
messages)."""
limit = max(0, int(limit)) if limit is not None else None
offset = max(0, int(offset or 0))
files = _session_files_newest()
out = []
for fname in files:
summary = _session_summary_from_file(fname)
if not summary or not _session_matches_query(summary, query):
continue
out.append(summary)
if query:
continue
if limit is not None and len(out) >= offset + limit:
break
if query:
out.sort(key=lambda s: s["updated_at"], reverse=True)
end = None if limit is None else offset + limit
return out[offset:end]
def _delete_session(session_id):
"""Remove a session file. Returns True if something was deleted."""
path = _session_path(session_id)
try:
os.remove(path)
return True
except OSError:
return False
# After this many user turns, minion asks the model for a short (≤70 char)
# description of the whole conversation so far and stores it in the session
# file's `description` field. The description refreshes on every Nth turn
# thereafter, so it tracks what the chat is actually about as it evolves —
# far more useful in `minion sessions` than a static first-message title.
# 0 disables the refresh entirely (the auto-derived title is used as-is).
# The actual value is resolved after _env_int() is defined (below), so this
# is just a sentinel; see SESSION_DESC_REFRESH.
_DESC_REFRESH_DEFAULT = 6
def _short_id(session_id):
"""The scannable tail of a session id (the 6-hex suffix), for listings.
The full id is `YYYYMMDD-HHMMSS-XXXXXX`; in a list of recent sessions the
date+time prefix is shared/redundant, so we show just the 6 hex chars as a
quick tag the user can grep or pass to --resume."""
if session_id and "-" in session_id:
return session_id.rsplit("-", 1)[-1]
return session_id or ""
def _maybe_refresh_description(session_id, messages):
"""Ask the model for a one-line session description, if enough turns have
passed since the last refresh.
Refreshes at the configured interval (every SESSION_DESC_REFRESH user
turns). The description is stored in the session file's `description`
field and surfaced in `minion sessions` / `/sessions` listings. A failure
(server down, empty response) leaves the existing description untouched.
Returns the new description string, or None if no refresh happened.
"""
if SESSION_DESC_REFRESH <= 0:
return None
# Count user turns (exclude synthetic runtime-note-only turns).
user_turns = sum(
1 for m in messages
if m.get("role") == "user"
and isinstance(m.get("content"), str)
and not m["content"].lstrip().startswith("[")
)
existing = _load_session(session_id) or {}
last_desc_turns = existing.get("desc_turns", 0)
# Refresh when we've crossed a multiple of SESSION_DESC_REFRESH since the
# last recorded refresh. Don't refresh before the first threshold (so a
# 1-turn "hello" session doesn't burn a model call).
if user_turns < SESSION_DESC_REFRESH:
return None
if user_turns - last_desc_turns < SESSION_DESC_REFRESH:
return None
# Build a compact transcript for the summarizer — truncate tool outputs
# and skip the system prompt to keep the call cheap.
def _trim(msgs, per_msg=500, cap=20):
out = []
for m in msgs:
if m.get("role") == "system":
continue
c = m.get("content")
if c is None and m.get("tool_calls"):
calls = ", ".join(
f"{tc['function']['name']}(...)" for tc in m["tool_calls"])
c = f"→ {calls}"
elif isinstance(c, list):
c = " ".join(p.get("text", "") for p in c if isinstance(p, dict))
c = (c or "").replace("\n", " ").strip()
if len(c) > per_msg:
c = c[:per_msg - 1] + "…"
out.append(f"[{m.get('role', '?')}] {c}")
if len(out) >= cap:
break
return "\n".join(out)
prompt = _trim(messages[-30:]) # last ~30 messages is plenty of context
payload = [
{"role": "system", "content": DESC_SYSTEM},
{"role": "user", "content": prompt},
]
try:
_log_event("req", {"model": MODEL, "messages": payload,
"stream": False, "_purpose": "session_desc"})
resp = client.chat.completions.create(
model=MODEL, messages=payload, stream=False, timeout=20,
**(ACTIVE.extra_request_kwargs() if ACTIVE else {}))
try:
_log_event("resp", {"_purpose": "session_desc", "data": resp.model_dump()})
except Exception:
pass
except APIConnectionError:
return None # server down — leave existing description as-is
except Exception:
return None
desc = (resp.choices[0].message.content or "").strip().splitlines()
desc = desc[0].strip() if desc else ""
if not desc:
return None
desc = _safe_title(desc, maxlen=70) or desc[:70]
# Persist the description + the turn count it was generated at so we know
# when to refresh next. Merge into existing meta (don't clobber messages).
_write_session(session_id, messages, {"description": desc,
"desc_turns": user_turns})
return desc
def _resolve_session(target, sessions=None):
"""Resolve a user-typed target to a session id.
Accepts: a full id, a numeric index into the recent-sessions list,
a unique id prefix, or an exact title. Returns the id or None.
"""
if not target:
return None
target = target.strip()
sessions = sessions if sessions is not None else _list_sessions(limit=50)
ids = [s["id"] for s in sessions]
# numeric index → recent-sessions slot
if target.isdigit():
idx = int(target)
if 1 <= idx <= len(sessions):
return sessions[idx - 1]["id"]
# exact id
if target in ids:
return target
# unique prefix
prefixed = [i for i in ids if i.startswith(target)]
if len(prefixed) == 1:
return prefixed[0]
# short id (the 6-hex suffix shown in listings) — match the tail segment
# since the date+time prefix is shared/redundant across sessions created
# in the same minute.
suffixed = [i for i in ids if i.endswith("-" + target) or _short_id(i) == target]
if len(suffixed) == 1:
return suffixed[0]
# exact title
titled = [s["id"] for s in sessions if s["title"] == target]
if len(titled) == 1:
return titled[0]
return None
# --- model sources ----------------------------------------------------------
# minion talks to any OpenAI-compatible endpoint. A "source" bundles a
# base_url, api_key, and model name. Define sources with env vars:
#
# MINION_SOURCES=local,zai
# MINION_SOURCE_LOCAL_BASE_URL=http://localhost:8080/v1
# MINION_SOURCE_ZAI_BASE_URL=https://api.z.ai/api/paas/v4
# MINION_SOURCE_ZAI_API_KEY=$zai_test ← $name = look up env/file key
# MINION_SOURCE_ZAI_MODEL=glm-x-preview
#
# If no MINION_SOURCE_* vars are present, a single "local" source is built
# from the legacy MINION_BASE_URL / MINION_API_KEY / MINION_MODEL vars
# (same defaults as before, so existing setups keep working).
# Switch at runtime with /source.
class Source:
def __init__(self, name, base_url, api_key, model=None, extra_body=None,
http_headers=None):
self.name = name
self.base_url = base_url
self.api_key = api_key or "sk-noop"
self.model = model or None # None → ask the server at resolve time
# Default HTTP headers sent on every request. Used by aggregators like
# OpenRouter which read HTTP-Referer (your site URL) and X-Title (your
# app name) to identify the calling app in their dashboard. Ignored by
# non-consumers (llama.cpp, Together, …) so it's safe to always pass.
self.http_headers = http_headers or None
client_kwargs = {"base_url": base_url, "api_key": self.api_key}
if self.http_headers:
client_kwargs["default_headers"] = self.http_headers
self.client = OpenAI(**client_kwargs)
# Lazily-resolved max context window (in tokens) for the active model,
# or None when no probe could determine it. Cached after first success
# so the footer + /source list don't re-hit the network each turn.
# Call resolve_context_window(force=True) to re-probe (e.g. after a
# /source <name> <model> override pins a different model id).
self._context_window = None
# Per-request body fields the OpenAI SDK doesn't accept as kwargs, merged
# into every chat.completions.create() call via extra_body. The canonical
# use is OpenRouter provider routing — a `provider` object whose `order`
# picks which upstream serves a given model id (different providers back
# the same endpoint at different prices / precisions / latencies):
#
# {"provider": {"order": ["parasail/fp8"], "allow_fallbacks": false,
# "require_parameters": true, "data_collection": "deny"}}
#
# For local servers (llama.cpp) this is empty and contributes nothing;
# unknown keys are silently ignored by non-consumers, so it's safe to
# always pass it through. Set via MINION_SOURCE_<NAME>_EXTRA_BODY (a JSON
# string) or the /provider slash command (ephemeral, per-session).
self.extra_body = extra_body or None
def extra_request_kwargs(self):
"""extra_body kwarg to merge into every chat.completions.create(), or
{} when none is configured. Non-consumers ignore unknown body keys, so
this is a no-op for backends that don't understand it (llama.cpp,
Together, …)."""
if not self.extra_body:
return {}
return {"extra_body": dict(self.extra_body)}
# Server-advertised ids that carry no real identity — when /v1/models
# returns one of these (bare llama.cpp with no --alias, or a generic
# OpenAI-compat stub), fall through to a /props probe before giving up so
# saved sessions don't all collapse into a meaningless "local-model".
_GENERIC_MODEL_IDS = {"local-model", "model", "auto", "unknown", "gpt-3.5-turbo"}
@staticmethod
def _clean_model_id(advertised):
"""Shorten a server-advertised model id into a concise display name.
Only touches local-server ids that look like file paths (llama.cpp,
Ollama, …) where /v1/models returns the full GGUF/HF file path. Remote
API ids in org/model form (e.g. "zai-org/GLM-5.2") are returned
unchanged.
Examples:
/media/h/.../GLM-5.2-GGUF/UD-IQ4_NL/GLM-5.2-UD-IQ4_NL-00001-of-00009.gguf
→ GLM-5.2-UD-IQ4_NL
/models/Meta-Llama-3-8B-Instruct-Q4_K_M.gguf
→ Meta-Llama-3-8B-Instruct-Q4_K_M
Anything that doesn't look like a local model file path is returned
as-is so we never mangle a legitimate remote model id.
"""
if not advertised:
return advertised
# Only clean up local file paths — ones that end in a model file
# extension. Anything else (org/model, bare names) is passed through.
lower = advertised.lower()
if not any(lower.endswith(ext) for ext in (".gguf", ".bin", ".safetensors")):
return advertised
name = advertised.rsplit("/", 1)[-1]
# Strip shard suffix on multi-file quantizations
# (e.g. "-00001-of-00009")
name = re.sub(r"-\d{5}-of-\d{5}(?=$|\.)", "", name)
# Strip extension
for ext in (".gguf", ".bin", ".safetensors"):
if name.lower().endswith(ext):
name = name[: -len(ext)]
break
return name
def resolve_model(self):
if self.model:
return self.model
advertised = None
try:
advertised = self.client.models.list(timeout=10).data[0].id
except Exception:
advertised = None
if advertised and advertised.strip().lower() not in self._GENERIC_MODEL_IDS:
return self._clean_model_id(advertised)
# The endpoint gave us nothing useful. Many local servers (llama.cpp's
# llama-server) expose the actually-loaded model file at /props even
# when /v1/models only advertises a generic id — recover the real name
# (incl. quant) from there. Best-effort; any failure keeps the old value.
probed = self._probe_loaded_model()
return probed or advertised or "local-model"
def _probe_loaded_model(self):
"""Best-effort GET <server>/props for the loaded model path/alias.
llama.cpp serves /props at the root (not under /v1). Returns None on
any failure — never raises, never required, makes no assumption about
what (if anything) consumes minion's session metrics."""
try:
root = re.sub(r"/v\d+/?$", "", self.base_url.rstrip("/"))
with urllib.request.urlopen(root + "/props", timeout=5) as r:
props = json.loads(r.read().decode("utf-8"))
except Exception:
return None
for key in ("model_alias", "model_path", "model"):
val = props.get(key)
if isinstance(val, str) and val.strip() and \
val.strip().lower() not in self._GENERIC_MODEL_IDS:
return val.strip()
return None
def display_model(self):
return self.model or "auto"
# Regex for the provider-agnostic context-limit probe: Together (and any
# OpenAI-compat backend that mirrors OpenAI's error wording) rejects an
# over-large request with "This model's maximum context length is N tokens,
# but the request …". We send a deliberately over-sized max_tokens with a
# one-token prompt so the server tells us N without us ever generating.
_CTX_LIMIT_RE = re.compile(r"maximum context length is (\d+) tokens", re.IGNORECASE)
def _is_local(self):
"""True if this source points at a host on the local machine or LAN
(llama.cpp, Ollama, etc.) rather than a remote API (Together, Z.ai,
OpenAI, …). Local servers expose /v1/models meta and /props cheaply
(sub-millisecond LAN round-trips); remote hosts return empty lists or
404 there and waste a multi-second TLS round-trip, so the probe order
is flipped for them (over-max_tokens first)."""
host = (self.base_url or "").lower()
# strip the scheme
if "://" in host:
host = host.split("://", 1)[1]
host = host.split("/", 1)[0].split(":", 1)[0]
if not host:
return True # blank → assume local
if host in ("localhost", "0.0.0.0", "::1"):
return True
# 127.x.x.x / 10.x / 192.168.x / 169.254.x / 172.16-31.x are LAN
if re.match(r"^(127\.|10\.|192\.168\.|169\.254\.|172\.(1[6-9]|2[0-9]|3[01])\.)", host):
return True
return False
def resolve_context_window(self, model=None, force=False):
"""Best-effort max context window (tokens) for `model` on this source.
Returns the cached value if present (unless force=True), else probes
and caches. Never raises — any failure returns None and the footer
just omits the "/<max>" suffix. Probe order depends on host locality:
• Local (llama.cpp etc.) — /v1/models meta, then /props, then the
over-max_tokens chat probe. Local metadata endpoints are cheap
(sub-ms LAN) and llama.cpp stashes n_ctx in data[0].meta, so they
win on the first try.
• Remote (Together, Z.ai, OpenAI, …) — over-max_tokens chat probe
FIRST (one cheap request, ~0.1s, works for any OpenAI-compat
host that mirrors the "maximum context length is N tokens" 400),
then /v1/models as a fallback. Remote /v1/models often returns an
empty list or lacks context_length, and the TLS round-trip alone
costs 2-3s — leading with it added multi-second latency to the
background probe, so the first turn's footer rendered before the
max resolved. The chat probe resolves in well under a second.
`model` defaults to the source's configured model, falling back to a
live resolve_model() so an auto source is probed against the model it
will actually use. The result is keyed to that model id, so a
/source <name> <other-model> override should call with force=True.
A single probe attempt can hit a transient error — most notably
llama.cpp's 503 "Loading model" while the weights are still being
mmapped, which blocks /v1/models AND /props even though a chat slot
may already be serving. So a failed attempt does NOT cache None;
the caller (footer/listing) re-arms the probe on a later turn until
it resolves. Use force=True to retry immediately (e.g. an explicit
/source switch the user is waiting on)."""
if not force and self._context_window is not None:
return self._context_window
mid = model or self.model or self.resolve_model()
if self._is_local():
n = self._ctx_from_models(mid) or self._ctx_from_props()
if n is None:
n = self._ctx_from_overrun_probe(mid)
else:
# Remote: the over-max_tokens chat probe is cheap and universal;
# lead with it so the max resolves on the first turn instead of
# after a multi-second /v1/models round-trip that returns nothing.
n = self._ctx_from_overrun_probe(mid)
if n is None:
n = self._ctx_from_models(mid) or self._ctx_from_props()
if isinstance(n, int) and n > 0:
self._context_window = n
# NOTE: a miss does NOT set _context_window — stays None so the
# footer re-probes next turn (the server may have finished loading).
return self._context_window
def _ctx_from_models(self, mid):
"""Pull n_ctx / context_length from GET /v1/models. llama.cpp stashes
it under data[0].meta.n_ctx; some generic hosts expose context_length
as a top-level model field. Returns int or None."""
try:
data = self.client.models.list(timeout=10).data
except Exception:
return None
# Prefer the entry whose id matches the active model (multi-model
# hosts), else the first. Match loosely on a trailing token so a full
# path id ("…/GLM-5.2-…gguf") still hits a short alias ("GLM-5.2").
pick = None
if mid:
mtail = mid.rsplit("/", 1)[-1].lower()
for m in data:
if (m.id or "").lower() == mid.lower() or \
(m.id or "").rsplit("/", 1)[-1].lower() == mtail:
pick = m
break
if pick is None and data:
pick = data[0]
if pick is None:
return None
# OpenAI SDK preserves unknown fields in __pydantic_extra__.
extra = getattr(pick, "__pydantic_extra__", None) or {}
meta = extra.get("meta") if isinstance(extra, dict) else None
if isinstance(meta, dict):
for k in ("n_ctx", "context_length", "context_window",
"max_context_length", "max_input_tokens"):
v = meta.get(k)
if isinstance(v, int) and v > 0:
return v
# Some hosts put it directly on the model object (OpenAI-compat extra).
for k in ("context_length", "context_window", "max_context_length",
"max_input_tokens", "max_tokens", "max_model_len"):
v = extra.get(k) if isinstance(extra, dict) else None
if v is None:
v = getattr(pick, k, None)
if isinstance(v, int) and v > 0:
return v
return None
def _ctx_from_props(self):
"""llama.cpp /props fallback: default_generation_settings.n_ctx."""
try:
root = re.sub(r"/v\d+/?$", "", self.base_url.rstrip("/"))
with urllib.request.urlopen(root + "/props", timeout=5) as r:
props = json.loads(r.read().decode("utf-8"))
except Exception:
return None
dgs = props.get("default_generation_settings")
if isinstance(dgs, dict):
for k in ("n_ctx", "context_length", "context_window"):
v = dgs.get(k)
if isinstance(v, int) and v > 0:
return v
# Some builds put n_ctx at the top level of /props.
for k in ("n_ctx", "context_length", "context_window"):
v = props.get(k)
if isinstance(v, int) and v > 0:
return v
return None
def _ctx_from_overrun_probe(self, mid):
"""Send a chat completion with max_tokens far beyond any real context
and a 1-token prompt; parse the 400's "maximum context length is N
tokens" message. Works for Together and any host mirroring OpenAI's
over-limit wording. No tokens are generated (the request is rejected
before inference). Returns int or None."""
if not mid:
return None
try:
self.client.chat.completions.create(
model=mid,
messages=[{"role": "user", "content": "hi"}],
max_tokens=10_000_000,
stream=False,
timeout=30,
)
except Exception as e:
msg = str(e)
body = getattr(e, "body", None)
if isinstance(body, dict):
# Together nests it under body["message"]["message"]; OpenAI
# under body["error"]["message"]. Flatten to a string search.
msg = json.dumps(body) + " " + msg
m = self._CTX_LIMIT_RE.search(msg)
if m:
return int(m.group(1))
return None
def _resolve_api_key(val):
"""$name → look up env var (populated from ~/.env if present); else literal."""
if val and val.startswith("$"):
return os.environ.get(val[1:], "")
return val
def _parse_extra_body(raw):
"""Parse a MINION_SOURCE_<NAME>_EXTRA_BODY env value into a dict, or None.
Accepts a JSON object string and merges it into every chat request as the
OpenAI SDK's `extra_body` — the canonical channel for fields the SDK doesn't
model as top-level kwargs. The primary use case is OpenRouter provider
routing (a `provider` object whose `order` picks which upstream serves a
model id). Returns None on a blank/invalid value (with a stderr warning on
bad JSON) so a typo never silently drops routing — it fails loudly at load.
Example:
MINION_SOURCE_OR_EXTRA_BODY={"provider":{"order":["parasail/fp8"],"allow_fallbacks":false}}
"""
if not raw or not raw.strip():
return None
try:
obj = json.loads(raw)
except json.JSONDecodeError as e:
sys.stderr.write(
f"minion: ignoring bad MINION_*_EXTRA_BODY JSON ({e.msg} at "
f"char {e.pos}); provider routing is NOT set\n")
return None
if isinstance(obj, dict) and obj:
return obj
if isinstance(obj, dict):
return None # empty object {} → no routing, same as unset
sys.stderr.write(
"minion: MINION_*_EXTRA_BODY must be a JSON object, ignoring "
f"(got {type(obj).__name__}); provider routing is NOT set\n")
return None
def _build_http_headers(app_name=None, app_url=None):
"""Build default HTTP headers for API requests, for aggregators like
OpenRouter which read HTTP-Referer (your site URL) and X-Title (your app
name) to identify the calling app in their dashboard.
Set via MINION_SOURCE_<NAME>_APP_NAME and MINION_SOURCE_<NAME>_APP_URL.
Returns None when neither is provided so the OpenAI client is constructed
without default_headers (no overhead for non-aggregator sources).
"""
headers = {}
if app_url:
headers["HTTP-Referer"] = app_url
if app_name:
headers["X-Title"] = app_name
return headers or None
def _discover_sources():
"""Build SOURCES + SOURCE_ORDER from MINION_SOURCE_* env vars, falling
back to a single 'local' source from the legacy MINION_* vars."""
names = []
raw = os.environ.get("MINION_SOURCES", "")
if raw:
names = [n.strip() for n in raw.split(",") if n.strip()]
# auto-discover from MINION_SOURCE_<NAME>_BASE_URL if MINION_SOURCES absent
if not names:
prefix = "MINION_SOURCE_"
found = []
for k in os.environ:
if k.startswith(prefix) and k.endswith("_BASE_URL"):
found.append(k[len(prefix):-len("_BASE_URL")].lower())
names = sorted(found)
for name in names:
p = f"MINION_SOURCE_{name.upper()}_"
base_url = os.environ.get(p + "BASE_URL")
if not base_url:
continue
api_key = _resolve_api_key(os.environ.get(p + "API_KEY"))
model = os.environ.get(p + "MODEL")
extra_body = _parse_extra_body(os.environ.get(p + "EXTRA_BODY"))
# HTTP headers for aggregators like OpenRouter: HTTP-Referer (site
# URL) and X-Title (app name) identify the calling app in their
# dashboard. Set via MINION_SOURCE_<NAME>_APP_NAME /
# MINION_SOURCE_<NAME>_APP_URL.
http_headers = _build_http_headers(
os.environ.get(p + "APP_NAME"),
os.environ.get(p + "APP_URL"))
src = Source(name, base_url, api_key, model, extra_body=extra_body,
http_headers=http_headers)
SOURCES[name] = src
SOURCE_ORDER.append(name)
if not SOURCES:
# legacy fallback: one source from MINION_BASE_URL etc.
src = Source(
"local",
os.environ.get("MINION_BASE_URL", "http://localhost:8080/v1"),
os.environ.get("MINION_API_KEY", "sk-noop"),
os.environ.get("MINION_MODEL"),
)
SOURCES["local"] = src
SOURCE_ORDER.append("local")
# Built-in convenience source: Together AI. It's a multi-model host (you
# point it at any model by id), so unlike the local fallback it only
# appears when a key is actually available — and only when the user
# hasn't already defined a "together" source themselves (so an explicit
# MINION_SOURCE_TOGETHER_* config always wins). Registered last, so the
# user's first/source-listed source stays the default at startup and
# `/source together` (or `--source together`) is purely opt-in.
if "together" not in SOURCES:
together_key = _resolve_api_key(os.environ.get("TOGETHER_API_KEY", ""))
if together_key:
SOURCES["together"] = Source(
"together",
"https://api.together.xyz/v1",
together_key,
"zai-org/GLM-5.2", # default model; override per-switch via /source together <model>
)
SOURCE_ORDER.append("together")
# Built-in convenience source: OpenRouter. Like Together it's a multi-model
# host (you address any model by id), so it only registers when a key is
# available and only when the user hasn't defined an "openrouter" source
# themselves (an explicit MINION_SOURCE_OPENROUTER_* config always wins).
# Registered last, so it never displaces the user's default startup source —
# opt in with `/source openrouter` (or `--source openrouter`).
#
# The difference from Together is provider routing: OpenRouter fronts many
# upstream providers behind one model id, each with its own price / precision
# / latency / data-collection policy. Routing rides in the request body as a
# `provider` object (extra_body), so the built-in seeds it from
# MINION_SOURCE_OPENROUTER_EXTRA_BODY (a JSON string) if present, and the
# ephemeral /provider command can override it per-session. The default model
# is z-ai/glm-5.2; the default routing pins parasail/fp8 — cheap, fast, and a
# deliberate single-provider choice so you know exactly what's serving you.
if "openrouter" not in SOURCES:
or_key = _resolve_api_key(os.environ.get("OPENROUTER_API_KEY", ""))
if or_key:
or_body = _parse_extra_body(
os.environ.get("MINION_SOURCE_OPENROUTER_EXTRA_BODY", ""))
if or_body is None:
or_body = {"provider": {"order": ["parasail/fp8"],
"allow_fallbacks": False}}
or_headers = _build_http_headers(
os.environ.get("MINION_SOURCE_OPENROUTER_APP_NAME", "Minion"),
os.environ.get("MINION_SOURCE_OPENROUTER_APP_URL",
"https://github.com/Sentdex/minion"))
SOURCES["openrouter"] = Source(
"openrouter",
"https://openrouter.ai/api/v1",
or_key,
"z-ai/glm-5.2", # default model; override via /source openrouter <model>
extra_body=or_body,
http_headers=or_headers,
)
SOURCE_ORDER.append("openrouter")
SOURCES = {} # name → Source
SOURCE_ORDER = [] # preserve definition order for /source listing
ACTIVE = None # current Source
# `client` and `MODEL` are bare globals read throughout the file. They always
# mirror the active source; switch_source() reassigns both. Every function that
# needs them (open_stream, _assess_risk, compress, …) does a call-time global
# lookup, so a mid-session swap is picked up instantly — same pattern /yolo
# already uses for its own globals.
client = None
MODEL = None
# Updated by model_turn() on every turn that reports a prompt-token count
# (llama.cpp timings.prompt_n or OpenAI/Z.ai usage.prompt_tokens). Read by
# _maybe_autocompress() after a turn settles to decide whether the context
# window is full enough to warrant a silent auto-compress.
_LAST_PROMPT_TOKENS = 0
def switch_source(name, model_override=None):
"""Swap the active source. Reassigns client + MODEL globals. Returns True
on success, False (with a message) if the name is unknown.
`model_override` (optional) pins MODEL to a specific model id for this
switch instead of resolving the source's default — used by
`/source <name> <model>` so a multi-model host (e.g. Together) can be
pointed at any of its models without a config edit. A bare switch (no
override) always falls back to the source's configured/default model,
so `/source together` returns to GLM-5.2 even after an override."""
global ACTIVE, client, MODEL
src = SOURCES.get(name)
if not src:
print(f"{RED} ✗ unknown source {name!r}{RESET}")
return False
ACTIVE = src
client = src.client
MODEL = model_override if model_override else src.resolve_model()