import { and, eq, inArray, isNull, type SQL } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; import { channels, issues } from "@paperclipai/db"; import { isUuidLike, parseLabelFilterExpr } from "@paperclipai/shared"; import { badRequest, notFound } from "../../errors.js"; import { assertChannelAccess, buildSqlIssueLabelFilterCondition, canAccessChannel, channelSubtreeCondition, enforceHeadlessScopes, findInaccessibleChannelIds, type DbOrTx, type HeadlessActorContext, } from "../headless-common.js"; import { ensureChannel, normalizeChannelPathOrThrow, } from "../headless-channels.js"; export function buildRunnerChannelActor(input: { companyId: string; agentId: string; agentName?: string | null; agentRole?: string | null; responsibleUserId: string | null; museRuntime?: boolean; externalAuthorizingUserId?: string; }): HeadlessActorContext { const effectiveUserId = input.museRuntime ? (input.externalAuthorizingUserId ?? null) : (input.responsibleUserId ?? null); return { companyId: input.companyId, companyName: "", companyPrefix: "", agentIdentityPolicy: "strict_agent_keys", principalType: "agent", userId: effectiveUserId, agentId: input.agentId, agentName: input.agentName ?? null, agentRole: input.agentRole ?? null, actorProfile: input.agentName ?? null, scopes: null, isInstanceAdmin: false, responsibleUserId: input.responsibleUserId, }; } export async function resolveAccessibleTaskChannelPaths( dbOrTx: DbOrTx, companyId: string, actor: HeadlessActorContext, channelIds: Iterable, ): Promise<{ accessiblePaths: Map; inaccessibleIds: Set }> { const uniqueIds = Array.from( new Set( Array.from(channelIds).filter( (id): id is string => typeof id === "string" && id.length > 0, ), ), ); if (uniqueIds.length === 0) { return { accessiblePaths: new Map(), inaccessibleIds: new Set() }; } const rows = await dbOrTx .select({ id: channels.id, companyId: channels.companyId, path: channels.path, visibility: channels.visibility, createdByUserId: channels.createdByUserId, createdByAgentId: channels.createdByAgentId, }) .from(channels) .where(and(eq(channels.companyId, companyId), inArray(channels.id, uniqueIds))); const inaccessibleList = await findInaccessibleChannelIds( dbOrTx, companyId, actor, rows, ); const inaccessibleIds = new Set(inaccessibleList); const accessiblePaths = new Map(); for (const row of rows) { if (!inaccessibleIds.has(row.id)) { accessiblePaths.set(row.id, row.path); } } return { accessiblePaths, inaccessibleIds }; } export type AuthorizedRunnerTaskChannel = | { kind: "existing"; channel: typeof channels.$inferSelect } | { kind: "ensure_path"; path: string }; export async function authorizeRunnerTaskChannel( tx: DbOrTx, companyId: string, actor: HeadlessActorContext, rawChannel: string, ): Promise { const trimmed = rawChannel.trim(); if (isUuidLike(trimmed)) { const [existing] = await tx .select() .from(channels) .where( and( eq(channels.companyId, companyId), eq(channels.id, trimmed), isNull(channels.archivedAt), ), ) .limit(1); if (!existing) { throw notFound(`Channel '${trimmed}' not found`); } await assertChannelAccess(tx, existing, actor); return { kind: "existing", channel: existing }; } const normalized = normalizeChannelPathOrThrow(trimmed, { allowSubtreePrefix: false, }); enforceHeadlessScopes(actor, { channelPath: normalized.path }); const [existing] = await tx .select() .from(channels) .where(and(eq(channels.companyId, companyId), eq(channels.path, normalized.path))) .limit(1); if (existing) { if (existing.archivedAt) { throw badRequest(`Channel '${existing.path}' is archived`, { error: "channel_archived", code: "channel_archived", }); } await assertChannelAccess(tx, existing, actor); return { kind: "existing", channel: existing }; } const parts = normalized.path.split("/"); if (parts.length > 1) { const ancestorPaths: string[] = []; for (let i = 1; i < parts.length; i += 1) { ancestorPaths.push(parts.slice(0, i).join("/")); } const ancestors = await tx .select() .from(channels) .where( and( eq(channels.companyId, companyId), inArray(channels.path, ancestorPaths), isNull(channels.archivedAt), ), ); for (const anc of ancestors) { if (anc.visibility === "private") { await assertChannelAccess(tx, anc, actor); } } } return { kind: "ensure_path", path: normalized.path }; } export async function materializeRunnerTaskChannel( tx: DbOrTx, companyId: string, actor: HeadlessActorContext, authorized: AuthorizedRunnerTaskChannel, ): Promise { if (authorized.kind === "existing") { return authorized.channel; } return ensureChannel(tx, companyId, actor, { path: authorized.path }); } export async function resolveRunnerSearchChannelIds( db: Db, companyId: string, actor: HeadlessActorContext, rawChannel: unknown, ): Promise { if (typeof rawChannel !== "string") { throw badRequest("channel must be a string", { error: "invalid_channel_path", code: "invalid_channel_path", }); } const trimmed = rawChannel.trim(); if (!trimmed || trimmed.length > 140) { throw badRequest("channel must be between 1 and 140 characters", { error: "invalid_channel_path", code: "invalid_channel_path", }); } if (isUuidLike(trimmed)) { const [row] = await db .select() .from(channels) .where( and( eq(channels.companyId, companyId), eq(channels.id, trimmed), isNull(channels.archivedAt), ), ) .limit(1); if (!row) return []; try { enforceHeadlessScopes(actor, { channelPath: row.path }); } catch { return []; } return (await canAccessChannel(db, row, actor)) ? [row.id] : []; } const normalizedInput = trimmed.endsWith("/*") ? `${trimmed.slice(0, -2)}/` : trimmed; const normalized = normalizeChannelPathOrThrow(normalizedInput, { allowSubtreePrefix: true, }); const matched = await db .select() .from(channels) .where( and( eq(channels.companyId, companyId), isNull(channels.archivedAt), normalized.isSubtreePrefix ? channelSubtreeCondition(normalized.path) : eq(channels.path, normalized.path), ), ); const accessibleIds: string[] = []; for (const ch of matched) { try { enforceHeadlessScopes(actor, { channelPath: ch.path }); } catch { continue; } if (await canAccessChannel(db, ch, actor)) { accessibleIds.push(ch.id); } } return accessibleIds; } export async function resolveRunnerTaskSearchFilters( db: Db, companyId: string, actor: HeadlessActorContext, baseReadCondition: SQL, input: { labelFilter?: unknown; channel?: unknown; query?: string }, ): Promise< | { empty: true } | { empty: false; readCondition: SQL; includeChannelScope: boolean; } > { let labelFilterCondition: SQL | null = null; if (input.labelFilter !== undefined && input.labelFilter !== null) { if (typeof input.labelFilter !== "string" || input.labelFilter.length > 256) { throw badRequest("labelFilter must be a string of at most 256 characters", { error: "invalid_label_filter", code: "invalid_label_filter", }); } let parsedLabelExpr; try { parsedLabelExpr = parseLabelFilterExpr(input.labelFilter); } catch (err) { throw badRequest( err instanceof Error ? err.message : `Invalid labelFilter '${input.labelFilter}'`, { error: "invalid_label_filter", code: "invalid_label_filter" }, ); } labelFilterCondition = buildSqlIssueLabelFilterCondition(parsedLabelExpr); } let channelFilterIds: string[] | null = null; if (input.channel !== undefined && input.channel !== null) { channelFilterIds = await resolveRunnerSearchChannelIds( db, companyId, actor, input.channel, ); if (channelFilterIds.length === 0) { return { empty: true }; } } const includeChannelScope = Boolean( channelFilterIds || labelFilterCondition || input.query?.trim(), ); const readCondition = and( baseReadCondition, ...(includeChannelScope ? [isNull(issues.conversationAgentId)] : []), ...(labelFilterCondition ? [labelFilterCondition] : []), ...(channelFilterIds ? [inArray(issues.channelId, channelFilterIds)] : []), ) as SQL; return { empty: false, readCondition, includeChannelScope }; }