sumo-agents 0.0.0-stage → 0.1.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 (62) hide show
  1. package/AGENTS.md +37 -0
  2. package/LICENSE +21 -0
  3. package/README.md +625 -2
  4. package/bin/sumo.mjs +31 -0
  5. package/guides/delegation.md +32 -0
  6. package/guides/feature.md +14 -0
  7. package/guides/fix.md +14 -0
  8. package/guides/memory.md +23 -0
  9. package/guides/projects.md +27 -0
  10. package/guides/review.md +16 -0
  11. package/guides/workflows.md +26 -0
  12. package/logo.txt +19 -0
  13. package/package.json +41 -4
  14. package/prompts/agent.md +7 -0
  15. package/prompts/dream.md +12 -0
  16. package/prompts/scribe.md +20 -0
  17. package/spinner.txt +90 -0
  18. package/src/advisor.mjs +59 -0
  19. package/src/apply.mjs +308 -0
  20. package/src/auth.mjs +80 -0
  21. package/src/card.mjs +67 -0
  22. package/src/catalog.mjs +167 -0
  23. package/src/chat.mjs +987 -0
  24. package/src/cli.mjs +726 -0
  25. package/src/db.mjs +345 -0
  26. package/src/dream.mjs +97 -0
  27. package/src/editor.mjs +198 -0
  28. package/src/export.mjs +132 -0
  29. package/src/guard.mjs +121 -0
  30. package/src/guides.mjs +86 -0
  31. package/src/herdr.mjs +117 -0
  32. package/src/hooks.mjs +263 -0
  33. package/src/images.mjs +89 -0
  34. package/src/jobs.mjs +637 -0
  35. package/src/jobtools.mjs +79 -0
  36. package/src/local-server.mjs +169 -0
  37. package/src/lock.mjs +45 -0
  38. package/src/loop.mjs +533 -0
  39. package/src/mcp.mjs +574 -0
  40. package/src/memory.mjs +365 -0
  41. package/src/model.mjs +269 -0
  42. package/src/page.html +304 -0
  43. package/src/page.mjs +133 -0
  44. package/src/paths.mjs +26 -0
  45. package/src/prime.mjs +168 -0
  46. package/src/projects.mjs +232 -0
  47. package/src/recall.mjs +45 -0
  48. package/src/redact.mjs +173 -0
  49. package/src/render.mjs +44 -0
  50. package/src/route.mjs +209 -0
  51. package/src/scan.mjs +204 -0
  52. package/src/scribe.mjs +347 -0
  53. package/src/sessions.mjs +368 -0
  54. package/src/setup.mjs +463 -0
  55. package/src/text.mjs +92 -0
  56. package/src/tools.mjs +456 -0
  57. package/src/transcript.mjs +106 -0
  58. package/src/tty.mjs +528 -0
  59. package/src/ui.mjs +1307 -0
  60. package/src/verify.mjs +326 -0
  61. package/src/web.mjs +49 -0
  62. package/src/workflows.mjs +270 -0
