sumo-agents 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/loop.mjs CHANGED
@@ -1,21 +1,22 @@
1
1
  import Anthropic from '@anthropic-ai/sdk';
2
- import { readFileSync, rmSync } from 'node:fs';
3
- import { join } from 'node:path';
2
+ import { existsSync, readFileSync, rmSync } from 'node:fs';
3
+ import { join, resolve } from 'node:path';
4
4
  import { ADVISOR_BETA, ADVISOR_SPENT, ADVISOR_SPENT_AT, ADVISOR_STOP_AT, advisorIn, advisorLine, advisorOf, advisorResult, advisorRuns, advisorTool, isAdvisorCall, isAdvisorResult } from './advisor.mjs';
5
5
  import { anthropicClient, authenticatedRequest, resolveAnthropicCredential } from './auth.mjs';
6
6
  import { MODEL_IDS, modelId, MODELS, usableModels } from './catalog.mjs';
7
7
  import { getMeta, tx } from './db.mjs';
8
8
  import { handleEvent } from './hooks.mjs';
9
- import { brief, getJob, takeInbox } from './jobs.mjs';
9
+ import { brief, getJob, planOf, readState, runLockFile, settle, takeInbox, toldToClose, treeOf } from './jobs.mjs';
10
10
  import { isJobTool, jobTools, runJobTool } from './jobtools.mjs';
11
11
  import { takeLock } from './lock.mjs';
12
- import { gateMcp, isMcpTool, mcpReady, runMcpTool, TOOL_SEARCH } from './mcp.mjs';
12
+ import { DECLINED, gateMcp, isMcpTool, mcpReady, runMcpTool, TOOL_SEARCH } from './mcp.mjs';
13
13
  import { UsageError } from './memory.mjs';
14
- import { costOf, logRun, usageOf } from './model.mjs';
14
+ import { callLocalModel, costOf, logRun, usageOf } from './model.mjs';
15
15
  import { paths, REPO_ROOT } from './paths.mjs';
16
16
  import { getProject } from './projects.mjs';
17
17
  import { CONFIG_DEFAULTS } from './setup.mjs';
18
- import { BASH_TOOL, childEnv, EDITOR_TOOL, INTERRUPTED, runTool } from './tools.mjs';
18
+ import { ASK_TOOL, BASH_TOOL, childEnv, EDITOR_TOOL, INTERRUPTED, killGroup, runTool } from './tools.mjs';
19
+ import { changesSince, diffStat, verdictLines } from './verify.mjs';
19
20
  import { isWebCall, isWebResult, WEB_TOOLS, webResult } from './web.mjs';
20
21
 
21
22
  /**
@@ -42,8 +43,46 @@ export const RETRY = { limit: 6, baseMs: 1000, capMs: 30_000 };
42
43
  /** The same call with the same input and the same answer, over and over: said to the model at the third, and the run stopped at the fifth. */
43
44
  const REPEAT_NUDGE_AT = 3;
44
45
  const REPEAT_STOP_AT = 5;
