major-chat 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
major_chat/README.md ADDED
@@ -0,0 +1,19 @@
1
+ # major-chat
2
+
3
+ A full-screen terminal chat for **Major**, a very small language model.
4
+
5
+ ```
6
+ pip install major-chat
7
+ major-chat
8
+ ```
9
+
10
+ You need an account to use it. On first run it asks you to sign in or create one (username and password, no email), then opens the chat.
11
+ Chats are saved to your account, so `/resume` brings them back, including on another machine.
12
+
13
+ - Type `/` to see the commands; use the arrow keys to choose, Enter to run.
14
+ - `/model` choose the model (one today: `major-1`), `/theme` six colour themes (default `noir`), `/temp` and `/length` reply settings, `/resume` saved chats, `/new`, `/whoami`, `/logout`, `/quit`.
15
+ - Up and down scroll the conversation; `ctrl+p` and `ctrl+n` bring back earlier prompts; `ctrl+c` stops a reply.
16
+ - The window can be resized at any time.
17
+
18
+ The chat runs on a Major server. `major-chat` finds the current server link on its own; use `--api https://…` to point at a different one,
19
+ and `major-chat logout` to forget the saved sign-in. Major is a 43M-parameter model and gets facts wrong. It is an AI and can make mistakes.
major_chat/__init__.py ADDED
@@ -0,0 +1,2 @@
1
+ """Major terminal chat: a full-screen TUI for the Major 1 language model."""
2
+ __version__ = "0.1.0"
major_chat/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ main()
major_chat/app.py ADDED
@@ -0,0 +1,499 @@
1
+ """The full-screen chat UI (prompt_toolkit). Layout is recomputed on every redraw, so resizing the terminal just works."""
2
+ from __future__ import annotations
3
+
4
+ import re
5
+ import textwrap
6
+ import threading
7
+ import time
8
+
9
+ from prompt_toolkit.application import Application, get_app
10
+ from prompt_toolkit.buffer import Buffer
11
+ from prompt_toolkit.completion import Completer, Completion
12
+ from prompt_toolkit.filters import Condition
13
+ from prompt_toolkit.formatted_text import FormattedText
14
+ from prompt_toolkit.key_binding import KeyBindings
15
+ from prompt_toolkit.layout import (BufferControl, ConditionalContainer, Dimension, Float, FloatContainer, FormattedTextControl, HSplit, Layout, Window)
16
+ from prompt_toolkit.layout.menus import CompletionsMenu
17
+ from prompt_toolkit.layout.processors import BeforeInput
18
+ from prompt_toolkit.mouse_events import MouseEventType
19
+ from prompt_toolkit.styles import Style
20
+
21
+ from . import __version__
22
+ from .client import Api, ApiError, LocalEngine, new_chat_id, local_paths
23
+ from .config import save_settings
24
+ from .themes import DESCRIPTIONS, ORDER, style_dict
25
+
26
+ class ScrollText(FormattedTextControl):
27
+ """Transcript control that scrolls with the mouse wheel / trackpad (we keep our own scroll offset)."""
28
+ def __init__(self, *a, on_scroll=None, **k):
29
+ super().__init__(*a, **k); self.on_scroll = on_scroll
30
+
31
+ def mouse_handler(self, ev):
32
+ if ev.event_type == MouseEventType.SCROLL_UP: self.on_scroll(3); return None
33
+ if ev.event_type == MouseEventType.SCROLL_DOWN: self.on_scroll(-3); return None
34
+ return NotImplemented
35
+
36
+
37
+ COMMANDS = [
38
+ ("/new", "start a new chat"), ("/resume", "open a saved chat"), ("/model", "choose the model"), ("/mouse", "wheel scrolling on or off (off = select text freely)"), ("/theme", "choose a colour theme"), ("/temp", "temperature: steadier or more varied"),
39
+ ("/length", "maximum reply length"), ("/whoami", "show who you are signed in as"), ("/logout", "sign out and exit"), ("/help", "show commands and keys"),
40
+ ("/quit", "exit"),
41
+ ]
42
+ MARK = "▟▛"
43
+ THINK = re.compile(r"^\s*Thinking:\s*(.*?)(?:\s*\bAnswer:\s*(.*))?$", re.S)
44
+
45
+
46
+ class SlashCompleter(Completer):
47
+ def get_completions(self, document, complete_event):
48
+ t = document.text_before_cursor
49
+ if not t.startswith("/") or " " in t:
50
+ return
51
+ for name, desc in COMMANDS:
52
+ if name.startswith(t.lower()):
53
+ yield Completion(name, start_position=-len(t), display=name, display_meta=desc)
54
+
55
+
56
+ class Selector:
57
+ """A centred list you move through with the arrow keys. Enter picks, Esc cancels."""
58
+
59
+ def __init__(self):
60
+ self.title, self.items, self.index, self.cb, self.open = "", [], 0, None, False
61
+
62
+ def show(self, title, items, current, cb):
63
+ """items: [(label, value, description)]"""
64
+ self.title, self.items, self.cb, self.open = title, items, cb, True
65
+ self.index = next((i for i, it in enumerate(items) if it[1] == current), 0)
66
+
67
+ def fragments(self):
68
+ w = max([len(self.title)] + [len(i[0]) + len(i[2]) + 6 for i in self.items]) + 4
69
+ w = min(max(w, 34), 70)
70
+ out = [("class:menu.title", " " + self.title.ljust(w - 1) + "\n")]
71
+ for i, (label, value, desc) in enumerate(self.items):
72
+ sel = i == self.index
73
+ txt = f" {'›' if sel else ' '} {label}"
74
+ out.append(("class:menu.sel" if sel else "class:menu", txt.ljust(max(0, w - len(desc) - 2)) + (desc + " " if True else "")))
75
+ out[-1] = (out[-1][0], out[-1][1].ljust(w) + "\n")
76
+ out.append(("class:menu.dim", " ↑↓ choose · enter select · esc cancel".ljust(w) + "\n"))
77
+ return out[:-1] + [(out[-1][0], out[-1][1].rstrip("\n"))]
78
+
79
+
80
+ class ChatApp:
81
+ def __init__(self, api: Api | None, user: str, settings: dict, backend: str = "hosted", models=None):
82
+ self.api, self.user, self.s = api, user, settings
83
+ self.models = models or [{"id": "major-1", "desc": "43M parameters, 2-bit weights, remembers 512 tokens"}]
84
+ self.model_id = self.models[0]["id"]
85
+ self.msgs: list[dict] = [] # {role, text, meta}
86
+ self.chat_id, self.created = new_chat_id(), int(time.time() * 1000)
87
+ self.busy, self.cancel, self.err = False, threading.Event(), ""
88
+ self.off = 0 # lines scrolled up from the bottom
89
+ self.engine: LocalEngine | None = None
90
+ self.local = local_paths() if backend == "local" else None
91
+ self.selector = Selector()
92
+ self.notice, self.notice_t = "", 0.0
93
+ self.last_h = 20
94
+ self.quit_armed = 0.0
95
+ self.buf = Buffer(completer=SlashCompleter(), complete_while_typing=True, accept_handler=self._accept, multiline=False)
96
+ self.app = self._build()
97
+
98
+ # ------------------------------------------------------------- helpers
99
+ def say(self, text, secs=4):
100
+ self.notice, self.notice_t = text, time.time() + secs
101
+ self.app.invalidate()
102
+
103
+ def hist(self):
104
+ return [[m["u"], m["a"]] for m in self.pairs()]
105
+
106
+ def pairs(self):
107
+ out, u = [], None
108
+ for m in self.msgs:
109
+ if m["role"] == "user":
110
+ u = m["text"]
111
+ elif u is not None and not m.get("partial"):
112
+ out.append({"u": u, "a": m["text"]}); u = None
113
+ return out
114
+
115
+ # ------------------------------------------------------------- transcript
116
+ def transcript_lines(self, width):
117
+ W = max(20, width - 4)
118
+ lines = []
119
+
120
+ def add(frags):
121
+ lines.append(frags)
122
+
123
+ for i, m in enumerate(self.msgs):
124
+ if m["role"] == "user":
125
+ for j, ln in enumerate(self._wrap(m["text"], W - 2)):
126
+ add([("class:user", "› " if j == 0 else " "), ("", ln)])
127
+ add([])
128
+ else:
129
+ t = m["text"].strip()
130
+ mt = THINK.match(t) if t.startswith("Thinking:") else None
131
+ first = True
132
+ glyph = (MARK + " ") if not m.get("partial") else ("▚▞"[int(time.time() * 6) % 2] + " ")
133
+ if m.get("partial") and not t:
134
+ add([("class:accent", glyph), ("class:dim", "thinking")]); continue
135
+ if mt:
136
+ for ln in self._wrap(mt.group(1), W - 6):
137
+ add([("class:accent", glyph if first else " "), ("class:reasonbar", "│ "), ("class:reason", ln)]); first = False
138
+ if mt.group(2) is not None:
139
+ for ln in self._wrap(mt.group(2), W - 3):
140
+ add([("class:accent", glyph if first else " "), ("class:bot", ln)]); first = False
141
+ else:
142
+ for ln in self._wrap(t, W - 3):
143
+ add([("class:accent", glyph if first else " "), ("class:bot", ln)]); first = False
144
+ if m.get("partial"):
145
+ lines[-1] = lines[-1] + [("class:accent", "▌")]
146
+ elif m.get("meta"):
147
+ add([("", " "), ("class:faint", m["meta"])])
148
+ elif m.get("err"):
149
+ add([("", " "), ("class:err", m["err"])])
150
+ add([])
151
+ return lines
152
+
153
+ @staticmethod
154
+ def _wrap(text, width):
155
+ out = []
156
+ for para in text.split("\n") or [""]:
157
+ out += textwrap.wrap(para, width, break_long_words=True, replace_whitespace=False) or [""]
158
+ return out
159
+
160
+ def transcript_fragments(self):
161
+ size = get_app().output.get_size(); cols = size.columns
162
+ h = max(3, self.last_h)
163
+ lines = self.transcript_lines(cols)
164
+ if not lines:
165
+ return self.empty_screen(cols, h)
166
+ self.max_off = max(0, len(lines) - h)
167
+ self.off = min(max(0, self.off), self.max_off)
168
+ end = len(lines) - self.off
169
+ view = lines[max(0, end - h):end]
170
+ out = []
171
+ for ln in view:
172
+ out.append(("", " "))
173
+ out.extend(ln)
174
+ out.append(("", "\n"))
175
+ if self.off:
176
+ out.append(("class:faint", f" ↓ {self.off} more lines below (End to jump)"))
177
+ elif out:
178
+ out.pop() # trailing newline
179
+ return FormattedText(out)
180
+
181
+ def empty_screen(self, cols, h):
182
+ pad = max(0, (h - 8) // 2)
183
+ c = lambda s: max(0, (cols - len(s)) // 2)
184
+ rows = [[]] * pad
185
+ rows += [[("", " " * c("▟▛ M A J O R")), ("class:accent", "▟▛ M A J O R")], [],
186
+ [("", " " * c("How can I help?")), ("", "How can I help?")], [],
187
+ [("", " " * c("type / for commands")), ("class:faint", "type / for commands")]]
188
+ out = []
189
+ for r in rows:
190
+ out.extend(r); out.append(("", "\n"))
191
+ return FormattedText(out[:-1])
192
+
193
+ # ------------------------------------------------------------- chrome
194
+ def header(self):
195
+ cols = get_app().output.get_size().columns
196
+ mid = f" {self.model_id} · {self.s['theme']}"
197
+ left = [("class:accent", f" {MARK} MAJOR"), ("class:faint", mid)]
198
+ right = f"{self.user} " if self.user else ""
199
+ pad = max(1, cols - len(" ▟▛ MAJOR") - len(mid) - len(right))
200
+ return FormattedText(left + [("", " " * pad), ("class:dim", right)])
201
+
202
+ def status(self):
203
+ if self.notice and time.time() < self.notice_t:
204
+ return FormattedText([("class:accent", " " + self.notice)])
205
+ if self.busy:
206
+ return FormattedText([("class:dim", " generating · ctrl+c to stop")])
207
+ cols = get_app().output.get_size().columns
208
+ full = " Major is an AI and can make mistakes · / commands · ↑↓ scroll · ctrl+p/n earlier prompts"
209
+ return FormattedText([("class:faint", full if cols >= len(full) + 2 else " / commands · ↑↓ scroll · ctrl+c stop" if cols >= 42 else " / commands")])
210
+
211
+ def rule(self):
212
+ cols = get_app().output.get_size().columns
213
+ return FormattedText([("class:hr", "─" * cols)])
214
+
215
+ # ------------------------------------------------------------- input handling
216
+ def _accept(self, buf):
217
+ text = buf.text.strip()
218
+ buf.reset()
219
+ if not text:
220
+ return True
221
+ if text.startswith("/"):
222
+ self.command(text)
223
+ elif self.busy:
224
+ self.say("Wait for the reply to finish, or press ctrl+c to stop it.")
225
+ else:
226
+ self.send(text)
227
+ return True
228
+
229
+ def command(self, text):
230
+ cmd, _, arg = text[1:].partition(" ")
231
+ cmd = cmd.lower()
232
+ if cmd in ("quit", "exit", "q"):
233
+ self.app.exit()
234
+ elif cmd == "new":
235
+ self.new_chat()
236
+ elif cmd == "help":
237
+ self.help()
238
+ elif cmd == "model":
239
+ self.selector.show("Model", [(m["id"], m["id"], m.get("desc", "")) for m in self.models], self.model_id, self.set_model)
240
+ elif cmd == "mouse":
241
+ self.s["mouse"] = not self.s.get("mouse", True); save_settings(self.s)
242
+ self.say("mouse wheel scrolling on (hold shift or option to select text)" if self.s["mouse"] else "mouse wheel scrolling off")
243
+ elif cmd == "theme":
244
+ self.selector.show("Theme", [(n, n, DESCRIPTIONS[n]) for n in ORDER], self.s["theme"], self.set_theme)
245
+ elif cmd == "temp":
246
+ opts = [(f"{v:.1f}", v, d) for v, d in ((0.0, "most predictable"), (0.1, ""), (0.2, ""), (0.3, "default"), (0.5, "a little varied"), (0.7, "varied"), (1.0, "wild"))]
247
+ self.selector.show("Temperature", opts, self.s["temp"], self.set_temp)
248
+ elif cmd == "length":
249
+ opts = [(str(v), v, d) for v, d in ((60, "short"), (120, ""), (180, ""), (256, "default"), (320, "longest"))]
250
+ self.selector.show("Reply length (tokens)", opts, self.s["max_new"], self.set_len)
251
+ elif cmd == "resume":
252
+ self.resume()
253
+ elif cmd == "whoami":
254
+ self.say(f"signed in as {self.user}" if self.user else "not signed in")
255
+ elif cmd == "logout":
256
+ from .config import clear_auth
257
+ if self.api:
258
+ self.api.logout()
259
+ clear_auth(); self.app.exit(result="logout")
260
+ else:
261
+ self.say(f"unknown command /{cmd} · type / to see the list")
262
+
263
+ def help(self):
264
+ rows = [f" {n:<9} {d}" for n, d in COMMANDS] + ["", " wheel, ↑ ↓ pgup pgdn scroll the chat home / end top / bottom", " ctrl+p / ctrl+n earlier prompts ctrl+c stop a reply",
265
+ " ctrl+d quit tab complete a command"]
266
+ self.msgs.append({"role": "assistant", "text": "Commands\n" + "\n".join(rows), "meta": ""})
267
+ self.off = 0
268
+
269
+ def set_model(self, mid):
270
+ if mid != self.model_id:
271
+ self.model_id = mid; self._drop_engine()
272
+ self.say(f"model: {mid}")
273
+
274
+ def set_theme(self, name):
275
+ self.s["theme"] = name; save_settings(self.s)
276
+ self.app.style = Style.from_dict(style_dict(name)); self.say(f"theme: {name}")
277
+
278
+ def set_temp(self, v):
279
+ self.s["temp"] = v; save_settings(self.s); self.say(f"temperature {v:.1f}")
280
+
281
+ def set_len(self, v):
282
+ self.s["max_new"] = v; save_settings(self.s); self.say(f"reply length {v}")
283
+
284
+ def new_chat(self):
285
+ self.stop()
286
+ self.msgs.clear(); self.chat_id, self.created, self.off = new_chat_id(), int(time.time() * 1000), 0
287
+ self._drop_engine(); self.say("new chat")
288
+
289
+ def resume(self):
290
+ if not self.api:
291
+ return self.say("saved chats need an account")
292
+ try:
293
+ chats = self.api.chats()
294
+ except ApiError as e:
295
+ return self.say(str(e))
296
+ if not chats:
297
+ return self.say("no saved chats yet")
298
+ items = [((c.get("title") or "untitled")[:44], c, f"{len(c.get('turns', []))} turns") for c in chats[:30]]
299
+ self.selector.show("Saved chats", items, None, self.load_chat)
300
+
301
+ def load_chat(self, c):
302
+ self.stop(); self._drop_engine()
303
+ self.chat_id, self.created, self.off = c["id"], c.get("created") or int(time.time() * 1000), 0
304
+ self.msgs = []
305
+ for t in c.get("turns", []):
306
+ self.msgs.append({"role": "user", "text": t["u"]})
307
+ meta = t.get("meta") or {}
308
+ self.msgs.append({"role": "assistant", "text": t["a"], "meta": f"{meta['tokens']} tokens" if meta.get("tokens") else ""})
309
+ self.say("chat loaded")
310
+
311
+ # ------------------------------------------------------------- generation
312
+ def stop(self):
313
+ if self.busy:
314
+ self.cancel.set()
315
+
316
+ def _drop_engine(self):
317
+ if self.engine:
318
+ self.engine.close(); self.engine = None
319
+
320
+ def send(self, text):
321
+ self.err = ""
322
+ hist = self.hist()
323
+ self.msgs.append({"role": "user", "text": text})
324
+ self.msgs.append({"role": "assistant", "text": "", "partial": True})
325
+ self.busy, self.off = True, 0
326
+ self.cancel = threading.Event()
327
+ threading.Thread(target=self._run, args=(text, hist, self.cancel), daemon=True).start()
328
+ self.app.invalidate()
329
+
330
+ def _run(self, text, hist, cancel):
331
+ m = self.msgs[-1]
332
+ stats, full, stopped = None, "", False
333
+ try:
334
+ if self.local:
335
+ eng, mod = self.local
336
+ if not self.engine or self.engine.sig != (self.s["temp"], self.s["max_new"]) or self.engine.turns != len(hist):
337
+ self._drop_engine(); self.engine = LocalEngine(eng, mod, self.s["temp"], self.s["max_new"], hist)
338
+ gen = self.engine.ask(text, cancel)
339
+ else:
340
+ gen = self.api.stream(text, hist, self.s["temp"], self.s["max_new"], self.chat_id, cancel, self.model_id)
341
+ for full, stats in gen:
342
+ m["text"] = full
343
+ self.app.invalidate()
344
+ if cancel.is_set():
345
+ stopped = True
346
+ break
347
+ except ApiError as e:
348
+ m["err"] = str(e) + (" (type /logout to sign in again)" if e.status == 401 else "")
349
+ except Exception as e: # noqa: BLE001
350
+ m["err"] = f"error: {e}"
351
+ m["partial"] = False
352
+ if stopped:
353
+ self._drop_engine() # the engine cannot be interrupted: rebuild it from the saved turns next time
354
+ m["text"] = (full.strip() + " (stopped)") if full.strip() else "(stopped)"
355
+ m["partial"] = False
356
+ self.msgs.pop(-2) if False else None
357
+ elif stats:
358
+ tok, ms = stats
359
+ m["meta"] = f"{tok} tokens · {tok / max(ms, 1) * 1000:.0f} tok/s"
360
+ self.save_remote()
361
+ elif not m.get("text") and not m.get("err"):
362
+ m["err"] = "(no reply)"
363
+ self.busy = False
364
+ self.app.invalidate()
365
+
366
+ def save_remote(self):
367
+ if not self.api or not self.user:
368
+ return
369
+ pairs = self.pairs()
370
+ if not pairs:
371
+ return
372
+ turns = [{"u": p["u"], "a": p["a"], "meta": {}} for p in pairs]
373
+ title = pairs[0]["u"][:60]
374
+ try:
375
+ self.api.save_chat({"id": self.chat_id, "title": title, "model": "major-1", "created": self.created, "updated": int(time.time() * 1000), "turns": turns})
376
+ except ApiError:
377
+ pass # saving is best effort; the chat itself still works
378
+
379
+ # ------------------------------------------------------------- build
380
+ def _build(self):
381
+ kb = KeyBindings()
382
+ sel_open = Condition(lambda: self.selector.open)
383
+ has_comp = Condition(lambda: self.buf.complete_state is not None and bool(self.buf.complete_state.completions) and not self.selector.open)
384
+ plain = ~sel_open & ~has_comp
385
+
386
+ @kb.add("up", filter=sel_open, eager=True)
387
+ def _(e): self.selector.index = (self.selector.index - 1) % len(self.selector.items)
388
+
389
+ @kb.add("down", filter=sel_open, eager=True)
390
+ def _(e): self.selector.index = (self.selector.index + 1) % len(self.selector.items)
391
+
392
+ @kb.add("enter", filter=sel_open, eager=True)
393
+ def _(e):
394
+ it = self.selector.items[self.selector.index]; cb = self.selector.cb
395
+ self.selector.open = False
396
+ if cb:
397
+ cb(it[1])
398
+
399
+ @kb.add("escape", filter=sel_open, eager=True)
400
+ @kb.add("q", filter=sel_open, eager=True)
401
+ def _(e): self.selector.open = False
402
+
403
+ @kb.add("up", filter=has_comp, eager=True)
404
+ def _(e): self.buf.complete_previous()
405
+
406
+ @kb.add("down", filter=has_comp, eager=True)
407
+ def _(e): self.buf.complete_next()
408
+
409
+ @kb.add("enter", filter=has_comp, eager=True)
410
+ def _(e):
411
+ st = self.buf.complete_state
412
+ c = st.current_completion or st.completions[0]
413
+ self.buf.cancel_completion() if st.current_completion else None
414
+ self.buf.text = c.text
415
+ self.buf.validate_and_handle()
416
+
417
+ @kb.add("tab", filter=has_comp, eager=True)
418
+ def _(e):
419
+ st = self.buf.complete_state
420
+ self.buf.apply_completion(st.current_completion or st.completions[0])
421
+
422
+ @kb.add("escape", filter=has_comp, eager=True)
423
+ def _(e): self.buf.cancel_completion(); self.buf.reset()
424
+
425
+ def scroll(n):
426
+ self.off = max(0, self.off + n)
427
+
428
+ @kb.add("up", filter=plain, eager=True)
429
+ def _(e): scroll(1)
430
+
431
+ @kb.add("down", filter=plain, eager=True)
432
+ def _(e): scroll(-1)
433
+
434
+ @kb.add("pageup", filter=~sel_open, eager=True)
435
+ def _(e): scroll(max(3, self.last_h - 2))
436
+
437
+ @kb.add("pagedown", filter=~sel_open, eager=True)
438
+ def _(e): scroll(-max(3, self.last_h - 2))
439
+
440
+ @kb.add("home", filter=plain & Condition(lambda: not self.buf.text), eager=True)
441
+ def _(e): self.off = 10 ** 6
442
+
443
+ @kb.add("end", filter=plain & Condition(lambda: not self.buf.text), eager=True)
444
+ def _(e): self.off = 0
445
+
446
+ @kb.add("c-p", filter=~sel_open)
447
+ def _(e): self.buf.history_backward()
448
+
449
+ @kb.add("c-n", filter=~sel_open)
450
+ def _(e): self.buf.history_forward()
451
+
452
+ @kb.add("c-c", eager=True)
453
+ def _(e):
454
+ if self.selector.open:
455
+ self.selector.open = False
456
+ elif self.busy:
457
+ self.stop(); self.say("stopped")
458
+ elif self.buf.text:
459
+ self.buf.reset()
460
+ elif time.time() - self.quit_armed < 2:
461
+ e.app.exit()
462
+ else:
463
+ self.quit_armed = time.time(); self.say("press ctrl+c again (or ctrl+d) to quit")
464
+
465
+ @kb.add("c-d", eager=True)
466
+ def _(e): e.app.exit()
467
+
468
+ transcript = Window(ScrollText(self.transcript_fragments, focusable=False, on_scroll=scroll), wrap_lines=False, always_hide_cursor=True, style="class:root")
469
+ self.transcript = transcript
470
+ inp = Window(BufferControl(self.buf, input_processors=[BeforeInput([("class:accent", "› ")])]), height=Dimension(min=1, max=1), wrap_lines=False, style="class:root")
471
+ selw = ConditionalContainer(Window(FormattedTextControl(self.selector.fragments), width=Dimension(min=34, max=72), height=Dimension(min=3), style="class:menu"), filter=Condition(lambda: self.selector.open))
472
+ body = HSplit([
473
+ Window(FormattedTextControl(self.header), height=1, style="class:root"),
474
+ transcript,
475
+ Window(FormattedTextControl(self.rule), height=1, style="class:root"),
476
+ inp,
477
+ Window(FormattedTextControl(self.rule), height=1, style="class:root"),
478
+ Window(FormattedTextControl(self.status), height=1, style="class:root"),
479
+ ], style="class:root")
480
+ root = FloatContainer(body, style="class:root", floats=[
481
+ Float(xcursor=True, ycursor=True, content=CompletionsMenu(max_height=9, scroll_offset=1), transparent=False),
482
+ Float(content=selw),
483
+ ])
484
+ app = Application(layout=Layout(root, focused_element=inp), key_bindings=kb, style=Style.from_dict(style_dict(self.s["theme"])), full_screen=True,
485
+ refresh_interval=0.12, mouse_support=Condition(lambda: self.s.get("mouse", True)), erase_when_done=True)
486
+
487
+ def after_render(_):
488
+ ri = transcript.render_info
489
+ if ri and ri.window_height != self.last_h:
490
+ self.last_h = ri.window_height
491
+ app.invalidate()
492
+ app.after_render += after_render
493
+ return app
494
+
495
+ def run(self):
496
+ try:
497
+ return self.app.run()
498
+ finally:
499
+ self._drop_engine()
major_chat/cli.py ADDED
@@ -0,0 +1,104 @@
1
+ """major-chat: entry point. Signs you in (an account is required), then opens the full-screen chat.
2
+
3
+ major-chat sign in if needed, then chat
4
+ major-chat --local use the local engine instead of the hosted server (needs a source checkout, built engine and model file)
5
+ major-chat --api URL use another server
6
+ major-chat logout forget the saved sign-in
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import getpass
12
+ import sys
13
+
14
+ from . import __version__
15
+ from .client import Api, ApiError, local_paths
16
+ from .config import clear_auth, load_auth, load_settings, resolve_link, save_auth, save_settings
17
+
18
+
19
+ def ask(label, secret=False):
20
+ try:
21
+ return (getpass.getpass(label) if secret else input(label)).strip() if not secret else getpass.getpass(label)
22
+ except (EOFError, KeyboardInterrupt):
23
+ print(); raise SystemExit(1)
24
+
25
+
26
+ def sign_in(link) -> tuple[Api, str]:
27
+ """Use the saved token if it still works, otherwise ask the user to sign in or create an account."""
28
+ saved = load_auth()
29
+ if saved.get("token") and saved.get("link") == link:
30
+ api = Api(link, saved["token"])
31
+ try:
32
+ return api, api.me()
33
+ except ApiError as e:
34
+ if e.status not in (401, 403):
35
+ raise SystemExit(f"Cannot reach the Major server at {link}\n {e}\n(it may be offline, or you may not be on its network. Use --api URL for another server.)")
36
+ clear_auth()
37
+ print("\n MAJOR · sign in to chat\n")
38
+ while True:
39
+ choice = (ask(" [l] sign in [c] create an account [q] quit > ") or "l").lower()[:1]
40
+ if choice == "q":
41
+ raise SystemExit(0)
42
+ if choice not in ("l", "c"):
43
+ continue
44
+ user = ask(" username: ")
45
+ pw = ask(" password: ", secret=True)
46
+ if choice == "c":
47
+ if ask(" repeat password: ", secret=True) != pw:
48
+ print(" passwords do not match\n"); continue
49
+ api = Api(link)
50
+ try:
51
+ r = api.signup(user, pw) if choice == "c" else api.login(user, pw)
52
+ except ApiError as e:
53
+ print(f" {e}\n")
54
+ if not e.status:
55
+ raise SystemExit(1)
56
+ continue
57
+ api.token = r["token"]
58
+ save_auth({"link": link, "token": r["token"], "user": r["user"]})
59
+ print(f" signed in as {r['user']}\n")
60
+ return api, r["user"]
61
+
62
+
63
+ def main(argv=None):
64
+ ap = argparse.ArgumentParser(prog="major-chat", description="Chat with Major in your terminal.")
65
+ ap.add_argument("command", nargs="?", choices=["chat", "login", "logout"], default="chat")
66
+ ap.add_argument("--api", default="", help="server URL (default: the current link)")
67
+ ap.add_argument("--local", action="store_true", help="use the local engine (source checkout only)")
68
+ ap.add_argument("--theme", default="", help="start with this theme")
69
+ ap.add_argument("--version", action="version", version=f"major-chat {__version__}")
70
+ a = ap.parse_args(argv)
71
+ if a.command == "logout":
72
+ clear_auth(); print("signed out"); return
73
+ link = resolve_link(a.api)
74
+ if not link:
75
+ link = ask("Server URL (the Major link): ").rstrip("/")
76
+ if not link:
77
+ raise SystemExit("no server link")
78
+ s = load_settings()
79
+ if a.api:
80
+ s["link"] = link
81
+ if a.theme:
82
+ s["theme"] = a.theme
83
+ api, user = sign_in(link)
84
+ save_settings(s)
85
+ if a.command == "login":
86
+ return
87
+ if a.local and not local_paths():
88
+ raise SystemExit("--local needs a source checkout with a built engine and models/major-1.cact (see install_tui.sh)")
89
+ from .app import ChatApp
90
+ while True:
91
+ try:
92
+ models = api.models()
93
+ except ApiError:
94
+ models = None
95
+ if a.local and models: # the King-1 Preview is server only: offline mode has just the chip model
96
+ models = [m for m in models if m["id"] == "major-1"] or None
97
+ r = ChatApp(api, user, s, "local" if a.local else "hosted", models).run()
98
+ if r == "logout":
99
+ print("signed out"); return
100
+ return
101
+
102
+
103
+ if __name__ == "__main__":
104
+ main()
major_chat/client.py ADDED
@@ -0,0 +1,165 @@
1
+ """Talking to the Major server (accounts, saved chats, streamed replies) and to a local engine."""
2
+ from __future__ import annotations
3
+
4
+ import codecs
5
+ import json
6
+ import os
7
+ import re
8
+ import subprocess
9
+ import urllib.error
10
+ import urllib.request
11
+ import uuid
12
+
13
+ from .config import repo_root
14
+
15
+ MODEL = "major-1"
16
+
17
+
18
+ class ApiError(Exception):
19
+ def __init__(self, msg, status=0):
20
+ super().__init__(msg)
21
+ self.status = status
22
+
23
+
24
+ class Api:
25
+ def __init__(self, link: str, token: str = ""):
26
+ self.link, self.token = link.rstrip("/"), token
27
+
28
+ def _open(self, method, path, body=None, timeout=30):
29
+ h = {"Content-Type": "application/json", "X-Major-Client": "tui"}
30
+ if self.token:
31
+ h["Authorization"] = "Bearer " + self.token
32
+ req = urllib.request.Request(self.link + path, None if body is None else json.dumps(body).encode(), h, method=method)
33
+ try:
34
+ return urllib.request.urlopen(req, timeout=timeout)
35
+ except urllib.error.HTTPError as e:
36
+ try:
37
+ msg = json.loads(e.read()).get("detail", "")
38
+ except Exception: # noqa: BLE001
39
+ msg = ""
40
+ raise ApiError(msg or f"server said {e.code}", e.code)
41
+ except (urllib.error.URLError, OSError) as e:
42
+ raise ApiError(f"cannot reach {self.link} ({getattr(e, 'reason', e)})")
43
+
44
+ def call(self, method, path, body=None):
45
+ with self._open(method, path, body) as r:
46
+ return json.loads(r.read() or b"{}")
47
+
48
+ def signup(self, user, pw):
49
+ return self.call("POST", "/api/auth/signup", {"username": user, "password": pw})
50
+
51
+ def login(self, user, pw):
52
+ return self.call("POST", "/api/auth/login", {"username": user, "password": pw})
53
+
54
+ def me(self):
55
+ return self.call("GET", "/api/me")["user"]
56
+
57
+ def logout(self):
58
+ try:
59
+ self.call("POST", "/api/auth/logout")
60
+ except ApiError:
61
+ pass
62
+
63
+ def chats(self):
64
+ return self.call("GET", "/api/chats")["chats"]
65
+
66
+ def models(self):
67
+ return self.call("GET", "/api/models")["models"]
68
+
69
+ def save_chat(self, doc):
70
+ return self.call("PUT", "/api/chats/" + doc["id"], doc)
71
+
72
+ def delete_chat(self, cid):
73
+ return self.call("DELETE", "/api/chats/" + cid)
74
+
75
+ def stream(self, text, hist, temp, max_new, chat_id, cancel, model=MODEL):
76
+ """Yield (text_so_far, None) while streaming, then (text, (tokens, ms))."""
77
+ body = {"chat_id": chat_id, "model": model, "temp": temp, "max_new": max_new, "history": hist, "message": text}
78
+ full = ""
79
+ r = self._open("POST", "/api/chat", body, timeout=180)
80
+ try:
81
+ for line in r:
82
+ if cancel.is_set():
83
+ return
84
+ try:
85
+ ev = json.loads(line)
86
+ except ValueError:
87
+ continue
88
+ if "t" in ev:
89
+ full += ev["t"]
90
+ yield full, None
91
+ elif ev.get("done"):
92
+ yield full, (ev["tokens"], ev["ms"])
93
+ return
94
+ elif ev.get("error"):
95
+ raise ApiError(ev["error"])
96
+ finally:
97
+ r.close()
98
+
99
+
100
+ # ------------------------------------------------------------------ local engine (source checkout with a built engine and a model file)
101
+ DONE = re.compile(r"\n\[(\d+) tokens, (\d+) ms host\]\n> $")
102
+
103
+
104
+ def one_line(t, cap=1000):
105
+ return " ".join(str(t).split())[:cap]
106
+
107
+
108
+ def local_paths():
109
+ root = repo_root() or os.environ.get("MAJOR_HOME")
110
+ if not root:
111
+ return None
112
+ eng = next((p for p in (os.path.join(root, "build", "host", n) for n in ("nd_serve", "nd_chat")) if os.path.exists(p)), None)
113
+ mod = next((p for p in (os.path.join(root, d, "major-1.cact") for d in ("models", "")) if os.path.exists(p)), None)
114
+ return (eng, mod) if eng and mod else None
115
+
116
+
117
+ class LocalEngine:
118
+ """One nd_serve / nd_chat process holding the conversation; restarted with /feed when settings change or a reply is stopped."""
119
+
120
+ def __init__(self, engine, model, temp, max_new, history):
121
+ self.sig = (temp, max_new)
122
+ cmd = [engine, model, "--temp", str(temp), "--max-new", str(max_new)] + (["--threads", "2"] if engine.endswith("nd_serve") else [])
123
+ self.p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, bufsize=0)
124
+ self._until_prompt()
125
+ for u, a in history:
126
+ self.p.stdin.write(f"/feed {one_line(u)}\t{one_line(a, 2000)}\n".encode()); self.p.stdin.flush()
127
+ self._until_prompt()
128
+ self.turns = len(history)
129
+
130
+ def _until_prompt(self):
131
+ buf, dec = "", codecs.getincrementaldecoder("utf-8")("replace")
132
+ while not buf.endswith("> "):
133
+ c = os.read(self.p.stdout.fileno(), 4096)
134
+ if not c:
135
+ raise ApiError("local engine exited")
136
+ buf += dec.decode(c)
137
+
138
+ def ask(self, text, cancel):
139
+ self.p.stdin.write((one_line(text) + "\n").encode()); self.p.stdin.flush()
140
+ dec, buf = codecs.getincrementaldecoder("utf-8")("replace"), ""
141
+ while True:
142
+ c = os.read(self.p.stdout.fileno(), 4096)
143
+ if not c:
144
+ raise ApiError("local engine exited")
145
+ buf += dec.decode(c)
146
+ m = DONE.search(buf)
147
+ if m:
148
+ self.turns += 1
149
+ yield buf[:m.start()], (int(m.group(1)), int(m.group(2)))
150
+ return
151
+ cut = buf.rfind("\n")
152
+ tail = buf[cut + 1:] if cut >= 0 else None
153
+ yield (buf[:cut] if tail is not None and (tail == "" or tail.startswith("[")) else buf), None
154
+ if cancel.is_set():
155
+ return
156
+
157
+ def close(self):
158
+ try:
159
+ self.p.stdin.close(); self.p.terminate(); self.p.wait(3)
160
+ except Exception: # noqa: BLE001
161
+ self.p.kill()
162
+
163
+
164
+ def new_chat_id():
165
+ return "tui" + uuid.uuid4().hex[:14]
major_chat/config.py ADDED
@@ -0,0 +1,82 @@
1
+ """Where the terminal chat keeps its settings and sign-in, and how it finds the chat server ("the current link")."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import os
6
+ import urllib.request
7
+
8
+ CONFIG_DIR = os.path.join(os.environ.get("XDG_CONFIG_HOME") or os.path.expanduser("~/.config"), "major-chat")
9
+ SETTINGS = os.path.join(CONFIG_DIR, "settings.json")
10
+ AUTH = os.path.join(CONFIG_DIR, "auth.json")
11
+ # Public pointer to the current backend (the static site publishes it). Used only when nothing else says where the server is.
12
+ POINTER = "https://yixuanxu-ai.github.io/major/config.json"
13
+ DEFAULTS = {"theme": "noir", "temp": 0.3, "max_new": 256}
14
+
15
+
16
+ def _read(path, default):
17
+ try:
18
+ with open(path) as f:
19
+ return json.load(f)
20
+ except Exception: # noqa: BLE001
21
+ return default
22
+
23
+
24
+ def _write(path, data, private=False):
25
+ os.makedirs(CONFIG_DIR, exist_ok=True)
26
+ tmp = path + ".tmp"
27
+ with open(tmp, "w") as f:
28
+ json.dump(data, f, indent=1)
29
+ if private:
30
+ os.chmod(tmp, 0o600)
31
+ os.replace(tmp, path)
32
+
33
+
34
+ def load_settings() -> dict:
35
+ s = {**DEFAULTS, **_read(SETTINGS, {})}
36
+ if s.get("max_new") == 120: # the old default
37
+ s["max_new"] = 256
38
+ if s.get("theme") == "major": # renamed
39
+ s["theme"] = "noir"
40
+ return s
41
+
42
+
43
+ def save_settings(s: dict):
44
+ _write(SETTINGS, s)
45
+
46
+
47
+ def load_auth() -> dict:
48
+ return _read(AUTH, {})
49
+
50
+
51
+ def save_auth(a: dict):
52
+ _write(AUTH, a, private=True) # the token is a credential: owner-only file
53
+
54
+
55
+ def clear_auth():
56
+ try:
57
+ os.remove(AUTH)
58
+ except FileNotFoundError:
59
+ pass
60
+
61
+
62
+ def repo_root():
63
+ """The source checkout this package lives in (has web/ and build/), or None for a pip install."""
64
+ root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
65
+ return root if os.path.isdir(os.path.join(root, "web")) else None
66
+
67
+
68
+ def resolve_link(cli_value: str = "") -> str:
69
+ """--api, $MAJOR_API, the saved link, the repo's web/config.json, then the published pointer. '' if none is found."""
70
+ for v in (cli_value, os.environ.get("MAJOR_API", ""), load_settings().get("link", "")):
71
+ if v:
72
+ return v.rstrip("/")
73
+ root = repo_root()
74
+ if root:
75
+ v = _read(os.path.join(root, "web", "config.json"), {}).get("api_base", "")
76
+ if v:
77
+ return v.rstrip("/")
78
+ try:
79
+ with urllib.request.urlopen(POINTER, timeout=6) as r:
80
+ return json.load(r).get("api_base", "").rstrip("/")
81
+ except Exception: # noqa: BLE001
82
+ return ""
major_chat/themes.py ADDED
@@ -0,0 +1,24 @@
1
+ """Colour themes. Each maps semantic names to colours; the app builds one prompt_toolkit Style from it."""
2
+ THEMES = {
3
+ # background text dim faint accent reasoning menu_bg menu_sel_bg menu_sel_fg
4
+ "noir": ("#000000", "#f2f2f2", "#8a8a8a", "#4d4d4d", "#ffffff", "#9a9a9a", "#101010", "#ffffff", "#000000"),
5
+ "paper": ("#f6f4ee", "#1d1d1d", "#6b6b6b", "#b4b0a6", "#000000", "#5e5e5e", "#e9e6dd", "#1d1d1d", "#f6f4ee"),
6
+ "amber": ("#0b0700", "#ffb000", "#b37a00", "#5c3f00", "#ffd24d", "#cc8c00", "#1a1100", "#ffb000", "#0b0700"),
7
+ "matrix": ("#000a02", "#39ff7a", "#1f9a4a", "#0f4a24", "#b6ffcb", "#2bc860", "#021407", "#39ff7a", "#000a02"),
8
+ "ocean": ("#06121f", "#d7ecff", "#6f93b3", "#2f4a63", "#7cc4ff", "#8fb2cf", "#0b1e33", "#7cc4ff", "#06121f"),
9
+ "dusk": ("#120a1c", "#eadcff", "#9a86b8", "#473a5c", "#c9a3ff", "#a893c9", "#1b1128", "#c9a3ff", "#120a1c"),
10
+ }
11
+ ORDER = list(THEMES)
12
+ DESCRIPTIONS = {"noir": "black and white (default)", "paper": "light, warm paper", "amber": "amber phosphor terminal", "matrix": "green on black",
13
+ "ocean": "deep blue", "dusk": "soft purple"}
14
+
15
+
16
+ def style_dict(name):
17
+ name = "noir" if name == "major" else name # the default used to be called "major"
18
+ bg, fg, dim, faint, acc, reas, mbg, msel_bg, msel_fg = THEMES.get(name, THEMES["noir"])
19
+ return {"": f"{fg} bg:{bg}", "root": f"{fg} bg:{bg}", "dim": dim, "faint": faint, "accent": f"bold {acc}", "user": f"bold {acc}", "bot": fg, "reason": f"italic {reas}",
20
+ "reasonbar": faint, "err": "#ff6b6b", "hr": faint,
21
+ "menu": f"{fg} bg:{mbg}", "menu.sel": f"{msel_fg} bg:{msel_bg}", "menu.dim": f"{dim} bg:{mbg}", "menu.title": f"bold {acc} bg:{mbg}",
22
+ "completion-menu": f"bg:{mbg} {fg}", "completion-menu.completion": f"bg:{mbg} {fg}", "completion-menu.completion.current": f"bg:{msel_bg} {msel_fg}",
23
+ "completion-menu.meta.completion": f"bg:{mbg} {dim}", "completion-menu.meta.completion.current": f"bg:{msel_bg} {msel_fg}",
24
+ "scrollbar.background": f"bg:{mbg}", "scrollbar.button": f"bg:{faint}"}
@@ -0,0 +1,34 @@
1
+ Metadata-Version: 2.4
2
+ Name: major-chat
3
+ Version: 0.1.0
4
+ Summary: Full-screen terminal chat for Major, a tiny language model (sign-in required).
5
+ License-Expression: GPL-3.0-or-later
6
+ Project-URL: Repository, https://github.com/yixuanxu-ai/major-1
7
+ Keywords: llm,chat,tui,terminal,tiny-model
8
+ Classifier: Environment :: Console
9
+ Classifier: Intended Audience :: End Users/Desktop
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Topic :: Communications :: Chat
12
+ Requires-Python: >=3.9
13
+ Description-Content-Type: text/markdown
14
+ Requires-Dist: prompt_toolkit>=3.0.40
15
+
16
+ # major-chat
17
+
18
+ A full-screen terminal chat for **Major**, a very small language model.
19
+
20
+ ```
21
+ pip install major-chat
22
+ major-chat
23
+ ```
24
+
25
+ You need an account to use it. On first run it asks you to sign in or create one (username and password, no email), then opens the chat.
26
+ Chats are saved to your account, so `/resume` brings them back, including on another machine.
27
+
28
+ - Type `/` to see the commands; use the arrow keys to choose, Enter to run.
29
+ - `/model` choose the model (one today: `major-1`), `/theme` six colour themes (default `noir`), `/temp` and `/length` reply settings, `/resume` saved chats, `/new`, `/whoami`, `/logout`, `/quit`.
30
+ - Up and down scroll the conversation; `ctrl+p` and `ctrl+n` bring back earlier prompts; `ctrl+c` stops a reply.
31
+ - The window can be resized at any time.
32
+
33
+ The chat runs on a Major server. `major-chat` finds the current server link on its own; use `--api https://…` to point at a different one,
34
+ and `major-chat logout` to forget the saved sign-in. Major is a 43M-parameter model and gets facts wrong. It is an AI and can make mistakes.
@@ -0,0 +1,13 @@
1
+ major_chat/README.md,sha256=9yGCKc4SugBRYqFhplEwysjYxVvGOmdzd5HRgnBJ9yM,1072
2
+ major_chat/__init__.py,sha256=hYQsya1UDnBCSEbtdj-5UEGi8y8G_yCKtNoXnoZ1zLQ,99
3
+ major_chat/__main__.py,sha256=bYt9eEaoRQWdejEHFD8REx9jxVEdZptECFsV7F49Ink,30
4
+ major_chat/app.py,sha256=Q3Z_nCJn8YY1LTdPRdWOHFgB2iwCInG_0FDQZhZ-wHM,22659
5
+ major_chat/cli.py,sha256=1Mo1O3NSrdy15D3pK4tuqDUx8u1I_G2CDQzv_pvcmvM,4209
6
+ major_chat/client.py,sha256=LQK1EcZ2BTyzuiOM5dfGylNUGadRv2v6rVZU5Fe8lAI,6068
7
+ major_chat/config.py,sha256=XkJJUDYsqvv0cZGovEGT7EvnP0_-V7t9VA4X_qNvNZU,2690
8
+ major_chat/themes.py,sha256=-kDCWqCupm-FoPFVg29c2wLLVBs1fZyNDGSK_6F_qGc,2146
9
+ major_chat-0.1.0.dist-info/METADATA,sha256=f2nIrNEdTCBYaC6Drn-Mel2dkZy6xxCo2OQbo-d7dyQ,1638
10
+ major_chat-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
11
+ major_chat-0.1.0.dist-info/entry_points.txt,sha256=TZAFBDN35tlOO-LYaTuJGJNeN50mJS65TStrAbGJbeA,51
12
+ major_chat-0.1.0.dist-info/top_level.txt,sha256=1ikzXKTzvnGeKng9uLzmuKAPAko6k0KXq5ZUuXNIxXY,11
13
+ major_chat-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ major-chat = major_chat.cli:main
@@ -0,0 +1 @@
1
+ major_chat