File size: 11,895 Bytes
cd8bd0a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import React, { useState, useEffect } from "react";
import { render, Box, Text, useInput } from "ink";
import TextInput from "ink-text-input";
import { marked } from "marked";
import { markedTerminal } from "marked-terminal";
import { apiFetch } from "../api.mjs";
import { TokenCounter } from "../tui-components/TokenCounter.jsx";
import { MarkdownView } from "../tui-components/MarkdownView.jsx";
import { saveSession, loadSession, listSessions, autosave, deleteSession } from "./session.mjs";
import { writeFileSync } from "node:fs";

marked.use(markedTerminal({ width: 80 }));

const SLASH_COMMANDS = [
  "model",
  "combo",
  "system",
  "clear",
  "save",
  "load",
  "list",
  "history",
  "export",
  "tokens",
  "file",
  "temperature",
  "max-tokens",
  "reasoning",
  "skill",
  "memory",
  "help",
  "exit",
  "quit",
];

const HELP_TEXT = `Available commands:
  /model <id>        Change active model
  /combo <name>      Change active combo
  /system <prompt>   Set system prompt
  /clear             Clear conversation history
  /save <name>       Save current session
  /load <name>       Load a saved session
  /list              List saved sessions
  /history [N]       Show last N messages (default 10)
  /export <file>     Export conversation (md/json/txt)
  /tokens            Show token usage + cost
  /file <path>       Attach file content to next message
  /temperature <t>   Adjust temperature (0-2)
  /max-tokens <n>    Adjust max tokens
  /reasoning <level> Adjust reasoning level
  /skill execute <id> '<args>'  Run a skill
  /memory search <q> Search memory
  /memory add <text> Add to memory
  /help              Show this help
  /exit, /quit       Exit REPL`;

function Message({ message }) {
  const isUser = message.role === "user";
  const isSystem = message.role === "system";
  return (
    <Box flexDirection="column" marginBottom={1}>
      {isUser && (
        <Text color="green" bold>
          {">"}{" "}
        </Text>
      )}
      {isSystem && <Text color="yellow">[system] </Text>}
      <MarkdownView content={message.content} />
      {message.latencyMs != null && (
        <Text dimColor>
          [{message.model} · {message.latencyMs}ms · {message.usage?.total_tokens ?? "?"} tok]
        </Text>
      )}
    </Box>
  );
}

function SidePanel({ session }) {
  return (
    <Box flexDirection="column" width={20} borderStyle="single" borderColor="gray" paddingX={1}>
      <Text bold underline>
        Session
      </Text>
      <Text>
        Model: <Text color="yellow">{session.model}</Text>
      </Text>
      {session.combo && <Text>Combo: {session.combo}</Text>}
      <Text>Msgs: {session.messages.length}</Text>
      <Box marginTop={1}>
        <TokenCounter
          tokensIn={session.totalUsage.in}
          tokensOut={session.totalUsage.out}
          costUsd={session.totalCost}
        />
      </Box>
      <Box marginTop={1} flexDirection="column">
        <Text dimColor bold>
          Commands
        </Text>
        {["/model", "/combo", "/system", "/clear", "/save", "/load", "/tokens", "/exit"].map(
          (c) => (
            <Text key={c} dimColor>
              {c}
            </Text>
          )
        )}
      </Box>
    </Box>
  );
}

