sumo-agents 0.3.0 → 0.4.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/README.md CHANGED
@@ -32,7 +32,8 @@ are covered in [Install](https://github.com/sumododda/sumo-agents/wiki/Install).
32
32
 
33
33
  ## Your first session
34
34
 
35
- - Just talk. Name the project you mean; the first time, Sumo confirms its path and registers it.
35
+ - Just talk. Name the project you mean; the first time, Sumo confirms its path and registers it. Started inside a
36
+ registered project, the chat works there from the start.
36
37
  - Say how you like things done. "Always run the linter before you commit" is remembered in your words and
37
38
  loaded next time.
38
39
  - `/fix`, `/feature` and `/review` load a short written procedure for that kind of work. They also load on
@@ -40,7 +41,9 @@ are covered in [Install](https://github.com/sumododda/sumo-agents/wiki/Install).
40
41
  - Big work is delegated without being asked. A row for the job appears under the box, you keep talking,
41
42
  and its report comes back into the conversation.
42
43
  - `/new` starts a fresh session, and a new task deserves one. `/resume` picks an old one up. `/help` lists
43
- the rest.
44
+ the rest, and `?` on an empty box shows the keys you reach for most.
45
+ - Ctrl-R searches what you sent before. `/context` shows how full the context is and what the session has cost.
46
+ `/export` writes the conversation to a Markdown file.
44
47
 
45
48
  ## Good to know
46
49
 
@@ -69,8 +72,10 @@ are covered in [Install](https://github.com/sumododda/sumo-agents/wiki/Install).
69
72
  | `chat.model` | `opus` | What the chat runs on. `auto` lets the local router pick per turn. |
70
73
  | `chat.effort` | `medium` | Effort when the chat model is fixed. |
71
74
  | `chat.budget` | `5` | Dollars a chat session costs before the screen says so; `0` never. |
75
+ | `chat.motion` | `on` | `off` keeps the working line still: no colours flowing through it. |
72
76
  | `projects.home` | `~` | Where new projects are created. |
73
77
  | `jobs.budget` | `10` | Dollars one job may spend before it is stopped; `0` for no cap. |
78
+ | `jobs.floor` | `haiku` | The smallest model a job may run on: `sonnet` keeps every job off Haiku, `opus` puts them all on Opus or Fable. |
74
79
  | `jobs.minutes` | `60` | Minutes one job may run before it is stopped; `0` for no limit. |
75
80
  | `jobs.escalate` | `on` | A worker's failed first attempt is retried once on the next model up. |
76
81
  | `jobs.review` | `risky` | Which verified work gets a reviewer without asking: `risky`, `all` or `off`. |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sumo-agents",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "One repo you talk to: a local memory engine and working process for coding agents.",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/chat.mjs CHANGED
@@ -17,7 +17,7 @@ import { takeLock } from './lock.mjs';
17
17
  import { paths, REPO_ROOT } from './paths.mjs';
18
18
  import { UsageError } from './memory.mjs';
19
19
  import { openInBrowser, servePage } from './page.mjs';
20
- import { getProject, scratchDir } from './projects.mjs';
20
+ import { getProject, projectAt, scratchDir } from './projects.mjs';
21
21
  import { redact } from './redact.mjs';
22
22
  import { chooseChatRoute, EFFORTS } from './route.mjs';
23
23
  import { verifyCommands } from './scan.mjs';
@@ -26,7 +26,7 @@ import { currentProject, describeSaved, findSaved, loadState, lockFile, recordTu
26
26
  import { ASK_TOOL, BASH_TOOL, cap, capRedacted, DELEGATE_TOOL, EDITOR_TOOL, INTERRUPTED, nextUndoTurn, runCommand, undoLast } from './tools.mjs';
27
27
  import { CONFIG_DEFAULTS } from './setup.mjs';
28
28
  import { estimateTokens, head } from './text.mjs';
29
- import { colourEnabled, createRenderer, header, pathFrom, prompt, renderBlock, safeForTerminal, styles, tilde, widthOf } from './tty.mjs';
29
+ import { colourEnabled, createRenderer, header, pathFrom, prompt, renderBlock, safeForTerminal, styles, tilde, toolView, widthOf } from './tty.mjs';
30
30
  import { hasCommit } from './verify.mjs';
31
31
  import { sourcesOf, WEB_FETCH_TOOL, WEB_SEARCH_TOOL, WEB_TOOLS } from './web.mjs';
32
32
 
@@ -76,11 +76,14 @@ export function commandList(db, { effortNow = () => null, saved = () => [], runn
76
76
  { name: 'memory', hint: 'see the memory in the browser: say yes or no, edit, forget' },
77
77
  { name: 'mcp', hint: 'the MCP servers: connected or not, their tools, what may run unasked' },
78
78
  { name: 'resume', hint: 'pick a saved session up where it stopped', choices: (given) => (given.length === 0 ? saved().map((s) => ({ name: shortId(s.id), hint: s.hint })) : []) },
79
- { name: 'copy', hint: 'the last reply to the clipboard, as it was written; `code` for its last code block', choices: (given) => (given.length === 0 ? ['code'] : []) },
79
+ { name: 'copy', hint: 'the last reply to the clipboard, as it was written; `code` for its last code block; a number for one further back', choices: (given) => (given.length === 0 ? ['code'] : []) },
80
80
  { name: 'undo', hint: "put back the files the editor changed in the last turn that changed any; again for the turn before — bash's changes are not tracked" },
81
81
  { name: 'stop', hint: 'stop a job at work in the background', choices: (given) => (given.length === 0 ? running().map((id) => `j${id}`) : []) },
82
+ { name: 'context', hint: 'what this session has used: how full the context is, the tokens and the cost, by model' },
83
+ { name: 'export', hint: 'the conversation as a Markdown file: to a path, or into the home\'s exports folder' },
84
+ { name: 'thinking', hint: 'the model\'s thinking under the working line: on or off', choices: (given) => (given.length === 0 ? ['on', 'off'] : []) },
82
85
  { name: 'help', hint: 'the commands and the keys' },
83
- { name: 'new', hint: 'start a fresh session' },
86
+ { name: 'new', hint: 'start a fresh session (/clear does too)' },
84
87
  { name: 'exit', hint: 'leave' },
85
88
  ];
86
89
  }
@@ -198,14 +201,23 @@ export function parseRoute(args, current, db) {
198
201
  * draws a reply, set in under its line. `clean` is done to the words before they are drawn: a wrapped line must not
199
202
  * break a secret apart where the redaction after it would no longer see it whole.
200
203
  */
201
- export function jobPrinter(write, s, { width = 98, clean = (text) => text } = {}) {
204
+ export function jobPrinter(write, s, { width = 98, clean = (text) => text, cwd = null } = {}) {
205
+ // Each call as the chat names it — Bash(npm test), Read(src/cart.js) — a file from the project the job works in.
206
+ const at = () => (typeof cwd === 'function' ? cwd() : cwd);
202
207
  return {
203
208
  onStart: (job) => write(`⏺ ${s.bold(`j${job.id}`)} ${job.agent} · ${routeOf(job)} — ${job.title}\n`),
204
- onTool: (call) => write(` ⏺ ${describeCall(call)}\n`),
209
+ onTool: (call) => {
210
+ const view = toolView(call, null, { cwd: at() });
211
+ // One line, and where more was cut away, the ellipsis that says so.
212
+ const [first, ...rest] = clean(view.detail).split('\n');
213
+ const line = first.length > 160 ? `${first.slice(0, 159)}…` : rest.length > 0 && !first.endsWith('…') ? `${first} …` : first;
214
+ write(` ⏺ ${s.bold(view.title)}(${line})\n`);
215
+ },
205
216
  onRetry: (r) => write(` ${s.dim(retryLine(r))}\n`),
206
217
  onCompact: (c) => write(` ${s.dim(compactLine(c))}\n`),
207
218
  onResult: (call, result) => {
208
- const first = String(result.content ?? '').split('\n').find((l) => l.trim()) ?? '';
219
+ // The line that says how it went, as the chat's screen would show it: what a command printed first, a read's size, an edit's first change.
220
+ const first = toolView(call, { content: String(result.content ?? ''), isError: Boolean(result.isError), edit: result.edit }, { cwd: at() }).lines[0]?.text ?? '';
209
221
  write(` ⎿ ${s.dim(clean(first).slice(0, 160))}\n`);
210
222
  },
211
223
  onTurn: (response) => {
@@ -224,9 +236,29 @@ export function jobPrinter(write, s, { width = 98, clean = (text) => text } = {}
224
236
  export const retryLine = ({ attempt, limit, delayMs, reason }) => `retrying in ${Math.max(1, Math.round(delayMs / 1000))}s (${attempt} of ${limit}) — ${reason}`;
225
237
  /** A conversation summarized to make room, in one line: how big it had grown. */
226
238
  export const compactLine = ({ before }) => `the conversation was summarized at ${Math.round(before / 1000)}k tokens to make room, and goes on from the summary`;
239
+ const kilo = (n) => (n >= 1000 ? `${(n / 1000).toFixed(n >= 10_000 ? 0 : 1)}k` : String(n));
240
+
241
+ /**
242
+ * `/context`: how full the context is — against the size where it is time to start afresh, with the word for its band — and
243
+ * what the session has used, by who asked and on which model. Markdown, drawn as a reply is.
244
+ */
245
+ export function contextReport({ contextTokens = 0, rows = [], turns = 0, calls = 0 }) {
246
+ const full = Math.min(1, contextTokens / CONTEXT_FULL);
247
+ const bar = `${'█'.repeat(Math.round(full * 20))}${'░'.repeat(20 - Math.round(full * 20))}`;
248
+ const band = contextTokens >= CONTEXT_FULL ? 'very large — /new now; the memory brings the thread back' : contextTokens >= CONTEXT_LARGE ? 'large — quality drops from here; finish the piece in hand, then /new' : 'room to spare';
249
+ const cost = rows.reduce((sum, row) => sum + row.cost, 0);
250
+ const lines = [`**Context** ${kilo(contextTokens)} tokens · \`${bar}\` ${Math.round(full * 100)}% of ${kilo(CONTEXT_FULL)} · ${band}`, '', `**This session** ${turns} turn${turns === 1 ? '' : 's'} · ${calls} tool call${calls === 1 ? '' : 's'} · $${cost.toFixed(2)}`];
251
+ if (rows.length === 0) return [...lines, '', 'No request has been made yet.'].join('\n');
252
+ return [...lines, '', '| Who | Model | Requests | In | Cached | Out | Cost |', '|---|---|--:|--:|--:|--:|--:|', ...rows.map((row) => `| ${row.kind} | ${row.model} | ${row.requests} | ${kilo(row.input)} | ${kilo(row.cached)} | ${kilo(row.output)} | $${row.cost.toFixed(2)} |`)].join('\n');
253
+ }
254
+
227
255
  /** A session past its budget, in one line: what it has cost, how to start afresh, and how to move the line. */
228
256
  export const budgetLine = (cost) => `this session has cost $${cost.toFixed(2)} — /new starts a fresh one; sumo config chat.budget changes when this is said`;
229
257
 
258
+ /** Where the context is large enough that quality drops, and where it is time for /new: the bands the session is told about. */
259
+ const CONTEXT_LARGE = 60_000;
260
+ const CONTEXT_FULL = 150_000;
261
+
230
262
  /** The session log, one JSON line per message, the shape the scribe reads assistant replies from and the gauge reads usage from. */
231
263
  function logLine(file, entry) {
232
264
  appendFileSync(file, `${JSON.stringify({ timestamp: new Date().toISOString(), ...entry })}\n`, { mode: 0o600 });
@@ -283,6 +315,8 @@ export function createChat(db, { model, effort, cwd = process.cwd(), send = send
283
315
  const own = CHAT_TOOLS;
284
316
  /** The MCP servers of this process, once connected: their tools join the request, deferred, and their names the system prompt. */
285
317
  let registry = null;
318
+ /** Whether the servers' tools have joined the requests: once, at the first turn after they connected. */
319
+ let joined = false;
286
320
  const connecting = mcpReady().then((r) => {
287
321
  registry = r;
288
322
  });
@@ -366,6 +400,8 @@ export function createChat(db, { model, effort, cwd = process.cwd(), send = send
366
400
  if (modelId(model) === MODEL_IDS.haiku) effort = 'none';
367
401
  }
368
402
  params = paramsFor({ model: model === 'auto' ? (routed?.model ?? CONFIG_DEFAULTS['chat.model']) : model, effort: model === 'auto' ? routed?.effort : effort, tools: toolsNow(), system: systemNow(), text: saved ? undefined : block });
403
+ // What jobs reported that this session had not read comes back with it; a fresh session has read nothing, and is owed nothing.
404
+ reports.splice(0, reports.length, ...(saved?.pending ?? []));
369
405
  if (saved) {
370
406
  params.messages = withoutThinking(saved.messages);
371
407
  note = `resumed: this session was saved ${ago(saved.savedAt, now())} and picked up again now, in ${cwd}. Carry on where it stopped; memory may have changed since this session's first block — search it before assuming.`;
@@ -390,11 +426,20 @@ export function createChat(db, { model, effort, cwd = process.cwd(), send = send
390
426
  return `resumed ${sessionLine(found, now())} — the first reply pays one uncached turn`;
391
427
  }
392
428
 
429
+ /** The session kept where nothing can say a failure: a save that fails here is tried again after the next turn. */
430
+ function keepQuietly() {
431
+ try {
432
+ persist();
433
+ } catch {
434
+ // Said, if it still fails, by the save after the next turn.
435
+ }
436
+ }
437
+
393
438
  /** The session as it stands, kept after every turn. A save that fails is said as the turn's error: the turn itself went fine. */
394
439
  function persist() {
395
440
  if (!spoken) return;
396
441
  try {
397
- saveState({ id: sessionId, messages: params.messages, model, effort, routed, cwd, contextTokens: lastContext, now: now() });
442
+ saveState({ id: sessionId, messages: params.messages, model, effort, routed, cwd, contextTokens: lastContext, now: now(), pending: reports.map(({ id, quiet, text }) => ({ id, quiet, text })) });
398
443
  } catch (cause) {
399
444
  throw new UsageError(`the session could not be saved: ${cause.message}`);
400
445
  }
@@ -431,9 +476,12 @@ export function createChat(db, { model, effort, cwd = process.cwd(), send = send
431
476
  /** Where this session's turns keep what the editor changed, for /undo. */
432
477
  const undoDir = () => join(paths().logs, 'undo', sessionId);
433
478
 
434
- /** The project the work is in: the one whose card came in last, else none (tools then run in scratch, wherever the chat was started). */
479
+ /**
480
+ * The project the work is in: the one whose card came in last; before any has, the one the chat was started in; else none
481
+ * (tools then run in scratch).
482
+ */
435
483
  function workspace() {
436
- const slug = currentProject(db, sessionId);
484
+ const slug = currentProject(db, sessionId) ?? projectAt(db, cwd);
437
485
  if (slug && project?.slug !== slug) project = getProject(db, slug);
438
486
  return contextFor(project ?? { path: scratchDir() }, { sandbox: sandboxOn(db), network: networkOn(db) });
439
487
  }
@@ -558,6 +606,8 @@ export function createChat(db, { model, effort, cwd = process.cwd(), send = send
558
606
  runs.delete(run);
559
607
  const quiet = ids.filter((each) => stoppedByUser.delete(each)).length > 0;
560
608
  reports.push({ id, quiet, text: `An automated event, not a message from the user: ${ids.map((each) => `j${each}`).join(', ')} ${ids.length === 1 ? 'has' : 'have'} reported.\n${result.content}` });
609
+ // Kept with the session as soon as it comes: a chat closed before the next message still has it when picked up again.
610
+ keepQuietly();
561
611
  watch({ type: 'job-report', job: id, result, quiet });
562
612
  });
563
613
  runs.add(run);
@@ -608,7 +658,7 @@ export function createChat(db, { model, effort, cwd = process.cwd(), send = send
608
658
  // Its work is written down as it happens, for `sumo job watch` — in a Herdr tab of its own, or any terminal —
609
659
  // and without its secrets, through the same redaction as what the model sees.
610
660
  const record = (t) => appendLive(id, redact(t).text);
611
- const live = jobPrinter(record, styles(false), { clean: (t) => redact(t).text });
661
+ const live = jobPrinter(record, styles(false), { clean: (t) => redact(t).text, cwd: () => getProject(db, getJob(db, id)?.project ?? '')?.path ?? null });
612
662
  let ended = [];
613
663
  try {
614
664
  const outcome = await runJob(db, id, {
@@ -783,12 +833,14 @@ export function createChat(db, { model, effort, cwd = process.cwd(), send = send
783
833
  const checks = declared();
784
834
  if (checks.length === 0 || checks.some((c) => String(call.input?.command ?? '').includes(c))) unchecked.clear();
785
835
  };
786
- // The servers connect while the first turn is typed; the first request waits for them, and Esc does not.
787
- if (!registry) {
836
+ // The servers connect while the first turn is typed; the first request waits for them, and Esc does not. Their tools
837
+ // join the request then — even when something else, /mcp, already waited for them to connect.
838
+ if (!joined) {
788
839
  const stopped = new Promise((resolve) => stopper.signal.addEventListener('abort', () => resolve('stopped'), { once: true }));
789
840
  if ((await Promise.race([connecting, stopped])) === 'stopped') return { stop: 'interrupted', error: null, text: '' };
790
841
  params.tools = toolsNow();
791
842
  params.system[0].text = systemNow();
843
+ joined = true;
792
844
  if (registry.servers().length > 0 || registry.error) watch({ type: 'mcp', servers: registry.servers(), error: registry.error });
793
845
  }
794
846
  // On auto the router names this turn's model first; a router that cannot answer refuses the turn, and nothing of it reaches the conversation.
@@ -927,8 +979,9 @@ export function createChat(db, { model, effort, cwd = process.cwd(), send = send
927
979
  if (!m) return { text: line };
928
980
  const [, name, args = ''] = m;
929
981
  if (name === 'exit' || name === 'quit') return { control: 'quit' };
930
- if (name === 'new' || name === 'memory' || name === 'undo') return { control: name };
931
- if (name === 'model' || name === 'resume' || name === 'mcp' || name === 'copy' || name === 'help' || name === 'stop') return { control: name, args: args.trim() };
982
+ if (name === 'new' || name === 'clear') return { control: 'new' };
983
+ if (name === 'memory' || name === 'undo' || name === 'context') return { control: name };
984
+ if (name === 'model' || name === 'resume' || name === 'mcp' || name === 'copy' || name === 'help' || name === 'stop' || name === 'export' || name === 'thinking') return { control: name, args: args.trim() };
932
985
  const make = Object.hasOwn(COMMANDS, name) ? COMMANDS[name] : undefined;
933
986
  return make ? { ...make(args.trim()), said: args.trim() } : { error: `no such command /${name} — one of: ${commands.map((c) => `/${c.name}`).join(' ')}` };
934
987
  }
@@ -956,6 +1009,18 @@ export function createChat(db, { model, effort, cwd = process.cwd(), send = send
956
1009
  return { cwd: at, name: project?.slug ?? basename(at), branch: branchOf(at) };
957
1010
  }
958
1011
 
1012
+ /** What this session's requests have used so far, the jobs it delegated included: by the kind of conversation and the model, dearest first. */
1013
+ const usage = () =>
1014
+ sessionId
1015
+ ? db
1016
+ .prepare(
1017
+ `SELECT kind, model, COUNT(*) AS requests, COALESCE(SUM(input_tokens), 0) AS input, COALESCE(SUM(output_tokens), 0) AS output,
1018
+ COALESCE(SUM(cache_read_tokens), 0) AS cached, COALESCE(SUM(cost_usd), 0) AS cost
1019
+ FROM model_runs WHERE session_id = ? GROUP BY kind, model ORDER BY cost DESC`,
1020
+ )
1021
+ .all(sessionId)
1022
+ : [];
1023
+
959
1024
  /** What this session's requests have cost so far, the jobs it delegated included: the ledger's own sum. */
960
1025
  const spent = () => (sessionId ? db.prepare('SELECT COALESCE(SUM(cost_usd), 0) AS cost FROM model_runs WHERE session_id = ?').get(sessionId).cost : 0);
961
1026
 
@@ -974,6 +1039,8 @@ export function createChat(db, { model, effort, cwd = process.cwd(), send = send
974
1039
  }
975
1040
 
976
1041
  function end() {
1042
+ // Kept as it stands, reports not yet read with it, before the session is let go.
1043
+ if (sessionId) keepQuietly();
977
1044
  event('session-end', {});
978
1045
  if (lock) rmSync(lock, { force: true });
979
1046
  lock = null;
@@ -995,6 +1062,7 @@ export function createChat(db, { model, effort, cwd = process.cwd(), send = send
995
1062
  waiting,
996
1063
  where,
997
1064
  spent,
1065
+ usage,
998
1066
  tell,
999
1067
  shell,
1000
1068
  undo,
@@ -1010,6 +1078,10 @@ export function createChat(db, { model, effort, cwd = process.cwd(), send = send
1010
1078
  get sessionId() {
1011
1079
  return sessionId;
1012
1080
  },
1081
+ /** Whether anything has been said in this session: one nobody spoke to is not kept, and there is nothing to pick up again. */
1082
+ get spoken() {
1083
+ return spoken;
1084
+ },
1013
1085
  get model() {
1014
1086
  return model;
1015
1087
  },
@@ -1045,7 +1117,13 @@ async function screen(db, { model, effort, resume }) {
1045
1117
  ask: (question) => new Promise((resolve) => events.emit('ask', { ...question, resolve })),
1046
1118
  });
1047
1119
  try {
1048
- await runUi({ session, events, resume, notify: configured(db, 'chat.notify') !== 'off' }).waitUntilExit();
1120
+ await runUi({ session, events, resume, notify: configured(db, 'chat.notify') !== 'off', motion: configured(db, 'chat.motion') !== 'off' }).waitUntilExit();
1121
+ // The way back in, said as the screen closes: the command that picks this session up again, and what it cost.
1122
+ if (session.spoken) {
1123
+ const s = styles(colourEnabled());
1124
+ const cost = session.spent();
1125
+ process.stdout.write(`\n${s.dim(` sumo chat --resume ${shortId(session.sessionId)} picks this session up again${cost >= 0.005 ? ` · it cost $${cost.toFixed(2)}` : ''}`)}\n\n`);
1126
+ }
1049
1127
  } finally {
1050
1128
  // Jobs still at work in the background are stopped with the chat, and let go of what they hold before it closes.
1051
1129
  await session.settle();
@@ -1142,6 +1220,17 @@ export async function chat(db, { model, effort, resume = null, send, input = pro
1142
1220
  result(control === 'model' ? session.route(args) : control === 'undo' ? session.undo() : control === 'mcp' ? (await session.mcp()).join('\n ') : await session.memoryPage());
1143
1221
  continue;
1144
1222
  }
1223
+ if (control === 'context') {
1224
+ reply.write(contextReport({ contextTokens: session.contextTokens, rows: session.usage() }));
1225
+ reply.flush();
1226
+ write('\n');
1227
+ continue;
1228
+ }
1229
+ // The rest belong to the screen — a clipboard, a pager, jobs under the box — and are never sent to the model as words.
1230
+ if (control) {
1231
+ result(`/${control} is for the chat on a terminal screen`);
1232
+ continue;
1233
+ }
1145
1234
  write('\n');
1146
1235
  const outcome = await session.say(text, said, [], { guide });
1147
1236
  reply.flush();
package/src/editor.mjs CHANGED
@@ -4,8 +4,15 @@
4
4
  * function from one state to the next, so the screen only has to draw it.
5
5
  */
6
6
 
7
- /** An empty box. `history` is what Up recalls, oldest first; `at` is the entry shown, one past the end for the text being written. */
8
- export const editor = (history = []) => ({ text: '', cursor: 0, history, at: history.length, draft: '', pick: 0 });
7
+ /**
8
+ * An empty box. `history` is what Up recalls, oldest first; `at` is the entry shown, one past the end for the text being written.
9
+ * `undo` is what the text was before each change, newest last; `kill` is the last thing cut, for Ctrl-Y; `search`, while Ctrl-R
10
+ * looks back through history, what has been typed to find and where it was found.
11
+ */
12
+ export const editor = (history = [], kill = '') => ({ text: '', cursor: 0, history, at: history.length, draft: '', pick: 0, undo: [], kill, search: null });
13
+
14
+ /** How many changes Ctrl-_ can take back. */
15
+ const UNDO_KEPT = 100;
9
16
 
10
17
  /**
11
18
  * The menu for what is being typed: the commands a half-typed slash could mean, or, once a command's
@@ -13,8 +20,28 @@ export const editor = (history = []) => ({ text: '', cursor: 0, history, at: his
13
20
  * command that offers none. Each entry says what to show (`label`), its hint, and the whole text
14
21
  * picking it leaves in the box (`complete`).
15
22
  */
23
+ /** How well a few typed letters name a command: from its start best, then anywhere in it, then in order with gaps between; -1 when they do not. */
24
+ function nameRank(name, typed) {
25
+ if (name.startsWith(typed)) return 0;
26
+ if (name.includes(typed)) return 1;
27
+ let at = 0;
28
+ for (const ch of typed) {
29
+ at = name.indexOf(ch, at) + 1;
30
+ if (at === 0) return -1;
31
+ }
32
+ return 2;
33
+ }
34
+
16
35
  export function menuFor(text, commands) {
17
- if (/^\/\w*$/.test(text)) return commands.filter((c) => c.name.startsWith(text.slice(1))).map((c) => ({ name: c.name, label: `/${c.name}`, hint: c.hint, complete: `/${c.name} ` }));
36
+ if (/^\/\w*$/.test(text)) {
37
+ // A command is found by any of its letters, in order: /rsm is /resume. The ones it starts with come first, in the menu's own order.
38
+ const typed = text.slice(1);
39
+ return commands
40
+ .map((c, i) => [nameRank(c.name, typed), i, c])
41
+ .filter(([rank]) => rank !== -1)
42
+ .sort((a, b) => a[0] - b[0] || a[1] - b[1])
43
+ .map(([, , c]) => ({ name: c.name, label: `/${c.name}`, hint: c.hint, complete: `/${c.name} ` }));
44
+ }
18
45
  const m = /^\/(\w+)\s+([^\n]*)$/.exec(text);
19
46
  const command = m && commands.find((c) => c.name === m[1] && c.choices);
20
47
  if (!command) return [];
@@ -89,7 +116,56 @@ const insert = (state, chunk) => edit(state, state.text.slice(0, state.cursor) +
89
116
  const cut = (state, from, to) => edit(state, state.text.slice(0, from) + state.text.slice(to), from);
90
117
 
91
118
  /** Pasted text goes in whole, its line ends made plain; a newline in it is never Enter. */
92
- export const paste = (state, text) => insert(state, text.replace(/\r\n?/g, '\n'));
119
+ export const paste = (state, text) => remember(state, insert(state, text.replace(/\r\n?/g, '\n')));
120
+
121
+ /**
122
+ * Characters nobody sees that change what text says: direction overrides, zero-width spaces, the invisible tag letters that
123
+ * can carry a hidden instruction. The joiner and the selectors an emoji is built from are not among them.
124
+ */
125
+ const INVISIBLE = /[\u200b\u200c\u200e\u200f\u202a-\u202e\u2060-\u2064\u2066-\u2069\ufeff\u{e0000}-\u{e007f}]/gu;
126
+
127
+ /** Text from the clipboard as the box takes it: without the characters nobody sees, and how many were taken out. */
128
+ export function cleanPaste(text) {
129
+ const removed = String(text).match(INVISIBLE)?.length ?? 0;
130
+ return { text: removed ? String(text).replace(INVISIBLE, '') : String(text), removed };
131
+ }
132
+
133
+ /** A marker standing for something put in the box — an image, a long paste — ending at the cursor: deleted whole, never a character of it. */
134
+ const MARKER_BEFORE = /\[(?:Image #\d+|Pasted text #\d+[^\]\n]*)\] ?$/;
135
+
136
+ /** The state after a change, carrying what the text was before it so Ctrl-_ can take it back. A run of letters typed is one change. */
137
+ function remember(before, after, typing = false) {
138
+ if (after.text === before.text) return after;
139
+ const run = typing && before.typing;
140
+ const undo = run ? before.undo : [...before.undo, { text: before.text, cursor: before.cursor }].slice(-UNDO_KEPT);
141
+ return { ...after, undo, typing };
142
+ }
143
+
144
+ /** What was cut is kept for Ctrl-Y as well as gone from the box. */
145
+ const killed = (state, from, to) => ({ ...cut(state, from, to), kill: state.text.slice(from, to) || state.kill });
146
+
147
+ /** Ctrl-R: the newest line sent before `below` that holds `query`, put in the box with the cursor where it was found. */
148
+ function find(state, query, below, further = false) {
149
+ const { search } = state;
150
+ for (let i = Math.min(below, state.history.length) - 1; i >= 0; i--) {
151
+ const at = query ? state.history[i].toLowerCase().indexOf(query.toLowerCase()) : -1;
152
+ if (at !== -1) return { ...state, text: state.history[i], cursor: at, search: { ...search, query, at: i, failed: false, end: false } };
153
+ }
154
+ // Nothing further back keeps what was found; nothing at all says so.
155
+ if (further && search.at !== null) return { ...state, search: { ...search, end: true } };
156
+ return { ...state, search: { ...search, query, at: null, failed: query !== '', end: false } };
157
+ }
158
+
159
+ /** A key while Ctrl-R looks back: typing narrows it, Ctrl-R goes further back, Enter keeps what was found, Esc puts the draft back. */
160
+ function searching(state, input, key) {
161
+ const { search } = state;
162
+ if (key.escape || (key.ctrl && (input === 'g' || input === 'c'))) return { ...state, text: search.draft.text, cursor: search.draft.cursor, search: null };
163
+ if (key.ctrl && input === 'r') return find(state, search.query, search.at ?? state.history.length, true);
164
+ if (key.backspace) return find(state, search.query.slice(0, -1), state.history.length);
165
+ if (input && !key.ctrl && !key.meta && !key.return && !key.tab) return find(state, search.query + input, state.history.length);
166
+ // Anything else keeps what was found in the box, to send or to edit.
167
+ return { ...state, at: state.history.length, search: null };
168
+ }
93
169
 
94
170
  const BURST_KEYS = { '\r': ['\r', { return: true }], '\t': ['', { tab: true }], '\x7f': ['', { backspace: true }] };
95
171
  /** A control character is Ctrl and a letter: 3 is Ctrl-C. */
@@ -141,7 +217,7 @@ function send(state) {
141
217
  const text = state.text.trim();
142
218
  if (!text) return { state: edit(state, '', 0) };
143
219
  const history = state.history.at(-1) === text ? state.history : [...state.history, text];
144
- return { state: editor(history), submit: text };
220
+ return { state: editor(history, state.kill), submit: text };
145
221
  }
146
222
 
147
223
  /**
@@ -150,6 +226,22 @@ function send(state) {
150
226
  * sent the text.
151
227
  */
152
228
  export function press(state, input, key, commands = [], files = null) {
229
+ if (state.search) return { state: searching(state, input, key) };
230
+ if (key.ctrl && input === 'r') return { state: find({ ...state, search: { query: '', at: null, failed: false, draft: { text: state.text, cursor: state.cursor } } }, '', state.history.length) };
231
+ // Ctrl-_ (Ctrl-/ on most keyboards): the text as it was before the last change.
232
+ if (input === '\x1f') {
233
+ const last = state.undo.at(-1);
234
+ return { state: last ? { ...state, text: last.text, cursor: last.cursor, undo: state.undo.slice(0, -1), typing: false, pick: 0 } : state };
235
+ }
236
+ const pressed = keyed(state, input, key, commands, files);
237
+ const typing = !key.ctrl && !key.meta && input.length === 1 && /\S/.test(input) && !key.return && !key.tab;
238
+ // Sent, the box starts afresh: there is nothing to take back into it. A key that changed nothing hands back the same state:
239
+ // the screen reads that as Down having left the box.
240
+ if (pressed.submit !== undefined || pressed.state === state) return pressed;
241
+ return { ...pressed, state: { ...remember(state, pressed.state, typing), typing } };
242
+ }
243
+
244
+ function keyed(state, input, key, commands, files) {
153
245
  const menu = menuOf(state, commands, files);
154
246
  const { text, cursor } = state;
155
247
  const word = key.meta || key.ctrl;
@@ -171,7 +263,11 @@ export function press(state, input, key, commands = [], files = null) {
171
263
  if (key.rightArrow) return { state: { ...state, cursor: word ? wordRight(state) : cursor + under(state).length } };
172
264
  if (key.home) return { state: { ...state, cursor: lineStart(state) } };
173
265
  if (key.end) return { state: { ...state, cursor: lineEnd(state) } };
174
- if (key.backspace) return { state: cut(state, key.meta ? wordLeft(state) : cursor - before(state).length, cursor) };
266
+ if (key.backspace && key.meta) return { state: killed(state, wordLeft(state), cursor) };
267
+ if (key.backspace) {
268
+ const marker = MARKER_BEFORE.exec(text.slice(0, cursor));
269
+ return { state: cut(state, marker ? cursor - marker[0].length : cursor - before(state).length, cursor) };
270
+ }
175
271
  if (key.delete) return { state: cut(state, cursor, cursor + under(state).length) };
176
272
 
177
273
  if (key.ctrl) {
@@ -181,16 +277,21 @@ export function press(state, input, key, commands = [], files = null) {
181
277
  if (input === 'u') {
182
278
  // At the start of a line nothing of it is before the cursor: the line above goes instead, so pressing it again clears a box of many lines.
183
279
  const start = lineStart(state);
184
- return { state: cut(state, start === cursor && cursor > 0 ? lineStart({ text: state.text, cursor: cursor - 1 }) : start, cursor) };
280
+ return { state: killed(state, start === cursor && cursor > 0 ? lineStart({ text: state.text, cursor: cursor - 1 }) : start, cursor) };
185
281
  }
186
- if (input === 'k') return { state: cut(state, cursor, lineEnd(state)) };
187
- if (input === 'w') return { state: cut(state, wordLeft(state), cursor) };
282
+ if (input === 'k') return { state: killed(state, cursor, lineEnd(state)) };
283
+ if (input === 'w') return { state: killed(state, wordLeft(state), cursor) };
188
284
  if (input === 'd') return { state: cut(state, cursor, cursor + under(state).length) };
285
+ // What Ctrl-U, Ctrl-K, Ctrl-W or Option-Backspace cut, put back where the cursor is.
286
+ if (input === 'y') return { state: state.kill ? insert(state, state.kill) : state };
287
+ if (input === 'b') return { state: { ...state, cursor: cursor - before(state).length } };
288
+ if (input === 'f') return { state: { ...state, cursor: cursor + under(state).length } };
189
289
  return { state };
190
290
  }
191
291
  if (key.meta) {
192
292
  if (input === 'b') return { state: { ...state, cursor: wordLeft(state) } };
193
293
  if (input === 'f') return { state: { ...state, cursor: wordRight(state) } };
294
+ if (input === 'd') return { state: killed(state, cursor, wordRight(state)) };
194
295
  return { state };
195
296
  }
196
297
  if (!input) return { state };
package/src/herdr.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  import { spawnSync } from 'node:child_process';
2
- import { paths } from './paths.mjs';
2
+ import { existsSync } from 'node:fs';
3
+ import { paths, SELF } from './paths.mjs';
3
4
 
4
5
  /**
5
6
  * Herdr is where a delegated job can be watched. The job itself runs in the chat's process; inside Herdr it also
@@ -37,7 +38,9 @@ export function openWatchTab(herdr, { job, project, env = process.env, onFail =
37
38
  if (tab.error) throw new Error(tab.error);
38
39
  // Marked as the tab's own, so the watcher may close it behind a job that is done; the home goes with the command,
39
40
  // or a chat on another home would be watched from the default one.
40
- const command = `env SUMO_JOB_TAB=1 SUMO_AGENTS_HOME=${shellWord(paths().home)} ${shellWord(paths().launcher)} job watch ${job.id}`;
41
+ // The launcher setup made, where there is one; else this very sumo, node and entry by their full paths — a clone not set up yet still has a watcher.
42
+ const sumo = existsSync(paths().launcher) ? shellWord(paths().launcher) : SELF.map(shellWord).join(' ');
43
+ const command = `env SUMO_JOB_TAB=1 SUMO_AGENTS_HOME=${shellWord(paths().home)} ${sumo} job watch ${job.id}`;
41
44
  startWatcher(herdr, { pane: tab.id, job: job.id, command, sleep })
42
45
  .then((started) => started || onFail('its Herdr tab never started the watcher'))
43
46
  .catch((cause) => onFail(cause.message));
package/src/hooks.mjs CHANGED
@@ -7,7 +7,7 @@ import { guardCommand, guardPath } from './guard.mjs';
7
7
  import { autoGuides, firingGuides, matchGuide, renderGuide } from './guides.mjs';
8
8
  import { paths } from './paths.mjs';
9
9
  import { prime } from './prime.mjs';
10
- import { detect, keepScratch, touch } from './projects.mjs';
10
+ import { detect, keepScratch, projectAt, touch } from './projects.mjs';
11
11
  import { closingQuestions, recallBeforeAsking } from './recall.mjs';
12
12
  import { line } from './render.mjs';
13
13
  import { shouldRun, spawnDetached } from './scribe.mjs';
@@ -159,7 +159,10 @@ const HANDLERS = {
159
159
 
160
160
  const shown = new Set(injectedSlugs(db, e.sessionId));
161
161
  const cards = [];
162
- for (const slug of detect(db, e.prompt)) {
162
+ // A session started inside a project, whose first words name none, is about that project: it is the one meant.
163
+ const named = detect(db, e.prompt);
164
+ const here = named.length === 0 && shown.size === 0 && e.cwd ? projectAt(db, e.cwd) : null;
165
+ for (const slug of here ? [here] : named) {
163
166
  touch(db, slug, now);
164
167
  // Every mention is stamped, not only the first: the project named last is the one the session is about, also when its card was shown before.
165
168
  markInjected(db, e.sessionId, slug, now);
package/src/projects.mjs CHANGED
@@ -167,6 +167,24 @@ export function detect(db, text) {
167
167
  return [...found];
168
168
  }
169
169
 
170
+ /**
171
+ * The registered project a directory is in — the project itself or a folder inside it, the deepest when one holds another —
172
+ * or null. A path reached through a link is read as where it leads, as a project's own path is.
173
+ */
174
+ export function projectAt(db, dir) {
175
+ let at;
176
+ try {
177
+ at = realpathSync(resolve(dir));
178
+ } catch {
179
+ at = resolve(dir);
180
+ }
181
+ const inside = db
182
+ .prepare(`SELECT slug, path FROM projects WHERE status = 'active'`)
183
+ .all()
184
+ .filter(({ path }) => at === path || at.startsWith(path.endsWith('/') ? path : `${path}/`));
185
+ return inside.sort((a, b) => b.path.length - a.path.length)[0]?.slug ?? null;
186
+ }
187
+
170
188
  /** The project for work that belongs to none. It lives in Sumo's own home, and a chore in it is kept only while it is worked on. */
171
189
  export const SCRATCH = 'scratch';
172
190
  const DAY_MS = 24 * 3_600_000;
package/src/route.mjs CHANGED
@@ -1,4 +1,6 @@
1
1
  import { MODELS, usableModels } from './catalog.mjs';
2
+ import { getMeta } from './db.mjs';
3
+ import { CONFIG_DEFAULTS } from './setup.mjs';
2
4
  import { callLocalModel } from './model.mjs';
3
5
  import { UsageError } from './memory.mjs';
4
6
  import { elapsed } from './text.mjs';
@@ -148,7 +150,7 @@ function routerPrompt(db, { agent, project, task, title, retryOf }) {
148
150
  return [
149
151
  `role: ${agent}`,
150
152
  `project: ${project.slug}${stack ? ` (${stack})` : ''}`,
151
- `models: ${usableModels(db).join(', ')}`,
153
+ `models: ${jobModels(db).join(', ')}`,
152
154
  ...(retryOf === undefined ? [] : [retryLine(db, retryOf)].filter(Boolean)),
153
155
  'history:',
154
156
  historyText(db, project.slug),
@@ -177,10 +179,20 @@ function chatRouterPrompt(db, { project, text }) {
177
179
  return [`project: ${project ? `${project.slug}${stack ? ` (${stack})` : ''}` : 'none'}`, `models: ${usableModels(db).join(', ')}`, 'turn:', String(text ?? '').slice(0, TASK_CUT)].join('\n');
178
180
  }
179
181
 
180
- const askRouter = (db, { agent, project, task, title, retryOf }) => askFor(db, agent === 'scout' ? SCOUT_ROUTER_SYSTEM : ROUTER_SYSTEM, routerPrompt(db, { agent, project, task, title, retryOf }));
182
+ /** The smallest model a job may run on (`jobs.floor`); haiku, the cheapest, holds nothing back. */
183
+ export const jobFloor = (db) => getMeta(db, 'config.jobs.floor') ?? CONFIG_DEFAULTS['jobs.floor'];
181
184
 
182
- async function askFor(db, system, prompt) {
185
+ /** The models a job may be routed to: the ones that are on, from the floor up — or all of them, when none at or above it is on. */
186
+ export function jobModels(db) {
183
187
  const usable = usableModels(db);
188
+ const above = usable.filter((m) => MODELS.indexOf(m) >= MODELS.indexOf(jobFloor(db)));
189
+ return above.length > 0 ? above : usable;
190
+ }
191
+
192
+ const askRouter = (db, { agent, project, task, title, retryOf }) => askFor(db, agent === 'scout' ? SCOUT_ROUTER_SYSTEM : ROUTER_SYSTEM, routerPrompt(db, { agent, project, task, title, retryOf }), jobModels(db));
193
+
194
+ async function askFor(db, system, prompt, models = usableModels(db)) {
195
+ const usable = models;
184
196
  if (usable.length === 0) throw new UsageError('no model is on — sumo models enable <name>');
185
197
  const result = await callLocalModel(db, { system, prompt, schema: routerSchema(usable) });
186
198
  if (!result.ok) return { ok: false, error: result.error };
@@ -220,9 +232,17 @@ function stepAbove({ model, effort }, usable) {
220
232
  * or nothing; `usable` is the models that are on, cheapest first. An attempt with no route Sumo knows has nothing to go
221
233
  * above. `policy` says what changed and why, or is null.
222
234
  */
223
- export function routePolicy({ agent, routed, retryOf: prev, reviews: target, usable }) {
235
+ export function routePolicy({ agent, routed, retryOf: prev, reviews: target, usable, floor = null }) {
224
236
  let route = { model: routed.model, effort: routed.effort };
225
237
  const why = [];
238
+ // The user's floor before anything else: a job never starts on a model below it while one at or above it is on.
239
+ if (floor && modelRank(route.model) < modelRank(floor)) {
240
+ const up = usable.find((m) => modelRank(m) >= modelRank(floor));
241
+ if (up) {
242
+ route = { model: up, effort: up === 'haiku' ? 'none' : EFFORTS.includes(route.effort) ? route.effort : 'medium' };
243
+ why.push(`jobs.floor is ${floor}`);
244
+ }
245
+ }
226
246
  if (!prev) {
227
247
  if (agent === 'worker' && route.model === 'fable' && usable.includes('opus')) {
228
248
  route.model = 'opus';
@@ -275,7 +295,7 @@ const jobRoute = (db, id) => (id === undefined || id === null ? null : (db.prepa
275
295
  export async function chooseRoute(db, { agent, project, task, title, retryOf, reviews }) {
276
296
  const routed = await askRouter(db, { agent, project, task, title, retryOf });
277
297
  if (!routed.ok) throw new UsageError(`the router failed: ${routed.error} — no job was created`);
278
- const { model, effort, policy } = routePolicy({ agent, routed, retryOf: jobRoute(db, retryOf), reviews: jobRoute(db, reviews), usable: usableModels(db) });
298
+ const { model, effort, policy } = routePolicy({ agent, routed, retryOf: jobRoute(db, retryOf), reviews: jobRoute(db, reviews), usable: usableModels(db), floor: jobFloor(db) });
279
299
  return { model, effort, reason: `router: ${routed.reason}${policy ? `; policy: ${policy}` : ''}`, risky: routed.risky };
280
300
  }
281
301
 
package/src/sessions.mjs CHANGED
@@ -235,11 +235,12 @@ export function withoutThinking(messages) {
235
235
  }
236
236
 
237
237
  /** Writes the session's state whole, then moves it into place: a crash while writing leaves the last good one. */
238
- export function saveState({ id, messages, model, effort, routed, cwd, contextTokens, now }) {
238
+ export function saveState({ id, messages, model, effort, routed, cwd, contextTokens, now, pending = [] }) {
239
239
  mkdirSync(sessionsDir(), { recursive: true, mode: 0o700 });
240
240
  const file = stateFile(id);
241
241
  // The summary first, so a listing can read it without the messages behind it; the route's reason last, since it is prose of any length.
242
- const state = { version: 1, id, savedAt: now, contextTokens, model, effort, cwd, messages: keepable(messages), routed };
242
+ // `pending` is what jobs reported that the model has not read yet: it goes with the session, to be read when it is picked up again.
243
+ const state = { version: 1, id, savedAt: now, contextTokens, model, effort, cwd, messages: keepable(messages), routed, pending };
243
244
  writeFileSync(`${file}.tmp`, JSON.stringify(state), { mode: 0o600 });
244
245
  renameSync(`${file}.tmp`, file);
245
246
  return file;