sumo-agents 0.5.0 → 0.7.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/CHANGELOG.md +86 -0
- package/README.md +50 -37
- package/guides/memory.md +21 -14
- package/package.json +2 -2
- package/prompts/dream.md +3 -16
- package/prompts/scribe.md +20 -15
- package/src/apply.mjs +364 -230
- package/src/card.mjs +16 -11
- package/src/catalog.mjs +3 -3
- package/src/chat.mjs +44 -23
- package/src/check.mjs +371 -0
- package/src/cli.mjs +218 -144
- package/src/db.mjs +147 -2
- package/src/dream.mjs +97 -189
- package/src/export.mjs +43 -18
- package/src/herdr.mjs +1 -3
- package/src/hooks.mjs +115 -22
- package/src/jobs.mjs +4 -2
- package/src/keeper.mjs +14 -51
- package/src/ledger.mjs +126 -0
- package/src/logs.mjs +10 -5
- package/src/loop.mjs +4 -4
- package/src/mcp.mjs +129 -51
- package/src/memeval.mjs +167 -0
- package/src/memory.mjs +261 -130
- package/src/page.mjs +3 -3
- package/src/paths.mjs +1 -0
- package/src/prime.mjs +82 -13
- package/src/rebuild.mjs +162 -0
- package/src/render.mjs +22 -0
- package/src/route.mjs +1 -1
- package/src/sandbox.mjs +5 -2
- package/src/scan.mjs +16 -4
- package/src/scribe.mjs +361 -113
- package/src/search.mjs +48 -0
- package/src/sessions.mjs +304 -53
- package/src/settings.mjs +868 -0
- package/src/setup.mjs +57 -65
- package/src/spool.mjs +308 -0
- package/src/text.mjs +118 -6
- package/src/tools.mjs +18 -7
- package/src/transcript.mjs +3 -47
- package/src/tty.mjs +102 -63
- package/src/ui.mjs +313 -271
- package/src/verify.mjs +23 -27
package/src/settings.mjs
ADDED
|
@@ -0,0 +1,868 @@
|
|
|
1
|
+
import { readdirSync, readFileSync, statSync } from 'node:fs';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { Box, render, Text, useApp, useInput, usePaste, useWindowSize } from 'ink';
|
|
5
|
+
import { createElement as h, useReducer } from 'react';
|
|
6
|
+
import { discoverModels, discoverySummary, MODEL_IDS, MODELS, modelStates, setModel } from './catalog.mjs';
|
|
7
|
+
import { getMeta, openDb } from './db.mjs';
|
|
8
|
+
import { addServer, allowedBy, CLAUDE_CODE_TOKEN, connect, readConfig, removeServer, setAllow } from './mcp.mjs';
|
|
9
|
+
import { redact } from './redact.mjs';
|
|
10
|
+
import { CHAT_EFFORTS, CONFIG_DEFAULTS, config, fetchModel } from './setup.mjs';
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* The settings page: every setting Sumo has, on one page, changed with the arrow keys and saved the moment it changes —
|
|
14
|
+
* there is no file to edit and no command that sets a thing by name. `/config` opens it in the chat, in the box's place;
|
|
15
|
+
* `sumo config` at a terminal opens it on its own. Each change goes through the same checks `config()` has always made,
|
|
16
|
+
* the API models' switches through the catalog's, and the MCP servers and their allow lists through mcp.mjs: the page
|
|
17
|
+
* is one more way in to each, never a second set of rules. It needs a person at a terminal, so the model's shell —
|
|
18
|
+
* which has none — can read the settings but never change them.
|
|
19
|
+
*
|
|
20
|
+
* The page is a model that draws itself as lines of `[text, tone]` and takes key names; `SettingsView` puts those lines
|
|
21
|
+
* on an Ink screen, so the chat and `sumo config` draw it the same way and a test can drive it without a terminal.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
const ACCENT = '#d77757';
|
|
25
|
+
const TONES = { acc: { color: ACCENT }, b: { bold: true }, d: { dimColor: true }, g: { color: 'green' }, r: { color: 'red' }, y: { color: 'yellow' }, gr: { color: 'gray' }, v: { inverse: true } };
|
|
26
|
+
const VALUE_WIDTH = 18;
|
|
27
|
+
/** A value typed here with no `${NAME}` in it would be stored, and a header is where a token goes. */
|
|
28
|
+
const NAMED = /\$\{[A-Za-z_][A-Za-z0-9_]*\}/;
|
|
29
|
+
const cap = (s) => s[0].toUpperCase() + s.slice(1);
|
|
30
|
+
const len = (t) => [...String(t)].length;
|
|
31
|
+
const width = (line) => line.reduce((n, [t]) => n + len(t), 0);
|
|
32
|
+
|
|
33
|
+
/** A line cut to `w` columns, its last one an ellipsis when anything was cut. */
|
|
34
|
+
function fit(line, w) {
|
|
35
|
+
if (width(line) <= w) return line;
|
|
36
|
+
const out = [];
|
|
37
|
+
let n = 0;
|
|
38
|
+
for (const [t, c] of line) {
|
|
39
|
+
const ch = [...String(t)];
|
|
40
|
+
if (n + ch.length <= w - 1) {
|
|
41
|
+
out.push([t, c]);
|
|
42
|
+
n += ch.length;
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
out.push([ch.slice(0, Math.max(0, w - 1 - n)).join('') + '…', c]);
|
|
46
|
+
break;
|
|
47
|
+
}
|
|
48
|
+
return out;
|
|
49
|
+
}
|
|
50
|
+
const padLine = (line, w) => (width(line) < w ? [...line, [' '.repeat(w - width(line)), '']] : fit(line, w));
|
|
51
|
+
const pad = (s, n) => (len(s) >= n ? `${[...s].slice(0, n - 2).join('')}… ` : s + ' '.repeat(n - len(s)));
|
|
52
|
+
const trimKeys = (keys, room) => {
|
|
53
|
+
let k = keys;
|
|
54
|
+
while (k && len(k) > room) {
|
|
55
|
+
const at = k.lastIndexOf(' · ');
|
|
56
|
+
k = at > 0 ? k.slice(0, at) : '';
|
|
57
|
+
}
|
|
58
|
+
return k;
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
/** Words of a command line, quotes kept together: what a pasted `npx -y @scope/server --flag "a b"` runs. */
|
|
62
|
+
const wordsOf = (line) => [...line.matchAll(/"([^"]*)"|'([^']*)'|(\S+)/g)].map((m) => m[1] ?? m[2] ?? m[3]);
|
|
63
|
+
|
|
64
|
+
/** A server's name from what was pasted: the host of an address, or the package of a command, without its `mcp`. */
|
|
65
|
+
export function nameFrom(addr) {
|
|
66
|
+
const a = addr.trim();
|
|
67
|
+
if (!a) return '';
|
|
68
|
+
if (/^https?:\/\//i.test(a)) {
|
|
69
|
+
try {
|
|
70
|
+
return new URL(a).hostname.split('.').filter((p) => !['mcp', 'www', 'api', 'com', 'app', 'dev', 'io', 'ai', 'org', 'net'].includes(p))[0] ?? '';
|
|
71
|
+
} catch {
|
|
72
|
+
return '';
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
const pkg = wordsOf(a).find((w) => !w.startsWith('-') && !['npx', 'uvx', 'node', 'python', 'python3', 'bunx', 'docker', 'run', 'pnpm', 'dlx'].includes(w)) ?? '';
|
|
76
|
+
let name = pkg.replace(/(?<=.)@[^/@]*$/, '').split('/').pop().replace(/^(server-|mcp-)/, '').replace(/(-mcp|-server)$/, '');
|
|
77
|
+
if ((name === 'mcp' || name === 'server') && pkg.includes('/')) name = pkg.split('/')[0].replace(/^@/, '');
|
|
78
|
+
return name.replace(/[^A-Za-z0-9_-]/g, '-');
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* The servers Claude Code knows — its own and this project's, from its file — as Sumo would run them. Read, never
|
|
83
|
+
* written. One whose header or environment holds a token itself is listed but cannot be brought in: Sumo keeps no
|
|
84
|
+
* token, only a `${NAME}` filled from the shell.
|
|
85
|
+
*/
|
|
86
|
+
export function claudeCodeServers(cwd = process.cwd(), env = process.env) {
|
|
87
|
+
const file = join(env.CLAUDE_CONFIG_DIR || env.HOME || homedir(), '.claude.json');
|
|
88
|
+
let data;
|
|
89
|
+
try {
|
|
90
|
+
data = JSON.parse(readFileSync(file, 'utf8'));
|
|
91
|
+
} catch {
|
|
92
|
+
return [];
|
|
93
|
+
}
|
|
94
|
+
const found = { ...(data?.mcpServers ?? {}), ...(data?.projects?.[cwd]?.mcpServers ?? {}) };
|
|
95
|
+
const out = [];
|
|
96
|
+
for (const [name, s] of Object.entries(found)) {
|
|
97
|
+
if (!s || typeof s !== 'object') continue;
|
|
98
|
+
const literal = (values) => Object.values(values ?? {}).some((v) => !NAMED.test(String(v)) && redact(String(v)) !== String(v));
|
|
99
|
+
if (s.url) {
|
|
100
|
+
const headers = s.headers && Object.keys(s.headers).length > 0 ? s.headers : null;
|
|
101
|
+
const why = s.type === 'sse' ? 'an SSE server — Sumo speaks stdio and streamable HTTP' : headers && Object.values(headers).some((v) => !NAMED.test(String(v))) ? "its header holds a token in Claude Code's file — add it here with ${NAME}" : null;
|
|
102
|
+
out.push({ name, shown: s.url, transport: 'http', why, spec: { url: s.url, ...(headers ? { headers } : { token: CLAUDE_CODE_TOKEN }) } });
|
|
103
|
+
} else if (s.command) {
|
|
104
|
+
const envs = s.env && Object.keys(s.env).length > 0 ? s.env : null;
|
|
105
|
+
out.push({ name, shown: [s.command, ...(s.args ?? [])].join(' '), transport: 'stdio', why: literal(envs) ? "its environment holds a token in Claude Code's file — add it here with ${NAME}" : null, spec: { command: s.command, args: s.args ?? [], ...(envs ? { env: envs } : {}) } });
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return out;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** The tools a server offers, by connecting to it once. */
|
|
112
|
+
async function toolNames(name, spec) {
|
|
113
|
+
const session = await connect(name, spec);
|
|
114
|
+
try {
|
|
115
|
+
return session.tools.map((t) => t.name);
|
|
116
|
+
} finally {
|
|
117
|
+
await session.close();
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** The page's name for a key Ink read, or null for one it does nothing with. */
|
|
122
|
+
export function keyName(input, key) {
|
|
123
|
+
if (key.upArrow) return 'up';
|
|
124
|
+
if (key.downArrow) return 'down';
|
|
125
|
+
if (key.leftArrow) return 'left';
|
|
126
|
+
if (key.rightArrow) return 'right';
|
|
127
|
+
if (key.return) return 'enter';
|
|
128
|
+
if (key.escape) return 'escape';
|
|
129
|
+
if (key.tab) return 'tab';
|
|
130
|
+
if (key.backspace || key.delete) return 'backspace';
|
|
131
|
+
if (key.ctrl && (input === 'c' || input === 'd')) return 'escape';
|
|
132
|
+
if (key.ctrl || key.meta) return null;
|
|
133
|
+
if (input === ' ') return 'space';
|
|
134
|
+
return input || null;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* The page. `live` is what the chat lends it: `route(args)` switches the chat's model and effort as the page changes
|
|
139
|
+
* them, `servers()` says how its MCP servers connected, `left()` is the status line's left side. Without it (`sumo
|
|
140
|
+
* config`) a change is for the next chat. `toolsOf`, `download`, `discover` and `claude` are the slow or outside parts,
|
|
141
|
+
* passed in so a test can stand in for them.
|
|
142
|
+
*/
|
|
143
|
+
export function settingsPage({ live = {}, cwd = process.cwd(), toolsOf = toolNames, download = fetchModel, discover = discoverModels, claude = () => claudeCodeServers(cwd), onChange = () => {} } = {}) {
|
|
144
|
+
const db = openDb();
|
|
145
|
+
const values = () => Object.fromEntries(Object.keys(CONFIG_DEFAULTS).map((k) => [k, getMeta(db, `config.${k}`) ?? CONFIG_DEFAULTS[k]]));
|
|
146
|
+
const switches = () => Object.fromEntries(MODELS.map((m) => [m, modelStates(db)[m].on]));
|
|
147
|
+
const serversNow = () => Object.entries(readConfig().mcpServers).map(([name, spec]) => ({ name, spec }));
|
|
148
|
+
const S = { v: values(), on: switches(), servers: [], view: 'page', f: 0, tf: 0, sv: 0, edit: null, msg: null, ask: null, add: null, tools: null, busy: 0, scroll: {}, log: [], closed: false };
|
|
149
|
+
try {
|
|
150
|
+
S.servers = serversNow();
|
|
151
|
+
} catch (cause) {
|
|
152
|
+
S.msg = { err: cause.message };
|
|
153
|
+
}
|
|
154
|
+
const snap = { v: { ...S.v }, on: { ...S.on } };
|
|
155
|
+
const err = (text) => {
|
|
156
|
+
S.msg = { err: String(text).split('\n')[0] };
|
|
157
|
+
};
|
|
158
|
+
// Work that takes a while answers later: if the page moved on, or closed, in the meantime the answer is dropped.
|
|
159
|
+
let generation = 0;
|
|
160
|
+
const busy = () => S.busy !== 0 && S.busy === generation;
|
|
161
|
+
const later = (promise, done) => {
|
|
162
|
+
const mine = ++generation;
|
|
163
|
+
S.busy = mine;
|
|
164
|
+
Promise.resolve(promise)
|
|
165
|
+
.then(
|
|
166
|
+
(value) => mine === generation && !S.closed && done(value, null),
|
|
167
|
+
(cause) => mine === generation && !S.closed && done(null, cause),
|
|
168
|
+
)
|
|
169
|
+
.finally(() => {
|
|
170
|
+
if (S.busy === mine) S.busy = 0;
|
|
171
|
+
if (!S.closed) onChange();
|
|
172
|
+
});
|
|
173
|
+
};
|
|
174
|
+
|
|
175
|
+
const sections = () => [
|
|
176
|
+
['Chat', [
|
|
177
|
+
{ id: 'chat.model', label: 'Model', type: 'choice', opts: () => ['auto', ...MODELS], disabled: (o) => o !== 'auto' && !S.on[o], when: live.route ? 'this chat too' : 'from the next chat', hint: 'the model chats run on — auto: the router picks one each turn' },
|
|
178
|
+
{ id: 'chat.effort', label: 'Effort', type: 'choice', opts: () => CHAT_EFFORTS, when: live.route ? 'this chat too' : 'from the next chat', hint: 'how much the model thinks before it acts' },
|
|
179
|
+
{ id: 'chat.budget', label: 'Spend notice', type: 'money', step: 1, unit: 'a session', zero: 'never', when: live.route ? 'this chat too' : '', hint: 'what a chat may cost before the screen says so, once — ←→ by $1 or type it, 0 for never' },
|
|
180
|
+
{ id: 'chat.notify', label: 'Notify', type: 'toggle', when: 'from the next chat', hint: 'the bell and a notification when a long turn ends behind another window' },
|
|
181
|
+
{ id: 'chat.screen', label: 'Screen', type: 'choice', opts: () => ['full', 'still', 'plain'], when: 'from the next chat', hint: 'full: colours flow through the working line · still: nothing moves · plain: for a screen reader' },
|
|
182
|
+
]],
|
|
183
|
+
['Jobs', [
|
|
184
|
+
{ id: 'jobs.floor', label: 'Smallest model', type: 'choice', opts: () => MODELS, disabled: (o) => !S.on[o], when: 'jobs from now on', hint: 'the smallest model a job may run on — haiku holds nothing back' },
|
|
185
|
+
{ id: 'jobs.budget', label: 'Budget', type: 'money', step: 1, unit: 'a job', zero: 'no cap', when: 'jobs from now on', hint: 'what one job may spend before it is stopped — 0 for no cap' },
|
|
186
|
+
{ id: 'jobs.minutes', label: 'Time limit', type: 'minutes', step: 15, zero: 'no limit', when: 'jobs from now on', hint: 'how long one job may run before it is stopped — ←→ by 15 or type it, 0 for no limit' },
|
|
187
|
+
{ id: 'jobs.review', label: 'Review', type: 'choice', opts: () => ['risky', 'all', 'off'], when: 'jobs from now on', hint: 'which workers that finish DONE are reviewed unasked: the risky ones, every one, or none' },
|
|
188
|
+
{ id: 'jobs.advisor', label: 'Advisor', type: 'toggle', when: 'jobs from now on', hint: 'a job asking the next model up for advice, from inside its own request' },
|
|
189
|
+
]],
|
|
190
|
+
['Memory', [
|
|
191
|
+
{ id: 'memory.model', label: 'Filed by', type: 'choice', opts: () => ['local', ...MODELS, 'off'], disabled: (o) => MODELS.includes(o) && !S.on[o], when: 'from the next pass', hint: 'the model that files what you say and tidies memory — local runs on this Mac for $0' },
|
|
192
|
+
{ id: 'model.url', label: 'Local model', type: 'url', action: 'enter: change', ph: 'paste the address of a .gguf file', hint: 'the .gguf file the local model comes from — a new one is downloaded as it is set' },
|
|
193
|
+
]],
|
|
194
|
+
['Shell', [
|
|
195
|
+
{ id: 'shell.sandbox', label: 'Sandbox', type: 'toggle', when: 'from the next chat', hint: "the model's shell writes only in the project, the temporary folders and the tool caches" },
|
|
196
|
+
{ id: 'shell.network', label: 'Network', type: 'toggle', when: 'from the next chat', hint: 'the sandboxed shell reaching past this machine — off: only loopback and local sockets' },
|
|
197
|
+
]],
|
|
198
|
+
['Projects', [{ id: 'projects.home', label: 'New ones go in', type: 'path', action: 'enter: change', when: 'at once', hint: 'the folder a new project is made in' }]],
|
|
199
|
+
['API models', [
|
|
200
|
+
...MODELS.map((m) => ({ id: `model:${m}`, label: cap(m), type: 'model', m, hint: 'on: offered for chats, jobs and memory · off: never used' })),
|
|
201
|
+
{ id: 'discover', label: 'Discover', type: 'action', text: 'ask the API which this login can use', action: 'enter', hint: 'sets the switches from the answer — one you turned off stays off' },
|
|
202
|
+
]],
|
|
203
|
+
['MCP servers', [
|
|
204
|
+
...S.servers.map((s, i) => ({ id: `server:${s.name}`, label: s.name, type: 'server', s, i, action: 'enter: tools', hint: `${s.spec.url ?? [s.spec.command, ...(s.spec.args ?? [])].join(' ')} — enter: its tools, and which run without asking` })),
|
|
205
|
+
{ id: 'add', label: '+ add a server', type: 'action', text: '', action: 'enter', hint: 'paste a command or an address, or bring one in from Claude Code' },
|
|
206
|
+
]],
|
|
207
|
+
];
|
|
208
|
+
const pageItems = () => sections().flatMap(([title, rows]) => [{ head: title }, ...rows]);
|
|
209
|
+
const focusables = (items) => items.filter((x) => !x.head && !x.note);
|
|
210
|
+
|
|
211
|
+
const toolItems = () => {
|
|
212
|
+
const s = S.servers[S.sv];
|
|
213
|
+
const it = [{ note: `${s.spec.url ? 'http' : 'stdio'} · ${s.spec.url ?? [s.spec.command, ...(s.spec.args ?? [])].join(' ')}${s.spec.token === CLAUDE_CODE_TOKEN ? " · login: Claude Code's" : ''}` }];
|
|
214
|
+
if (S.tools === null) it.push({ note: `connecting to ${s.name}…` });
|
|
215
|
+
else if (S.tools.error) it.push({ note: `✗ ${S.tools.error}`, cls: 'r' });
|
|
216
|
+
else if (S.tools.names.length === 0) it.push({ note: `${s.name} offers no tools` });
|
|
217
|
+
else S.tools.names.forEach((t) => it.push({ id: `tool:${t}`, label: t, type: 'tool', t, hint: allowedBy(s.spec, t) ? 'runs without asking you' : 'asks you each time — "always" in that question switches it on here too' }));
|
|
218
|
+
it.push({ id: 'remove', label: 'remove this server', type: 'danger', hint: 'asks first; its allow list goes with it' });
|
|
219
|
+
return it;
|
|
220
|
+
};
|
|
221
|
+
const logins = (http) => (http ? ['none', "Claude Code's", 'a header'] : ['none', 'env from your shell']);
|
|
222
|
+
const addItems = () => {
|
|
223
|
+
const a = S.add;
|
|
224
|
+
const http = /^https?:\/\//i.test(a.addr.trim());
|
|
225
|
+
const ls = logins(http);
|
|
226
|
+
if (a.login >= ls.length) a.login = 0;
|
|
227
|
+
const it = [
|
|
228
|
+
{ head: 'A server of your own' },
|
|
229
|
+
{ id: 'addr', label: 'Command or address', type: 'text', ph: 'paste npx -y @scope/server … or https://…', hint: 'a command runs as a process on this Mac; an address is reached over HTTP' },
|
|
230
|
+
{ id: 'name', label: 'Name', type: 'text', ph: 'filled in from the address', hint: 'what the server is called in the chat and on this page' },
|
|
231
|
+
{ id: 'login', label: 'Login', type: 'achoice', opts: ls, hint: http ? 'none · the login Claude Code holds for it (claude mcp login <name>) · or a header from your shell' : 'none · or variables from your shell' },
|
|
232
|
+
];
|
|
233
|
+
if (a.login > 0 && !(http && a.login === 1)) it.push({ id: 'cred', label: http ? 'Header' : 'Env', type: 'text', ph: http ? 'Authorization: Bearer ${TOKEN}' : 'GITHUB_TOKEN=${GITHUB_TOKEN}', hint: '${NAME} is filled in from your shell when the server starts — the token itself is never stored' });
|
|
234
|
+
it.push({ id: 'go', label: 'Add it', type: 'action', text: '', action: 'enter', hint: 'connects once to list its tools; every tool asks first' });
|
|
235
|
+
if (a.claude.length > 0) {
|
|
236
|
+
it.push({ head: 'Or bring one in from Claude Code' });
|
|
237
|
+
for (const c of a.claude) it.push({ id: `cc:${c.name}`, label: c.name, type: 'pick', c, hint: c.why ?? `${c.transport} · read from Claude Code's list, which is never changed` });
|
|
238
|
+
it.push({ id: 'bring', label: a.picked.size > 0 ? `Bring in ${a.picked.size}` : 'Bring them in', type: 'action', text: '', action: 'enter', hint: 'each tool asks first until you switch it' });
|
|
239
|
+
}
|
|
240
|
+
return it;
|
|
241
|
+
};
|
|
242
|
+
const focused = () => {
|
|
243
|
+
if (S.closed || S.view === 'ask') return null;
|
|
244
|
+
if (S.view === 'tools') return focusables(toolItems())[S.tf];
|
|
245
|
+
if (S.view === 'add') return focusables(addItems())[S.add.f];
|
|
246
|
+
return focusables(pageItems())[S.f];
|
|
247
|
+
};
|
|
248
|
+
|
|
249
|
+
// ── what a row shows ──
|
|
250
|
+
const show = (r, v) => {
|
|
251
|
+
if (r.type === 'money') return Number(v) === 0 ? r.zero : `$${Number(v).toFixed(2)}`;
|
|
252
|
+
if (r.type === 'minutes') return Number(v) === 0 ? r.zero : `${v} min`;
|
|
253
|
+
if (r.type === 'url') return String(v).split('/').pop().replace(/\.gguf$/i, '');
|
|
254
|
+
return String(v);
|
|
255
|
+
};
|
|
256
|
+
let plain = false;
|
|
257
|
+
const tog = (on, extra = '') => [[plain ? (on ? 'on' : 'off') : on ? '● on' : '○ off', (on ? 'g' : 'd') + extra]];
|
|
258
|
+
const field = (text, ph, foc, room) => {
|
|
259
|
+
if (!text) return foc ? [[' ', 'v'], [ph ?? '', 'd']] : [[ph ?? '', 'd']];
|
|
260
|
+
const t = foc && len(text) + 1 > room ? `…${[...text].slice(-(room - 2)).join('')}` : text;
|
|
261
|
+
return foc ? [[t, ''], [' ', 'v']] : [[t, '']];
|
|
262
|
+
};
|
|
263
|
+
const allowSummary = (s) => {
|
|
264
|
+
const live_ = live.servers?.().find((x) => x.name === s.name);
|
|
265
|
+
const allow = s.spec.allow === 'all' ? 'every tool runs unasked' : Array.isArray(s.spec.allow) && s.spec.allow.length > 0 ? `${s.spec.allow.length} run unasked` : 'all ask first';
|
|
266
|
+
if (live_ && !live_.ok) return [[`${plain ? 'x' : '✗'} failed to connect`, 'r'], [` · ${allow}`, 'd']];
|
|
267
|
+
return [[`${s.spec.url ? 'http' : 'stdio'}${live_ ? ` · ${live_.tools} tools` : ''} · ${allow}`, '']];
|
|
268
|
+
};
|
|
269
|
+
const valueOf = (r, foc, room) => {
|
|
270
|
+
if (S.view === 'page' && S.edit && S.edit.id === r.id) return field(S.edit.text, r.ph, true, room);
|
|
271
|
+
const v = S.v[r.id];
|
|
272
|
+
const ch = r.id in CONFIG_DEFAULTS && v !== CONFIG_DEFAULTS[r.id] ? ' b' : '';
|
|
273
|
+
switch (r.type) {
|
|
274
|
+
case 'choice':
|
|
275
|
+
return plain ? [[`<${v}>`, (foc ? 'acc' : '') + ch]] : [['‹ ', foc ? 'acc' : 'd'], [v, (foc ? 'acc' : '') + ch], [' ›', foc ? 'acc' : 'd']];
|
|
276
|
+
case 'toggle':
|
|
277
|
+
return tog(v === 'on', ch);
|
|
278
|
+
case 'money':
|
|
279
|
+
return [[Number(v) === 0 ? r.zero : `$${Number(v).toFixed(2)} ${r.unit}`, ch.trim()]];
|
|
280
|
+
case 'minutes':
|
|
281
|
+
return [[Number(v) === 0 ? r.zero : `${v} min`, ch.trim()]];
|
|
282
|
+
case 'url':
|
|
283
|
+
case 'path':
|
|
284
|
+
return [[show(r, v), ch.trim()]];
|
|
285
|
+
case 'model': {
|
|
286
|
+
const t = tog(S.on[r.m]);
|
|
287
|
+
t[0][0] = t[0][0].padEnd(plain ? 3 : 5);
|
|
288
|
+
return [...t, [` ${MODEL_IDS[r.m]}`, 'd']];
|
|
289
|
+
}
|
|
290
|
+
case 'action':
|
|
291
|
+
return r.text ? [[r.text, 'd']] : [];
|
|
292
|
+
case 'server':
|
|
293
|
+
return allowSummary(r.s);
|
|
294
|
+
case 'tool': {
|
|
295
|
+
const on = allowedBy(S.servers[S.sv].spec, r.t);
|
|
296
|
+
return [[plain ? (on ? 'runs unasked' : 'asks first') : on ? '● runs unasked' : '○ asks first', on ? 'g' : 'd']];
|
|
297
|
+
}
|
|
298
|
+
case 'text':
|
|
299
|
+
return field(S.add[r.id], r.ph, foc, room);
|
|
300
|
+
case 'achoice': {
|
|
301
|
+
const o = r.opts[S.add.login];
|
|
302
|
+
return plain ? [[`<${o}>`, foc ? 'acc' : '']] : [['‹ ', foc ? 'acc' : 'd'], [o, foc ? 'acc' : ''], [' ›', foc ? 'acc' : 'd']];
|
|
303
|
+
}
|
|
304
|
+
case 'pick': {
|
|
305
|
+
const here = S.servers.some((s) => s.name === r.c.name);
|
|
306
|
+
const picked = S.add.picked.has(r.c.name);
|
|
307
|
+
const mark = here || r.c.why ? '[–]' : picked ? '[x]' : '[ ]';
|
|
308
|
+
return [[mark, here || r.c.why ? 'd' : picked ? 'acc' : ''], [` ${r.c.transport} · ${r.c.shown}${here ? ' · already here' : ''}`, 'd']];
|
|
309
|
+
}
|
|
310
|
+
default:
|
|
311
|
+
return [];
|
|
312
|
+
}
|
|
313
|
+
};
|
|
314
|
+
const optionsOf = (r) => {
|
|
315
|
+
const [opts, cur] = r.type === 'choice' ? [r.opts(), S.v[r.id]] : r.type === 'achoice' ? [r.opts, r.opts[S.add.login]] : [null, null];
|
|
316
|
+
if (!opts) return null;
|
|
317
|
+
const out = [];
|
|
318
|
+
opts.forEach((o, i) => {
|
|
319
|
+
if (i) out.push([' · ', 'd']);
|
|
320
|
+
out.push([o + (r.disabled?.(o) ? ' (off)' : ''), o === cur ? '' : 'd']);
|
|
321
|
+
});
|
|
322
|
+
return out;
|
|
323
|
+
};
|
|
324
|
+
const line = (item, foc, inner, lw) => {
|
|
325
|
+
if (item.head) return [[plain ? `${item.head}:` : item.head, 'b']];
|
|
326
|
+
if (item.note) return fit([[` ${item.note}`, item.cls ?? 'd']], inner);
|
|
327
|
+
const mark = foc ? [plain ? '> ' : '› ', 'acc'] : [' ', ''];
|
|
328
|
+
const labCls = item.type === 'danger' ? 'r' : ['add', 'go', 'bring'].includes(item.id) ? 'acc' : foc ? 'b' : '';
|
|
329
|
+
let l = [mark, [pad(item.label, lw), labCls], ...valueOf(item, foc, inner - 2 - lw - 1)];
|
|
330
|
+
const act = foc && item.action && !(S.edit && S.edit.id === item.id) ? item.action : '';
|
|
331
|
+
const opts = optionsOf(item);
|
|
332
|
+
if (opts) {
|
|
333
|
+
const col = 2 + lw + VALUE_WIDTH;
|
|
334
|
+
const base = width(l);
|
|
335
|
+
if (Math.max(base + 2, col) + width(opts) + (act ? len(act) + 2 : 0) <= inner) l = [...l, [' '.repeat(Math.max(2, col - base)), ''], ...opts];
|
|
336
|
+
}
|
|
337
|
+
if (act && width(l) + 2 + len(act) <= inner) l = [...l, [' '.repeat(inner - width(l) - len(act)), ''], [act, 'd']];
|
|
338
|
+
return fit(l, inner);
|
|
339
|
+
};
|
|
340
|
+
/** As many lines as fit, the focused one always among them, with what is above and below counted. */
|
|
341
|
+
const windowed = (lines, fi, max, key) => {
|
|
342
|
+
if (lines.length <= max) {
|
|
343
|
+
S.scroll[key] = 0;
|
|
344
|
+
return lines;
|
|
345
|
+
}
|
|
346
|
+
let start = S.scroll[key] ?? 0;
|
|
347
|
+
for (let guard = 0; guard < 400; guard++) {
|
|
348
|
+
start = Math.max(0, Math.min(start, lines.length - 1));
|
|
349
|
+
const up = start > 0 ? 1 : 0;
|
|
350
|
+
let end = Math.min(lines.length, start + max - up);
|
|
351
|
+
const down = end < lines.length ? 1 : 0;
|
|
352
|
+
end = Math.min(lines.length, start + max - up - down);
|
|
353
|
+
if (fi < start) {
|
|
354
|
+
start = Math.max(0, fi - 1);
|
|
355
|
+
continue;
|
|
356
|
+
}
|
|
357
|
+
if (fi >= end) {
|
|
358
|
+
start += fi - end + 1;
|
|
359
|
+
continue;
|
|
360
|
+
}
|
|
361
|
+
S.scroll[key] = start;
|
|
362
|
+
return [...(up ? [[[` ↑ ${start} more`, 'd']]] : []), ...lines.slice(start, end), ...(down ? [[[` ↓ ${lines.length - end} more`, 'd']]] : [])];
|
|
363
|
+
}
|
|
364
|
+
return lines.slice(0, max);
|
|
365
|
+
};
|
|
366
|
+
const framed = (title, body, columns, cls = 'gr') => {
|
|
367
|
+
const inner = columns - 4;
|
|
368
|
+
if (plain) return [...(title ? [[[title, 'b']]] : []), ...body.map((l) => fit(l, columns))];
|
|
369
|
+
const top = title ? [['╭─ ', cls], [title, 'b'], [` ${'─'.repeat(Math.max(0, columns - 5 - len(title)))}╮`, cls]] : [[`╭${'─'.repeat(columns - 2)}╮`, cls]];
|
|
370
|
+
return [top, ...body.map((l) => [['│ ', cls], ...padLine(l, inner), [' │', cls]]), [[`╰${'─'.repeat(columns - 2)}╯`, cls]]];
|
|
371
|
+
};
|
|
372
|
+
const panel = (columns, maxLines) => {
|
|
373
|
+
const spec =
|
|
374
|
+
S.view === 'tools' ? { items: toolItems(), f: S.tf, title: `settings › ${S.servers[S.sv].name}`, lw: 26 }
|
|
375
|
+
: S.view === 'add' ? { items: addItems(), f: S.add.f, title: 'settings › add a server', lw: 21 }
|
|
376
|
+
: { items: pageItems(), f: S.f, title: 'settings', lw: 18 };
|
|
377
|
+
const inner = plain ? columns : columns - 4;
|
|
378
|
+
const lines = [];
|
|
379
|
+
let fi = 0;
|
|
380
|
+
let k = 0;
|
|
381
|
+
for (const it of spec.items) {
|
|
382
|
+
if (it.head || it.note) {
|
|
383
|
+
lines.push(line(it, false, inner, spec.lw));
|
|
384
|
+
continue;
|
|
385
|
+
}
|
|
386
|
+
const foc = k === spec.f;
|
|
387
|
+
if (foc) fi = lines.length;
|
|
388
|
+
lines.push(line(it, foc, inner, spec.lw));
|
|
389
|
+
k++;
|
|
390
|
+
}
|
|
391
|
+
return framed(spec.title, windowed(lines, fi, Math.max(3, maxLines - (plain ? 1 : 2)), S.view), columns);
|
|
392
|
+
};
|
|
393
|
+
const askFrame = (columns) => {
|
|
394
|
+
const a = S.ask;
|
|
395
|
+
if (plain) return [[[`Question: ${a.title}`, 'b y']], [[` ${a.why}`, 'd']], [[` ${a.what}`, '']], [[a.keys, 'b']]];
|
|
396
|
+
return framed(null, [[[`⚠ ${a.title}`, 'b y']], [], [[` ${a.why}`, 'd']], [[` ${a.what}`, '']], [], [[a.keys, 'b']]], columns, 'y');
|
|
397
|
+
};
|
|
398
|
+
const hintLine = (columns) => {
|
|
399
|
+
const m = S.msg;
|
|
400
|
+
if (m) {
|
|
401
|
+
const cls = m.err ? 'r' : m.ok ? 'g' : m.warn ? 'y' : 'd';
|
|
402
|
+
const mark = m.err ? (plain ? 'x ' : '✗ ') : m.ok ? (plain ? 'ok ' : '✓ ') : m.warn ? '! ' : '';
|
|
403
|
+
return fit([[` ${mark}${m.err ?? m.ok ?? m.warn ?? m.info}`, cls]], columns);
|
|
404
|
+
}
|
|
405
|
+
const r = focused();
|
|
406
|
+
if (!r) return [];
|
|
407
|
+
let hint = r.hint ?? '';
|
|
408
|
+
if (S.view === 'page' && S.edit) hint = r.type === 'path' ? 'a folder that is there, absolute or under ~' : r.type === 'url' ? 'the whole address of a .gguf file, https://…' : `${r.type === 'money' ? 'dollars, like 5 or 2.50' : 'whole minutes'} — 0 for ${r.zero}`;
|
|
409
|
+
// The default goes first: a long hint is cut at the window's edge, and this is what ⌫ would do.
|
|
410
|
+
else if (r.id in CONFIG_DEFAULTS && S.v[r.id] !== CONFIG_DEFAULTS[r.id]) hint = `default ${show(r, CONFIG_DEFAULTS[r.id])} (⌫) · ${hint}`;
|
|
411
|
+
return fit([[` ${hint}`, 'd']], columns);
|
|
412
|
+
};
|
|
413
|
+
const keysFor = () => {
|
|
414
|
+
if (S.view === 'ask') return '';
|
|
415
|
+
if (S.view === 'page' && S.edit) return focused()?.type === 'path' ? 'enter keeps it · tab completes · esc puts it back' : 'enter keeps it · esc puts it back';
|
|
416
|
+
if (S.view === 'tools') return '↑↓ move · ←→ switch · a all · esc back';
|
|
417
|
+
if (S.view === 'add') return '↑↓ move · type or paste · ←→ login · space picks · esc back';
|
|
418
|
+
return '↑↓ move · ←→ change · enter edit · ⌫ default · esc close';
|
|
419
|
+
};
|
|
420
|
+
|
|
421
|
+
// ── what a key does ──
|
|
422
|
+
function set(r, value) {
|
|
423
|
+
const old = S.v[r.id];
|
|
424
|
+
if (old === value) return;
|
|
425
|
+
try {
|
|
426
|
+
config(r.id, value);
|
|
427
|
+
} catch (cause) {
|
|
428
|
+
return err(cause.message);
|
|
429
|
+
}
|
|
430
|
+
S.v[r.id] = value;
|
|
431
|
+
S.msg = { ok: `saved · ${r.label.toLowerCase()}: ${show(r, old)} → ${show(r, value)}${r.when ? ` · ${r.when}` : ''}` };
|
|
432
|
+
if (r.id === 'shell.sandbox' && value === 'off') S.msg = { warn: "saved · sandbox off from the next chat — the model's shell can write anywhere you can" };
|
|
433
|
+
if ((r.id === 'chat.model' || r.id === 'chat.effort') && live.route) {
|
|
434
|
+
try {
|
|
435
|
+
live.route(S.v['chat.model'] === 'auto' ? 'auto' : `${S.v['chat.model']} ${S.v['chat.effort']}`);
|
|
436
|
+
} catch (cause) {
|
|
437
|
+
S.msg = { warn: `saved for new chats; this one did not switch: ${cause.message}` };
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
if (r.id === 'model.url') {
|
|
441
|
+
S.msg = { info: `saved · downloading ${show(r, value)}… — the old model is used until it is here` };
|
|
442
|
+
later(download(), (said, cause) => {
|
|
443
|
+
S.msg = cause ? { err: cause.message } : /not|fail|could/i.test(String(said)) ? { warn: String(said).replace(/^model\s+/, '') } : { ok: String(said ?? 'downloaded').replace(/^model\s+/, '') };
|
|
444
|
+
});
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
function change(r, d) {
|
|
448
|
+
if (r.type === 'choice') {
|
|
449
|
+
const o = r.opts();
|
|
450
|
+
let i = o.indexOf(S.v[r.id]);
|
|
451
|
+
for (let n = 0; n < o.length; n++) {
|
|
452
|
+
i = (i + d + o.length) % o.length;
|
|
453
|
+
if (!r.disabled?.(o[i])) break;
|
|
454
|
+
}
|
|
455
|
+
return set(r, o[i]);
|
|
456
|
+
}
|
|
457
|
+
if (r.type === 'toggle') return flip(r);
|
|
458
|
+
if (r.type === 'money' || r.type === 'minutes') return set(r, String(Math.max(0, Math.round((Number(S.v[r.id]) + d * r.step) * 100) / 100)));
|
|
459
|
+
if (r.type === 'model') return flipModel(r.m);
|
|
460
|
+
S.msg = { info: r.type === 'server' || r.type === 'action' ? 'enter opens it' : 'enter changes it' };
|
|
461
|
+
}
|
|
462
|
+
function flip(r) {
|
|
463
|
+
if (r.id === 'shell.sandbox' && S.v[r.id] === 'on') {
|
|
464
|
+
S.ask = { title: 'Turn the sandbox off?', why: "the model's shell could then write anywhere you can, from the next chat on", what: 'Sandbox on → off', keys: 'y turn it off · n keep it on', yes: () => set(r, 'off'), no: () => (S.msg = { info: 'the sandbox stays on' }), back: 'page' };
|
|
465
|
+
S.view = 'ask';
|
|
466
|
+
return;
|
|
467
|
+
}
|
|
468
|
+
set(r, S.v[r.id] === 'on' ? 'off' : 'on');
|
|
469
|
+
}
|
|
470
|
+
function flipModel(m) {
|
|
471
|
+
if (S.on[m]) {
|
|
472
|
+
const users = [['chat.model', "the chat's model"], ['jobs.floor', "the jobs' smallest model"], ['memory.model', 'the model that files memory']].filter(([k]) => S.v[k] === m);
|
|
473
|
+
if (users.length > 0) return err(`${m} is ${users[0][1]} — pick another there first`);
|
|
474
|
+
if (MODELS.filter((x) => S.on[x]).length === 1) return err('one model stays on: chats and jobs need one');
|
|
475
|
+
}
|
|
476
|
+
setModel(db, m, !S.on[m]);
|
|
477
|
+
S.on = switches();
|
|
478
|
+
S.msg = { ok: S.on[m] ? `saved · ${m} on` : `saved · ${m} off · no longer offered anywhere` };
|
|
479
|
+
}
|
|
480
|
+
function reset(r) {
|
|
481
|
+
if (!(r.id in CONFIG_DEFAULTS)) return void (S.msg = { info: r.type === 'model' ? 'a model has no default — Discover sets the switches from what this login can use' : 'nothing to put back here' });
|
|
482
|
+
if (S.v[r.id] === CONFIG_DEFAULTS[r.id]) return void (S.msg = { info: `already the default (${show(r, CONFIG_DEFAULTS[r.id])})` });
|
|
483
|
+
if (r.disabled?.(CONFIG_DEFAULTS[r.id])) return err(`the default, ${CONFIG_DEFAULTS[r.id]}, is off — turn it on under API models first`);
|
|
484
|
+
set(r, CONFIG_DEFAULTS[r.id]);
|
|
485
|
+
}
|
|
486
|
+
function openTools(r) {
|
|
487
|
+
S.sv = r.i;
|
|
488
|
+
S.tf = 0;
|
|
489
|
+
S.tools = null;
|
|
490
|
+
S.view = 'tools';
|
|
491
|
+
S.scroll.tools = 0;
|
|
492
|
+
const { name, spec } = S.servers[r.i];
|
|
493
|
+
later(toolsOf(name, spec), (names, cause) => {
|
|
494
|
+
S.tools = cause ? { error: String(cause.message).split('\n')[0] } : { names };
|
|
495
|
+
});
|
|
496
|
+
}
|
|
497
|
+
function activate(r) {
|
|
498
|
+
switch (r.type) {
|
|
499
|
+
case 'choice':
|
|
500
|
+
case 'toggle':
|
|
501
|
+
case 'model':
|
|
502
|
+
return change(r, 1);
|
|
503
|
+
case 'money':
|
|
504
|
+
case 'minutes':
|
|
505
|
+
case 'url':
|
|
506
|
+
S.edit = { id: r.id, text: '' };
|
|
507
|
+
return;
|
|
508
|
+
case 'path':
|
|
509
|
+
S.edit = { id: r.id, text: S.v[r.id] };
|
|
510
|
+
return;
|
|
511
|
+
case 'server':
|
|
512
|
+
return openTools(r);
|
|
513
|
+
}
|
|
514
|
+
if (r.id === 'discover') {
|
|
515
|
+
S.msg = { info: 'asking the API which models this login can use…' };
|
|
516
|
+
later(discover(db), (found, cause) => {
|
|
517
|
+
S.on = switches();
|
|
518
|
+
S.msg = cause ? { err: cause.message } : found.ok ? { ok: discoverySummary(found) } : { err: found.error };
|
|
519
|
+
});
|
|
520
|
+
}
|
|
521
|
+
if (r.id === 'add') {
|
|
522
|
+
let known = [];
|
|
523
|
+
try {
|
|
524
|
+
known = claude();
|
|
525
|
+
} catch {
|
|
526
|
+
known = [];
|
|
527
|
+
}
|
|
528
|
+
S.add = { addr: '', name: '', nameTouched: false, login: 0, cred: '', picked: new Set(), f: 0, claude: known };
|
|
529
|
+
S.view = 'add';
|
|
530
|
+
S.scroll.add = 0;
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
/** What was typed into a row, saved — or refused with why, the row still open to put it right. */
|
|
534
|
+
function commit(r, raw) {
|
|
535
|
+
const t = raw.trim();
|
|
536
|
+
if (!t) return err(r.type === 'url' ? 'paste the whole address of a .gguf file, https://…/<file>.gguf' : 'nothing typed — esc puts it back as it was');
|
|
537
|
+
const number = (r.type === 'money' || r.type === 'minutes') && /^\d+(\.\d+)?$/.test(t);
|
|
538
|
+
set(r, r.type === 'path' && t.length > 1 ? t.replace(/\/+$/, '') : number ? String(Number(t)) : t);
|
|
539
|
+
if (!S.msg?.err) S.edit = null;
|
|
540
|
+
}
|
|
541
|
+
/** Tab on a folder: the one folder it can only be, or as far as they all agree. */
|
|
542
|
+
function complete(e) {
|
|
543
|
+
const typed = e.text;
|
|
544
|
+
const full = typed.replace(/^~(?=$|\/)/, homedir());
|
|
545
|
+
const at = full.lastIndexOf('/');
|
|
546
|
+
const dir = at === -1 ? '.' : full.slice(0, at) || '/';
|
|
547
|
+
const stem = full.slice(at + 1);
|
|
548
|
+
let names = [];
|
|
549
|
+
try {
|
|
550
|
+
names = readdirSync(dir).filter((n) => n.startsWith(stem) && (stem.startsWith('.') || !n.startsWith('.')) && statSync(join(dir, n)).isDirectory());
|
|
551
|
+
} catch {
|
|
552
|
+
names = [];
|
|
553
|
+
}
|
|
554
|
+
if (names.length === 0) return void (S.msg = { info: `no folder starts with ${typed}` });
|
|
555
|
+
let common = names[0];
|
|
556
|
+
for (const n of names) while (!n.startsWith(common)) common = common.slice(0, -1);
|
|
557
|
+
e.text = typed.slice(0, typed.length - stem.length) + common + (names.length === 1 ? '/' : '');
|
|
558
|
+
if (names.length > 1) S.msg = { info: names.slice(0, 8).join(' · ') + (names.length > 8 ? ` · and ${names.length - 8} more` : '') };
|
|
559
|
+
}
|
|
560
|
+
function typeInto(r, text) {
|
|
561
|
+
const a = S.add;
|
|
562
|
+
a[r.id] += text;
|
|
563
|
+
if (r.id === 'addr' && !a.nameTouched) a.name = nameFrom(a.addr);
|
|
564
|
+
if (r.id === 'name') a.nameTouched = true;
|
|
565
|
+
}
|
|
566
|
+
/** What was pasted and picked on the add view, as the server Sumo would run; a token typed in is refused, never stored. */
|
|
567
|
+
function specOf(a) {
|
|
568
|
+
const addr = a.addr.trim();
|
|
569
|
+
const http = /^https?:\/\//i.test(addr);
|
|
570
|
+
if (!addr) throw new Error('paste a command or an address first');
|
|
571
|
+
const cred = a.cred.trim();
|
|
572
|
+
if (http) {
|
|
573
|
+
if (a.login === 1) return { url: addr, token: CLAUDE_CODE_TOKEN };
|
|
574
|
+
if (a.login === 2) {
|
|
575
|
+
const m = /^([^:\s]+)\s*:\s*(.+)$/.exec(cred);
|
|
576
|
+
if (!m) throw new Error('the header, as Name: value — with ${NAME} where the token goes');
|
|
577
|
+
if (!NAMED.test(m[2])) throw new Error('a token typed here would be stored — write ${NAME} and keep the token in your shell');
|
|
578
|
+
return { url: addr, headers: { [m[1]]: m[2] } };
|
|
579
|
+
}
|
|
580
|
+
return { url: addr };
|
|
581
|
+
}
|
|
582
|
+
const [command, ...args] = wordsOf(addr);
|
|
583
|
+
if (a.login === 1) {
|
|
584
|
+
const pairs = wordsOf(cred).map((p) => /^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(p));
|
|
585
|
+
if (pairs.length === 0 || pairs.some((p) => !p)) throw new Error('variables as NAME=${NAME}, one or more');
|
|
586
|
+
if (pairs.some((p) => !NAMED.test(p[2]) && redact(p[2]) !== p[2])) throw new Error('a token typed here would be stored — write ${NAME} and keep the token in your shell');
|
|
587
|
+
return { command, args, env: Object.fromEntries(pairs.map((p) => [p[1], p[2]])) };
|
|
588
|
+
}
|
|
589
|
+
return { command, args };
|
|
590
|
+
}
|
|
591
|
+
/** A server joins: its tools listed once, each asking first. One that will not connect is kept, and why is said. */
|
|
592
|
+
function joined(name, spec) {
|
|
593
|
+
S.servers = serversNow();
|
|
594
|
+
S.log.push(`${name} added`);
|
|
595
|
+
S.view = 'page';
|
|
596
|
+
S.add = null;
|
|
597
|
+
S.f = focusables(pageItems()).findIndex((x) => x.id === `server:${name}`);
|
|
598
|
+
S.msg = { info: `connecting to ${name}…` };
|
|
599
|
+
const next = live.route ? ' · this chat connects it when it starts again' : '';
|
|
600
|
+
later(toolsOf(name, spec), (names, cause) => {
|
|
601
|
+
S.msg = cause ? { warn: `${name} is added, but it did not connect: ${String(cause.message).split('\n')[0]}` } : { ok: `${name}: ${names.length} tools, each asks first until you switch it here${next}` };
|
|
602
|
+
});
|
|
603
|
+
}
|
|
604
|
+
function addOwn() {
|
|
605
|
+
const a = S.add;
|
|
606
|
+
let spec;
|
|
607
|
+
try {
|
|
608
|
+
spec = specOf(a);
|
|
609
|
+
addServer(a.name.trim(), spec);
|
|
610
|
+
} catch (cause) {
|
|
611
|
+
return err(cause.message);
|
|
612
|
+
}
|
|
613
|
+
joined(a.name.trim(), spec);
|
|
614
|
+
}
|
|
615
|
+
function bring() {
|
|
616
|
+
const picked = S.add.claude.filter((c) => S.add.picked.has(c.name));
|
|
617
|
+
if (picked.length === 0) return err('pick one first: space on its row');
|
|
618
|
+
const brought = [];
|
|
619
|
+
for (const c of picked) {
|
|
620
|
+
try {
|
|
621
|
+
addServer(c.name, c.spec);
|
|
622
|
+
brought.push(c.name);
|
|
623
|
+
S.log.push(`${c.name} brought in`);
|
|
624
|
+
} catch (cause) {
|
|
625
|
+
return err(`${c.name}: ${cause.message}`);
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
S.servers = serversNow();
|
|
629
|
+
S.view = 'page';
|
|
630
|
+
S.add = null;
|
|
631
|
+
S.f = focusables(pageItems()).findIndex((x) => x.id === `server:${brought[0]}`);
|
|
632
|
+
S.msg = { ok: `brought in from Claude Code: ${brought.join(', ')} · each tool asks first` };
|
|
633
|
+
}
|
|
634
|
+
function toggleTool(s, t) {
|
|
635
|
+
const on = allowedBy(s.spec, t);
|
|
636
|
+
setAllow(s.name, t, !on, S.tools.names);
|
|
637
|
+
S.servers = serversNow();
|
|
638
|
+
if (!S.log.includes(`${s.name} allow list`)) S.log.push(`${s.name} allow list`);
|
|
639
|
+
S.msg = { ok: `${t} ${on ? 'asks first again' : 'runs without asking'}${live.route ? ' · from the next chat' : ''}` };
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
function onPage(k) {
|
|
643
|
+
const its = focusables(pageItems());
|
|
644
|
+
const r = its[S.f];
|
|
645
|
+
switch (k) {
|
|
646
|
+
case 'up':
|
|
647
|
+
S.f = Math.max(0, S.f - 1);
|
|
648
|
+
return;
|
|
649
|
+
case 'down':
|
|
650
|
+
S.f = Math.min(its.length - 1, S.f + 1);
|
|
651
|
+
return;
|
|
652
|
+
case 'left':
|
|
653
|
+
return change(r, -1);
|
|
654
|
+
case 'right':
|
|
655
|
+
return change(r, 1);
|
|
656
|
+
case 'enter':
|
|
657
|
+
case 'space':
|
|
658
|
+
return activate(r);
|
|
659
|
+
case 'backspace':
|
|
660
|
+
return reset(r);
|
|
661
|
+
case 'escape':
|
|
662
|
+
return close();
|
|
663
|
+
}
|
|
664
|
+
if (/^\d$/.test(k) && (r.type === 'money' || r.type === 'minutes')) {
|
|
665
|
+
S.edit = { id: r.id, text: k };
|
|
666
|
+
return;
|
|
667
|
+
}
|
|
668
|
+
S.msg = { info: `the keys: ${keysFor()}` };
|
|
669
|
+
}
|
|
670
|
+
function onEdit(k) {
|
|
671
|
+
const r = focused();
|
|
672
|
+
const e = S.edit;
|
|
673
|
+
if (k === 'escape') {
|
|
674
|
+
S.edit = null;
|
|
675
|
+
S.msg = { info: 'put back as it was' };
|
|
676
|
+
} else if (k === 'enter') commit(r, e.text);
|
|
677
|
+
else if (k === 'backspace') e.text = e.text.slice(0, -1);
|
|
678
|
+
else if (k === 'tab') {
|
|
679
|
+
if (r.type === 'path') complete(e);
|
|
680
|
+
} else if (k === 'space') e.text += ' ';
|
|
681
|
+
else if (len(k) === 1) e.text += k;
|
|
682
|
+
}
|
|
683
|
+
function onTools(k) {
|
|
684
|
+
const its = focusables(toolItems());
|
|
685
|
+
const r = its[S.tf];
|
|
686
|
+
const s = S.servers[S.sv];
|
|
687
|
+
if (k === 'up') S.tf = Math.max(0, S.tf - 1);
|
|
688
|
+
else if (k === 'down') S.tf = Math.min(its.length - 1, S.tf + 1);
|
|
689
|
+
else if (k === 'escape') {
|
|
690
|
+
S.view = 'page';
|
|
691
|
+
generation++;
|
|
692
|
+
} else if (k === 'a' || k === 'A') {
|
|
693
|
+
if (!S.tools?.names?.length) return err('no tools to switch: it has not connected');
|
|
694
|
+
const every = s.spec.allow === 'all' || S.tools.names.every((t) => allowedBy(s.spec, t));
|
|
695
|
+
setAllow(s.name, 'all', !every);
|
|
696
|
+
S.servers = serversNow();
|
|
697
|
+
if (!S.log.includes(`${s.name} allow list`)) S.log.push(`${s.name} allow list`);
|
|
698
|
+
S.msg = every ? { ok: `every ${s.name} tool asks first again` } : { warn: `every ${s.name} tool runs without asking — new ones it adds too` };
|
|
699
|
+
} else if (['left', 'right', 'enter', 'space'].includes(k) && r?.type === 'tool') toggleTool(s, r.t);
|
|
700
|
+
else if ((k === 'enter' || k === 'space') && r?.type === 'danger') {
|
|
701
|
+
S.ask = {
|
|
702
|
+
title: `Remove ${s.name}?`,
|
|
703
|
+
why: 'its allow list goes with it — added again, every tool asks first',
|
|
704
|
+
what: s.spec.url ?? [s.spec.command, ...(s.spec.args ?? [])].join(' '),
|
|
705
|
+
keys: 'y remove it · n keep it',
|
|
706
|
+
yes: () => {
|
|
707
|
+
try {
|
|
708
|
+
removeServer(s.name);
|
|
709
|
+
} catch (cause) {
|
|
710
|
+
return err(cause.message);
|
|
711
|
+
}
|
|
712
|
+
S.servers = serversNow();
|
|
713
|
+
S.log.push(`${s.name} removed`);
|
|
714
|
+
S.view = 'page';
|
|
715
|
+
S.f = Math.min(S.f, focusables(pageItems()).length - 1);
|
|
716
|
+
S.msg = { ok: `${s.name} removed` };
|
|
717
|
+
},
|
|
718
|
+
no: () => (S.msg = { info: `${s.name} stays` }),
|
|
719
|
+
back: 'tools',
|
|
720
|
+
};
|
|
721
|
+
S.view = 'ask';
|
|
722
|
+
} else if (len(k) === 1) S.msg = { info: `the keys: ${keysFor()}` };
|
|
723
|
+
}
|
|
724
|
+
function onAdd(k) {
|
|
725
|
+
const a = S.add;
|
|
726
|
+
const its = focusables(addItems());
|
|
727
|
+
const r = its[a.f];
|
|
728
|
+
if (k === 'escape') {
|
|
729
|
+
S.view = 'page';
|
|
730
|
+
S.add = null;
|
|
731
|
+
S.msg = { info: 'nothing added' };
|
|
732
|
+
return;
|
|
733
|
+
}
|
|
734
|
+
if (k === 'up') return void (a.f = Math.max(0, a.f - 1));
|
|
735
|
+
if (k === 'down' || k === 'tab') return void (a.f = Math.min(its.length - 1, a.f + 1));
|
|
736
|
+
if (r.type === 'text') {
|
|
737
|
+
if (k === 'enter') a.f = Math.min(its.length - 1, a.f + 1);
|
|
738
|
+
else if (k === 'backspace') {
|
|
739
|
+
a[r.id] = a[r.id].slice(0, -1);
|
|
740
|
+
if (r.id === 'addr' && !a.nameTouched) a.name = nameFrom(a.addr);
|
|
741
|
+
if (r.id === 'name') a.nameTouched = true;
|
|
742
|
+
} else if (k === 'space') typeInto(r, ' ');
|
|
743
|
+
else if (len(k) === 1) typeInto(r, k);
|
|
744
|
+
return;
|
|
745
|
+
}
|
|
746
|
+
if (r.type === 'achoice' && ['left', 'right', 'enter', 'space'].includes(k)) {
|
|
747
|
+
a.login = (a.login + (k === 'left' ? -1 : 1) + r.opts.length) % r.opts.length;
|
|
748
|
+
return;
|
|
749
|
+
}
|
|
750
|
+
if (r.type === 'pick' && ['left', 'right', 'enter', 'space'].includes(k)) {
|
|
751
|
+
if (S.servers.some((s) => s.name === r.c.name)) return void (S.msg = { info: `${r.c.name} is already here` });
|
|
752
|
+
if (r.c.why) return err(r.c.why);
|
|
753
|
+
if (a.picked.has(r.c.name)) a.picked.delete(r.c.name);
|
|
754
|
+
else a.picked.add(r.c.name);
|
|
755
|
+
return;
|
|
756
|
+
}
|
|
757
|
+
if (r.id === 'go' && (k === 'enter' || k === 'space')) return addOwn();
|
|
758
|
+
if (r.id === 'bring' && (k === 'enter' || k === 'space')) return bring();
|
|
759
|
+
if (len(k) === 1) S.msg = { info: `the keys: ${keysFor()}` };
|
|
760
|
+
}
|
|
761
|
+
function onAsk(k) {
|
|
762
|
+
const a = S.ask;
|
|
763
|
+
if (k === 'y' || k === 'Y' || k === 'n' || k === 'N' || k === 'escape') {
|
|
764
|
+
S.view = a.back;
|
|
765
|
+
S.ask = null;
|
|
766
|
+
if (k === 'y' || k === 'Y') a.yes();
|
|
767
|
+
else a.no();
|
|
768
|
+
return;
|
|
769
|
+
}
|
|
770
|
+
S.msg = { info: `y or n — ${a.keys}` };
|
|
771
|
+
}
|
|
772
|
+
function close() {
|
|
773
|
+
S.closed = true;
|
|
774
|
+
generation++;
|
|
775
|
+
db.close();
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
return {
|
|
779
|
+
/** A key, by the page's name for it (`keyName`). True once the page has closed. */
|
|
780
|
+
key(k) {
|
|
781
|
+
if (S.closed || k === null) return S.closed;
|
|
782
|
+
// While something slow is under way only Esc is taken: it goes back, and the answer, when it comes, is dropped.
|
|
783
|
+
if (busy() && k !== 'escape') return false;
|
|
784
|
+
if (busy() && S.view === 'page') generation++;
|
|
785
|
+
S.msg = null;
|
|
786
|
+
if (S.view === 'ask') onAsk(k);
|
|
787
|
+
else if (S.view === 'tools') onTools(k);
|
|
788
|
+
else if (S.view === 'add') onAdd(k);
|
|
789
|
+
else if (S.edit) onEdit(k);
|
|
790
|
+
else onPage(k);
|
|
791
|
+
return S.closed;
|
|
792
|
+
},
|
|
793
|
+
/** Pasted text goes into the field being typed in — and with nothing being typed, into a new server's address. */
|
|
794
|
+
paste(text) {
|
|
795
|
+
const t = String(text).replace(/\s*\n\s*/g, ' ').trim();
|
|
796
|
+
if (S.closed || busy() || !t) return;
|
|
797
|
+
if (S.view === 'page' && S.edit) {
|
|
798
|
+
S.edit.text += t;
|
|
799
|
+
return;
|
|
800
|
+
}
|
|
801
|
+
if (S.view === 'page') {
|
|
802
|
+
activate({ id: 'add', type: 'action' });
|
|
803
|
+
S.f = focusables(pageItems()).findIndex((x) => x.id === 'add');
|
|
804
|
+
}
|
|
805
|
+
if (S.view !== 'add') return;
|
|
806
|
+
const r = focusables(addItems())[S.add.f];
|
|
807
|
+
typeInto(r.type === 'text' ? r : focusables(addItems())[0], t);
|
|
808
|
+
},
|
|
809
|
+
/** The page as lines of `[text, tone]`, `columns` wide and at most `rows` tall: the frame, the hint under it, the keys. */
|
|
810
|
+
lines({ columns, rows, plain: bare = false }) {
|
|
811
|
+
plain = bare;
|
|
812
|
+
const left = live.left?.() ?? '';
|
|
813
|
+
const keys = keysFor();
|
|
814
|
+
const leftShown = left && len(left) + 4 + len(trimKeys(keys, columns - 4)) <= columns ? left : '';
|
|
815
|
+
const k = trimKeys(keys, columns - 2 - (leftShown ? len(leftShown) + 2 : 0));
|
|
816
|
+
const foot = [hintLine(columns), leftShown ? [[` ${leftShown}`, 'd'], [' '.repeat(Math.max(2, columns - 2 - len(leftShown) - len(k))), ''], [k, 'd']] : [[` ${k}`, 'd']]];
|
|
817
|
+
const body = S.view === 'ask' ? askFrame(columns) : panel(columns, rows - foot.length);
|
|
818
|
+
return [...body, ...foot].map((l) => fit(l, columns));
|
|
819
|
+
},
|
|
820
|
+
/** What changed while the page was open, in a line for the chat's scrollback or `sumo config`'s output. */
|
|
821
|
+
summary() {
|
|
822
|
+
const out = [];
|
|
823
|
+
for (const [, rows] of sections()) {
|
|
824
|
+
for (const r of rows) if (r.id in snap.v && snap.v[r.id] !== S.v[r.id]) out.push(`${r.label.toLowerCase()} ${show(r, snap.v[r.id])} → ${show(r, S.v[r.id])}`);
|
|
825
|
+
}
|
|
826
|
+
for (const m of MODELS) if (snap.on[m] !== S.on[m]) out.push(`${m} ${S.on[m] ? 'on' : 'off'}`);
|
|
827
|
+
return [...out, ...S.log];
|
|
828
|
+
},
|
|
829
|
+
get closed() {
|
|
830
|
+
return S.closed;
|
|
831
|
+
},
|
|
832
|
+
};
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
const toneOf = (cls) => Object.assign({}, ...String(cls ?? '').split(' ').filter(Boolean).map((c) => TONES[c] ?? {}));
|
|
836
|
+
|
|
837
|
+
/** The page's lines on an Ink screen. */
|
|
838
|
+
export function SettingsView({ page, columns, rows, plain = false }) {
|
|
839
|
+
const lines = page.lines({ columns, rows, plain });
|
|
840
|
+
return h(Box, { flexDirection: 'column' }, ...lines.map((l, i) => h(Text, { key: i, wrap: 'truncate' }, ...(l.length === 0 ? [' '] : l.map(([t, c], j) => h(Text, { key: j, ...toneOf(c) }, t))))));
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
/** `sumo config` at a terminal: the page on its own, until Esc; then what changed, said once. */
|
|
844
|
+
export async function runSettings({ stdin = process.stdin, stdout = process.stdout, plain = false } = {}) {
|
|
845
|
+
let wake = () => {};
|
|
846
|
+
function App() {
|
|
847
|
+
const { exit } = useApp();
|
|
848
|
+
const { columns, rows } = useWindowSize();
|
|
849
|
+
const [, redraw] = useReducer((n) => n + 1, 0);
|
|
850
|
+
wake = redraw;
|
|
851
|
+
useInput((input, key) => {
|
|
852
|
+
if (page.key(keyName(input, key))) return exit();
|
|
853
|
+
redraw();
|
|
854
|
+
});
|
|
855
|
+
usePaste((text) => {
|
|
856
|
+
page.paste(text);
|
|
857
|
+
redraw();
|
|
858
|
+
});
|
|
859
|
+
// One row short of the window: Ink draws a frame that fills it as a full screen, wiping what was above.
|
|
860
|
+
return h(SettingsView, { page, columns, rows: Math.max(8, rows - 1), plain });
|
|
861
|
+
}
|
|
862
|
+
const page = settingsPage({ onChange: () => wake() });
|
|
863
|
+
const app = render(h(App), { stdin, stdout, exitOnCtrlC: false, interactive: Boolean(stdout.isTTY) });
|
|
864
|
+
await app.waitUntilExit();
|
|
865
|
+
const changed = page.summary();
|
|
866
|
+
return changed.length > 0 ? changed.map((c) => `saved: ${c}`) : ['nothing changed'];
|
|
867
|
+
}
|
|
868
|
+
|