@mumbrane/arrakis 0.2.0 → 0.3.0

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.
package/README.md CHANGED
@@ -12,15 +12,20 @@ Requires Node.js 18.17 or later.
12
12
 
13
13
  ## Set up
14
14
 
15
- Arrakis talks to any OpenAI-compatible `/chat/completions` API with tool calling (your own model server, vLLM, SGLang and similar).
15
+ Run `arrakis`. The first time, it walks you through setup:
16
16
 
17
- ```bash
18
- arrakis config set baseUrl https://api.example.com/v1
19
- arrakis config set apiKey YOUR_KEY
20
- arrakis config set model your-model-name
21
- ```
17
+ 1. **Pick a provider** with the arrow keys: Anthropic (Claude), OpenAI, Google Gemini, OpenRouter, xAI, DeepSeek, Mistral, Groq, Together AI, Ollama (local) or any other OpenAI-compatible API.
18
+ 2. **Paste your API key.** It's hidden as you type, checked against the provider, and saved to `~/.arrakis/config.json` (readable only by you).
19
+ 3. **Pick a model** from the provider's live model list. Type to search.
20
+
21
+ That's it. Switch any time inside a session:
22
+
23
+ - `/model` picks another model from the same provider.
24
+ - `/provider` switches provider or updates your key. Each provider remembers its own key and model.
25
+
26
+ Outside a session: `arrakis setup` reruns setup, `arrakis models` lists models, `arrakis logout` removes saved keys.
22
27
 
23
- If `model` isn't set, arrakis uses the first model listed at `/models`. Settings live in `~/.arrakis/config.json`. You can also set them with environment variables (`ARRAKIS_BASE_URL`, `ARRAKIS_API_KEY`, `ARRAKIS_MODEL`, `ARRAKIS_CONTEXT_WINDOW`), which take precedence over the file.
28
+ For CI or scripts, skip setup with environment variables: `ARRAKIS_PROVIDER` (e.g. `anthropic`), `ARRAKIS_API_KEY`, `ARRAKIS_MODEL`, or `ARRAKIS_BASE_URL` for any OpenAI-compatible endpoint.
24
29
 
25
30
  ## Use
26
31
 
@@ -40,7 +45,8 @@ In a session:
40
45
  | `/help` | List commands |
41
46
  | `/status` | Session, model, context usage, permissions |
42
47
  | `/compact` | Summarize history to free up context |
43
- | `/model [name]` | Show or switch the model |
48
+ | `/model [name]` | Pick a model from your provider |
49
+ | `/provider` | Switch provider or update your API key |
44
50
  | `/clear` | Start a new session |
45
51
  | `/yolo` | Toggle running tool calls without asking |
46
52
  | `/exit` | Quit (or Ctrl-D) |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mumbrane/arrakis",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Arrakis: a coding agent for your terminal, built by Mumbrane",
5
5
  "type": "module",
6
6
  "main": "./index.js",
