sumo-agents 0.0.0-stage → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +38 -0
- package/LICENSE +21 -0
- package/README.md +111 -2
- package/bin/sumo.mjs +33 -0
- package/guides/delegation.md +33 -0
- package/guides/feature.md +14 -0
- package/guides/fix.md +14 -0
- package/guides/memory.md +23 -0
- package/guides/projects.md +27 -0
- package/guides/review.md +16 -0
- package/guides/workflows.md +26 -0
- package/logo.txt +19 -0
- package/package.json +42 -4
- package/prompts/agent.md +7 -0
- package/prompts/dream.md +13 -0
- package/prompts/scribe.md +21 -0
- package/spinner.txt +90 -0
- package/src/advisor.mjs +59 -0
- package/src/apply.mjs +368 -0
- package/src/auth.mjs +80 -0
- package/src/card.mjs +72 -0
- package/src/catalog.mjs +167 -0
- package/src/chat.mjs +1162 -0
- package/src/cli.mjs +815 -0
- package/src/cost.mjs +128 -0
- package/src/db.mjs +384 -0
- package/src/dream.mjs +97 -0
- package/src/editor.mjs +198 -0
- package/src/export.mjs +132 -0
- package/src/guard.mjs +121 -0
- package/src/guides.mjs +86 -0
- package/src/herdr.mjs +117 -0
- package/src/hooks.mjs +270 -0
- package/src/images.mjs +89 -0
- package/src/jobs.mjs +1184 -0
- package/src/jobtools.mjs +82 -0
- package/src/local-server.mjs +169 -0
- package/src/lock.mjs +45 -0
- package/src/loop.mjs +838 -0
- package/src/mcp.mjs +604 -0
- package/src/memory.mjs +400 -0
- package/src/model.mjs +270 -0
- package/src/page.html +304 -0
- package/src/page.mjs +135 -0
- package/src/paths.mjs +33 -0
- package/src/prime.mjs +177 -0
- package/src/projects.mjs +232 -0
- package/src/recall.mjs +45 -0
- package/src/redact.mjs +173 -0
- package/src/render.mjs +45 -0
- package/src/route.mjs +287 -0
- package/src/sandbox.mjs +173 -0
- package/src/scan.mjs +204 -0
- package/src/scribe.mjs +349 -0
- package/src/sessions.mjs +371 -0
- package/src/setup.mjs +528 -0
- package/src/sqlite.mjs +66 -0
- package/src/text.mjs +97 -0
- package/src/tools.mjs +987 -0
- package/src/transcript.mjs +106 -0
- package/src/tty.mjs +529 -0
- package/src/ui.mjs +1363 -0
- package/src/verify.mjs +369 -0
- package/src/web.mjs +49 -0
- package/src/workflows.mjs +270 -0
- package/src/worktree.mjs +128 -0
package/src/cli.mjs
ADDED
|
@@ -0,0 +1,815 @@
|
|
|
1
|
+
import { closeSync, existsSync, fstatSync, openSync, readFileSync, readSync } from 'node:fs';
|
|
2
|
+
import { StringDecoder } from 'node:string_decoder';
|
|
3
|
+
import { createInterface } from 'node:readline';
|
|
4
|
+
import { applyOps } from './apply.mjs';
|
|
5
|
+
import { card } from './card.mjs';
|
|
6
|
+
import { discoverModels, knownModel, MODEL_IDS, modelLines, setModel } from './catalog.mjs';
|
|
7
|
+
import { openDb } from './db.mjs';
|
|
8
|
+
import { dreamStatus, runDream } from './dream.mjs';
|
|
9
|
+
import { backup, exportJson, exportMarkdown, purgeFromBackups } from './export.mjs';
|
|
10
|
+
import { resolveAnthropicCredential } from './auth.mjs';
|
|
11
|
+
import { chat, jobPrinter } from './chat.mjs';
|
|
12
|
+
import { costLines } from './cost.mjs';
|
|
13
|
+
import { closeJobTab, reportAgent, runHerdr } from './herdr.mjs';
|
|
14
|
+
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
|
+
import * as jobs from './jobs.mjs';
|
|
18
|
+
import * as memory from './memory.mjs';
|
|
19
|
+
import { UsageError } from './memory.mjs';
|
|
20
|
+
import { openInBrowser, servePage } from './page.mjs';
|
|
21
|
+
import { prime } from './prime.mjs';
|
|
22
|
+
import * as projects from './projects.mjs';
|
|
23
|
+
import { detail, historyLine, line, scopeLabel } from './render.mjs';
|
|
24
|
+
import { buildBundle, modelStats, outcomeLines, runScribe, scribeStatus } from './scribe.mjs';
|
|
25
|
+
import { findSaved, searchTurns, taskEndedNudge } from './sessions.mjs';
|
|
26
|
+
import { overlap } from './text.mjs';
|
|
27
|
+
import { CHAT_EFFORTS, config, doctor, positiveInteger, setup } from './setup.mjs';
|
|
28
|
+
import { colourEnabled, safeForTerminal, styles } from './tty.mjs';
|
|
29
|
+
import { ftsQuery } from './text.mjs';
|
|
30
|
+
import { verdictLines } from './verify.mjs';
|
|
31
|
+
|
|
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]]
|
|
55
|
+
|
|
56
|
+
Scope is global plus --project; other projects stay hidden without --everywhere.
|
|
57
|
+
`;
|
|
58
|
+
|
|
59
|
+
const LEARN_USAGE = `sumo learn "<short title>" --cue "<the action, in plain words: create a PR>" [--gate '<regex>'] [--project S] <<'EOF'
|
|
60
|
+
1. first step
|
|
61
|
+
2. second step
|
|
62
|
+
EOF
|
|
63
|
+
(the steps come on stdin, or from --from-file <path>.
|
|
64
|
+
--cue brings the steps in with the user's message when they ask for the thing.
|
|
65
|
+
--gate a regular expression over the shell command; a match waits until the steps have been shown,
|
|
66
|
+
e.g. --gate 'gh(-axi)? pr create|glab mr create'. Without it, the cue's words are matched.)`;
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Shown by `sumo <command> --help` and whenever a command is called wrongly. An agent's first
|
|
70
|
+
* guess at a command is often wrong; the reply has to be enough to get the second one right.
|
|
71
|
+
*/
|
|
72
|
+
const USAGE = {
|
|
73
|
+
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)',
|
|
75
|
+
add: `sumo add preference|fact|decision|gotcha "<one sentence>" [--project S] [--topic T] [--pin] [--supersedes ID] [--observed]
|
|
76
|
+
a workflow (steps to repeat) is saved with sumo learn instead:
|
|
77
|
+
${LEARN_USAGE}`,
|
|
78
|
+
learn: LEARN_USAGE,
|
|
79
|
+
show: 'sumo show <id>',
|
|
80
|
+
history: 'sumo history <id>',
|
|
81
|
+
supersede: 'sumo supersede <old-id> <new-id>',
|
|
82
|
+
gate: "sumo gate <workflow-id> '<regex over the shell command>' | sumo gate <workflow-id> off",
|
|
83
|
+
forget: 'sumo forget <id> [--purge]',
|
|
84
|
+
confirm: 'sumo confirm <id>',
|
|
85
|
+
reject: 'sumo reject <id>',
|
|
86
|
+
memory: 'sumo memory (serves the page on this machine and opens it; Ctrl-C stops it)',
|
|
87
|
+
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)`,
|
|
89
|
+
job: `sumo job new --project S --title T [--agent scout|worker|reviewer] (task on stdin)
|
|
90
|
+
[--guide fix|feature|review|none] carry guides/<name>.md into the brief (unsaid: what the title and goal ask for)
|
|
91
|
+
[--reviews <id>] reviewer: judge that job's change (default: what is uncommitted)
|
|
92
|
+
[--tests-may-change] worker: this task is allowed to edit tests that already exist
|
|
93
|
+
[--attempts 2|3] worker: that many attempts, each in a worktree of its own; the best verified one is kept
|
|
94
|
+
sumo job brief|show|abandon <id>
|
|
95
|
+
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)
|
|
97
|
+
sumo job watch <id> what a job running in the chat is doing, as it does it (a Herdr tab shows this)
|
|
98
|
+
sumo job note|ask|answer|tell <id> (text on stdin; tell: a message a running job reads next)
|
|
99
|
+
sumo job baseline <id> the project's checks, before the work
|
|
100
|
+
sumo job verify <id> the same checks now, judged against the baseline
|
|
101
|
+
sumo job changes <id> everything the job changed, as one file
|
|
102
|
+
sumo job finish <id> --status DONE|FAILED [--accept "<why>"] (report on stdin)
|
|
103
|
+
sumo job retry <id> a failed job, or a done one reviewed with important >= 3, routed afresh
|
|
104
|
+
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]`,
|
|
106
|
+
prime: 'sumo prime [--budget N]',
|
|
107
|
+
scribe: 'sumo scribe run|show|status|stats',
|
|
108
|
+
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
|
+
apply: 'sumo apply <ops.json> [--source scribe|dream]',
|
|
111
|
+
export: 'sumo export [--json]',
|
|
112
|
+
backup: 'sumo backup',
|
|
113
|
+
models: `sumo models every model Sumo knows: on or off, its API id, and why
|
|
114
|
+
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
|
+
sumo models enable|disable <name>`,
|
|
116
|
+
mcp: `sumo mcp every configured server: where it is, its tools or why it failed, what may run unasked
|
|
117
|
+
sumo mcp add <name> [--env K=V]... -- <command> [args...] a server run as a process (stdio)
|
|
118
|
+
sumo mcp add <name> --url <url> [--header K=V]... a server reached over HTTP
|
|
119
|
+
\${NAME} in a value is filled from the shell when the server starts: the file never holds a token
|
|
120
|
+
sumo mcp remove <name>
|
|
121
|
+
sumo mcp tools <name> the server's tools, one a line
|
|
122
|
+
sumo mcp allow <name> <tool>|all let it run without asking sumo mcp revoke <name> <tool>|all`,
|
|
123
|
+
setup: 'sumo setup [--bin-dir DIR] [--no-link] [--model-source URL] [--no-model]',
|
|
124
|
+
doctor: 'sumo doctor',
|
|
125
|
+
config: 'sumo config [key [value]]',
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
const ADDABLE = ['preference', 'fact', 'decision', 'gotcha'];
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Who runs this command: the model's shell carries SUMO_TOOL, a job's SUMO_JOB too. Under either, what only the user does is
|
|
132
|
+
* refused — the allow list, the switches and the configuration — and a job writes no memory at all. The chat may still remember
|
|
133
|
+
* for the user, held to what the user typed: a statement none of their recent words say is kept unconfirmed, for them to say yes to.
|
|
134
|
+
*/
|
|
135
|
+
const fromTool = () => Boolean(process.env.SUMO_TOOL || process.env.SUMO_JOB);
|
|
136
|
+
const fromJob = () => process.env.SUMO_JOB || null;
|
|
137
|
+
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
|
+
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
|
+
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. */
|
|
143
|
+
function saidByUser(db, text) {
|
|
144
|
+
return db
|
|
145
|
+
.prepare('SELECT text FROM user_turns ORDER BY id DESC LIMIT ?')
|
|
146
|
+
.all(RECENT_TURNS)
|
|
147
|
+
.some((turn) => overlap(text, turn.text) >= SAID_BY_USER);
|
|
148
|
+
}
|
|
149
|
+
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
|
+
/** The docs say "workflow", the store says "procedure"; whoever types either means the same thing. */
|
|
151
|
+
const WORKFLOW_NAMES = ['workflow', 'procedure'];
|
|
152
|
+
|
|
153
|
+
/** value: flags that take an argument; bool: flags that don't. Anything else is a typo and says so. */
|
|
154
|
+
const COMMANDS = {
|
|
155
|
+
search: { value: ['project', 'type', 'n', 'since', 'before'], bool: ['everywhere', 'all', 'turns'], run: runSearch },
|
|
156
|
+
add: { value: ['project', 'topic', 'supersedes'], bool: ['pin', 'observed'], run: runAdd },
|
|
157
|
+
learn: { value: ['project', 'cue', 'gate', 'from-file'], bool: [], run: runLearn },
|
|
158
|
+
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 },
|
|
175
|
+
models: { value: [], bool: [], run: runModels },
|
|
176
|
+
mcp: { value: ['url'], multi: ['env', 'header'], bool: [], run: runMcp },
|
|
177
|
+
};
|
|
178
|
+
|
|
179
|
+
/** Memory a job's shell never writes: it reports, and the user or the chat decides. */
|
|
180
|
+
const JOB_NEVER = ['add', 'learn', 'gate', 'supersede', 'forget', 'confirm', 'reject', 'apply'];
|
|
181
|
+
/** What the model's shell never changes, by command and the subcommands that change something. */
|
|
182
|
+
const OWNER_COMMANDS = new Map([
|
|
183
|
+
['mcp', (args) => ['add', 'remove', 'allow', 'revoke'].includes(args[0])],
|
|
184
|
+
['models', (args) => ['enable', 'disable', 'discover'].includes(args[0])],
|
|
185
|
+
]);
|
|
186
|
+
|
|
187
|
+
function parse(argv, spec) {
|
|
188
|
+
const args = [];
|
|
189
|
+
const flags = {};
|
|
190
|
+
const nameOf = (token) => (token.startsWith('--') ? token.slice(2) : token === '-n' ? 'n' : null);
|
|
191
|
+
// 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));
|
|
193
|
+
for (let i = 0; i < argv.length; i++) {
|
|
194
|
+
const token = argv[i];
|
|
195
|
+
if (token === '--') {
|
|
196
|
+
args.push(...argv.slice(i + 1));
|
|
197
|
+
break;
|
|
198
|
+
}
|
|
199
|
+
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 --`);
|
|
202
|
+
if (name === null) {
|
|
203
|
+
args.push(token);
|
|
204
|
+
} else if (spec.bool.includes(name)) {
|
|
205
|
+
flags[name] = true;
|
|
206
|
+
} 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];
|
|
209
|
+
if (spec.multi?.includes(name)) (flags[name] ??= []).push(value);
|
|
210
|
+
else flags[name] = value;
|
|
211
|
+
} else {
|
|
212
|
+
throw new UsageError(`unknown option ${token}`);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
return { args, flags };
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function need(args, count, command) {
|
|
219
|
+
if (args.length < count) throw new UsageError(`usage: ${USAGE[command]}`);
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
const DAY_MS = 86_400_000;
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* A day as typed after --since or --before: 2026-10-01 is the start of that day in UTC, the day every date memory shows
|
|
226
|
+
* is in. Where `back` allows it, 7d is that many days back from now.
|
|
227
|
+
*/
|
|
228
|
+
function dayFlag(raw, flag, { back = false } = {}) {
|
|
229
|
+
if (raw === undefined) return undefined;
|
|
230
|
+
const days = back ? /^(\d+)d$/.exec(raw) : null;
|
|
231
|
+
const time = days && Number(days[1]) > 0 ? new Date(Date.now() - Number(days[1]) * DAY_MS) : null;
|
|
232
|
+
if (time && !Number.isNaN(time.getTime())) return time.toISOString();
|
|
233
|
+
// A day that does not exist, 2026-02-30, would roll over into the next month: it is a typo, and said as one.
|
|
234
|
+
const day = /^\d{4}-\d{2}-\d{2}$/.test(raw) ? new Date(`${raw}T00:00:00.000Z`) : null;
|
|
235
|
+
if (day && !Number.isNaN(day.getTime()) && day.toISOString().startsWith(raw)) return day.toISOString();
|
|
236
|
+
throw new UsageError(`${flag} takes a day (YYYY-MM-DD)${back ? ' or a number of days back (7d)' : ''}, not "${raw}"`);
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function runSearch(db, { args, flags }) {
|
|
240
|
+
need(args, 1, 'search');
|
|
241
|
+
const limit = flags.n === undefined ? undefined : positiveInteger(flags.n, '-n needs a positive number');
|
|
242
|
+
const since = dayFlag(flags.since, '--since', { back: true });
|
|
243
|
+
const before = dayFlag(flags.before, '--before');
|
|
244
|
+
|
|
245
|
+
if (flags.turns) {
|
|
246
|
+
if (since || before) throw new UsageError('--since and --before hold memories to a time, not what the user typed — leave out --turns, or the dates');
|
|
247
|
+
const match = ftsQuery(args.join(' '));
|
|
248
|
+
if (!match) throw new UsageError('nothing to search for');
|
|
249
|
+
const turns = searchTurns(db, match, limit);
|
|
250
|
+
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
|
+
}
|
|
252
|
+
|
|
253
|
+
const { results, elsewhere } = memory.search(db, args.join(' '), {
|
|
254
|
+
project: flags.project,
|
|
255
|
+
type: WORKFLOW_NAMES.includes(flags.type) ? 'procedure' : flags.type,
|
|
256
|
+
everywhere: flags.everywhere,
|
|
257
|
+
all: flags.all,
|
|
258
|
+
since,
|
|
259
|
+
before,
|
|
260
|
+
limit,
|
|
261
|
+
});
|
|
262
|
+
|
|
263
|
+
// An explicit "nothing" is an answer: it is what lets an agent say
|
|
264
|
+
// "not in memory" instead of guessing.
|
|
265
|
+
const out = results.length > 0 ? results.map(line) : [`nothing in memory for: ${args.join(' ')}`];
|
|
266
|
+
const others = Object.entries(elsewhere);
|
|
267
|
+
if (others.length > 0) {
|
|
268
|
+
const where = others.map(([scope, n]) => `${scopeLabel(scope)} (${n})`).join(', ');
|
|
269
|
+
out.push(`matches in other projects, not shown: ${where} — add --project <name> or --everywhere`);
|
|
270
|
+
}
|
|
271
|
+
return out;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
function savedLines({ memory: saved, similar, redacted }) {
|
|
275
|
+
const out = [`saved ${line(saved)}`];
|
|
276
|
+
if (redacted > 0) out.push(`redacted ${redacted} secret-looking value${redacted === 1 ? '' : 's'} before storing`);
|
|
277
|
+
if (similar.length > 0) {
|
|
278
|
+
out.push(`similar — if m${saved.id} replaces one: sumo supersede <old-id> m${saved.id}`);
|
|
279
|
+
for (const m of similar) out.push(` ${line(m)}`);
|
|
280
|
+
}
|
|
281
|
+
return out;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
function runAdd(db, { args, flags }) {
|
|
285
|
+
need(args, 2, 'add');
|
|
286
|
+
if (fromJob()) throw new UsageError(jobWrites());
|
|
287
|
+
const [type, ...text] = args;
|
|
288
|
+
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
|
+
if (!ADDABLE.includes(type)) throw new UsageError(`unknown type "${type}" — one of: ${ADDABLE.join(', ')} (for a workflow: sumo learn)`);
|
|
290
|
+
const body = text.join(' ');
|
|
291
|
+
// From the model's shell, the user's word is checked against the user's words: an inferred memory waits unconfirmed.
|
|
292
|
+
const held = fromTool() && !saidByUser(db, body);
|
|
293
|
+
const saved = memory.add(db, {
|
|
294
|
+
type,
|
|
295
|
+
body,
|
|
296
|
+
project: flags.project,
|
|
297
|
+
topic: flags.topic,
|
|
298
|
+
pin: flags.pin,
|
|
299
|
+
supersedes: flags.supersedes === undefined ? undefined : memory.parseId(flags.supersedes),
|
|
300
|
+
provenance: held ? 'inferred' : flags.observed ? 'observed' : 'stated',
|
|
301
|
+
});
|
|
302
|
+
return savedLines(saved).concat(held ? [HELD(saved.memory.id)] : []);
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
function runLearn(db, { args, flags }) {
|
|
306
|
+
need(args, 1, 'learn');
|
|
307
|
+
if (fromJob()) throw new UsageError(jobWrites());
|
|
308
|
+
const body = flags['from-file'] ? readFileSync(flags['from-file'], 'utf8') : process.stdin.isTTY ? '' : readFileSync(0, 'utf8');
|
|
309
|
+
if (!body.trim()) throw new UsageError('no steps given — pipe them in, or use --from-file <path>');
|
|
310
|
+
const title = args.join(' ');
|
|
311
|
+
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' });
|
|
313
|
+
return savedLines(saved).concat(flags.gate ? [`gates shell commands matching: ${flags.gate}`] : [], held ? [HELD(saved.memory.id)] : []);
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
function runGate(db, { args }) {
|
|
317
|
+
need(args, 2, 'gate');
|
|
318
|
+
const saved = memory.setGate(db, memory.parseId(args[0]), args[1] === 'off' ? null : args.slice(1).join(' '));
|
|
319
|
+
return [saved.gate ? `${line(saved)}\ngates shell commands matching: ${saved.gate}` : `${line(saved)}\nno gate — its cue words are matched instead`];
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
function runSupersede(db, { args }) {
|
|
323
|
+
need(args, 2, 'supersede');
|
|
324
|
+
const old = memory.supersede(db, memory.parseId(args[0]), memory.parseId(args[1]));
|
|
325
|
+
return [`superseded ${line(old)}`];
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
function runForget(db, { args, flags }) {
|
|
329
|
+
need(args, 1, 'forget');
|
|
330
|
+
const gone = memory.forget(db, memory.parseId(args[0]), { purge: flags.purge });
|
|
331
|
+
if (!flags.purge) return [`forgot ${line(gone)}`];
|
|
332
|
+
const { cleaned, failed } = purgeFromBackups(gone);
|
|
333
|
+
const copies = cleaned > 0 ? `, and from ${cleaned} backup${cleaned === 1 ? '' : 's'}` : '';
|
|
334
|
+
const lines = [gone.source_turn !== null ? `purged m${gone.id} — erased, not recoverable, with the sentence it came from${copies}` : `purged m${gone.id} — erased, not recoverable${copies}; no sentence of the user's was tied to it — sumo search --turns finds one if it is there`];
|
|
335
|
+
if (failed.length > 0) lines.push(`still in ${failed.length} backup${failed.length === 1 ? '' : 's'} that could not be cleaned — delete ${failed.length === 1 ? 'it' : 'them'} by hand: ${failed.join(' ')}`);
|
|
336
|
+
return lines;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
function runProject(db, { args, flags }) {
|
|
340
|
+
const [sub, ...rest] = args;
|
|
341
|
+
switch (sub) {
|
|
342
|
+
case 'add': {
|
|
343
|
+
need(rest, 1, 'project');
|
|
344
|
+
const { project, created, restored, changes } = projects.addProject(db, rest[0], { slug: flags.slug, aliases: flags.alias });
|
|
345
|
+
const rescanned = `rescanned (${changes.added} new, ${changes.updated} changed, ${changes.removed} gone)`;
|
|
346
|
+
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)];
|
|
348
|
+
}
|
|
349
|
+
case 'show':
|
|
350
|
+
need(rest, 1, 'project');
|
|
351
|
+
return [card(db, rest[0])];
|
|
352
|
+
case 'list': {
|
|
353
|
+
const all = projects.listProjects(db, { includeArchived: flags.all });
|
|
354
|
+
if (all.length === 0) return ['no projects registered — sumo project add <path>'];
|
|
355
|
+
return all.map((p) => {
|
|
356
|
+
const aliases = projects.aliasesOf(db, p.slug);
|
|
357
|
+
return `${p.slug} ${p.path}${aliases.length ? ` (also: ${aliases.join(', ')})` : ''}${p.status === 'archived' ? ' [archived]' : ''}`;
|
|
358
|
+
});
|
|
359
|
+
}
|
|
360
|
+
case 'rescan': {
|
|
361
|
+
need(rest, 1, 'project');
|
|
362
|
+
const changes = projects.rescan(db, rest[0]);
|
|
363
|
+
return [`rescanned: ${changes.added} new, ${changes.updated} changed, ${changes.removed} gone`, card(db, rest[0])];
|
|
364
|
+
}
|
|
365
|
+
case 'alias': {
|
|
366
|
+
need(rest, 2, 'project');
|
|
367
|
+
const project = projects.getProject(db, rest[0]);
|
|
368
|
+
return [`${projects.addAlias(db, project.slug, rest[1])} now means ${project.slug}`];
|
|
369
|
+
}
|
|
370
|
+
case 'archive':
|
|
371
|
+
need(rest, 1, 'project');
|
|
372
|
+
return [`archived ${projects.archive(db, rest[0])} — its memories are kept, it just stops coming up`];
|
|
373
|
+
default:
|
|
374
|
+
throw new UsageError(`usage: ${USAGE.project}`);
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/** Long text comes on stdin so one allow rule (`Bash(sumo *)`) covers every job command; --from-file is the fallback. */
|
|
379
|
+
function stdinText(flags) {
|
|
380
|
+
if (flags['from-file']) return readFileSync(flags['from-file'], 'utf8');
|
|
381
|
+
return process.stdin.isTTY ? '' : readFileSync(0, 'utf8');
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/** The lines `new` and `retry` both print: the job, its route, and exactly what to start it with. Several attempts are one line each. */
|
|
385
|
+
function createdLines(job, warnings, attempts = null) {
|
|
386
|
+
if (attempts) {
|
|
387
|
+
return [
|
|
388
|
+
...attempts.map((a) => `created ${jobs.jobLine(a)}`),
|
|
389
|
+
...warnings,
|
|
390
|
+
`route: ${job.model}/${job.effort} — ${job.route_reason}`,
|
|
391
|
+
`run each: ${attempts.map((a) => `sumo job run ${a.id}`).join(' · ')} — once all have closed, the best verified one is brought back`,
|
|
392
|
+
];
|
|
393
|
+
}
|
|
394
|
+
return [
|
|
395
|
+
`created ${jobs.jobLine(job)}`,
|
|
396
|
+
...warnings,
|
|
397
|
+
`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}`,
|
|
399
|
+
];
|
|
400
|
+
}
|
|
401
|
+
|
|
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) {
|
|
404
|
+
print?.(job);
|
|
405
|
+
reportAgent(runHerdr, process.env, { job, state: 'working', message: job.title });
|
|
406
|
+
if (process.stdin.isTTY) {
|
|
407
|
+
const typed = createInterface({ input: process.stdin });
|
|
408
|
+
typed.on('line', (line) => {
|
|
409
|
+
if (!line.trim()) return;
|
|
410
|
+
try {
|
|
411
|
+
jobs.tell(db, job.id, line);
|
|
412
|
+
} catch (cause) {
|
|
413
|
+
// A job that has closed itself can still be saying its last words; a line it cannot take is said back, not thrown at the run.
|
|
414
|
+
process.stdout.write(`${cause.message}\n`);
|
|
415
|
+
}
|
|
416
|
+
});
|
|
417
|
+
process.stdin.unref();
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
function tabEnds(job, status) {
|
|
421
|
+
process.stdin.pause();
|
|
422
|
+
reportAgent(runHerdr, process.env, { job, state: job.status === 'needs_input' ? 'blocked' : 'idle', message: status });
|
|
423
|
+
closeJobTab(runHerdr, process.env, job);
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
/**
|
|
427
|
+
* `sumo job watch <id>`: what a job running in the chat is doing, as it does it — what its Herdr tab shows, and
|
|
428
|
+
* what any terminal can show. A line typed here is said to the job. Ends with how the run ended.
|
|
429
|
+
*/
|
|
430
|
+
async function watchJob(db, id) {
|
|
431
|
+
const job = jobs.getJob(db, id);
|
|
432
|
+
if (!existsSync(jobs.liveFile(id)) && job.status !== 'running' && job.status !== 'needs_input') return [`j${id} is ${job.status} — nothing is running`];
|
|
433
|
+
// The record opens with the job's own line, so nothing is printed for it here.
|
|
434
|
+
tabBegins(db, job);
|
|
435
|
+
let at = 0;
|
|
436
|
+
// A character split across two reads is held until its other half arrives.
|
|
437
|
+
const decoder = new StringDecoder('utf8');
|
|
438
|
+
for (;;) {
|
|
439
|
+
// Looked at before reading, so nothing written before the end is missed.
|
|
440
|
+
const ended = existsSync(jobs.endFile(id));
|
|
441
|
+
at = copyFrom(jobs.liveFile(id), at, decoder);
|
|
442
|
+
if (ended) break;
|
|
443
|
+
await new Promise((r) => setTimeout(r, 250));
|
|
444
|
+
}
|
|
445
|
+
const lines = safeForTerminal(readFileSync(jobs.endFile(id), 'utf8')).trimEnd().split('\n');
|
|
446
|
+
tabEnds(jobs.getJob(db, id), lines[0]);
|
|
447
|
+
return lines;
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/** Writes what a file gained since `at`, and says where it ends now. A file not there yet has gained nothing. */
|
|
451
|
+
function copyFrom(file, at, decoder) {
|
|
452
|
+
let fd;
|
|
453
|
+
try {
|
|
454
|
+
fd = openSync(file, 'r');
|
|
455
|
+
} catch {
|
|
456
|
+
return at;
|
|
457
|
+
}
|
|
458
|
+
try {
|
|
459
|
+
const size = fstatSync(fd).size;
|
|
460
|
+
// A run that began again starts its record afresh: read it from the top.
|
|
461
|
+
const from = size < at ? 0 : at;
|
|
462
|
+
if (size > from) {
|
|
463
|
+
const chunk = Buffer.alloc(size - from);
|
|
464
|
+
readSync(fd, chunk, 0, chunk.length, from);
|
|
465
|
+
// What a job wrote is shown, never obeyed: colours pass, every other escape is dropped.
|
|
466
|
+
process.stdout.write(safeForTerminal(decoder.write(chunk)));
|
|
467
|
+
}
|
|
468
|
+
return size;
|
|
469
|
+
} finally {
|
|
470
|
+
closeSync(fd);
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
/** A job closed from a shell has its worktree settled here — unless it is the job's own shell, whose run settles it once the run ends. */
|
|
475
|
+
const settleHere = (db, id) => (process.env.SUMO_JOB === String(id) ? [] : jobs.settle(db, id));
|
|
476
|
+
|
|
477
|
+
async function runJob(db, { args, flags }) {
|
|
478
|
+
const [sub, rawId] = args;
|
|
479
|
+
if (sub === 'new') {
|
|
480
|
+
if (!flags.project) throw new UsageError(`usage: ${USAGE.job}`);
|
|
481
|
+
const { job, jobs: attempts, warnings } = await jobs.newJob(db, {
|
|
482
|
+
project: flags.project,
|
|
483
|
+
title: flags.title,
|
|
484
|
+
agent: flags.agent,
|
|
485
|
+
task: stdinText(flags),
|
|
486
|
+
guide: flags.guide,
|
|
487
|
+
reviews: flags.reviews === undefined ? undefined : jobs.parseJobId(flags.reviews),
|
|
488
|
+
testsMayChange: Boolean(flags['tests-may-change']),
|
|
489
|
+
attempts: flags.attempts === undefined ? 1 : Number(flags.attempts),
|
|
490
|
+
});
|
|
491
|
+
return createdLines(job, warnings, attempts);
|
|
492
|
+
}
|
|
493
|
+
if (sub === 'list') {
|
|
494
|
+
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`] : [])];
|
|
497
|
+
}
|
|
498
|
+
if (sub === 'stats') {
|
|
499
|
+
return jobs.stats(db, { project: flags.project });
|
|
500
|
+
}
|
|
501
|
+
if (sub === 'retry') {
|
|
502
|
+
const { job, warnings } = await jobs.retry(db, jobs.parseJobId(rawId));
|
|
503
|
+
return createdLines(job, warnings);
|
|
504
|
+
}
|
|
505
|
+
if (!['brief', 'note', 'ask', 'answer', 'tell', 'finish', 'show', 'abandon', 'baseline', 'verify', 'changes', 'run', 'watch'].includes(sub)) {
|
|
506
|
+
throw new UsageError(`usage: ${USAGE.job}`);
|
|
507
|
+
}
|
|
508
|
+
if (rawId === undefined) throw new UsageError(`sumo job ${sub} needs a job id, like j17 — sumo job list shows them`);
|
|
509
|
+
// 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
|
+
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.`);
|
|
512
|
+
}
|
|
513
|
+
const id = jobs.parseJobId(rawId);
|
|
514
|
+
switch (sub) {
|
|
515
|
+
case 'brief':
|
|
516
|
+
return [jobs.brief(db, id)];
|
|
517
|
+
case 'run': {
|
|
518
|
+
// The job runs here, in Sumo's own loop, on the route the router chose; it closes itself the way its brief says.
|
|
519
|
+
// On a terminal the work is shown as it happens — the lines a Herdr pane shows; piped, only how it ended.
|
|
520
|
+
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`);
|
|
522
|
+
}
|
|
523
|
+
// 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
|
+
const watch = process.stdout.isTTY ? jobPrinter((t) => process.stdout.write(safeForTerminal(t)), styles(colourEnabled())) : {};
|
|
525
|
+
// 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.
|
|
526
|
+
const stop = new AbortController();
|
|
527
|
+
const interrupt = () => stop.abort();
|
|
528
|
+
process.once('SIGINT', interrupt);
|
|
529
|
+
// What follows the job unasked — a retry one step up of a first attempt that failed, a review of risky work done — runs
|
|
530
|
+
// here after it, the same way, and each is said in turn. The job's tab is the first one's: what is typed there goes to it.
|
|
531
|
+
let ran;
|
|
532
|
+
let last;
|
|
533
|
+
try {
|
|
534
|
+
ran = await jobs.runFollowed(
|
|
535
|
+
db,
|
|
536
|
+
id,
|
|
537
|
+
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) } : {}) });
|
|
539
|
+
return [...warnings, ...runLines(last), ...last.settled];
|
|
540
|
+
},
|
|
541
|
+
{ signal: stop.signal },
|
|
542
|
+
);
|
|
543
|
+
} finally {
|
|
544
|
+
process.off('SIGINT', interrupt);
|
|
545
|
+
}
|
|
546
|
+
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]);
|
|
548
|
+
return lines;
|
|
549
|
+
}
|
|
550
|
+
case 'show':
|
|
551
|
+
return [jobs.show(db, id)];
|
|
552
|
+
case 'watch':
|
|
553
|
+
return watchJob(db, id);
|
|
554
|
+
case 'note':
|
|
555
|
+
jobs.note(db, id, stdinText(flags));
|
|
556
|
+
return [`noted on j${id}`];
|
|
557
|
+
case 'ask':
|
|
558
|
+
jobs.ask(db, id, stdinText(flags));
|
|
559
|
+
return [`STATUS: NEEDS_INPUT — j${id}. Stop now; you will be resumed with the answer.`];
|
|
560
|
+
case 'answer':
|
|
561
|
+
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)`];
|
|
563
|
+
case 'tell':
|
|
564
|
+
jobs.tell(db, id, stdinText(flags));
|
|
565
|
+
return [`told j${id} — it reads it with its next request`];
|
|
566
|
+
case 'abandon':
|
|
567
|
+
jobs.abandon(db, id);
|
|
568
|
+
// A task just ended: if the session is already big, this is the cheapest moment to start a fresh one.
|
|
569
|
+
return [`abandoned j${id}`, ...(await settleHere(db, id)), ...[taskEndedNudge(db)].filter(Boolean)];
|
|
570
|
+
case 'baseline':
|
|
571
|
+
return jobs.baseline(db, id);
|
|
572
|
+
case 'verify': {
|
|
573
|
+
const verdict = jobs.verifyJob(db, id);
|
|
574
|
+
return [verdict.ok ? `j${id} would be accepted as DONE:` : `j${id} would be REFUSED as DONE:`, ...verdictLines(verdict).map((l) => ` ${l}`)];
|
|
575
|
+
}
|
|
576
|
+
case 'changes': {
|
|
577
|
+
const { file, files } = jobs.changes(db, id);
|
|
578
|
+
return [`${files} file${files === 1 ? '' : 's'} changed — ${file}`];
|
|
579
|
+
}
|
|
580
|
+
default: {
|
|
581
|
+
// Taking work unverified is the user's call: never granted from inside a job's own shell, whatever the command looked like.
|
|
582
|
+
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.`);
|
|
584
|
+
}
|
|
585
|
+
const { job, learned, verdict, unverified } = jobs.finish(db, id, { status: String(flags.status ?? '').toUpperCase(), report: stdinText(flags), accept: flags.accept });
|
|
586
|
+
// A worker's plain DONE means the checks agreed; the verdict is in the report. Only the exceptions are said here.
|
|
587
|
+
return [
|
|
588
|
+
`STATUS: ${job.status === 'done' ? 'DONE' : 'FAILED'}${unverified ? ' (UNVERIFIED — taken without running the checks)' : ''} — j${id}`,
|
|
589
|
+
...(verdict?.flags ?? []).map((f) => ` look at: ${f}`),
|
|
590
|
+
...learned.applied.map((l) => ` ${l}`),
|
|
591
|
+
...(await settleHere(db, id)),
|
|
592
|
+
...[taskEndedNudge(db)].filter(Boolean),
|
|
593
|
+
];
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
/** A pass's lines, said where they always were; one that failed also exits 1, so a script or a shell can tell. */
|
|
599
|
+
function passLines(outcome) {
|
|
600
|
+
const lines = outcomeLines(outcome);
|
|
601
|
+
return outcome.ok === false && !outcome.skipped ? Object.assign(lines, { exitCode: 1 }) : lines;
|
|
602
|
+
}
|
|
603
|
+
|
|
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}`);
|
|
611
|
+
}
|
|
612
|
+
|
|
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}`);
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
/** Runs a model's proposed operations through the same validator the automatic passes use. */
|
|
620
|
+
function runApply(db, { args, flags }) {
|
|
621
|
+
need(args, 1, 'apply');
|
|
622
|
+
const source = flags.source ?? 'scribe';
|
|
623
|
+
if (source !== 'scribe' && source !== 'dream') throw new UsageError('--source is scribe or dream');
|
|
624
|
+
let ops;
|
|
625
|
+
try {
|
|
626
|
+
ops = JSON.parse(readFileSync(args[0], 'utf8')).ops;
|
|
627
|
+
} catch (cause) {
|
|
628
|
+
throw new UsageError(`${args[0]} is not a JSON file of operations ({"ops": [...]}): ${cause.message.split('\n')[0]}`);
|
|
629
|
+
}
|
|
630
|
+
const ids = (Array.isArray(ops) ? ops : []).map((op) => Number(op?.turn)).filter(Number.isInteger);
|
|
631
|
+
const rows = ids.length > 0 ? db.prepare(`SELECT * FROM user_turns WHERE id IN (${ids.map(() => '?').join(', ')})`).all(...ids) : [];
|
|
632
|
+
const { applied, dropped } = applyOps(db, ops, { source, turns: new Map(rows.map((t) => [t.id, t])), now: new Date().toISOString() });
|
|
633
|
+
return [...applied, ...dropped.map((l) => `dropped — ${l}`), ...(applied.length + dropped.length === 0 ? ['no operations'] : [])];
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
/** Runs until Ctrl-C: the page is only there while someone is looking at it. */
|
|
637
|
+
async function runMemoryPage(db) {
|
|
638
|
+
const page = await servePage(db);
|
|
639
|
+
process.stdout.write(`your memory: ${page.url}\nCtrl-C to stop\n`);
|
|
640
|
+
openInBrowser(page.url);
|
|
641
|
+
await new Promise((resolve) => process.once('SIGINT', resolve));
|
|
642
|
+
await page.close();
|
|
643
|
+
return ['stopped'];
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
/** The models Sumo can run on, their switches, and the two ways the switches are set: by the API's answer, or by hand. */
|
|
647
|
+
async function runModels(db, { args }) {
|
|
648
|
+
const [sub, name] = args;
|
|
649
|
+
if (sub === undefined) return modelLines(db);
|
|
650
|
+
if (sub === 'discover') {
|
|
651
|
+
const result = await discoverModels(db);
|
|
652
|
+
if (!result.ok) throw new Error(`could not check the models — ${result.error}; nothing was changed`);
|
|
653
|
+
return modelLines(db);
|
|
654
|
+
}
|
|
655
|
+
if ((sub === 'enable' || sub === 'disable') && name !== undefined) {
|
|
656
|
+
setModel(db, name, sub === 'enable');
|
|
657
|
+
return modelLines(db, [name]);
|
|
658
|
+
}
|
|
659
|
+
throw new UsageError(`usage: ${USAGE.models}`);
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
/** `NAME=value` pairs from the command line, as an object. The values are stored as typed: `${NAME}` is filled from the shell when the server starts. */
|
|
663
|
+
function pairs(list = [], flag) {
|
|
664
|
+
return Object.fromEntries(
|
|
665
|
+
list.map((pair) => {
|
|
666
|
+
const at = pair.indexOf('=');
|
|
667
|
+
if (at < 1) throw new UsageError(`${flag} takes NAME=value, not "${pair}"`);
|
|
668
|
+
return [pair.slice(0, at), pair.slice(at + 1)];
|
|
669
|
+
}),
|
|
670
|
+
);
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
/** MCP servers: configured here, connected by every chat and job; what may run without asking is set here too. */
|
|
674
|
+
async function runMcp(db, { args, flags }) {
|
|
675
|
+
const [sub = 'list', name, ...rest] = args;
|
|
676
|
+
switch (sub) {
|
|
677
|
+
case 'list': {
|
|
678
|
+
const registry = await mcpReady();
|
|
679
|
+
try {
|
|
680
|
+
return mcpLines(registry);
|
|
681
|
+
} finally {
|
|
682
|
+
await closeMcp();
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
case 'add': {
|
|
686
|
+
if (!name) throw new UsageError(`usage: ${USAGE.mcp}`);
|
|
687
|
+
let spec;
|
|
688
|
+
if (flags.url) {
|
|
689
|
+
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') } : {}) };
|
|
691
|
+
} else if (rest.length > 0) {
|
|
692
|
+
spec = { command: rest[0], args: rest.slice(1), ...(flags.env ? { env: pairs(flags.env, '--env') } : {}) };
|
|
693
|
+
} else {
|
|
694
|
+
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
|
+
}
|
|
696
|
+
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`];
|
|
698
|
+
}
|
|
699
|
+
case 'remove':
|
|
700
|
+
if (!name) throw new UsageError(`usage: ${USAGE.mcp}`);
|
|
701
|
+
removeServer(name);
|
|
702
|
+
return [`removed ${name}`];
|
|
703
|
+
case 'tools': {
|
|
704
|
+
if (!name) throw new UsageError(`usage: ${USAGE.mcp}`);
|
|
705
|
+
const spec = readConfig().mcpServers[name];
|
|
706
|
+
if (!spec) throw new UsageError(`no MCP server called ${name} — sumo mcp lists them`);
|
|
707
|
+
const session = await connect(name, spec);
|
|
708
|
+
try {
|
|
709
|
+
if (session.tools.length === 0) return [`${name} offers no tools`];
|
|
710
|
+
const wide = Math.max(...session.tools.map((t) => t.name.length)) + 2;
|
|
711
|
+
return session.tools.map((t) => ` ${t.name.padEnd(wide)}${allowedBy(spec, t.name) ? '(allowed) ' : ''}${String(t.description ?? '').split('\n')[0]}`);
|
|
712
|
+
} finally {
|
|
713
|
+
await session.close();
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
case 'allow':
|
|
717
|
+
case 'revoke': {
|
|
718
|
+
const tool = rest[0];
|
|
719
|
+
if (!name || !tool) throw new UsageError(`usage: ${USAGE.mcp}`);
|
|
720
|
+
setAllow(name, tool, sub === 'allow');
|
|
721
|
+
if (tool === 'all') return [sub === 'allow' ? `${name}: every tool may run without asking` : `${name}: every call asks first`];
|
|
722
|
+
return [sub === 'allow' ? `${name}: ${tool} may run without asking` : `${name}: ${tool} asks first`];
|
|
723
|
+
}
|
|
724
|
+
default:
|
|
725
|
+
throw new UsageError(`usage: ${USAGE.mcp}`);
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
function runExport(db, { flags }) {
|
|
730
|
+
return [flags.json ? JSON.stringify(exportJson(db), null, 2) : exportMarkdown(db)];
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
function runBackup(db) {
|
|
734
|
+
const { file, pruned } = backup(db);
|
|
735
|
+
return [`backed up to ${file}${pruned > 0 ? ` (removed ${pruned} old)` : ''}`];
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
async function runDoctor() {
|
|
739
|
+
const checks = await doctor();
|
|
740
|
+
// On a terminal the mark is coloured, so a failure stands out of a column of oks; piped, it is the same words.
|
|
741
|
+
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
|
+
}
|
|
746
|
+
return checks.some((c) => !c.ok && !c.warn) ? 1 : 0;
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
export async function main(argv) {
|
|
750
|
+
const [command, ...rest] = argv;
|
|
751
|
+
try {
|
|
752
|
+
if (command === undefined || command === 'help' || command === '--help' || command === '-h') {
|
|
753
|
+
process.stdout.write(HELP);
|
|
754
|
+
return 0;
|
|
755
|
+
}
|
|
756
|
+
if (Object.hasOwn(USAGE, command) && (rest.includes('--help') || rest.includes('-h'))) {
|
|
757
|
+
process.stdout.write(`${USAGE[command]}\n`);
|
|
758
|
+
return 0;
|
|
759
|
+
}
|
|
760
|
+
if (command === 'setup') {
|
|
761
|
+
const { flags } = parse(rest, { value: ['bin-dir', 'model-source'], bool: ['no-link', 'no-model'] });
|
|
762
|
+
const lines = await setup({ binDir: flags['bin-dir'], link: !flags['no-link'], modelSource: flags['model-source'], noModel: !!flags['no-model'] });
|
|
763
|
+
process.stdout.write(`${lines.join('\n')}\n`);
|
|
764
|
+
return 0;
|
|
765
|
+
}
|
|
766
|
+
if (command === 'hook') {
|
|
767
|
+
// No usage errors, no exit codes, no stderr: an event that complains breaks the session it serves.
|
|
768
|
+
process.stdout.write(runHook(rest[0], process.stdin.isTTY ? '' : readFileSync(0, 'utf8')));
|
|
769
|
+
return 0;
|
|
770
|
+
}
|
|
771
|
+
if (command === 'chat') {
|
|
772
|
+
const { args: given, flags } = parse(rest, { value: ['model', 'effort'], bool: ['resume'] });
|
|
773
|
+
// `--resume` alone is the newest saved session; with an id, or the start of one, that session.
|
|
774
|
+
const resume = flags.resume ? (given[0] ?? 'last') : null;
|
|
775
|
+
// Said once, before the screen: past here every turn would fail the same way.
|
|
776
|
+
// A full API id is taken too (claude-opus-5-5), as the chat itself takes one.
|
|
777
|
+
if (flags.model !== undefined && flags.model !== 'auto' && !Object.values(MODEL_IDS).includes(flags.model)) knownModel(flags.model, ['auto']);
|
|
778
|
+
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');
|
|
780
|
+
const db = openDb();
|
|
781
|
+
try {
|
|
782
|
+
// A session that is not there to resume is said here too, before the screen.
|
|
783
|
+
if (resume !== null) findSaved(db, resume, { now: new Date().toISOString() });
|
|
784
|
+
return await chat(db, { model: flags.model, effort: flags.effort, resume });
|
|
785
|
+
} finally {
|
|
786
|
+
db.close();
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
if (command === 'doctor') return await runDoctor();
|
|
790
|
+
if (command === 'config') {
|
|
791
|
+
const { args } = parse(rest, { value: [], bool: [] });
|
|
792
|
+
if (args[1] !== undefined && fromTool()) throw new UsageError(OWNER_ONLY);
|
|
793
|
+
process.stdout.write(`${config(args[0], args[1]).join('\n')}\n`);
|
|
794
|
+
return 0;
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
// Own keys only: `sumo constructor` is not a command just because every object has one.
|
|
798
|
+
const spec = Object.hasOwn(COMMANDS, command) ? COMMANDS[command] : null;
|
|
799
|
+
if (!spec) throw new UsageError(`unknown command "${command}" — see: sumo help`);
|
|
800
|
+
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);
|
|
803
|
+
const db = openDb();
|
|
804
|
+
try {
|
|
805
|
+
const lines = await spec.run(db, parsed);
|
|
806
|
+
process.stdout.write(`${lines.join('\n')}\n`);
|
|
807
|
+
return lines.exitCode ?? 0;
|
|
808
|
+
} finally {
|
|
809
|
+
db.close();
|
|
810
|
+
}
|
|
811
|
+
} catch (cause) {
|
|
812
|
+
process.stderr.write(`sumo: ${cause.message}\n`);
|
|
813
|
+
return cause instanceof UsageError ? 2 : 1;
|
|
814
|
+
}
|
|
815
|
+
}
|