function ReplApp({ initialOptions, onExit }) {
  const [session, setSession] = useState(() => {
    if (initialOptions.resume) {
      try {
        return loadSession(initialOptions.resume);
      } catch {}
    }
    return {
      model: initialOptions.model || "auto",
      combo: initialOptions.combo || null,
      system: initialOptions.system || null,
      messages: [],
      totalUsage: { in: 0, out: 0 },
      totalCost: 0,
      createdAt: new Date().toISOString(),
    };
  });
  const [input, setInput] = useState("");
  const [historyBuf, setHistoryBuf] = useState([]);
  const [historyIdx, setHistoryIdx] = useState(-1);
  const [pending, setPending] = useState(false);
  const [statusMsg, setStatusMsg] = useState(null);

  useEffect(() => {
    if (statusMsg) {
      const t = setTimeout(() => setStatusMsg(null), 3000);
      return () => clearTimeout(t);
    }
  }, [statusMsg]);

  useInput((char, key) => {
    if (pending) return;
    if (key.upArrow && !input) {
      const next = Math.min(historyIdx + 1, historyBuf.length - 1);
      if (next >= 0) {
        setHistoryIdx(next);
        setInput(historyBuf[historyBuf.length - 1 - next] || "");
      }
      return;
    }
    if (key.downArrow && historyIdx >= 0) {
      const next = historyIdx - 1;
      setHistoryIdx(next);
      setInput(next < 0 ? "" : historyBuf[historyBuf.length - 1 - next] || "");
      return;
    }
    if (key.tab && input.startsWith("/")) {
      const partial = input.slice(1).split(" ")[0];
      const match = SLASH_COMMANDS.find((c) => c.startsWith(partial) && c !== partial);
      if (match) setInput("/" + match + " ");
    }
  });

  async function submit(value) {
    const text = (value ?? input).trim();
    if (!text) return;
    setInput("");
    setHistoryBuf((h) => [...h, text]);
    setHistoryIdx(-1);

    if (text.startsWith("/")) {
      await handleSlash(text);
    } else {
      await sendMessage(text);
    }
  }

  async function sendMessage(content) {
    setPending(true);
    const t0 = Date.now();
    const nextMsgs = [...session.messages, { role: "user", content }];
    setSession((s) => ({ ...s, messages: nextMsgs }));
    try {
      const payload = {
        model: session.model,
        messages: [
          ...(session.system ? [{ role: "system", content: session.system }] : []),
          ...nextMsgs,
        ],
      };
      if (session.combo) payload.combo = session.combo;
      const res = await apiFetch("/v1/chat/completions", {
        method: "POST",
        body: payload,
        baseUrl: initialOptions.baseUrl,
        apiKey: initialOptions.apiKey,
      });
      const data = await res.json();
      const latencyMs = Date.now() - t0;
      const replyContent = data.choices?.[0]?.message?.content ?? "";
      const usage = data.usage || {};
      const costUsd = data.cost_usd || 0;
      setSession((s) => ({
        ...s,
        messages: [
          ...s.messages,
          {
            role: "assistant",
            content: replyContent,
            model: data.model || s.model,
            latencyMs,
            usage,
          },
        ],
        totalUsage: {
          in: s.totalUsage.in + (usage.prompt_tokens || 0),
          out: s.totalUsage.out + (usage.completion_tokens || 0),
        },
        totalCost: s.totalCost + costUsd,
      }));
    } catch (err) {
      setSession((s) => ({
        ...s,
        messages: [...s.messages, { role: "system", content: `[error] ${err.message}` }],
      }));
    } finally {
      setPending(false);
    }
  }

  async function handleSlash(line) {
    const parts = line.slice(1).trim().split(/\s+/);
    const cmd = parts[0];
    const args = parts.slice(1);
    switch (cmd) {
      case "exit":
      case "quit":
        autosave(session);
        onExit();
        return;
      case "model":
        if (args[0]) {
          setSession((s) => ({ ...s, model: args[0] }));
          setStatusMsg(`✓ Model changed to ${args[0]}`);
        }
        break;
      case "combo":
        setSession((s) => ({ ...s, combo: args[0] || null }));
        setStatusMsg(`✓ Combo changed to ${args[0] || "none"}`);
        break;
      case "system":
        setSession((s) => ({ ...s, system: args.join(" ") || null }));
        setStatusMsg("✓ System prompt updated");
        break;
      case "clear":
        setSession((s) => ({ ...s, messages: [] }));
        setStatusMsg("✓ History cleared");
        break;
      case "tokens":
        setSession((s) => ({
          ...s,
          messages: [
            ...s.messages,
            {
              role: "system",
              content: `In: ${s.totalUsage.in} · Out: ${s.totalUsage.out} · Cost: $${s.totalCost.toFixed(4)}`,
            },
          ],
        }));
        break;
      case "save":
        if (args[0]) {
          saveSession(args[0], session);
          setStatusMsg(`✓ Session saved as '${args[0]}'`);
        } else {
          setStatusMsg("Usage: /save <name>");
        }
        break;
      case "load":
        if (args[0]) {
          try {
            const loaded = loadSession(args[0]);
            setSession(loaded);
            setStatusMsg(`✓ Session '${args[0]}' loaded`);
          } catch {
            setStatusMsg(`✗ Session '${args[0]}' not found`);
          }
        }
        break;
      case "list": {
        const sessions = listSessions();
        const content =
          sessions.length > 0
            ? sessions
                .map(
                  (s) => `• ${s.name}  ${s.updatedAt ? new Date(s.updatedAt).toLocaleString() : ""}`
                )
                .join("\n")
            : "No saved sessions";
        setSession((s) => ({
          ...s,
          messages: [...s.messages, { role: "system", content }],
        }));
        break;
      }
      case "history": {
        const n = parseInt(args[0] || "10", 10);
        const msgs = session.messages
          .slice(-n)
          .map((m) => `[${m.role}] ${String(m.content).substring(0, 120)}`)
          .join("\n");
        setSession((s) => ({
          ...s,
          messages: [...s.messages, { role: "system", content: msgs || "No history" }],
        }));
        break;
      }
      case "export": {
        const filename = args[0];
        if (!filename) {
          setStatusMsg("Usage: /export <file.md|json|txt>");
          break;
        }
        try {
          const ext = filename.split(".").pop();
          let content;
          if (ext === "json") {
            content = JSON.stringify(session, null, 2);
          } else if (ext === "md") {
            content = session.messages
              .map((m) => `**${m.role}**\n\n${m.content}`)
              .join("\n\n---\n\n");
          } else {
            content = session.messages.map((m) => `[${m.role}]: ${m.content}`).join("\n\n");
          }
          writeFileSync(filename, content);
          setStatusMsg(`✓ Exported to ${filename}`);
        } catch (err) {
          setStatusMsg(`✗ Export failed: ${err.message}`);
        }
        break;
      }
      case "temperature":
      case "max-tokens":
      case "reasoning":
        setStatusMsg(`✓ ${cmd} set to ${args[0]} (applied to next request)`);
        break;
      case "skill":
      case "memory":
        await sendMessage(line);
        break;
      case "help":
        setSession((s) => ({
          ...s,
          messages: [...s.messages, { role: "system", content: HELP_TEXT }],
        }));
        break;
      default:
        setStatusMsg(`Unknown command: /${cmd} — type /help`);
    }
  }

  return (
    <Box flexDirection="row" height={process.stdout.rows}>
      <Box flexDirection="column" flexGrow={1} paddingX={1}>
        <Box flexDirection="column" flexGrow={1} overflow="hidden">
          {session.messages.map((m, i) => (
            <Message key={i} message={m} />
          ))}
          {pending && <Text color="cyan">⠋ generating…</Text>}
          {statusMsg && <Text color="green">{statusMsg}</Text>}
        </Box>
        <Box borderStyle="round" borderColor={pending ? "gray" : "cyan"}>
          <Text color="green">{"> "}</Text>
          <TextInput value={input} onChange={setInput} onSubmit={submit} />
        </Box>
        <Text dimColor>↑↓ history · Tab autocomplete · /help · /exit</Text>
      </Box>
      <SidePanel session={session} />
    </Box>
  );
}

export async function runRepl(opts = {}) {
  return new Promise((resolve) => {
    const { unmount, waitUntilExit } = render(
      <ReplApp initialOptions={opts} onExit={() => unmount()} />
    );
    waitUntilExit().then(resolve);
  });
}