Skip to content
← Public packages

@kody/agent-mail

AgentMail inboxes for agents: create/list inboxes, messages, threads, and Svix webhook ingress.

src/list-threads.ts

47 lines · 1.7 KB · TypeScript
import { agentMailRequest, clean, encodePathSegment } from './core.ts'

export type ListThreadsInput = {
	/** When set, list threads for this inbox; otherwise list org-scoped threads. */
	inboxId?: string
	limit?: number
	pageToken?: string
	ascending?: boolean
}

/**
 * List AgentMail threads for an inbox or the whole organization.
 * Read-only; uses GET /v0/inboxes/{inbox_id}/threads or GET /v0/threads.
 *
 * @param input.inboxId - Optional inbox id to scope the list
 * @param input.limit - Max items to return
 * @param input.pageToken - Pagination cursor
 * @param input.ascending - Sort ascending when true
 * @returns Thread list payload from AgentMail
 *
 * @example
 * import listThreads from 'kody:@kody/agent-mail/list-threads'
 * const { threads } = await listThreads({ inboxId: 'inbox_123', limit: 10 })
 */
export default async function listThreads(input: ListThreadsInput = {}) {
	const query: Record<string, unknown> = {}
	if (input.limit !== undefined && input.limit !== null) query.limit = Number(input.limit)
	if (clean(input.pageToken)) query.page_token = clean(input.pageToken)
	if (input.ascending !== undefined) query.ascending = Boolean(input.ascending)

	const path = clean(input.inboxId)
		? `/v0/inboxes/${encodePathSegment(input.inboxId, 'inboxId')}/threads`
		: '/v0/threads'

	const result = (await agentMailRequest({
		path,
		query,
		label: 'AgentMail list threads',
	})) as { threads?: unknown[]; count?: number; next_page_token?: string }

	return {
		inboxId: clean(input.inboxId) || null,
		count: result.count ?? (Array.isArray(result.threads) ? result.threads.length : 0),
		threads: Array.isArray(result.threads) ? result.threads : [],
		nextPageToken: result.next_page_token ?? null,
	}
}