Skip to content

A one-of-a-kind resume builder that keeps your privacy in mind. Completely secure, customizable, portable, open-source and free forever. Try it out today!

5.2 KB
Raw Blame
import { eventIterator } from "@orpc/server";
import z from "zod";
import { workspaceTabSchema } from "@reactive-resume/schema/career";
import { protectedProcedure } from "../../context";
import { uiMessageSchema } from "../../dto/agent";
import { aiRequestRateLimit } from "../../middleware/rate-limit";
import { mapAgentEnvironmentError } from "./routing";
import { agentService } from "./service";

export const messagesRouter = {
	send: protectedProcedure
		.route({
			method: "POST",
			path: "/agent/messages/send",
			tags: ["Agent"],
			operationId: "sendAgentMessage",
			summary: "Send agent message",
		})
		.input(
			z.object({
				threadId: z.string(),
				message: uiMessageSchema,
				attachmentIds: z
					.array(z.string().trim().min(1))
					.max(10)
					.refine((ids) => new Set(ids).size === ids.length, { message: "Attachment IDs must be unique." })
					.optional(),
				// The context chips: leaving one out keeps it out of what's sent.
				context: z
					.object({
						document: z.boolean().optional().describe("Share the open document (on by default)."),
						posting: z.boolean().optional().describe("Share the job posting it's for (on by default)."),
						application: z
							.boolean()
							.optional()
							.describe("Career coach: share the application (or summaries of all of them) and the documents sent."),
						memory: z
							.boolean()
							.optional()
							.describe(
								"Career coach: share switched-on facts, stories and preferences (on by default). Document conversations: let the assistant search shared facts and stories, read-only (off by default).",
							),
						web: z
							.boolean()
							.optional()
							.describe(
								"Career coach: let the coach search public pages through the web search service (off by default).",
							),
						tab: workspaceTabSchema.optional().describe("Career coach: the workspace tab the user is on, as a hint."),
						offerIds: z
							.array(z.string().min(1))
							.max(2)
							.optional()
							.describe("Career coach: saved offers to compare (Plan what to ask)."),
						applicationId: z.string().trim().min(1).max(255).optional(),
					})
					.optional(),
			}),
		)
		.use(aiRequestRateLimit)
		.use(mapAgentEnvironmentError)
		.output(eventIterator(z.string()))
		.handler(({ context, input }) =>
			agentService.messages.send({
				userId: context.user.id,
				nativeSearchFallback: context.reqHeaders.get("x-ai-native-search") === "1",
				deviceTimeZone: context.reqHeaders.get("x-client-timezone") ?? undefined,
				threadId: input.threadId,
				message: input.message,
				...(input.attachmentIds ? { attachmentIds: input.attachmentIds } : {}),
				...(input.context ? { context: input.context } : {}),
			}),
		),

	stop: protectedProcedure
		.route({
			method: "POST",
			path: "/agent/messages/stop",
			tags: ["Agent"],
			operationId: "stopAgentMessage",
			summary: "Stop active agent run",
		})
		.input(
			z.object({
				threadId: z.string(),
				// Deprecated and ignored: partial content now persists server-side via the run's
				// abort path. Kept in the schema for one release so mid-deploy clients still parse.
				partialMessage: uiMessageSchema.optional(),
			}),
		)
		.output(z.void())
		.use(mapAgentEnvironmentError)
		.handler(({ context, input }) =>
			agentService.messages.stop({
				userId: context.user.id,
				threadId: input.threadId,
			}),
		),

	resume: protectedProcedure
		.route({
			method: "GET",
			path: "/agent/messages/resume",
			tags: ["Agent"],
			operationId: "resumeAgentMessages",
			summary: "Resume agent message stream",
		})
		.input(z.object({ threadId: z.string() }))
		.use(mapAgentEnvironmentError)
		.output(eventIterator(z.string()))
		.handler(({ context, input }) =>
			agentService.messages.resume({ userId: context.user.id, threadId: input.threadId }),
		),

	setEditStatus: protectedProcedure
		.route({
			method: "POST",
			path: "/agent/messages/edit-status",
			tags: ["Agent"],
			operationId: "setAgentEditStatus",
			summary: "Record what happened to proposed edits",
			description:
				"Records that proposed edits were accepted, rejected, rewritten by the user, or are pending again (after an undo), so past conversations show their outcome.",
		})
		.input(
			z.object({
				threadId: z.string(),
				messageId: z.string(),
				toolCallId: z.string(),
				edits: z
					.array(
						z.object({
							id: z.string(),
							status: z.enum(["pending", "accepted", "rejected"]),
							text: z
								.string()
								.trim()
								.min(1)
								.max(2_000)
								.optional()
								.describe("The user's own wording for the edit's new text, in plain text, when they rewrote it."),
							after: z
								.string()
								.max(50_000)
								.optional()
								.describe(
									"The edit's new text (after) as the client showed it. When given, the decision is refused if the edit has since been reworded elsewhere; apply it to the document only after this succeeds.",
								),
						}),
					)
					.min(1)
					.max(50),
			}),
		)
		.output(z.object({ editsProposed: z.number(), editsAccepted: z.number() }))
		.use(mapAgentEnvironmentError)
		.handler(({ context, input }) => agentService.messages.setEditStatus({ userId: context.user.id, ...input })),
};