sumo-agents 0.0.0-stage → 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.
Files changed (66) hide show
  1. package/AGENTS.md +38 -0
  2. package/LICENSE +21 -0
  3. package/README.md +111 -2
  4. package/bin/sumo.mjs +33 -0
  5. package/guides/delegation.md +33 -0
  6. package/guides/feature.md +14 -0
  7. package/guides/fix.md +14 -0
  8. package/guides/memory.md +23 -0
  9. package/guides/projects.md +27 -0
  10. package/guides/review.md +16 -0
  11. package/guides/workflows.md +26 -0
  12. package/logo.txt +19 -0
  13. package/package.json +42 -4
  14. package/prompts/agent.md +7 -0
  15. package/prompts/dream.md +13 -0
  16. package/prompts/scribe.md +21 -0
  17. package/spinner.txt +90 -0
  18. package/src/advisor.mjs +59 -0
  19. package/src/apply.mjs +368 -0
  20. package/src/auth.mjs +80 -0
  21. package/src/card.mjs +72 -0
  22. package/src/catalog.mjs +167 -0
  23. package/src/chat.mjs +1162 -0
  24. package/src/cli.mjs +815 -0
  25. package/src/cost.mjs +128 -0
  26. package/src/db.mjs +384 -0
  27. package/src/dream.mjs +97 -0
  28. package/src/editor.mjs +198 -0
  29. package/src/export.mjs +132 -0
  30. package/src/guard.mjs +121 -0
  31. package/src/guides.mjs +86 -0
  32. package/src/herdr.mjs +117 -0
  33. package/src/hooks.mjs +270 -0
  34. package/src/images.mjs +89 -0
  35. package/src/jobs.mjs +1184 -0
  36. package/src/jobtools.mjs +82 -0
  37. package/src/local-server.mjs +169 -0
  38. package/src/lock.mjs +45 -0
  39. package/src/loop.mjs +838 -0
  40. package/src/mcp.mjs +604 -0
  41. package/src/memory.mjs +400 -0
  42. package/src/model.mjs +270 -0
  43. package/src/page.html +304 -0
  44. package/src/page.mjs +135 -0
  45. package/src/paths.mjs +33 -0
  46. package/src/prime.mjs +177 -0
  47. package/src/projects.mjs +232 -0
  48. package/src/recall.mjs +45 -0
  49. package/src/redact.mjs +173 -0
  50. package/src/render.mjs +45 -0
  51. package/src/route.mjs +287 -0
  52. package/src/sandbox.mjs +173 -0
  53. package/src/scan.mjs +204 -0
  54. package/src/scribe.mjs +349 -0
  55. package/src/sessions.mjs +371 -0
  56. package/src/setup.mjs +528 -0
  57. package/src/sqlite.mjs +66 -0
  58. package/src/text.mjs +97 -0
  59. package/src/tools.mjs +987 -0
  60. package/src/transcript.mjs +106 -0
  61. package/src/tty.mjs +529 -0
  62. package/src/ui.mjs +1363 -0
  63. package/src/verify.mjs +369 -0
  64. package/src/web.mjs +49 -0
  65. package/src/workflows.mjs +270 -0
  66. package/src/worktree.mjs +128 -0
