feat: add AI agent workspace (#3062)

* chore(ai): remove local AI store now that providers live server-side

The Zustand-based useAIStore has been replaced by the server-side
aiProviders oRPC router (encrypted credentials persisted in DB).
Delete the dead store + tests, drop the ./store export, and remove
zustand/immer deps which are no longer referenced anywhere in
packages/ai/src/.

* feat(agent): archive/delete actions and read-only state for agent threads

- Backend: mark archived threads as read-only in threads.get and reject
  messages.send with CONFLICT when the thread is archived.
- Frontend: render archived threads in the sidebar with muted styling and
  an Archived badge; add a per-thread dropdown menu in the chat header
  with Archive (non-destructive) and Delete (with confirmation); show a
  read-only banner above the message list that disambiguates archived
  vs. missing-resource causes; suppress the Retry and Stop buttons in
  read-only mode.
- Tests: new packages/api/src/services/agent.test.ts covering the
  archived-thread isReadOnly flag and the archived-thread send refusal.

* fix(agent): abort run on archive and verify ownership before deleting thread

- threads.archive: before flipping status, abort any in-flight run controller
  and clear the active-run state on the thread; cleanup failures are logged
  but do not block the status update.
- threads.delete: assert thread ownership via getThread before destructive
  work so an authenticated user cannot wipe another user's attachment rows
  by passing a foreign threadId.

Adds focused tests for both behaviors.

* feat(agent): display patch diffs and surface revert conflicts

Render apply_resume_patch tool messages with a status-aware card (applied/
reverted/conflicted), expandable operation list, and a Revert button that
correctly handles RESUME_VERSION_CONFLICT responses. Adds unit tests for
the inverse-patch builder and the agentService.actions.revert flow.

* chore(agent): remove out-of-scope attachment tests accidentally added in Task 6

The Task 6 commit (73ef1acca) accidentally re-introduced three attachment-
related tests that belong to a separate task:

- `buildAttachmentModelParts > converts text, image, supported binary, and
  unsupported attachments into model parts`
- `agentService.messages.send > persists the user message with file UI parts
  and links selected attachments to it` (was failing — the `ToolLoopAgent`
  mock is not callable as a constructor)
- `agentService.messages.send > rejects attachments that are missing, foreign,
  or already linked before persisting a message`

These were likely re-added during a stash recovery and were not requested
for Task 6, whose scope was limited to the `agentService.actions.revert`
flow. Remove them along with the helpers/fixtures (`buildAttachment`,
`buildActiveThread`, `selectWhereResult`, `selectOrderByResult`) that they
were the only consumers of. `selectLimitResult` is preserved because it is
used by the revert tests.

* chore(agent): configure runtime dependencies

* feat(db): add agent workspace schema

* feat(api): add agent backend services

* feat(web): add agent workspace UI

* chore(agent): remove legacy builder assistant

* test(agent): make agent stream mocks constructible

* chore(web): remove unused resume replacement hook

* feat(api): add unsafe AI base URL flag

* chore(dev): expose local services in compose

* fix(web): normalize resume preview gaps

* feat(api): improve agent tool handling

* feat(web): polish agent workspace UI

* chore: update dependencies

* fix(api,web): address PR review feedback for agent workspace

Security/correctness:
- Restrict AI provider URLs to http/https even in unsafe mode
- Stop exposing Redis on host network by default
- Make .env.local optional and drop app profile in compose.dev.yml
- Store agent attachments with private ACL on S3
- Reset provider test status when provider/model/baseURL changes
- Decouple non-agent AI endpoints from REDIS_URL requirement
- Fix JSON Patch add inverse for existing object members
- Wrap resume patch + agent action insert in db transaction
- Validate partialMessage at runtime and rate-limit attachment uploads
- Add unique index on agent_messages (thread_id, sequence)

UX/bugs:
- Mark agent thread route as ssr: false and guard SSE chunk parsing
- Show config-specific banner only on known configuration error
- Gate AI provider checks behind loading state in resume import
- Fix relative-time formatter blank gap between 45-59 seconds
- Clarify thread delete confirmation message

Polish:
- Raise ENCRYPTION_SECRET minimum to 32 characters
- Bucket AI rate limits by resumeId/threadId/messageId
- Trim form values before submitting AI provider config
- Use single key identifier and nullish-coalesce baseURL display

* fix: address ai agent review feedback

* fix: preserve mobile agent chat state

* docs: add ai agent workspace guides

* feat: introduce design system for Reactive Resume
This commit is contained in:
Amruth Pillai
2026-05-14 15:00:04 +02:00
committed by GitHub
parent 22c60c64b6
commit 6d8d8f6e55
115 changed files with 15623 additions and 2123 deletions
+287
View File
@@ -0,0 +1,287 @@
import type { UIMessage } from "ai";
import { ORPCError } from "@orpc/client";
import z from "zod";
import { protectedProcedure } from "../context";
import { aiRequestRateLimit, storageUploadRateLimit } from "../middleware/rate-limit";
import { agentService } from "../services/agent";
function isAgentEnvironmentUnavailable(error: unknown) {
return error instanceof Error && error.message === "AGENT_ENVIRONMENT_UNAVAILABLE";
}
function throwUnavailable(): never {
throw new ORPCError("PRECONDITION_FAILED", {
message: "AI agent workspace is unavailable because REDIS_URL or ENCRYPTION_SECRET is not configured.",
});
}
function base64ToUint8Array(value: string) {
return Uint8Array.from(Buffer.from(value, "base64"));
}
function isUiMessage(value: unknown): value is UIMessage {
if (!value || typeof value !== "object") return false;
const message = value as Partial<UIMessage>;
return (
typeof message.id === "string" &&
(message.role === "system" || message.role === "user" || message.role === "assistant") &&
Array.isArray(message.parts)
);
}
const threadsRouter = {
list: protectedProcedure
.route({
method: "GET",
path: "/agent/threads",
tags: ["Agent"],
operationId: "listAgentThreads",
summary: "List agent threads",
})
.handler(async ({ context }) => {
try {
return await agentService.threads.list({ userId: context.user.id });
} catch (error) {
if (isAgentEnvironmentUnavailable(error)) throwUnavailable();
throw error;
}
}),
create: protectedProcedure
.route({
method: "POST",
path: "/agent/threads",
tags: ["Agent"],
operationId: "createAgentThread",
summary: "Create agent thread",
})
.input(z.object({ aiProviderId: z.string().optional(), sourceResumeId: z.string().optional() }))
.handler(async ({ context, input }) => {
try {
return await agentService.threads.create({
userId: context.user.id,
locale: context.locale,
...(input.aiProviderId ? { aiProviderId: input.aiProviderId } : {}),
...(input.sourceResumeId ? { sourceResumeId: input.sourceResumeId } : {}),
});
} catch (error) {
if (isAgentEnvironmentUnavailable(error)) throwUnavailable();
throw error;
}
}),
get: protectedProcedure
.route({
method: "GET",
path: "/agent/threads/{id}",
tags: ["Agent"],
operationId: "getAgentThread",
summary: "Get agent thread",
})
.input(z.object({ id: z.string() }))
.handler(async ({ context, input }) => {
try {
return await agentService.threads.get({ id: input.id, userId: context.user.id });
} catch (error) {
if (isAgentEnvironmentUnavailable(error)) throwUnavailable();
throw error;
}
}),
archive: protectedProcedure
.route({
method: "POST",
path: "/agent/threads/{id}/archive",
tags: ["Agent"],
operationId: "archiveAgentThread",
summary: "Archive agent thread",
})
.input(z.object({ id: z.string() }))
.output(z.void())
.handler(async ({ context, input }) => {
try {
await agentService.threads.archive({ id: input.id, userId: context.user.id });
} catch (error) {
if (isAgentEnvironmentUnavailable(error)) throwUnavailable();
throw error;
}
}),
delete: protectedProcedure
.route({
method: "DELETE",
path: "/agent/threads/{id}",
tags: ["Agent"],
operationId: "deleteAgentThread",
summary: "Delete agent thread",
})
.input(z.object({ id: z.string() }))
.output(z.void())
.handler(async ({ context, input }) => {
try {
await agentService.threads.delete({ id: input.id, userId: context.user.id });
} catch (error) {
if (isAgentEnvironmentUnavailable(error)) throwUnavailable();
throw error;
}
}),
};
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: z.custom<UIMessage>(isUiMessage, { message: "Invalid UI message." }),
attachmentIds: z.array(z.string().trim().min(1)).max(10).optional(),
}),
)
.use(aiRequestRateLimit)
.handler(async ({ context, input }) => {
try {
return await agentService.messages.send({
userId: context.user.id,
threadId: input.threadId,
message: input.message,
...(input.attachmentIds ? { attachmentIds: input.attachmentIds } : {}),
});
} catch (error) {
if (isAgentEnvironmentUnavailable(error)) throwUnavailable();
throw error;
}
}),
stop: protectedProcedure
.route({
method: "POST",
path: "/agent/messages/stop",
tags: ["Agent"],
operationId: "stopAgentMessage",
summary: "Stop active agent run",
})
.input(
z.object({
threadId: z.string(),
partialMessage: z.custom<UIMessage>(isUiMessage, { message: "Invalid UI message." }).optional(),
}),
)
.output(z.void())
.handler(async ({ context, input }) => {
try {
await agentService.messages.stop({
userId: context.user.id,
threadId: input.threadId,
...(input.partialMessage ? { partialMessage: input.partialMessage } : {}),
});
} catch (error) {
if (isAgentEnvironmentUnavailable(error)) throwUnavailable();
throw error;
}
}),
resume: protectedProcedure
.route({
method: "GET",
path: "/agent/messages/resume",
tags: ["Agent"],
operationId: "resumeAgentMessages",
summary: "Resume agent message stream",
})
.input(z.object({ threadId: z.string() }))
.handler(async ({ context, input }) => {
try {
return await agentService.messages.resume({ userId: context.user.id, threadId: input.threadId });
} catch (error) {
if (isAgentEnvironmentUnavailable(error)) throwUnavailable();
throw error;
}
}),
};
const attachmentsRouter = {
create: protectedProcedure
.route({
method: "POST",
path: "/agent/attachments",
tags: ["Agent"],
operationId: "createAgentAttachment",
summary: "Create agent attachment",
})
.input(
z.object({
threadId: z.string(),
filename: z.string().trim().min(1),
mediaType: z.string().trim().min(1),
data: z.string().min(1),
}),
)
.use(storageUploadRateLimit)
.handler(async ({ context, input }) => {
try {
return await agentService.attachments.create({
userId: context.user.id,
threadId: input.threadId,
filename: input.filename,
mediaType: input.mediaType,
data: base64ToUint8Array(input.data),
});
} catch (error) {
if (isAgentEnvironmentUnavailable(error)) throwUnavailable();
throw error;
}
}),
delete: protectedProcedure
.route({
method: "DELETE",
path: "/agent/attachments/{id}",
tags: ["Agent"],
operationId: "deleteAgentAttachment",
summary: "Delete agent attachment",
})
.input(z.object({ id: z.string() }))
.output(z.void())
.handler(async ({ context, input }) => {
try {
await agentService.attachments.delete({ id: input.id, userId: context.user.id });
} catch (error) {
if (isAgentEnvironmentUnavailable(error)) throwUnavailable();
throw error;
}
}),
};
const actionsRouter = {
revert: protectedProcedure
.route({
method: "POST",
path: "/agent/actions/{id}/revert",
tags: ["Agent"],
operationId: "revertAgentAction",
summary: "Revert agent action",
})
.input(z.object({ id: z.string() }))
.handler(async ({ context, input }) => {
try {
return await agentService.actions.revert({ id: input.id, userId: context.user.id });
} catch (error) {
if (isAgentEnvironmentUnavailable(error)) throwUnavailable();
throw error;
}
}),
};
export const agentRouter = {
threads: threadsRouter,
messages: messagesRouter,
attachments: attachmentsRouter,
actions: actionsRouter,
};
+185
View File
@@ -0,0 +1,185 @@
import type { AiProviderResponse } from "../services/ai-providers";
import { ORPCError } from "@orpc/client";
import { type } from "@orpc/server";
import z from "zod";
import { aiProviderSchema } from "@reactive-resume/ai/types";
import { protectedProcedure } from "../context";
import { aiRequestRateLimit } from "../middleware/rate-limit";
import { aiProvidersService } from "../services/ai-providers";
const providerInput = z.object({
label: z.string().trim().min(1),
provider: aiProviderSchema,
model: z.string().trim().min(1),
baseURL: z.string().trim().optional().default(""),
apiKey: z.string().trim().min(1),
});
const updateProviderInput = providerInput
.partial()
.extend({ id: z.string(), enabled: z.boolean().optional() })
.refine((input) => Object.keys(input).some((key) => key !== "id"), {
message: "At least one field must be provided.",
});
function isAgentEnvironmentUnavailable(error: unknown) {
return error instanceof Error && error.message === "AGENT_ENVIRONMENT_UNAVAILABLE";
}
function throwUnavailable(): never {
throw new ORPCError("PRECONDITION_FAILED", {
message: "AI agent workspace is unavailable because REDIS_URL or ENCRYPTION_SECRET is not configured.",
});
}
function isInvalidAiBaseUrl(error: unknown) {
return error instanceof Error && error.message === "INVALID_AI_BASE_URL";
}
function throwInvalidProviderConfig(): never {
throw new ORPCError("BAD_REQUEST", { message: "Invalid AI provider configuration." });
}
export const aiProvidersRouter = {
list: protectedProcedure
.route({
method: "GET",
path: "/ai-providers",
tags: ["AI Providers"],
operationId: "listAiProviders",
summary: "List saved AI providers",
description: "Lists saved provider/model/API key combinations for the authenticated user. API keys are redacted.",
})
.output(type<AiProviderResponse[]>())
.errors({
PRECONDITION_FAILED: { message: "AI agent workspace is not configured.", status: 412 },
})
.handler(async ({ context }) => {
try {
return await aiProvidersService.list({ userId: context.user.id });
} catch (error) {
if (isAgentEnvironmentUnavailable(error)) throwUnavailable();
throw error;
}
}),
create: protectedProcedure
.route({
method: "POST",
path: "/ai-providers",
tags: ["AI Providers"],
operationId: "createAiProvider",
summary: "Create saved AI provider",
description: "Stores an encrypted provider/model/API key combination. The key is never returned.",
})
.input(providerInput)
.output(type<AiProviderResponse>())
.errors({
BAD_REQUEST: { message: "Invalid AI provider configuration.", status: 400 },
PRECONDITION_FAILED: { message: "AI agent workspace is not configured.", status: 412 },
})
.handler(async ({ context, input }) => {
try {
return await aiProvidersService.create({
userId: context.user.id,
label: input.label,
provider: input.provider,
model: input.model,
baseURL: input.baseURL,
apiKey: input.apiKey,
});
} catch (error) {
if (isAgentEnvironmentUnavailable(error)) throwUnavailable();
if (isInvalidAiBaseUrl(error)) throwInvalidProviderConfig();
throw error;
}
}),
update: protectedProcedure
.route({
method: "PATCH",
path: "/ai-providers/{id}",
tags: ["AI Providers"],
operationId: "updateAiProvider",
summary: "Update saved AI provider",
description:
"Updates a saved provider/model/API key combination. Updating the key requires retesting before use.",
})
.input(updateProviderInput)
.output(type<AiProviderResponse>())
.errors({
BAD_REQUEST: { message: "Invalid AI provider configuration.", status: 400 },
NOT_FOUND: { message: "AI provider was not found.", status: 404 },
PRECONDITION_FAILED: { message: "AI agent workspace is not configured.", status: 412 },
})
.handler(async ({ context, input }) => {
try {
return await aiProvidersService.update({
id: input.id,
userId: context.user.id,
...(input.label !== undefined ? { label: input.label } : {}),
...(input.provider !== undefined ? { provider: input.provider } : {}),
...(input.model !== undefined ? { model: input.model } : {}),
...(input.baseURL !== undefined ? { baseURL: input.baseURL } : {}),
...(input.apiKey !== undefined ? { apiKey: input.apiKey } : {}),
...(input.enabled !== undefined ? { enabled: input.enabled } : {}),
});
} catch (error) {
if (isAgentEnvironmentUnavailable(error)) throwUnavailable();
if (isInvalidAiBaseUrl(error)) throwInvalidProviderConfig();
throw error;
}
}),
delete: protectedProcedure
.route({
method: "DELETE",
path: "/ai-providers/{id}",
tags: ["AI Providers"],
operationId: "deleteAiProvider",
summary: "Delete saved AI provider",
description: "Deletes a saved provider/model/API key combination.",
})
.input(z.object({ id: z.string() }))
.output(z.void())
.errors({
PRECONDITION_FAILED: { message: "AI agent workspace is not configured.", status: 412 },
})
.handler(async ({ context, input }) => {
try {
await aiProvidersService.delete({ id: input.id, userId: context.user.id });
} catch (error) {
if (isAgentEnvironmentUnavailable(error)) throwUnavailable();
throw error;
}
}),
test: protectedProcedure
.route({
method: "POST",
path: "/ai-providers/{id}/test",
tags: ["AI Providers"],
operationId: "testAiProvider",
summary: "Test saved AI provider",
description: "Decrypts the saved API key server-side and validates the provider/model connection.",
})
.input(z.object({ id: z.string() }))
.output(type<AiProviderResponse>())
.use(aiRequestRateLimit)
.errors({
BAD_REQUEST: { message: "Invalid AI provider configuration.", status: 400 },
BAD_GATEWAY: { message: "The AI provider returned an error or is unreachable.", status: 502 },
NOT_FOUND: { message: "AI provider was not found.", status: 404 },
PRECONDITION_FAILED: { message: "AI agent workspace is not configured.", status: 412 },
})
.handler(async ({ context, input }) => {
try {
return await aiProvidersService.test({ id: input.id, userId: context.user.id });
} catch (error) {
if (isAgentEnvironmentUnavailable(error)) throwUnavailable();
if (isInvalidAiBaseUrl(error)) throwInvalidProviderConfig();
if (error instanceof ORPCError) throw error;
throw new ORPCError("BAD_GATEWAY", { message: "Could not reach the AI provider." });
}
}),
};
+75 -54
View File
@@ -5,14 +5,12 @@ import { type } from "@orpc/server";
import { AISDKError } from "ai";
import { flattenError, ZodError, z } from "zod";
import { storedResumeAnalysisSchema } from "@reactive-resume/schema/resume/analysis";
import { resumeDataSchema } from "@reactive-resume/schema/resume/data";
import { protectedProcedure } from "../context";
import { aiRequestRateLimit } from "../middleware/rate-limit";
import { aiCredentialsSchema, aiService, fileInputSchema } from "../services/ai";
import { aiService, fileInputSchema } from "../services/ai";
import { aiProvidersService } from "../services/ai-providers";
import { resumeService } from "../services/resume";
type AIProvider = z.infer<typeof aiCredentialsSchema.shape.provider>;
function isInvalidAiBaseUrlError(error: unknown): boolean {
return error instanceof Error && error.message === "INVALID_AI_BASE_URL";
}
@@ -21,6 +19,10 @@ function isAiProviderGatewayError(error: unknown): boolean {
return error instanceof AISDKError;
}
function isCredentialEncryptionUnavailable(error: unknown): boolean {
return error instanceof Error && error.message === "AI_CREDENTIAL_ENCRYPTION_UNAVAILABLE";
}
function throwAiProviderGatewayError(): never {
throw new ORPCError("BAD_GATEWAY", { message: "Could not reach the AI provider." });
}
@@ -29,6 +31,12 @@ function throwAiProviderConfigError(): never {
throw new ORPCError("BAD_REQUEST", { message: "Invalid AI provider configuration." });
}
function throwCredentialEncryptionUnavailable(): never {
throw new ORPCError("PRECONDITION_FAILED", {
message: "AI providers are unavailable because ENCRYPTION_SECRET is not configured.",
});
}
function throwResumeStructureError(error: ZodError): never {
throw new ORPCError("BAD_REQUEST", {
message: "Invalid resume data structure",
@@ -36,35 +44,17 @@ function throwResumeStructureError(error: ZodError): never {
});
}
export const aiRouter = {
testConnection: protectedProcedure
.route({
method: "POST",
path: "/ai/test-connection",
tags: ["AI"],
operationId: "testAiConnection",
summary: "Test AI provider connection",
description:
"Validates the connection to an AI provider by sending a simple test prompt. Requires the provider type, model name, API key, and an optional base URL. Supported providers: OpenAI, Anthropic, Google Gemini, Ollama, OpenRouter, and Vercel AI Gateway. Requires authentication.",
successDescription: "The AI provider connection was successful.",
})
.input(z.object({ ...aiCredentialsSchema.shape }))
.use(aiRequestRateLimit)
.errors({
BAD_GATEWAY: { message: "The AI provider returned an error or is unreachable.", status: 502 },
BAD_REQUEST: { message: "Invalid AI provider configuration.", status: 400 },
})
.handler(async ({ input }) => {
try {
return await aiService.testConnection(input);
} catch (error) {
console.error(error);
if (isInvalidAiBaseUrlError(error)) throwAiProviderConfigError();
if (isAiProviderGatewayError(error)) throwAiProviderGatewayError();
throw error;
}
}),
async function getRunnableProvider(userId: string, aiProviderId?: string) {
const provider = aiProviderId
? await aiProvidersService.getRunnableById({ id: aiProviderId, userId })
: await aiProvidersService.getDefaultRunnable({ userId });
if (!provider) throw new ORPCError("BAD_REQUEST", { message: "No tested AI provider is available." });
return provider;
}
export const aiRouter = {
parsePdf: protectedProcedure
.route({
method: "POST",
@@ -76,16 +66,24 @@ export const aiRouter = {
"Extracts structured resume data from a PDF file using the specified AI provider. The file should be sent as a base64-encoded string along with AI provider credentials. Returns a complete ResumeData object. Requires authentication.",
successDescription: "The PDF was successfully parsed into structured resume data.",
})
.input(z.object({ ...aiCredentialsSchema.shape, file: fileInputSchema }))
.input(z.object({ aiProviderId: z.string().optional(), file: fileInputSchema }))
.use(aiRequestRateLimit)
.errors({
BAD_GATEWAY: { message: "The AI provider returned an error or is unreachable.", status: 502 },
BAD_REQUEST: { message: "The AI returned an improperly formatted structure.", status: 400 },
})
.handler(async ({ input }): Promise<ResumeData> => {
.handler(async ({ context, input }): Promise<ResumeData> => {
try {
return await aiService.parsePdf(input);
const provider = await getRunnableProvider(context.user.id, input.aiProviderId);
return await aiService.parsePdf({
provider: provider.provider,
model: provider.model,
apiKey: provider.apiKey,
baseURL: provider.baseURL ?? "",
file: input.file,
});
} catch (error) {
if (isCredentialEncryptionUnavailable(error)) throwCredentialEncryptionUnavailable();
if (isInvalidAiBaseUrlError(error)) throwAiProviderConfigError();
if (isAiProviderGatewayError(error)) throwAiProviderGatewayError();
if (error instanceof ZodError) throwResumeStructureError(error);
@@ -106,7 +104,7 @@ export const aiRouter = {
})
.input(
z.object({
...aiCredentialsSchema.shape,
aiProviderId: z.string().optional(),
file: fileInputSchema,
mediaType: z.enum([
"application/msword",
@@ -119,10 +117,19 @@ export const aiRouter = {
BAD_GATEWAY: { message: "The AI provider returned an error or is unreachable.", status: 502 },
BAD_REQUEST: { message: "The AI returned an improperly formatted structure.", status: 400 },
})
.handler(async ({ input }) => {
.handler(async ({ context, input }) => {
try {
return await aiService.parseDocx(input);
const provider = await getRunnableProvider(context.user.id, input.aiProviderId);
return await aiService.parseDocx({
provider: provider.provider,
model: provider.model,
apiKey: provider.apiKey,
baseURL: provider.baseURL ?? "",
mediaType: input.mediaType,
file: input.file,
});
} catch (error) {
if (isCredentialEncryptionUnavailable(error)) throwCredentialEncryptionUnavailable();
if (isInvalidAiBaseUrlError(error)) throwAiProviderConfigError();
if (isAiProviderGatewayError(error)) throwAiProviderGatewayError();
if (error instanceof ZodError) throwResumeStructureError(error);
@@ -142,20 +149,30 @@ export const aiRouter = {
})
.input(
type<{
provider: AIProvider;
model: string;
apiKey: string;
baseURL: string;
aiProviderId?: string;
messages: UIMessage[];
resumeData: ResumeData;
resumeUpdatedAt: Date;
resumeId: string;
}>(),
)
.use(aiRequestRateLimit)
.handler(async ({ input }) => {
.handler(async ({ context, input }) => {
try {
return await aiService.chat(input);
const [provider, resume] = await Promise.all([
getRunnableProvider(context.user.id, input.aiProviderId),
resumeService.getById({ id: input.resumeId, userId: context.user.id }),
]);
return await aiService.chat({
provider: provider.provider,
model: provider.model,
apiKey: provider.apiKey,
baseURL: provider.baseURL ?? "",
messages: input.messages,
resumeData: resume.data,
resumeUpdatedAt: resume.updatedAt,
});
} catch (error) {
if (isCredentialEncryptionUnavailable(error)) throwCredentialEncryptionUnavailable();
if (isInvalidAiBaseUrlError(error)) throwAiProviderConfigError();
if (isAiProviderGatewayError(error)) throwAiProviderGatewayError();
throw error;
@@ -175,9 +192,8 @@ export const aiRouter = {
})
.input(
z.object({
...aiCredentialsSchema.shape,
aiProviderId: z.string().optional(),
resumeId: z.string(),
resumeData: resumeDataSchema,
}),
)
.use(aiRequestRateLimit)
@@ -188,12 +204,16 @@ export const aiRouter = {
})
.handler(async ({ context, input }) => {
try {
const [provider, resume] = await Promise.all([
getRunnableProvider(context.user.id, input.aiProviderId),
resumeService.getById({ id: input.resumeId, userId: context.user.id }),
]);
const analysis = await aiService.analyzeResume({
provider: input.provider,
model: input.model,
apiKey: input.apiKey,
baseURL: input.baseURL,
resumeData: input.resumeData,
provider: provider.provider,
model: provider.model,
apiKey: provider.apiKey,
baseURL: provider.baseURL ?? "",
resumeData: resume.data,
});
return await resumeService.analysis.upsert({
@@ -202,10 +222,11 @@ export const aiRouter = {
analysis: {
...analysis,
updatedAt: new Date(),
modelMeta: { provider: input.provider, model: input.model },
modelMeta: { provider: provider.provider, model: provider.model },
},
});
} catch (error) {
if (isCredentialEncryptionUnavailable(error)) throwCredentialEncryptionUnavailable();
if (isInvalidAiBaseUrlError(error)) throwAiProviderConfigError();
if (isAiProviderGatewayError(error)) throwAiProviderGatewayError();
if (error instanceof ZodError) {
+4
View File
@@ -1,4 +1,6 @@
import { agentRouter } from "./agent";
import { aiRouter } from "./ai";
import { aiProvidersRouter } from "./ai-providers";
import { authRouter } from "./auth";
import { flagsRouter } from "./flags";
import { resumeRouter } from "./resume";
@@ -7,6 +9,8 @@ import { storageRouter } from "./storage";
export default {
ai: aiRouter,
aiProviders: aiProvidersRouter,
agent: agentRouter,
auth: authRouter,
flags: flagsRouter,
resume: resumeRouter,