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/cli.mjs CHANGED
@@ -5,55 +5,53 @@ import { applyOps } from './apply.mjs';
5
5
  import { card } from './card.mjs';
6
6
  import { discoverModels, knownModel, MODEL_IDS, modelLines, setModel } from './catalog.mjs';
7
7
  import { openDb } from './db.mjs';
8
- import { dreamStatus, runDream } from './dream.mjs';
9
- import { backup, exportJson, exportMarkdown, purgeFromBackups } from './export.mjs';
8
+ import { backup, damaged, exportJson, exportMarkdown, liveDatabase, purgeFromBackups, restoreCandidate, restoreHint, restoreLines, restoreQuestion } from './export.mjs';
10
9
  import { resolveAnthropicCredential } from './auth.mjs';
11
- import { chat, jobPrinter } from './chat.mjs';
12
10
  import { costLines } from './cost.mjs';
13
- import { closeJobTab, reportAgent, runHerdr } from './herdr.mjs';
14
11
  import { runHook } from './hooks.mjs';
15
- import { runJob as runJobLoop, runLines } from './loop.mjs';
16
- import { addServer, allowedBy, closeMcp, connect, mcpLines, mcpReady, readConfig, removeServer, setAllow } from './mcp.mjs';
17
12
  import * as jobs from './jobs.mjs';
18
13
  import * as memory from './memory.mjs';
19
- import { UsageError } from './memory.mjs';
20
- import { openInBrowser, servePage } from './page.mjs';
14
+ import { NeedsCredential, Refusal, UsageError } from './memory.mjs';
21
15
  import { prime } from './prime.mjs';
22
16
  import * as projects from './projects.mjs';
23
17
  import { detail, historyLine, line, scopeLabel } from './render.mjs';
24
- import { buildBundle, modelStats, outcomeLines, runScribe, scribeStatus } from './scribe.mjs';
18
+ import { memoryStatus, passLines as memoryPassLines, runMemoryPass } from './keeper.mjs';
19
+ import { buildBundle, outcomeLines } from './scribe.mjs';
25
20
  import { findSaved, searchTurns, taskEndedNudge } from './sessions.mjs';
26
- import { overlap } from './text.mjs';
27
- import { CHAT_EFFORTS, config, doctor, positiveInteger, setup } from './setup.mjs';
21
+ import { closest, saysAs } from './text.mjs';
22
+ import { heldBy } from './lock.mjs';
23
+ import { redact } from './redact.mjs';
24
+ import { VERSION } from './paths.mjs';
25
+ import { CHAT_EFFORTS, config, doctor, makePrivate, positiveInteger, reportOf, setup, uninstall, uninstallPlan, uninstallQuestion } from './setup.mjs';
28
26
  import { colourEnabled, safeForTerminal, styles } from './tty.mjs';
29
27
  import { ftsQuery } from './text.mjs';
30
28
  import { verdictLines } from './verify.mjs';
31
29
 
32
- const HELP = `sumo — local memory for the sumo-agents process
33
-
34
- sumo chat [--model M] [--effort E] [--resume [id]] talk: the chat, with this memory behind it
35
- sumo search <query> [--project S] [--type T] [--everywhere] [--all] [--turns] [--since <YYYY-MM-DD|Nd>] [--before <YYYY-MM-DD>] [-n N]
36
- sumo add <type> "<text>" [--project S] [--topic T] [--pin] [--supersedes ID] [--observed]
37
- types: preference · fact · decision · gotcha
38
- sumo learn "<title>" --cue "<action>" [--gate '<regex>'] [--project S] workflow steps on stdin
39
- sumo show <id> sumo history <id> sumo gate <workflow-id> '<regex>'|off
40
- sumo supersede <old-id> <new-id>
41
- sumo forget <id> [--purge]
42
- sumo confirm <id> sumo reject <id>
43
- sumo memory the memory as a page in the browser: say yes or no, edit, forget
44
- sumo project add <path> [--slug S] [--alias A]... show S · list · rescan S · alias S A · archive S
45
- sumo job new --project S --title T [--agent scout|worker|reviewer]
46
- brief ID · run ID · watch ID · note ID · ask ID · answer ID · tell ID · baseline ID · verify ID · changes ID
47
- finish ID --status DONE|FAILED · show ID · list [--all] · abandon ID · retry ID · stats
48
- sumo prime the block a session starts with
49
- sumo scribe run|show|status|stats sumo dream run|status the cheap-model passes
50
- sumo export [--json] sumo backup sumo cost [--days N] [--project S] where the money went
51
- sumo models [discover | enable <name> | disable <name>] the API models: which are here, which are on
52
- sumo mcp [add <name> -- <command> [args…] | add <name> --url U | remove N | tools N | allow N <tool>|all | revoke N <tool>|all]
53
- MCP servers: their tools reach the chat and every job; a tool not allowed asks first
54
- sumo setup sumo doctor sumo config [key [value]]
30
+ const DOCS = 'https://github.com/sumododda/sumo-agents/wiki';
31
+ const ISSUES = 'https://github.com/sumododda/sumo-agents/issues';
32
+
33
+ const HELP = `sumo — one chat across your projects, memory that lasts, and jobs checked before they say done
34
+
35
+ sumo chat [--model M] [--effort E] [--resume [id]] talk, with this memory behind it
36
+ sumo search <query> [--project S] [--type T] [-n N] what is remembered; --turns: what was said
37
+ sumo add <type> "<text>" [--project S] a preference · fact · decision · gotcha
38
+ sumo learn "<title>" --cue "<action>" a workflow, its steps on stdin · sumo gate
39
+ sumo show|history|confirm|reject|forget <id> sumo supersede <old> <new>
40
+ sumo memory [run [--tidy] | status | show] the page · the pass that files and tidies
41
+ sumo project add <path> [--slug S] [--alias A]... show · list · rescan · alias · archive
42
+ sumo job new --project S --title T [--agent A] a job, its task on stdin
43
+ by id: run · watch · tell · note · ask · answer · show · brief · baseline · verify · changes
44
+ finish <id> --status DONE|FAILED · abandon · retry · list [--all] · stats
45
+ sumo prime · sumo --version the block a session starts with · which sumo
46
+ sumo export [--json] · sumo backup [restore [file]] · sumo cost [--days N] [--project S]
47
+ sumo models [discover | enable <name> | disable <name>] the API models: which are here and on
48
+ sumo mcp [add | remove | tools | allow | revoke] <name> MCP servers, for the chat and every job
49
+ sumo setup · sumo uninstall · sumo config [key [value]] · sumo doctor [--fix] [--report]
55
50
 
56
51
  Scope is global plus --project; other projects stay hidden without --everywhere.
52
+ Exit: 0 done · 1 not done or failed · 2 the command line was wrong · 4 needs an Anthropic credential
53
+ Every option: sumo help <command> · the docs: ${DOCS}
54
+ A bug: sumo doctor --report, redacted, to ${ISSUES}
57
55
  `;
58
56
 
59
57
  const LEARN_USAGE = `sumo learn "<short title>" --cue "<the action, in plain words: create a PR>" [--gate '<regex>'] [--project S] <<'EOF'
@@ -71,21 +69,29 @@ EOF
71
69
  */