package/src/setup.mjs ADDED
@@ -0,0 +1,528 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import {
3
+ accessSync, chmodSync, constants, createWriteStream, existsSync, lstatSync, mkdirSync, readFileSync,
4
+ readlinkSync, realpathSync, renameSync, rmSync, statSync, symlinkSync, unlinkSync, writeFileSync,
5
+ } from 'node:fs';
6
+ import { homedir, hostname } from 'node:os';
7
+ import { basename, delimiter, isAbsolute, join } from 'node:path';
8
+ import { createInterface } from 'node:readline/promises';
9
+ import { pipeline } from 'node:stream/promises';
10
+ import { Readable, Transform } from 'node:stream';
11
+ import { anthropicClient, authenticatedRequest, resolveAnthropicCredential } from './auth.mjs';
12
+ import { assertOn, describeApiError, discoverModels, discoverySummary, knownModel, MODELS, modelsChecked, modelStates } from './catalog.mjs';
13
+ import { getMeta, openDb, SCHEMA_VERSION, schemaVersion, setMeta } from './db.mjs';
14
+ import { stopLocalServer } from './local-server.mjs';
15
+ import { UsageError } from './memory.mjs';
16
+ import { COMPILED, ENTRY, paths, REPO_ROOT } from './paths.mjs';
17
+
18
+ const NODE_REQUIREMENT = '22.19+ or 24.6+';
19
+ // route.mjs's EFFORTS, spelled out: importing it would close a cycle (route → model → setup). A test keeps them equal.
20
+ export const CHAT_EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max'];
21
+
22
+ /** The settings `sumo config` accepts, with the value used when none is stored. */
23
+ export const CONFIG_DEFAULTS = {
24
+ 'prime.budget': '800',
25
+ 'scribe.model': 'local',
26
+ 'dream.model': 'local',
27
+ 'chat.model': 'opus',
28
+ 'chat.effort': 'medium',
29
+ 'chat.notify': 'on',
30
+ 'chat.budget': '5',
31
+ 'guides.auto': 'on',
32
+ 'jobs.advisor': 'off',
33
+ 'jobs.budget': '10',
34
+ 'jobs.escalate': 'on',
35
+ 'jobs.review': 'risky',
36
+ 'shell.sandbox': 'on',
37
+ 'jobs.minutes': '60',
38
+ 'shell.network': 'on',
39
+ 'projects.home': '~',
40
+ 'scratch.days': '14',
41
+ 'model.source': 'https://huggingface.co',
42
+ 'model.repo': 'Qwen/Qwen3-4B-GGUF',
43
+ 'model.file': 'Qwen3-4B-Q4_K_M.gguf',
44
+ };
45
+
46
+ /**
47
+ * The launcher exists because hooks and sub-agents run where a version
48
+ * manager's `node` is not on PATH and the repo's location is unknown. It pins
49
+ * both as absolute paths, so `sumo` means the same thing everywhere.
50
+ */
51
+ function launcherScript() {
52
+ // Single quotes keep a `$`, backtick or `"` in either path literal; a `'` is closed, escaped and reopened.
53
+ const quote = (s) => `'${s.replaceAll("'", `'\\''`)}'`;
54
+ const self = COMPILED ? quote(ENTRY) : `${quote(process.execPath)} --disable-warning=ExperimentalWarning ${quote(ENTRY)}`;
55
+ return `#!/bin/sh\nexport NODE_USE_SYSTEM_CA=1\nexec ${self} "$@"\n`;
56
+ }
57
+
58
+ /** A directory already on PATH, inside the home folder, that a command can be linked into without sudo. */
59
+ function pickBinDir() {
60
+ const home = homedir();
61
+ const onPath = (process.env.PATH ?? '').split(delimiter).filter(Boolean);
62
+ const usable = (dir) => {
63
+ try {
64
+ accessSync(dir, constants.W_OK);
65
+ return statSync(dir).isDirectory();
66
+ } catch {
67
+ return false;
68
+ }
69
+ };
70
+ // Version-manager and toolchain directories are on PATH too, but they are
71
+ // replaced on upgrade — a link placed there silently disappears.
72
+ const volatile = /\/(\.nvm|\.volta|\.asdf|\.cargo|\.bun|node_modules|\.rbenv|\.pyenv)\//;
73
+ const preferred = [join(home, '.local', 'bin'), join(home, 'bin')].filter((d) => onPath.includes(d));
74
+ const others = onPath.filter((d) => d.startsWith(`${home}/`) && !volatile.test(`${d}/`));
75
+ return [...preferred, ...others].find(usable) ?? null;
76
+ }
77
+
78
+ function linkInto(binDir, launcher) {
79
+ const link = join(binDir, 'sumo');
80
+ let existing = null;
81
+ try {
82
+ existing = lstatSync(link);
83
+ } catch {
84
+ // Nothing there yet.
85
+ }
86
+ if (existing) {
87
+ const ours = existing.isSymbolicLink() && readlinkSync(link) === launcher;
88
+ if (ours) return { link, status: 'already linked' };
89
+ if (!existing.isSymbolicLink() || !readlinkSync(link).endsWith('/.sumo-agents/bin/sumo')) {
90
+ return { link, status: 'skipped — a different `sumo` is already there' };
91
+ }
92
+ unlinkSync(link);
93
+ }
94
+ symlinkSync(launcher, link);
95
+ return { link, status: 'linked' };
96
+ }
97
+
98
+ /** "2621440000" -> "2.4 GB". Decimal (1000-based), the way Hugging Face itself labels file sizes. */
99
+ function formatBytes(n) {
100
+ const units = ['B', 'KB', 'MB', 'GB', 'TB'];
101
+ let value = n;
102
+ let i = 0;
103
+ while (value >= 1000 && i < units.length - 1) {
104
+ value /= 1000;
105
+ i++;
106
+ }
107
+ return `${value.toFixed(1)} ${units[i]}`;
108
+ }
109
+
110
+ /** This layout also works behind a JFrog Artifactory Hugging Face remote, whose base is its huggingfaceml URL. */
111
+ function modelUrl({ source, repo, file }) {
112
+ return `${source}/${repo}/resolve/main/${file}`;
113
+ }
114
+
115
+ /**
116
+ * Downloads the router model unless it is already there at the size the server reports (HEAD first).
117
+ * Streams to `<file>.part` then renames, so a run that dies never leaves a file that looks finished.
118
+ * Never throws: a model that could not be fetched is not a reason for `sumo setup` to fail.
119
+ */
120
+ async function ensureModel(db, { modelSource } = {}) {
121
+ const file = getMeta(db, 'config.model.file') ?? CONFIG_DEFAULTS['model.file'];
122
+ const repo = getMeta(db, 'config.model.repo') ?? CONFIG_DEFAULTS['model.repo'];
123
+ const source = modelSource ?? getMeta(db, 'config.model.source') ?? CONFIG_DEFAULTS['model.source'];
124
+ // The file name decides where the bytes land; a separator in it would let `sumo config` point outside models/.
125
+ if (file !== basename(file) || file === '..' || file === '.') {
126
+ return `model.file "${file}" is refused — a file name, with no path separator: sumo config model.file <name>`;
127
+ }
128
+ const dest = join(paths().models, file);
129
+ const url = modelUrl({ source, repo, file });
130
+ const shown = redactUrl(url);
131
+ // Unique per run: two setups at once must not interleave into one file, and a dead run must not leave a
132
+ // part file that a later run mistakes for progress.
133
+ const partPath = `${dest}.${process.pid}.part`;
134
+ try {
135
+ // fetch refuses a URL with credentials in it, so a token pasted into the source travels as a header instead.
136
+ const { href, headers } = withoutCredentials(url);
137
+ const head = await fetch(href, { method: 'HEAD', headers });
138
+ if (!head.ok) throw new Error(`HEAD ${shown} → HTTP ${head.status}`);
139
+ const lengthHeader = head.headers.get('content-length');
140
+ const remoteSize = lengthHeader === null ? null : Number(lengthHeader);
141
+ const localSize = existsSync(dest) ? statSync(dest).size : null;
142
+ // No Content-Length (a JFrog remote that has not cached the artifact yet) → keep what is there rather than
143
+ // fetch gigabytes on every setup; a size mismatch is the only reason to download again.
144
+ if (localSize !== null && (remoteSize === null || localSize === remoteSize)) {
145
+ return `model ${dest} (${formatBytes(localSize)}, present)`;
146
+ }
147
+ const res = await fetch(href, { headers });
148
+ if (!res.ok) throw new Error(`GET ${shown} → HTTP ${res.status}`);
149
+ await pipeline(Readable.fromWeb(res.body), cappedAt(MAX_MODEL_BYTES), createWriteStream(partPath));
150
+ renameSync(partPath, dest);
151
+ return `model ${dest} (${formatBytes(statSync(dest).size)}, downloaded)`;
152
+ } catch (cause) {
153
+ rmSync(partPath, { force: true });
154
+ const why = redactUrl(cause.message);
155
+ // Offline, with the model already here: that is a model that could not be checked, not one that is missing.
156
+ if (existsSync(dest)) return `model ${dest} (${formatBytes(statSync(dest).size)}, present; not checked against ${shown}: ${why})`;
157
+ return `could not download the router model from ${shown}: ${why}`;
158
+ }
159
+ }
160
+
161
+ /** The URL without its `user:token@`, and that pair as a Basic authorization header. */
162
+ function withoutCredentials(raw) {
163
+ const url = new URL(raw);
164
+ if (!url.username && !url.password) return { href: url.href, headers: {} };
165
+ const pair = `${decodeURIComponent(url.username)}:${decodeURIComponent(url.password)}`;
166
+ url.username = '';
167
+ url.password = '';
168
+ return { href: url.href, headers: { authorization: `Basic ${Buffer.from(pair).toString('base64')}` } };
169
+ }
170
+
171
+ /** A source pasted with a token in it (`https://user:token@host/…`) must never reach stdout or a transcript. */
172
+ function redactUrl(text) {
173
+ return String(text).replace(/(https?:\/\/)[^/\s@]+@/g, '$1');
174
+ }
175
+
176
+ // Larger than any model setup would fetch; a server that streams past its advertised size stops here, not at a full disk.
177
+ const MAX_MODEL_BYTES = 8 * 1000 * 1000 * 1000;
178
+
179
+ /** Passes bytes through until the cap, then fails the pipeline instead of filling the disk. */
180
+ function cappedAt(limit) {
181
+ let seen = 0;
182
+ return new Transform({
183
+ transform(chunk, _encoding, done) {
184
+ seen += chunk.length;
185
+ if (seen > limit) done(new Error(`download exceeded ${formatBytes(limit)}`));
186
+ else done(null, chunk);
187
+ },
188
+ });
189
+ }
190
+
191
+ /** A model source is a web address; anything else is refused before it is stored, since every later setup would fail on it. */
192
+ function sourceOrRefuse(value) {
193
+ if (!/^https?:\/\/[^\s/]/i.test(value)) throw new UsageError(`"${redactUrl(value)}" is not a web address — a model source looks like https://<host>[/<path>]`);
194
+ // The router model is run on every job: fetched in clear text it is anyone's on the way to replace. Loopback, a mirror on this machine, is the exception.
195
+ if (/^http:/i.test(value) && !/^http:\/\/(?:[^@/]*@)?(?:127\.0\.0\.1|localhost|\[::1\])(?::\d+)?(?:\/|$)/i.test(value)) {
196
+ throw new UsageError(`"${redactUrl(value)}" is plain http: the model would cross the network in clear text. Use https:// (http:// is taken only for 127.0.0.1 and localhost)`);
197
+ }
198
+ return value;
199
+ }
200
+
201
+ /** The one question `sumo setup` ever asks, and only when nothing is stored yet and a person is there to answer it. */
202
+ async function askModelSource(defaultSource) {
203
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
204
+ try {
205
+ // A slip at the prompt is asked again, not the end of setup.
206
+ for (;;) {
207
+ // Ctrl-C at the prompt stops setup; Ctrl-D is no answer, so the default. Neither is a stack trace.
208
+ const answer = (
209
+ await rl.question(`Download the router model from [${defaultSource}]: `).catch((cause) => {
210
+ if (cause?.name === 'AbortError') throw new UsageError('setup stopped — nothing was downloaded');
211
+ return '';
212
+ })
213
+ ).trim();
214
+ if (!answer) return defaultSource;
215
+ try {
216
+ return sourceOrRefuse(answer);
217
+ } catch (cause) {
218
+ process.stdout.write(`${cause.message}\n`);
219
+ }
220
+ }
221
+ } finally {
222
+ rl.close();
223
+ }
224
+ }
225
+
226
+ export async function setup({ binDir, link = true, modelSource, noModel = false } = {}) {
227
+ const p = paths();
228
+ for (const dir of [p.home, p.bin, p.logs, p.backups, p.jobs, p.models, p.scratch]) {
229
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
230
+ }
231
+ chmodSync(p.home, 0o700);
232
+
233
+ const db = openDb();
234
+ chmodSync(p.db, 0o600);
235
+ if (!getMeta(db, 'machine')) setMeta(db, 'machine', hostname().replace(/\.local$/, ''));
236
+ // The model or the binary may be about to change; the next local call starts a server for what is current.
237
+ stopLocalServer(db);
238
+ // Pinned for the same reason the launcher pins node: the router runs where PATH cannot be trusted.
239
+ const llama = commandOnPath('llama-server');
240
+ if (llama) setMeta(db, 'llama.path', llama);
241
+
242
+ let source = modelSource === undefined ? undefined : sourceOrRefuse(modelSource);
243
+ if (source === undefined && !noModel && !getMeta(db, 'config.model.source') && process.stdin.isTTY) {
244
+ source = await askModelSource(CONFIG_DEFAULTS['model.source']);
245
+ }
246
+ if (source !== undefined) setMeta(db, 'config.model.source', source);
247
+
248
+ // SUMO_AGENTS_MODEL_CMD marks a hermetic test/dev harness, the same way it tells callModel and
249
+ // callLocalModel never to run a real model — an explicit --model-source still means "go fetch it".
250
+ const harnessSkip = Boolean(process.env.SUMO_AGENTS_MODEL_CMD) && modelSource === undefined;
251
+ let modelLine = null;
252
+ if (!noModel) {
253
+ modelLine = harnessSkip
254
+ ? 'model not downloaded — SUMO_AGENTS_MODEL_CMD is set (unset it, or pass --model-source, to fetch it)'
255
+ : await ensureModel(db, { modelSource: source });
256
+ }
257
+ const modelsLine = await checkModels(db);
258
+ db.close();
259
+
260
+ // Written aside and renamed in, so a hook running the launcher mid-setup never reads half a script.
261
+ const staged = `${p.launcher}.${process.pid}.tmp`;
262
+ writeFileSync(staged, launcherScript(), { mode: 0o755 });
263
+ chmodSync(staged, 0o755);
264
+ renameSync(staged, p.launcher);
265
+
266
+ const lines = [`home ${p.home}`, `database ${p.db}`, `launcher ${p.launcher}`];
267
+ // What was skipped is said too: the next step depends on it.
268
+ lines.push(modelLine ?? `model not fetched (--no-model) — the router needs it: sumo setup`);
269
+ lines.push(modelsLine);
270
+ if (!llama) lines.push('llama-server not found — brew install llama.cpp');
271
+ if (link) {
272
+ const dir = binDir ?? pickBinDir();
273
+ if (dir) {
274
+ const { link: at, status } = linkInto(dir, p.launcher);
275
+ lines.push(`command ${at} (${status})`);
276
+ } else {
277
+ lines.push(`command not linked — add this to your shell profile: export PATH="${p.bin}:$PATH"`);
278
+ }
279
+ } else {
280
+ lines.push(`command not linked (--no-link) — run ${p.launcher}, or put ${p.bin} on PATH`);
281
+ }
282
+ lines.push('next sumo doctor');
283
+ return lines;
284
+ }
285
+
286
+ /**
287
+ * Which of Sumo's models this credential can use, asked of the API the first time only: a later setup
288
+ * leaves the switches as they are, since the user may have set some by hand — `sumo models discover` asks again.
289
+ * Never throws: a check that could not be made is not a reason for `sumo setup` to fail.
290
+ */
291
+ async function checkModels(db) {
292
+ const checked = modelsChecked(db);
293
+ if (checked) return `models checked ${checked.slice(0, 10)} — sumo models discover to check again`;
294
+ const result = await discoverModels(db);
295
+ return result.ok ? `models ${discoverySummary(result)}` : `models not checked — ${result.error}`;
296
+ }
297
+
298
+ function commandOnPath(name) {
299
+ for (const dir of (process.env.PATH ?? '').split(delimiter).filter(Boolean)) {
300
+ const candidate = join(dir, name);
301
+ try {
302
+ // A directory passes the X_OK check too (it means "searchable"), so it is ruled out the way `which` rules it out.
303
+ accessSync(candidate, constants.X_OK);
304
+ if (statSync(candidate).isFile()) return candidate;
305
+ } catch {
306
+ // Not in this directory.
307
+ }
308
+ }
309
+ return null;
310
+ }
311
+
312
+ /** Each check is [ok, label, how to fix]. `warn` checks never fail the run. */
313
+ export async function doctor() {
314
+ const p = paths();
315
+ const checks = [];
316
+ const check = (ok, label, fix, warn = false) => checks.push({ ok, label, fix, warn });
317
+
318
+ // First, so it is still visible when a terminal folds the rest away: "did the update land?" is the
319
+ // question asked most often, and the answer is which commit this copy is running.
320
+ const code = codeVersion();
321
+ check(code !== null, `code ${code ?? 'unknown'}`, 'neither a git checkout nor an installed package — reinstall: npm i -g sumo-agents', true);
322
+
323
+ const [major, minor] = process.versions.node.split('.').map(Number);
324
+ const nodeOk = (major === 22 && minor >= 19) || (major === 24 && minor >= 6) || major > 24;
325
+ // The binary Bun builds carries its own runtime, whatever Node version that says it is.
326
+ if (process.versions.bun) check(true, `bun ${process.versions.bun} (a built binary: no Node needed)`, '');
327
+ else check(nodeOk, `node ${process.versions.node}`, `needs Node ${NODE_REQUIREMENT}`);
328
+
329
+ let db = null;
330
+ // Read here, inside the one guarded open: a database that will not open is a failed check, not the end of the report.
331
+ let stored = { modelFile: null, llama: null, models: null, checked: null, configured: [] };
332
+ try {
333
+ db = openDb();
334
+ const options = db.prepare('PRAGMA compile_options').all().map((r) => Object.values(r)[0]);
335
+ check(options.includes('ENABLE_FTS5'), 'SQLite full-text search (FTS5)', 'this Node build lacks FTS5 — use the official nodejs.org build');
336
+ check(schemaVersion(db) === SCHEMA_VERSION, `schema version ${schemaVersion(db)}`, 'database is from a newer sumo-agents — update this repo');
337
+ const setting = (key) => getMeta(db, `config.${key}`) ?? CONFIG_DEFAULTS[key];
338
+ stored = {
339
+ modelFile: getMeta(db, 'config.model.file'),
340
+ llama: getMeta(db, 'llama.path'),
341
+ models: modelStates(db),
342
+ checked: modelsChecked(db),
343
+ configured: ['chat.model', 'scribe.model', 'dream.model'].map((key) => [key, setting(key)]),
344
+ };
345
+ } catch (cause) {
346
+ check(false, 'database opens', cause.message);
347
+ } finally {
348
+ db?.close();
349
+ }
350
+
351
+ // The models the chat, the router and the passes may use: none on means nothing can run, and a setting naming one that is off runs nothing either.
352
+ if (stored.models) {
353
+ const on = MODELS.filter((name) => stored.models[name].on);
354
+ const off = MODELS.filter((name) => !stored.models[name].on);
355
+ check(on.length > 0, `models on: ${on.join(', ') || 'none'}${off.length > 0 ? `; off: ${off.join(', ')}` : ''}`, 'sumo models enable <name>');
356
+ check(stored.checked !== null, `models checked against the API${stored.checked ? ` (${stored.checked.slice(0, 10)})` : ''}`, 'run: sumo models discover', true);
357
+ for (const [key, value] of stored.configured) {
358
+ if (MODELS.includes(value)) check(stored.models[value].on, `${key} is on (${value})`, `sumo models enable ${value}, or sumo config ${key} <name>`);
359
+ }
360
+ }
361
+
362
+ const mode = (file) => (existsSync(file) ? statSync(file).mode & 0o777 : null);
363
+ check(mode(p.home) === 0o700, 'home directory is private (0700)', 'run: sumo setup');
364
+ check(mode(p.db) === 0o600, 'database is private (0600)', 'run: sumo setup');
365
+
366
+ const launcherOk = existsSync(p.launcher) && readFileSync(p.launcher, 'utf8') === launcherScript();
367
+ check(launcherOk, 'launcher points at this repo and this node', 'run: sumo setup');
368
+ check(launcherOk && launcherRuns(), 'launcher runs the way a hook would call it', 'run: sumo setup');
369
+
370
+ const herdr = commandOnPath('herdr');
371
+ // Optional: without it a job still runs in the chat; only the tab that shows it as it works is not opened.
372
+ check(herdr !== null, 'herdr on PATH (optional: a tab per job, to watch it work)', 'brew install herdr — jobs run without it, unseen until they end; sumo job watch <id> shows one', true);
373
+ // Ours is the launcher, or the shim `npm install -g` makes, which points straight at this copy's entry.
374
+ const found = commandOnPath('sumo');
375
+ const real = found === null ? null : realpathSync(found);
376
+ const ours = real !== null && ((existsSync(p.launcher) && real === realpathSync(p.launcher)) || real === realpathSync(ENTRY));
377
+ check(ours, '`sumo` on PATH is this one', found ? `PATH finds ${found} instead` : 'run: sumo setup');
378
+
379
+ // The chat and every job go to the API; the memory passes run locally and only fall back to it.
380
+ const standInKey = Boolean(process.env.SUMO_AGENTS_MODEL_CMD);
381
+ check(
382
+ standInKey || Boolean(resolveAnthropicCredential()),
383
+ 'ANTHROPIC_API_KEY is set or CLAUDE_CODE_OAUTH_TOKEN is set (chat, jobs, and the passes\' fallback)',
384
+ 'export ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN in the shell that starts sessions and hooks',
385
+ );
386
+ // What every request of each role pays for before its first word: the first number of the ledger, and never a failed check.
387
+ const chatModel = stored.configured.find(([key]) => key === 'chat.model')?.[1];
388
+ checks.push(await promptCheck(MODELS.includes(chatModel) ? chatModel : CONFIG_DEFAULTS['chat.model']));
389
+
390
+ // Not a warning: every job is routed by it, and without an answer no job can be created.
391
+ const standIn = process.env.SUMO_AGENTS_MODEL_CMD;
392
+ if (standIn) {
393
+ check(true, `router stand-in (SUMO_AGENTS_MODEL_CMD=${standIn})`, '');
394
+ } else {
395
+ const model = join(p.models, stored.modelFile ?? CONFIG_DEFAULTS['model.file']);
396
+ check(existsSync(model), `router model (${basename(model)})`, 'run: sumo setup');
397
+
398
+ const llama = stored.llama ?? commandOnPath('llama-server');
399
+ check(llama !== null && existsSync(llama), 'llama-server found (runs the router model)', 'brew install llama.cpp, then: sumo setup');
400
+ }
401
+
402
+ return checks;
403
+ }
404
+
405
+ /** How long doctor waits for a count: it is one request, and a doctor that hangs tells nobody anything. */
406
+ const COUNT_TIMEOUT_MS = 15_000;
407
+
408
+ /**
409
+ * The fixed prompt of each role — its tools and its system prompt, with a one-word turn after them, as the endpoint takes
410
+ * no empty conversation — counted by the API's free count_tokens, every role on the chat's model so the numbers compare.
411
+ * The MCP servers' tools are left out: connecting them is not doctor's to do, and they go deferred, outside the prefix.
412
+ * Without a credential, or on any error, it is a warning that says why nothing was counted.
413
+ */
414
+ async function promptCheck(model) {
415
+ const skipped = (why) => ({ ok: false, warn: true, label: 'prompt: not counted', fix: why });
416
+ const credential = resolveAnthropicCredential();
417
+ if (!credential) return skipped('no Anthropic credential to count with');
418
+ try {
419
+ // Loaded here: the loop and the chat import this module, and only doctor needs them from it.
420
+ const { jobParams, paramsFor } = await import('./loop.mjs');
421
+ const { CHAT_TOOLS, chatSystem } = await import('./chat.mjs');
422
+ const requests = [
423
+ ['chat', paramsFor({ model, tools: CHAT_TOOLS, system: chatSystem(), text: 'hi' })],
424
+ ...['worker', 'scout', 'reviewer'].map((agent) => [agent, jobParams({ job: { agent, model }, text: 'hi' })]),
425
+ ];
426
+ const client = anthropicClient({ timeout: COUNT_TIMEOUT_MS, maxRetries: 0 }, credential);
427
+ // Sent as each role sends it, less what only bounds a reply.
428
+ const counts = await Promise.all(requests.map(([, { max_tokens: _bound, ...params }]) => client.beta.messages.countTokens(authenticatedRequest(params, credential))));
429
+ const said = requests.map(([role], i) => `${role} ${counts[i].input_tokens.toLocaleString('en-US')}`).join(' · ');
430
+ return { ok: true, warn: false, label: `prompt: ${said} tokens on ${model}, without MCP tools`, fix: '' };
431
+ } catch (cause) {
432
+ return skipped(describeApiError(cause));
433
+ }
434
+ }
435
+
436
+ /** A checkout says its commit; an installed package says its version. */
437
+ function codeVersion() {
438
+ try {
439
+ if (existsSync(join(REPO_ROOT, '.git'))) {
440
+ return execFileSync('git', ['-C', REPO_ROOT, 'log', '-1', '--format=%h · %cs · %s'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim() || null;
441
+ }
442
+ return JSON.parse(readFileSync(join(REPO_ROOT, 'package.json'), 'utf8')).version ?? null;
443
+ } catch {
444
+ return null;
445
+ }
446
+ }
447
+
448
+ /** A whole number above zero, as `-n` and `--budget` take it; anything else is refused with `message`. */
449
+ export function positiveInteger(raw, message) {
450
+ const n = Number(raw);
451
+ if (!(Number.isInteger(n) && n > 0)) throw new UsageError(message);
452
+ return n;
453
+ }
454
+
455
+ export function config(key, value) {
456
+ const db = openDb();
457
+ // A model source can carry a token (`https://user:token@host/…`); it is stored whole, for the download, and shown without it.
458
+ const shown = (k) => `${k} = ${redactUrl(getMeta(db, `config.${k}`) ?? CONFIG_DEFAULTS[k])}`;
459
+ try {
460
+ if (key === undefined) {
461
+ return Object.keys(CONFIG_DEFAULTS).map(shown);
462
+ }
463
+ if (!Object.hasOwn(CONFIG_DEFAULTS, key)) {
464
+ throw new UsageError(`unknown setting "${key}" — one of: ${Object.keys(CONFIG_DEFAULTS).join(', ')}`);
465
+ }
466
+ if (value !== undefined) {
467
+ // A budget that is not a number would be no budget at all: every session's block would carry every preference.
468
+ if (key === 'prime.budget') positiveInteger(value, 'prime.budget needs a positive number');
469
+ // A cap that is not a number of dollars would be read as the default without a word; 0 is a choice, no cap at all.
470
+ if (key === 'jobs.budget' && !/^\d+(\.\d+)?$/.test(value)) throw new UsageError('jobs.budget needs a number of dollars, 0 or more: what one job may spend before it is stopped, 0 for no cap');
471
+ // The same for a limit in time: whole minutes, and 0 for none.
472
+ if (key === 'jobs.minutes' && !/^\d+$/.test(value)) throw new UsageError('jobs.minutes needs a whole number of minutes, 0 or more: how long one job may run before it is stopped, 0 for no limit');
473
+ // Zero or a word would let go of every chore at the next session start, or of none ever.
474
+ if (key === 'scratch.days') positiveInteger(value, 'scratch.days needs a positive number: the days a chore nothing is written in is kept');
475
+ // Where a new project is made: a place that is not there, or that moves with the shell's directory, is no answer to "where".
476
+ if (key === 'projects.home') {
477
+ const dir = value.replace(/^~(?=$|\/)/, homedir());
478
+ if (!isAbsolute(dir) || !existsSync(dir) || !statSync(dir).isDirectory()) throw new UsageError(`${value} is not a directory — projects.home is where new projects are made, absolute or under ~`);
479
+ }
480
+ // Sent with every chat turn: a word the API does not take would fail each one, not this command.
481
+ if (key === 'chat.effort' && !CHAT_EFFORTS.includes(value)) throw new UsageError(`no such effort "${value}" — one of: ${CHAT_EFFORTS.join(', ')}`);
482
+ if (key === 'chat.notify' && value !== 'on' && value !== 'off') throw new UsageError('chat.notify is on or off: the bell and the notification when a long turn ends behind another window');
483
+ // A word would be no budget at all, and the line it holds back would never be said.
484
+ if (key === 'chat.budget' && !/^\d+(\.\d+)?$/.test(value)) throw new UsageError('chat.budget is a sum in US dollars, like 5 or 2.50 (0 for never): what a chat session costs before the screen says so, once');
485
+ if (key === 'guides.auto' && value !== 'on' && value !== 'off') throw new UsageError('guides.auto is on or off: a guide riding in with the message that asks for its kind of work, and a turn held for an edit nothing checked');
486
+ if (key === 'jobs.advisor' && value !== 'on' && value !== 'off') throw new UsageError('jobs.advisor is on or off: a job asking the next model up for advice, from inside its own request');
487
+ if (key === 'jobs.escalate' && value !== 'on' && value !== 'off') throw new UsageError('jobs.escalate is on or off: a worker\'s first attempt that fails retried once, one step up, without being asked');
488
+ if (key === 'jobs.review' && !['risky', 'all', 'off'].includes(value)) {
489
+ throw new UsageError('jobs.review is risky, all or off: which workers that finish DONE, verified, are reviewed without being asked — the ones the router called risky, every one, or none');
490
+ }
491
+ if (key === 'shell.sandbox' && value !== 'on' && value !== 'off') throw new UsageError('shell.sandbox is on or off: the model\'s shell writing only in the project, the temporary folders and the tool caches, on macOS');
492
+ if (key === 'shell.network' && value !== 'on' && value !== 'off') throw new UsageError('shell.network is on or off: the sandboxed shell reaching past this machine — off, it reaches only loopback and local sockets');
493
+ // Stored for every later setup: one that is not a URL would fail each of them.
494
+ if (key === 'model.source') sourceOrRefuse(value);
495
+ // The file name decides where the bytes land and what the server is asked for: a name, never a path.
496
+ if (key === 'model.file' && (value !== basename(value) || value === '..' || value === '.' || value === '')) {
497
+ throw new UsageError(`model.file is a file name, with no path separator: sumo config model.file <name>.gguf`);
498
+ }
499
+ // A model is one Sumo knows and one that is on; the passes also take `local` and `off`, the chat `auto`.
500
+ if (key === 'chat.model' && value !== 'auto') {
501
+ knownModel(value, ['auto']);
502
+ assertOn(db, value);
503
+ }
504
+ if ((key === 'scribe.model' || key === 'dream.model') && value !== 'local' && value !== 'off') {
505
+ knownModel(value, ['local', 'off']);
506
+ assertOn(db, value);
507
+ }
508
+ setMeta(db, `config.${key}`, value);
509
+ // Read once a process, so a shell that edits the database cannot switch them off under itself: a chat already open keeps
510
+ // what it read, for the jobs it starts too.
511
+ if (key === 'shell.sandbox' || key === 'shell.network') {
512
+ return [shown(key), 'takes effect in chats and `sumo job run`s started from now on — a chat already open keeps its setting, for the jobs it starts too, until it is started again'];
513
+ }
514
+ }
515
+ return [shown(key)];
516
+ } finally {
517
+ db.close();
518
+ }
519
+ }
520
+
521
+ /** Runs the launcher the way a hook would — bare environment, no PATH help — to prove it works end to end. */
522
+ function launcherRuns() {
523
+ try {
524
+ return execFileSync(paths().launcher, ['help'], { encoding: 'utf8', env: { PATH: '/usr/bin:/bin' } }).startsWith('sumo');
525
+ } catch {
526
+ return false;
527
+ }
528
+ }
package/src/sqlite.mjs ADDED
@@ -0,0 +1,66 @@
1
+ const PREFIXES = [':', '$', '@'];
2
+
3
+ /**
4
+ * The class every sumo database is opened with. Under Node it is node:sqlite's DatabaseSync itself. The binary
5
+ * `npm run build:bin` makes runs on Bun, which has no node:sqlite: there it is bun:sqlite's Database made to answer
6
+ * the calls sumo makes the way DatabaseSync does. Node never loads bun:sqlite, nor Bun node:sqlite.
7
+ */
8
+ export const DatabaseSync = process.versions.bun
9
+ ? bunDatabaseSync((await import('bun:sqlite')).Database)
10
+ : (await import('node:sqlite')).DatabaseSync;
11
+
12
+ /**
13
+ * The values for one statement, as bun:sqlite takes them. node:sqlite binds a named value given bare ({ id }) to
14
+ * :id, $id or @id, and bun:sqlite only one spelled with its prefix; node:sqlite leaves a placeholder it was given no
15
+ * value for NULL, and bun:sqlite refuses the statement.
16
+ */
17
+ export function bunArgs(args, count) {
18
+ const [first] = args;
19
+ if (args.length === 1 && first !== null && typeof first === 'object' && !ArrayBuffer.isView(first)) {
20
+ const named = {};
21
+ for (const [key, value] of Object.entries(first)) {
22
+ for (const name of PREFIXES.includes(key[0]) ? [key] : PREFIXES.map((p) => `${p}${key}`)) named[name] = value;
23
+ }
24
+ return [named];
25
+ }
26
+ return args.length < count ? [...args, ...Array(count - args.length).fill(null)] : args;
27
+ }
28
+
29
+ /** DatabaseSync's surface over bun:sqlite's Database, for what sumo uses: prepare().get/all/run/iterate, exec, close. */
30
+ export function bunDatabaseSync(Database) {
31
+ const statement = (db, stmt) => {
32
+ const bind = (args) => bunArgs(args, stmt.paramsCount);
33
+ return {
34
+ // No row is undefined from node:sqlite, null from bun:sqlite.
35
+ get: (...args) => stmt.get(...bind(args)) ?? undefined,
36
+ all: (...args) => stmt.all(...bind(args)),
37
+ run: (...args) => {
38
+ const { lastInsertRowid } = stmt.run(...bind(args));
39
+ // bun:sqlite counts the rows its triggers wrote too (an index kept in step); node:sqlite, as SQLite's changes(), the statement's own.
40
+ return { changes: db.query('SELECT changes() AS n').get().n, lastInsertRowid };
41
+ },
42
+ iterate: (...args) => stmt.iterate(...bind(args)),
43
+ };
44
+ };
45
+ return class DatabaseSync {
46
+ #db;
47
+
48
+ constructor(path, { readOnly = false } = {}) {
49
+ this.#db = new Database(path, readOnly ? { readonly: true } : { readwrite: true, create: true });
50
+ // node:sqlite turns foreign keys on for every connection it opens; SQLite's own default is off.
51
+ this.#db.exec('PRAGMA foreign_keys = ON');
52
+ }
53
+
54
+ prepare(sql) {
55
+ return statement(this.#db, this.#db.prepare(sql));
56
+ }
57
+
58
+ exec(sql) {
59
+ this.#db.exec(sql);
60
+ }
61
+
62
+ close() {
63
+ this.#db.close();
64
+ }
65
+ };
66
+ }