package/src/agent.js CHANGED
@@ -50,6 +50,8 @@ export class Agent {
50
50
  return false;
51
51
  } catch (err) {
52
52
  if (err.name === 'AbortError') this.ui.info('Interrupted.');
53
+ else if (err.status === 401 || err.status === 403) this.ui.error(`${err.message}\nYour API key was rejected. Run /provider (or: arrakis setup) to update it.`);
54
+ else if (err.status === 404) this.ui.error(`${err.message}\nThe model may not exist for this provider. Pick another with /model.`);
53
55
  else this.ui.error(err.message);
54
56
  return false;
55
57
  } finally {
package/src/cli.js CHANGED
@@ -1,6 +1,9 @@
1
1
  import { parseArgs } from 'node:util';
2
- import { loadConfig, setConfigValue, readConfigFile, maskSecret, CONFIG_KEYS, CONFIG_PATH } from './config.js';
3
- import { resolveModel } from './client.js';
2
+ import { loadConfig, setConfigValue, readConfigFile, maskSecret, saveProvider, removeProviderKeys, CONFIG_KEYS, CONFIG_PATH } from './config.js';
3
+ import { resolveModel, listModels } from './client.js';
4
+ import { getProvider } from './providers.js';
5
+ import { createPrompts } from './prompts.js';
6
+ import { runSetup, pickModel } from './setup.js';
4
7
  import { Session, listSessions } from './session.js';
5
8
  import { Agent, estimateTokens } from './agent.js';
6
9
  import { Permissions } from './permissions.js';
@@ -12,13 +15,16 @@ import { VERSION } from './version.js';
12
15
  const HELP = `arrakis ${VERSION} — a coding agent for your terminal
13
16
 
14
17
  Usage
15
- arrakis [prompt] Start an interactive session (optionally with a first message)
18
+ arrakis [prompt] Start an interactive session (first run walks you through setup)
16
19
  arrakis -p "prompt" Run one task non-interactively and print the answer
17
20
  arrakis -c Continue the most recent session in this directory
18
21
  arrakis -r <id> Resume a session by id (or id prefix)
22
+ arrakis setup Choose a provider, enter an API key and pick a model
23
+ arrakis models List the models your provider offers
19
24
  arrakis sessions List recent sessions
20
25
  arrakis config Show configuration
21
- arrakis config set <key> <v> Set a config value (baseUrl, apiKey, model, contextWindow, maxTokens)
26
+ arrakis config set <key> <v> Set a value (provider, baseUrl, apiKey, model, contextWindow, maxTokens)
27
+ arrakis logout Remove saved API keys
22
28
 
23
29
  Options
24
30
  -p, --print Non-interactive: print the response and exit (reads stdin if no prompt)
@@ -31,13 +37,14 @@ Options
31
37
  -v, --version Print version
32
38
  -h, --help Show this help
33
39
 
34
- Environment
35
- ARRAKIS_BASE_URL, ARRAKIS_API_KEY, ARRAKIS_MODEL, ARRAKIS_CONTEXT_WINDOW, ARRAKIS_HOME`;
40
+ Environment (overrides the config file)
41
+ ARRAKIS_PROVIDER, ARRAKIS_BASE_URL, ARRAKIS_API_KEY, ARRAKIS_MODEL, ARRAKIS_CONTEXT_WINDOW, ARRAKIS_HOME`;
36
42
 
37
43
  const SLASH_HELP = `/help Show commands
38
44
  /clear Start a new session
39
45
  /compact Summarize history to free up context
40
- /model [name] Show or switch the model
46
+ /model [name] Pick a model from your provider (or set one by name)
47
+ /provider Switch provider or update your API key
41
48
  /sessions List recent sessions
42
49
  /status Session, model, context usage and permissions
43
50
  /yolo Toggle allowing all tool calls without asking
@@ -48,6 +55,12 @@ End a line with \\ to continue on the next line. Ctrl-C interrupts the model.`;
48
55
  export async function main(argv) {
49
56
  if (argv[0] === 'config') return configCommand(argv.slice(1));
50
57
  if (argv[0] === 'sessions') return sessionsCommand();
58
+ if (argv[0] === 'setup' || argv[0] === 'login') return setupCommand();
59
+ if (argv[0] === 'models') return modelsCommand();
60
+ if (argv[0] === 'logout') {
61
+ removeProviderKeys();
62
+ return console.log(`Removed saved API keys from ${CONFIG_PATH}`);
63
+ }
51
64
 
52
65
  const { values, positionals } = parseArgs({
53
66
  args: argv,
@@ -73,7 +86,20 @@ export async function main(argv) {
73
86
  if (print && !prompt) throw new Error('No prompt given. Usage: arrakis -p "your task"');
74
87
 
75
88
  const cwd = process.cwd();
76
- const config = loadConfig({ model: values.model, baseUrl: values['base-url'] });
89
+ let config = loadConfig({ model: values.model, baseUrl: values['base-url'] });
90
+ const ui = new UI({ print });
91
+ const prompts = createPrompts(ui);
92
+ if (!config.configured) {
93
+ if (print) throw new Error('arrakis is not set up yet. Run `arrakis` once to choose a provider and enter an API key.');
94
+ ui.start();
95
+ const next = await runSetup({ ui, prompts, welcome: true });
96
+ if (!next) {
97
+ ui.close();
98
+ ui.write(ui.out, 'Setup cancelled. Run arrakis again when you are ready.\n');
99
+ return;
100
+ }
101
+ config = loadConfig({ model: values.model, baseUrl: values['base-url'] });
102
+ }
77
103
  config.model = await resolveModel(config);
78
104
 
79
105
  let session;
@@ -83,7 +109,6 @@ export async function main(argv) {
83
109
  if (!session) throw new Error(`No previous session in ${cwd}. Start one with: arrakis`);
84
110
  } else session = Session.create({ cwd, model: config.model });
85
111
 
86
- const ui = new UI({ print });
87
112
  const permissions = new Permissions({
88
113
  ui,
89
114
  mode: values.yolo ? 'yolo' : print ? 'deny' : 'ask',
@@ -100,10 +125,10 @@ export async function main(argv) {
100
125
  process.exitCode = ok ? 0 : 1;
101
126
  return;
102
127
  }
103
- await interactive({ agent, ui, config, cwd, firstPrompt: prompt });
128
+ await interactive({ agent, ui, prompts, config, cwd, firstPrompt: prompt });
104
129
  }
105
130
 
106
- async function interactive({ agent, ui, config, cwd, firstPrompt }) {
131
+ async function interactive({ agent, ui, prompts, config, cwd, firstPrompt }) {
107
132
  const c = ui.c;
108
133
  ui.start();
109
134
  let armedExit = false;
@@ -120,7 +145,7 @@ async function interactive({ agent, ui, config, cwd, firstPrompt }) {
120
145
 
121
146
  const instr = loadProjectInstructions(cwd).filter((i) => i.text.trim());
122
147
  ui.write(ui.out, `\n${c.accent(c.bold(' ◆ arrakis'))} ${c.dim(`v${VERSION}`)}\n`);
123
- ui.write(ui.out, c.dim(` model ${config.model} · ${cwd}\n`));
148
+ ui.write(ui.out, c.dim(` ${config.model} · ${config.providerName || config.baseUrl} · ${cwd}\n`));
124
149
  if (instr.length) ui.write(ui.out, c.dim(` instructions: ${instr.map((i) => i.file).join(', ')}\n`));
125
150
  if (agent.session.messages.length) ui.write(ui.out, c.dim(` resumed session ${agent.session.id} (${agent.session.messages.length} messages)\n`));
126
151
  ui.write(ui.out, c.dim(' /help for commands · Ctrl-C to interrupt · Ctrl-D to quit\n\n'));
@@ -133,7 +158,7 @@ async function interactive({ agent, ui, config, cwd, firstPrompt }) {
133
158
  const text = line.trim();
134
159
  if (!text) continue;
135
160
  if (text.startsWith('/')) {
136
- if ((await slashCommand(text, { agent, ui, config, cwd })) === 'exit') break;
161
+ if ((await slashCommand(text, { agent, ui, prompts, config, cwd })) === 'exit') break;
137
162
  continue;
138
163
  }
139
164
  await agent.send(text);
@@ -143,7 +168,7 @@ async function interactive({ agent, ui, config, cwd, firstPrompt }) {
143
168
  ui.write(ui.out, c.dim(`Session saved. Resume with: arrakis -r ${agent.session.id}\n`));
144
169
  }
145
170
 
146
- async function slashCommand(text, { agent, ui, config, cwd }) {
171
+ async function slashCommand(text, { agent, ui, prompts, config, cwd }) {
147
172
  const [cmd, ...rest] = text.slice(1).split(/\s+/);
148
173
  const arg = rest.join(' ');
149
174
  const c = ui.c;
@@ -171,12 +196,32 @@ async function slashCommand(text, { agent, ui, config, cwd }) {
171
196
  }
172
197
  break;
173
198
  }
174
- case 'model':
175
- if (arg) {
176
- config.model = arg;
177
- ui.info(`Model set to ${arg} for this session. To make it the default: arrakis config set model ${arg}`);
178
- } else ui.info(`Model: ${config.model}`);
199
+ case 'model': {
200
+ let chosen = arg ? { id: arg } : null;
201
+ if (!arg) {
202
+ let models = [];
203
+ try {
204
+ models = await listModels(config);
205
+ } catch (err) {
206
+ ui.error(`Couldn't list models: ${err.message}`);
207
+ }
208
+ chosen = await pickModel({ ui, prompts, provider: getProvider(config.provider), models, current: config.model });
209
+ }
210
+ if (!chosen) break;
211
+ config.model = chosen.id;
212
+ if (chosen.contextWindow) config.contextWindow = chosen.contextWindow;
213
+ if (config.provider) saveProvider(config.provider, { model: chosen.id, contextWindow: chosen.contextWindow || undefined });
214
+ ui.info(`Now using ${chosen.id}.`);
215
+ break;
216
+ }
217
+ case 'provider':
218
+ case 'setup':
219
+ case 'login': {
220
+ if (agent.session.messages.length) ui.info('Your conversation carries over to the new provider.');
221
+ const next = await runSetup({ ui, prompts });
222
+ if (next) Object.assign(config, next);
179
223
  break;
224
+ }
180
225
  case 'sessions':
