Skip to content

Your team of AI agents, on your Mac, Windows or Linux. Agents that talk in channels, write code, review each other and use your tools, on the Claude Code, Codex, OpenCode or Pi you already have. Anything that touches the real world waits for your yes.

Keep a Claude Code session per agent and conversation, with its process open between replies (#147)

Diasddf93549e4b7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 41cf287..cbe1480 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,7 @@ What changed in each version of Tucano. The format follows [Keep a Changelog](ht
> - **Conversas longas não pesam mais enquanto um agente responde.** Cada palavra recebida redesenhava todas as mensagens; agora só a que mudou.
> - **O navegador dos agentes abre páginas num servidor Linux que é um PC.** O Chrome esperava o chaveiro bloqueado da área de trabalho e nenhuma página carregava; no servidor ele agora usa o próprio armazenamento.
> - **A página do servidor abre por HTTP num endereço privado,** como o Tailscale ou a rede de casa. Ela ficava em branco.
+> - **Os agentes do Claude respondem mais rápido e gastam menos do plano em conversas longas.** Cada agente continua a mesma sessão do Claude Code na conversa e manda só o que é novo; entre uma resposta e outra o processo fica aberto por 5 minutos. O primeiro trecho da resposta chega quase 1 segundo antes, e uma conversa longa não é mandada inteira de novo a cada resposta.
> - **Um agente só acorda outro quando precisa.** Quando um agente menciona outro na resposta, o router lê e chama só quem tem algo a fazer: um agradecimento ou um “combinado” não acordam ninguém. Na dúvida, chama.
> - **O app abre fora do instalador mesmo com uma versão estranha.** O atualizador, que nem é usado ali, conferia a versão ao abrir e derrubava o app.
> - **Agentes no Grok.** Um agente pode rodar no Grok CLI, com a assinatura do grok.com, como roda no Cursor CLI. Cada resposta usa uma pasta própria: os seus plugins, skills e hooks não carregam, e só as ferramentas do Tucano ficam à mão.
@@ -20,6 +21,7 @@ What changed in each version of Tucano. The format follows [Keep a Changelog](ht
### Changed
+- **Claude agents reply faster, and long conversations spend less of the plan.** An agent now keeps its Claude Code session for each conversation and thread: its first reply sends the conversation, and the next ones only what's new since (other people's and agents' messages, and the task). The process stays open for five minutes after a reply (two at most at a time), so the next reply skips starting Claude Code. Measured with Haiku in a DM of about 16k tokens, the first words of a reply come about 0.9 s sooner (1.45 s instead of 2.33 s). Past the conversation's window, where each reply used to write the whole history to the prompt cache again (about 16,600 tokens), it now writes about 200. The session starts over when the agent's instructions, memories or tools change, a message it saw is edited, its last reply was stopped or failed, or after an hour idle. Thanks [@rjgdias](https://github.com/rjgdias)! ([#147](https://github.com/eduwxyz/tucano/pull/147))
- **A reply's steps say what each call did, as it runs.** A connector call shows what it asked (the SQL, a path, a search) from the moment it starts, and what came back once it ends, in a few words: the rows of a table or a SQL answer, the items of a list, the lines of a long text. A command shows whole, or as **Ran SQL** with the SQL taken out of it, and ends with what it printed or its exit code and the last lines of stderr; reading a skill says which skill and file. Tokens, passwords, keys and auth headers are masked on the screen and in the log (the agent still gets the real output). The steps list stays open while the agent works, unless closed, and folds when the reply is done. Thanks [@rjgdias](https://github.com/rjgdias)! ([#135](https://github.com/eduwxyz/tucano/pull/135))
- **An agent wakes another only when it needs to.** When an agent's reply mentions other agents, the router reads it first and hands the turn only to those asked to do something: a request, a question, a task, a decision. A thank-you, an "okay" or a credit wakes no one, and the decision shows as a step on the reply. In doubt, or if the router fails, everyone mentioned is called, as before; a mention in your own message still goes straight to the agent. Thanks [@eialanjones](https://github.com/eialanjones)! ([#139](https://github.com/eduwxyz/tucano/pull/139))
diff --git a/docs/spec-mvp.md b/docs/spec-mvp.md
index 74ba2c8..0dd668c 100644
--- a/docs/spec-mvp.md
+++ b/docs/spec-mvp.md
@@ -62,7 +62,7 @@ Usuário do MVP: eu, numa máquina só. Quem baixar o repositório usa do mesmo
- O estado do run, os steps e a chamada de ferramenta pendente ficam no SQLite. Um run esperando aprovação ou resposta sobrevive a fechar o app.
- **Sem processo pendurado:** quando o run precisa esperar (aprovação ou `ask_user`), o turno da CLI termina. Depois da decisão, o app abre um turno novo com o resultado no contexto. Assim nada depende de um processo vivo por horas.
- Ao reabrir o app, runs que estavam em `running` viram `interrupted`, com um botão **Retomar** (abre um turno novo a partir do último step completo).
-- **Contexto de cada turno** (o app monta, a CLI não guarda sessão entre turnos):
+- **Contexto de cada turno** (o app monta; no Claude Code, a sessão é guardada por agente, conversa e thread, e as respostas seguintes mandam só o que é novo; veja *Sessão guardada* abaixo):
1. Contexto do workspace
2. Instruções do agente
3. Últimas N mensagens da conversa (default 30), com o autor de cada uma
@@ -86,7 +86,8 @@ Expostas pelo gateway, como qualquer outra. Todas as demais vêm de conectores M
### 5. Motores
-- **Claude Code:** `claude -p --output-format stream-json --verbose --include-partial-messages`, com `--model`, `--system-prompt`, `--tools ""` (nenhuma ferramenta embutida: sem shell, sem arquivos), `--strict-mcp-config --mcp-config <gateway>`, `--setting-sources ""` (ignora hooks, plugins e configurações do usuário) e `--no-session-persistence`. Não usar `--bare`, que desliga o login por assinatura.
+- **Claude Code:** `claude -p --output-format stream-json --verbose --include-partial-messages`, com `--model`, `--system-prompt`, `--tools ""` (nenhuma ferramenta embutida: sem shell, sem arquivos), `--strict-mcp-config --mcp-config <gateway>`, `--setting-sources ""` (ignora hooks, plugins e configurações do usuário) e `--no-session-persistence` (fora as respostas de agente, que guardam sessão). Não usar `--bare`, que desliga o login por assinatura.
+- **Sessão guardada (Claude Code):** a primeira resposta de um agente numa conversa ou thread começa uma sessão (`--session-id`) com a conversa inteira; as próximas a retomam (`--resume`) mandando só as mensagens novas desde a última resposta dele e a tarefa. O processo fica aberto 5 min depois de uma resposta (no máximo 2 esperando, ~140 MB cada), e a próxima é escrita nele; depois disso, a próxima abre outro processo e retoma do disco. O token do gateway fica o mesmo enquanto a sessão vive (entre respostas, as chamadas são recusadas). Começa outra sessão quando: o system prompt ou as ferramentas mudam (o `--resume` mantém o primeiro system prompt), uma mensagem que ela viu foi editada ou apagada, aparece uma mensagem no meio, a última resposta não terminou bem (parada, travada, limite, reserva), em "Tentar de novo", passou de ~60k tokens de contexto ou de 55 min parada (o cache dura 1 h), ou o app reabriu. Enquanto outro agente ainda escreve uma mensagem que ela veria pela metade, a resposta vai sem sessão. Os arquivos das sessões largadas são apagados.
- **Codex:** `codex exec --json --ephemeral --ignore-user-config --ignore-rules --skip-git-repo-check -s read-only -C <diretório vazio do run>`, com `-m`, `-c model_reasoning_effort=…`, skills e docs de projeto desligados, busca na web só com a Web ligada (§16), `--disable` em cada recurso embutido (shell, exec, plugins, apps, navegador, computer use, multiagente, imagens, memórias, hooks) e o gateway como único servidor MCP via `-c mcp_servers…` com `default_tools_approval_mode="approve"` (quem decide é o gateway).
- **O Codex roda com um home próprio do app** (`HOME` e `CODEX_HOME` numa pasta do Tucano). Medido com `codex debug prompt-input`: com o home do usuário, mesmo com `--ignore-user-config`, ele carrega o `~/.codex/AGENTS.md` e as skills do usuário, e num teste real usou o shell pra rodar uma ferramenta pessoal. Por isso o usuário faz um login próprio do Codex pro Tucano, pelo fluxo do próprio Codex, uma vez.
- O app **nunca** toca em credenciais: não lê, não guarda, não repassa token. O login acontece no fluxo da própria CLI (`claude auth login` / `codex login`), que o app abre num Terminal.
diff --git a/scripts/bench-kept-session.ts b/scripts/bench-kept-session.ts
new file mode 100644
index 0000000..bb16f81
--- /dev/null
+++ b/scripts/bench-kept-session.ts
@@ -0,0 +1,85 @@
+// How fast, and how much from the prompt cache, the next replies in a DM come, through the real
+// runner and the real Claude Code (Haiku, low effort, the person's own login), three ways:
+// today a new `claude -p` per reply, with the whole conversation again
+// resumed the session kept, resumed from disk in a new process per reply
+// kept open the session kept, and its process open between replies
+// The DM starts with `history` messages (20: about 16k tokens). With more than 30 the window slides
+// at every reply (the oldest message leaves), as it does after a summary is rewritten or with a task
+// block at the end: today's way then writes the whole history to the cache again. Spends a little
+// of the plan.
+// npx -y tsx scripts/bench-kept-session.ts [replies per way, default 4] [history, default 20]
+import { mkdirSync, mkdtempSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { randomUUID } from 'node:crypto'
+import { Db } from '../src/core/db'
+import { claudeEngine } from '../src/core/engines/claude'
+import { detectClaude } from '../src/core/engines/detect'
+import { fakeEngine } from '../src/core/engines/fake'
+import type { Engine } from '../src/core/engines/types'
+import { Gateway } from '../src/core/gateway'
+import { Runner } from '../src/core/runs'
+import type { CoreEvent } from '../src/shared/rpc'
+import type { Agent, EngineId, Settings } from '../src/shared/types'
+
+const replies = Number(process.argv[2] ?? 4)
+const seeded = Number(process.argv[3] ?? 20)
+const bin = process.env['CLAUDE_BIN'] || (await detectClaude()).path
+if (!bin) throw new Error('Claude Code not found')
+const ready = { installed: true, loggedIn: true }
+const settings = { workspaceName: 'Gabriel', context: '', engines: { claude: ready, codex: ready, opencode: ready, pi: ready, gemini: ready, cursor: ready }, routerModel: 'haiku', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1000, approvalTtlHours: 24, theme: 'system', language: 'pt' } as Settings
+const lia: Agent = { id: 'lia', name: 'Lia', handle: 'lia', role: 'Dados', color: 'sky', instructions: 'Você é a Lia, de engenharia de dados. Responda em uma frase curta.', modelId: 'haiku', effort: 'low', limit: 100_000_000, used: 0, grants: {}, memory: 'auto', computer: false, archived: false }
+const line = (i: number): string => `Mensagem ${i}: a tabela vendas_diarias teve ${1000 + i} linhas hoje, e o job de ingestão rodou em ${30 + i} segundos sem erro. ${'Detalhe do log do job, linha repetida para ocupar espaço. '.repeat(25)}`
+
+type Row = { way: string; reply: number; firstMs: number; totalMs: number; input: number; cacheRead: number }
+
+async function measure(way: string, sessions: boolean, after?: (engine: Engine) => void): Promise<Row[]> {
+ const db = new Db(join(mkdtempSync(join(tmpdir(), 'bench-db-')), 'bench.db'))
+ db.saveAgent(lia)
+ db.createConversation({ id: 'dm', kind: 'dm', name: 'lia', members: ['lia'] })
+ const t0 = Date.now() - seeded * 60_000 - 60_000
+ for (let i = 0; i < seeded; i++) db.saveMessage({ id: randomUUID(), conversationId: 'dm', author: i % 2 ? { kind: 'agent', id: 'lia' } : { kind: 'me' }, text: line(i), at: t0 + i * 60_000 })
+
+ const real = claudeEngine(() => bin)
+ const claude: Engine = sessions ? real : { id: 'claude', run: (t) => real.run(t) }
+ const engines: Record<EngineId, Engine> = { claude, codex: fakeEngine('codex'), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor') }
+ const gateway = new Gateway()
+ await gateway.start()
+ const workDir = join(tmpdir(), 'bench-work')
+ mkdirSync(workDir, { recursive: true })
+ let firstAt = 0
+ const runner = new Runner({ db, engines, settings: async () => settings, emit: (e: CoreEvent) => void (e.type === 'delta' && !firstAt && (firstAt = Date.now())), workDir, gateway })
+
+ const rows: Row[] = []
+ for (let n = 0; n <= replies; n++) {
+ firstAt = 0
+ const sent = Date.now()
+ await runner.send('dm', n === 0 ? 'Oi Lia, me resume o que rolou com o job hoje.' : `E agora, mensagem nova ${n}: o job das ${10 + n}h também passou?`)
+ await runner.idle()
+ const reply = db.messages().filter((m) => m.author.kind === 'agent').at(-1)!
+ const r = reply.run?.receipt
+ if (reply.run?.status !== 'done' || !r) throw new Error(`${way}: reply ${n} ${reply.run?.status}: ${reply.run?.error ?? ''}`)
+ rows.push({ way, reply: n, firstMs: firstAt - sent, totalMs: r.ms, input: r.inputTokens, cacheRead: r.cacheReadTokens })
+ after?.(real)
+ await new Promise((res) => setTimeout(res, 2000)) // like a person reading; and a process closed has time to go
+ }
+ real.dispose?.()
+ await gateway.stop()
+ return rows
+}
+
+const all = [
+ ...(await measure('today', false)),
+ ...(await measure('resumed', true, (e) => e.dispose?.())), // the process closes after each reply, as after 5 min idle
+ ...(await measure('kept open', true))
+]
+const median = (xs: number[]): number => [...xs].sort((a, b) => a - b)[Math.floor(xs.length / 2)]!
+console.log('| way | reply | first token | total | input | from cache | not from cache |')
+console.log('|---|---|---|---|---|---|---|')
+for (const r of all) console.log(`| ${r.way} | ${r.reply === 0 ? 'first' : r.reply} | ${(r.firstMs / 1000).toFixed(2)} s | ${(r.totalMs / 1000).toFixed(2)} s | ${r.input} | ${r.cacheRead} | ${r.input - r.cacheRead} |`)
+console.log('\nMedians of the next replies (not the first):')
+for (const way of ['today', 'resumed', 'kept open']) {
+ const next = all.filter((r) => r.way === way && r.reply > 0)
+ console.log(`- ${way}: first token ${(median(next.map((r) => r.firstMs)) / 1000).toFixed(2)} s, total ${(median(next.map((r) => r.totalMs)) / 1000).toFixed(2)} s, from cache ${median(next.map((r) => r.cacheRead))}, not from cache ${median(next.map((r) => r.input - r.cacheRead))}`)
+}
+process.exit(0)
diff --git a/src/core/context.ts b/src/core/context.ts
index 735cb6d..e1ae520 100644
--- a/src/core/context.ts
+++ b/src/core/context.ts
@@ -1,6 +1,7 @@
// Builds what a turn sends to the engine: a system prompt (stable per agent)
-// and a prompt with the conversation transcript. The CLI keeps no session
-// between turns, so everything the agent knows comes from here.
+// and a prompt with the conversation transcript. Everything the agent knows
+// comes from here; a kept session (sessions.ts) gets it once, then only the
+// blocks of what's new.
import { L, lang, locale } from '../shared/lang'
import { MENTION } from '../shared/mention-text'
import { CODE_SPANS, describeSchedule, PROJECTS_DIR, type Agent, type AgentApp, type Conversation, type Memory, type Message, type Routine, type Settings, type Skill } from '../shared/types'
@@ -272,9 +273,9 @@ export const clock = (at: number): string => {
}
// The conversation as blocks, one per message, oldest first. Nothing in them
-// changes between turns (no "now", no closing line), so the next turn starts
-// with the same blocks and reads them from the cache. `task` (to continue after
-// an approval, a routine…) goes last, with the time, since it may come later.
+// changes between turns (no "now", no closing line), so a kept session can tell
+// what it already saw by its block. `task` (to continue after an approval, a
+// routine…) goes last, with the time, since it may come later.
// `images`: the names of the images attached to each message (by id). `thread`: the message
// that started the thread this reply is in (`messages` is then that thread, root first, and
// `summary` the thread's own). `searchable`: the agent has buscar_threads and ler_thread.
diff --git a/src/core/engines/claude.ts b/src/core/engines/claude.ts
index 94b23aa..2a3d142 100644
--- a/src/core/engines/claude.ts
+++ b/src/core/engines/claude.ts
@@ -1,7 +1,7 @@
-import { readFileSync } from 'node:fs'
+import { readdirSync, readFileSync, rmdirSync, rmSync } from 'node:fs'
import { homedir } from 'node:os'
-import { join } from 'node:path'
-import { lastLines, num, parseJson, runCli, type Parser } from './cli'
+import { dirname, join } from 'node:path'
+import { lastLines, LiveCli, num, parseJson, runCli, type Parser } from './cli'
import type { Engine, EngineEvent, Turn } from './types'
import { L } from '../../shared/lang'
@@ -29,17 +29,18 @@ export function userProvider(dir = process.env['CLAUDE_CONFIG_DIR'] || join(home
}
// Flags that keep the CLI isolated: no built-in tools (shell, files), no
-// user settings, hooks, plugins or MCP servers, and no saved session. Not
+// user settings, hooks, plugins or MCP servers, and no saved session unless
+// the turn keeps one (then it starts it with its id, or resumes it). Not
// --bare: it turns off the subscription login. The app's gateway, when given,
// is the only MCP server, and its tools are pre-allowed: the gateway decides.
// With web, the only built-in tools are web search and page reading.
-export function claudeArgs(turn: Pick<Turn, 'model' | 'effort' | 'system' | 'mcpUrl' | 'web' | 'blocks' | 'images'>, apiKeyHelper?: string): string[] {
+export function claudeArgs(turn: Pick<Turn, 'model' | 'effort' | 'system' | 'mcpUrl' | 'web' | 'blocks' | 'images' | 'session'>, apiKeyHelper?: string): string[] {
const web = turn.web ? WEB_TOOLS : []
const allowed = [...(turn.mcpUrl ? [`mcp__${GATEWAY_NAME}`] : []), ...web]
const gateway = turn.mcpUrl ? ['--mcp-config', JSON.stringify({ mcpServers: { [GATEWAY_NAME]: { type: 'http', url: turn.mcpUrl } } })] : []
return [
'-p',
- ...(turn.blocks?.some((b) => b.trim()) || turn.images?.length ? ['--input-format', 'stream-json'] : []),
+ ...(turn.session || turn.blocks?.some((b) => b.trim()) || turn.images?.length ? ['--input-format', 'stream-json'] : []),
'--output-format', 'stream-json',
'--verbose',
'--include-partial-messages',
@@ -49,7 +50,7 @@ export function claudeArgs(turn: Pick<Turn, 'model' | 'effort' | 'system' | 'mcp
'--tools', web.join(','),
'--strict-mcp-config',
'--setting-sources', '',
- '--no-session-persistence',
+ ...(turn.session ? [turn.session.resume ? '--resume' : '--session-id', turn.session.id] : ['--no-session-persistence']),
// --settings still applies with no setting sources; only the key helper goes in it
...(apiKeyHelper ? ['--settings', JSON.stringify({ apiKeyHelper })] : []),
...gateway,
@@ -57,13 +58,15 @@ export function claudeArgs(turn: Pick<Turn, 'model' | 'effort' | 'system' | 'mcp
]
}
-// With blocks, one user message with a text block per piece: the CLI marks the
-// last block for caching, and the next turn, which starts with the same blocks,
-// reads them back from the cache instead of sending them again. An attached
-// image goes right after the block of the message it came with.
-export function claudeInput(turn: Pick<Turn, 'prompt' | 'blocks' | 'images'>): string {
+// With blocks, one user message with a text block per piece; an attached image
+// goes right after the block of the message it came with. A new turn with the
+// same blocks plus the new ones doesn't read them back from the cache (measured:
+// only the system prompt and tools are), so a kept session sends only the new
+// ones, and its turns before come from the cache. It always gets a JSON message:
+// its process reads one per turn.
+export function claudeInput(turn: Pick<Turn, 'prompt' | 'blocks' | 'images' | 'session'>): string {
const images = turn.images ?? []
- const blocks = turn.blocks?.length ? turn.blocks : images.length ? [turn.prompt] : []
+ const blocks = turn.blocks?.length ? turn.blocks : images.length || turn.session ? [turn.prompt] : []
const content: Record<string, unknown>[] = []
blocks.forEach((text, i) => {
if (text.trim()) content.push({ type: 'text', text })
@@ -148,6 +151,7 @@ export function claudeParser(): Parser {
out.push({
type: 'done',
text,
+ context: callInput + callOutput,
usage: {
inputTokens: num(u['input_tokens']) + cacheRead + num(u['cache_creation_input_tokens']),
cacheReadTokens: cacheRead,
@@ -168,15 +172,51 @@ export function claudeParser(): Parser {
}
// Without CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC the CLI makes one more model call after the
-// reply (its post-turn summary) and only then sends `result` and exits: about 2.5 s on every
-// reply, at times over 10 s. Nobody reads that summary here, and the CLI runs one reply and goes.
+// reply (its post-turn summary) and only then sends `result`: about 2.5 s on every reply, at
+// times over 10 s. Nobody reads that summary here.
export function claudeEnv(p: Provider, account?: string): NodeJS.ProcessEnv {
return { ...process.env, CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: '1', ...p.env, ...(account ? { CLAUDE_CONFIG_DIR: account } : {}), MCP_TOOL_TIMEOUT: '900000' }
}
+// Where Claude Code keeps a session: its config folder, then the working folder with every
+// character other than a letter or digit turned into "-".
+export const claudeProjectDir = (configDir: string, cwd: string): string => join(configDir, 'projects', cwd.replace(/[^a-zA-Z0-9]/g, '-'))
+const configDirOf = (account?: string): string => account || process.env['CLAUDE_CONFIG_DIR'] || join(homedir(), '.claude')
+
+// A process kept open after a reply waits this long for the next one, and only this many wait at
+// once (each holds about 140 MB): past either, it closes, and the next reply resumes the session
+// from disk in a new process instead.
+const SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
+export const KEEP_IDLE_MS = 5 * 60_000
+export const MAX_IDLE = 2
+
+interface Kept {
+ cli: LiveCli
+ key: string // what it was started with: another turn may write to it only with the same
+ timer?: NodeJS.Timeout
+ usedAt: number
+}
+
export function claudeEngine(bin: () => string | undefined, provider: () => Promise<Provider> = async () => userProvider()): Engine {
+ const kept = new Map<string, Kept>() // by session id
+ const files = new Map<string, string>() // session id → its file
+
+ const close = (id: string): void => {
+ const k = kept.get(id)
+ if (!k) return
+ kept.delete(id)
+ if (k.timer) clearTimeout(k.timer)
+ k.cli.kill()
+ }
+ // Waiting processes past the cap close, the longest waiting first.
+ const trim = (): void => {
+ const idle = [...kept].filter(([, k]) => !k.cli.busy).sort((a, b) => a[1].usedAt - b[1].usedAt)
+ for (const [id] of idle.slice(0, Math.max(0, idle.length - MAX_IDLE))) close(id)
+ }
+
return {
id: 'claude',
+ sessions: true,
async *run(turn) {
const path = bin()
if (!path) {
@@ -185,7 +225,96 @@ export function claudeEngine(bin: () => string | undefined, provider: () => Prom
}
// The gateway's token goes in the environment, never in the arguments (other processes can read those).
const p = await provider()
- yield* runCli({ bin: path, args: claudeArgs(turn, p.apiKeyHelper), stdin: claudeInput(turn), cwd: turn.cwd, signal: turn.signal, parser: claudeParser(), env: claudeEnv(p, turn.account) })
+ const env = claudeEnv(p, turn.account)
+ const session = turn.session
+ if (!session) {
+ yield* runCli({ bin: path, args: claudeArgs(turn, p.apiKeyHelper), stdin: claudeInput(turn), cwd: turn.cwd, signal: turn.signal, parser: claudeParser(), env })
+ return
+ }
+
+ files.set(session.id, join(claudeProjectDir(configDirOf(turn.account), turn.cwd), `${session.id}.jsonl`))
+ // The same flags and provider as the open process: then it can take this turn.
+ const key = JSON.stringify([path, turn.cwd, claudeArgs({ ...turn, session: { id: session.id, resume: true } }, p.apiKeyHelper), p.env, turn.account ?? ''])
+ let k = kept.get(session.id)
+ if (k && (k.key !== key || !k.cli.alive || k.cli.busy || !session.resume)) {
+ close(session.id)
+ k = undefined
+ }
+ if (k?.timer) clearTimeout(k.timer)
+ if (!k) {
+ k = { cli: new LiveCli({ bin: path, args: claudeArgs(turn, p.apiKeyHelper), cwd: turn.cwd, env }), key, usedAt: Date.now() }
+ kept.set(session.id, k)
+ }
+ const current = k
+ let ended = false // a whole turn, with its result
+ try {
+ for await (const ev of current.cli.turn(claudeInput(turn), claudeParser(), turn.signal)) {
+ if (ev.type === 'done') ended = true
+ yield ev
+ }
+ } finally {
+ // Kept for the next reply only after a clean one; anything else and it goes.
+ if (kept.get(session.id) === current) {
+ if (ended && session.keep && current.cli.alive && !turn.signal.aborted) {
+ current.usedAt = Date.now()
+ current.timer = setTimeout(() => kept.get(session.id) === current && close(session.id), KEEP_IDLE_MS)
+ current.timer.unref()
+ trim()
+ } else close(session.id)
+ }
+ }
+ },
+ release(id) {
+ const open = kept.get(id)?.cli
+ close(id)
+ const file = files.get(id)
+ files.delete(id)
+ if (!file) return
+ // The file, and the folder Claude Code may keep beside it (tool results). Only once the process
+ // is gone: on its way out it writes the session's last prompt and cost to the file again.
+ // Still in use (on Windows), it stays: the next start's clean() takes it.
+ const remove = (): void => {
+ for (const p of [file, file.slice(0, -'.jsonl'.length)])
+ try {
+ rmSync(p, { recursive: true, force: true })
+ } catch {
+ /* in use */
+ }
+ try {
+ rmdirSync(dirname(file)) // the agent's folder, once it holds nothing
+ } catch {
+ /* not empty */
+ }
+ }
+ if (open?.alive) void open.exited().then(remove)
+ else remove()
+ },
+ // Only the exact folders of the agents under workDir, in the usual config folder and in each
+ // account's: Claude Code's folder names are lossy, so a prefix could take someone else's.
+ clean(workDir, accountDirs = []) {
+ let agents: string[]
+ try {
+ agents = readdirSync(workDir)
+ } catch {
+ return // no agent has worked here yet
+ }
+ for (const config of [configDirOf(), ...accountDirs])
+ for (const a of agents) {
+ const dir = claudeProjectDir(config, join(workDir, a))
+ try {
+ for (const f of readdirSync(dir)) {
+ const id = f.endsWith('.jsonl') ? f.slice(0, -'.jsonl'.length) : f
+ if (!files.has(id) && (f.endsWith('.jsonl') || SESSION_ID.test(f))) rmSync(join(dir, f), { recursive: true, force: true })
+ }
+ if (!readdirSync(dir).length) rmdirSync(dir)
+ } catch {
+ /* none here, in use, or gone: the next start tries again */
+ }
+ }
+ },
+ dispose() {
+ for (const [, k] of kept) k.cli.killNow()
+ kept.clear()
}
}
}
diff --git a/src/core/engines/cli.ts b/src/core/engines/cli.ts
index ca1945b..46483ec 100644
--- a/src/core/engines/cli.ts
+++ b/src/core/engines/cli.ts
@@ -1,4 +1,4 @@
-import { spawn } from 'node:child_process'
+import { spawn, type ChildProcess } from 'node:child_process'
import { createInterface } from 'node:readline'
import { isWin, killTree, spawnable } from '../platform'
import type { EngineEvent } from './types'
@@ -64,6 +64,105 @@ export async function* runCli(opts: {
}
}
+// A CLI that stays open between turns, reading one JSON message per turn on stdin (Claude Code with
+// `--input-format stream-json`). A turn's events come until its parser reports the end of it (`done`
+// or `error`); a stop kills the process, since what it was doing can't be trusted to go on.
+export class LiveCli {
+ private readonly child: ChildProcess
+ private lines: string[] = []
+ private wake: (() => void) | null = null
+ private stderr = ''
+ private code: number | null | undefined // set once it exited
+ private turning = false
+ private exits: (() => void)[] = []
+
+ constructor(opts: { bin: string; args: string[]; cwd: string; env?: NodeJS.ProcessEnv }) {
+ const s = spawnable(opts.bin, opts.args)
+ this.child = spawn(s.file, s.args, { cwd: opts.cwd, stdio: ['pipe', 'pipe', 'pipe'], env: opts.env ?? process.env, windowsHide: true, windowsVerbatimArguments: s.verbatim })
+ this.child.stderr!.setEncoding('utf8')
+ this.child.stderr!.on('data', (chunk: string) => {
+ this.stderr = (this.stderr + chunk).slice(-8000)
+ })
+ this.child.stdin!.on('error', () => {}) // it may exit before reading
+ createInterface({ input: this.child.stdout!, crlfDelay: Infinity }).on('line', (line) => {
+ if (!this.turning || !line.trim()) return // between turns there's nothing to read
+ this.lines.push(line)
+ this.wake?.()
+ })
+ const exit = (code: number | null): void => {
+ if (this.code !== undefined) return
+ this.code = code
+ this.wake?.()
+ for (const done of this.exits.splice(0)) done()
+ }
+ this.child.on('close', exit)
+ this.child.on('error', (err) => {
+ this.stderr += `
+${err.message}`
+ exit(-1)
+ })
+ }
+
+ get alive(): boolean {
+ return this.code === undefined
+ }
+
+ get busy(): boolean {
+ return this.turning
+ }
+
+ // Once it has exited (at once if it already has).
+ exited(): Promise<void> {
+ return this.alive ? new Promise((resolve) => this.exits.push(resolve)) : Promise.resolve()
+ }
+
+ async *turn(input: string, parser: Parser, signal: AbortSignal): AsyncIterable<EngineEvent> {
+ if (this.turning) throw new Error('a turn is already running in this process')
+ this.turning = true
+ this.lines = []
+ const stop = (): void => {
+ this.kill()
+ this.wake?.()
+ }
+ signal.addEventListener('abort', stop, { once: true })
+ try {
+ if (this.alive && !signal.aborted) this.child.stdin!.write(input)
+ for (;;) {
+ if (signal.aborted) return
+ const line = this.lines.shift()
+ if (line !== undefined) {
+ const events = parser.line(line)
+ yield* events
+ if (events.some((e) => e.type === 'done' || e.type === 'error')) return
+ continue
+ }
+ if (!this.alive) {
+ yield* parser.end(this.code ?? null, this.stderr)
+ return
+ }
+ await new Promise<void>((resolve) => (this.wake = resolve))
+ this.wake = null
+ }
+ } finally {
+ signal.removeEventListener('abort', stop)
+ this.turning = false
+ }
+ }
+
+ kill(): void {
+ if (!this.alive) return
+ const pid = this.child.pid
+ if (isWin && pid) return killTree(pid)
+ this.child.kill('SIGTERM')
+ setTimeout(() => this.alive && this.child.kill('SIGKILL'), 5_000).unref()
+ }
+
+ // The app is quitting: nothing async, the process may be gone before taskkill would run.
+ killNow(): void {
+ if (this.alive) this.child.kill()
+ }
+}
+
export function parseJson(line: string): Record<string, unknown> | null {
try {
const v: unknown = JSON.parse(line)
diff --git a/src/core/engines/fake.ts b/src/core/engines/fake.ts
index ba85000..c18c7fb 100644
--- a/src/core/engines/fake.ts
+++ b/src/core/engines/fake.ts
@@ -9,10 +9,12 @@ import type { Engine, EngineEvent, Turn } from './types'
// Deterministic engine for tests and screenshots. Never spawns anything, but
// behaves like the real ones where it matters: it routes when given the
// router prompt, and calls ask_user through the gateway when asked to ask.
-export function fakeEngine(id: Engine['id'], opts: { delayMs?: number; reply?: (turn: Turn) => string } = {}): Engine {
+// `sessions`: it takes kept sessions like Claude Code does, and `released` gets the ones let go.
+export function fakeEngine(id: Engine['id'], opts: { delayMs?: number; reply?: (turn: Turn) => string; sessions?: boolean; released?: string[] } = {}): Engine {
const delay = opts.delayMs ?? 25
return {
id,
+ ...(opts.sessions ? { sessions: true, release: (sessionId: string) => void opts.released?.push(sessionId) } : {}),
async *run(turn): AsyncIterable<EngineEvent> {
const last = lastMessage(turn.prompt)
// "acabou o limite": Claude's usual login is out, to see an agent's reserve take over (another
diff --git a/src/core/engines/types.ts b/src/core/engines/types.ts
index 2405938..5de12d7 100644
--- a/src/core/engines/types.ts
+++ b/src/core/engines/types.ts
@@ -12,6 +12,10 @@ export interface Turn {
mcpUrl?: string // the app's gateway for this turn: the only tools the CLI gets, besides the web ones
web?: boolean // the CLI's own web search and page reading
account?: string // the folder of another login of this harness (Settings › Accounts); unset: its usual one
+ // A session the engine keeps on disk: `resume` false starts it with this id,
+ // true goes on from it, and then `blocks` hold only what's new since its last reply. `keep`: the
+ // process may stay open a few minutes after the reply, for the next one.
+ session?: { id: string; resume: boolean; keep?: boolean }
}
// An image file, shown to the model right after block `block` (the message it came with).
@@ -36,10 +40,15 @@ export type EngineEvent =
// A web search or page read the CLI did on its own (not through the gateway).
| { type: 'web'; action: 'search' | 'fetch'; detail: string }
| { type: 'quota'; quota: Quota } // the subscription's usage windows, when the CLI tells
- | { type: 'done'; text: string; usage: Usage }
+ // `context`: the tokens the last model call of the turn saw, its reply included (how big a kept session is).
+ | { type: 'done'; text: string; usage: Usage; context?: number }
| { type: 'error'; message: string }
export interface Engine {
id: EngineId
run(turn: Turn): AsyncIterable<EngineEvent>
+ sessions?: boolean // takes `turn.session`; without it, every turn gets the whole conversation
+ release?(sessionId: string): void // a session that won't be resumed: its process and its file go
+ clean?(workDir: string, accountDirs?: string[]): void // sessions left from an earlier run of the app, by agents under workDir
+ dispose?(): void // the app is quitting: processes kept open close
}
diff --git a/src/core/gateway.ts b/src/core/gateway.ts
index 26ebbbc..1774460 100644
--- a/src/core/gateway.ts
+++ b/src/core/gateway.ts
@@ -1,5 +1,6 @@
// The gateway is a local MCP server and the only source of tools a CLI gets.
-// Each turn opens a session with its own secret URL and its own tool list;
+// Each turn opens a session with its own secret URL (a kept session's lasts
+// as long as it does) and its own tool list;
// the gateway answers tools/list with exactly that list and refuses any call
// outside it. The CLI never talks to connectors directly.
import { randomBytes } from 'node:crypto'
@@ -23,6 +24,12 @@ export interface Session {
export const textResult = (text: string, isError = false): CallToolResult => ({ content: [{ type: 'text', text }], isError })
+// Between two turns of a kept session: the process may list its tools again, but nothing runs.
+const parked = (tools: ToolDef[]): Session => ({
+ tools,
+ call: async () => textResult(L('Nenhuma resposta está rodando agora.', 'No reply is running right now.'), true)
+})
+
export class Gateway {
private http: HttpServer | null = null
private port = 0
@@ -56,10 +63,22 @@ export class Gateway {
}
// Returns the URL to hand to the CLI, and a function that revokes it.
- open(session: Session): { url: string; close: () => void } {
- const token = randomBytes(24).toString('hex')
- this.sessions.set(token, session)
- return { url: `http://127.0.0.1:${this.port}/mcp/${token}`, close: () => this.sessions.delete(token) }
+ // With `token` (a kept session's), the URL stays the same from one turn to the next, since a
+ // process kept open can't be given another: closing then only parks it, with the same tool list
+ // and every call refused, until `release`.
+ open(session: Session, token?: string): { url: string; close: () => void } {
+ const t = token ?? randomBytes(24).toString('hex')
+ this.sessions.set(t, session)
+ const close = token
+ ? () => {
+ if (this.sessions.get(t) === session) this.sessions.set(t, parked(session.tools))
+ }
+ : () => this.sessions.delete(t)
+ return { url: `http://127.0.0.1:${this.port}/mcp/${t}`, close }
+ }
+
+ release(token: string): void {
+ this.sessions.delete(token)
}
private async handle(req: import('node:http').IncomingMessage, res: import('node:http').ServerResponse): Promise<void> {
diff --git a/src/core/index.ts b/src/core/index.ts
index a440010..9fe3a78 100644
--- a/src/core/index.ts
+++ b/src/core/index.ts
@@ -753,6 +753,7 @@ const api: Api = {
if (archived) {
for (const m of db.messages()) if (m.author.kind === 'agent' && m.author.id === id && (m.run?.status === 'working' || m.run?.status === 'waiting_approval')) runner.stop(m.id)
routines.pauseAgent(id)
+ runner.forgetSessions({ agentId: id })
if (agent.browser) void browser.close(id)
}
db.saveAgent({ ...agent, archived })
@@ -798,6 +799,7 @@ const api: Api = {
for (const m of db.messages()) if (m.conversationId === id && (m.run?.status === 'working' || m.run?.status === 'waiting_approval')) runner.stop(m.id)
for (const r of db.routines()) if (r.conversationId === id) routines.remove(r.id)
for (const a of db.approvals()) if (a.conversationId === id && a.state === 'pending' && db.decideApproval(a.id, 'expired', L('O canal foi excluído.', 'The channel was deleted.'))) emit({ type: 'approval', approval: db.approvals().find((x) => x.id === a.id)! })
+ runner.forgetSessions({ conversationId: id })
db.deleteConversation(id)
emit({ type: 'conversation_removed', id })
},
@@ -1211,7 +1213,10 @@ process.parentPort.on('message', (e) => {
port.start()
})
-process.on('exit', () => db.close())
+process.on('exit', () => {
+ for (const e of Object.values(engineImpls)) e.dispose?.() // the Claude Code processes kept open between replies
+ db.close()
+})
// The app stops the core with SIGTERM, which by default skips the 'exit' handlers
// above and leaves the agents' Chromes running with nothing to drive them.
process.on('SIGTERM', () => process.exit(0))
diff --git a/src/core/runs.ts b/src/core/runs.ts
index b1fbb27..88c60f7 100644
--- a/src/core/runs.ts
+++ b/src/core/runs.ts
@@ -1,4 +1,4 @@
-import { mkdirSync, writeFileSync } from 'node:fs'
+import { mkdirSync, readdirSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
import { randomUUID } from 'node:crypto'
import { L, locale } from '../shared/lang'
@@ -20,7 +20,8 @@ import type { Db } from './db'
import type { Engine, TurnImage } from './engines/types'
import { accountDir } from './engines/detect'
import { outOfQuota } from './engines/cli'
-import { textResult, type Gateway, type ToolDef } from './gateway'
+import { textResult, type Gateway, type Session, type ToolDef } from './gateway'
+import { sessionConfig, Sessions, type SessionPlan, type Shown } from './sessions'
import { JEV_MODEL, routeJev } from './jev'
import { ROUTER_HISTORY, route, screenHandoff } from './router'
import { allowed, approvalHash, canonical } from './policy'
@@ -146,8 +147,42 @@ export class Runner {
private controllers = new Map<string, Control>()
private paused = false // "Pausar tudo": nobody starts working until it's off
private idleWaiters: (() => void)[] = []
+ private sessions: Sessions
+
+ constructor(private deps: RunnerDeps) {
+ this.sessions = new Sessions({
+ exists: (id) => !!deps.db.message(id),
+ // The token first: a failure letting the process or its file go must not keep it, nor the reply.
+ forget: (s) => {
+ deps.gateway?.release(s.token)
+ for (const e of Object.values(deps.engines))
+ try {
+ e.release?.(s.id)
+ } catch (err) {
+ console.error('[sessions] release', err)
+ }
+ }
+ })
+ // Left by an earlier run of the app, under the usual login and each account's.
+ const accounts = deps.dataDir ? join(deps.dataDir, 'accounts') : undefined
+ let accountDirs: string[] = []
+ try {
+ if (accounts) accountDirs = readdirSync(accounts).map((d) => join(accounts, d))
+ } catch {
+ // no accounts
+ }
+ for (const e of Object.values(deps.engines)) e.clean?.(deps.workDir, accountDirs)
+ setInterval(() => this.sessions.sweep(), 10 * 60_000).unref()
+ }
- constructor(private deps: RunnerDeps) {}
+ // An archived agent's sessions, or a deleted conversation's, go now: their process and the
+ // transcript Claude Code keeps on disk.
+ forgetSessions(of: { agentId?: string; conversationId?: string }): void {
+ this.sessions.dropWhere((key) => {
+ const [agent, conversation] = key.split(':')
+ return (of.agentId !== undefined && agent === of.agentId) || (of.conversationId !== undefined && conversation === of.conversationId)
+ })
+ }
setPaused(paused: boolean): void {
this.paused = paused
@@ -1156,7 +1191,7 @@ export class Runner {
}
}
- const session = this.deps.gateway?.open({
+ const tools: Session = {
tools: toolDefs,
call: async (name, args) => {
if (overBudget) {
@@ -1193,10 +1228,10 @@ export class Runner {
sign()
}
}
- })
+ }
let progress = { tokens: 0, cacheRead: 0 }
- let result: { text: string; usage: Omit<Receipt, 'model' | 'ms'> } | null = null
+ let result: { text: string; usage: Omit<Receipt, 'model' | 'ms'>; context?: number } | null = null
let error: string | null = null
let thrown: unknown // what the engine threw, if it did: a bug reads differently from a CLI's own words
@@ -1210,35 +1245,56 @@ export class Runner {
const images: TurnImage[] = attached
.slice(-MAX_TURN_IMAGES)
.flatMap((a) => (blockOf.has(a.messageId) ? [{ block: blockOf.get(a.messageId)!, path: join(this.deps.dataDir!, 'artifacts', a.id, a.name), mime: mimeOf(a.name) }] : []))
+ const system = systemPrompt({
+ agent,
+ settings,
+ conversation: conv,
+ peers,
+ memories: promptMemories,
+ canRemember,
+ hasComputer: !!computers,
+ computerOff,
+ browser: !!browser,
+ apps: apps ? agent.apps : undefined,
+ offline: (this.deps.connectors?.list() ?? []).filter((c) => (c.status === 'error' || c.status === 'needs_auth') && (agent.grants[c.id] ?? 'none') !== 'none').map((c) => c.name),
+ macFolder: computers?.mac && agent.computerKind === 'mac' ? computers.mac.cwd(agent) : undefined,
+ web: agent.web !== false,
+ routines: routines?.forAgent(agent.id),
+ skills: skills && mySkills,
+ wiki: wiki ? { pages: wiki.count(), kinds: wiki.kinds() } : undefined,
+ publish: repos,
+ builder: builds ? builderSection(settings, { models: this.deps.models?.() ?? availableModels(settings), connectors: this.deps.connectors?.list() ?? [], team: db.agents().filter((a) => !a.archived && a.kind !== 'tuca'), own: agent.modelId }) : undefined
+ })
+
+ // A kept session: the reply goes on from this agent's last one here (this conversation, or this
+ // thread) with only what's new since. Not while another agent is still writing a message this
+ // reply would see half of: that one goes the usual way, and the session takes it all next time.
+ const sessionKey = `${agent.id}:${conv.id}:${msg.threadId ?? ''}`
+ const config = sessionConfig({ engine: engineId, model: modelName, effort: agent.effort, account: account?.id ?? '', web: agent.web !== false, system, tools: toolDefs, gateway: !!this.deps.gateway })
+ const shown: Shown[] = [...blockOf].map(([id, i]) => ({ id, block: blocks[i]! }))
+ const writing = history.some((m) => m.author.kind === 'agent' && m.run?.status === 'working')
+ let plan = engines[engineId].sessions && !writing ? this.sessions.begin(sessionKey, { config, shown, restart: !!opts.existing, task: !!task }) : undefined
+ let lost: SessionPlan | undefined // given up on in the middle (the reserve took the reply)
+ const session = this.deps.gateway?.open(tools, plan?.token)
+ const whole = { prompt: blocks.join('\n\n'), blocks, images }
+ // Resumed: the new messages' blocks, then the task's, with their images.
+ const since = (p: SessionPlan): typeof whole => {
+ const at = p.send.map((id) => blockOf.get(id)!)
+ if (task) at.push(blocks.length - 1)
+ const pos = new Map(at.map((b, i) => [b, i]))
+ const sent = at.map((i) => blocks[i]!)
+ return { prompt: sent.join('\n\n'), blocks: sent, images: images.flatMap((img) => (pos.has(img.block) ? [{ ...img, block: pos.get(img.block)! }] : [])) }
+ }
+ let input = plan?.resume ? since(plan) : whole
try {
for (;;) {
try {
const events = engines[engineId].run({
model: modelName,
effort: agent.effort,
- system: systemPrompt({
- agent,
- settings,
- conversation: conv,
- peers,
- memories: promptMemories,
- canRemember,
- hasComputer: !!computers,
- computerOff,
- browser: !!browser,
- apps: apps ? agent.apps : undefined,
- offline: (this.deps.connectors?.list() ?? []).filter((c) => (c.status === 'error' || c.status === 'needs_auth') && (agent.grants[c.id] ?? 'none') !== 'none').map((c) => c.name),
- macFolder: computers?.mac && agent.computerKind === 'mac' ? computers.mac.cwd(agent) : undefined,
- web: agent.web !== false,
- routines: routines?.forAgent(agent.id),
- skills: skills && mySkills,
- wiki: wiki ? { pages: wiki.count(), kinds: wiki.kinds() } : undefined,
- publish: repos,
- builder: builds ? builderSection(settings, { models: this.deps.models?.() ?? availableModels(settings), connectors: this.deps.connectors?.list() ?? [], team: db.agents().filter((a) => !a.archived && a.kind !== 'tuca'), own: agent.modelId }) : undefined
- }),
- prompt: blocks.join('\n\n'),
- blocks,
- images,
+ system,
+ ...input,
+ session: plan && { id: plan.id, resume: plan.resume, keep: true },
cwd,
signal: control.ctl.signal,
mcpUrl: session?.url,
@@ -1284,6 +1340,10 @@ export class Runner {
const from = `${engineLabel}${account ? ` (${account.name})` : ''}`
flush()
msg.text = '' // the CLI's own "you've hit your limit", when it wrote it as text
+ // The reserve starts from the whole conversation: the session stays with the main model.
+ lost = plan
+ plan = undefined
+ input = whole
onReserve = true
modelId = agent.fallbackModelId!
modelName = reserve.model.id
@@ -1300,6 +1360,8 @@ export class Runner {
clearInterval(stall)
flush()
session?.close()
+ if (lost) this.sessions.end(sessionKey, lost, { ok: false, config, shown })
+ if (plan) this.sessions.end(sessionKey, plan, { ok: !!result && !control.reason, config, shown, reply: msg.id, context: result?.context })
this.controllers.delete(msg.id)
}
diff --git a/src/core/sessions.ts b/src/core/sessions.ts
new file mode 100644
index 0000000..4d70154
--- /dev/null
+++ b/src/core/sessions.ts
@@ -0,0 +1,146 @@
+// A session kept per agent, conversation and thread, so a reply goes on from the agent's last one
+// with only what's new since (other people's and agents' messages, then the task), instead of the
+// whole transcript again: the history is read back from the prompt cache, not written to it again.
+//
+// What the session saw is what decides whether it can go on. It starts over when anything it saw
+// changed: the system prompt or the tools (Claude Code keeps the first system prompt on resume, so a
+// new one needs a new session), a message it saw was edited or deleted, a message turns up in
+// between, its last reply didn't end well, or it grew past what a fresh start would cost.
+import { createHash, randomBytes, randomUUID } from 'node:crypto'
+
+export const SESSION_TTL_MS = 55 * 60_000 // the prompt cache lasts an hour: past it, resuming costs what starting over does
+export const SESSION_MAX_CONTEXT = 60_000 // tokens; past it, the next reply starts over from the summary and the window
+export const MAX_SESSIONS = 100
+
+// A message as the transcript shows it: its id and its block.
+export interface Shown {
+ id: string
+ block: string
+}
+
+export interface SessionPlan {
+ id: string // the engine's session id
+ token: string // the gateway's, for as long as the session lives: a process kept open keeps its URL
+ resume: boolean
+ send: string[] // the messages to send, of those shown: all of them when it starts, the new ones when it resumes
+}
+
+interface Entry {
+ id: string
+ token: string
+ config: string
+ seen: Map<string, string> // message id → its block's hash; '*' for its own replies, whose text it wrote
+ usedAt: number
+ context: number
+}
+
+const OWN = '*'
+const hash = (text: string): string => createHash('sha256').update(text).digest('base64url')
+
+// Everything a session is tied to: a change in any of these starts a new one.
+export const sessionConfig = (parts: Record<string, unknown>): string => hash(JSON.stringify(parts))
+
+export class Sessions {
+ private entries = new Map<string, Entry>()
+ private busy = new Set<string>()
+ private doomed = new Set<string>() // to go when their running reply ends
+ private readonly now: () => number
+
+ constructor(
+ private readonly opts: {
+ exists(messageId: string): boolean // still in the database: a deleted message ends the session that saw it
+ forget(s: { id: string; token: string }): void // the engine's process and file, and the gateway's token
+ now?: () => number
+ ttlMs?: number
+ maxContext?: number
+ }
+ ) {
+ this.now = opts.now ?? Date.now
+ }
+
+ // Undefined when a reply for the same key is already running: that one goes without a session.
+ // `restart`: start over regardless ("try again" redoes a reply the session already holds).
+ // `task`: the turn ends with a task block, so it has something to send even with no new message.
+ begin(key: string, input: { config: string; shown: Shown[]; restart?: boolean; task?: boolean }): SessionPlan | undefined {
+ if (this.busy.has(key)) return undefined
+ this.busy.add(key)
+ const e = this.entries.get(key)
+ if (e && !input.restart) {
+ const send = this.since(e, input)
+ if (send && (send.length || input.task)) return { id: e.id, token: e.token, resume: true, send }
+ }
+ if (e) this.drop(key)
+ return { id: randomUUID(), token: randomBytes(24).toString('hex'), resume: false, send: input.shown.map((s) => s.id) }
+ }
+
+ // The reply ended. `ok`: it finished on its own (not stopped, cut or failed), so the session holds
+ // a whole turn and can go on; `reply`: the agent's own message; `context`: its size now, in tokens.
+ end(key: string, plan: SessionPlan, out: { ok: boolean; config: string; shown: Shown[]; reply?: string; context?: number }): void {
+ this.busy.delete(key)
+ const e = this.entries.get(key)
+ if (!out.ok || this.doomed.delete(key)) {
+ if (e?.id === plan.id) this.drop(key)
+ else this.opts.forget(plan)
+ return
+ }
+ const entry: Entry = e?.id === plan.id ? e : { id: plan.id, token: plan.token, config: out.config, seen: new Map(), usedAt: 0, context: 0 }
+ for (const s of out.shown) entry.seen.set(s.id, hash(s.block))
+ if (out.reply) entry.seen.set(out.reply, OWN)
+ entry.config = out.config
+ entry.usedAt = this.now()
+ entry.context = out.context ?? entry.context
+ this.entries.set(key, entry)
+ if (this.entries.size > MAX_SESSIONS) {
+ const oldest = [...this.entries].filter(([k]) => !this.busy.has(k)).sort((a, b) => a[1].usedAt - b[1].usedAt)[0]
+ if (oldest) this.drop(oldest[0])
+ }
+ }
+
+ // Sessions that can't go on: their agent was archived or their conversation deleted. Keys are
+ // agent:conversation:thread. One with a reply running goes when that reply ends.
+ dropWhere(match: (key: string) => boolean): void {
+ for (const k of new Set([...this.entries.keys(), ...this.busy]))
+ if (!match(k)) continue
+ else if (this.busy.has(k)) this.doomed.add(k)
+ else this.drop(k)
+ }
+
+ // Sessions whose cache is gone: resuming them would cost what starting over does.
+ sweep(): void {
+ const ttl = this.opts.ttlMs ?? SESSION_TTL_MS
+ for (const [k, e] of [...this.entries]) if (!this.busy.has(k) && this.now() - e.usedAt > ttl) this.drop(k)
+ }
+
+ has(key: string): boolean {
+ return this.entries.has(key)
+ }
+
+ // What's new since the session's last reply, or undefined when it can't go on.
+ private since(e: Entry, input: { config: string; shown: Shown[] }): string[] | undefined {
+ if (e.config !== input.config) return undefined
+ if (this.now() - e.usedAt > (this.opts.ttlMs ?? SESSION_TTL_MS)) return undefined
+ if (e.context > (this.opts.maxContext ?? SESSION_MAX_CONTEXT)) return undefined
+ const send: string[] = []
+ const shownIds = new Set<string>()
+ for (const s of input.shown) {
+ shownIds.add(s.id)
+ const was = e.seen.get(s.id)
+ if (was === undefined) {
+ send.push(s.id)
+ continue
+ }
+ if (send.length) return undefined // a message it saw comes after one it didn't: something turned up in between
+ if (was !== OWN && was !== hash(s.block)) return undefined // edited since
+ }
+ // Out of the window now, or deleted.
+ for (const id of e.seen.keys()) if (!shownIds.has(id) && !this.opts.exists(id)) return undefined
+ return send
+ }
+
+ private drop(key: string): void {
+ const e = this.entries.get(key)
+ if (!e) return
+ this.entries.delete(key)
+ this.opts.forget(e)
+ }
+}
diff --git a/test/engines.test.ts b/test/engines.test.ts
index c504e23..4034379 100644
--- a/test/engines.test.ts
+++ b/test/engines.test.ts
@@ -29,6 +29,7 @@ describe('Claude Code stream', () => {
expect(done).toEqual({
type: 'done',
text: 'oi, tudo certo.',
+ context: 10 + 6617 + 84, // the last model call's input and output
usage: { inputTokens: 10 + 6617, cacheReadTokens: 6617, outputTokens: 84, apiCostUsd: 0.0010917 }
})
expect(events.some((e) => e.type === 'error')).toBe(false)
diff --git a/test/fixtures/fake-claude.mjs b/test/fixtures/fake-claude.mjs
new file mode 100644
index 0000000..a78b406
--- /dev/null
+++ b/test/fixtures/fake-claude.mjs
@@ -0,0 +1,21 @@
+// Stands in for Claude Code reading `--input-format stream-json`: one reply per message on stdin,
+// for as long as stdin stays open. The reply says which process and which turn it was, and whether
+// it was started to resume a session. "demore" in the message: it takes 5 s before answering.
+import { createInterface } from 'node:readline'
+
+const resume = process.argv.includes('--resume')
+let turn = 0
+const out = (ev) => process.stdout.write(`${JSON.stringify(ev)}\n`)
+
+createInterface({ input: process.stdin }).on('line', async (line) => {
+ if (!line.trim()) return
+ const msg = JSON.parse(line)
+ const text = (msg.message?.content ?? []).map((c) => c.text ?? '').join('\n')
+ turn++
+ out({ type: 'system', subtype: 'init' })
+ out({ type: 'stream_event', event: { type: 'message_start', message: { usage: { input_tokens: 10, cache_read_input_tokens: 0 } } } })
+ if (/demore/.test(text)) await new Promise((r) => setTimeout(r, 5000))
+ const reply = `pid=${process.pid} turn=${turn} resume=${resume}`
+ out({ type: 'stream_event', event: { type: 'content_block_delta', delta: { type: 'text_delta', text: reply } } })
+ out({ type: 'result', subtype: 'success', result: reply, usage: { input_tokens: 10, output_tokens: 5 } })
+})
diff --git a/test/kept-session.test.ts b/test/kept-session.test.ts
new file mode 100644
index 0000000..d97efb6
--- /dev/null
+++ b/test/kept-session.test.ts
@@ -0,0 +1,445 @@
+import { Client } from '@modelcontextprotocol/sdk/client/index.js'
+import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'
+import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import type { Agent, EngineId, Message, Settings } from '../src/shared/types'
+import { Db } from '../src/core/db'
+import { claudeArgs, claudeEngine, claudeInput, claudeParser, claudeProjectDir, MAX_IDLE } from '../src/core/engines/claude'
+import { LiveCli } from '../src/core/engines/cli'
+import { fakeEngine } from '../src/core/engines/fake'
+import type { Engine, EngineEvent, Turn } from '../src/core/engines/types'
+import { Gateway, textResult, type ToolDef } from '../src/core/gateway'
+import { Runner } from '../src/core/runs'
+import { SESSION_MAX_CONTEXT, SESSION_TTL_MS, sessionConfig, Sessions, type Shown } from '../src/core/sessions'
+
+const ready = { installed: true, loggedIn: true }
+const isWin = process.platform === 'win32'
+
+// ---------- the store ----------
+
+describe('Sessions', () => {
+ let now = 1_000
+ let forgot: string[] = []
+ let gone = new Set<string>()
+ const store = (): Sessions => new Sessions({ exists: (id) => !gone.has(id), forget: (s) => void forgot.push(s.id), now: () => now })
+ const msgs = (...ids: string[]): Shown[] => ids.map((id) => ({ id, block: `[Edu]\n${id}` }))
+ const cfg = sessionConfig({ system: 'a', tools: [] })
+
+ beforeEach(() => {
+ now = 1_000
+ forgot = []
+ gone = new Set()
+ })
+
+ // A first reply over m1, m2; the agent answers r1.
+ const started = (s: Sessions) => {
+ const p = s.begin('k', { config: cfg, shown: msgs('m1', 'm2') })!
+ s.end('k', p, { ok: true, config: cfg, shown: msgs('m1', 'm2'), reply: 'r1', context: 1_000 })
+ return p
+ }
+
+ it('starts with everything, then goes on with only what came after its last reply', () => {
+ const s = store()
+ const first = started(s)
+ expect(first).toMatchObject({ resume: false, send: ['m1', 'm2'] })
+ const next = s.begin('k', { config: cfg, shown: [...msgs('m1', 'm2'), { id: 'r1', block: '[Lia]\nresposta' }, ...msgs('m3', 'm4')] })
+ expect(next).toEqual({ id: first.id, token: first.token, resume: true, send: ['m3', 'm4'] })
+ })
+
+ it('goes on after older messages leave the window', () => {
+ const s = store()
+ started(s)
+ expect(s.begin('k', { config: cfg, shown: [{ id: 'r1', block: 'x' }, ...msgs('m3')] })).toMatchObject({ resume: true, send: ['m3'] })
+ })
+
+ it('starts over, letting the old one go, when anything it saw changed', () => {
+ const cases: [string, (s: Sessions) => ReturnType<Sessions['begin']>][] = [
+ ['another system prompt or tools', (s) => s.begin('k', { config: sessionConfig({ system: 'b', tools: [] }), shown: msgs('m1', 'm2', 'm3') })],
+ ['a message edited', (s) => s.begin('k', { config: cfg, shown: [{ id: 'm1', block: '[Edu]\nmudou' }, ...msgs('m2', 'm3')] })],
+ ['a message turning up in between', (s) => s.begin('k', { config: cfg, shown: msgs('m1', 'mx', 'm2', 'm3') })],
+ ['a message deleted', (s) => ((gone = new Set(['m1'])), s.begin('k', { config: cfg, shown: msgs('m2', 'm3') }))],
+ ['the cache gone', (s) => ((now += SESSION_TTL_MS + 1), s.begin('k', { config: cfg, shown: msgs('m1', 'm2', 'm3') }))],
+ ['"try again"', (s) => s.begin('k', { config: cfg, shown: msgs('m1', 'm2', 'm3'), restart: true })],
+ ['nothing new to send', (s) => s.begin('k', { config: cfg, shown: msgs('m1', 'm2') })]
+ ]
+ for (const [why, next] of cases) {
+ forgot = []
+ gone = new Set()
+ now = 1_000
+ const s = store()
+ const first = started(s)
+ const p = next(s)
+ expect(p?.resume, why).toBe(false)
+ expect(p?.id, why).not.toBe(first.id)
+ expect(forgot, why).toEqual([first.id])
+ }
+ })
+
+ it('goes on with nothing new when the reply has a task (an approval, a routine)', () => {
+ const s = store()
+ started(s)
+ expect(s.begin('k', { config: cfg, shown: msgs('m1', 'm2'), task: true })).toMatchObject({ resume: true, send: [] })
+ })
+
+ it('starts over once it has grown past what a fresh start costs', () => {
+ const s = store()
+ const p = s.begin('k', { config: cfg, shown: msgs('m1') })!
+ s.end('k', p, { ok: true, config: cfg, shown: msgs('m1'), reply: 'r1', context: SESSION_MAX_CONTEXT + 1 })
+ expect(s.begin('k', { config: cfg, shown: msgs('m1', 'm2') })?.resume).toBe(false)
+ })
+
+ it('lets a session go when its reply didn’t end well', () => {
+ const s = store()
+ const first = started(s)
+ const p = s.begin('k', { config: cfg, shown: msgs('m1', 'm2', 'm3') })!
+ s.end('k', p, { ok: false, config: cfg, shown: msgs('m1', 'm2', 'm3') })
+ expect(forgot).toEqual([first.id])
+ expect(s.has('k')).toBe(false)
+ // and a new one that never got a good reply is let go too
+ const q = s.begin('k', { config: cfg, shown: msgs('m1') })!
+ s.end('k', q, { ok: false, config: cfg, shown: msgs('m1') })
+ expect(forgot).toEqual([first.id, q.id])
+ })
+
+ it('gives no session to a second reply while the first one runs', () => {
+ const s = store()
+ expect(s.begin('k', { config: cfg, shown: msgs('m1') })).toBeDefined()
+ expect(s.begin('k', { config: cfg, shown: msgs('m1') })).toBeUndefined()
+ expect(s.begin('other', { config: cfg, shown: msgs('m1') })).toBeDefined()
+ })
+
+ it('lets an archived agent’s or a deleted conversation’s sessions go, a running one when it ends', () => {
+ const s = store()
+ const idle = started(s)
+ const p = s.begin('a1:c2:', { config: cfg, shown: msgs('m1') })!
+ s.dropWhere((key) => key === 'k' || key.startsWith('a1:'))
+ expect(forgot).toEqual([idle.id])
+ s.end('a1:c2:', p, { ok: true, config: cfg, shown: msgs('m1'), reply: 'r1' })
+ expect(forgot).toEqual([idle.id, p.id])
+ expect(s.has('a1:c2:')).toBe(false)
+ })
+
+ it('sweeps the ones past the cache', () => {
+ const s = store()
+ const first = started(s)
+ now += SESSION_TTL_MS + 1
+ s.sweep()
+ expect(forgot).toEqual([first.id])
+ })
+})
+
+// ---------- the runner, with a fake engine that takes sessions ----------
+
+function agent(id: string, handle: string, extra: Partial<Agent> = {}): Agent {
+ return { id, name: handle, handle, role: '', color: 'sky', instructions: '', modelId: 'sonnet', effort: 'low', limit: 1_000_000, used: 0, grants: {}, memory: 'auto', computer: false, archived: false, ...extra }
+}
+
+describe('a reply with a kept session', () => {
+ let db: Db
+ let settings: Settings
+ let turns: Turn[]
+ let released: string[]
+
+ const recorded = (e: Engine): Engine => ({ ...e, run: (t) => (turns.push(t), e.run(t)) })
+ function runner(opts: { delayMs?: number; reply?: (t: Turn) => string; sessions?: boolean } = {}): Runner {
+ const claude = recorded(fakeEngine('claude', { delayMs: opts.delayMs ?? 1, reply: opts.reply, sessions: opts.sessions ?? true, released }))
+ const engines: Record<EngineId, Engine> = { claude, codex: fakeEngine('codex', { delayMs: 1 }), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor'), grok: fakeEngine('grok') }
+ return new Runner({ db, engines, settings: async () => settings, emit: () => {}, workDir: mkdtempSync(join(tmpdir(), 'ks-work-')) })
+ }
+ const agentMessages = (): Message[] => db.messages().filter((m) => m.author.kind === 'agent')
+
+ beforeEach(() => {
+ db = new Db(join(mkdtempSync(join(tmpdir(), 'ks-db-')), 'test.db'))
+ turns = []
+ released = []
+ settings = { workspaceName: 'Edu', context: '', engines: { claude: ready, codex: ready, opencode: ready, pi: ready, gemini: ready, cursor: ready, grok: ready }, routerModel: 'haiku', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1000, approvalTtlHours: 24, theme: 'system', language: 'pt' }
+ db.saveAgent(agent('a1', 'lia'))
+ db.saveAgent(agent('a2', 'theo'))
+ db.createConversation({ id: 'd1', kind: 'dm', name: 'a1', members: ['a1'] })
+ db.createConversation({ id: 'c1', kind: 'channel', name: 'engenharia', members: ['a1', 'a2'] })
+ })
+
+ it('sends the whole conversation once, then only the new message', async () => {
+ const r = runner()
+ await r.send('d1', 'oi')
+ await r.idle()
+ await r.send('d1', 'e o job de ontem?')
+ await r.idle()
+
+ const [first, second] = turns
+ expect(first!.session).toMatchObject({ resume: false, keep: true })
+ expect(first!.blocks!.some((b) => b.includes('oi'))).toBe(true)
+ expect(second!.session).toEqual({ id: first!.session!.id, resume: true, keep: true })
+ expect(second!.blocks).toHaveLength(1)
+ expect(second!.blocks![0]).toMatch(/^\[Edu · .*\]\ne o job de ontem\?$/)
+ expect(second!.prompt).not.toContain('Resposta de teste') // its own reply is in the session already
+ expect(agentMessages().map((m) => m.run?.status)).toEqual(['done', 'done'])
+ })
+
+ it('keeps one session per thread', async () => {
+ db.createConversation({ id: 'c2', kind: 'channel', name: 'dados', members: ['a1'], threads: true })
+ const r = runner()
+ await r.send('c2', 'primeira')
+ await r.idle()
+ await r.send('c2', 'segunda')
+ await r.idle()
+ expect(turns[1]!.session!.resume).toBe(false)
+ expect(turns[1]!.session!.id).not.toBe(turns[0]!.session!.id)
+ const thread = agentMessages()[0]!.threadId!
+ await r.send('c2', 'na thread', [], thread)
+ await r.idle()
+ expect(turns[2]!.session).toMatchObject({ id: turns[0]!.session!.id, resume: true })
+ })
+
+ it('starts over, letting the old one go, when the agent’s instructions change', async () => {
+ const r = runner()
+ await r.send('d1', 'oi')
+ await r.idle()
+ db.saveAgent(agent('a1', 'lia', { instructions: 'Responda em tópicos.' }))
+ await r.send('d1', 'de novo')
+ await r.idle()
+ expect(turns[1]!.session!.resume).toBe(false)
+ expect(released).toEqual([turns[0]!.session!.id])
+ expect(turns[1]!.blocks!.some((b) => b.includes('oi'))).toBe(true)
+ })
+
+ it('starts over after a message it saw was edited', async () => {
+ const r = runner()
+ await r.send('d1', 'oi')
+ await r.idle()
+ const mine = db.messages().find((m) => m.author.kind === 'me')!
+ db.saveMessage({ ...mine, text: 'olá' })
+ await r.send('d1', 'de novo')
+ await r.idle()
+ expect(turns[1]!.session!.resume).toBe(false)
+ expect(released).toEqual([turns[0]!.session!.id])
+ })
+
+ it('lets a stopped reply’s session go, and the next one starts over', async () => {
+ const r = runner({ delayMs: 30, reply: () => 'uma resposta bem longa que demora pra chegar inteira' })
+ await r.send('d1', 'oi')
+ await new Promise((res) => setTimeout(res, 80))
+ r.stop(agentMessages()[0]!.id)
+ await r.idle()
+ expect(released).toEqual([turns[0]!.session!.id])
+ await r.send('d1', 'de novo')
+ await r.idle()
+ expect(turns[1]!.session!.resume).toBe(false)
+ expect(turns[1]!.session!.id).not.toBe(turns[0]!.session!.id)
+ })
+
+ it('goes without a session while another agent is still writing what it would see', async () => {
+ const r = runner()
+ const half: Message = { id: 'm-theo', conversationId: 'c1', author: { kind: 'agent', id: 'a2' }, text: 'Estou olhando a tab', at: Date.now() - 1000, run: { status: 'working', depth: 1, steps: [] } }
+ db.saveMessage(half)
+ await r.send('c1', '@lia oi')
+ await r.idle()
+ expect(turns[0]!.session).toBeUndefined()
+ // Once it's done, the next reply starts a session with all of it.
+ db.saveMessage({ ...half, text: 'Estou olhando a tabela de vendas.', run: { status: 'done', depth: 1, steps: [] } })
+ await r.send('c1', '@lia e agora?')
+ await r.idle()
+ expect(turns[1]!.session?.resume).toBe(false)
+ expect(turns[1]!.blocks!.some((b) => b.includes('tabela de vendas'))).toBe(true)
+ })
+
+ it('lets the session go when its conversation is deleted or its agent archived', async () => {
+ const r = runner()
+ await r.send('d1', 'oi')
+ await r.idle()
+ r.forgetSessions({ conversationId: 'c1' })
+ expect(released).toEqual([])
+ r.forgetSessions({ agentId: 'a1' })
+ expect(released).toEqual([turns[0]!.session!.id])
+ await r.send('d1', 'de novo')
+ await r.idle()
+ expect(turns[1]!.session).toMatchObject({ resume: false })
+ })
+
+ it('finishes the reply when letting a session go fails', async () => {
+ const claude = recorded(fakeEngine('claude', { delayMs: 1, sessions: true, released }))
+ const failing: Engine = { ...claude, release: () => { throw new Error('EBUSY: resource busy or locked') } }
+ const engines: Record<EngineId, Engine> = { claude: failing, codex: fakeEngine('codex', { delayMs: 1 }), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor'), grok: fakeEngine('grok') }
+ const r = new Runner({ db, engines, settings: async () => settings, emit: () => {}, workDir: mkdtempSync(join(tmpdir(), 'ks-work-')) })
+ await r.send('d1', 'oi')
+ await r.idle()
+ db.saveAgent({ ...db.agent('a1')!, instructions: 'outra coisa' }) // the next reply starts over, letting the first go
+ await r.send('d1', 'de novo')
+ await r.idle()
+ expect(agentMessages().map((m) => m.run?.status)).toEqual(['done', 'done'])
+ await r.send('d1', 'e agora?')
+ await r.idle()
+ expect(turns[2]!.session).toMatchObject({ resume: true }) // the key isn't stuck busy
+ })
+
+ it('gives an engine that takes no sessions the whole conversation every time', async () => {
+ const r = runner({ sessions: false })
+ await r.send('d1', 'oi')
+ await r.idle()
+ await r.send('d1', 'de novo')
+ await r.idle()
+ expect(turns.map((t) => t.session)).toEqual([undefined, undefined])
+ expect(turns[1]!.blocks!.some((b) => b.includes('oi'))).toBe(true)
+ })
+})
+
+// ---------- the gateway's URL for a kept session ----------
+
+describe('a kept session’s gateway URL', () => {
+ let gateway: Gateway
+ beforeEach(async () => {
+ gateway = new Gateway()
+ await gateway.start()
+ })
+ afterEach(() => gateway.stop())
+
+ const tool: ToolDef = { name: 'ask_user', description: 'x', inputSchema: { type: 'object', properties: {} } }
+ async function connect(url: string): Promise<Client> {
+ const client = new Client({ name: 'test', version: '0.0.0' })
+ await client.connect(new StreamableHTTPClientTransport(new URL(url)))
+ return client
+ }
+
+ it('stays the same across turns, refuses calls between them, and goes on release', async () => {
+ const token = 'ab'.repeat(24)
+ const a = gateway.open({ tools: [tool], call: async () => textResult('turn 1') }, token)
+ a.close()
+ const b = gateway.open({ tools: [tool], call: async () => textResult('turn 2') }, token)
+ expect(b.url).toBe(a.url)
+ const client = await connect(b.url)
+ expect(await client.callTool({ name: 'ask_user', arguments: {} })).toMatchObject({ content: [{ text: 'turn 2' }] })
+ b.close()
+ expect((await client.listTools()).tools.map((t) => t.name)).toEqual(['ask_user'])
+ expect(await client.callTool({ name: 'ask_user', arguments: {} })).toMatchObject({ isError: true })
+ await client.close()
+ gateway.release(token)
+ expect((await fetch(b.url, { method: 'POST' })).status).toBe(404)
+ })
+})
+
+// ---------- Claude Code's flags, input and output for a session ----------
+
+describe('Claude Code with a session', () => {
+ const base = { model: 'haiku', effort: 'low' as const, system: 'x' }
+
+ it('starts it with its id, or resumes it, and saves it', () => {
+ const start = claudeArgs({ ...base, session: { id: 's1', resume: false } })
+ expect(start).toEqual(expect.arrayContaining(['--session-id', 's1', '--input-format', 'stream-json']))
+ expect(start).not.toContain('--no-session-persistence')
+ expect(claudeArgs({ ...base, session: { id: 's1', resume: true } })).toEqual(expect.arrayContaining(['--resume', 's1']))
+ expect(claudeArgs(base)).toContain('--no-session-persistence')
+ })
+
+ it('always writes a JSON message, one line per turn', () => {
+ const line = claudeInput({ prompt: 'oi', session: { id: 's1', resume: true } })
+ expect(line.endsWith('\n')).toBe(true)
+ expect(JSON.parse(line)).toEqual({ type: 'user', message: { role: 'user', content: [{ type: 'text', text: 'oi' }] } })
+ })
+
+ it('reports how big the context was at the end of the turn', () => {
+ const p = claudeParser()
+ p.line(JSON.stringify({ type: 'stream_event', event: { type: 'message_start', message: { usage: { input_tokens: 3, cache_read_input_tokens: 20_000, cache_creation_input_tokens: 500 } } } }))
+ p.line(JSON.stringify({ type: 'stream_event', event: { type: 'message_delta', usage: { output_tokens: 40 } } }))
+ const [done] = p.line(JSON.stringify({ type: 'result', subtype: 'success', result: 'ok', usage: {} }))
+ expect(done).toMatchObject({ type: 'done', context: 20_543 })
+ })
+
+ it('keeps its file under the config folder, by working folder', () => {
+ expect(claudeProjectDir('/cfg', 'E:\\tucano-tmp\\probe-agent')).toBe(join('/cfg', 'projects', 'E--tucano-tmp-probe-agent'))
+ })
+})
+
+// ---------- a process kept open between turns (a stand-in for Claude Code) ----------
+
+describe('a Claude Code process kept open', () => {
+ let dir: string
+ let bin: string
+ let cfg: string
+
+ beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), 'ks-cli-'))
+ cfg = join(dir, 'config')
+ mkdirSync(cfg)
+ const script = join(dir, 'fake-claude.mjs')
+ copyFileSync(join(__dirname, 'fixtures', 'fake-claude.mjs'), script)
+ if (isWin) {
+ bin = join(dir, 'claude.cmd')
+ writeFileSync(bin, '@"%~dp0\\fake-claude.mjs" %*\r\n')
+ } else {
+ bin = join(dir, 'claude')
+ writeFileSync(bin, `#!/usr/bin/env node\n${readFileSync(script, 'utf8')}`)
+ chmodSync(bin, 0o755)
+ }
+ })
+
+ const collect = async (events: AsyncIterable<EngineEvent>): Promise<EngineEvent[]> => {
+ const out: EngineEvent[] = []
+ for await (const e of events) out.push(e)
+ return out
+ }
+ const textOf = (events: EngineEvent[]): string => events.flatMap((e) => (e.type === 'done' ? [e.text] : [])).join('')
+
+ it('answers one turn after another in the same process, until a stop kills it', async () => {
+ const cli = new LiveCli({ bin: isWin ? process.execPath : bin, args: isWin ? [join(dir, 'fake-claude.mjs')] : [], cwd: dir })
+ const line = (t: string) => claudeInput({ prompt: t, session: { id: 's', resume: false } })
+ const one = textOf(await collect(cli.turn(line('oi'), claudeParser(), new AbortController().signal)))
+ const two = textOf(await collect(cli.turn(line('de novo'), claudeParser(), new AbortController().signal)))
+ expect(one).toMatch(/turn=1/)
+ expect(two).toMatch(/turn=2/)
+ expect(one.split(' ')[0]).toBe(two.split(' ')[0]) // the same pid
+ const stop = new AbortController()
+ setTimeout(() => stop.abort(), 200)
+ const cut = await collect(cli.turn(line('demore'), claudeParser(), stop.signal))
+ expect(cut.some((e) => e.type === 'done')).toBe(false)
+ // taskkill on Windows takes its time, more so with the whole suite running
+ for (let i = 0; i < 100 && cli.alive; i++) await new Promise((r) => setTimeout(r, 100))
+ expect(cli.alive).toBe(false)
+ }, 30_000)
+
+ it('writes the next turn of a session to the process still open, and keeps only a few waiting', async () => {
+ const engine = claudeEngine(() => bin, async () => ({ env: {} }))
+ const turn = (id: string, resume: boolean, prompt = 'oi'): Turn => ({ ...{ model: 'haiku', effort: 'low', system: 'x', prompt, cwd: dir, account: cfg }, signal: new AbortController().signal, session: { id, resume, keep: true } })
+ const first = textOf(await collect(engine.run(turn('s1', false))))
+ const second = textOf(await collect(engine.run(turn('s1', true))))
+ expect(second.split(' ')[0]).toBe(first.split(' ')[0])
+ expect(second).toMatch(/turn=2 resume=false/)
+
+ // Past the cap, the one waiting longest closes: its next turn resumes it in a new process.
+ for (let i = 2; i <= MAX_IDLE + 1; i++) await collect(engine.run(turn(`s${i}`, false)))
+ const again = textOf(await collect(engine.run(turn('s1', true))))
+ expect(again.split(' ')[0]).not.toBe(first.split(' ')[0])
+ expect(again).toMatch(/turn=1 resume=true/)
+
+ // Let go: its process and its file.
+ const file = join(claudeProjectDir(cfg, dir), 's1.jsonl')
+ mkdirSync(claudeProjectDir(cfg, dir), { recursive: true })
+ writeFileSync(file, '{}\n')
+ mkdirSync(join(claudeProjectDir(cfg, dir), 's1', 'tool-results'), { recursive: true })
+ engine.release!('s1')
+ for (let i = 0; i < 50 && existsSync(file); i++) await new Promise((r) => setTimeout(r, 100)) // once its process is gone
+ expect(existsSync(file)).toBe(false)
+ expect(existsSync(join(claudeProjectDir(cfg, dir), 's1'))).toBe(false)
+ engine.dispose!()
+ }, 30_000)
+
+ it('cleans what an earlier run left in the agents’ own folders only, the accounts’ too', () => {
+ const engine = claudeEngine(() => bin, async () => ({ env: {} }))
+ const work = join(dir, 'agents')
+ mkdirSync(join(work, 'a1'), { recursive: true })
+ const id = '0f8fad5b-d9cb-469f-a165-70867728950e'
+ const left = join(claudeProjectDir(cfg, join(work, 'a1')), `${id}.jsonl`)
+ const beside = join(claudeProjectDir(cfg, join(work, 'a1')), id)
+ const neighbour = join(claudeProjectDir(cfg, join(dir, 'agents-backup', 'x')), `${id}.jsonl`)
+ for (const f of [left, neighbour]) {
+ mkdirSync(join(f, '..'), { recursive: true })
+ writeFileSync(f, '{}\n')
+ }
+ mkdirSync(beside)
+ engine.clean!(work, [cfg])
+ expect(existsSync(left)).toBe(false)
+ expect(existsSync(beside)).toBe(false)
+ expect(existsSync(neighbour)).toBe(true)
+ })
+})