72
70
  const USAGE = {
73
71
  chat: 'sumo chat [--model auto|<model>] [--effort <effort>] [--resume [id]] (piped: plain lines, the memory block first; --resume picks a saved session up, the newest without an id)',
74
- search: 'sumo search <query> [--project S] [--type T] [--everywhere] [--all] [--turns] [--since <YYYY-MM-DD|Nd>] [--before <YYYY-MM-DD>] [-n N] (--since: said or changed since that day, or in the last N days; --before: said before that day)',
72
+ search: `sumo search <query> [--project S] [--type T] [--since <YYYY-MM-DD|Nd>] [--before <YYYY-MM-DD>]
73
+ --project S that project's memories beside the global ones; other projects stay hidden
74
+ --everywhere every project's memories
75
+ --type T preference, fact, decision, gotcha or workflow
76
+ --all forgotten and replaced memories too
77
+ --since said or changed since that day, or in the last N days (7d); --before: said before that day
78
+ -n N at most N, the best first (8 unless said)
79
+ --json one object for a script: {memories, more, elsewhere} (with --turns: {turns})
80
+ --turns what the user typed, not what is remembered`,
75
81
  add: `sumo add preference|fact|decision|gotcha "<one sentence>" [--project S] [--topic T] [--pin] [--supersedes ID] [--observed]
76
82
  a workflow (steps to repeat) is saved with sumo learn instead:
77
83
  ${LEARN_USAGE}`,
78
84
  learn: LEARN_USAGE,
79
- show: 'sumo show <id>',
85
+ show: 'sumo show <id> [--json]',
80
86
  history: 'sumo history <id>',
81
87
  supersede: 'sumo supersede <old-id> <new-id>',
82
88
  gate: "sumo gate <workflow-id> '<regex over the shell command>' | sumo gate <workflow-id> off",
83
- forget: 'sumo forget <id> [--purge]',
89
+ forget: 'sumo forget <id> [--purge [--yes]] (--purge erases it for good, from every backup; it asks first, or --yes)',
84
90
  confirm: 'sumo confirm <id>',
85
91
  reject: 'sumo reject <id>',
86
- memory: 'sumo memory (serves the page on this machine and opens it; Ctrl-C stops it)',
92
+ memory: 'sumo memory [run [--tidy] | status | show] (no argument serves the page on this machine and opens it; Ctrl-C stops it)',
87
93
  project: `sumo project add <path> [--slug S] [--alias A]...
88
- sumo project show <name> | list [--all] | rescan <name> | alias <name> <alias> | archive <name> (add it again to bring it back)`,
94
+ sumo project show <name> | list [--all] [--json] | rescan <name> | alias <name> <alias> | archive <name> (add it again to bring it back)`,
89
95
  job: `sumo job new --project S --title T [--agent scout|worker|reviewer] (task on stdin)
90
96
  [--guide fix|feature|review|none] carry guides/<name>.md into the brief (unsaid: what the title and goal ask for)
91
97
  [--reviews <id>] reviewer: judge that job's change (default: what is uncommitted)
@@ -93,7 +99,7 @@ sumo project show <name> | list [--all] | rescan <name> | alias <name> <alias> |
93
99
  [--attempts 2|3] worker: that many attempts, each in a worktree of its own; the best verified one is kept
94
100
  sumo job brief|show|abandon <id>
95
101
  sumo job run <id> runs the job here, in Sumo's own loop, on its route; it closes itself as its brief says
96
- then, unasked: a first attempt that failed is retried one step up (jobs.escalate), risky work done is reviewed (jobs.review)
102
+ then, unasked: a first attempt that failed is retried one step up, risky work done is reviewed (jobs.review)
97
103
  sumo job watch <id> what a job running in the chat is doing, as it does it (a Herdr tab shows this)
98
104
  sumo job note|ask|answer|tell <id> (text on stdin; tell: a message a running job reads next)
99
105
  sumo job baseline <id> the project's checks, before the work
@@ -102,14 +108,12 @@ sumo job changes <id> everything the job changed, as one file
102
108
  sumo job finish <id> --status DONE|FAILED [--accept "<why>"] (report on stdin)
103
109
  sumo job retry <id> a failed job, or a done one reviewed with important >= 3, routed afresh
104
110
  sumo job stats [--project S] jobs, done, failed, reviewed, avg important, and what a job took — per role and model/effort
105
- sumo job list [--all]`,
111
+ sumo job list [--all] [--json]`,
106
112
  prime: 'sumo prime [--budget N]',
107
- scribe: 'sumo scribe run|show|status|stats',
108
113
  cost: 'sumo cost [--days N] [--project S] what the requests cost, by kind and model: fresh input, cache reads, cache writes and output; then the cache rewrites — context written again while the cache should still have held it',
109
- dream: 'sumo dream run|status',
110
114
  apply: 'sumo apply <ops.json> [--source scribe|dream]',
111
115
  export: 'sumo export [--json]',
112
- backup: 'sumo backup',
116
+ backup: 'sumo backup [restore [file] [--yes]] (restore: the newest copy, or the one named, put back, the one there kept aside; over a database that is fine it asks first, or --yes)',
113
117
  models: `sumo models every model Sumo knows: on or off, its API id, and why
114
118
  sumo models discover ask the API which of them this credential can use, and set the switches from the answer (one turned off by hand stays off)
115
119
  sumo models enable|disable <name>`,
@@ -117,14 +121,39 @@ sumo models enable|disable <name>`,
117
121
  sumo mcp add <name> [--env K=V]... -- <command> [args...] a server run as a process (stdio)
118
122
  sumo mcp add <name> --url <url> [--header K=V]... a server reached over HTTP
119
123
  \${NAME} in a value is filled from the shell when the server starts: the file never holds a token
124
+ sumo mcp add <name> --url <url> --from-claude a server Claude Code is logged in to (claude mcp login <name>): its token is borrowed
120
125
  sumo mcp remove <name>
121
126
  sumo mcp tools <name> the server's tools, one a line
122
127
  sumo mcp allow <name> <tool>|all let it run without asking sumo mcp revoke <name> <tool>|all`,
123
128
  setup: 'sumo setup [--bin-dir DIR] [--no-link] [--model-source URL] [--no-model]',
124
- doctor: 'sumo doctor',
129
+ uninstall: 'sumo uninstall [--yes] [--discard-memory] (removes what setup made — the home\'s own files, its sumo links, the local model\'s server — after copying the memory out beside the home; asks first, or --yes)',
130
+ doctor: 'sumo doctor [--fix] [--report] (--fix: make the files of the home private · --report: version, checks, settings, MCP server names, the last crash and the logs\' tails — redacted, printed here, sent nowhere)',
125
131
  config: 'sumo config [key [value]]',
132
+ hook: 'sumo hook session-start|prompt|pre-tool|stop|session-end (for a harness\'s hook configuration: the event\'s JSON on stdin, what to add to the session on stdout; never fails the session)',
126
133
  };
127
134
 
135
+ /** A usage text as `--help` prints it: a line too wide for the terminal (100 columns at most, or piped) goes on, indented, below. */
136
+ function wrapped(text, width = Math.min(process.stdout.columns || 100, 100)) {
137
+ return text
138
+ .split('\n')
139
+ .flatMap((line) => {
140
+ if (line.length <= width) return [line];
141
+ const lead = line.match(/^ */)[0];
142
+ const indent = `${lead} `;
143
+ const lines = [];
144
+ let current = lead;
145
+ for (const word of line.trimStart().split(/ +/)) {
146
+ const joined = current.trim() === '' ? `${current}${word}` : `${current} ${word}`;
147
+ if (joined.length > width && current.trim() !== '') {
148
+ lines.push(current);
149
+ current = `${indent}${word}`;
150
+ } else current = joined;
151
+ }
152
+ return [...lines, current];
153
+ })
154
+ .join('\n');
155
+ }
156
+
128
157
  const ADDABLE = ['preference', 'fact', 'decision', 'gotcha'];
129
158
 
130
159
  /**
@@ -134,82 +163,118 @@ const ADDABLE = ['preference', 'fact', 'decision', 'gotcha'];
134
163
  */
135
164
  const fromTool = () => Boolean(process.env.SUMO_TOOL || process.env.SUMO_JOB);
136
165
  const fromJob = () => process.env.SUMO_JOB || null;
166
+ /** Typed by the user at a terminal: no model's shell, and a terminal at both ends — another harness's tool runs without one. */
167
+ const byUser = () => (!fromTool() && process.stdin.isTTY && process.stdout.isTTY ? 'user' : undefined);
137
168
  const OWNER_ONLY = "Refused: the model's shell does not change what the user controls — the MCP allow list, the models and the configuration. If the user wants it, they run it themselves: `! sumo …`";
138
169
  const jobWrites = () => `Refused: j${fromJob()} runs this command, and a job never writes memory. Put what you learned in your report; the user, or the chat, decides what is kept.`;
139
- /** The scribe's bar for "the user said this": the memory shares this much of its words with a turn the user typed. */
140
- const SAID_BY_USER = 0.34;
141
170
  const RECENT_TURNS = 40;
142
- /** Whether something the user typed lately says what the memory says, so a memory the model files as the user's is really theirs. */
171
+ /**
172
+ * Whether something the user typed lately says what the memory says — nearly all of its words, the same way round — so
173
+ * a memory the model files as the user's is really theirs. A few of the user's words inside much they never said, or
174
+ * their rule turned round, is not.
175
+ */
143
176
  function saidByUser(db, text) {
144
177
  return db
145
178
  .prepare('SELECT text FROM user_turns ORDER BY id DESC LIMIT ?')
146
179
  .all(RECENT_TURNS)
147
- .some((turn) => overlap(text, turn.text) >= SAID_BY_USER);
180
+ .some((turn) => saysAs(text, turn.text));
148
181
  }
149
182
  const HELD = (id) => `held as unconfirmed: nothing the user typed lately says this, so it is theirs to confirm — sumo confirm m${id}, or sumo reject m${id}`;
150
183
  /** The docs say "workflow", the store says "procedure"; whoever types either means the same thing. */
151
184
  const WORKFLOW_NAMES = ['workflow', 'procedure'];
152
185
 
