Skip to content

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

Keep each thread to itself, and let agents look the others up (#120)

Eduardo Machadocdda114bdd6a
diff --git a/src/core/context.ts b/src/core/context.ts
index a18cf95..efda704 100644
--- a/src/core/context.ts
+++ b/src/core/context.ts
@@ -3,6 +3,7 @@
// between turns, so everything the agent knows comes from here.
import { L, lang, locale } from '../shared/lang'
import { CODE_SPANS, describeSchedule, PROJECTS_DIR, type Agent, type AgentApp, type Conversation, type Memory, type Message, type Routine, type Settings, type Skill } from '../shared/types'
+import type { ToolDef } from './gateway'
import { osOf, shellCommand, systemName } from './platform'
export const HISTORY_LIMIT = 30
@@ -265,16 +266,34 @@ export const clock = (at: number): string => {
// with the same blocks and reads them from the cache. `task` (to continue after
// an approval, a routine…) goes last, with the time, since it may come later.
// `images`: the names of the images attached to each message (by id). `thread`: the message
-// that started the thread this reply is in (then `messages` is that thread, root first).
-type TranscriptOpts = { agent: Agent; conversation: Conversation; messages: Message[]; agents: Agent[]; me: string; task?: string; summary?: string; images?: Map<string, string[]>; thread?: Message }
+// that started the thread this reply is in (`messages` is then that thread, root first, and
+// `summary` the thread's own). `searchable`: the agent has buscar_threads and ler_thread.
+type TranscriptOpts = {
+ agent: Agent
+ conversation: Conversation
+ messages: Message[]
+ agents: Agent[]
+ me: string
+ task?: string
+ summary?: string
+ images?: Map<string, string[]>
+ thread?: Message
+ searchable?: boolean
+}
export function transcript(opts: TranscriptOpts): string[] {
return transcriptBlocks(opts).blocks
}
+// One line of text, cut at `max` characters.
+export const snip = (text: string, max: number): string => {
+ const t = text.replace(/\s+/g, ' ').trim()
+ return t.length > max ? `${t.slice(0, max - 1)}…` : t
+}
+
// 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 } = opts
+ const { agent, conversation, messages, agents, me, task, summary, images, thread, searchable } = opts
const name = (m: Message): string | null => {
if (m.author.kind === 'me') return me
if (m.author.kind === 'system') return null
@@ -309,12 +328,22 @@ export function transcriptBlocks(opts: TranscriptOpts): { blocks: string[]; bloc
: starter?.kind === 'routine'
? L(`por uma rotina de ${me}`, `by a routine of ${me}'s`)
: L('pelo app', 'by the app')
+ // A thread is a conversation of its own: the others reach it only when looked up.
+ const apart = searchable
+ ? L(
+ ` Ela é uma conversa à parte: você não vê as outras threads de ${where}. Se ${me} falar de outra conversa, ou de algo combinado antes que não está aqui nem nas memórias, procure com buscar_threads e leia com ler_thread.`,
+ ` It's a conversation of its own: you don't see the other threads of ${where}. If ${me} mentions another conversation, or something agreed before that isn't here or in the memories, look it up with buscar_threads and read it with ler_thread.`
+ )
+ : ''
const head = [
- summary?.trim() && `${L(`Resumo do que veio antes em ${where}`, `Summary of what came before in ${where}`)}:\n${summary.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()}`
+ : `${L(`Resumo do que veio antes em ${where}`, `Summary of what came before in ${where}`)}:\n${summary.trim()}`),
thread
? L(
- `Você está respondendo numa thread em ${where}, aberta ${by}. Abaixo, a mensagem que abriu a thread e as respostas dela, das mais antigas pras mais novas:`,
- `You're replying in a thread in ${where}, started ${by}. Below, the message that started the thread and its replies, oldest to newest:`
+ `Você está respondendo numa thread em ${where}, aberta ${by}.${apart} Abaixo, a mensagem que abriu a thread e as respostas dela, das mais antigas pras mais novas:`,
+ `You're replying in a thread in ${where}, started ${by}.${apart} Below, the message that started the thread and its replies, oldest to newest:`
)
: `${summary?.trim() ? L('Mensagens desde o resumo', 'Messages since the summary') : L(`Conversa em ${where}`, `Conversation in ${where}`)}, ${L('das mais antigas pras mais novas', 'oldest to newest')}:`
].filter((b): b is string => !!b)
@@ -323,6 +352,43 @@ export function transcriptBlocks(opts: TranscriptOpts): { blocks: string[]; bloc
return { blocks, blockOf }
}
+export const BUSCAR_THREADS: ToolDef = {
+ name: 'buscar_threads',
+ get description() {
+ return L(
+ 'Procura nas outras threads das conversas em que você está (canais e DMs), por palavras que estariam nelas. Devolve as que mais batem, com o id de cada uma pra ler inteira com ler_thread. Sem resultado, o assunto não foi tratado nas conversas recentes: não invente.',
+ "Searches the other threads of the conversations you're in (channels and DMs), by words that would be in them. Returns the best matches, each with its id to read in full with ler_thread. With no result, the subject wasn't covered in the recent conversations: don't make it up."
+ )
+ },
+ get inputSchema() {
+ return {
+ type: 'object' as const,
+ properties: {
+ busca: { type: 'string', description: L('Palavras-chave, ex.: "calendário rotinas PR".', 'Keywords, e.g. "calendar routines PR".') },
+ limite: { type: 'number', description: L('Quantas trazer, de 1 a 10. Padrão: 5.', 'How many to bring, 1 to 10. Default: 5.') }
+ },
+ required: ['busca']
+ }
+ }
+}
+
+export const LER_THREAD: ToolDef = {
+ name: 'ler_thread',
+ get description() {
+ return L(
+ 'Lê uma outra thread das conversas em que você está: a mensagem que a abriu, o resumo dela e as respostas, pelo id que buscar_threads devolve. Use quando o que foi dito lá importa pra sua resposta.',
+ "Reads another thread of the conversations you're in: the message that opened it, its summary and its replies, by the id buscar_threads returns. Use it when what was said there matters for your reply."
+ )
+ },
+ get inputSchema() {
+ return {
+ type: 'object' as const,
+ properties: { id: { type: 'string', description: L('O id da thread, como buscar_threads mostra.', 'The thread id, as buscar_threads shows it.') } },
+ required: ['id']
+ }
+ }
+}
+
// @handles in the text that belong to the given agents, in order of appearance. Handles inside
// code are quoted content, not a call (CODE_SPANS): a prompt shown in a fenced block, say.
export function mentioned(text: string, agents: Agent[]): Agent[] {
diff --git a/src/core/db.ts b/src/core/db.ts
index 4f7e615..5334482 100644
--- a/src/core/db.ts
+++ b/src/core/db.ts
@@ -1,5 +1,5 @@
import { DatabaseSync } from 'node:sqlite'
-import { CACHE_READ_WEIGHT, routineCap, type Agent, type AgentApp, type AgentColor, type Approval, type ApprovalState, type Artifact, type ArtifactKind, type Author, type Connector, type ConnectorAuth, type ConnectorTool, type Conversation, type Effort, type LentFolder, type Memory, type MemoryMode, type MemoryState, type Message, type Receipt, type Routine, type RoutineRun, type Run, type Settings, type Skill, type SkillVersion, type ToolClass, type Trigger } from '../shared/types'
+import { CACHE_READ_WEIGHT, routineCap, type Agent, type AgentApp, type AgentColor, type Approval, type ApprovalState, type Artifact, type ArtifactKind, type Author, type Connector, type ConnectorAuth, type ConnectorTool, type Conversation, type Effort, type LentFolder, type Memory, type MemoryMode, type MemoryState, type Message, type Receipt, type Routine, type RoutineRun, type Run, type Settings, type Skill, type SkillVersion, type ThreadSummary, type ToolClass, type Trigger } from '../shared/types'
// Each entry runs once, in order; PRAGMA user_version records how far we got.
const MIGRATIONS = [
@@ -250,6 +250,9 @@ const MIGRATIONS = [
`
ALTER TABLE messages ADD COLUMN thread_id TEXT;
CREATE INDEX messages_by_thread ON messages (conversation_id, thread_id, at);
+ `,
+ `
+ ALTER TABLE messages ADD COLUMN thread_summary TEXT;
`
]
@@ -484,7 +487,8 @@ export class Db {
at: Number(r['at']),
run: r['run'] ? (JSON.parse(str(r['run'])) as Run) : undefined,
routine: r['routine'] ? (JSON.parse(str(r['routine'])) as RoutineRun) : undefined,
- threadId: r['thread_id'] ? str(r['thread_id']) : undefined
+ threadId: r['thread_id'] ? str(r['thread_id']) : undefined,
+ ...(r['thread_summary'] ? { threadSummary: JSON.parse(str(r['thread_summary'])) as ThreadSummary } : {})
}
}
@@ -500,6 +504,31 @@ export class Db {
return rows.reverse().map((r) => this.toMessage(r))
}
+ // A thread's summary, on its first message; leave `until` out to keep it (a hand edit).
+ setThreadSummary(rootId: string, text: string, until?: number): void {
+ const kept = until ?? this.message(rootId)?.threadSummary?.until ?? 0
+ this.db.prepare('UPDATE messages SET thread_summary = ? WHERE id = ?').run(JSON.stringify({ text, until: kept, at: Date.now() } satisfies ThreadSummary), rootId)
+ }
+
+ // The messages that started a thread with replies in it.
+ threadRoots(conversationId: string): Set<string> {
+ const rows = this.db.prepare('SELECT DISTINCT thread_id FROM messages WHERE conversation_id = ? AND thread_id IS NOT NULL').all(conversationId) as Row[]
+ return new Set(rows.map((r) => str(r['thread_id'])))
+ }
+
+ // Threads quiet since `before`, active after `since`, with something said after their summary.
+ 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`
+ )
+ .all(before, since) as Row[]
+ return rows.map((r) => ({ id: str(r['id']), conversationId: str(r['conversation_id']), last: Number(r['last']) }))
+ }
+
// Oldest first.
messagesAfter(conversationId: string, at: number): Message[] {
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))
diff --git a/src/core/index.ts b/src/core/index.ts
index 2144a78..949a5a2 100644
--- a/src/core/index.ts
+++ b/src/core/index.ts
@@ -571,6 +571,8 @@ void ready.then(async () => {
for (const a of db.agents()) if (a.computer && !a.archived) void computers.refresh(a)
await runner.expireApprovals()
setInterval(() => void runner.expireApprovals(), 60_000).unref()
+ // A thread that went quiet gets its own summary, and the memories in it.
+ setInterval(() => void memory.sweep().catch((e: unknown) => console.error('[memory]', e)), 60_000).unref()
routines.start()
// Nothing here waits on the keychain: the first use after an update can be a
// macOS prompt that stays open until someone answers it.
@@ -979,6 +981,8 @@ const api: Api = {
purgeMemory: ({ id }) => memory.purge(id),
editSummary: ({ conversationId, text }) => memory.editSummary(conversationId, text),
summarizeNow: ({ conversationId }) => void memory.consolidate(conversationId, true),
+ editThreadSummary: ({ rootId, text }) => memory.editThreadSummary(rootId, text),
+ summarizeThreadNow: ({ rootId }) => void memory.consolidateThread(rootId, 'now'),
computerAction: ({ agentId, action }) => {
const agent = db.agent(agentId)
diff --git a/src/core/jev.ts b/src/core/jev.ts
index b6d164b..984e75c 100644
--- a/src/core/jev.ts
+++ b/src/core/jev.ts
@@ -5,6 +5,7 @@
import { randomUUID } from 'node:crypto'
import { L } from '../shared/lang'
import type { Agent, Connector, Message } from '../shared/types'
+import type { ThreadDigest } from './memory'
import { describeAgent, MAX_ROUTED, REPLY_JSON, routerPrompt } from './router'
export const JEV_MODEL = 'jev' // the routerModel value that picks it
@@ -44,6 +45,7 @@ export async function routeJev(opts: {
me: string
connectors?: Connector[]
thread?: Message
+ threads?: ThreadDigest[]
fetch?: Fetch
}): Promise<{ agents: Agent[]; reason: string; ms: number } | { error: string; ms: number }> {
const started = Date.now()
diff --git a/src/core/memory.ts b/src/core/memory.ts
index 2e8943e..c0bcc80 100644
--- a/src/core/memory.ts
+++ b/src/core/memory.ts
@@ -7,13 +7,19 @@ import { join } from 'node:path'
import { randomBytes } from 'node:crypto'
import { L } from '../shared/lang'
import type { CoreEvent } from '../shared/rpc'
-import { ENGINES, usable, modelInfo, splitForPrompt, SUMMARY_MAX_AFTER, SUMMARY_WINDOW, type Agent, type Conversation, type EngineId, type Memory, type MemoryScope, type Message, type Settings } from '../shared/types'
+import { ENGINES, usable, modelInfo, splitForPrompt, SUMMARY_MAX_AFTER, SUMMARY_WINDOW, type Agent, type Conversation, type EngineId, type Memory, type MemoryScope, type Message, type RunStatus, type Settings } from '../shared/types'
import type { Db } from './db'
import type { Engine } from './engines/types'
import type { ToolDef } from './gateway'
export const WINDOW = SUMMARY_WINDOW
export const MAX_AFTER = SUMMARY_MAX_AFTER
+// A thread is summarized (and its memories extracted) once it's quiet this long...
+export const THREAD_QUIET_MS = 10 * 60_000
+// ...with this many messages since its summary, at least: a question and its answer alone wait.
+export const THREAD_MIN = 3
+const THREAD_HORIZON_MS = 24 * 60 * 60_000 // threads quiet for longer were swept already (or predate this)
+const SWEEP_BATCH = 3
const MAX_MEMORY_CHARS = 500
export const BUSCAR_MEMORIAS: ToolDef = {
@@ -99,8 +105,9 @@ const JSON_SHAPE = '{"summary": "...", "memories": [{"op": "add", "text": "...",
type Op = { op: 'add'; text: string; evidence: number[] } | { op: 'update'; id: string; text: string; evidence: number[] } | { op: 'confirm'; id: string }
-export function consolidationPrompt(opts: { summary?: string; messages: Message[]; me: string; agents: Agent[]; memories: Memory[]; forgotten: Memory[] }): string {
- const { summary, messages, me, agents, memories, forgotten } = opts
+// `thread`: the stretch is a thread's, since its summary (not what leaves a conversation's window).
+export function consolidationPrompt(opts: { summary?: string; messages: Message[]; me: string; agents: Agent[]; memories: Memory[]; forgotten: Memory[]; thread?: boolean }): string {
+ const { summary, messages, me, agents, memories, forgotten, thread } = opts
const author = (m: Message): string =>
m.author.kind === 'me'
? me
@@ -112,9 +119,9 @@ export function consolidationPrompt(opts: { summary?: string; messages: Message[
L('Resumo atual:', 'Current summary:'),
summary?.trim() || L('(ainda não há)', '(none yet)'),
'',
- L('Trecho que vai sair da janela:', 'Stretch about to leave the window:'),
- // Thread replies are folded in too, marked, since the channel's window leaves them out.
- ...messages.map((m, i) => `(${i + 1}) [${author(m)}${m.threadId ? L(' · numa thread', ' · in a thread') : ''}] ${m.text.trim().slice(0, 4000)}`),
+ thread ? L('Mensagens da thread desde o resumo:', "The thread's messages since the summary:") : L('Trecho que vai sair da janela:', 'Stretch about to leave the window:'),
+ // In a conversation's stretch, thread replies are marked: each thread also has its own summary.
+ ...messages.map((m, i) => `(${i + 1}) [${author(m)}${!thread && m.threadId ? L(' · numa thread', ' · in a thread') : ''}] ${m.text.trim().slice(0, 4000)}`),
'',
L(`Memórias sobre ${me}:`, `Memories about ${me}:`),
...(memories.length ? memories.map((m) => `- [${m.id}] ${m.text}`) : [none]),
@@ -151,22 +158,89 @@ export function parseConsolidation(text: string): { summary: string; ops: Op[] }
return { summary: summary.trim(), ops }
}
-// A reply in a thread: the message that started it, then the replies before this one.
-// The root goes in however old it is; the replies are capped like the conversation's window.
-// What an agent reads before replying: the conversation's recent messages, threads included
-// (every answer goes in the thread of what it answers, so the threads are the conversation),
-// and the whole thread it replies in, however old. `until`: what the summary already covers.
-export function contextWindow(db: Pick<Db, 'message' | 'recentMessages'>, before: Message, limit: number, until = 0): Message[] {
- const recent = db
- .recentMessages(before.conversationId, limit + 40)
- .filter((m) => m.id !== before.id && m.at <= before.at && m.at > until)
- .slice(-limit)
- if (!before.threadId) return recent
- const seen = new Set(recent.map((m) => m.id))
- const thread = [db.message(before.threadId), ...db.recentMessages(before.conversationId, limit + 40, before.threadId)].filter(
- (m): m is Message => !!m && m.id !== before.id && m.at <= before.at && !seen.has(m.id)
- )
- return [...recent, ...thread].sort((a, b) => a.at - b.at)
+// Another thread of the conversation, in a line: what opened it, who answered and who is
+// on it now. Only the router reads these: an agent's thread is a conversation of its own.
+export interface ThreadDigest {
+ id: string // the message that opened it
+ root?: Message
+ last?: Message // its newest reply with something said
+ replies: number
+ agents: string[] // who answered in it
+ working: { agentId: string; status: RunStatus }[]
+ at: number // its latest activity
+}
+
+export const MAX_DIGESTS = 12
+const BUSY: RunStatus[] = ['working', 'waiting_input', 'waiting_approval']
+
+// The other threads active in `recent`, oldest activity first, the newest MAX_DIGESTS.
+function digests(db: Pick<Db, 'message'>, recent: Message[], except?: string): ThreadDigest[] {
+ const groups = new Map<string, Message[]>()
+ for (const m of recent) {
+ const key = m.threadId ?? m.id
+ if (key !== except) groups.set(key, [...(groups.get(key) ?? []), m])
+ }
+ return [...groups]
+ .map(([id, ms]): ThreadDigest => {
+ const said = ms.filter((m) => m.id !== id && m.author.kind !== 'system' && m.text.trim())
+ const agents = [...new Set(ms.flatMap((m) => (m.id !== id && m.author.kind === 'agent' ? [m.author.id] : [])))]
+ const working = ms.flatMap((m) => (m.author.kind === 'agent' && m.run && BUSY.includes(m.run.status) ? [{ agentId: m.author.id, status: m.run.status }] : []))
+ return { id, root: ms.find((m) => m.id === id) ?? db.message(id), last: said.at(-1), replies: said.length, agents, working, at: Math.max(...ms.map((m) => m.at)) }
+ })
+ .sort((a, b) => a.at - b.at)
+ .slice(-MAX_DIGESTS)
+}
+
+// What a reply reads of the conversation. In a thread, only that thread: the message that
+// opened it and its newest `limit` replies, with the thread's summary when older ones are
+// left out. The other threads aren't in it (an agent looks them up with buscar_threads);
+// `threads` digests them for the router. Outside threads (a routine, a conversation from
+// before them): the recent messages after `until`, what the conversation's summary covers.
+export function contextWindow(
+ db: Pick<Db, 'message' | 'recentMessages'>,
+ before: Message,
+ limit: number,
+ until = 0
+): { messages: Message[]; threads: ThreadDigest[]; summary?: string } {
+ const recent = db.recentMessages(before.conversationId, limit + 40).filter((m) => m.id !== before.id && m.at <= before.at && m.at > until)
+ if (!before.threadId) return { messages: recent.slice(-limit), threads: [] }
+ const root = db.message(before.threadId)
+ const replies = db.recentMessages(before.conversationId, limit + 2, before.threadId).filter((m) => m.id !== before.id && m.at <= before.at)
+ const omitted = replies.length > limit
+ return {
+ messages: [...(root ? [root] : []), ...replies.slice(-limit)],
+ threads: digests(db, recent, before.threadId),
+ ...(omitted && root?.threadSummary?.text.trim() ? { summary: root.threadSummary.text } : {})
+ }
+}
+
+// One thread found by buscar_threads.
+export interface ThreadHit {
+ id: string
+ conversationId: string
+ root?: Message
+ last?: Message
+ at: number
+}
+
+// buscar_threads: the threads of these conversations that best match the words, by what was
+// said in them and their summaries (a thread just opened has none yet). `except`: the thread
+// the search is made from.
+export function searchThreads(db: Pick<Db, 'message' | 'recentMessages'>, conversationIds: string[], query: string, except?: string, limit = 5): ThreadHit[] {
+ const groups = new Map<string, Message[]>()
+ for (const c of conversationIds)
+ for (const m of db.recentMessages(c, 400)) {
+ const key = m.threadId ?? m.id
+ if (key === except || m.author.kind === 'system' || !m.text.trim()) continue
+ groups.set(key, [...(groups.get(key) ?? []), m])
+ }
+ const docs = [...groups].map(([id, ms]) => {
+ const root = ms.find((m) => m.id === id) ?? db.message(id)
+ const replies = ms.filter((m) => m.id !== id)
+ const text = [root?.text ?? '', root?.threadSummary?.text ?? '', ...replies.map((m) => m.text)].join('\n')
+ return { hit: { id, conversationId: ms[0]!.conversationId, root, last: replies.at(-1), at: ms.at(-1)!.at }, text }
+ })
+ return rank(docs, (d) => d.text, query, limit, (a, b) => b.hit.at - a.hit.at).map((d) => d.hit)
}
// For matching a new memory against forgotten and existing ones.
@@ -188,6 +262,7 @@ export interface MemoryDeps {
export class Memories {
private running = new Map<string, Promise<void>>()
+ private swept = new Map<string, number>() // thread → the last activity a sweep already tried
constructor(private deps: MemoryDeps) {}
@@ -209,16 +284,18 @@ export class Memories {
return rankMemories(out, query, limit)
}
- // What a turn sees of the conversation: the summary and every message after it,
- // outside threads. A reply in a thread sees the summary and that thread instead.
- window(conv: Conversation, before: Message): { summary?: string; messages: Message[] } {
- return { summary: conv.summary, messages: contextWindow(this.deps.db, before, MAX_AFTER, conv.summaryUntil ?? 0) }
+ // What a turn sees of the conversation (contextWindow): in a thread, the thread and its own
+ // summary; outside threads, the conversation's summary and what came after it.
+ window(conv: Conversation, before: Message): { summary?: string; messages: Message[]; threads: ThreadDigest[] } {
+ const w = contextWindow(this.deps.db, before, MAX_AFTER, conv.summaryUntil ?? 0)
+ return before.threadId ? w : { ...w, summary: conv.summary }
}
// ---------- short term: consolidation ----------
- // Folds what is about to leave the window into the summary and extracts
- // memories about me from it. One at a time per conversation.
+ // Folds what is about to leave the window into the conversation's summary (for what reads
+ // it: replies outside threads, like a routine's) and extracts memories about me from the
+ // messages outside threads; a thread's come from its own consolidation. One at a time per conversation.
consolidate(conversationId: string, force = false): Promise<void> {
const current = this.running.get(conversationId)
if (current) return current
@@ -274,16 +351,104 @@ export class Memories {
db.setSummary(conv.id, parsed.summary, chunk.at(-1)!.at)
emit({ type: 'conversation', conversation: db.conversation(conv.id)! })
- if (settings.memoryLearning !== 'off') this.applyExtraction(parsed.ops, chunk, conv.id, settings.memoryLearning)
+ const threads = db.threadRoots(conv.id)
+ if (settings.memoryLearning !== 'off') this.applyExtraction(parsed.ops, chunk, conv.id, settings.memoryLearning, (m) => !m.threadId && !threads.has(m.id))
}
- private applyExtraction(ops: Op[], chunk: Message[], conversationId: string, learning: 'approve' | 'auto'): void {
+ // ---------- threads ----------
+
+ // A thread's own summary and the memories in it, in one call. 'grown': only once more than
+ // MAX_AFTER messages follow its summary (the older ones leave the replies' window); 'quiet':
+ // it stopped (sweep), with at least THREAD_MIN messages to read; 'now': asked for. One at a time per thread.
+ consolidateThread(rootId: string, reason: 'grown' | 'quiet' | 'now'): Promise<void> {
+ const key = `thread:${rootId}`
+ const current = this.running.get(key)
+ if (current) return current
+ const p = this.doThread(rootId, reason)
+ .catch((e: unknown) => console.error('[memory]', e))
+ .finally(() => this.running.delete(key))
+ this.running.set(key, p)
+ return p
+ }
+
+ // The threads quiet for THREAD_QUIET_MS with at least THREAD_MIN messages since their summary,
+ // a few per call (the clock calls it every minute), never one with a reply still being
+ // written. Each is tried once per stretch: if it fails, it waits for something new in it.
+ async sweep(now = Date.now()): Promise<void> {
+ const { db } = this.deps
+ const due = db.quietThreads(now - THREAD_QUIET_MS, now - THREAD_HORIZON_MS).filter((t) => {
+ if (this.swept.get(t.id) === t.last) return false
+ const root = db.message(t.id)
+ const since = root?.threadSummary?.until ?? 0
+ const replies = db.recentMessages(t.conversationId, 1000, t.id)
+ if (replies.some((m) => m.run?.status === 'working')) return false
+ return [root, ...replies].filter((m) => m && m.at > since && m.author.kind !== 'system' && m.text.trim()).length >= THREAD_MIN
+ })
+ for (const t of due.slice(0, SWEEP_BATCH)) {
+ this.swept.set(t.id, t.last)
+ await this.consolidateThread(t.id, 'quiet')
+ }
+ }
+
+ private async doThread(rootId: string, reason: 'grown' | 'quiet' | 'now'): Promise<void> {
+ const { db, engines, emit } = this.deps
+ const root = db.message(rootId)
+ if (!root || root.threadId) return
+ const since = root.threadSummary?.until ?? 0
+ const stretch = [root, ...db.recentMessages(root.conversationId, 1000, root.id)].filter((m) => m.at > since && m.author.kind !== 'system' && m.text.trim())
+ if (reason === 'grown' && stretch.length <= MAX_AFTER) return
+ if (reason === 'quiet' && stretch.length < THREAD_MIN) return
+ if (stretch.length === 0) return
+
+ const settings = await this.deps.settings()
+ const model = usable(modelInfo(settings.memoryModel)) ?? modelInfo('haiku')!
+ const status = settings.engines[model.engine]
+ if (!status.installed || !status.loggedIn) return console.log(`[memory] skipped: ${ENGINES[model.engine].label} not ready`)
+
+ const cwd = join(this.deps.workDir, '_memory')
+ mkdirSync(cwd, { recursive: true })
+ const prompt = consolidationPrompt({
+ summary: root.threadSummary?.text,
+ messages: stretch,
+ me: settings.workspaceName,
+ agents: db.agents(),
+ memories: db.memories({ scope: 'me', state: 'active' }),
+ forgotten: db.memories({ scope: 'me', state: 'forgotten' }).slice(-50),
+ thread: true
+ })
+ const started = Date.now()
+ let text = ''
+ let error: string | undefined
+ for await (const ev of engines[model.engine].run({ model: model.id, effort: 'low', system: memorySystem(), prompt, cwd, signal: AbortSignal.timeout(120_000) })) {
+ if (ev.type === 'text') text += ev.delta
+ else if (ev.type === 'done') {
+ text = ev.text || text
+ db.addReceipt({ ...ev.usage, model: model.id, ms: Date.now() - started, messageId: rootId, agentId: 'memory', engine: model.engine, at: Date.now() })
+ } else if (ev.type === 'error') error = ev.message
+ }
+ const parsed = error ? null : parseConsolidation(text)
+ if (!parsed) return console.log(`[memory] thread consolidation failed: ${error ?? 'resposta fora do formato'}`)
+
+ db.setThreadSummary(rootId, parsed.summary, stretch.at(-1)!.at)
+ emit({ type: 'message', message: db.message(rootId)! })
+ if (settings.memoryLearning !== 'off') this.applyExtraction(parsed.ops, stretch, root.conversationId, settings.memoryLearning)
+ }
+
+ editThreadSummary(rootId: string, text: string): void {
+ const root = this.deps.db.message(rootId)
+ if (!root || root.threadId) return
+ this.deps.db.setThreadSummary(rootId, text.trim())
+ this.deps.emit({ type: 'message', message: this.deps.db.message(rootId)! })
+ }
+
+ // `counts`: which messages of the chunk may back a memory (the rest is only read for context).
+ private applyExtraction(ops: Op[], chunk: Message[], conversationId: string, learning: 'approve' | 'auto', counts: (m: Message) => boolean = () => true): void {
const known = new Map(this.deps.db.memories({ scope: 'me', state: 'active' }).map((m) => [m.id, m]))
// Only what I said counts as evidence about me (an agent's guess never does).
const evidence = (nums: number[]): string[] =>
nums
.map((n) => chunk[n - 1])
- .filter((m): m is Message => m?.author.kind === 'me')
+ .filter((m): m is Message => m?.author.kind === 'me' && counts(m))
.map((m) => m.id)
for (const op of ops) {
if (op.op === 'confirm') {
@@ -442,9 +607,14 @@ function matches(term: string, word: string): boolean {
// BM25 over the memories given, best first; ties go to the most recently confirmed.
export function rankMemories(memories: Memory[], query: string, limit = 5): Memory[] {
+ return rank(memories, (m) => m.text, query, limit, (x, y) => y.confirmedAt - x.confirmedAt)
+}
+
+// BM25 over any items, by their text, best first (at most 10); `tie` orders equal scores.
+function rank<T>(items: T[], text: (t: T) => string, query: string, limit: number, tie: (x: T, y: T) => number): T[] {
const terms = [...new Set(words(query))]
- if (!terms.length || !memories.length) return []
- const docs = memories.map((m) => ({ m, w: words(m.text) }))
+ if (!terms.length || !items.length) return []
+ const docs = items.map((m) => ({ m, w: words(text(m)) }))
const avg = docs.reduce((n, d) => n + d.w.length, 0) / docs.length || 1
const k1 = 1.2
const b = 0.75
@@ -461,7 +631,7 @@ export function rankMemories(memories: Memory[], query: string, limit = 5): Memo
}, 0)
}))
.filter((r) => r.score > 0)
- .sort((x, y) => y.score - x.score || y.m.confirmedAt - x.m.confirmedAt)
+ .sort((x, y) => y.score - x.score || tie(x.m, y.m))
.slice(0, Math.min(Math.max(1, Math.floor(limit)), 10))
.map((r) => r.m)
}
diff --git a/src/core/router.ts b/src/core/router.ts
index 22cb844..cda5b3c 100644
--- a/src/core/router.ts
+++ b/src/core/router.ts
@@ -5,6 +5,7 @@
import { L } from '../shared/lang'
import type { Agent, Connector, Message } from '../shared/types'
import type { Engine, Usage } from './engines/types'
+import type { ThreadDigest } from './memory'
export const ROUTER_HISTORY = 10
export const MAX_ROUTED = 2
@@ -45,26 +46,32 @@ export function describeAgent(a: Agent, connectors: Connector[] = []): string {
export const REPLY_JSON = (): string => L('Responda só com o JSON.', 'Reply with the JSON only.')
-// `thread`: the message that started the thread the last message is in; `messages` are then its replies.
-export function routerPrompt(opts: { messages: Message[]; agents: Agent[]; me: string; connectors?: Connector[]; thread?: Message }): string {
- const { messages, agents, me, connectors = [], thread } = opts
+// `thread`: the message that started the thread the last message is in; `messages` are then
+// that thread, and `threads` the conversation's other threads, a line each (who took what).
+export function routerPrompt(opts: { messages: Message[]; agents: Agent[]; me: string; connectors?: Connector[]; thread?: Message; threads?: ThreadDigest[] }): string {
+ const { messages, agents, me, connectors = [], thread, threads = [] } = opts
const roster = agents.map((a) => `- ${a.handle}: ${describeAgent(a, connectors)}`)
const said = (m: Message): boolean => !!m.text.trim() && m.author.kind !== 'system'
- const recent = messages.filter(said).slice(-ROUTER_HISTORY)
- const lines = [...(thread && said(thread) ? [thread] : []), ...recent]
- .map((m) => {
- const author =
- m.author.kind === 'me'
- ? me
- : m.author.kind === 'routine'
- ? L(`rotina de ${me}`, `${me}'s routine`)
- : (agents.find((a) => m.author.kind === 'agent' && a.id === m.author.id)?.name ?? L('agente', 'agent'))
- return `[${author}] ${m.text.trim().slice(0, 600)}`
+ const name = (m: Message): string =>
+ m.author.kind === 'me'
+ ? me
+ : m.author.kind === 'routine'
+ ? L(`rotina de ${me}`, `${me}'s routine`)
+ : (agents.find((a) => m.author.kind === 'agent' && a.id === m.author.id)?.name ?? L('agente', 'agent'))
+ const recent = messages.filter((m) => said(m) && m.id !== thread?.id).slice(-ROUTER_HISTORY)
+ const lines = [...(thread && said(thread) ? [thread] : []), ...recent].map((m) => `[${name(m)}] ${m.text.trim().slice(0, 600)}`)
+ // Who answered what elsewhere, so a follow-up goes to whoever handled the subject.
+ const others = threads
+ .filter((t) => t.root && said(t.root))
+ .map((t) => {
+ const who = t.agents.map((id) => agents.find((a) => a.id === id)?.name ?? L('agente', 'agent')).join(', ')
+ return `- [${name(t.root!)}] ${t.root!.text.replace(/\s+/g, ' ').trim().slice(0, 200)} → ${who || L('sem resposta', 'no reply')}`
})
return [
L('Agentes no canal:', 'Agents in the channel:'),
...roster,
'',
+ ...(others.length ? [L('Outras threads recentes (outros assuntos, só contexto: quem respondeu cada uma):', 'Other recent threads (other subjects, context only: who answered each):'), ...others, ''] : []),
thread
? L('Thread (a primeira mensagem abriu a thread; a última é a que precisa de resposta):', 'Thread (the first message started it; the last one is the one that needs an answer):')
: L('Conversa (a última é a que precisa de resposta):', 'Conversation (the last one is the one that needs an answer):'),
@@ -107,6 +114,7 @@ export async function route(opts: {
me: string
connectors?: Connector[]
thread?: Message
+ threads?: ThreadDigest[]
cwd: string
}): Promise<{ agents: Agent[]; reason: string; usage?: Usage; ms: number } | { error: string; usage?: Usage; ms: number }> {
const started = Date.now()
diff --git a/src/core/runs.ts b/src/core/runs.ts
index 86e5a0d..5b275a6 100644
--- a/src/core/runs.ts
+++ b/src/core/runs.ts
@@ -6,8 +6,8 @@ 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, REPEAT_STOP, REPEAT_WARN, 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 Routine, type Run, type RunStatus, type Settings, type Step, wikiAccess } from '../shared/types'
-import { HISTORY_LIMIT, mentioned, systemPrompt, transcriptBlocks } from './context'
-import { BUSCAR_MEMORIAS, contextWindow, LEMBRAR, type Memories } from './memory'
+import { BUSCAR_THREADS, clock, HISTORY_LIMIT, LER_THREAD, mentioned, snip, systemPrompt, transcript, transcriptBlocks } 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'
import { APP_TOOL_NAMES, APPS, appStep, appTools, type DesktopApps } from './apps'
@@ -370,7 +370,7 @@ export class Runner {
this.deps.emit({ type: 'message', message: { ...m } })
}
- // The router reads the conversation, threads included, and the thread it picks for.
+ // The router reads the thread it picks for, and the conversation's other threads in a line each.
private async routeAndRun(conv: Conversation, members: Agent[], threadId?: string): Promise<void> {
const { db, engines } = this.deps
this.routing++
@@ -379,8 +379,10 @@ export class Runner {
this.update(note, { text: L(`Não consegui escolher quem responde (${why}). Mencione um agente com **@nome**.`, `I couldn't pick who answers (${why}). Mention an agent with **@name**.`), run: undefined })
try {
const settings = await this.deps.settings()
+ const { messages, threads } = contextWindow(db, note, 20)
const input = {
- messages: [...new Map([...db.recentMessages(conv.id, 20), ...(threadId ? db.recentMessages(conv.id, 60, threadId) : [])].map((m) => [m.id, m])).values()].sort((a, b) => a.at - b.at),
+ messages,
+ threads,
thread: threadId ? db.message(threadId) : undefined,
agents: members,
me: settings.workspaceName,
@@ -544,10 +546,7 @@ export class Runner {
const members = this.members(conv)
const peers = members.filter((a) => a.id !== agent.id)
const memory = this.deps.memory
- const { summary, messages: history } = memory?.window(db.conversation(conv.id) ?? conv, msg) ?? {
- summary: undefined,
- messages: contextWindow(db, msg, HISTORY_LIMIT)
- }
+ const { summary, messages: history } = memory?.window(db.conversation(conv.id) ?? conv, msg) ?? contextWindow(db, msg, HISTORY_LIMIT)
// What this reply counts toward: given (a chain, a routine's issue), or an issue named in the message it answers.
const asked = [...history].reverse().find((m) => m.author.kind === 'me' || m.author.kind === 'routine')
const work = opts.work ?? opts.existing?.run?.work ?? (asked ? workIn(asked.text) : undefined)
@@ -555,6 +554,9 @@ export class Runner {
// Past the prompt's budget, the older memories are searched instead: the tool shows up only then.
const promptMemories = memory?.forPrompt(agent)
const canSearch = !!this.deps.gateway && !!promptMemories?.searchable
+ // A thread sees only itself: the other threads, of the conversations this agent is in, are looked up.
+ const canSeekThreads = !!this.deps.gateway && !!msg.threadId
+ const myConversations = (): Conversation[] => db.conversations().filter((c) => c.members.includes(agent.id))
// The Tuca proposes agents; nobody else does.
const builds = !!this.deps.gateway && agent.kind === 'tuca'
const computers = this.deps.gateway && agent.computer ? this.deps.computers : undefined
@@ -624,7 +626,7 @@ export class Runner {
const services: string[] = []
const routineIds: string[] = []
const exposed = new Map<string, Exposed>()
- const taken = new Set<string>([ASK_USER.name, ACCESS_REQUEST, ABRIR_PR, LEMBRAR.name, ...COMPUTER_TOOL_NAMES, ...BROWSER_TOOL_NAMES, ...APP_TOOL_NAMES, ...ROUTINE_TOOL_NAMES, ...SKILL_TOOL_NAMES])
+ const taken = new Set<string>([ASK_USER.name, ACCESS_REQUEST, ABRIR_PR, LEMBRAR.name, BUSCAR_THREADS.name, LER_THREAD.name, ...COMPUTER_TOOL_NAMES, ...BROWSER_TOOL_NAMES, ...APP_TOOL_NAMES, ...ROUTINE_TOOL_NAMES, ...SKILL_TOOL_NAMES])
for (const c of this.deps.connectors?.list() ?? []) {
if (c.status !== 'connected') continue
for (const t of db.tools(c.id)) if (allowed(t, agent.grants[c.id])) exposed.set(exposedName(c, t.name, taken), { connector: c, tool: t })
@@ -678,6 +680,7 @@ export class Runner {
...(prTool ? [prTool] : []),
...(canRemember ? [LEMBRAR] : []),
...(canSearch ? [BUSCAR_MEMORIAS] : []),
+ ...(canSeekThreads ? [BUSCAR_THREADS, LER_THREAD] : []),
...(builds ? [PROPOR_AGENTE] : []),
...(computers ? computerTools(agent) : []),
...(browser ? browserTools() : []),
@@ -753,6 +756,48 @@ export class Runner {
return textResult(found.map((m) => `- [${m.id}] ${m.text} (${about(m)}, ${new Date(m.confirmedAt).toLocaleDateString(locale())})`).join('\n'))
}
+ if (name === BUSCAR_THREADS.name && canSeekThreads) {
+ const busca = typeof args['busca'] === 'string' ? args['busca'].trim() : ''
+ if (!busca) return textResult(L('Faltou o que buscar.', 'Missing what to search for.'), true)
+ const convs = myConversations()
+ const hits = searchThreads(db, convs.map((c) => c.id), busca, msg.threadId, typeof args['limite'] === 'number' ? args['limite'] : 5)
+ addSteps({ id: randomUUID(), label: L('Buscou nas threads', 'Searched threads'), detail: `${busca} · ${hits.length === 1 ? L('1 achada', '1 found') : L(`${hits.length} achadas`, `${hits.length} found`)}`, status: 'done' })
+ if (!hits.length) return textResult(L(`Nenhuma thread com "${busca}". Tente outras palavras; se não achar, o assunto não foi tratado nas conversas recentes.`, `No thread with "${busca}". Try other words; if nothing turns up, the subject wasn't covered in the recent conversations.`))
+ const who = (m: Message): string => (m.author.kind === 'me' ? settings.workspaceName : m.author.kind === 'agent' ? (db.agent(m.author.id)?.name ?? L('agente', 'agent')) : L('rotina', 'routine'))
+ const lines = hits.map((h) => {
+ const c = convs.find((x) => x.id === h.conversationId)
+ const where = c?.kind === 'dm' ? L('DM', 'DM') : `#${c?.name ?? '?'}`
+ const opened = h.root ? `${who(h.root)}: "${snip(h.root.text, 200)}"` : L('(a mensagem que abriu foi apagada)', '(the message that opened it was deleted)')
+ const gist = h.root?.threadSummary?.text.trim()
+ ? `${L('resumo', 'summary')}: "${snip(h.root.threadSummary.text, 400)}"`
+ : h.last
+ ? `${L('última resposta', 'last reply')} (${who(h.last)}): "${snip(h.last.text, 300)}"`
+ : L('sem resposta', 'no reply')
+ return `- [${h.id}] ${where} · ${clock(h.at)} · ${opened} · ${gist}`
+ })
+ return textResult(lines.join('\n'))
+ }
+
+ if (name === LER_THREAD.name && canSeekThreads) {
+ const id = typeof args['id'] === 'string' ? args['id'].trim().replace(/^\[|\]$/g, '') : ''
+ const found = id ? db.message(id) : undefined
+ const c = found && myConversations().find((x) => x.id === found.conversationId)
+ // Only threads of the conversations it's in, and not the one it's replying in (that's in the prompt).
+ const root = c && found ? (found.threadId ? db.message(found.threadId) : found) : undefined
+ if (!c || !root || root.id === msg.threadId) return textResult(L('Não achei essa thread nas suas conversas. Use um id que buscar_threads devolveu.', "I couldn't find that thread in your conversations. Use an id buscar_threads returned."), true)
+ const replies = db.recentMessages(c.id, HISTORY_LIMIT + 1, root.id).filter((m) => m.id !== msg.id)
+ const older = replies.length > HISTORY_LIMIT && root.threadSummary?.text.trim()
+ const where = c.kind === 'dm' ? L(`DM com ${settings.workspaceName}`, `DM with ${settings.workspaceName}`) : `#${c.name}`
+ addSteps({ id: randomUUID(), label: L('Leu uma thread', 'Read a thread'), detail: snip(root.text, 80), status: 'done' })
+ return textResult(
+ [
+ L(`Thread em ${where}:`, `Thread in ${where}:`),
+ ...(older ? [`${L('Resumo do começo dela', 'Summary of its beginning')}:\n${root.threadSummary!.text.trim()}`] : []),
+ ...transcript({ agent, conversation: c, messages: [root, ...replies.slice(-HISTORY_LIMIT)], agents: db.agents(), me: settings.workspaceName }).slice(1)
+ ].join('\n\n')
+ )
+ }
+
if (name === LEMBRAR.name && canRemember) {
const current = db.agent(agent.id) ?? agent // the mode may have changed mid-turn
if (current.memory === 'read') return textResult(L('Sua memória está só leitura agora.', 'Your memory is read-only right now.'), true)
@@ -1109,7 +1154,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, task, summary, images: names, thread })
+ const { blocks, blockOf } = transcriptBlocks({ agent, conversation: conv, messages: history, agents: db.agents(), me: settings.workspaceName, task, summary, images: names, thread, searchable: canSeekThreads })
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) }] : []))
@@ -1277,6 +1322,7 @@ export class Runner {
const updated = db.agent(agent.id)
if (updated) emit({ type: 'agent', agent: updated })
void memory?.consolidate(conv.id)
+ if (msg.threadId) void memory?.consolidateThread(msg.threadId, 'grown')
if (!opts.routine && msg.run?.status === 'done') this.deps.wikiCurator?.afterReply(conv.id)
return msg
}
diff --git a/src/renderer/src/components/Conversation.tsx b/src/renderer/src/components/Conversation.tsx
index 9acff5c..e7e0640 100644
--- a/src/renderer/src/components/Conversation.tsx
+++ b/src/renderer/src/components/Conversation.tsx
@@ -14,6 +14,7 @@ import {
decideMemory,
describeSchedule,
editSummary,
+ editThreadSummary,
ENGINES,
forgetMemory,
modelById,
@@ -32,6 +33,7 @@ import {
setTab,
stopRun,
summarizeNow,
+ summarizeThreadNow,
useStore,
SUMMARY_MAX_AFTER,
SUMMARY_WINDOW,
@@ -563,6 +565,7 @@ function ThreadPanel({ rootId, conv, title, members }: { rootId: string; conv: C
const root = useStore((s) => s.messages.find((m) => m.id === rootId))
const replies = useStore((s) => s.messages.filter((m) => m.threadId === rootId))
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
const replying = [...new Set(replies.flatMap((m) => (m.run?.status === 'working' && m.author.kind === 'agent' ? [m.author.id] : [])))].map((id) => agents.find((a) => a.id === id)?.name ?? L('agente', 'agent'))
// Open, the thread is seen as it goes; closed, up to when it closed.
@@ -601,12 +604,24 @@ function ThreadPanel({ rootId, conv, title, members }: { rootId: string; conv: C
<strong className="side-panel__title">{L('Thread', 'Thread')}</strong>
<span className="side-panel__where">{L(`em ${title}`, `in ${title}`)}</span>
<span className="grow" />
+ {root && (
+ <button
+ className={`icon-btn ${showSummary ? 'is-active' : ''}`}
+ title={L('O que esta thread já cobriu', 'What this thread has covered')}
+ aria-label={L('Resumo da thread', 'Thread summary')}
+ aria-pressed={showSummary}
+ onClick={() => setShowSummary(!showSummary)}
+ >
+ <Icon name="book" size={14} />
+ </button>
+ )}
<button className="icon-btn" title={L('Fechar', 'Close')} aria-label={L('Fechar a thread', 'Close the thread')} onClick={() => openPanel(null)}>
<Icon name="x" size={14} />
</button>
</header>
{root?.conversationId === conv.id ? (
<>
+ {showSummary && <ThreadSummaryPanel root={root} replies={replies} onClose={() => setShowSummary(false)} />}
<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…')} />
</>
@@ -639,52 +654,99 @@ function CodeBlock({ children }: { children?: ReactNode }): ReactNode {
}
function SummaryPanel({ conv, messages, onClose }: { conv: Conversation; messages: Message[]; onClose: () => void }): ReactNode {
- const [text, setText] = useState(conv.summary ?? '')
+ const since = messages.filter((m) => m.author.kind !== 'system' && m.text.trim() && m.at > (conv.summaryUntil ?? 0)).length
+ return (
+ <SummaryBox
+ title={L('Resumo da conversa', 'Conversation summary')}
+ summary={conv.summary}
+ at={conv.summaryAt}
+ ready={since > SUMMARY_WINDOW}
+ notYet={L(`As últimas ${SUMMARY_WINDOW} mensagens sempre vão inteiras; ainda não há o que resumir.`, `The last ${SUMMARY_WINDOW} messages always go in full; nothing to summarize yet.`)}
+ empty={L(`Quando passar de ${SUMMARY_MAX_AFTER} mensagens, o que sair da janela vira um resumo aqui.`, `Past ${SUMMARY_MAX_AFTER} messages, what leaves the window becomes a summary here.`)}
+ hint={L(
+ `Numa thread, os agentes leem só a thread. Este resumo vai pras respostas fora de threads, como as das rotinas: elas recebem ${conv.summary ? 'este resumo e ' : ''}as ${since} mensagens ${conv.summary ? 'desde ele' : 'da conversa'}.`,
+ `In a thread, agents read only the thread. This summary goes to replies outside threads, like routines': they get ${conv.summary ? 'this summary and ' : ''}the ${since} messages ${conv.summary ? 'since it' : 'of the conversation'}.`
+ )}
+ onSummarize={() => summarizeNow(conv.id)}
+ onSave={(text) => editSummary(conv.id, text)}
+ onClose={onClose}
+ />
+ )
+}
+
+// A thread's own summary: made once it's quiet for a while (or grows long), and where the
+// memories about me in it come from.
+function ThreadSummaryPanel({ root, replies, onClose }: { root: Message; replies: Message[]; onClose: () => void }): ReactNode {
+ const s = root.threadSummary
+ const since = [root, ...replies].filter((m) => m.author.kind !== 'system' && m.text.trim() && m.at > (s?.until ?? 0)).length
+ return (
+ <SummaryBox
+ title={L('Resumo da thread', 'Thread summary')}
+ summary={s?.text}
+ at={s?.at}
+ ready={since > 0}
+ notYet={L('Nada novo desde o resumo.', 'Nothing new since the summary.')}
+ empty={L('Quando a thread ficar parada por alguns minutos, o que foi dito vira um resumo aqui, e as memórias sobre você saem dele.', 'Once the thread is quiet for a few minutes, what was said becomes a summary here, and the memories about you come from it.')}
+ hint={L(
+ `Os agentes de outras threads acham esta por ele, quando procuram. Aqui, eles recebem a thread inteira até ${SUMMARY_MAX_AFTER} respostas; passando disso, este resumo e as mais recentes.`,
+ `Agents in other threads find this one by it when they search. Here, they get the whole thread up to ${SUMMARY_MAX_AFTER} replies; past that, this summary and the newest ones.`
+ )}
+ onSummarize={() => summarizeThreadNow(root.id)}
+ onSave={(text) => editThreadSummary(root.id, text)}
+ onClose={onClose}
+ />
+ )
+}
+
+function SummaryBox(p: {
+ title: string
+ summary?: string
+ at?: number
+ ready: boolean // there's something new to summarize
+ notYet: string // why not, when there isn't
+ empty: string
+ hint: string
+ onSummarize: () => void
+ onSave: (text: string) => void
+ onClose: () => void
+}): ReactNode {
+ const [text, setText] = useState(p.summary ?? '')
const [asked, setAsked] = useState<number | null>(null)
- useEffect(() => setText(conv.summary ?? ''), [conv.summary, conv.summaryAt])
+ useEffect(() => setText(p.summary ?? ''), [p.summary, p.at])
useEffect(() => {
if (asked === null) return
const t = setTimeout(() => setAsked(null), 120_000) // give up waiting; the core logs failures
return () => clearTimeout(t)
}, [asked])
- const busy = asked !== null && (conv.summaryAt ?? 0) < asked
- const since = messages.filter((m) => m.author.kind !== 'system' && m.text.trim() && m.at > (conv.summaryUntil ?? 0)).length
- const changed = text.trim() !== (conv.summary ?? '').trim()
+ const busy = asked !== null && (p.at ?? 0) < asked
+ const changed = text.trim() !== (p.summary ?? '').trim()
return (
<div className="summary">
<div className="summary__head">
- <strong>{L('Resumo da conversa', 'Conversation summary')}</strong>
- <span className="muted small">{conv.summaryAt ? L(`atualizado ${time(conv.summaryAt)}`, `updated ${time(conv.summaryAt)}`) : L('ainda não há', 'none yet')}</span>
+ <strong>{p.title}</strong>
+ <span className="muted small">{p.at ? L(`atualizado ${time(p.at)}`, `updated ${time(p.at)}`) : L('ainda não há', 'none yet')}</span>
<span className="grow" />
<button
className="btn btn--sm"
- disabled={busy || since <= SUMMARY_WINDOW}
- title={since <= SUMMARY_WINDOW ? L(`As últimas ${SUMMARY_WINDOW} mensagens sempre vão inteiras; ainda não há o que resumir.`, `The last ${SUMMARY_WINDOW} messages always go in full; nothing to summarize yet.`) : undefined}
+ disabled={busy || !p.ready}
+ title={p.ready ? undefined : p.notYet}
onClick={() => {
setAsked(Date.now())
- summarizeNow(conv.id)
+ p.onSummarize()
}}
>
{busy ? L('Resumindo…', 'Summarizing…') : L('Resumir agora', 'Summarize now')}
</button>
- <button className="icon-btn" title={L('Fechar', 'Close')} onClick={onClose}>
+ <button className="icon-btn" title={L('Fechar', 'Close')} onClick={p.onClose}>
<Icon name="x" size={14} />
</button>
</div>
- {conv.summary !== undefined || changed ? (
- <textarea rows={6} value={text} onChange={(e) => setText(e.target.value)} />
- ) : (
- <p className="muted small">
- {L(`Quando passar de ${SUMMARY_MAX_AFTER} mensagens, o que sair da janela vira um resumo aqui, e os agentes recebem o resumo mais as mensagens recentes.`, `Past ${SUMMARY_MAX_AFTER} messages, what leaves the window becomes a summary here, and agents get the summary plus the recent messages.`)}
- </p>
- )}
+ {p.summary !== undefined || changed ? <textarea rows={6} value={text} onChange={(e) => setText(e.target.value)} /> : <p className="muted small">{p.empty}</p>}
<div className="row row--between">
- <span className="hint">
- {L(`Os agentes recebem ${conv.summary ? 'este resumo e ' : ''}as ${since} mensagens ${conv.summary ? 'desde ele' : 'da conversa'}.`, `Agents get ${conv.summary ? 'this summary and ' : ''}the ${since} messages ${conv.summary ? 'since it' : 'of the conversation'}.`)}
- </span>
+ <span className="hint">{p.hint}</span>
{changed && (
- <button className="btn btn--sm btn--primary" onClick={() => editSummary(conv.id, text)}>
+ <button className="btn btn--sm btn--primary" onClick={() => p.onSave(text)}>
{L('Salvar resumo', 'Save summary')}
</button>
)}
diff --git a/src/renderer/src/store.ts b/src/renderer/src/store.ts
index 3edee81..d9c49c5 100644
--- a/src/renderer/src/store.ts
+++ b/src/renderer/src/store.ts
@@ -533,6 +533,8 @@ export const forgetMemory = (id: string, reason?: string): void => void fire(L('
export const purgeMemory = (id: string): void => void fire(L('Não consegui apagar a memória.', "I couldn't delete the memory."), 'purgeMemory', { id })
export const editSummary = (conversationId: string, text: string): void => void fire(L('Não consegui salvar o resumo.', "I couldn't save the summary."), 'editSummary', { conversationId, text })
export const summarizeNow = (conversationId: string): void => void fire(L('Não consegui resumir a conversa.', "I couldn't summarize the conversation."), 'summarizeNow', { conversationId })
+export const editThreadSummary = (rootId: string, text: string): void => void fire(L('Não consegui salvar o resumo.', "I couldn't save the summary."), 'editThreadSummary', { rootId, text })
+export const summarizeThreadNow = (rootId: string): void => void fire(L('Não consegui resumir a thread.', "I couldn't summarize the thread."), 'summarizeThreadNow', { rootId })
// Saves one field of a stored agent without touching the rest of its page.
export function patchAgent(agentId: string, patch: Partial<Agent>): void {
diff --git a/src/shared/rpc.ts b/src/shared/rpc.ts
index b5d4a6e..95952de 100644
--- a/src/shared/rpc.ts
+++ b/src/shared/rpc.ts
@@ -76,6 +76,8 @@ export interface Api {
purgeMemory(p: { id: string }): void // removes even the record that it was forgotten
editSummary(p: { conversationId: string; text: string }): void
summarizeNow(p: { conversationId: string }): void
+ editThreadSummary(p: { rootId: string; text: string }): void
+ summarizeThreadNow(p: { rootId: string }): void
computerAction(p: { agentId: string; action: 'start' | 'restart' | 'erase' | 'open_folder' | 'refresh' }): void
stopService(p: { agentId: string; name: string }): void
browserAction(p: { agentId: string; action: 'show' | 'hide' | 'clear' }): void
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 69fae03..3893571 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -201,6 +201,14 @@ export interface Message {
run?: Run
routine?: RoutineRun // set on the message a routine posts (author kind 'routine')
threadId?: string // a reply in a thread: the id of the message that started it (threads are one level deep)
+ threadSummary?: ThreadSummary // on the message that started a thread: what the thread has covered
+}
+
+// A thread's own summary, kept on its first message. `until`: the `at` of the last message it covers.
+export interface ThreadSummary {
+ text: string
+ until: number
+ at: number
}
// Dictation with whisper-cli. Unset paths are looked for in the usual places.
diff --git a/test/governance.test.ts b/test/governance.test.ts
index 8d6ac1f..f992ed3 100644
--- a/test/governance.test.ts
+++ b/test/governance.test.ts
@@ -134,7 +134,7 @@ describe('grants', () => {
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', 'tarefas__list_tasks']) // it can ask for more, not take it
+ expect(seen.tools[0]).toEqual(['ask_user', 'pedir_acesso', 'buscar_threads', 'ler_thread', 'tarefas__list_tasks']) // it can ask for more, not take it
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/memory.test.ts b/test/memory.test.ts
index 010617f..9cac6c8 100644
--- a/test/memory.test.ts
+++ b/test/memory.test.ts
@@ -8,7 +8,7 @@ import { Db } from '../src/core/db'
import { fakeEngine } from '../src/core/engines/fake'
import type { Engine, Turn } from '../src/core/engines/types'
import { Gateway } from '../src/core/gateway'
-import { MAX_AFTER, Memories, memorySystem, parseConsolidation, WINDOW } from '../src/core/memory'
+import { MAX_AFTER, Memories, memorySystem, parseConsolidation, THREAD_QUIET_MS, WINDOW } from '../src/core/memory'
import { Runner } from '../src/core/runs'
const ready = { installed: true, loggedIn: true }
@@ -40,8 +40,8 @@ async function settle(): Promise<void> {
}
let clock = 1_000_000
-function put(conversationId: string, author: Author, text: string): Message {
- const m: Message = { id: `m${clock}`, conversationId, author, text, at: clock++ }
+function put(conversationId: string, author: Author, text: string, threadId?: string): Message {
+ const m: Message = { id: `m${clock}`, conversationId, author, text, at: clock++, ...(threadId ? { threadId } : {}) }
db.saveMessage(m)
return m
}
@@ -81,7 +81,7 @@ describe('parseConsolidation', () => {
})
describe('summary (short term)', () => {
- it('folds what leaves the window into the summary, and the next turn sees it plus every newer message', async () => {
+ it('folds what leaves the window into the summary, which a reply outside threads reads with every newer message', async () => {
put('c1', { kind: 'me' }, 'ZEBRA é o cupom da campanha')
for (let i = 1; i < MAX_AFTER + 10; i++) put('c1', i % 2 ? { kind: 'agent', id: 'a1' } : { kind: 'me' }, `mensagem ${i}`)
const all = db.messagesAfter('c1', 0)
@@ -91,13 +91,18 @@ describe('summary (short term)', () => {
expect(conv.summary).toContain('ZEBRA')
expect(conv.summaryUntil).toBe(all[all.length - WINDOW - 1]!.at)
+ // Outside threads (a routine's reply): the summary and what came after it.
+ const outside = memory.window(conv, { id: 'x', conversationId: 'c1', author: { kind: 'agent', id: 'a1' }, text: '', at: clock })
+ expect(outside.summary).toContain('ZEBRA')
+ expect(outside.messages.map((m) => m.text)).not.toContain('ZEBRA é o cupom da campanha') // it left the window
+ expect(outside.messages.at(-1)?.text).toBe(`mensagem ${MAX_AFTER + 9}`)
+
+ // A thread is a conversation of its own: neither the summary nor those messages.
await runner.send('c1', '@lia qual é o cupom?')
await settle()
const prompt = agentTurns('lia')[0]!.prompt
- expect(prompt).toContain('Resumo do que veio antes em #engenharia:')
- expect(prompt).toContain('ZEBRA')
- expect(prompt).not.toContain('\nZEBRA é o cupom') // the message itself left the window
- expect(prompt).toContain(`mensagem ${MAX_AFTER + 9}`)
+ expect(prompt).not.toContain('ZEBRA')
+ expect(prompt).not.toContain(`mensagem ${MAX_AFTER + 9}`)
})
it('consolidates on its own once more than MAX_AFTER messages follow the summary', async () => {
@@ -116,6 +121,69 @@ describe('summary (short term)', () => {
})
})
+describe('a thread\'s own summary', () => {
+ it('a quiet thread gets its summary and the memories in it, once; a busy one waits', async () => {
+ const root = put('c1', { kind: 'me' }, 'qual café a gente compra?')
+ put('c1', { kind: 'agent', id: 'a1' }, 'tem o de sempre e um novo', root.id)
+ const last = put('c1', { kind: 'me' }, 'eu prefiro café sem açúcar', root.id)
+ const busy = put('c1', { kind: 'me' }, 'faz o relatório')
+ db.saveMessage({ ...put('c1', { kind: 'agent', id: 'a2' }, 'metade', busy.id), run: { status: 'working', depth: 1, steps: [] } })
+ for (let i = 0; i < WINDOW; i++) put('c1', { kind: 'me' }, `solta ${i}`) // outside threads, after both
+
+ const later = clock + THREAD_QUIET_MS
+ await memory.sweep(later)
+ await memory.idle()
+ expect(db.message(root.id)?.threadSummary).toMatchObject({ text: expect.stringContaining('Resumo de teste: qual café a gente') as string, until: last.at })
+ expect(db.memories().map((m) => [m.text, m.state])).toEqual([['Prefere café sem açúcar', 'pending']])
+ expect(db.message(busy.id)?.threadSummary).toBeUndefined() // a reply is still being written
+
+ // Nothing new since: no second call. And the conversation's summary reads the thread
+ // but doesn't learn from it again: that's the thread's.
+ const calls = turns.filter((t) => t.system === memorySystem()).length
+ await memory.sweep(later + 60_000)
+ await memory.idle()
+ expect(turns.filter((t) => t.system === memorySystem())).toHaveLength(calls)
+ await memory.consolidate('c1', true)
+ expect(db.memories()).toHaveLength(1)
+ })
+
+ it("not before it's quiet, nor for a question and its answer alone", async () => {
+ const root = put('c1', { kind: 'me' }, 'oi')
+ put('c1', { kind: 'agent', id: 'a1' }, 'oi!', root.id)
+ const busy = put('c1', { kind: 'me' }, 'pergunta longa')
+ put('c1', { kind: 'agent', id: 'a1' }, 'resposta', busy.id)
+ put('c1', { kind: 'me' }, 'e mais uma coisa', busy.id)
+ await memory.sweep(clock + 60_000) // a minute later: not quiet yet
+ await memory.sweep(clock + THREAD_QUIET_MS) // quiet: only the one with three messages
+ await memory.idle()
+ expect(db.message(root.id)?.threadSummary).toBeUndefined()
+ expect(db.message(busy.id)?.threadSummary?.text).toContain('Resumo de teste')
+ })
+
+ it("past MAX_AFTER replies, a reply reads the thread's summary, the message that opened it and the newest replies", async () => {
+ const root = put('c1', { kind: 'me' }, 'RAIZ: ZEBRA é o cupom')
+ for (let i = 0; i < MAX_AFTER + 5; i++) put('c1', i % 2 ? { kind: 'agent', id: 'a1' } : { kind: 'me' }, `resposta ${i}`, root.id)
+ await runner.send('c1', '@lia qual era o cupom?', [], root.id)
+ await settle() // the thread grew past MAX_AFTER: it gets its summary
+ expect(db.message(root.id)?.threadSummary?.text).toContain('ZEBRA')
+
+ await runner.send('c1', '@lia e agora?', [], root.id)
+ await settle()
+ const prompt = agentTurns('lia').at(-1)!.prompt
+ expect(prompt).toContain('Resumo do começo desta thread')
+ expect(prompt).toContain('RAIZ: ZEBRA é o cupom') // the message that opened it always goes
+ expect(prompt).not.toContain('\nresposta 0\n')
+ expect(prompt).toContain('@lia e agora?')
+ })
+
+ it('a hand edit keeps what the summary covers, and the thread shows it', () => {
+ const root = put('c1', { kind: 'me' }, 'raiz')
+ db.setThreadSummary(root.id, 'feito pelo modelo', root.at)
+ memory.editThreadSummary(root.id, ' corrigido à mão ')
+ expect(db.message(root.id)?.threadSummary).toMatchObject({ text: 'corrigido à mão', until: root.at })
+ })
+})
+
describe('lembrar (long term)', () => {
it('a memory saved in a DM reaches another agent in a channel', async () => {
await runner.send('d1', 'lembra que eu prefiro PR pequeno')
diff --git a/test/routines.test.ts b/test/routines.test.ts
index 6ddab4a..78521e8 100644
--- a/test/routines.test.ts
+++ b/test/routines.test.ts
@@ -219,7 +219,7 @@ describe('routines', () => {
await runner.send('d1', 'oi de novo') // its next turn sees the time and only its active routines
await runner.idle()
- expect(turns.at(-1)!.prompt).toMatch(/\[Edu · (dom|seg|ter|qua|qui|sex|sáb) \d\d\/\d\d \d\d:\d\d\]\noi de novo$/) // the time, with the weekday, in each message
+ expect(turns.at(-1)!.prompt).toMatch(/\[Edu · (dom|seg|ter|qua|qui|sex|sáb) \d\d\/\d\d \d\d:\d\d\]\noi de novo(\n|$)/) // the time, with the weekday, in each message
expect(turns.at(-1)!.system).not.toContain('## Suas rotinas')
})
diff --git a/test/threads.test.ts b/test/threads.test.ts
index fbf8eb8..b35941b 100644
--- a/test/threads.test.ts
+++ b/test/threads.test.ts
@@ -5,7 +5,7 @@ import { DatabaseSync } from 'node:sqlite'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import type { Agent, Author, EngineId, Message, Settings } from '../src/shared/types'
import { Db } from '../src/core/db'
-import { fakeEngine } from '../src/core/engines/fake'
+import { callTool, fakeEngine } from '../src/core/engines/fake'
import type { Engine, Turn } from '../src/core/engines/types'
import { Gateway } from '../src/core/gateway'
import { consolidationPrompt, MAX_AFTER, Memories, memorySystem } from '../src/core/memory'
@@ -25,9 +25,16 @@ let turns: Turn[]
let notes: { conversationId?: string; kind?: string; threadId?: string }[]
let memory: Memories
-function runner(opts: { reply?: (t: Turn) => string; memory?: boolean } = {}): Runner {
+function runner(opts: { reply?: (t: Turn) => string; memory?: boolean; onTurn?: (t: Turn) => Promise<unknown> } = {}): Runner {
const base = fakeEngine('claude', { delayMs: 1, reply: opts.reply })
- const claude: Engine = { id: 'claude', run: (t) => (turns.push(t), base.run(t)) }
+ const claude: Engine = {
+ id: 'claude',
+ async *run(t) {
+ turns.push(t)
+ await opts.onTurn?.(t)
+ yield* 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') }
const workDir = mkdtempSync(join(tmpdir(), 'ad-work-'))
memory = new Memories({ db, engines, settings: async () => settings, emit: () => {}, workDir })
@@ -107,10 +114,10 @@ describe('sending into a thread', () => {
})
describe("what the agent sees", () => {
- it('in a thread: the summary, the recent conversation and the whole thread, however old', async () => {
+ it("in a thread: only that thread, however old; not the channel's summary nor the other threads", async () => {
const root = put('c1', { kind: 'me' }, 'RAIZ: o plano de lançamento')
put('c1', { kind: 'agent', id: 'a1' }, 'RESPOSTA ANTIGA na thread', root.id)
- db.setSummary('c1', 'RESUMO DO CANAL', root.at + 5) // the summary already covers the thread's start
+ db.setSummary('c1', 'RESUMO DO CANAL', root.at + 5)
clock += 10
put('c1', { kind: 'me' }, 'OUTRO ASSUNTO depois')
const r = runner({ memory: true })
@@ -118,16 +125,39 @@ describe("what the agent sees", () => {
await r.idle()
const prompt = agentTurns()[0]!.prompt
- expect(prompt).toContain('RESUMO DO CANAL')
expect(prompt).toContain('Você está respondendo numa thread em #lancamento, aberta por Edu.')
+ expect(prompt).toContain('Ela é uma conversa à parte')
expect(prompt).toContain('RAIZ: o plano de lançamento')
expect(prompt).toContain('RESPOSTA ANTIGA na thread')
- expect(prompt).toContain('OUTRO ASSUNTO depois')
expect(prompt).toContain('@lia e a data?')
expect(prompt.indexOf('RAIZ')).toBeLessThan(prompt.indexOf('RESPOSTA ANTIGA'))
+ expect(prompt).not.toContain('RESUMO DO CANAL')
+ expect(prompt).not.toContain('OUTRO ASSUNTO')
})
- it("a new message: the agent reads what was said in the earlier threads, so it doesn't start from zero", async () => {
+ it('two threads at once: a reply that goes on in its thread never sees the other, newer one', async () => {
+ // The PR review goes on (after an approval, a pause) once I've asked something else meanwhile.
+ const pr = put('c1', { kind: 'me' }, 'THREAD A: revisa o ENG-105')
+ const paused = put('c1', { kind: 'agent', id: 'a1' }, 'metade da revisão', pr.id)
+ const other = put('c1', { kind: 'me' }, 'THREAD B: implementa o ENG-200')
+ put('c1', { kind: 'agent', id: 'a2' }, 'RESPOSTA DA B', other.id)
+ for (const withMemory of [false, true]) {
+ turns = []
+ db.saveMessage({ ...paused, run: { status: 'paused', depth: 1, steps: [] } })
+ const r = runner({ memory: withMemory })
+ await r.continue(paused.id)
+ await r.idle()
+
+ const prompt = agentTurns()[0]!.prompt
+ expect(prompt).toContain('THREAD A: revisa o ENG-105')
+ expect(prompt).toContain('metade da revisão')
+ expect(prompt).not.toContain('THREAD B')
+ expect(prompt).not.toContain('RESPOSTA DA B')
+ expect(replies().at(-1)).toMatchObject({ threadId: pr.id, run: { work: 'ENG-105' } })
+ }
+ })
+
+ it("a new message is a conversation of its own: the earlier threads aren't given, they're looked up", async () => {
const root = put('d1', { kind: 'me' }, 'as 3 notícias de IA?')
put('d1', { kind: 'agent', id: 'a1' }, 'NOTÍCIAS: IPO, buyouts, busca', root.id)
for (const withMemory of [false, true]) {
@@ -136,9 +166,42 @@ describe("what the agent sees", () => {
await r.send('d1', 'e sobre a Apple?')
await r.idle()
const prompt = agentTurns()[0]!.prompt
- expect(prompt).toContain('NOTÍCIAS: IPO, buyouts, busca')
+ expect(prompt).not.toContain('NOTÍCIAS')
+ expect(prompt).toContain('procure com buscar_threads')
}
})
+
+ it("buscar_threads finds threads of the conversations the agent is in and ler_thread reads them; not where it isn't, nor its own", async () => {
+ const other = put('c1', { kind: 'me' }, 'THREAD B: o plano do post')
+ put('c1', { kind: 'agent', id: 'a2' }, 'RESPOSTA COMPLETA DA B, com o plano inteiro', other.id)
+ put('d1', { kind: 'me' }, 'DM: o plano da viagem')
+ db.createConversation({ id: 'c2', kind: 'channel', name: 'dados', members: ['a2'] }) // Lia isn't in it
+ const theirs = put('c2', { kind: 'me' }, 'PLANO de outro canal')
+ const root = put('c1', { kind: 'me' }, 'THREAD A: o plano?')
+ const results: string[] = []
+ const r = runner({
+ onTurn: async (t) => {
+ if (!t.mcpUrl) return
+ results.push(JSON.stringify(await callTool(t.mcpUrl, 'buscar_threads', { busca: 'plano' })))
+ for (const id of [other.id, theirs.id, root.id]) results.push(JSON.stringify(await callTool(t.mcpUrl, 'ler_thread', { id })))
+ }
+ })
+ await r.send('c1', '@lia e o plano?', [], root.id)
+ await r.idle()
+
+ const [found, read, elsewhere, own] = results
+ expect(found).toContain(`[${other.id}] #lancamento`)
+ expect(found).toContain('RESPOSTA COMPLETA DA B')
+ expect(found).toContain('DM: o plano da viagem') // her DM is one of her conversations
+ expect(found).not.toContain('PLANO de outro canal')
+ expect(found).not.toContain(`[${root.id}]`)
+ expect(read).toContain('Thread em #lancamento')
+ expect(read).toContain('RESPOSTA COMPLETA DA B, com o plano inteiro')
+ expect(elsewhere).toContain('Não achei essa thread')
+ expect(elsewhere).not.toContain('PLANO de outro canal')
+ expect(own).toContain('Não achei essa thread')
+ expect(replies().at(-1)?.run?.steps.map((s) => s.label)).toEqual(expect.arrayContaining(['Buscou nas threads', 'Leu uma thread']))
+ })
})
describe('who answers in a thread', () => {
@@ -164,6 +227,23 @@ describe('who answers in a thread', () => {
expect(replies().map((m) => [(m.author as { id: string }).id, m.threadId])).toEqual([['a2', root.id]])
expect(db.messages().find((m) => m.author.kind === 'system')).toMatchObject({ threadId: root.id, text: expect.stringContaining('Chamei **Theo**') as string })
})
+
+ it('the router reads the thread, and the other threads a line each with who answered them', async () => {
+ const root = put('c1', { kind: 'me' }, 'RAIZ: precisamos da métrica de retenção')
+ const other = put('c1', { kind: 'me' }, 'OUTRA THREAD: e o post?')
+ put('c1', { kind: 'agent', id: 'a1' }, 'RESPOSTA NA OUTRA', other.id)
+ const r = runner()
+ await r.send('c1', 'qual a média da semana?', [], root.id)
+ await r.idle()
+
+ const routed = turns.find((t) => t.system === routerSystem())!.prompt
+ const thread = routed.slice(routed.indexOf('Thread (a primeira mensagem'))
+ expect(routed).toContain('- [Edu] OUTRA THREAD: e o post? → Lia')
+ expect(routed).not.toContain('RESPOSTA NA OUTRA')
+ expect(routed.indexOf('Outras threads recentes')).toBeLessThan(routed.indexOf('Thread (a primeira mensagem'))
+ expect(thread).not.toContain('OUTRA')
+ expect(thread.split('\n').slice(1, 3)).toEqual(['[Edu] RAIZ: precisamos da métrica de retenção', '[Edu] qual a média da semana?'])
+ })
})
describe('questions in threads', () => {
@@ -263,13 +343,13 @@ describe('what a thread message sets off stays in the thread', () => {
})
describe('the database', () => {
- it('an existing database gains thread_id, and messages round-trip it', () => {
+ it('an existing database gains thread_id and thread_summary, and messages round-trip them', () => {
const file = join(mkdtempSync(join(tmpdir(), 'ad-db-')), 'old.db')
- // A database from before threads: the schema one migration back, with a message in it.
+ // A database from before threads: the schema two migrations back, with a message in it.
new Db(file).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; ALTER TABLE messages DROP COLUMN thread_id; PRAGMA user_version = ${user_version - 1};`)
+ raw.exec(`ALTER TABLE messages DROP COLUMN thread_summary; DROP INDEX messages_by_thread; ALTER TABLE messages DROP COLUMN thread_id; PRAGMA user_version = ${user_version - 2};`)
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()
@@ -281,6 +361,10 @@ describe('the database', () => {
expect(reopened.recentMessages('c1', 10, 'old').map((m) => m.id)).toEqual(['r1'])
expect(reopened.recentMessages('c1', 10, null).map((m) => m.id)).toEqual(['old'])
expect(reopened.recentMessages('c1', 10).map((m) => m.id)).toEqual(['old', 'r1'])
+ reopened.setThreadSummary('old', 'o que a thread cobriu', 2)
+ reopened.saveMessage({ ...reopened.message('old')!, text: 'antes das threads (editada)' }) // saving a message keeps its summary
+ reopened.setThreadSummary('old', 'editado à mão') // a hand edit keeps what it covers
+ expect(reopened.message('old')?.threadSummary).toMatchObject({ text: 'editado à mão', until: 2 })
reopened.close()
})
})