sumo-agents 0.4.0 → 0.5.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 (52) hide show
  1. package/AGENTS.md +8 -6
  2. package/CHANGELOG.md +155 -0
  3. package/README.md +76 -18
  4. package/bin/sumo.mjs +13 -2
  5. package/guides/feature.md +2 -1
  6. package/guides/memory.md +6 -4
  7. package/guides/projects.md +1 -1
  8. package/guides/review.md +1 -1
  9. package/package.json +5 -4
  10. package/prompts/dream.md +6 -0
  11. package/spinner.txt +25 -1
  12. package/src/apply.mjs +146 -18
  13. package/src/auth.mjs +32 -5
  14. package/src/card.mjs +39 -2
  15. package/src/catalog.mjs +6 -3
  16. package/src/chat.mjs +197 -86
  17. package/src/cli.mjs +359 -135
  18. package/src/cost.mjs +67 -8
  19. package/src/db.mjs +106 -3
  20. package/src/dream.mjs +445 -19
  21. package/src/editor.mjs +3 -2
  22. package/src/export.mjs +105 -7
  23. package/src/guard.mjs +57 -11
  24. package/src/guides.mjs +5 -4
  25. package/src/herdr.mjs +4 -2
  26. package/src/hooks.mjs +31 -18
  27. package/src/jobs.mjs +118 -39
  28. package/src/jobtools.mjs +6 -4
  29. package/src/keeper.mjs +77 -0
  30. package/src/local-server.mjs +9 -16
  31. package/src/lock.mjs +2 -1
  32. package/src/logs.mjs +165 -0
  33. package/src/loop.mjs +121 -44
  34. package/src/mcp.mjs +72 -16
  35. package/src/memory.mjs +142 -15
  36. package/src/model.mjs +41 -21
  37. package/src/paths.mjs +38 -0
  38. package/src/prime.mjs +19 -31
  39. package/src/projects.mjs +76 -12
  40. package/src/redact.mjs +10 -0
  41. package/src/render.mjs +2 -1
  42. package/src/route.mjs +16 -22
  43. package/src/sandbox.mjs +82 -3
  44. package/src/scan.mjs +35 -1
  45. package/src/scribe.mjs +10 -22
  46. package/src/sessions.mjs +46 -11
  47. package/src/setup.mjs +423 -78
  48. package/src/text.mjs +100 -1
  49. package/src/tools.mjs +258 -21
  50. package/src/tty.mjs +205 -78
  51. package/src/ui.mjs +869 -293
  52. package/src/verify.mjs +17 -1
package/src/setup.mjs CHANGED
@@ -1,19 +1,26 @@
1
- import { execFileSync } from 'node:child_process';
1
+ import { execFileSync, spawnSync } from 'node:child_process';
2
2
  import {
3
- accessSync, chmodSync, constants, createWriteStream, existsSync, lstatSync, mkdirSync, readFileSync,
3
+ accessSync, chmodSync, constants, createWriteStream, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync,
4
4
  readlinkSync, realpathSync, renameSync, rmSync, statSync, symlinkSync, unlinkSync, writeFileSync,
5
5
  } from 'node:fs';
6
6
  import { homedir, hostname } from 'node:os';
7
- import { basename, delimiter, isAbsolute, join } from 'node:path';
7
+ import { basename, delimiter, dirname, isAbsolute, join } from 'node:path';
8
8
  import { createInterface } from 'node:readline/promises';
9
9
  import { pipeline } from 'node:stream/promises';
10
10
  import { Readable, Transform } from 'node:stream';
11
- import { anthropicClient, authenticatedRequest, resolveAnthropicCredential } from './auth.mjs';
11
+ import { anthropicClient, authenticatedRequest, FALLBACK_BETA, resolveAnthropicCredential } from './auth.mjs';
12
12
  import { assertOn, describeApiError, discoverModels, discoverySummary, knownModel, MODELS, modelsChecked, modelStates } from './catalog.mjs';
13
13
  import { getMeta, openDb, SCHEMA_VERSION, schemaVersion, setMeta } from './db.mjs';
14
+ import { damaged, restoreHint } from './export.mjs';
14
15
  import { stopLocalServer } from './local-server.mjs';
15
- import { UsageError } from './memory.mjs';
16
- import { COMPILED, ENTRY, paths, REPO_ROOT } from './paths.mjs';
16
+ import { latestCrash, crashFiles, logFiles, tailOf } from './logs.mjs';
17
+ import { memoryHealth, memoryHealthLine, Refusal, UsageError } from './memory.mjs';
18
+ import { COMPILED, ENTRY, homeProblem, paths, REPO_ROOT, VERSION } from './paths.mjs';
19
+ import { redact } from './redact.mjs';
20
+ import { unsandboxable } from './sandbox.mjs';
21
+ import { DatabaseSync } from './sqlite.mjs';
22
+ import { closest } from './text.mjs';
23
+ import { tilde } from './tty.mjs';
17
24
 
18
25
  const NODE_REQUIREMENT = '22.19+ or 24.6+';
19
26
  // route.mjs's EFFORTS, spelled out: importing it would close a cycle (route → model → setup). A test keeps them equal.
@@ -21,28 +28,34 @@ export const CHAT_EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max'];
21
28
 
22
29
  /** The settings `sumo config` accepts, with the value used when none is stored. */
