aether-code 0.33.0 → 0.33.2

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.
@@ -28,7 +28,7 @@ import {
28
28
  import readline from "node:readline";
29
29
  import { c, errorLine, divider, setTerminalTitle } from "../src/render.js";
30
30
 
31
- const VERSION = "0.33.0";
31
+ const VERSION = "0.33.2";
32
32
 
33
33
  /**
34
34
  * Try to start MCP servers from ~/.aether/mcp.json. Returns a started
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aether-code",
3
- "version": "0.33.0",
3
+ "version": "0.33.2",
4
4
  "description": "Uncensored AI coding agent for your terminal — Claude Code alternative with MCP support. Reads code, writes files, runs commands. Drives IDA Pro, Roblox Studio, Wireshark, Blender, and any MCP server. No refusal layer.",
5
5
  "homepage": "https://trynoguard.com",
6
6
  "repository": {
@@ -25,7 +25,7 @@
25
25
  },
26
26
  "scripts": {
27
27
  "postinstall": "node scripts/postinstall.js",
28
- "lint": "node --check bin/aether-code.js src/agent.js src/api.js src/config.js src/render.js src/tools.js src/diff.js src/repl.js src/mcp.js src/mcp-cli.js src/mcp-registry.js src/skills.js src/update-check.js src/ink-input.js scripts/postinstall.js",
28
+ "lint": "node --check bin/aether-code.js src/agent.js src/api.js src/config.js src/render.js src/tools.js src/diff.js src/repl.js src/mcp.js src/mcp-cli.js src/mcp-registry.js src/skills.js src/update-check.js src/box-input.js src/ink-input.js scripts/postinstall.js",
29
29
  "test": "node --test \"test/**/*.test.js\"",
30
30
  "prepublishOnly": "npm run lint && npm test"
31
31
  },