45
- /** Said with the results of the turn before the last: a run that hits the limit still gets to close or sum up. */
46
- const LAST_TURN = 'This is the last request of this run: the turn limit is reached after it. If you have a job, close it with `finish` now — DONE or FAILED, with your report; otherwise say where things stand and what remains.';
46
+ /** A round of two to four calls gone round with the same input and the same answers is a loop too: said and stopped at the same counts. */
47
+ const ROUND_SIZES = [2, 3, 4];
48
+ /** The calls kept to find a round in: the longest round, gone round as often as it takes to stop it. */
49
+ const TRAIL_LENGTH = ROUND_SIZES.at(-1) * REPEAT_STOP_AT;
50
+ /** The editor's commands that change a file, and how many changes to one file in a run are enough before the model is told to step back. */
51
+ const CHANGES = ['str_replace', 'insert', 'create'];
52
+ const EDITS_NOTE_AFTER = 10;
53
+ /** Calls the user declined in one conversation: a model that keeps asking, or asks for the same thing another way, is stopped here. */
54
+ const DECLINE_STOP_AT = 3;
55
+ /**
56
+ * Said with the results three requests before the limit: a run that hits it still gets to close or sum up — and a worker
57
+ * room for both of its `finish` calls, the first of which is answered with the check against the task.
58
+ */
59
+ const CLOSING_TURNS = 3;
60
+ const LAST_TURN = 'This run has three requests left: the turn limit is reached after them. If you have a job, close it with `finish` now — DONE or FAILED, with your report; a worker\'s first DONE is answered with a check against the task, and calling `finish` again goes on to verification. Otherwise say where things stand and what remains.';
61
+ /** Said the same way, once, to a job that has spent this much of its budget: it still gets to close before the cap stops it. */
62
+ const BUDGET_WARN_AT = 0.8;
63
+ const BUDGET_LOW = (spent, usd) =>
64
+ `This job has spent $${spent.toFixed(2)} of its $${usd.toFixed(2)} budget, and is stopped when it reaches it. Close it with \`finish\` now: DONE only if the work is verified, otherwise FAILED with where it stands and what remains. A worker's first DONE is answered with a check against the task; call \`finish\` again to go on.`;
65
+ /** Said the same way, once, to a job that has run this much of its time: it still gets to close before the limit stops it. */
66
+ const TIME_WARN_AT = 0.8;
67
+ const TIME_LOW = (ranMs, limitMs) =>
68
+ `This job has run ${Math.floor(ranMs / 60_000)} of its ${Math.round(limitMs / 60_000)} minutes, and is stopped when it reaches them. Close it with \`finish\` now: DONE only if the work is verified, otherwise FAILED with where it stands and what remains. A worker's first DONE is answered with a check against the task; call \`finish\` again to go on.`;
69
+ /**
70
+ * A line of a failed command's output that reads as an error, and how many times the same one comes back in a run before the model
71
+ * is told to look for its cause. What changes from one try to the next — an absolute path, a hex id, a number — does not make it another.
72
+ */
73
+ const ERROR_LINE = /error|Error|ERR!|FAIL|failed|Traceback|panic:/;
74
+ const ERROR_NOTE_AT = 4;
75
+ const ABSOLUTE_PATH = /(?<![\w.~-])\/[^\s'"`:,;()[\]{}<>]+/g;
76
+ const HEX_ID = /\b0x[0-9a-f]+\b|\b(?=[0-9a-f]*\d)(?=[0-9a-f]*[a-f])[0-9a-f]{6,}\b/gi;
77
+ /**
78
+ * Every thirty requests a job's last twelve calls — the tool and its input, cut to 200 characters each — are put to the local model,
79
+ * which says whether they go round in circles; a yes is said to the model with why. It costs nothing, and holds the turn for twenty
80
+ * seconds at most: a check that is slower, fails, or has no local model to ask is skipped without a word.
81
+ */
82
+ export const CIRCLES = { every: 30, calls: 12, chars: 200, ms: 20_000 };
83
+ const CIRCLES_SYSTEM =
84
+ "You watch a coding agent at work. You are shown its last tool calls, oldest first, one a line: the tool, then its input. Answer with JSON only. stuck: true when the calls go round in circles — the same things tried again and again, or in other words, with nothing new learned and nothing changed — and false when they move forward, however slowly. why: one sentence on what keeps coming back, or on what moves.";
85
+ const CIRCLES_SCHEMA = { type: 'object', properties: { stuck: { type: 'boolean' }, why: { type: 'string', maxLength: 200 } }, required: ['stuck', 'why'], additionalProperties: false };
47
86
 
48
87
  /** The beta under which one request summarizes the conversation server-side, in place of answering it. */
49
88
  const COMPACT_BETA = 'compact-2026-09-04';
@@ -57,6 +96,8 @@ export const COMPACT_INSTRUCTIONS =
57
96
  'every decision made and why; what was tried and set aside; what is done, what is in hand, what is blocked; the next step; the files, commands, names, numbers ' +
58
97
  'and error text that would be hard to find again; what the user said, close to their words; which checks were run and what they showed. Condense the reasoning to what it concluded.';
59
98
  const RESUMED = (brief) => `The conversation before this point was summarized above to make room. Carry on from where the summary leaves it: what it says is done is done.${brief ? ` ${brief}` : ''}`;
99
+ /** The lines of what a job changed that ride after its summary: git's stat of the tracked files, then the new ones. */
100
+ const CHANGED_LINES = 20;
60
101
 
61
102
  /**
62
103
  * The one compaction request: the same conversation, without the context edits (the API takes one or the other) and
@@ -68,11 +109,35 @@ export function compactionParams(params, instructions = COMPACT_INSTRUCTIONS) {
68
109
  return { ...rest, betas: [...new Set([...(params.betas ?? []), COMPACT_BETA])], compaction: { type: 'summarize', instructions } };
69
110
  }
70
111
 
71
- /** Old tool results are cleared server-side once the context is this big; never rewritten here, so the history stays append-only. */
112
+ /** What a job's `state` says of its work, for the line after its summary; nothing when it has nothing to say or fails to. */
113
+ function recordedBy(compact) {
114
+ try {
115
+ return compact.state?.() ?? '';
116
+ } catch {
117
+ return '';
118
+ }
119
+ }
120
+
121
+ /**
122
+ * Old tool results are cleared server-side once the context is this big; never rewritten here, so the history stays append-only.
123
+ * Rarely and in big chunks: each clear breaks the cache after the system prompt, and the whole conversation is written to it
124
+ * again at the write price — a small clear that comes back every few requests costs more than the tokens it saves. The last
125
+ * five tool uses stay: the model is working from them. What the user answered stays always: the chat's `ask` and a job's
126
+ * (jobtools.mjs) go by the same name, and a result of either is never cleared.
127
+ */
72
128
  const CONTEXT_EDITS = [
73
- { type: 'clear_tool_uses_20250919', trigger: { type: 'input_tokens', value: 60_000 }, keep: { type: 'tool_uses', value: 5 }, clear_at_least: { type: 'input_tokens', value: 10_000 } },
129
+ { type: 'clear_tool_uses_20250919', trigger: { type: 'input_tokens', value: 100_000 }, keep: { type: 'tool_uses', value: 5 }, clear_at_least: { type: 'input_tokens', value: 40_000 }, exclude_tools: [ASK_TOOL.name] },
74
130
  ];
75
131
 
132
+ /** What the API cleared before it answered, for the ledger row: how many tool uses, and how many tokens they held. */
133
+ function clearedBy(response) {
134
+ const edits = (response.context_management?.applied_edits ?? []).filter((edit) => edit.cleared_tool_uses > 0);
135
+ if (edits.length === 0) return '';
136
+ const uses = edits.reduce((n, edit) => n + edit.cleared_tool_uses, 0);
137
+ const tokens = edits.reduce((n, edit) => n + (edit.cleared_input_tokens ?? 0), 0);
138
+ return ` cleared ${uses} tool use${uses === 1 ? '' : 's'} (${Math.round(tokens / 1000)}k)`;
139
+ }
140
+
76
141
  export const promptFile = (name) => readFileSync(join(REPO_ROOT, 'prompts', name), 'utf8').trim();
77
142
  /**
78
143
  * A sub-agent works by the user's coding rules as the chat does: the Coding section of AGENTS.md, read from its one
@@ -127,30 +192,39 @@ export const withServers = (system, registry) => (registry?.hasTools ? `${system
127
192
  /**
128
193
  * The first of two guards on a job taking its own work unverified: the command as written — `--accept` on a finish,
129
194
  * or clearing or setting the SUMO_JOB marker the second guard reads (reading code that names it is fine). `sumo job finish` refuses `--accept` under that marker
130
- * however the command was spelled. Both stop mistakes, not a shell set on getting round them: a job's shell runs
131
- * with the user's own access.
195
+ * however the command was spelled. The chat's commands carry a marker of their own, SUMO_TOOL, under which `sumo` refuses what only the
196
+ * user does — the allow list, the configuration, memory written as the user's word — and the same patterns hold it. All of this stops
197
+ * mistakes, not a shell set on getting round them: the shell runs with the user's own access.
132
198
  */
133
199
  // Each part is held to one command, and the marker to where a shell would set it, so a search through code that names
134
200
  // them (`grep -rn "SUMO_JOB=" src`, `rg "job finish" && grep -- --accept`) is reading, not granting.
135
- const SELF_GRANT = new RegExp(
136
- [
137
- /\bjob\s+finish\b[^;&|\n]*--accept\b/.source,
138
- // Clearing the marker, however a shell spells it.
139
- /\bunset\b[^;&|\n]*\bSUMO_JOB\b/.source,
140
- /\benv\b[^;&|\n]*(?:\s-u\s*|\s--unset=)["']?SUMO_JOB\b/.source,
141
- /\b(?:export\s+-n|declare\s+\+x|typeset\s+\+x)\b[^;&|\n]*\bSUMO_JOB\b/.source,
142
- // Setting it where a command starts: after a separator, a keyword, sudo or eval, inside `sh -c "…"`, behind other assignments.
143
- // An assignment's value is read as a shell reads a word — an escaped character, a quoted string, or a plain character —
144
- // so a quote means one thing: where it could also be a character of its own, a long run of them was paired every way there is.
145
- // The same for sudo's flags: one that takes a value takes the next word only when that word is not a flag itself.
146
- /(?:^|[;&|(`{!\n]|\$\(|\b(?:if|then|else|elif|do|while|until|time|eval|sudo(?:\s+(?:-[ugCDhpRrTt]\s+(?!-\S)\S+|-\S+))*)\s|\b(?:ba|z|da|k)?sh\b[^;&|\n]*\s-c\s+["'])\s*(?:[A-Za-z_]\w*=(?:\\.|"(?:[^"\\]|\\.)*"|'[^']*'|[^\s"'\\])*\s+)*["']?SUMO_JOB=/.source,
147
- /\b(?:export|env|declare|typeset|readonly|local)\b[^;&|\n]*?\s["']?SUMO_JOB=/.source,
148
- ].join('|'),
149
- );
201
+ const MARKER = 'SUMO_(?:JOB|TOOL)';
202
+ /** Clearing or setting a marker, however a shell spells it. */
203
+ const MARKER_PATTERNS = [
204
+ // Clearing the marker, however a shell spells it.
205
+ `\\bunset\\b[^;&|\\n]*\\b${MARKER}\\b`,
206
+ `\\benv\\b[^;&|\\n]*(?:\\s-u\\s*|\\s--unset=)["']?${MARKER}\\b`,
207
+ `\\b(?:export\\s+-n|declare\\s+\\+x|typeset\\s+\\+x)\\b[^;&|\\n]*\\b${MARKER}\\b`,
208
+ // Setting it where a command starts: after a separator, a keyword, sudo or eval, inside `sh -c "…"`, behind other assignments.
209
+ // An assignment's value is read as a shell reads a word — an escaped character, a quoted string, or a plain character —
210
+ // so a quote means one thing: where it could also be a character of its own, a long run of them was paired every way there is.
211
+ // The same for sudo's flags: one that takes a value takes the next word only when that word is not a flag itself.
212
+ `(?:^|[;&|(\`{!\\n]|\\$\\(|\\b(?:if|then|else|elif|do|while|until|time|eval|sudo(?:\\s+(?:-[ugCDhpRrTt]\\s+(?!-\\S)\\S+|-\\S+))*)\\s|\\b(?:ba|z|da|k)?sh\\b[^;&|\\n]*\\s-c\\s+["'])\\s*(?:[A-Za-z_]\\w*=(?:\\\\.|"(?:[^"\\\\]|\\\\.)*"|'[^']*'|[^\\s"'\\\\])*\\s+)*["']?${MARKER}=`,
213
+ `\\b(?:export|env|declare|typeset|readonly|local)\\b[^;&|\\n]*?\\s["']?${MARKER}=`,
214
+ ];
215
+ const TAMPERS = new RegExp(MARKER_PATTERNS.join('|'));
216
+ const SELF_GRANT = new RegExp([/\bjob\s+finish\b[^;&|\n]*--accept\b/.source, ...MARKER_PATTERNS].join('|'));
150
217
  /** Whether a command, as written, takes its own work unverified or clears the marker that would stop it; a line continued with `\` is one line. */
151
218
  export const grantsItself = (command) => SELF_GRANT.test(command.replace(/\\\n/g, ' '));
219
+ /** Whether a command, as written, clears or sets the marker that says it is the model's. */
220
+ export const tampersMarker = (command) => TAMPERS.test(command.replace(/\\\n/g, ' '));
221
+ export const TAMPER_REFUSED = 'Refused: the marker that says this shell is the model\'s is not yours to clear or set. What it holds back, the user does themselves.';
152
222
  const SELF_GRANT_REFUSED = "Refused: work is never taken unverified on its author's word. Finish FAILED with what blocks verification, or ask.";
153
223
 
224
+ /** How many requests apart a job is shown its own plan again, and how. */
225
+ const PLAN_EVERY = 10;
226
+ const PLAN_AGAIN = (plan) => `Your plan, as your latest checklist note has it — when a step is done, note the list again with it ticked:\n${plan}`;
227
+
154
228
  /** Said once to a job that ended its turn with the job still open: it finished the work but never said so. */
155
229
  const UNCLOSED = 'You ended without closing the job. Call `finish` now — DONE or FAILED, with your report — or `ask` if you are blocked.';
156
230
 
@@ -232,6 +306,21 @@ const pause = (ms, signal) =>
232
306
 
233
307
  /** One tool call and its answer as one string, so a call made again with the same answer is seen to be the same. */
234
308
  const sameAs = (call, result) => `${call.name}\n${JSON.stringify(call.input ?? {})}\n${result.content}`;
309
+ /**
310
+ * How many times the last calls went round the same two to four calls, in the same order with the same input and the same
311
+ * answers, when a round has just come to an end; null otherwise. A round whose answers change is work going on — a wait and a
312
+ * look, again — and is not one. Nor is one call made again, or a shorter round twice: that is the repeat's to count.
313
+ */
314
+ function roundOf(trail) {
315
+ for (const size of ROUND_SIZES) {
316
+ const round = trail.slice(-size);
317
+ if (round.length < size || [1, 2].some((d) => d < size && size % d === 0 && round.every((key, i) => key === round[i % d]))) continue;
318
+ let run = size;
319
+ while (run < trail.length && trail.at(-1 - run) === trail.at(-1 - run + size)) run++;
320
+ if (run >= 2 * size && run % size === 0) return { size, rounds: run / size };
321
+ }
322
+ return null;
323
+ }
235
324
  /**
236
325
  * What the conversation holds after a reply: what its last pass read and wrote. A reply the API made in several passes —
237
326
  * the model asked the advisor, and went on — counts every pass at the top of its usage, and so the conversation more than once.
@@ -241,6 +330,33 @@ function contextOf(model, usage) {
241
330
  return last.inputTokens + last.outputTokens;
242
331
  }
243
332
  const repeated = (count) => `\n[sumo: this is the same call with the same answer, ${count} times in a row — doing it again changes nothing. Do something else, or stop and say what blocks you.]`;
333
+ const roundAgain = ({ size, rounds }) => `\n[sumo: these ${size} calls, with the same input and the same answers in the same order, ${rounds} times in a row — going round them again changes nothing. Do something else, or stop and say what blocks you.]`;
334
+ const editedOften = (path, count) => `\n[sumo: this is change ${count} to ${path} in this run — step back: view the whole region you are changing, then make it right in one edit.]`;
335
+ const errorAgain = (count, line) => `\n[sumo: this error has come back ${count} times in this run: "${line.slice(0, 200)}" — step back and find its cause rather than trying another variation.]`;
336
+ const inCircles = (count, why) => `\n[sumo: your last ${count} calls look to be going round in circles: ${why.slice(0, 200)} — step back and find what blocks you, or stop and say so.]`;
337
+
338
+ /** The first line of a command's output that reads as an error, as it came and with what changes from one try to the next taken out; null when none does. */
339
+ function errorOf(output) {
340
+ const line = String(output).split('\n').find((l) => ERROR_LINE.test(l))?.trim();
341
+ if (!line) return null;
342
+ return { line, key: line.replace(ABSOLUTE_PATH, '<path>').replace(HEX_ID, '<id>').replace(/\d+/g, 'N').replace(/\s+/g, ' ') };
343
+ }
344
+
345
+ /** What `promise` comes to, or null when it fails, takes longer than `ms`, or the user says stop first; no timer is left behind either way. */
346
+ function within(promise, ms, signal) {
347
+ return new Promise((resolve) => {
348
+ const done = (value) => {
349
+ clearTimeout(timer);
350
+ signal?.removeEventListener('abort', skip);
351
+ resolve(value);
352
+ };
353
+ const skip = () => done(null);
354
+ const timer = setTimeout(skip, ms);
355
+ signal?.addEventListener('abort', skip, { once: true });
356
+ if (signal?.aborted) skip();
357
+ promise.then(done, skip);
358
+ });
359
+ }
244
360
 
245
361
  /**
246
362
  * Runs one conversation from its current messages until the model stops
@@ -254,23 +370,46 @@ const repeated = (count) => `\n[sumo: this is the same call with the same answer
254
370
  * while it worked: it is read with the next request, behind the tool results,
255
371
  * and a conversation about to end is given one more request to answer it.
256
372
  * `onOutput` is handed what a shell command prints, as it prints it.
373
+ * `budget` is a job's cap in dollars — `usd`, what an earlier run of the
374
+ * same job `spent`, and whether it was `warned`: told once near it, and
375
+ * nothing more is sent once it is reached. The chat has none. `clock` is a
376
+ * job's limit in time the same way — `ms`, the run's start `from` by the
377
+ * conversation's own `now`, and `warned`. `circling` is a job's look, every
378
+ * `every` requests, at whether its last calls go round in circles: `ask` is
379
+ * handed them and answers why, or null. `remind` is asked, with the request
380
+ * count, at each round of tool results, for a text to say after them — or nothing.
381
+ * `toldLast` comes back true when the conversation was told it had three requests left.
257
382
  */
258
- export async function converse(db, params, { send = sendToApi, ctx, ledger, beforeTool = null, concurrent = null, onText = null, onThinking = null, onTool = null, onOutput = null, onResult = null, onTurn = null, onRetry = null, onCompact = null, inbox = null, signal = null, retry = RETRY, compact = null, now = () => new Date().toISOString() }) {
383
+ export async function converse(db, params, { send = sendToApi, ctx, ledger, beforeTool = null, concurrent = null, onText = null, onThinking = null, onTool = null, onOutput = null, onResult = null, onTurn = null, onRetry = null, onCompact = null, inbox = null, signal = null, retry = RETRY, compact = null, budget = null, clock = null, circling = null, remind = null, now = () => new Date().toISOString() }) {
259
384
  const totals = { inputTokens: 0, outputTokens: 0, costUsd: 0, toolCalls: 0, contextTokens: 0 };
260
385
  let turns = 0;
261
386
  let stop = 'max_turns';
262
387
  let text = '';
263
388
  let compactedAt = -Infinity;
389
+ let toldLast = false;
264
390
  // The ledger names the model that answered: with a fallback that is not always the one asked for.
265
391
  const log = (result, note, model = params.model) => logRun(db, { kind: ledger.kind, model, result, note, now: now(), jobId: ledger.jobId ?? null, sessionId: ledger.sessionId ?? null });
266
392
  // What the inbox hands over is the user's words — or, as `{ event }`, something that happened and is nobody's words: said as it is.
267
393
  const heard = () => (inbox?.() ?? []).map((said) => ({ type: 'text', text: typeof said === 'string' ? `The user says, while you work: ${said}` : said.event }));
268
394
  const interrupted = () => {
269
395
  log({ ok: false, usage: usageOf(params.model, null) }, `turn ${turns}: interrupted`);
270
- return { turns, stop: 'interrupted', error: null, text, totals };
396
+ return { turns, stop: 'interrupted', error: null, text, totals, toldLast };
271
397
  };
272
398
  /** The last call made and answered, and how many times in a row it has been exactly that. */
273
399
  const repeat = { key: null, count: 0 };
400
+ /** The last calls made, by name and input, to find a round in; and how many times the editor changed each file. */
401
+ const trail = [];
402
+ const edited = new Map();
403
+ /** How many times each error has come back from a failed command, and the last calls made, as the local model is shown them. */
404
+ const errors = new Map();
405
+ const recent = [];
406
+ let declined = 0;
407
+ // What a job has spent, over this run and the one before it.
408
+ const costSoFar = () => (budget?.spent ?? 0) + totals.costUsd;
409
+ const overBudget = () => budget !== null && costSoFar() >= budget.usd;
410
+ // How long a job has run, from the start of its run.
411
+ const ranMs = () => Date.parse(now()) - clock.from;
412
+ const overTime = () => clock !== null && ranMs() >= clock.ms;
274
413
  // A search, a fetch or a question to the advisor runs on the API's side, inside the request: its call and what came back are blocks of
275
414
  // the reply. Each is said as any call and its answer are — as it streams, or from the whole reply when nothing streamed — and once: a
276
415
  // paused turn's answer comes with the next reply. One the request ended on is answered here, so nothing is left running on the screen.
@@ -298,6 +437,16 @@ export async function converse(db, params, { send = sendToApi, ctx, ledger, befo
298
437
  };
299
438
 
300
439
  while (turns < MAX_TURNS) {
440
+ // A job that has spent its budget sends nothing more: the last round it made is answered, and the run ends there.
441
+ if (overBudget()) {
442
+ stop = 'budget';
443
+ break;
444
+ }
445
+ // So does one that has run its time.
446
+ if (overTime()) {
447
+ stop = 'time';
448
+ break;
449
+ }
301
450
  turns++;
302
451
  markTail(params.messages);
303
452
  let response;
@@ -319,7 +468,7 @@ export async function converse(db, params, { send = sendToApi, ctx, ledger, befo
319
468
  continue;
320
469
  }
321
470
  log({ ok: false, usage: usageOf(params.model, null) }, `turn ${turns}: ${why}`);
322
- return { turns, stop: 'error', error: describeFailure(cause).slice(0, 300), status: cause.status ?? null, text, totals };
471
+ return { turns, stop: 'error', error: describeFailure(cause).slice(0, 300), status: cause.status ?? null, text, totals, toldLast };
323
472
  }
324
473
  }
325
474
  const served = response.model ?? params.model;
@@ -328,7 +477,7 @@ export async function converse(db, params, { send = sendToApi, ctx, ledger, befo
328
477
  totals.outputTokens += usage.outputTokens;
329
478
  totals.costUsd += costOf(served, response.usage ?? {});
330
479
  totals.contextTokens = contextOf(served, response.usage);
331
- log({ ok: true, usage }, `turn ${turns} ${response.stop_reason}`, served);
480
+ log({ ok: true, usage }, `turn ${turns} ${response.stop_reason}${clearedBy(response)}`, served);
332
481
  // What the advisor read and wrote is not in the reply's own count: it is paid at the advisor's price, and has a row under its name.
333
482
  for (const run of advisorRuns(response.usage)) {
334
483
  const spent = usageOf(run.model, run);
@@ -386,28 +535,68 @@ export async function converse(db, params, { send = sendToApi, ctx, ledger, befo
386
535
  stop = 'interrupted';
387
536
  break;
388
537
  }
389
- // A call made again and again with the same answer is going nowhere: the model is told so, and then stopped.
538
+ // A call made again and again with the same answer is going nowhere: the model is told so, and then stopped. So is a round of
539
+ // a few calls gone round with the same answers. A file changed again and again is said once, and the run goes on; so is the
540
+ // same error back from failed commands, try after try, whatever else the commands did.
390
541
  let looping = false;
391
542
  for (const [i, call] of calls.entries()) {
392
543
  const key = sameAs(call, results[i]);
544
+ const error = call.name === BASH_TOOL.name && results[i].is_error ? errorOf(results[i].content) : null;
393
545
  repeat.count = key === repeat.key ? repeat.count + 1 : 1;
394
546
  repeat.key = key;
395
547
  if (repeat.count >= REPEAT_STOP_AT) looping = true;
396
548
  else if (repeat.count >= REPEAT_NUDGE_AT) results[i] = { ...results[i], content: `${results[i].content}${repeated(repeat.count)}` };
549
+ trail.push(key);
550
+ if (trail.length > TRAIL_LENGTH) trail.shift();
551
+ const round = roundOf(trail);
552
+ if (round && round.rounds >= REPEAT_STOP_AT) looping = true;
553
+ else if (round && round.rounds >= REPEAT_NUDGE_AT) results[i] = { ...results[i], content: `${results[i].content}${roundAgain(round)}` };
554
+ if (call.name === EDITOR_TOOL.name && CHANGES.includes(call.input?.command) && !results[i].is_error) {
555
+ const path = resolve(ctx?.cwd ?? '', String(call.input.path));
556
+ const count = (edited.get(path) ?? 0) + 1;
557
+ edited.set(path, count);
558
+ if (count === EDITS_NOTE_AFTER + 1) results[i] = { ...results[i], content: `${results[i].content}${editedOften(path, count)}` };
559
+ }
560
+ if (error) {
561
+ const count = (errors.get(error.key) ?? 0) + 1;
562
+ errors.set(error.key, count);
563
+ if (count === ERROR_NOTE_AT) results[i] = { ...results[i], content: `${results[i].content}${errorAgain(count, error.line)}` };
564
+ }
565
+ if (circling) {
566
+ recent.push(`${call.name} ${JSON.stringify(call.input ?? {})}`.slice(0, circling.chars));
567
+ if (recent.length > circling.calls) recent.shift();
568
+ }
397
569
  }
398
570
  // The advisor asked again and again is the same, and its tool cannot be taken away: the model is told so once, and then stopped.
399
- if (looping || advisor.asked >= ADVISOR_STOP_AT) {
571
+ // So is a model the user has said no to, again and again: each no is final, and three of them end the conversation.
572
+ declined += results.filter((r) => r.content === DECLINED).length;
573
+ if (looping || advisor.asked >= ADVISOR_STOP_AT || declined >= DECLINE_STOP_AT) {
400
574
  params.messages.push({ role: 'user', content: results });
401
- stop = looping ? 'loop' : 'advisor';
575
+ stop = looping ? 'loop' : declined >= DECLINE_STOP_AT ? 'declined' : 'advisor';
402
576
  break;
403
577
  }
578
+ // Every so many requests a job's last calls are put to the local model — free, and never for longer than its cap; a yes rides on the last answer, with why.
579
+ if (circling && turns % circling.every === 0 && recent.length > 0) {
580
+ const why = await within(Promise.resolve().then(() => circling.ask([...recent])), circling.ms, signal);
581
+ if (typeof why === 'string' && why.trim()) results[results.length - 1] = { ...results.at(-1), content: `${results.at(-1).content}${inCircles(recent.length, why.trim())}` };
582
+ }
404
583
  const enough = advisor.asked >= ADVISOR_SPENT_AT && !advisor.told ? [{ type: 'text', text: ADVISOR_SPENT }] : [];
405
584
  if (enough.length > 0) advisor.told = true;
406
- params.messages.push({ role: 'user', content: [...results, ...heard(), ...enough, ...(turns === MAX_TURNS - 1 ? [{ type: 'text', text: LAST_TURN }] : [])] });
585
+ const low = budget !== null && !budget.warned && costSoFar() >= budget.usd * BUDGET_WARN_AT ? [{ type: 'text', text: BUDGET_LOW(costSoFar(), budget.usd) }] : [];
586
+ if (low.length > 0) budget.warned = true;
587
+ const late = clock !== null && !clock.warned && ranMs() >= clock.ms * TIME_WARN_AT ? [{ type: 'text', text: TIME_LOW(ranMs(), clock.ms) }] : [];
588
+ if (late.length > 0) clock.warned = true;
589
+ const last = turns === MAX_TURNS - CLOSING_TURNS ? [{ type: 'text', text: LAST_TURN }] : [];
590
+ if (last.length > 0) toldLast = true;
591
+ params.messages.push({ role: 'user', content: [...results, ...heard(), ...enough, ...low, ...late, ...last] });
592
+
593
+ // What the caller keeps in the model's view — a job's plan, from runJob — goes last with these results, when it has something to say.
594
+ const reminder = remind?.(turns);
595
+ if (reminder) params.messages.at(-1).content.push({ type: 'text', text: reminder });
407
596
 
408
597
  // Past the band where the work must either stop or shed its past: the conversation so far is summarized server-side, here, at the
409
598
  // end of a tool round, and goes on from the summary. A summary that cannot be had costs nothing but its request: the run goes on as it was.
410
- if (compact && totals.contextTokens >= compact.at && turns - compactedAt >= COMPACT_GAP) {
599
+ if (compact && !overBudget() && !overTime() && totals.contextTokens >= compact.at && turns - compactedAt >= COMPACT_GAP) {
411
600
  compactedAt = turns;
412
601
  try {
413
602
  const summary = await send(compactionParams(params, compact.instructions), { signal });
@@ -419,7 +608,8 @@ export async function converse(db, params, { send = sendToApi, ctx, ledger, befo
419
608
  totals.costUsd += costOf(by, summary.usage ?? {});
420
609
  log({ ok: Boolean(block), usage: spent }, `turn ${turns} compaction${block ? '' : ': no summary came back'}`, by);
421
610
  if (block) {
422
- params.messages = [{ role: 'assistant', content: summary.content }, { role: 'user', content: [{ type: 'text', text: RESUMED(compact.brief) }] }];
611
+ // A job's own record of its work rides after the line, from code and not from the summary; whatever cannot be read is left out.
612
+ params.messages = [{ role: 'assistant', content: summary.content }, { role: 'user', content: [{ type: 'text', text: [RESUMED(compact.brief), recordedBy(compact)].filter(Boolean).join('\n\n') }] }];
423
613
  onCompact?.({ turns, before: totals.contextTokens, summary: block.content });
424
614
  }
425
615
  } catch (cause) {
@@ -430,20 +620,40 @@ export async function converse(db, params, { send = sendToApi, ctx, ledger, befo
430
620
  }
431
621
 
432
622
  endHosted();
433
- return { turns, stop, error: null, text, totals };
623
+ return { turns, stop, error: null, text, totals, toldLast };
434
624
  }
435
625
 
436
626
  /**
437
627
  * The tool context for work inside one project: its directory, the jail around it, an environment without the secrets,
438
- * and where the whole of a command's output goes when the model is shown only its ends — the job's own folder, or the logs.
628
+ * where the whole of a command's output goes when the model is shown only its ends — the job's own folder, or the logs —
629
+ * and whether its shell runs in the OS sandbox, and reaches past this machine there. A job given a worktree of its own (`tree`)
630
+ * works there and only there: the project's own files belong to another worker.
439
631
  */
440
- export function contextFor(project, { jobId = null } = {}) {
441
- // A job's commands are marked as its own, so what only the user may grant — taking work unverified — is refused where it is read, however it was spelled.
442
- const env = jobId === null ? childEnv() : { ...childEnv(), SUMO_JOB: String(jobId) };
632
+ export function contextFor(project, { jobId = null, sandbox = true, network = true, tree = null } = {}) {
633
+ // Every command is marked as the model's, and a job's as its own: what only the user may do — change the allow list or the
634
+ // configuration, take work unverified, write memory as if they had said it — is refused where it is read, however it was spelled.
635
+ const env = { ...childEnv(), SUMO_TOOL: '1', ...(jobId === null ? {} : { SUMO_JOB: String(jobId) }) };
443
636
  const spill = jobId === null ? join(paths().logs, 'output') : join(paths().jobs, String(jobId), 'output');
444
- return { cwd: project.path, roots: [project.path, ...(jobId === null ? [] : [join(paths().jobs, String(jobId))])], env, spill };
637
+ const root = tree ?? project.path;
638
+ return { cwd: root, roots: [root, ...(jobId === null ? [] : [join(paths().jobs, String(jobId))])], env, spill, sandbox, network };
445
639
  }
446
640
 
641
+ /**
642
+ * The user's switches for the model's shell, read once a process and kept. The database stays writable from that shell —
643
+ * the sumo commands the model runs write it — so a model could change them there: a change takes effect at the next
644
+ * start, never in the session that is running — nor in the jobs a chat already open starts, which run in its process.
645
+ */
646
+ let shellSwitches = null;
647
+ const shellSwitch = (db, key) => {
648
+ shellSwitches ??= Object.fromEntries(['shell.sandbox', 'shell.network'].map((k) => [k, getMeta(db, `config.${k}`) ?? CONFIG_DEFAULTS[k]]));
649
+ return shellSwitches[key];
650
+ };
651
+
652
+ /** Whether the model's shell runs in the OS sandbox: on, unless the user turned it off. */
653
+ export const sandboxOn = (db) => shellSwitch(db, 'shell.sandbox') !== 'off';
654
+ /** Whether the sandboxed shell reaches past this machine: on, unless the user turned it off. */
655
+ export const networkOn = (db) => shellSwitch(db, 'shell.network') !== 'off';
656
+
447
657
  /**
448
658
  * Runs a job to the end of its conversation. Returns what happened, never
449
659
  * throws for anything the model did; a job that is not open is refused up front.
@@ -454,7 +664,11 @@ export function contextFor(project, { jobId = null } = {}) {
454
664
  * What `sumo job tell` left on disk is read with the caller's inbox, so a job
455
665
  * can be spoken to from any shell wherever it runs. `approve` is how an MCP
456
666
  * call not on the allow list reaches the user; without one, such a call is
457
- * refused with the way to allow it.
667
+ * refused with the way to allow it. It also puts a command the sandbox kept
668
+ * from writing to them, for one run outside it. What the job left running in
669
+ * the background ends with it, before anything is settled. A job that closed has its worktree, if it
670
+ * was given one, settled before the run returns (`settle`, src/jobs.mjs): what
671
+ * became of it is in `settled`, and in the report.
458
672
  */
459
673
  export async function runJob(db, id, { send = sendToApi, now, signal = null, onStart = null, onTool = null, onResult = null, onTurn = null, onThinking = null, onRetry = null, onCompact = null, inbox = null, approve = null } = {}) {
460
674
  const job = getJob(db, id);
@@ -464,14 +678,24 @@ export async function runJob(db, id, { send = sendToApi, now, signal = null, onS
464
678
  throw new UsageError(`j${id} is routed to ${job.model}, which is off — sumo models enable ${job.model}, or abandon it and create it again`);
465
679
  }
466
680
  const project = getProject(db, job.project);
681
+ const tree = treeOf(db, id);
682
+ if (tree && !existsSync(tree.path)) throw new UsageError(`j${id}'s worktree, ${tree.path}, no longer exists — abandon it and create it again`);
467
683
  // The MCP servers of this process are the job's too: their tools behind the search tool, their names in its prompt.
468
684
  const registry = await mcpReady();
469
685
  // Whom this job may ask, by the setting and the switches as they are now: the next model up that is on, or nobody.
470
686
  const advisor = (getMeta(db, 'config.jobs.advisor') ?? CONFIG_DEFAULTS['jobs.advisor']) === 'on' ? advisorOf(job.model, usableModels(db)) : null;
687
+ // What this job may spend, by the setting as it is now; shared by both runs, so the second goes on from what the first spent.
688
+ const usd = jobBudget(db);
689
+ const budget = usd === null ? null : { usd, spent: 0, warned: false };
690
+ // How long it may run, the same way: from the start of this run, which both of its conversations share. A job run again — resumed
691
+ // with an answer, say — counts from its own start, as its budget does: nothing of an earlier `sumo job run` is carried over.
692
+ const minutes = jobMinutes(db);
693
+ const clock = minutes === null ? null : { ms: minutes * 60_000, from: Date.parse(now?.() ?? new Date().toISOString()), warned: false };
471
694
  const params = jobParams({ job, text: brief(db, id), system: withServers(systemPrompt(), registry), mcp: registry.tools(), advisor });
472
695
  const lock = tx(db, () => takeRunLock(id));
473
696
  const heard = () => [...(inbox?.() ?? []), ...takeInbox(id)];
474
- const ctx = contextFor(project, { jobId: id });
697
+ // A command the sandbox blocked is put to the user with the job named, as its MCP calls are; its background commands are its own to end.
698
+ const ctx = { ...contextFor(project, { jobId: id, sandbox: sandboxOn(db), network: networkOn(db), tree: tree?.path }), approve: approve && ((ask) => approve({ ...ask, job: id })), background: new Set() };
475
699
  // The workflow gate holds a job's commands as it holds the chat's: once per session for this job, which has a context of its own,
476
700
  // and with the job's own project in scope whether or not its card came up in the session.
477
701
  const gate = (call) => {
@@ -480,29 +704,107 @@ export async function runJob(db, id, { send = sendToApi, now, signal = null, onS
480
704
  if (call.name !== BASH_TOOL.name) return null;
481
705
  if (grantsItself(String(call.input?.command ?? ''))) return { content: SELF_GRANT_REFUSED, isError: true };
482
706
  // A job created where no session had begun is still gated, under a session of its own: it holds no turns, only what was shown.
483
- const held = handleEvent(db, 'pre-tool', { session_id: job.session_id ?? `job:j${id}`, agent_id: `j${id}`, project: job.project, cwd: project.path, tool_name: 'bash', tool_input: { command: String(call.input?.command ?? '') } }, now?.());
707
+ const held = handleEvent(db, 'pre-tool', { session_id: job.session_id ?? `job:j${id}`, agent_id: `j${id}`, project: job.project, cwd: ctx.cwd, tool_name: 'bash', tool_input: { command: String(call.input?.command ?? '') } }, now?.());
484
708
  return held ? { content: JSON.parse(held).deny, isError: true } : null;
485
709
  };
486
710
  try {
487
711
  onStart?.(job);
488
- // A job that outgrows the context is summarized and goes on; its brief is on disk for whatever the summary left out.
489
- const compact = { at: COMPACT_AT, instructions: COMPACT_INSTRUCTIONS, brief: `Your brief, whole, is printed by: sumo job brief ${id}` };
490
- const run = () => converse(db, params, { send, now, signal, onTool, onResult, onTurn, onThinking, onRetry, onCompact, compact, inbox: heard, beforeTool: gate, ctx, ledger: { kind: job.agent, jobId: id, sessionId: job.session_id } });
712
+ // A job that outgrows the context is summarized and goes on; its brief is on disk for whatever the summary left out, and what code
713
+ // recorded of its work is said after the summary.
714
+ const compact = { at: COMPACT_AT, instructions: COMPACT_INSTRUCTIONS, brief: `Your brief, whole, is printed by: sumo job brief ${id}`, state: () => jobWork(db, id, ctx.cwd) };
715
+ const circling = { ...CIRCLES, ask: (calls) => circlingWhy(db, calls) };
716
+ // The job's plan — the latest checklist among its notes — is put back in front of it every so often, as the notes have it then.
717
+ const remind = (turns) => {
718
+ const plan = turns % PLAN_EVERY === 0 ? planOf(id) : null;
719
+ return plan && PLAN_AGAIN(plan);
720
+ };
721
+ const run = () => converse(db, params, { send, now, signal, onTool, onResult, onTurn, onThinking, onRetry, onCompact, compact, budget, clock, circling, remind, inbox: heard, beforeTool: gate, ctx, ledger: { kind: job.agent, jobId: id, sessionId: job.session_id } });
491
722
  let outcome = await run();
492
723
  if (outcome.stop === 'end_turn' && getJob(db, id).status === 'running') {
493
724
  params.messages.push({ role: 'user', content: [{ type: 'text', text: UNCLOSED }] });
725
+ if (budget) budget.spent = outcome.totals.costUsd;
494
726
  const more = await run();
495
727
  const totals = Object.fromEntries(Object.keys(more.totals).map((k) => [k, k === 'contextTokens' ? more.totals[k] : outcome.totals[k] + more.totals[k]]));
496
- outcome = { ...more, turns: outcome.turns + more.turns, text: more.text || outcome.text, totals };
728
+ outcome = { ...more, turns: outcome.turns + more.turns, text: more.text || outcome.text, totals, toldLast: outcome.toldLast || more.toldLast };
497
729
  }
498
- return { ...outcome, job: getJob(db, id) };
730
+ // Kept for what follows the job: one told here to close near a limit is not retried past it (`followUp`, src/jobs.mjs).
731
+ toldToClose(db, id, budget?.warned ? 'budget' : clock?.warned ? 'time' : outcome.toldLast ? 'turns' : null);
732
+ // What it left running in the background goes before its worktree is settled: still running, it would write into a tree being
733
+ // brought back and removed, or be there when the change lands in the project.
734
+ for (const group of ctx.background) killGroup(group);
735
+ const settled = await settle(db, id, now?.());
736
+ return { ...outcome, job: getJob(db, id), settled };
499
737
  } finally {
738
+ for (const group of ctx.background) killGroup(group);
500
739
  rmSync(lock, { force: true });
501
740
  }
502
741
  }
503
742
 
743
+ /** What one job may spend, in dollars, by the setting: none at 0, the default for anything that is not a number. */
744
+ export function jobBudget(db) {
745
+ const raw = String(getMeta(db, 'config.jobs.budget') ?? CONFIG_DEFAULTS['jobs.budget']).trim();
746
+ const asked = raw === '' ? NaN : Number(raw);
747
+ const usd = Number.isFinite(asked) && asked >= 0 ? asked : Number(CONFIG_DEFAULTS['jobs.budget']);
748
+ return usd > 0 ? usd : null;
749
+ }
750
+
751
+ /** How long one job may run, in minutes, by the setting: none at 0, the default for anything that is not a whole number. */
752
+ export function jobMinutes(db) {
753
+ const raw = String(getMeta(db, 'config.jobs.minutes') ?? CONFIG_DEFAULTS['jobs.minutes']).trim();
754
+ const minutes = /^\d+$/.test(raw) ? Number(raw) : Number(CONFIG_DEFAULTS['jobs.minutes']);
755
+ return minutes > 0 ? minutes : null;
756
+ }
757
+
758
+ /**
759
+ * What code recorded of a job's work, said after its summary so the summary is not the only word on it: the files changed since the
760
+ * job began, in twenty lines at most; the last time the checks ran and what they found; and the notes the job kept. Each part that
761
+ * cannot be read is left out without a word; empty when none can.
762
+ */
763
+ function jobWork(db, id, root) {
764
+ const parts = [];
765
+ const record = readState(db, id);
766
+ let changes = null;
767
+ if (record?.snap) {
768
+ try {
769
+ changes = changesSince(root, record.snap);
770
+ // git's stat is its files, a line of "..." past the count, and the totals; the new files fill what is left, the last line saying how many did not fit.
771
+ const stat = diffStat(root, record.snap, CHANGED_LINES - 3).split('\n').filter(Boolean);
772
+ const created = changes.created.map((f) => ` new file: ${f}`);
773
+ const room = CHANGED_LINES - stat.length - 1;
774
+ const listed = stat.length + created.length > CHANGED_LINES ? [...stat, ...created.slice(0, room), ` … and ${created.length - room} more new files`] : [...stat, ...created];
775
+ parts.push(`Changed since the job began:\n${listed.length > 0 ? listed.join('\n') : ' nothing yet'}`);
776
+ } catch {
777
+ changes = null;
778
+ }
779
+ }
780
+ const verdict = record?.verdict;
781
+ if (verdict?.checks) {
782
+ try {
783
+ const moved = changes !== null && verdict.fingerprint !== changes.fingerprint;
784
+ parts.push(`The checks last ran at ${verdict.at} and ${verdict.ok ? 'passed' : 'did not pass'}${moved ? ', on files that have changed since' : ''}:\n${verdictLines(verdict).map((l) => `- ${l}`).join('\n')}`);
785
+ } catch {
786
+ // Left out.
787
+ }
788
+ }
789
+ try {
790
+ const notes = readFileSync(join(paths().jobs, String(id), 'notes.md'), 'utf8').split(/^### /m).filter((n) => n.trim()).map((n) => n.replace(/^[^\n]*\n/, '').trim()).filter(Boolean);
791
+ if (notes.length > 0) parts.push(`Your notes so far:\n${notes.map((n) => `- ${n}`).join('\n')}`);
792
+ } catch {
793
+ // None kept, or none to read.
794
+ }
795
+ return parts.join('\n\n');
796
+ }
797
+
798
+ /** Why the local model finds a job's last calls going round in circles, or null: when it does not, answers outside its shape, or cannot be asked. */
799
+ async function circlingWhy(db, calls) {
800
+ // Given up on as the turn gives up on it: a question still open when the cap is reached would hold the process after the job is over.
801
+ const result = await callLocalModel(db, { system: CIRCLES_SYSTEM, prompt: calls.join('\n'), schema: CIRCLES_SCHEMA, kind: 'loop', log: false, timeoutMs: CIRCLES.ms });
802
+ const { stuck, why } = result.ok ? (result.data ?? {}) : {};
803
+ return stuck === true && typeof why === 'string' && why.trim() ? why.replace(/\s+/g, ' ').trim() : null;
804
+ }
805
+
504
806
  /** One run per job: two would drive two agents over the same tree. */
505
- const takeRunLock = (id) => takeLock(join(paths().jobs, String(id), 'run.lock'), (holder) => `j${id} is already being run (process ${holder}) — wait for it, or stop it there`);
807
+ const takeRunLock = (id) => takeLock(runLockFile(id), (holder) => `j${id} is already being run (process ${holder}) — wait for it, or stop it there`);
506
808
 
507
809
  /** Why a conversation ended, when it was neither the model finishing nor the user stopping it nor an error; null otherwise. Said to a chat as to a job. */
508
810
  export function stopReason(stop) {
@@ -510,8 +812,11 @@ export function stopReason(stop) {
510
812
  if (stop === 'max_tokens') return 'stopped: a reply hit the output limit';
511
813
  if (stop === 'model_context_window_exceeded') return 'stopped: the conversation no longer fits in the model\'s context';
512
814
  if (stop === 'max_turns') return `stopped: ${MAX_TURNS} turns without an end`;
513
- if (stop === 'loop') return `stopped: the same call was made ${REPEAT_STOP_AT} times with the same answer`;
815
+ if (stop === 'loop') return `stopped: the same call, or the same round of calls, was made ${REPEAT_STOP_AT} times in a row`;
816
+ if (stop === 'budget') return 'stopped: the job reached its budget — sumo config jobs.budget sets it, 0 for none';
817
+ if (stop === 'time') return 'stopped: the job reached its time limit — sumo config jobs.minutes sets it, 0 for none';
514
818
  if (stop === 'advisor') return `stopped: the advisor was asked ${ADVISOR_STOP_AT} times`;
819
+ if (stop === 'declined') return `stopped: the user declined ${DECLINE_STOP_AT} calls`;
515
820
  return null;
516
821
  }
517
822