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.
TypeScript agent-teamagentic-aiai-agentsai-assistantclaude-codecodexcursorelectrongrokgrok-bot-alternativelinuxlocal-firstmacosmcpmulti-agentopenclaw-alternativeopencodewindows
Faster replies and a lighter window (#179)
Eduardo Machado6cc7f0162fc1
diff --git a/src/core/apps.ts b/src/core/apps.tsindex e899448..505c60e 100644--- a/src/core/apps.ts+++ b/src/core/apps.ts@@ -102,21 +102,42 @@ export async function macApps(): Promise<{ name: string; bundleId?: string; pathreturn []}})]- // One app at a time (a broken one can't throw the others off), several at once.- const meta = (path: string): Promise<{ name: string; bundleId?: string; path: string }> =>- new Promise((resolve) =>- execFile('mdls', ['-name', 'kMDItemCFBundleIdentifier', '-name', 'kMDItemDisplayName', '-raw', path], { timeout: 5_000 }, (_e, stdout) => {- const [id = '', name = ''] = String(stdout ?? '').split('\0').map((v) => clean(v))- const shown = name.normalize('NFC').replace(/\.app$/, '')- resolve({ name: shown && shown !== '(null)' ? shown : basename(path, '.app'), ...(id && id !== '(null)' ? { bundleId: id } : {}), path })- })- )- const out: { name: string; bundleId?: string; path: string }[] = []- for (let i = 0; i < paths.length; i += 32) out.push(...(await Promise.all(paths.slice(i, i + 32).map(meta))))+ type MacApp = { name: string; bundleId?: string; path: string }+ const mdls = (batch: string[]): Promise<string> =>+ new Promise((resolve) => execFile('mdls', ['-name', 'kMDItemCFBundleIdentifier', '-name', 'kMDItemDisplayName', '-raw', ...batch], { timeout: 10_000 }, (_e, stdout) => resolve(String(stdout ?? ''))))+ // Many apps per mdls (one process each took seconds). It stops at an app Spotlight can't+ // read: that one goes by its file's name, and the rest are asked again.+ const read = async (batch: string[]): Promise<MacApp[]> => {+ if (!batch.length) return []+ const apps = parseMdls(await mdls(batch), batch)+ if (apps?.length === batch.length) return apps+ if (!apps) return (await Promise.all(batch.map((p) => (batch.length > 1 ? read([p]) : [{ name: basename(p, '.app'), path: p }])))).flat()+ const stuck = batch[apps.length]!+ return [...apps, { name: basename(stuck, '.app'), path: stuck }, ...(await read(batch.slice(apps.length + 1)))]+ }+ const batches: string[][] = []+ for (let i = 0; i < paths.length; i += 40) batches.push(paths.slice(i, i + 40))+ const out = (await Promise.all(batches.map(read))).flat()// The same app in two places (~/Applications and /Applications): once.return out.filter((a, i) => !a.bundleId || out.findIndex((b) => b.bundleId === a.bundleId) === i)}+// What `mdls -raw` prints for several apps: two values each (bundle id, then name), split by NULs.+// Fewer apps than asked when it stopped at one it couldn't read; undefined when the values don't+// pair up, so one app's answer can't be told from the next one's.+export function parseMdls(stdout: string, paths: string[]): { name: string; bundleId?: string; path: string }[] | undefined {+ // Its complaint comes on stdout too, glued to the last value: "<first path>: could not find <path>."+ const complaint = stdout.lastIndexOf(`${paths[0]}: could not find `)+ const text = complaint >= 0 ? stdout.slice(0, complaint) : stdout+ const values = text === '' ? [] : text.split('\0').map((v) => clean(v))+ if (values.length % 2 || values.length > paths.length * 2) return undefined+ return paths.slice(0, values.length / 2).map((path, i) => {+ const id = values[i * 2] ?? ''+ const shown = (values[i * 2 + 1] ?? '').normalize('NFC').replace(/\.app$/, '')+ return { name: shown && shown !== '(null)' ? shown : basename(path, '.app'), ...(id && id !== '(null)' ? { bundleId: id } : {}), path }+ })+}+export function agentDesktop(bin: () => string | undefined = desktopBin): Cli {return (args, timeoutMs = 45_000) =>new Promise((resolve) => {diff --git a/src/core/browser.ts b/src/core/browser.tsindex f5516a7..2835288 100644--- a/src/core/browser.ts+++ b/src/core/browser.ts@@ -301,7 +301,13 @@ export class Browser {if (!f.timer)f.timer = setTimeout(() => {f.timer = undefined- if (f.next && this.views.get(agentId)?.url) this.update(agentId, { frame: `data:image/jpeg;base64,${f.next}` })+ const now = this.views.get(agentId)+ // Only the picture goes out: the rest of the view is the same, and the page redraws just the screen.+ if (f.next && now?.url) {+ const frame = `data:image/jpeg;base64,${f.next}`+ this.views.set(agentId, { ...now, frame })+ this.deps.emit({ type: 'browser_frame', agentId, frame, ...(now.conversationId ? { conversationId: now.conversationId } : {}) })+ }f.next = undefined}, 100)return truediff --git a/src/core/computer.ts b/src/core/computer.tsindex f762e67..a700d5d 100644--- a/src/core/computer.ts+++ b/src/core/computer.ts@@ -418,19 +418,19 @@ export class Computers {// Before a turn: when Docker was last seen off, whether it still is (what the person has to do), read// again now. A quick `docker inspect`, which fails at once with the daemon down; nothing when it was fine,- // so a turn never waits on Docker for nothing.+ // so a turn never waits on Docker for nothing. A daemon still starting doesn't hold the reply past 3 s.async unavailable(agent: Agent): Promise<string | undefined> {if (agent.computerKind === 'mac' || this.infos.get(agent.id)?.state !== 'no_docker') return undefined- await this.refresh(agent)+ await this.refresh(agent, 3_000)const info = this.infos.get(agent.id)return info?.state === 'no_docker' ? info.detail : undefined}// Reads the container's real state, for the agent page.- async refresh(agent: Agent): Promise<void> {+ async refresh(agent: Agent, timeoutMs = 10_000): Promise<void> {if (agent.computerKind === 'mac') return this.mac.refresh(agent)if (!agent.computer) return this.set(agent.id, { state: 'off', services: [] })- const r = await docker(['inspect', '-f', '{{.State.Running}}', this.name(agent.id)], { timeoutMs: 10_000 })+ const r = await docker(['inspect', '-f', '{{.State.Running}}', this.name(agent.id)], { timeoutMs })if (r.code !== 0) {const problem = dockerProblem(r.stderr, r.late)return this.set(agent.id, { state: problem ? 'no_docker' : 'stopped', detail: problem, services: [] })diff --git a/src/core/context.ts b/src/core/context.tsindex bdd5247..88b35cd 100644--- a/src/core/context.ts+++ b/src/core/context.ts@@ -1,7 +1,9 @@-// Builds what a turn sends to the engine: a system prompt (stable per agent)-// 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.+// Builds what a turn sends to the engine: a system prompt (stable per agent),+// the live context (what changes on its own: memories, the wiki, skills,+// routines, connectors down, the Tuca's view of the team) 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,+// and the live context again only when it changed.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 Person, type Routine, type Settings, type Skill } from '../shared/types'@@ -10,7 +12,7 @@ import { osOf, shellCommand, systemName } from './platform'export const HISTORY_LIMIT = 30-export function systemPrompt(opts: {+export type PromptOpts = {agent: Agentsettings: Pick<Settings, 'workspaceName' | 'context'>conversation: Conversation@@ -26,12 +28,18 @@ export function systemPrompt(opts: {apps?: AgentApp[] // the person's own apps it may useroutines?: Routine[] // its own, when it can scheduleskills?: Skill[] // the active ones it follows, when it has skill tools- builder?: string // the Tuca's view of the workspace: models, connectors, the team+ builder?: string // the Tuca's view of the workspace: models, connectors, the team (live)+ builderGuide?: string // how to propose agents, teams, routines and channels, and the Tuca's guide (stable)wiki?: { pages: number; kinds: string[] } // the wiki it may readconnectors?: boolean // it has connector tools (Slack, Databricks…)people?: Person[] // the Tucano's people; with more than one, the agent is told who they are-}): string {- const { agent, settings, conversation, peers, memories, canRemember, hasComputer, computerOff, macFolder, offline, web, browser, apps, routines, skills, builder, wiki, connectors, people } = opts+}++// What doesn't change between replies unless the agent's setup does. A change here starts a new+// session (Claude Code keeps the first system prompt on resume), so whatever changes on its own+// goes in liveContext instead.+export function systemPrompt(opts: PromptOpts): string {+ const { agent, settings, conversation, peers, canRemember, hasComputer, computerOff, macFolder, web, browser, apps, routines, skills, connectors, builderGuide, people } = optsconst me = settings.workspaceName || L('o usuário', 'the user')const where =conversation.kind === 'dm'@@ -83,25 +91,7 @@ export function systemPrompt(opts: {.join('\n'),browser && browserSection(me),apps?.length && appsSection(me, apps),- builder,- memories && (memories.aboutMe.length > 0 || memories.own.length > 0 || !!memories.searchable) && memorySection(me, memories, people),- wiki &&- L(- `## A wiki\n${me} tem uma wiki com ${wiki.pages === 1 ? '1 página' : `${wiki.pages} páginas`} (${wiki.kinds.join(', ')}): o que ${me} e o time sabem, escrito. Quando a pergunta puder estar lá (uma pessoa, um cliente, um projeto, uma decisão, um assunto), consulte antes de responder ou de perguntar: wiki_indice pra ver o que existe, wiki_buscar pra achar, wiki_ler pra abrir. Ao usar uma página, cite com [[Título]]. Se a wiki não disser, diga que não está lá; não invente. Você só lê a wiki: o curador a atualiza sozinho depois da conversa, com o que ficar decidido; não diga que ela vai ficar desatualizada nem peça pra alguém editar.`,- `## The wiki\n${me} has a wiki with ${wiki.pages === 1 ? '1 page' : `${wiki.pages} pages`} (${wiki.kinds.join(', ')}): what ${me} and the team know, written down. When the answer could be there (a person, a client, a project, a decision, a topic), look before replying or asking: wiki_indice to see what exists, wiki_buscar to find, wiki_ler to open. When you use a page, cite it as [[Title]]. If the wiki doesn't say, say it isn't there; don't make it up. You only read the wiki: the curator updates it on its own after the conversation, with what was settled; don't say it will be out of date or ask anyone to edit it.`- ),- skills &&- skills.length > 0 &&- `${L(- `## Suas skills\nReceitas que ${me} aprovou pra tipos de tarefa. Quando a tarefa bater com o "quando usar", leia a receita com ler_skill antes de começar e siga.`,- `## Your skills\nRecipes ${me} approved for kinds of task. When the task matches the "when to use", read the recipe with ler_skill before starting and follow it.`- )}\n${skills.map((k) => `- ${k.name}: ${k.description}`).join('\n')}`,- routines &&- routines.length > 0 &&- `${L(- '## Suas rotinas\nPedidos agendados que você roda sozinho. Pra mudar ou apagar, use agendar_rotina com substitui, ou cancelar_rotina.',- '## Your routines\nScheduled requests you run on your own. To change or delete one, use agendar_rotina with substitui, or cancelar_rotina.'- )}\n${routines.map((r) => `- [${r.id}] ${r.name}: ${describeSchedule(r.schedule).toLowerCase()} · ${r.prompt.replace(/\s+/g, ' ').slice(0, 160)}`).join('\n')}`,+ builderGuide,[L('## Como responder', '## How to reply'),`- ${where} ${L(@@ -145,11 +135,6 @@ export function systemPrompt(opts: {`- Your other tools are the ones ${me} granted you. Sensitive actions don't run right away: they become an approval request, and you get the result after the decision.`),connectors && readingData(me),- offline?.length &&- L(- `- Você tem acesso a ${offline.join(', ')}, mas ${offline.length > 1 ? 'eles estão desconectados' : 'ele está desconectado'} agora, então as ferramentas não aparecem pra você. Se precisar, peça a ${me} pra reconectar em Conectores (não é falta de permissão).`,- `- You have access to ${offline.join(', ')}, but ${offline.length > 1 ? "they're disconnected" : "it's disconnected"} right now, so the tools don't show up for you. If you need them, ask ${me} to reconnect in Connectors (it's not a lack of permission).`- ),hasComputer? L('- Não diga que fez algo que nenhuma ferramenta sua fez.', "- Don't say you did something none of your tools did."): L(@@ -164,6 +149,55 @@ export function systemPrompt(opts: {.join('\n\n')}+// What changes on its own between replies: it goes at the top of the transcript, and a kept session+// gets it again (whole, after what it already has) only when it changed, so a new memory or a page+// in the wiki doesn't end every agent's session. '' when there's nothing.+export function liveContext(opts: Pick<PromptOpts, 'settings' | 'memories' | 'offline' | 'routines' | 'skills' | 'builder' | 'wiki' | 'people'>): string {+ const { settings, memories, offline, routines, skills, builder, wiki, people } = opts+ const me = settings.workspaceName || L('o usuário', 'the user')+ const parts = [+ builder,+ memories && (memories.aboutMe.length > 0 || memories.own.length > 0 || !!memories.searchable) && memorySection(me, memories, people),+ wiki &&+ L(+ `## A wiki\n${me} tem uma wiki com ${wiki.pages === 1 ? '1 página' : `${wiki.pages} páginas`} (${wiki.kinds.join(', ')}): o que ${me} e o time sabem, escrito. Quando a pergunta puder estar lá (uma pessoa, um cliente, um projeto, uma decisão, um assunto), consulte antes de responder ou de perguntar: wiki_indice pra ver o que existe, wiki_buscar pra achar, wiki_ler pra abrir. Ao usar uma página, cite com [[Título]]. Se a wiki não disser, diga que não está lá; não invente. Você só lê a wiki: o curador a atualiza sozinho depois da conversa, com o que ficar decidido; não diga que ela vai ficar desatualizada nem peça pra alguém editar.`,+ `## The wiki\n${me} has a wiki with ${wiki.pages === 1 ? '1 page' : `${wiki.pages} pages`} (${wiki.kinds.join(', ')}): what ${me} and the team know, written down. When the answer could be there (a person, a client, a project, a decision, a topic), look before replying or asking: wiki_indice to see what exists, wiki_buscar to find, wiki_ler to open. When you use a page, cite it as [[Title]]. If the wiki doesn't say, say it isn't there; don't make it up. You only read the wiki: the curator updates it on its own after the conversation, with what was settled; don't say it will be out of date or ask anyone to edit it.`+ ),+ skills &&+ skills.length > 0 &&+ `${L(+ `## Suas skills\nReceitas que ${me} aprovou pra tipos de tarefa. Quando a tarefa bater com o "quando usar", leia a receita com ler_skill antes de começar e siga.`,+ `## Your skills\nRecipes ${me} approved for kinds of task. When the task matches the "when to use", read the recipe with ler_skill before starting and follow it.`+ )}\n${skills.map((k) => `- ${k.name}: ${k.description}`).join('\n')}`,+ routines &&+ routines.length > 0 &&+ `${L(+ '## Suas rotinas\nPedidos agendados que você roda sozinho. Pra mudar ou apagar, use agendar_rotina com substitui, ou cancelar_rotina.',+ '## Your routines\nScheduled requests you run on your own. To change or delete one, use agendar_rotina with substitui, or cancelar_rotina.'+ )}\n${routines.map((r) => `- [${r.id}] ${r.name}: ${describeSchedule(r.schedule).toLowerCase()} · ${r.prompt.replace(/\s+/g, ' ').slice(0, 160)}`).join('\n')}`,+ offline?.length &&+ L(+ `## Conectores desconectados\nVocê tem acesso a ${offline.join(', ')}, mas ${offline.length > 1 ? 'eles estão desconectados' : 'ele está desconectado'} agora, então as ferramentas não aparecem pra você. Se precisar, peça a ${me} pra reconectar em Conectores (não é falta de permissão).`,+ `## Disconnected connectors\nYou have access to ${offline.join(', ')}, but ${offline.length > 1 ? "they're disconnected" : "it's disconnected"} right now, so the tools don't show up for you. If you need them, ask ${me} to reconnect in Connectors (it's not a lack of permission).`+ )+ ].filter(Boolean)+ if (!parts.length) return ''+ return [LIVE_HEAD(), ...parts].join('\n\n')+}++const LIVE_HEAD = (): string =>+ L(+ '# Contexto de agora\nIsto vem do app, não de uma mensagem. Se aparecer de novo mais adiante na conversa, vale a versão mais nova.',+ "# Context right now\nThis comes from the app, not from a message. If it shows up again later in the conversation, the newest version wins."+ )++// A kept session saw a live context that is now empty: what tells it the old one is gone.+export const NO_LIVE = (): string =>+ L(+ '# Contexto de agora\nO contexto de antes não vale mais: agora não há memórias, wiki, skills, rotinas nem conectores desconectados.',+ '# Context right now\nThe earlier context no longer holds: there are no memories, wiki, skills, routines or disconnected connectors now.'+ )+// With more than one person, who they are: names in the transcript are theirs, and `me` (what the// rest of the prompt calls "the person") is whoever this reply is for.function peopleSection(people: Person[]): string {@@ -336,6 +370,7 @@ type TranscriptOpts = {thread?: Messagesearchable?: booleanunix?: boolean // message times with the year, the offset and the Unix seconds: for an agent whose tools filter by time+ live?: string // liveContext: the first blockpeople?: Pick<Person, 'id' | 'name'>[] // who wrote each human message; one not found reads as `me`routineOwner?: string | ((routineId: string) => string | undefined) // who scheduled each routine here (undefined: the channel's); `me` when unsetanswering?: Message // a routed reply's message (the last one shown): said in so many words, so it answers that one@@ -356,7 +391,7 @@ export const snip = (text: string, max: number): string => {// The blocks, and which block each message became (where its images go).export function transcriptBlocks(opts: TranscriptOpts): { blocks: string[]; blockOf: Map<string, number> } {- const { agent, conversation, messages, agents, me, task, summary, images, thread, searchable, unix, people } = opts+ const { agent, conversation, messages, agents, me, task, summary, images, thread, searchable, unix, people, live } = optsconst scheduler = (id: string): string | undefined => (typeof opts.routineOwner === 'function' ? opts.routineOwner(id) : (opts.routineOwner ?? me))const personName = (id: string): string => people?.find((p) => p.id === id)?.name || meconst name = (m: Message): string | null => {@@ -407,6 +442,7 @@ export function transcriptBlocks(opts: TranscriptOpts): { blocks: string[]; bloc: ` ${L('As threads ficam à parte: daqui você só vê a mensagem que abriu cada uma.', 'Threads are kept apart: from here you only see the message that started each one.')} ${lookUp}`: ''const head = [+ live?.trim(),summary?.trim() &&(thread? `${L('Resumo do começo desta thread (as mensagens mais antigas dela não vão inteiras)', "Summary of this thread's beginning (its oldest messages don't go in full)")}:\n${summary.trim()}`diff --git a/src/core/db.ts b/src/core/db.tsindex f10abf3..8c04504 100644--- a/src/core/db.ts+++ b/src/core/db.ts@@ -1,4 +1,4 @@-import { DatabaseSync } from 'node:sqlite'+import { DatabaseSync, type StatementSync } from 'node:sqlite'import { randomUUID } from 'node:crypto'import { existsSync, mkdirSync, renameSync, rmSync } from 'node:fs'import { ALL_PARTS, GENERAL_SETTINGS, WORKSPACE_PARTS, type WorkspaceParts } from '../shared/workspaces'@@ -474,6 +474,13 @@ export const MIGRATIONS = [// second person, say.`CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);+ `,+ // What reads by thread (the quiet-thread sweep, every minute), by author (where an agent wrote+ // last) and a reply's receipts used to scan the whole table.+ `+ CREATE INDEX IF NOT EXISTS messages_by_thread_id ON messages (thread_id, at);+ CREATE INDEX IF NOT EXISTS messages_by_author ON messages (author_id, at);+ CREATE INDEX IF NOT EXISTS receipts_by_message ON receipts (message_id);`]@@ -493,6 +500,7 @@ export class Db {constructor(private file: string) {this.db = new DatabaseSync(file)+ this.keepStatements()this.db.exec('PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON;')try { this.migrate(file) }catch (error) { this.db.close(); throw error }@@ -502,6 +510,19 @@ export class Db {this.db.close()}+ // Each query is compiled once and kept: the same few dozen run many times a turn. node:sqlite+ // resets a statement after every get/all/run, so a kept one holds no lock between uses.+ private keepStatements(): void {+ const prepare = this.db.prepare.bind(this.db)+ const kept = new Map<string, StatementSync>()+ this.db.prepare = (sql, options) => {+ if (options) return prepare(sql, options)+ let stmt = kept.get(sql)+ if (!stmt) kept.set(sql, (stmt = prepare(sql)))+ return stmt+ }+ }+// A consistent copy of the whole database, while it's in use.backupTo(file: string): void {this.db.exec(`VACUUM INTO '${file.replace(/'/g, "''")}'`)@@ -740,12 +761,16 @@ export class Db {).all(personId) as Row[]const members = this.db.prepare('SELECT conversation_id, agent_id FROM members').all() as { conversation_id: string; agent_id: string }[]- return rows.map((r) => ({+ return rows.map((r) => this.toConversation(r, members.filter((m) => m.conversation_id === r['id']).map((m) => m.agent_id)))+ }++ private toConversation(r: Row, members: string[]): Conversation {+ return {id: str(r['id']),kind: str(r['kind']) as Conversation['kind'],name: str(r['name']),topic: r['topic'] ? str(r['topic']) : undefined,- members: members.filter((m) => m.conversation_id === r['id']).map((m) => m.agent_id),+ members,summary: r['summary'] ? str(r['summary']) : undefined,summaryUntil: r['summary_until'] ? Number(r['summary_until']) : undefined,summaryAt: r['summary_at'] ? Number(r['summary_at']) : undefined,@@ -754,7 +779,7 @@ export class Db {...(r['owner'] ? { owner: str(r['owner']) } : {}),...(r['created_by'] ? { createdBy: str(r['created_by']) } : {}),unread: Number(r['unread'])- }))+ }}// `until` is the `at` of the last message the summary covers; leave it out to keep it (a hand edit).@@ -763,8 +788,17 @@ export class Db {else this.db.prepare('UPDATE conversations SET summary = ?, summary_until = ?, summary_at = ? WHERE id = ?').run(summary, until, Date.now(), conversationId)}- conversation(id: string, personId?: string): Conversation | undefined {- return this.conversations(personId).find((c) => c.id === id)+ // Just that one: it's read several times a turn, and the full list grows with every DM.+ conversation(id: string, personId = this.ownerId()): Conversation | undefined {+ const r = this.db+ .prepare(+ `SELECT c.*, (SELECT COUNT(*) FROM unread x JOIN messages m ON m.id = x.message_id WHERE x.person_id = ? AND m.conversation_id = c.id) AS unread+ FROM conversations c WHERE c.id = ?`+ )+ .get(personId, id) as Row | undefined+ if (!r) return undefined+ const members = (this.db.prepare('SELECT agent_id FROM members WHERE conversation_id = ? ORDER BY rowid').all(id) as { agent_id: string }[]).map((m) => m.agent_id)+ return this.toConversation(r, members)}// Only whose a conversation is, for checks on every event (no counts, no members).@@ -940,13 +974,14 @@ export class Db {}// Threads quiet since `before`, active after `since`, with something said after their summary.+ // From the replies (the thread index), then each one's first message: not every message, every minute.quietThreads(before: number, since: number): { id: string; conversationId: string; last: number }[] {const rows = this.db.prepare(- `SELECT r.id, r.conversation_id, MAX(m.at) AS last, COALESCE(json_extract(r.thread_summary, '$.until'), 0) AS until- FROM messages r JOIN messages m ON m.thread_id = r.id- WHERE r.thread_id IS NULL AND m.author_kind != 'system'- GROUP BY r.id HAVING last < ? AND last > ? AND last > until ORDER BY last`+ `SELECT r.id, r.conversation_id, t.last, COALESCE(json_extract(r.thread_summary, '$.until'), 0) AS until+ FROM (SELECT thread_id, MAX(at) AS last FROM messages WHERE thread_id IS NOT NULL AND author_kind != 'system' GROUP BY thread_id) t+ CROSS JOIN messages r ON r.id = t.thread_id+ WHERE r.thread_id IS NULL AND t.last < ? AND t.last > ? AND t.last > until ORDER BY t.last`).all(before, since) as Row[]return rows.map((r) => ({ id: str(r['id']), conversationId: str(r['conversation_id']), last: Number(r['last']) }))@@ -957,6 +992,61 @@ export class Db {return (this.db.prepare('SELECT * FROM messages WHERE conversation_id = ? AND at > ? ORDER BY at').all(conversationId, at) as Row[]).map((r) => this.toMessage(r))}+ // What the window opens with: each conversation's latest `n` messages outside threads, the threads+ // still going wherever they started, and every routine's request with its reply (Routines draws what+ // ran), each with all its replies. `since`: per conversation with older ones left, from when it's whole.+ openingMessages(n: number): { messages: Message[]; since: Record<string, number> } {+ const ranked = 'ranked AS (SELECT id, conversation_id, thread_id, at, ROW_NUMBER() OVER (PARTITION BY conversation_id, thread_id IS NULL ORDER BY at DESC) AS n FROM messages)'+ const rows = this.db+ .prepare(+ `WITH ${ranked},+ asks AS (SELECT a.id, a.conversation_id, a.at, x.agent_id FROM messages a LEFT JOIN routines x ON x.id = a.author_id WHERE a.author_kind = 'routine'),+ roots AS (+ SELECT id FROM ranked WHERE thread_id IS NULL AND n <= ?+ UNION SELECT thread_id FROM ranked WHERE thread_id IS NOT NULL AND n <= ?+ UNION SELECT id FROM asks+ UNION SELECT (SELECT r.id FROM messages r WHERE r.conversation_id = asks.conversation_id AND r.author_kind = 'agent' AND r.at > asks.at AND (asks.agent_id IS NULL OR r.author_id = asks.agent_id) ORDER BY r.at LIMIT 1) FROM asks+ )+ SELECT * FROM messages WHERE id IN (SELECT id FROM roots) OR thread_id IN (SELECT id FROM roots) ORDER BY at`+ )+ .all(n, n) as Row[]+ const cut = this.db+ .prepare(`WITH ${ranked} SELECT conversation_id, at FROM ranked WHERE thread_id IS NULL AND n = ? AND conversation_id IN (SELECT conversation_id FROM ranked WHERE thread_id IS NULL AND n = ?)`)+ .all(n, n + 1) as Row[]+ return { messages: rows.map((r) => this.toMessage(r)), since: Object.fromEntries(cut.map((r) => [str(r['conversation_id']), Number(r['at'])])) }+ }++ // Further back, a page at a time: the `n` messages outside threads before `before` (all of them back+ // to `from`, when given), with their replies. `since`: from when it's whole now, 0 once all of it is.+ messagesBefore(conversationId: string, before: number, n: number, from?: number): { messages: Message[]; since: number } {+ const page = (+ from === undefined+ ? this.db.prepare('SELECT id, at FROM messages WHERE conversation_id = ? AND thread_id IS NULL AND at < ? ORDER BY at DESC LIMIT ?').all(conversationId, before, n)+ : this.db.prepare('SELECT id, at FROM messages WHERE conversation_id = ? AND thread_id IS NULL AND at < ? AND at >= ? ORDER BY at DESC').all(conversationId, before, from)+ ) as Row[]+ const oldest = page.length ? Number(page.at(-1)!['at']) : Math.min(before, from ?? before)+ const more = !!this.db.prepare('SELECT 1 FROM messages WHERE conversation_id = ? AND thread_id IS NULL AND at < ? LIMIT 1').get(conversationId, oldest)+ const since = more ? oldest : 0+ if (!page.length) return { messages: [], since }+ const ids = JSON.stringify(page.map((r) => str(r['id'])))+ const rows = this.db+ .prepare('SELECT * FROM messages WHERE conversation_id = ? AND (id IN (SELECT value FROM json_each(?)) OR thread_id IN (SELECT value FROM json_each(?))) ORDER BY at')+ .all(conversationId, ids, ids) as Row[]+ return { messages: rows.map((r) => this.toMessage(r)), since }+ }++ // The connector tools an agent called in its replies since `since`, most used first, as each step+ // names them ("Linear · list_issues"), with how many times.+ toolsUsedBy(agentId: string, since: number, replies = 200): { detail: string; count: number }[] {+ const rows = this.db.prepare("SELECT run FROM messages WHERE author_kind = 'agent' AND author_id = ? AND at > ? AND run IS NOT NULL ORDER BY at DESC LIMIT ?").all(agentId, since, replies) as Row[]+ const counts = new Map<string, number>()+ for (const r of rows) {+ const steps = (JSON.parse(str(r['run'])) as { steps?: { detail?: unknown }[] }).steps ?? []+ for (const s of steps) if (typeof s.detail === 'string' && s.detail.includes(' · ')) counts.set(s.detail, (counts.get(s.detail) ?? 0) + 1)+ }+ return [...counts].map(([detail, count]) => ({ detail, count })).sort((a, b) => b.count - a.count)+ }+// Where the agent wrote last: while it works, the conversation of its reply.lastConversationOf(agentId: string): string | undefined {const r = this.db.prepare("SELECT conversation_id FROM messages WHERE author_kind = 'agent' AND author_id = ? ORDER BY at DESC LIMIT 1").get(agentId) as Row | undefined@@ -987,10 +1077,20 @@ export class Db {)}+ // The replies whose run is in one of these states, oldest first. Found in SQL: the rest of+ // the messages are never parsed.+ messagesWithRun(statuses: Run['status'][]): Message[] {+ if (!statuses.length) return []+ const rows = this.db+ .prepare(`SELECT * FROM messages WHERE run IS NOT NULL AND json_extract(run, '$.status') IN (${statuses.map(() => '?').join(', ')}) ORDER BY at`)+ .all(...statuses) as Row[]+ return rows.map((r) => this.toMessage(r))+ }+// Runs that were working when the app closed can't continue: their CLI process is gone.interruptStaleRuns(): number {let n = 0- for (const m of this.messages()) {+ for (const m of this.messagesWithRun(['working'])) {if (m.run?.status !== 'working') continuen++this.saveMessage({@@ -1183,6 +1283,11 @@ export class Db {return (this.db.prepare('SELECT * FROM approvals ORDER BY created_at').all() as Row[]).map((r) => this.toApproval(r))}+ // What the workspace switcher counts, often: only the pending ones, from their index.+ pendingApprovals(): number {+ return Number((this.db.prepare("SELECT COUNT(*) AS n FROM approvals WHERE state = 'pending'").get() as { n: number }).n)+ }+approval(id: string): Approval | undefined {const r = this.db.prepare('SELECT * FROM approvals WHERE id = ?').get(id) as Row | undefinedreturn r && this.toApproval(r)@@ -1275,7 +1380,16 @@ export class Db {// ---------- artifacts ----------artifacts(): Artifact[] {- return (this.db.prepare('SELECT * FROM artifacts ORDER BY created_at').all() as Row[]).map((r) => ({+ return (this.db.prepare('SELECT * FROM artifacts ORDER BY created_at').all() as Row[]).map((r) => this.toArtifact(r))+ }++ artifact(id: string): Artifact | undefined {+ const r = this.db.prepare('SELECT * FROM artifacts WHERE id = ?').get(id) as Row | undefined+ return r && this.toArtifact(r)+ }++ private toArtifact(r: Row): Artifact {+ return {id: str(r['id']),agentId: str(r['agent_id']),conversationId: str(r['conversation_id']),@@ -1286,7 +1400,7 @@ export class Db {source: str(r['source']),size: Number(r['size']),createdAt: Number(r['created_at'])- }))+ }}saveArtifact(a: Artifact): void {diff --git a/src/core/engine-check.ts b/src/core/engine-check.tsnew file mode 100644index 0000000..83e1381--- /dev/null+++ b/src/core/engine-check.ts@@ -0,0 +1,147 @@+// What the harnesses' CLIs say about themselves (installed, signed in, the models they list),+// checked without holding anything up: the last check is kept on disk, so the app opens on+// it, and the next one runs behind. A check takes seconds and starts a dozen processes, so+// whoever asks while one runs shares it instead of starting another.+import { readFileSync, renameSync, writeFileSync } from 'node:fs'+import type { EngineId, EngineStatus } from '../shared/types'+import { codexModels, detectClaude, detectCodex, detectCursor, detectGemini, detectGrok, detectOpenCode, detectPi, type CodexModel } from './engines/detect'+import { withInstallDirs } from './platform'++export interface AccountLogin {+ loggedIn: boolean+ detail?: string+}++export interface EngineFindings {+ engines: Record<EngineId, EngineStatus>+ listed: Partial<Record<EngineId, string[]>>+ codexCatalog: CodexModel[]+ accounts?: Record<string, AccountLogin> // the other logins of Settings › Accounts+}++// One harness, checked again on its own (after a sign-in or an install in a terminal).+export interface OneFinding {+ status: EngineStatus+ listed?: string[]+ codexCatalog?: CodexModel[]+}++const IDS: EngineId[] = ['claude', 'codex', 'opencode', 'pi', 'gemini', 'cursor', 'grok']++// Before the first check ever: nothing known yet, and the screens can say so.+export const checkingFindings = (): EngineFindings => ({+ engines: Object.fromEntries(IDS.map((e) => [e, { installed: false, loggedIn: false, checking: true }])) as Record<EngineId, EngineStatus>,+ listed: {},+ codexCatalog: []+})++export interface EngineCheckDeps {+ all: () => Promise<Omit<EngineFindings, 'accounts'>>+ one: (engine: EngineId) => Promise<OneFinding>+ // Runs inside the same check, so whoever waits on it gets the accounts too.+ after?: (found: EngineFindings, engine?: EngineId) => Promise<Partial<EngineFindings> | void>+ file?: string // where the last check is kept+}++export class EngineCheck {+ current: EngineFindings+ // Whether `current` came from a check, this run's or the last one's, rather than a guess.+ known: boolean+ private all?: Promise<EngineFindings>+ private one = new Map<EngineId, Promise<EngineFindings>>()++ constructor(private deps: EngineCheckDeps) {+ const kept = deps.file ? readKept(deps.file) : undefined+ this.current = kept ?? checkingFindings()+ this.known = !!kept+ }++ // Every harness. A call while a check runs gets that check.+ detect(): Promise<EngineFindings> {+ return (this.all ??= this.run(async () => ({ ...(await this.deps.all()), accounts: this.current.accounts })).finally(() => (this.all = undefined)))+ }++ // Only this harness, unless every one is being checked already.+ recheck(engine: EngineId): Promise<EngineFindings> {+ if (this.all) return this.all+ let p = this.one.get(engine)+ if (!p) {+ p = this.run(async () => {+ const f = await this.deps.one(engine)+ const listed = { ...this.current.listed }+ // As detectEngines lists them: Codex only with a catalog, Claude Code never.+ if (f.listed && (engine !== 'codex' || f.listed.length)) listed[engine] = f.listed+ else delete listed[engine]+ return { ...this.current, engines: { ...this.current.engines, [engine]: f.status }, listed, ...(engine === 'codex' ? { codexCatalog: f.codexCatalog ?? [] } : {}) }+ }, engine).finally(() => this.one.delete(engine))+ this.one.set(engine, p)+ }+ return p+ }++ // Kept as the latest (and on disk) once `after` has had its say.+ private async run(find: () => Promise<EngineFindings>, engine?: EngineId): Promise<EngineFindings> {+ const found = await find()+ const more = (await this.deps.after?.(found, engine)) ?? {}+ this.current = { ...found, ...more }+ this.known = true+ this.save()+ return this.current+ }++ // The accounts change apart from a check too (one signed in, one added).+ setAccounts(accounts: Record<string, AccountLogin>): void {+ this.current = { ...this.current, accounts }+ if (this.known) this.save()+ }++ private save(): void {+ if (!this.deps.file) return+ try {+ // Written aside and moved in: a crash mid-write can't leave half a file to read next time.+ writeFileSync(`${this.deps.file}.tmp`, JSON.stringify(this.current))+ renameSync(`${this.deps.file}.tmp`, this.deps.file)+ } catch (e) {+ console.warn('[engines] could not keep the last check', e)+ }+ }+}++function readKept(file: string): EngineFindings | undefined {+ try {+ const f = JSON.parse(readFileSync(file, 'utf8')) as Partial<EngineFindings>+ if (!f.engines || typeof f.engines !== 'object') return undefined+ // A harness this version knows and the last check didn't: unknown until checked.+ const engines = Object.fromEntries(IDS.map((e) => [e, f.engines![e] ?? { installed: false, loggedIn: false, checking: true }])) as Record<EngineId, EngineStatus>+ return { engines, listed: f.listed ?? {}, codexCatalog: f.codexCatalog ?? [], ...(f.accounts ? { accounts: f.accounts } : {}) }+ } catch {+ return undefined+ }+}++// One harness's own check, the same detectEngines runs for each.+export async function detectEngine(engine: EngineId, codexHome: string): Promise<OneFinding> {+ // A CLI installed while the app is open may have created its folder just now.+ process.env['PATH'] = withInstallDirs(process.env['PATH'] ?? '')+ switch (engine) {+ case 'claude':+ return { status: await detectClaude() }+ case 'codex': {+ const status = await detectCodex(codexHome)+ // A gateway serves its own list (asked when picking); a plan or an API key gets Codex's catalog.+ const codexCatalog = status.loggedIn && status.route !== 'gateway' && status.path ? await codexModels(status.path, codexHome) : []+ return { status, codexCatalog, listed: codexCatalog.map((m) => m.slug) }+ }+ case 'opencode':+ return found(await detectOpenCode())+ case 'pi':+ return found(await detectPi())+ case 'gemini':+ return found(await detectGemini())+ case 'cursor':+ return found(await detectCursor())+ case 'grok':+ return found(await detectGrok())+ }+}+const found = (r: { status: EngineStatus; models: string[] }): OneFinding => ({ status: r.status, listed: r.models })diff --git a/src/core/engines/claude.ts b/src/core/engines/claude.tsindex e44f1ed..b1d007e 100644--- a/src/core/engines/claude.ts+++ b/src/core/engines/claude.ts@@ -7,6 +7,7 @@ import { L } from '../../shared/lang'export const GATEWAY_NAME = 'tucano'const WEB_TOOLS = ['WebSearch', 'WebFetch'] // run on Anthropic's side, on the subscription+const TOOL_SEARCH = 'ToolSearch' // loads a deferred MCP tool by name; touches nothing on the computer// How the user's own Claude Code reaches the model, from their settings.json:// the `env` block (a company gateway: ANTHROPIC_BASE_URL and its token, or@@ -34,11 +35,16 @@ export function userProvider(dir = process.env['CLAUDE_CONFIG_DIR'] || join(home// --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.+// With the gateway, also ToolSearch: without it the CLI turns tool search off and puts every+// connector tool in every model call (measured: 198 tools, 239k tokens a call, up to 7.8 s to the+// first token; with it, 11k). The CLI then lists the connector tools by name and the model loads+// the ones it needs; the app's own tools stay in the prompt (ALWAYS_LOAD in the gateway).export const GATEWAY_ENV = 'TUCANO_MCP_URL'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 search = turn.mcpUrl ? [TOOL_SEARCH] : []+ const allowed = [...(turn.mcpUrl ? [`mcp__${GATEWAY_NAME}`] : []), ...search, ...web]// The address carries the gateway's token: the CLI fills it in from the environment, so it// never shows in the arguments, which any program on the computer can list.const gateway = turn.mcpUrl ? ['--mcp-config', JSON.stringify({ mcpServers: { [GATEWAY_NAME]: { type: 'http', url: `\${${GATEWAY_ENV}}` } } })] : []@@ -51,7 +57,7 @@ export function claudeArgs(turn: Pick<Turn, 'model' | 'effort' | 'system' | 'mcp'--model', turn.model,'--effort', turn.effort,'--system-prompt', turn.system,- '--tools', web.join(','),+ '--tools', [...search, ...web].join(','),'--strict-mcp-config','--setting-sources', '',...(turn.session ? [turn.session.resume ? '--resume' : '--session-id', turn.session.id] : ['--no-session-persistence']),@@ -197,10 +203,11 @@ const configDirOf = (account?: string): string => account || process.env['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.+// from disk in a new process instead. Two were too few for a team: switching between three agents+// started a process on every reply.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+export const KEEP_IDLE_MS = 10 * 60_000+export const MAX_IDLE = 4// A process started ahead of a turn with no session (the router's) waits this long, and only this// many wait: it's started while the person types, so the message comes soon or not at all.export const SPARE_MS = 2 * 60_000diff --git a/src/core/engines/codex-app.ts b/src/core/engines/codex-app.tsnew file mode 100644index 0000000..265112b--- /dev/null+++ b/src/core/engines/codex-app.ts@@ -0,0 +1,825 @@+// Codex as a long-lived `codex app-server` (JSON-RPC over stdio) instead of one `codex exec` per+// turn. One process per login and provider holds every agent's thread: a turn goes on from the+// thread's last one with only what's new (kept on disk, so a thread unloaded or a process gone is+// resumed from there), its text streams as it's written, and a process with a thread ready is+// started while the person types. Method and event names are those of `codex app-server+// generate-ts` (Codex 0.153).+//+// Isolated as `codex exec` is (see codexArgs): the same features off, read-only sandbox in the+// agent's empty folder, no approvals asked, no skills or project docs, the gateway as the only MCP+// server, and a home of the app's own. What exec takes as flags with no app-server equivalent:+// --ignore-user-config and --ignore-rules skip the config.toml and the rules in that home, so with+// either there the engine runs exec instead (see `isolated`); --ephemeral: a thread kept for a+// session is written to that home and deleted with thread/delete when the session goes, and at the+// next start whatever an earlier run left of the agents' threads (see `clean`).+import { spawn, type ChildProcess } from 'node:child_process'+import { closeSync, existsSync, openSync, readdirSync, readSync } from 'node:fs'+import { dirname, join, resolve } from 'node:path'+import { createInterface } from 'node:readline'+import { isWin, killTree, spawnable } from '../platform'+import { lastLines, num, parseJson, type Parser } from './cli'+import type { EngineEvent, Turn, TurnShape, Usage } from './types'+import { L } from '../../shared/lang'++export interface RpcMessage {+ id?: number | string+ method?: string+ params?: Record<string, unknown>+ result?: unknown+ error?: { code: number; message: string }+}++export class RpcError extends Error {+ constructor(+ message: string,+ readonly code?: number+ ) {+ super(message)+ }+}++const METHOD_NOT_FOUND = -32601+const INIT_MS = 30_000+const REQUEST_MS = 60_000++// What the process asks of the client. With approvals off none of these should come, and nothing+// is granted if one does: no command, patch or permission; no answers for the model, no form.+function refusal(method: string): unknown {+ switch (method) {+ case 'item/commandExecution/requestApproval':+ case 'item/fileChange/requestApproval':+ return { decision: 'decline' }+ case 'applyPatchApproval':+ case 'execCommandApproval':+ return { decision: 'denied' }+ case 'item/tool/requestUserInput':+ return { answers: {} }+ case 'mcpServer/elicitation/request':+ return { action: 'decline', content: null, _meta: null }+ case 'item/tool/call':+ return { success: false, contentItems: [] }+ default:+ return undefined // answered with an error+ }+}++// The process: requests and their answers by id, notifications to whoever listens to their thread.+export class AppServer {+ private readonly child: ChildProcess+ private nextId = 1+ private pending = new Map<number, { resolve: (v: unknown) => void; reject: (e: Error) => void; timer: NodeJS.Timeout }>()+ private listeners = new Map<string, Set<(m: RpcMessage) => void>>() // by thread id+ private exits: (() => void)[] = []+ private code: number | null | undefined // set once it exited+ stderr = ''+ readonly ready: Promise<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) => this.receive(line))+ const exit = (code: number | null): void => {+ if (this.code !== undefined) return+ this.code = code+ const err = new RpcError(L(`O Codex saiu (código ${code ?? '?'}).`, `Codex exited (code ${code ?? '?'}).`) + (lastLines(this.stderr) ? `\n${lastLines(this.stderr)}` : ''))+ for (const [, p] of this.pending) {+ clearTimeout(p.timer)+ p.reject(err)+ }+ this.pending.clear()+ for (const set of this.listeners.values()) for (const l of [...set]) l({ method: '$exit' })+ for (const done of this.exits.splice(0)) done()+ }+ this.child.on('close', exit)+ this.child.on('error', (err) => {+ this.stderr += `\n${err.message}`+ exit(-1)+ })+ this.ready = this.request('initialize', { clientInfo: { name: 'tucano', title: 'Tucano', version: '1' }, capabilities: { experimentalApi: false, requestAttestation: false } }, INIT_MS).then(() =>+ this.notify('initialized')+ )+ this.ready.catch(() => this.kill())+ }++ // Also asks the system: on Windows a killed process is gone a while before its exit comes, and a+ // resumed thread sent to it then would fail instead of going to a new process.+ get alive(): boolean {+ if (this.code !== undefined) return false+ const pid = this.child.pid+ if (pid === undefined) return true // still starting (or about to say it couldn't)+ try {+ process.kill(pid, 0)+ return true+ } catch (e) {+ return (e as NodeJS.ErrnoException).code === 'EPERM'+ }+ }++ get exitCode(): number | null | undefined {+ return this.code+ }++ exited(): Promise<void> {+ return this.alive ? new Promise((resolve) => this.exits.push(resolve)) : Promise.resolve()+ }++ request<T = unknown>(method: string, params: unknown, timeoutMs = REQUEST_MS): Promise<T> {+ if (!this.alive) return Promise.reject(new RpcError(L('O Codex já tinha saído.', 'Codex had already exited.')))+ const id = this.nextId+++ return new Promise<T>((resolve, reject) => {+ const timer = setTimeout(() => {+ this.pending.delete(id)+ reject(new RpcError(L(`O Codex não respondeu a ${method}.`, `Codex didn't answer ${method}.`)))+ }, timeoutMs)+ timer.unref()+ this.pending.set(id, { resolve: resolve as (v: unknown) => void, reject, timer })+ this.write({ id, method, params })+ })+ }++ notify(method: string, params?: unknown): void {+ this.write(params === undefined ? { method } : { method, params })+ }++ // Notifications about this thread, until the returned function is called. `$exit` when the process goes.+ listen(threadId: string, fn: (m: RpcMessage) => void): () => void {+ let set = this.listeners.get(threadId)+ if (!set) this.listeners.set(threadId, (set = new Set()))+ set.add(fn)+ return () => {+ set.delete(fn)+ if (!set.size) this.listeners.delete(threadId)+ }+ }++ 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.+ killNow(): void {+ if (this.alive) this.child.kill()+ }++ private write(msg: unknown): void {+ if (this.alive) this.child.stdin!.write(`${JSON.stringify(msg)}\n`)+ }++ private receive(line: string): void {+ const m = parseJson(line) as RpcMessage | null+ if (!m) return+ if (m.id !== undefined && m.method === undefined) {+ const p = typeof m.id === 'number' ? this.pending.get(m.id) : undefined+ if (!p) return+ this.pending.delete(m.id as number)+ clearTimeout(p.timer)+ if (m.error) p.reject(new RpcError(m.error.message, m.error.code))+ else p.resolve(m.result)+ return+ }+ if (m.id !== undefined && m.method) {+ const result = refusal(m.method)+ this.write(result === undefined ? { id: m.id, error: { code: METHOD_NOT_FOUND, message: `${m.method} is not supported` } } : { id: m.id, result })+ return+ }+ const thread = m.params?.['threadId']+ if (typeof thread === 'string') for (const l of [...(this.listeners.get(thread) ?? [])]) l(m)+ }+}++// ---------- one turn's events ----------++type Breakdown = { input: number; cached: number; output: number }+const breakdown = (v: unknown): Breakdown => {+ const b = (v ?? {}) as Record<string, unknown>+ return { input: num(b['inputTokens']), cached: num(b['cachedInputTokens']), output: num(b['outputTokens']) }+}++// A turn's notifications as engine events: the text as it streams (each agent message its own+// paragraph), the running token count, web searches, and how it ended. Pure, so it can be fed the+// output of the real CLI. `line` takes one JSON message, `message` the same already parsed.+export function codexAppParser(): Parser & { message(m: RpcMessage): EngineEvent[]; readonly finished: boolean } {+ const items: { id: string; text: string; streamed: boolean }[] = []+ let base: Breakdown | undefined // the thread's total before this turn+ let total: Breakdown = { input: 0, cached: 0, output: 0 }+ let last: Breakdown = { input: 0, cached: 0, output: 0 }+ let finished = false++ const itemOf = (id: string): (typeof items)[number] => {+ let it = items.find((i) => i.id === id)+ if (!it) items.push((it = { id, text: '', streamed: false }))+ return it+ }+ // A paragraph break before an agent message's first words, when another one wrote before it.+ const sep = (it: (typeof items)[number]): string => (!it.text && items.some((i) => i !== it && i.text) ? '\n\n' : '')+ const usage = (): Usage => ({ inputTokens: total.input - (base?.input ?? 0), cacheReadTokens: total.cached - (base?.cached ?? 0), outputTokens: total.output - (base?.output ?? 0) })++ const message = (m: RpcMessage): EngineEvent[] => {+ if (finished) return []+ const p = m.params ?? {}+ const out: EngineEvent[] = []+ switch (m.method) {+ case 'item/agentMessage/delta': {+ const delta = typeof p['delta'] === 'string' ? p['delta'] : ''+ if (!delta) break+ const it = itemOf(String(p['itemId']))+ const d = sep(it) + delta+ it.text += delta+ it.streamed = true+ out.push({ type: 'text', delta: d })+ break+ }+ case 'item/completed': {+ const item = (p['item'] ?? {}) as Record<string, unknown>+ if (item['type'] === 'agentMessage' && typeof item['text'] === 'string') {+ const it = itemOf(String(item['id']))+ // A message that came whole (no deltas), or more than its deltas said: the rest of it.+ const full = item['text']+ if (full.startsWith(it.text) && full.length > it.text.length) {+ const d = sep(it) + full.slice(it.text.length)+ it.text = full+ out.push({ type: 'text', delta: d })+ } else it.text = full+ } else if (item['type'] === 'webSearch') {+ const action = (item['action'] ?? {}) as Record<string, unknown>+ const url = typeof action['url'] === 'string' ? action['url'] : undefined+ if (url) out.push({ type: 'web', action: 'fetch', detail: url })+ else {+ const queries = Array.isArray(action['queries']) ? action['queries'].filter((q): q is string => typeof q === 'string') : []+ out.push({ type: 'web', action: 'search', detail: String(item['query'] || action['query'] || queries.join(' · ') || '') })+ }+ }+ break+ }+ case 'thread/tokenUsage/updated': {+ const u = (p['tokenUsage'] ?? {}) as Record<string, unknown>+ total = breakdown(u['total'])+ last = breakdown(u['last'])+ // `total` is the thread's, earlier turns included: this turn's starts where the first call's `last` began.+ base ??= { input: total.input - last.input, cached: total.cached - last.cached, output: total.output - last.output }+ const n = usage()+ out.push({ type: 'progress', tokens: n.inputTokens + n.outputTokens, cacheRead: n.cacheReadTokens })+ break+ }+ case 'error': {+ if (p['willRetry'] === true) break // the CLI tries again on its own+ finished = true+ out.push({ type: 'error', message: errorText(p['error']) })+ break+ }+ case 'turn/completed': {+ finished = true+ const turn = (p['turn'] ?? {}) as Record<string, unknown>+ if (turn['status'] === 'completed') {+ out.push({ type: 'done', text: items.map((i) => i.text).filter(Boolean).join('\n\n'), usage: usage(), context: last.input + last.output })+ } else if (turn['status'] === 'failed') out.push({ type: 'error', message: errorText(turn['error']) })+ // interrupted: stopped on purpose, nothing to say+ break+ }+ }+ return out+ }++ return {+ message,+ line(line) {+ const m = parseJson(line) as RpcMessage | null+ return m ? message(m) : []+ },+ end(code, stderr) {+ if (finished) return []+ finished = true+ const detail = lastLines(stderr)+ return [{ type: 'error', message: L(`O Codex saiu sem resposta (código ${code ?? '?'}).`, `Codex exited without a reply (code ${code ?? '?'}).`) + (detail ? `\n${detail}` : '') }]+ },+ get finished() {+ return finished+ }+ }+}++function errorText(e: unknown): string {+ const err = (e ?? {}) as Record<string, unknown>+ const message = typeof err['message'] === 'string' && err['message'] ? err['message'] : L('O Codex terminou com erro.', 'Codex ended with an error.')+ const details = typeof err['additionalDetails'] === 'string' && err['additionalDetails'] ? err['additionalDetails'] : ''+ return details && !message.includes(details) ? `${message}\n${details}` : message+}++const turnOf = (m: RpcMessage): unknown => m.params?.['turnId'] ?? (m.params?.['turn'] as Record<string, unknown> | undefined)?.['id']++// ---------- what each request says ----------++// The turn's text and images, in order: each image right after the block of the message it came with.+export function codexAppInput(turn: Pick<Turn, 'prompt' | 'blocks' | 'images'>): Record<string, unknown>[] {+ const images = (turn.images ?? []).filter((i) => existsSync(i.path))+ const blocks = turn.blocks?.length ? turn.blocks : [turn.prompt]+ const input: Record<string, unknown>[] = []+ blocks.forEach((text, i) => {+ if (text.trim()) input.push({ type: 'text', text, text_elements: [] })+ for (const img of images.filter((x) => x.block === i)) input.push({ type: 'localImage', path: img.path })+ })+ // Images whose block isn't there (a prompt with no blocks): after the text.+ for (const img of images.filter((x) => x.block >= blocks.length)) input.push({ type: 'localImage', path: img.path })+ if (!input.length) input.push({ type: 'text', text: turn.prompt, text_elements: [] })+ return input+}++export interface CodexAppSetup {+ // A thread's settings, for thread/start and thread/resume: model, effort, instructions, folder, web, gateway.+ thread(turn: TurnShape): Record<string, unknown>+}++// ---------- the engine's processes and threads ----------++// A thread kept after a reply waits this long for the next one loaded, with its gateway connection+// open, and only this many wait: past either it's unloaded, and the next reply resumes it from disk+// (in the same process, if it's still up). A process with no thread loaded closes after a while.+// Threads share their process (about 85 MB, a loaded thread adds little), so more wait than Claude Code's.+export const KEEP_IDLE_MS = 5 * 60_000+export const MAX_IDLE = 4+export const SPARE_MS = 2 * 60_000 // a thread started ahead of a turn with no session (the router's)+export const MAX_SPARES = 2+export const HOST_IDLE_MS = 2 * 60_000+const INTERRUPT_MS = 5_000 // a stopped turn that hasn't ended by then: its process goes++export interface Launch {+ key: string // the process's home, provider and variables: threads share a process only with the same+ home: string // CODEX_HOME+ args: string[] // what's the same for every thread (features off, skills, project docs, the provider)+ env: NodeJS.ProcessEnv+ cwd: string+}++interface Host {+ bin: string+ key: string+ home: string+ server: AppServer+ loaded: Set<string> // threads loaded in it+ turns: number+ timer?: NodeJS.Timeout+}++interface Kept {+ threadId: string+ home: string+ shape: TurnShape+ host?: Host // where it's loaded+ timer?: NodeJS.Timeout+ usedAt: number+ busy: Promise<void> // the turn or the resume going on+}++interface Spare {+ host: Host+ threadId: Promise<string>+ timer: NodeJS.Timeout+ at: number+}++// Why the app-server can't take a turn at all (an old CLI): then the turn goes to exec.+export class Unsupported extends Error {}++export class CodexApp {+ private hosts = new Map<string, Promise<Host>>()+ private servers = new Map<string, AppServer>() // each host's process, to tell a dead one before its exit comes+ private kept = new Map<string, Kept>() // by session id+ private spares = new Map<string, Spare>()+ private removing = new Set<Promise<void>>()+ private unsupported = new Set<string>() // binaries whose app-server didn't start+ private later: ((bin: string) => void) | undefined // a clean asked for before the CLI was found++ constructor(private readonly setup: CodexAppSetup) {}++ supports(bin: string): boolean {+ return !this.unsupported.has(bin)+ }++ // ---- processes ----++ private host(bin: string, l: Launch): Promise<Host> {+ const key = JSON.stringify([bin, l.key])+ const had = this.hosts.get(key)+ if (had && this.servers.get(key)?.alive !== false) return had+ const server = new AppServer({ bin, args: l.args, cwd: l.cwd, env: l.env })+ this.servers.set(key, server)+ const host: Host = { bin, key, home: l.home, server, loaded: new Set(), turns: 0 }+ const ready = server.ready.then(+ () => host,+ (e: unknown) => {+ if (this.hosts.get(key) === ready) this.hosts.delete(key)+ // It never answered initialize: this CLI has no app-server (or not this one).+ if (!(e instanceof RpcError) || e.code === undefined || e.code === METHOD_NOT_FOUND) this.unsupported.add(bin)+ throw new Unsupported(e instanceof Error ? e.message : String(e))+ }+ )+ this.hosts.set(key, ready)+ const later = this.later+ this.later = undefined+ later?.(bin)+ void server.exited().then(() => {+ if (this.hosts.get(key) === ready) this.hosts.delete(key)+ if (this.servers.get(key) === server) this.servers.delete(key)+ if (host.timer) clearTimeout(host.timer)+ for (const k of this.kept.values()) if (k.host === host) this.unpark(k)+ for (const [sk, s] of this.spares) if (s.host === host) this.dropSpare(sk)+ })+ this.idle(host)+ return ready+ }++ // A process with nothing loaded and no turn closes after a while.+ private idle(host: Host): void {+ if (host.timer) clearTimeout(host.timer)+ host.timer = undefined+ if (host.loaded.size || host.turns || !host.server.alive) return+ host.timer = setTimeout(() => {+ if (!host.loaded.size && !host.turns) host.server.kill()+ }, HOST_IDLE_MS)+ host.timer.unref()+ }++ // A new thread. Failing, it throws Unsupported: the turn can still go to exec, with everything.+ private async start(host: Host, shape: TurnShape, ephemeral: boolean): Promise<string> {+ let id: string | undefined+ try {+ const r = await host.server.request<{ thread?: { id?: string } }>('thread/start', { ...this.setup.thread(shape), ephemeral })+ id = r?.thread?.id+ } catch (e) {+ if (e instanceof RpcError && e.code === METHOD_NOT_FOUND) this.unsupported.add(host.bin)+ throw new Unsupported(e instanceof Error ? e.message : String(e))+ }+ if (!id) throw new Unsupported('thread/start: no thread id')+ host.loaded.add(id)+ this.idle(host)+ return id+ }++ private unload(host: Host | undefined, threadId: string): Promise<void> {+ if (!host) return Promise.resolve()+ host.loaded.delete(threadId)+ const gone = host.server.alive ? host.server.request('thread/unsubscribe', { threadId }).then(() => {}, () => {}) : Promise.resolve()+ this.idle(host)+ return gone+ }++ // ---- one turn on a loaded thread ----++ private async *turn(host: Host, threadId: string, turn: Turn, settled: (p: Promise<void>) => void): AsyncIterable<EngineEvent> {+ const parser = codexAppParser()+ const queue: RpcMessage[] = []+ let wake: (() => void) | null = null+ let turnId: string | undefined+ let ended!: () => void+ const completed = new Promise<void>((r) => (ended = r))+ settled(completed)+ const over = new Set<unknown>() // turns that ended, by id+ const off = host.server.listen(threadId, (m) => {+ if (m.method === 'turn/completed') over.add(turnOf(m))+ if (m.method === '$exit' || (turnId && over.has(turnId))) ended()+ queue.push(m)+ wake?.()+ })+ host.turns+++ if (host.timer) clearTimeout(host.timer)+ const interrupt = (): void => {+ wake?.()+ if (!turnId) return+ void host.server.request('turn/interrupt', { threadId, turnId }, INTERRUPT_MS).catch(() => {})+ // A turn that doesn't stop takes its process with it: a stop always ends the turn.+ const t = setTimeout(() => host.server.kill(), INTERRUPT_MS)+ t.unref()+ void completed.then(() => clearTimeout(t))+ }+ const finish = (): void => {+ off()+ ended()+ host.turns--+ this.idle(host)+ }+ try {+ if (turn.signal.aborted) return+ const started = await host.server+ .request<{ turn?: { id?: string } }>('turn/start', { threadId, input: codexAppInput(turn) })+ .then((r) => r?.turn?.id)+ .catch((e: unknown) => (e instanceof Error ? e : new Error(String(e))))+ if (started instanceof Error) {+ if (!turn.signal.aborted) yield { type: 'error', message: started.message }+ return+ }+ turnId = started+ if (over.has(turnId)) ended()+ if (turn.signal.aborted) return interrupt()+ turn.signal.addEventListener('abort', interrupt, { once: true })+ try {+ for (;;) {+ if (turn.signal.aborted) return+ const m = queue.shift()+ if (m) {+ if (m.method === '$exit') {+ yield* parser.end(host.server.exitCode ?? null, host.server.stderr)+ return+ }+ const id = turnOf(m)+ if (id !== undefined && id !== turnId) continue // a turn before this one, ending late+ yield* parser.message(m)+ if (parser.finished) return+ continue+ }+ await new Promise<void>((r) => (wake = r))+ wake = null+ }+ } finally {+ turn.signal.removeEventListener('abort', interrupt)+ }+ } finally {+ // Stopped: the listener stays until the turn has really ended, so the thread is free after.+ if (turn.signal.aborted && turnId && host.server.alive) void Promise.race([completed, host.server.exited()]).then(finish)+ else finish()+ }+ }++ // ---- what the engine calls ----++ // A turn with no session: a thread of its own, not written to disk, unloaded after.+ async *oneShot(bin: string, turn: Turn, l: Launch): AsyncIterable<EngineEvent> {+ const { prompt: _p, blocks: _b, images: _i, signal: _s, session: _n, ...shape } = turn+ const sk = JSON.stringify([bin, l.key, this.setup.thread(shape)])+ const spare = this.spares.get(sk)+ let host: Host+ let threadId: string+ if (spare?.host.server.alive) {+ this.spares.delete(sk)+ clearTimeout(spare.timer)+ host = spare.host+ try {+ threadId = await spare.threadId+ } catch {+ return yield* this.oneShot(bin, turn, l) // that one didn't start: a new one+ }+ } else {+ host = await this.host(bin, l)+ threadId = await this.start(host, shape, true)+ }+ try {+ yield* this.turn(host, threadId, turn, () => {})+ } finally {+ void this.unload(host, threadId)+ }+ }++ // A turn of a kept session: a new thread when it starts, the same one when it goes on.+ async *session(bin: string, turn: Turn & { session: NonNullable<Turn['session']> }, l: Launch): AsyncIterable<EngineEvent> {+ const { prompt: _p, blocks: _b, images: _i, signal: _s, session, ...shape } = turn+ let k = this.kept.get(session.id)+ if (!session.resume || !k) {+ if (session.resume) {+ yield { type: 'error', message: L('O Codex não tem mais essa conversa; ela recomeça na próxima resposta.', "Codex no longer has this conversation; it starts over on the next reply.") }+ return+ }+ if (k) this.release(bin, session.id, async () => l)+ const host = await this.host(bin, l)+ const threadId = await this.start(host, shape, false)+ k = { threadId, home: l.home, shape, host, usedAt: Date.now(), busy: Promise.resolve() }+ this.kept.set(session.id, k)+ } else {+ await k.busy // a rewarm resuming it, or a stopped turn still ending+ if (this.kept.get(session.id) !== k) {+ yield { type: 'error', message: L('O Codex não tem mais essa conversa; ela recomeça na próxima resposta.', "Codex no longer has this conversation; it starts over on the next reply.") }+ return+ }+ k.shape = shape+ const err = await this.load(bin, k, l)+ if (err) {+ yield { type: 'error', message: err }+ return+ }+ }+ if (k.timer) clearTimeout(k.timer)+ k.timer = undefined // in a turn, not waiting+ const current = k+ const host = current.host!+ let done = false+ try {+ for await (const ev of this.turn(host, current.threadId, turn, (p) => (current.busy = p))) {+ if (ev.type === 'done') done = true+ yield ev+ }+ } finally {+ if (this.kept.get(session.id) === current) {+ if (done && session.keep && !turn.signal.aborted && host.server.alive) this.park(current)+ else+ void current.busy.then(() => {+ if (this.kept.get(session.id) === current && current.host === host) this.unpark(current)+ })+ }+ }+ }++ // The thread loaded in a process with this turn's settings: as it is, or resumed from disk.+ private async load(bin: string, k: Kept, l: Launch): Promise<string | undefined> {+ const key = JSON.stringify([bin, l.key])+ if (k.host?.server.alive && k.host.key === key) return+ if (k.host) {+ this.unpark(k) // another process (the provider changed): it leaves that one first+ await k.busy+ }+ try {+ const host = await this.host(bin, l)+ await host.server.request('thread/resume', { threadId: k.threadId, ...this.setup.thread(k.shape) })+ host.loaded.add(k.threadId)+ k.host = host+ this.idle(host)+ return+ } catch (e) {+ return e instanceof Error ? e.message : String(e)+ }+ }++ private park(k: Kept): void {+ if (k.timer) clearTimeout(k.timer)+ k.usedAt = Date.now()+ k.timer = setTimeout(() => this.unpark(k), KEEP_IDLE_MS)+ k.timer.unref()+ // Waiting past the cap: the one waiting longest is unloaded.+ const idle = [...this.kept.values()].filter((x) => x.host && x.timer).sort((a, b) => a.usedAt - b.usedAt)+ for (const x of idle.slice(0, Math.max(0, idle.length - MAX_IDLE))) this.unpark(x)+ }++ // Unloaded; what comes next for the thread waits for that (a resume, its deletion).+ private unpark(k: Kept): void {+ if (k.timer) clearTimeout(k.timer)+ k.timer = undefined+ const host = k.host+ k.host = undefined+ if (!host) return+ const gone = this.unload(host, k.threadId)+ k.busy = Promise.all([k.busy, gone]).then(() => {})+ }++ warm(bin: string, shape: TurnShape, l: Launch): void {+ const sk = JSON.stringify([bin, l.key, this.setup.thread(shape)])+ const had = this.spares.get(sk)+ if (had?.host.server.alive) {+ clearTimeout(had.timer)+ had.timer = setTimeout(() => this.spares.get(sk) === had && this.dropSpare(sk), SPARE_MS)+ had.timer.unref()+ return+ }+ if (had) this.dropSpare(sk)+ void this.host(bin, l).then(+ (host) => {+ if (this.spares.has(sk)) return+ const threadId = this.start(host, shape, true)+ threadId.catch(() => this.spares.get(sk) === spare && this.dropSpare(sk))+ const spare: Spare = { host, threadId, at: Date.now(), timer: setTimeout(() => this.spares.get(sk) === spare && this.dropSpare(sk), SPARE_MS) }+ spare.timer.unref()+ this.spares.set(sk, spare)+ const oldest = [...this.spares].sort((a, b) => a[1].at - b[1].at)+ for (const [o] of oldest.slice(0, Math.max(0, oldest.length - MAX_SPARES))) this.dropSpare(o)+ },+ () => {}+ )+ }++ private dropSpare(sk: string): void {+ const s = this.spares.get(sk)+ if (!s) return+ this.spares.delete(sk)+ clearTimeout(s.timer)+ void s.threadId.then(+ (id) => this.unload(s.host, id),+ () => {}+ )+ }++ // The session's thread loaded again ahead of its next turn, if it was unloaded.+ rewarm(bin: string, sessionId: string, launch: (shape: TurnShape) => Promise<Launch>): void {+ const k = this.kept.get(sessionId)+ if (!k) return+ if (k.host?.server.alive) {+ if (k.timer) this.park(k) // loaded and waiting: it waits a while longer+ return+ }+ const step = k.busy.then(async () => {+ if (this.kept.get(sessionId) !== k || k.host) return+ if (!(await this.load(bin, k, await launch(k.shape)))) this.park(k)+ })+ k.busy = step.catch(() => {})+ }++ // A session that won't be resumed: its thread leaves the process and the disk.+ release(bin: string | undefined, sessionId: string, launch: (shape: TurnShape) => Promise<Launch>): void {+ const k = this.kept.get(sessionId)+ if (!k) return+ this.kept.delete(sessionId)+ if (k.timer) clearTimeout(k.timer)+ const gone = k.busy+ .then(async () => {+ const host = k.host?.server.alive ? k.host : bin ? await this.host(bin, await launch(k.shape)) : undefined+ if (!host) return+ k.host = undefined+ host.loaded.delete(k.threadId)+ await host.server.request('thread/unsubscribe', { threadId: k.threadId }).catch(() => {})+ await host.server.request('thread/delete', { threadId: k.threadId }).catch(() => {})+ this.idle(host)+ })+ .catch(() => {})+ this.removing.add(gone)+ void gone.finally(() => this.removing.delete(gone))+ }++ // Threads an earlier run of the app left on disk, of the agents under workDir: deleted through+ // a process of their home's, which takes the thread's history out of its databases too.+ clean(bin: string | undefined, workDir: string, homes: string[], launch: (home: string) => Launch): void {+ if (!bin) {+ this.later = (b) => this.clean(b, workDir, homes, launch) // at the app's start the CLI may not be found yet+ return+ }+ const dir = resolve(workDir)+ const mine = new Set([...this.kept.values()].map((k) => k.threadId))+ for (const home of homes) {+ const left = leftThreads(home).filter((t) => t.cwd && resolve(dirname(t.cwd)) === dir && !mine.has(t.id))+ if (!left.length) continue+ const gone = this.host(bin, launch(home))+ .then(async (host) => {+ for (const t of left) await host.server.request('thread/delete', { threadId: t.id }).catch(() => {})+ this.idle(host)+ })+ .catch(() => {})+ this.removing.add(gone)+ void gone.finally(() => this.removing.delete(gone))+ }+ }++ async settle(): Promise<void> {+ await Promise.all([...this.removing])+ }++ dispose(): void {+ for (const k of this.kept.values()) if (k.timer) clearTimeout(k.timer)+ for (const s of this.spares.values()) clearTimeout(s.timer)+ this.kept.clear()+ this.spares.clear()+ for (const h of this.hosts.values()) void h.then((host) => host.server.killNow(), () => {})+ this.hosts.clear()+ }+}++// The threads written to a Codex home (CODEX_HOME), with the folder each ran in, from the first+// line of its file (sessions/YYYY/MM/DD/rollout-<time>-<id>.jsonl).+export function leftThreads(home: string): { id: string; cwd?: string; file: string }[] {+ const out: { id: string; cwd?: string; file: string }[] = []+ const walk = (d: string, depth: number): void => {+ let names: string[]+ try {+ names = readdirSync(d)+ } catch {+ return+ }+ for (const n of names) {+ const p = join(d, n)+ if (depth < 3) walk(p, depth + 1)+ else if (/^rollout-.*\.jsonl$/.test(n)) {+ const meta = parseJson(firstLine(p))+ const payload = (meta?.['payload'] ?? {}) as Record<string, unknown>+ if (meta?.['type'] !== 'session_meta' || typeof payload['id'] !== 'string') continue+ out.push({ id: payload['id'], ...(typeof payload['cwd'] === 'string' ? { cwd: payload['cwd'] } : {}), file: p })+ }+ }+ }+ walk(join(home, 'sessions'), 0)+ return out+}++// The first line of a file, read in pieces (the first line of a thread holds Codex's whole prompt).+function firstLine(file: string, max = 4 << 20): string {+ let fd: number | undefined+ try {+ fd = openSync(file, 'r')+ const chunks: Buffer[] = []+ const buf = Buffer.alloc(64 << 10)+ for (let read = 0; read < max; ) {+ const n = readSync(fd, buf, 0, buf.length, read)+ if (!n) break+ const nl = buf.subarray(0, n).indexOf(10)+ chunks.push(Buffer.from(buf.subarray(0, nl < 0 ? n : nl)))+ if (nl >= 0) break+ read += n+ }+ return Buffer.concat(chunks).toString('utf8')+ } catch {+ return ''+ } finally {+ if (fd !== undefined) closeSync(fd)+ }+}diff --git a/src/core/engines/codex.ts b/src/core/engines/codex.tsindex a1ce4ce..f0f73a5 100644--- a/src/core/engines/codex.ts+++ b/src/core/engines/codex.ts@@ -4,7 +4,8 @@ import { join } from 'node:path'import { parse } from 'smol-toml'import { GATEWAY_NAME } from './claude'import { lastLines, num, parseJson, runCli, type Parser } from './cli'-import type { Engine, EngineEvent, Turn } from './types'+import { CodexApp, Unsupported, type Launch } from './codex-app'+import type { Engine, EngineEvent, Turn, TurnShape } from './types'import { L } from '../../shared/lang'// Codex reads AGENTS.md, skills, plugins and memories from the user's home no@@ -93,6 +94,9 @@ const sandboxNote = (): string =>"Codex's own sandbox here is read-only and empty on purpose: it isn't your computer, and its apply_patch and shell don't reach it. Your files are on your computer: create and change them with write_file and edit_file, which do work.")+// The agent's instructions, with the sandbox note when it has a computer.+export const codexInstructions = (turn: Pick<Turn, 'system' | 'mcpUrl'>): string => (turn.mcpUrl && turn.system.includes('write_file') ? `${turn.system}\n\n${sandboxNote()}` : turn.system)+export function codexArgs(turn: Pick<Turn, 'model' | 'effort' | 'system' | 'cwd' | 'mcpUrl' | 'web' | 'images'>, provider: string[] = []): string[] {const gateway = turn.mcpUrl? [@@ -114,7 +118,7 @@ export function codexArgs(turn: Pick<Turn, 'model' | 'effort' | 'system' | 'cwd''-C', turn.cwd,'-m', turn.model,'-c', `model_reasoning_effort=${JSON.stringify(turn.effort)}`,- '-c', `developer_instructions=${JSON.stringify(turn.mcpUrl && turn.system.includes('write_file') ? `${turn.system}\n\n${sandboxNote()}` : turn.system)}`,+ '-c', `developer_instructions=${JSON.stringify(codexInstructions(turn))}`,'-c', 'skills.include_instructions=false','-c', 'skills.bundled.enabled=false','-c', `web_search=${turn.web ? '"live"' : '"disabled"'}`,@@ -175,25 +179,137 @@ export function codexParser(): Parser {}}+// The same isolation as codexArgs, for `codex app-server`: what's the same for every thread goes in+// the process's flags; the rest (model, effort, instructions, folder, web, the gateway) in each+// thread's settings (web search on or off always said there), sent over stdin, so the gateway's+// address and its token never show in the arguments. The app-server has no --ignore-user-config or --ignore-rules: see codexIsolated.+// mcp_optional_startup_grace_ms=0: since Codex 0.147 a turn may start before an MCP server is up,+// and then goes without its tools; this waits for the gateway (local, quick to answer).+export function codexAppArgs(provider: string[] = []): string[] {+ return [+ 'app-server',+ ...CODEX_DISABLED_FEATURES.flatMap((f) => ['--disable', f]),+ '-c', 'sandbox_mode="read-only"',+ '-c', 'approval_policy="never"',+ '-c', 'skills.include_instructions=false',+ '-c', 'skills.bundled.enabled=false',+ '-c', 'project_doc_max_bytes=0',+ '-c', 'history.persistence="none"',+ '-c', 'mcp_optional_startup_grace_ms=0',+ ...provider+ ]+}++export function codexThread(turn: TurnShape): Record<string, unknown> {+ return {+ model: turn.model,+ cwd: turn.cwd,+ sandbox: 'read-only',+ approvalPolicy: 'never',+ developerInstructions: codexInstructions(turn),+ config: {+ model_reasoning_effort: turn.effort,+ web_search: turn.web ? 'live' : 'disabled',+ ...(turn.mcpUrl ? { [`mcp_servers.${GATEWAY_NAME}`]: { url: turn.mcpUrl, default_tools_approval_mode: 'approve', tool_timeout_sec: 900 } } : {})+ }+ }+}++// What --ignore-user-config and --ignore-rules leave out, absent from the home: then the+// app-server loads nothing exec wouldn't. With either there, Codex runs as exec.+export const codexIsolated = (codexHome: string): boolean => !existsSync(join(codexHome, 'config.toml')) && !existsSync(join(codexHome, 'rules'))++// Each turn as one `codex exec` (the CLI before the app-server, or a home that has its own+// config): it gets the whole conversation every time.+const EXEC_ONLY = 'TUCANO_CODEX_EXEC'+export function codexEngine(bin: () => string | undefined,home: string,shellEnv: () => Promise<NodeJS.ProcessEnv> = async () => ({}),provider: () => Promise<CodexProvider & { env?: Record<string, string> }> = async () => userCodexProvider()): Engine {+ const codexHome = (account?: string): string => join(account ?? home, '.codex')+ const notIsolated = new Set<string>() // homes found with a config of their own+ const isolated = (account?: string): boolean => {+ const h = codexHome(account)+ if (codexIsolated(h)) return true+ notIsolated.add(h)+ return false+ }+ // The gateway's key lives in the user's shell (.zshrc), which an app opened from Finder doesn't get.+ const launch = async (t: Pick<TurnShape, 'account'>): Promise<{ env: NodeJS.ProcessEnv; config: string[]; launch: Launch }> => {+ const p = await provider()+ const shell = await shellEnv() // read once per launch+ const keys = Object.fromEntries(p.envNames.flatMap((n) => (shell[n] ? [[n, shell[n]]] : [])))+ const env = { ...codexEnv(t.account ?? home), ...keys, ...p.env }+ return { env, config: p.config, launch: { key: JSON.stringify([t.account ?? home, p.config, keys, p.env ?? {}]), home: codexHome(t.account), args: codexAppArgs(p.config), env, cwd: t.account ?? home } }+ }+ const app = new CodexApp({ thread: codexThread })+ const appLaunch = async (t: Pick<TurnShape, 'account'>): Promise<Launch> => (await launch(t)).launch+ // Whether this turn can go to the app-server: one that resumes a session has to.+ const usable = (path: string, account?: string): boolean => !process.env[EXEC_ONLY] && app.supports(path) && isolated(account)++ const exec = (path: string, turn: Turn, l: { env: NodeJS.ProcessEnv; config: string[] }): AsyncIterable<EngineEvent> =>+ runCli({ bin: path, args: codexArgs(turn, l.config), stdin: turn.prompt, cwd: turn.cwd, signal: turn.signal, parser: codexParser(), env: l.env })+return {id: 'codex',+ // Sessions only while every turn can go to the app-server; otherwise each gets the whole conversation.+ get sessions() {+ const path = bin()+ return !!path && !notIsolated.size && usable(path)+ },async *run(turn) {const path = bin()if (!path) {yield { type: 'error', message: L('O Codex não está instalado. Veja em Configurações.', "Codex isn't installed. See Settings.") }return}- // The gateway's key lives in the user's shell (.zshrc), which an app opened from Finder doesn't get.- const p = await provider()- const shell = await shellEnv() // read once per launch- const keys = Object.fromEntries(p.envNames.flatMap((n) => (shell[n] ? [[n, shell[n]]] : [])))- yield* runCli({ bin: path, args: codexArgs(turn, p.config), stdin: turn.prompt, cwd: turn.cwd, signal: turn.signal, parser: codexParser(), env: { ...codexEnv(turn.account ?? home), ...keys, ...p.env } })- }+ const l = await launch(turn)+ if (!usable(path, turn.account)) {+ if (turn.session?.resume) {+ yield { type: 'error', message: L('O Codex não tem mais essa conversa; ela recomeça na próxima resposta.', "Codex no longer has this conversation; it starts over on the next reply.") }+ return+ }+ yield* exec(path, turn, l)+ return+ }+ const session = turn.session+ const events = session ? app.session(path, { ...turn, session }, l.launch) : app.oneShot(path, turn, l.launch)+ let any = false+ try {+ for await (const ev of events) {+ any = true+ yield ev+ }+ } catch (e) {+ if (!(e instanceof Unsupported) || any) throw e+ // No app-server to take it (an old CLI): exec does, with everything, and from now on. A+ // session's first turn only then: the next would come with only what's new.+ if (session && app.supports(path)) {+ yield { type: 'error', message: e.message }+ return+ }+ yield* exec(path, turn, l)+ }+ },+ warm(turn) {+ const path = bin()+ if (!path || !usable(path, turn.account)) return+ void appLaunch(turn).then((l) => app.warm(path, turn, l), () => {})+ },+ rewarm(id) {+ const path = bin()+ if (path) app.rewarm(path, id, appLaunch)+ },+ release(id) {+ app.release(bin(), id, appLaunch)+ },+ clean(workDir, accountDirs = []) {+ app.clean(bin(), workDir, [home, ...accountDirs].map((h) => codexHome(h)), (h) => ({ key: JSON.stringify(['clean', h]), home: h, args: codexAppArgs(), env: codexEnv(join(h, '..')), cwd: join(h, '..') }))+ },+ settle: () => app.settle(),+ dispose: () => app.dispose()}}diff --git a/src/core/engines/fake.ts b/src/core/engines/fake.tsindex 21e0e0b..935e567 100644--- a/src/core/engines/fake.ts+++ b/src/core/engines/fake.ts@@ -43,7 +43,7 @@ export function fakeEngine(id: Engine['id'], opts: { delayMs?: number; reply?: (reply = JSON.stringify(fakeCuration(turn.prompt))} else if (opts.reply) {reply = opts.reply(turn)- } else if (turn.mcpUrl && (turn.system.includes('## Pra montar agentes') || turn.system.includes('## For building agents'))) {+ } else if (turn.mcpUrl && (`${turn.system}\n${turn.prompt}`.includes('## Pra montar agentes') || `${turn.system}\n${turn.prompt}`.includes('## For building agents'))) {// The Tuca: asks once, then proposes a support agent.if (/suporte|ticket|cliente|support|customer/i.test(last)) {const r = await callTool(turn.mcpUrl, 'propor_agente', {diff --git a/src/core/gateway.ts b/src/core/gateway.tsindex 1774460..46ddf6c 100644--- a/src/core/gateway.ts+++ b/src/core/gateway.ts@@ -15,8 +15,13 @@ export interface ToolDef {name: stringdescription: stringinputSchema: { type: 'object'; properties?: Record<string, unknown>; required?: string[] }+ _meta?: Record<string, unknown> // goes out as is in tools/list}+// Claude Code keeps an MCP server's tools behind tool search (by name only, loaded when the model+// looks one up). A tool listed with this stays in the prompt: the app's own, few and used often.+export const ALWAYS_LOAD = { 'anthropic/alwaysLoad': true } as const+export interface Session {tools: ToolDef[]call(name: string, args: Record<string, unknown>): Promise<CallToolResult>diff --git a/src/core/index.ts b/src/core/index.tsindex bd83ca3..ab39f57 100644--- a/src/core/index.ts+++ b/src/core/index.ts@@ -28,7 +28,8 @@ import { piEngine } from './engines/pi'import { geminiAppDir, geminiEngine } from './engines/gemini'import { cursorAppDir, cursorEngine } from './engines/cursor'import { grokEngine } from './engines/grok'-import { accountDir, accountStatus, adoptLoginShellPath, detectEngines, type CodexModel } from './engines/detect'+import { accountDir, accountStatus, adoptLoginShellPath, detectEngines } from './engines/detect'+import { detectEngine, EngineCheck, type EngineFindings } from './engine-check'import { fakeEngine } from './engines/fake'import { relocating } from './engines/relocate'import { DesktopApps, macApps, SELF } from './apps'@@ -108,24 +109,31 @@ const DEFAULTS: Omit<Settings, 'engines'> = {const people = new People(db)if (!db.owner().name) db.renamePerson(db.ownerId(), db.getSettings(DEFAULTS).workspaceName, false)-const unknownEngine: EngineStatus = { installed: false, loggedIn: false }-let engines: Record<EngineId, EngineStatus> = { claude: unknownEngine, codex: unknownEngine, opencode: unknownEngine, pi: unknownEngine, gemini: unknownEngine, cursor: unknownEngine, grok: unknownEngine }-// The models OpenCode and Pi list (what the person has logins for), from the last check.-let listed: Partial<Record<EngineId, string[]>> = {}-// Codex's own catalog for this login (names and what each model is for), from the last check.-let codexCatalog: CodexModel[] = []-const fakeStatus = (v: string): EngineStatus => ({ installed: true, loggedIn: true, path: 'fake', version: v, account: L('Motor de teste', 'Test engine'), route: 'plan' })-async function detect(): Promise<void> {- if (fake) {- engines = { claude: fakeStatus('0.0.0'), codex: fakeStatus('0.0.0'), opencode: { ...fakeStatus('0.0.0'), route: 'providers', account: 'OpenAI, OpenCode · 3 modelos' }, pi: { installed: false, loggedIn: false }, gemini: { installed: false, loggedIn: false }, cursor: { installed: false, loggedIn: false }, grok: { installed: false, loggedIn: false } }- listed = { opencode: ['openai/gpt-5.5', 'opencode/big-pickle', 'opencode-go/qwen3.8-max'] }- } else ({ engines, listed, codexCatalog } = await detectEngines(codexHome))- await checkAccounts()- rememberModels(codexCatalog.map((m) => ({ id: m.slug, engine: 'codex', label: m.label, hint: m.description ?? '' })))- gatewayLists.clear()- emit({ type: 'settings', settings: settings() })-}+const fakeFindings = (): Omit<EngineFindings, 'accounts'> => ({+ engines: { claude: fakeStatus('0.0.0'), codex: fakeStatus('0.0.0'), opencode: { ...fakeStatus('0.0.0'), route: 'providers', account: 'OpenAI, OpenCode · 3 modelos' }, pi: { installed: false, loggedIn: false }, gemini: { installed: false, loggedIn: false }, cursor: { installed: false, loggedIn: false }, grok: { installed: false, loggedIn: false } },+ listed: { opencode: ['openai/gpt-5.5', 'opencode/big-pickle', 'opencode-go/qwen3.8-max'] },+ codexCatalog: []+})+// The harnesses' last check, kept in the data folder: the window opens on it while the next runs.+const engineCheck = new EngineCheck({+ file: join(dataDir, 'engines.json'),+ all: async () => (fake ? fakeFindings() : detectEngines(codexHome)),+ one: async (e) => (fake ? { status: fakeFindings().engines[e], listed: fakeFindings().listed[e] } : detectEngine(e, codexHome)),+ after: async (found, engine) => {+ ;({ engines, listed, codexCatalog } = found)+ await checkAccounts(undefined, engine)+ rememberModels(codexCatalog.map((m) => ({ id: m.slug, engine: 'codex', label: m.label, hint: m.description ?? '' })))+ gatewayLists.clear()+ emit({ type: 'settings', settings: settings() })+ return { accounts: Object.fromEntries(accountLogins) }+ }+})+// The models OpenCode and Pi list (what the person has logins for), and Codex's own catalog for+// this login (names and what each model is for), from the last check.+let { engines, listed, codexCatalog } = engineCheck.current+// Everything checked again; a call while a check runs gets that one.+const detect = (): Promise<unknown> => engineCheck.detect().catch((e: unknown) => console.error('[engines]', e))// The harness's own sign-in, in a terminal, with the variables that say which login it is.function openLogin(engine: EngineId, vars: Record<string, string>): { opened: boolean; command: string } {const bin = engines[engine].path ?? ENGINES[engine].cli@@ -146,19 +154,29 @@ function openLogin(engine: EngineId, vars: Record<string, string>): { opened: bo// After a sign-in or an install in a terminal, the harness is checked again every few// seconds until it shows up (for 10 minutes at most): it appears with no "Check again".+// Only that harness is checked, not all of them.let watching: ReturnType<typeof setInterval> | undefined+let watched: EngineId | undefinedfunction watchEngine(engine: EngineId, done: (s: EngineStatus) => boolean): void {if (watching) clearInterval(watching)const until = Date.now() + 10 * 60_000+ const stop = (): void => (clearInterval(watching), (watched = undefined))+ watched = enginewatching = setInterval(() => {- if (done(engines[engine]) || Date.now() > until) return void clearInterval(watching)- void detect()+ if (done(engines[engine]) || Date.now() > until) return stop()+ void engineCheck.recheck(engine).catch((e: unknown) => console.error('[engines]', e))}, 4_000)watching.unref()}const gateway = new Gateway()-const ready = Promise.all([gateway.start(), (fake ? Promise.resolve() : adoptLoginShellPath()).then(detect)])+// The login shell's PATH comes before any CLI starts: harnesses, connectors and Docker are found on it.+const pathReady = fake ? Promise.resolve() : adoptLoginShellPath().catch((e: unknown) => console.error('[path]', e))+// The harnesses are checked behind the window (it opens on the last check). What truly needs+// them (a reply, the memory, routines, a connection test) waits for this.+const enginesReady = pathReady.then(detect)+// The window waits only for the database, open by now, and the gateway.+const ready = gateway.start()const settings = (): Settings => {const s = db.getSettings(DEFAULTS)@@ -168,12 +186,13 @@ const settings = (): Settings => {// More logins of Claude Code and Codex (Settings › Accounts): each in its own folder, checked with// the CLI's own status when the harnesses are, and every few seconds after a sign-in.-const accountLogins = new Map<string, { loggedIn: boolean; detail?: string }>()+const accountLogins = new Map<string, { loggedIn: boolean; detail?: string }>(Object.entries(engineCheck.current.accounts ?? {}))const savedAccounts = (): Account[] => (db.getSettings(DEFAULTS).accounts ?? []).map(({ id, engine, name }) => ({ id, engine, name }))-async function checkAccounts(only?: string): Promise<void> {+// `only`: that account; `engine`: that harness's accounts.+async function checkAccounts(only?: string, engine?: EngineId): Promise<void> {await Promise.all(savedAccounts()- .filter((a) => !only || a.id === only)+ .filter((a) => (!only || a.id === only) && (!engine || a.engine === engine)).map(async (a) => {const bin = engines[a.engine].pathif (fake) accountLogins.set(a.id, { loggedIn: true, detail: L('Motor de teste', 'Test engine') })@@ -187,7 +206,10 @@ function watchAccount(id: string): void {const until = Date.now() + 10 * 60_000watchingAccount = setInterval(() => {if (accountLogins.get(id)?.loggedIn || Date.now() > until || !savedAccounts().some((a) => a.id === id)) return void clearInterval(watchingAccount!)- void checkAccounts(id).then(() => emit({ type: 'settings', settings: settings() }))+ void checkAccounts(id).then(() => {+ engineCheck.setAccounts(Object.fromEntries(accountLogins))+ emit({ type: 'settings', settings: settings() })+ })}, 4_000)watchingAccount.unref()}@@ -195,7 +217,7 @@ function watchAccount(id: string): void {// A harness that moved since it was found (an update to another folder) is looked for again.function moved(id: EngineId): Parameters<typeof relocating>[1] {- return { path: () => engines[id].path, label: ENGINES[id].label, redetect: detect }+ return { path: () => engines[id].path, label: ENGINES[id].label, redetect: () => detect().then(() => undefined) }}const engineImpls: Record<EngineId, Engine> = fake@@ -260,7 +282,7 @@ function workspaceSummary(): void {// The owner's counts: the switcher is on the desktop, the owner's app.const owner = db.owner()const unread = db.conversations(owner.id).filter((c) => people.canSeeConversation(owner, c)).reduce((n, c) => n + (c.unread ?? 0), 0)- const summary = { type: 'workspace-summary', name: workspaceLabel(current), paused: !!current.paused, unread, approvals: db.approvals().filter((a) => a.state === 'pending').length }+ const summary = { type: 'workspace-summary', name: workspaceLabel(current), paused: !!current.paused, unread, approvals: db.pendingApprovals() }const wire = JSON.stringify(summary)if (wire !== lastSummary) process.parentPort.postMessage(summary)lastSummary = wire@@ -482,7 +504,8 @@ const appIcons = (paths: string[]): Promise<Record<string, string>> =>// The person's installed apps, with their icons, kept in the data folder: the apps picker// shows them at once, even right after a restart, and a refresh runs behind it when they-// may have changed. Made once a few seconds after start, so even the first look is instant.+// may have changed. Made at start only when the kept one is a day old: a scan starts a hundred+// processes, so it waits for the harnesses' check to end too.// bundleId: a Mac app's bundle id, a Windows app's AppUserModelID, a Linux desktop id.type ShelfApp = { name: string; bundleId?: string; path?: string; icon?: string; exe?: string; exec?: string[]; chromium?: boolean }// Each system's own list: the Mac's Applications folders, Windows' Start menu, Linux's application menu.@@ -524,7 +547,7 @@ const shelfNow = async (): Promise<ShelfApp[]> => {if (Date.now() - shelf.at > 5 * 60_000) void restock()return shelf.list}-if (!serverMode && !fake) setTimeout(() => void restock(), 4_000).unref()+if (!serverMode && !fake && (!shelf || Date.now() - shelf.at > 24 * 3600_000)) void enginesReady.then(() => setTimeout(() => void restock(), 5_000).unref())// On a server there's no Electron: the agents' Chrome takes the picture instead.const shoot: Shooter = (opts) => (serverMode && chrome ? chrome.shot(opts) : electronShoot(opts))@@ -618,7 +641,7 @@ const oauthCallback = async (url: URL): Promise<string> => {}gateway.route('/oauth/callback', oauthCallback)-const memory = new Memories({ db, engines: engineImpls, settings: () => ready.then(settings), emit, workDir: join(dataDir, 'agents') })+const memory = new Memories({ db, engines: engineImpls, settings: () => enginesReady.then(settings), emit, workDir: join(dataDir, 'agents') })const computers = new Computers({ db, dataDir, emit, shoot })const backups = join(dataDir, 'backups')@@ -648,10 +671,12 @@ const dmOf = (conversationId: string): string | null | undefined => {return c ? (dmOwner(c, db.ownerId()) ?? null) : undefined}const wiki = new Wiki({ dir: wikiDir(), indexPath: wikiIndex(wikiDir()), onChange: () => emit({ type: 'wiki' }), dmOf })-wiki.init()+// The folder is read behind the window: a big Obsidian vault takes a while.+wiki.init(true, true)toMain({ type: 'wiki_dir', path: wiki.dir })// The curator reads the conversations with the memory's cheap model, and keeps what lasts.const wikiLlm = async (system: string, prompt: string): Promise<string> => {+ await enginesReadyconst s = settings()const model = usable(modelInfo(s.memoryModel)) ?? modelInfo('haiku')!const st = s.engines[model.engine]@@ -680,7 +705,7 @@ setInterval(() => {const runner = new Runner({db,engines: engineImpls,- settings: () => ready.then(settings),+ settings: () => enginesReady.then(settings),emit,workDir: join(dataDir, 'agents'),dataDir,@@ -710,7 +735,7 @@ const runner = new Runner({})runner.setPaused(!!settings().paused)// Installs from before the Tuca get him at the first start after the introduction.-void ready.then(() => {+void enginesReady.then(() => {if (settings().onboarding?.done) ensureTuca()})@@ -761,9 +786,8 @@ hooks.on('error', (e) => console.error(`[gatilhos] porta ${runtimePorts.webhook}void ready.then(async () => {- connectors.connectAll()- returnChannelFolders()- for (const a of db.agents()) if (a.computer && !a.archived) void computers.refresh(a)+ toMain({ type: 'ready' })+ workspaceSummary()await runner.expireApprovals()setInterval(() => void runner.expireApprovals(), 60_000).unref()// A thread that went quiet gets its own summary, and the memories in it.@@ -776,9 +800,6 @@ void ready.then(async () => {hooks.listen(runtimePorts.webhook, '127.0.0.1')void telegram?.start()}- routines.start()- // A Tucano that had more people (or an invite out) before the heritage existed gets it now.- if (db.people({ removed: true }).length > 1 || db.invites().length) inherit()// A copy of the database once a day, the last 7 kept.const daily = (): void => {try {@@ -795,8 +816,15 @@ void ready.then(async () => {}daily()setInterval(daily, 3_600_000).unref()- toMain({ type: 'ready' })- workspaceSummary()+ // Connectors and computers start programs: they're found on the login shell's PATH.+ await pathReady+ connectors.connectAll()+ returnChannelFolders()+ for (const a of db.agents()) if (a.computer && !a.archived) void computers.refresh(a)+ await enginesReady+ routines.start()+ // A Tucano that had more people (or an invite out) before the heritage existed gets it now.+ if (db.people({ removed: true }).length > 1 || db.invites().length) inherit()}).catch((e: unknown) => {console.error('[core] startup failed', e)process.exit(1)@@ -868,7 +896,7 @@ function ensureTuca(modelId?: string, fresh = false, person = db.ownerId()): { aconst theirs = (c: { kind: 'channel' | 'dm'; owner?: string; name: string }): boolean => c.kind === 'dm' && c.name === tuca!.id && dmOwner(c, db.ownerId()) === personlet dm = db.conversations().find(theirs)if (dm && fresh) {- for (const m of db.messages()) if (m.conversationId === dm.id && m.run?.status === 'working') runner.stop(m.id)+ for (const m of db.messagesWithRun(['working'])) if (m.conversationId === dm.id) runner.stop(m.id)db.deleteConversation(dm.id)emit({ type: 'conversation_removed', id: dm.id, for: person })dm = undefined@@ -905,6 +933,8 @@ function settleDraft(messageId: string, agentId?: string): void {}+const PAGE = 100 // messages outside threads per conversation, per page sent to the window+// Each method gets who is asking: every human action is that person's.type Handlers = { [M in Method]: (p: Params<M>, ctx: Ctx) => ReturnType<Api[M]> }@@ -1014,7 +1044,7 @@ const api: Handlers = {},// The page loads from file://, which can't fetch tucano:// (CORS); text comes through the core instead.artifactText: ({ id }, ctx) => {- const a = db.artifacts().find((x) => x.id === id)+ const a = db.artifact(id)if (!a || !people.canSeeConversation(ctx.person, db.conversation(a.conversationId)) || !people.artifactVisible(ctx.person, a)) return nullconst file = join(dataDir, 'artifacts', a.id, a.name)try {@@ -1029,7 +1059,7 @@ const api: Handlers = {defaultWorkspace,settings: settings(),agents: db.agents(),- messages: db.messages(),+ ...db.openingMessages(PAGE), // each conversation's latest: the rest come as the scroll gets thereconnectors: connectors.list(),approvals: db.approvals(),memories: db.memories(),@@ -1046,14 +1076,31 @@ const api: Handlers = {demoServer: existsSync(demoPath) ? { command: 'node', args: [demoPath] } : undefined}, { server: serverMode }),+ olderMessages: ({ conversationId, before, through }, ctx) => {+ reach(ctx, conversationId)+ // Back to a message to show (a reply: from its thread's first message), or one more page.+ const target = through ? db.message(through) : undefined+ const start = target?.threadId ? db.message(target.threadId) : target+ const page = db.messagesBefore(conversationId, before, PAGE, start?.conversationId === conversationId ? start.at : undefined)+ const messages = people.pageFor(ctx.person, page.messages)+ // Past the heritage, to a member, there's nothing more to read.+ return { messages, since: messages.length < page.messages.length ? 0 : page.since }+ },+ threadMessages: ({ rootId }, ctx) => {+ const root = db.message(rootId)+ if (!root) return []+ reach(ctx, root.conversationId)+ return people.pageFor(ctx.person, [root, ...db.recentMessages(root.conversationId, 100_000, rootId)])+ },+sendMessage: ({ conversationId, text, images, threadId }, ctx) => {reach(ctx, conversationId)bg(runner.send(conversationId, text, images, threadId, ctx.person.id), 'sendMessage')},- typing: ({ conversationId, threadId }, ctx) => {+ typing: ({ conversationId, threadId, opened }, ctx) => {reach(ctx, conversationId)- void runner.typing(conversationId, threadId).catch((e: unknown) => console.warn('[typing]', e))+ void runner.typing(conversationId, threadId, opened).catch((e: unknown) => console.warn('[typing]', e))},stopRun: ({ messageId }, ctx) => (reachMessage(ctx, messageId), runner.stop(messageId)),@@ -1098,7 +1145,7 @@ const api: Handlers = {if (!agent || agent.archived === archived) returnrecord(ctx, archived ? 'agent.archived' : 'agent.restored', id, { name: agent.name })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)+ for (const m of db.messagesWithRun(['working', 'waiting_approval'])) if (m.author.kind === 'agent' && m.author.id === id) runner.stop(m.id)routines.pauseAgent(id)runner.forgetSessions({ agentId: id })if (agent.browser) bg(browser.close(id), 'archiveAgent')@@ -1160,7 +1207,7 @@ const api: Handlers = {reach(ctx, id)if (c.kind === 'channel') must(ctx.person, { kind: 'admin' })record(ctx, c.kind === 'channel' ? 'channel.deleted' : 'dm.deleted', id, c.kind === 'channel' ? { name: c.name } : undefined)- 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 m of db.messagesWithRun(['working', 'waiting_approval'])) if (m.conversationId === id) 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 })@@ -1332,6 +1379,7 @@ const api: Handlers = {// The models a harness offers, besides the app's list for a plan: what OpenCode// and Pi list, or what the gateway in Claude Code's or Codex's config lists.engineModels: async ({ engine }) => {+ if (!engineCheck.known) await enginesReadyif (engine === 'codex' && codexCatalog.length)return { models: codexCatalog.map((m) => m.slug), labels: Object.fromEntries(codexCatalog.map((m) => [m.slug, { label: m.label, ...(m.description ? { hint: m.description } : {}) }])) }if (listed[engine]) return { models: listed[engine]! }@@ -1350,6 +1398,7 @@ const api: Handlers = {// A real question through the chosen engine and model: what fails here would fail every reply.testEngine: async ({ model }) => {+ await enginesReadyconst m = modelInfo(model)if (!m?.id) return { ok: false, message: L('Escolha um modelo pra testar.', 'Pick a model to test.') }const st = settings().engines[m.engine]@@ -1414,7 +1463,7 @@ const api: Handlers = {if (!serverMode && patch.theme !== undefined) toMain({ type: 'theme', theme: patch.theme })if (patch.paused !== undefined) runner.setPaused(patch.paused)if (patch.openAtLogin !== undefined) toMain({ type: 'login_item', open: patch.openAtLogin })- if (patch.onboarding?.done) bg(ready.then(() => ensureTuca()), 'ensureTuca') // skipping the introduction still gets the Tuca+ if (patch.onboarding?.done) bg(enginesReady.then(() => ensureTuca()), 'ensureTuca') // skipping the introduction still gets the Tucaif (patch.language) toMain({ type: 'lang', lang: patch.language })emit({ type: 'settings', settings: settings() })},@@ -1786,8 +1835,9 @@ const api: Handlers = {return routines.runNow(id)},+ // While a sign-in or an install is being watched, only that harness: the screens ask every few seconds.refreshEngines: () => {- bg(detect(), 'refreshEngines')+ bg(watched ? engineCheck.recheck(watched) : detect(), 'refreshEngines')},// Login always happens in the CLI's own flow; the app never sees credentials.@@ -1804,7 +1854,13 @@ const api: Handlers = {const account: Account = { id: randomUUID().slice(0, 8), engine, name: name.trim() || ENGINES[engine].label }mkdirSync(join(accountDir(dataDir, account.id), '.codex'), { recursive: true })db.setSettings({ accounts: [...savedAccounts(), account] })- bg(checkAccounts(account.id).then(() => emit({ type: 'settings', settings: settings() })), 'addAccount')+ bg(+ checkAccounts(account.id).then(() => {+ engineCheck.setAccounts(Object.fromEntries(accountLogins))+ emit({ type: 'settings', settings: settings() })+ }),+ 'addAccount'+ )emit({ type: 'settings', settings: settings() })return account},diff --git a/src/core/people.ts b/src/core/people.tsindex 46a7ea1..591f17e 100644--- a/src/core/people.ts+++ b/src/core/people.ts@@ -258,6 +258,12 @@ export class People {return Number(this.db.meta('heritageAt') ?? 0)}// Where a member's view of a channel starts: one line, in place of what came before.+ // A page of one conversation's messages (scrolling back, a thread) as this person reads it.+ pageFor(person: Pick<Person, 'id' | 'role'>, messages: Message[]): Message[] {+ const shown = messages.filter((m) => this.visibleAt(person, m))+ return shown.length < messages.length ? [this.boundaryLine(messages[0]!.conversationId), ...shown] : shown+ }+private boundaryLine(conversationId: string): Message {return { id: `heritage:${conversationId}`, conversationId, author: { kind: 'system' }, text: L('Histórico anterior visível só pro dono', 'Earlier history visible to the owner only'), at: this.heritageAt() }}@@ -316,6 +322,9 @@ export class People {return this.canSeeMemory(person, event.memory) ? event : undefinedcase 'browser':return { type: 'browser', view: this.browserFor(person, event.view) }+ // The screen of a browser working for a conversation this person doesn't see: not theirs.+ case 'browser_frame':+ return !event.conversationId || this.canSeeConversation(person, this.conversationOf(event.conversationId)) ? event : undefinedcase 'computer':return { type: 'computer', computer: this.computerFor(person, event.computer) }case 'inbox':@@ -482,6 +491,7 @@ export class People {...(person.role === 'owner' && demoServer ? { demoServer } : {}),settings: this.settingsFor(person, base.settings),conversations,+ ...(base.since ? { since: Object.fromEntries(Object.entries(base.since).filter(([id]) => seen.has(id) && !cut.has(id))) } : {}),messages: cut.size ? [...[...cut].map((id) => this.boundaryLine(id)), ...messages] : messages,connectors: base.connectors.map((c) => this.connectorFor(person, c)),artifacts: base.artifacts.filter((a) => seen.has(a.conversationId) && this.artifactVisible(person, a)),diff --git a/src/core/policy-people.ts b/src/core/policy-people.tsindex cce604f..418e25d 100644--- a/src/core/policy-people.ts+++ b/src/core/policy-people.ts@@ -85,6 +85,8 @@ export const NEEDS: Record<Method, Need> = {artifactText: 'anyone',sendMessage: 'anyone',typing: 'anyone',+ olderMessages: 'anyone',+ threadMessages: 'anyone',stopRun: 'anyone',retryRun: 'anyone',continueRun: 'anyone',diff --git a/src/core/runs.ts b/src/core/runs.tsindex 3ecfe4e..a787dc3 100644--- a/src/core/runs.ts+++ b/src/core/runs.ts@@ -6,7 +6,7 @@ import { friendly, toolLabel } from '../shared/errors'import type { CoreEvent } from '../shared/rpc'import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'import { ACCESS_REQUEST, CACHE_READ_WEIGHT, describeSchedule, workIn, ENGINES, ERRORS_STOP, usable, modelInfo, PENDING_WAIT_MINUTES, REPEAT_STOP, REPEAT_WARN, SAME_TOOL_STOP, SAME_TOOL_WARN, SLEEPS_FREE, SLEEPS_STOP, RUN_BUDGET_PCT, RUN_STALL_MINUTES, IMAGE_MIMES, MAX_IMAGE_BYTES, MAX_IMAGES_PER_MESSAGE, type Account, type Agent, type Approval, type Artifact, type ImageUpload, type Connector, type ConnectorTool, type Conversation, type EngineId, type Message, type Quota, type Receipt, type Person, type Question, type Routine, type Run, type RunStatus, type Settings, type Step, delegating, wikiAccess } from '../shared/types'-import { BUSCAR_THREADS, clock, HISTORY_LIMIT, LER_THREAD, mentioned, snip, systemPrompt, transcript, transcriptBlocks } from './context'+import { BUSCAR_THREADS, clock, HISTORY_LIMIT, LER_THREAD, liveContext, mentioned, NO_LIVE, snip, systemPrompt, transcript, transcriptBlocks, type PromptOpts } from './context'import { BUSCAR_MEMORIAS, contextWindow, LEMBRAR, searchThreads, type Memories } from './memory'import { WIKI_TOOL_NAMES, WIKI_TOOLS, wikiCall, type Wiki } from './wiki'import { BROWSER_TOOL_NAMES, browserStep, browserTools, NAVEGADOR, type Browser } from './browser'@@ -14,14 +14,14 @@ import { APP_TOOL_NAMES, APPS, appStep, appTools, type DesktopApps } from './appimport { COMPUTER_TOOL_NAMES, computerTools, stepFor, type Computers } from './computer'import { AGENDAR, CANCELAR, outcome, ROUTINE_TOOL_NAMES, type Routines } from './routines'import { LER_SKILL, PROPOR_SKILL, SKILL_TOOL_NAMES, type Skills } from './skills'-import { availableModels, builderSection, draftFrom, helperSection, PROPOR_AGENTE, PROPOR_TIME, teamFrom } from './tuca'+import { availableModels, builderGuide, builderSection, draftFrom, helperSection, PROPOR_AGENTE, PROPOR_TIME, teamFrom } from './tuca'import { LER_GUIA, readGuide } from './guide'import { proposalFrom, PROPOSAL_TOOLS, VER_ESTADO, workspaceState } from './tuca-help'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 Session, type ToolDef } from './gateway'+import { ALWAYS_LOAD, textResult, type Gateway, type Session, type ToolDef } from './gateway'import { Followups, replyKey } from './followups'import { sessionConfig, Sessions, type SessionPlan, type Shown } from './sessions'import { JEV_MODEL, routeJev } from './jev'@@ -38,6 +38,14 @@ const GITHUB = 'github'const ABRIR_PR = 'abrir_pr'const MAX_CONCURRENT = 4+// Connector tools wait behind tool search, and loading one costs a model call (1.5–2 s). The ones an+// agent called lately are listed loaded, so its usual lookups don't pay that: at most this many.+export const PRELOAD_TOOLS = 12+export const PRELOAD_DAYS = 14+// Replies to something the person just did (a message, an approval, a retry) go ahead of routines,+// hand-offs and follow-ups, and may run past MAX_CONCURRENT up to this: four routines running+// mustn't keep a reply to the person waiting for minutes.+export const MAX_CONCURRENT_URGENT = 6const MAX_TURN_IMAGES = 6 // attached images a reply sees as images; older ones only by nameconst mimeOf = (name: string): string => ({ png: 'image/png', gif: 'image/gif', webp: 'image/webp' })[name.split('.').pop()!.toLowerCase()] ?? 'image/jpeg'const MAX_MENTIONS = 3@@ -193,7 +201,7 @@ export function routedHistory(db: Pick<Db, 'message'>, windowed: Message[], anch}export class Runner {- private queue: (() => Promise<unknown>)[] = []+ private queue: { job: () => Promise<unknown>; urgent: boolean }[] = []private active = 0private routing = 0private controllers = new Map<string, Control>()@@ -276,7 +284,9 @@ export class Runner {// session, if its process closed; in a channel of several, the router. A first reply has no// session to start yet, and a mention or a pending question skips the router: then the// process started waits a couple of minutes and goes.- async typing(conversationId: string, threadId?: string): Promise<void> {+ // `opened`: the person only opened the conversation. Its kept sessions start again, but not the router: a+ // channel looked at without a message would hold a process for nothing.+ async typing(conversationId: string, threadId?: string, opened = false): Promise<void> {const { db, engines } = this.depsconst conv = db.conversation(conversationId)if (!conv || this.paused) return@@ -292,7 +302,18 @@ export class Runner {if (id && ready(engine)) engines[engine].rewarm?.(id)return}- if (members.length < 2 || settings.routerModel === JEV_MODEL) return+ if (members.length < 2) return+ // In a channel, whoever answered last here is the likeliest to answer again: its session too.+ const lastAgent = db+ .recentMessages(conv.id, 20, conv.threads ? (threadId ?? null) : undefined)+ .reverse()+ .flatMap(({ author }) => (author.kind === 'agent' ? members.filter((a) => a.id === author.id) : []))[0]+ if (lastAgent) {+ const engine = modelInfo(lastAgent.modelId)?.engine ?? 'claude'+ const id = this.sessions.idOf(replyKey(lastAgent.id, conv.id, threadId))+ if (id && ready(engine)) engines[engine].rewarm?.(id)+ }+ if (opened || settings.routerModel === JEV_MODEL) returnconst model = usable(modelInfo(settings.routerModel)) ?? modelInfo('haiku')!if (!ready(model.engine)) returnconst cwd = join(this.deps.workDir, '_router')@@ -393,7 +414,7 @@ export class Runner {return}}- for (const agent of responders) this.enqueue(() => this.execute(agent, conv, { depth: 1, threadId: replyIn, replyTo: mine.id, ...(onBehalf?.agent === agent.id ? { task: onBehalf.task } : {}) }))+ for (const agent of responders) this.enqueue(() => this.execute(agent, conv, { depth: 1, threadId: replyIn, replyTo: mine.id, ...(onBehalf?.agent === agent.id ? { task: onBehalf.task } : {}) }), true)}// An image I attached, kept in the artifact store with my message (no agent made it).@@ -428,7 +449,7 @@ export class Runner {const agent = db.agent(msg.author.id)const conv = db.conversation(msg.conversationId)if (!agent || !conv) return- this.enqueue(() => this.execute(agent, conv, { depth: msg.run!.depth ?? 1, existing: msg }))+ this.enqueue(() => this.execute(agent, conv, { depth: msg.run!.depth ?? 1, existing: msg }), true)}// A reply paused at its budget goes on in a new reply that knows what it did:@@ -458,7 +479,7 @@ export class Runner {].filter(Boolean).join('\n\n')- this.enqueue(() => this.execute(agent, conv, { depth: msg.run!.depth ?? 1, task, work: msg.run!.work, threadId: msg.threadId }))+ this.enqueue(() => this.execute(agent, conv, { depth: msg.run!.depth ?? 1, task, work: msg.run!.work, threadId: msg.threadId }), true)}// Posts a routine's request in its conversation and runs its agent on it.@@ -655,7 +676,7 @@ export class Runner {this.enqueue(() => {if (this.waiting.get(key) === slot) this.waiting.delete(key)return this.execute(agent, conv, { depth: 1, threadId: note.threadId, trigger: slot.trigger })- })+ }, true)}}this.waiting.set(key, slot)@@ -668,15 +689,19 @@ export class Runner {if (!this.followups.busy(key)) this.waiting.get(key)?.start()}- private enqueue(job: () => Promise<unknown>): void {- this.queue.push(job)+ // `urgent`: it answers something the person just did (see MAX_CONCURRENT_URGENT).+ private enqueue(job: () => Promise<unknown>, urgent = false): void {+ this.queue.push({ job, urgent })this.pump()}private pump(): void {- while (this.active < MAX_CONCURRENT && this.queue.length > 0) {+ for (;;) {if (this.paused) return // paused: nothing new starts, queued work waits- const job = this.queue.shift()!+ const urgent = this.queue.findIndex((q) => q.urgent)+ const at = this.active < MAX_CONCURRENT ? (urgent >= 0 ? urgent : this.queue.length > 0 ? 0 : -1) : this.active < MAX_CONCURRENT_URGENT ? urgent : -1+ if (at < 0) return+ const { job } = this.queue.splice(at, 1)[0]!if (this.active++ === 0) this.deps.onBusy?.(true)void job().catch((e: unknown) => console.error('[runner]', e))@@ -980,8 +1005,9 @@ export class Runner {}}: undefined+ // The app's own tools stay in the prompt; the connectors' wait behind tool search (ALWAYS_LOAD).const others = db.people()- const toolDefs: ToolDef[] = [+ const ownTools: ToolDef[] = [askUserFor(others.map((p) => (p.id === db.ownerId() ? ownerName || p.name : p.name))),...(accessTool ? [accessTool] : []),...(canRemember ? [LEMBRAR] : []),@@ -994,7 +1020,18 @@ export class Runner {...(apps ? appTools(agent) : []),...(routines ? [AGENDAR, CANCELAR] : []),...(skills ? [...(mySkills.length ? [LER_SKILL] : []), PROPOR_SKILL] : []),- ...(wiki ? WIKI_TOOLS : []),+ ...(wiki ? WIKI_TOOLS : [])+ ]+ // The connector tools it called lately, by the steps of its replies ("Linear · list_issues").+ const byStep = new Map([...exposed].map(([name, { connector, tool }]) => [`${connector.name} · ${tool.name}`, name]))+ const preload = new Set(+ db+ .toolsUsedBy(agent.id, Date.now() - PRELOAD_DAYS * 86_400_000)+ .flatMap((u) => (byStep.has(u.detail) ? [byStep.get(u.detail)!] : []))+ .slice(0, PRELOAD_TOOLS)+ )+ const toolDefs: ToolDef[] = [+ ...ownTools.map((t) => ({ ...t, _meta: { ...t._meta, ...ALWAYS_LOAD } })),...[...exposed].map(([name, { connector, tool }]): ToolDef => {const schema = tool.inputSchema as ToolDef['inputSchema']if (tool.cls !== 'sensitive') return { name, description: `[${connector.name}] ${tool.description}`, inputSchema: schema }@@ -1011,6 +1048,7 @@ export class Runner {}}})+ .map((t) => (preload.has(t.name) ? { ...t, _meta: { ...ALWAYS_LOAD } } : t))]const addSteps = (...steps: Step[]): void => {@@ -1599,11 +1637,7 @@ export class Runner {const names = new Map<string, string[]>()for (const a of attached) names.set(a.messageId, [...(names.get(a.messageId) ?? []), a.name])const thread = msg.threadId ? db.message(msg.threadId) : undefined- const { blocks, blockOf } = transcriptBlocks({ agent, conversation: conv, messages: history, agents: db.agents(), me: settings.workspaceName, people: named, routineOwner: scheduledBy, task, summary, images: names, thread, searchable: canSeekThreads, unix: exposed.size > 0, ...(anchor && history.at(-1)?.id === anchor.id ? { answering: anchor } : {}) })- 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({+ const promptOpts: PromptOpts = {agent,settings,conversation: conv,@@ -1623,27 +1657,36 @@ export class Runner {connectors: exposed.size > 0,people,builder: proposes- ? [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, tuca: helps, me: settings.workspaceName }), helps && helperSection()].filter(Boolean).join('\n\n')- : undefined- })+ ? 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,+ builderGuide: proposes ? [builderGuide({ tuca: helps, me: settings.workspaceName }), helps && helperSection()].filter(Boolean).join('\n\n') : undefined+ }+ const system = systemPrompt(promptOpts)+ const live = liveContext(promptOpts)+ const { blocks, blockOf } = transcriptBlocks({ agent, conversation: conv, messages: history, agents: db.agents(), me: settings.workspaceName, people: named, routineOwner: scheduledBy, task, summary, images: names, thread, searchable: canSeekThreads, unix: exposed.size > 0, live, ...(anchor && history.at(-1)?.id === anchor.id ? { answering: anchor } : {}) })+ 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) }] : []))// 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 = replyKey(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 })+ // Which tools come loaded (_meta) stays out: a tool used for the first time in this reply mustn't end the session.+ const config = sessionConfig({ engine: engineId, model: modelName, effort: agent.effort, account: account?.id ?? '', web: agent.web !== false, system, tools: toolDefs.map(({ _meta: _m, ...t }) => t), 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 plan = engines[engineId].sessions && !writing ? this.sessions.begin(sessionKey, { config, shown, live, restart: !!opts.existing, task: !!task }) : undefinedlet 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.+ // Resumed: the live context if it changed, 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]!)+ const lead = p.live ? [live || NO_LIVE()] : []+ const pos = new Map(at.map((b, i) => [b, lead.length + i]))+ const sent = [...lead, ...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@@ -1721,8 +1764,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 })+ if (lost) this.sessions.end(sessionKey, lost, { ok: false, config, shown, live })+ if (plan) this.sessions.end(sessionKey, plan, { ok: !!result && !control.reason, config, shown, live, reply: msg.id, context: result?.context })this.controllers.delete(msg.id)}@@ -1987,7 +2030,7 @@ export class Runner {}})}- if (agent && conv && !agent.archived) this.enqueue(() => this.execute(agent, conv, { depth: 1, task, work: msg?.run?.work, threadId: msg?.threadId }))+ if (agent && conv && !agent.archived) this.enqueue(() => this.execute(agent, conv, { depth: 1, task, work: msg?.run?.work, threadId: msg?.threadId }), true)}// ---------- questions to people ----------@@ -2052,7 +2095,8 @@ export class Runner {work: asked?.run?.work,threadId: q.threadId,task: L(`${by.name} não autorizou perguntar a ${who}. Siga sem essa resposta ou pergunte a ${by.name} o que fazer.`, `${by.name} didn't allow asking ${who}. Go on without that answer or ask ${by.name} what to do.`)- })+ }),+ true)}@@ -2133,7 +2177,8 @@ export class Runner {work: asked.run?.work,threadId: asked.threadId,task: L(`${workspaceName} devolveu o controle do seu navegador. Continue de onde parou.`, `${workspaceName} handed your browser back. Pick up where you left off.`)- })+ }),+ true)}diff --git a/src/core/sessions.ts b/src/core/sessions.tsindex 0196aac..92d4fe4 100644--- a/src/core/sessions.ts+++ b/src/core/sessions.ts@@ -5,7 +5,8 @@// 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.+// between, its last reply didn't end well, or it grew past what a fresh start would cost. The live+// context (memories, the wiki, routines…) is the exception: changed, it goes again with what's new.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@@ -23,6 +24,7 @@ export interface SessionPlan {token: string // the gateway's, for as long as the session lives: a process kept open keeps its URLresume: booleansend: string[] // the messages to send, of those shown: all of them when it starts, the new ones when it resumes+ live: boolean // resuming: the live context changed since, so it goes again before the new messages}interface Entry {@@ -32,6 +34,7 @@ interface Entry {seen: Map<string, string> // message id → its block's hash; '*' for its own replies, whose text it wroteusedAt: numbercontext: number+ live: string // the hash of the live context it last got}const OWN = '*'@@ -61,21 +64,22 @@ export class Sessions {// 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 {+ // `live`: the live context this reply would show.+ begin(key: string, input: { config: string; shown: Shown[]; live?: string; restart?: boolean; task?: boolean }): SessionPlan | undefined {if (this.busy.has(key)) return undefinedthis.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 (send && (send.length || input.task)) return { id: e.id, token: e.token, resume: true, send, live: e.live !== hash(input.live ?? '') }}if (e) this.drop(key)- return { id: randomUUID(), token: randomBytes(24).toString('hex'), resume: false, send: input.shown.map((s) => s.id) }+ return { id: randomUUID(), token: randomBytes(24).toString('hex'), resume: false, send: input.shown.map((s) => s.id), live: false }}// 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 {+ end(key: string, plan: SessionPlan, out: { ok: boolean; config: string; shown: Shown[]; live?: string; reply?: string; context?: number }): void {this.busy.delete(key)const e = this.entries.get(key)if (!out.ok || this.doomed.delete(key)) {@@ -83,10 +87,11 @@ export class Sessions {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 }+ const entry: Entry = e?.id === plan.id ? e : { id: plan.id, token: plan.token, config: out.config, seen: new Map(), usedAt: 0, context: 0, live: '' }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.live = hash(out.live ?? '')entry.usedAt = this.now()entry.context = out.context ?? entry.contextthis.entries.set(key, entry)diff --git a/src/core/tuca.ts b/src/core/tuca.tsindex c81a2e2..df0ea1f 100644--- a/src/core/tuca.ts+++ b/src/core/tuca.ts@@ -205,16 +205,22 @@ export function availableModels(s: Pick<Settings, 'engines'>, listed: Partial<Re// What the Tuca sees of the workspace in his prompt.// `tuca`: him, whose instructions already say how; any other agent gets the short version, and when to propose.-export function builderSection(s: Pick<Settings, 'engines'>, ctx: { models: { id: string; label: string }[]; connectors: Connector[]; team: Agent[]; own: string; tuca?: boolean; me?: string }): string {- const gateway = (Object.keys(s.engines) as (keyof Settings['engines'])[]).filter((e) => s.engines[e].loggedIn && s.engines[e].route === 'gateway')+// How to propose: the same in every reply, so it goes in the system prompt. What there is to propose+// with (models, connectors, the team) changes, and goes in the live context: builderSection.+export function builderGuide(ctx: { tuca?: boolean; me?: string }): string {const me = ctx.me ?? L('a pessoa', 'the person')- return [- ctx.tuca- ? L('## Pra montar agentes', '## For building agents')- : L(+ return ctx.tuca+ ? L('## Pra montar agentes', '## For building agents')+ : L(`## Pra propor agentes, times, rotinas e canais\nVocê pode propor, num card que ${me} aplica: um agente novo (propor_agente), um time de agentes com um canal (propor_time), mudar um agente (propor_ajuste), uma rotina de outro agente (propor_rotina; as suas, agende com agendar_rotina) e um canal (propor_canal). Proponha quando ${me} pedir, ou quando for claramente o que resolve o pedido; não no meio de outra tarefa. Nada existe ou muda até ${me} aplicar. Num agente novo: instruções de 4 a 8 linhas falando com ele, conectores só em leitura se a tarefa não pede escrita, o modelo mais simples que dá conta. Dúvida de como usar o Tucano (telas, configurações, por que algo não funciona) é com o Tuca: diga pra perguntar a ele. Ele não muda o seu acesso nem as suas permissões: se faltar uma, diga a ${me} qual, sem mandar pedir ao Tuca.`,`## For proposing agents, teams, routines and channels\nYou can propose, as a card ${me} applies: a new agent (propor_agente), a team of agents with a channel (propor_time), changing an agent (propor_ajuste), a routine for another agent (propor_rotina; your own you schedule with agendar_rotina) and a channel (propor_canal). Propose when ${me} asks, or when it's clearly what solves the request; not in the middle of another task. Nothing exists or changes until ${me} applies it. For a new agent: 4 to 8 lines of instructions talking to it, connectors read-only unless the task needs writing, the simplest model that does the job. Questions about how to use Tucano (screens, settings, why something isn't working) are for the Tuca: say to ask him. He doesn't change your access or permissions: if one is missing, tell ${me} which, without sending them to the Tuca.`- ),+ )+}++export function builderSection(s: Pick<Settings, 'engines'>, ctx: { models: { id: string; label: string }[]; connectors: Connector[]; team: Agent[]; own: string }): string {+ const gateway = (Object.keys(s.engines) as (keyof Settings['engines'])[]).filter((e) => s.engines[e].loggedIn && s.engines[e].route === 'gateway')+ return [+ L('## Pra propor: o que existe agora', '## For proposing: what there is now'),`${L('Modelos que dá pra usar (passe o id em "modelo")', 'Models you can use (pass the id in "modelo")')}:\n${ctx.models.map((m) => `- ${m.id}: ${m.label}`).join('\n') || `- ${ctx.own}: ${L('o seu', 'yours')}`}`,gateway.length > 0 &&L(diff --git a/src/core/wiki.ts b/src/core/wiki.tsindex 156dd40..13903b6 100644--- a/src/core/wiki.ts+++ b/src/core/wiki.ts@@ -6,6 +6,7 @@// a save made from an older copy of a page is refused instead of overwriting the newer one.import { createHash } from 'node:crypto'import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, watch, writeFileSync, type FSWatcher } from 'node:fs'+import { readdir, stat } from 'node:fs/promises'import { basename, join, relative, resolve, sep } from 'node:path'import { DatabaseSync } from 'node:sqlite'import { L, locale } from '../shared/lang'@@ -105,6 +106,32 @@ function walk(root: string, keep: (rel: string) => boolean = () => true): stringif (existsSync(root)) go('')return out}+// The same, with each file's mtime, read without blocking: a big vault has thousands of files.+async function walkTimes(root: string, keep: (rel: string) => boolean): Promise<[string, number][]> {+ const out: [string, number][] = []+ const go = async (rel: string): Promise<void> => {+ let entries+ try {+ entries = await readdir(rel ? join(root, rel) : root, { withFileTypes: true })+ } catch {+ return // gone since it was listed+ }+ await Promise.all(+ entries.map(async (e) => {+ if (e.name.startsWith('.') || SKIP.has(e.name)) return+ const r = rel ? `${rel}/${e.name}` : e.name+ if (e.isDirectory()) {+ if (keep(`${r}/`)) await go(r)+ } else if (keep(r)) {+ const at = await stat(join(root, r)).then((st) => Math.round(st.mtimeMs), () => undefined)+ if (at !== undefined) out.push([r, at])+ }+ })+ )+ }+ if (existsSync(root)) await go('')+ return out.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0))+}const pageText = (meta: Record<string, string>, body: string): string => {const keys = Object.entries(meta).filter(([, v]) => v !== '')return (keys.length ? `---\n${keys.map(([k, v]) => `${k}: ${/[:#[\]{}]/.test(v) ? JSON.stringify(v) : v}`).join('\n')}\n---\n\n` : '') + body.replace(/^\n+/, '')@@ -233,6 +260,16 @@ export class Wiki {// vault the person pointed it to (notes at its root, in folders of its own).private root = ''private importing = false+ // Bumped when the index closes: a scan still reading the old folder drops what it found.+ private gen = 0+ private scanning = false+ private rescanAfter = false+ // The map and the log, as last read: the wiki screen asks for both on every change.+ private indexed = 0+ private graphKept?: { at: number; graph: ReturnType<Wiki['graph']> }+ private logKept?: { key: string; lines: string[] }+ // The folder's first read, when it runs behind (init with `background`).+ loaded: Promise<void> = Promise.resolve()private get pagesDir(): string {return this.root}@@ -245,7 +282,8 @@ export class Wiki {// A file under the root that's a page: Markdown, and not one of Tucano's own files.private isPage = (rel: string): boolean => (rel.endsWith('/') ? !(this.root === this.dir && rel === `${SOURCES}/`) : rel.endsWith('.md') && !(this.root === this.dir && [SCHEMA, INDEX, LOG].includes(rel)))- init(watchFolder = true): void {+ // `background`: the folder is read without blocking (a big vault takes a while); `loaded` says when.+ init(watchFolder = true, background = false): void {this.root = this.pickRoot()mkdirSync(this.pagesDir, { recursive: true })mkdirSync(join(this.dir, SOURCES), { recursive: true })@@ -306,17 +344,34 @@ export class Wiki {this.db.exec('INSERT OR IGNORE INTO held_log (title, person) SELECT title, person FROM held; INSERT OR IGNORE INTO held_log (title, person) SELECT DISTINCT key, held_for FROM versions WHERE held_for IS NOT NULL')// A source deleted before its changes went with it: they go now.this.dropOrphans()- this.scan()- // Links kept by the target's lowercase title before: by its key now (see pageKey), once.- if (!this.getMeta('linksByKey')) {- for (const r of this.db.prepare('SELECT file FROM pages').all() as { file: string }[]) {- const path = join(this.pagesDir, r.file)- if (existsSync(path)) this.indexLinks(r.file, parsePage(readFileSync(path, 'utf8')))- }- this.setMeta('linksByKey', '1')+ this.indexed+++ if (!background) {+ this.scan()+ this.linksByKey()+ this.writeIndex()+ if (watchFolder) this.watchFolder()+ return}- this.writeIndex()- if (watchFolder) this.watchFolder()+ const gen = this.gen+ this.loaded = this.scanAsync()+ .then((changed) => {+ if (gen !== this.gen) return+ this.linksByKey()+ this.writeIndex()+ if (watchFolder) this.watchFolder()+ if (changed) this.onChange()+ })+ .catch((e: unknown) => console.error('[wiki]', e))+ }++ // Links kept by the target's lowercase title before: by its key now (see pageKey), once. After a scan.+ private linksByKey(): void {+ if (this.getMeta('linksByKey')) return+ for (const r of this.db.prepare('SELECT file FROM pages').all() as { file: string }[]) {+ const path = join(this.pagesDir, r.file)+ if (existsSync(path)) this.indexLinks(r.file, parsePage(readFileSync(path, 'utf8')))+ }+ this.setMeta('linksByKey', '1')}// Another folder: the index is that folder's own; what was in the old one stays there.@@ -329,6 +384,7 @@ export class Wiki {}close(): void {+ this.gen++this.watcher?.close()if (this.timer) clearTimeout(this.timer)this.db?.close()@@ -340,25 +396,74 @@ export class Wiki {this.watcher = watch(this.pagesDir, { recursive: true }, () => {if (this.importing) returnif (this.timer) clearTimeout(this.timer)- this.timer = setTimeout(() => {- if (this.scan()) (this.writeIndex(), this.onChange())- }, 250)+ this.timer = setTimeout(() => this.rescan(), 250)})} catch {// Some file systems can't be watched: pages written by the app still index right away.}}+ // A change seen in the folder: read again behind, one read at a time.+ private rescan(): void {+ if (this.scanning) return void (this.rescanAfter = true)+ this.scanning = true+ const gen = this.gen+ void this.scanAsync()+ .then((changed) => {+ if (changed && gen === this.gen) (this.writeIndex(), this.onChange())+ })+ .catch((e: unknown) => console.error('[wiki]', e))+ .finally(() => {+ this.scanning = false+ if (this.rescanAfter && gen === this.gen) (this.rescanAfter = false), this.rescan()+ })+ }+// Brings the index in line with the folder. True when something changed.scan(): boolean {- const files = walk(this.pagesDir, this.isPage)- const known = new Map((this.db.prepare('SELECT file, hash, mtime FROM pages').all() as { file: string; hash: string; mtime: number }[]).map((r) => [r.file, r]))+ const found: [string, number][] = walk(this.pagesDir, this.isPage).map((file) => [file, Math.round(statSync(join(this.pagesDir, file)).mtimeMs)])+ const logs: string[] = []+ const changed = this.tx(() => this.applyFiles(found, false, logs))+ const left = this.tx(() => this.removeMissing(found, new Set(), false, logs))+ this.appendLog(...logs)+ return changed || left+ }++ // The same without blocking: the folder is read in the background, and the index brought in line+ // a few hundred files at a time (each batch one transaction), with a turn for the rest between.+ async scanAsync(): Promise<boolean> {+ const gen = this.gen+ const found = await walkTimes(this.pagesDir, this.isPage)+ const logs: string[] = []+ const gone = new Set<string>()+ let changed = false+ for (let i = 0; i < found.length; i += 200) {+ if (gen !== this.gen) return false+ if (this.tx(() => this.applyFiles(found.slice(i, i + 200), true, logs, gone))) changed = true+ await new Promise((r) => setImmediate(r))+ }+ if (gen !== this.gen) return false+ if (this.tx(() => this.removeMissing(found, gone, true, logs))) changed = true+ this.appendLog(...logs)+ return changed+ }++ // `late`: the files were listed a moment ago, so what the app wrote since is checked again+ // instead of taken for a change made outside (or for a page that left the folder).+ private applyFiles(found: [string, number][], late: boolean, logs: string[], gone = new Set<string>()): boolean {let changed = false- for (const file of files) {+ for (const [file, seen] of found) {const path = join(this.pagesDir, file)- const mtime = Math.round(statSync(path).mtimeMs)- const k = known.get(file)- known.delete(file)+ const k = this.db.prepare('SELECT hash, mtime FROM pages WHERE file = ?').get(file) as { hash: string; mtime: number } | undefined+ let mtime = seen+ if (late && k?.mtime !== mtime) {+ try {+ mtime = Math.round(statSync(path).mtimeMs)+ } catch {+ gone.add(file) // deleted since: it leaves the index below+ continue+ }+ }if (k && k.mtime === mtime) continueconst text = readFileSync(path, 'utf8')if (k && k.hash === sha(text)) {@@ -368,13 +473,22 @@ export class Wiki {const before = k ? this.bodyOf(file) : nullthis.indexFile(file, text, mtime, 'outside')this.version(this.titleOf(file, text), 'outside', k ? 'edit' : 'create', before, parsePage(text).body)- this.appendLog(k ? L(`[[${this.titleOf(file, text)}]] mudou fora do Tucano`, `[[${this.titleOf(file, text)}]] changed outside Tucano`) : L(`[[${this.titleOf(file, text)}]] apareceu na pasta`, `[[${this.titleOf(file, text)}]] showed up in the folder`))+ logs.push(k ? L(`[[${this.titleOf(file, text)}]] mudou fora do Tucano`, `[[${this.titleOf(file, text)}]] changed outside Tucano`) : L(`[[${this.titleOf(file, text)}]] apareceu na pasta`, `[[${this.titleOf(file, text)}]] showed up in the folder`))changed = true}- for (const file of known.keys()) {+ return changed+ }++ // The pages indexed but no longer in the folder.+ private removeMissing(found: [string, number][], gone: Set<string>, late: boolean, logs: string[]): boolean {+ const listed = new Set(found.map(([f]) => f))+ let changed = false+ for (const { file } of this.db.prepare('SELECT file FROM pages').all() as { file: string }[]) {+ if (listed.has(file) && !gone.has(file)) continue+ if (late && existsSync(join(this.pagesDir, file))) continue // written by the app after the listingconst title = (this.db.prepare('SELECT title FROM pages WHERE file = ?').get(file) as { title: string } | undefined)?.title ?? filethis.version(title, 'outside', 'delete', this.bodyOf(file), null)- this.appendLog(L(`${title} saiu da pasta`, `${title} left the folder`))+ logs.push(L(`${title} saiu da pasta`, `${title} left the folder`))this.unindex(file)this.release(title, true)changed = true@@ -382,6 +496,19 @@ export class Wiki {return changed}+ private tx<T>(fn: () => T): T {+ if (this.db.isTransaction) return fn()+ this.db.exec('BEGIN')+ try {+ const r = fn()+ this.db.exec('COMMIT')+ return r+ } catch (e) {+ this.db.exec('ROLLBACK')+ throw e+ }+ }+// A page is called by its file's name, as in Obsidian (that's what [[links]] point to).private titleOf(file: string, _text?: string): string {return file.split('/').pop()!.replace(/\.md$/, '')@@ -400,6 +527,7 @@ export class Wiki {}private indexFile(file: string, text: string, mtime: number, by: string): void {+ this.indexed++const { meta, body } = parsePage(text)const title = this.titleOf(file, text)this.unindex(file)@@ -414,6 +542,7 @@ export class Wiki {for (const target of new Set([...linksIn(body), ...linksIn(Object.values(meta).join('\n'))].map(pageKey))) this.db.prepare('INSERT INTO links (src, target) VALUES (?, ?)').run(file, target)}private unindex(file: string): void {+ this.indexed++this.db.prepare('DELETE FROM pages WHERE file = ?').run(file)this.db.prepare('DELETE FROM links WHERE src = ?').run(file)this.db.prepare('DELETE FROM fts WHERE file = ?').run(file)@@ -663,18 +792,30 @@ export class Wiki {return existsSync(p) ? readFileSync(p, 'utf8') : ''}- // The latest lines of the log, newest first.+ // The latest lines of the log, newest first. Read again only when the file changed: it only grows.log(limit = 30): string[] {- return this.logLines().slice(-limit).reverse()+ const lines = this.logLines()+ if (this.logShown?.from !== lines || this.logShown.limit !== limit) this.logShown = { from: lines, limit, list: lines.slice(-limit).reverse() }+ return this.logShown.list}+ private logShown?: { from: string[]; limit: number; list: string[] }// All of the log's lines, oldest first.private logLines(): string[] {const p = join(this.dir, LOG)- if (!existsSync(p)) return []- return readFileSync(p, 'utf8')+ let key: string+ try {+ const st = statSync(p)+ key = `${p}|${st.mtimeMs}|${st.size}`+ } catch {+ return []+ }+ if (this.logKept?.key === key) return this.logKept.lines+ const lines = readFileSync(p, 'utf8').split(/\r?\n/).filter((l) => l.startsWith('- ')).map((l) => l.slice(2))+ this.logKept = { key, lines }+ return lines}// ---------- writing ----------@@ -827,9 +968,11 @@ export class Wiki {return { ...saved, reheld: true }}- private appendLog(line: string): void {+ // Several lines at once, as a scan has them: the file is rewritten once, not once per page.+ private appendLog(...lines: string[]): void {+ if (!lines.length) returnconst when = new Date().toLocaleString(locale(), { dateStyle: 'short', timeStyle: 'short' })- writeFileSync(join(this.dir, LOG), `${existsSync(join(this.dir, LOG)) ? readFileSync(join(this.dir, LOG), 'utf8').replace(/\n*$/, '\n') : ''}- ${when} · ${line}\n`)+ writeFileSync(join(this.dir, LOG), `${existsSync(join(this.dir, LOG)) ? readFileSync(join(this.dir, LOG), 'utf8').replace(/\n*$/, '\n') : ''}${lines.map((l) => `- ${when} · ${l}\n`).join('')}`)}// índice.md: every page by kind, with its first line. Kept by Tucano, read by the agents.@@ -946,7 +1089,14 @@ export class Wiki {}// The pages and their links, for the map; a link to a page not written yet is a node too.+ // Made again only after the index changed.graph(): { nodes: { title: string; kind: string; links: number; missing?: boolean }[]; edges: [string, string][] } {+ if (this.graphKept?.at === this.indexed) return this.graphKept.graph+ const graph = this.makeGraph()+ this.graphKept = { at: this.indexed, graph }+ return graph+ }+ private makeGraph(): ReturnType<Wiki['graph']> {const pages = this.db.prepare('SELECT file, title, kind FROM pages').all() as { file: string; title: string; kind: string }[]const byFile = new Map(pages.map((p) => [p.file, p.title]))const byName = new Map(pages.map((p) => [pageKey(p.title), p.title]))diff --git a/src/main/index.ts b/src/main/index.tsindex f76b8d3..e08ef29 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -112,6 +112,20 @@ function startCore(workspace: Workspace): Runtime {return runtime}+// The workspace on screen starts first; the others follow it one at a time, a few seconds+// apart, so they don't all run their login shell and check every harness at once.+function startWorkspaces(): void {+ const first = registry.selected()+ const rest = registry.list().filter((w) => w.id !== first.id)+ void startCore(first).ready.catch(() => {}).then(async () => {+ for (const w of rest) {+ await new Promise((r) => setTimeout(r, 5_000))+ if (quitting) return+ if (registry.list().some((x) => x.id === w.id)) startCore(w) // not deleted meanwhile+ }+ })+}+type CoreRequest =| { type: 'theme'; theme: Settings['theme']; initial?: boolean }| { type: 'ready' }@@ -776,7 +790,7 @@ if (moved === 'old-app-open' || moved === 'keychain-denied') {protocol.handle('tucano', serveArtifact)registry = new Workspaces(dataDir())nativeTheme.themeSource = registry.theme() ?? 'system'- for (const workspace of registry.list()) startCore(workspace)+ startWorkspaces()// The Mac wakes for a few seconds at a time while asleep (maintenance, "DarkWake"):// routines wait for a real wake, so a run doesn't start and freeze mid-way.powerMonitor.on('suspend', () => { for (const r of cores.values()) r.child.postMessage({ type: 'power', awake: false }) })diff --git a/src/preload/index.ts b/src/preload/index.tsindex b47a1dc..0ae6f97 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -53,8 +53,11 @@ contextBridge.exposeInMainWorld('tucano', {open: (id: string): void => ipcRenderer.send('servers:open', id),local: (): void => ipcRenderer.send('servers:local'),forget: (id: string): Promise<unknown> => ipcRenderer.invoke('servers:forget', id),- onChanged: (cb: () => void): void => {- ipcRenderer.on('servers', () => cb())+ // Returns how to stop listening: each screen showing the list listens while it's open.+ onChanged: (cb: () => void): (() => void) => {+ const listener = (): void => cb()+ ipcRenderer.on('servers', listener)+ return () => ipcRenderer.removeListener('servers', listener)}}})diff --git a/src/renderer/src/components/Conversation.tsx b/src/renderer/src/components/Conversation.tsxindex c2814b6..9fad871 100644--- a/src/renderer/src/components/Conversation.tsx+++ b/src/renderer/src/components/Conversation.tsx@@ -4,16 +4,27 @@ import Markdown, { type ExtraProps } from 'react-markdown'import { safeUrl } from '../links'import { remarkLocalPaths } from '../../../shared/path-text'import { remarkMentions, splitMentions } from '../../../shared/mention-text'-import { asSaid, saidAt } from '../../../shared/types'+import { saidAt } from '../../../shared/types'import { localLinkFor } from './LocalLink'import remarkGfm from 'remark-gfm'import { KeepInWiki, WikiChip, WikiLink, wikiLinks } from './Wiki'import { canEditChannel,agentById,+ askerIn,+ attachedTo,+ conversationIndex,initials,isMine,personName,conversationTitle,+ lastBrowserIn,+ loadOlder,+ loadThread,+ messageById,+ repliesOf,+ timelineOf,+ useLiveText,+ workingIds,openDialog,decideApproval,decideMemory,@@ -45,6 +56,7 @@ import { canEditChannel,SUMMARY_WINDOW,type Agent,type Approval,+ type Artifact,type Conversation,type ImageUpload,type Author,@@ -129,8 +141,16 @@ export function ConversationView({ id }: { id: string }): ReactNode {const all = conv.members.map((m) => agentById(s, m)).filter((a): a is Agent => !!a)return conv.kind === 'dm' ? all : all.filter(isTeam)})- const messages = useStore((s) => s.messages.filter((m) => m.conversationId === id))+ const timeline = useStore((s) => timelineOf(s, id))+ // The index, not its Map: useStore's shallow compare finds no keys in a Map and would keep the first one.+ const { replies } = useStore((s) => conversationIndex(s, id))+ const older = useStore((s) => !!s.history[id])const focus = useStore((s) => (s.view?.kind === 'conversation' && s.view.id === id ? s.view.message : undefined))+ // Opened on a message from before what's here (a routine's run, a report): it comes first.+ const focusHere = !!focus && timeline.some((m) => m.id === focus)+ useEffect(() => {+ if (focus && !focusHere) void loadOlder(id, focus)+ }, [id, focus, focusHere])const thread = useStore((s) => (s.panel?.kind === 'thread' ? s.panel.id : undefined))const [showSummary, setShowSummary] = useState(false)const firstChannel = useStore((s) => s.conversations.find((c) => c.kind === 'channel'))@@ -195,9 +215,9 @@ export function ConversationView({ id }: { id: string }): ReactNode {</div></header>- {showSummary && <SummaryPanel conv={conv} messages={messages.filter((m) => !m.threadId)} onClose={() => setShowSummary(false)} />}+ {showSummary && <SummaryPanel conv={conv} messages={timeline} onClose={() => setShowSummary(false)} />}- <MessageList messages={messages} conversationId={id} empty={conv.kind === 'channel' && members.length === 0} focus={focus} threads />+ <MessageList messages={timeline} replies={replies} older={older} conversationId={id} empty={conv.kind === 'channel' && members.length === 0} focus={focus} /><Composer conversationId={id} members={members} placeholder={dmAgent ? L(`Mensagem pra ${dmAgent.name}`, `Message ${dmAgent.name}`) : L(`Mensagem em #${title}`, `Message #${title}`)} /></section>{thread ? <ThreadPanel rootId={thread} conv={conv} title={conv.kind === 'channel' ? `#${title}` : title} members={members} /> : <SidePanel />}@@ -207,8 +227,9 @@ export function ConversationView({ id }: { id: string }): ReactNode {const NO_REPLIES: Message[] = []-// `threads`: the timeline shows only what's outside threads, and each message can start one.-export function MessageList({ messages: all, conversationId, empty, focus, threads, lead }: { messages: Message[]; conversationId: string; empty?: boolean; focus?: string; threads?: boolean; lead?: ReactNode }): ReactNode {+// `replies`: a timeline with threads, where each message can start one (its replies by its id).+// `older`: there's more before the first message, loaded as the scroll gets near the top.+export function MessageList({ messages, replies, older, conversationId, empty, focus, lead }: { messages: Message[]; replies?: Map<string, Message[]>; older?: boolean; conversationId: string; empty?: boolean; focus?: string; lead?: ReactNode }): ReactNode {const editsChannel = useStore((s) => {const c = s.conversations.find((x) => x.id === conversationId)return !!c && canEditChannel(s, c)@@ -216,28 +237,19 @@ export function MessageList({ messages: all, conversationId, empty, focus, threaconst ref = useRef<HTMLDivElement>(null)const stick = useRef(true)const [farFromBottom, setFarFromBottom] = useState(false)- const { messages, replies } = useMemo(() => {- const said = asSaid(all)- if (!threads) return { messages: said, replies: undefined }- const replies = new Map<string, Message[]>()- for (const m of said) {- if (!m.threadId) continue- const list = replies.get(m.threadId)- if (list) list.push(m)- else replies.set(m.threadId, [m])- }- return { messages: said.filter((m) => !m.threadId), replies }- }, [all, threads])+ const [loading, setLoading] = useState(false)+ const before = useRef<{ height: number; top: number } | null>(null) // the list as it was, while older messages come// In a DM, whose it is (for the empty state).const dmName = useStore((s) => {const c = s.conversations.find((x) => x.id === conversationId)return c?.kind === 'dm' && c.members[0] ? agentById(s, c.members[0])?.name : undefined})- // Opened on a message (a routine's run, say): scroll to it and flash it once.+ // Opened on a message (a routine's run, say): scroll to it and flash it once. It may come a moment+ // later, from further back.+ const focusAt = focus ? messages.findIndex((m) => m.id === focus) : -1useEffect(() => {- const i = focus ? messages.findIndex((m) => m.id === focus) : -1- const el = i >= 0 ? (ref.current?.children[i + (lead ? 1 : 0)] as HTMLElement | undefined) : undefined+ const el = focus && focusAt >= 0 ? ref.current?.querySelector<HTMLElement>(`:scope > [data-id="${CSS.escape(focus)}"]`) : nullif (!el) returnstick.current = falseel.scrollIntoView({ block: 'center' })@@ -245,7 +257,7 @@ export function MessageList({ messages: all, conversationId, empty, focus, threaconst t = setTimeout(() => el.classList.remove('is-flash'), 1800)return () => clearTimeout(t)// eslint-disable-next-line react-hooks/exhaustive-deps- }, [focus, conversationId])+ }, [focus, conversationId, focusAt >= 0])useEffect(() => {if (!lead) stick.current = true@@ -253,9 +265,48 @@ export function MessageList({ messages: all, conversationId, empty, focus, threa// eslint-disable-next-line react-hooks/exhaustive-deps}, [conversationId])+ // To the end when a message arrives or changes there; the rows growing on their own (a reply+ // streaming, an image loading) are watched below, so a word streamed doesn't lay the list out again.+ const last = messages.at(-1)useLayoutEffect(() => {const el = ref.currentif (el && stick.current) el.scrollTop = el.scrollHeight+ }, [last, messages.length])+ useEffect(() => {+ const el = ref.current+ if (!el) return+ const watch = new ResizeObserver(() => {+ if (stick.current) el.scrollTop = el.scrollHeight+ })+ for (const row of el.children) watch.observe(row)+ return () => watch.disconnect()+ })++ // Older messages came in above: what was on screen stays where it was (unless the browser kept it already).+ const first = messages[0]?.id+ useLayoutEffect(() => {+ const el = ref.current+ const was = before.current+ before.current = null+ if (!el || !was) return+ const grown = el.scrollHeight - was.height+ if (grown > 0 && Math.abs(el.scrollTop - was.top) < 2) el.scrollTop = was.top + grown+ }, [first])++ const more = (el: HTMLDivElement): void => {+ if (!older || loading || el.scrollTop > 800) return+ setLoading(true)+ before.current = { height: el.scrollHeight, top: el.scrollTop }+ void loadOlder(conversationId).finally(() => setLoading(false))+ }+ // Too little to scroll: the page before comes without waiting for a scroll (once per page, so a+ // failure doesn't ask again and again).+ const tried = useRef<string | undefined>(undefined)+ useEffect(() => {+ const el = ref.current+ if (!el || tried.current === first) return+ tried.current = first+ more(el)})// A thread opens at its latest message, like Slack: the message that started it is a scroll up.@@ -310,8 +361,10 @@ export function MessageList({ messages: all, conversationId, empty, focus, threaconst fromBottom = el.scrollHeight - el.scrollTop - el.clientHeightstick.current = fromBottom < 60setFarFromBottom(fromBottom > el.clientHeight / 2)+ more(el)}}>+ {loading && <div className="messages__older muted small">{L('Carregando mensagens anteriores…', 'Loading earlier messages…')}</div>}{lead}{messages.map((m, i) => {const prev = messages[i - 1]@@ -342,6 +395,8 @@ const PLAIN_PLUGINS = [remarkGfm, remarkMentions]// Parsing is by far the most expensive part of drawing a message, so it only runs when the text changes.const MessageMarkdown = memo(Markdown)+const STREAM_MS = 140 // a streaming reply's Markdown, about 7 times a second+const NO_ATTACHED: Artifact[] = []// `replies`: in a timeline with threads, the replies to this message (none yet: empty).// Memoized because each word an agent streams redraws the list: only the row that changed should pay for it.@@ -353,21 +408,25 @@ const MessageRow = memo(function MessageRow({ message, grouped, replies }: { mesconst approval = useStore((s) => (message.run?.approvalId ? s.approvals.find((a) => a.id === message.run!.approvalId) : undefined))// Someone else's message reads with their name and initials; mine, as always.const other = useStore((s) => (message.author.kind === 'person' && !isMine(s, message.author) ? personName(s, message.author.id) : undefined))- const attached = useStore((s) => (message.author.kind === 'person' ? s.artifacts.filter((a) => a.messageId === message.id && a.agentId === '') : []))+ const attached = useStore((s) => (message.author.kind === 'person' ? attachedTo(s, message.id) : NO_ATTACHED))// The browser shows live on the agent's latest message that used it, unless it's open on the side.const liveBrowser = useStore((s) =>!!message.run?.browser &&!(s.panel?.kind === 'browser' && s.panel.agentId === agent?.id) &&- s.messages.findLast((m) => m.conversationId === message.conversationId && m.run?.browser && m.author.kind === 'agent' && m.author.id === agent?.id)?.id === message.id+ !!agent &&+ lastBrowserIn(s, message.conversationId, agent.id) === message.id)+ // Streamed words wake only this row; while they come, the Markdown is drawn a few times a second,+ // whole again once the reply ends.+ const text = useLiveText(message, message.run?.status === 'working' ? STREAM_MS : 0)// The same object between renders, or every link would start over.const agentMarkdown = useMemo(() => ({ pre: CodeBlock, a: localLinkFor(message.id), span: MentionSpan }), [message.id])if (message.author.kind === 'system') {return (- <div className={`system-line ${message.run?.status === 'working' ? 'is-pending' : ''}`}>+ <div className={`system-line ${message.run?.status === 'working' ? 'is-pending' : ''}`} data-id={message.id}><Icon name="spark" size={13} /><SystemText text={message.text} /><span className="muted">{time(message.at)}</span>@@ -380,7 +439,7 @@ const MessageRow = memo(function MessageRow({ message, grouped, replies }: { mesconst name = agent ? agent.name : (other ?? me.name)return (// Someone else's message reads like any other voice in the conversation: on the left, with their name.- <article className={`msg ${agent ? 'msg--agent' : other ? 'msg--agent msg--person' : 'msg--me'} ${grouped ? 'msg--grouped' : ''} ${threadOpen ? 'is-thread-open' : ''}`}>+ <article className={`msg ${agent ? 'msg--agent' : other ? 'msg--agent msg--person' : 'msg--me'} ${grouped ? 'msg--grouped' : ''} ${threadOpen ? 'is-thread-open' : ''}`} data-id={message.id}><div className="msg__gutter">{!grouped && (agent ? <AgentAvatar agent={agent} size={34} busy={message.run?.status === 'working'} /> : <MeAvatar initials={other ? initials(other) : me.initials} size={34} />)}</div>@@ -403,12 +462,12 @@ const MessageRow = memo(function MessageRow({ message, grouped, replies }: { mes</div>)}{message.run && <RunSteps message={message} />}- {message.text ? (+ {text ? (<div className="md">{agent && message.run?.status !== 'working' ? (- <MessageMarkdown urlTransform={safeUrl} remarkPlugins={AGENT_PLUGINS} components={agentMarkdown}>{wikiLinks(message.text)}</MessageMarkdown>+ <MessageMarkdown urlTransform={safeUrl} remarkPlugins={AGENT_PLUGINS} components={agentMarkdown}>{wikiLinks(text)}</MessageMarkdown>) : (- <MessageMarkdown urlTransform={safeUrl} remarkPlugins={PLAIN_PLUGINS} components={plainMarkdown}>{wikiLinks(message.text)}</MessageMarkdown>+ <MessageMarkdown urlTransform={safeUrl} remarkPlugins={PLAIN_PLUGINS} components={plainMarkdown}>{wikiLinks(text)}</MessageMarkdown>)}</div>) : null}@@ -481,7 +540,7 @@ function RoutineMessage({ message, replies }: { message: Message; replies?: Messconst exists = useStore((s) => s.routines.some((r) => message.author.kind === 'routine' && r.id === message.author.id))const info = message.routinereturn (- <article className="msg msg--routine">+ <article className="msg msg--routine" data-id={message.id}><div className="msg__gutter"><span className="avatar avatar--routine" style={{ width: 34, height: 34 }}><Icon name="clock" size={17} />@@ -628,8 +687,14 @@ function ThreadLink({ message, replies }: { message: Message; replies: Message[]// A thread on the side: the message that started it, set apart, then its replies and a// field that answers there.function ThreadPanel({ rootId, conv, title, members }: { rootId: string; conv: Conversation; title: string; members: Agent[] }): ReactNode {- const root = useStore((s) => s.messages.find((m) => m.id === rootId))- const replies = useStore((s) => s.messages.filter((m) => m.threadId === rootId))+ const root = useStore((s) => messageById(s, rootId, conv.id))+ const replies = useStore((s) => repliesOf(s, conv.id, rootId))+ // A thread from before what's here comes from the core; only then is it gone if it isn't there.+ const [looked, setLooked] = useState<string | null>(null)+ useEffect(() => {+ if (!root) void loadThread(rootId).finally(() => setLooked(rootId))+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [rootId, !root])const agents = useStore((s) => s.agents)const [showSummary, setShowSummary] = useState(false)const said = replies.filter((m) => m.author.kind !== 'system' && m.run?.status !== 'working').length@@ -691,9 +756,9 @@ function ThreadPanel({ rootId, conv, title, members }: { rootId: string; conv: C<MessageList key={rootId} messages={replies} conversationId={conv.id} lead={lead} /><Composer conversationId={conv.id} threadId={rootId} members={members} placeholder={L('Responder na thread…', 'Reply in thread…')} /></>- ) : (+ ) : looked === rootId || root ? (<p className="empty">{L('Essa mensagem não está mais aqui.', 'That message is no longer here.')}</p>- )}+ ) : null}</aside>)}@@ -1626,6 +1691,8 @@ function RecordingClock({ since }: { since: number }): ReactNode {)}+// The field sizes itself to its text where CSS can (styles.css: field-sizing).+const FIELD_SIZING = typeof CSS !== 'undefined' && CSS.supports('field-sizing', 'content')const TYPE = ['font-family', 'font-size', 'font-weight', 'line-height', 'letter-spacing', 'word-spacing', 'tab-size', 'text-transform', 'text-indent', 'padding']// `threadId`: it answers in the thread that message started, not in the conversation.@@ -1649,12 +1716,12 @@ export function Composer({ conversationId, threadId, members, placeholder }: { cconst team = useStore(teamMode)const people = useStore((s) => s.people)const you = useStore((s) => s.you)- // Replies at work and questions asked here: in this thread, or outside threads.- const here = (m: Message): boolean => m.conversationId === conversationId && m.threadId === threadId- const working = useStore((s) => s.messages.filter((m) => here(m) && m.author.kind === 'agent' && m.run?.status === 'working'))+ // Replies at work and questions asked here: in this thread, or outside threads. Ids, not the+ // messages, so a reply's steps don't redraw the field.+ const working = useStore((s) => workingIds(s, conversationId, threadId))// With a team, only a question my message would answer (mine, or one I may answer) asks me here.const asker = useStore((s) => {- const q = s.messages.findLast((m) => here(m) && m.run?.status === 'waiting_input')+ const q = askerIn(s, conversationId, threadId)if (q && teamMode(s) && q.run?.askedTo && !s.inbox.questions.some((x) => x.id === q.id && x.confirm !== 'pending')) return undefinedreturn q?.author.kind === 'agent' ? agentById(s, q.author.id)?.name : undefined})@@ -1668,6 +1735,8 @@ export function Composer({ conversationId, threadId, members, placeholder }: { cwindow.addEventListener('tucano:reloading', save)return () => window.removeEventListener('tucano:reloading', save)}, [key])+ // Opened: the agent that answers here gets its process up while the person reads.+ useEffect(() => typing(conversationId, threadId, true), [conversationId, threadId])useEffect(() => {const draft = drafts.get(key)setText(draft?.text ?? '')@@ -1747,23 +1816,28 @@ export function Composer({ conversationId, threadId, members, placeholder }: { c}}, [inThread])- // The field grows with its text, up to a point; on a narrower window the same text takes more lines.+ // The field grows with its text, up to a point. With CSS field-sizing (Electron has it) that takes no+ // measuring on each key; elsewhere (a browser, on a server) the height is set from the text.const fit = (): void => {const el = ref.current- if (!el) return+ if (!el || FIELD_SIZING) returnel.style.height = 'auto'el.style.height = `${Math.min(el.scrollHeight, 220)}px`- followField()}useLayoutEffect(fit, [text])+ // The copy follows the field's size as it changes (a new line, a narrower window), and takes its+ // type again only when the width changes (a phone's breakpoint): not on every key.useEffect(() => {const el = ref.currentif (!el) return- let width = el.clientWidth+ let width = -1const watch = new ResizeObserver(() => {- if (el.clientWidth === width) return // only a new width changes the lines; fit's own height doesn't- width = el.clientWidth- fit()+ if (el.clientWidth !== width) {+ width = el.clientWidth+ fit()+ copyType()+ }+ followField()})watch.observe(el)return () => watch.disconnect()@@ -1773,12 +1847,17 @@ export function Composer({ conversationId, threadId, members, placeholder }: { c// on top keeps the caret and the selection. The copy takes the field's type as computed (a phone// gets 16 px, and a field doesn't inherit letter spacing), its width (a scrollbar takes some) and// its size and its scroll, so both break the lines in the same places and scroll as far.- const followField = (): void => {+ const copyType = (): void => {const el = ref.currentconst m = mirror.currentif (!el || !m) returnconst field = getComputedStyle(el)for (const p of TYPE) m.style.setProperty(p, field.getPropertyValue(p))+ }+ const followField = (): void => {+ const el = ref.current+ const m = mirror.current+ if (!el || !m) returnm.style.width = `${el.clientWidth}px`m.style.height = `${el.clientHeight}px`m.scrollTop = el.scrollTop@@ -1965,7 +2044,7 @@ export function Composer({ conversationId, threadId, members, placeholder }: { c{note || (members[0]?.kind === 'tuca' ? L('Nada é criado sem você', 'Nothing is created without you') : threadId ? L('Fica nesta thread · @ chama alguém', 'Stays in this thread · @ calls someone') : isDm ? L(`${members[0]?.name ?? 'O agente'} sempre responde aqui`, `${members[0]?.name ?? 'The agent'} always replies here`) : L('Quem estiver no canal responde · pra chamar alguém, use @', 'Whoever is in the channel replies · to call on someone, use @'))}</span>{working.length > 0 ? (- <button className="btn btn--sm" onClick={() => working.forEach((m) => stopRun(m.id))}>+ <button className="btn btn--sm" onClick={() => working.forEach((id) => stopRun(id))}><Icon name="stop" size={12} /> {L('Parar', 'Stop')}</button>) : null}diff --git a/src/renderer/src/components/Harness.tsx b/src/renderer/src/components/Harness.tsxindex 11e9f3e..239a9fa 100644--- a/src/renderer/src/components/Harness.tsx+++ b/src/renderer/src/components/Harness.tsx@@ -233,7 +233,7 @@ function HarnessRow({ engine, st, picked, toggle }: { engine: EngineId; st: Engi<label className="grow harness__name" htmlFor={checkId}><strong>{ENGINES[engine].label}</strong><span className="harness__account">- {!st.installed ? L('Não instalado', 'Not installed') : st.account ?? (st.loggedIn ? L('Pronto', 'Ready') : L('Falta entrar', 'Not signed in'))}+ {st.checking ? L('Conferindo…', 'Checking…') : !st.installed ? L('Não instalado', 'Not installed') : st.account ?? (st.loggedIn ? L('Pronto', 'Ready') : L('Falta entrar', 'Not signed in'))}</span></label>{st.soon ? (diff --git a/src/renderer/src/components/Onboarding.tsx b/src/renderer/src/components/Onboarding.tsxindex 3fbf5b4..b52f27c 100644--- a/src/renderer/src/components/Onboarding.tsx+++ b/src/renderer/src/components/Onboarding.tsx@@ -30,6 +30,8 @@ import {ensureTuca,settleDraft,updateSettings,+ anyReplyDone,+ messagesIn,useStore,type Agent,type AgentColor,@@ -726,7 +728,7 @@ function MeetTuca({ conv: session, onUse, onManual, onBack }: { conv: { id?: str}, [build, model, tuca?.modelId])useEffect(() => () => clearTimeout(typed.current), [])const error = session.error ?? ''- const messages = useStore((s) => (conv ? s.messages.filter((m) => m.conversationId === conv) : []))+ const messages = useStore((s) => (conv ? messagesIn(s, conv) : []))const latest = [...messages].reverse().find((m) => m.run?.agentDraft && !m.run.agentDraft.state)?.run?.agentDraftasync function start(value: string): Promise<void> {@@ -1134,7 +1136,7 @@ const ITEMS = (): Item[] => [id: 'reply',title: L('Ver um agente trabalhando', 'Watch an agent work'),how: L('Mande uma tarefa e acompanhe cada passo na conversa.', 'Send a task and follow every step in the conversation.'),- done: (s) => s.messages.some((m) => m.author.kind === 'agent' && m.run?.status === 'done'),+ done: anyReplyDone,go: firstChannel,action: L('Abrir canal', 'Open channel')},diff --git a/src/renderer/src/components/Panel.tsx b/src/renderer/src/components/Panel.tsxindex 3a878b6..e9f5cfb 100644--- a/src/renderer/src/components/Panel.tsx+++ b/src/renderer/src/components/Panel.tsx@@ -5,7 +5,7 @@ import { useEffect, useState, type ReactNode } from 'react'import Markdown from 'react-markdown'import { safeUrl } from '../links'import remarkGfm from 'remark-gfm'-import { agentById, amAdmin, getState, openLightbox, artifactUrl, browserAction, browserInput, browserOf, reachable, windowless, computerOf, openExternal, openPanel, stopService, useStore, type Artifact } from '../store'+import { agentById, amAdmin, getState, openLightbox, artifactUrl, browserAction, browserInput, browserOf, reachable, windowless, computerOf, openExternal, openPanel, stopService, useFrame, useStore, workingAgents, type Artifact } from '../store'import { call } from '../rpc'import { Icon, ownColor, type IconName } from './ui'@@ -117,7 +117,7 @@ const clock = (at: number): string => new Date(at).toLocaleTimeString(locale(),// Live while the agent is answering with it, or while I drive it.function useLive(agentId: string): boolean {- const working = useStore((s) => s.messages.some((m) => m.author.kind === 'agent' && m.author.id === agentId && m.run?.status === 'working'))+ const working = useStore((s) => workingAgents(s).has(agentId))const view = useStore((s) => browserOf(s, agentId))return working || !!view?.doing || !!view?.shown}@@ -156,9 +156,10 @@ function UrlBar({ url }: { url: string }): ReactNode {// The screen: what Chrome streams, with the agent's cursor where it last clicked or typed.function BrowserScreen({ agentId, onOpen }: { agentId: string; onOpen?: () => void }): ReactNode {const view = useStore((s) => browserOf(s, agentId))+ const frame = useFrame(agentId) // apart from the view: it changes many times a secondconst agent = useStore((s) => agentById(s, agentId))const live = useLive(agentId)- if (!view?.frame)+ if (!view || !frame)return (<div className="screen screen--empty"><Icon name="globe" size={22} />@@ -168,10 +169,10 @@ function BrowserScreen({ agentId, onOpen }: { agentId: string; onOpen?: () => voconst c = view.cursor// Taken over on a server: the picture is the browser. Clicks land where I click,// keys and pastes go to the page, the wheel scrolls it.- if (view.shown && windowless() && !onOpen) return <DrivenScreen agentId={agentId} frame={view.frame} title={view.title} />+ if (view.shown && windowless() && !onOpen) return <DrivenScreen agentId={agentId} frame={frame} title={view.title} />return (<div className={`screen ${onOpen ? 'screen--button' : ''}`} onClick={onOpen} role={onOpen ? 'button' : undefined}>- <img className="screen__frame" src={view.frame} alt={view.title} draggable={false} />+ <img className="screen__frame" src={frame} alt={view.title} draggable={false} />{c && !view.shown && agent && (<span className={`screen__cursor c-${agent.color} ${live ? '' : 'is-idle'}`} style={{ ...ownColor(agent), transform: `translate(${c.x * 100}%, ${c.y * 100}%)` }}><i key={c.at} className="screen__ripple" />@@ -291,6 +292,7 @@ function TakeOver({ agentId }: { agentId: string }): ReactNode {// with what it did. Older messages get a small card.export function BrowserCard({ agentId, big }: { agentId: string; big?: boolean }): ReactNode {const view = useStore((s) => browserOf(s, agentId))+ const frame = useFrame(agentId)const name = useStore((s) => agentById(s, agentId)?.name ?? L('agente', 'agent'))const open = useStore((s) => s.panel?.kind === 'browser' && s.panel.agentId === agentId)const show = (): void => openPanel({ kind: 'browser', agentId })@@ -324,8 +326,8 @@ export function BrowserCard({ agentId, big }: { agentId: string; big?: boolean }return (<button className={`artifact-card browser-card ${open ? 'is-open' : ''}`} onClick={show}>- {view?.frame ? (- <img className="browser-card__thumb" src={view.frame} alt="" />+ {frame ? (+ <img className="browser-card__thumb" src={frame} alt="" />) : (<span className="artifact-card__icon"><Icon name="globe" size={16} />diff --git a/src/renderer/src/components/Routines.tsx b/src/renderer/src/components/Routines.tsxindex d7f11a8..aa48bab 100644--- a/src/renderer/src/components/Routines.tsx+++ b/src/renderer/src/components/Routines.tsx@@ -16,6 +16,7 @@ import {useStore,type Message,type Routine,+ type State,type RoutineInput,type RunStatus,type Trigger,@@ -94,7 +95,7 @@ type Draft = RoutineInput & { conversationId: string } // '' while the agent's Dexport function RoutinesPage(): ReactNode {const routines = useStore((s) => s.routines)const agents = useStore((s) => s.agents.filter(isTeam))- const messages = useStore((s) => s.messages)+ const runs = useStore(allRuns)const [draft, setDraft] = useState<Draft | null>(null)const [week, setWeek] = useState(() => startOfWeek(Date.now()))const [open, setOpen] = useState<{ occ: Occ; rect: DOMRect } | null>(null)@@ -136,7 +137,7 @@ export function RoutinesPage(): ReactNode {const days = Array.from({ length: 7 }, (_, i) => dayAt(week, i))const end = dayAt(week, 7)- const occs = [...runsOf(messages, routines), ...planned(routines, week, now)].filter((o) => o.at >= week && o.at < end)+ const occs = [...runs, ...planned(routines, week, now)].filter((o) => o.at >= week && o.at < end)const watching = routines.filter((r) => r.enabled && r.trigger)const finished = (r: Routine): boolean => !r.enabled && !!r.schedule.once && !!r.lastAt && !r.triggerconst off = routines.filter((r) => !r.enabled && !finished(r))@@ -294,14 +295,31 @@ const dayAt = (week: number, i: number): number => {}const hm = (t: number): string => new Date(t).toLocaleTimeString(locale(), { hour: '2-digit', minute: '2-digit' })-// What actually ran: each request a routine posted, with the agent's reply after it.+// What actually ran: each request a routine posted, with the agent's reply after it. Worked out per+// conversation, once per change of it, so a reply elsewhere doesn't redo the calendar.+const runsCache = new WeakMap<Message[], { routines: Routine[]; occs: Occ[] }>()+function allRuns(s: State): Occ[] {+ return Object.values(s.messages).flatMap((list) => {+ const had = runsCache.get(list)+ if (had?.routines === s.routines) return had.occs+ const occs = runsOf(list, s.routines)+ runsCache.set(list, { routines: s.routines, occs })+ return occs+ })+}++// In one conversation's messages, oldest first.function runsOf(messages: Message[], routines: Routine[]): Occ[] {const out: Occ[] = []messages.forEach((ask, i) => {if (ask.author.kind !== 'routine') returnconst id = ask.author.idconst r = routines.find((x) => x.id === id)- const reply = messages.slice(i + 1).find((m) => m.conversationId === ask.conversationId && m.author.kind === 'agent' && (!r || m.author.id === r.agentId))+ let reply: Message | undefined+ for (let j = i + 1; j < messages.length && !reply; j++) {+ const m = messages[j]!+ if (m.author.kind === 'agent' && (!r || m.author.id === r.agentId)) reply = m+ }const agentId = r?.agentId ?? (reply?.author.kind === 'agent' ? reply.author.id : undefined)if (!agentId) returnout.push({ key: ask.id, routine: r, name: r?.name ?? ask.routine?.name ?? L('Rotina', 'Routine'), agentId, at: ask.at, conversationId: ask.conversationId, status: reply?.run?.status, replyId: reply?.id })@@ -530,7 +548,7 @@ function Popover({ occ, rect, now, onClose, onEdit }: { occ: Occ; rect: DOMRect;const r = useStore((s) => (occ.routine ? s.routines.find((x) => x.id === occ.routine!.id) : undefined))const agent = useStore((s) => agentById(s, occ.agentId))const conv = useStore((s) => s.conversations.find((c) => c.id === (r?.conversationId ?? occ.conversationId)))- const history = useStore((s) => (r ? runsOf(s.messages, [r]).filter((o) => o.routine) : []))+ const history = useStore((s) => (r ? allRuns(s).filter((o) => o.routine?.id === r.id) : []))const connector = useStore((s) => (r?.trigger?.kind === 'poll' ? s.connectors.find((c) => c.id === (r.trigger as { connectorId: string }).connectorId) : undefined))const [confirm, setConfirm] = useState(false)// Someone else's own routine, or the channel's for a member: seen, not changed here (the editor says why).diff --git a/src/renderer/src/components/Servers.tsx b/src/renderer/src/components/Servers.tsxindex 4111a18..ca4c0d3 100644--- a/src/renderer/src/components/Servers.tsx+++ b/src/renderer/src/components/Servers.tsx@@ -20,9 +20,10 @@ export function ServersCard(): ReactNode {let alive = trueconst load = (): void => void api.list().then((l) => alive && setList(l))load()- api.onChanged(load)+ const off = api.onChanged(load)return () => {alive = false+ off()}}, [api])@@ -111,9 +112,10 @@ export function useServers(): Server[] {let alive = trueconst load = (): void => void api.list().then((l) => alive && setList(l))load()- api.onChanged(load)+ const off = api.onChanged(load)return () => {alive = false+ off()}}, [api])return listdiff --git a/src/renderer/src/components/Sidebar.tsx b/src/renderer/src/components/Sidebar.tsxindex ac77f76..f79d39f 100644--- a/src/renderer/src/components/Sidebar.tsx+++ b/src/renderer/src/components/Sidebar.tsx@@ -1,8 +1,9 @@import { L } from '../../../shared/lang'-import { useCallback, useRef, useState, type HTMLAttributes, type ReactNode } from 'react'+import { memo, useCallback, useRef, useState, type HTMLAttributes, type ReactNode } from 'react'import {agentById,archiveAgent,+ isWorking,openTuca,isTeam,deleteConversation,@@ -108,16 +109,24 @@ function GroupFold({ id, label, unread, head, naming, children }: { id: string;const unreadIn = (conversations: { unread?: number }[]): number => conversations.reduce((sum, c) => sum + (c.unread ?? 0), 0)export function Sidebar(): ReactNode {- const s = useStore((s) => s)- const channels = s.conversations.filter((c) => c.kind === 'channel')- const dms = s.conversations.filter((c) => c.kind === 'dm' && agentById(s, c.name)?.kind !== 'tuca')+ // Only what it draws: the whole state changes with every step an agent takes.+ const conversations = useStore((s) => s.conversations)+ const agents = useStore((s) => s.agents)+ const settings = useStore((s) => s.settings)+ const platform = useStore((s) => s.platform)+ const people = useStore((s) => s.people)+ const you = useStore((s) => s.you)// With a team: who I am, what waits on me, and only what my role may change.- const team = teamMode(s)- const admin = amAdmin(s)- const me = youPerson(s)- const pending = team ? inboxCount(s) : pendingApprovals(s).length- const suggestions = pendingMemories(s).length- const proposals = s.skills.filter((k) => k.state === 'pending').length+ const team = teamMode({ people })+ const admin = amAdmin({ people, you })+ const owner = amOwner({ people, you })+ const me = youPerson({ people, you })+ const pending = useStore((s) => (teamMode(s) ? inboxCount(s) : pendingApprovals(s).length))+ const suggestions = useStore((s) => pendingMemories(s).length)+ const proposals = useStore((s) => s.skills.filter((k) => k.state === 'pending').length)+ const agentOf = (id: string): Agent | undefined => agents.find((a) => a.id === id)+ const channels = conversations.filter((c) => c.kind === 'channel')+ const dms = conversations.filter((c) => c.kind === 'dm' && agentOf(c.name)?.kind !== 'tuca')const [menu, setMenu] = useState<MenuState>(null)const closeMenu = useCallback(() => setMenu(null), [])const open = (e: React.MouseEvent, items: MenuItem[]): void => {@@ -125,7 +134,7 @@ export function Sidebar(): ReactNode {setMenu({ x: e.clientX, y: e.clientY, items })}// The order and groups are the person's: the core only keeps them.- const layout = s.settings.channelLayout+ const layout = settings.channelLayoutconst arranged = arrange(channels, layout)const whole: ChannelLayout = { loose: arranged.loose.map((c) => c.id), groups: arranged.groups.map((g) => ({ ...g, channels: g.channels.map((c) => c.id) })) }const saveLayout = (next: ChannelLayout): void => updateSettings({ channelLayout: next })@@ -174,10 +183,10 @@ export function Sidebar(): ReactNode {onClick: () => void call('setWikiCapture', { conversationId: id, on: !on })})const channelMenu = (c: (typeof channels)[number]): MenuItem[] => [- ...(canEditChannel(s, c) ? [{ label: L('Adicionar ou remover agentes…', 'Add or remove agents…'), icon: 'users' as const, onClick: () => openDialog({ kind: 'members', id: c.id }) }] : []),+ ...(canEditChannel({ people, you }, c) ? [{ label: L('Adicionar ou remover agentes…', 'Add or remove agents…'), icon: 'users' as const, onClick: () => openDialog({ kind: 'members', id: c.id }) }] : []),{ label: L('Configurações do canal…', 'Channel settings…'), icon: 'gear', onClick: () => openDialog({ kind: 'settings', id: c.id }) },...(c.unread ? [{ label: L('Marcar como lido', 'Mark as read'), icon: 'check' as const, onClick: () => markRead(c.id) }] : []),- ...(canEditChannel(s, c) ? [wikiItem(c.id, c.wikiCapture !== false)] : []),+ ...(canEditChannel({ people, you }, c) ? [wikiItem(c.id, c.wikiCapture !== false)] : []),...channelMenuRest(c)]const channelMenuRest = (c: (typeof channels)[number]): MenuItem[] => [@@ -210,7 +219,7 @@ export function Sidebar(): ReactNode {{ label: L(`Ver ${agentName}`, `See ${agentName}`), icon: 'eye', onClick: () => navigate({ kind: 'agent', id: agentId }) },{ label: L('Marcar como lido', 'Mark as read'), icon: 'check', onClick: () => markRead(id) },{ label: L('Configurações da conversa…', 'Conversation settings…'), icon: 'gear', onClick: () => openDialog({ kind: 'settings', id }) },- wikiItem(id, s.conversations.find((x) => x.id === id)?.wikiCapture !== false),+ wikiItem(id, conversations.find((x) => x.id === id)?.wikiCapture !== false),'separator',{label: L('Apagar a conversa…', 'Delete the conversation…'),@@ -249,7 +258,7 @@ export function Sidebar(): ReactNode {]const isDark =- s.settings.theme === 'dark' || (s.settings.theme === 'system' && matchMedia('(prefers-color-scheme: dark)').matches)+ settings.theme === 'dark' || (settings.theme === 'system' && matchMedia('(prefers-color-scheme: dark)').matches)return (<aside className="sidebar">@@ -257,11 +266,11 @@ export function Sidebar(): ReactNode {<div className="workspace"><WorkspaceSelector />{admin && <button- className={`icon-btn ${s.settings.paused ? 'is-paused' : ''}`}- title={s.settings.paused ? L('Retomar os agentes deste workspace', 'Resume agents in this workspace') : L('Pausar este workspace: nenhum agente começa a trabalhar e nenhuma rotina roda', 'Pause this workspace: no agent starts working and no routine runs')}- onClick={() => updateSettings({ paused: !s.settings.paused })}+ className={`icon-btn ${settings.paused ? 'is-paused' : ''}`}+ title={settings.paused ? L('Retomar os agentes deste workspace', 'Resume agents in this workspace') : L('Pausar este workspace: nenhum agente começa a trabalhar e nenhuma rotina roda', 'Pause this workspace: no agent starts working and no routine runs')}+ onClick={() => updateSettings({ paused: !settings.paused })}>- <Icon name={s.settings.paused ? 'play' : 'pause'} />+ <Icon name={settings.paused ? 'play' : 'pause'} /></button>}<buttonclassName="icon-btn"@@ -281,7 +290,7 @@ export function Sidebar(): ReactNode {</span></button>)}- {s.settings.paused && (+ {settings.paused && (<button className="paused-banner" disabled={!admin} onClick={() => updateSettings({ paused: false })}><Icon name="pause" size={13} /> {L('Agentes pausados', 'Agents paused')}{admin && <> · <u>{L('retomar', 'resume')}</u></>}</button>@@ -300,7 +309,7 @@ export function Sidebar(): ReactNode {label={L('Canais', 'Channels')}unread={unreadIn(channels)}action={- <button className="icon-btn icon-btn--sm" title={L(`Novo canal (${shortcut(s.platform, 'N')})`, `New channel (${shortcut(s.platform, 'N')})`)} onClick={() => openDialog({ kind: 'new-channel' })}>+ <button className="icon-btn icon-btn--sm" title={L(`Novo canal (${shortcut(platform, 'N')})`, `New channel (${shortcut(platform, 'N')})`)} onClick={() => openDialog({ kind: 'new-channel' })}><Icon name="plus" size={14} /></button>}@@ -350,7 +359,7 @@ export function Sidebar(): ReactNode {{dms.length > 0 && (<Section id="dms" label={team ? L('Suas mensagens diretas', 'Your direct messages') : L('Mensagens diretas', 'Direct messages')} unread={unreadIn(dms)}>{dms.map((c) => {- const agent = agentById(s, c.name)+ const agent = agentOf(c.name)if (!agent) return nullreturn (<div key={c.id} onContextMenu={(e) => open(e, dmMenu(c.id, agent.id, agent.name))}>@@ -372,25 +381,25 @@ export function Sidebar(): ReactNode {) : undefined}>- {s.agents+ {agents.filter(isTeam).map((a) => (<div key={a.id} onContextMenu={(e) => open(e, agentMenu(a.id, a.name))}>- <AgentItem id={a.id} owner={team && a.owner !== s.you ? personById(s, a.owner)?.name : undefined} />+ <AgentItem id={a.id} owner={team && a.owner !== you ? personById({ people }, a.owner)?.name : undefined} /></div>))}- {s.agents.some((a) => a.archived) && (+ {agents.some((a) => a.archived) && (<button className="nav-item nav-item--quiet" onClick={() => openDialog({ kind: 'archived' })}><Icon name="layers" /><span className="nav-item__label">{L('Arquivados', 'Archived')}</span>- <span className="nav-item__meta">{s.agents.filter((a) => a.archived).length}</span>+ <span className="nav-item__meta">{agents.filter((a) => a.archived).length}</span></button>)}</Section></nav>{/* The introduction's checklist sets the Tucano up (and its phone): the owner's. */}- {amOwner(s) && s.settings.onboarding?.done && !s.settings.onboarding.checklistHidden && <GettingStarted />}+ {owner && settings.onboarding?.done && !settings.onboarding.checklistHidden && <GettingStarted />}<ContextMenu menu={menu} onClose={closeMenu} /><div className="sidebar__foot"><UpdateNote />@@ -402,9 +411,9 @@ export function Sidebar(): ReactNode {)}-function ChannelItem({ id, name, unread }: { id: string; name: string; unread?: number }): ReactNode {+const ChannelItem = memo(function ChannelItem({ id, name, unread }: { id: string; name: string; unread?: number }): ReactNode {const active = useStore((s) => s.view?.kind === 'conversation' && s.view.id === id)- const working = useStore((s) => s.messages.some((m) => m.conversationId === id && m.run?.status === 'working'))+ const working = useStore((s) => isWorking(s, id))return (<button className={`nav-item ${active ? 'is-active' : ''} ${unread ? 'is-unread' : ''}`} onClick={() => navigate({ kind: 'conversation', id })}><Icon name="hash" />@@ -413,7 +422,7 @@ function ChannelItem({ id, name, unread }: { id: string; name: string; unread?:{unread ? <span key={unread} className="badge badge--soft">{unread}</span> : null}</button>)-}+})// Working: the dot pulses. Just finished: it turns green for a moment and fades out, instead of vanishing.function LiveDot({ working }: { working: boolean }): ReactNode {@@ -422,10 +431,10 @@ function LiveDot({ working }: { working: boolean }): ReactNode {return <span className={`pulse ${done ? 'is-done' : ''}`} title={working ? L('Trabalhando', 'Working') : undefined} />}-function DmItem({ id, agent, unread }: { id: string; agent: Agent; unread?: number }): ReactNode {+const DmItem = memo(function DmItem({ id, agent, unread }: { id: string; agent: Agent; unread?: number }): ReactNode {const name = agent.nameconst active = useStore((s) => s.view?.kind === 'conversation' && s.view.id === id)- const working = useStore((s) => s.messages.some((m) => m.conversationId === id && m.run?.status === 'working'))+ const working = useStore((s) => isWorking(s, id))return (<button className={`nav-item ${active ? 'is-active' : ''} ${unread ? 'is-unread' : ''}`} onClick={() => navigate({ kind: 'conversation', id })}><AgentAvatar agent={agent} size={18} busy={working} />@@ -434,10 +443,10 @@ function DmItem({ id, agent, unread }: { id: string; agent: Agent; unread?: numb{unread ? <span key={unread} className="badge badge--soft">{unread}</span> : null}</button>)-}+})// `owner`: with a team, whose agent it is (its approvals go to them), when it isn't mine.-function AgentItem({ id, owner }: { id: string; owner?: string }): ReactNode {+const AgentItem = memo(function AgentItem({ id, owner }: { id: string; owner?: string }): ReactNode {const agent = useStore((s) => agentById(s, id))const active = useStore((s) => s.view?.kind === 'agent' && s.view.id === id)// The agent list is configuration: working shows on the thread (DM, channel),@@ -457,4 +466,4 @@ function AgentItem({ id, owner }: { id: string; owner?: string }): ReactNode {{pct >= 0.8 && <span className={`dot ${pct >= 1 ? 'dot--danger' : 'dot--warn'}`} title={pct >= 1 ? L('Bateu o limite do mês', 'Hit the monthly limit') : L('Já usou mais de 80% do limite', 'Over 80% of the limit used')} />}</button>)-}+})diff --git a/src/renderer/src/components/Tuca.tsx b/src/renderer/src/components/Tuca.tsxindex e5857b5..d0b9682 100644--- a/src/renderer/src/components/Tuca.tsx+++ b/src/renderer/src/components/Tuca.tsx@@ -15,6 +15,7 @@ import {sendMessage,settleDraft,slug,+ messagesIn,useStore,type Agent,type AgentDraft,@@ -41,7 +42,7 @@ export function AgentProposal({ message }: { message: Message }): ReactNode {const created = useStore((s) => (d.agentId ? s.agents.find((a) => a.id === d.agentId) : undefined))const by = useStore((s) => (message.author.kind === 'agent' && s.agents.find((a) => a.id === (message.author as { id: string }).id)?.name) || 'Tuca')// A newer proposal in the same conversation replaces this one.- const replaced = useStore((s) => s.messages.some((m) => m.conversationId === message.conversationId && m.at > message.at && !!m.run?.agentDraft))+ const replaced = useStore((s) => messagesIn(s, message.conversationId).some((m) => m.at > message.at && !!m.run?.agentDraft))const [open, setOpen] = useState(false)const [busy, setBusy] = useState(false)const [error, setError] = useState('')@@ -140,7 +141,7 @@ export function ProposalCard({ message }: { message: Message }): ReactNode {const connectors = useStore((s) => s.connectors)const conversations = useStore((s) => s.conversations)// A newer proposal in the same conversation replaces this one.- const replaced = useStore((s) => s.messages.some((m) => m.conversationId === message.conversationId && m.at > message.at && !!m.run?.proposal))+ const replaced = useStore((s) => messagesIn(s, message.conversationId).some((m) => m.at > message.at && !!m.run?.proposal))const [busy, setBusy] = useState(false)const [error, setError] = useState('')const [sent, setSent] = useState('')diff --git a/src/renderer/src/components/Update.tsx b/src/renderer/src/components/Update.tsxindex d8aa4ca..53262e7 100644--- a/src/renderer/src/components/Update.tsx+++ b/src/renderer/src/components/Update.tsx@@ -6,7 +6,7 @@ import changelog from '../../../../CHANGELOG.md?raw'import { L, lang, locale } from '../../../shared/lang'import { newsPages, newsSince, type NewsPage } from '../../../shared/release-notes'import type { UpdateState } from '../../../shared/types'-import { updateSettings, useStore } from '../store'+import { updateSettings, useStore, workingAgents } from '../store'import { Modal } from './Modal'import { ago, Icon } from './ui'@@ -41,7 +41,7 @@ function useUpdate(): UpdateState | null {const notes = (version?: string): string => (version ? `${RELEASES}/tag/v${version}` : RELEASES)// How many agents are in the middle of a reply: restarting now would cut them off.-const useWorking = (): number => useStore((s) => new Set(s.messages.filter((m) => m.run?.status === 'working' && m.author.kind === 'agent').map((m) => (m.author.kind === 'agent' ? m.author.id : ''))).size)+const useWorking = (): number => useStore((s) => workingAgents(s).size)const workingNote = (n: number): string => (n === 1 ? L('1 agente trabalhando: reinicie quando ele terminar.', '1 agent working: restart once it’s done.') : L(`${n} agentes trabalhando: reinicie quando terminarem.`, `${n} agents working: restart once they’re done.`))diff --git a/src/renderer/src/components/Usage.tsx b/src/renderer/src/components/Usage.tsxindex ba853c0..6c4e89d 100644--- a/src/renderer/src/components/Usage.tsx+++ b/src/renderer/src/components/Usage.tsx@@ -2,7 +2,7 @@// Claude subscription's windows, and where each agent will end the month.import { L, locale } from '../../../shared/lang'import { useEffect, useState, type CSSProperties, type ReactNode } from 'react'-import { agentById, amAdmin, countedTokens, ENGINES, isTeam, loadUsage, modelInfo, navigate, useStore, type Agent, type EngineId, type EngineStatus, type UsageReport } from '../store'+import { agentById, amAdmin, countedTokens, ENGINES, isTeam, loadUsage, messageById, modelInfo, navigate, receipts, useStore, type Agent, type EngineId, type EngineStatus, type UsageReport } from '../store'import { Sheet } from './Pages'import { AdminOnly } from './People'import { AgentAvatar, duration, Icon, tokens, usd } from './ui'@@ -53,10 +53,10 @@ function useBilling(u: UsageReport | null): { id: EngineId; label: string; statuexport function UsagePage(): ReactNode {const [u, setU] = useState<UsageReport | null>(null)// Recomputed whenever a reply lands with its receipt.- const receipts = useStore((s) => s.messages.reduce((n, m) => n + (m.run?.receipt ? 1 : 0), 0))+ const count = useStore((s) => receipts(s).length)// What the team spends is the admins' (a member can still land here from the search).const admin = useStore(amAdmin)- useEffect(() => void (admin && loadUsage().then(setU)), [receipts, admin])+ useEffect(() => void (admin && loadUsage().then(setU)), [count, admin])const billing = useBilling(u)const allPlan = billing.length > 0 && billing.every((b) => b.status.route === 'plan')@@ -421,7 +421,7 @@ function Backstage({ u }: { u: UsageReport }): ReactNode {function Receipts(): ReactNode {const [shown, setShown] = useState(10)- const all = useStore((s) => s.messages.filter((m) => m.run?.receipt))+ const all = useStore(receipts)const recent = [...all].sort((a, b) => b.at - a.at)if (recent.length === 0) return nullreturn (@@ -453,7 +453,7 @@ function Receipts(): ReactNode {}function ReceiptRow({ id }: { id: string }): ReactNode {- const m = useStore((s) => s.messages.find((x) => x.id === id)!)+ const m = useStore((s) => messageById(s, id)!)const agent = useStore((s) => (m.author.kind === 'agent' ? agentById(s, m.author.id) : undefined))const conv = useStore((s) => s.conversations.find((c) => c.id === m.conversationId))const r = m.run!.receipt!diff --git a/src/renderer/src/components/Wiki.tsx b/src/renderer/src/components/Wiki.tsxindex 165a0f9..ac486c8 100644--- a/src/renderer/src/components/Wiki.tsx+++ b/src/renderer/src/components/Wiki.tsx@@ -93,8 +93,12 @@ export function wikiWho(state: Pick<State, 'you' | 'me' | 'people' | 'former' |: (agentById(state as State, by)?.name ?? (by === state.you || state.people.some((p) => p.id === by) || state.former?.some((p) => p.id === by) ? personName(state, by) : by))}function useWho(): (by: string) => string {- const state = useStore((s) => s)- return wikiWho(state)+ const you = useStore((s) => s.you)+ const me = useStore((s) => s.me)+ const people = useStore((s) => s.people)+ const former = useStore((s) => s.former)+ const agents = useStore((s) => s.agents)+ return useMemo(() => wikiWho({ you, me, people, former, agents }), [you, me, people, former, agents])}function Who({ by, size = 22 }: { by: string; size?: number }): ReactNode {const me = useStore((s) => s.me)diff --git a/src/renderer/src/rpc.ts b/src/renderer/src/rpc.tsindex 5bfb442..1b1c81f 100644--- a/src/renderer/src/rpc.ts+++ b/src/renderer/src/rpc.ts@@ -34,7 +34,7 @@ declare global {open: (id: string) => voidlocal: () => void // back to this computer's Tucanoforget: (id: string) => Promise<boolean>- onChanged: (cb: () => void) => void+ onChanged: (cb: () => void) => () => void // returns the unsubscribe}}}diff --git a/src/renderer/src/store.ts b/src/renderer/src/store.tsindex 7d53bc0..31a2da2 100644--- a/src/renderer/src/store.ts+++ b/src/renderer/src/store.ts@@ -1,10 +1,11 @@// Renderer state. Everything except the current view comes from the core and// is kept in sync by its events; actions go to the core over RPC.-import { useRef, useSyncExternalStore } from 'react'+import { useCallback, useRef, useSyncExternalStore } from 'react'import { L, setLang } from '../../shared/lang'import type { CoreEvent, Method, Params } from '../../shared/rpc'import type { AppProvider } from '../../shared/connector-catalog'import {+ asSaid,type Account,type AccountEngine,MAX_AGENT_ROUTINES,@@ -86,7 +87,8 @@ export interface State {connectors: Connector[]lightbox: { items: { url: string; title: string; video?: boolean }[]; index: number } | nullconversations: Conversation[]- messages: Message[]+ messages: Record<string, Message[]> // per conversation, oldest first; read through messagesIn and the indexes below+ history: Record<string, number> // per conversation with older messages still in the core: from when it's here wholeapprovals: Approval[]memories: Memory[]artifacts: Artifact[]@@ -168,7 +170,8 @@ let state: State = {connectors: [],lightbox: null,conversations: [],- messages: [],+ messages: {},+ history: {},approvals: [],memories: [],artifacts: [],@@ -230,6 +233,261 @@ export const getState = (): State => stateconst upsert = <T extends { id: string }>(list: T[], item: T): T[] =>list.some((x) => x.id === item.id) ? list.map((x) => (x.id === item.id ? item : x)) : [...list, item]+// ---------- messages ----------+// Kept per conversation, oldest first, so a change copies one conversation and not all of them.+// What the screens ask of them (a thread's replies, who's at work) is worked out once per change,+// in an index each list gets the first time something reads it.++const NO_MESSAGES: Message[] = []+export const messagesIn = (s: State, conversationId: string): Message[] => s.messages[conversationId] ?? NO_MESSAGES++const byConversation = (list: Message[]): Record<string, Message[]> => {+ const out: Record<string, Message[]> = {}+ for (const m of list) (out[m.conversationId] ??= []).push(m)+ return out+}++// A new message almost always goes last; one that changed stays where it was.+function upsertMessage(list: Message[], m: Message): Message[] {+ for (let i = list.length - 1; i >= 0; i--)+ if (list[i]!.id === m.id) {+ const next = list.slice()+ next[i] = m+ return next+ }+ let i = list.length+ while (i > 0 && list[i - 1]!.at > m.at) i--+ return [...list.slice(0, i), m, ...list.slice(i)]+}++// What came from further back joins in time order; what's here already stays (events keep it current).+function mergeMessages(list: Message[], more: Message[]): Message[] {+ const have = indexOf(list).byId+ const fresh = more.filter((m) => !have.has(m.id))+ return fresh.length ? [...list, ...fresh].sort((a, b) => a.at - b.at) : list+}++interface ConversationIndex {+ byId: Map<string, Message>+ timeline: Message[] // what's outside threads+ replies: Map<string, Message[]> // a thread's first message → its replies+ working: Message[] // replies at work, and notes still pending+ waiting: Message[] // questions waiting on me+ browser: Map<string, string> // an agent → its latest message that used the browser+ receipts: Message[]+ agentDone: boolean // some agent finished a reply here+ shown?: { from: number; list: Message[] }+}++const indexes = new WeakMap<Message[], ConversationIndex>()+const lastIndex = new Map<string, ConversationIndex>() // per conversation: the replies that didn't change keep their array+const sameList = (a: Message[], b: Message[]): boolean => a.length === b.length && a.every((m, i) => m === b[i])++function indexOf(list: Message[]): ConversationIndex {+ const had = indexes.get(list)+ if (had) return had+ const ix: ConversationIndex = { byId: new Map(), timeline: [], replies: new Map(), working: [], waiting: [], browser: new Map(), receipts: [], agentDone: false }+ // In the order things were said (a reply when it ended), whoever is still working at the end.+ for (const m of asSaid(list)) {+ ix.byId.set(m.id, m)+ if (!m.threadId) ix.timeline.push(m)+ else {+ const r = ix.replies.get(m.threadId)+ if (r) r.push(m)+ else ix.replies.set(m.threadId, [m])+ }+ const status = m.run?.status+ if (status === 'working') ix.working.push(m)+ else if (status === 'waiting_input') ix.waiting.push(m)+ if (m.run?.receipt) ix.receipts.push(m)+ if (m.author.kind === 'agent') {+ if (m.run?.browser) ix.browser.set(m.author.id, m.id)+ if (status === 'done') ix.agentDone = true+ }+ }+ // The same array for a thread that didn't change, so its row doesn't draw again.+ const prev = list[0] && lastIndex.get(list[0].conversationId)+ if (prev)+ for (const [root, r] of ix.replies) {+ const old = prev.replies.get(root)+ if (old && sameList(old, r)) ix.replies.set(root, old)+ }+ indexes.set(list, ix)+ if (list[0]) lastIndex.set(list[0].conversationId, ix)+ return ix+}++export const conversationIndex = (s: State, conversationId: string): ConversationIndex => indexOf(messagesIn(s, conversationId))++// The timeline as it shows: what's outside threads, from where it's here whole (older messages+// kept for a routine's run or a thread wait until the scroll gets there).+export function timelineOf(s: State, conversationId: string): Message[] {+ const ix = conversationIndex(s, conversationId)+ const from = s.history[conversationId] ?? 0+ if (!from) return ix.timeline+ if (ix.shown?.from !== from) ix.shown = { from, list: ix.timeline.filter((m) => m.at >= from) }+ return ix.shown.list+}++export const repliesOf = (s: State, conversationId: string, rootId: string): Message[] => conversationIndex(s, conversationId).replies.get(rootId) ?? NO_MESSAGES++export function messageById(s: State, id: string, conversationId?: string): Message | undefined {+ if (conversationId) return conversationIndex(s, conversationId).byId.get(id)+ for (const list of Object.values(s.messages)) {+ const m = indexOf(list).byId.get(id)+ if (m) return m+ }+ return undefined+}++export const isWorking = (s: State, conversationId: string): boolean => conversationIndex(s, conversationId).working.length > 0+// The agents' replies at work in a place: in a thread, or outside threads.+export const workingIds = (s: State, conversationId: string, threadId?: string): string[] =>+ conversationIndex(s, conversationId)+ .working.filter((m) => m.threadId === threadId && m.author.kind === 'agent')+ .map((m) => m.id)+export const askerIn = (s: State, conversationId: string, threadId?: string): Message | undefined => conversationIndex(s, conversationId).waiting.findLast((m) => m.threadId === threadId)+export const lastBrowserIn = (s: State, conversationId: string, agentId: string): string | undefined => conversationIndex(s, conversationId).browser.get(agentId)++// Across conversations, once per change.+interface Everywhere {+ workingAgents: Set<string>+ receipts: Message[]+ agentDone: boolean+}+const everywhere = new WeakMap<Record<string, Message[]>, Everywhere>()+function across(s: State): Everywhere {+ const had = everywhere.get(s.messages)+ if (had) return had+ const all: Everywhere = { workingAgents: new Set(), receipts: [], agentDone: false }+ for (const list of Object.values(s.messages)) {+ const ix = indexOf(list)+ for (const m of ix.working) if (m.author.kind === 'agent') all.workingAgents.add(m.author.id)+ all.receipts.push(...ix.receipts)+ all.agentDone ||= ix.agentDone+ }+ everywhere.set(s.messages, all)+ return all+}+export const workingAgents = (s: State): Set<string> => across(s).workingAgents+export const receipts = (s: State): Message[] => across(s).receipts+export const anyReplyDone = (s: State): boolean => across(s).agentDone++// What I attached to my own messages, by message, once per change of the artifacts.+const NO_ARTIFACTS: Artifact[] = []+const attached = new WeakMap<Artifact[], Map<string, Artifact[]>>()+export function attachedTo(s: State, messageId: string): Artifact[] {+ let byMessage = attached.get(s.artifacts)+ if (!byMessage) {+ byMessage = new Map()+ for (const a of s.artifacts) {+ if (a.agentId !== '' || !a.messageId) continue+ const list = byMessage.get(a.messageId)+ if (list) list.push(a)+ else byMessage.set(a.messageId, [a])+ }+ attached.set(s.artifacts, byMessage)+ }+ return byMessage.get(messageId) ?? NO_ARTIFACTS+}++// Older messages, a page at a time as the scroll gets there, or back to `through` (a message to show).+const loadingOlder = new Map<string, Promise<void>>()+export function loadOlder(conversationId: string, through?: string): Promise<void> {+ const busy = loadingOlder.get(conversationId)+ if (busy) return through ? busy.then(() => loadOlder(conversationId, through)) : busy+ const before = state.history[conversationId]+ if (!before) return Promise.resolve()+ const p = call('olderMessages', { conversationId, before, ...(through ? { through } : {}) })+ .then(({ messages, since }) =>+ set((s) => {+ const { [conversationId]: _was, ...history } = s.history+ return { ...s, messages: { ...s.messages, [conversationId]: mergeMessages(messagesIn(s, conversationId), messages) }, history: since ? { ...history, [conversationId]: since } : history }+ })+ )+ .catch(() => {}) // the next scroll asks again+ .finally(() => loadingOlder.delete(conversationId))+ loadingOlder.set(conversationId, p)+ return p+}++// A thread from before what's here (a notification about it, say): the message that started it, and its replies.+export async function loadThread(rootId: string): Promise<void> {+ const list = await call('threadMessages', { rootId }).catch((): Message[] => [])+ const id = list[0]?.conversationId+ if (id) set((s) => ({ ...s, messages: { ...s.messages, [id]: mergeMessages(messagesIn(s, id), list) } }))+}++// ---------- streaming ----------+// A reply's words as they stream, kept out of the state: a delta wakes only the row that shows it.++const live = new Map<string, string>()+const liveListeners = new Map<string, Set<() => void>>()++function listen(map: Map<string, Set<() => void>>, key: string, l: () => void): () => void {+ let ls = map.get(key)+ if (!ls) map.set(key, (ls = new Set()))+ ls.add(l)+ return () => {+ ls.delete(l)+ if (!ls.size) map.delete(key)+ }+}+const wake = (map: Map<string, Set<() => void>>, key: string): void => map.get(key)?.forEach((l) => l())++function stream(id: string, text: string): void {+ live.set(id, (live.get(id) ?? messageById(state, id)?.text ?? '') + text)+ wake(liveListeners, id)+}++export const liveText = (id: string): string | undefined => live.get(id)++// The message's text as it is now. `every`: wake at most that often (ms), for what is costly to draw.+export function useLiveText(m: Message, every = 0): string {+ const subscribe = useCallback(+ (l: () => void) => {+ let timer: ReturnType<typeof setTimeout> | undefined+ let last = 0+ const off = listen(liveListeners, m.id, () => {+ if (!every) return l()+ if (timer) return+ timer = setTimeout(+ () => {+ timer = undefined+ last = Date.now()+ l()+ },+ Math.max(0, last + every - Date.now())+ )+ })+ return () => {+ clearTimeout(timer)+ off()+ }+ },+ [m.id, every]+ )+ return useSyncExternalStore(subscribe, () => live.get(m.id) ?? m.text)+}++// ---------- browser frames ----------+// An agent's browser sends its screen up to ten times a second: kept apart, like the streamed words.++const frames = new Map<string, string>()+const frameListeners = new Map<string, Set<() => void>>()++function showFrame(agentId: string, frame: string | undefined): void {+ if (frames.get(agentId) === frame) return+ if (frame) frames.set(agentId, frame)+ else frames.delete(agentId)+ wake(frameListeners, agentId)+}++export function useFrame(agentId: string): string | undefined {+ const subscribe = useCallback((l: () => void) => listen(frameListeners, agentId, l), [agentId])+ return useSyncExternalStore(subscribe, () => frames.get(agentId))+}+// ---------- core sync ----------// My name: the owner's is the settings' (what the agents have always called them); anyone else's, theirs.@@ -245,13 +503,15 @@ function withSettings(s: State, settings: Settings): State {}function apply(e: CoreEvent): void {+ // Streamed words and the browser's screen come many times a second: they wake only what shows them.+ if (e.type === 'delta') return stream(e.id, e.text)+ if (e.type === 'browser_frame') return showFrame(e.agentId, e.frame)set((s) => {switch (e.type) {case 'message': {- return { ...s, messages: upsert(s.messages, e.message) }+ const id = e.message.conversationId+ return { ...s, messages: { ...s.messages, [id]: upsertMessage(messagesIn(s, id), e.message) } }}- case 'delta':- return { ...s, messages: s.messages.map((m) => (m.id === e.id ? { ...m, text: m.text + e.text } : m)) }case 'agent':return { ...s, agents: upsert(s.agents, e.agent) }case 'conversation': {@@ -285,10 +545,13 @@ function apply(e: CoreEvent): void {const left = s.conversations.filter((c) => c.id !== e.id)const here = s.view?.kind === 'conversation' && s.view.id === e.idconst first = left.find((c) => c.kind === 'channel') ?? left[0]+ const { [e.id]: _gone, ...messages } = s.messages+ const { [e.id]: _from, ...history } = s.historyreturn {...s,conversations: left,- messages: s.messages.filter((m) => m.conversationId !== e.id),+ messages,+ history,view: here ? (first ? { kind: 'conversation', id: first.id } : { kind: 'new-agent' }) : s.view,panel: here ? null : s.panel}@@ -309,6 +572,9 @@ function apply(e: CoreEvent): void {return { ...s, inbox: e.inbox ?? s.inbox }}})+ // A full message carries all its text so far: what streamed before it is in there.+ if (e.type === 'message' && live.delete(e.message.id)) wake(liveListeners, e.message.id)+ if (e.type === 'browser') showFrame(e.view.agentId, e.view.frame)}export async function start(): Promise<void> {@@ -331,6 +597,7 @@ export async function start(): Promise<void> {})await connect(apply)const snap = await call('snapshot')+ for (const b of snap.browsers) showFrame(b.agentId, b.frame)set((s) => {const first = snap.conversations.find((c) => c.kind === 'channel') ?? snap.conversations[0]const view = s.view ?? (first ? { kind: 'conversation' as const, id: first.id } : { kind: 'new-agent' as const })@@ -343,7 +610,8 @@ export async function start(): Promise<void> {view,agents: snap.agents,conversations: snap.conversations,- messages: snap.messages,+ messages: byConversation(snap.messages),+ history: snap.since ?? {},connectors: snap.connectors,approvals: snap.approvals,memories: snap.memories,@@ -586,13 +854,14 @@ export const sendMessage = (conversationId: string, text: string, images: ImageU}// The person is writing: the core gets what will answer ready. Once in a while per place, and-// nobody needs to hear if it didn't work.+// nobody needs to hear if it didn't work. `opened`: they only opened it (the agent's kept session+// starts again, while they read; the router waits for them to type).const typed = new Map<string, number>()-export const typing = (conversationId: string, threadId?: string): void => {- const where = `${conversationId}:${threadId ?? ''}`+export const typing = (conversationId: string, threadId?: string, opened = false): void => {+ const where = `${conversationId}:${threadId ?? ''}:${opened ? 'o' : 't'}`if (Date.now() - (typed.get(where) ?? 0) < 20_000) returntyped.set(where, Date.now())- void call('typing', { conversationId, ...(threadId ? { threadId } : {}) }).catch(() => {})+ void call('typing', { conversationId, ...(threadId ? { threadId } : {}), ...(opened ? { opened } : {}) }).catch(() => {})}export const stopRun = (messageId: string): void => void fire(L('Não consegui parar a resposta.', "I couldn't stop the reply."), 'stopRun', { messageId })diff --git a/src/renderer/src/styles.css b/src/renderer/src/styles.cssindex 5b95f03..07b8de8 100644--- a/src/renderer/src/styles.css+++ b/src/renderer/src/styles.css@@ -693,6 +693,14 @@ h3 {.c-green .avatar__eyes i { animation-duration: 4.9s; animation-delay: 3.2s; }.c-teal .avatar__eyes i { animation-duration: 6.8s; animation-delay: 1.7s; }.c-graphite .avatar__eyes i { animation-duration: 5.3s; animation-delay: 2.8s; }+/* A long conversation has hundreds of faces: only the latest messages' still blink (before the+ happy squint below, which wins over this). */+.messages .avatar__eyes i {+ animation-name: none;+}+.messages > :nth-last-child(-n + 3) .avatar__eyes i {+ animation-name: blink;+}/* At work: the eyes read, left to right, and come back. */.avatar.is-busy .avatar__eyes {animation: read 1.8s var(--ease-out) infinite;@@ -994,6 +1002,29 @@ h3 {flex: 1;overflow-y: auto;padding: 24px 0 12px;+ contain: content; /* what changes in the list lays out only the list */+}+/* Rows off screen skip layout and paint until the scroll gets near; each keeps its last real height. */+.messages > .msg,+.messages > .system-line {+ content-visibility: auto;+ contain-intrinsic-block-size: auto 96px;+}+.messages > .system-line {+ contain-intrinsic-block-size: auto 30px;+}+/* The latest always draw: the list opens at its end, and they're what changes. */+.messages > :nth-last-child(-n + 12) {+ content-visibility: visible;+}+/* Older messages on their way, over the top of the list (it takes no room, so nothing jumps). */+.messages__older {+ position: sticky;+ top: 0;+ height: 0;+ overflow: visible;+ text-align: center;+ z-index: 1;}/* "Go to the end": rides the bottom of the list while you read further up. */.messages__jump {@@ -1650,6 +1681,7 @@ h3 {padding: 13px 16px 4px;background: transparent;max-height: 220px;+ field-sizing: content; /* grows with its text, without measuring on each key (Composer) */}.composer textarea:focus {box-shadow: none;diff --git a/src/shared/rpc-shapes.ts b/src/shared/rpc-shapes.tsindex 1f05f78..57c8ea4 100644--- a/src/shared/rpc-shapes.ts+++ b/src/shared/rpc-shapes.ts@@ -11,7 +11,9 @@ export const SHAPES: Record<Method, Record<string, string>> = {snapshot: {},artifactText: { id: 's' },sendMessage: { conversationId: 's', text: 's', images: 'a?', threadId: 's?' },- typing: { conversationId: 's', threadId: 's?' },+ typing: { conversationId: 's', threadId: 's?', opened: 'b?' },+ olderMessages: { conversationId: 's', before: 'n', through: 's?' },+ threadMessages: { rootId: 's' },stopRun: { messageId: 's' },retryRun: { messageId: 's' },continueRun: { messageId: 's' },diff --git a/src/shared/rpc.ts b/src/shared/rpc.tsindex a761ba8..6d99f70 100644--- a/src/shared/rpc.ts+++ b/src/shared/rpc.ts@@ -9,7 +9,8 @@ export interface Snapshot {settings: Settingsagents: Agent[]conversations: Conversation[]- messages: Message[]+ messages: Message[] // each conversation's latest, with their threads; older ones come with olderMessages+ since?: Record<string, number> // per conversation with older messages left: from when `messages` has it wholeconnectors: Connector[]approvals: Approval[]memories: Memory[]@@ -32,9 +33,11 @@ export interface Snapshot {export interface Api {markRead(p: { conversationId: string }): voidsnapshot(): Snapshot+ olderMessages(p: { conversationId: string; before: number; through?: string }): { messages: Message[]; since: number } // a page from before `before` (or back to `through`, a message to show), with their threads; since: from when it's whole now, 0 once all of it is+ threadMessages(p: { rootId: string }): Message[] // a thread whole: the message that started it and its repliesartifactText(p: { id: string }): string | null // a text file an agent showed (Markdown, CSV, code), for the side panelsendMessage(p: { conversationId: string; text: string; images?: ImageUpload[]; threadId?: string }): void // threadId: a reply in the thread that message started- typing(p: { conversationId: string; threadId?: string }): void // the person is writing there: what will answer gets ready+ typing(p: { conversationId: string; threadId?: string; opened?: boolean }): void // the person is writing there (or just opened it): what will answer gets readystopRun(p: { messageId: string }): voidretryRun(p: { messageId: string }): voidcontinueRun(p: { messageId: string }): void // a reply paused at its budget goes on@@ -196,6 +199,7 @@ export type CoreEvent =| { type: 'memory_removed'; id: string; for?: string } // for: whose it was, when it was someone's own (no one else hears of it)| { type: 'computer'; computer: ComputerInfo }| { type: 'browser'; view: BrowserView }+ | { type: 'browser_frame'; agentId: string; frame: string; conversationId?: string } // the browser's screen as it changes, without the rest of its view (conversationId: whom it works for, who may see it)| { type: 'artifact'; artifact: Artifact }| { type: 'routine'; routine: Routine }| { type: 'routine_removed'; id: string; for?: string } // for: a DM's person, the only one who saw it@@ -207,7 +211,7 @@ export type CoreEvent =| { type: 'inbox'; inbox?: Inbox } // what waits on this person changed (each gets their own)// Every kind of event, so a test can go through them all (people.ts's eventFor decides each one's audience).-export const CORE_EVENT_TYPES = ['voice', 'message', 'delta', 'agent', 'conversation', 'settings', 'connector', 'connector_removed', 'approval', 'memory', 'memory_removed', 'computer', 'browser', 'artifact', 'routine', 'routine_removed', 'conversation_removed', 'skill', 'skill_removed', 'wiki', 'people', 'inbox'] as const satisfies readonly CoreEvent['type'][]+export const CORE_EVENT_TYPES = ['voice', 'message', 'delta', 'agent', 'conversation', 'settings', 'connector', 'connector_removed', 'approval', 'memory', 'memory_removed', 'computer', 'browser', 'browser_frame', 'artifact', 'routine', 'routine_removed', 'conversation_removed', 'skill', 'skill_removed', 'wiki', 'people', 'inbox'] as const satisfies readonly CoreEvent['type'][]// …and none left out: a new kind of event fails to compile here until it's listed.type _AllListed = Exclude<CoreEvent['type'], (typeof CORE_EVENT_TYPES)[number]> extends never ? true : neverexport const _allEventsListed: _AllListed = truediff --git a/src/shared/types.ts b/src/shared/types.tsindex 8c433fe..174bdf2 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -47,6 +47,7 @@ export interface EngineStatus {gateway?: string // the gateway's hostoff?: boolean // the person didn't pick this harness: no agent runs on itsoon?: boolean // the app can't run agents on it yet+ checking?: boolean // not checked yet: the app has just opened for the first time}// The agents of the team: not archived, and not the Tuca, who belongs to the app.diff --git a/test/apps.test.ts b/test/apps.test.tsindex da49eab..57a7d99 100644--- a/test/apps.test.ts+++ b/test/apps.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest'import { setLang } from '../src/shared/lang'-import { appStep, appTools, DesktopApps, grantOf, isTucano, itemize, keyFor, parseLsappinfo, pick, riskyClick, riskyKey, run, typeKeys, type Cli, type Envelope } from '../src/core/apps'+import { appStep, appTools, DesktopApps, grantOf, isTucano, itemize, keyFor, parseLsappinfo, parseMdls, pick, riskyClick, riskyKey, run, typeKeys, type Cli, type Envelope } from '../src/core/apps'import type { Agent } from '../src/shared/types'// A Notes window as agent-desktop describes it.@@ -334,3 +334,24 @@ describe('labels of what happens in an app', () => {expect(appStep('app_ver', {}).label).toBe('Leu')})})++describe('the Mac apps, many per mdls', () => {+ it('reads two values per app from one answer', () => {+ const out = 'com.apple.Safari\0Safari\0com.apple.Notes\0Notas.app\0(null)\0(null)'+ expect(parseMdls(out, ['/Applications/Safari.app', '/System/Applications/Notes.app', '/Applications/Velho.app'])).toEqual([+ { name: 'Safari', bundleId: 'com.apple.Safari', path: '/Applications/Safari.app' },+ { name: 'Notas', bundleId: 'com.apple.Notes', path: '/System/Applications/Notes.app' },+ { name: 'Velho', path: '/Applications/Velho.app' }+ ])+ })++ it('stops where mdls stopped, at an app Spotlight can’t read', () => {+ // Its complaint comes on stdout, glued to the last value it printed.+ expect(parseMdls('com.apple.Safari\0Safari/a/Safari.app: could not find /a/Quebrado.app.\n', ['/a/Safari.app', '/a/Quebrado.app', '/a/Notes.app'])).toEqual([{ name: 'Safari', bundleId: 'com.apple.Safari', path: '/a/Safari.app' }])+ expect(parseMdls('/a/Quebrado.app: could not find /a/Quebrado.app.\n', ['/a/Quebrado.app'])).toEqual([])+ })++ it('an answer whose values don’t pair up is refused, so each app is asked alone', () => {+ expect(parseMdls('com.apple.Safari\0Safari\0com.apple.Notes', ['/a/Safari.app', '/a/Notes.app'])).toBeUndefined()+ })+})diff --git a/test/browser.test.ts b/test/browser.test.tsindex 53076a8..9336e14 100644--- a/test/browser.test.ts+++ b/test/browser.test.ts@@ -157,6 +157,8 @@ describe("an agent's browser", () => {expect(browser.frame('lia-0001', Buffer.from('novo').toString('base64'))).toBe(true) // just worked: liveawait new Promise((r) => setTimeout(r, 150))expect(browser.view('lia-0001')!.frame).toBe(`data:image/jpeg;base64,${Buffer.from('novo').toString('base64')}`)+ // Only the picture goes out, not the whole view with its log.+ expect(events.at(-1)).toEqual({ type: 'browser_frame', agentId: 'lia-0001', frame: `data:image/jpeg;base64,${Buffer.from('novo').toString('base64')}`, conversationId: ctx.conversationId })})it('clicks and types by text, without any model', async () => {diff --git a/test/codex-app.test.ts b/test/codex-app.test.tsnew file mode 100644index 0000000..d7ac6f2--- /dev/null+++ b/test/codex-app.test.ts@@ -0,0 +1,317 @@+import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { codexAppInput, codexAppParser, KEEP_IDLE_MS, leftThreads, MAX_IDLE } from '../src/core/engines/codex-app'+import { CODEX_DISABLED_FEATURES, codexAppArgs, codexEngine, codexIsolated, codexThread } from '../src/core/engines/codex'+import type { Engine, EngineEvent, Turn } from '../src/core/engines/types'++const isWin = process.platform === 'win32'++// Recorded from `codex app-server` 0.153.4 (gpt-5.6-luna, low): one turn that calls a gateway tool,+// then answers, streamed in deltas. Local paths trimmed.+const fixture = readFileSync(join(import.meta.dirname, 'fixtures', 'codex-app-turn.jsonl'), 'utf8').split('\n').filter(Boolean)+const feed = (lines: string[], exit = 0, stderr = ''): EngineEvent[] => {+ const p = codexAppParser()+ return [...lines.flatMap((l) => p.line(l)), ...p.end(exit, stderr)]+}+const textOf = (events: EngineEvent[]): string => events.flatMap((e) => (e.type === 'text' ? [e.delta] : [])).join('')+const n = (method: string, params: Record<string, unknown>): string => JSON.stringify({ method, params: { threadId: 't', turnId: 'u', ...params } })++describe('Codex app-server stream', () => {+ it('streams the text as it comes and reports the turn usage', () => {+ const events = feed(fixture)+ const deltas = events.filter((e) => e.type === 'text')+ expect(deltas.length).toBeGreaterThan(50) // word by word, not one chunk at the end+ const done = events.find((e) => e.type === 'done')+ expect(done).toMatchObject({ type: 'done', usage: { inputTokens: 21916, cacheReadTokens: 6016, outputTokens: 422 }, context: 7971 + 259 })+ expect(textOf(events)).toBe(done?.type === 'done' ? done.text : '')+ expect(textOf(events)).toMatch(/^pong-42; tools: /)+ const progress = events.flatMap((e) => (e.type === 'progress' ? [e.tokens] : []))+ expect(progress).toEqual([6253, 14108, 22338])+ // The rate limits it reports aren't the ones the app shows (those are Claude's): none go out.+ expect(events.some((e) => e.type === 'error' || e.type === 'quota')).toBe(false)+ })++ it("counts only this turn's tokens on a thread that had turns before", () => {+ const usage = (total: number, last: number): string => n('thread/tokenUsage/updated', { tokenUsage: { total: { inputTokens: total, cachedInputTokens: 0, outputTokens: 0 }, last: { inputTokens: last, cachedInputTokens: 0, outputTokens: 0 } } })+ const events = feed([usage(5000, 1200), usage(6500, 1500), n('turn/completed', { turn: { id: 'u', status: 'completed' } })])+ expect(events.flatMap((e) => (e.type === 'progress' ? [e.tokens] : []))).toEqual([1200, 2700])+ expect(events.find((e) => e.type === 'done')).toMatchObject({ usage: { inputTokens: 2700 }, context: 1500 })+ })++ it('keeps each agent message its own paragraph, and takes one that came whole', () => {+ const events = feed([+ n('item/agentMessage/delta', { itemId: 'a', delta: 'Vou ver.' }),+ n('item/completed', { item: { type: 'agentMessage', id: 'a', text: 'Vou ver.' } }),+ n('item/completed', { item: { type: 'agentMessage', id: 'b', text: 'Pronto.' } }),+ n('turn/completed', { turn: { id: 'u', status: 'completed' } })+ ])+ expect(textOf(events)).toBe('Vou ver.\n\nPronto.')+ expect(events.find((e) => e.type === 'done')).toMatchObject({ text: 'Vou ver.\n\nPronto.' })+ })++ it('reports web searches and page reads', () => {+ const item = (action: object): string => n('item/completed', { item: { type: 'webSearch', id: 'w', query: '', action } })+ expect(feed([item({ type: 'search', query: 'electron release', queries: null }), item({ type: 'openPage', url: 'https://electronjs.org' })]).filter((e) => e.type === 'web')).toEqual([+ { type: 'web', action: 'search', detail: 'electron release' },+ { type: 'web', action: 'fetch', detail: 'https://electronjs.org' }+ ])+ })++ it('turns a failed turn, or an error it gives up on, into an error event', () => {+ const failed = feed([n('turn/completed', { turn: { id: 'u', status: 'failed', error: { message: "You've hit your usage limit.", codexErrorInfo: 'usageLimitExceeded', additionalDetails: null } } })])+ expect(failed).toEqual([{ type: 'error', message: "You've hit your usage limit." }])+ const retried = feed([n('error', { willRetry: true, error: { message: 'Reconnecting... 1/5' } }), n('turn/completed', { turn: { id: 'u', status: 'completed' } })])+ expect(retried.some((e) => e.type === 'error')).toBe(false)+ expect(feed([n('error', { willRetry: false, error: { message: 'stream disconnected' } })])).toEqual([{ type: 'error', message: 'stream disconnected' }])+ // stopped on purpose: nothing to report+ expect(feed([n('turn/completed', { turn: { id: 'u', status: 'interrupted' } })])).toEqual([])+ expect(feed([], 1, 'boom')).toEqual([{ type: 'error', message: expect.stringMatching(/boom/) }])+ })++ it('sends each image right after the message it came with', () => {+ const png = join(mkdtempSync(join(tmpdir(), 'ca-img-')), 'tela.png')+ writeFileSync(png, 'x')+ const input = codexAppInput({ prompt: 'a\n\nb', blocks: ['a', 'b'], images: [{ block: 0, path: png, mime: 'image/png' }, { block: 1, path: '/nao/existe.png', mime: 'image/png' }] })+ expect(input).toEqual([+ { type: 'text', text: 'a', text_elements: [] },+ { type: 'localImage', path: png },+ { type: 'text', text: 'b', text_elements: [] }+ ])+ expect(codexAppInput({ prompt: 'oi' })).toEqual([{ type: 'text', text: 'oi', text_elements: [] }])+ })+})++describe('Codex app-server isolation', () => {+ it('turns off every built-in tool exec does, read-only with no approvals, no skills or project docs', () => {+ const args = codexAppArgs()+ expect(args[0]).toBe('app-server')+ for (const f of CODEX_DISABLED_FEATURES) expect(args[args.indexOf(f) - 1]).toBe('--disable')+ expect(args).toEqual(+ expect.arrayContaining(['sandbox_mode="read-only"', 'approval_policy="never"', 'skills.include_instructions=false', 'skills.bundled.enabled=false', 'project_doc_max_bytes=0', 'history.persistence="none"', 'mcp_optional_startup_grace_ms=0'])+ )+ })++ it("gives each thread its folder, model and gateway, the gateway's address only over stdin", () => {+ const url = 'http://127.0.0.1:1/mcp/' + 'a'.repeat(48)+ const t = codexThread({ model: 'gpt-5.6-luna', effort: 'low', system: 'Você é Theo.', cwd: '/tmp/x', mcpUrl: url })+ expect(t).toEqual({+ model: 'gpt-5.6-luna',+ cwd: '/tmp/x',+ sandbox: 'read-only',+ approvalPolicy: 'never',+ developerInstructions: 'Você é Theo.',+ config: { model_reasoning_effort: 'low', web_search: 'disabled', 'mcp_servers.tucano': { url, default_tools_approval_mode: 'approve', tool_timeout_sec: 900 } }+ })+ expect(codexAppArgs(['-c', 'model_provider="corp"']).join(' ')).not.toContain('/mcp/')+ expect(codexThread({ model: 'm', effort: 'low', system: 'x', cwd: '/tmp/x', web: true }).config).toEqual({ model_reasoning_effort: 'low', web_search: 'live' })+ // the same note exec gets, for an agent with a computer+ expect(codexThread({ model: 'm', effort: 'low', system: 'Use write_file on /work.', cwd: '/tmp/x', mcpUrl: url }).developerInstructions).toMatch(/apply_patch/)+ })++ it('is isolated only in a home with no config.toml and no rules of its own', () => {+ const h = mkdtempSync(join(tmpdir(), 'ca-home-'))+ expect(codexIsolated(h)).toBe(true)+ writeFileSync(join(h, 'config.toml'), 'model = "x"\n')+ expect(codexIsolated(h)).toBe(false)+ const r = mkdtempSync(join(tmpdir(), 'ca-home-'))+ mkdirSync(join(r, 'rules'))+ expect(codexIsolated(r)).toBe(false)+ })+})++describe('Codex app-server process', () => {+ let dir: string+ let bin: string+ let home: string+ let logFile: string+ let engine: Engine | undefined+ const env = { ...process.env }++ beforeEach(() => {+ dir = mkdtempSync(join(tmpdir(), 'ca-cli-'))+ home = join(dir, 'home')+ mkdirSync(join(home, '.codex'), { recursive: true })+ logFile = join(dir, 'log.jsonl')+ process.env['FAKE_CODEX_LOG'] = logFile+ const script = join(dir, 'fake-codex.mjs')+ copyFileSync(join(import.meta.dirname, 'fixtures', 'fake-codex.mjs'), script)+ if (isWin) {+ bin = join(dir, 'codex.cmd')+ writeFileSync(bin, `@"${process.execPath}" "%~dp0\\fake-codex.mjs" %*\r\n`)+ } else {+ bin = join(dir, 'codex')+ writeFileSync(bin, `#!/usr/bin/env node\n${readFileSync(script, 'utf8')}`)+ chmodSync(bin, 0o755)+ }+ })+ afterEach(() => {+ engine?.dispose?.()+ engine = undefined+ process.env = { ...env }+ })++ const make = (): Engine => (engine = codexEngine(() => bin, home, async () => ({}), async () => ({ config: [], envNames: [] })))+ const collect = async (events: AsyncIterable<EngineEvent>): Promise<EngineEvent[]> => {+ const out: EngineEvent[] = []+ for await (const e of events) out.push(e)+ return out+ }+ const reply = (events: EngineEvent[]): string => events.flatMap((e) => (e.type === 'done' ? [e.text] : e.type === 'error' ? [`ERROR ${e.message}`] : [])).join('')+ const field = (s: string, k: string): string => new RegExp(`${k}=(\\S+)`).exec(s)?.[1] ?? ''+ const requests = (): { pid: number; method?: string; params?: Record<string, unknown>; argv?: string[]; exec?: string[] }[] =>+ existsSync(logFile) ? readFileSync(logFile, 'utf8').split('\n').filter(Boolean).map((l) => JSON.parse(l)) : []+ const cwd = (): string => {+ const c = join(dir, 'agents', 'a1')+ mkdirSync(c, { recursive: true })+ return c+ }+ const turn = (id: string | undefined, resume: boolean, prompt = 'oi', signal = new AbortController().signal): Turn => ({+ model: 'gpt-5.6-luna',+ effort: 'low',+ system: 'x',+ prompt,+ blocks: [prompt],+ cwd: cwd(),+ mcpUrl: 'http://127.0.0.1:1/mcp/' + 'a'.repeat(48),+ signal,+ ...(id ? { session: { id, resume, keep: true } } : {})+ })+ const until = async (ok: () => boolean): Promise<void> => {+ for (let i = 0; i < 100 && !ok(); i++) await new Promise((r) => setTimeout(r, 50))+ }++ it('goes on in the same thread of the same process, with only the new message', async () => {+ const e = make()+ expect(e.sessions).toBe(true)+ const one = reply(await collect(e.run(turn('s1', false, 'primeira'))))+ const two = reply(await collect(e.run(turn('s1', true, 'segunda'))))+ expect(field(two, 'pid')).toBe(field(one, 'pid'))+ expect(field(two, 'thread')).toBe(field(one, 'thread'))+ expect(two).toMatch(/turn=2 resumed=false/)+ const starts = requests().filter((r) => r.method === 'turn/start')+ expect(starts.map((r) => (r.params!['input'] as { text: string }[])[0]!.text)).toEqual(['primeira', 'segunda'])+ // isolated as exec is, and the gateway's token never in the arguments+ const argv = requests().find((r) => r.argv)!.argv!+ expect(argv).toEqual(codexAppArgs())+ expect(argv.join(' ')).not.toContain('/mcp/')+ const start = requests().find((r) => r.method === 'thread/start')!.params!+ expect(start).toMatchObject({ sandbox: 'read-only', approvalPolicy: 'never', ephemeral: false, cwd: cwd() })+ }, 20_000)++ it('past the cap of waiting threads, unloads the oldest; its next turn resumes it from disk', async () => {+ const e = make()+ const first = reply(await collect(e.run(turn('s0', false))))+ for (let i = 1; i <= MAX_IDLE; i++) await collect(e.run(turn(`s${i}`, false)))+ await until(() => requests().some((r) => r.method === 'thread/unsubscribe'))+ const again = reply(await collect(e.run(turn('s0', true))))+ expect(field(again, 'pid')).toBe(field(first, 'pid')) // the same process+ expect(again).toMatch(/turn=1 resumed=true/)+ expect(KEEP_IDLE_MS).toBeGreaterThan(0)+ }, 20_000)++ it('never unloads a thread in the middle of its turn, warmed again or past the cap', async () => {+ const e = make()+ await collect(e.run(turn('s0', false)))+ const long = collect(e.run(turn('s0', true, 'demore')))+ await until(() => requests().filter((r) => r.method === 'turn/start').length === 2)+ e.rewarm!('s0')+ for (let i = 1; i <= MAX_IDLE + 1; i++) await collect(e.run(turn(`s${i}`, false)))+ expect(reply(await long)).toMatch(/turn=2 resumed=false/)+ const thread = (r: { params?: Record<string, unknown> }): unknown => r.params?.['threadId']+ const s0 = thread(requests().find((r) => r.method === 'turn/start')!)+ expect(requests().filter((r) => r.method === 'thread/unsubscribe').map(thread)).not.toContain(s0)+ }, 20_000)++ it('resumes a thread in a new process when its process is gone, and deletes it on release', async () => {+ const e = make()+ const first = reply(await collect(e.run(turn('s1', false))))+ process.kill(Number(field(first, 'pid')))+ await until(() => requests().some((r) => r.method === 'thread/start') && !isAlive(Number(field(first, 'pid'))))+ const again = reply(await collect(e.run(turn('s1', true))))+ expect(field(again, 'pid')).not.toBe(field(first, 'pid'))+ expect(field(again, 'thread')).toBe(field(first, 'thread'))+ expect(again).toMatch(/resumed=true/)+ const sessions = join(home, '.codex', 'sessions')+ expect(leftThreads(join(home, '.codex')).map((t) => t.id)).toEqual([field(first, 'thread')])+ e.release!('s1')+ await e.settle!()+ expect(leftThreads(join(home, '.codex'))).toEqual([])+ expect(existsSync(sessions)).toBe(true)+ }, 20_000)++ it('interrupts a stopped turn and lets its thread go', async () => {+ const e = make()+ const stop = new AbortController()+ const running = collect(e.run(turn('s1', false, 'demore', stop.signal)))+ await until(() => requests().some((r) => r.method === 'turn/start'))+ const t0 = Date.now()+ stop.abort()+ const cut = await running+ expect(Date.now() - t0).toBeLessThan(2000) // it doesn't wait the 5 s+ expect(cut.some((x) => x.type === 'done' || x.type === 'error')).toBe(false)+ await until(() => requests().some((r) => r.method === 'thread/unsubscribe'))+ expect(requests().some((r) => r.method === 'turn/interrupt')).toBe(true)+ expect(requests().some((r) => r.method === 'thread/unsubscribe')).toBe(true)+ }, 20_000)++ it('starts a thread of its own, not on disk, ahead of a turn with no session, and uses it', async () => {+ const e = make()+ const t = turn(undefined, false)+ const { prompt: _p, blocks: _b, signal: _s, ...shape } = t+ e.warm!(shape)+ await until(() => requests().some((r) => r.method === 'thread/start'))+ const warmed = requests().find((r) => r.method === 'thread/start')!+ expect(warmed.params!['ephemeral']).toBe(true)+ const out = reply(await collect(e.run(t)))+ expect(out).toMatch(/turn=1/)+ expect(requests().filter((r) => r.method === 'thread/start')).toHaveLength(1) // the warmed one+ expect(leftThreads(join(home, '.codex'))).toEqual([])+ }, 20_000)++ it('goes to exec, with no sessions, on a CLI without the app-server', async () => {+ process.env['FAKE_CODEX_OLD'] = '1'+ const e = make()+ expect(e.sessions).toBe(true) // not known yet+ const out = reply(await collect(e.run(turn('s1', false))))+ expect(out).toMatch(/^exec pid=/)+ expect(e.sessions).toBe(false)+ expect(reply(await collect(e.run(turn(undefined, false))))).toMatch(/^exec pid=/)+ }, 20_000)++ it('goes to exec in a home with a config of its own, which the app-server would read', async () => {+ writeFileSync(join(home, '.codex', 'config.toml'), 'model = "x"\n')+ const e = make()+ expect(e.sessions).toBe(false)+ expect(reply(await collect(e.run(turn(undefined, false))))).toMatch(/^exec pid=/)+ expect(requests().some((r) => r.argv)).toBe(false)+ }, 20_000)++ it("cleans the threads an earlier run left, of the agents' folders only", async () => {+ const day = join(home, '.codex', 'sessions', '2026', '11', '06')+ mkdirSync(day, { recursive: true })+ const left = (id: string, folder: string): string => {+ const f = join(day, `rollout-2026-11-06T10-00-00-${id}.jsonl`)+ writeFileSync(f, `${JSON.stringify({ type: 'session_meta', payload: { id, cwd: folder } })}\n`)+ return f+ }+ const mine = left('0f8fad5b-d9cb-469f-a165-70867728950e', join(dir, 'agents', 'a1'))+ const other = left('1f8fad5b-d9cb-469f-a165-70867728950e', join(dir, 'agents-backup', 'x'))+ const e = make()+ e.clean!(join(dir, 'agents'))+ await e.settle!()+ expect(existsSync(mine)).toBe(false)+ expect(existsSync(other)).toBe(true)+ expect(readdirSync(day)).toHaveLength(1)+ }, 20_000)+})++function isAlive(pid: number): boolean {+ try {+ process.kill(pid, 0)+ return true+ } catch {+ return false+ }+}diff --git a/test/core-startup.test.ts b/test/core-startup.test.tsnew file mode 100644index 0000000..586cbfb--- /dev/null+++ b/test/core-startup.test.ts@@ -0,0 +1,87 @@+import { EventEmitter } from 'node:events'+import { mkdtempSync, readFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterAll, describe, expect, it, vi } from 'vitest'+import type { EngineId, EngineStatus } from '../src/shared/types'+import type { CoreEvent, Wire } from '../src/shared/rpc'++// The harnesses' check, held for as long as the test wants: on a real computer it takes+// seconds (a dozen CLIs), and longer with a hung one or no network.+const detection = vi.hoisted(() => {+ let release: (() => void) | undefined+ return { calls: 0, held: new Promise<void>((r) => (release = r)), release: () => release?.() }+})+const signedIn: EngineStatus = { installed: true, loggedIn: true, path: '/usr/local/bin/claude', version: '2.1.0', route: 'plan', account: 'Plano Claude Max' }+vi.mock('../src/core/engines/detect', async (original) => ({+ ...(await original<typeof import('../src/core/engines/detect')>()),+ adoptLoginShellPath: async () => {},+ detectEngines: async () => {+ detection.calls+++ await detection.held+ const no: EngineStatus = { installed: false, loggedIn: false }+ const engines: Record<EngineId, EngineStatus> = { claude: signedIn, codex: no, opencode: no, pi: no, gemini: no, cursor: no, grok: no }+ return { engines, listed: {}, codexCatalog: [] }+ }+}))++const dataDir = mkdtempSync(join(tmpdir(), 'tucano-startup-'))+const parent = Object.assign(new EventEmitter(), { postMessage: vi.fn() })+const saved = { ...process.env }+afterAll(() => {+ process.env = saved+})++// What the window does: a port, then the snapshot; and the events that come after.+function connect(): { events: CoreEvent[]; call: (method: string) => Promise<unknown> } {+ const events: CoreEvent[] = []+ const handlers: ((m: { data: unknown }) => void)[] = []+ const waits = new Map<number, (r: unknown) => void>()+ const port = {+ on: (ev: string, fn: (m: { data: unknown }) => void) => void (ev === 'message' && handlers.push(fn)),+ start: () => {},+ postMessage: (w: Wire) => {+ if ('event' in w) events.push(w.event)+ else waits.get(w.id)?.('result' in w ? w.result : w)+ }+ }+ parent.emit('message', { data: undefined, ports: [port] })+ let id = 0+ return {+ events,+ call: (method) =>+ new Promise((resolve) => {+ waits.set(++id, resolve)+ for (const h of handlers) h({ data: { id, method, params: {} } })+ })+ }+}++describe('the core starting', () => {+ it('says it is ready before the harnesses are checked, and tells the window when they are', async () => {+ Object.assign(process.env, { TUCANO_DATA: dataDir, TUCANO_DEFAULT_WORKSPACE: '0', TUCANO_SEED: '0', TUCANO_WEBHOOK_PORT: '47967', TUCANO_GIT_PORT: '47968', TUCANO_WIKI: join(dataDir, 'wiki') })+ delete process.env['TUCANO_FAKE_ENGINES']+ ;(process as unknown as { parentPort: typeof parent }).parentPort = parent+ const started = Date.now()+ await import('../src/core/index')+ await vi.waitFor(() => expect(parent.postMessage).toHaveBeenCalledWith({ type: 'ready' }), { timeout: 5_000 })+ expect(Date.now() - started).toBeLessThan(5_000)+ expect(detection.calls).toBe(1) // started, and still running++ const window = connect()+ const snapshot = (await window.call('snapshot')) as { settings: { engines: Record<EngineId, EngineStatus> } }+ // Nothing known yet on a first start: the screens say "checking", not "not installed".+ expect(snapshot.settings.engines.claude.checking).toBe(true)++ // The screens asking again meanwhile join the same check.+ await window.call('refreshEngines')+ await window.call('refreshEngines')+ expect(detection.calls).toBe(1)++ detection.release()+ await vi.waitFor(() => expect(window.events.some((e) => e.type === 'settings' && e.settings.engines.claude.loggedIn)).toBe(true))+ // Kept for the next start, which opens on it.+ const kept = JSON.parse(readFileSync(join(dataDir, 'engines.json'), 'utf8')) as { engines: Record<EngineId, EngineStatus> }+ expect(kept.engines.claude).toMatchObject({ loggedIn: true, account: 'Plano Claude Max' })+ }, 15_000)+})diff --git a/test/db-queries.test.ts b/test/db-queries.test.tsnew file mode 100644index 0000000..57ae5a2--- /dev/null+++ b/test/db-queries.test.ts@@ -0,0 +1,123 @@+import { mkdtempSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { DatabaseSync } from 'node:sqlite'+import { describe, expect, it } from 'vitest'+import { Db } from '../src/core/db'+import type { Agent, Approval, Message, Run } from '../src/shared/types'++const agent = (id: string): Agent => ({ id, name: id, handle: id, role: '', color: 'sky', instructions: '', modelId: 'sonnet', effort: 'low', limit: 1000, used: 0, grants: {}, memory: 'auto', computer: false, archived: false })+const run = (status: Run['status']): Run => ({ status, steps: [{ id: 's1', label: 'lendo', status: 'running' }] })+const msg = (id: string, conversationId: string, at: number, extra: Partial<Message> = {}): Message => ({ id, conversationId, author: { kind: 'agent', id: 'a1' }, text: id, at, ...extra })+const approval = (id: string, state: Approval['state']): Approval => ({ id, hash: id, agentId: 'a1', conversationId: 'c1', messageId: 'm1', connectorId: 'k', connectorName: 'K', tool: 't', args: {}, why: '', highRisk: false, state, createdAt: 1, expiresAt: Date.now() + 60_000 })++function seeded(): Db {+ const db = new Db(':memory:')+ for (const id of ['a1', 'a2', 'a3']) db.saveAgent(agent(id))+ db.createConversation({ id: 'c1', kind: 'channel', name: 'geral', members: ['a3', 'a1'] })+ db.createConversation({ id: 'c2', kind: 'dm', name: 'a2', members: ['a2'], threads: true })+ db.saveMessage(msg('m1', 'c1', 1, { run: run('working') }))+ db.saveMessage(msg('m2', 'c1', 2, { run: run('done') }))+ db.saveMessage(msg('m3', 'c2', 3, { run: run('waiting_approval') }))+ db.saveMessage(msg('m4', 'c2', 4))+ for (const id of ['m1', 'm2', 'm3']) db.recordActivity(db.message(id)!, null)+ return db+}++describe('reading just what is asked', () => {+ it('one conversation, the same as in the full list', () => {+ const db = seeded()+ for (const c of db.conversations()) expect(db.conversation(c.id)).toEqual(c)+ expect(db.conversation('c1')).toMatchObject({ members: ['a3', 'a1'], unread: 1 }) // members in the order they joined+ expect(db.conversation('c2')).toMatchObject({ threads: true, unread: 1 })+ expect(db.conversation('nope')).toBeUndefined()+ db.markRead('c1')+ expect(db.conversation('c1')?.unread).toBe(0)+ })++ it('the replies by the state of their run', () => {+ const db = seeded()+ expect(db.messagesWithRun(['working']).map((m) => m.id)).toEqual(['m1'])+ expect(db.messagesWithRun(['working', 'waiting_approval']).map((m) => m.id)).toEqual(['m1', 'm3'])+ expect(db.messagesWithRun([])).toEqual([])+ })++ it('a start marks only the working replies as interrupted', () => {+ const db = seeded()+ expect(db.interruptStaleRuns()).toBe(1)+ expect(db.message('m1')?.run).toMatchObject({ status: 'interrupted', steps: [{ status: 'error' }] })+ expect(db.message('m2')?.run?.status).toBe('done')+ expect(db.message('m3')?.run?.status).toBe('waiting_approval')+ expect(db.interruptStaleRuns()).toBe(0)+ })++ it('the pending approvals, counted', () => {+ const db = seeded()+ db.createApproval(approval('p1', 'pending'))+ db.createApproval(approval('p2', 'pending'))+ db.createApproval(approval('d1', 'refused'))+ expect(db.pendingApprovals()).toBe(2)+ db.decideApproval('p1', 'approved')+ expect(db.pendingApprovals()).toBe(db.approvals().filter((a) => a.state === 'pending').length)+ })++ it('one artifact by its id', () => {+ const db = seeded()+ const a = { id: 'f1', agentId: 'a1', conversationId: 'c1', messageId: 'm1', kind: 'file' as const, name: 'notas.md', title: 'Notas', source: 'x', size: 3, createdAt: 5 }+ db.saveArtifact(a)+ db.saveArtifact({ ...a, id: 'f2', name: 'outro.md' })+ expect(db.artifact('f1')).toEqual(a)+ expect(db.artifact('f1')).toEqual(db.artifacts().find((x) => x.id === 'f1'))+ expect(db.artifact('nope')).toBeUndefined()+ })+})++describe('indexes for what runs often', () => {+ const plan = (raw: DatabaseSync, sql: string): string => (raw.prepare(`EXPLAIN QUERY PLAN ${sql}`).all() as { detail: string }[]).map((r) => r.detail).join(' | ')++ it('an existing database gains them, keeps its data, and the hot queries use them', () => {+ const file = join(mkdtempSync(join(tmpdir(), 'tucano-idx-')), 'tucano.db')+ // A database from before the indexes: the last migration undone, with messages in it.+ const db0 = new Db(file)+ db0.saveAgent(agent('a1'))+ db0.createConversation({ id: 'c1', kind: 'channel', name: 'geral', members: ['a1'] })+ db0.saveMessage(msg('root', 'c1', 1))+ db0.saveMessage(msg('reply', 'c1', 2, { threadId: 'root' }))+ db0.close()+ const raw = new DatabaseSync(file)+ const { user_version } = raw.prepare('PRAGMA user_version').get() as { user_version: number }+ raw.exec(`DROP INDEX messages_by_thread_id; DROP INDEX messages_by_author; DROP INDEX receipts_by_message; PRAGMA user_version = ${user_version - 1}`)+ expect(plan(raw, "SELECT conversation_id FROM messages WHERE author_kind = 'agent' AND author_id = 'a1' ORDER BY at DESC LIMIT 1")).toContain('SCAN messages')+ raw.close()++ const db = new Db(file)+ expect(db.message('reply')?.threadId).toBe('root')+ expect(db.lastConversationOf('a1')).toBe('c1')+ expect(db.quietThreads(10, 0).map((t) => t.id)).toEqual(['root'])+ db.close()++ const after = new DatabaseSync(file)+ expect((after.prepare('PRAGMA user_version').get() as { user_version: number }).user_version).toBe(user_version)+ expect(plan(after, "SELECT conversation_id FROM messages WHERE author_kind = 'agent' AND author_id = 'a1' ORDER BY at DESC LIMIT 1")).toContain('messages_by_author')+ expect(plan(after, "SELECT COALESCE(ROUND(SUM(output_tokens)), 0) FROM receipts WHERE message_id = 'm1'")).toContain('receipts_by_message')+ expect(+ plan(+ after,+ `SELECT r.id, t.last FROM (SELECT thread_id, MAX(at) AS last FROM messages WHERE thread_id IS NOT NULL AND author_kind != 'system' GROUP BY thread_id) t+ CROSS JOIN messages r ON r.id = t.thread_id WHERE r.thread_id IS NULL AND t.last < 10 ORDER BY t.last`+ )+ ).toMatch(/SEARCH messages USING INDEX messages_by_thread_id.*SEARCH r USING INDEX sqlite_autoindex_messages_1/)+ after.close()+ })++ it('a query asked again reuses its compiled statement, which holds nothing between uses', () => {+ const db = seeded()+ const inner = (db as unknown as { db: DatabaseSync }).db+ expect(inner.prepare('SELECT * FROM messages WHERE id = ?')).toBe(inner.prepare('SELECT * FROM messages WHERE id = ?'))+ expect(db.message('m1')?.id).toBe('m1')+ expect(db.message('m2')?.id).toBe('m2')+ expect(inner.isTransaction).toBe(false)+ db.tx(() => db.saveMessage(msg('m5', 'c1', 5))) // a write right after a get still goes through+ expect(db.message('m5')?.text).toBe('m5')+ })+})diff --git a/test/engine-check.test.ts b/test/engine-check.test.tsnew file mode 100644index 0000000..74c5fce--- /dev/null+++ b/test/engine-check.test.ts@@ -0,0 +1,148 @@+import { existsSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { describe, expect, it } from 'vitest'+import { checkingFindings, EngineCheck, type EngineFindings, type OneFinding } from '../src/core/engine-check'+import type { EngineId, EngineStatus } from '../src/shared/types'++// A promise the test settles by hand: a check that takes as long as the test wants.+function later<T>(): { promise: Promise<T>; resolve: (v: T) => void } {+ let resolve!: (v: T) => void+ const promise = new Promise<T>((r) => (resolve = r))+ return { promise, resolve }+}++const signedIn: EngineStatus = { installed: true, loggedIn: true, path: '/bin/claude', version: '2.0.0', route: 'plan' }+const findings = (over: Partial<Record<EngineId, EngineStatus>> = {}): Omit<EngineFindings, 'accounts'> => {+ const base = checkingFindings()+ const engines = Object.fromEntries(Object.keys(base.engines).map((e) => [e, { installed: false, loggedIn: false }])) as Record<EngineId, EngineStatus>+ return { engines: { ...engines, ...over }, listed: { opencode: [] }, codexCatalog: [] }+}+const tmpFile = (): string => join(mkdtempSync(join(tmpdir(), 'tucano-engines-')), 'engines.json')++describe('checking the harnesses', () => {+ it('shares one check among everyone who asks while it runs', async () => {+ const runs: ReturnType<typeof later<Omit<EngineFindings, 'accounts'>>>[] = []+ const check = new EngineCheck({+ all: () => {+ const r = later<Omit<EngineFindings, 'accounts'>>()+ runs.push(r)+ return r.promise+ },+ one: async () => ({ status: signedIn })+ })+ const a = check.detect()+ const b = check.detect()+ const c = check.detect()+ expect(runs).toHaveLength(1) // three callers, one check+ expect(b).toBe(a)+ runs[0]!.resolve(findings({ claude: signedIn }))+ const [ra, rb, rc] = await Promise.all([a, b, c])+ expect(ra.engines.claude.loggedIn).toBe(true)+ expect(rb).toBe(ra)+ expect(rc).toBe(ra)+ // Once it ended, the next call is a new check.+ void check.detect()+ expect(runs).toHaveLength(2)+ runs[1]!.resolve(findings())+ })++ it('a check that fails lets the next one run', async () => {+ let n = 0+ const check = new EngineCheck({+ all: async () => {+ n+++ if (n === 1) throw new Error('a CLI hung')+ return findings({ claude: signedIn })+ },+ one: async () => ({ status: signedIn })+ })+ await expect(check.detect()).rejects.toThrow('a CLI hung')+ expect(check.known).toBe(false)+ expect((await check.detect()).engines.claude.loggedIn).toBe(true)+ expect(n).toBe(2)+ })++ it('checks only the harness being signed into, and joins a full check already running', async () => {+ const full = later<Omit<EngineFindings, 'accounts'>>()+ const asked: EngineId[] = []+ const one = later<OneFinding>()+ let fulls = 0+ const check = new EngineCheck({+ all: () => (fulls++, full.promise),+ one: (e) => (asked.push(e), one.promise)+ })+ // A full check running: a recheck waits for it instead of starting its own.+ const running = check.detect()+ expect(check.recheck('codex')).toBe(running)+ expect(asked).toEqual([])+ full.resolve(findings({ claude: signedIn }))+ await running++ // Nothing running: only that harness, once however many times it's asked.+ const r1 = check.recheck('codex')+ const r2 = check.recheck('codex')+ expect(r2).toBe(r1)+ expect(asked).toEqual(['codex'])+ one.resolve({ status: { installed: true, loggedIn: true, route: 'plan' }, listed: ['gpt-5.6-luna'], codexCatalog: [{ slug: 'gpt-5.6-luna', label: 'Luna' }] })+ const after = await r1+ expect(fulls).toBe(1)+ expect(after.engines.codex.loggedIn).toBe(true)+ expect(after.engines.claude.loggedIn).toBe(true) // the others stay as the last check found them+ expect(after.listed.codex).toEqual(['gpt-5.6-luna'])+ expect(after.listed.opencode).toEqual([])+ expect(after.codexCatalog.map((m) => m.slug)).toEqual(['gpt-5.6-luna'])+ })++ it('the accounts are checked inside the same check, and only that harness’s on a recheck', async () => {+ const seen: (EngineId | undefined)[] = []+ const check = new EngineCheck({+ all: async () => findings({ claude: signedIn }),+ one: async () => ({ status: signedIn }),+ after: async (_found, engine) => {+ seen.push(engine)+ return { accounts: { work: { loggedIn: true, detail: 'Plano Claude Max' } } }+ }+ })+ expect((await check.detect()).accounts).toEqual({ work: { loggedIn: true, detail: 'Plano Claude Max' } })+ await check.recheck('claude')+ expect(seen).toEqual([undefined, 'claude'])+ })+})++describe('the last check, kept', () => {+ it('before any check, every harness says it is being checked', () => {+ const check = new EngineCheck({ file: tmpFile(), all: async () => findings(), one: async () => ({ status: signedIn }) })+ expect(check.known).toBe(false)+ expect(Object.values(check.current.engines).every((s) => s.checking && !s.installed)).toBe(true)+ })++ it('the next start opens on what the last check found, until the new one ends', async () => {+ const file = tmpFile()+ const first = new EngineCheck({ file, all: async () => findings({ claude: signedIn }), one: async () => ({ status: signedIn }), after: async () => ({ accounts: { a1: { loggedIn: true } } }) })+ await first.detect()+ expect(existsSync(file)).toBe(true)++ const slow = later<Omit<EngineFindings, 'accounts'>>()+ const next = new EngineCheck({ file, all: () => slow.promise, one: async () => ({ status: signedIn }) })+ expect(next.known).toBe(true)+ expect(next.current.engines.claude).toEqual(signedIn)+ expect(next.current.engines.codex.checking).toBeUndefined()+ expect(next.current.accounts).toEqual({ a1: { loggedIn: true } })+ const done = next.detect()+ slow.resolve(findings())+ expect((await done).engines.claude.loggedIn).toBe(false) // signed out since: the new check wins+ expect((JSON.parse(readFileSync(file, 'utf8')) as EngineFindings).engines.claude.loggedIn).toBe(false)+ })++ it('a damaged file, or one from a version with fewer harnesses, is read safely', () => {+ const file = tmpFile()+ writeFileSync(file, '{ not json')+ expect(new EngineCheck({ file, all: async () => findings(), one: async () => ({ status: signedIn }) }).known).toBe(false)+ writeFileSync(file, JSON.stringify({ engines: { claude: signedIn }, listed: {}, codexCatalog: [] }))+ const check = new EngineCheck({ file, all: async () => findings(), one: async () => ({ status: signedIn }) })+ expect(check.known).toBe(true)+ expect(check.current.engines.claude).toEqual(signedIn)+ expect(check.current.engines.grok.checking).toBe(true)+ })+})diff --git a/test/engines.test.ts b/test/engines.test.tsindex 94823d0..db7365b 100644--- a/test/engines.test.ts+++ b/test/engines.test.ts@@ -69,11 +69,19 @@ describe('Claude Code stream', () => {// The address (and its token) comes from the environment: never in the arguments, which other programs can list.expect(JSON.parse(args[args.indexOf('--mcp-config') + 1]!)).toEqual({ mcpServers: { tucano: { type: 'http', url: '${TUCANO_MCP_URL}' } } })expect(args.join(' ')).not.toContain('/mcp/abc')- expect(args[args.indexOf('--allowedTools') + 1]).toBe('mcp__tucano')+ expect(args.slice(args.indexOf('--allowedTools') + 1)).toEqual(['mcp__tucano', 'ToolSearch'])expect(args).toContain('--strict-mcp-config')expect(claudeArgs({ model: 'sonnet', effort: 'low', system: 'x' })).not.toContain('--mcp-config')})+ it('keeps tool search on with the gateway, so connector tools stay out of every call', () => {+ // Without ToolSearch among the tools, the CLI puts every MCP tool in every model call.+ const args = claudeArgs({ model: 'sonnet', effort: 'low', system: 'x', mcpUrl: 'http://127.0.0.1:1/mcp/abc' })+ expect(args[args.indexOf('--tools') + 1]).toBe('ToolSearch')+ const noGateway = claudeArgs({ model: 'sonnet', effort: 'low', system: 'x', web: true })+ expect(noGateway[noGateway.indexOf('--tools') + 1]).toBe('WebSearch,WebFetch')+ })+it('runs isolated: no built-in tools, no user settings, no session, never --bare', () => {const args = claudeArgs({ model: 'sonnet', effort: 'medium', system: 'x' })expect(args).toEqual(expect.arrayContaining(['-p', '--strict-mcp-config', '--no-session-persistence']))@@ -152,8 +160,8 @@ describe('Claude Code stream', () => {it('with web, gets only the web tools, pre-allowed, and reports each search and page read', () => {const args = claudeArgs({ model: 'sonnet', effort: 'low', system: 'x', mcpUrl: 'http://127.0.0.1:1/mcp/abc', web: true })- expect(args[args.indexOf('--tools') + 1]).toBe('WebSearch,WebFetch')- expect(args.slice(args.indexOf('--allowedTools') + 1)).toEqual(['mcp__tucano', 'WebSearch', 'WebFetch'])+ expect(args[args.indexOf('--tools') + 1]).toBe('ToolSearch,WebSearch,WebFetch')+ expect(args.slice(args.indexOf('--allowedTools') + 1)).toEqual(['mcp__tucano', 'ToolSearch', 'WebSearch', 'WebFetch'])const assistant = JSON.stringify({type: 'assistant',message: {diff --git a/test/fixtures/codex-app-turn.jsonl b/test/fixtures/codex-app-turn.jsonlnew file mode 100644index 0000000..4108ea9--- /dev/null+++ b/test/fixtures/codex-app-turn.jsonl@@ -0,0 +1,113 @@+{"method":"thread/started","params":{"thread":{"id":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","extra":null,"sessionId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-5.6-luna","reasoningEffort":"low","createdAt":1794008170,"updatedAt":1794008170,"recencyAt":1794008170,"status":{"type":"idle"},"path":"/tmp/tucano/codex-home/.codex/sessions/2026/11/06/rollout-2026-11-06T20-36-10-01a1b338-3f84-7a10-85e3-9b3f62e8b22b.jsonl","cwd":"/tmp/tucano/agents/a1","cliVersion":"0.153.4","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"turns":[]}},"emittedAtMs":1794008170427}+{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","name":"tucano","status":"starting","error":null,"failureReason":null},"emittedAtMs":1794008170427}+{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","name":"tucano","status":"ready","error":null,"failureReason":null},"emittedAtMs":1794008170427}+{"method":"thread/status/changed","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1794008170497}+{"method":"turn/started","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turn":{"id":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1794008170,"completedAt":null,"durationMs":null}},"emittedAtMs":1794008170497}+{"method":"item/started","params":{"item":{"type":"userMessage","id":"01a1b338-4672-7fc3-b2b8-0d7ce1adff8f","clientId":null,"content":[{"type":"text","text":"Call the ping tool. Then reply in one line: its result, and the exact names of every tool you can call (all of them, built-in ones included).","text_elements":[]}]},"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","startedAtMs":1794008172146},"emittedAtMs":1794008172148}+{"method":"item/completed","params":{"item":{"type":"userMessage","id":"01a1b338-4672-7fc3-b2b8-0d7ce1adff8f","clientId":null,"content":[{"type":"text","text":"Call the ping tool. Then reply in one line: its result, and the exact names of every tool you can call (all of them, built-in ones included).","text_elements":[]}]},"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","completedAtMs":1794008172146},"emittedAtMs":1794008172157}+{"method":"item/started","params":{"item":{"type":"reasoning","id":"rs_0a00cbce65e413b1016aee646d7f1c87d2b54f9db92502c3f7","summary":[],"content":[]},"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","startedAtMs":1794008173520},"emittedAtMs":1794008173520}+{"method":"item/completed","params":{"item":{"type":"reasoning","id":"rs_0a00cbce65e413b1016aee646d7f1c87d2b54f9db92502c3f7","summary":[],"content":[]},"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","completedAtMs":1794008173520},"emittedAtMs":1794008173527}+{"method":"turn/moderationMetadata","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","metadata":{"prompt":{"omnimod":{"protection_type":"omnimod","outputs":[{"results":[{"category_flags":{"A1":false,"A2":false,"A3":false,"C1":false,"C11":false,"C2":false,"E1":false,"E2":false,"E3":false,"H1":false,"H2":false,"H3":false,"JB1":false,"K1":false,"K2":false,"K3":false,"K4":false,"P1":false,"P2":false,"P3":false,"P4":false,"PD1":false,"PD4":false,"S1":false,"S3+":false,"S4":false,"SH":false,"TXT-C3":false,"TXT-C4":false,"V1":false,"V2+":false,"V4+":false,"REFUSED":false,"CBRN-B1+":false,"IMG-C1":false,"IMG-C11":false,"IMG-C2":false,"IMG-S1":false,"IMG-SH":false,"IMG-V1":false,"IMG-V2+":false,"IMG-V4+":false}}],"is_blocked":false}]}},"generation":{},"tool_call":{},"tool_response":{}}},"emittedAtMs":1794008174219}+{"method":"thread/tokenUsage/updated","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","tokenUsage":{"total":{"totalTokens":6253,"inputTokens":6188,"cachedInputTokens":0,"cacheWriteInputTokens":0,"outputTokens":65,"reasoningOutputTokens":29},"last":{"totalTokens":6253,"inputTokens":6188,"cachedInputTokens":0,"cacheWriteInputTokens":0,"outputTokens":65,"reasoningOutputTokens":29},"modelContextWindow":258400}},"emittedAtMs":1794008174692}+{"method":"account/rateLimits/updated","params":{"rateLimits":{"limitId":"codex","limitName":null,"primary":{"usedPercent":3,"windowDurationMins":10080,"resetsAt":1794567151},"secondary":null,"credits":{"hasCredits":false,"unlimited":false,"balance":"0"},"individualLimit":null,"spendControlReached":null,"planType":"plus","rateLimitReachedType":null}},"emittedAtMs":1794008174692}+{"method":"item/started","params":{"item":{"type":"reasoning","id":"rs_0a00cbce65e413b1016aee6470599087d2895caaae77e948ab","summary":[],"content":[]},"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","startedAtMs":1794008176366},"emittedAtMs":1794008176366}+{"method":"item/completed","params":{"item":{"type":"reasoning","id":"rs_0a00cbce65e413b1016aee6470599087d2895caaae77e948ab","summary":[],"content":[]},"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","completedAtMs":1794008176366},"emittedAtMs":1794008176379}+{"method":"item/started","params":{"item":{"type":"mcpToolCall","id":"exec-485b2802-8315-4b6d-8f63-a4002804e467","server":"tucano","tool":"ping","status":"inProgress","arguments":{},"appContext":null,"pluginId":null,"readOnlyHint":null,"result":null,"error":null,"durationMs":null},"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","startedAtMs":1794008177260},"emittedAtMs":1794008177290}+{"method":"turn/moderationMetadata","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","metadata":{"prompt":{},"generation":{},"tool_call":{},"tool_response":{}}},"emittedAtMs":1794008177290}+{"method":"item/completed","params":{"item":{"type":"mcpToolCall","id":"exec-485b2802-8315-4b6d-8f63-a4002804e467","server":"tucano","tool":"ping","status":"completed","arguments":{},"appContext":null,"pluginId":null,"readOnlyHint":null,"result":{"content":[{"type":"text","text":"pong-42"}],"structuredContent":null,"_meta":null},"error":null,"durationMs":36},"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","completedAtMs":1794008177311},"emittedAtMs":1794008177322}+{"method":"thread/tokenUsage/updated","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","tokenUsage":{"total":{"totalTokens":14108,"inputTokens":13945,"cachedInputTokens":6016,"cacheWriteInputTokens":0,"outputTokens":163,"reasoningOutputTokens":82},"last":{"totalTokens":7855,"inputTokens":7757,"cachedInputTokens":6016,"cacheWriteInputTokens":0,"outputTokens":98,"reasoningOutputTokens":53},"modelContextWindow":258400}},"emittedAtMs":1794008177337}+{"method":"account/rateLimits/updated","params":{"rateLimits":{"limitId":"codex","limitName":null,"primary":{"usedPercent":3,"windowDurationMins":10080,"resetsAt":1794567151},"secondary":null,"credits":{"hasCredits":false,"unlimited":false,"balance":"0"},"individualLimit":null,"spendControlReached":null,"planType":"plus","rateLimitReachedType":null}},"emittedAtMs":1794008177337}+{"method":"item/started","params":{"item":{"type":"reasoning","id":"rs_0a00cbce65e413b1016aee6475005087d2ada38f701ce10389","summary":[],"content":[]},"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","startedAtMs":1794008181054},"emittedAtMs":1794008181054}+{"method":"item/completed","params":{"item":{"type":"reasoning","id":"rs_0a00cbce65e413b1016aee6475005087d2ada38f701ce10389","summary":[],"content":[]},"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","completedAtMs":1794008181054},"emittedAtMs":1794008181063}+{"method":"item/started","params":{"item":{"type":"agentMessage","id":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","text":"","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null},"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","startedAtMs":1794008181237},"emittedAtMs":1794008181237}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"pong"},"emittedAtMs":1794008181237}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"-"},"emittedAtMs":1794008181359}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"42"},"emittedAtMs":1794008181359}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":";"},"emittedAtMs":1794008181359}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":" tools"},"emittedAtMs":1794008181359}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":":"},"emittedAtMs":1794008181359}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":" apply"},"emittedAtMs":1794008181359}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"_patch"},"emittedAtMs":1794008181359}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":","},"emittedAtMs":1794008181359}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":" list"},"emittedAtMs":1794008181359}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"_m"},"emittedAtMs":1794008181359}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"cp"},"emittedAtMs":1794008181359}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"_resource"},"emittedAtMs":1794008181360}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"_templates"},"emittedAtMs":1794008181495}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":","},"emittedAtMs":1794008181495}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":" list"},"emittedAtMs":1794008181495}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"_m"},"emittedAtMs":1794008181495}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"cp"},"emittedAtMs":1794008181495}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"_resources"},"emittedAtMs":1794008181495}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":","},"emittedAtMs":1794008181495}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":" m"},"emittedAtMs":1794008181495}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"cp"},"emittedAtMs":1794008181632}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"__"},"emittedAtMs":1794008181632}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"t"},"emittedAtMs":1794008181632}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"uc"},"emittedAtMs":1794008181632}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"ano"},"emittedAtMs":1794008181632}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"__"},"emittedAtMs":1794008181632}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"ping"},"emittedAtMs":1794008181632}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":","},"emittedAtMs":1794008181632}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":" multi"},"emittedAtMs":1794008181778}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"_agent"},"emittedAtMs":1794008181778}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"_v"},"emittedAtMs":1794008181778}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"1"},"emittedAtMs":1794008181778}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"__"},"emittedAtMs":1794008181778}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"close"},"emittedAtMs":1794008181778}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"_agent"},"emittedAtMs":1794008181778}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":","},"emittedAtMs":1794008181778}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":" multi"},"emittedAtMs":1794008181925}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"_agent"},"emittedAtMs":1794008181925}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"_v"},"emittedAtMs":1794008181925}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"1"},"emittedAtMs":1794008181925}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"__"},"emittedAtMs":1794008181925}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"resume"},"emittedAtMs":1794008181925}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"_agent"},"emittedAtMs":1794008181925}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":","},"emittedAtMs":1794008181925}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":" multi"},"emittedAtMs":1794008182060}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"_agent"},"emittedAtMs":1794008182060}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"_v"},"emittedAtMs":1794008182060}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"1"},"emittedAtMs":1794008182060}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"__"},"emittedAtMs":1794008182060}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"send"},"emittedAtMs":1794008182060}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"_input"},"emittedAtMs":1794008182060}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":","},"emittedAtMs":1794008182060}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":" multi"},"emittedAtMs":1794008182204}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"_agent"},"emittedAtMs":1794008182204}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"_v"},"emittedAtMs":1794008182204}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"1"},"emittedAtMs":1794008182204}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"__"},"emittedAtMs":1794008182204}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"spawn"},"emittedAtMs":1794008182204}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"_agent"},"emittedAtMs":1794008182204}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":","},"emittedAtMs":1794008182204}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":" multi"},"emittedAtMs":1794008182349}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"_agent"},"emittedAtMs":1794008182349}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"_v"},"emittedAtMs":1794008182349}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"1"},"emittedAtMs":1794008182349}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"__"},"emittedAtMs":1794008182350}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"wait"},"emittedAtMs":1794008182350}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"_agent"},"emittedAtMs":1794008182350}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":","},"emittedAtMs":1794008182350}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":" read"},"emittedAtMs":1794008182492}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"_m"},"emittedAtMs":1794008182492}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"cp"},"emittedAtMs":1794008182492}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"_resource"},"emittedAtMs":1794008182492}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":","},"emittedAtMs":1794008182492}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":" functions"},"emittedAtMs":1794008182492}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":".exec"},"emittedAtMs":1794008182492}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":","},"emittedAtMs":1794008182492}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":" functions"},"emittedAtMs":1794008182626}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":".wait"},"emittedAtMs":1794008182627}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":","},"emittedAtMs":1794008182627}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":" functions"},"emittedAtMs":1794008182627}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":".request"},"emittedAtMs":1794008182627}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"_user"},"emittedAtMs":1794008182627}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"_input"},"emittedAtMs":1794008182627}+{"method":"item/agentMessage/delta","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","itemId":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","delta":"."},"emittedAtMs":1794008182627}+{"method":"turn/moderationMetadata","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","metadata":{"prompt":{},"generation":{},"tool_call":{},"tool_response":{}}},"emittedAtMs":1794008182711}+{"method":"item/completed","params":{"item":{"type":"agentMessage","id":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","text":"pong-42; tools: apply_patch, list_mcp_resource_templates, list_mcp_resources, mcp__tucano__ping, multi_agent_v1__close_agent, multi_agent_v1__resume_agent, multi_agent_v1__send_input, multi_agent_v1__spawn_agent, multi_agent_v1__wait_agent, read_mcp_resource, functions.exec, functions.wait, functions.request_user_input.","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null},"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","completedAtMs":1794008182711},"emittedAtMs":1794008182724}+{"method":"thread/tokenUsage/updated","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turnId":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","tokenUsage":{"total":{"totalTokens":22338,"inputTokens":21916,"cachedInputTokens":6016,"cacheWriteInputTokens":0,"outputTokens":422,"reasoningOutputTokens":250},"last":{"totalTokens":8230,"inputTokens":7971,"cachedInputTokens":0,"cacheWriteInputTokens":0,"outputTokens":259,"reasoningOutputTokens":168},"modelContextWindow":258400}},"emittedAtMs":1794008182729}+{"method":"account/rateLimits/updated","params":{"rateLimits":{"limitId":"codex","limitName":null,"primary":{"usedPercent":3,"windowDurationMins":10080,"resetsAt":1794567151},"secondary":null,"credits":{"hasCredits":false,"unlimited":false,"balance":"0"},"individualLimit":null,"spendControlReached":null,"planType":"plus","rateLimitReachedType":null}},"emittedAtMs":1794008182729}+{"method":"thread/status/changed","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","status":{"type":"idle"}},"emittedAtMs":1794008182734}+{"method":"turn/completed","params":{"threadId":"01a1b338-3f84-7a10-85e3-9b3f62e8b22b","turn":{"id":"01a1b338-3fc3-72c3-bffb-c883a001c2e9","items":[{"type":"agentMessage","id":"msg_0a00cbce65e413b1016aee6475176087d28193a66988a179ad","text":"pong-42; tools: apply_patch, list_mcp_resource_templates, list_mcp_resources, mcp__tucano__ping, multi_agent_v1__close_agent, multi_agent_v1__resume_agent, multi_agent_v1__send_input, multi_agent_v1__spawn_agent, multi_agent_v1__wait_agent, read_mcp_resource, functions.exec, functions.wait, functions.request_user_input.","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1794008170,"completedAt":1794008182,"durationMs":12286}},"emittedAtMs":1794008182734}diff --git a/test/fixtures/fake-codex.mjs b/test/fixtures/fake-codex.mjsnew file mode 100644index 0000000..cfa2902--- /dev/null+++ b/test/fixtures/fake-codex.mjs@@ -0,0 +1,105 @@+// Stands in for the Codex CLI: `codex app-server` speaking its JSON-RPC over stdio (the method and+// event names of Codex 0.153), and `codex exec --json` for the fallback. A reply says which process,+// which thread, which of the thread's turns it was, and whether the thread was resumed into this+// process. "demore" in the message: it takes 5 s before answering, unless interrupted. A thread+// not ephemeral is written to CODEX_HOME/sessions as Codex does, and thread/delete takes it away.+// FAKE_CODEX_OLD=1: a CLI with no app-server. FAKE_CODEX_LOG: every request goes there, one per line.+import { randomUUID } from 'node:crypto'+import { appendFileSync, existsSync, mkdirSync, readdirSync, rmSync, writeFileSync } from 'node:fs'+import { join } from 'node:path'+import { createInterface } from 'node:readline'++const log = (entry) => process.env.FAKE_CODEX_LOG && appendFileSync(process.env.FAKE_CODEX_LOG, `${JSON.stringify({ pid: process.pid, ...entry })}\n`)+const out = (msg) => process.stdout.write(`${JSON.stringify(msg)}\n`)+const home = process.env.CODEX_HOME ?? join(process.env.HOME ?? '.', '.codex')+const day = join(home, 'sessions', '2026', '11', '06')+const fileOf = (id) => join(day, `rollout-2026-11-06T10-00-00-${id}.jsonl`)+const find = (id) => (existsSync(day) ? readdirSync(day).find((f) => f.endsWith(`-${id}.jsonl`)) : undefined)++if (process.argv[2] === 'exec') {+ log({ exec: process.argv.slice(2) })+ let input = ''+ process.stdin.on('data', (d) => (input += d))+ process.stdin.on('end', () => {+ out({ type: 'thread.started', thread_id: 'x' })+ out({ type: 'item.completed', item: { id: 'i0', type: 'agent_message', text: `exec pid=${process.pid}` } })+ out({ type: 'turn.completed', usage: { input_tokens: 10, cached_input_tokens: 0, output_tokens: 2 } })+ })+} else if (process.argv[2] === 'app-server') {+ if (process.env.FAKE_CODEX_OLD) {+ process.stderr.write("error: unrecognized subcommand 'app-server'\n")+ process.exit(2)+ }+ log({ argv: process.argv.slice(2) })+ const threads = new Map() // id → { turns, resumed, running }+ createInterface({ input: process.stdin }).on('line', async (line) => {+ const m = JSON.parse(line)+ if (m.method) log({ method: m.method, params: m.params })+ const reply = (result) => out({ id: m.id, result })+ const fail = (message, code = -32600) => out({ id: m.id, error: { code, message } })+ switch (m.method) {+ case 'initialize':+ return reply({ userAgent: 'fake', codexHome: home, platformFamily: 'unix', platformOs: 'macos' })+ case 'initialized':+ return+ case 'thread/start': {+ const id = randomUUID()+ threads.set(id, { turns: 0, resumed: false })+ if (!m.params.ephemeral) {+ mkdirSync(day, { recursive: true })+ writeFileSync(fileOf(id), `${JSON.stringify({ type: 'session_meta', payload: { id, cwd: m.params.cwd } })}\n`)+ }+ return reply({ thread: { id, path: m.params.ephemeral ? null : fileOf(id), ephemeral: !!m.params.ephemeral }, model: m.params.model, cwd: m.params.cwd, instructionSources: [], approvalPolicy: 'never', sandbox: { type: 'readOnly' } })+ }+ case 'thread/resume': {+ if (!find(m.params.threadId)) return fail(`no rollout found for thread id ${m.params.threadId}`)+ threads.set(m.params.threadId, { turns: 0, resumed: true })+ return reply({ thread: { id: m.params.threadId } })+ }+ case 'thread/unsubscribe':+ threads.delete(m.params.threadId)+ return reply({ status: 'unsubscribed' })+ case 'thread/delete': {+ const f = find(m.params.threadId)+ if (!f) return fail(`no rollout found for thread id ${m.params.threadId}`)+ rmSync(join(day, f))+ return reply({})+ }+ case 'turn/interrupt': {+ const t = threads.get(m.params.threadId)+ if (t?.running) {+ clearTimeout(t.running.timer)+ t.running.end('interrupted')+ }+ return reply({})+ }+ case 'turn/start': {+ const threadId = m.params.threadId+ const t = threads.get(threadId)+ if (!t) return fail(`thread not loaded: ${threadId}`)+ const turnId = randomUUID()+ t.turns+++ reply({ turn: { id: turnId, items: [], status: 'inProgress' } })+ const text = m.params.input.map((i) => i.text ?? '').join('\n')+ const words = `pid=${process.pid} thread=${threadId} turn=${t.turns} resumed=${t.resumed}`+ const say = (method, params) => out({ method, params: { threadId, turnId, ...params } })+ say('turn/started', { turn: { id: turnId, status: 'inProgress' } })+ const end = (status) => {+ t.running = undefined+ out({ method: 'turn/completed', params: { threadId, turn: { id: turnId, status, items: [], error: null } } })+ }+ const answer = () => {+ say('thread/tokenUsage/updated', { tokenUsage: { total: { inputTokens: 100 * t.turns, cachedInputTokens: 50 * t.turns, outputTokens: 5 * t.turns }, last: { inputTokens: 100, cachedInputTokens: 50, outputTokens: 5 } } })+ say('item/agentMessage/delta', { itemId: 'm1', delta: words.slice(0, 6) })+ say('item/agentMessage/delta', { itemId: 'm1', delta: words.slice(6) })+ say('item/completed', { item: { type: 'agentMessage', id: 'm1', text: words } })+ end('completed')+ }+ t.running = { end, timer: setTimeout(answer, /demore/.test(text) ? 5000 : 10) }+ return+ }+ default:+ if (m.id !== undefined) fail(`unknown method ${m.method}`, -32601)+ }+ })+}diff --git a/test/governance.test.ts b/test/governance.test.tsindex f58b903..fdaf008 100644--- a/test/governance.test.ts+++ b/test/governance.test.ts@@ -25,7 +25,7 @@ const ready = { installed: true, loggedIn: true }type Plan = { tool: string; args: Record<string, unknown> } | null// A "model" that, on each turn, lists its tools and makes at most one call.-function scripted(plan: (turn: Turn, tools: string[]) => Plan, seen: { turns: Turn[]; tools: string[][]; results: unknown[] }): Engine {+function scripted(plan: (turn: Turn, tools: string[]) => Plan, seen: { turns: Turn[]; tools: string[][]; results: unknown[]; alwaysLoad: string[][] }): Engine {return {id: 'claude',async *run(turn) {@@ -34,8 +34,10 @@ function scripted(plan: (turn: Turn, tools: string[]) => Plan, seen: { turns: Tuif (turn.mcpUrl) {const client = new Client({ name: 'scripted', version: '0' })await client.connect(new StreamableHTTPClientTransport(new URL(turn.mcpUrl)))- const tools = (await client.listTools()).tools.map((t) => t.name)+ const listed = (await client.listTools()).tools+ const tools = listed.map((t) => t.name)seen.tools.push(tools)+ seen.alwaysLoad.push(listed.filter((t) => t._meta?.['anthropic/alwaysLoad'] === true).map((t) => t.name))const p = plan(turn, tools)if (p) {const r = await client.callTool({ name: p.tool, arguments: p.args })@@ -58,7 +60,7 @@ let connectors: ConnectorManagerlet events: CoreEvent[]let settings: Settingslet connectorId: string-let seen: { turns: Turn[]; tools: string[][]; results: unknown[] }+let seen: { turns: Turn[]; tools: string[][]; results: unknown[]; alwaysLoad: string[][] }let runnerRef = { current: undefined as Runner | undefined }const agent = (grant: GrantLevel): Agent => ({@@ -100,7 +102,7 @@ beforeEach(async () => {tasksFile = join(dir, 'tasks.json')db = new Db(join(dir, 'test.db'))events = []- seen = { turns: [], tools: [], results: [] }+ seen = { turns: [], tools: [], results: [], alwaysLoad: [] }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' }gateway = new Gateway()await gateway.start()@@ -140,12 +142,26 @@ describe('connectors', () => {})describe('grants', () => {+ it('lists the connector tools the agent called lately as loaded, the others behind tool search', async () => {+ db.saveAgent(agent('read'))+ let first = true+ const r = runner((_, tools) => (first ? ((first = false), { tool: tools.find((t) => t.endsWith('__list_tasks'))!, args: {} }) : null))+ await r.send('d1', 'quais tarefas?')+ await r.idle()+ expect(seen.alwaysLoad[0]).not.toContain('tarefas__list_tasks') // never called yet+ await r.send('d1', 'e agora?')+ await r.idle()+ expect(seen.alwaysLoad[1]).toContain('tarefas__list_tasks')+ })+it('read: the agent sees only read tools, and a forced call to another is refused without running', async () => {db.saveAgent(agent('read'))const r = runner((_, tools) => ({ tool: tools.find((t) => t.endsWith('__create_task')) ?? 'tarefas__create_task', args: { title: 'invasora' } }))await r.send('d1', 'oi')await r.idle()expect(seen.tools[0]).toEqual(['ask_user', 'pedir_acesso', 'propor_agente', 'propor_time', 'propor_ajuste', 'propor_rotina', 'propor_canal', 'agendar_rotina', 'cancelar_rotina', 'tarefas__list_tasks']) // it can ask for more, not take it+ // Claude Code keeps the app's own tools in the prompt; the connector's wait behind tool search.+ expect(seen.alwaysLoad[0]).toEqual(seen.tools[0]!.filter((t) => !t.startsWith('tarefas__')))expect(seen.results[0]).toMatchObject({ isError: true })expect(textOf(seen.results[0])).toContain('não permitida')expect(tasks().some((t) => t.title === 'invasora')).toBe(false)diff --git a/test/kept-session.test.ts b/test/kept-session.test.tsindex db6dc7c..119fa7a 100644--- a/test/kept-session.test.ts+++ b/test/kept-session.test.ts@@ -45,7 +45,17 @@ describe('Sessions', () => {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'] })+ expect(next).toEqual({ id: first.id, token: first.token, resume: true, send: ['m3', 'm4'], live: false })+ })++ it('goes on when only the live context changed, and sends it again only then', () => {+ const s = store()+ const p = s.begin('k', { config: cfg, shown: msgs('m1'), live: 'memórias: A' })!+ s.end('k', p, { ok: true, config: cfg, shown: msgs('m1'), live: 'memórias: A', reply: 'r1', context: 1_000 })+ expect(s.begin('k', { config: cfg, shown: [...msgs('m1'), { id: 'r1', block: 'x' }, ...msgs('m2')], live: 'memórias: A' })).toMatchObject({ id: p.id, resume: true, live: false })+ s.end('k', p, { ok: true, config: cfg, shown: msgs('m1', 'm2'), live: 'memórias: A', reply: 'r2', context: 1_000 })+ expect(s.begin('k', { config: cfg, shown: [...msgs('m1'), { id: 'r1', block: 'x' }, ...msgs('m2'), { id: 'r2', block: 'x' }, ...msgs('m3')], live: 'memórias: A, B' })).toMatchObject({ id: p.id, resume: true, send: ['m3'], live: true })+ expect(forgot).toEqual([])})it('goes on after older messages leave the window', () => {diff --git a/test/mac.test.ts b/test/mac.test.tsindex 34c6f0f..491832f 100644--- a/test/mac.test.ts+++ b/test/mac.test.ts@@ -4,7 +4,7 @@ import { homedir, tmpdir } from 'node:os'import { join } from 'node:path'import { afterEach, beforeEach, describe, expect, it } from 'vitest'import type { Agent, Conversation } from '../src/shared/types'-import { systemPrompt } from '../src/core/context'+import { liveContext, systemPrompt } from '../src/core/context'import { artifactKind, Computers, computerTools, linuxTools, stepFor } from '../src/core/computer'import { Db } from '../src/core/db'import { loginEnv, MacComputer, macPath } from '../src/core/mac'@@ -163,7 +163,7 @@ describe('an agent whose computer is this Mac', () => {if (win) expect(prompt).toMatch(/Git Bash|cmd\.exe/)expect(prompt).toContain(`Eles começam em ${work} (sua pasta de trabalho)`)expect(prompt).not.toContain('A pasta de trabalho é /work')- const off = systemPrompt({ agent: me, settings: { workspaceName: 'Edu', context: '' }, conversation: conv, peers: [], offline: ['Linear'] })+ const off = liveContext({ settings: { workspaceName: 'Edu', context: '' }, offline: ['Linear'] })expect(off).toContain('Você tem acesso a Linear, mas ele está desconectado agora')})})diff --git a/test/memory-search.test.ts b/test/memory-search.test.tsindex b3f2d48..fd0a04b 100644--- a/test/memory-search.test.ts+++ b/test/memory-search.test.ts@@ -81,8 +81,8 @@ describe('buscar_memorias', () => {db.saveMemory(mem('z', 'O cupom da campanha é ZEBRA', 5))await runner.send('d1', 'qual o cupom?')await runner.idle()- expect(turns[0]!.system).toContain('ZEBRA')- expect(turns[0]!.system).not.toContain('buscar_memorias')+ expect(turns[0]!.prompt).toContain('ZEBRA')+ expect(turns[0]!.prompt).not.toContain('buscar_memorias')expect(JSON.stringify(results[0])).not.toContain('ZEBRA') // no such tool})@@ -91,7 +91,7 @@ describe('buscar_memorias', () => {for (let i = 0; i < 60; i++) db.saveMemory(filler(i))await runner.send('d1', 'qual o cupom?')await runner.idle()- const system = turns[0]!.system+ const system = turns[0]!.promptexpect(system).not.toContain('ZEBRA')expect(system).toContain('procure com buscar_memorias')expect(JSON.stringify(results[0])).toContain('ZEBRA')diff --git a/test/memory.test.ts b/test/memory.test.tsindex 61abfce..16c09ce 100644--- a/test/memory.test.ts+++ b/test/memory.test.ts@@ -24,9 +24,9 @@ let turns: Turn[]let memory: Memorieslet runner: Runner-function setup(): void {- const base = fakeEngine('claude', { delayMs: 1 })- const claude: Engine = { id: 'claude', run: (t) => (turns.push(t), base.run(t)) }+function setup(sessions = false): void {+ const base = fakeEngine('claude', { delayMs: 1, sessions })+ const claude: Engine = { ...base, run: (t) => (turns.push(t), base.run(t)) }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') }const emit = (_: CoreEvent): void => {}const workDir = mkdtempSync(join(tmpdir(), 'ad-work-'))@@ -196,11 +196,34 @@ describe('lembrar (long term)', () => {await runner.send('c1', '@theo oi')await settle()- const system = agentTurns('theo')[0]!.system+ const system = agentTurns('theo')[0]!.promptexpect(system).toContain('Sobre Edu (todos os agentes veem):')expect(system).toContain('eu prefiro PR pequeno')})+ it('a new memory goes on the kept session with only the new context, instead of starting over', async () => {+ setup(true)+ await runner.send('c1', '@theo oi')+ await settle()+ const before = agentTurns('theo')+ expect(before[0]!.session).toMatchObject({ resume: false })+ expect(before[0]!.prompt).not.toContain('PR pequeno')++ db.saveMemory({ id: 'mem1', scope: 'me', text: 'eu prefiro PR pequeno', state: 'active', origin: 'me', messageIds: [], createdAt: clock, confirmedAt: clock })+ await runner.send('c1', '@theo e agora?')+ await settle()+ const [first, second] = agentTurns('theo')+ expect(second!.system).toBe(first!.system) // the system prompt holds: the session and its cache go on+ expect(second!.session).toEqual({ id: first!.session!.id, resume: true, keep: true })+ expect(second!.blocks![0]).toMatch(/^# Contexto de agora/)+ expect(second!.blocks![0]).toContain('eu prefiro PR pequeno')+ expect(second!.blocks!.at(-1)).toContain('e agora?')++ await runner.send('c1', '@theo e mais?')+ await settle()+ expect(agentTurns('theo')[2]!.blocks!.some((b) => b.includes('# Contexto de agora'))).toBe(false) // unchanged: not again+ })+it('with "pede aprovação" nothing reaches a prompt until I accept it', async () => {db.saveAgent(agent('a1', 'lia', { memory: 'approve' }))await runner.send('d1', 'lembra que eu prefiro PR pequeno')@@ -210,12 +233,12 @@ describe('lembrar (long term)', () => {await runner.send('c1', '@theo oi')await settle()- expect(agentTurns('theo')[0]!.system).not.toContain('PR pequeno')+ expect(agentTurns('theo')[0]!.prompt).not.toContain('PR pequeno')memory.decide(pending!.id, true)await runner.send('c1', '@theo e agora?')await settle()- expect(agentTurns('theo')[1]!.system).toContain('PR pequeno')+ expect(agentTurns('theo')[1]!.prompt).toContain('PR pequeno')})it('an agent set to "só lê" does not get the tool', async () => {@@ -284,6 +307,6 @@ describe('extraction', () => {memory.forget(db.memories()[0]!.id)await runner.send('c1', '@theo oi')await settle()- expect(agentTurns('theo')[0]!.system).not.toContain('PR pequeno')+ expect(agentTurns('theo')[0]!.prompt).not.toContain('PR pequeno')})})diff --git a/test/message-history.test.ts b/test/message-history.test.tsnew file mode 100644index 0000000..5fc0eb1--- /dev/null+++ b/test/message-history.test.ts@@ -0,0 +1,75 @@+import { mkdtempSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { beforeEach, describe, expect, it } from 'vitest'+import type { Agent, Author, Message } from '../src/shared/types'+import { Db } from '../src/core/db'++const agent = (id: string, handle: string): Agent => ({+ id, name: handle, handle, role: '', color: 'teal', instructions: '', modelId: 'sonnet', effort: 'low',+ limit: 1_000_000, used: 0, grants: {}, memory: 'auto', computer: false, archived: false+})++let db: Db+let clock: number+const say = (conversationId: string, text: string, author: Author = { kind: 'person', id: 'p1' }, threadId?: string): Message => {+ const m: Message = { id: `m${clock}`, conversationId, author, text, at: clock++, ...(threadId ? { threadId } : {}) }+ db.saveMessage(m)+ return m+}+const ids = (list: Message[]): string[] => list.map((m) => m.text)++beforeEach(() => {+ db = new Db(join(mkdtempSync(join(tmpdir(), 'ad-history-')), 'test.db'))+ clock = 1_000+ db.saveAgent(agent('a1', 'lia'))+ db.createConversation({ id: 'c1', kind: 'channel', name: 'geral', members: ['a1'], threads: true })+ db.createConversation({ id: 'c2', kind: 'channel', name: 'curto', members: ['a1'] })+})++describe('the messages the window opens with', () => {+ it("brings each conversation's latest, with their threads, and says from when each is whole", () => {+ const old = Array.from({ length: 6 }, (_, i) => say('c1', `c1-${i}`))+ say('c1', 'reply to c1-5', { kind: 'agent', id: 'a1' }, old[5]!.id)+ say('c2', 'c2-0')+ const { messages, since } = db.openingMessages(3)+ expect(ids(messages.filter((m) => m.conversationId === 'c1'))).toEqual(['c1-3', 'c1-4', 'c1-5', 'reply to c1-5'])+ expect(ids(messages.filter((m) => m.conversationId === 'c2'))).toEqual(['c2-0'])+ expect(since).toEqual({ c1: old[3]!.at }) // c2 came whole+ })++ it('keeps a thread still going, wherever it started, and every routine run with its reply', () => {+ const root = say('c1', 'an old question')+ db.saveRoutine({ id: 'r1', name: 'Resumo', agentId: 'a1', conversationId: 'c1', prompt: 'resuma', schedule: { days: [1], time: '09:00' }, enabled: true, createdAt: 0 })+ say('c1', 'resuma', { kind: 'routine', id: 'r1' })+ say('c1', 'the summary', { kind: 'agent', id: 'a1' })+ for (let i = 0; i < 5; i++) say('c1', `later-${i}`)+ say('c1', 'still answering', { kind: 'agent', id: 'a1' }, root.id)+ const { messages } = db.openingMessages(2)+ expect(ids(messages)).toEqual(['an old question', 'resuma', 'the summary', 'later-3', 'later-4', 'still answering'])+ })+})++describe('older messages, as the scroll gets there', () => {+ it('come a page at a time, with their threads, until there are no more', () => {+ const all = Array.from({ length: 7 }, (_, i) => say('c1', `m-${i}`))+ say('c1', 'reply to m-1', { kind: 'agent', id: 'a1' }, all[1]!.id)+ const first = db.openingMessages(3)+ const page = db.messagesBefore('c1', first.since['c1']!, 3)+ expect(ids(page.messages)).toEqual(['m-1', 'm-2', 'm-3', 'reply to m-1']) // in time order: the reply came last+ expect(page.since).toBe(all[1]!.at)+ const last = db.messagesBefore('c1', page.since, 3)+ expect(ids(last.messages)).toEqual(['m-0'])+ expect(last.since).toBe(0) // all of it is here now+ })++ it('go back to a message to show, however far', () => {+ const all = Array.from({ length: 10 }, (_, i) => say('c1', `m-${i}`))+ const { since } = db.openingMessages(2)+ const back = db.messagesBefore('c1', since['c1']!, 2, all[3]!.at)+ expect(ids(back.messages)).toEqual(['m-3', 'm-4', 'm-5', 'm-6', 'm-7'])+ expect(back.since).toBe(all[3]!.at)+ // Already here: nothing comes, and it stays whole from where it was.+ expect(db.messagesBefore('c1', since['c1']!, 2, all[9]!.at)).toEqual({ messages: [], since: since['c1'] })+ })+})diff --git a/test/queue-priority.test.ts b/test/queue-priority.test.tsnew file mode 100644index 0000000..cbb4691--- /dev/null+++ b/test/queue-priority.test.ts@@ -0,0 +1,60 @@+import { mkdtempSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { beforeEach, describe, expect, it } from 'vitest'+import type { Agent, EngineId, Routine, Settings } from '../src/shared/types'+import { Db } from '../src/core/db'+import { fakeEngine } from '../src/core/engines/fake'+import type { Engine, Turn } from '../src/core/engines/types'+import { Runner } from '../src/core/runs'++const ready = { installed: true, loggedIn: true }+const agent = (id: string, handle: string): Agent => ({ 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 })++describe('the queue', () => {+ let db: Db+ let started: Turn[]+ let release: () => void+ let runner: Runner++ beforeEach(() => {+ db = new Db(join(mkdtempSync(join(tmpdir(), 'qp-db-')), 'test.db'))+ started = []+ let open!: () => void+ const gate = new Promise<void>((r) => (open = r))+ release = open+ const base = fakeEngine('claude', { delayMs: 1 })+ // Routine turns hold until released; everything else answers right away.+ const claude: Engine = {+ ...base,+ async *run(t) {+ started.push(t)+ if (t.prompt.includes('rotina lenta')) await gate+ yield* base.run(t)+ }+ }+ const engines = { claude, codex: fakeEngine('codex'), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor'), grok: fakeEngine('grok') } as Record<EngineId, Engine>+ const settings: 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' }+ runner = new Runner({ db, engines, settings: async () => settings, emit: () => {}, workDir: mkdtempSync(join(tmpdir(), 'qp-work-')) })+ for (let i = 0; i < 6; i++) {+ db.saveAgent(agent(`r${i}`, `rot${i}`))+ db.createConversation({ id: `d-r${i}`, kind: 'dm', name: `r${i}`, members: [`r${i}`] })+ }+ db.saveAgent(agent('a1', 'lia'))+ db.createConversation({ id: 'd1', kind: 'dm', name: 'a1', members: ['a1'] })+ })++ const routine = (i: number): Routine => ({ id: `rt${i}`, name: `R${i}`, agentId: `r${i}`, conversationId: `d-r${i}`, prompt: 'rotina lenta', schedule: { days: [1], time: '09:00' }, enabled: true, createdAt: 1 })++ it("doesn't keep a reply to the person waiting behind routines that fill every slot", async () => {+ const runs = [0, 1, 2, 3, 4, 5].map((i) => runner.runRoutine(routine(i), { scheduledAt: 1, late: false }))+ await expect.poll(() => started.length).toBe(4) // the usual limit: two routines wait+ await runner.send('d1', 'oi, tá aí?')+ await expect.poll(() => db.messages().find((m) => m.author.kind === 'agent' && m.author.id === 'a1')?.run?.status).toBe('done')+ expect(started.filter((t) => t.prompt.includes('rotina lenta'))).toHaveLength(4) // the waiting routines still wait+ release()+ await Promise.all(runs)+ await runner.idle()+ expect(started.filter((t) => t.prompt.includes('rotina lenta'))).toHaveLength(6)+ })+})diff --git a/test/skills.test.ts b/test/skills.test.tsindex 48c7ddd..9c0d700 100644--- a/test/skills.test.ts+++ b/test/skills.test.ts@@ -102,8 +102,8 @@ describe('in a reply', () => {db.createConversation({ id: 'd1', kind: 'dm', name: 'a1', members: ['a1'] })await r.send('d1', 'roda os testes')await r.idle()- expect(turns[0]!.system).toContain('## Suas skills')- expect(turns[0]!.system).toContain('- testes-do-core: Ao rodar ou consertar testes do Core')+ expect(turns[0]!.prompt).toContain('## Suas skills')+ expect(turns[0]!.prompt).toContain('- testes-do-core: Ao rodar ou consertar testes do Core')expect(replies[0]).toContain('swift test --package-path Core')expect(replies[1]).toContain('Ela só vale depois que o usuário aprovar')const steps = db.messages().find((m) => m.author.kind === 'agent')!.run!.steps.map((s) => `${s.label}: ${s.detail}`)diff --git a/test/store.test.ts b/test/store.test.tsnew file mode 100644index 0000000..c11a969--- /dev/null+++ b/test/store.test.ts@@ -0,0 +1,101 @@+// The window's store, driven as the core drives it: a snapshot, then events over the port.+import { beforeAll, describe, expect, it } from 'vitest'+import type { CoreEvent } from '../src/shared/rpc'+import type { Conversation, Message } from '../src/shared/types'++type Store = typeof import('../src/renderer/src/store')+let store: Store+let emit: (e: CoreEvent) => void+const asked: { method: string; params: unknown }[] = []++const conv = (id: string): Conversation => ({ id, kind: 'channel', name: id, members: [], threads: true }) as Conversation+const msg = (id: string, conversationId: string, at: number, extra: Partial<Message> = {}): Message => ({ id, conversationId, author: { kind: 'person', id: 'p1' }, text: id, at, ...extra })++// c1 opens with its last three messages (from t=10) and, from before that, a routine's run (t=2).+const opening = [msg('ask', 'c1', 2, { author: { kind: 'routine', id: 'r1' } }), msg('m10', 'c1', 10), msg('m11', 'c1', 11), msg('root', 'c1', 12), msg('r1', 'c1', 13, { threadId: 'root' }), msg('x1', 'c2', 5)]+const older = [msg('m8', 'c1', 8), msg('m9', 'c1', 9)]++beforeAll(async () => {+ let listener: ((e: unknown) => void) | null = null+ const port = {+ onmessage: null as ((m: { data: unknown }) => void) | null,+ postMessage(req: { id: number; method: string; params: unknown }) {+ asked.push({ method: req.method, params: req.params })+ const result =+ req.method === 'snapshot'+ ? { settings: { workspaceName: 'Edu', language: 'pt', engines: {} }, agents: [], conversations: [conv('c1'), conv('c2')], messages: opening, since: { c1: 10 }, connectors: [], approvals: [], memories: [], artifacts: [], computers: [], browsers: [], routines: [], skills: [], platform: 'mac', packaged: false, isolatedComputers: true, people: [], you: '' }+ : req.method === 'olderMessages'+ ? { messages: [...older, opening[0]], since: 0 }+ : undefined+ queueMicrotask(() => port.onmessage!({ data: { id: req.id, result } }))+ }+ }+ const win: Record<string, unknown> = {+ addEventListener: (_: string, l: (e: unknown) => void) => (listener = l),+ removeEventListener: () => {},+ tucano: { onNavigate: () => {}, viewing: () => {}, connect: () => queueMicrotask(() => listener!({ source: win, data: 'core:port', ports: [port] })) }+ }+ ;(globalThis as Record<string, unknown>).window = win+ store = await import('../src/renderer/src/store')+ await store.start()+ emit = (event) => port.onmessage!({ data: { event } })+})++describe("the window's messages", () => {+ it('come per conversation; the timeline starts where they are whole, the older run kept aside', () => {+ const s = store.getState()+ expect(store.messagesIn(s, 'c1').map((m) => m.id)).toEqual(['ask', 'm10', 'm11', 'root', 'r1'])+ expect(store.timelineOf(s, 'c1').map((m) => m.id)).toEqual(['m10', 'm11', 'root'])+ expect(store.messageById(s, 'ask')?.author.kind).toBe('routine')+ expect(store.repliesOf(s, 'c1', 'root').map((m) => m.id)).toEqual(['r1'])+ expect(s.history).toEqual({ c1: 10 })+ })++ it('stream without waking the store: only the text of that message grows', () => {+ emit({ type: 'message', message: msg('reply', 'c1', 14, { author: { kind: 'agent', id: 'a1' }, text: '', threadId: 'root', run: { status: 'working', steps: [] } }) })+ const before = store.getState()+ expect(store.isWorking(before, 'c1')).toBe(true)+ expect(store.workingIds(before, 'c1', 'root')).toEqual(['reply'])+ expect(store.workingIds(before, 'c1')).toEqual([])+ emit({ type: 'delta', id: 'reply', text: 'Olá, ' })+ emit({ type: 'delta', id: 'reply', text: 'Edu' })+ expect(store.getState()).toBe(before)+ expect(store.liveText('reply')).toBe('Olá, Edu')+ // The full message carries the text so far: the streamed copy goes.+ emit({ type: 'message', message: msg('reply', 'c1', 14, { author: { kind: 'agent', id: 'a1' }, text: 'Olá, Edu!', threadId: 'root', run: { status: 'done', steps: [] } }) })+ expect(store.liveText('reply')).toBeUndefined()+ expect(store.messageById(store.getState(), 'reply')?.text).toBe('Olá, Edu!')+ expect(store.workingAgents(store.getState()).size).toBe(0)+ })++ it("keeps a thread's replies the same array while only another thread changes", () => {+ emit({ type: 'message', message: msg('other', 'c1', 15) })+ const replies = store.repliesOf(store.getState(), 'c1', 'root')+ emit({ type: 'message', message: msg('r-other', 'c1', 16, { threadId: 'other' }) })+ expect(store.repliesOf(store.getState(), 'c1', 'root')).toBe(replies)+ expect(store.repliesOf(store.getState(), 'c1', 'other').map((m) => m.id)).toEqual(['r-other'])+ })++ it("doesn't wake the store for a browser's frame", () => {+ const before = store.getState()+ emit({ type: 'browser_frame', agentId: 'a1', frame: 'data:image/jpeg;base64,AAAA' })+ expect(store.getState()).toBe(before)+ })++ it('load older ones in time order, once, and then the timeline is whole', async () => {+ await Promise.all([store.loadOlder('c1'), store.loadOlder('c1')])+ expect(asked.filter((a) => a.method === 'olderMessages')).toEqual([{ method: 'olderMessages', params: { conversationId: 'c1', before: 10 } }])+ const s = store.getState()+ expect(store.messagesIn(s, 'c1').map((m) => m.id)).toEqual(['ask', 'm8', 'm9', 'm10', 'm11', 'root', 'r1', 'reply', 'other', 'r-other'])+ expect(store.timelineOf(s, 'c1').map((m) => m.id)).toEqual(['ask', 'm8', 'm9', 'm10', 'm11', 'root', 'other'])+ expect(s.history).toEqual({})+ await store.loadOlder('c1') // nothing more to ask for+ expect(asked.filter((a) => a.method === 'olderMessages')).toHaveLength(1)+ })++ it('drop a conversation whole when it goes', () => {+ emit({ type: 'conversation_removed', id: 'c1' })+ expect(store.messagesIn(store.getState(), 'c1')).toEqual([])+ expect(store.messagesIn(store.getState(), 'c2').map((m) => m.id)).toEqual(['x1'])+ })+})diff --git a/test/team-round2.test.ts b/test/team-round2.test.tsindex f942a62..039c1b1 100644--- a/test/team-round2.test.ts+++ b/test/team-round2.test.ts@@ -72,7 +72,7 @@ describe('1. a memory learned in a DM', () => {async *run(t: Turn) {if (t.system === memorySystem()) memoryPrompts.push(t.prompt)else if (t.system !== routerSystem() && t.system !== handoffSystem()) {- systems.push(t.system)+ systems.push(`${t.system}\n${t.prompt}`) // memories come in the live context, at the top of the promptif (t.mcpUrl && /SEGREDO/.test(t.prompt)) await callTool(t.mcpUrl, 'lembrar', { texto: 'Ana está em tratamento SEGREDO-MÉDICO', sobre: 'usuario' })}yield* base.run(t)diff --git a/test/team-round3.test.ts b/test/team-round3.test.tsindex 0d04bda..bbe001d 100644--- a/test/team-round3.test.ts+++ b/test/team-round3.test.ts@@ -145,6 +145,7 @@ describe('G. every event reaches only who may see what it is about', () => {memory_removed: { event: { type: 'memory_removed', id: 'k1', for: ana.id }, is: 'hidden' },computer: { event: { type: 'computer', computer: { agentId: 'a1', state: 'running', services: [{ name: 'segredo', port: 3000, conversationId: 'dm-ana' }] } as unknown as ComputerInfo }, is: 'own' },browser: { event: { type: 'browser', view: { agentId: 'a1', url: 'https://segredo', title: 'segredo', shown: true, log: [], at: 1, conversationId: 'dm-ana' } as BrowserView }, is: 'own' },+ browser_frame: { event: { type: 'browser_frame', agentId: 'a1', frame: 'data:segredo', conversationId: 'dm-ana' }, is: 'hidden' },artifact: { event: { type: 'artifact', artifact: { id: 'f1', conversationId: 'dm-ana', messageId: 'm-dm', agentId: 'a1', name: 'segredo.txt', mime: 'text/plain', size: 1, at: 1 } as unknown as Artifact }, is: 'hidden' },routine: { event: { type: 'routine', routine }, is: 'hidden' },routine_removed: { event: { type: 'routine_removed', id: 'r1', for: ana.id }, is: 'hidden' },diff --git a/test/team-stress.test.ts b/test/team-stress.test.tsindex 23d437a..12e6e7e 100644--- a/test/team-stress.test.ts+++ b/test/team-stress.test.ts@@ -704,7 +704,8 @@ describe('what the owner alone sees (23, 24)', () => {expect(pages).toContain("...(owner ? [['integracoes', L('Celular', 'Phone')]] : [])")expect(pages).toContain('const tabs = SETTINGS_TABS(team, admin, owner)')const sidebar = readFileSync(join(import.meta.dirname, '..', 'src', 'renderer', 'src', 'components', 'Sidebar.tsx'), 'utf8')- expect(sidebar).toMatch(/\{amOwner\(s\) && s\.settings\.onboarding\?\.done && !s\.settings\.onboarding\.checklistHidden && <GettingStarted \/>\}/)+ expect(sidebar).toMatch(/const owner = amOwner\(/)+ expect(sidebar).toMatch(/\{owner && settings\.onboarding\?\.done && !settings\.onboarding\.checklistHidden && <GettingStarted \/>\}/)})it('a locked channel routine says "Me avise" is all a member changes there', () => {diff --git a/test/threads.test.ts b/test/threads.test.tsindex ea0a89b..91655b0 100644--- a/test/threads.test.ts+++ b/test/threads.test.ts@@ -408,10 +408,10 @@ describe('what a thread message sets off stays in the thread', () => {describe('the database', () => {it('an existing database gains thread_id, thread_summary and threads, and round-trips them', () => {const file = join(mkdtempSync(join(tmpdir(), 'ad-db-')), 'old.db')- // A database from before threads: the schema five migrations back (unread and people came after), with a message in it.+ // A database from before threads: the schema six migrations back (unread, people and the indexes came after), with a message in it.const raw = new DatabaseSync(file)- for (const m of MIGRATIONS.slice(0, MIGRATIONS.length - 5)) raw.exec(m)- raw.exec(`PRAGMA user_version = ${MIGRATIONS.length - 5};`)+ for (const m of MIGRATIONS.slice(0, MIGRATIONS.length - 6)) raw.exec(m)+ raw.exec(`PRAGMA user_version = ${MIGRATIONS.length - 6};`)raw.exec("INSERT INTO conversations (id, kind, name, created_at) VALUES ('c1', 'channel', 'geral', 1)")raw.exec("INSERT INTO messages (id, conversation_id, author_kind, text, at) VALUES ('old', 'c1', 'me', 'antes das threads', 1)")raw.close()diff --git a/test/tuca-help.test.ts b/test/tuca-help.test.tsindex 675596d..2614e52 100644--- a/test/tuca-help.test.ts+++ b/test/tuca-help.test.ts@@ -202,7 +202,7 @@ describe('the Tuca helping, in a conversation', () => {await runner.idle()expect(turns[0]!.system).toContain('## O guia do Tucano')expect(turns[0]!.system).toContain('(#abrir/conectores)')- expect(turns[0]!.system).toContain('Lia (@lia)')+ expect(turns[0]!.prompt).toContain('Lia (@lia)')const texts = results.map((r) => (r as { content: { text: string }[] }).content[0]!.text)if (GUIDE.length) expect(texts[0]).toContain(`# ${GUIDE[0]!.title}`)expect(texts[1]).toContain('Linear: pede login')diff --git a/test/tuca.test.ts b/test/tuca.test.tsindex f182cc4..870e516 100644--- a/test/tuca.test.ts+++ b/test/tuca.test.ts@@ -48,7 +48,7 @@ describe('the Tuca in a conversation', () => {await gateway.start()systems.length = 0const base = fakeEngine('claude', { delayMs: 1 })- const claude: Engine = { id: 'claude', run: (t) => (systems.push(t.system), base.run(t)) }+ const claude: Engine = { id: 'claude', run: (t) => (systems.push(`${t.system}\n\n${t.prompt}`), base.run(t)) }const engines: Record<EngineId, Engine> = { claude, codex: fakeEngine('codex'), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor'), grok: fakeEngine('grok') }runner = new Runner({ db, engines, settings: async () => settings, emit: () => {}, workDir: mkdtempSync(join(tmpdir(), 'ad-work-')), gateway, connectors: { list: () => [linear], call: async () => ({ content: [] }) } })})diff --git a/test/warm-start.test.ts b/test/warm-start.test.tsindex a0fb96b..edfccee 100644--- a/test/warm-start.test.ts+++ b/test/warm-start.test.ts@@ -58,6 +58,26 @@ describe('while the person types', () => {expect(warmed).toEqual(['warm haiku'])})+ it('in a channel, also starts the session of whoever answered last there', async () => {+ const r = runner()+ await r.send('c1', '@theo oi')+ await r.idle()+ warmed.length = 0+ await r.typing('c1')+ expect(warmed).toEqual([`rewarm ${turns[0]!.session!.id}`, 'warm haiku'])+ })++ it('opened without typing, starts the kept sessions but not the router', async () => {+ const r = runner()+ await r.typing('c1', undefined, true)+ expect(warmed).toEqual([])+ await r.send('c1', '@theo oi')+ await r.idle()+ warmed.length = 0+ await r.typing('c1', undefined, true)+ expect(warmed).toEqual([`rewarm ${turns[0]!.session!.id}`])+ })+it('starts nothing for a new thread, when paused, or with the router’s harness signed out', async () => {const r = runner()await r.typing('c2') // answers in threads: a new message opens a new one@@ -102,7 +122,7 @@ describe('a Claude Code process started ahead', () => {const engine = claudeEngine(() => bin, async () => ({ env: {} }))const turn = (): Turn => ({ ...routerTurn('haiku', dir), prompt: 'quem responde?', signal: new AbortController().signal })engine.warm!(routerTurn('haiku', dir))- await wait(1500)+ await wait(2500) // a busy machine (the whole suite at once) takes over a second to boot nodeconst warm = await reply(engine.run(turn()))expect(upOf(warm)).toBeGreaterThanOrEqual(1000)const cold = await reply(engine.run(turn())) // the spare is used up: a new process, as before@@ -117,7 +137,7 @@ describe('a Claude Code process started ahead', () => {await reply(engine.run(turn(false)))engine.dispose!() // as if it had closed after its five minutesengine.rewarm!('s1')- await wait(1500)+ await wait(2500) // a busy machine (the whole suite at once) takes over a second to boot nodeconst next = await reply(engine.run(turn(true)))expect(next).toMatch(/turn=1 resume=true/)expect(upOf(next)).toBeGreaterThanOrEqual(1000)diff --git a/test/wiki.test.ts b/test/wiki.test.tsindex 4473413..360652f 100644--- a/test/wiki.test.ts+++ b/test/wiki.test.ts@@ -1,4 +1,4 @@-import { existsSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'import { describe, expect, it } from 'vitest'@@ -104,3 +104,72 @@ describe('the agents and the wiki', () => {expect(fileOf('a/b: c?')).toBe('a-b- c-.md')})})++describe('reading the folder behind the window', () => {+ it('a start indexes the folder without blocking, then watches it', async () => {+ const root = mkdtempSync(join(tmpdir(), 'tucano-wiki-'))+ const dir = join(root, 'vault')+ mkdirSync(join(dir, '.obsidian'), { recursive: true })+ mkdirSync(join(dir, 'Clientes'))+ for (let i = 0; i < 40; i++) writeFileSync(join(dir, 'Clientes', `Cliente ${i}.md`), `Cliente número ${i}, ligado a [[Cliente ${(i + 1) % 40}]].\n`)+ let changes = 0+ const w = new Wiki({ dir, indexPath: join(root, 'wiki.db'), onChange: () => changes++ })+ w.init(true, true)+ expect(w.list()).toEqual([]) // nothing read yet: init returned at once+ await w.loaded+ expect(w.list()).toHaveLength(40)+ expect(w.page('Cliente 3')?.kind).toBe('Clientes')+ expect(changes).toBe(1) // the screen hears that the pages came in+ w.close()++ // Opened again with nothing changed: no change to tell.+ const again = new Wiki({ dir, indexPath: join(root, 'wiki.db'), onChange: () => changes++ })+ again.init(false, true)+ await again.loaded+ expect(again.list()).toHaveLength(40)+ expect(changes).toBe(1)+ again.close()+ })++ it('what the app wrote after the folder was listed is not taken for a change from outside', () => {+ const w = fresh()+ w.save({ title: 'Antiga', body: 'v1', ...by })+ const listed: [string, number][] = [['Antiga.md', 1]] // as the folder was a moment ago+ w.save({ title: 'Antiga', body: 'v2', ...by, expectedHash: w.page('Antiga')!.hash })+ w.save({ title: 'Nova', body: 'escrita agora', ...by })+ const inner = w as unknown as { applyFiles: (found: [string, number][], late: boolean, logs: string[]) => boolean; removeMissing: (found: [string, number][], gone: Set<string>, late: boolean, logs: string[]) => boolean }+ expect(inner.applyFiles(listed, true, [])).toBe(false)+ expect(inner.removeMissing(listed, new Set(), true, [])).toBe(false)+ expect(w.page('Nova')?.body).toContain('escrita agora') // not dropped as gone from the folder+ expect(w.history('Antiga').every((v) => v.by !== 'outside')).toBe(true)+ })++ it('a page deleted after the folder was listed leaves the index', () => {+ const w = fresh()+ w.save({ title: 'Some', body: 'logo some', ...by })+ const listed: [string, number][] = [['Some.md', 1]]+ rmSync(join(w.dir, 'pages', 'Some.md'))+ const inner = w as unknown as { applyFiles: (found: [string, number][], late: boolean, logs: string[], gone: Set<string>) => boolean; removeMissing: (found: [string, number][], gone: Set<string>, late: boolean, logs: string[]) => boolean }+ const gone = new Set<string>()+ const logs: string[] = []+ inner.applyFiles(listed, true, logs, gone)+ expect(inner.removeMissing(listed, gone, true, logs)).toBe(true)+ expect(w.page('Some')).toBeUndefined()+ expect(logs).toEqual(['Some saiu da pasta'])+ })++ it('the map and the log are read again only after something changed', () => {+ const w = fresh()+ w.save({ title: 'A', body: 'liga a [[B]]', ...by })+ const g1 = w.graph()+ expect(w.graph()).toBe(g1)+ const log1 = w.log()+ expect(w.log()).toBe(log1)+ w.save({ title: 'B', body: 'agora existe', ...by })+ const g2 = w.graph()+ expect(g2).not.toBe(g1)+ expect(g2.nodes.find((n) => n.title === 'B')?.missing).toBeUndefined()+ expect(w.log()).not.toBe(log1)+ expect(w.log()[0]).toContain('B')+ })+})