sumo-agents 0.3.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +8 -6
- package/CHANGELOG.md +155 -0
- package/README.md +82 -19
- package/bin/sumo.mjs +13 -2
- package/guides/feature.md +2 -1
- package/guides/memory.md +6 -4
- package/guides/projects.md +1 -1
- package/guides/review.md +1 -1
- package/package.json +5 -4
- package/prompts/dream.md +6 -0
- package/spinner.txt +25 -1
- package/src/apply.mjs +146 -18
- package/src/auth.mjs +32 -5
- package/src/card.mjs +39 -2
- package/src/catalog.mjs +6 -3
- package/src/chat.mjs +289 -89
- package/src/cli.mjs +359 -135
- package/src/cost.mjs +67 -8
- package/src/db.mjs +106 -3
- package/src/dream.mjs +445 -19
- package/src/editor.mjs +113 -11
- package/src/export.mjs +105 -7
- package/src/guard.mjs +57 -11
- package/src/guides.mjs +5 -4
- package/src/herdr.mjs +9 -4
- package/src/hooks.mjs +35 -19
- package/src/jobs.mjs +118 -39
- package/src/jobtools.mjs +6 -4
- package/src/keeper.mjs +77 -0
- package/src/local-server.mjs +9 -16
- package/src/lock.mjs +2 -1
- package/src/logs.mjs +165 -0
- package/src/loop.mjs +121 -44
- package/src/mcp.mjs +72 -16
- package/src/memory.mjs +142 -15
- package/src/model.mjs +41 -21
- package/src/paths.mjs +38 -0
- package/src/prime.mjs +19 -31
- package/src/projects.mjs +94 -12
- package/src/redact.mjs +10 -0
- package/src/render.mjs +2 -1
- package/src/route.mjs +39 -25
- package/src/sandbox.mjs +82 -3
- package/src/scan.mjs +35 -1
- package/src/scribe.mjs +10 -22
- package/src/sessions.mjs +49 -13
- package/src/setup.mjs +425 -76
- package/src/text.mjs +100 -1
- package/src/tools.mjs +258 -21
- package/src/tty.mjs +481 -105
- package/src/ui.mjs +1205 -276
- package/src/verify.mjs +17 -1
package/src/apply.mjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { tx } from './db.mjs';
|
|
1
|
+
import { getMeta, setMeta, tx } from './db.mjs';
|
|
2
2
|
import * as memory from './memory.mjs';
|
|
3
3
|
import { line } from './render.mjs';
|
|
4
|
-
import { addCheckpoint, currentProject } from './sessions.mjs';
|
|
5
|
-
import { asksForWork, overlap } from './text.mjs';
|
|
4
|
+
import { addCheckpoint, currentProject, outsideReadsOf } from './sessions.mjs';
|
|
5
|
+
import { asksForWork, onlyAlternative, overlap, sameWayRound, sharedStems } from './text.mjs';
|
|
6
6
|
|
|
7
7
|
/**
|
|
8
8
|
* The only door through which a model's suggestion becomes a memory.
|
|
@@ -22,6 +22,8 @@ const QUOTE_MIN_CHARS = 6;
|
|
|
22
22
|
/** A paraphrase shares words with its source. Below this, the quote is real but the claim is about something else. */
|
|
23
23
|
const BODY_MATCHES_TURN = 0.34;
|
|
24
24
|
const SAME_STATEMENT = 0.8;
|
|
25
|
+
/** What the slow pass proposes from a sentence already filed is that memory again when it shares this much with it. */
|
|
26
|
+
const ALREADY_FILED = 0.5;
|
|
25
27
|
/** "use eslint for linting" / "use biome for linting": three words of four. Close enough to ask about, too different to call a repeat. */
|
|
26
28
|
const LOOKS_ALIKE = 0.7;
|
|
27
29
|
|
|
@@ -37,7 +39,7 @@ const RETIRING = ['supersede'];
|
|
|
37
39
|
|
|
38
40
|
const OPS_BY_SOURCE = {
|
|
39
41
|
scribe: ['add', 'supersede', 'gotcha', 'checkpoint'],
|
|
40
|
-
dream: ['add', 'supersede', 'gotcha', 'checkpoint', 'contradiction', 'procedure'],
|
|
42
|
+
dream: ['add', 'supersede', 'gotcha', 'checkpoint', 'contradiction', 'same', 'procedure'],
|
|
41
43
|
// A delegated sub-agent's report: it may tell us about traps it hit, and nothing else.
|
|
42
44
|
worker: ['gotcha'],
|
|
43
45
|
};
|
|
@@ -65,6 +67,26 @@ function sentencesAround(text, quote) {
|
|
|
65
67
|
return sentences.filter((s, i) => starts[i] < to && starts[i] + s.length > from).join(' ');
|
|
66
68
|
}
|
|
67
69
|
|
|
70
|
+
/** The clauses of the quote's sentence that the quote touches, whole — split at commas, semicolons, colons, dashes and "but". */
|
|
71
|
+
function clausesAround(text, quote) {
|
|
72
|
+
const sentence = sentencesAround(text, quote);
|
|
73
|
+
const q = normalize(quote);
|
|
74
|
+
const from = sentence.indexOf(q);
|
|
75
|
+
if (from === -1) return sentence;
|
|
76
|
+
const to = from + q.length;
|
|
77
|
+
const parts = [];
|
|
78
|
+
const cut = /[,;:]|\s[—–-]\s|\sbut\s/g;
|
|
79
|
+
let start = 0;
|
|
80
|
+
for (const m of sentence.matchAll(cut)) {
|
|
81
|
+
parts.push([start, m.index]);
|
|
82
|
+
start = m.index + m[0].length;
|
|
83
|
+
}
|
|
84
|
+
parts.push([start, sentence.length]);
|
|
85
|
+
// The touched clauses are side by side: one slice of the sentence keeps the commas between them, which say what is set aside.
|
|
86
|
+
const touched = parts.filter(([a, b]) => a < to && b > from);
|
|
87
|
+
return sentence.slice(touched[0][0], touched.at(-1)[1]).trim();
|
|
88
|
+
}
|
|
89
|
+
|
|
68
90
|
function resolveScope(db, scope) {
|
|
69
91
|
if (scope === 'global' || scope === undefined) return { scope: 'global', project: undefined };
|
|
70
92
|
const match = /^project:(.+)$/.exec(String(scope));
|
|
@@ -93,13 +115,22 @@ function cleanBody(op) {
|
|
|
93
115
|
function verify(op, body, turns) {
|
|
94
116
|
const named = turns.get(Number(op.turn)) ?? null;
|
|
95
117
|
if (typeof op.quote !== 'string' || !op.quote.trim()) return { turn: named, verified: false, why: 'no quote given' };
|
|
96
|
-
|
|
118
|
+
// The words, without the quote marks or the full stop a model may put round them.
|
|
119
|
+
const said = op.quote.trim().replace(/^["'“‘]+|["'”’]+$/g, '').replace(/[.!?]+$/, '');
|
|
120
|
+
const quote = normalize(said);
|
|
97
121
|
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
122
|
|
|
99
123
|
const candidates = [...(named ? [named] : []), ...[...turns.values()].filter((t) => t !== named)];
|
|
100
124
|
const source = candidates.find((t) => normalize(t.text).includes(quote));
|
|
101
125
|
if (!source) return { turn: named, verified: false, why: 'the user never typed the quoted words' };
|
|
102
126
|
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' };
|
|
127
|
+
// The user's words, turned round — "never" filed from an "always" — are not the user's word. Judged on the clauses the quote
|
|
128
|
+
// is in, whole: "we use biome now, not eslint" negates the old tool, not the rule; a quote cut short of its "never" still has it.
|
|
129
|
+
// An alternative set aside ("…, never npm") is looked for in the whole sentence: a quote that stops at the comma left it
|
|
130
|
+
// there. A quote of nothing but the alternative is judged with the sentence it is set against.
|
|
131
|
+
const sentence = sentencesAround(source.text, said);
|
|
132
|
+
const clauses = clausesAround(source.text, said);
|
|
133
|
+
if (!sameWayRound(body, onlyAlternative(clauses) ? sentence : clauses, sentence)) return { turn: source, verified: false, why: 'the quote is real but the memory says it the other way round' };
|
|
103
134
|
return { turn: source, verified: true, why: null };
|
|
104
135
|
}
|
|
105
136
|
|
|
@@ -145,13 +176,53 @@ function savedFromTurn(db, turnId, scope, body, exclude, quote) {
|
|
|
145
176
|
return fromTurn.find((m) => statementOf(body) === statementOf(m.body) && quotesAgree(m)) ?? null;
|
|
146
177
|
}
|
|
147
178
|
|
|
179
|
+
/**
|
|
180
|
+
* Something only the user can settle about two memories, put in the block until it stops being true: `lookalike` or
|
|
181
|
+
* `contradiction`, the pair stored lowest id first. One pair is raised once, whatever its kind; false when it already was.
|
|
182
|
+
*/
|
|
183
|
+
export function raiseNotice(db, { kind, a, b, note, now }) {
|
|
184
|
+
const [lo, hi] = a < b ? [a, b] : [b, a];
|
|
185
|
+
if (db.prepare('SELECT 1 FROM notices WHERE memory_a = ? AND memory_b = ?').get(lo, hi)) return false;
|
|
186
|
+
db.prepare('INSERT INTO notices (kind, memory_a, memory_b, note, created_at) VALUES (?, ?, ?, ?, ?)').run(kind, lo, hi, note, now);
|
|
187
|
+
return true;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** Where the pairs a pass named wait to be judged on their own. */
|
|
191
|
+
const NAMED_PAIRS = 'dream.named_pairs';
|
|
192
|
+
|
|
193
|
+
/** The pairs a pass named that wait to be judged on their own, in the order named: `{ label, a, b, note }`, a < b. */
|
|
194
|
+
export function namedPairs(db) {
|
|
195
|
+
try {
|
|
196
|
+
const named = JSON.parse(getMeta(db, NAMED_PAIRS) ?? '[]');
|
|
197
|
+
return Array.isArray(named) ? named.filter((p) => Number.isInteger(p?.a) && Number.isInteger(p?.b)) : [];
|
|
198
|
+
} catch {
|
|
199
|
+
return [];
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** What waits to be judged from here on: those named, less any judged now. */
|
|
204
|
+
export const keepNamed = (db, named) => setMeta(db, NAMED_PAIRS, JSON.stringify(named));
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* What a pass that read memories by number says of two of them waits until the pair is judged on its own (dream.mjs):
|
|
208
|
+
* reading sixty memories and a dozen turns, a small model writes one number for another — a turn's for a memory's, a
|
|
209
|
+
* neighbour's for the one it meant — and a pair it never looked at side by side would be a question for the user. The
|
|
210
|
+
* reason it is not named, or null: asked once — a pair raised, judged, or waiting already is not named again.
|
|
211
|
+
*/
|
|
212
|
+
export function nameForJudging(db, { label, a, b, note }) {
|
|
213
|
+
const [lo, hi] = a < b ? [a, b] : [b, a];
|
|
214
|
+
if (db.prepare('SELECT 1 FROM notices WHERE memory_a = ? AND memory_b = ?').get(lo, hi)) return 'already raised';
|
|
215
|
+
const judged = db.prepare('SELECT label FROM memory_pairs WHERE a = ? AND b = ?').get(lo, hi);
|
|
216
|
+
if (judged) return `m${lo} and m${hi} were judged on their own already: ${judged.label}`;
|
|
217
|
+
const waiting = namedPairs(db);
|
|
218
|
+
if (waiting.some((p) => p.a === lo && p.b === hi)) return 'already waiting to be judged';
|
|
219
|
+
keepNamed(db, [...waiting, { label, a: lo, b: hi, note }]);
|
|
220
|
+
return null;
|
|
221
|
+
}
|
|
222
|
+
|
|
148
223
|
/** Two active memories that look alike but are not the same: only the user can say whether one replaces the other. */
|
|
149
224
|
function flagLookalike(db, saved, other, now) {
|
|
150
|
-
|
|
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
|
-
);
|
|
225
|
+
raiseNotice(db, { kind: 'lookalike', a: saved.id, b: other.id, note: 'they look alike — if the newer one replaces the older, supersede it; if both hold, leave them', now });
|
|
155
226
|
}
|
|
156
227
|
|
|
157
228
|
/** The user has now said, in so many words, what was only a guess: the guess becomes a stated memory. */
|
|
@@ -186,6 +257,12 @@ function addStated(db, op, ctx, { supersedes } = {}) {
|
|
|
186
257
|
|
|
187
258
|
const again = savedFromTurn(db, turn?.id ?? null, scope, body, supersedes, op.quote);
|
|
188
259
|
if (again) throw new Rejected(`already saved from this turn as m${again.id}`);
|
|
260
|
+
// The slow pass reads conversations the writer has filed already: a sentence it filed is not filed again in other
|
|
261
|
+
// words. Another rule from the same sentence, sharing little with what was filed, is one of its own.
|
|
262
|
+
if (ctx.source === 'dream' && turn && supersedes === undefined) {
|
|
263
|
+
const filed = db.prepare(`SELECT id, body FROM memories WHERE source_turn = ? AND state = 'active'`).all(turn.id).find((m) => overlap(body, m.body) >= ALREADY_FILED);
|
|
264
|
+
if (filed) throw new Rejected(`already filed from that sentence: m${filed.id}`);
|
|
265
|
+
}
|
|
189
266
|
|
|
190
267
|
// What is being replaced naturally resembles its replacement, so it is left out of the comparison.
|
|
191
268
|
const twin = lookalike(db, scope, body, supersedes);
|
|
@@ -258,7 +335,12 @@ const HANDLERS = {
|
|
|
258
335
|
// A trap met twice is written up twice, in other words: the one already here stands for both.
|
|
259
336
|
const twin = lookalike(db, scope, body);
|
|
260
337
|
if (twin) throw new Rejected(`already known as m${twin.memory.id}`);
|
|
261
|
-
|
|
338
|
+
// A trap read in a conversation that searched or fetched the web, or called an MCP server, may be what a page told
|
|
339
|
+
// it: held for the user, never filed as observed. A gotcha names no turn, so every conversation the pass read counts.
|
|
340
|
+
const outside = outsideReadsOf(db, [ctx.sessionId, ...[...(ctx.turns?.values() ?? [])].map((t) => t.session_id)]);
|
|
341
|
+
const { memory: saved } = memory.add(db, { type: 'gotcha', body, project, keys: op.keys, provenance: outside.length > 0 ? 'inferred' : 'observed', writtenBy: ctx.source, now: ctx.now });
|
|
342
|
+
if (outside.length > 0) db.prepare(`UPDATE memories SET held_for = 'outside' WHERE id = ?`).run(saved.id);
|
|
343
|
+
if (outside.length > 0) return `held for confirmation ${line(saved)} — the conversation read ${outside.join(', ')}, and a trap it passes on may be what it was told`;
|
|
262
344
|
return `saved ${line(saved)}`;
|
|
263
345
|
},
|
|
264
346
|
|
|
@@ -276,24 +358,59 @@ const HANDLERS = {
|
|
|
276
358
|
return `checkpoint ${project}: ${done}${next ? ` → next: ${next}` : ''}`;
|
|
277
359
|
},
|
|
278
360
|
|
|
279
|
-
/**
|
|
361
|
+
/**
|
|
362
|
+
* Two memories that cannot both be true. Never resolved here: only the user knows which one is. Only memories the pass
|
|
363
|
+
* was shown, still active, can be named: one it never saw is a wrong number, whatever the note says.
|
|
364
|
+
*/
|
|
280
365
|
contradiction(db, op, ctx) {
|
|
281
366
|
const [a, b] = (Array.isArray(op.ids) ? op.ids : []).map(idOf);
|
|
282
367
|
if (!a || !b || a === b) throw new Rejected('a contradiction names two different memories');
|
|
283
|
-
for (const id of [a, b])
|
|
368
|
+
for (const id of [a, b]) {
|
|
369
|
+
if (ctx.shown && !ctx.shown.has(id)) throw new Rejected(`m${id} is not one of the memories this pass was shown`);
|
|
370
|
+
if (memory.get(db, id).state !== 'active') throw new Rejected(`m${id} is not active`);
|
|
371
|
+
}
|
|
372
|
+
// Two things that clash are about something in common, or the note says what each is about: a memory sharing no word
|
|
373
|
+
// with either is a wrong number, not a clash to put to the user.
|
|
374
|
+
const said = typeof op.note === 'string' ? op.note : '';
|
|
375
|
+
for (const [x, y] of [[a, b], [b, a]]) {
|
|
376
|
+
if (sharedStems(memory.get(db, x).body, `${memory.get(db, y).body} ${said}`) === 0) throw new Rejected(`m${x} shares no word with m${y} or the note — not the memory meant`);
|
|
377
|
+
}
|
|
284
378
|
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
379
|
const note = typeof op.note === 'string' && op.note.trim() ? op.note.trim().slice(0, 200) : 'they cannot both be true';
|
|
287
|
-
|
|
380
|
+
if (ctx.shown) return judgedFirst(db, { label: 'conflict', lo, hi, note, said: 'cannot both be true' });
|
|
381
|
+
if (!raiseNotice(db, { kind: 'contradiction', a: lo, b: hi, note, now: ctx.now })) throw new Rejected('already raised');
|
|
288
382
|
return `raised for the user: m${lo} vs m${hi} — ${note}`;
|
|
289
383
|
},
|
|
290
384
|
|
|
385
|
+
/**
|
|
386
|
+
* Two memories that say one thing in other words — what no word overlap finds. Raised as a look-alike for the user to
|
|
387
|
+
* settle; nothing is retired here. Only memories the pass was shown, still active, can be named.
|
|
388
|
+
*/
|
|
389
|
+
same(db, op, ctx) {
|
|
390
|
+
const [a, b] = (Array.isArray(op.ids) ? op.ids : []).map(idOf);
|
|
391
|
+
if (!a || !b || a === b) throw new Rejected('same names two different memories');
|
|
392
|
+
for (const id of [a, b]) {
|
|
393
|
+
if (ctx.shown && !ctx.shown.has(id)) throw new Rejected(`m${id} is not one of the memories this pass was shown`);
|
|
394
|
+
if (memory.get(db, id).state !== 'active') throw new Rejected(`m${id} is not active`);
|
|
395
|
+
}
|
|
396
|
+
const [lo, hi] = a < b ? [a, b] : [b, a];
|
|
397
|
+
const note = typeof op.note === 'string' && op.note.trim() ? op.note.replace(/\s+/g, ' ').trim().slice(0, 200) : 'they say one thing in other words';
|
|
398
|
+
if (ctx.shown) return judgedFirst(db, { label: 'same', lo, hi, note, said: 'say the same thing' });
|
|
399
|
+
if (!raiseNotice(db, { kind: 'lookalike', a: lo, b: hi, note, now: ctx.now })) throw new Rejected('already raised');
|
|
400
|
+
return `raised for the user: m${lo} and m${hi} say the same thing — ${note}`;
|
|
401
|
+
},
|
|
402
|
+
|
|
291
403
|
/** A workflow the model thinks it saw the user repeat. Always a proposal. */
|
|
292
404
|
procedure(db, op, ctx) {
|
|
293
405
|
const title = typeof op.title === 'string' ? op.title.trim() : '';
|
|
294
406
|
const body = typeof op.body === 'string' ? op.body.trim() : '';
|
|
295
407
|
if (!title || !body) throw new Rejected('a procedure needs a title and steps');
|
|
296
408
|
const { scope, project } = resolveScope(db, op.scope);
|
|
409
|
+
// A routine is walked through more than once: what starts it, said in one turn only, was a one-off ask. Said nowhere, it is
|
|
410
|
+
// the model's own words for a pattern, and the user is asked.
|
|
411
|
+
const trigger = (typeof op.cue === 'string' && op.cue.trim() ? op.cue : title).replace(/\s+/g, ' ').trim();
|
|
412
|
+
const turns = db.prepare('SELECT text FROM user_turns ORDER BY id DESC LIMIT 2000').all();
|
|
413
|
+
if (turns.filter((t) => overlap(trigger, t.text) >= SAME_STATEMENT).length === 1) throw new Rejected(`a routine is something done more than once, and "${trigger.slice(0, 80)}" was said once`);
|
|
297
414
|
const existing = db.prepare(`SELECT * FROM memories WHERE scope = ? AND type = 'procedure' AND state IN ('active', 'unconfirmed', 'rejected')`).all(scope);
|
|
298
415
|
const twin = existing.find((m) => overlap(title, m.title) >= SAME_STATEMENT);
|
|
299
416
|
if (twin) throw new Rejected(`a workflow like this exists already (m${twin.id}, ${twin.state})`);
|
|
@@ -305,6 +422,13 @@ const HANDLERS = {
|
|
|
305
422
|
},
|
|
306
423
|
};
|
|
307
424
|
|
|
425
|
+
/** A pair a pass that read memories by number named, put to the pair judge before the user (`nameForJudging`). */
|
|
426
|
+
function judgedFirst(db, { label, lo, hi, note, said }) {
|
|
427
|
+
const not = nameForJudging(db, { label, a: lo, b: hi, note });
|
|
428
|
+
if (not) throw new Rejected(not);
|
|
429
|
+
return `to be judged on their own: m${lo} and m${hi} ${said} — ${note}`;
|
|
430
|
+
}
|
|
431
|
+
|
|
308
432
|
/** Each operation in turn. With `refused` — why — every one that would retire a memory is dropped for that reason. */
|
|
309
433
|
function applyEach(db, ops, ctx, refused = null) {
|
|
310
434
|
const applied = [];
|
|
@@ -350,10 +474,14 @@ function tooWide(db, before) {
|
|
|
350
474
|
* @param ctx.turns Map of turn id → user_turns row the model was shown
|
|
351
475
|
*/
|
|
352
476
|
export function applyOps(db, ops, ctx) {
|
|
353
|
-
if (!Array.isArray(ops)) return { applied: [], dropped: ['the answer had no list of operations'] };
|
|
477
|
+
if (!Array.isArray(ops)) return { applied: [], dropped: ['the answer had no list of operations'], written: [] };
|
|
354
478
|
|
|
355
479
|
return tx(db, () => {
|
|
356
|
-
|
|
480
|
+
// `written`: the memories this call made, by id. The transaction holds the write lock, so every id past the highest
|
|
481
|
+
// at its start is this call's — never another process's that finished a moment before or after.
|
|
482
|
+
const from = db.prepare('SELECT COALESCE(MAX(id), 0) AS id FROM memories').get().id;
|
|
483
|
+
const made = (outcome) => ({ ...outcome, written: db.prepare('SELECT id FROM memories WHERE id > ? ORDER BY id').all(from).map((m) => m.id) });
|
|
484
|
+
if (ctx.source !== 'dream') return made(applyEach(db, ops, ctx));
|
|
357
485
|
// The slow pass's answer is tried first and counted, then kept or undone: what it would retire is known exactly
|
|
358
486
|
// that way — a replacement that is only a guess, or aimed at the wrong memory, retires nothing. Too wide, it is
|
|
359
487
|
// applied again without what retires anything, and what it adds is kept.
|
|
@@ -363,6 +491,6 @@ export function applyOps(db, ops, ctx) {
|
|
|
363
491
|
const refused = tooWide(db, before);
|
|
364
492
|
if (refused) db.exec('ROLLBACK TO dream_ops');
|
|
365
493
|
db.exec('RELEASE dream_ops');
|
|
366
|
-
return refused ? applyEach(db, ops, ctx, refused) : tried;
|
|
494
|
+
return made(refused ? applyEach(db, ops, ctx, refused) : tried);
|
|
367
495
|
});
|
|
368
496
|
}
|
package/src/auth.mjs
CHANGED
|
@@ -1,8 +1,29 @@
|
|
|
1
|
-
|
|
1
|
+
/**
|
|
2
|
+
* The SDK, loaded the first time a request is to be made, not when this module is: it is a third of every command's
|
|
3
|
+
* start, and most commands — a hook on every prompt, a search, the memory status — never call the API. The same ES
|
|
4
|
+
* module the rest of the process imports, so its error classes are the ones `instanceof` is checked against.
|
|
5
|
+
*/
|
|
6
|
+
let sdk = null;
|
|
7
|
+
export async function loadSdk() {
|
|
8
|
+
sdk ??= (await import('@anthropic-ai/sdk')).default;
|
|
9
|
+
return sdk;
|
|
10
|
+
}
|
|
11
|
+
/** The SDK if a request has loaded it, else null — and with no SDK loaded, no error can be one of its. */
|
|
12
|
+
export const loadedSdk = () => sdk;
|
|
2
13
|
|
|
3
14
|
/** The request identity Anthropic requires when a Claude Code OAuth token calls the Messages API directly. */
|
|
4
|
-
|
|
5
|
-
|
|
15
|
+
const CLAUDE_CODE_SYSTEM = "You are Claude Code, Anthropic's official CLI for Claude.";
|
|
16
|
+
const CLAUDE_CODE_BETAS = ['claude-code-20250219', 'oauth-2025-04-20'];
|
|
17
|
+
/**
|
|
18
|
+
* The beta a request's server-side fallback is under: a reply the safety classifiers declined is run again on the model
|
|
19
|
+
* Anthropic names for the category, in the same call. Sent with an API key; dropped on the OAuth path, which is not known
|
|
20
|
+
* to take it, and where one unknown beta would refuse every request.
|
|
21
|
+
*/
|
|
22
|
+
export const FALLBACK_BETA = 'server-side-fallback-2026-07-01';
|
|
23
|
+
/** The beta an effort said in the conversation is under — a system message with no content and an `output_config`; dropped on the OAuth path as the fallback is. */
|
|
24
|
+
export const EFFORT_MESSAGE_BETA = 'mid-conversation-output-config-2026-07-01';
|
|
25
|
+
/** Whether a message is an effort said in the conversation: a system message with no content, carrying only the effort. */
|
|
26
|
+
export const effortOnly = (m) => m.role === 'system' && Array.isArray(m.content) && m.content.length === 0 && m.output_config?.effort !== undefined;
|
|
6
27
|
|
|
7
28
|
// Pin the protocol version so authentication does not depend on a local Claude installation.
|
|
8
29
|
const CLAUDE_CODE_VERSION = '2.1.280';
|
|
@@ -33,12 +54,14 @@ export function resolveAnthropicCredential(env = process.env) {
|
|
|
33
54
|
* shell exported another — gets a client of its own; the old one is simply not asked again.
|
|
34
55
|
*/
|
|
35
56
|
const clients = new Map();
|
|
57
|
+
/** A client for the credential; the SDK is loaded first (`await loadSdk()`), by whoever is about to make the request. */
|
|
36
58
|
export function anthropicClient({ timeout, maxRetries = undefined } = {}, credential = resolveAnthropicCredential(), env = process.env) {
|
|
59
|
+
if (!sdk) throw new Error('the Anthropic SDK is not loaded yet: await loadSdk() before asking for a client');
|
|
37
60
|
// The base URL is read from the shell when a client is made: one made for another is not this one.
|
|
38
61
|
const key = JSON.stringify([credential?.type ?? null, credential?.token ?? null, timeout ?? null, maxRetries ?? null, env.ANTHROPIC_BASE_URL ?? null]);
|
|
39
62
|
let client = clients.get(key);
|
|
40
63
|
if (!client) {
|
|
41
|
-
client = new
|
|
64
|
+
client = new sdk({ ...anthropicClientOptions(timeout, credential), ...(maxRetries === undefined ? {} : { maxRetries }) });
|
|
42
65
|
clients.set(key, client);
|
|
43
66
|
}
|
|
44
67
|
return client;
|
|
@@ -64,7 +87,11 @@ export function anthropicClientOptions(timeout, credential = resolveAnthropicCre
|
|
|
64
87
|
return { timeout };
|
|
65
88
|
}
|
|
66
89
|
|
|
67
|
-
/**
|
|
90
|
+
/**
|
|
91
|
+
* Add the OAuth protocol fields — Claude Code's betas and its system line first — without mutating the conversation
|
|
92
|
+
* state reused on later turns. Nothing else changes: the fallback, an effort said by a message and structured output
|
|
93
|
+
* are taken on that path as on an API key (probes/oauth-features.mjs, measured Oct 28 2026).
|
|
94
|
+
*/
|
|
68
95
|
export function authenticatedRequest(params, credential = resolveAnthropicCredential()) {
|
|
69
96
|
if (credential?.type !== 'oauth') return params;
|
|
70
97
|
const system = Array.isArray(params.system)
|
package/src/card.mjs
CHANGED
|
@@ -16,16 +16,49 @@ export function ago(iso, now) {
|
|
|
16
16
|
return `${Math.round(hours / 24)}d ago`;
|
|
17
17
|
}
|
|
18
18
|
|
|
19
|
+
/** How long a guess is put to the user; after that it waits on the memory page and in search. */
|
|
20
|
+
const GUESS_ASKED_DAYS = 14;
|
|
21
|
+
const ASK_LINE_MAX = 120;
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* What to put to the user about these scopes: guesses newer than two weeks, and notices whose two memories both
|
|
25
|
+
* still stand — superseding or forgetting either settles one. The session-start block asks about everything and the
|
|
26
|
+
* session's own project; a project's card asks about that project, wherever the session was started.
|
|
27
|
+
*/
|
|
28
|
+
export function askLines(db, { scopes, now, guesses: maxGuesses, notices: maxNotices }) {
|
|
29
|
+
const marks = scopes.map(() => '?').join(', ');
|
|
30
|
+
const since = new Date(Date.parse(now) - GUESS_ASKED_DAYS * 86_400_000).toISOString();
|
|
31
|
+
const guesses = db.prepare(`SELECT * FROM memories WHERE state = 'unconfirmed' AND scope IN (${marks}) AND created_at >= ? ORDER BY id LIMIT ?`).all(...scopes, since, maxGuesses);
|
|
32
|
+
const out = guesses.map((m) => `Ask the user (then sumo confirm|reject m${m.id}): is this right? "${clip(m.type === 'procedure' ? `workflow "${m.title}"` : m.body, ASK_LINE_MAX)}"`);
|
|
33
|
+
const notices = db
|
|
34
|
+
.prepare(
|
|
35
|
+
`SELECT n.* FROM notices n
|
|
36
|
+
JOIN memories a ON a.id = n.memory_a AND a.state = 'active' AND a.scope IN (${marks})
|
|
37
|
+
JOIN memories b ON b.id = n.memory_b AND b.state = 'active' AND b.scope IN (${marks})
|
|
38
|
+
ORDER BY n.id LIMIT ?`,
|
|
39
|
+
)
|
|
40
|
+
.all(...scopes, ...scopes, maxNotices);
|
|
41
|
+
for (const n of notices) {
|
|
42
|
+
const verb = n.kind === 'lookalike' ? 'look alike' : 'disagree';
|
|
43
|
+
out.push(`Ask the user: m${n.memory_a} and m${n.memory_b} ${verb} — ${clip(n.note, ASK_LINE_MAX)} (sumo show both; settle with sumo supersede or sumo forget)`);
|
|
44
|
+
}
|
|
45
|
+
return out;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** The most a card asks: room is kept for what the project is. */
|
|
49
|
+
const CARD_GUESSES = 2;
|
|
50
|
+
const CARD_NOTICES = 1;
|
|
51
|
+
|
|
19
52
|
/**
|
|
20
53
|
* What an agent needs the moment a project comes up, under a hard budget.
|
|
21
54
|
* To fit, whole lines are left out — and counted, so the card says how much it
|
|
22
55
|
* is not showing. A single over-long line is clipped with a visible ellipsis;
|
|
23
56
|
* `sumo show <id>` has the rest.
|
|
24
57
|
*/
|
|
25
|
-
export function card(db, nameOrAlias, { budget = CARD_BUDGET_TOKENS, now = new Date().toISOString() } = {}) {
|
|
58
|
+
export function card(db, nameOrAlias, { budget = CARD_BUDGET_TOKENS, now = new Date().toISOString(), asks = false } = {}) {
|
|
26
59
|
const project = getProject(db, nameOrAlias);
|
|
27
60
|
// Scratch has no memory to show: its card is how it is used.
|
|
28
|
-
if (isScratch(project)) return [`<project ${project.slug}> ${project.path}`, ...scratchRules(
|
|
61
|
+
if (isScratch(project)) return [`<project ${project.slug}> ${project.path}`, ...scratchRules(), '</project>'].join('\n');
|
|
29
62
|
const scope = `project:${project.slug}`;
|
|
30
63
|
const rows = db
|
|
31
64
|
.prepare(`SELECT * FROM memories WHERE scope = ? AND state = 'active' ORDER BY pinned DESC, importance DESC, hits DESC, id DESC`)
|
|
@@ -36,6 +69,10 @@ export function card(db, nameOrAlias, { budget = CARD_BUDGET_TOKENS, now = new D
|
|
|
36
69
|
// A line that is a memory carries its id, so what the card shows can be counted as used.
|
|
37
70
|
const offer = (priority, text, id = null) => candidates.push({ priority, order: order++, text: clip(text, LINE_MAX), id });
|
|
38
71
|
|
|
72
|
+
// Asked of the user, so only where the user is: first, and whole — clipped, a question would lose what it asks.
|
|
73
|
+
// A job's brief and `sumo project show` leave them out.
|
|
74
|
+
if (asks) for (const text of askLines(db, { scopes: [scope], now, guesses: CARD_GUESSES, notices: CARD_NOTICES })) candidates.push({ priority: 0, order: order++, text, id: null });
|
|
75
|
+
|
|
39
76
|
for (const m of rows.filter((r) => r.scan_key)) offer(SCAN_PRIORITY[m.scan_key] ?? 11, m.body, m.id);
|
|
40
77
|
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
78
|
|
package/src/catalog.mjs
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
import Anthropic from '@anthropic-ai/sdk';
|
|
2
1
|
import { spawnSync } from 'node:child_process';
|
|
3
|
-
import { anthropicClient, resolveAnthropicCredential } from './auth.mjs';
|
|
2
|
+
import { anthropicClient, loadedSdk, loadSdk, resolveAnthropicCredential } from './auth.mjs';
|
|
4
3
|
import { getMeta, setMeta } from './db.mjs';
|
|
5
4
|
import { UsageError } from './memory.mjs';
|
|
6
5
|
|
|
@@ -12,7 +11,7 @@ import { UsageError } from './memory.mjs';
|
|
|
12
11
|
* job's run all read the switches as they are now.
|
|
13
12
|
*/
|
|
14
13
|
export const MODEL_IDS = {
|
|
15
|
-
haiku: 'claude-haiku-
|
|
14
|
+
haiku: 'claude-haiku-5-5',
|
|
16
15
|
sonnet: 'claude-sonnet-5-5',
|
|
17
16
|
opus: 'claude-opus-5-5',
|
|
18
17
|
fable: 'claude-fable-5-1',
|
|
@@ -85,6 +84,9 @@ export function modelLines(db, names = MODELS) {
|
|
|
85
84
|
|
|
86
85
|
/** What went wrong with an API call, in one line a person can act on. */
|
|
87
86
|
export function describeApiError(cause) {
|
|
87
|
+
// Only the SDK makes these errors: with it not loaded, none can be one of them.
|
|
88
|
+
const Anthropic = loadedSdk();
|
|
89
|
+
if (!Anthropic) return String(cause?.message ?? cause).slice(0, 300);
|
|
88
90
|
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
91
|
if (cause instanceof Anthropic.RateLimitError) return 'the API is rate-limiting this key — try again in a minute';
|
|
90
92
|
if (cause instanceof Anthropic.APIError) return `the API answered ${cause.status ?? 'an error'}: ${String(cause.message).slice(0, 300)}`;
|
|
@@ -113,6 +115,7 @@ async function askApi() {
|
|
|
113
115
|
if (standIn) return askStandIn(standIn);
|
|
114
116
|
const credential = resolveAnthropicCredential();
|
|
115
117
|
if (!credential) return { error: 'no Anthropic credential — export ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN in this shell' };
|
|
118
|
+
const Anthropic = await loadSdk();
|
|
116
119
|
const client = anthropicClient({ timeout: TIMEOUT_MS }, credential);
|
|
117
120
|
const options = credential.type === 'oauth' ? { headers: { 'anthropic-beta': OAUTH_BETA } } : {};
|
|
118
121
|
const entries = await Promise.all(
|