Q12: read_messages reads threads, pages back, and searches

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
ZacharyZhang-NYandClaude Opus 5.5 committed 2026-10-08 03:59:00 -04:00
1 parent 22632a4695
commit f15e47eda1
4 files changed
+138 -29

No files matched your search

+72 -26
View File
@@ -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 };
}
+5 -2
View File
@@ -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: [],
},