File size: 11,194 Bytes
97c39f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""TinyLiquid Analyst - neon terminal UI (stdlib curses, zero deps).

An OpenCode-style agent terminal themed like Parrot OS meets Matrix:
near-black background, matrix-green neon, pink/blue/purple accents.
Chat with the analyst/skeptic personas, run SOP-driven cases, search and
read the library, manage case files.

Usage:
  .venv/bin/python tui/analyst.py --ckpt ckpt/dpo
  .venv/bin/python tui/analyst.py --ckpt ckpt/dpo --case mycase.json
"""

import argparse
import curses
import random
import textwrap

from tui.engine import AnalystEngine
from tui.cli import handle_cmd

WRAP = 78

# --- neon palette (256-color) ---
C_BG = 0          # terminal default (black)
C_GREEN = 82      # matrix green
C_PINK = 205
C_BLUE = 39
C_PURPLE = 141
C_CYAN = 51
C_WHITE = 255
C_DIM = 240

PAIR = {
    "bg": 1, "green": 2, "pink": 3, "blue": 4, "purple": 5,
    "cyan": 6, "white": 7, "dim": 8, "user": 9, "model": 10,
    "skeptic": 11, "system": 12, "error": 13, "header": 14,
}


def setup_colors(stdscr):
    curses.start_color()
    curses.use_default_colors()
    try:
        if curses.COLORS >= 256:
            curses.init_pair(PAIR["bg"], C_WHITE, C_BG)
            curses.init_pair(PAIR["green"], C_GREEN, C_BG)
            curses.init_pair(PAIR["pink"], C_PINK, C_BG)
            curses.init_pair(PAIR["blue"], C_BLUE, C_BG)
            curses.init_pair(PAIR["purple"], C_PURPLE, C_BG)
            curses.init_pair(PAIR["cyan"], C_CYAN, C_BG)
            curses.init_pair(PAIR["white"], C_WHITE, C_BG)
            curses.init_pair(PAIR["dim"], C_DIM, C_BG)
            curses.init_pair(PAIR["user"], C_CYAN, C_BG)
            curses.init_pair(PAIR["model"], C_GREEN, C_BG)
            curses.init_pair(PAIR["skeptic"], C_PINK, C_BG)
            curses.init_pair(PAIR["system"], C_PURPLE, C_BG)
            curses.init_pair(PAIR["error"], C_PINK, C_BG)
            curses.init_pair(PAIR["header"], C_GREEN, C_BG)
        else:
            for k in PAIR:
                curses.init_pair(PAIR[k], curses.COLOR_WHITE, curses.COLOR_BLACK)
            curses.init_pair(PAIR["green"], curses.COLOR_GREEN, curses.COLOR_BLACK)
            curses.init_pair(PAIR["pink"], curses.COLOR_RED, curses.COLOR_BLACK)
            curses.init_pair(PAIR["blue"], curses.COLOR_CYAN, curses.COLOR_BLACK)
            curses.init_pair(PAIR["purple"], curses.COLOR_MAGENTA, curses.COLOR_BLACK)
            curses.init_pair(PAIR["cyan"], curses.COLOR_CYAN, curses.COLOR_BLACK)
            curses.init_pair(PAIR["user"], curses.COLOR_CYAN, curses.COLOR_BLACK)
            curses.init_pair(PAIR["model"], curses.COLOR_GREEN, curses.COLOR_BLACK)
            curses.init_pair(PAIR["skeptic"], curses.COLOR_RED, curses.COLOR_BLACK)
            curses.init_pair(PAIR["system"], curses.COLOR_MAGENTA, curses.COLOR_BLACK)
            curses.init_pair(PAIR["error"], curses.COLOR_RED, curses.COLOR_BLACK)
            curses.init_pair(PAIR["header"], curses.COLOR_GREEN, curses.COLOR_BLACK)
    except curses.error:
        pass


def wrap(text, width):
    return "\n".join(textwrap.fill(p, width) for p in text.splitlines()) or " "


class Rain:
    """Minimal matrix-rain strip for the header (lightweight, idle-animated)."""

    def __init__(self, width, rows=1):
        self.width = max(1, width)
        self.rows = rows
        self.cols = [random.randint(0, self.width - 1) for _ in range(self.rows)]

    def frame(self):
        chars = [" "] * self.width
        for i, c in enumerate(self.cols):
            if random.random() < 0.75:
                chars[c] = random.choice("01$#&@!?ABCDEF")
            self.cols[i] = (c + random.choice([-1, 0, 1])) % self.width
        return "".join(chars)


class TerminalUI:
    def __init__(self, stdscr, eng):
        self.stdscr = stdscr
        self.eng = eng
        self.lines = []          # list of (kind, text)
        self.history = []
        self.hist_idx = -1
        self.scroll = 0
        self.input_text = ""
        self.cursor = 0
        self.rain = Rain(10)
        self.status = f"persona: analyst | case: {eng.case.name}"

    def add(self, kind, text):
        for ln in wrap(text, WRAP).splitlines() or [""]:
            self.lines.append((kind, ln))
        self.scroll = 0

    def header(self, wd):
        title = " TINYLIQUID ANALYST "
        left = (wd - len(title)) // 2
        top = "═" * wd
        line = " " * left + title
        return top, line[:wd], self.rain.frame()[:wd]

    def draw(self):
        h, wd = self.stdscr.getmaxyx()
        top, title, rain = self.header(wd)
        body_h = max(1, h - 6)

        self.stdscr.erase()
        self.stdscr.addnstr(0, 0, top[:wd], wd, curses.color_pair(PAIR["purple"]))
        self.stdscr.addnstr(1, 0, title[:wd], wd, curses.color_pair(PAIR["header"]))
        self.stdscr.addnstr(2, 0, rain[:wd], wd, curses.color_pair(PAIR["green"]))

        start = len(self.lines) - body_h - self.scroll
        start = max(0, min(start, max(0, len(self.lines) - body_h)))
        for i in range(body_h):
            idx = start + i
            if idx < len(self.lines):
                kind, ln = self.lines[idx]
                pair = {"user": PAIR["user"], "model": PAIR["model"],
                        "skeptic": PAIR["skeptic"], "system": PAIR["system"],
                        "error": PAIR["error"]}.get(kind, PAIR["white"])
                self.stdscr.addnstr(3 + i, 0, ln[:wd], wd, curses.color_pair(pair))

        self.stdscr.addnstr(h - 3, 0, "─" * wd, wd, curses.color_pair(PAIR["purple"]))
        self.stdscr.addnstr(h - 2, 0, self.status[:wd], wd,
                            curses.color_pair(PAIR["system"]) | curses.A_REVERSE)
        prompt = "❯ "
        self.stdscr.addnstr(h - 1, 0, prompt + self.input_text[:wd - len(prompt) - 1], wd,
                            curses.color_pair(PAIR["green"]))
        try:
            self.stdscr.move(h - 1, min(self.cursor + len(prompt), wd - 1))
        except curses.error:
            pass
        self.stdscr.refresh()

    def run_cmd(self, cmd):
        if cmd in ("/quit", "/exit", "/q"):
            return False
        if cmd == "/clear":
            self.lines = []
            self.add("system", "cleared.")
            return True
        self.add("user", cmd if cmd.startswith("/") else "you> " + cmd)
        if not cmd.startswith("/"):
            # streamed chat: redraw as tokens arrive
            buf = []
            self.lines.append(("model", "…"))
            try:
                def on_token(tok_id):
                    buf.append(tok_id)
                    self.lines[-1] = ("model", self.eng.tok.decode(buf))
                    self.draw()
                self.eng.chat(cmd, on_token=on_token)
            except Exception as e:
                self.lines[-1] = ("error", f"error: {e}")
                self.draw()
                return True
            self.lines[-1] = ("model", self.eng.tok.decode(buf))
            self.draw()
            return True
        try:
            out = handle_cmd(self.eng, cmd)
        except Exception as e:
            out = f"error: {e}"
            self.add("error", out)
            return True
        kind = "skeptic" if cmd.startswith(("/skeptic",)) else "model"
        # render JSON reports nicely
        if out.strip().startswith("{") or out.strip().startswith("["):
            import json as _json
            try:
                data = _json.loads(out)
                out = _json.dumps(data, indent=2, ensure_ascii=False)
            except Exception:
                pass
        for ln in out.splitlines():
            self.add(kind, ln)
        return True

    def loop(self):
        setup_colors(self.stdscr)
        curses.curs_set(1)
        self.stdscr.timeout(80)
        self.add("system", "TinyLiquid Analyst — on-device forensic research terminal")
        self.add("dim", "Authorized research/OSINT only. Outputs are decision support, never a verdict.")
        self.add("dim", "type /help for commands | /quit to exit")
        while True:
            self.draw()
            try:
                ch = self.stdscr.get_wch()
            except curses.error:
                continue
            if ch in ("\n", "\r", "KEY_ENTER"):
                cmd = self.input_text.strip()
                self.input_text, self.cursor = "", 0
                self.history.append(cmd)
                self.hist_idx = len(self.history)
                if cmd and not self.run_cmd(cmd):
                    break
                continue
            if ch in ("\x7f", "KEY_BACKSPACE"):
                if self.cursor > 0:
                    self.input_text = self.input_text[:self.cursor - 1] + self.input_text[self.cursor:]
                    self.cursor -= 1
                continue
            if ch == "KEY_DC":
                self.input_text = self.input_text[:self.cursor] + self.input_text[self.cursor + 1:]
                continue
            if ch == "KEY_LEFT":
                self.cursor = max(0, self.cursor - 1)
                continue
            if ch == "KEY_RIGHT":
                self.cursor = min(len(self.input_text), self.cursor + 1)
                continue
            if ch == "KEY_HOME":
                self.cursor = 0
                continue
            if ch == "KEY_END":
                self.cursor = len(self.input_text)
                continue
            if ch in ("KEY_PPAGE",):
                self.scroll = min(self.scroll + 5, max(0, len(self.lines) - 1))
                continue
            if ch in ("KEY_NPAGE",):
                self.scroll = max(0, self.scroll - 5)
                continue
            if ch == "KEY_UP":
                if self.history and self.hist_idx > 0:
                    self.hist_idx -= 1
                    self.input_text = self.history[self.hist_idx]
                    self.cursor = len(self.input_text)
                continue
            if ch == "KEY_DOWN":
                if self.history and self.hist_idx < len(self.history) - 1:
                    self.hist_idx += 1
                    self.input_text = self.history[self.hist_idx]
                    self.cursor = len(self.input_text)
                else:
                    self.input_text, self.hist_idx = "", len(self.history)
                continue
            if isinstance(ch, str) and ch.isprintable():
                self.input_text = self.input_text[:self.cursor] + ch + self.input_text[self.cursor:]
                self.cursor += 1


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--ckpt", default="ckpt/v8_lora/best.pt")
    ap.add_argument("--tok", default="data/tokenizer.json")
    ap.add_argument("--case", default=None)
    ap.add_argument("--threads", type=int, default=4)
    args = ap.parse_args()

    eng = AnalystEngine(ckpt=args.ckpt, tok_path=args.tok, threads=args.threads)
    if args.case:
        eng.load_case(args.case)

    def go(stdscr):
        ui = TerminalUI(stdscr, eng)
        ui.status = f"persona: {eng.persona} | case: {eng.case.name} | {eng.ckpt}"
        ui.loop()

    try:
        curses.wrapper(go)
    except KeyboardInterrupt:
        pass
    print("session ended.")


if __name__ == "__main__":
    main()