153
- /** value: flags that take an argument; bool: flags that don't. Anything else is a typo and says so. */
186
+ /** value: flags that take an argument; bool: flags that don't; max: the most words it takes. Anything else is a typo and says so. */
154
187
  const COMMANDS = {
155
- search: { value: ['project', 'type', 'n', 'since', 'before'], bool: ['everywhere', 'all', 'turns'], run: runSearch },
188
+ search: { value: ['project', 'type', 'n', 'since', 'before'], bool: ['everywhere', 'all', 'turns', 'json'], run: runSearch },
156
189
  add: { value: ['project', 'topic', 'supersedes'], bool: ['pin', 'observed'], run: runAdd },
157
190
  learn: { value: ['project', 'cue', 'gate', 'from-file'], bool: [], run: runLearn },
158
191
  gate: { value: [], bool: [], run: runGate },
159
- show: { value: [], bool: [], run: (db, { args }) => [detail(memory.get(db, memory.parseId(args[0])))] },
160
- history: { value: [], bool: [], run: (db, { args }) => memory.history(db, memory.parseId(args[0])).map(historyLine) },
161
- supersede: { value: [], bool: [], run: runSupersede },
162
- forget: { value: [], bool: ['purge'], run: runForget },
163
- confirm: { value: [], bool: [], run: (db, { args }) => [`confirmed ${line(memory.confirm(db, memory.parseId(args[0])))}`] },
164
- reject: { value: [], bool: [], run: (db, { args }) => [`rejected ${line(memory.reject(db, memory.parseId(args[0])))}`] },
165
- memory: { value: [], bool: [], run: runMemoryPage },
166
- project: { value: ['slug'], multi: ['alias'], bool: ['all'], run: runProject },
167
- job: { value: ['project', 'title', 'agent', 'status', 'from-file', 'guide', 'reviews', 'accept', 'attempts'], bool: ['all', 'tests-may-change'], run: runJob },
168
- prime: { value: ['budget'], bool: [], run: (db, { flags }) => [prime(db, { budget: flags.budget === undefined ? undefined : positiveInteger(flags.budget, '--budget needs a positive number') })] },
169
- scribe: { value: [], bool: [], run: runScribeCommand },
170
- cost: { value: ['days', 'project'], bool: [], run: (db, { flags }) => costLines(db, { days: flags.days === undefined ? undefined : positiveInteger(flags.days, '--days needs a positive number'), project: flags.project }) },
171
- dream: { value: [], bool: [], run: runDreamCommand },
172
- apply: { value: ['source'], bool: [], run: runApply },
173
- export: { value: [], bool: ['json', 'md'], run: runExport },
174
- backup: { value: [], bool: [], run: runBackup },
192
+ show: { value: [], bool: ['json'], max: 1, run: (db, { args, flags }) => (flags.json ? asJson({ memory: memory.get(db, memory.parseId(args[0])) }) : [detail(memory.get(db, memory.parseId(args[0])))]) },
193
+ history: { value: [], bool: [], max: 1, run: (db, { args }) => memory.history(db, memory.parseId(args[0])).map(historyLine) },
194
+ supersede: { value: [], bool: [], max: 2, run: runSupersede },
195
+ forget: { value: [], bool: ['purge', 'yes'], max: 1, run: runForget },
196
+ confirm: { value: [], bool: [], max: 1, run: runConfirm },
197
+ reject: { value: [], bool: [], max: 1, run: (db, { args }) => [`rejected ${line(memory.reject(db, memory.parseId(args[0])))}`] },
198
+ memory: { value: [], bool: ['tidy'], run: runMemoryCommand },
199
+ project: { value: ['slug'], multi: ['alias'], bool: ['all', 'json'], run: runProject },
200
+ job: { value: ['project', 'title', 'agent', 'status', 'from-file', 'guide', 'reviews', 'accept', 'attempts'], bool: ['all', 'tests-may-change', 'json'], run: runJob },
201
+ prime: { value: ['budget'], bool: [], max: 0, run: (db, { flags }) => [forPerson(prime(db, { budget: flags.budget === undefined ? undefined : positiveInteger(flags.budget, '--budget needs a positive number') }))] },
202
+ scribe: { value: [], bool: [], run: renamed },
203
+ cost: { value: ['days', 'project'], bool: [], max: 0, run: (db, { flags }) => costLines(db, { days: flags.days === undefined ? undefined : positiveInteger(flags.days, '--days needs a positive number'), project: flags.project }) },
204
+ dream: { value: [], bool: [], run: renamed },
205
+ apply: { value: ['source'], bool: [], max: 1, run: runApply },
206
+ export: { value: [], bool: ['json', 'md'], max: 0, run: runExport },
207
+ backup: { value: [], bool: ['yes'], run: runBackup },
175
208
  models: { value: [], bool: [], run: runModels },
176
- mcp: { value: ['url'], multi: ['env', 'header'], bool: [], run: runMcp },
209
+ mcp: { value: ['url'], multi: ['env', 'header'], bool: ['from-claude'], run: runMcp },
177
210
  };
178
211
 
212
+ /**
213
+ * At a terminal, text written for a model reads as text for a person: the tags that mark it — <sumo-memory>, <project …>
214
+ * — become words. Piped, to a hook, a harness or the model, it is exactly what the model reads.
215
+ */
216
+ function forPerson(text) {
217
+ if (!process.stdout.isTTY) return text;
218
+ return text
219
+ .replace(/^<sumo-memory>\n?/m, () => 'What a session starts with:\n')
220
+ .replace(/^<project ([^>\s]+)( \(archived\))?> /m, (_, slug, archived = '') => `${slug}${archived} · `)
221
+ .replace(/\n?<\/(?:sumo-memory|project)>\s*$/, () => '');
222
+ }
223
+
224
+ /** What `--json` prints: one object, its lists named, for a script to read; nothing else on stdout. */
225
+ const asJson = (value) => [JSON.stringify(value, null, 2)];
226
+ /** A memory as a script sees it: the stored row, without what ranking added to it. */
227
+ const plainMemory = ({ rank, score, ...row }) => row;
228
+
179
229
  /** Memory a job's shell never writes: it reports, and the user or the chat decides. */
180
230
  const JOB_NEVER = ['add', 'learn', 'gate', 'supersede', 'forget', 'confirm', 'reject', 'apply'];
181
231
  /** What the model's shell never changes, by command and the subcommands that change something. */
182
232
  const OWNER_COMMANDS = new Map([
183
233
  ['mcp', (args) => ['add', 'remove', 'allow', 'revoke'].includes(args[0])],
184
234
  ['models', (args) => ['enable', 'disable', 'discover'].includes(args[0])],
235
+ ['backup', (args) => args[0] === 'restore'],
185
236
  ]);
186
237
 
