Skip to content

Job application tracker and AI-powered job search assistant. Helps job seekers manage their search journey with AI resume review, job matching, task logging, and application analytics, all while keeping your data private.

feat: agent chat add_job tool and /api/ai/chat route

Khuram Niaz7e1dac2e66c2
diff --git a/__tests__/agentAddJobTool.spec.ts b/__tests__/agentAddJobTool.spec.ts
new file mode 100644
index 0000000..2cf0986
--- /dev/null
+++ b/__tests__/agentAddJobTool.spec.ts
@@ -0,0 +1,108 @@
+import { buildAddJobTool } from "@/lib/agent/tools/addJob";
+import { buildAgentTools } from "@/lib/agent/tools";
+import { createJobFromNames } from "@/lib/jobs/createJobFromNames";
+
+vi.mock("@/lib/jobs/createJobFromNames", () => ({ createJobFromNames: vi.fn() }));
+
+const created = {
+ created: true,
+ jobId: "job-1",
+ resolutions: [{ id: "c1", label: "Acme", created: true }],
+ descriptionCompleteness: "full",
+ message: 'Created Acme; Matched Engineer. Job created (id: job-1).',
+};
+
+const longDescription = Array.from({ length: 200 }, () => "word").join(" ");
+const execute = (tool: any, input: any) => tool.execute(input, { toolCallId: "c", messages: [] });
+
+describe("add_job agent tool", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ (createJobFromNames as any).mockResolvedValue(created);
+ });
+
+ it("requires approval — a mutating tool can never execute unapproved", () => {
+ expect(buildAddJobTool("user-1").needsApproval).toBe(true);
+ });
+
+ it("passes the SESSION userId, never one supplied by the model", async () => {
+ const tool = buildAddJobTool("session-user");
+ await execute(tool, { company: "Acme", jobTitle: "Engineer", jobDescription: longDescription, userId: "attacker-user" });
+ const [, userId] = (createJobFromNames as any).mock.calls[0];
+ expect(userId).toBe("session-user");
+ expect((createJobFromNames as any).mock.calls[0][0].userId).toBeUndefined();
+ });
+
+ it("splices the closure's pasted text over anything the model sent", async () => {
+ const tool = buildAddJobTool("user-1", "THE REAL PASTED POSTING");
+ await execute(tool, { company: "Acme", jobTitle: "Engineer", jobDescription: "a paraphrase the model wrote" });
+ expect((createJobFromNames as any).mock.calls[0][0].jobDescription).toBe("THE REAL PASTED POSTING");
+ });
+
+ it("falls back to the model's description when nothing was pasted", async () => {
+ const tool = buildAddJobTool("user-1");
+ await execute(tool, { company: "Acme", jobTitle: "Engineer", jobDescription: longDescription });
+ expect((createJobFromNames as any).mock.calls[0][0].jobDescription).toBe(longDescription);
+ });
+
+ it('sets createdVia to "chat"', async () => {
+ await execute(buildAddJobTool("user-1", "posting"), { company: "Acme", jobTitle: "Engineer" });
+ expect((createJobFromNames as any).mock.calls[0][0].createdVia).toBe("chat");
+ });
+
+ it("never forwards allowDuplicate, even if the model invents it", async () => {
+ await execute(buildAddJobTool("user-1", "posting"), { company: "Acme", jobTitle: "Engineer", allowDuplicate: true, upsert: true });
+ const passed = (createJobFromNames as any).mock.calls[0][0];
+ expect(passed.allowDuplicate).toBeUndefined();
+ expect(passed.upsert).toBeUndefined();
+ });
+
+ it("returns structured fields and not the helper's agent-facing message", async () => {
+ const result: any = await execute(buildAddJobTool("user-1", "posting"), { company: "Acme", jobTitle: "Engineer" });
+ expect(result).toMatchObject({
+ created: true,
+ jobId: "job-1",
+ descriptionSource: "pasted",
+ descriptionCompleteness: "full",
+ });
+ expect(result.message).toBeUndefined();
+ expect(JSON.stringify(result)).not.toContain("update_job");
+ expect(JSON.stringify(result)).not.toContain("allowDuplicate");
+ });
+
+ it("reports a duplicate without creating a second job", async () => {
+ (createJobFromNames as any).mockResolvedValue({
+ created: false,
+ duplicateOf: { id: "job-9", title: "Engineer", company: "Acme" },
+ resolutions: [],
+ message: 'Duplicate detected — call update_job with jobId "job-9". Pass allowDuplicate: true ...',
+ });
+ const result: any = await execute(buildAddJobTool("user-1", "posting"), { company: "Acme", jobTitle: "Engineer" });
+ expect(result.created).toBe(false);
+ expect(result.duplicateOf.id).toBe("job-9");
+ expect(JSON.stringify(result)).not.toContain("update_job");
+ });
+
+ it("returns a validation message rather than throwing when no description exists", async () => {
+ const result: any = await execute(buildAddJobTool("user-1"), { company: "Acme", jobTitle: "Engineer" });
+ expect(result.validationError).toMatch(/description/i);
+ expect(createJobFromNames).not.toHaveBeenCalled();
+ });
+
+ it("returns a ZodError from the in-execute parse as a tool result, not a throw", async () => {
+ const result: any = await execute(buildAddJobTool("user-1", "posting"), { company: "Acme", jobTitle: "Engineer", dueDate: "next friday" });
+ expect(result.validationError).toMatch(/dueDate/);
+ expect(createJobFromNames).not.toHaveBeenCalled();
+ });
+
+ it("returns a tool result rather than throwing when the helper fails", async () => {
+ (createJobFromNames as any).mockRejectedValue(new Error("db is down"));
+ const result: any = await execute(buildAddJobTool("user-1", "posting"), { company: "Acme", jobTitle: "Engineer" });
+ expect(result.validationError).toBeTruthy();
+ expect(result.validationError).not.toContain("db is down");
+ });
+
+ it("registers exactly one tool in v1", () => {
+ expect(Object.keys(buildAgentTools({ userId: "user-1" }))).toEqual(["add_job"]);
+ });
+});
diff --git a/__tests__/agentChatRoute.spec.ts b/__tests__/agentChatRoute.spec.ts
new file mode 100644
index 0000000..c3977a5
--- /dev/null
+++ b/__tests__/agentChatRoute.spec.ts
@@ -0,0 +1,170 @@
+vi.mock("@/auth", () => ({ auth: vi.fn() }));
+vi.mock("next/server", () => ({
+ NextResponse: {
+ json: (data: unknown, init?: { status?: number }) => ({
+ status: init?.status ?? 200,
+ json: async () => data,
+ }),
+ },
+}));
+vi.mock("@/lib/ai/rate-limiter", () => ({ checkRateLimit: vi.fn() }));
+vi.mock("@/lib/ai/providers", () => ({ getModel: vi.fn() }));
+vi.mock("@/actions/userSettings.actions", () => ({ getUserSettings: vi.fn() }));
+vi.mock("@/actions/agentChat.actions", () => ({ saveChatConversation: vi.fn() }));
+vi.mock("@/lib/agent/tools", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@/lib/agent/tools")>();
+ return { ...actual, buildAgentTools: vi.fn(actual.buildAgentTools) };
+});
+
+const toUIMessageStreamResponse = vi.fn(() => ({ status: 200, __stream: true }));
+const streamText = vi.fn((..._args: any[]) => ({ toUIMessageStreamResponse }));
+const streamArgs = (): any => streamText.mock.calls[0]![0];
+vi.mock("ai", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("ai")>();
+ return { ...actual, streamText: (...args: unknown[]) => streamText(...(args as [])) };
+});
+
+import { POST } from "@/app/api/ai/chat/route";
+import { auth } from "@/auth";
+import { checkRateLimit } from "@/lib/ai/rate-limiter";
+import { getModel } from "@/lib/ai/providers";
+import { getUserSettings } from "@/actions/userSettings.actions";
+import { saveChatConversation } from "@/actions/agentChat.actions";
+import { buildAgentTools } from "@/lib/agent/tools";
+import { APP_CONSTANTS } from "@/lib/constants";
+import { AGENT_PASTE_PART_TYPE } from "@/models/agent.model";
+
+const req = (body: unknown) => ({ json: async () => body }) as any;
+
+const pasteMessage = (text: string) => ({
+ id: "m1",
+ role: "user",
+ parts: [
+ { type: "text", text: "add this job" },
+ { type: AGENT_PASTE_PART_TYPE, id: "p1", data: { id: "p1", text, chars: text.length, truncated: false } },
+ ],
+});
+
+describe("POST /api/ai/chat", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ (auth as any).mockResolvedValue({ user: { id: "user-1" } });
+ (checkRateLimit as any).mockReturnValue({ allowed: true, remaining: 29, resetIn: 60000 });
+ (getUserSettings as any).mockResolvedValue({
+ success: true,
+ data: { settings: { ai: { provider: "ollama", model: "qwen3.5:9b" } } },
+ });
+ (getModel as any).mockResolvedValue({ id: "fake-model" });
+ (saveChatConversation as any).mockResolvedValue({ success: true });
+ });
+
+ it("returns 401 without a session", async () => {
+ (auth as any).mockResolvedValue(null);
+ expect((await POST(req({ messages: [] }))).status).toBe(401);
+ });
+
+ it("returns 429 using the chat bucket, not the shared one", async () => {
+ (checkRateLimit as any).mockReturnValue({ allowed: false, remaining: 0, resetIn: 30000 });
+ expect((await POST(req({ messages: [] }))).status).toBe(429);
+ expect(checkRateLimit).toHaveBeenCalledWith("user-1", "chat");
+ });
+
+ it("returns 400 for a malformed body", async () => {
+ expect((await POST(req({ nope: true }))).status).toBe(400);
+ });
+
+ it("returns 400, not a 500, for messages the SDK cannot convert", async () => {
+ // z.array(z.any()) lets this through; convertToModelMessages rejects on
+ // the unknown role (correction #5), and that is a bad request.
+ const res = await POST(req({ messages: [{ id: "m1", role: "wizard", parts: [{ type: "text", text: "hi" }] }] }));
+ expect(res.status).toBe(400);
+ expect(streamText).not.toHaveBeenCalled();
+ });
+
+ it("returns 503 when the provider credential is missing", async () => {
+ (getModel as any).mockRejectedValue(new Error("Ollama credential not configured"));
+ const res = await POST(req({ messages: [pasteMessage("posting")] }));
+ expect(res.status).toBe(503);
+ });
+
+ it("persists the incoming messages BEFORE calling the model", async () => {
+ const messages = [pasteMessage("the 6kb posting")];
+ await POST(req({ messages }));
+ expect(saveChatConversation).toHaveBeenCalled();
+ const saveOrder = (saveChatConversation as any).mock.invocationCallOrder[0];
+ const streamOrder = streamText.mock.invocationCallOrder[0];
+ expect(saveOrder).toBeLessThan(streamOrder);
+ });
+
+ it("sends only the truncated head to the model, never the full paste", async () => {
+ const posting = "HEAD_MARKER " + "x".repeat(APP_CONSTANTS.AGENT_CHAT_PASTE_HEAD_CHARS) + " TAIL_MARKER";
+ await POST(req({ messages: [pasteMessage(posting)] }));
+ const sent = JSON.stringify(streamArgs().messages);
+ expect(sent).toContain("HEAD_MARKER");
+ expect(sent).not.toContain("TAIL_MARKER");
+ });
+
+ it("hands the FULL pasted text to the tool factory", async () => {
+ const posting = "HEAD_MARKER " + "x".repeat(APP_CONSTANTS.AGENT_CHAT_PASTE_HEAD_CHARS) + " TAIL_MARKER";
+ await POST(req({ messages: [pasteMessage(posting)] }));
+ // The factory is spied (partial module mock above) so the closure's text
+ // is asserted directly — with the previous test, this pins the split:
+ // head to the model, full text to the tool.
+ expect(buildAgentTools).toHaveBeenCalledWith(
+ expect.objectContaining({ userId: "user-1", pastedText: posting }),
+ );
+ expect(Object.keys(streamArgs().tools)).toEqual(["add_job"]);
+ });
+
+ it("configures the loop bounds the design specifies", async () => {
+ await POST(req({ messages: [pasteMessage("posting")] }));
+ const args = streamArgs();
+ expect(args.stopWhen).toHaveLength(2);
+ expect(args.temperature).toBe(0.1);
+ expect(args.abortSignal).toBeDefined();
+ expect(args.providerOptions.ollama.options.num_ctx).toBe(APP_CONSTANTS.AGENT_CHAT_NUM_CTX);
+ });
+
+ it("returns 503 naming Settings when no model is configured, and never guesses one", async () => {
+ (getUserSettings as any).mockResolvedValue({
+ success: true,
+ data: { settings: { ai: { provider: "ollama", model: undefined } } },
+ });
+ const res = await POST(req({ messages: [pasteMessage("posting")] }));
+ expect(res.status).toBe(503);
+ expect((await res.json()).error).toMatch(/settings/i);
+ expect(getModel).not.toHaveBeenCalled();
+ expect(streamText).not.toHaveBeenCalled();
+ });
+
+ it("uses the configured model exactly as configured", async () => {
+ await POST(req({ messages: [pasteMessage("posting")] }));
+ expect(getModel).toHaveBeenCalledWith("ollama", "qwen3.5:9b", "user-1");
+ });
+
+ it("sends at most AGENT_CHAT_HISTORY_MESSAGES to the model", async () => {
+ const many = Array.from({ length: APP_CONSTANTS.AGENT_CHAT_HISTORY_MESSAGES + 10 }, (_, i) => ({
+ id: `m${i}`,
+ role: "user",
+ parts: [{ type: "text", text: `hello ${i}` }],
+ }));
+ await POST(req({ messages: many }));
+ expect(streamArgs().messages.length).toBeLessThanOrEqual(
+ APP_CONSTANTS.AGENT_CHAT_HISTORY_MESSAGES,
+ );
+ });
+
+ it("does not re-inject the paste head on the approval POST", async () => {
+ const messages = [
+ pasteMessage("HEAD_MARKER posting body"),
+ {
+ id: "m2",
+ role: "assistant",
+ parts: [{ type: "tool-add_job", toolCallId: "c1", state: "approval-responded", input: { company: "Acme", jobTitle: "Eng" }, approval: { id: "a1", approved: true } }],
+ },
+ ];
+ await POST(req({ messages }));
+ const sent = JSON.stringify(streamArgs().messages);
+ expect(sent).not.toContain("<<<PASTED_");
+ });
+});
diff --git a/__tests__/api-auth-contract.spec.ts b/__tests__/api-auth-contract.spec.ts
index 676ab40..4b669a6 100644
--- a/__tests__/api-auth-contract.spec.ts
+++ b/__tests__/api-auth-contract.spec.ts
@@ -28,6 +28,7 @@ import {
} from "@/app/api/profile/resume/route";
import { POST as reviewResume } from "@/app/api/ai/resume/review/route";
import { POST as generateCoverLetter } from "@/app/api/ai/cover-letter/route";
+import { POST as agentChat } from "@/app/api/ai/chat/route";
const anonAuth = () => (auth as any).mockResolvedValue(null);
@@ -80,4 +81,9 @@ describe("API auth contract: guarded routes reject anonymous requests", () => {
const res = await generateCoverLetter(req());
expect(res.status).toBe(401);
});
+
+ it("POST /api/ai/chat -> 401", async () => {
+ const res = await agentChat(req());
+ expect(res.status).toBe(401);
+ });
});
diff --git a/src/app/api/ai/chat/route.ts b/src/app/api/ai/chat/route.ts
new file mode 100644
index 0000000..a29e7a0
--- /dev/null
+++ b/src/app/api/ai/chat/route.ts
@@ -0,0 +1,176 @@
+import "server-only";
+
+import { auth } from "@/auth";
+import { NextRequest, NextResponse } from "next/server";
+import {
+ convertToModelMessages,
+ hasToolCall,
+ isToolUIPart,
+ stepCountIs,
+ streamText,
+ type UIMessage,
+} from "ai";
+import { getModel, type ProviderType } from "@/lib/ai/providers";
+import { checkRateLimit } from "@/lib/ai/rate-limiter";
+import { TEMPERATURES } from "@/lib/ai/config";
+import { APP_CONSTANTS } from "@/lib/constants";
+import { AgentChatRequestSchema } from "@/models/agent.schema";
+import { AGENT_CHAT_SYSTEM_PROMPT, buildPasteContextMessage } from "@/lib/agent/prompt";
+import {
+ resolvePastedText,
+ stubConsumedPastes,
+ windowMessages,
+} from "@/lib/agent/paste";
+import { truncateForModel } from "@/lib/agent/paste.server";
+import { buildAgentTools } from "@/lib/agent/tools";
+import { mapAgentError } from "@/lib/agent/errors";
+import { getUserSettings } from "@/actions/userSettings.actions";
+import { saveChatConversation } from "@/actions/agentChat.actions";
+import { AiProvider } from "@/models/ai.model";
+import type { AgentAddJobResult } from "@/models/agent.model";
+
+// One structured line per turn. Sizes and outcomes only — never the pasted
+// posting and never the extracted arguments.
+function logTurn(fields: Record<string, unknown>) {
+ console.info("[agent-chat]", JSON.stringify(fields));
+}
+
+function outcomeOf(message: UIMessage | undefined): {
+ tool: string | null;
+ state: string | null;
+ outcome: string;
+} {
+ for (const part of message?.parts ?? []) {
+ if (!isToolUIPart(part)) continue;
+ const output = part.output as AgentAddJobResult | undefined;
+ const outcome =
+ part.state !== "output-available"
+ ? part.state
+ : output?.validationError
+ ? "validation"
+ : output?.created
+ ? "created"
+ : "duplicate";
+ return { tool: part.type.replace(/^tool-/, ""), state: part.state, outcome };
+ }
+ return { tool: null, state: null, outcome: "none" };
+}
+
+export const POST = async (req: NextRequest) => {
+ const session = await auth();
+ const userId = session?.user?.id;
+ if (!session || !userId) {
+ return NextResponse.json({ error: "Not Authenticated" }, { status: 401 });
+ }
+
+ const rateLimit = checkRateLimit(userId, "chat");
+ if (!rateLimit.allowed) {
+ return NextResponse.json(
+ { error: `Rate limit exceeded. Try again in ${Math.ceil(rateLimit.resetIn / 1000)} seconds.` },
+ { status: 429 },
+ );
+ }
+
+ const parsed = AgentChatRequestSchema.safeParse(await req.json());
+ if (!parsed.success) {
+ return NextResponse.json({ error: "Invalid chat request." }, { status: 400 });
+ }
+
+ const messages = parsed.data.messages as UIMessage[];
+ const { pageContext } = parsed.data;
+
+ // Write-on-receipt. The user's message and the posting they pasted are the
+ // expensive half to reproduce, so they are durable before the model is
+ // called — a reload, an error or a stop() mid-stream cannot lose them.
+ await saveChatConversation(messages);
+
+ const settings = await getUserSettings();
+ const ai = settings?.data?.settings?.ai;
+ // provider is always present — defaultUserSettings supplies it. model is
+ // not, and it is NOT substituted: picking a model the user never chose
+ // turns a knowable configuration error into a mid-stream "model not
+ // found" naming something they never configured.
+ const provider = (ai?.provider ?? AiProvider.OLLAMA) as ProviderType;
+ const modelName = ai?.model;
+ if (!modelName) {
+ return NextResponse.json(
+ { error: "No AI model is configured. Pick one in Settings to use the assistant." },
+ { status: 503 },
+ );
+ }
+ const errorContext = { provider, model: modelName };
+
+ let model;
+ try {
+ model = await getModel(provider, modelName, userId);
+ } catch (error) {
+ return NextResponse.json({ error: mapAgentError(error, errorContext) }, { status: 503 });
+ }
+
+ const pastedText = resolvePastedText(messages);
+
+ // Async in ai@6 (correction #5), and the messages array is client-supplied
+ // — a shape z.array(z.any()) let through can reject the conversion, and
+ // that is a bad request, not a server crash.
+ let modelMessages;
+ try {
+ modelMessages = await convertToModelMessages(windowMessages(messages));
+ } catch {
+ return NextResponse.json({ error: "Invalid chat request." }, { status: 400 });
+ }
+
+ // Injected only on the turn that introduced the paste. On the approval POST
+ // the last message is the assistant's, so nothing is re-injected — and the
+ // full text never reaches the model on any turn.
+ const lastIsUser = messages[messages.length - 1]?.role === "user";
+ if (pastedText && lastIsUser) {
+ const { block } = truncateForModel(pastedText);
+ modelMessages.push({ role: "user", content: buildPasteContextMessage(block) });
+ }
+
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), APP_CONSTANTS.AGENT_CHAT_TIMEOUT_MS);
+
+ const result = streamText({
+ model,
+ system: AGENT_CHAT_SYSTEM_PROMPT,
+ messages: modelMessages,
+ tools: buildAgentTools({ userId, pastedText, pageContext }),
+ // Stop after the write: the result card renders deterministically from
+ // structured fields, so a second generation just to narrate it is 10-30s
+ // of local inference for a sentence that could be wrong.
+ stopWhen: [stepCountIs(APP_CONSTANTS.AGENT_CHAT_MAX_STEPS), hasToolCall("add_job")],
+ // Argument extraction wants determinism.
+ temperature: TEMPERATURES.ANALYSIS,
+ abortSignal: controller.signal,
+ providerOptions: {
+ ollama: { options: { num_ctx: APP_CONSTANTS.AGENT_CHAT_NUM_CTX } },
+ },
+ });
+
+ return result.toUIMessageStreamResponse({
+ originalMessages: messages,
+ onFinish: async ({ messages: finalMessages, responseMessage, isAborted }) => {
+ clearTimeout(timer);
+ const { tool, state, outcome } = outcomeOf(responseMessage);
+ logTurn({
+ provider,
+ model: modelName,
+ tool,
+ toolState: state,
+ outcome,
+ aborted: isAborted,
+ pasteChars: pastedText?.length ?? 0,
+ messageCount: finalMessages.length,
+ });
+ // Stubbing happens here so it lives in exactly one place.
+ await saveChatConversation(stubConsumedPastes(finalMessages));
+ },
+ // NOTE: this signature takes the error directly, unlike streamText's
+ // onError which takes { error }.
+ onError: (error) => {
+ clearTimeout(timer);
+ return mapAgentError(error, errorContext);
+ },
+ });
+};
diff --git a/src/lib/agent/tools/addJob.ts b/src/lib/agent/tools/addJob.ts
new file mode 100644
index 0000000..edb6a88
--- /dev/null
+++ b/src/lib/agent/tools/addJob.ts
@@ -0,0 +1,69 @@
+import { tool } from "ai";
+import { APP_CONSTANTS } from "@/lib/constants";
+import { AGENT_TOOL_DESCRIPTIONS } from "@/lib/agent/prompt";
+import { AgentAddJobParseSchema, AgentAddJobSchema } from "@/models/agent.schema";
+import { createJobFromNames } from "@/lib/jobs/createJobFromNames";
+import type { AgentAddJobResult } from "@/models/agent.model";
+
+const NO_DESCRIPTION = "No job description was supplied. Ask the user to paste the job posting, or to type the role's details, then try again.";
+
+function failed(validationError: string): AgentAddJobResult {
+ return { created: false, resolutions: [], validationError };
+}
+
+/**
+ * userId and pastedText are captured from the route's authenticated session
+ * and message array. Anything with those names inside the model's input is
+ * ignored — this is the IDOR boundary and it has a dedicated test.
+ */
+export function buildAddJobTool(userId: string, pastedText?: string) {
+ return tool({
+ description: AGENT_TOOL_DESCRIPTIONS.add_job,
+ // Date transforms are deferred here so this schema doubles as the JSON
+ // schema the model reads — see src/models/agent.schema.ts.
+ inputSchema: AgentAddJobSchema,
+ needsApproval: true,
+ execute: async (raw): Promise<AgentAddJobResult> => {
+ const parsed = AgentAddJobParseSchema.safeParse(raw);
+ if (!parsed.success) {
+ // Returned, not thrown, so the model can see why and retry.
+ return failed(
+ parsed.error.issues
+ .map((issue) => `${issue.path.join(".") || "input"}: ${issue.message}`)
+ .join("; "),
+ );
+ }
+
+ const input = parsed.data;
+ const jobDescription = pastedText ?? input.jobDescription;
+ if (!jobDescription) return failed(NO_DESCRIPTION);
+
+ try {
+ const result = await createJobFromNames(
+ {
+ ...input,
+ jobDescription,
+ createdVia: APP_CONSTANTS.AGENT_CHAT_CREATED_VIA,
+ },
+ userId,
+ );
+
+ // result.message is deliberately NOT returned: it is MCP-facing
+ // protocol text naming update_job and allowDuplicate, neither of
+ // which this surface exposes. The card composes its own copy.
+ return {
+ created: result.created,
+ jobId: result.jobId,
+ duplicateOf: result.duplicateOf,
+ resolutions: result.resolutions,
+ descriptionSource: pastedText ? "pasted" : "model",
+ descriptionChars: jobDescription.length,
+ descriptionCompleteness: result.descriptionCompleteness,
+ };
+ } catch (error) {
+ console.error("[agent-chat] add_job failed:", error);
+ return failed("Saving the job failed. Try again, or add it from the Jobs page.");
+ }
+ },
+ });
+}
diff --git a/src/lib/agent/tools/index.ts b/src/lib/agent/tools/index.ts
new file mode 100644
index 0000000..eb62a27
--- /dev/null
+++ b/src/lib/agent/tools/index.ts
@@ -0,0 +1,17 @@
+import type { ToolSet } from "ai";
+import type { PageContext } from "@/models/agent.model";
+import { buildAddJobTool } from "./addJob";
+
+// A context object rather than positional args: read tools will need
+// pageContext, and this stops the signature churning when they land.
+export function buildAgentTools(ctx: {
+ userId: string;
+ pastedText?: string;
+ pageContext?: PageContext;
+}): ToolSet {
+ return {
+ add_job: buildAddJobTool(ctx.userId, ctx.pastedText),
+ };
+}
+
+export { buildAddJobTool };