diff --git a/src/main/services/agent-read-messages.ts b/src/main/services/agent-read-messages.ts index 9b7f901a..15ae4d2a 100644 --- a/src/main/services/agent-read-messages.ts +++ b/src/main/services/agent-read-messages.ts @@ -2,11 +2,24 @@ import { optionalString } from "./agent-tool-args"; import type { AgentToolContext, AgentToolDeps } from "./agent-tools"; import type { JsonRecord } from "./provider-http"; +interface MessageFilter { + before: { createdAt: string; rowid: number } | null; + query: string | null; + limit: number; +} + export function readMessagesTool(deps: AgentToolDeps, ctx: AgentToolContext, args: JsonRecord): string { const channel = optionalString(args.channel); const withTeammate = optionalString(args.with); - const limit = Math.min(Math.max(Number(args.limit) || 10, 1), 30); - if (channel && withTeammate) throw new Error('Pass either "channel" or "with", not both.'); + const threadId = optionalString(args.thread_id); + if ([channel, withTeammate, threadId].filter(Boolean).length > 1) { + throw new Error('Pass only one of "channel", "with", or "thread_id".'); + } + const filter: MessageFilter = { + before: beforeCursor(deps, ctx.orgId, optionalString(args.before)), + query: optionalString(args.query), + limit: Math.min(Math.max(Number(args.limit) || 10, 1), 30), + }; if (withTeammate) { const counterpart = deps.db.prepare(` select id, name, 'agent' as kind from agents where org_id = ? and lower(name) = lower(?) and lifecycle = 'active' @@ -20,19 +33,54 @@ export function readMessagesTool(deps: AgentToolDeps, ctx: AgentToolContext, arg { type: "agent", id: ctx.agent.id }, { type: counterpart.kind, id: counterpart.id }, ); - const rows = recentMessagesIn(deps, ctx.orgId, spaceId, limit); - if (rows.length === 0) return `No messages yet in your direct conversation with ${counterpart.name}.`; - return rows.map((m) => `[${m.sender_name}] (thread=${m.thread_id}): ${m.body_md}`).join("\n"); + return messagePage(deps, ctx.orgId, { column: "space_id", id: spaceId }, filter, `your direct conversation with ${counterpart.name}`); } if (channel) { const space = deps.db.prepare( "select id from chat_spaces where org_id = ? and lower(name) = lower(?) and space_type <> 'direct' limit 1", ).get(ctx.orgId, channel) as { id: string } | undefined; if (!space) throw new Error(`No channel named "${channel}".`); - const rows = recentMessagesIn(deps, ctx.orgId, space.id, limit); - if (rows.length === 0) return `No recent messages in #${channel}.`; - return rows.map((m) => `[${m.sender_name}] (thread=${m.thread_id}): ${m.body_md}`).join("\n"); + return messagePage(deps, ctx.orgId, { column: "space_id", id: space.id }, filter, `#${channel}`); } + if (threadId) { + const thread = deps.db.prepare("select id from chat_threads where id = ? and org_id = ?").get(threadId, ctx.orgId); + if (!thread) throw new Error(`No thread with thread_id "${threadId}".`); + return messagePage(deps, ctx.orgId, { column: "thread_id", id: threadId }, filter, `thread ${threadId}`); + } + return unansweredMentions(deps, ctx, filter.limit); +} + +function messagePage( + deps: AgentToolDeps, + orgId: string, + scope: { column: "space_id" | "thread_id"; id: string }, + filter: MessageFilter, + label: string, +): string { + const rows = deps.db.prepare(` + select m.id, m.rowid as row_id, m.body_md, m.created_at, m.thread_id, + coalesce(a.name, e.display_name, m.sender_type) as sender_name + from chat_messages m + left join agents a on a.id = m.sender_id and m.sender_type = 'agent' + left join employees e on e.id = m.sender_id and m.sender_type = 'employee' + where m.${scope.column} = ? and m.org_id = ? and m.deleted_at is null + and (? is null or m.created_at < ? or (m.created_at = ? and m.rowid < ?)) + and (? is null or instr(lower(m.body_md), lower(?)) > 0) + order by m.created_at desc, m.rowid desc + limit ? + `).all( + scope.id, orgId, + filter.before?.createdAt ?? null, filter.before?.createdAt ?? null, filter.before?.createdAt ?? null, filter.before?.rowid ?? null, + filter.query, filter.query, filter.limit + 1, + ) as Array<{ id: string; row_id: number; body_md: string; created_at: string; thread_id: string; sender_name: string }>; + if (rows.length === 0) return `No messages${filter.query ? ` matching "${filter.query}"` : ""}${filter.before ? " before that point" : ""} in ${label}.`; + const page = rows.slice(0, filter.limit).reverse(); + const lines = page.map((m) => `[${m.created_at}] ${m.sender_name} (thread=${m.thread_id}): ${m.body_md}`); + if (rows.length > filter.limit) lines.unshift(`(Older messages exist: pass before="${page[0].id}" to read them.)`); + return lines.join("\n"); +} + +function unansweredMentions(deps: AgentToolDeps, ctx: AgentToolContext, limit: number): string { const rows = deps.db.prepare(` select m.body_md, coalesce(a.name, e.display_name, m.sender_type) as sender_name, @@ -58,22 +106,20 @@ export function readMessagesTool(deps: AgentToolDeps, ctx: AgentToolContext, arg }).join("\n"); } -function recentMessagesIn( - deps: AgentToolDeps, - orgId: string, - spaceId: string, - limit: number, -): Array<{ body_md: string; sender_name: string; thread_id: string }> { - const rows = deps.db.prepare(` - select m.body_md, - coalesce(a.name, e.display_name, m.sender_type) as sender_name, - m.thread_id - from chat_messages m - left join agents a on a.id = m.sender_id and m.sender_type = 'agent' - left join employees e on e.id = m.sender_id and m.sender_type = 'employee' - where m.space_id = ? and m.org_id = ? and m.deleted_at is null - order by m.created_at desc - limit ? - `).all(spaceId, orgId, limit) as Array<{ body_md: string; sender_name: string; thread_id: string }>; - return rows.reverse(); +/** A message_id cursor from a previous page, or a UTC time. */ +function beforeCursor(deps: AgentToolDeps, orgId: string, text: string | null): MessageFilter["before"] { + if (!text) return null; + if (text.startsWith("msg_")) { + const row = deps.db.prepare("select created_at, rowid as row_id from chat_messages where id = ? and org_id = ?") + .get(text, orgId) as { created_at: string; row_id: number } | undefined; + if (!row) throw new Error(`No message with id "${text}".`); + return { createdAt: row.created_at, rowid: row.row_id }; + } + const match = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(\.\d{3})?Z$/.exec(text); + const normalized = match ? `${match[1]}${match[2] ?? ".000"}Z` : ""; + const time = new Date(normalized); + if (!match || Number.isNaN(time.getTime()) || time.toISOString() !== normalized) { + throw new Error(`"before" must be a message_id from a previous page or a UTC ISO timestamp like 2026-01-31T09:00:00Z, got "${text}".`); + } + return { createdAt: normalized, rowid: -1 }; } diff --git a/src/main/services/agent-tools.ts b/src/main/services/agent-tools.ts index 58dc407d..3fdfb635 100644 --- a/src/main/services/agent-tools.ts +++ b/src/main/services/agent-tools.ts @@ -135,14 +135,17 @@ export const AGENT_TOOLS: ToolDefinition[] = [ }, { name: "read_messages", - description: "Read recent messages from a channel, a direct conversation, or (with no arguments) the mentions you have not answered in their thread yet. Check what your teammates have been saying before you respond or start work.", + description: "Read messages from a channel, a direct conversation, or one thread — newest first page, with before= to page back and query= to search — or, with no arguments, the mentions you have not answered in their thread yet.", parameters: { type: "object", additionalProperties: false, properties: { channel: { type: "string", description: "Channel name: 'engineering', 'product', 'general'." }, with: { type: "string", description: "Teammate name to read your direct conversation with, e.g. 'CEO'." }, - limit: { type: "number", description: "Number of recent messages (default 10, max 30)." }, + thread_id: { type: "string", description: "Read one thread, e.g. a thread_id from a message or handoff." }, + before: { type: "string", description: "Page back: the message_id a previous page told you to pass, or a UTC ISO timestamp." }, + query: { type: "string", description: "Only messages containing this text (case-insensitive)." }, + limit: { type: "number", description: "Number of messages (default 10, max 30)." }, }, required: [], }, diff --git a/tests/unit/agent-direct-messages.test.ts b/tests/unit/agent-direct-messages.test.ts index 9e55a116..90ba5fc0 100644 --- a/tests/unit/agent-direct-messages.test.ts +++ b/tests/unit/agent-direct-messages.test.ts @@ -153,6 +153,6 @@ describe("agent direct messages", () => { dispatchAgentTool(deps, h.ctx, call("send_message", { to: "Dana", body: "Morning - priorities for today are in the doc." })); const readBack = dispatchAgentTool(deps, h.ctx, call("read_messages", { with: "Dana" })); expect(readBack).toContain("priorities for today"); - expect(readBack).toContain("[CEO]"); + expect(readBack).toMatch(/\] CEO \(thread=/); }); }); diff --git a/tests/unit/mention-resolution.test.ts b/tests/unit/mention-resolution.test.ts index 90371654..5f90f611 100644 --- a/tests/unit/mention-resolution.test.ts +++ b/tests/unit/mention-resolution.test.ts @@ -144,3 +144,63 @@ describe("mention resolution", () => { expect(dispatchAgentTool(deps, danaCtx, call("read_messages", {}))).toContain("status on the rollback"); }); }); + +describe("read_messages history access", () => { + test("reads one thread, pages back with before, and searches with query", () => { + const connection = new DatabaseConnection(join(tmpdir(), `ac-history-${randomUUID()}.db`)); + const organization = new OrganizationService(connection.db); + let orgId = ""; + let ceoId = ""; + connection.transaction(() => { + orgId = organization.createOrganization({ organizationName: "HistCorp", employeeName: "Yang", mission: "m", goal: "g" }); + const providerId = (connection.db.prepare("select id from providers where org_id = ? and provider_key = 'openai'").get(orgId) as { id: string }).id; + ceoId = organization.createAgent({ + orgId, name: "CEO", role: "CEO", department: "Executive", + modelProviderId: providerId, modelId: "gpt-5.4", budgetCents: 25000, managerAgentId: null, + }); + }); + const deps = { db: connection.db, organization, chat: new ChatService(connection.db) }; + const ctx: AgentToolContext = { + orgId, agent: { id: ceoId, modelProviderId: null, modelId: null }, + taskProjectId: null, taskGoalId: null, taskId: null, sourceThreadId: null, workspace: null, + }; + const first = dispatchAgentTool(deps, ctx, call("send_message", { channel: "general", body: "Decision 0: use Postgres" })); + const threadId = /thread_id="([^"]+)"/.exec(first)![1]; + for (let index = 1; index <= 14; index += 1) { + dispatchAgentTool(deps, ctx, call("send_message", { channel: "general", body: `Decision ${index}`, thread_id: threadId })); + } + dispatchAgentTool(deps, ctx, call("send_message", { channel: "general", body: "Unrelated chatter" })); + connection.db.prepare("update chat_messages set created_at = '2026-01-01T00:00:' || printf('%02d', rowid) || '.000Z'").run(); + + const page = dispatchAgentTool(deps, ctx, call("read_messages", { thread_id: threadId, limit: 5 })); + expect(page).not.toContain("Unrelated chatter"); + expect(page).toContain("Decision 14"); + expect(page).not.toContain("Decision 9"); + const before = /before="([^"]+)"/.exec(page)![1]; + const older = dispatchAgentTool(deps, ctx, call("read_messages", { thread_id: threadId, limit: 5, before })); + expect(older).toContain("Decision 9"); + expect(older).not.toContain("Decision 10"); + + const found = dispatchAgentTool(deps, ctx, call("read_messages", { channel: "general", query: "postgres" })); + expect(found).toContain("Decision 0: use Postgres"); + expect(found).not.toContain("Decision 1"); + expect(dispatchAgentTool(deps, ctx, call("read_messages", { thread_id: threadId, channel: "general" }))).toContain('Pass only one of'); + for (const bad of ["yesterday", "2026-02-30T00:00:00.000Z", "2026-01-01 00:00:00", "2026-01-01T00:00:00+08:00"]) { + expect(dispatchAgentTool(deps, ctx, call("read_messages", { channel: "general", before: bad }))).toContain('"before" must be a message_id from a previous page or a UTC ISO timestamp'); + } + expect(dispatchAgentTool(deps, ctx, call("read_messages", { thread_id: threadId, before: "2026-01-01T00:00:03Z" }))).toContain("Decision 1"); + + // Messages sharing one timestamp still page through completely. + connection.db.prepare("update chat_messages set created_at = '2026-01-01T00:00:00.000Z' where thread_id = ?").run(threadId); + const seen = new Set(); + let cursor: string | undefined; + for (let pageIndex = 0; pageIndex < 5; pageIndex += 1) { + const result = dispatchAgentTool(deps, ctx, call("read_messages", { thread_id: threadId, limit: 4, ...(cursor ? { before: cursor } : {}) })); + for (const match of result.matchAll(/: (Decision \d+)/g)) seen.add(match[1].split(":")[0]); + cursor = /before="([^"]+)"/.exec(result)?.[1]; + if (!cursor) break; + } + expect(seen.size).toBe(15); + connection.close(); + }); +});