package/src/apply.mjs ADDED
@@ -0,0 +1,308 @@
1
+ import { tx } from './db.mjs';
2
+ import * as memory from './memory.mjs';
3
+ import { line } from './render.mjs';
4
+ import { addCheckpoint, currentProject } from './sessions.mjs';
5
+ import { asksForWork, overlap } from './text.mjs';
6
+
7
+ /**
8
+ * The only door through which a model's suggestion becomes a memory.
9
+ *
10
+ * A model proposes; this code decides. Nothing here trusts the model's word:
11
+ * a claim that the user said something is checked against what the user
12
+ * actually typed, and anything that cannot be checked is held back as a guess
13
+ * for the user to confirm. One bad operation is dropped and logged; it never
14
+ * takes the good ones down with it.
15
+ */
16
+
17
+ const STATED_TYPES = ['preference', 'fact', 'decision'];
18
+ const BODY_MAX = 300;
19
+ /** Enough to be unmistakable, short enough that a real "no emojis" still counts. */
20
+ const QUOTE_MIN_WORDS = 2;
21
+ const QUOTE_MIN_CHARS = 6;
22
+ /** A paraphrase shares words with its source. Below this, the quote is real but the claim is about something else. */
23
+ const BODY_MATCHES_TURN = 0.34;
24
+ const SAME_STATEMENT = 0.8;
25
+ /** "use eslint for linting" / "use biome for linting": three words of four. Close enough to ask about, too different to call a repeat. */
26
+ const LOOKS_ALIKE = 0.7;
27
+
28
+ const OPS_BY_SOURCE = {
29
+ scribe: ['add', 'supersede', 'gotcha', 'checkpoint'],
30
+ dream: ['add', 'supersede', 'gotcha', 'checkpoint', 'contradiction', 'procedure'],
31
+ // A delegated sub-agent's report: it may tell us about traps it hit, and nothing else.
32
+ worker: ['gotcha'],
33
+ };
34
+
35
+ class Rejected extends Error {}
36
+
37
+ const normalize = (text) => text.toLowerCase().replace(/[‘’]/g, "'").replace(/[“”]/g, '"').replace(/\s+/g, ' ').trim();
38
+
39
+ /**
40
+ * The sentences a quote was taken from, whole: the shortest run of the turn's sentences that holds every quoted word.
41
+ * The model picks where a quote starts and ends; what the user was doing in that sentence is not its to trim away.
42
+ */
43
+ function sentencesAround(text, quote) {
44
+ const sentences = text.split(/(?<=[.!?])\s+|\n+/).map(normalize).filter(Boolean);
45
+ // One pass: where each sentence starts in the turn as normalized, then the ones the quote's span touches.
46
+ const starts = [];
47
+ let at = 0;
48
+ for (const s of sentences) {
49
+ starts.push(at);
50
+ at += s.length + 1;
51
+ }
52
+ const from = sentences.join(' ').indexOf(normalize(quote));
53
+ if (from === -1) return text;
54
+ const to = from + normalize(quote).length;
55
+ return sentences.filter((s, i) => starts[i] < to && starts[i] + s.length > from).join(' ');
56
+ }
57
+
58
+ function resolveScope(db, scope) {
59
+ if (scope === 'global' || scope === undefined) return { scope: 'global', project: undefined };
60
+ const match = /^project:(.+)$/.exec(String(scope));
61
+ if (!match) throw new Rejected(`scope "${scope}" is neither global nor project:<name>`);
62
+ try {
63
+ const slug = memory.resolveProject(db, match[1]);
64
+ return { scope: `project:${slug}`, project: slug };
65
+ } catch {
66
+ throw new Rejected(`unknown project in scope "${scope}"`);
67
+ }
68
+ }
69
+
70
+ function cleanBody(op) {
71
+ const body = typeof op.body === 'string' ? op.body.replace(/\s+/g, ' ').trim() : '';
72
+ if (!body) throw new Rejected('empty body');
73
+ if (body.length > BODY_MAX) throw new Rejected(`body over ${BODY_MAX} characters — a memory is one statement`);
74
+ return body;
75
+ }
76
+
77
+ /**
78
+ * Did the user really say it? The quoted words must appear in something the
79
+ * user typed, and the memory must be about that sentence. The turn the model
80
+ * names is tried first, then every other turn it was shown: models mix up turn
81
+ * numbers, and the words being the user's own is what matters, not the label.
82
+ */
83
+ function verify(op, body, turns) {
84
+ const named = turns.get(Number(op.turn)) ?? null;
85
+ if (typeof op.quote !== 'string' || !op.quote.trim()) return { turn: named, verified: false, why: 'no quote given' };
86
+ const quote = normalize(op.quote);
87
+ if (quote.length < QUOTE_MIN_CHARS || quote.split(' ').length < QUOTE_MIN_WORDS) return { turn: named, verified: false, why: 'the quote is too short to prove anything' };
88
+
89
+ const candidates = [...(named ? [named] : []), ...[...turns.values()].filter((t) => t !== named)];
90
+ const source = candidates.find((t) => normalize(t.text).includes(quote));
91
+ if (!source) return { turn: named, verified: false, why: 'the user never typed the quoted words' };
92
+ if (overlap(body, source.text) < BODY_MATCHES_TURN) return { turn: source, verified: false, why: 'the quote is real but the memory is about something else' };
93
+ return { turn: source, verified: true, why: null };
94
+ }
95
+
96
+ /**
97
+ * A memory in this scope that looks like this one. `same` means it says the same thing in the same
98
+ * words. Merely looking alike is a different and more dangerous case: "slate uses pnpm" and "slate
99
+ * uses bun" share every word but one, and the second is a correction, not a repeat. Treating it as
100
+ * already known would leave memory wrong for good — so look-alikes are never dropped, only flagged.
101
+ */
102
+ // Identifier case and punctuation carry meaning (Release/release, feature/a/feature-a).
103
+ const statementOf = (text) => text.replace(/[‘’]/g, "'").replace(/[“”]/g, '"').replace(/\s+/g, ' ').trim();
104
+
105
+ function lookalike(db, scope, body, exclude) {
106
+ const inScope = db
107
+ .prepare(`SELECT * FROM memories WHERE scope = ? AND type != 'procedure' AND state IN ('active', 'unconfirmed', 'rejected') AND id IS NOT ?`)
108
+ .all(scope, exclude ?? null);
109
+ // Only the same statement is a repeat: case and punctuation can change a branch, path or version.
110
+ const said = statementOf(body);
111
+ const same = inScope.find((m) => statementOf(m.body) === said);
112
+ if (same) return { memory: same, same: true };
113
+ const alike = inScope.find((m) => m.state === 'active' && overlap(body, m.body) >= LOOKS_ALIKE);
114
+ return alike ? { memory: alike, same: false } : null;
115
+ }
116
+
117
+ /**
118
+ * The same sentence is often proposed twice from one turn — once by a retry, once by the chat model saving it directly.
119
+ * A repeat quotes the same words; two rules given in one sentence quote different ones, and are both kept.
120
+ */
121
+ function savedFromTurn(db, turnId, scope, body, exclude, quote) {
122
+ if (turnId === null) return null;
123
+ const fromTurn = db.prepare(`SELECT * FROM memories WHERE source_turn = ? AND scope = ? AND state != 'unconfirmed' AND id IS NOT ?`).all(turnId, scope, exclude ?? null);
124
+ const said = typeof quote === 'string' ? normalize(quote) : '';
125
+ const quotesAgree = (m) => {
126
+ const theirs = m.source_quote ? normalize(m.source_quote) : '';
127
+ return !said || !theirs || said.includes(theirs) || theirs.includes(said);
128
+ };
129
+ return fromTurn.find((m) => statementOf(body) === statementOf(m.body) && quotesAgree(m)) ?? null;
130
+ }
131
+
132
+ /** Two active memories that look alike but are not the same: only the user can say whether one replaces the other. */
133
+ function flagLookalike(db, saved, other, now) {
134
+ const [lo, hi] = saved.id < other.id ? [saved.id, other.id] : [other.id, saved.id];
135
+ if (db.prepare('SELECT 1 FROM notices WHERE memory_a = ? AND memory_b = ?').get(lo, hi)) return;
136
+ db.prepare(`INSERT INTO notices (kind, memory_a, memory_b, note, created_at) VALUES ('lookalike', ?, ?, ?, ?)`).run(
137
+ lo, hi, 'they look alike — if the newer one replaces the older, supersede it; if both hold, leave them', now,
138
+ );
139
+ }
140
+
141
+ /** The user has now said, in so many words, what was only a guess: the guess becomes a stated memory. */
142
+ function promote(db, guess, { turn, quote, supersedes, now }) {
143
+ db.prepare(`UPDATE memories SET state = 'active', provenance = 'stated', source_session = ?, source_turn = ?, source_quote = ? WHERE id = ?`).run(
144
+ turn.session_id, turn.id, quote, guess.id,
145
+ );
146
+ if (supersedes !== undefined) memory.supersede(db, supersedes, guess.id, now);
147
+ return memory.get(db, guess.id);
148
+ }
149
+
150
+ function addStated(db, op, ctx, { supersedes } = {}) {
151
+ if (!STATED_TYPES.includes(op.type)) throw new Rejected(`type "${op.type}" cannot come from a model — one of: ${STATED_TYPES.join(', ')}`);
152
+ const body = cleanBody(op);
153
+ const { turn, verified, why } = verify(op, body, ctx.turns);
154
+ // The words being the user's is not enough: asked to describe or fix something, the user stated nothing that lasts.
155
+ // Judged on the quote and on the whole sentence it came from, so a quote cut short of its "delegate" proves no more than the sentence.
156
+ if (verified && (asksForWork(op.quote) || asksForWork(sentencesAround(turn.text, op.quote)))) {
157
+ throw new Rejected('the quote is from a sentence that asks for work or an answer; it states nothing that lasts');
158
+ }
159
+ // A guess costs the user a question; one drawn from a request — describe this, fix that — is the model answering it, not the user saying it.
160
+ if (!verified && turn && asksForWork(turn.text)) throw new Rejected(`a guess from a request, not kept — ${why}`);
161
+ // No scope given: what was said in the middle of work on a project belongs to that project.
162
+ const focus = op.scope === undefined && turn ? currentProject(db, turn.session_id) : null;
163
+ const { scope, project } = resolveScope(db, focus ? `project:${focus}` : op.scope);
164
+
165
+ const again = savedFromTurn(db, turn?.id ?? null, scope, body, supersedes, op.quote);
166
+ if (again) throw new Rejected(`already saved from this turn as m${again.id}`);
167
+
168
+ // What is being replaced naturally resembles its replacement, so it is left out of the comparison.
169
+ const twin = lookalike(db, scope, body, supersedes);
170
+ if (twin?.same) {
171
+ const known = twin.memory;
172
+ if (known.state === 'unconfirmed' && verified) {
173
+ return `saved ${line(promote(db, known, { turn, quote: op.quote.trim(), supersedes, now: ctx.now }))}`;
174
+ }
175
+ if (known.state === 'active' && verified && supersedes !== undefined) {
176
+ // The statement was filed earlier; only now is it clear what it replaces.
177
+ memory.supersede(db, supersedes, known.id, ctx.now);
178
+ return `m${known.id} now replaces m${supersedes}`;
179
+ }
180
+ if (known.state === 'rejected' && !verified) throw new Rejected(`the user already said no to this (m${known.id})`);
181
+ if (known.state !== 'rejected') throw new Rejected(`already known as m${known.id}`);
182
+ }
183
+
184
+ const { memory: saved } = memory.add(db, {
185
+ type: op.type,
186
+ body,
187
+ project,
188
+ topic: typeof op.topic === 'string' ? op.topic : undefined,
189
+ provenance: verified ? 'stated' : 'inferred',
190
+ // A guess must never be able to hide something true: only a verified statement supersedes.
191
+ supersedes: verified ? supersedes : undefined,
192
+ writtenBy: ctx.source,
193
+ sourceSession: turn?.session_id ?? null,
194
+ sourceTurn: turn?.id ?? null,
195
+ sourceQuote: verified ? op.quote.trim() : null,
196
+ now: ctx.now,
197
+ });
198
+ if (verified && twin && !twin.same) flagLookalike(db, saved, twin.memory, ctx.now);
199
+ return verified ? `saved ${line(saved)}` : `held for confirmation ${line(saved)} — ${why}`;
200
+ }
201
+
202
+ /** The scope a model named, as it is stored; null when it names nothing that exists. */
203
+ function reachOf(db, scope) {
204
+ try {
205
+ return resolveScope(db, scope).scope;
206
+ } catch {
207
+ return null;
208
+ }
209
+ }
210
+
211
+ /** A memory id as a person or a file writes it — 12 or "m12" — or NaN; the passes' schema gives numbers, `sumo apply` may not. */
212
+ const idOf = (raw) => Number(/^m?(\d+)$/.exec(String(raw ?? '').trim())?.[1] ?? NaN);
213
+
214
+ const HANDLERS = {
215
+ add: (db, op, ctx) => addStated(db, op, ctx),
216
+
217
+ supersede(db, op, ctx) {
218
+ const old = db.prepare('SELECT * FROM memories WHERE id = ?').get(idOf(op.old)) ?? null;
219
+ const type = STATED_TYPES.includes(op.type) ? op.type : STATED_TYPES.includes(old?.type) ? old.type : 'fact';
220
+ // A real statement aimed at the wrong target — a memory that is gone, or one about something
221
+ // else — is still a real statement. It is kept; it just does not get to replace anything.
222
+ // Nor does it replace a taught workflow — its steps and its gate are not a sentence to overwrite — or a memory of another
223
+ // reach: a rule said for one project leaves the one that holds everywhere, and the one of another project, in force.
224
+ const reach = op.scope ? reachOf(db, op.scope) : (old?.scope ?? null);
225
+ const related = old?.state === 'active' && old.type !== 'procedure' && (reach === old.scope || reach === 'global') && overlap(cleanBody(op), old.body) >= BODY_MATCHES_TURN;
226
+ if (!related) return addStated(db, { ...op, type }, ctx);
227
+ return addStated(db, { ...op, scope: op.scope ?? old.scope, type }, ctx, { supersedes: old.id });
228
+ },
229
+
230
+ /** Something learned by doing the work, not something the user said — so no quote, and only this one kind. */
231
+ gotcha(db, op, ctx) {
232
+ const body = cleanBody(op);
233
+ const { scope, project } = resolveScope(db, op.scope);
234
+ const twin = lookalike(db, scope, body);
235
+ if (twin?.same) throw new Rejected(`already known as m${twin.memory.id}`);
236
+ const { memory: saved } = memory.add(db, { type: 'gotcha', body, project, provenance: 'observed', writtenBy: ctx.source, now: ctx.now });
237
+ return `saved ${line(saved)}`;
238
+ },
239
+
240
+ checkpoint(db, op, ctx) {
241
+ let project;
242
+ try {
243
+ project = memory.resolveProject(db, String(op.project ?? ''));
244
+ } catch {
245
+ throw new Rejected(`checkpoint for unknown project "${op.project}"`);
246
+ }
247
+ const done = typeof op.done === 'string' ? op.done.replace(/\s+/g, ' ').trim().slice(0, BODY_MAX) : '';
248
+ if (!done) throw new Rejected('checkpoint says nothing was done');
249
+ const next = typeof op.next === 'string' && op.next.trim() ? op.next.replace(/\s+/g, ' ').trim().slice(0, 200) : null;
250
+ addCheckpoint(db, { sessionId: ctx.sessionId ?? null, project, done, next, now: ctx.now });
251
+ return `checkpoint ${project}: ${done}${next ? ` → next: ${next}` : ''}`;
252
+ },
253
+
254
+ /** Two memories that cannot both be true. Never resolved here: only the user knows which one is. */
255
+ contradiction(db, op, ctx) {
256
+ const [a, b] = (Array.isArray(op.ids) ? op.ids : []).map(idOf);
257
+ if (!a || !b || a === b) throw new Rejected('a contradiction names two different memories');
258
+ for (const id of [a, b]) if (memory.get(db, id).state !== 'active') throw new Rejected(`m${id} is not active`);
259
+ const [lo, hi] = a < b ? [a, b] : [b, a];
260
+ if (db.prepare('SELECT 1 FROM notices WHERE memory_a = ? AND memory_b = ?').get(lo, hi)) throw new Rejected('already raised');
261
+ const note = typeof op.note === 'string' && op.note.trim() ? op.note.trim().slice(0, 200) : 'they cannot both be true';
262
+ db.prepare(`INSERT INTO notices (kind, memory_a, memory_b, note, created_at) VALUES ('contradiction', ?, ?, ?, ?)`).run(lo, hi, note, ctx.now);
263
+ return `raised for the user: m${lo} vs m${hi} — ${note}`;
264
+ },
265
+
266
+ /** A workflow the model thinks it saw the user repeat. Always a proposal. */
267
+ procedure(db, op, ctx) {
268
+ const title = typeof op.title === 'string' ? op.title.trim() : '';
269
+ const body = typeof op.body === 'string' ? op.body.trim() : '';
270
+ if (!title || !body) throw new Rejected('a procedure needs a title and steps');
271
+ const { scope, project } = resolveScope(db, op.scope);
272
+ const existing = db.prepare(`SELECT * FROM memories WHERE scope = ? AND type = 'procedure' AND state IN ('active', 'unconfirmed', 'rejected')`).all(scope);
273
+ const twin = existing.find((m) => overlap(title, m.title) >= SAME_STATEMENT);
274
+ if (twin) throw new Rejected(`a workflow like this exists already (m${twin.id}, ${twin.state})`);
275
+ const { memory: saved } = memory.add(db, {
276
+ type: 'procedure', title, cue: typeof op.cue === 'string' ? op.cue : undefined, body: body.slice(0, 2000), project,
277
+ provenance: 'inferred', writtenBy: ctx.source, now: ctx.now,
278
+ });
279
+ return `held for confirmation ${line(saved)}`;
280
+ },
281
+ };
282
+
283
+ /**
284
+ * @param ops what the model returned
285
+ * @param ctx.source 'scribe' | 'dream' — decides which operations are even allowed
286
+ * @param ctx.turns Map of turn id → user_turns row the model was shown
287
+ */
288
+ export function applyOps(db, ops, ctx) {
289
+ const applied = [];
290
+ const dropped = [];
291
+ if (!Array.isArray(ops)) return { applied, dropped: ['the answer had no list of operations'] };
292
+ const allowed = OPS_BY_SOURCE[ctx.source] ?? [];
293
+
294
+ tx(db, () => {
295
+ for (const op of ops) {
296
+ const name = op?.op;
297
+ try {
298
+ if (!allowed.includes(name)) throw new Rejected(`operation "${name}" is not allowed from ${ctx.source}`);
299
+ applied.push(HANDLERS[name](db, op, ctx));
300
+ } catch (cause) {
301
+ // Rejected and UsageError are verdicts on the model's suggestion; anything else is a bug and must surface.
302
+ if (!(cause instanceof Rejected) && !(cause instanceof memory.UsageError)) throw cause;
303
+ dropped.push(`${name ?? '?'}: ${cause.message}`);
304
+ }
305
+ }
306
+ });
307
+ return { applied, dropped };
308
+ }
package/src/auth.mjs ADDED
@@ -0,0 +1,80 @@
1
+ import Anthropic from '@anthropic-ai/sdk';
2
+
3
+ /** The request identity Anthropic requires when a Claude Code OAuth token calls the Messages API directly. */
4
+ export const CLAUDE_CODE_SYSTEM = "You are Claude Code, Anthropic's official CLI for Claude.";
5
+ export const CLAUDE_CODE_BETAS = ['claude-code-20250219', 'oauth-2025-04-20'];
6
+
7
+ // Pin the protocol version so authentication does not depend on a local Claude installation.
8
+ const CLAUDE_CODE_VERSION = '2.1.280';
9
+
10
+ /** The names a credential is read from — and the only names a command run for the model goes without. */
11
+ export const CREDENTIAL_NAMES = ['ANTHROPIC_API_KEY', 'CLAUDE_CODE_OAUTH_TOKEN', 'ANTHROPIC_AUTH_TOKEN'];
12
+
13
+ /** Resolve one credential without ever copying it into a child process or output. API keys keep their documented precedence. */
14
+ export function resolveAnthropicCredential(env = process.env) {
15
+ const apiKey = env.ANTHROPIC_API_KEY?.trim();
16
+ if (apiKey) {
17
+ return apiKey.startsWith('sk-ant-oat')
18
+ ? { type: 'oauth', token: apiKey, source: 'ANTHROPIC_API_KEY' }
19
+ : { type: 'api_key', token: apiKey, source: 'ANTHROPIC_API_KEY' };
20
+ }
21
+
22
+ const oauth = env.CLAUDE_CODE_OAUTH_TOKEN?.trim();
23
+ if (oauth) return { type: 'oauth', token: oauth, source: 'CLAUDE_CODE_OAUTH_TOKEN' };
24
+
25
+ const bearer = env.ANTHROPIC_AUTH_TOKEN?.trim();
26
+ if (bearer) return { type: 'bearer', token: bearer, source: 'ANTHROPIC_AUTH_TOKEN' };
27
+ return null;
28
+ }
29
+
30
+ /**
31
+ * One client per credential and per way of calling: the SDK keeps a connection pool, its retry state and its logger on the
32
+ * client, so a request made on a fresh one every time opens a new connection every time. A credential that changes — the
33
+ * shell exported another — gets a client of its own; the old one is simply not asked again.
34
+ */
35
+ const clients = new Map();
36
+ export function anthropicClient({ timeout, maxRetries = undefined } = {}, credential = resolveAnthropicCredential(), env = process.env) {
37
+ // The base URL is read from the shell when a client is made: one made for another is not this one.
38
+ const key = JSON.stringify([credential?.type ?? null, credential?.token ?? null, timeout ?? null, maxRetries ?? null, env.ANTHROPIC_BASE_URL ?? null]);
39
+ let client = clients.get(key);
40
+ if (!client) {
41
+ client = new Anthropic({ ...anthropicClientOptions(timeout, credential), ...(maxRetries === undefined ? {} : { maxRetries }) });
42
+ clients.set(key, client);
43
+ }
44
+ return client;
45
+ }
46
+
47
+ /** Anthropic SDK constructor options for an API key, generic bearer token, or Claude Code OAuth token. */
48
+ export function anthropicClientOptions(timeout, credential = resolveAnthropicCredential()) {
49
+ if (credential?.type === 'oauth') {
50
+ return {
51
+ timeout,
52
+ apiKey: null,
53
+ authToken: credential.token,
54
+ defaultHeaders: {
55
+ accept: 'application/json',
56
+ 'anthropic-dangerous-direct-browser-access': 'true',
57
+ 'user-agent': `claude-cli/${CLAUDE_CODE_VERSION}`,
58
+ 'x-app': 'cli',
59
+ },
60
+ };
61
+ }
62
+ if (credential?.type === 'bearer') return { timeout, apiKey: null, authToken: credential.token };
63
+ if (credential?.type === 'api_key') return { timeout, apiKey: credential.token, authToken: null };
64
+ return { timeout };
65
+ }
66
+
67
+ /** Add the OAuth protocol fields without mutating the conversation state reused on later turns. */
68
+ export function authenticatedRequest(params, credential = resolveAnthropicCredential()) {
69
+ if (credential?.type !== 'oauth') return params;
70
+ const system = Array.isArray(params.system)
71
+ ? params.system
72
+ : typeof params.system === 'string' && params.system
73
+ ? [{ type: 'text', text: params.system }]
74
+ : [];
75
+ return {
76
+ ...params,
77
+ betas: [...new Set([...CLAUDE_CODE_BETAS, ...(params.betas ?? [])])],
78
+ system: [{ type: 'text', text: CLAUDE_CODE_SYSTEM }, ...system],
79
+ };
80
+ }
package/src/card.mjs ADDED
@@ -0,0 +1,67 @@
1
+ import { aliasesOf, getProject, isScratch, scratchRules } from './projects.mjs';
2
+ import { clip, estimateTokens } from './text.mjs';
3
+
4
+ const CARD_BUDGET_TOKENS = 200;
5
+ const LINE_MAX = 110;
6
+
7
+ /** Lower number = kept first when the card has to shrink. Scanned facts are ranked by their key. */
8
+ const SCAN_PRIORITY = { instructions: 1, stack: 2, commands: 3, index: 7, workspaces: 9, gaps: 9, ci: 10, about: 11 };
9
+ const PRIORITY = { rule: 4, last: 5, gotcha: 6, workflow: 6, fact: 8 };
10
+
11
+ export function ago(iso, now) {
12
+ const hours = (Date.parse(now) - Date.parse(iso)) / 3_600_000;
13
+ if (hours < 1) return 'just now';
14
+ if (hours < 48) return `${Math.round(hours)}h ago`;
15
+ return `${Math.round(hours / 24)}d ago`;
16
+ }
17
+
18
+ /**
19
+ * What an agent needs the moment a project comes up, under a hard budget.
20
+ * To fit, whole lines are left out — and counted, so the card says how much it
21
+ * is not showing. A single over-long line is clipped with a visible ellipsis;
22
+ * `sumo show <id>` has the rest.
23
+ */
24
+ export function card(db, nameOrAlias, { budget = CARD_BUDGET_TOKENS, now = new Date().toISOString() } = {}) {
25
+ const project = getProject(db, nameOrAlias);
26
+ // Scratch has no memory to show: its card is how it is used.
27
+ if (isScratch(project)) return [`<project ${project.slug}> ${project.path}`, ...scratchRules(db), '</project>'].join('\n');
28
+ const scope = `project:${project.slug}`;
29
+ const rows = db
30
+ .prepare(`SELECT * FROM memories WHERE scope = ? AND state = 'active' ORDER BY pinned DESC, importance DESC, hits DESC, id DESC`)
31
+ .all(scope);
32
+
33
+ const candidates = [];
34
+ let order = 0;
35
+ const offer = (priority, text) => candidates.push({ priority, order: order++, text: clip(text, LINE_MAX) });
36
+
37
+ for (const m of rows.filter((r) => r.scan_key)) offer(SCAN_PRIORITY[m.scan_key] ?? 11, m.body);
38
+ for (const m of rows.filter((r) => !r.scan_key && (r.type === 'preference' || r.type === 'decision'))) offer(PRIORITY.rule, `rule m${m.id}: ${m.body}`);
39
+
40
+ const last = db.prepare('SELECT * FROM checkpoints WHERE project = ? ORDER BY ts DESC, id DESC LIMIT 1').get(project.slug);
41
+ if (last) offer(PRIORITY.last, `last (${ago(last.ts, now)}): ${last.done}${last.next_step ? ` → next: ${last.next_step}` : ''}`);
42
+
43
+ for (const m of rows.filter((r) => r.type === 'gotcha')) offer(PRIORITY.gotcha, `gotcha m${m.id}: ${m.body}`);
44
+ for (const m of rows.filter((r) => r.type === 'procedure')) offer(PRIORITY.workflow, `workflow m${m.id}: "${m.title}"${m.cue ? ` (when: ${m.cue})` : ''} — follow it: sumo show m${m.id}`);
45
+ for (const m of rows.filter((r) => !r.scan_key && r.type === 'fact')) offer(PRIORITY.fact, `fact m${m.id}: ${m.body}`);
46
+
47
+ const aliases = aliasesOf(db, project.slug);
48
+ const header = `<project ${project.slug}${project.status === 'archived' ? ' (archived)' : ''}> ${project.path}${aliases.length ? ` · also called: ${aliases.join(', ')}` : ''}`;
49
+ const footer = '</project>';
50
+ const more = (n) => `(+${n} more — sumo search "<topic>" --project ${project.slug})`;
51
+
52
+ let used = estimateTokens(`${header}\n${footer}`);
53
+ const kept = [];
54
+ const byPriority = [...candidates].sort((a, b) => a.priority - b.priority || a.order - b.order);
55
+ // Reserve room for the "+N more" line up front, so adding it can never push the card over.
56
+ const reserve = estimateTokens(more(99)) + 1;
57
+ for (const line of byPriority) {
58
+ const cost = estimateTokens(line.text) + 1;
59
+ if (used + cost > budget - reserve) continue;
60
+ used += cost;
61
+ kept.push(line);
62
+ }
63
+
64
+ const dropped = candidates.length - kept.length;
65
+ const body = kept.sort((a, b) => a.priority - b.priority || a.order - b.order).map((l) => l.text);
66
+ return [header, ...body, ...(dropped > 0 ? [more(dropped)] : []), footer].join('\n');
67
+ }
@@ -0,0 +1,167 @@
1
+ import Anthropic from '@anthropic-ai/sdk';
2
+ import { spawnSync } from 'node:child_process';
3
+ import { anthropicClient, resolveAnthropicCredential } from './auth.mjs';
4
+ import { getMeta, setMeta } from './db.mjs';
5
+ import { UsageError } from './memory.mjs';
6
+
7
+ /**
8
+ * The models Sumo can run on: the short names the router, `/model` and `sumo config` use, cheapest
9
+ * first, and the API model each one means. Each has a switch. `sumo setup` asks the API once which
10
+ * of them this credential can use and sets the switches from the answer; `sumo models discover` asks
11
+ * again; `sumo models enable|disable <name>` sets one by hand. The chat, the router, the passes and a
12
+ * job's run all read the switches as they are now.
13
+ */
14
+ export const MODEL_IDS = {
15
+ haiku: 'claude-haiku-4-5-20251001',
16
+ sonnet: 'claude-sonnet-5-5',
17
+ opus: 'claude-opus-5-5',
18
+ fable: 'claude-fable-5-1',
19
+ };
20
+ export const MODELS = Object.keys(MODEL_IDS);
21
+
22
+ export const modelId = (model) => MODEL_IDS[model] ?? model;
23
+
24
+ const STATE_KEY = 'models.state';
25
+ const CHECKED_KEY = 'models.checked';
26
+ const TIMEOUT_MS = 30_000;
27
+ /** What a Claude Code OAuth token needs on a request outside the Messages API. */
28
+ const OAUTH_BETA = 'oauth-2025-04-20';
29
+
30
+ const day = (now) => String(now).slice(0, 10);
31
+
32
+ /** Every model's switch and the note that explains it — on, and "not checked", until something is recorded. */
33
+ export function modelStates(db) {
34
+ let stored = {};
35
+ try {
36
+ stored = JSON.parse(getMeta(db, STATE_KEY) ?? '{}');
37
+ } catch {
38
+ stored = {};
39
+ }
40
+ return Object.fromEntries(MODELS.map((name) => [name, { on: stored[name]?.on !== false, note: stored[name]?.note ?? 'not checked' }]));
41
+ }
42
+
43
+ const writeStates = (db, states) => setMeta(db, STATE_KEY, JSON.stringify(states));
44
+
45
+ /** The models the chat, the router and the passes may use, cheapest first. */
46
+ export function usableModels(db) {
47
+ const states = modelStates(db);
48
+ return MODELS.filter((name) => states[name].on);
49
+ }
50
+
51
+ /** When the API was last asked which models it has, or null while it never was. */
52
+ export const modelsChecked = (db) => getMeta(db, CHECKED_KEY);
53
+
54
+ /** `name` is a model Sumo knows, or a usage error listing them — after `also`, the other values the setting takes. */
55
+ export function knownModel(name, also = []) {
56
+ if (!MODELS.includes(name)) throw new UsageError(`no such model "${name}" — one of: ${[...also, ...MODELS].join(', ')}`);
57
+ }
58
+
59
+ /** Why `name` cannot be used right now, with the way out (`orElse` is another one), or null while it is on. */
60
+ export function offLine(db, name, orElse) {
61
+ if (modelStates(db)[name].on) return null;
62
+ return `${name} is off — sumo models enable ${name}${orElse ? `, or ${orElse}` : ''}`;
63
+ }
64
+
65
+ /** `name` is on, or a usage error saying how to turn it on. */
66
+ export function assertOn(db, name, orElse) {
67
+ const line = offLine(db, name, orElse);
68
+ if (line) throw new UsageError(line);
69
+ }
70
+
71
+ /** Turns one model on or off by hand. */
72
+ export function setModel(db, name, on, now = new Date().toISOString()) {
73
+ knownModel(name);
74
+ const states = modelStates(db);
75
+ states[name] = { on, note: `turned ${on ? 'on' : 'off'} ${day(now)}` };
76
+ writeStates(db, states);
77
+ return states[name];
78
+ }
79
+
80
+ /** One line per model: its name, its switch, the API id and the note — what `sumo models` prints. */
81
+ export function modelLines(db, names = MODELS) {
82
+ const states = modelStates(db);
83
+ return names.map((name) => `${name.padEnd(7)} ${states[name].on ? 'on ' : 'off'} ${MODEL_IDS[name].padEnd(26)} ${states[name].note}`);
84
+ }
85
+
86
+ /** What went wrong with an API call, in one line a person can act on. */
87
+ export function describeApiError(cause) {
88
+ if (cause instanceof Anthropic.AuthenticationError) return 'the Anthropic credential is missing or invalid — export ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN in the shell that runs sumo';
89
+ if (cause instanceof Anthropic.RateLimitError) return 'the API is rate-limiting this key — try again in a minute';
90
+ if (cause instanceof Anthropic.APIError) return `the API answered ${cause.status ?? 'an error'}: ${String(cause.message).slice(0, 300)}`;
91
+ return String(cause?.message ?? cause).slice(0, 300);
92
+ }
93
+
94
+ /** The stand-in's answer to "which models are there": `{ found: [names], errors: { name: why } }`; anything else is a failed check. */
95
+ function askStandIn(standIn) {
96
+ const run = spawnSync(standIn, [], { input: JSON.stringify({ kind: 'models', models: MODEL_IDS }), encoding: 'utf8', timeout: TIMEOUT_MS });
97
+ if (run.error) return { error: `could not run ${standIn}: ${run.error.message}` };
98
+ let answer;
99
+ try {
100
+ answer = JSON.parse(run.stdout);
101
+ } catch {
102
+ return { error: (run.stderr || run.stdout).trim().slice(0, 200) || `exit ${run.status}` };
103
+ }
104
+ if (!answer || typeof answer !== 'object') return { error: `${standIn} answered ${String(run.stdout).trim().slice(0, 80)}, not a list of models` };
105
+ const found = new Set(answer.found ?? []);
106
+ const errors = answer.errors ?? {};
107
+ return Object.fromEntries(MODELS.map((name) => [name, found.has(name) ? 'found' : Object.hasOwn(errors, name) ? String(errors[name]) : 'missing']));
108
+ }
109
+
110
+ /** One GET /v1/models/<id> per model, together: found, missing, or what went wrong asking. */
111
+ async function askApi() {
112
+ const standIn = process.env.SUMO_AGENTS_MODEL_CMD;
113
+ if (standIn) return askStandIn(standIn);
114
+ const credential = resolveAnthropicCredential();
115
+ if (!credential) return { error: 'no Anthropic credential — export ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN in this shell' };
116
+ const client = anthropicClient({ timeout: TIMEOUT_MS }, credential);
117
+ const options = credential.type === 'oauth' ? { headers: { 'anthropic-beta': OAUTH_BETA } } : {};
118
+ const entries = await Promise.all(
119
+ MODELS.map(async (name) => {
120
+ try {
121
+ await client.models.retrieve(MODEL_IDS[name], options);
122
+ return [name, 'found'];
123
+ } catch (cause) {
124
+ return [name, cause instanceof Anthropic.NotFoundError ? 'missing' : describeApiError(cause)];
125
+ }
126
+ }),
127
+ );
128
+ return Object.fromEntries(entries);
129
+ }
130
+
131
+ /**
132
+ * Asks the API which of Sumo's models this credential can use, and sets the switches from the answer:
133
+ * found → on, not there → off; a model whose own check errored is left as it was, with the error in its
134
+ * note. An answer with none of them found is a failed check, not an API that has none: nothing is changed
135
+ * and the reason is returned. Never throws.
136
+ */
137
+ export async function discoverModels(db, { now = new Date().toISOString() } = {}) {
138
+ const answers = await askApi();
139
+ if (answers.error) return { ok: false, error: answers.error };
140
+ const found = MODELS.filter((name) => answers[name] === 'found');
141
+ const missing = MODELS.filter((name) => answers[name] === 'missing');
142
+ const errors = Object.fromEntries(MODELS.filter((name) => answers[name] !== 'found' && answers[name] !== 'missing').map((name) => [name, answers[name]]));
143
+ if (found.length === 0) {
144
+ // Any model that could not be asked says more than the ones that were not there: a connection that failed is not a credential that cannot see.
145
+ const failed = Object.values(errors);
146
+ const error = failed.length > 0 ? failed[0] : 'the API found none of the models Sumo knows — the credential may not be allowed to see them';
147
+ return { ok: false, error };
148
+ }
149
+ const states = modelStates(db);
150
+ // A model the user turned off stays off: the API says what this credential can use, not what the user wants used.
151
+ const offByHand = (name) => !states[name].on && /^turned off /.test(states[name].note ?? '');
152
+ for (const name of found) if (!offByHand(name)) states[name] = { on: true, note: `found ${day(now)}` };
153
+ for (const name of missing) states[name] = { on: false, note: `not found ${day(now)}` };
154
+ for (const [name, error] of Object.entries(errors)) states[name] = { on: states[name].on, note: `not checked — ${error}` };
155
+ writeStates(db, states);
156
+ setMeta(db, CHECKED_KEY, now);
157
+ return { ok: true, found, missing, errors };
158
+ }
159
+
160
+ /** A finished discovery in one line: what was found, what was turned off, what could not be checked. */
161
+ export function discoverySummary({ found, missing, errors }) {
162
+ const parts = [`found: ${found.join(', ')}`];
163
+ if (missing.length > 0) parts.push(`not found, turned off: ${missing.join(', ')}`);
164
+ const failed = Object.entries(errors);
165
+ if (failed.length > 0) parts.push(`not checked: ${failed.map(([name, error]) => `${name} (${error})`).join(', ')}`);
166
+ return parts.join(' — ');
167
+ }