Files
PaperClipAI/server/src/services/work-interview.ts
T

115 lines
6.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { isDeepStrictEqual } from "node:util";
import { and, eq, sql } from "drizzle-orm";
import { authUsers, issueThreadInteractions, userCompanyPreferences, type Db, type issues } from "@paperclipai/db";
import { questionSetToAskUserQuestionsPayload, type AskUserQuestionsAnswer, type AskUserQuestionsInteraction, type AskUserQuestionsResult } from "@paperclipai/shared";
import { forbidden, unprocessable } from "../errors.js";
import { interviewSearchProvider, searchPublicWork } from "./work-interview-search.js";
import { persistActivity } from "./activity-log.js";
export const WORK_PROFILE_CHAT = "work_profile_chat";
export function isWorkInterviewChat(kind: string) {
return kind === "onboarding_chat" || kind === WORK_PROFILE_CHAT;
}
const WORK_LOOKUP_KEY = "work-lookup:";
const WORK_PROFILE_KEY = "work-profile:";
const profileLimit = 3000;
export function workInterviewCard(key: string | null | undefined) {
if (key?.startsWith(WORK_LOOKUP_KEY)) return "lookup";
if (key?.startsWith(WORK_PROFILE_KEY)) return "profile";
return null;
}
export function interviewQuestionPayload(kind: "lookup" | "profile", draft?: string | null) {
if (kind === "lookup") {
const provider = interviewSearchProvider();
return questionSetToAskUserQuestionsPayload({
schema: "paperclip.question_set.v1",
title: "How would you like to start?",
questions: [{
id: "work_lookup", prompt: provider ? `May I send your signup email and name to ${provider.name} for a public search about your work?`
: "May I use your signup email and name with my available web search tools to look up your work?",
answerMode: "single_select", required: true, options: [
{ id: "lookup", label: "Look up my work" },
{ id: "manual", label: "I’ll tell you about my work" },
],
}],
});
}
return questionSetToAskUserQuestionsPayload({
schema: "paperclip.question_set.v1", title: "Review your work profile", submitLabel: "Save profile",
questions: [{
id: "work_profile", prompt: "What should your agents remember about your work in this company?",
helpText: "Edit the summary before saving. Clear the text to remove your saved profile, or cancel to keep it as it is.",
answerMode: "text", required: false, initialText: (draft ?? "").slice(0, profileLimit),
textValidation: { maxLength: profileLimit },
}],
});
}
export async function readWorkProfile(db: Db, companyId: string, userId: string) {
const [row] = await db.select({ profile: userCompanyPreferences.workProfile }).from(userCompanyPreferences)
.where(and(eq(userCompanyPreferences.companyId, companyId), eq(userCompanyPreferences.userId, userId)));
return row?.profile ?? null;
}
// Called only inside the winning answer transaction, using the locked chat, the
// resolver's identity and the server-rendered form. Signed-in identity never
// appears on an unanswered form or a manual-interview receipt.
export async function applyWorkInterviewAnswer(db: Db, input: {
kind: "lookup" | "profile"; companyId: string; userId: string;
ownerUserId: string | null; agentId: string | null; createdByAgentId: string | null;
answers: AskUserQuestionsAnswer[];
}) {
if (input.ownerUserId !== input.userId || !input.agentId || input.createdByAgentId !== input.agentId) {
throw forbidden("Only the owner of this private chat can answer the work interview");
}
if (input.kind !== "profile") return;
const answer = input.answers.find(entry => entry.questionId === "work_profile");
// An intentionally blank field clears the profile. A missing answer can
// also come from an old client that never rendered the editable field.
if (!answer) throw unprocessable("Submit the work profile field or cancel the review");
const profile = answer.otherText?.trim() || null;
if (profile && profile.length > profileLimit) throw unprocessable("Work profile is too long");
await db.insert(userCompanyPreferences).values({ companyId: input.companyId, userId: input.userId, workProfile: profile })
.onConflictDoUpdate({
target: [userCompanyPreferences.companyId, userCompanyPreferences.userId],
set: { workProfile: profile, updatedAt: new Date() },
});
await persistActivity(db, {
companyId: input.companyId, actorType: "user", actorId: input.userId, action: profile ? "work_profile.saved" : "work_profile.cleared",
entityType: "user_preference", entityId: input.userId,
});
}
async function researchWorkForAnswer(db: Db, userId: string): Promise<NonNullable<AskUserQuestionsResult["workLookup"]>> {
const provider = interviewSearchProvider();
const [identity] = await db.select({ name: authUsers.name, email: authUsers.email }).from(authUsers)
.where(eq(authUsers.id, userId));
if (!identity?.email) return { kind: "unavailable", text: "No signup email is available. Continue the manual interview." };
if (!provider) return { kind: "signup_identity", text: JSON.stringify(identity) };
const evidence = await searchPublicWork(identity, provider);
return evidence ? { kind: "sources", text: evidence }
: { kind: "unavailable", text: "No usable public sources were returned. Continue the manual interview." };
}
// The question outbox owns the delivery lease. A lost race to a manual answer
// never sends an email. A retry after evidence was saved reuses the receipt.
export async function completeInterviewLookup(db: Db, issue: typeof issues.$inferSelect, card: AskUserQuestionsInteraction) {
const result = card.result;
if (!result || result.workLookup || card.status !== "answered" || !issue.conversationUserId
|| issue.companyId !== card.companyId || issue.id !== card.issueId || !isWorkInterviewChat(issue.originKind)
|| issue.visibility !== "private" || issue.originId !== issue.conversationUserId
|| issue.conversationUserId !== card.resolvedByUserId || card.resolvedByAgentId || card.resolvedByRunId
|| !issue.conversationAgentId || issue.conversationAgentId !== card.createdByAgentId
|| !result.answers.some(a => a.questionId === "work_lookup" && a.optionIds.includes("lookup"))) return;
const sameProvider = isDeepStrictEqual(card.payload.questionSet, interviewQuestionPayload("lookup").questionSet);
const evidence = sameProvider ? await researchWorkForAnswer(db, issue.conversationUserId)
: { kind: "unavailable" as const, text: "The search provider changed. Continue the interview manually or offer a new lookup." };
await db.update(issueThreadInteractions).set({ result: { ...result, workLookup: evidence } })
.where(and(eq(issueThreadInteractions.id, card.id), eq(issueThreadInteractions.companyId, card.companyId),
eq(issueThreadInteractions.status, "answered"), sql`${issueThreadInteractions.result}->'workLookup' is null`));
}