sumo-agents 0.3.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +8 -6
- package/CHANGELOG.md +155 -0
- package/README.md +82 -19
- package/bin/sumo.mjs +13 -2
- package/guides/feature.md +2 -1
- package/guides/memory.md +6 -4
- package/guides/projects.md +1 -1
- package/guides/review.md +1 -1
- package/package.json +5 -4
- package/prompts/dream.md +6 -0
- package/spinner.txt +25 -1
- package/src/apply.mjs +146 -18
- package/src/auth.mjs +32 -5
- package/src/card.mjs +39 -2
- package/src/catalog.mjs +6 -3
- package/src/chat.mjs +289 -89
- package/src/cli.mjs +359 -135
- package/src/cost.mjs +67 -8
- package/src/db.mjs +106 -3
- package/src/dream.mjs +445 -19
- package/src/editor.mjs +113 -11
- package/src/export.mjs +105 -7
- package/src/guard.mjs +57 -11
- package/src/guides.mjs +5 -4
- package/src/herdr.mjs +9 -4
- package/src/hooks.mjs +35 -19
- package/src/jobs.mjs +118 -39
- package/src/jobtools.mjs +6 -4
- package/src/keeper.mjs +77 -0
- package/src/local-server.mjs +9 -16
- package/src/lock.mjs +2 -1
- package/src/logs.mjs +165 -0
- package/src/loop.mjs +121 -44
- package/src/mcp.mjs +72 -16
- package/src/memory.mjs +142 -15
- package/src/model.mjs +41 -21
- package/src/paths.mjs +38 -0
- package/src/prime.mjs +19 -31
- package/src/projects.mjs +94 -12
- package/src/redact.mjs +10 -0
- package/src/render.mjs +2 -1
- package/src/route.mjs +39 -25
- package/src/sandbox.mjs +82 -3
- package/src/scan.mjs +35 -1
- package/src/scribe.mjs +10 -22
- package/src/sessions.mjs +49 -13
- package/src/setup.mjs +425 -76
- package/src/text.mjs +100 -1
- package/src/tools.mjs +258 -21
- package/src/tty.mjs +481 -105
- package/src/ui.mjs +1205 -276
- package/src/verify.mjs +17 -1
package/src/chat.mjs
CHANGED
|
@@ -1,34 +1,35 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
2
|
import { EventEmitter } from 'node:events';
|
|
3
|
-
import { appendFileSync,
|
|
4
|
-
import { basename, dirname, join, relative, resolve } from 'node:path';
|
|
3
|
+
import { appendFileSync, mkdirSync, readFileSync, rmSync, statSync } from 'node:fs';
|
|
4
|
+
import { basename, dirname, join, relative, resolve, sep } from 'node:path';
|
|
5
5
|
import { createInterface } from 'node:readline/promises';
|
|
6
6
|
import { isAdvisorTool } from './advisor.mjs';
|
|
7
7
|
import { ago } from './card.mjs';
|
|
8
8
|
import { getMeta } from './db.mjs';
|
|
9
|
-
import { runDream } from './dream.mjs';
|
|
10
9
|
import { openWatchTab, runHerdr } from './herdr.mjs';
|
|
11
10
|
import { appendLive, attemptsSettled, endLive, getJob, newJob, parseJobId, reportOf, runFollowed, startLive, tell as tellJob, treeOf } from './jobs.mjs';
|
|
12
11
|
import { handleEvent } from './hooks.mjs';
|
|
13
|
-
import { contextFor, converse, networkOn, paramsFor, runJob, runLines, sandboxOn, sendToApi, stopReason, TAMPER_REFUSED, tampersMarker, textOf, thinkingFor, withMcp, withServers } from './loop.mjs';
|
|
12
|
+
import { COMPACT_INSTRUCTIONS, compactionParams, contextFor, converse, describeFailure, networkOn, paramsFor, QUIET_RETRIES, runJob, runLines, sandboxOn, sendToApi, stopReason, TAMPER_REFUSED, tampersMarker, textOf, thinkingFor, withFallback, withMcp, withServers } from './loop.mjs';
|
|
13
|
+
import { logRun, usageOf } from './model.mjs';
|
|
14
14
|
import { closeMcp, compactInput, gateMcp, isMcpTool, mcpLines, mcpReady, splitMcpName } from './mcp.mjs';
|
|
15
|
+
import { EFFORT_MESSAGE_BETA, effortOnly } from './auth.mjs';
|
|
15
16
|
import { assertOn, MODEL_IDS, MODELS, modelId, usableModels } from './catalog.mjs';
|
|
16
17
|
import { takeLock } from './lock.mjs';
|
|
17
18
|
import { paths, REPO_ROOT } from './paths.mjs';
|
|
18
19
|
import { UsageError } from './memory.mjs';
|
|
19
20
|
import { openInBrowser, servePage } from './page.mjs';
|
|
20
|
-
import { getProject, scratchDir } from './projects.mjs';
|
|
21
|
+
import { getProject, projectAt, scratchDir } from './projects.mjs';
|
|
21
22
|
import { redact } from './redact.mjs';
|
|
22
23
|
import { chooseChatRoute, EFFORTS } from './route.mjs';
|
|
23
24
|
import { verifyCommands } from './scan.mjs';
|
|
24
|
-
import {
|
|
25
|
-
import { currentProject, describeSaved, findSaved, loadState, lockFile, recordTurn, saveState, savedSessions, sessionLine, shortId, withoutThinking } from './sessions.mjs';
|
|
25
|
+
import { passLines, runMemoryPass } from './keeper.mjs';
|
|
26
|
+
import { currentProject, describeSaved, findSaved, loadState, lockFile, noteSessionOutside, recordTurn, saveState, savedSessions, sessionLine, shortId, withoutThinking } from './sessions.mjs';
|
|
26
27
|
import { ASK_TOOL, BASH_TOOL, cap, capRedacted, DELEGATE_TOOL, EDITOR_TOOL, INTERRUPTED, nextUndoTurn, runCommand, undoLast } from './tools.mjs';
|
|
27
28
|
import { CONFIG_DEFAULTS } from './setup.mjs';
|
|
28
|
-
import { estimateTokens, head } from './text.mjs';
|
|
29
|
-
import { colourEnabled, createRenderer, header, pathFrom, prompt, renderBlock, safeForTerminal, styles, tilde, widthOf } from './tty.mjs';
|
|
29
|
+
import { closest, estimateTokens, head } from './text.mjs';
|
|
30
|
+
import { colourEnabled, createRenderer, explained, header, ledger, OUT_AT, pathFrom, prompt, renderBlock, safeForTerminal, styles, TEXT_AT, tilde, toolView, widthOf, wrap } from './tty.mjs';
|
|
30
31
|
import { hasCommit } from './verify.mjs';
|
|
31
|
-
import { sourcesOf, WEB_FETCH_TOOL, WEB_SEARCH_TOOL, WEB_TOOLS } from './web.mjs';
|
|
32
|
+
import { isWebTool, sourcesOf, WEB_FETCH_TOOL, WEB_SEARCH_TOOL, WEB_TOOLS } from './web.mjs';
|
|
32
33
|
|
|
33
34
|
/**
|
|
34
35
|
* The conversation the user has with Sumo: the same loop a job runs in, with
|
|
@@ -43,7 +44,9 @@ import { sourcesOf, WEB_FETCH_TOOL, WEB_SEARCH_TOOL, WEB_TOOLS } from './web.mjs
|
|
|
43
44
|
*/
|
|
44
45
|
|
|
45
46
|
/** Models that take operator instructions as `role: "system"` messages mid-conversation; the others get them as text in the user turn. */
|
|
46
|
-
const SYSTEM_MESSAGES = new Set([MODEL_IDS.opus, MODEL_IDS.sonnet, MODEL_IDS.fable]);
|
|
47
|
+
const SYSTEM_MESSAGES = new Set([MODEL_IDS.haiku, MODEL_IDS.opus, MODEL_IDS.sonnet, MODEL_IDS.fable]);
|
|
48
|
+
/** Models whose effort can be changed by a message in the conversation, leaving the cache whole: the same four, with thinking on as it always is here. */
|
|
49
|
+
const EFFORT_MESSAGES = SYSTEM_MESSAGES;
|
|
47
50
|
|
|
48
51
|
// The guide comes with the command, by name, through the prompt hook — the same way it comes when the user's words ask for
|
|
49
52
|
// it: from inside a project the tools cannot reach guides/ by a relative path, and the editor is jailed away from it.
|
|
@@ -51,44 +54,62 @@ const COMMANDS = {
|
|
|
51
54
|
fix: (args) => ({ text: `Fix this: ${args}`, guide: 'fix' }),
|
|
52
55
|
feature: (args) => ({ text: `Build this: ${args}`, guide: 'feature' }),
|
|
53
56
|
review: (args) => ({ text: `Review this: ${args}`, guide: 'review' }),
|
|
54
|
-
dream: () => ({ text: 'Run `sumo dream run` and tell me, in a few lines, what it changed and what it wants me to confirm.' }),
|
|
55
57
|
};
|
|
56
58
|
|
|
59
|
+
/** What each model is for, as `/model`'s menu says it: the kinds of work the router gives it. */
|
|
60
|
+
const MODEL_HINTS = {
|
|
61
|
+
auto: 'the router picks a model and an effort each turn',
|
|
62
|
+
haiku: 'quickest and cheapest: small, mechanical changes',
|
|
63
|
+
sonnet: 'everyday features and fixes',
|
|
64
|
+
opus: 'hard problems: design, a bug with no clear cause',
|
|
65
|
+
fable: 'novel work: new algorithms, deep reviews',
|
|
66
|
+
};
|
|
67
|
+
/** And each effort: how much the model thinks before it acts. */
|
|
68
|
+
const EFFORT_HINTS = { low: 'quickest: one spot', medium: 'a few files', high: 'many parts that work together', xhigh: 'more thought still, slower', max: 'the most thought, the slowest' };
|
|
69
|
+
|
|
57
70
|
/**
|
|
58
|
-
* What the command menu shows, in the order it shows it
|
|
59
|
-
* The
|
|
71
|
+
* What the command menu shows, in the order it shows it, each with what it does for the user — and, for /help, what it
|
|
72
|
+
* takes (`args`). The models `/model` offers are the ones that are on as it is typed, each with what it is for and the one
|
|
73
|
+
* in use marked (`inUse`). The effort a model would keep comes first (`effortNow`), so Enter on the open menu keeps it
|
|
74
|
+
* rather than dropping to the lowest.
|
|
60
75
|
*/
|
|
61
|
-
|
|
76
|
+
function commandList(db, { effortNow = () => null, inUse = () => ({}), saved = () => [], running = () => [] } = {}) {
|
|
62
77
|
const efforts = () => {
|
|
63
|
-
const
|
|
64
|
-
return EFFORTS.includes(
|
|
78
|
+
const kept = effortNow();
|
|
79
|
+
return EFFORTS.includes(kept) ? [kept, ...EFFORTS.filter((e) => e !== kept)] : EFFORTS;
|
|
65
80
|
};
|
|
81
|
+
const marked = (name, hint, current) => ({ name, hint: `${hint}${name === current ? ' (current)' : ''}` });
|
|
66
82
|
const modelChoices = (given) => {
|
|
67
83
|
const usable = usableModels(db);
|
|
68
|
-
|
|
84
|
+
const { model, effort } = inUse();
|
|
85
|
+
if (given.length === 0) return ['auto', ...usable].map((name) => marked(name, MODEL_HINTS[name] ?? '', model));
|
|
86
|
+
return given.length === 1 && usable.includes(given[0]) ? efforts().map((name) => marked(name, EFFORT_HINTS[name] ?? '', model === 'auto' ? null : effort)) : [];
|
|
69
87
|
};
|
|
70
88
|
return [
|
|
71
|
-
{ name: 'fix', hint: 'fix a bug,
|
|
72
|
-
{ name: 'feature', hint: 'build something,
|
|
73
|
-
{ name: 'review', hint: 'have a reviewer
|
|
74
|
-
{ name: '
|
|
75
|
-
{ name: '
|
|
76
|
-
{ name: '
|
|
77
|
-
{ name: '
|
|
78
|
-
{ name: '
|
|
79
|
-
{ name: '
|
|
80
|
-
{ name: '
|
|
81
|
-
{ name: '
|
|
89
|
+
{ name: 'fix', args: '<bug>', hint: 'fix a bug: find the cause, change it, check it' },
|
|
90
|
+
{ name: 'feature', args: '<what>', hint: 'build something new, with its tests' },
|
|
91
|
+
{ name: 'review', args: '<what>', hint: 'have a reviewer look over a change' },
|
|
92
|
+
{ name: 'model', args: '[model] [effort]', hint: 'the model and effort: see them, or change them', choices: modelChoices },
|
|
93
|
+
{ name: 'memory', hint: 'your memory in the browser: confirm, edit, forget' },
|
|
94
|
+
{ name: 'mcp', hint: 'the MCP servers: which are connected, and their tools' },
|
|
95
|
+
{ name: 'resume', args: '[id]', hint: 'pick up a saved session where it stopped', choices: (given) => (given.length === 0 ? saved().map((s) => ({ name: shortId(s.id), hint: s.hint })) : []) },
|
|
96
|
+
{ name: 'copy', args: '[code] [n]', hint: 'copy the last reply, or its code, to the clipboard', choices: (given) => (given.length === 0 ? ['code'] : []) },
|
|
97
|
+
{ name: 'undo', hint: 'put back the files the last turn edited' },
|
|
98
|
+
{ name: 'stop', args: '[job]', hint: 'stop a job working in the background', choices: (given) => (given.length === 0 ? running().map((id) => `j${id}`) : []) },
|
|
99
|
+
{ name: 'context', hint: 'how full the context is, and what it has cost' },
|
|
100
|
+
{ name: 'export', args: '[path]', hint: 'save the conversation as a Markdown file' },
|
|
101
|
+
{ name: 'thinking', args: 'on|off', hint: "show or hide the model's thinking as it works", choices: (given) => (given.length === 0 ? ['on', 'off'] : []) },
|
|
82
102
|
{ name: 'help', hint: 'the commands and the keys' },
|
|
83
|
-
{ name: '
|
|
84
|
-
{ name: '
|
|
103
|
+
{ name: 'handoff', hint: 'start fresh from a hand-off the model writes' },
|
|
104
|
+
{ name: 'new', hint: 'start a fresh session (/clear does too)' },
|
|
105
|
+
{ name: 'exit', hint: 'leave (/quit does too)' },
|
|
85
106
|
];
|
|
86
107
|
}
|
|
87
108
|
|
|
88
109
|
/** A job is run with `delegate`, never from the shell: there it would be an agent in a shell of its own, holding no credential. */
|
|
89
110
|
const JOB_RUN = /(?:^|[\n;&|(`]|\$\()\s*(?:\w+=\S*\s+|nohup\s+|exec\s+)*sumo\s+job\s+(run|new)\b/;
|
|
90
|
-
/**
|
|
91
|
-
const PASS_RUN = /^\s*sumo\s+
|
|
111
|
+
/** The memory pass the model asks for: run here too, since the shell it would start in holds no credential. */
|
|
112
|
+
const PASS_RUN = /^\s*sumo\s+memory\s+run(\s+--tidy)?\s*$/;
|
|
92
113
|
|
|
93
114
|
/**
|
|
94
115
|
* Operator text for the model, placed so the cached prefix is untouched: a
|
|
@@ -147,7 +168,7 @@ export function describeCall(call) {
|
|
|
147
168
|
* The branch a directory's repository is on, read from its HEAD — no process is started for it. A worktree's `.git` is a
|
|
148
169
|
* file that names where its HEAD is. A detached head is the start of its commit; a directory in no repository has none.
|
|
149
170
|
*/
|
|
150
|
-
|
|
171
|
+
function branchOf(dir) {
|
|
151
172
|
for (let at = resolve(dir); ; at = dirname(at)) {
|
|
152
173
|
const git = join(at, '.git');
|
|
153
174
|
try {
|
|
@@ -172,9 +193,9 @@ export const routeOf = ({ model, effort }) => (effort && effort !== 'none' ? `${
|
|
|
172
193
|
|
|
173
194
|
/**
|
|
174
195
|
* What `/model` was given: a model that is on, a model and an effort, or `auto`. The model alone keeps
|
|
175
|
-
* the effort in hand
|
|
196
|
+
* the effort in hand. Anything else is said back, and nothing changes.
|
|
176
197
|
*/
|
|
177
|
-
|
|
198
|
+
function parseRoute(args, current, db) {
|
|
178
199
|
const [model, effort, ...rest] = args.split(/\s+/).filter(Boolean);
|
|
179
200
|
if (model === 'auto') {
|
|
180
201
|
if (effort) throw new UsageError('auto takes no effort — the router picks it each turn');
|
|
@@ -183,10 +204,6 @@ export function parseRoute(args, current, db) {
|
|
|
183
204
|
if (!MODELS.includes(model)) throw new UsageError(`no such model "${model}" — one of: auto, ${usableModels(db).join(', ')}`);
|
|
184
205
|
assertOn(db, model);
|
|
185
206
|
if (rest.length > 0) throw new UsageError(`/model takes a model and an effort, not "${args}"`);
|
|
186
|
-
if (model === 'haiku') {
|
|
187
|
-
if (effort) throw new UsageError('haiku takes no effort setting');
|
|
188
|
-
return { model, effort: 'none' };
|
|
189
|
-
}
|
|
190
207
|
if (effort !== undefined && !EFFORTS.includes(effort)) throw new UsageError(`no such effort "${effort}" — one of: ${EFFORTS.join(', ')}`);
|
|
191
208
|
const kept = current.effort && current.effort !== 'none' ? current.effort : CONFIG_DEFAULTS['chat.effort'];
|
|
192
209
|
return { model, effort: effort ?? kept };
|
|
@@ -198,24 +215,34 @@ export function parseRoute(args, current, db) {
|
|
|
198
215
|
* draws a reply, set in under its line. `clean` is done to the words before they are drawn: a wrapped line must not
|
|
199
216
|
* break a secret apart where the redaction after it would no longer see it whole.
|
|
200
217
|
*/
|
|
201
|
-
export function jobPrinter(write, s, { width = 98, clean = (text) => text } = {}) {
|
|
218
|
+
export function jobPrinter(write, s, { width = 98, clean = (text) => text, cwd = null } = {}) {
|
|
219
|
+
// Each call as the chat's ledger names it — run npm test, read src/cart.js — a file from the project the job works in.
|
|
220
|
+
const at = () => (typeof cwd === 'function' ? cwd() : cwd);
|
|
202
221
|
return {
|
|
203
|
-
onStart: (job) => write(
|
|
204
|
-
onTool: (call) =>
|
|
205
|
-
|
|
206
|
-
|
|
222
|
+
onStart: (job) => write(`${s.bold(ledger(`j${job.id}`))}${job.agent} · ${routeOf(job)} — ${job.title}\n`),
|
|
223
|
+
onTool: (call) => {
|
|
224
|
+
const view = toolView(call, null, { cwd: at() });
|
|
225
|
+
// One line, and where more was cut away, the ellipsis that says so.
|
|
226
|
+
const [first, ...rest] = clean(view.detail).split('\n');
|
|
227
|
+
const line = first.length > 160 ? `${first.slice(0, 159)}…` : rest.length > 0 && !first.endsWith('…') ? `${first} …` : first;
|
|
228
|
+
write(`${s.dim(ledger(view.title))}${line}\n`);
|
|
229
|
+
},
|
|
230
|
+
onRetry: (r) => write(`${' '.repeat(TEXT_AT)}${s.dim(retryLine(r))}\n`),
|
|
231
|
+
onCompact: (c) => write(`${' '.repeat(TEXT_AT)}${s.dim(compactLine(c))}\n`),
|
|
207
232
|
onResult: (call, result) => {
|
|
208
|
-
|
|
209
|
-
|
|
233
|
+
// 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
|
|
234
|
+
// edit's first change — under the step's words; a failure with its mark, which says so without the colour.
|
|
235
|
+
const first = toolView(call, { content: String(result.content ?? ''), isError: Boolean(result.isError), edit: result.edit }, { cwd: at() }).lines[0]?.text ?? '';
|
|
236
|
+
write(`${' '.repeat(OUT_AT - 2)}${result.isError ? `${s.red('✗')} ` : ' '}${s.dim(clean(first).slice(0, 160))}\n`);
|
|
210
237
|
},
|
|
211
238
|
onTurn: (response) => {
|
|
212
239
|
const text = textOf(response.content);
|
|
213
240
|
if (!text) return;
|
|
214
241
|
const drawn = [];
|
|
215
|
-
const reply = createRenderer((t) => drawn.push(t), s, { width });
|
|
242
|
+
const reply = createRenderer((t) => drawn.push(t), s, { width: width - TEXT_AT });
|
|
216
243
|
reply.write(clean(text));
|
|
217
244
|
reply.flush();
|
|
218
|
-
write(`${drawn.join('').split('\n').map((l) => (l ?
|
|
245
|
+
write(`${drawn.join('').split('\n').map((l, i) => (i === 0 ? `${s.bold(ledger('sumo'))}${l}` : l ? `${' '.repeat(TEXT_AT)}${l}` : l)).join('\n')}\n`);
|
|
219
246
|
},
|
|
220
247
|
};
|
|
221
248
|
}
|
|
@@ -224,8 +251,28 @@ export function jobPrinter(write, s, { width = 98, clean = (text) => text } = {}
|
|
|
224
251
|
export const retryLine = ({ attempt, limit, delayMs, reason }) => `retrying in ${Math.max(1, Math.round(delayMs / 1000))}s (${attempt} of ${limit}) — ${reason}`;
|
|
225
252
|
/** A conversation summarized to make room, in one line: how big it had grown. */
|
|
226
253
|
export const compactLine = ({ before }) => `the conversation was summarized at ${Math.round(before / 1000)}k tokens to make room, and goes on from the summary`;
|
|
254
|
+
const kilo = (n) => (n >= 1000 ? `${(n / 1000).toFixed(n >= 10_000 ? 0 : 1)}k` : String(n));
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* `/context`: how full the context is — against the size where it is time to start afresh, with the word for its band — and
|
|
258
|
+
* what the session has used, by who asked and on which model. Markdown, drawn as a reply is.
|
|
259
|
+
*/
|
|
260
|
+
export function contextReport({ contextTokens = 0, rows = [], turns = 0, calls = 0 }) {
|
|
261
|
+
const full = Math.min(1, contextTokens / CONTEXT_FULL);
|
|
262
|
+
const bar = `${'█'.repeat(Math.round(full * 20))}${'░'.repeat(20 - Math.round(full * 20))}`;
|
|
263
|
+
const band = contextTokens >= CONTEXT_FULL ? 'very large — /handoff now, or /new; the memory brings the thread back' : contextTokens >= CONTEXT_LARGE ? 'large — quality drops from here; finish the piece in hand, then /handoff' : 'room to spare';
|
|
264
|
+
const cost = rows.reduce((sum, row) => sum + row.cost, 0);
|
|
265
|
+
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)}`];
|
|
266
|
+
if (rows.length === 0) return [...lines, '', 'No request has been made yet.'].join('\n');
|
|
267
|
+
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');
|
|
268
|
+
}
|
|
269
|
+
|
|
227
270
|
/** A session past its budget, in one line: what it has cost, how to start afresh, and how to move the line. */
|
|
228
|
-
|
|
271
|
+
const budgetLine = (cost) => `this session has cost $${cost.toFixed(2)} — /new starts a fresh one; sumo config chat.budget changes when this is said`;
|
|
272
|
+
|
|
273
|
+
/** Where the context is large enough that quality drops, and where it is time for /handoff: the bands the session is told about. */
|
|
274
|
+
const CONTEXT_LARGE = 60_000;
|
|
275
|
+
const CONTEXT_FULL = 150_000;
|
|
229
276
|
|
|
230
277
|
/** The session log, one JSON line per message, the shape the scribe reads assistant replies from and the gauge reads usage from. */
|
|
231
278
|
function logLine(file, entry) {
|
|
@@ -275,14 +322,14 @@ export function createChat(db, { model, effort, cwd = process.cwd(), send = send
|
|
|
275
322
|
const named = MODELS.find((name) => MODEL_IDS[name] === model) ?? model;
|
|
276
323
|
if (named !== 'auto' && MODELS.includes(named)) assertOn(db, named, 'sumo config chat.model <name>');
|
|
277
324
|
effort ??= model === 'auto' ? null : configured(db, 'chat.effort');
|
|
278
|
-
// Haiku takes no effort setting, however the chat came to be on it: by flag, by configuration, or by /model.
|
|
279
|
-
if (modelId(model) === MODEL_IDS.haiku) effort = 'none';
|
|
280
325
|
/** On auto, the route the last turn ran on; null otherwise. */
|
|
281
326
|
let routed = null;
|
|
282
327
|
const system = chatSystem();
|
|
283
328
|
const own = CHAT_TOOLS;
|
|
284
329
|
/** The MCP servers of this process, once connected: their tools join the request, deferred, and their names the system prompt. */
|
|
285
330
|
let registry = null;
|
|
331
|
+
/** Whether the servers' tools have joined the requests: once, at the first turn after they connected. */
|
|
332
|
+
let joined = false;
|
|
286
333
|
const connecting = mcpReady().then((r) => {
|
|
287
334
|
registry = r;
|
|
288
335
|
});
|
|
@@ -302,6 +349,8 @@ export function createChat(db, { model, effort, cwd = process.cwd(), send = send
|
|
|
302
349
|
let note = null;
|
|
303
350
|
/** The files the model has viewed or written in this session, as they stood then: an edit to one changed on disk since says so. */
|
|
304
351
|
let seen = new Map();
|
|
352
|
+
/** The files outside the project the user let the editor change for the rest of this session. */
|
|
353
|
+
let opened = new Set();
|
|
305
354
|
/** Whether the screen has said what this session cost: once a session, when it first passes `chat.budget`. */
|
|
306
355
|
let costSaid = false;
|
|
307
356
|
/** The jobs running here, each with what the user has said to it that it has not read yet. */
|
|
@@ -331,13 +380,14 @@ export function createChat(db, { model, effort, cwd = process.cwd(), send = send
|
|
|
331
380
|
const kept = effort ?? configured(db, 'chat.effort');
|
|
332
381
|
return kept && kept !== 'none' ? kept : CONFIG_DEFAULTS['chat.effort'];
|
|
333
382
|
},
|
|
383
|
+
inUse: () => ({ model, effort }),
|
|
334
384
|
saved: () => others().map((s) => ({ id: s.id, hint: describeSaved(s, now()) })),
|
|
335
385
|
running: () => [...stops.keys()],
|
|
336
386
|
});
|
|
337
387
|
|
|
338
388
|
const emit = (text) => out(text);
|
|
339
389
|
/** The conversation as the model in hand can take it: one that takes no operator messages is sent them as text. The history itself is left alone, so a model that does take them still reads it from its cache. */
|
|
340
|
-
const sendAs = (p, options) => send(SYSTEM_MESSAGES.has(p.model) ? p : { ...p, messages: p.messages.map((m) => (m.role === 'system' ? asText(m.content) : m)) }, options);
|
|
390
|
+
const sendAs = (p, options) => send(SYSTEM_MESSAGES.has(p.model) ? p : { ...p, messages: p.messages.filter((m) => !effortOnly(m)).map((m) => (m.role === 'system' ? asText(m.content) : m)) }, options);
|
|
341
391
|
|
|
342
392
|
const busy = (id) => (holder) => `session ${shortId(id)} is open in another terminal (process ${holder})`;
|
|
343
393
|
|
|
@@ -356,6 +406,7 @@ export function createChat(db, { model, effort, cwd = process.cwd(), send = send
|
|
|
356
406
|
costSaid = false;
|
|
357
407
|
project = null;
|
|
358
408
|
seen = new Map();
|
|
409
|
+
opened = new Set();
|
|
359
410
|
spoken = Boolean(saved);
|
|
360
411
|
transcript = join(paths().logs, 'sessions', `${sessionId}.jsonl`);
|
|
361
412
|
const block = handleEvent(db, 'session-start', { session_id: sessionId, cwd, transcript_path: transcript, source }, now());
|
|
@@ -363,9 +414,10 @@ export function createChat(db, { model, effort, cwd = process.cwd(), send = send
|
|
|
363
414
|
model = saved.model;
|
|
364
415
|
routed = saved.routed ?? null;
|
|
365
416
|
if (!given.effort) effort = saved.effort;
|
|
366
|
-
if (modelId(model) === MODEL_IDS.haiku) effort = 'none';
|
|
367
417
|
}
|
|
368
418
|
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 });
|
|
419
|
+
// What jobs reported that this session had not read comes back with it; a fresh session has read nothing, and is owed nothing.
|
|
420
|
+
reports.splice(0, reports.length, ...(saved?.pending ?? []));
|
|
369
421
|
if (saved) {
|
|
370
422
|
params.messages = withoutThinking(saved.messages);
|
|
371
423
|
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,24 +442,55 @@ export function createChat(db, { model, effort, cwd = process.cwd(), send = send
|
|
|
390
442
|
return `resumed ${sessionLine(found, now())} — the first reply pays one uncached turn`;
|
|
391
443
|
}
|
|
392
444
|
|
|
445
|
+
/** The session kept where nothing can say a failure: a save that fails here is tried again after the next turn. */
|
|
446
|
+
function keepQuietly() {
|
|
447
|
+
try {
|
|
448
|
+
persist();
|
|
449
|
+
} catch {
|
|
450
|
+
// Said, if it still fails, by the save after the next turn.
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
|
|
393
454
|
/** 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
455
|
function persist() {
|
|
395
456
|
if (!spoken) return;
|
|
396
457
|
try {
|
|
397
|
-
saveState({ id: sessionId, messages: params.messages, model, effort, routed, cwd, contextTokens: lastContext, now: now() });
|
|
458
|
+
saveState({ id: sessionId, messages: params.messages, model, effort, routed, cwd, contextTokens: lastContext, now: now(), pending: reports.map(({ id, quiet, text }) => ({ id, quiet, text })) });
|
|
398
459
|
} catch (cause) {
|
|
399
460
|
throw new UsageError(`the session could not be saved: ${cause.message}`);
|
|
400
461
|
}
|
|
401
462
|
}
|
|
402
463
|
|
|
403
|
-
/**
|
|
464
|
+
/**
|
|
465
|
+
* The request from here on goes to this model at this effort, thinking as that model does; the conversation so far stays.
|
|
466
|
+
* On the same model, a new effort is said in the conversation — a system message with no content, carrying the effort — so
|
|
467
|
+
* the cached history is not written again, as changing the request's own effort would have it. A model switch writes it
|
|
468
|
+
* again whichever way, so there the request's own effort changes; one said earlier in the conversation would outrank it,
|
|
469
|
+
* so when one was, the new effort is said again too.
|
|
470
|
+
*/
|
|
404
471
|
function apply({ model: m, effort: e }) {
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
const
|
|
409
|
-
|
|
410
|
-
|
|
472
|
+
const id = modelId(m);
|
|
473
|
+
const wanted = e && e !== 'none' ? e : null;
|
|
474
|
+
const switched = params.model !== id;
|
|
475
|
+
const spoken = params.messages.some(effortOnly);
|
|
476
|
+
const inForce = params.messages.findLast(effortOnly)?.output_config.effort ?? params.output_config?.effort ?? null;
|
|
477
|
+
if (switched) {
|
|
478
|
+
params.model = id;
|
|
479
|
+
if (wanted) params.output_config = { effort: wanted };
|
|
480
|
+
else delete params.output_config;
|
|
481
|
+
const thinking = thinkingFor(m);
|
|
482
|
+
if (thinking) params.thinking = thinking;
|
|
483
|
+
else delete params.thinking;
|
|
484
|
+
withFallback(params, m);
|
|
485
|
+
}
|
|
486
|
+
if (wanted === inForce && !(switched && spoken)) return;
|
|
487
|
+
if (wanted && EFFORT_MESSAGES.has(id) && params.messages.length > 0 && (!switched || spoken)) {
|
|
488
|
+
params.messages.push({ role: 'system', content: [], output_config: { effort: wanted } });
|
|
489
|
+
if (!params.betas.includes(EFFORT_MESSAGE_BETA)) params.betas = [...params.betas, EFFORT_MESSAGE_BETA];
|
|
490
|
+
} else if (!switched) {
|
|
491
|
+
if (wanted) params.output_config = { effort: wanted };
|
|
492
|
+
else delete params.output_config;
|
|
493
|
+
}
|
|
411
494
|
}
|
|
412
495
|
|
|
413
496
|
/**
|
|
@@ -431,9 +514,12 @@ export function createChat(db, { model, effort, cwd = process.cwd(), send = send
|
|
|
431
514
|
/** Where this session's turns keep what the editor changed, for /undo. */
|
|
432
515
|
const undoDir = () => join(paths().logs, 'undo', sessionId);
|
|
433
516
|
|
|
434
|
-
/**
|
|
517
|
+
/**
|
|
518
|
+
* 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
|
|
519
|
+
* (tools then run in scratch).
|
|
520
|
+
*/
|
|
435
521
|
function workspace() {
|
|
436
|
-
const slug = currentProject(db, sessionId);
|
|
522
|
+
const slug = currentProject(db, sessionId) ?? projectAt(db, cwd);
|
|
437
523
|
if (slug && project?.slug !== slug) project = getProject(db, slug);
|
|
438
524
|
return contextFor(project ?? { path: scratchDir() }, { sandbox: sandboxOn(db), network: networkOn(db) });
|
|
439
525
|
}
|
|
@@ -478,8 +564,8 @@ export function createChat(db, { model, effort, cwd = process.cwd(), send = send
|
|
|
478
564
|
if (gate) return { content: JSON.parse(gate).deny, isError: true };
|
|
479
565
|
const pass = PASS_RUN.exec(command);
|
|
480
566
|
if (pass) {
|
|
481
|
-
activity(
|
|
482
|
-
return { content:
|
|
567
|
+
activity(pass[1] ? 'tidying memory…' : 'running the memory pass…');
|
|
568
|
+
return { content: passLines(await runMemoryPass(db, { tidy: Boolean(pass[1]) }), { asked: Boolean(pass[1]) }).join('\n') };
|
|
483
569
|
}
|
|
484
570
|
const job = JOB_RUN.exec(command);
|
|
485
571
|
if (job) return { content: `jobs are not ${job[1] === 'new' ? 'made' : 'run'} from the shell: use the delegate tool${job[1] === 'run' ? ' (only `job` for one already made)' : ''}`, isError: true };
|
|
@@ -558,6 +644,8 @@ export function createChat(db, { model, effort, cwd = process.cwd(), send = send
|
|
|
558
644
|
runs.delete(run);
|
|
559
645
|
const quiet = ids.filter((each) => stoppedByUser.delete(each)).length > 0;
|
|
560
646
|
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}` });
|
|
647
|
+
// Kept with the session as soon as it comes: a chat closed before the next message still has it when picked up again.
|
|
648
|
+
keepQuietly();
|
|
561
649
|
watch({ type: 'job-report', job: id, result, quiet });
|
|
562
650
|
});
|
|
563
651
|
runs.add(run);
|
|
@@ -608,7 +696,7 @@ export function createChat(db, { model, effort, cwd = process.cwd(), send = send
|
|
|
608
696
|
// Its work is written down as it happens, for `sumo job watch` — in a Herdr tab of its own, or any terminal —
|
|
609
697
|
// and without its secrets, through the same redaction as what the model sees.
|
|
610
698
|
const record = (t) => appendLive(id, redact(t).text);
|
|
611
|
-
const live = jobPrinter(record, styles(false), { clean: (t) => redact(t).text });
|
|
699
|
+
const live = jobPrinter(record, styles(false), { clean: (t) => redact(t).text, cwd: () => getProject(db, getJob(db, id)?.project ?? '')?.path ?? null });
|
|
612
700
|
let ended = [];
|
|
613
701
|
try {
|
|
614
702
|
const outcome = await runJob(db, id, {
|
|
@@ -716,10 +804,10 @@ export function createChat(db, { model, effort, cwd = process.cwd(), send = send
|
|
|
716
804
|
return id;
|
|
717
805
|
}
|
|
718
806
|
|
|
719
|
-
/** A turn that ended before the model answered left its operator message at the tail; the API takes one only where the model answers next, so before anything follows it, it becomes text. */
|
|
807
|
+
/** A turn that ended before the model answered left its operator message at the tail; the API takes one only where the model answers next, so before anything follows it, it becomes text. An effort said there may stand anywhere, and stays. */
|
|
720
808
|
function settleTail() {
|
|
721
809
|
const tail = params.messages.at(-1);
|
|
722
|
-
if (tail?.role === 'system') params.messages[params.messages.length - 1] = asText(tail.content);
|
|
810
|
+
if (tail?.role === 'system' && !effortOnly(tail)) params.messages[params.messages.length - 1] = asText(tail.content);
|
|
723
811
|
}
|
|
724
812
|
|
|
725
813
|
/**
|
|
@@ -772,23 +860,32 @@ export function createChat(db, { model, effort, cwd = process.cwd(), send = send
|
|
|
772
860
|
|
|
773
861
|
async function turn(text, said, images, automated = false, guide = null) {
|
|
774
862
|
stopper = new AbortController();
|
|
775
|
-
// Edits nothing has checked: an editor call that
|
|
776
|
-
//
|
|
777
|
-
// left. The shell can edit too (`sed -i`,
|
|
863
|
+
// Edits nothing has checked: an editor call that wrote adds its file — one refused, or whose old_str was not found,
|
|
864
|
+
// changed nothing and adds none; one of the project's declared checks running clears them — any command does when
|
|
865
|
+
// the project declares none. The gate at the end of the turn is told what is left. The shell can edit too (`sed -i`,
|
|
866
|
+
// a redirect); that is not seen.
|
|
778
867
|
const unchecked = new Set();
|
|
779
868
|
const declared = () => verifyCommands(workspace().cwd).map((c) => c.command);
|
|
780
869
|
const noteCall = (call) => {
|
|
781
|
-
if (call.name === EDITOR_TOOL.name && call.input?.command !== 'view' && call.input?.path) unchecked.add(resolve(workspace().cwd, String(call.input.path)));
|
|
782
870
|
if (call.name !== BASH_TOOL.name) return;
|
|
783
871
|
const checks = declared();
|
|
784
872
|
if (checks.length === 0 || checks.some((c) => String(call.input?.command ?? '').includes(c))) unchecked.clear();
|
|
785
873
|
};
|
|
786
|
-
//
|
|
787
|
-
|
|
874
|
+
// Only the project's own files are the project's check to judge: a file outside it the user let change is theirs.
|
|
875
|
+
const noteResult = (call, result) => {
|
|
876
|
+
if (call.name !== EDITOR_TOOL.name || call.input?.command === 'view' || !call.input?.path || result?.isError) return;
|
|
877
|
+
const { cwd: root } = workspace();
|
|
878
|
+
const path = resolve(root, String(call.input.path));
|
|
879
|
+
if (path.startsWith(`${root}${sep}`)) unchecked.add(path);
|
|
880
|
+
};
|
|
881
|
+
// The servers connect while the first turn is typed; the first request waits for them, and Esc does not. Their tools
|
|
882
|
+
// join the request then — even when something else, /mcp, already waited for them to connect.
|
|
883
|
+
if (!joined) {
|
|
788
884
|
const stopped = new Promise((resolve) => stopper.signal.addEventListener('abort', () => resolve('stopped'), { once: true }));
|
|
789
885
|
if ((await Promise.race([connecting, stopped])) === 'stopped') return { stop: 'interrupted', error: null, text: '' };
|
|
790
886
|
params.tools = toolsNow();
|
|
791
887
|
params.system[0].text = systemNow();
|
|
888
|
+
joined = true;
|
|
792
889
|
if (registry.servers().length > 0 || registry.error) watch({ type: 'mcp', servers: registry.servers(), error: registry.error });
|
|
793
890
|
}
|
|
794
891
|
// 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.
|
|
@@ -834,8 +931,9 @@ export function createChat(db, { model, effort, cwd = process.cwd(), send = send
|
|
|
834
931
|
for (;;) {
|
|
835
932
|
const outcome = await converse(db, params, {
|
|
836
933
|
send: sendAs,
|
|
837
|
-
// A command the sandbox kept from writing is put to the user as an MCP call off the allow list is, for one run outside it
|
|
838
|
-
|
|
934
|
+
// A command the sandbox kept from writing is put to the user as an MCP call off the allow list is, for one run outside it;
|
|
935
|
+
// so is a change to a file outside the project, once or for the session.
|
|
936
|
+
ctx: { ...workspace(), seen, opened, undo: undoFolder, approve },
|
|
839
937
|
ledger,
|
|
840
938
|
beforeTool,
|
|
841
939
|
concurrent: (call) => call.name === DELEGATE_TOOL.name,
|
|
@@ -852,8 +950,13 @@ export function createChat(db, { model, effort, cwd = process.cwd(), send = send
|
|
|
852
950
|
activity(describeCall(call));
|
|
853
951
|
watch({ type: 'tool', call });
|
|
854
952
|
noteCall(call);
|
|
953
|
+
// A page or an MCP server read here: what this conversation says from now on may be what it was told.
|
|
954
|
+
if (isWebTool(call) || isMcpTool(call.name)) noteSessionOutside(db, sessionId, call.name);
|
|
955
|
+
},
|
|
956
|
+
onResult: (call, result) => {
|
|
957
|
+
noteResult(call, result);
|
|
958
|
+
watch({ type: 'result', call, result });
|
|
855
959
|
},
|
|
856
|
-
onResult: (call, result) => watch({ type: 'result', call, result }),
|
|
857
960
|
onTurn: (response, totals) => {
|
|
858
961
|
lastContext = totals.contextTokens;
|
|
859
962
|
logLine(transcript, { type: 'assistant', message: { role: 'assistant', model: response.model ?? params.model, usage: response.usage, content: response.content } });
|
|
@@ -906,6 +1009,38 @@ export function createChat(db, { model, effort, cwd = process.cwd(), send = send
|
|
|
906
1009
|
return `undid the last turn that changed files: ${what} — changes made through bash are not tracked, so they stay`;
|
|
907
1010
|
}
|
|
908
1011
|
|
|
1012
|
+
/**
|
|
1013
|
+
* `/handoff`: the model writes a hand-off of this session — the task, what is done, what was tried, the files and
|
|
1014
|
+
* the next step, by the instructions a job's compaction summarizes under — and a fresh session starts with it as its
|
|
1015
|
+
* first note, so a piece in hand survives the start. The request is this session's last; the session is then kept,
|
|
1016
|
+
* as /new keeps it, and the new one begins. A hand-off that cannot be had leaves this session as it is.
|
|
1017
|
+
*/
|
|
1018
|
+
async function handoff() {
|
|
1019
|
+
if (!spoken) throw new UsageError('nothing to hand off: nothing has been said in this session — /new starts fresh');
|
|
1020
|
+
stopper = new AbortController();
|
|
1021
|
+
settleTail();
|
|
1022
|
+
const row = (model, result, said) => logRun(db, { kind: 'chat', model, result, note: said, now: now(), sessionId });
|
|
1023
|
+
let summary;
|
|
1024
|
+
try {
|
|
1025
|
+
summary = await sendAs(compactionParams(params, COMPACT_INSTRUCTIONS), { signal: stopper.signal, retries: QUIET_RETRIES });
|
|
1026
|
+
} catch (cause) {
|
|
1027
|
+
const why = describeFailure(cause).slice(0, 200);
|
|
1028
|
+
row(params.model, { ok: false, usage: usageOf(params.model, null) }, `hand-off: ${why}`);
|
|
1029
|
+
if (stopper.signal.aborted) throw new UsageError('the hand-off was stopped: this session goes on');
|
|
1030
|
+
throw new UsageError(`no hand-off could be written: ${why} — /new starts fresh; the memory brings the thread back`);
|
|
1031
|
+
}
|
|
1032
|
+
const block = summary.content.find((b) => b.type === 'compaction' && b.content);
|
|
1033
|
+
const by = summary.model ?? params.model;
|
|
1034
|
+
row(by, { ok: Boolean(block), usage: usageOf(by, summary.usage) }, block ? 'hand-off' : 'hand-off: no summary came back');
|
|
1035
|
+
if (!block) throw new UsageError('no hand-off came back from the model — /new starts fresh; the memory brings the thread back');
|
|
1036
|
+
const text = redact(String(block.content)).text.trim();
|
|
1037
|
+
const from = shortId(sessionId);
|
|
1038
|
+
end();
|
|
1039
|
+
const opening = start('handoff');
|
|
1040
|
+
note = `hand-off: the session before this one (${from}) ended with this hand-off, written by the model that worked it. Carry on from where it leaves off: what it says is done is done.\n\n${text}`;
|
|
1041
|
+
return { block: opening, text, from };
|
|
1042
|
+
}
|
|
1043
|
+
|
|
909
1044
|
/** `! <command>`: the user runs it themselves, where the model would be refused; the model sees what it printed. */
|
|
910
1045
|
async function shell(command) {
|
|
911
1046
|
stopper = new AbortController();
|
|
@@ -927,10 +1062,14 @@ export function createChat(db, { model, effort, cwd = process.cwd(), send = send
|
|
|
927
1062
|
if (!m) return { text: line };
|
|
928
1063
|
const [, name, args = ''] = m;
|
|
929
1064
|
if (name === 'exit' || name === 'quit') return { control: 'quit' };
|
|
930
|
-
if (name === 'new' || name === '
|
|
931
|
-
if (name === '
|
|
1065
|
+
if (name === 'new' || name === 'clear') return { control: 'new' };
|
|
1066
|
+
if (name === 'memory' || name === 'undo' || name === 'context' || name === 'handoff') return { control: name };
|
|
1067
|
+
if (name === 'model' || name === 'resume' || name === 'mcp' || name === 'copy' || name === 'help' || name === 'stop' || name === 'export' || name === 'thinking') return { control: name, args: args.trim() };
|
|
932
1068
|
const make = Object.hasOwn(COMMANDS, name) ? COMMANDS[name] : undefined;
|
|
933
|
-
|
|
1069
|
+
if (make) return { ...make(args.trim()), said: args.trim() };
|
|
1070
|
+
// A command mistyped is answered with the one it is closest to, two keys off at most; one close to none, with them all.
|
|
1071
|
+
const close = closest(name, commands.map((c) => c.name));
|
|
1072
|
+
return { error: close ? `no command /${name} — did you mean /${close}?` : `no command /${name} — one of: ${commands.map((c) => `/${c.name}`).join(' ')}` };
|
|
934
1073
|
}
|
|
935
1074
|
|
|
936
1075
|
/** `/mcp`: the servers as `sumo mcp` lists them. They connect once, while the first turn is typed, so an early look waits for them. */
|
|
@@ -956,6 +1095,18 @@ export function createChat(db, { model, effort, cwd = process.cwd(), send = send
|
|
|
956
1095
|
return { cwd: at, name: project?.slug ?? basename(at), branch: branchOf(at) };
|
|
957
1096
|
}
|
|
958
1097
|
|
|
1098
|
+
/** What this session's requests have used so far, the jobs it delegated included: by the kind of conversation and the model, dearest first. */
|
|
1099
|
+
const usage = () =>
|
|
1100
|
+
sessionId
|
|
1101
|
+
? db
|
|
1102
|
+
.prepare(
|
|
1103
|
+
`SELECT kind, model, COUNT(*) AS requests, COALESCE(SUM(input_tokens), 0) AS input, COALESCE(SUM(output_tokens), 0) AS output,
|
|
1104
|
+
COALESCE(SUM(cache_read_tokens), 0) AS cached, COALESCE(SUM(cost_usd), 0) AS cost
|
|
1105
|
+
FROM model_runs WHERE session_id = ? GROUP BY kind, model ORDER BY cost DESC`,
|
|
1106
|
+
)
|
|
1107
|
+
.all(sessionId)
|
|
1108
|
+
: [];
|
|
1109
|
+
|
|
959
1110
|
/** What this session's requests have cost so far, the jobs it delegated included: the ledger's own sum. */
|
|
960
1111
|
const spent = () => (sessionId ? db.prepare('SELECT COALESCE(SUM(cost_usd), 0) AS cost FROM model_runs WHERE session_id = ?').get(sessionId).cost : 0);
|
|
961
1112
|
|
|
@@ -974,6 +1125,8 @@ export function createChat(db, { model, effort, cwd = process.cwd(), send = send
|
|
|
974
1125
|
}
|
|
975
1126
|
|
|
976
1127
|
function end() {
|
|
1128
|
+
// Kept as it stands, reports not yet read with it, before the session is let go.
|
|
1129
|
+
if (sessionId) keepQuietly();
|
|
977
1130
|
event('session-end', {});
|
|
978
1131
|
if (lock) rmSync(lock, { force: true });
|
|
979
1132
|
lock = null;
|
|
@@ -982,6 +1135,7 @@ export function createChat(db, { model, effort, cwd = process.cwd(), send = send
|
|
|
982
1135
|
return {
|
|
983
1136
|
start,
|
|
984
1137
|
say,
|
|
1138
|
+
handoff,
|
|
985
1139
|
interrupt: () => stopper?.abort(),
|
|
986
1140
|
/** Said to the chat while it works: read with the model's next request of this turn. */
|
|
987
1141
|
steer: (text) => void steers.push(text),
|
|
@@ -995,6 +1149,7 @@ export function createChat(db, { model, effort, cwd = process.cwd(), send = send
|
|
|
995
1149
|
waiting,
|
|
996
1150
|
where,
|
|
997
1151
|
spent,
|
|
1152
|
+
usage,
|
|
998
1153
|
tell,
|
|
999
1154
|
shell,
|
|
1000
1155
|
undo,
|
|
@@ -1010,6 +1165,10 @@ export function createChat(db, { model, effort, cwd = process.cwd(), send = send
|
|
|
1010
1165
|
get sessionId() {
|
|
1011
1166
|
return sessionId;
|
|
1012
1167
|
},
|
|
1168
|
+
/** Whether anything has been said in this session: one nobody spoke to is not kept, and there is nothing to pick up again. */
|
|
1169
|
+
get spoken() {
|
|
1170
|
+
return spoken;
|
|
1171
|
+
},
|
|
1013
1172
|
get model() {
|
|
1014
1173
|
return model;
|
|
1015
1174
|
},
|
|
@@ -1045,7 +1204,13 @@ async function screen(db, { model, effort, resume }) {
|
|
|
1045
1204
|
ask: (question) => new Promise((resolve) => events.emit('ask', { ...question, resolve })),
|
|
1046
1205
|
});
|
|
1047
1206
|
try {
|
|
1048
|
-
await runUi({ session, events, resume, notify: configured(db, 'chat.notify') !== 'off' }).waitUntilExit();
|
|
1207
|
+
await runUi({ session, events, resume, notify: configured(db, 'chat.notify') !== 'off', motion: configured(db, 'chat.screen') === 'full', plain: configured(db, 'chat.screen') === 'plain' }).waitUntilExit();
|
|
1208
|
+
// The way back in, said as the screen closes: the command that picks this session up again, and what it cost.
|
|
1209
|
+
if (session.spoken) {
|
|
1210
|
+
const s = styles(colourEnabled());
|
|
1211
|
+
const cost = session.spent();
|
|
1212
|
+
process.stdout.write(farewell({ id: shortId(session.sessionId), cost, columns: process.stdout.columns || 80 }, s));
|
|
1213
|
+
}
|
|
1049
1214
|
} finally {
|
|
1050
1215
|
// Jobs still at work in the background are stopped with the chat, and let go of what they hold before it closes.
|
|
1051
1216
|
await session.settle();
|
|
@@ -1055,12 +1220,21 @@ async function screen(db, { model, effort, resume }) {
|
|
|
1055
1220
|
return 0;
|
|
1056
1221
|
}
|
|
1057
1222
|
|
|
1223
|
+
/**
|
|
1224
|
+
* The way back in, said as the screen closes: the command that picks the session up again, and what it cost — two short
|
|
1225
|
+
* lines, each with its margin, folded to the window under it: a narrow one never has them back at the edge.
|
|
1226
|
+
*/
|
|
1227
|
+
export function farewell({ id, cost, columns }, s) {
|
|
1228
|
+
const said = wrap(`picks this session up again${cost >= 0.005 ? ` · it cost $${cost.toFixed(2)}` : ''}`, Math.max(20, columns - 3));
|
|
1229
|
+
return `\n${s.dim(` sumo chat --resume ${id}`)}\n${said.split('\n').map((row) => s.dim(` ${row}`)).join('\n')}\n\n`;
|
|
1230
|
+
}
|
|
1231
|
+
|
|
1058
1232
|
/**
|
|
1059
1233
|
* The terminal. With a keyboard and a screen it is the full-screen chat; piped,
|
|
1060
1234
|
* it is plain lines: a header, the prompt with the model in it, the reply
|
|
1061
1235
|
* rendered as it streams, tool lines dim, errors red, a rule between turns.
|
|
1062
1236
|
*/
|
|
1063
|
-
export async function chat(db, { model, effort, resume = null, send, input = process.stdin, output = process.stdout } = {}) {
|
|
1237
|
+
export async function chat(db, { model, effort, resume = null, send, input = process.stdin, output = process.stdout, errors = process.stderr } = {}) {
|
|
1064
1238
|
if (input.isTTY && output.isTTY) return screen(db, { model, effort, resume });
|
|
1065
1239
|
const rl = createInterface({ input, output });
|
|
1066
1240
|
// Every line is a turn. Lines that arrive while one is being answered wait here for theirs; a question would hear only the next.
|
|
@@ -1070,6 +1244,15 @@ export async function chat(db, { model, effort, resume = null, send, input = pro
|
|
|
1070
1244
|
// Piped in is not piped out: what the model or a command prints may reach a terminal, and only colour gets through to it.
|
|
1071
1245
|
// A carriage return redraws a progress bar in place; as plain lines each redraw is a line of its own, not run into the next.
|
|
1072
1246
|
const write = (t) => output.write(safeForTerminal(String(t).replace(/\r(?!\n)/g, '\n')));
|
|
1247
|
+
/** Whether a turn failed: the chat then exits 1, so a script that piped into it can tell. */
|
|
1248
|
+
let failed = false;
|
|
1249
|
+
/** A turn that failed, said where failures go — stderr — in the screen's own words, with what to do and what came back under it. */
|
|
1250
|
+
const failure = (message) => {
|
|
1251
|
+
const { text, detail } = explained(message);
|
|
1252
|
+
const e = styles(colourEnabled(errors));
|
|
1253
|
+
errors.write(`${e.red(safeForTerminal(text))}\n${detail ? `${e.dim(` ${safeForTerminal(detail)}`)}\n` : ''}`);
|
|
1254
|
+
failed = true;
|
|
1255
|
+
};
|
|
1073
1256
|
const reply = createRenderer(write, s, { width });
|
|
1074
1257
|
const session = createChat(db, {
|
|
1075
1258
|
model,
|
|
@@ -1083,7 +1266,7 @@ export async function chat(db, { model, effort, resume = null, send, input = pro
|
|
|
1083
1266
|
// Piped, nobody answers a question: one of the model's is not asked, an MCP call not on the allow list is refused, and a server that failed is said.
|
|
1084
1267
|
watch: (e) => {
|
|
1085
1268
|
if (e.type === 'retry' && e.job === undefined) return write(`${s.dim(` › ${retryLine(e)}`)}\n`);
|
|
1086
|
-
if (e.type === 'sources') return write(`\n${e.sources.map((page) => s.dim(`
|
|
1269
|
+
if (e.type === 'sources') return write(`\n${e.sources.map((page) => s.dim(` ${safeForTerminal(`${page.title} — ${page.url}`).replace(/\s+/g, ' ')}`)).join('\n')}\n`);
|
|
1087
1270
|
if (e.type !== 'mcp') return;
|
|
1088
1271
|
if (e.error) write(`${s.red(`mcp: ${e.error}`)}\n`);
|
|
1089
1272
|
for (const server of e.servers.filter((x) => !x.ok)) write(`${s.red(`mcp ${server.name}: ${server.error}`)}\n`);
|
|
@@ -1091,7 +1274,7 @@ export async function chat(db, { model, effort, resume = null, send, input = pro
|
|
|
1091
1274
|
});
|
|
1092
1275
|
const rule = () => write(`\n${s.dim('─'.repeat(width))}\n\n`);
|
|
1093
1276
|
/** A line under what the user typed, as a tool's result is drawn: what a command did. */
|
|
1094
|
-
const result = (text) => write(`${s.dim(`
|
|
1277
|
+
const result = (text) => write(`${s.dim(` ${text}`)}\n`);
|
|
1095
1278
|
/** The header, then the memory block of a fresh session or the line that says what a resumed one is. */
|
|
1096
1279
|
const show = (block, after = '') => {
|
|
1097
1280
|
write(`${header({ route: routeLine(session), cwd: process.cwd() }, s)}\n\n`);
|
|
@@ -1127,6 +1310,12 @@ export async function chat(db, { model, effort, resume = null, send, input = pro
|
|
|
1127
1310
|
show(session.start('new'));
|
|
1128
1311
|
continue;
|
|
1129
1312
|
}
|
|
1313
|
+
if (control === 'handoff') {
|
|
1314
|
+
const handed = await session.handoff();
|
|
1315
|
+
write(`${s.dim(handed.text)}\n\n`);
|
|
1316
|
+
show(handed.block, `handed off from ${handed.from}: the hand-off rides in with your next message`);
|
|
1317
|
+
continue;
|
|
1318
|
+
}
|
|
1130
1319
|
if (control === 'resume') {
|
|
1131
1320
|
if (!args) {
|
|
1132
1321
|
const saved = session.saved();
|
|
@@ -1139,14 +1328,25 @@ export async function chat(db, { model, effort, resume = null, send, input = pro
|
|
|
1139
1328
|
continue;
|
|
1140
1329
|
}
|
|
1141
1330
|
if (control === 'model' || control === 'memory' || control === 'mcp' || control === 'undo') {
|
|
1142
|
-
result(control === 'model' ? session.route(args) : control === 'undo' ? session.undo() : control === 'mcp' ? (await session.mcp()).join('\n
|
|
1331
|
+
result(control === 'model' ? session.route(args) : control === 'undo' ? session.undo() : control === 'mcp' ? (await session.mcp()).join('\n ') : await session.memoryPage());
|
|
1332
|
+
continue;
|
|
1333
|
+
}
|
|
1334
|
+
if (control === 'context') {
|
|
1335
|
+
reply.write(contextReport({ contextTokens: session.contextTokens, rows: session.usage() }));
|
|
1336
|
+
reply.flush();
|
|
1337
|
+
write('\n');
|
|
1338
|
+
continue;
|
|
1339
|
+
}
|
|
1340
|
+
// The rest belong to the screen — a clipboard, a pager, jobs under the box — and are never sent to the model as words.
|
|
1341
|
+
if (control) {
|
|
1342
|
+
result(`/${control} is for the chat on a terminal screen`);
|
|
1143
1343
|
continue;
|
|
1144
1344
|
}
|
|
1145
1345
|
write('\n');
|
|
1146
1346
|
const outcome = await session.say(text, said, [], { guide });
|
|
1147
1347
|
reply.flush();
|
|
1148
|
-
if (outcome.stop === 'error')
|
|
1149
|
-
if (stopReason(outcome.stop)) write(`\n${s.dim(stopReason(outcome.stop))}\n`);
|
|
1348
|
+
if (outcome.stop === 'error') failure(outcome.error);
|
|
1349
|
+
if (stopReason(outcome.stop)) write(`\n${s.dim(stopReason(outcome.stop, outcome.stopDetail))}\n`);
|
|
1150
1350
|
rule();
|
|
1151
1351
|
} catch (cause) {
|
|
1152
1352
|
reply.flush();
|
|
@@ -1158,5 +1358,5 @@ export async function chat(db, { model, effort, resume = null, send, input = pro
|
|
|
1158
1358
|
rl.close();
|
|
1159
1359
|
await closeMcp();
|
|
1160
1360
|
}
|
|
1161
|
-
return 0;
|
|
1361
|
+
return failed ? 1 : 0;
|
|
1162
1362
|
}
|