23
30
  export const CONFIG_DEFAULTS = {
24
- 'prime.budget': '800',
25
- 'scribe.model': 'local',
26
- 'dream.model': 'local',
27
- 'chat.model': 'opus',
31
+ 'chat.budget': '5',
28
32
  'chat.effort': 'medium',
33
+ 'chat.model': 'opus',
29
34
  'chat.notify': 'on',
30
- 'chat.motion': 'on',
31
- 'chat.budget': '5',
32
- 'guides.auto': 'on',
35
+ 'chat.screen': 'full',
33
36
  'jobs.advisor': 'off',
34
37
  'jobs.budget': '10',
35
38
  'jobs.floor': 'haiku',
36
- 'jobs.escalate': 'on',
37
- 'jobs.review': 'risky',
38
- 'shell.sandbox': 'on',
39
39
  'jobs.minutes': '60',
40
- 'shell.network': 'on',
40
+ 'jobs.review': 'risky',
41
+ 'memory.model': 'local',
42
+ 'model.url': 'https://huggingface.co/Qwen/Qwen3-4B-GGUF/resolve/main/Qwen3-4B-Q4_K_M.gguf',
41
43
  'projects.home': '~',
42
- 'scratch.days': '14',
43
- 'model.source': 'https://huggingface.co',
44
- 'model.repo': 'Qwen/Qwen3-4B-GGUF',
45
- 'model.file': 'Qwen3-4B-Q4_K_M.gguf',
44
+ 'shell.network': 'on',
45
+ 'shell.sandbox': 'on',
46
+ };
47
+
48
+ /** What a setting that is gone became, said when its old name is used, instead of "unknown setting". */
49
+ const RETIRED = {
50
+ 'chat.motion': 'chat.motion is now chat.screen: sumo config chat.screen still',
51
+ 'chat.plain': 'chat.plain is now chat.screen: sumo config chat.screen plain',
52
+ 'model.source': 'model.source is now part of model.url, the model file\'s whole address: sumo config model.url https://<host>/…/<file>.gguf',
53
+ 'model.repo': 'model.repo is now part of model.url, the model file\'s whole address: sumo config model.url https://<host>/…/<file>.gguf',
54
+ 'model.file': 'model.file is now part of model.url, the model file\'s whole address: sumo config model.url https://<host>/…/<file>.gguf',
55
+ 'prime.budget': 'prime.budget is no longer a setting: the memory block every session starts with holds 800 tokens; the rest is found by search',
56
+ 'scratch.days': 'scratch.days is no longer a setting: a scratch folder nothing is written in for 14 days is deleted',
57
+ 'jobs.escalate': 'jobs.escalate is no longer a setting: a worker\'s first attempt that fails is always retried once, one step up',
58
+ 'guides.auto': 'guides.auto is no longer a setting: a guide always rides in with a message that asks for its kind of work (--guide none on a job for none)',
46
59
  };
47
60
 