187
238
  function parse(argv, spec) {
188
239
  const args = [];
189
240
  const flags = {};
190
241
  const nameOf = (token) => (token.startsWith('--') ? token.slice(2) : token === '-n' ? 'n' : null);
242
+ const names = [...spec.value, ...(spec.multi ?? []), ...spec.bool];
243
+ const spelled = (o) => (o === 'n' ? '-n' : `--${o}`);
191
244
  // One of this command's own flags where a value belongs means the value was left out — `--topic --pin` is not a topic.
192
- const isFlag = (token) => [...spec.bool, ...spec.value, ...(spec.multi ?? [])].includes(nameOf(token));
245
+ const isFlag = (token) => names.includes(nameOf(token.split('=')[0]));
193
246
  for (let i = 0; i < argv.length; i++) {
194
- const token = argv[i];
247
+ let token = argv[i];
195
248
  if (token === '--') {
196
249
  args.push(...argv.slice(i + 1));
197
250
  break;
198
251
  }
252
+ // `--days=7` is `--days 7`, and `-n5` is `-n 5`, as everywhere else on the command line.
253
+ let given;
254
+ if (/^--[^=]+=/.test(token)) [token, given] = [token.slice(0, token.indexOf('=')), token.slice(token.indexOf('=') + 1)];
255
+ else if (/^-n\d+$/.test(token) && spec.value.includes('n')) [token, given] = ['-n', token.slice(2)];
199
256
  const name = nameOf(token);
200
- // `-p` is not a word of the query: a short flag nobody here takes is a mistake to say, not text to search for.
201
- if (name === null && /^-[A-Za-z]+$/.test(token)) throw new UsageError(`unknown option ${token} — options are spelled out (--project, --type, …); to mean it as text, quote the whole value or put it after --`);
257
+ if (name === null && /^-[A-Za-z]+$/.test(token)) {
258
+ // `-p` is not a word of the query: a short flag nobody here takes is a mistake to say, not text to search for.
259
+ const meant = names.filter((o) => o !== 'n' && o.startsWith(token[1].toLowerCase()));
260
+ const hint = meant.length === 1 ? `did you mean --${meant[0]}?` : 'options are spelled out (--project, --type, …)';
261
+ throw new UsageError(`unknown option ${token} — ${hint} To mean it as text, quote the whole value or put it after --`);
262
+ }
202
263
  if (name === null) {
203
264
  args.push(token);
204
265
  } else if (spec.bool.includes(name)) {
266
+ if (given !== undefined) throw new UsageError(`${token} takes no value — leave out =${given}`);
205
267
  flags[name] = true;
206
268
  } else if (spec.value.includes(name) || spec.multi?.includes(name)) {
207
- if (i + 1 >= argv.length || isFlag(argv[i + 1])) throw new UsageError(`${token} needs a value`);
208
- const value = argv[++i];
269
+ if (given === undefined && (i + 1 >= argv.length || isFlag(argv[i + 1]))) throw new UsageError(`${token} needs a value`);
270
+ const value = given ?? argv[++i];
209
271
  if (spec.multi?.includes(name)) (flags[name] ??= []).push(value);
210
272
  else flags[name] = value;
211
273
  } else {
212
- throw new UsageError(`unknown option ${token}`);
274
+ // Said with the one it most likely meant, or the ones it does take, so the next try is the right one.
275
+ const near = closest(name, names);
276
+ const takes = names.length > 0 ? `takes ${[...names].sort().map(spelled).join(', ')}` : 'takes none';
277
+ throw new UsageError(`unknown option ${token} — ${near ? `did you mean ${spelled(near)}? It ${takes}` : `this command ${takes}`}`);
213
278
  }
214
279
  }
215
280
  return { args, flags };
@@ -219,6 +284,28 @@ function need(args, count, command) {
219
284
  if (args.length < count) throw new UsageError(`usage: ${USAGE[command]}`);
220
285
  }
221
286
 
287
+ /**
288
+ * Asked at a terminal before what cannot be taken back, or what loses work: true only when one of `answers` is typed.
289
+ * `--yes` is the answer given up front; with no terminal and no --yes there is nobody to ask, and nothing is done.
290
+ */
291
+ async function confirmed(flags, why, question, answers) {
292
+ if (flags.yes) return true;
293
+ if (!process.stdin.isTTY || !process.stdout.isTTY) throw new UsageError(`${why}, so it asks first — run it in a terminal, or add --yes`);
294
+ const { createInterface: asker } = await import('node:readline/promises');
295
+ const rl = asker({ input: process.stdin, output: process.stdout });
296
+ try {
297
+ // What it is about first, then the question on a line of its own: readline redraws only the last line.
298
+ const said = question.split('\n');
299
+ const asked = said.pop();
300
+ if (said.length > 0) process.stdout.write(`${said.join('\n')}\n`);
301
+ // Ctrl-C or Ctrl-D at the question is a no.
302
+ const typed = await rl.question(asked).catch(() => '');
303
+ return answers.includes(typed.trim().toLowerCase());
304
+ } finally {
305
+ rl.close();
306
+ }
307
+ }
308
+
222
309
  const DAY_MS = 86_400_000;
223
310
 
224
311
  /**
@@ -247,10 +334,11 @@ function runSearch(db, { args, flags }) {
247
334
  const match = ftsQuery(args.join(' '));
248
335
  if (!match) throw new UsageError('nothing to search for');
249
336
  const turns = searchTurns(db, match, limit);
337
+ if (flags.json) return asJson({ turns });
250
338
  return turns.length > 0 ? turns.map((t) => `t${t.id} ${t.ts.slice(0, 10)} ${t.text.replace(/\s+/g, ' ').slice(0, 200)}`) : [`the user never said anything like: ${args.join(' ')}`];
251
339
  }
252
340
 
253
- const { results, elsewhere } = memory.search(db, args.join(' '), {
341
+ const { results, elsewhere, more } = memory.search(db, args.join(' '), {
254
342
  project: flags.project,
255
343
  type: WORKFLOW_NAMES.includes(flags.type) ? 'procedure' : flags.type,
256
344
  everywhere: flags.everywhere,
@@ -260,9 +348,12 @@ function runSearch(db, { args, flags }) {
260
348
  limit,
261
349
  });
262
350
 
351
+ if (flags.json) return asJson({ memories: results.map(plainMemory), more, elsewhere });
263
352
  // An explicit "nothing" is an answer: it is what lets an agent say
264
353
  // "not in memory" instead of guessing.
265
354
  const out = results.length > 0 ? results.map(line) : [`nothing in memory for: ${args.join(' ')}`];
355
+ // A list cut short says so, and how to see the rest.
356
+ if (more > 0) out.push(`… ${more} more — -n ${results.length + more} shows them all, or narrow the words`);
266
357
  const others = Object.entries(elsewhere);
267
358
  if (others.length > 0) {
268
359
  const where = others.map(([scope, n]) => `${scopeLabel(scope)} (${n})`).join(', ');
@@ -283,7 +374,7 @@ function savedLines({ memory: saved, similar, redacted }) {
283
374
 
284
375
  function runAdd(db, { args, flags }) {
285
376
  need(args, 2, 'add');
286
- if (fromJob()) throw new UsageError(jobWrites());
377
+ if (fromJob()) throw new Refusal(jobWrites());
287
378
  const [type, ...text] = args;
288
379
  if (WORKFLOW_NAMES.includes(type)) throw new UsageError(`a workflow has a title and steps, so it is saved with sumo learn, not sumo add:\n${LEARN_USAGE}`);
289
380
  if (!ADDABLE.includes(type)) throw new UsageError(`unknown type "${type}" — one of: ${ADDABLE.join(', ')} (for a workflow: sumo learn)`);
@@ -298,18 +389,19 @@ function runAdd(db, { args, flags }) {
298
389
  pin: flags.pin,
299
390
  supersedes: flags.supersedes === undefined ? undefined : memory.parseId(flags.supersedes),
300
391
  provenance: held ? 'inferred' : flags.observed ? 'observed' : 'stated',
392
+ writtenBy: byUser(),
301
393
  });
302
394
  return savedLines(saved).concat(held ? [HELD(saved.memory.id)] : []);
303
395
  }
304
396
 
305
397
  function runLearn(db, { args, flags }) {
306
398
  need(args, 1, 'learn');
307
- if (fromJob()) throw new UsageError(jobWrites());
399
+ if (fromJob()) throw new Refusal(jobWrites());
308
400
  const body = flags['from-file'] ? readFileSync(flags['from-file'], 'utf8') : process.stdin.isTTY ? '' : readFileSync(0, 'utf8');
309
401
  if (!body.trim()) throw new UsageError('no steps given — pipe them in, or use --from-file <path>');
310
402
  const title = args.join(' ');
311
403
  const held = fromTool() && !saidByUser(db, [title, flags.cue ?? '', body].join(' '));
312
- const saved = memory.add(db, { type: 'procedure', title, cue: flags.cue, gate: flags.gate, body, project: flags.project, provenance: held ? 'inferred' : 'stated' });
404
+ const saved = memory.add(db, { type: 'procedure', title, cue: flags.cue, gate: flags.gate, body, project: flags.project, provenance: held ? 'inferred' : 'stated', writtenBy: byUser() });
313
405
  return savedLines(saved).concat(flags.gate ? [`gates shell commands matching: ${flags.gate}`] : [], held ? [HELD(saved.memory.id)] : []);
314
406
  }
315
407
 
@@ -325,9 +417,37 @@ function runSupersede(db, { args }) {
325
417
  return [`superseded ${line(old)}`];
326
418
  }
327
419
 
328
- function runForget(db, { args, flags }) {
420
+ /** A reply that says yes to the question put. */
421
+ const AFFIRMS = /^\s*(?:yes|yep|yeah|yup|y|correct|right|that['’]?s right|confirm(?:ed)?|ok(?:ay)?|sure|true|exactly|agreed?|keep (?:it|that)|do it)\b/i;
422
+
423
+ /**
424
+ * A guess made a memory of the user's. From the model's shell only once the user has spoken since the guess was made,
425
+ * and said yes, or said the thing itself: a model may not add a guess and vouch for it in one go, nor a page tell it
426
+ * to. One held because its conversation read the web or an MCP server only the user confirms (memory.confirm).
427
+ */
428
+ function runConfirm(db, { args }) {
429
+ const id = memory.parseId(args[0]);
430
+ if (fromTool()) {
431
+ const row = memory.get(db, id);
432
+ const since = db.prepare('SELECT text FROM user_turns WHERE ts > ? ORDER BY id DESC LIMIT 1').get(row.created_at);
433
+ if (row.state === 'unconfirmed' && row.held_for !== 'outside' && !(since && (AFFIRMS.test(since.text) || saysAs(row.body, since.text)))) {
434
+ throw new UsageError(`m${id} is a guess, and the user has not said yes to it since it was made: ask them first (the ask tool), then sumo confirm m${id} — or they confirm it on the memory page, /memory`);
435
+ }
436
+ }
437
+ return [`confirmed ${line(memory.confirm(db, id, { byUser: !fromTool() }))}`];
438
+ }
439
+
440
+ async function runForget(db, { args, flags }) {
329
441
  need(args, 1, 'forget');
330
- const gone = memory.forget(db, memory.parseId(args[0]), { purge: flags.purge });
442
+ // Erased for good, from the backups too: only the user decides that. A forget without --purge keeps the history.
443
+ if (flags.purge && fromTool()) throw new Refusal(`erasing a memory for good is the user's to do: they run sumo forget ${args[0]} --purge themselves. sumo forget ${args[0]} stops it being true and keeps its history`);
444
+ const id = memory.parseId(args[0]);
445
+ if (flags.purge) {
446
+ // Seen before it goes: the memory as it stands, and its id typed back — the strongest yes, for what no backup brings back.
447
+ const shown = `${line(memory.get(db, id))}\nErase m${id} for good, from every backup too? Type m${id} to confirm: `;
448
+ if (!(await confirmed(flags, `erasing m${id} for good cannot be undone`, shown, [`m${id}`, String(id)]))) throw new Error(`nothing was erased — the answer was not m${id}`);
449
+ }
450
+ const gone = memory.forget(db, id, { purge: flags.purge });
331
451
  if (!flags.purge) return [`forgot ${line(gone)}`];
332
452
  const { cleaned, failed } = purgeFromBackups(gone);
333
453
  const copies = cleaned > 0 ? `, and from ${cleaned} backup${cleaned === 1 ? '' : 's'}` : '';
@@ -338,20 +458,28 @@ function runForget(db, { args, flags }) {
338
458
 
339
459
  function runProject(db, { args, flags }) {
340
460
  const [sub, ...rest] = args;
461
+ if (flags.json && sub !== 'list') throw new UsageError('--json goes with sumo project list');
341
462
  switch (sub) {
342
463
  case 'add': {
343
464
  need(rest, 1, 'project');
344
465
  const { project, created, restored, changes } = projects.addProject(db, rest[0], { slug: flags.slug, aliases: flags.alias });
345
466
  const rescanned = `rescanned (${changes.added} new, ${changes.updated} changed, ${changes.removed} gone)`;
346
467
  const summary = created ? `registered ${project.slug}` : restored ? `${project.slug} is back from the archive — ${rescanned}` : `${project.slug} was already registered — ${rescanned}`;
347
- return [summary, card(db, project.slug)];
468
+ // A name asked for a project that has one already is said to be unused, not dropped without a word.
469
+ const kept = !created && flags.slug !== undefined && flags.slug !== project.slug ? [`--slug is for a new project: this one keeps the name ${project.slug} (an alias adds a name: --alias ${flags.slug})`] : [];
470
+ return [summary, ...kept, card(db, project.slug)];
348
471
  }
349
472
  case 'show':
350
473
  need(rest, 1, 'project');
351
- return [card(db, rest[0])];
474
+ return [forPerson(card(db, rest[0]))];
352
475
  case 'list': {
353
476
  const all = projects.listProjects(db, { includeArchived: flags.all });
354
- if (all.length === 0) return ['no projects registered — sumo project add <path>'];
477
+ if (flags.json) return asJson({ projects: all.map((p) => ({ ...p, aliases: projects.aliasesOf(db, p.slug) })) });
478
+ if (all.length === 0) {
479
+ // None in use is not none at all: archived ones are said, with how to see them.
480
+ const archived = flags.all ? 0 : projects.listProjects(db, { includeArchived: true }).length;
481
+ return [archived > 0 ? `no active projects — ${archived} archived: sumo project list --all` : 'no projects registered — sumo project add <path>'];
482
+ }
355
483
  return all.map((p) => {
356
484
  const aliases = projects.aliasesOf(db, p.slug);
357
485
  return `${p.slug} ${p.path}${aliases.length ? ` (also: ${aliases.join(', ')})` : ''}${p.status === 'archived' ? ' [archived]' : ''}`;
@@ -385,24 +513,24 @@ function stdinText(flags) {
385
513
  function createdLines(job, warnings, attempts = null) {
386
514
  if (attempts) {
387
515
  return [
388
- ...attempts.map((a) => `created ${jobs.jobLine(a)}`),
516
+ ...attempts.map((a) => `created ${jobs.jobLine(a, 'not started')}`),
389
517
  ...warnings,
390
518
  `route: ${job.model}/${job.effort} — ${job.route_reason}`,
391
519
  `run each: ${attempts.map((a) => `sumo job run ${a.id}`).join(' · ')} — once all have closed, the best verified one is brought back`,
392
520
  ];
393
521
  }
394
522
  return [
395
- `created ${jobs.jobLine(job)}`,
523
+ `created ${jobs.jobLine(job, 'not started')}`,
396
524
  ...warnings,
397
525
  `route: ${job.model}/${job.effort} — ${job.route_reason}`,
398
- `run it: sumo job run ${job.id} (append & to carry on without waiting for it) — inside the chat: delegate with job ${job.id}`,
526
+ `run it: sumo job run j${job.id} (append & to carry on without waiting for it) — inside the chat: delegate with job j${job.id}`,
399
527
  ];
400
528
  }
401
529
 
402
- /** A job's own tab in Herdr: it says it is working, and a line typed into the tab is a message to the job. */
403
- function tabBegins(db, job, print) {
530
+ /** A job's own tab in Herdr: it says it is working, and a line typed into the tab is a message to the job. `herdr` is herdr.mjs, loaded by the run. */
531
+ function tabBegins(db, job, print, herdr) {
404
532
  print?.(job);
405
- reportAgent(runHerdr, process.env, { job, state: 'working', message: job.title });
533
+ herdr.reportAgent(herdr.runHerdr, process.env, { job, state: 'working', message: job.title });
406
534
  if (process.stdin.isTTY) {
407
535
  const typed = createInterface({ input: process.stdin });
408
536
  typed.on('line', (line) => {
@@ -417,10 +545,10 @@ function tabBegins(db, job, print) {
417
545
  process.stdin.unref();
418
546
  }
419
547
  }
420
- function tabEnds(job, status) {
548
+ function tabEnds(job, status, herdr) {
421
549
  process.stdin.pause();
422
- reportAgent(runHerdr, process.env, { job, state: job.status === 'needs_input' ? 'blocked' : 'idle', message: status });
423
- closeJobTab(runHerdr, process.env, job);
550
+ herdr.reportAgent(herdr.runHerdr, process.env, { job, state: job.status === 'needs_input' ? 'blocked' : 'idle', message: status });
551
+ herdr.closeJobTab(herdr.runHerdr, process.env, job);
424
552
  }
425
553
 
426
554
  /**
@@ -430,8 +558,15 @@ function tabEnds(job, status) {
430
558
  async function watchJob(db, id) {
431
559
  const job = jobs.getJob(db, id);
432
560
  if (!existsSync(jobs.liveFile(id)) && job.status !== 'running' && job.status !== 'needs_input') return [`j${id} is ${job.status} — nothing is running`];
561
+ // A job made but never started has no record to follow: that is said, not waited on for ever. A run starting this
562
+ // moment writes its record within a few seconds, or holds its lock while it gets there.
563
+ for (let waited = 0; !existsSync(jobs.liveFile(id)); waited += 250) {
564
+ if (waited >= 5000 && heldBy(jobs.runLockFile(id)) === null) throw new Error(`j${id} has not started — run it: sumo job run j${id}, or in the chat: delegate with job j${id}`);
565
+ await new Promise((r) => setTimeout(r, 250));
566
+ }
433
567
  // The record opens with the job's own line, so nothing is printed for it here.
434
- tabBegins(db, job);
568
+ const herdr = await import('./herdr.mjs');
569
+ tabBegins(db, job, undefined, herdr);
435
570
  let at = 0;
436
571
  // A character split across two reads is held until its other half arrives.
437
572
  const decoder = new StringDecoder('utf8');
@@ -443,7 +578,7 @@ async function watchJob(db, id) {
443
578
  await new Promise((r) => setTimeout(r, 250));
444
579
  }
445
580
  const lines = safeForTerminal(readFileSync(jobs.endFile(id), 'utf8')).trimEnd().split('\n');
446
- tabEnds(jobs.getJob(db, id), lines[0]);
581
+ tabEnds(jobs.getJob(db, id), lines[0], herdr);
447
582
  return lines;
448
583
  }
449
584
 
@@ -476,6 +611,7 @@ const settleHere = (db, id) => (process.env.SUMO_JOB === String(id) ? [] : jobs.
476
611
 
477
612
  async function runJob(db, { args, flags }) {
478
613
  const [sub, rawId] = args;
614
+ if (flags.json && sub !== 'list') throw new UsageError('--json goes with sumo job list');
479
615
  if (sub === 'new') {
480
616
  if (!flags.project) throw new UsageError(`usage: ${USAGE.job}`);
481
617
  const { job, jobs: attempts, warnings } = await jobs.newJob(db, {
@@ -492,8 +628,9 @@ async function runJob(db, { args, flags }) {
492
628
  }
493
629
  if (sub === 'list') {
494
630
  const all = jobs.listJobs(db, { all: flags.all });
495
- if (all.length === 0) return ['no open jobs'];
496
- return [...all.map(jobs.jobLine), ...(all.more > 0 ? [`… ${all.more} older — sumo job show <id> for one of them`] : [])];
631
+ if (flags.json) return asJson({ jobs: [...all], more: all.more });
632
+ if (all.length === 0) return [flags.all ? 'no jobs yet — sumo job new --project <name> --title <what> starts one' : 'no open jobs'];
633
+ return [...all.map((job) => jobs.jobLine(job, job.shown)), ...(all.more > 0 ? [`… ${all.more} older — sumo job show <id> for one of them`] : [])];
497
634
  }
498
635
  if (sub === 'stats') {
499
636
  return jobs.stats(db, { project: flags.project });
@@ -508,7 +645,7 @@ async function runJob(db, { args, flags }) {
508
645
  if (rawId === undefined) throw new UsageError(`sumo job ${sub} needs a job id, like j17 — sumo job list shows them`);
509
646
  // An answer and a message reach a job as the user's own words: a job's shell, or text it read, never speaks for the user.
510
647
  if ((sub === 'tell' || sub === 'answer') && process.env.SUMO_JOB) {
511
- throw new UsageError(`Refused: j${process.env.SUMO_JOB} runs this command, and only the user answers or tells a job. Ask instead: the ask tool.`);
648
+ throw new Refusal(`Refused: j${process.env.SUMO_JOB} runs this command, and only the user answers or tells a job. Ask instead: the ask tool.`);
512
649
  }
513
650
  const id = jobs.parseJobId(rawId);
514
651
  switch (sub) {
@@ -518,8 +655,10 @@ async function runJob(db, { args, flags }) {
518
655
  // The job runs here, in Sumo's own loop, on the route the router chose; it closes itself the way its brief says.
519
656
  // On a terminal the work is shown as it happens — the lines a Herdr pane shows; piped, only how it ended.
520
657
  if (!resolveAnthropicCredential()) {
521
- throw new UsageError(`j${id} not started — this shell has no Anthropic credential. Inside the chat, the delegate tool runs it; in a terminal, export CLAUDE_CODE_OAUTH_TOKEN or ANTHROPIC_API_KEY first`);
658
+ throw new NeedsCredential(`j${id} not started — this shell has no Anthropic credential. Inside the chat, the delegate tool runs it; in a terminal, export CLAUDE_CODE_OAUTH_TOKEN or ANTHROPIC_API_KEY first`);
522
659
  }
660
+ // The run's own machinery, loaded only for a run: the loop brings the SDK, and no other command needs any of it.
661
+ const [{ jobPrinter }, { runJob: runJobLoop, runLines }, herdr] = await Promise.all([import('./chat.mjs'), import('./loop.mjs'), import('./herdr.mjs')]);
523
662
  // What the model and its commands print reaches this terminal as text only: no escape of theirs titles the window or writes the clipboard.
524
663
  const watch = process.stdout.isTTY ? jobPrinter((t) => process.stdout.write(safeForTerminal(t)), styles(colourEnabled())) : {};
525
664
  // Ctrl-C stops the run the way Esc stops one in the chat: what it started is stopped, and how it ended is still said.
@@ -535,7 +674,7 @@ async function runJob(db, { args, flags }) {
535
674
  db,
536
675
  id,
537
676
  async (each, warnings = []) => {
538
- last = await runJobLoop(db, each, { ...watch, signal: stop.signal, ...(process.stdout.isTTY && each === id ? { onStart: (job) => tabBegins(db, job, watch.onStart) } : {}) });
677
+ last = await runJobLoop(db, each, { ...watch, signal: stop.signal, ...(process.stdout.isTTY && each === id ? { onStart: (job) => tabBegins(db, job, watch.onStart, herdr) } : {}) });
539
678
  return [...warnings, ...runLines(last), ...last.settled];
540
679
  },
541
680
  { signal: stop.signal },
@@ -544,7 +683,7 @@ async function runJob(db, { args, flags }) {
544
683
  process.off('SIGINT', interrupt);
545
684
  }
546
685
  const lines = ran.flatMap((step) => [...(step.line ? ['', step.line] : []), ...(step.result ?? []), ...(step.error ? [`j${step.id} stopped on an error: ${step.error}`] : [])]).map(safeForTerminal);
547
- tabEnds(last.job, runLines(last)[0]);
686
+ tabEnds(last.job, runLines(last)[0], herdr);
548
687
  return lines;
549
688
  }
550
689
  case 'show':
@@ -559,7 +698,7 @@ async function runJob(db, { args, flags }) {
559
698
  return [`STATUS: NEEDS_INPUT — j${id}. Stop now; you will be resumed with the answer.`];
560
699
  case 'answer':
561
700
  jobs.answer(db, id, stdinText(flags));
562
- return [`answered j${id}. Continue it: delegate with job ${id}, or sumo job run ${id} in a terminal (the brief now carries the answer)`];
701
+ return [`answered j${id}. Continue it: delegate with job j${id}, or sumo job run j${id} in a terminal (the brief now carries the answer)`];
563
702
  case 'tell':
564
703
  jobs.tell(db, id, stdinText(flags));
565
704
  return [`told j${id} — it reads it with its next request`];
@@ -580,7 +719,7 @@ async function runJob(db, { args, flags }) {
580
719
  default: {
581
720
  // Taking work unverified is the user's call: never granted from inside a job's own shell, whatever the command looked like.
582
721
  if (flags.accept !== undefined && process.env.SUMO_JOB) {
583
- throw new UsageError(`Refused: j${process.env.SUMO_JOB} runs this command, and work is never taken unverified on its author's word. Finish FAILED with what blocks verification, or ask.`);
722
+ throw new Refusal(`Refused: j${process.env.SUMO_JOB} runs this command, and work is never taken unverified on its author's word. Finish FAILED with what blocks verification, or ask.`);
584
723
  }
585
724
  const { job, learned, verdict, unverified } = jobs.finish(db, id, { status: String(flags.status ?? '').toUpperCase(), report: stdinText(flags), accept: flags.accept });
586
725
  // A worker's plain DONE means the checks agreed; the verdict is in the report. Only the exceptions are said here.
@@ -601,19 +740,26 @@ function passLines(outcome) {
601
740
  return outcome.ok === false && !outcome.skipped ? Object.assign(lines, { exitCode: 1 }) : lines;
602
741
  }
603
742
 
604
- async function runScribeCommand(db, { args }) {
605
- if (args[0] === 'run') return passLines(await runScribe(db));
606
- if (args[0] === 'status') return scribeStatus(db);
607
- if (args[0] === 'stats') return modelStats(db);
608
- // Exactly what the cheap model would be sent right now — nothing about the writer is hidden from the user.
609
- if (args[0] === 'show') return [buildBundle(db)?.prompt ?? 'nothing new was said'];
610
- throw new UsageError(`usage: ${USAGE.scribe}`);
743
+ /**
744
+ * Memory: with no argument, the page to confirm, edit and forget on; `run` the memory pass now — it files what was said
745
+ * and tidies when that is due, or now with `--tidy`; `status` how the pass is doing; `show` exactly what the next
746
+ * pass would be sent, so nothing about it is hidden from the user.
747
+ */
748
+ async function runMemoryCommand(db, { args, flags }) {
749
+ // The page waits on the user until Ctrl-C: from the model's shell it would only hang there.
750
+ if (args[0] === undefined && fromTool()) throw new Refusal('the memory page is the user\'s: they open it with /memory in the chat, or sumo memory');
751
+ // Nor with no terminal: piped or in a script, nobody is there to look at it, or to press Ctrl-C.
752
+ if (args[0] === undefined && (!process.stdin.isTTY || !process.stdout.isTTY)) throw new UsageError('the memory page runs until Ctrl-C, so it needs a terminal — run sumo memory in one; sumo memory status and sumo search work anywhere');
753
+ if (args[0] === undefined) return runMemoryPage(db);
754
+ if (args[0] === 'run') return memoryPassLines(await runMemoryPass(db, { tidy: flags.tidy === true }), { asked: flags.tidy === true });
755
+ if (args[0] === 'status') return memoryStatus(db);
756
+ if (args[0] === 'show') return [buildBundle(db)?.prompt ?? 'nothing waits to be filed: the next memory pass has nothing new to read'];
757
+ throw new UsageError(`usage: ${USAGE.memory}`);
611
758
  }
612
759
 
613
- async function runDreamCommand(db, { args }) {
614
- if (args[0] === 'run') return passLines(await runDream(db, { force: true }));
615
- if (args[0] === 'status') return dreamStatus(db);
616
- throw new UsageError(`usage: ${USAGE.dream}`);
760
+ /** The writer and the tidier were two commands; they are one memory pass now, and the old names say so. */
761
+ function renamed() {
762
+ throw new UsageError('the writer and the tidier are one memory pass now: sumo memory run [--tidy] · sumo memory status · sumo memory show');
617
763
  }
618
764
 
619
765
  /** Runs a model's proposed operations through the same validator the automatic passes use. */
@@ -635,6 +781,7 @@ function runApply(db, { args, flags }) {
635
781
 
636
782
  /** Runs until Ctrl-C: the page is only there while someone is looking at it. */
637
783
  async function runMemoryPage(db) {
784
+ const { openInBrowser, servePage } = await import('./page.mjs');
638
785
  const page = await servePage(db);
639
786
  process.stdout.write(`your memory: ${page.url}\nCtrl-C to stop\n`);
640
787
  openInBrowser(page.url);
@@ -649,7 +796,7 @@ async function runModels(db, { args }) {
649
796
  if (sub === undefined) return modelLines(db);
650
797
  if (sub === 'discover') {
651
798
  const result = await discoverModels(db);
652
- if (!result.ok) throw new Error(`could not check the models — ${result.error}; nothing was changed`);
799
+ if (!result.ok) throw new (/no Anthropic credential/.test(result.error) ? NeedsCredential : Error)(`could not check the models — ${result.error}; nothing was changed`);
653
800
  return modelLines(db);
654
801
  }
655
802
  if ((sub === 'enable' || sub === 'disable') && name !== undefined) {
@@ -665,19 +812,32 @@ function pairs(list = [], flag) {
665
812
  list.map((pair) => {
666
813
  const at = pair.indexOf('=');
667
814
  if (at < 1) throw new UsageError(`${flag} takes NAME=value, not "${pair}"`);
668
- return [pair.slice(0, at), pair.slice(at + 1)];
815
+ const [name, value] = [pair.slice(0, at), pair.slice(at + 1)];
816
+ // The file never holds a token: one given in the clear is refused, with how to pass it instead — it stays in the shell.
817
+ if (redact(value).text !== value) {
818
+ throw new UsageError(`${flag} ${name} holds a token in the clear, and the file never does — export it in your shell and write \${NAME} in its place (${flag} "${name}=${value.startsWith('Bearer ') ? 'Bearer ' : ''}\${MY_TOKEN}"): it is filled in when the server starts`);
819
+ }
820
+ return [name, value];
669
821
  }),
670
822
  );
671
823
  }
672
824
 
673
825
  /** MCP servers: configured here, connected by every chat and job; what may run without asking is set here too. */
674
826
  async function runMcp(db, { args, flags }) {
827
+ const { addServer, allowedBy, CLAUDE_CODE_TOKEN, closeMcp, connect, mcpLines, mcpReady, readConfig, removeServer, setAllow } = await import('./mcp.mjs');
675
828
  const [sub = 'list', name, ...rest] = args;
676
829
  switch (sub) {
677
830
  case 'list': {
831
+ // Connecting can take a while — each server is given up to a minute — so a terminal is told what it is waiting for.
832
+ const configured = Object.keys(readConfig().mcpServers ?? {}).length;
833
+ if (configured > 0 && process.stderr.isTTY) process.stderr.write(`connecting to ${configured} MCP server${configured === 1 ? '' : 's'}…\n`);
678
834
  const registry = await mcpReady();
679
835
  try {
680
- return mcpLines(registry);
836
+ const lines = mcpLines(registry);
837
+ // Every server failing is a failure, for a script as for a person.
838
+ const servers = registry.error ? [] : registry.servers();
839
+ if (servers.length > 0 && servers.every((one) => !one.ok)) lines.exitCode = 1;
840
+ return lines;
681
841
  } finally {
682
842
  await closeMcp();
683
843
  }
@@ -687,14 +847,19 @@ async function runMcp(db, { args, flags }) {
687
847
  let spec;
688
848
  if (flags.url) {
689
849
  if (rest.length > 0) throw new UsageError('a server is a command or a --url, not both');
690
- spec = { url: flags.url, ...(flags.header ? { headers: pairs(flags.header, '--header') } : {}) };
850
+ if (!/^https?:\/\/[^\s/]/i.test(flags.url)) throw new UsageError(`--url takes a web address, https://… — not "${flags.url}"`);
851
+ if (flags['from-claude'] && flags.header) throw new UsageError('a token borrowed from Claude Code or --header, not both');
852
+ spec = { url: flags.url, ...(flags.header ? { headers: pairs(flags.header, '--header') } : {}), ...(flags['from-claude'] ? { token: CLAUDE_CODE_TOKEN } : {}) };
853
+ } else if (flags['from-claude']) {
854
+ throw new UsageError('--from-claude goes with --url: the server Claude Code is logged in to');
691
855
  } else if (rest.length > 0) {
692
856
  spec = { command: rest[0], args: rest.slice(1), ...(flags.env ? { env: pairs(flags.env, '--env') } : {}) };
693
857
  } else {
694
858
  throw new UsageError('a server is a command (after --) or a --url:\nsumo mcp add <name> -- <command> [args...] | sumo mcp add <name> --url <url>');
695
859
  }
696
860
  addServer(name, spec);
697
- return [`added ${name} (${spec.url ? `http: ${spec.url}` : `stdio: ${[spec.command, ...spec.args].join(' ')}`})`, `next: sumo mcp — connects to it and lists its tools; sumo mcp allow ${name} <tool>|all — lets them run without asking`];
861
+ const borrowed = spec.token === CLAUDE_CODE_TOKEN ? `, with Claude Code's login — log in there first: claude mcp add --transport http --scope user ${name} ${spec.url}, then claude mcp login ${name}` : '';
862
+ return [`added ${name} (${spec.url ? `http: ${spec.url}` : `stdio: ${[spec.command, ...spec.args].join(' ')}`}${borrowed})`, `next: sumo mcp — connects to it and lists its tools; sumo mcp allow ${name} <tool>|all — lets them run without asking`];
698
863
  }
699
864
  case 'remove':
700
865
  if (!name) throw new UsageError(`usage: ${USAGE.mcp}`);
@@ -735,14 +900,22 @@ function runBackup(db) {
735
900
  return [`backed up to ${file}${pruned > 0 ? ` (removed ${pruned} old)` : ''}`];
736
901
  }
737
902
 
738
- async function runDoctor() {
903
+ /** The checks as doctor prints them, one a line: the mark, what was checked, and what to do when it is not ok. */
904
+ const checkLine = (c, s) => `${c.ok ? s.green('ok ') : c.warn ? s.yellow('warn') : s.red('FAIL')} ${c.label}${c.ok ? '' : ` — ${c.fix}`}`;
905
+
906
+ async function runDoctor({ fix = false, report = false } = {}) {
907
+ if (fix) {
908
+ const fixed = makePrivate();
909
+ process.stdout.write(`fixed: ${fixed.length === 0 ? 'nothing to fix' : `made ${fixed.length} place${fixed.length === 1 ? '' : 's'} private`}\n`);
910
+ }
739
911
  const checks = await doctor();
912
+ if (report) {
913
+ process.stdout.write(`${await reportOf(checks.map((c) => checkLine(c, styles(false))))}\n`);
914
+ return 0;
915
+ }
740
916
  // On a terminal the mark is coloured, so a failure stands out of a column of oks; piped, it is the same words.
741
917
  const s = styles(colourEnabled());
742
- for (const c of checks) {
743
- const mark = c.ok ? s.green('ok ') : c.warn ? s.yellow('warn') : s.red('FAIL');
744
- process.stdout.write(`${mark} ${c.label}${c.ok ? '' : ` — ${c.fix}`}\n`);
745
- }
918
+ for (const c of checks) process.stdout.write(`${checkLine(c, s)}\n`);
746
919
  return checks.some((c) => !c.ok && !c.warn) ? 1 : 0;
747
920
  }
748
921
 
@@ -750,11 +923,26 @@ export async function main(argv) {
750
923
  const [command, ...rest] = argv;
751
924
  try {
752
925
  if (command === undefined || command === 'help' || command === '--help' || command === '-h') {
753
- process.stdout.write(HELP);
926
+ const topic = command === 'help' ? rest[0] : undefined;
927
+ if (topic === undefined) {
928
+ process.stdout.write(HELP);
929
+ return 0;
930
+ }
931
+ if (!Object.hasOwn(USAGE, topic)) {
932
+ const near = closest(topic, Object.keys(USAGE));
933
+ throw new UsageError(`no help for "${topic}" — ${near ? `did you mean "${near}"? ` : ''}the commands are in: sumo help`);
934
+ }
935
+ process.stdout.write(`${wrapped(USAGE[topic])}\n`);
754
936
  return 0;
755
937
  }
756
- if (Object.hasOwn(USAGE, command) && (rest.includes('--help') || rest.includes('-h'))) {
757
- process.stdout.write(`${USAGE[command]}\n`);
938
+ if (command === '--version' || command === '-v' || command === 'version') {
939
+ process.stdout.write(`sumo ${VERSION || 'unknown'}\n`);
940
+ return 0;
941
+ }
942
+ // After `--` it is text: `sumo search -- --help` searches for it.
943
+ const options = rest.includes('--') ? rest.slice(0, rest.indexOf('--')) : rest;
944
+ if (Object.hasOwn(USAGE, command) && (options.includes('--help') || options.includes('-h'))) {
945
+ process.stdout.write(`${wrapped(USAGE[command])}\n`);
758
946
  return 0;
759
947
  }
760
948
  if (command === 'setup') {
@@ -763,6 +951,17 @@ export async function main(argv) {
763
951
  process.stdout.write(`${lines.join('\n')}\n`);
764
952
  return 0;
765
953
  }
954
+ if (command === 'uninstall') {
955
+ const { args, flags } = parse(rest, { value: [], bool: ['yes', 'discard-memory'] });
956
+ if (args.length > 0) throw new UsageError(`uninstall takes no arguments, not "${args.join(' ')}" — usage: ${USAGE.uninstall}`);
957
+ if (fromTool()) throw new Refusal("removing sumo is the user's to do: they run sumo uninstall themselves");
958
+ // Looked at first — what would go, and a home that must never be removed — and only then asked.
959
+ const plan = uninstallPlan();
960
+ const keepMemory = !flags['discard-memory'];
961
+ if (!(await confirmed(flags, 'removing sumo cannot be undone', uninstallQuestion(plan, { keepMemory }), ['uninstall']))) throw new Error('nothing was removed — the answer was not uninstall');
962
+ process.stdout.write(`${uninstall(plan, { keepMemory }).join('\n')}\n`);
963
+ return 0;
964
+ }
766
965
  if (command === 'hook') {
767
966
  // No usage errors, no exit codes, no stderr: an event that complains breaks the session it serves.
768
967
  process.stdout.write(runHook(rest[0], process.stdin.isTTY ? '' : readFileSync(0, 'utf8')));
@@ -776,30 +975,53 @@ export async function main(argv) {
776
975
  // A full API id is taken too (claude-opus-5-5), as the chat itself takes one.
777
976
  if (flags.model !== undefined && flags.model !== 'auto' && !Object.values(MODEL_IDS).includes(flags.model)) knownModel(flags.model, ['auto']);
778
977
  if (flags.effort !== undefined && !CHAT_EFFORTS.includes(flags.effort)) throw new UsageError(`no such effort "${flags.effort}" — one of: ${CHAT_EFFORTS.join(', ')}`);
779
- if (!resolveAnthropicCredential()) throw new UsageError('the chat needs an Anthropic credential — export ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN in this shell, then: sumo chat');
978
+ if (!resolveAnthropicCredential()) throw new NeedsCredential('the chat needs an Anthropic credential — export ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN in this shell, then: sumo chat');
780
979
  const db = openDb();
781
980
  try {
782
981
  // A session that is not there to resume is said here too, before the screen.
783
982
  if (resume !== null) findSaved(db, resume, { now: new Date().toISOString() });
983
+ const { chat } = await import('./chat.mjs');
784
984
  return await chat(db, { model: flags.model, effort: flags.effort, resume });
785
985
  } finally {
786
986
  db.close();
787
987
  }
788
988
  }
789
- if (command === 'doctor') return await runDoctor();
989
+ if (command === 'doctor') {
990
+ const { flags } = parse(rest, { value: [], bool: ['fix', 'report'] });
991
+ return await runDoctor(flags);
992
+ }
790
993
  if (command === 'config') {
791
994
  const { args } = parse(rest, { value: [], bool: [] });
792
- if (args[1] !== undefined && fromTool()) throw new UsageError(OWNER_ONLY);
995
+ if (args[1] !== undefined && fromTool()) throw new Refusal(OWNER_ONLY);
793
996
  process.stdout.write(`${config(args[0], args[1]).join('\n')}\n`);
794
997
  return 0;
795
998
  }
796
999
 
797
1000
  // Own keys only: `sumo constructor` is not a command just because every object has one.
798
1001
  const spec = Object.hasOwn(COMMANDS, command) ? COMMANDS[command] : null;
799
- if (!spec) throw new UsageError(`unknown command "${command}" — see: sumo help`);
1002
+ if (!spec) {
1003
+ const near = closest(command, [...Object.keys(COMMANDS), ...Object.keys(USAGE), 'help', 'hook']);
1004
+ throw new UsageError(`unknown command "${command}" — ${near ? `did you mean "${near}"? See: sumo help` : 'see: sumo help'}`);
1005
+ }
800
1006
  const parsed = parse(rest, spec);
801
- if (JOB_NEVER.includes(command) && fromJob()) throw new UsageError(jobWrites());
802
- if (OWNER_COMMANDS.has(command) && fromTool() && OWNER_COMMANDS.get(command)(parsed.args)) throw new UsageError(OWNER_ONLY);
1007
+ // A word more than the command uses is refused, never dropped: `forget m1 m2` must not forget m1 alone and say nothing.
1008
+ if (spec.max !== undefined && parsed.args.length > spec.max) {
1009
+ const takes = spec.max === 0 ? 'no arguments' : spec.max === 1 ? 'one argument' : `${spec.max} arguments`;
1010
+ throw new UsageError(`${command} takes ${takes}, not ${parsed.args.length} ("${parsed.args.slice(spec.max).join(' ')}" is left over) — usage: ${USAGE[command]}`);
1011
+ }
1012
+ if (JOB_NEVER.includes(command) && fromJob()) throw new Refusal(jobWrites());
1013
+ if (OWNER_COMMANDS.has(command) && fromTool() && OWNER_COMMANDS.get(command)(parsed.args)) throw new Refusal(OWNER_ONLY);
1014
+ // Putting a copy back is done without opening the database: it may be the one that cannot be opened.
1015
+ if (command === 'backup' && parsed.args[0] === 'restore') {
1016
+ const copy = restoreCandidate(parsed.args[1] ?? null);
1017
+ // A damaged database has nothing to lose; one that is fine loses whatever came after the copy, so that is asked.
1018
+ const live = liveDatabase();
1019
+ const why = live && `the database in place opens and holds ${live.memories} memor${live.memories === 1 ? 'y' : 'ies'}, and putting a backup over it drops what came after`;
1020
+ if (live && !(await confirmed(parsed.flags, why, restoreQuestion(copy, live), ['y', 'yes']))) throw new Error('nothing was restored');
1021
+ process.stdout.write(`${restoreLines(copy, live).join('\n')}\n`);
1022
+ return 0;
1023
+ }
1024
+ if (command === 'backup' && parsed.args.length > 0) throw new UsageError(`usage: ${USAGE.backup}`);
803
1025
  const db = openDb();
804
1026
  try {
805
1027
  const lines = await spec.run(db, parsed);
@@ -809,7 +1031,9 @@ export async function main(argv) {
809
1031
  db.close();
810
1032
  }
811
1033
  } catch (cause) {
812
- process.stderr.write(`sumo: ${cause.message}\n`);
813
- return cause instanceof UsageError ? 2 : 1;
1034
+ // A database SQLite cannot read is said with the way back: the newest copy, and the command that restores it.
1035
+ process.stderr.write(`sumo: ${cause.message}${damaged(cause) ? ` — ${restoreHint()}` : ''}\n`);
1036
+ // 2: the command line was wrong · 1: understood and not done, or it failed · 4: an Anthropic credential is needed.
1037
+ return cause instanceof UsageError ? cause.exit : 1;
814
1038
  }
815
1039
  }