package/src/box-input.js CHANGED
@@ -1,132 +1,208 @@
1
- // Bordered single-line text input — raw-mode, cmd.exe-safe.
2
- //
3
- // Like the ask_user menu, this is NOT Ink (which ghosts in the legacy Windows
4
- // console). It draws a 3-line box + hint, and on every keystroke moves the
5
- // cursor back up (ESC[nA), clears (ESC[J), and reprints. The caret is a FAKE
6
- // cursor (inverse-video cell) and the real terminal cursor is hidden, so there
7
- // is no cursor-column math to get wrong. Long input scrolls horizontally under
8
- // a fixed right border.
9
- //
10
- // Returns the typed string, or EXIT_SIGNAL on Ctrl+C / Ctrl+D.
11
-
12
- import readline from "node:readline";
13
- import { c } from "./render.js";
14
-
15
- export const EXIT_SIGNAL = "<<aether-exit>>";
16
-
17
- const HIDE = "\x1b[?25l";
18
- const SHOW = "\x1b[?25h";
19
- const INV = (s) => `\x1b[7m${s}\x1b[27m`;
20
-
21
- export function promptBox({ history = [], placeholder = "type a message… /help for commands" } = {}) {
22
- return new Promise((resolve) => {
23
- // Non-interactive (piped / tests): plain readline, no box.
24
- if (!process.stdin.isTTY) {
25
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
26
- rl.question(c.magenta("› "), (a) => { rl.close(); resolve(a); });
27
- return;
28
- }
29
-
30
- let buf = "";
31
- let pos = 0; // caret index within buf
32
- const hist = history.slice();
33
- let histIdx = hist.length; // points one past the end (current draft)
34
- let draft = "";
35
- let drawn = 0;
36
- let lastSigint = 0;
37
-
38
- const innerW = () => Math.max(24, Math.min(process.stdout.columns || 80, 100) - 6);
39
-
40
- const draw = (first) => {
41
- const W = innerW();
42
- if (!first) process.stdout.write(`\x1b[${drawn}A`);
43
- process.stdout.write("\x1b[J");
44
-
45
- // Horizontal scroll: keep the caret within the visible window.
46
- const maxVisible = W - 1;
47
- const start = pos > maxVisible ? pos - maxVisible : 0;
48
- const view = buf.slice(start, start + W);
49
- const rel = pos - start;
50
-
51
- let content;
52
- if (buf.length === 0) {
53
- const ph = placeholder.slice(0, W - 1);
54
- content = INV(" ") + c.dim(ph) + " ".repeat(Math.max(0, W - 1 - ph.length));
55
- } else {
56
- let s = "";
57
- for (let i = 0; i < W; i++) {
58
- const ch = view[i] ?? " ";
59
- s += i === rel ? INV(ch) : ch;
60
- }
61
- content = s;
62
- }
63
-
64
- const top = c.magenta("╭" + "─".repeat(W + 4) + "╮");
65
- const mid = c.magenta("│") + " " + c.magenta("›") + " " + content + " " + c.magenta("│");
66
- const bot = c.magenta("╰" + "─".repeat(W + 4) + "╯");
67
- const hint = c.dim(" Enter send · ↑↓ history · @file for images · /help · /exit");
68
-
69
- process.stdout.write(top + "\n" + mid + "\n" + bot + "\n" + hint + "\n");
70
- drawn = 4;
71
- };
72
-
73
- const finish = (result) => {
74
- process.stdin.removeListener("keypress", onKey);
75
- if (process.stdin.isTTY) process.stdin.setRawMode(false);
76
- process.stdin.pause();
77
- process.stdout.write(`\x1b[${drawn}A\x1b[J` + SHOW);
78
- // Echo the submitted line so it persists in scrollback.
79
- if (result && result !== EXIT_SIGNAL && result.trim()) {
80
- process.stdout.write(c.magenta("› ") + result + "\n");
81
- }
82
- resolve(result);
83
- };
84
-
85
- const onKey = (str, key) => {
86
- if (!key) return;
87
- const k = key.name;
88
-
89
- if (k === "return" || k === "enter") return finish(buf);
90
- if (key.ctrl && k === "c") {
91
- const now = Date.now();
92
- if (now - lastSigint < 1500 || buf.length === 0) return finish(EXIT_SIGNAL);
93
- lastSigint = now;
94
- buf = ""; pos = 0; draw(false);
95
- return;
96
- }
97
- if (key.ctrl && k === "d") return finish(buf.length === 0 ? EXIT_SIGNAL : buf);
98
-
99
- if (k === "backspace") { if (pos > 0) { buf = buf.slice(0, pos - 1) + buf.slice(pos); pos--; } }
100
- else if (k === "delete") { buf = buf.slice(0, pos) + buf.slice(pos + 1); }
101
- else if (k === "left") { if (pos > 0) pos--; }
102
- else if (k === "right") { if (pos < buf.length) pos++; }
103
- else if (k === "home" || (key.ctrl && k === "a")) pos = 0;
104
- else if (k === "end" || (key.ctrl && k === "e")) pos = buf.length;
105
- else if (key.ctrl && k === "u") { buf = ""; pos = 0; }
106
- else if (k === "up") {
107
- if (histIdx === hist.length) draft = buf;
108
- if (histIdx > 0) { histIdx--; buf = hist[histIdx] ?? ""; pos = buf.length; }
109
- }
110
- else if (k === "down") {
111
- if (histIdx < hist.length) {
112
- histIdx++;
113
- buf = histIdx === hist.length ? draft : (hist[histIdx] ?? "");
114
- pos = buf.length;
115
- }
116
- }
117
- else if (str && !key.ctrl && !key.meta && str >= " " && str !== "\x7f") {
118
- buf = buf.slice(0, pos) + str + buf.slice(pos);
119
- pos += str.length;
120
- }
121
- else return; // ignore unhandled keys without a redraw
122
- draw(false);
123
- };
124
-
125
- process.stdout.write(HIDE);
126
- readline.emitKeypressEvents(process.stdin);
127
- if (process.stdin.isTTY) process.stdin.setRawMode(true);
128
- process.stdin.resume();
129
- process.stdin.on("keypress", onKey);
130
- draw(true);
131
- });
132
- }
1
+ // Minimal prompt input — raw-mode, cmd.exe-safe.
2
+ // No box/border — just a bare "> " prompt like Claude Code.
3
+ //
4
+ // Features:
5
+ // - Ctrl+V / Alt+V: paste image from clipboard
6
+ // - @file.png: reference images by path (parsed by agent.js)
7
+ // - Arrow keys, Home/End, Ctrl+A/E, Ctrl+U, history navigation
8
+ // - Horizontal scroll for long input
9
+ //
10
+ // Returns the typed string (with @temppath appended for clipboard images),
11
+ // or EXIT_SIGNAL on Ctrl+C / Ctrl+D.
12
+
13
+ import readline from "node:readline";
14
+ import { execFileSync } from "node:child_process";
15
+ import fs from "node:fs";
16
+ import os from "node:os";
17
+ import path from "node:path";
18
+ import { c } from "./render.js";
19
+
20
+ export const EXIT_SIGNAL = "<<aether-exit>>";
21
+
22
+ const HIDE = "\x1b[?25l";
23
+ const SHOW = "\x1b[?25h";
24
+ const INV = (s) => `\x1b[7m${s}\x1b[27m`;
25
+
26
+ // Save clipboard image to a temp file. Returns the file path or null.
27
+ function grabClipboardImage() {
28
+ const tmpFile = path.join(os.tmpdir(), `aether-paste-${Date.now()}.png`);
29
+
30
+ try {
31
+ if (process.platform === "win32") {
32
+ const script =
33
+ "Add-Type -AssemblyName System.Windows.Forms;" +
34
+ "$img=[System.Windows.Forms.Clipboard]::GetImage();" +
35
+ "if($img){$img.Save('" + tmpFile.replace(/'/g, "''") + "'," +
36
+ "[System.Drawing.Imaging.ImageFormat]::Png);'OK'}else{'NO_IMAGE'}";
37
+ const out = execFileSync("powershell.exe", [
38
+ "-NoProfile", "-NonInteractive", "-Command", script,
39
+ ], { timeout: 5000, encoding: "utf8", stdio: ["pipe", "pipe", "pipe"] }).trim();
40
+ if (out.endsWith("OK") && fs.existsSync(tmpFile)) return tmpFile;
41
+ } else if (process.platform === "darwin") {
42
+ try {
43
+ execFileSync("pngpaste", [tmpFile], { timeout: 3000, stdio: "pipe" });
44
+ if (fs.existsSync(tmpFile) && fs.statSync(tmpFile).size > 0) return tmpFile;
45
+ } catch { /* pngpaste not installed */ }
46
+ } else {
47
+ try {
48
+ const fd = fs.openSync(tmpFile, "w");
49
+ try {
50
+ execFileSync("xclip", ["-selection", "clipboard", "-t", "image/png", "-o"], {
51
+ timeout: 3000, stdio: ["pipe", fd, "pipe"],
52
+ });
53
+ } finally {
54
+ fs.closeSync(fd);
55
+ }
56
+ if (fs.existsSync(tmpFile) && fs.statSync(tmpFile).size > 0) return tmpFile;
57
+ } catch { /* xclip not installed */ }
58
+ }
59
+ } catch { /* any failure — fall through */ }
60
+
61
+ try { if (fs.existsSync(tmpFile)) fs.unlinkSync(tmpFile); } catch { /* ignore */ }
62
+ return null;
63
+ }
64
+
65
+ export function promptBox({ history = [], placeholder = "Message Aether…" } = {}) {
66
+ return new Promise((resolve) => {
67
+ if (!process.stdin.isTTY) {
68
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
69
+ rl.question(c.cyan("> "), (a) => { rl.close(); resolve(a); });
70
+ return;
71
+ }
72
+
73
+ let buf = "";
74
+ let pos = 0;
75
+ const hist = history.slice();
76
+ let histIdx = hist.length;
77
+ let draft = "";
78
+ let drawn = 0;
79
+ let lastSigint = 0;
80
+ const clipImages = [];
81
+
82
+ const termW = () => Math.max(30, (process.stdout.columns || 80) - 4);
83
+
84
+ const draw = (first) => {
85
+ const W = termW();
86
+ if (!first) process.stdout.write(`\x1b[${drawn}A`);
87
+ process.stdout.write("\x1b[J");
88
+
89
+ // Horizontal scroll
90
+ const prefix = c.cyan("> ");
91
+ const prefixLen = 2; // "> " visible chars
92
+ const maxVisible = W - prefixLen;
93
+ const start = pos > maxVisible ? pos - maxVisible : 0;
94
+ const view = buf.slice(start, start + maxVisible);
95
+ const rel = pos - start;
96
+
97
+ let content;
98
+ if (buf.length === 0 && clipImages.length === 0) {
99
+ content = INV(" ") + c.dim(placeholder.slice(0, maxVisible - 1));
100
+ } else if (buf.length === 0 && clipImages.length > 0) {
101
+ const tag = `[${clipImages.length} image${clipImages.length > 1 ? "s" : ""} pasted]`;
102
+ content = INV(" ") + c.cyan(tag);
103
+ } else {
104
+ let s = "";
105
+ for (let i = 0; i < maxVisible; i++) {
106
+ const ch = view[i] ?? " ";
107
+ s += i === rel ? INV(ch) : ch;
108
+ }
109
+ if (clipImages.length > 0) {
110
+ s += " " + c.cyan(`[+${clipImages.length} img]`);
111
+ }
112
+ content = s;
113
+ }
114
+
115
+ // Prompt line — bare "> " like Claude Code
116
+ const promptLine = prefix + content;
117
+
118
+ // Status bar — mode + shortcuts, like Claude's bottom bar
119
+ const imgHint = clipImages.length > 0 ? " · " + c.cyan("images queued") : "";
120
+ const statusBar = c.dim(" ? for help · @file for images · Alt+V paste") + imgHint;
121
+
122
+ process.stdout.write(promptLine + "\n" + statusBar + "\n");
123
+ drawn = 2;
124
+ };
125
+
126
+ const finish = (result) => {
127
+ process.stdin.removeListener("keypress", onKey);
128
+ if (process.stdin.isTTY) process.stdin.setRawMode(false);
129
+ process.stdin.pause();
130
+ process.stdout.write(`\x1b[${drawn}A\x1b[J` + SHOW);
131
+
132
+ let finalResult = result;
133
+ if (result !== null && result !== EXIT_SIGNAL && clipImages.length > 0) {
134
+ const userText = (result || "").trim();
135
+ const imgRefs = clipImages.map((p) => `@"${p}"`).join(" ");
136
+ finalResult = userText ? `${userText} ${imgRefs}` : `What is in this image? ${imgRefs}`;
137
+ }
138
+
139
+ if (finalResult && finalResult !== EXIT_SIGNAL) {
140
+ const echoText = (result || "").trim();
141
+ const suffix = clipImages.length > 0
142
+ ? c.cyan(` [+${clipImages.length} image${clipImages.length > 1 ? "s" : ""}]`)
143
+ : "";
144
+ if (echoText || clipImages.length > 0) {
145
+ process.stdout.write(c.cyan("> ") + (echoText || c.dim("(image)")) + suffix + "\n");
146
+ }
147
+ }
148
+ resolve(finalResult);
149
+ };
150
+
151
+ const onKey = (str, key) => {
152
+ if (!key) return;
153
+ const k = key.name;
154
+
155
+ if (k === "return" || k === "enter") return finish(buf);
156
+ if (key.ctrl && k === "c") {
157
+ const now = Date.now();
158
+ if (now - lastSigint < 1500 || (buf.length === 0 && clipImages.length === 0)) return finish(EXIT_SIGNAL);
159
+ lastSigint = now;
160
+ buf = ""; pos = 0; clipImages.length = 0; draw(false);
161
+ return;
162
+ }
163
+ if (key.ctrl && k === "d") return finish(buf.length === 0 ? EXIT_SIGNAL : buf);
164
+
165
+ // Alt+V or Ctrl+V: paste image from clipboard
166
+ if ((key.meta && k === "v") || (key.ctrl && k === "v")) {
167
+ const imgPath = grabClipboardImage();
168
+ if (imgPath) {
169
+ clipImages.push(imgPath);
170
+ }
171
+ draw(false);
172
+ return;
173
+ }
174
+
175
+ if (k === "backspace") { if (pos > 0) { buf = buf.slice(0, pos - 1) + buf.slice(pos); pos--; } }
176
+ else if (k === "delete") { buf = buf.slice(0, pos) + buf.slice(pos + 1); }
177
+ else if (k === "left") { if (pos > 0) pos--; }
178
+ else if (k === "right") { if (pos < buf.length) pos++; }
179
+ else if (k === "home" || (key.ctrl && k === "a")) pos = 0;
180
+ else if (k === "end" || (key.ctrl && k === "e")) pos = buf.length;
181
+ else if (key.ctrl && k === "u") { buf = ""; pos = 0; }
182
+ else if (k === "up") {
183
+ if (histIdx === hist.length) draft = buf;
184
+ if (histIdx > 0) { histIdx--; buf = hist[histIdx] ?? ""; pos = buf.length; }
185
+ }
186
+ else if (k === "down") {
187
+ if (histIdx < hist.length) {
188
+ histIdx++;
189
+ buf = histIdx === hist.length ? draft : (hist[histIdx] ?? "");
190
+ pos = buf.length;
191
+ }
192
+ }
193
+ else if (str && !key.ctrl && !key.meta && str >= " " && str !== "\x7f") {
194
+ buf = buf.slice(0, pos) + str + buf.slice(pos);
195
+ pos += str.length;
196
+ }
197
+ else return;
198
+ draw(false);
199
+ };
200
+
201
+ process.stdout.write(HIDE);
202
+ readline.emitKeypressEvents(process.stdin);
203
+ if (process.stdin.isTTY) process.stdin.setRawMode(true);
204
+ process.stdin.resume();
205
+ process.stdin.on("keypress", onKey);
206
+ draw(true);
207
+ });
208
+ }
package/src/repl.js CHANGED
@@ -1,291 +1,249 @@
1
- // Interactive REPL — Claude-CLI-style. Launched when `aether-code` is run
2
- // without a task argument.
3
- //
4
- // Behaviors:
5
- // - Banner on startup (version, model, balance, cwd, mode)
6
- // - Persistent message history across prompts within the session
7
- // - Slash commands: /help, /exit, /clear, /balance, /cwd, /yes, /turns
8
- // - Bottom status line is rendered after each turn
9
- // - Ctrl+C: first press cancels in-progress turn, second press exits
10
-
11
- import path from "node:path";
12
- import { runAgent } from "./agent.js";
13
- import { fetchBalance, AetherError } from "./api.js";
14
- import { runSetup } from "./setup.js";
15
- import { c, errorLine, boxLines, sideBySide } from "./render.js";
16
- import { checkForUpdate } from "./update-check.js";
17
- import { promptBox, EXIT_SIGNAL } from "./box-input.js";
18
-
19
- const VERSION = "0.33.0";
20
- const MODEL_NAME = "Aether Core";
21
-
22
- // /model aliases → { id, name }. id=null = server default (gemma / Aether Core).
23
- // Premium models are gated SERVER-SIDE: if you haven't purchased credits, the
24
- // server transparently uses Core instead — selecting one here can't bypass that.
25
- const MODEL_ALIASES = {
26
- core: { id: null, name: "Aether Core" },
27
- gemma: { id: null, name: "Aether Core" },
28
- ultra: { id: "claude-opus-4-6", name: "Aether Ultra" },
29
- opus: { id: "claude-opus-4-6", name: "Aether Ultra" },
30
- };
31
-
32
- const SHORTCUTS = `
33
- ${c.cyan("/help")} Show this help
34
- ${c.cyan("/exit")} Exit (or Ctrl+C twice)
35
- ${c.cyan("/clear")} Clear conversation history (start fresh)
36
- ${c.cyan("/balance")} Refresh and show credit balance
37
- ${c.cyan("/cwd")} ${c.gray("[path]")} Show or change working directory
38
- ${c.cyan("/yes")} Toggle auto-approve mode (skip y/N prompts)
39
- ${c.cyan("/turns")} ${c.gray("<n>")} Set max turns per prompt (default 25)
40
- ${c.cyan("/model")} ${c.gray("[core|ultra]")} Show or switch model (ultra=Opus — premium)
41
-
42
- ${c.gray("Anything else is sent to the agent as your next message.")}
43
- ${c.gray("Conversation history is kept across messages until you /clear.")}
44
- `;
45
-
46
- export async function runRepl({ cwd: initialCwd, autoYes: initialAutoYes, unsafePaths: initialUnsafePaths, maxTurns: initialMaxTurns, model: initialModel = null, mcpManager = null }) {
47
- const initialAlias = Object.values(MODEL_ALIASES).find((a) => a.id === initialModel);
48
- const state = {
49
- cwd: initialCwd,
50
- autoYes: !!initialAutoYes,
51
- unsafePaths: !!initialUnsafePaths,
52
- maxTurns: initialMaxTurns ?? 25,
53
- model: initialModel ?? null,
54
- modelName: initialAlias?.name ?? MODEL_NAME,
55
- messages: [], // accumulates across turns
56
- balance: null,
57
- sessionCredits: 0,
58
- sessionIn: 0,
59
- sessionOut: 0,
60
- };
61
-
62
- // Kick off the npm update check concurrently with the balance fetch so it
63
- // adds no startup latency; the nudge (if any) prints just under the banner.
64
- const updatePromise = checkForUpdate().catch(() => null);
65
-
66
- // Free balance check up front. If no key configured, walk through first-time
67
- // setup flow (open browser → paste key → verify → save).
68
- let needsSetup = false;
69
- try {
70
- const me = await fetchBalance();
71
- state.balance = me.balance;
72
- state.plan = me.plan || "FREE";
73
- } catch (err) {
74
- if (err instanceof AetherError && (err.code === "NO_API_KEY" || err.status === 401)) {
75
- needsSetup = true;
76
- } else {
77
- // Transient network or other — surface but don't block
78
- console.log(c.gray(`(could not fetch balance: ${err.message})`));
79
- }
80
- }
81
-
82
- if (needsSetup) {
83
- const ok = await runSetup();
84
- if (!ok) {
85
- console.log(c.gray("Aborting — no valid API key."));
86
- process.exit(1);
87
- }
88
- // Re-fetch balance now that the key is saved
89
- try {
90
- const me = await fetchBalance();
91
- state.balance = me.balance;
92
- state.plan = me.plan || "FREE";
93
- } catch { /* tolerate — banner just won't show balance */ }
94
- }
95
-
96
- printBanner(state);
97
- const updateNudge = await updatePromise;
98
- if (updateNudge) console.log(updateNudge + "\n");
99
-
100
- // Input: a bordered raw-mode box (box-input.js) — cmd.exe-safe and identical
101
- // everywhere. (Ink's live redraw ghosts in the legacy Windows console, so we
102
- // don't use it.) Each prompt is independent; the tool y/N prompts and the
103
- // ask_user menu run BETWEEN prompts in raw mode too, so nothing overlaps.
104
- const inputHistory = [];
105
-
106
- while (true) {
107
- const raw = await promptBox({ history: inputHistory });
108
- if (raw === EXIT_SIGNAL) { console.log(c.gray("bye.")); return; }
109
- const line = (raw ?? "").trim();
110
- if (!line) continue;
111
-
112
- // promptBox already echoes "› <line>" on submit, so no echo needed here.
113
- inputHistory.push(line);
114
-
115
- // Slash command?
116
- if (line.startsWith("/") || line === "?") {
117
- const handled = await handleSlash(line, state);
118
- if (handled === "exit") return;
119
- printStatusLine(state);
120
- continue;
121
- }
122
-
123
- // Otherwise — send as a message to the agent
124
- const result = await runAgent({
125
- initialPrompt: line,
126
- priorMessages: state.messages.length > 0 ? state.messages : undefined,
127
- cwd: state.cwd,
128
- autoYes: state.autoYes,
129
- unsafePaths: state.unsafePaths,
130
- model: state.model,
131
- maxTurns: state.maxTurns,
132
- mcpManager,
133
- });
134
-
135
- state.sessionCredits += result.totalCredits ?? 0;
136
- state.sessionIn += result.totalIn ?? 0;
137
- state.sessionOut += result.totalOut ?? 0;
138
- if (typeof result.balance === "number") state.balance = result.balance;
139
- if (result.messages) state.messages = result.messages;
140
-
141
- if (!result.ok && result.error) {
142
- console.log("\n" + errorLine(result.error.message || String(result.error)));
143
- // Don't kill the session on a single error — surface it and continue.
144
- }
145
-
146
- printStatusLine(state);
147
- }
148
- }
149
-
150
- /* ───────── slash commands ───────── */
151
-
152
- async function handleSlash(line, state) {
153
- const [cmd, ...rest] = line.replace(/^\//, "").split(/\s+/);
154
- const arg = rest.join(" ").trim();
155
-
156
- switch ((cmd || "").toLowerCase()) {
157
- case "":
158
- case "help":
159
- case "?":
160
- console.log(SHORTCUTS);
161
- break;
162
- case "exit":
163
- case "quit":
164
- case "q":
165
- console.log(c.gray("bye."));
166
- return "exit";
167
- case "clear":
168
- state.messages = [];
169
- state.sessionCredits = 0;
170
- state.sessionIn = 0;
171
- state.sessionOut = 0;
172
- console.log(c.gray("Conversation cleared."));
173
- break;
174
- case "balance": {
175
- try {
176
- const me = await fetchBalance();
177
- state.balance = me.balance;
178
- state.plan = me.plan || "FREE";
179
- console.log(
180
- c.cyan(`balance: ${me.balance.toLocaleString()} credits`) +
181
- c.gray(` · plan: ${me.plan || "FREE"} (${me.planCredits ?? 0} plan + ${me.topupCredits ?? 0} topup)`),
182
- );
183
- } catch (err) {
184
- console.log(errorLine(err.message || String(err)));
185
- }
186
- break;
187
- }
188
- case "cwd":
189
- if (arg) {
190
- const next = path.resolve(arg);
191
- try {
192
- process.chdir(next);
193
- state.cwd = next;
194
- console.log(c.gray(`cwd → ${state.cwd}`));
195
- } catch (err) {
196
- console.log(errorLine(err.message));
197
- }
198
- } else {
199
- console.log(c.gray(`cwd: ${state.cwd}`));
200
- }
201
- break;
202
- case "yes":
203
- state.autoYes = !state.autoYes;
204
- console.log(c.gray(`auto-yes: ${state.autoYes ? "on (writes/shells will skip y/N)" : "off"}`));
205
- break;
206
- case "turns": {
207
- const n = parseInt(arg, 10);
208
- if (!Number.isFinite(n) || n < 1 || n > 200) {
209
- console.log(errorLine(`/turns expects 1..200, got "${arg}"`));
210
- } else {
211
- state.maxTurns = n;
212
- console.log(c.gray(`max turns: ${state.maxTurns}`));
213
- }
214
- break;
215
- }
216
- case "model": {
217
- const key = (arg || "").trim().toLowerCase();
218
- if (!key) {
219
- console.log(c.gray(`model: ${state.modelName}`));
220
- console.log(c.gray("switch with /model core | ultra (ultra=Opus — premium, need credits)"));
221
- } else if (MODEL_ALIASES[key]) {
222
- state.model = MODEL_ALIASES[key].id;
223
- state.modelName = MODEL_ALIASES[key].name;
224
- const premium = state.model !== null;
225
- console.log(
226
- c.gray(`model → ${c.cyan(state.modelName)}`) +
227
- (premium ? c.gray(" (premium — needs purchased credits, else falls back to Core)") : ""),
228
- );
229
- } else {
230
- console.log(errorLine(`Unknown model "${key}". Try: core, ultra`));
231
- }
232
- break;
233
- }
234
- default:
235
- console.log(errorLine(`Unknown command: /${cmd}. Type ${c.cyan("/help")} for shortcuts.`));
236
- }
237
- return null;
238
- }
239
-
240
- /* ───────── banner + status ───────── */
241
-
242
- const visLen = (s) => s.replace(/\x1b\[[0-9;]*m/g, "").length;
243
- const shortenPath = (p, max) => (p.length <= max ? p : "..." + p.slice(p.length - max + 3));
244
-
245
- // Short, hand-curated highlights shown in the "What's new" box. Update with
246
- // notable releases — keep it to ~3 lines so it balances the banner height.
247
- const WHATS_NEW = [
248
- "Image support — @file.png in your prompt",
249
- "Live token counter + turn stats",
250
- "Enhanced spinner with mm:ss timing",
251
- ];
252
-
253
- function printBanner(state) {
254
- const mode = state.autoYes ? (state.unsafePaths ? "skip-permissions" : "auto-yes") : "review mode";
255
- const credits = state.balance != null ? `${state.balance.toLocaleString()} credits` : "";
256
- const left = boxLines(
257
- [
258
- c.bold(c.magenta("aether")) + c.gray(" · ") + c.bold(state.modelName) + c.gray(" v" + VERSION),
259
- c.gray("uncensored AI coding agent"),
260
- c.gray((credits ? credits + " · " : "") + mode),
261
- c.gray(shortenPath(state.cwd, 52)),
262
- ],
263
- { color: c.magenta, padX: 2 },
264
- );
265
- const right = boxLines(
266
- [c.bold(c.cyan("What's new")), ...WHATS_NEW.map((s) => c.gray("• " + s))],
267
- { color: c.cyan, padX: 2 },
268
- );
269
-
270
- console.log("");
271
- const cols = process.stdout.columns || 80;
272
- // Only place the two boxes side by side when there's room; otherwise the
273
- // banner alone (narrow terminals would wrap and tear the second box).
274
- if (cols >= visLen(left[0]) + visLen(right[0]) + 4) {
275
- console.log(sideBySide(left, right, 3));
276
- } else {
277
- console.log(left.join("\n"));
278
- }
279
- console.log("");
280
- }
281
-
282
- function printStatusLine(state) {
283
- const parts = [];
284
- parts.push(c.gray(`session: ${state.sessionCredits} cr · ${state.sessionIn}→${state.sessionOut} tokens`));
285
- if (state.balance != null) parts.push(c.gray(`balance: ${state.balance.toLocaleString()}`));
286
- if (state.messages.length > 0) {
287
- parts.push(c.gray(`history: ${state.messages.length} msg${state.messages.length === 1 ? "" : "s"}`));
288
- }
289
- parts.push(c.cyan(state.autoYes ? "auto-yes" : "review"));
290
- console.log(c.dim(parts.join(" · ")));
291
- }
1
+ // Interactive REPL — Claude-CLI-style. Launched when `aether-code` is run
2
+ // without a task argument.
3
+
4
+ import path from "node:path";
5
+ import { runAgent } from "./agent.js";
6
+ import { fetchBalance, AetherError } from "./api.js";
7
+ import { runSetup } from "./setup.js";
8
+ import { c, errorLine } from "./render.js";
9
+ import { autoUpdate } from "./update-check.js";
10
+ import { promptBox, EXIT_SIGNAL } from "./box-input.js";
11
+
12
+ const VERSION = "0.33.2";
13
+ const MODEL_NAME = "Aether Core";
14
+
15
+ const MODEL_ALIASES = {
16
+ core: { id: null, name: "Aether Core" },
17
+ gemma: { id: null, name: "Aether Core" },
18
+ ultra: { id: "claude-opus-4-6", name: "Aether Ultra" },
19
+ opus: { id: "claude-opus-4-6", name: "Aether Ultra" },
20
+ };
21
+
22
+ const SHORTCUTS = `
23
+ ${c.cyan("/help")} Show this help
24
+ ${c.cyan("/exit")} Exit (or Ctrl+C twice)
25
+ ${c.cyan("/clear")} Clear conversation history (start fresh)
26
+ ${c.cyan("/balance")} Refresh and show credit balance
27
+ ${c.cyan("/cwd")} ${c.gray("[path]")} Show or change working directory
28
+ ${c.cyan("/yes")} Toggle auto-approve mode (skip y/N prompts)
29
+ ${c.cyan("/turns")} ${c.gray("<n>")} Set max turns per prompt (default 25)
30
+ ${c.cyan("/model")} ${c.gray("[core|ultra]")} Show or switch model (ultra=Opus — premium)
31
+
32
+ ${c.gray("Anything else is sent to the agent as your next message.")}
33
+ ${c.gray("Conversation history is kept across messages until you /clear.")}
34
+ `;
35
+
36
+ export async function runRepl({ cwd: initialCwd, autoYes: initialAutoYes, unsafePaths: initialUnsafePaths, maxTurns: initialMaxTurns, model: initialModel = null, mcpManager = null }) {
37
+ const initialAlias = Object.values(MODEL_ALIASES).find((a) => a.id === initialModel);
38
+ const state = {
39
+ cwd: initialCwd,
40
+ autoYes: !!initialAutoYes,
41
+ unsafePaths: !!initialUnsafePaths,
42
+ maxTurns: initialMaxTurns ?? 25,
43
+ model: initialModel ?? null,
44
+ modelName: initialAlias?.name ?? MODEL_NAME,
45
+ messages: [],
46
+ balance: null,
47
+ sessionCredits: 0,
48
+ sessionIn: 0,
49
+ sessionOut: 0,
50
+ };
51
+
52
+ // Auto-update + balance fetch in parallel — zero startup latency added.
53
+ const updatePromise = autoUpdate().catch(() => null);
54
+
55
+ let needsSetup = false;
56
+ try {
57
+ const me = await fetchBalance();
58
+ state.balance = me.balance;
59
+ state.plan = me.plan || "FREE";
60
+ } catch (err) {
61
+ if (err instanceof AetherError && (err.code === "NO_API_KEY" || err.status === 401)) {
62
+ needsSetup = true;
63
+ } else {
64
+ console.log(c.gray(`(could not fetch balance: ${err.message})`));
65
+ }
66
+ }
67
+
68
+ if (needsSetup) {
69
+ const ok = await runSetup();
70
+ if (!ok) {
71
+ console.log(c.gray("Aborting — no valid API key."));
72
+ process.exit(1);
73
+ }
74
+ try {
75
+ const me = await fetchBalance();
76
+ state.balance = me.balance;
77
+ state.plan = me.plan || "FREE";
78
+ } catch { /* tolerate */ }
79
+ }
80
+
81
+ printBanner(state);
82
+ const updateMsg = await updatePromise;
83
+ if (updateMsg) console.log(updateMsg);
84
+ console.log("");
85
+
86
+ const inputHistory = [];
87
+
88
+ while (true) {
89
+ const raw = await promptBox({ history: inputHistory });
90
+ if (raw === EXIT_SIGNAL) { console.log(c.gray("bye.")); return; }
91
+ const line = (raw ?? "").trim();
92
+ if (!line) continue;
93
+
94
+ inputHistory.push(line);
95
+
96
+ if (line.startsWith("/") || line === "?") {
97
+ const handled = await handleSlash(line, state);
98
+ if (handled === "exit") return;
99
+ printStatusLine(state);
100
+ continue;
101
+ }
102
+
103
+ const result = await runAgent({
104
+ initialPrompt: line,
105
+ priorMessages: state.messages.length > 0 ? state.messages : undefined,
106
+ cwd: state.cwd,
107
+ autoYes: state.autoYes,
108
+ unsafePaths: state.unsafePaths,
109
+ model: state.model,
110
+ maxTurns: state.maxTurns,
111
+ mcpManager,
112
+ });
113
+
114
+ state.sessionCredits += result.totalCredits ?? 0;
115
+ state.sessionIn += result.totalIn ?? 0;
116
+ state.sessionOut += result.totalOut ?? 0;
117
+ if (typeof result.balance === "number") state.balance = result.balance;
118
+ if (result.messages) state.messages = result.messages;
119
+
120
+ if (!result.ok && result.error) {
121
+ console.log("\n" + errorLine(result.error.message || String(result.error)));
122
+ }
123
+
124
+ printStatusLine(state);
125
+ }
126
+ }
127
+
128
+ /* ───────── slash commands ───────── */
129
+
130
+ async function handleSlash(line, state) {
131
+ const [cmd, ...rest] = line.replace(/^\//, "").split(/\s+/);
132
+ const arg = rest.join(" ").trim();
133
+
134
+ switch ((cmd || "").toLowerCase()) {
135
+ case "":
136
+ case "help":
137
+ case "?":
138
+ console.log(SHORTCUTS);
139
+ break;
140
+ case "exit":
141
+ case "quit":
142
+ case "q":
143
+ console.log(c.gray("bye."));
144
+ return "exit";
145
+ case "clear":
146
+ state.messages = [];
147
+ state.sessionCredits = 0;
148
+ state.sessionIn = 0;
149
+ state.sessionOut = 0;
150
+ console.log(c.gray("Conversation cleared."));
151
+ break;
152
+ case "balance": {
153
+ try {
154
+ const me = await fetchBalance();
155
+ state.balance = me.balance;
156
+ state.plan = me.plan || "FREE";
157
+ console.log(
158
+ c.cyan(`balance: ${me.balance.toLocaleString()} credits`) +
159
+ c.gray(` · plan: ${me.plan || "FREE"} (${me.planCredits ?? 0} plan + ${me.topupCredits ?? 0} topup)`),
160
+ );
161
+ } catch (err) {
162
+ console.log(errorLine(err.message || String(err)));
163
+ }
164
+ break;
165
+ }
166
+ case "cwd":
167
+ if (arg) {
168
+ const next = path.resolve(arg);
169
+ try {
170
+ process.chdir(next);
171
+ state.cwd = next;
172
+ console.log(c.gray(`cwd → ${state.cwd}`));
173
+ } catch (err) {
174
+ console.log(errorLine(err.message));
175
+ }
176
+ } else {
177
+ console.log(c.gray(`cwd: ${state.cwd}`));
178
+ }
179
+ break;
180
+ case "yes":
181
+ state.autoYes = !state.autoYes;
182
+ console.log(c.gray(`auto-yes: ${state.autoYes ? "on (writes/shells will skip y/N)" : "off"}`));
183
+ break;
184
+ case "turns": {
185
+ const n = parseInt(arg, 10);
186
+ if (!Number.isFinite(n) || n < 1 || n > 200) {
187
+ console.log(errorLine(`/turns expects 1..200, got "${arg}"`));
188
+ } else {
189
+ state.maxTurns = n;
190
+ console.log(c.gray(`max turns: ${state.maxTurns}`));
191
+ }
192
+ break;
193
+ }
194
+ case "model": {
195
+ const key = (arg || "").trim().toLowerCase();
196
+ if (!key) {
197
+ console.log(c.gray(`model: ${state.modelName}`));
198
+ console.log(c.gray("switch with /model core | ultra (ultra=Opus — premium, need credits)"));
199
+ } else if (MODEL_ALIASES[key]) {
200
+ state.model = MODEL_ALIASES[key].id;
201
+ state.modelName = MODEL_ALIASES[key].name;
202
+ const premium = state.model !== null;
203
+ console.log(
204
+ c.gray(`model → ${c.cyan(state.modelName)}`) +
205
+ (premium ? c.gray(" (premium — needs purchased credits, else falls back to Core)") : ""),
206
+ );
207
+ } else {
208
+ console.log(errorLine(`Unknown model "${key}". Try: core, ultra`));
209
+ }
210
+ break;
211
+ }
212
+ default:
213
+ console.log(errorLine(`Unknown command: /${cmd}. Type ${c.cyan("/help")} for shortcuts.`));
214
+ }
215
+ return null;
216
+ }
217
+
218
+ /* ───────── banner + status ───────── */
219
+
220
+ const shortenPath = (p, max) => (p.length <= max ? p : "..." + p.slice(p.length - max + 3));
221
+
222
+ function printBanner(state) {
223
+ const credits = state.balance != null ? `${state.balance.toLocaleString()} credits` : "";
224
+ const mode = state.autoYes ? (state.unsafePaths ? "skip-permissions" : "auto-yes") : "review";
225
+
226
+ // No boxes — plain text, exactly like Claude Code
227
+ console.log("");
228
+ console.log(
229
+ " " + c.bold(c.cyan("✦")) + " " +
230
+ c.bold("Aether Code") + " " + c.dim("v" + VERSION),
231
+ );
232
+ console.log(
233
+ " " + state.modelName +
234
+ (credits ? c.dim(" · ") + credits : "") +
235
+ (state.plan && state.plan !== "FREE" ? c.dim(" · ") + c.cyan(state.plan) : ""),
236
+ );
237
+ console.log(" " + c.dim(shortenPath(state.cwd, 60)));
238
+ }
239
+
240
+ function printStatusLine(state) {
241
+ const parts = [];
242
+ parts.push(c.gray(`session: ${state.sessionCredits} cr · ${state.sessionIn}→${state.sessionOut} tokens`));
243
+ if (state.balance != null) parts.push(c.gray(`balance: ${state.balance.toLocaleString()}`));
244
+ if (state.messages.length > 0) {
245
+ parts.push(c.gray(`history: ${state.messages.length} msg${state.messages.length === 1 ? "" : "s"}`));
246
+ }
247
+ parts.push(c.cyan(state.autoYes ? "auto-yes" : "review"));
248
+ console.log(c.dim(parts.join(" · ")));
249
+ }
@@ -1,60 +1,117 @@
1
- // Startup update check — like Claude Code / npm itself nudging you when a newer
2
- // version is published. Never throws, bounded by a short timeout so it can't
3
- // slow or block startup; silent when offline or already current.
4
-
5
- import { readFileSync } from "node:fs";
6
- import { fileURLToPath } from "node:url";
7
- import { dirname, join } from "node:path";
8
- import { c } from "./render.js";
9
-
10
- export function currentVersion() {
11
- try {
12
- const p = join(dirname(fileURLToPath(import.meta.url)), "..", "package.json");
13
- return JSON.parse(readFileSync(p, "utf8")).version || null;
14
- } catch {
15
- return null;
16
- }
17
- }
18
-
19
- // Compare two "x.y.z" strings. Returns >0 if a is newer than b.
20
- export function cmpVersion(a, b) {
21
- const pa = String(a).split(".").map(Number);
22
- const pb = String(b).split(".").map(Number);
23
- for (let i = 0; i < 3; i++) {
24
- const d = (pa[i] || 0) - (pb[i] || 0);
25
- if (d !== 0) return d;
26
- }
27
- return 0;
28
- }
29
-
30
- /**
31
- * Resolve a one-line "update available" nudge if the npm registry has a newer
32
- * version than the installed one — otherwise null. Bounded to ~2s; any failure
33
- * (offline, timeout, registry hiccup) resolves to null silently.
34
- */
35
- export async function checkForUpdate({ fetchImpl = fetch, timeoutMs = 2000 } = {}) {
36
- const current = currentVersion();
37
- if (!current) return null;
38
- try {
39
- const ac = new AbortController();
40
- const t = setTimeout(() => ac.abort(), timeoutMs);
41
- let res;
42
- try {
43
- res = await fetchImpl("https://registry.npmjs.org/aether-code/latest", { signal: ac.signal });
44
- } finally {
45
- clearTimeout(t);
46
- }
47
- if (!res || !res.ok) return null;
48
- const latest = (await res.json())?.version;
49
- if (latest && cmpVersion(latest, current) > 0) {
50
- return (
51
- c.yellow("update available: ") +
52
- c.gray(current) + " -> " + c.bold(c.green(latest)) +
53
- c.gray(" · run ") + c.cyan("npm i -g aether-code@latest")
54
- );
55
- }
56
- } catch {
57
- /* offline / aborted / parse error — stay silent */
58
- }
59
- return null;
60
- }
1
+ // Startup update check + auto-update. On every REPL launch, checks the npm
2
+ // registry and silently installs the latest version in the background if one
3
+ // exists. Never throws, bounded by a short timeout so it can't slow startup.
4
+
5
+ import { readFileSync, writeFileSync, existsSync } from "node:fs";
6
+ import { fileURLToPath } from "node:url";
7
+ import { dirname, join } from "node:path";
8
+ import { tmpdir } from "node:os";
9
+ import { spawn } from "node:child_process";
10
+ import { c } from "./render.js";
11
+
12
+ export function currentVersion() {
13
+ try {
14
+ const p = join(dirname(fileURLToPath(import.meta.url)), "..", "package.json");
15
+ return JSON.parse(readFileSync(p, "utf8")).version || null;
16
+ } catch {
17
+ return null;
18
+ }
19
+ }
20
+
21
+ // Compare two "x.y.z" strings. Returns >0 if a is newer than b.
22
+ export function cmpVersion(a, b) {
23
+ const pa = String(a).split(".").map(Number);
24
+ const pb = String(b).split(".").map(Number);
25
+ for (let i = 0; i < 3; i++) {
26
+ const d = (pa[i] || 0) - (pb[i] || 0);
27
+ if (d !== 0) return d;
28
+ }
29
+ return 0;
30
+ }
31
+
32
+ const COOLDOWN_FILE = join(tmpdir(), "aether-update-ts");
33
+ const COOLDOWN_MS = 3600_000; // 1 hour
34
+
35
+ /**
36
+ * Check for updates. If a newer version exists on npm, spawn a background
37
+ * `npm install -g` to auto-install it. Returns a one-line status message
38
+ * or null. Cooldown: only checks once per hour.
39
+ */
40
+ export async function autoUpdate({ fetchImpl = fetch, timeoutMs = 2000 } = {}) {
41
+ const current = currentVersion();
42
+ if (!current) return null;
43
+
44
+ // Skip if we checked less than 1 hour ago
45
+ try {
46
+ const ts = parseInt(readFileSync(COOLDOWN_FILE, "utf8"), 10);
47
+ if (Date.now() - ts < COOLDOWN_MS) return null;
48
+ } catch { /* no file or parse error — check now */ }
49
+
50
+ try {
51
+ const ac = new AbortController();
52
+ const t = setTimeout(() => ac.abort(), timeoutMs);
53
+ let res;
54
+ try {
55
+ res = await fetchImpl("https://registry.npmjs.org/aether-code/latest", { signal: ac.signal });
56
+ } finally {
57
+ clearTimeout(t);
58
+ }
59
+ if (!res || !res.ok) return null;
60
+ const latest = (await res.json())?.version;
61
+
62
+ // Write cooldown regardless of whether an update is available
63
+ try { writeFileSync(COOLDOWN_FILE, String(Date.now())); } catch { /* ignore */ }
64
+
65
+ if (!latest || cmpVersion(latest, current) <= 0) return null;
66
+
67
+ // Spawn background npm install — detached so it doesn't block the CLI.
68
+ // On Windows, `npm` is a cmd script, so shell:true is required.
69
+ const child = spawn("npm", ["install", "-g", `aether-code@${latest}`], {
70
+ detached: true,
71
+ stdio: "ignore",
72
+ shell: true,
73
+ windowsHide: true,
74
+ });
75
+ child.unref();
76
+
77
+ return (
78
+ c.cyan("↑ auto-updating ") +
79
+ c.gray(current) + c.gray(" → ") + c.bold(c.green(latest)) +
80
+ c.gray(" (background — applies next launch)")
81
+ );
82
+ } catch {
83
+ /* offline / aborted / parse error — stay silent */
84
+ }
85
+ return null;
86
+ }
87
+
88
+ /**
89
+ * Legacy nudge-only check (kept for the test suite). Same as before: returns
90
+ * a one-line "update available" string or null.
91
+ */
92
+ export async function checkForUpdate({ fetchImpl = fetch, timeoutMs = 2000 } = {}) {
93
+ const current = currentVersion();
94
+ if (!current) return null;
95
+ try {
96
+ const ac = new AbortController();
97
+ const t = setTimeout(() => ac.abort(), timeoutMs);
98
+ let res;
99
+ try {
100
+ res = await fetchImpl("https://registry.npmjs.org/aether-code/latest", { signal: ac.signal });
101
+ } finally {
102
+ clearTimeout(t);
103
+ }
104
+ if (!res || !res.ok) return null;
105
+ const latest = (await res.json())?.version;
106
+ if (latest && cmpVersion(latest, current) > 0) {
107
+ return (
108
+ c.yellow("update available: ") +
109
+ c.gray(current) + " -> " + c.bold(c.green(latest)) +
110
+ c.gray(" · run ") + c.cyan("npm i -g aether-code@latest")
111
+ );
112
+ }
113
+ } catch {
114
+ /* offline / aborted / parse error — stay silent */
115
+ }
116
+ return null;
117
+ }