-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
2492 lines (2236 loc) · 110 KB
/
Copy pathmain.py
File metadata and controls
2492 lines (2236 loc) · 110 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
import json
import os
import sys
import threading
import time
from pathlib import Path
from typing import Optional
from core.output import APP_VERSION, app_header, assistant_panel, emoji_supported, error_panel, info_panel, make_console, meta_line, normalize_text, remove_emoji_only, safe_text, section_rule, setup_windows_console, strip_emoji, styled_table, table_box, terminal_report
setup_windows_console()
import typer
from rich.console import Console
from rich.panel import Panel
from rich.table import Table
from core.api_client import KiloError, chat_completion, list_models, list_providers, stream_chat_completion
from mcpclient.config import add_server as mcp_add_server
from mcpclient.config import remove_server as mcp_remove_server
from mcpclient.config import get_server as mcp_get_server
from mcpclient.config import list_servers as mcp_list_servers
from mcpclient.manager import manager as mcp_manager, run_tool as mcp_run_tool
from mcpclient.manager import reload_sync as mcp_reload_sync, reload_if_stale_sync as mcp_reload_if_stale
import mcpclient.tools as mcp_tools_mod
from mcpclient import defaults as mcp_defaults
from core.chat import Conversation
from core.config import (
CACHE_DIR,
MODELS_CACHE_FILE,
MODELS_CACHE_TTL,
get_api_key,
get_base_url,
get_default_model,
get_sessions_dir,
set_default_model,
)
from core.store import add_message as db_add_message
from core.store import config_all as db_config_all
from core.store import config_get as db_config_get
from core.store import config_set as db_config_set
from core.store import create_session as db_create_session
from core.store import delete_session as db_delete_session
from core.store import get_session as db_get_session
from core.store import last_session_id as db_last_session
from core.store import list_sessions as db_list_sessions
from core.store import migrate_legacy_dir as db_migrate_legacy
from core.store import new_session_id as db_new_session_id
from core.store import set_last_session as db_set_last
from core.store import set_session_model as db_set_session_model
from core.models import Message, ModelInfo
app = typer.Typer(add_completion=False, rich_markup_mode="rich")
def _allow_emoji(explicit_no_emoji: bool = False) -> bool:
if explicit_no_emoji:
return False
if os.getenv("ZUMBA_NO_EMOJI", "") == "1":
return False
if os.getenv("ZUMBA_FORCE_EMOJI", "") == "1":
return True
return emoji_supported()
console: Console = make_console(_allow_emoji())
BANNER = "[bold white]ZUMBA[/] [dim]v1.1.0 · Personal AI Assistant · NIM[/]"
_WINDOW_CACHE: dict[str, dict] = {}
_WHY_LAST: dict[str, dict] = {}
_WHY_ON: dict[str, bool] = {}
def _why_store(session_id: str, query: str, text: str, hits: list) -> None:
_WHY_LAST[session_id] = {"query": query, "text": text or "", "hits": hits or []}
def _why_render(session_id: str) -> str:
data = _WHY_LAST.get(session_id) or {}
if not data.get("text") and not data.get("hits"):
return "No memory was injected on the last turn (nothing recalled)."
lines = [f"query: {data.get('query', '')}"]
hits = data.get("hits") or []
if not hits:
lines.append("(recall block came from core profile blocks, not scored hits)")
for i, h in enumerate(hits, 1):
meta = h.get("meta") or {}
ref = f" id={meta.get('id')}" if meta.get("id") is not None else ""
lines.append(f"{i}. [{h.get('kind')}] score={h.get('score')}{ref} :: {h.get('snippet', '')[:160]}")
return "\n".join(lines)
def _window_cache_for(msgs: list[Message]) -> dict:
"""Per-session rolling-summary cache, keyed by the session anchor (first
user message). Lets build_window reuse summaries across turns."""
import hashlib
anchor = next((m.content for m in msgs if m.role == "user"), "")
key = hashlib.sha256(anchor.encode("utf-8", errors="replace")).hexdigest()[:16]
return _WINDOW_CACHE.setdefault(key, {})
def _fit_window(msgs: list[Message]) -> list[Message]:
try:
from core.context_budget import build_window, get_context_limit
return build_window(msgs, model_limit=get_context_limit(), cache=_window_cache_for(msgs))
except Exception:
return msgs
_MEM = None
_MCP_DISABLE = os.getenv("ZUMBA_NO_MCP", "") == "1"
def _mcp():
"""Lazily-initialized MCP manager; None if disabled. Never crashes chat.
Set ZUMBA_NO_MCP=1 to disable entirely."""
if _MCP_DISABLE:
return None
try:
return mcp_manager()
except Exception:
return None
def _mcp_preamble(msgs: list[Message], tools: list) -> list[Message]:
"""Inject a tool description preamble as a system message before the last
user turn (like memory recall) for models without native function calling.
The behavioral note is generated from defaults and can be overridden via
the ZUMBA_MCP_SYSTEM_NOTE env var or the `mcp_system_note` config pref."""
preamble = mcp_tools_mod.system_preamble(tools)
if not preamble or not msgs:
return msgs
note = db_config_get("mcp_system_note", "") or mcp_defaults.SYSTEM_NOTE
sys_msg = Message(role="system", content=(
"Connected MCP tools (call them via the function/tool-call mechanism; "
"names are prefixed by their server):\n" + preamble +
"\n" + note.replace("{meta}", mcp_defaults.META_SERVER) +
"\nShell: zumba__shell_run executes UNRESTRICTED Windows PowerShell in one persistent "
"session (cwd/env persist) — chain state instead of re-stating it. "
"ALWAYS use PowerShell syntax: Get-ChildItem (never `ls -la`), Get-Content (never `cat`), "
"Get-Location (never `pwd`), Select-String (never `grep`). Bash flags like -la/-rf do not exist. "
"Soul files live at ~/.zumba/soul.md and ~/.zumba/user.md — read them with "
"Get-Content when the user asks what was drafted, never guess; never run `ls -la`. "
"Web: zumba__web_search / zumba__web_news / zumba__web_fetch are your realtime internet — "
"use them for anything time-sensitive instead of guessing; web_fetch the top result for depth. "
"Geo: zumba__geo_route for distance, zumba__geo_weather for rain, zumba__geo_geocode + "
"zumba__geo_nearby for 'places near X'; on 'heading to X' chain geocode → route (from "
"zumba__geo_whereami) → zumba__geo_traffic → weather at arrival → nearby → ONE briefing with "
"leave-by time, route, weather, personal context, maps link. "
"Vault: zumba__vault_search / zumba__vault_doc / zumba__vault_read answer from the user's local "
"documents — use them for 'what does my doc say / find the email' questions. Every document claim "
"MUST cite [Doc Title p.N]. zumba__vault_ask answers with citations; zumba__vault_status reports health. "
"Goals: zumba__goal_add / zumba__goal_list / zumba__goal_show / zumba__goal_complete_step / zumba__remind_add track "
"the user's stated intentions — create a goal when they say 'I want to ... by <date>' instead of "
"letting it fade; complete steps as they report progress. "
"Memory: zumba__memory_search before 'what do you remember' questions; zumba__memory_remember for durable facts; "
"zumba__memory_forget to invalidate. zumba__brief gives the daily briefing. "
"Identity: zumba__soul_show reads soul.md, zumba__me_show reads user.md — call them instead of guessing. "
"Soul rewrite: when the user asks to rewrite/change your soul, say yes and ask what to change; "
"then soul_show, draft the full file, soul_propose it, show soul_diff, and only soul_accept after explicit confirmation."
))
return msgs[:-1] + [sys_msg, msgs[-1]]
def _mcp_agent_turn(msgs: list[Message], model: str, key: str, max_tokens, temperature, allow_emoji: bool) -> tuple:
"""Run the MCP agent loop for one chat turn. Returns (reply, tools used, transcript)."""
from mcpclient.agent import run_agent_loop
mgr = mcp_manager()
tools = mgr.all_tools()
convo = _mcp_preamble(list(msgs), tools) if tools else list(msgs)
convo = _fit_window(convo)
used = {"n": 0}
transcript: list = []
def on_tool(name, args, result):
used["n"] += 1
shown = result[:400] + ("..." if len(result) > 400 else "")
args_s = json.dumps(args, ensure_ascii=False)[:200]
console.print(f"[dim] tool › [cyan]{safe_text(name, allow_emoji)}[/]({safe_text(args_s, allow_emoji)})[/]")
console.print(Panel(safe_text(shown, allow_emoji), title=f"TOOL · {safe_text(name, allow_emoji)}",
title_align="left", border_style="magenta", box=table_box(allow_emoji), padding=(0, 2)))
result = None
try:
result = run_agent_loop(
convo, model,
call_model=lambda ms, m, tools, **kw: chat_completion(
ms, m, api_key=key, tools=tools, max_tokens=max_tokens, temperature=temperature),
execute_tool=lambda name, args: mcp_run_tool(name, args),
tools=tools,
on_tool=on_tool,
transcript_out=transcript,
max_iterations=mcp_defaults.MAX_ITERATIONS,
)
except KiloError as exc:
if getattr(exc, "status_code", 0) in (400, 404, 500):
convo2 = _fit_window(list(msgs))
with console.status("[cyan]Retrying without tools...[/]", spinner="dots"):
plain = chat_completion(convo2, model, api_key=key, max_tokens=max_tokens, temperature=temperature)
console.print("[dim]Model rejected tool call; answered plain instead.[/]")
_print_assistant(plain.content, plain.model or model, allow_emoji, "")
return normalize_text(plain.content, allow_emoji), 0, []
raise
reply = result.content or ""
if not reply.strip() and used["n"]:
reply = result.content = "Did %d tool step(s) but the model gave no summary. Say 'continue' and I will carry on from the last tool result." % used["n"]
usage = getattr(result, "usage", None)
tokens = f"{usage.prompt_tokens} IN / {usage.completion_tokens} OUT" if usage and usage.total_tokens else ""
_print_assistant(reply, getattr(result, "model", "") or model, allow_emoji, tokens)
return normalize_text(reply, allow_emoji), used["n"], transcript
def _remember_tool_transcript(conv, transcript: list, keep: int = 10) -> None:
"""Persist tool exchanges into conversation history so follow-up turns see
prior tool results. Caps retained tool context to the latest `keep` entries."""
try:
for m in transcript or []:
conv.messages.append(m)
related = [m for m in conv.messages if m.role == "tool" or (m.role == "assistant" and m.tool_calls)]
while len(related) > keep:
conv.messages.remove(related.pop(0))
except Exception:
pass
def _save_tool_transcript(session_id: str, transcript: list) -> None:
"""Persist tool exchanges to the session DB so `continue` and `--resume`
keep tool context. Orphan-safe: resume folds these into a system digest
(see _fold_saved_tool_context) instead of sending bare tool messages."""
try:
for m in transcript or []:
content = (m.content or "").strip()
if m.role == "assistant" and not content:
content = "(tool call — see following tool result)"
db_add_message(session_id, m.role, content)
except Exception:
pass
def _fold_saved_tool_context(messages: list[Message]) -> list[Message]:
"""Fold saved tool exchanges into one system digest.
Bare `role=tool` messages (and their content-less assistant parents,
whose tool_calls don't survive the DB) would fail API validation if
replayed, so replace them with a system note carrying the results."""
try:
tools = [m for m in messages if m.role == "tool"]
if not tools:
return messages
lines = []
for m in tools[-8:]:
name = getattr(m, "name", "") or "tool"
lines.append(f"{name}: {(m.content or '').strip()[:300]}")
digest = Message(role="system", content=(
"Prior tool context from saved session (these tools already ran — "
"use these results instead of re-running blindly):\n" + "\n".join(lines)))
kept = [m for m in messages
if m.role != "tool" and not (m.role == "assistant" and not (m.content or "").strip())]
idx = 0
while idx < len(kept) and kept[idx].role == "system":
idx += 1
kept.insert(idx, digest)
return kept
except Exception:
return messages
def _memory():
"""Lazily-initialized memory service; None if disabled or unavailable.
Memory must never crash chat: every failure mode degrades to no memory.
Set ZUMBA_NO_MEMORY=1 to disable entirely.
"""
global _MEM
if os.getenv("ZUMBA_NO_MEMORY", "") == "1":
return None
if _MEM is None:
try:
from memory import get_memory
_MEM = get_memory()
except Exception:
_MEM = False
return _MEM or None
def _mem_capture(mem, session_id: str, user_text: str, reply: str, kind: str = "chat") -> None:
"""Queue the exchange for background ingestion (serialized worker thread),
then opportunistically consolidate (decay, note links, contradictions,
communities, core blocks). Never blocks or crashes the chat loop."""
try:
mem.capture_async(user_text, reply, session_id=session_id, kind=kind)
except Exception:
pass
def _soul_onboarding(allow_emoji: bool) -> None:
try:
from identity import soul as _soul
if not _soul.needs_bootstrap():
return
console.print(info_panel(
"First run — let's give Zumba a soul (30s, skippable).\n"
f"1. {_soul.BOOTSTRAP_QUESTIONS[0]}\n"
f"2. {_soul.BOOTSTRAP_QUESTIONS[1]}\n"
f"3. {_soul.BOOTSTRAP_QUESTIONS[2]}\n"
"Answer with: /soul init <how I should sound> | <keep in mind> | <off-limits>\n"
"Or: /soul wingit (I'll draft it from our first exchanges)",
title="SOUL", allow_emoji=allow_emoji))
except Exception:
pass
def _soul_chat_cmd(arg: str, allow_emoji: bool) -> bool:
from identity import soul as _soul
cmd = (arg or "").strip()
if cmd in ("", "show"):
text = _soul.load() or "(no soul.md yet — /soul wingit to draft one)"
console.print(Panel(safe_text(text[:6000], allow_emoji), title="SOUL",
title_align="left", border_style="cyan", box=_box(allow_emoji), padding=(0, 2)))
return True
if cmd == "wingit":
r = _soul.bootstrap_flow({"sound": "just wing it"})
console.print(section_rule(f"SOUL DRAFTED · {r.get('soul', '')}"))
return True
if cmd.startswith("init"):
rest = cmd[4:].strip()
parts = [p.strip() for p in rest.split("|")]
answers = {"sound": parts[0] if len(parts) > 0 else "", "keep": parts[1] if len(parts) > 1 else "",
"off_limits": parts[2] if len(parts) > 2 else ""}
if not any(answers.values()):
console.print(info_panel("Usage: /soul init <sound> | <keep in mind> | <off-limits>\nOr: /soul wingit",
title="SOUL", allow_emoji=allow_emoji))
return True
r = _soul.bootstrap_flow(answers)
console.print(section_rule(f"SOUL WRITTEN · {r.get('soul', '')}"))
return True
if cmd == "diff":
console.print(Panel(safe_text(_soul.diff_proposed(), allow_emoji), title="SOUL DIFF",
title_align="left", border_style="cyan", box=_box(allow_emoji), padding=(0, 2)))
return True
if cmd == "accept":
ok = _soul.apply_proposal()
console.print(section_rule("SOUL UPDATED" if ok else "NO PROPOSAL"))
return True
if cmd == "reject":
_soul.reject_proposal()
console.print(section_rule("SOUL PROPOSAL REJECTED"))
return True
if cmd.startswith("edit"):
import subprocess
editor = os.getenv("EDITOR", "notepad" if os.name == "nt" else "vi")
try:
subprocess.run([editor, str(_soul.soul_path())])
except Exception as exc:
console.print(error_panel(f"soul edit: {exc}", allow_emoji=allow_emoji))
return True
return False
def _session_reflect(mem, session_id: str) -> None:
try:
if mem is None:
return
mem.flush(timeout=60.0)
try:
from memory import db as _mdb
_mdb.ensure_tier2(mem._con if getattr(mem, "_con", None) is not None else _mdb.connect())
except Exception:
pass
exchanges: list = []
try:
con = mem._open()
try:
rows = con.execute(
"SELECT id, user_text, assistant_text FROM episodes WHERE session_id=? ORDER BY id", (session_id,)).fetchall()
exchanges = [{"user": r["user_text"], "assistant": r["assistant_text"], "episode_id": r["id"]} for r in rows]
finally:
if getattr(mem, "_own", True):
try:
con.close()
except Exception:
pass
except Exception:
exchanges = []
if not exchanges:
return
def _bg():
try:
mem.reflect_on_session(exchanges, session_id=session_id, use_llm=True)
except Exception:
pass
threading.Thread(target=_bg, daemon=True).start()
except Exception:
pass
def _header() -> Panel:
return app_header(_allow_emoji())
def _plain_system(system: str, allow_emoji: bool) -> str:
if allow_emoji or not system:
return system
return system.rstrip() + " Respond in plain text only. Do not use emojis or special symbols."
def _box(allow_emoji: bool):
return table_box(allow_emoji)
def _fail(message: str, hint: str = "") -> None:
console.print(error_panel(message, hint, _allow_emoji()))
raise typer.Exit(code=1)
def _cache_file():
try:
from core.config import get_models_cache_file
return get_models_cache_file()
except Exception:
return MODELS_CACHE_FILE
def _read_cache() -> Optional[list]:
try:
cache = _cache_file()
if not cache.exists():
# One-time migration from the old groq-specific cache file.
try:
from core.config import LEGACY_MODELS_CACHE_FILE
if LEGACY_MODELS_CACHE_FILE.exists():
cache = LEGACY_MODELS_CACHE_FILE
else:
return None
except Exception:
return None
age = time.time() - cache.stat().st_mtime
if age > MODELS_CACHE_TTL:
return None
return json.loads(cache.read_text(encoding="utf-8"))
except Exception:
return None
def _write_cache(data: list) -> None:
try:
cache = _cache_file()
cache.parent.mkdir(parents=True, exist_ok=True)
cache.write_text(json.dumps(data), encoding="utf-8")
except Exception:
pass
def _fetch_models(refresh: bool = False) -> list[ModelInfo]:
if not refresh:
cached = _read_cache()
if cached:
try:
return [ModelInfo.from_dict(m) for m in cached if isinstance(m, dict)]
except Exception:
pass
with console.status("Fetching models...", spinner="dots"):
try:
models = list_models()
except KiloError as exc:
_fail(str(exc))
_write_cache([m.to_dict() for m in models])
return models
def _models_table(models: list[ModelInfo], allow_emoji: bool = True) -> Table:
table = styled_table("AVAILABLE MODELS", allow_emoji)
table.add_column("#", style="dim", width=4, justify="right")
table.add_column("MODEL ID", style="cyan", no_wrap=False)
table.add_column("NAME", style="white")
table.add_column("CONTEXT", style="dim", justify="right")
table.add_column("COST", justify="center")
for i, m in enumerate(models, 1):
cost = "[bold green]FREE[/]" if m.is_free else "[dim]PAID[/]"
ctx = f"{m.context_length // 1000}K" if m.context_length else "-"
table.add_row(str(i), m.id, m.name[:52], ctx, cost)
return table
def _print_assistant(text: str, model: str = "", allow_emoji: bool = True, tokens: str = "") -> None:
shown = normalize_text(text, allow_emoji)
if not shown.strip():
console.print(info_panel("(empty response)", title="ASSISTANT", allow_emoji=allow_emoji))
return
console.print(assistant_panel(shown, model, allow_emoji, tokens))
def _stream_into_console(messages: list[Message], model: str, max_tokens: Optional[int], temperature: Optional[float], allow_emoji: bool = True) -> str:
from core.output import is_modern_terminal
full = ""
title = f"[bold white]ASSISTANT[/][dim]{' · ' + model if model else ''}[/]"
box_style = table_box(allow_emoji)
try:
gen = stream_chat_completion(messages, model, max_tokens=max_tokens, temperature=temperature)
if allow_emoji and is_modern_terminal():
from rich.live import Live
from rich.text import Text
live_panel = Panel(Text("", no_wrap=False), title=title, title_align="left", border_style="cyan", box=box_style, padding=(1, 2), expand=True)
with Live(live_panel, console=console, refresh_per_second=12, transient=False) as live:
for chunk in gen:
full += chunk
live.update(Panel(Text(full, no_wrap=False), title=title, title_align="left", border_style="cyan", box=box_style, padding=(1, 2), expand=True))
try:
live.update(assistant_panel(full, model, allow_emoji))
except Exception:
pass
return full
for chunk in gen:
full += chunk
try:
sys.stdout.write(normalize_text(chunk, allow_emoji))
sys.stdout.flush()
except Exception:
pass
try:
sys.stdout.write("\n")
sys.stdout.flush()
except Exception:
pass
final = normalize_text(full, allow_emoji)
try:
console.print(assistant_panel(final, model, allow_emoji))
except Exception:
pass
return final
except KiloError:
raise
@app.command("models")
def models_cmd(
free_only: bool = typer.Option(False, "--free/--all", help="Show only free models or all models (NIM has no free tier; --free matches legacy ':free' ids)."),
search: str = typer.Option("", "--search", "-s", help="Filter by id or name substring."),
limit: int = typer.Option(30, "--limit", "-n", help="Max rows to display."),
as_json: bool = typer.Option(False, "--json", help="Output raw JSON."),
refresh: bool = typer.Option(False, "--refresh", help="Ignore cache and refetch."),
no_emoji: bool = typer.Option(False, "--no-emoji", help="Strip emojis for legacy cmd."),
set_default: str = typer.Option("", "--set-default", help="Persist a model id as the default for new sessions."),
) -> None:
allow_emoji = _allow_emoji(no_emoji)
if set_default:
set_default_model(set_default.strip())
console.print(_header())
console.print(section_rule(f"DEFAULT MODEL · {get_default_model()}"))
return
models = _fetch_models(refresh=refresh)
if free_only:
models = [m for m in models if m.is_free]
if not models:
console.print(info_panel("Provider has no ':free' tier — showing all models instead.", title="MODELS", allow_emoji=allow_emoji))
models = _fetch_models(refresh=refresh)
if search:
q = search.lower()
models = [m for m in models if q in m.id.lower() or q in m.name.lower()]
if as_json:
console.print_json(json.dumps([m.to_dict() for m in models[:limit]]))
return
if not models:
console.print(info_panel("No models matched. Try: zumba models --all", title="MODELS", allow_emoji=allow_emoji))
return
console.print(_header())
console.print(_models_table([m for m in models[:limit]], allow_emoji))
console.print(section_rule(f"{len(models[:limit])} SHOWN · DEFAULT {get_default_model()}"))
@app.command("providers")
def providers_cmd(
as_json: bool = typer.Option(False, "--json", help="Output raw JSON."),
refresh: bool = typer.Option(False, "--refresh", help="Reserved flag for symmetry."),
) -> None:
del refresh
with console.status("Fetching providers...", spinner="dots"):
try:
data = list_providers()
except KiloError as exc:
_fail(str(exc))
if as_json:
console.print_json(json.dumps(data))
return
allow_emoji = _allow_emoji()
console.print(_header())
items = data.get("data", data) if isinstance(data, dict) else data
if not isinstance(items, list):
console.print_json(json.dumps(data))
return
table = styled_table("PROVIDERS", allow_emoji)
table.add_column("ID / NAME", style="cyan")
table.add_column("DETAILS", style="dim")
for p in items[:40]:
if isinstance(p, dict):
name = str(p.get("id", p.get("name", "?")))
info = str(p.get("description", p.get("status", "")) or "")[:72]
table.add_row(name, info)
else:
table.add_row(str(p), "")
console.print(table)
console.print(section_rule(f"{min(len(items), 40)} SHOWN"))
@app.command("ask")
def ask_cmd(
prompt: str = typer.Argument(..., help="Single question to ask."),
model: str = typer.Option("", "--model", "-m", help="Model id. Defaults to ZUMBA_MODEL or nvidia/nemotron-3-super-120b-a12b."),
system: str = typer.Option("You are Zumba, a concise helpful personal assistant.", "--system", "-s"),
no_stream: bool = typer.Option(False, "--no-stream", help="Disable streaming."),
max_tokens: Optional[int] = typer.Option(None, "--max-tokens"),
temperature: Optional[float] = typer.Option(None, "--temperature", "--temp"),
no_emoji: bool = typer.Option(False, "--no-emoji", help="Strip emojis for legacy cmd."),
) -> None:
allow_emoji = _allow_emoji(no_emoji)
chosen = (model or get_default_model()).strip()
try:
key = get_api_key(require=True)
except RuntimeError as exc:
_fail(str(exc), "Set ZUMBA_API_KEY first: https://build.nvidia.com")
return
base = get_base_url()
eff_system = _plain_system(system, allow_emoji)
msgs = [Message(role="system", content=eff_system), Message(role="user", content=prompt)] if eff_system else [Message(role="user", content=prompt)]
mem = _memory()
console.print(_header())
console.print(section_rule("REQUEST"))
console.print(f"{meta_line('Model', chosen)} {meta_line('Endpoint', base)}")
console.print(section_rule("RESPONSE"))
full_text = ""
try:
if no_stream:
with console.status("[cyan]Generating response...[/]", spinner="dots"):
result = chat_completion(msgs, chosen, api_key=key, max_tokens=max_tokens, temperature=temperature)
tokens = f"{result.usage.prompt_tokens} IN / {result.usage.completion_tokens} OUT" if result.usage.total_tokens else ""
full_text = result.content
_print_assistant(result.content, result.model or chosen, allow_emoji, tokens)
else:
full_text = _stream_into_console(msgs, chosen, max_tokens, temperature, allow_emoji)
if mem is not None and full_text:
_mem_capture(mem, "", prompt, full_text)
mem.flush(timeout=60.0)
except KiloError as exc:
_fail(str(exc))
except KeyboardInterrupt:
console.print("\n[dim]Interrupted.[/]")
@app.command("sessions")
def sessions_cmd(
search: str = typer.Option("", "--search", "-s", help="Full-text search across titles and messages."),
limit: int = typer.Option(20, "--limit", "-n"),
delete: str = typer.Option("", "--delete", help="Delete a session by id."),
show: str = typer.Option("", "--show", help="Show a session transcript by id."),
) -> None:
allow_emoji = _allow_emoji()
migrated = db_migrate_legacy(get_sessions_dir())
console.print(_header())
if delete:
found = _resolve_session_id(delete)
if not found:
_fail(f"Session not found: {delete}")
return
db_delete_session(found)
console.print(section_rule(f"DELETED · {found}"))
return
if show:
found = _resolve_session_id(show)
if not found:
_fail(f"Session not found: {show}")
return
data = db_get_session(found)
if not data:
_fail(f"Session not found: {show}")
return
console.print(section_rule(f"{data.get('title', '')} · {data.get('id', '')} · {data.get('model', '')}"))
for m in data.get("messages", []):
role = str(m.get("role", "")).upper()
body = str(m.get("content", ""))
if role == "USER":
console.print(f"[bold cyan]{role} ›[/] {safe_text(body[:2000], allow_emoji)}")
elif role == "ASSISTANT":
_print_assistant(body, str(data.get("model", "")), allow_emoji)
return
rows = db_list_sessions(limit=limit, search=search)
if migrated:
console.print(f"[dim]Imported {migrated} legacy file session(s) into the database.[/]")
if not rows:
console.print(info_panel("No saved sessions yet. Run: zumba chat", title="SESSIONS", allow_emoji=allow_emoji))
return
table = styled_table("SAVED SESSIONS", allow_emoji)
table.add_column("#", style="dim", width=4, justify="right")
table.add_column("TITLE", style="white")
table.add_column("MODEL", style="dim")
table.add_column("MSGS", justify="right", style="dim")
table.add_column("UPDATED", style="dim")
import datetime
for i, r in enumerate(rows, 1):
try:
mtime = datetime.datetime.fromtimestamp(float(r.get("updated_at", 0))).strftime("%m-%d %H:%M")
except Exception:
mtime = "-"
table.add_row(str(i), str(r.get("title", ""))[:42], str(r.get("model", ""))[:28], str(r.get("message_count", 0)), mtime)
console.print(table)
console.print(section_rule("RESUME WITH: zumba chat --resume <#> · SEARCH WITH: zumba sessions --search <text>"))
def _recent_sessions(limit: int = 50) -> list[dict]:
try:
return db_list_sessions(limit=limit)
except Exception:
return []
def _resolve_session_id(prefix: str) -> str:
prefix = (prefix or "").strip()
if not prefix:
return ""
if prefix.isdigit():
rows = _recent_sessions()
idx = int(prefix) - 1
if 0 <= idx < len(rows):
return str(rows[idx].get("id", ""))
return ""
direct = db_get_session(prefix)
if direct:
return str(direct.get("id", ""))
rows = _recent_sessions()
for r in rows:
if str(r.get("id", "")).startswith(prefix):
return str(r.get("id", ""))
lowered = prefix.lower()
for r in rows:
if lowered in str(r.get("title", "")).lower():
return str(r.get("id", ""))
return ""
def _render_history(conv: Conversation, chosen: str, allow_emoji: bool, header: str = "PREVIOUS MESSAGES") -> None:
past = [m for m in conv.messages if m.role in ("user", "assistant")]
if not past:
return
console.print(section_rule(f"{header} · {len(past)}"))
for m in past[-30:]:
body = normalize_text(m.content, allow_emoji)
if m.role == "user":
console.print(f"[bold cyan]YOU ›[/] {body[:1500]}")
else:
_print_assistant(body, chosen, allow_emoji)
console.print(section_rule("CONTINUING"))
def _pick_session_interactive(allow_emoji: bool) -> str:
rows = _recent_sessions(limit=15)
if not rows:
console.print(info_panel("No saved sessions yet.", title="SESSIONS", allow_emoji=allow_emoji))
return ""
table = styled_table("SAVED SESSIONS", allow_emoji)
table.add_column("#", style="dim", width=4, justify="right")
table.add_column("TITLE", style="white")
table.add_column("MODEL", style="dim")
table.add_column("MSGS", justify="right", style="dim")
for i, r in enumerate(rows, 1):
table.add_row(str(i), str(r.get("title", ""))[:44], str(r.get("model", ""))[:28], str(r.get("message_count", 0)))
console.print(table)
try:
choice = console.input("[bold cyan]Load # (number, Enter to stay) › [/]").strip()
except (KeyboardInterrupt, EOFError):
console.print()
return ""
if not choice:
return ""
found = _resolve_session_id(choice)
if not found:
console.print(error_panel(f"No session #{choice}.", allow_emoji=allow_emoji))
return ""
return found
@app.command("config")
def config_cmd(
set_model: str = typer.Option("", "--set-model", help="Persist default model for new sessions."),
set_system: str = typer.Option("", "--set-system", help="Persist default system prompt."),
set_style: str = typer.Option("", "--set-style", help="Persist persona style prefs (tone)."),
set_streaming: str = typer.Option("", "--set-streaming", help="on/off default for chat streaming."),
set_proactive: str = typer.Option("", "--set-proactive", help="Proactive nudges: off, or minutes between nudges (default 30)."),
clear: bool = typer.Option(False, "--clear", help="Clear saved preferences."),
) -> None:
allow_emoji = _allow_emoji()
console.print(_header())
if clear:
for k in ("default_model", "default_system", "streaming", "last_session"):
try:
db_config_set(k, "")
except Exception:
pass
console.print(section_rule("PREFERENCES CLEARED"))
return
if set_model:
set_default_model(set_model.strip())
if set_system:
db_config_set("default_system", set_system.strip())
if set_style:
db_config_set("style", set_style.strip())
if set_streaming:
db_config_set("streaming", "off" if set_streaming.strip().lower() in ("off", "0", "false", "no") else "on")
if set_proactive:
pv = set_proactive.strip().lower()
if pv in ("off", "0", "false", "no", "disable", "disabled"):
db_config_set("proactive", "off")
else:
try:
db_config_set("proactive", "on")
db_config_set("proactive_minutes", str(max(1, min(120, int(pv)))))
except Exception:
_fail("--set-proactive must be 'off' or minutes (1-120).")
return
if set_model or set_system or set_style or set_streaming or set_proactive:
console.print(section_rule("PREFERENCES SAVED"))
table = styled_table("PREFERENCES", allow_emoji)
table.add_column("KEY", style="cyan", no_wrap=True)
table.add_column("VALUE", style="white")
prefs = db_config_all()
table.add_row("default_model", prefs.get("default_model", "") or get_default_model())
table.add_row("default_system", (prefs.get("default_system", "") or "-")[:60])
table.add_row("style", (prefs.get("style", "") or "-")[:60])
table.add_row("streaming", prefs.get("streaming", "") or "on")
table.add_row("proactive", prefs.get("proactive", "") or "on")
table.add_row("proactive_minutes", prefs.get("proactive_minutes", "") or "30")
table.add_row("last_session", prefs.get("last_session", "") or "-")
table.add_row("ZUMBA_MODEL env", __import__("os").getenv("ZUMBA_MODEL", "") or "-")
console.print(table)
console.print(section_rule("ENV ZUMBA_MODEL OVERRIDES SAVED default_model"))
@app.command("chat")
def chat_cmd(
model: str = typer.Option("", "--model", "-m", help="Model id. Defaults to ZUMBA_MODEL or nvidia/nemotron-3-super-120b-a12b."),
system: str = typer.Option("You are Zumba, a concise helpful personal assistant.", "--system", "-s"),
resume: str = typer.Option("", "--resume", help="Resume a saved session by id, file path, or filename."),
last: bool = typer.Option(False, "--last", help="Resume the most recent session."),
no_stream: bool = typer.Option(False, "--no-stream", help="Disable streaming."),
max_tokens: Optional[int] = typer.Option(None, "--max-tokens"),
temperature: Optional[float] = typer.Option(None, "--temperature", "--temp"),
no_emoji: bool = typer.Option(False, "--no-emoji", help="Strip emojis for legacy cmd."),
) -> None:
allow_emoji = _allow_emoji(no_emoji)
db_migrate_legacy(get_sessions_dir())
saved_system = db_config_get("default_system", "")
from identity.persona import resolve_chat_system
system = resolve_chat_system(system, saved_system)
chosen = (model or get_default_model()).strip()
system = _plain_system(system, allow_emoji)
try:
key = get_api_key(require=True)
except RuntimeError as exc:
_fail(str(exc), "Set ZUMBA_API_KEY first: https://build.nvidia.com")
return
saved_streaming = db_config_get("streaming", "on")
conv: Conversation
session_id = ""
if last and not resume:
resume = db_last_session()
if not resume:
_fail("No previous session found.", "Start one with: zumba chat")
return
resumed_history = False
if resume:
if resume.strip().isdigit() or db_get_session(resume) is None:
resolved = _resolve_session_id(resume)
if resolved:
resume = resolved
data = db_get_session(resume)
if data:
resumed_history = True
session_id = str(data.get("id", ""))
chosen = (str(data.get("model", "")) or chosen)
system = str(data.get("system", "") or system)
conv = Conversation(model=chosen, system="")
conv.messages = []
for m in data.get("messages", []):
role = str(m.get("role", "user"))
content = str(m.get("content", ""))
if role == "system":
continue
conv.messages.append(Message(role=role, content=content))
conv.messages = _fold_saved_tool_context(conv.messages)
if system:
conv.messages.insert(0, Message(role="system", content=system))
conv.model = chosen
conv.system = system
else:
candidate = Path(resume)
if not candidate.exists():
candidate = get_sessions_dir() / resume
if not candidate.exists():
_fail(f"Session not found: {resume}", "Check with: zumba sessions")
return
try:
conv = Conversation.load(candidate)
chosen = conv.model or chosen
except Exception as exc:
_fail(f"Could not load session: {exc}")
return
session_id = db_new_session_id()
db_create_session(session_id, chosen, system, title="Imported file")
for m in conv.messages:
if m.role == "system":
continue
db_add_message(session_id, m.role, m.content)
else:
conv = Conversation(model=chosen, system=system)
session_id = db_new_session_id()
db_create_session(session_id, chosen, system)
conv.model = chosen
mem = _memory()
db_set_last(session_id)
if no_stream:
streaming = False
elif saved_streaming == "off":
streaming = False
else:
streaming = True
you_label = "YOU"
zumba_label = "ZUMBA"
console.print(_header())
console.print(section_rule("SESSION"))
mcp_header = _mcp()
mcp_note = f" {meta_line('MCP', f'{mcp_header.online_count()} online')}" if mcp_header is not None and mcp_header.servers else ""
console.print(
f"{meta_line('Model', chosen)} {meta_line('Streaming', 'ON' if streaming else 'OFF')} "
f"{meta_line('Emoji', 'ON' if allow_emoji else 'OFF')} {meta_line('Session', session_id[:12])}{mcp_note}"
)
console.print("[dim]Commands: /help · /models · /model <id> (saved) · /sessions · /load <#> · /new · /exit[/]")
if not allow_emoji:
console.print("[dim]Legacy console: emoji stripped. For full rendering use VS Code terminal or Windows Terminal. See: zumba doctor[/]")
if resumed_history:
_render_history(conv, chosen, allow_emoji)
else:
console.print(section_rule("CHAT"))
_soul_onboarding(allow_emoji)
try:
from memory import proactive as _pro
_pro.start()
except Exception:
pass
def show_help() -> None:
table = styled_table("COMMANDS", allow_emoji)
table.add_column("COMMAND", style="cyan", no_wrap=True)
table.add_column("DESCRIPTION", style="white")
table.add_row("/help", "Show this help")
table.add_row("/models", "List free models")
table.add_row("/model <id>", "Switch model (saved as default)")
table.add_row("/system <text>", "Set system prompt")
table.add_row("/clear", "Clear history")
table.add_row("/sessions", "Pick a saved session by number")
table.add_row("/load <#>", "Load a saved session by number")
table.add_row("/new", "Start a fresh session")
table.add_row("/stream", "Toggle streaming")
table.add_row("/emoji", "Toggle emoji stripping")
table.add_row("/remember <text>", "Store a fact in long-term memory")
table.add_row("/memory <query>", "Search long-term memory")
table.add_row("/why", "Explain the last turn's memory recall")
table.add_row("/forget <name>", "Invalidate facts about an entity")
table.add_row("/soul show|diff|accept|reject|edit|init|wingit", "Identity file (self-authored)")
table.add_row("/me", "Show your user profile (user.md)")
table.add_row("/brief", "Daily briefing from memory")
table.add_row("/mcp", "Show connected MCP servers + status")
table.add_row("/tools", "List all tools from connected MCP servers")
table.add_row("/shell <cmd>", "Run a shell command directly (god-mode, persistent)")
table.add_row("/search <q>", "Realtime web search (zero-key)")
table.add_row("/news <q>", "Realtime news via Google News RSS")
table.add_row("/fetch <url>", "Read a web page as text")
table.add_row("/vault ask|find|add|status|doc", "Local document vault")
table.add_row("/goal add|list|show|step ...", "Proactive goals")
table.add_row("/remind <text> --at <time>", "Schedule a reminder")
table.add_row("/tokens", "Show token estimate")
table.add_row("/exit, /quit", "Save and exit")
console.print(table)
while True:
try:
user_text = console.input("[bold cyan]YOU › [/]").strip()
except (KeyboardInterrupt, EOFError):
console.print("\n[dim]Saving and exiting...[/]")
break
if not user_text:
continue
_check_due_reminders(allow_emoji)
if user_text.startswith("/ "):