sumo-agents 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/AGENTS.md +38 -0
  2. package/LICENSE +21 -0
  3. package/README.md +111 -2
  4. package/bin/sumo.mjs +33 -0
  5. package/guides/delegation.md +33 -0
  6. package/guides/feature.md +14 -0
  7. package/guides/fix.md +14 -0
  8. package/guides/memory.md +23 -0
  9. package/guides/projects.md +27 -0
  10. package/guides/review.md +16 -0
  11. package/guides/workflows.md +26 -0
  12. package/logo.txt +19 -0
  13. package/package.json +42 -4
  14. package/prompts/agent.md +7 -0
  15. package/prompts/dream.md +13 -0
  16. package/prompts/scribe.md +21 -0
  17. package/spinner.txt +90 -0
  18. package/src/advisor.mjs +59 -0
  19. package/src/apply.mjs +368 -0
  20. package/src/auth.mjs +80 -0
  21. package/src/card.mjs +72 -0
  22. package/src/catalog.mjs +167 -0
  23. package/src/chat.mjs +1162 -0
  24. package/src/cli.mjs +815 -0
  25. package/src/cost.mjs +128 -0
  26. package/src/db.mjs +384 -0
  27. package/src/dream.mjs +97 -0
  28. package/src/editor.mjs +198 -0
  29. package/src/export.mjs +132 -0
  30. package/src/guard.mjs +121 -0
  31. package/src/guides.mjs +86 -0
  32. package/src/herdr.mjs +117 -0
  33. package/src/hooks.mjs +270 -0
  34. package/src/images.mjs +89 -0
  35. package/src/jobs.mjs +1184 -0
  36. package/src/jobtools.mjs +82 -0
  37. package/src/local-server.mjs +169 -0
  38. package/src/lock.mjs +45 -0
  39. package/src/loop.mjs +838 -0
  40. package/src/mcp.mjs +604 -0
  41. package/src/memory.mjs +400 -0
  42. package/src/model.mjs +270 -0
  43. package/src/page.html +304 -0
  44. package/src/page.mjs +135 -0
  45. package/src/paths.mjs +33 -0
  46. package/src/prime.mjs +177 -0
  47. package/src/projects.mjs +232 -0
  48. package/src/recall.mjs +45 -0
  49. package/src/redact.mjs +173 -0
  50. package/src/render.mjs +45 -0
  51. package/src/route.mjs +287 -0
  52. package/src/sandbox.mjs +173 -0
  53. package/src/scan.mjs +204 -0
  54. package/src/scribe.mjs +349 -0
  55. package/src/sessions.mjs +371 -0
  56. package/src/setup.mjs +528 -0
  57. package/src/sqlite.mjs +66 -0
  58. package/src/text.mjs +97 -0
  59. package/src/tools.mjs +987 -0
  60. package/src/transcript.mjs +106 -0
  61. package/src/tty.mjs +529 -0
  62. package/src/ui.mjs +1363 -0
  63. package/src/verify.mjs +369 -0
  64. package/src/web.mjs +49 -0
  65. package/src/workflows.mjs +270 -0
  66. package/src/worktree.mjs +128 -0