48
61
  /**
@@ -86,11 +99,12 @@ function linkInto(binDir, launcher) {
86
99
  // Nothing there yet.
87
100
  }
88
101
  if (existing) {
89
- const ours = existing.isSymbolicLink() && readlinkSync(link) === launcher;
90
- if (ours) return { link, status: 'already linked' };
91
- if (!existing.isSymbolicLink() || !readlinkSync(link).endsWith('/.sumo-agents/bin/sumo')) {
92
- return { link, status: 'skipped — a different `sumo` is already there' };
93
- }
102
+ const target = existing.isSymbolicLink() ? readlinkSync(link) : null;
103
+ if (target === launcher) return { link, status: 'already linked' };
104
+ if (target === null || !target.endsWith('/.sumo-agents/bin/sumo')) return { link, status: 'skipped — a different `sumo` is already there' };
105
+ // Another home's sumo, still there, is someone's main command — a second home set up beside it never takes it over.
106
+ // Only a link to a home that is gone is replaced.
107
+ if (existsSync(link)) return { link, status: `skipped — it runs the sumo in ${dirname(dirname(target))}; to point it here: ln -sf ${launcher} ${link}` };
94
108
  unlinkSync(link);
95
109
  }
96
110
  symlinkSync(launcher, link);
@@ -109,9 +123,32 @@ function formatBytes(n) {
109
123
  return `${value.toFixed(1)} ${units[i]}`;
110
124
  }
111
125
 
112
- /** This layout also works behind a JFrog Artifactory Hugging Face remote, whose base is its huggingfaceml URL. */
113
- function modelUrl({ source, repo, file }) {
114
- return `${source}/${repo}/resolve/main/${file}`;
126
+ /** Where the router model is downloaded from: the file's whole address. */
127
+ const modelUrlOf = (db) => getMeta(db, 'config.model.url') ?? CONFIG_DEFAULTS['model.url'];
128
+
129
+ /**
130
+ * The file the model is kept in under models/: the last part of its address. Not decoded, so an encoded separator
131
+ * (`%2F`) stays part of the name and the file is never anywhere but models/.
132
+ */
133
+ export const modelFileOfUrl = (url = CONFIG_DEFAULTS['model.url']) => new URL(url).pathname.split('/').pop();
134
+ export const modelFileOf = (db) => modelFileOfUrl(modelUrlOf(db));
135
+
136
+ /**
137
+ * The address with another source in front: `--model-source` and setup's question name a host, or a JFrog
138
+ * Artifactory Hugging Face remote's huggingfaceml URL, and the file keeps its path there (`<org>/<repo>/resolve/main/<file>`
139
+ * in Hugging Face's layout, else the file alone). A source that is itself a .gguf address is the whole answer.
140
+ */
141
+ function withSource(url, source) {
142
+ if (/\.gguf$/i.test(new URL(source).pathname)) return source;
143
+ const parts = url.split('/');
144
+ const tail = parts.slice(parts.at(-3) === 'resolve' ? -5 : -1).join('/');
145
+ return `${source.replace(/\/+$/, '')}/${tail}`;
146
+ }
147
+
148
+ /** The source part of an address, what setup's question offers to keep. */
149
+ function sourceOf(url) {
150
+ const parts = url.split('/');
151
+ return parts.slice(0, parts.at(-3) === 'resolve' ? -5 : -1).join('/');
115
152
  }
116
153
 
117
154
  /**
@@ -119,16 +156,9 @@ function modelUrl({ source, repo, file }) {
119
156
  * Streams to `<file>.part` then renames, so a run that dies never leaves a file that looks finished.
120
157
  * Never throws: a model that could not be fetched is not a reason for `sumo setup` to fail.
121
158
  */
122
- async function ensureModel(db, { modelSource } = {}) {
123
- const file = getMeta(db, 'config.model.file') ?? CONFIG_DEFAULTS['model.file'];
124
- const repo = getMeta(db, 'config.model.repo') ?? CONFIG_DEFAULTS['model.repo'];
125
- const source = modelSource ?? getMeta(db, 'config.model.source') ?? CONFIG_DEFAULTS['model.source'];
126
- // The file name decides where the bytes land; a separator in it would let `sumo config` point outside models/.
127
- if (file !== basename(file) || file === '..' || file === '.') {
128
- return `model.file "${file}" is refused — a file name, with no path separator: sumo config model.file <name>`;
129
- }
130
- const dest = join(paths().models, file);
131
- const url = modelUrl({ source, repo, file });
159
+ async function ensureModel(db) {
160
+ const url = modelUrlOf(db);
161
+ const dest = join(paths().models, modelFileOfUrl(url));
132
162
  const shown = redactUrl(url);
133
163
  // Unique per run: two setups at once must not interleave into one file, and a dead run must not leave a
134
164
  // part file that a later run mistakes for progress.
@@ -200,6 +230,19 @@ function sourceOrRefuse(value) {
200
230
  return value;
201
231
  }
202
232
 
233
+ /** A model's address is a web address of a .gguf file: anything else would fail every later setup. */
234
+ function modelUrlOrRefuse(value) {
235
+ sourceOrRefuse(value);
236
+ let path;
237
+ try {
238
+ path = new URL(value).pathname;
239
+ } catch {
240
+ throw new UsageError(`"${redactUrl(value)}" is not a web address — model.url looks like ${CONFIG_DEFAULTS['model.url']}`);
241
+ }
242
+ if (!/\/[^/]+\.gguf$/i.test(path)) throw new UsageError(`model.url is the model file's own address, ending in .gguf — like ${CONFIG_DEFAULTS['model.url']}`);
243
+ return value;
244
+ }
245
+
203
246
  /** The one question `sumo setup` ever asks, and only when nothing is stored yet and a person is there to answer it. */
204
247
  async function askModelSource(defaultSource) {
205
248
  const rl = createInterface({ input: process.stdin, output: process.stdout });
@@ -242,10 +285,10 @@ export async function setup({ binDir, link = true, modelSource, noModel = false
242
285
  if (llama) setMeta(db, 'llama.path', llama);
243
286
 
244
287
  let source = modelSource === undefined ? undefined : sourceOrRefuse(modelSource);
245
- if (source === undefined && !noModel && !getMeta(db, 'config.model.source') && process.stdin.isTTY) {
246
- source = await askModelSource(CONFIG_DEFAULTS['model.source']);
288
+ if (source === undefined && !noModel && !getMeta(db, 'config.model.url') && process.stdin.isTTY) {
289
+ source = await askModelSource(sourceOf(CONFIG_DEFAULTS['model.url']));
247
290
  }
248
- if (source !== undefined) setMeta(db, 'config.model.source', source);
291
+ if (source !== undefined) setMeta(db, 'config.model.url', modelUrlOrRefuse(withSource(modelUrlOf(db), source)));
249
292
 
250
293
  // SUMO_AGENTS_MODEL_CMD marks a hermetic test/dev harness, the same way it tells callModel and
251
294
  // callLocalModel never to run a real model — an explicit --model-source still means "go fetch it".
@@ -254,7 +297,7 @@ export async function setup({ binDir, link = true, modelSource, noModel = false
254
297
  if (!noModel) {
255
298
  modelLine = harnessSkip
256
299
  ? 'model not downloaded — SUMO_AGENTS_MODEL_CMD is set (unset it, or pass --model-source, to fetch it)'
257
- : await ensureModel(db, { modelSource: source });
300
+ : await ensureModel(db);
258
301
  }
259
302
  const modelsLine = await checkModels(db);
260
303
  db.close();
@@ -328,9 +371,16 @@ export async function doctor() {
328
371
  if (process.versions.bun) check(true, `bun ${process.versions.bun} (a built binary: no Node needed)`, '');
329
372
  else check(nodeOk, `node ${process.versions.node}`, `needs Node ${NODE_REQUIREMENT}`);
330
373
 
374
+ // A file where the home should be is the one thing to say: every check after this one reads from the home.
375
+ const notAFolder = homeProblem();
376
+ if (notAFolder) {
377
+ check(false, 'home is a folder', notAFolder);
378
+ return checks;
379
+ }
380
+
331
381
  let db = null;
332
382
  // Read here, inside the one guarded open: a database that will not open is a failed check, not the end of the report.
333
- let stored = { modelFile: null, llama: null, models: null, checked: null, configured: [] };
383
+ let stored = { modelFile: null, llama: null, models: null, checked: null, configured: [], sandbox: CONFIG_DEFAULTS['shell.sandbox'] };
334
384
  try {
335
385
  db = openDb();
336
386
  const options = db.prepare('PRAGMA compile_options').all().map((r) => Object.values(r)[0]);
@@ -338,14 +388,16 @@ export async function doctor() {
338
388
  check(schemaVersion(db) === SCHEMA_VERSION, `schema version ${schemaVersion(db)}`, 'database is from a newer sumo-agents — update this repo');
339
389
  const setting = (key) => getMeta(db, `config.${key}`) ?? CONFIG_DEFAULTS[key];
340
390
  stored = {
341
- modelFile: getMeta(db, 'config.model.file'),
391
+ modelFile: modelFileOf(db),
342
392
  llama: getMeta(db, 'llama.path'),
343
393
  models: modelStates(db),
344
394
  checked: modelsChecked(db),
345
- configured: ['chat.model', 'scribe.model', 'dream.model'].map((key) => [key, setting(key)]),
395
+ configured: ['chat.model', 'memory.model'].map((key) => [key, setting(key)]),
396
+ sandbox: setting('shell.sandbox'),
397
+ memory: memoryHealth(db),
346
398
  };
347
399
  } catch (cause) {
348
- check(false, 'database opens', cause.message);
400
+ check(false, 'database opens', damaged(cause) ? `${cause.message} — ${restoreHint()}` : cause.message);
349
401
  } finally {
350
402
  db?.close();
351
403
  }
@@ -362,8 +414,48 @@ export async function doctor() {
362
414
  }
363
415
 
364
416
  const mode = (file) => (existsSync(file) ? statSync(file).mode & 0o777 : null);
365
- check(mode(p.home) === 0o700, 'home directory is private (0700)', 'run: sumo setup');
366
- check(mode(p.db) === 0o600, 'database is private (0600)', 'run: sumo setup');
417
+ // doctor --fix sets both as they should be; only a home not made yet needs setup.
418
+ const modeFix = (file) => (mode(file) === null ? 'run: sumo setup' : 'run: sumo doctor --fix');
419
+ check(mode(p.home) === 0o700, 'home directory is private (0700)', modeFix(p.home));
420
+ check(mode(p.db) === 0o600, 'database is private (0600)', modeFix(p.db));
421
+ // Everything else the home keeps of the user's — what they typed, the sessions, the logs, the jobs' briefs — is theirs
422
+ // alone too; a file made before a mode was set keeps the mode it was born with until something changes it.
423
+ const loose = loosePlaces();
424
+ const shown = loose.slice(0, LOOSE_SHOWN).map((place) => place.slice(p.home.length + 1)).join(', ');
425
+ check(
426
+ loose.length === 0,
427
+ loose.length === 0 ? "the home's files are private (0600, folders 0700)" : `${loose.length} place${loose.length === 1 ? '' : 's'} in the home others can read: ${shown}${loose.length > LOOSE_SHOWN ? ` and ${loose.length - LOOSE_SHOWN} more` : ''}`,
428
+ 'run: sumo doctor --fix',
429
+ true,
430
+ );
431
+
432
+ // A crash in the last week is said, with where it was written: what it says is the start of a bug report.
433
+ const crash = latestCrash(new Date(Date.now() - CRASH_SHOWN_MS));
434
+ if (crash) check(false, `crash on ${crash.at.toISOString().slice(0, 19).replace('T', ' ')}: ${crash.said}`, `${crash.file}; sumo doctor --report bundles it for a bug report`, true);
435
+
436
+ // Memory, in one line: whether the user is being heard and filed, what waits for them, and scans gone stale.
437
+ if (stored.memory) {
438
+ const said = memoryHealthLine(stored.memory);
439
+ check(said.ok, said.label, said.fix, true);
440
+ }
441
+
442
+ // The shell's sandbox is on by default: where it cannot be, every command writes wherever the user can, and that is said.
443
+ if (stored.sandbox !== 'off') {
444
+ const why = unsandboxable();
445
+ check(why === null, 'shell sandbox (/usr/bin/sandbox-exec)', `${why} — the model's shell can write wherever you can; sumo config shell.sandbox off says you know`, true);
446
+ }
447
+ check(commandOnPath('git') !== null, 'git on PATH', "install git — a job's worktree, its changes and the checks that judge it need it", true);
448
+ // A file that does not read takes every MCP server with it, in the chat and in every job.
449
+ if (existsSync(join(p.home, 'mcp.json'))) {
450
+ const { readConfig } = await import('./mcp.mjs');
451
+ let unread = null;
452
+ try {
453
+ readConfig();
454
+ } catch (cause) {
455
+ unread = cause.message;
456
+ }
457
+ check(unread === null, 'MCP servers file reads (mcp.json)', unread ?? '');
458
+ }
367
459
 
368
460
  const launcherOk = existsSync(p.launcher) && readFileSync(p.launcher, 'utf8') === launcherScript();
369
461
  check(launcherOk, 'launcher points at this repo and this node', 'run: sumo setup');
@@ -371,19 +463,22 @@ export async function doctor() {
371
463
 
372
464
  const herdr = commandOnPath('herdr');
373
465
  // Optional: without it a job still runs in the chat; only the tab that shows it as it works is not opened.
374
- 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);
466
+ // Said within 100 columns: most machines have no herdr, and this is the line they all see.
467
+ check(herdr !== null, 'herdr on PATH (optional: a tab to watch each job)', 'brew install herdr, or sumo job watch <id>', true);
375
468
  // Ours is the launcher, or the shim `npm install -g` makes, which points straight at this copy's entry.
376
469
  const found = commandOnPath('sumo');
377
470
  const real = found === null ? null : realpathSync(found);
378
471
  const ours = real !== null && ((existsSync(p.launcher) && real === realpathSync(p.launcher)) || real === realpathSync(ENTRY));
379
- check(ours, '`sumo` on PATH is this one', found ? `PATH finds ${found} instead` : 'run: sumo setup');
472
+ // This one's folder as the user would type it on their PATH: by the variable that names the home, or under ~.
473
+ const bin = process.env.SUMO_AGENTS_HOME ? '$SUMO_AGENTS_HOME/bin' : tilde(p.bin);
474
+ check(ours, '`sumo` on PATH is this one', found ? `run: sumo setup, or put ${bin} first on PATH` : 'run: sumo setup');
380
475
 
381
476
  // The chat and every job go to the API; the memory passes run locally and only fall back to it.
382
477
  const standInKey = Boolean(process.env.SUMO_AGENTS_MODEL_CMD);
383
478
  check(
384
479
  standInKey || Boolean(resolveAnthropicCredential()),
385
- 'ANTHROPIC_API_KEY is set or CLAUDE_CODE_OAUTH_TOKEN is set (chat, jobs, and the passes\' fallback)',
386
- 'export ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN in the shell that starts sessions and hooks',
480
+ 'an Anthropic credential (chat, jobs)',
481
+ 'export ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN',
387
482
  );
388
483
  // What every request of each role pays for before its first word: the first number of the ledger, and never a failed check.
389
484
  const chatModel = stored.configured.find(([key]) => key === 'chat.model')?.[1];
@@ -392,13 +487,14 @@ export async function doctor() {
392
487
  // Not a warning: every job is routed by it, and without an answer no job can be created.
393
488
  const standIn = process.env.SUMO_AGENTS_MODEL_CMD;
394
489
  if (standIn) {
395
- check(true, `router stand-in (SUMO_AGENTS_MODEL_CMD=${standIn})`, '');
490
+ check(true, `local model stand-in (SUMO_AGENTS_MODEL_CMD=${standIn})`, '');
396
491
  } else {
397
- const model = join(p.models, stored.modelFile ?? CONFIG_DEFAULTS['model.file']);
398
- check(existsSync(model), `router model (${basename(model)})`, 'run: sumo setup');
492
+ // One local model routes every job and runs the memory pass: said as that, not by one of its jobs.
493
+ const model = join(p.models, stored.modelFile ?? modelFileOfUrl());
494
+ check(existsSync(model), `local model (${basename(model)})`, 'run: sumo setup');
399
495
 
400
496
  const llama = stored.llama ?? commandOnPath('llama-server');
401
- check(llama !== null && existsSync(llama), 'llama-server found (runs the router model)', 'brew install llama.cpp, then: sumo setup');
497
+ check(llama !== null && existsSync(llama), 'llama-server found (runs the local model)', 'brew install llama.cpp, then: sumo setup');
402
498
  }
403
499
 
404
500
  return checks;
@@ -427,7 +523,9 @@ async function promptCheck(model) {
427
523
  ];
428
524
  const client = anthropicClient({ timeout: COUNT_TIMEOUT_MS, maxRetries: 0 }, credential);
429
525
  // Sent as each role sends it, less what only bounds a reply.
430
- const counts = await Promise.all(requests.map(([, { max_tokens: _bound, ...params }]) => client.beta.messages.countTokens(authenticatedRequest(params, credential))));
526
+ // A fallback is the Messages endpoint's, not the counter's: left out with its beta.
527
+ const counted = ({ max_tokens: _bound, fallbacks: _fallbacks, ...params }) => ({ ...params, ...(params.betas ? { betas: params.betas.filter((b) => b !== FALLBACK_BETA) } : {}) });
528
+ const counts = await Promise.all(requests.map(([, params]) => client.beta.messages.countTokens(authenticatedRequest(counted(params), credential))));
431
529
  const said = requests.map(([role], i) => `${role} ${counts[i].input_tokens.toLocaleString('en-US')}`).join(' · ');
432
530
  return { ok: true, warn: false, label: `prompt: ${said} tokens on ${model}, without MCP tools`, fix: '' };
433
531
  } catch (cause) {
@@ -436,10 +534,15 @@ async function promptCheck(model) {
436
534
  }
437
535
 
438
536
  /** A checkout says its commit; an installed package says its version. */
537
+ /** The most of `code <hash> · <date> · <subject>` doctor shows: with its six-column mark and the word, inside 100. */
538
+ const CODE_SHOWN = 88;
539
+
439
540
  function codeVersion() {
440
541
  try {
441
542
  if (existsSync(join(REPO_ROOT, '.git'))) {
442
- return execFileSync('git', ['-C', REPO_ROOT, 'log', '-1', '--format=%h · %cs · %s'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim() || null;
543
+ // The subject cut short: a release's can run to a paragraph, and doctor's lines fit a window.
544
+ const said = execFileSync('git', ['-C', REPO_ROOT, 'log', '-1', '--format=%h · %cs · %s'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
545
+ return said ? (said.length > CODE_SHOWN ? `${said.slice(0, CODE_SHOWN - 1).trimEnd()}…` : said) : null;
443
546
  }
444
547
  return JSON.parse(readFileSync(join(REPO_ROOT, 'package.json'), 'utf8')).version ?? null;
445
548
  } catch {
@@ -447,6 +550,155 @@ function codeVersion() {
447
550
  }
448
551
  }
449
552
 
553
+ /** How many of the places others can read doctor names before it says how many more. */
554
+ const LOOSE_SHOWN = 5;
555
+ /** How far back doctor looks for a crash to say. */
556
+ const CRASH_SHOWN_MS = 7 * 24 * 60 * 60 * 1000;
557
+ /** The folders of the home whose every file and folder holds the user's words or settings. */
558
+ const PRIVATE_TREES = ['logs', 'backups', 'scribe'];
559
+
560
+ /**
561
+ * What in the home others can read, by full path: the home and its own files; everything in the logs, the backups and
562
+ * the scribe's folder; the jobs folder, each job's folder and the files directly in it — never deeper, where a job's
563
+ * worktree holds a copy of a project whose files keep their own modes. The models, the launcher's folder and scratch (a
564
+ * project) are not the user's words. Only group and other bits count: what the owner may do is the owner's.
565
+ */
566
+ function loosePlaces(home = paths().home) {
567
+ const found = [];
568
+ // A home that is not a folder, or not there, has nothing in it to make private — and a file there is not sumo's to change.
569
+ try {
570
+ if (!statSync(home).isDirectory()) return found;
571
+ } catch {
572
+ return found;
573
+ }
574
+ const look = (path, deep) => {
575
+ let st;
576
+ try {
577
+ st = lstatSync(path);
578
+ } catch {
579
+ return;
580
+ }
581
+ if (st.isSymbolicLink()) return;
582
+ if (st.mode & 0o077) found.push(path);
583
+ if (!st.isDirectory() || deep === 0) return;
584
+ for (const name of readdirSync(path)) look(join(path, name), deep - 1);
585
+ };
586
+ look(home, 0);
587
+ for (const name of existsSync(home) ? readdirSync(home) : []) {
588
+ const path = join(home, name);
589
+ if (PRIVATE_TREES.includes(name)) look(path, Infinity);
590
+ else if (name === 'jobs') {
591
+ look(path, 0);
592
+ for (const id of existsSync(path) ? readdirSync(path) : []) {
593
+ const job = join(path, id);
594
+ look(job, 0);
595
+ // Its own files only: a folder in it is a worktree, a copy of a project.
596
+ for (const file of lstatSync(job).isDirectory() ? readdirSync(job) : []) if (lstatSync(join(job, file)).isFile()) look(join(job, file), 0);
597
+ }
598
+ } else if (!['models', 'bin', 'scratch'].includes(name)) look(path, 0);
599
+ }
600
+ return found.sort();
601
+ }
602
+
603
+ /** `sumo doctor --fix`: each place others can read made the owner's alone — group and other bits taken off, the owner's kept. Returns what it changed. */
604
+ export function makePrivate(home = paths().home) {
605
+ const fixed = [];
606
+ // The home and the database are the owner's to read and write, as well as no one else's: a home that lost its write
607
+ // bit is one no command can open.
608
+ for (const [place, wanted, folder] of [[home, 0o700, true], [join(home, 'memory.db'), 0o600, false]]) {
609
+ try {
610
+ const st = lstatSync(place);
611
+ if ((folder ? st.isDirectory() : st.isFile()) && (st.mode & 0o777) !== wanted) {
612
+ chmodSync(place, wanted);
613
+ fixed.push(place);
614
+ }
615
+ } catch {
616
+ // Not there, or not ours: doctor says it again.
617
+ }
618
+ }
619
+ for (const place of loosePlaces(home)) {
620
+ try {
621
+ chmodSync(place, statSync(place).mode & 0o700);
622
+ fixed.push(place);
623
+ } catch {
624
+ // Gone, or not ours: doctor says it again.
625
+ }
626
+ }
627
+ return fixed;
628
+ }
629
+
630
+ /**
631
+ * `sumo doctor --report`: what is needed to read a problem, in one text to paste into a bug report — the version and
632
+ * runtime, doctor's lines, the settings, the MCP servers by name only, the last crash and the tail of each log. Every
633
+ * part is redacted, and nothing is sent anywhere: it is printed, for the user to read before they share it.
634
+ */
635
+ /**
636
+ * The logs that hold the user's own words — what the memory pass saved or dropped, what a hook was handed — and their
637
+ * older generations. A report counts them; it never quotes them.
638
+ */
639
+ const WORDS_LOGS = /^(?:scribe|hook)\.log(?:\.\d+)?$/;
640
+ /** The longest a failure line is said: its time, its pass and model, and the start of the error. */
641
+ const FAILURE_SHOWN = 160;
642
+
643
+ /**
644
+ * A words log, counted: for the memory pass's, its passes and failures and the last failure's own line — the line a pass
645
+ * writes about itself, never the "saved" and "dropped" lines under it, which quote what was said; for the hooks', its
646
+ * entries and the first line of the last.
647
+ */
648
+ function countedLog(file, name) {
649
+ let text = '';
650
+ try {
651
+ text = readFileSync(file, 'utf8');
652
+ } catch {
653
+ return '(could not be read)';
654
+ }
655
+ const lines = text.split('\n');
656
+ const cut = (line) => (line.length > FAILURE_SHOWN ? `${line.slice(0, FAILURE_SHOWN - 1)}…` : line);
657
+ if (name.startsWith('scribe')) {
658
+ const passes = lines.filter((l) => /^\S+ (?:scribe|dream)\S* \S+ (?:ok|FAILED) /.test(l));
659
+ const failed = passes.filter((l) => / FAILED /.test(l));
660
+ return `${count(passes.length, 'pass', 'passes')}, ${failed.length} failed${failed.length > 0 ? `; the last failure: ${cut(failed.at(-1))}` : ''}`;
661
+ }
662
+ const entries = lines.filter((l) => /^\d{4}-\d{2}-\d{2}T\S+ /.test(l));
663
+ return entries.length === 0 ? 'no entries' : `${count(entries.length, 'entry', 'entries')}; the last: ${cut(entries.at(-1))}`;
664
+ }
665
+ const count = (n, one, many) => `${n} ${n === 1 ? one : many}`;
666
+
667
+ export async function reportOf(doctorLines, { now = new Date() } = {}) {
668
+ const parts = [
669
+ `# sumo ${VERSION || 'unknown'} report`,
670
+ `node: ${process.versions.bun ? `bun ${process.versions.bun}` : process.version} · ${process.platform} ${process.arch}`,
671
+ `written: ${now.toISOString()} — redacted, and sent nowhere: read it before you share it`,
672
+ "memory text is left out: the memory pass's and the hooks' logs are counted here, not quoted",
673
+ '',
674
+ '## doctor',
675
+ ...doctorLines,
676
+ '',
677
+ '## config',
678
+ ];
679
+ try {
680
+ parts.push(...config());
681
+ } catch (cause) {
682
+ parts.push(`(could not be read: ${cause.message})`);
683
+ }
684
+ parts.push('', '## mcp servers');
685
+ try {
686
+ const { readConfig } = await import('./mcp.mjs');
687
+ const names = Object.keys(readConfig().mcpServers);
688
+ parts.push(...(names.length > 0 ? names : ['(none)']));
689
+ } catch (cause) {
690
+ parts.push(`(could not be read: ${cause.message})`);
691
+ }
692
+ const [crash] = crashFiles();
693
+ parts.push('', crash ? `## last crash: ${basename(crash)}` : '## last crash', crash ? tailOf(crash, 200) : '(none)');
694
+ for (const file of logFiles()) {
695
+ const name = basename(file);
696
+ if (WORDS_LOGS.test(name)) parts.push('', `## logs/${name} — ${countedLog(file, name)}`);
697
+ else parts.push('', `## logs/${name} (last 50 lines)`, tailOf(file, 50) || '(empty)');
698
+ }
699
+ return redact(parts.join('\n')).text;
700
+ }
701
+
450
702
  /** A whole number above zero, as `-n` and `--budget` take it; anything else is refused with `message`. */
451
703
  export function positiveInteger(raw, message) {
452
704
  const n = Number(raw);
@@ -456,24 +708,24 @@ export function positiveInteger(raw, message) {
456
708
 
457
709
  export function config(key, value) {
458
710
  const db = openDb();
459
- // A model source can carry a token (`https://user:token@host/…`); it is stored whole, for the download, and shown without it.
711
+ // A model's address can carry a token (`https://user:token@host/…`); it is stored whole, for the download, and shown without it.
460
712
  const shown = (k) => `${k} = ${redactUrl(getMeta(db, `config.${k}`) ?? CONFIG_DEFAULTS[k])}`;
461
713
  try {
714
+ // By name, so each section's settings stand together: chat.*, jobs.*, memory.*, shell.* …
462
715
  if (key === undefined) {
463
- return Object.keys(CONFIG_DEFAULTS).map(shown);
716
+ return Object.keys(CONFIG_DEFAULTS).sort().map(shown);
464
717
  }
718
+ if (Object.hasOwn(RETIRED, key)) throw new UsageError(RETIRED[key]);
465
719
  if (!Object.hasOwn(CONFIG_DEFAULTS, key)) {
466
- throw new UsageError(`unknown setting "${key}" — one of: ${Object.keys(CONFIG_DEFAULTS).join(', ')}`);
720
+ const near = closest(key, Object.keys(CONFIG_DEFAULTS));
721
+ throw new UsageError(`unknown setting "${key}" — ${near ? `did you mean ${near}? ` : ''}sumo config lists them all`);
467
722
  }
468
723
  if (value !== undefined) {
469
- // A budget that is not a number would be no budget at all: every session's block would carry every preference.
470
- if (key === 'prime.budget') positiveInteger(value, 'prime.budget needs a positive number');
471
724
  // 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.
472
725
  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');
473
726
  // The same for a limit in time: whole minutes, and 0 for none.
474
727
  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');
475
- // Zero or a word would let go of every chore at the next session start, or of none ever.
476
- if (key === 'scratch.days') positiveInteger(value, 'scratch.days needs a positive number: the days a chore nothing is written in is kept');
728
+
477
729
  // 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".
478
730
  if (key === 'projects.home') {
479
731
  const dir = value.replace(/^~(?=$|\/)/, homedir());
@@ -482,30 +734,28 @@ export function config(key, value) {
482
734
  // Sent with every chat turn: a word the API does not take would fail each one, not this command.
483
735
  if (key === 'chat.effort' && !CHAT_EFFORTS.includes(value)) throw new UsageError(`no such effort "${value}" — one of: ${CHAT_EFFORTS.join(', ')}`);
484
736
  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');
485
- if (key === 'chat.motion' && value !== 'on' && value !== 'off') throw new UsageError('chat.motion is on or off: the colours flowing through the working line — off, it stands still');
737
+ if (key === 'chat.screen' && !['full', 'still', 'plain'].includes(value)) {
738
+ throw new UsageError('chat.screen is full, still or plain: a spinner turning on the working line, the same standing still, or drawn for a screen reader — plain marks, no frames, nothing moving');
739
+ }
486
740
  // A word would be no budget at all, and the line it holds back would never be said.
487
741
  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');
488
- 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');
742
+
489
743
  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');
490
- 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');
744
+
491
745
  if (key === 'jobs.floor' && !['haiku', 'sonnet', 'opus', 'fable'].includes(value)) throw new UsageError('jobs.floor is haiku, sonnet, opus or fable: the smallest model a job may run on — haiku holds nothing back');
492
746
  if (key === 'jobs.review' && !['risky', 'all', 'off'].includes(value)) {
493
747
  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');
494
748
  }
495
749
  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');
496
750
  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');
497
- // Stored for every later setup: one that is not a URL would fail each of them.
498
- if (key === 'model.source') sourceOrRefuse(value);
499
- // The file name decides where the bytes land and what the server is asked for: a name, never a path.
500
- if (key === 'model.file' && (value !== basename(value) || value === '..' || value === '.' || value === '')) {
501
- throw new UsageError(`model.file is a file name, with no path separator: sumo config model.file <name>.gguf`);
502
- }
503
- // A model is one Sumo knows and one that is on; the passes also take `local` and `off`, the chat `auto`.
751
+ // Stored for every later setup: one that is not the address of a .gguf file would fail each of them.
752
+ if (key === 'model.url') modelUrlOrRefuse(value);
753
+ // A model is one Sumo knows and one that is on; the memory pass also takes `local` and `off`, the chat `auto`.
504
754
  if (key === 'chat.model' && value !== 'auto') {
505
755
  knownModel(value, ['auto']);
506
756
  assertOn(db, value);
507
757
  }
508
- if ((key === 'scribe.model' || key === 'dream.model') && value !== 'local' && value !== 'off') {
758
+ if (key === 'memory.model' && value !== 'local' && value !== 'off') {
509
759
  knownModel(value, ['local', 'off']);
510
760
  assertOn(db, value);
511
761
  }
@@ -513,7 +763,8 @@ export function config(key, value) {
513
763
  // Read once a process, so a shell that edits the database cannot switch them off under itself: a chat already open keeps
514
764
  // what it read, for the jobs it starts too.
515
765
  if (key === 'shell.sandbox' || key === 'shell.network') {
516
- 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'];
766
+ const warning = key === 'shell.sandbox' && value === 'off' ? ["warning: the model's shell is no longer held to the project — its commands can write anywhere you can"] : [];
767
+ return [shown(key), ...warning, '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'];
517
768
  }
518
769
  }
519
770
  return [shown(key)];
@@ -530,3 +781,97 @@ function launcherRuns() {
530
781
  return false;
531
782
  }
532
783
  }
784
+
785
+ /** What sumo makes in its home, by name: an uninstall removes these and leaves anything else where it is. */
786
+ const MADE_HERE = new Set(['memory.db', 'memory.db-wal', 'memory.db-shm', 'backups', 'bin', 'logs', 'jobs', 'models', 'scratch', 'history', 'mcp.json', 'scribe', 'sumo.db']);
787
+ const madeHere = (name) => MADE_HERE.has(name) || /^memory\.db\.(?:pre-v\d+\.bak|damaged-|replaced-)/.test(name);
788
+
789
+ /** The local model's servers for this home: every llama-server whose command line names its models folder. */
790
+ function serversFor(home) {
791
+ const models = join(home, 'models');
792
+ const listed = spawnSync('ps', ['-axo', 'pid=,command='], { encoding: 'utf8' }).stdout ?? '';
793
+ return listed
794
+ .split('\n')
795
+ .map((line) => /^\s*(\d+)\s+(.*)$/.exec(line))
796
+ .filter((m) => m && Number(m[1]) !== process.pid && m[2].includes('llama-server') && m[2].includes(models))
797
+ .map((m) => Number(m[1]));
798
+ }
799
+
800
+ /**
801
+ * What `sumo uninstall` would remove, looked at and nothing touched: this home's own files, the `sumo` links on the
802
+ * PATH that run it, and the local model's servers. A home that is the user's home folder, or above it, is refused —
803
+ * SUMO_AGENTS_HOME can name any folder, and an uninstall removes only one of sumo's own.
804
+ */
805
+ export function uninstallPlan() {
806
+ const { home, launcher } = paths();
807
+ const own = homedir();
808
+ if (home === '/' || home === own || own.startsWith(`${home}/`)) throw new Refusal(`${home} is your home folder, or above it — sumo uninstall removes only a folder of its own`);
809
+ if (!existsSync(home)) throw new Refusal(`nothing to remove: ${home} is not there`);
810
+ const entries = readdirSync(home);
811
+ if (!entries.some(madeHere)) throw new Refusal(`nothing of sumo's is in ${home} — sumo uninstall removes only a folder of its own`);
812
+ const links = [...new Set((process.env.PATH ?? '').split(delimiter).filter(Boolean))]
813
+ .map((dir) => join(dir, 'sumo'))
814
+ .filter((link) => {
815
+ try {
816
+ return lstatSync(link).isSymbolicLink() && readlinkSync(link) === launcher;
817
+ } catch {
818
+ return false;
819
+ }
820
+ });
821
+ return { home, links, servers: serversFor(home), removed: entries.filter(madeHere), kept: entries.filter((name) => !madeHere(name)) };
822
+ }
823
+
824
+ /** The plan as it is put to the user before anything is removed. */
825
+ export function uninstallQuestion(plan, { keepMemory }) {
826
+ return [
827
+ 'sumo uninstall removes:',
828
+ ` from ${plan.home}: ${plan.removed.join(', ')}${plan.removed.includes('scratch') ? ' — scratch holds work that belonged to no project' : ''}`,
829
+ ...plan.links.map((link) => ` the sumo link at ${link}`),
830
+ ...(plan.servers.length > 0 ? [" the local model's server"] : []),
831
+ ...(plan.kept.length > 0 ? [`and leaves, as not sumo's: ${plan.kept.join(', ')}`] : []),
832
+ keepMemory ? `Your memory is copied first, beside it, to ${dirname(plan.home)}.` : 'Your memory is not kept (--discard-memory).',
833
+ 'Type uninstall to go on: ',
834
+ ].join('\n');
835
+ }
836
+
837
+ /**
838
+ * Carries the plan out, a line said for each step: the memory copied out first unless it is not to be kept — a copy that
839
+ * cannot be made stops everything here — then the servers, the links and what sumo made in the home.
840
+ */
841
+ export function uninstall(plan, { keepMemory = true, now = new Date() } = {}) {
842
+ const lines = [];
843
+ const db = join(plan.home, 'memory.db');
844
+ if (keepMemory && existsSync(db)) {
845
+ const copy = join(dirname(plan.home), `sumo-memory-${now.toISOString().slice(0, 19).replace(/[:T]/g, '-')}.db`);
846
+ try {
847
+ const live = new DatabaseSync(db, { readOnly: true });
848
+ try {
849
+ live.prepare('VACUUM INTO ?').run(copy);
850
+ } finally {
851
+ live.close();
852
+ }
853
+ chmodSync(copy, 0o600);
854
+ } catch (cause) {
855
+ throw new Error(`the memory could not be copied out (${cause.message}) — nothing was removed. sumo uninstall --discard-memory removes it all the same`);
856
+ }
857
+ lines.push(`kept your memory: ${copy} — after a reinstall, sumo backup restore ${copy} --yes puts it back`);
858
+ }
859
+ for (const pid of plan.servers) {
860
+ try {
861
+ process.kill(pid, 'SIGTERM');
862
+ } catch {
863
+ // Gone between the look and the signal.
864
+ }
865
+ }
866
+ if (plan.servers.length > 0) lines.push("stopped the local model's server");
867
+ for (const link of plan.links) {
868
+ rmSync(link, { force: true });
869
+ lines.push(`removed the sumo link at ${link}`);
870
+ }
871
+ // Looked at again: copying the memory out opened it, and its -wal and -shm are back.
872
+ for (const name of readdirSync(plan.home).filter(madeHere)) rmSync(join(plan.home, name), { recursive: true, force: true });
873
+ if (plan.kept.length === 0) rmSync(plan.home, { recursive: true, force: true });
874
+ lines.push(`removed what sumo made in ${plan.home}${plan.kept.length > 0 ? ` — left in place, not sumo's: ${plan.kept.join(', ')}` : ''}`);
875
+ lines.push("last: npm uninstall -g sumo-agents (or delete the clone you built it from), and take out any `sumo hook` lines you added to a harness's hooks");
876
+ return lines;
877
+ }