181
226
  printSessions(ui.out, 10);
182
227
  break;
@@ -185,7 +230,8 @@ async function slashCommand(text, { agent, ui, config, cwd }) {
185
230
  ui.write(ui.out, [
186
231
  `session ${agent.session.id}`,
187
232
  `log ${agent.session.file}`,
188
- `model ${config.model} @ ${config.baseUrl}`,
233
+ `provider ${config.providerName || 'custom'} (${config.baseUrl})`,
234
+ `model ${config.model}`,
189
235
  `context ~${used.toLocaleString()} / ${config.contextWindow.toLocaleString()} tokens (${Math.round((used / config.contextWindow) * 100)}%)`,
190
236
  `permissions ${agent.permissions.mode}${agent.permissions.allowed.size ? ` (always allowed: ${[...agent.permissions.allowed].join(', ')})` : ''}`,
191
237
  `tools ${TOOLS.map((t) => t.name).join(', ')}`,
@@ -218,13 +264,37 @@ function configCommand(args) {
218
264
  const config = loadConfig();
219
265
  const file = readConfigFile();
220
266
  console.log(`Config file: ${CONFIG_PATH}\n`);
267
+ if (!config.configured) console.log('Not set up yet. Run: arrakis setup\n');
268
+ const providerFile = (config.provider && file.providers[config.provider]) || {};
221
269
  for (const [k, spec] of Object.entries(CONFIG_KEYS)) {
222
- const source = process.env[spec.env] ? `env ${spec.env}` : file[k] !== undefined ? 'config file' : 'default';
223
- const value = spec.secret ? maskSecret(config[k]) : config[k] || '(not set)';
224
- console.log(`${k.padEnd(14)} ${String(value).padEnd(36)} ${source}`);
270
+ const inFile = k === 'provider' ? file.provider !== undefined : spec.global ? file[k] !== undefined : providerFile[k] !== undefined;
271
+ const source = process.env[spec.env] ? `env ${spec.env}` : inFile ? 'config file' : 'default';
272
+ let value = spec.secret ? maskSecret(config[k]) : config[k] || '(not set)';
273
+ if (k === 'provider' && config.providerName) value = `${config.provider} (${config.providerName})`;
274
+ console.log(`${k.padEnd(14)} ${String(value).padEnd(40)} ${source}`);
275
+ }
276
+ const others = Object.keys(file.providers).filter((id) => id !== config.provider);
277
+ if (others.length) console.log(`\nOther saved providers: ${others.join(', ')}`);
278
+ }
279
+
280
+ async function setupCommand() {
281
+ const ui = new UI();
282
+ ui.start();
283
+ try {
284
+ await runSetup({ ui, prompts: createPrompts(ui), welcome: !loadConfig().configured });
285
+ } finally {
286
+ ui.close();
225
287
  }
226
288
  }
227
289
 
290
+ async function modelsCommand() {
291
+ const config = loadConfig();
292
+ if (!config.configured) throw new Error('Not set up yet. Run: arrakis setup');
293
+ const models = await listModels(config);
294
+ if (!models.length) return console.log(`${config.providerName || config.baseUrl} listed no models.`);
295
+ for (const m of models) console.log(`${m.id === config.model ? '*' : ' '} ${m.id}${m.contextWindow ? ` (${m.contextWindow.toLocaleString()} tokens)` : ''}`);
296
+ }
297
+
228
298
  function sessionsCommand() {
229
299
  printSessions(process.stdout, 20);
230
300
  }
package/src/client.js CHANGED
@@ -1,4 +1,5 @@
1
1
  // Minimal client for OpenAI-compatible /chat/completions with streaming and tool calls.
2
+ import { getProvider, normalizeModels } from './providers.js';
2
3
 
3
4
  function headers(config) {
4
5
  const h = { 'content-type': 'application/json' };
@@ -6,19 +7,21 @@ function headers(config) {
6
7
  return h;
7
8
  }
8
9
 
9
- async function request(config, pathname, init, { retries = 3 } = {}) {
10
+ async function request(config, pathname, init, { retries = 3, extraHeaders } = {}) {
10
11
  const url = `${config.baseUrl}${pathname}`;
11
12
  for (let attempt = 0; ; attempt++) {
12
13
  let res;
13
14
  try {
14
- res = await fetch(url, { ...init, headers: headers(config) });
15
+ res = await fetch(url, { ...init, headers: extraHeaders ? { 'content-type': 'application/json', ...extraHeaders } : headers(config) });
15
16
  } catch (err) {
16
17
  if (err.name === 'AbortError') throw err;
17
18
  if (attempt < retries) {
18
19
  await sleep(500 * 2 ** attempt, init.signal);
19
20
  continue;
20
21
  }
21
- throw new Error(`Could not reach ${config.baseUrl} (${err.cause?.code || err.message}). Check baseUrl with: arrakis config`);
22
+ const e = new Error(`Could not reach ${config.baseUrl} (${err.cause?.code || err.message}).`);
23
+ e.unreachable = true;
24
+ throw e;
22
25
  }
23
26
  if (res.ok) return res;
24
27
  const retryable = res.status === 429 || res.status >= 500;
@@ -28,7 +31,9 @@ async function request(config, pathname, init, { retries = 3 } = {}) {
28
31
  continue;
29
32
  }
30
33
  const body = await res.text().catch(() => '');
31
- throw new Error(`API error ${res.status} from ${url}: ${body.slice(0, 500)}`);
34
+ const e = new Error(`API error ${res.status} from ${url}: ${body.slice(0, 500)}`);
35
+ e.status = res.status;
36
+ throw e;
32
37
  }
33
38
  }
34
39
 
@@ -80,11 +85,17 @@ export async function completeText({ config, messages, signal }) {
80
85
  return text;
81
86
  }
82
87
 
88
+ // List the chat models the provider offers, newest first when it says.
89
+ export async function listModels(config) {
90
+ const provider = getProvider(config.provider);
91
+ const extraHeaders = provider?.modelsHeaders && config.apiKey ? provider.modelsHeaders(config.apiKey) : undefined;
92
+ const res = await request(config, `/models${provider?.modelsQuery ?? ''}`, { method: 'GET' }, { retries: 1, extraHeaders });
93
+ return normalizeModels(await res.json());
94
+ }
95
+
83
96
  export async function resolveModel(config) {
84
97
  if (config.model) return config.model;
85
- const res = await request(config, '/models', { method: 'GET' }, { retries: 1 });
86
- const json = await res.json();
87
- const id = json.data?.[0]?.id;
88
- if (!id) throw new Error(`No model configured and ${config.baseUrl}/models listed none. Set one with: arrakis config set model <name>`);
89
- return id;
98
+ const models = await listModels(config);
99
+ if (!models.length) throw new Error(`No model configured and ${config.baseUrl}/models listed none. Pick one with: arrakis setup`);
100
+ return models[0].id;
90
101
  }
package/src/config.js CHANGED
@@ -1,60 +1,133 @@
1
1
  import fs from 'node:fs';
2
2
  import os from 'node:os';
3
3
  import path from 'node:path';
4
+ import { getProvider } from './providers.js';
4
5
 
5
6
  export const HOME_DIR = process.env.ARRAKIS_HOME || path.join(os.homedir(), '.arrakis');
6
7
  export const CONFIG_PATH = path.join(HOME_DIR, 'config.json');
7
8
  export const SESSIONS_DIR = path.join(HOME_DIR, 'sessions');
8
9
 
10
+ // Config file shape:
11
+ // {
12
+ // "provider": "anthropic",
13
+ // "providers": { "anthropic": { "apiKey": "...", "model": "...", "contextWindow": 1000000 } },
14
+ // "maxTokens": 0
15
+ // }
16
+ // Each provider keeps its own key and last-used model, so switching back is instant.
17
+
9
18
  export const CONFIG_KEYS = {
10
- baseUrl: { env: 'ARRAKIS_BASE_URL', help: 'OpenAI-compatible API base URL, e.g. https://api.example.com/v1' },
11
- apiKey: { env: 'ARRAKIS_API_KEY', help: 'API key, sent as a Bearer token', secret: true },
12
- model: { env: 'ARRAKIS_MODEL', help: 'Model name (default: first model from /models)' },
19
+ provider: { env: 'ARRAKIS_PROVIDER', help: 'Active provider id (see: arrakis setup)', global: true },
20
+ baseUrl: { env: 'ARRAKIS_BASE_URL', help: 'API base URL (custom provider)' },
21
+ apiKey: { env: 'ARRAKIS_API_KEY', help: 'API key for the active provider', secret: true },
22
+ model: { env: 'ARRAKIS_MODEL', help: 'Model name' },
13
23
  contextWindow: { env: 'ARRAKIS_CONTEXT_WINDOW', help: 'Context window in tokens; history is compacted near 80%', number: true },
14
- maxTokens: { env: 'ARRAKIS_MAX_TOKENS', help: 'Max output tokens per response (optional)', number: true },
24
+ maxTokens: { env: 'ARRAKIS_MAX_TOKENS', help: 'Max output tokens per response (0 = provider default)', number: true, global: true },
15
25
  };
16
26
 
17
- const DEFAULTS = {
18
- baseUrl: 'http://localhost:8000/v1',
19
- apiKey: '',
20
- model: '',
21
- contextWindow: 128000,
22
- maxTokens: 0,
23
- };
27
+ const DEFAULT_CONTEXT = 128000;
24
28
 
25
29
  export function readConfigFile() {
30
+ let file;
26
31
  try {
27
- return JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8'));
32
+ file = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8'));
28
33
  } catch {
29
- return {};
34
+ return { providers: {} };
35
+ }
36
+ file.providers ??= {};
37
+ // Migrate the flat 0.2 format ({ baseUrl, apiKey, model }) to a custom provider.
38
+ if (!file.provider && file.baseUrl) {
39
+ file.providers.custom = { baseUrl: file.baseUrl, apiKey: file.apiKey, model: file.model, contextWindow: file.contextWindow };
40
+ file.provider = 'custom';
30
41
  }
42
+ delete file.baseUrl;
43
+ delete file.apiKey;
44
+ delete file.model;
45
+ delete file.contextWindow;
46
+ return file;
47
+ }
48
+
49
+ function writeConfigFile(file) {
50
+ fs.mkdirSync(HOME_DIR, { recursive: true });
51
+ fs.writeFileSync(CONFIG_PATH, JSON.stringify(file, null, 2) + '\n', { mode: 0o600 });
52
+ fs.chmodSync(CONFIG_PATH, 0o600);
31
53
  }
32
54
 
33
55
  export function loadConfig(overrides = {}) {
34
56
  const file = readConfigFile();
35
- const config = { ...DEFAULTS };
36
- for (const [key, spec] of Object.entries(CONFIG_KEYS)) {
37
- let value = config[key];
38
- if (file[key] !== undefined && file[key] !== '') value = file[key];
39
- if (process.env[spec.env]) value = process.env[spec.env];
40
- if (overrides[key] !== undefined && overrides[key] !== '') value = overrides[key];
41
- config[key] = spec.number ? Number(value) || 0 : value;
42
- }
57
+ const env = process.env;
58
+ let providerId = overrides.provider || env.ARRAKIS_PROVIDER || file.provider || null;
59
+ // A base URL from the environment or flags without a provider means a custom API.
60
+ if (!providerId && (env.ARRAKIS_BASE_URL || overrides.baseUrl)) providerId = 'custom';
61
+ const provider = providerId ? getProvider(providerId) : null;
62
+ if (providerId && !provider) throw new Error(`Unknown provider "${providerId}". Run: arrakis setup`);
63
+ const saved = (providerId && file.providers[providerId]) || {};
64
+
65
+ const config = {
66
+ provider: providerId,
67
+ providerName: provider?.name ?? '',
68
+ baseUrl: saved.baseUrl || provider?.baseUrl || '',
69
+ apiKey: saved.apiKey || '',
70
+ model: saved.model || '',
71
+ contextWindow: Number(saved.contextWindow) || provider?.contextWindow || DEFAULT_CONTEXT,
72
+ maxTokens: Number(file.maxTokens) || provider?.maxTokens || 0,
73
+ };
74
+ if (env.ARRAKIS_BASE_URL) config.baseUrl = env.ARRAKIS_BASE_URL;
75
+ if (env.ARRAKIS_API_KEY) config.apiKey = env.ARRAKIS_API_KEY;
76
+ if (env.ARRAKIS_MODEL) config.model = env.ARRAKIS_MODEL;
77
+ if (Number(env.ARRAKIS_CONTEXT_WINDOW)) config.contextWindow = Number(env.ARRAKIS_CONTEXT_WINDOW);
78
+ if (Number(env.ARRAKIS_MAX_TOKENS)) config.maxTokens = Number(env.ARRAKIS_MAX_TOKENS);
79
+ if (overrides.baseUrl) config.baseUrl = overrides.baseUrl;
80
+ if (overrides.model) config.model = overrides.model;
43
81
  config.baseUrl = String(config.baseUrl).replace(/\/+$/, '');
44
- if (!config.contextWindow) config.contextWindow = DEFAULTS.contextWindow;
82
+ config.configured = Boolean(config.provider && config.baseUrl && (config.apiKey || provider?.noKey || provider?.custom || env.ARRAKIS_BASE_URL));
45
83
  return config;
46
84
  }
47
85
 
86
+ // Save settings for one provider and (by default) make it the active one.
87
+ export function saveProvider(providerId, patch, { activate = true } = {}) {
88
+ const file = readConfigFile();
89
+ const current = file.providers[providerId] ?? {};
90
+ const next = { ...current, ...patch };
91
+ for (const k of Object.keys(next)) if (next[k] === undefined || next[k] === '') delete next[k];
92
+ file.providers[providerId] = next;
93
+ if (activate) file.provider = providerId;
94
+ writeConfigFile(file);
95
+ }
96
+
97
+ export function savedProviderSettings(providerId) {
98
+ return readConfigFile().providers[providerId] ?? {};
99
+ }
100
+
101
+ // `arrakis config set <key> <value>`
48
102
  export function setConfigValue(key, value) {
49
- if (!CONFIG_KEYS[key]) throw new Error(`Unknown config key "${key}". Keys: ${Object.keys(CONFIG_KEYS).join(', ')}`);
103
+ const spec = CONFIG_KEYS[key];
104
+ if (!spec) throw new Error(`Unknown config key "${key}". Keys: ${Object.keys(CONFIG_KEYS).join(', ')}`);
50
105
  const file = readConfigFile();
51
- if (value === undefined || value === '') delete file[key];
52
- else file[key] = CONFIG_KEYS[key].number ? Number(value) : value;
53
- fs.mkdirSync(HOME_DIR, { recursive: true });
54
- fs.writeFileSync(CONFIG_PATH, JSON.stringify(file, null, 2) + '\n', { mode: 0o600 });
106
+ const v = value === undefined || value === '' ? undefined : spec.number ? Number(value) : value;
107
+ if (key === 'provider') {
108
+ if (v && !getProvider(v)) throw new Error(`Unknown provider "${v}".`);
109
+ if (v) file.provider = v;
110
+ else delete file.provider;
111
+ } else if (spec.global) {
112
+ if (v === undefined) delete file[key];
113
+ else file[key] = v;
114
+ } else {
115
+ const id = file.provider ?? 'custom';
116
+ file.provider = id;
117
+ file.providers[id] ??= {};
118
+ if (v === undefined) delete file.providers[id][key];
119
+ else file.providers[id][key] = v;
120
+ }
121
+ writeConfigFile(file);
122
+ }
123
+
124
+ export function removeProviderKeys() {
125
+ const file = readConfigFile();
126
+ for (const p of Object.values(file.providers)) delete p.apiKey;
127
+ writeConfigFile(file);
55
128
  }
56
129
 
57
130
  export function maskSecret(value) {
58
131
  if (!value) return '(not set)';
59
- return value.length <= 8 ? '****' : `${value.slice(0, 4)}…${value.slice(-4)}`;
132
+ return value.length <= 10 ? '****' : `${value.slice(0, 6)}…${value.slice(-4)}`;
60
133
  }
package/src/prompts.js ADDED
@@ -0,0 +1,186 @@
1
+ // Interactive prompts: an arrow-key picker with type-to-search, masked secret
2
+ // input and plain text input. Without a TTY (piped input, CI) they fall back
3
+ // to numbered lists and plain line reads.
4
+ import readline from 'node:readline';
5
+ import { colors } from './ui.js';
6
+
7
+ const isTTY = () => Boolean(process.stdin.isTTY && process.stdout.isTTY && process.stdin.setRawMode);
8
+
9
+ // Read raw keypresses until done() is called. Hands stdin back afterwards.
10
+ function rawKeys(onKey) {
11
+ return new Promise((resolve) => {
12
+ const stdin = process.stdin;
13
+ readline.emitKeypressEvents(stdin);
14
+ const wasRaw = stdin.isRaw;
15
+ stdin.setRawMode(true);
16
+ stdin.resume();
17
+ const done = (value) => {
18
+ stdin.off('keypress', handler);
19
+ stdin.setRawMode(wasRaw);
20
+ stdin.pause();
21
+ resolve(value);
22
+ };
23
+ const handler = (str, key = {}) => onKey(str, key, done);
24
+ stdin.on('keypress', handler);
25
+ });
26
+ }
27
+
28
+ const printable = (str, key) => str && !key.ctrl && !key.meta && str.length >= 1 && !/[\x00-\x1f\x7f]/.test(str);
29
+
30
+ function truncateToWidth(s, width) {
31
+ // Strip ANSI for measuring; cut the visible text if it's too long.
32
+ const plain = s.replace(/\x1b\[[0-9;]*m/g, '');
33
+ if (plain.length <= width) return s;
34
+ return plain.slice(0, Math.max(0, width - 1)) + '…';
35
+ }
36
+
37
+ async function rawSelect({ title, items, initial = 0, pageSize = 10 }) {
38
+ const out = process.stdout;
39
+ const c = colors(out);
40
+ const searchable = items.length > 8;
41
+ let filter = '';
42
+ let cursor = Math.max(0, Math.min(initial, items.length - 1));
43
+ let rendered = 0;
44
+ const visible = () => {
45
+ if (!filter) return items;
46
+ const f = filter.toLowerCase();
47
+ return items.filter((i) => `${i.label} ${i.value} ${i.hint ?? ''}`.toLowerCase().includes(f));
48
+ };
49
+ const clear = () => {
50
+ if (!rendered) return;
51
+ readline.moveCursor(out, 0, -rendered);
52
+ readline.cursorTo(out, 0);
53
+ readline.clearScreenDown(out);
54
+ rendered = 0;
55
+ };
56
+ const render = () => {
57
+ clear();
58
+ const list = visible();
59
+ cursor = Math.max(0, Math.min(cursor, list.length - 1));
60
+ const width = (out.columns || 80) - 1;
61
+ const rows = [`${c.bold(title)} ${c.dim(searchable ? '↑↓ move · type to search · Enter select · Esc cancel' : '↑↓ move · Enter select · Esc cancel')}`];
62
+ if (searchable) rows.push(` ${c.dim('search:')} ${filter}${c.dim('▏')}`);
63
+ if (!list.length) rows.push(c.dim(' no matches'));
64
+ const start = Math.max(0, Math.min(cursor - Math.floor(pageSize / 2), list.length - pageSize));
65
+ list.slice(start, start + pageSize).forEach((item, i) => {
66
+ const selected = start + i === cursor;
67
+ const label = selected ? c.accent(c.bold(item.label)) : item.label;
68
+ rows.push(truncateToWidth(`${selected ? c.accent('❯') : ' '} ${label}${item.hint ? ' ' + c.dim(item.hint) : ''}`, width));
69
+ });
70
+ if (list.length > pageSize) rows.push(c.dim(` ${cursor + 1} of ${list.length}`));
71
+ out.write(rows.join('\n') + '\n');
72
+ rendered = rows.length;
73
+ };
74
+ out.write('\x1b[?25l');
75
+ render();
76
+ const result = await rawKeys((str, key, done) => {
77
+ const list = visible();
78
+ if (key.ctrl && key.name === 'c') return done(null);
79
+ if (key.name === 'escape') {
80
+ if (filter) {
81
+ filter = '';
82
+ cursor = 0;
83
+ return render();
84
+ }
85
+ return done(null);
86
+ }
87
+ if (key.name === 'return' || key.name === 'enter') return done(list[cursor] ?? null);
88
+ if (key.name === 'up') cursor = cursor > 0 ? cursor - 1 : list.length - 1;
89
+ else if (key.name === 'down') cursor = cursor < list.length - 1 ? cursor + 1 : 0;
90
+ else if (key.name === 'pageup') cursor = Math.max(0, cursor - pageSize);
91
+ else if (key.name === 'pagedown') cursor = Math.min(list.length - 1, cursor + pageSize);
92
+ else if (key.name === 'backspace') {
93
+ filter = filter.slice(0, -1);
94
+ cursor = 0;
95
+ } else if (searchable && printable(str, key)) {
96
+ filter += str;
97
+ cursor = 0;
98
+ } else return;
99
+ render();
100
+ });
101
+ clear();
102
+ out.write('\x1b[?25h');
103
+ out.write(`${c.bold(title)} ${result ? c.accent(result.label) : c.dim('cancelled')}\n`);
104
+ return result ? result.value : null;
105
+ }
106
+
107
+ async function rawSecret(label) {
108
+ const out = process.stdout;
109
+ const c = colors(out);
110
+ let value = '';
111
+ const draw = () => {
112
+ readline.cursorTo(out, 0);
113
+ readline.clearLine(out, 1);
114
+ const dots = '•'.repeat(Math.min(value.length, 32)) + (value.length > 32 ? c.dim(` +${value.length - 32}`) : '');
115
+ out.write(`${label}${dots}`);
116
+ };
117
+ draw();
118
+ const result = await rawKeys((str, key, done) => {
119
+ if (key.ctrl && key.name === 'c') return done(null);
120
+ if (key.name === 'escape') return done(null);
121
+ if (key.name === 'return' || key.name === 'enter') return done(value);
122
+ if (key.name === 'backspace') value = value.slice(0, -1);
123
+ else if (key.ctrl && key.name === 'u') value = '';
124
+ else if (printable(str, key)) value += str;
125
+ else return;
126
+ draw();
127
+ });
128
+ out.write('\n');
129
+ return result === null ? null : result.trim();
130
+ }
131
+
132
+ export function createPrompts(ui) {
133
+ return {
134
+ // items: [{ label, value, hint? }]. Resolves to the chosen value, or null.
135
+ async select({ title, items, initial = 0 }) {
136
+ if (isTTY()) {
137
+ ui.suspend();
138
+ try {
139
+ return await rawSelect({ title, items, initial });
140
+ } finally {
141
+ ui.resume();
142
+ }
143
+ }
144
+ return numberedSelect(ui, { title, items, initial });
145
+ },
146
+
147
+ async secret(label) {
148
+ if (isTTY()) {
149
+ ui.suspend();
150
+ try {
151
+ return await rawSecret(label);
152
+ } finally {
153
+ ui.resume();
154
+ }
155
+ }
156
+ const line = await ui.readLine(label);
157
+ return line === null ? null : line.trim();
158
+ },
159
+
160
+ async input(label) {
161
+ const line = await ui.readLine(label);
162
+ return line === null ? null : line.trim();
163
+ },
164
+ };
165
+ }
166
+
167
+ async function numberedSelect(ui, { title, items, initial }) {
168
+ const c = ui.c;
169
+ const shown = items.slice(0, 40);
170
+ ui.write(ui.out, `${c.bold(title)}\n`);
171
+ shown.forEach((item, i) => ui.write(ui.out, ` ${String(i + 1).padStart(2)}. ${item.label}${item.hint ? ' ' + c.dim(item.hint) : ''}\n`));
172
+ if (items.length > shown.length) ui.write(ui.out, c.dim(` … ${items.length - shown.length} more (type a name to pick one)\n`));
173
+ while (true) {
174
+ const answer = await ui.readLine(`Choose 1-${shown.length} ${c.dim(`[${initial + 1}]`)}: `);
175
+ if (answer === null) return null;
176
+ const a = answer.trim();
177
+ if (!a) return items[initial]?.value ?? null;
178
+ const n = Number(a);
179
+ if (Number.isInteger(n) && n >= 1 && n <= shown.length) return shown[n - 1].value;
180
+ const exact = items.find((i) => i.value === a || i.label.toLowerCase() === a.toLowerCase());
181
+ if (exact) return exact.value;
182
+ const partial = items.filter((i) => `${i.label} ${i.value}`.toLowerCase().includes(a.toLowerCase()));
183
+ if (partial.length === 1) return partial[0].value;
184
+ ui.write(ui.out, c.dim(partial.length ? ` ${partial.length} matches; be more specific.\n` : ' No match.\n'));
185
+ }
186
+ }
@@ -0,0 +1,60 @@
1
+ // Built-in providers. Every one speaks the OpenAI-compatible /chat/completions
2
+ // API. To add one (for example your own hosted model), add an entry here.
3
+ //
4
+ // id stable key used in config and ARRAKIS_PROVIDER
5
+ // name shown in the picker
6
+ // baseUrl API base URL (without /chat/completions)
7
+ // keyUrl where users create an API key
8
+ // noKey true for local servers that don't need a key
9
+ // custom true: the user enters the base URL
10
+ // defaultModel highlighted first in the model picker, if the provider lists it
11
+ // contextWindow fallback when the models API doesn't report one
12
+ // maxTokens max output tokens to request (some APIs require it)
13
+ // modelsHeaders headers for GET /models when they differ from Bearer auth
14
+
15
+ export const PROVIDERS = [
16
+ {
17
+ id: 'anthropic',
18
+ name: 'Anthropic (Claude)',
19
+ baseUrl: 'https://api.anthropic.com/v1',
20
+ keyUrl: 'https://platform.claude.com/settings/keys',
21
+ defaultModel: 'claude-opus-5-5',
22
+ contextWindow: 1000000,
23
+ maxTokens: 32000,
24
+ modelsHeaders: (key) => ({ 'x-api-key': key, 'anthropic-version': '2023-06-01' }),
25
+ modelsQuery: '?limit=1000',
26
+ },
27
+ { id: 'openai', name: 'OpenAI', baseUrl: 'https://api.openai.com/v1', keyUrl: 'https://platform.openai.com/api-keys' },
28
+ { id: 'google', name: 'Google Gemini', baseUrl: 'https://generativelanguage.googleapis.com/v1beta/openai', keyUrl: 'https://aistudio.google.com/apikey', contextWindow: 1000000 },
29
+ { id: 'openrouter', name: 'OpenRouter (hundreds of models)', baseUrl: 'https://openrouter.ai/api/v1', keyUrl: 'https://openrouter.ai/keys' },
30
+ { id: 'xai', name: 'xAI (Grok)', baseUrl: 'https://api.x.ai/v1', keyUrl: 'https://console.x.ai' },
31
+ { id: 'deepseek', name: 'DeepSeek', baseUrl: 'https://api.deepseek.com/v1', keyUrl: 'https://platform.deepseek.com/api_keys' },
32
+ { id: 'mistral', name: 'Mistral', baseUrl: 'https://api.mistral.ai/v1', keyUrl: 'https://console.mistral.ai/api-keys' },
33
+ { id: 'groq', name: 'Groq', baseUrl: 'https://api.groq.com/openai/v1', keyUrl: 'https://console.groq.com/keys' },
34
+ { id: 'together', name: 'Together AI', baseUrl: 'https://api.together.xyz/v1', keyUrl: 'https://api.together.ai/settings/api-keys' },
35
+ { id: 'ollama', name: 'Ollama (local models, no key)', baseUrl: 'http://localhost:11434/v1', noKey: true },
36
+ { id: 'custom', name: 'Other OpenAI-compatible API', custom: true },
37
+ ];
38
+
39
+ export const getProvider = (id) => PROVIDERS.find((p) => p.id === id) ?? null;
40
+
41
+ // Models that can't chat (embeddings, audio, images, moderation…).
42
+ const NON_CHAT = /(embed|whisper|tts|dall-e|moderation|transcribe|audio|realtime|image|imagen|veo|sora|davinci|babbage|rerank|aqa|guard)/i;
43
+
44
+ export function normalizeModels(json) {
45
+ const raw = Array.isArray(json) ? json : json?.data ?? json?.models ?? [];
46
+ const models = raw
47
+ .map((m) => {
48
+ const id = String(m.id ?? m.name ?? '').replace(/^models\//, '');
49
+ const created = typeof m.created === 'number' ? m.created * 1000 : m.created_at ? Date.parse(m.created_at) : 0;
50
+ return {
51
+ id,
52
+ name: m.display_name ?? m.displayName ?? (m.name && m.name !== m.id ? m.name : ''),
53
+ created: Number.isFinite(created) ? created : 0,
54
+ contextWindow: Number(m.max_input_tokens ?? m.context_length ?? m.context_window ?? m.inputTokenLimit ?? 0) || 0,
55
+ };
56
+ })
57
+ .filter((m) => m.id && !NON_CHAT.test(m.id));
58
+ if (models.some((m) => m.created)) models.sort((a, b) => b.created - a.created);
59
+ return models;
60
+ }
package/src/setup.js ADDED
@@ -0,0 +1,157 @@
1
+ // First-run setup and switching: choose a provider, paste a key, pick a model.
2
+ import { PROVIDERS, getProvider } from './providers.js';
3
+ import { listModels } from './client.js';
4
+ import { loadConfig, saveProvider, savedProviderSettings, maskSecret } from './config.js';
5
+
6
+ // Returns the new config, or null if the user cancelled.
7
+ export async function runSetup({ ui, prompts, welcome = false }) {
8
+ const c = ui.c;
9
+ if (welcome) {
10
+ ui.write(ui.out, `\n${c.accent(c.bold(' ◆ Welcome to arrakis'))}\n`);
11
+ ui.write(ui.out, c.dim(' Pick the AI provider to use. You can switch any time with /provider.\n\n'));
12
+ }
13
+ let current = null;
14
+ try {
15
+ current = loadConfig().provider;
16
+ } catch {}
17
+
18
+ const providerId = await prompts.select({
19
+ title: 'Provider',
20
+ items: PROVIDERS.map((p) => ({
21
+ label: p.name,
22
+ value: p.id,
23
+ hint: savedProviderSettings(p.id).apiKey ? 'key saved' : p.id === current ? 'current' : '',
24
+ })),
25
+ initial: Math.max(0, PROVIDERS.findIndex((p) => p.id === current)),
26
+ });
27
+ if (!providerId) return null;
28
+ const provider = getProvider(providerId);
29
+ const saved = savedProviderSettings(providerId);
30
+
31
+ let baseUrl = provider.baseUrl;
32
+ if (provider.custom) {
33
+ while (true) {
34
+ const hint = saved.baseUrl ? c.dim(` [${saved.baseUrl}]`) : '';
35
+ const answer = await prompts.input(`API base URL, e.g. https://api.example.com/v1${hint}: `);
36
+ if (answer === null) return null;
37
+ baseUrl = (answer || saved.baseUrl || '').replace(/\/+$/, '');
38
+ if (/^https?:\/\/\S+$/.test(baseUrl)) break;
39
+ ui.write(ui.out, c.red(' Enter a URL starting with http:// or https://\n'));
40
+ }
41
+ }
42
+
43
+ let apiKey = '';
44
+ let models = null;
45
+ let keepKey = false;
46
+ for (let attempt = 0; ; attempt++) {
47
+ if (!provider.noKey && !keepKey) {
48
+ const reuse = saved.apiKey && attempt === 0
49
+ ? await prompts.select({
50
+ title: 'API key',
51
+ items: [
52
+ { label: `Use saved key ${maskSecret(saved.apiKey)}`, value: 'reuse' },
53
+ { label: 'Enter a new key', value: 'new' },
54
+ ],
55
+ })
56
+ : 'new';
57
+ if (reuse === null) return null;
58
+ if (reuse === 'reuse') apiKey = saved.apiKey;
59
+ else {
60
+ if (provider.keyUrl) ui.write(ui.out, c.dim(` Get a key at ${provider.keyUrl}\n`));
61
+ const label = provider.custom ? 'API key (Enter if none): ' : `Paste your ${provider.name} API key: `;
62
+ const key = await prompts.secret(label);
63
+ if (key === null) return null;
64
+ if (!key && !provider.custom) {
65
+ ui.write(ui.out, c.red(' A key is required for this provider.\n'));
66
+ continue;
67
+ }
68
+ apiKey = key;
69
+ }
70
+ }
71
+
72
+ ui.write(ui.out, c.dim(' Checking…'));
73
+ try {
74
+ models = await listModels({ provider: providerId, baseUrl, apiKey });
75
+ ui.write(ui.out, `\r${c.green(' ✓')} Connected${models.length ? ` · ${models.length} models available` : ''}\n`);
76
+ break;
77
+ } catch (err) {
78
+ ui.write(ui.out, '\r');
79
+ if (err.status === 401 || err.status === 403) {
80
+ ui.write(ui.out, c.red(` ✗ ${provider.name} rejected that key (${err.status}). Check it and try again.\n`));
81
+ if (provider.noKey || attempt >= 4) return null;
82
+ keepKey = false;
83
+ continue;
84
+ }
85
+ if (err.unreachable) {
86
+ const msg = provider.id === 'ollama' ? 'Ollama is not running. Start it with: ollama serve' : `Could not reach ${baseUrl}.`;
87
+ ui.write(ui.out, c.red(` ✗ ${msg}\n`));
88
+ } else {
89
+ ui.write(ui.out, c.yellow(` ! Couldn't list models (${err.status ?? err.message}). You can type a model name instead.\n`));
90
+ models = [];
91
+ break;
92
+ }
93
+ const next = await prompts.select({
94
+ title: 'What now?',
95
+ items: [
96
+ { label: 'Try again', value: 'retry' },
97
+ { label: 'Continue anyway and type a model name', value: 'skip' },
98
+ { label: 'Cancel', value: 'cancel' },
99
+ ],
100
+ });
101
+ if (next === null || next === 'cancel') return null;
102
+ if (next === 'retry') {
103
+ keepKey = true;
104
+ continue;
105
+ }
106
+ models = [];
107
+ break;
108
+ }
109
+ }
110
+
111
+ const model = await pickModel({ ui, prompts, provider, models, current: saved.model });
112
+ if (!model) return null;
113
+
114
+ saveProvider(providerId, {
115
+ baseUrl: provider.custom ? baseUrl : undefined,
116
+ apiKey: apiKey || undefined,
117
+ model: model.id,
118
+ contextWindow: model.contextWindow || undefined,
119
+ });
120
+ ui.write(ui.out, `${c.green(' ✓')} Using ${c.bold(model.id)} from ${provider.name}. ${c.dim('Saved to ~/.arrakis/config.json')}\n\n`);
121
+ return loadConfig();
122
+ }
123
+
124
+ // Choose a model from the provider's list (or type one when there's no list).
125
+ export async function pickModel({ ui, prompts, provider, models, current }) {
126
+ if (!models?.length) {
127
+ const name = await prompts.input(`Model name${current ? ui.c.dim(` [${current}]`) : ''}: `);
128
+ if (name === null) return null;
129
+ const id = name || current;
130
+ return id ? { id } : null;
131
+ }
132
+ const preferred = [current, provider?.defaultModel].filter(Boolean);
133
+ let initial = 0;
134
+ for (const p of preferred) {
135
+ const i = models.findIndex((m) => m.id === p);
136
+ if (i >= 0) {
137
+ initial = i;
138
+ break;
139
+ }
140
+ }
141
+ const id = await prompts.select({
142
+ title: 'Model',
143
+ items: models.map((m) => ({
144
+ label: m.id,
145
+ value: m.id,
146
+ hint: [m.name && m.name !== m.id ? m.name : '', m.contextWindow ? `${formatTokens(m.contextWindow)} context` : '', m.id === current ? 'current' : '']
147
+ .filter(Boolean)
148
+ .join(' · '),
149
+ })),
150
+ initial,
151
+ });
152
+ return id ? models.find((m) => m.id === id) : null;
153
+ }
154
+
155
+ function formatTokens(n) {
156
+ return n >= 1_000_000 ? `${+(n / 1_000_000).toFixed(1)}M` : n >= 1000 ? `${Math.round(n / 1000)}K` : String(n);
157
+ }
package/src/ui.js CHANGED
@@ -31,21 +31,40 @@ export class UI {
31
31
  }
32
32
 
33
33
  start() {
34
- this.rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: !!process.stdin.isTTY, historySize: 200 });
35
- this.rl.on('line', (line) => {
34
+ if (this.rl || this.closed) return;
35
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: !!process.stdin.isTTY, historySize: 200 });
36
+ this.rl = rl;
37
+ if (this.history) rl.history = this.history;
38
+ rl.on('line', (line) => {
36
39
  if (this.waiter) {
37
40
  const w = this.waiter;
38
41
  this.waiter = null;
39
42
  w(line);
40
43
  } else this.queue.push(line);
41
44
  });
42
- this.rl.on('close', () => {
45
+ rl.on('close', () => {
46
+ if (rl.suspended) return;
43
47
  this.closed = true;
44
48
  this.cancelRead();
45
49
  });
50
+ if (this.interruptHandler) rl.on('SIGINT', this.interruptHandler);
51
+ }
52
+
53
+ // Hand the terminal to a raw-mode prompt (picker, secret input) and back.
54
+ suspend() {
55
+ if (!this.rl) return;
56
+ this.history = this.rl.history;
57
+ this.rl.suspended = true;
58
+ this.rl.close();
59
+ this.rl = null;
60
+ }
61
+
62
+ resume() {
63
+ this.start();
46
64
  }
47
65
 
48
66
  onInterrupt(handler) {
67
+ this.interruptHandler = handler;
49
68
  if (this.rl) this.rl.on('SIGINT', handler);
50
69
  process.on('SIGINT', handler);
51
70
  }