@@ -0,0 +1,59 @@
1
+ /**
2
+ * The advisor, as the API's own tool: a stronger model the one doing a job may ask from inside a request. It reads the
3
+ * whole conversation and answers the model, not the screen — the call and the advice are blocks of the reply and go back
4
+ * with the conversation exactly as they came: the advice is encrypted, and the API reads it from there on the next turn.
5
+ *
6
+ * For jobs only. A job keeps one model to its end; the tool cannot leave a conversation that has advice in it, nor be
7
+ * given a limit of none, so a chat that changes models could be left with an advisor weaker than the model asking.
8
+ */
9
+ import { MODEL_IDS, modelId, MODELS } from './catalog.mjs';
10
+
11
+ const ADVISOR_TYPE = 'advisor_20260301';
12
+ const ADVISOR_NAME = 'advisor';
13
+ export const ADVISOR_BETA = 'advisor-tool-2026-03-01';
14
+
15
+ /** Each asking has the advisor read the whole conversation at its own price: the job is told at the first of these, and the run stopped at the second. */
16
+ export const ADVISOR_SPENT_AT = 3;
17
+ export const ADVISOR_STOP_AT = 6;
18
+ /** Said once, with the answers of the turn that asked that many times: the tool itself cannot be taken away. */
19
+ export const ADVISOR_SPENT = `[sumo: the advisor has been asked ${ADVISOR_SPENT_AT} times in this job, and each asking has it read the whole conversation again. Do not ask it again: carry on with what you have. Asked ${ADVISOR_STOP_AT} times, the run is stopped.]`;
20
+
21
+ /** Whom a job's model may ask: the next model up that is on. None when nothing on is above it — a model asking itself pays twice for one opinion. */
22
+ export function advisorOf(model, usable) {
23
+ const at = MODELS.indexOf(model);
24
+ return at === -1 ? null : (MODELS.slice(at + 1).find((name) => usable.includes(name)) ?? null);
25
+ }
26
+
27
+ /** The tool, for a request. Its limit counts within one request and cannot be none: once a request, and the job's own limit is the loop's to keep. */
28
+ export const advisorTool = (advisor) => ({ type: ADVISOR_TYPE, name: ADVISOR_NAME, model: modelId(advisor), max_uses: 1 });
29
+
30
+ /** Said in the system prompt of a job that has one: the model cannot be made to ask, so it is told when asking is worth its price. */
31
+ export const advisorLine = (advisor) =>
32
+ `You have an advisor: the \`${ADVISOR_NAME}\` tool asks ${advisor}, a stronger model, which reads this whole conversation and answers with advice. ` +
33
+ 'Each asking costs a full read of the conversation, so ask early and where it changes the outcome: before settling a plan that touches several files or that you are unsure of, ' +
34
+ `and when two attempts at the same thing have failed. Not for routine steps, and not more than ${ADVISOR_SPENT_AT} times in a job. ` +
35
+ 'Weigh the advice against what you have seen yourself: the work, and what you report, stay yours.';
36
+
37
+ /** Who the advisor among a request's tools is, by the name the screen uses; null when there is none. */
38
+ export function advisorIn(tools) {
39
+ const id = tools?.find((tool) => tool.type === ADVISOR_TYPE)?.model;
40
+ return id === undefined ? null : (MODELS.find((name) => MODEL_IDS[name] === id) ?? id);
41
+ }
42
+
43
+ export const isAdvisorCall = (block) => block.type === 'server_tool_use' && block.name === ADVISOR_NAME;
44
+ export const isAdvisorResult = (block) => block.type === 'advisor_tool_result';
45
+ /** A call by its name alone, for the screen. */
46
+ export const isAdvisorTool = (call) => call.name === ADVISOR_NAME;
47
+
48
+ /** What asking came to, said as any tool's result is: that advice was given — it is the model's alone to read — or the failure by its code. */
49
+ export function advisorResult(block) {
50
+ const got = block.content;
51
+ if (got?.type !== 'advisor_redacted_result' && got?.type !== 'advisor_result') return { content: `advisor failed: ${got?.error_code ?? 'no reason given'}`, isError: true };
52
+ return { content: 'advice given', isError: false };
53
+ }
54
+
55
+ /**
56
+ * What the advisor itself read and wrote in one reply, each asking with the model that answered it. The top of a reply's
57
+ * usage counts the job's own model only; the advisor is among the iterations, and nowhere else.
58
+ */
59
+ export const advisorRuns = (usage) => (usage?.iterations ?? []).filter((entry) => entry.type === 'advisor_message');
package/src/apply.mjs ADDED
@@ -0,0 +1,368 @@
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
+ /**
29
+ * How much of memory the slow pass may retire in one go. A playbook a model was asked to rewrite whole shrank to a
30
+ * fraction of itself, and the agent did worse with it than with none. A few replacements a pass — a correction the user
31
+ * kept repeating — are its job; past either bound it is rewriting, and none of its replacements is taken.
32
+ */
33
+ const MAX_RETIRED = 10;
34
+ const MAX_RETIRED_SHARE = 0.25;
35
+ /** What retires a memory. Everything else a pass may do only adds. */
36
+ const RETIRING = ['supersede'];
37
+
38
+ const OPS_BY_SOURCE = {
39
+ scribe: ['add', 'supersede', 'gotcha', 'checkpoint'],
40
+ dream: ['add', 'supersede', 'gotcha', 'checkpoint', 'contradiction', 'procedure'],
41
+ // A delegated sub-agent's report: it may tell us about traps it hit, and nothing else.
42
+ worker: ['gotcha'],
43
+ };
44
+
45
+ class Rejected extends Error {}
46
+
47
+ const normalize = (text) => text.toLowerCase().replace(/[‘’]/g, "'").replace(/[“”]/g, '"').replace(/\s+/g, ' ').trim();
48
+
49
+ /**
50
+ * The sentences a quote was taken from, whole: the shortest run of the turn's sentences that holds every quoted word.
51
+ * The model picks where a quote starts and ends; what the user was doing in that sentence is not its to trim away.
52
+ */
53
+ function sentencesAround(text, quote) {
54
+ const sentences = text.split(/(?<=[.!?])\s+|\n+/).map(normalize).filter(Boolean);
55
+ // One pass: where each sentence starts in the turn as normalized, then the ones the quote's span touches.
56
+ const starts = [];
57
+ let at = 0;
58
+ for (const s of sentences) {
59
+ starts.push(at);
60
+ at += s.length + 1;
61
+ }
62
+ const from = sentences.join(' ').indexOf(normalize(quote));
63
+ if (from === -1) return text;
64
+ const to = from + normalize(quote).length;
65
+ return sentences.filter((s, i) => starts[i] < to && starts[i] + s.length > from).join(' ');
66
+ }
67
+
68
+ function resolveScope(db, scope) {
69
+ if (scope === 'global' || scope === undefined) return { scope: 'global', project: undefined };
70
+ const match = /^project:(.+)$/.exec(String(scope));
71
+ if (!match) throw new Rejected(`scope "${scope}" is neither global nor project:<name>`);
72
+ try {
73
+ const slug = memory.resolveProject(db, match[1]);
74
+ return { scope: `project:${slug}`, project: slug };
75
+ } catch {
76
+ throw new Rejected(`unknown project in scope "${scope}"`);
77
+ }
78
+ }
79
+
80
+ function cleanBody(op) {
81
+ const body = typeof op.body === 'string' ? op.body.replace(/\s+/g, ' ').trim() : '';
82
+ if (!body) throw new Rejected('empty body');
83
+ if (body.length > BODY_MAX) throw new Rejected(`body over ${BODY_MAX} characters — a memory is one statement`);
84
+ return body;
85
+ }
86
+
87
+ /**
88
+ * Did the user really say it? The quoted words must appear in something the
89
+ * user typed, and the memory must be about that sentence. The turn the model
90
+ * names is tried first, then every other turn it was shown: models mix up turn
91
+ * numbers, and the words being the user's own is what matters, not the label.
92
+ */
93
+ function verify(op, body, turns) {
94
+ const named = turns.get(Number(op.turn)) ?? null;
95
+ if (typeof op.quote !== 'string' || !op.quote.trim()) return { turn: named, verified: false, why: 'no quote given' };
96
+ const quote = normalize(op.quote);
97
+ 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' };
98
+
99
+ const candidates = [...(named ? [named] : []), ...[...turns.values()].filter((t) => t !== named)];
100
+ const source = candidates.find((t) => normalize(t.text).includes(quote));
101
+ if (!source) return { turn: named, verified: false, why: 'the user never typed the quoted words' };
102
+ 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' };
103
+ return { turn: source, verified: true, why: null };
104
+ }
105
+
106
+ /**
107
+ * A memory in this scope that looks like this one. `same` means it says the same thing in the same
108
+ * words. Merely looking alike is a different and more dangerous case: "slate uses pnpm" and "slate
109
+ * uses bun" share every word but one, and the second is a correction, not a repeat. Treating it as
110
+ * already known would leave memory wrong for good — so look-alikes are never dropped, only flagged.
111
+ */
112
+ // Identifier case and punctuation carry meaning (Release/release, feature/a/feature-a).
113
+ const statementOf = (text) => text.replace(/[‘’]/g, "'").replace(/[“”]/g, '"').replace(/\s+/g, ' ').trim();
114
+
115
+ function lookalike(db, scope, body, exclude) {
116
+ const inScope = db
117
+ .prepare(`SELECT * FROM memories WHERE scope = ? AND type != 'procedure' AND state IN ('active', 'unconfirmed', 'rejected') AND id IS NOT ?`)
118
+ .all(scope, exclude ?? null);
119
+ // Only the same statement is a repeat: case and punctuation can change a branch, path or version.
120
+ const said = statementOf(body);
121
+ const same = inScope.find((m) => statementOf(m.body) === said);
122
+ if (same) return { memory: same, same: true };
123
+ const alike = inScope.find((m) => m.state === 'active' && overlap(body, m.body) >= LOOKS_ALIKE);
124
+ return alike ? { memory: alike, same: false } : null;
125
+ }
126
+
127
+ /** A guess already put to the user in other words — still waiting, or refused: asked once is enough. */
128
+ function askedBefore(db, scope, body) {
129
+ const asked = db.prepare(`SELECT * FROM memories WHERE scope = ? AND type != 'procedure' AND state IN ('unconfirmed', 'rejected')`).all(scope);
130
+ return asked.find((m) => statementOf(m.body) !== statementOf(body) && overlap(body, m.body) >= LOOKS_ALIKE) ?? null;
131
+ }
132
+
133
+ /**
134
+ * The same sentence is often proposed twice from one turn — once by a retry, once by the chat model saving it directly.
135
+ * A repeat quotes the same words; two rules given in one sentence quote different ones, and are both kept.
136
+ */
137
+ function savedFromTurn(db, turnId, scope, body, exclude, quote) {
138
+ if (turnId === null) return null;
139
+ const fromTurn = db.prepare(`SELECT * FROM memories WHERE source_turn = ? AND scope = ? AND state != 'unconfirmed' AND id IS NOT ?`).all(turnId, scope, exclude ?? null);
140
+ const said = typeof quote === 'string' ? normalize(quote) : '';
141
+ const quotesAgree = (m) => {
142
+ const theirs = m.source_quote ? normalize(m.source_quote) : '';
143
+ return !said || !theirs || said.includes(theirs) || theirs.includes(said);
144
+ };
145
+ return fromTurn.find((m) => statementOf(body) === statementOf(m.body) && quotesAgree(m)) ?? null;
146
+ }
147
+
148
+ /** Two active memories that look alike but are not the same: only the user can say whether one replaces the other. */
149
+ function flagLookalike(db, saved, other, now) {
150
+ const [lo, hi] = saved.id < other.id ? [saved.id, other.id] : [other.id, saved.id];
151
+ if (db.prepare('SELECT 1 FROM notices WHERE memory_a = ? AND memory_b = ?').get(lo, hi)) return;
152
+ db.prepare(`INSERT INTO notices (kind, memory_a, memory_b, note, created_at) VALUES ('lookalike', ?, ?, ?, ?)`).run(
153
+ lo, hi, 'they look alike — if the newer one replaces the older, supersede it; if both hold, leave them', now,
154
+ );
155
+ }
156
+
157
+ /** The user has now said, in so many words, what was only a guess: the guess becomes a stated memory. */
158
+ function promote(db, guess, { turn, quote, supersedes, now }) {
159
+ db.prepare(`UPDATE memories SET state = 'active', provenance = 'stated', source_session = ?, source_turn = ?, source_quote = ? WHERE id = ?`).run(
160
+ turn.session_id, turn.id, quote, guess.id,
161
+ );
162
+ if (supersedes !== undefined) memory.supersede(db, supersedes, guess.id, now);
163
+ return memory.get(db, guess.id);
164
+ }
165
+
166
+ function addStated(db, op, ctx, { supersedes } = {}) {
167
+ if (!STATED_TYPES.includes(op.type)) throw new Rejected(`type "${op.type}" cannot come from a model — one of: ${STATED_TYPES.join(', ')}`);
168
+ const body = cleanBody(op);
169
+ const { turn, verified, why } = verify(op, body, ctx.turns);
170
+ // The words being the user's is not enough: asked to describe or fix something, the user stated nothing that lasts.
171
+ // 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.
172
+ if (verified && (asksForWork(op.quote) || asksForWork(sentencesAround(turn.text, op.quote)))) {
173
+ throw new Rejected('the quote is from a sentence that asks for work or an answer; it states nothing that lasts');
174
+ }
175
+ // 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.
176
+ if (!verified && turn && asksForWork(turn.text)) throw new Rejected(`a guess from a request, not kept — ${why}`);
177
+ // No scope given: what was said in the middle of work on a project belongs to that project.
178
+ const focus = op.scope === undefined && turn ? currentProject(db, turn.session_id) : null;
179
+ const { scope, project } = resolveScope(db, focus ? `project:${focus}` : op.scope);
180
+ // Nor is a guess kept that shares nothing with the turn it names: that is the assistant's reply, or what is remembered already,
181
+ // said in the user's name. The slow pass alone may guess past that — a pattern across conversations is what it reads for.
182
+ const aboutTurn = ctx.source === 'dream' || (turn !== null && overlap(body, turn.text) >= BODY_MATCHES_TURN);
183
+ if (!verified && !aboutTurn) throw new Rejected(`a guess about nothing the user typed, not kept — ${why}`);
184
+ const asked = verified ? null : askedBefore(db, scope, body);
185
+ if (asked) throw new Rejected(`a guess like m${asked.id}, which is ${asked.state} — not kept`);
186
+
187
+ const again = savedFromTurn(db, turn?.id ?? null, scope, body, supersedes, op.quote);
188
+ if (again) throw new Rejected(`already saved from this turn as m${again.id}`);
189
+
190
+ // What is being replaced naturally resembles its replacement, so it is left out of the comparison.
191
+ const twin = lookalike(db, scope, body, supersedes);
192
+ if (twin?.same) {
193
+ const known = twin.memory;
194
+ if (known.state === 'unconfirmed' && verified) {
195
+ return `saved ${line(promote(db, known, { turn, quote: op.quote.trim(), supersedes, now: ctx.now }))}`;
196
+ }
197
+ if (known.state === 'active' && verified && supersedes !== undefined) {
198
+ // The statement was filed earlier; only now is it clear what it replaces.
199
+ memory.supersede(db, supersedes, known.id, ctx.now);
200
+ return `m${known.id} now replaces m${supersedes}`;
201
+ }
202
+ if (known.state === 'rejected' && !verified) throw new Rejected(`the user already said no to this (m${known.id})`);
203
+ if (known.state !== 'rejected') throw new Rejected(`already known as m${known.id}`);
204
+ }
205
+
206
+ const { memory: saved } = memory.add(db, {
207
+ type: op.type,
208
+ body,
209
+ project,
210
+ topic: typeof op.topic === 'string' ? op.topic : undefined,
211
+ // Search terms only, checked where they are stored: a bad one is dropped there, never the memory.
212
+ keys: op.keys,
213
+ provenance: verified ? 'stated' : 'inferred',
214
+ // A guess must never be able to hide something true: only a verified statement supersedes.
215
+ supersedes: verified ? supersedes : undefined,
216
+ writtenBy: ctx.source,
217
+ sourceSession: turn?.session_id ?? null,
218
+ sourceTurn: turn?.id ?? null,
219
+ sourceQuote: verified ? op.quote.trim() : null,
220
+ now: ctx.now,
221
+ });
222
+ if (verified && twin && !twin.same) flagLookalike(db, saved, twin.memory, ctx.now);
223
+ return verified ? `saved ${line(saved)}` : `held for confirmation ${line(saved)} — ${why}`;
224
+ }
225
+
226
+ /** The scope a model named, as it is stored; null when it names nothing that exists. */
227
+ function reachOf(db, scope) {
228
+ try {
229
+ return resolveScope(db, scope).scope;
230
+ } catch {
231
+ return null;
232
+ }
233
+ }
234
+
235
+ /** 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. */
236
+ const idOf = (raw) => Number(/^m?(\d+)$/.exec(String(raw ?? '').trim())?.[1] ?? NaN);
237
+
238
+ const HANDLERS = {
239
+ add: (db, op, ctx) => addStated(db, op, ctx),
240
+
241
+ supersede(db, op, ctx) {
242
+ const old = db.prepare('SELECT * FROM memories WHERE id = ?').get(idOf(op.old)) ?? null;
243
+ const type = STATED_TYPES.includes(op.type) ? op.type : STATED_TYPES.includes(old?.type) ? old.type : 'fact';
244
+ // A real statement aimed at the wrong target — a memory that is gone, or one about something
245
+ // else — is still a real statement. It is kept; it just does not get to replace anything.
246
+ // Nor does it replace a taught workflow — its steps and its gate are not a sentence to overwrite — or a memory of another
247
+ // reach: a rule said for one project leaves the one that holds everywhere, and the one of another project, in force.
248
+ const reach = op.scope ? reachOf(db, op.scope) : (old?.scope ?? null);
249
+ const related = old?.state === 'active' && old.type !== 'procedure' && (reach === old.scope || reach === 'global') && overlap(cleanBody(op), old.body) >= BODY_MATCHES_TURN;
250
+ if (!related) return addStated(db, { ...op, type }, ctx);
251
+ return addStated(db, { ...op, scope: op.scope ?? old.scope, type }, ctx, { supersedes: old.id });
252
+ },
253
+
254
+ /** Something learned by doing the work, not something the user said — so no quote, and only this one kind. */
255
+ gotcha(db, op, ctx) {
256
+ const body = cleanBody(op);
257
+ const { scope, project } = resolveScope(db, op.scope);
258
+ // A trap met twice is written up twice, in other words: the one already here stands for both.
259
+ const twin = lookalike(db, scope, body);
260
+ if (twin) throw new Rejected(`already known as m${twin.memory.id}`);
261
+ const { memory: saved } = memory.add(db, { type: 'gotcha', body, project, keys: op.keys, provenance: 'observed', writtenBy: ctx.source, now: ctx.now });
262
+ return `saved ${line(saved)}`;
263
+ },
264
+
265
+ checkpoint(db, op, ctx) {
266
+ let project;
267
+ try {
268
+ project = memory.resolveProject(db, String(op.project ?? ''));
269
+ } catch {
270
+ throw new Rejected(`checkpoint for unknown project "${op.project}"`);
271
+ }
272
+ const done = typeof op.done === 'string' ? op.done.replace(/\s+/g, ' ').trim().slice(0, BODY_MAX) : '';
273
+ if (!done) throw new Rejected('checkpoint says nothing was done');
274
+ const next = typeof op.next === 'string' && op.next.trim() ? op.next.replace(/\s+/g, ' ').trim().slice(0, 200) : null;
275
+ addCheckpoint(db, { sessionId: ctx.sessionId ?? null, project, done, next, now: ctx.now });
276
+ return `checkpoint ${project}: ${done}${next ? ` → next: ${next}` : ''}`;
277
+ },
278
+
279
+ /** Two memories that cannot both be true. Never resolved here: only the user knows which one is. */
280
+ contradiction(db, op, ctx) {
281
+ const [a, b] = (Array.isArray(op.ids) ? op.ids : []).map(idOf);
282
+ if (!a || !b || a === b) throw new Rejected('a contradiction names two different memories');
283
+ for (const id of [a, b]) if (memory.get(db, id).state !== 'active') throw new Rejected(`m${id} is not active`);
284
+ const [lo, hi] = a < b ? [a, b] : [b, a];
285
+ if (db.prepare('SELECT 1 FROM notices WHERE memory_a = ? AND memory_b = ?').get(lo, hi)) throw new Rejected('already raised');
286
+ const note = typeof op.note === 'string' && op.note.trim() ? op.note.trim().slice(0, 200) : 'they cannot both be true';
287
+ db.prepare(`INSERT INTO notices (kind, memory_a, memory_b, note, created_at) VALUES ('contradiction', ?, ?, ?, ?)`).run(lo, hi, note, ctx.now);
288
+ return `raised for the user: m${lo} vs m${hi} — ${note}`;
289
+ },
290
+
291
+ /** A workflow the model thinks it saw the user repeat. Always a proposal. */
292
+ procedure(db, op, ctx) {
293
+ const title = typeof op.title === 'string' ? op.title.trim() : '';
294
+ const body = typeof op.body === 'string' ? op.body.trim() : '';
295
+ if (!title || !body) throw new Rejected('a procedure needs a title and steps');
296
+ const { scope, project } = resolveScope(db, op.scope);
297
+ const existing = db.prepare(`SELECT * FROM memories WHERE scope = ? AND type = 'procedure' AND state IN ('active', 'unconfirmed', 'rejected')`).all(scope);
298
+ const twin = existing.find((m) => overlap(title, m.title) >= SAME_STATEMENT);
299
+ if (twin) throw new Rejected(`a workflow like this exists already (m${twin.id}, ${twin.state})`);
300
+ const { memory: saved } = memory.add(db, {
301
+ type: 'procedure', title, cue: typeof op.cue === 'string' ? op.cue : undefined, body: body.slice(0, 2000), project,
302
+ provenance: 'inferred', writtenBy: ctx.source, now: ctx.now,
303
+ });
304
+ return `held for confirmation ${line(saved)}`;
305
+ },
306
+ };
307
+
308
+ /** Each operation in turn. With `refused` — why — every one that would retire a memory is dropped for that reason. */
309
+ function applyEach(db, ops, ctx, refused = null) {
310
+ const applied = [];
311
+ const dropped = [];
312
+ const allowed = OPS_BY_SOURCE[ctx.source] ?? [];
313
+ for (const op of ops) {
314
+ const name = op?.op;
315
+ try {
316
+ if (!allowed.includes(name)) throw new Rejected(`operation "${name}" is not allowed from ${ctx.source}`);
317
+ if (refused && RETIRING.includes(name)) {
318
+ const old = idOf(op.old);
319
+ throw new Rejected(`${Number.isNaN(old) ? 'what it replaces' : `m${old}`} is left as it is — ${refused}`);
320
+ }
321
+ applied.push(HANDLERS[name](db, op, ctx));
322
+ } catch (cause) {
323
+ // Rejected and UsageError are verdicts on the model's suggestion; anything else is a bug and must surface.
324
+ if (!(cause instanceof Rejected) && !(cause instanceof memory.UsageError)) throw cause;
325
+ dropped.push(`${name ?? '?'}: ${cause.message}`);
326
+ }
327
+ }
328
+ return { applied, dropped };
329
+ }
330
+
331
+ /** Why the memories retired since `before` (id → scope of every active memory then) are too many to take, or null. */
332
+ function tooWide(db, before) {
333
+ const still = new Set(db.prepare(`SELECT id FROM memories WHERE state = 'active'`).all().map((m) => m.id));
334
+ const retired = [...before].filter(([id]) => !still.has(id)).map(([, scope]) => scope);
335
+ const wide = ': a rewrite that wide is not taken from a model';
336
+ if (retired.length > MAX_RETIRED) return `this pass would retire ${retired.length} memories at once, more than ${MAX_RETIRED}${wide}`;
337
+ const had = [...before.values()];
338
+ for (const scope of new Set(retired)) {
339
+ const gone = retired.filter((s) => s === scope).length;
340
+ const total = had.filter((s) => s === scope).length;
341
+ // One at a time is never a rewrite: a scope of three must still be able to have one of them replaced.
342
+ if (gone > 1 && gone > total * MAX_RETIRED_SHARE) return `this pass would retire ${gone} of the ${total} memories in ${scope}, more than a quarter${wide}`;
343
+ }
344
+ return null;
345
+ }
346
+
347
+ /**
348
+ * @param ops what the model returned
349
+ * @param ctx.source 'scribe' | 'dream' — decides which operations are even allowed
350
+ * @param ctx.turns Map of turn id → user_turns row the model was shown
351
+ */
352
+ export function applyOps(db, ops, ctx) {
353
+ if (!Array.isArray(ops)) return { applied: [], dropped: ['the answer had no list of operations'] };
354
+
355
+ return tx(db, () => {
356
+ if (ctx.source !== 'dream') return applyEach(db, ops, ctx);
357
+ // The slow pass's answer is tried first and counted, then kept or undone: what it would retire is known exactly
358
+ // that way — a replacement that is only a guess, or aimed at the wrong memory, retires nothing. Too wide, it is
359
+ // applied again without what retires anything, and what it adds is kept.
360
+ const before = new Map(db.prepare(`SELECT id, scope FROM memories WHERE state = 'active'`).all().map((m) => [m.id, m.scope]));
361
+ db.exec('SAVEPOINT dream_ops');
362
+ const tried = applyEach(db, ops, ctx);
363
+ const refused = tooWide(db, before);
364
+ if (refused) db.exec('ROLLBACK TO dream_ops');
365
+ db.exec('RELEASE dream_ops');
366
+ return refused ? applyEach(db, ops, ctx, refused) : tried;
367
+ });
368
+ }
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,72 @@
1
+ import { markHits } from './memory.mjs';
2
+ import { aliasesOf, getProject, isScratch, scratchRules } from './projects.mjs';
3
+ import { clip, estimateTokens } from './text.mjs';
4
+
5
+ const CARD_BUDGET_TOKENS = 200;
6
+ const LINE_MAX = 110;
7
+
8
+ /** Lower number = kept first when the card has to shrink. Scanned facts are ranked by their key. */
9
+ const SCAN_PRIORITY = { instructions: 1, stack: 2, commands: 3, index: 7, workspaces: 9, gaps: 9, ci: 10, about: 11 };
10
+ const PRIORITY = { rule: 4, last: 5, gotcha: 6, workflow: 6, fact: 8 };
11
+
12
+ export function ago(iso, now) {
13
+ const hours = (Date.parse(now) - Date.parse(iso)) / 3_600_000;
14
+ if (hours < 1) return 'just now';
15
+ if (hours < 48) return `${Math.round(hours)}h ago`;
16
+ return `${Math.round(hours / 24)}d ago`;
17
+ }
18
+
19
+ /**
20
+ * What an agent needs the moment a project comes up, under a hard budget.
21
+ * To fit, whole lines are left out — and counted, so the card says how much it
22
+ * is not showing. A single over-long line is clipped with a visible ellipsis;
23
+ * `sumo show <id>` has the rest.
24
+ */
25
+ export function card(db, nameOrAlias, { budget = CARD_BUDGET_TOKENS, now = new Date().toISOString() } = {}) {
26
+ const project = getProject(db, nameOrAlias);
27
+ // Scratch has no memory to show: its card is how it is used.
28
+ if (isScratch(project)) return [`<project ${project.slug}> ${project.path}`, ...scratchRules(db), '</project>'].join('\n');
29
+ const scope = `project:${project.slug}`;
30
+ const rows = db
31
+ .prepare(`SELECT * FROM memories WHERE scope = ? AND state = 'active' ORDER BY pinned DESC, importance DESC, hits DESC, id DESC`)
32
+ .all(scope);
33
+
34
+ const candidates = [];
35
+ let order = 0;
36
+ // A line that is a memory carries its id, so what the card shows can be counted as used.
37
+ const offer = (priority, text, id = null) => candidates.push({ priority, order: order++, text: clip(text, LINE_MAX), id });
38
+
39
+ for (const m of rows.filter((r) => r.scan_key)) offer(SCAN_PRIORITY[m.scan_key] ?? 11, m.body, m.id);
40
+ 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}`, m.id);
41
+
42
+ const last = db.prepare('SELECT * FROM checkpoints WHERE project = ? ORDER BY ts DESC, id DESC LIMIT 1').get(project.slug);
43
+ if (last) offer(PRIORITY.last, `last (${ago(last.ts, now)}): ${last.done}${last.next_step ? ` → next: ${last.next_step}` : ''}`);
44
+
45
+ for (const m of rows.filter((r) => r.type === 'gotcha')) offer(PRIORITY.gotcha, `gotcha m${m.id}: ${m.body}`, m.id);
46
+ 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}`, m.id);
47
+ for (const m of rows.filter((r) => !r.scan_key && r.type === 'fact')) offer(PRIORITY.fact, `fact m${m.id}: ${m.body}`, m.id);
48
+
49
+ const aliases = aliasesOf(db, project.slug);
50
+ const header = `<project ${project.slug}${project.status === 'archived' ? ' (archived)' : ''}> ${project.path}${aliases.length ? ` · also called: ${aliases.join(', ')}` : ''}`;
51
+ const footer = '</project>';
52
+ const more = (n) => `(+${n} more — sumo search "<topic>" --project ${project.slug})`;
53
+
54
+ let used = estimateTokens(`${header}\n${footer}`);
55
+ const kept = [];
56
+ const byPriority = [...candidates].sort((a, b) => a.priority - b.priority || a.order - b.order);
57
+ // Reserve room for the "+N more" line up front, so adding it can never push the card over.
58
+ const reserve = estimateTokens(more(99)) + 1;
59
+ for (const line of byPriority) {
60
+ const cost = estimateTokens(line.text) + 1;
61
+ if (used + cost > budget - reserve) continue;
62
+ used += cost;
63
+ kept.push(line);
64
+ }
65
+
66
+ // What the card puts in front of someone is used; what it leaves out is not, and stays a search away.
67
+ markHits(db, kept.flatMap((l) => (l.id === null ? [] : [l.id])), now);
68
+
69
+ const dropped = candidates.length - kept.length;
70
+ const body = kept.sort((a, b) => a.priority - b.priority || a.order - b.order).map((l) => l.text);
71
+ return [header, ...body, ...(dropped > 0 ? [more(dropped)] : []), footer].join('\n');
72
+ }