Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/routes/api/system.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ router.get('/status', async (_req, res) => {
}
if (!capabilities) {
warnings.push(`${tenant.name}: the SuperOps schema has not been probed yet. Run the connection test in Settings.`);
} else if (!capabilities.bodyField) {
} else if (!capabilities.bodyField && !capabilities.conversationQuery) {
warnings.push(
`${tenant.name}: no ticket body field was found on this SuperOps schema, so classification uses the subject line only.`,
);
Expand Down
147 changes: 133 additions & 14 deletions src/services/psa/capabilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { createLogger, describeError } from '../../lib/logger';
const log = createLogger('SuperOps:probe');

/** Version stamp — bump to force a re-probe after changing the probe logic. */
export const CAPABILITIES_VERSION = 4;
export const CAPABILITIES_VERSION = 5;

export interface ObjectFieldShape {
/** 'leaf' needs no sub-selection; 'object' does; 'missing' means absent. */
Expand Down Expand Up @@ -56,6 +56,8 @@ export interface PsaCapabilities {
subjectField: string | null;
/** Long-form ticket text — the thing the classifier actually needs. */
bodyField: string | null;
/** When the body field is an object, the scalar inside it holding the text. */
bodySubField: string | null;
statusField: string | null;
priorityField: string | null;
createdField: string | null;
Expand All @@ -70,6 +72,20 @@ export interface PsaCapabilities {
/** Ticket fields only available on the detail query. */
detailOnlyFields: string[];

/**
* Where the ticket text lives when the ticket itself has no body field.
* SuperOps keeps the requester's original message as the first entry of the
* ticket's conversation thread rather than on the ticket.
*/
conversationQuery: string | null;
conversationArgName: string | null;
/** When the argument is an input object, the field inside it holding the ticket id. */
conversationArgIdField: string | null;
/** Field on the payload holding the array; null when the query returns the array itself. */
conversationResultField: string | null;
conversationContentField: string | null;
conversationTimeField: string | null;

/** Root query listing the MSP's clients, so the UI can offer a picker. */
clientListQuery: string | null;
clientListArgName: string | null;
Expand Down Expand Up @@ -150,6 +166,17 @@ const BODY_CANDIDATES = [
'message',
'note',
];
const CONVERSATION_QUERY_CANDIDATES = [
'getTicketConversationList',
'getTicketConversations',
'getConversationList',
'getTicketThreadList',
'getTicketThreads',
'ticketConversations',
];
const CONVERSATION_RESULT_CANDIDATES = ['conversations', 'conversationList', 'threads', 'items', 'data', 'results'];
const CONVERSATION_CONTENT_CANDIDATES = ['content', 'body', 'message', 'text', 'description', 'html', 'htmlContent'];
const CONVERSATION_TIME_CANDIDATES = ['time', 'createdTime', 'createdAt', 'sentTime', 'date', 'timestamp'];
const STATUS_CANDIDATES = ['status', 'ticketStatus', 'state'];
const PRIORITY_CANDIDATES = ['priority', 'ticketPriority', 'urgency'];
const CREATED_CANDIDATES = ['createdTime', 'createdAt', 'createdDate', 'creationTime'];
Expand Down Expand Up @@ -229,6 +256,7 @@ export async function probeCapabilities(
displayIdField: null,
subjectField: null,
bodyField: null,
bodySubField: null,
statusField: null,
priorityField: null,
createdField: null,
Expand All @@ -238,6 +266,12 @@ export async function probeCapabilities(
detailArgName: null,
detailArgIdField: null,
detailOnlyFields: [],
conversationQuery: null,
conversationArgName: null,
conversationArgIdField: null,
conversationResultField: null,
conversationContentField: null,
conversationTimeField: null,
clientListQuery: null,
clientListArgName: null,
clientListResultField: null,
Expand Down Expand Up @@ -355,14 +389,20 @@ export async function probeCapabilities(
const detailFields = (detailType?.fields ?? []).map((f) => f.name);
caps.detailOnlyFields = detailFields.filter((f) => !caps.ticketFields.includes(f));
if (!caps.bodyField) {
caps.bodyField = pickField(detailFields, BODY_CANDIDATES);
await assignBodyField(caps, detailType?.fields ?? [], describeType);
}
}
}

// ─── Conversation thread, where SuperOps keeps the original message ─────────
if (!caps.bodyField) {
await resolveConversation(caps, queryFields, describeType);
}

if (!caps.bodyField && !caps.conversationQuery) {
const seen = caps.ticketFields.length ? ` Ticket fields: ${caps.ticketFields.join(', ')}.` : '';
warnings.push(
`No ticket body field found (looked for: ${BODY_CANDIDATES.slice(0, 5).join(', ')}). Classification will use the subject line only, which measurably reduces accuracy.`,
`No ticket body found — no body field on the ticket (looked for: ${BODY_CANDIDATES.slice(0, 5).join(', ')}) and no conversation query (looked for: ${CONVERSATION_QUERY_CANDIDATES.slice(0, 2).join(', ')}). Classification will use the subject line only, which measurably reduces accuracy.${seen}`,
);
}

Expand Down Expand Up @@ -463,6 +503,95 @@ export async function probeCapabilities(
return caps;
}

/**
* Picks the ticket body: a scalar by a known name, else any scalar whose name
* says description or body, else an object by a known name with a text field
* inside it (selected as `description { content }`).
*/
async function assignBodyField(
caps: PsaCapabilities,
fields: FieldInfo[],
describeType: (name: string) => Promise<TypeResponse['__type']>,
): Promise<void> {
const leaves = fields.filter((f) => isLeafType(f.type)).map((f) => f.name);
const exact = pickField(leaves, BODY_CANDIDATES);
const fuzzy = leaves.find((n) => /description|body/i.test(n) && !/(id|type|format|count)$/i.test(n));
if (exact || fuzzy) {
caps.bodyField = (exact ?? fuzzy)!;
caps.bodySubField = null;
return;
}
const objects = fields.filter((f) => !isLeafType(f.type));
const objectName = pickField(objects.map((f) => f.name), BODY_CANDIDATES);
if (!objectName) return;
const typeName = namedType(objects.find((f) => f.name === objectName)!.type).name;
const type = typeName ? await describeType(typeName) : null;
const inner = pickField(
(type?.fields ?? []).filter((f) => isLeafType(f.type)).map((f) => f.name),
CONVERSATION_CONTENT_CANDIDATES,
);
if (inner) {
caps.bodyField = objectName;
caps.bodySubField = inner;
}
}

/** Finds a per-ticket conversation query and the text and time fields on its entries. */
async function resolveConversation(
caps: PsaCapabilities,
queryFields: FieldInfo[],
describeType: (name: string) => Promise<TypeResponse['__type']>,
): Promise<void> {
const field =
findRootField(queryFields, CONVERSATION_QUERY_CANDIDATES) ??
queryFields.find((f) => /^get\w*ticket\w*(conversation|thread)\w*$/i.test(f.name)) ??
null;
if (!field) return;
const arg = field.args?.[0];
if (!arg) return;

let argIdField: string | null = null;
if (namedType(arg.type).kind === 'INPUT_OBJECT') {
const argTypeName = namedType(arg.type).name;
const argType = argTypeName ? await describeType(argTypeName) : null;
const argFields = (argType?.inputFields ?? []).map((f) => f.name);
argIdField = pickField(argFields, ID_CANDIDATES);
if (!argIdField) return;
}

// Either the query returns the entries directly, or a wrapper holding them.
let resultField: string | null = null;
let entryTypeName = namedType(field.type).name;
if (!isListType(field.type) && entryTypeName) {
const wrapper = await describeType(entryTypeName);
const wrapperFields = wrapper?.fields ?? [];
const arrayField =
wrapperFields.find((f) => CONVERSATION_RESULT_CANDIDATES.includes(f.name)) ??
wrapperFields.find((f) => !isLeafType(f.type) && isListType(f.type));
if (!arrayField) return;
resultField = arrayField.name;
entryTypeName = namedType(arrayField.type).name;
}
const entryType = entryTypeName ? await describeType(entryTypeName) : null;
const scalars = (entryType?.fields ?? []).filter((f) => isLeafType(f.type)).map((f) => f.name);
const content = pickField(scalars, CONVERSATION_CONTENT_CANDIDATES);
if (!content) return;

caps.conversationQuery = field.name;
caps.conversationArgName = arg.name;
caps.conversationArgIdField = argIdField;
caps.conversationResultField = resultField;
caps.conversationContentField = content;
caps.conversationTimeField = pickField(scalars, CONVERSATION_TIME_CANDIDATES);
}

/** Where the ticket text comes from, for the UI. Null when nowhere. */
export function describeBodySource(caps: Pick<PsaCapabilities, 'bodyField' | 'bodySubField' | 'conversationQuery'>): string | null {
if (caps.bodyField) return caps.bodySubField ? `${caps.bodyField}.${caps.bodySubField}` : caps.bodyField;
if (caps.conversationQuery) return `${caps.conversationQuery} (first message)`;
return null;
}

function findRootField(fields: FieldInfo[], candidates: readonly string[]): FieldInfo | null {
const byLower = new Map(fields.map((f) => [f.name.toLowerCase(), f]));
for (const candidate of candidates) {
Expand All @@ -486,17 +615,7 @@ async function assignTicketFields(
caps.priorityField = pickField(names, PRIORITY_CANDIDATES);
caps.createdField = pickField(names, CREATED_CANDIDATES);

// Only accept a body field whose type is a leaf — a nested object here would
// need a sub-selection we cannot guess, and the AI wants plain text anyway.
const bodyName = pickField(names, BODY_CANDIDATES);
if (bodyName) {
const field = fields.find((f) => f.name === bodyName);
if (field && isLeafType(field.type)) {
caps.bodyField = bodyName;
} else {
warnings.push(`Ticket.${bodyName} is not a scalar, so it cannot be read as the ticket body.`);
}
}
await assignBodyField(caps, fields, describeType);

if (!caps.createdField) {
warnings.push('No ticket creation timestamp field found; the poll window cannot be narrowed by age.');
Expand Down
74 changes: 57 additions & 17 deletions src/services/psa/superops.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,35 +193,75 @@ export class SuperOpsClient implements PSAClient {
async enrichTicket(ticket: PsaTicket): Promise<PsaTicket> {
const caps = await this.ensureCapabilities();
if (ticket.body) return ticket;
if (!caps.detailQuery || !caps.detailArgName || !caps.bodyField) return ticket;

const selection = [caps.idField, caps.bodyField].filter(Boolean).join('\n ');
const argValue = caps.detailArgIdField
? { [caps.detailArgIdField]: ticket.ticketId }
: ticket.ticketId;
try {
const body =
caps.bodyField && caps.detailQuery && caps.detailArgName
? await this.fetchBodyField(caps, ticket.ticketId)
: caps.conversationQuery
? await this.fetchFirstConversation(caps, ticket.ticketId)
: null;
if (body) return { ...ticket, body };
} catch (err) {
log.warn(`Could not fetch the body for ticket ${ticket.ticketId}: ${describeError(err)}`);
}
return ticket;
}

private async fetchBodyField(caps: PsaCapabilities, ticketId: string): Promise<string | null> {
const bodySelection = caps.bodySubField ? `${caps.bodyField} { ${caps.bodySubField} }` : caps.bodyField;
const argValue = caps.detailArgIdField ? { [caps.detailArgIdField]: ticketId } : ticketId;
// The argument is inlined as a literal rather than declared as a variable:
// a `$var` declaration must name its type exactly, and that type is only
// known from introspection. `literal()` JSON-escapes every string.
const query = `
query SwoopTicketDetail {
${caps.detailQuery}(${caps.detailArgName}: ${literal(argValue)}) {
${selection}
${caps.idField}
${bodySelection}
}
}
`;
const data = await this.request<Record<string, unknown>>(query);
const node = data[caps.detailQuery!] as Record<string, unknown> | null;
let raw = node?.[caps.bodyField!];
if (caps.bodySubField && raw && typeof raw === 'object') raw = (raw as Record<string, unknown>)[caps.bodySubField];
return typeof raw === 'string' && raw.trim() ? htmlToText(raw) : null;
}

try {
const data = await this.request<Record<string, unknown>>(query);
const node = data[caps.detailQuery] as Record<string, unknown> | null;
const rawBody = node?.[caps.bodyField];
if (typeof rawBody === 'string' && rawBody.trim()) {
return { ...ticket, body: htmlToText(rawBody) };
/**
* The requester's original message, from the ticket's conversation thread —
* where SuperOps keeps it. The earliest entry is the one that opened the
* ticket; later replies are left out so a long thread cannot drown it.
*/
private async fetchFirstConversation(caps: PsaCapabilities, ticketId: string): Promise<string | null> {
const argValue = caps.conversationArgIdField ? { [caps.conversationArgIdField]: ticketId } : ticketId;
const entry = [caps.conversationContentField, caps.conversationTimeField].filter(Boolean).join(' ');
const selection = caps.conversationResultField ? `${caps.conversationResultField} { ${entry} }` : entry;
const query = `
query SwoopTicketConversations {
${caps.conversationQuery}(${caps.conversationArgName}: ${literal(argValue)}) {
${selection}
}
}
} catch (err) {
log.warn(`Could not fetch the body for ticket ${ticket.ticketId}: ${describeError(err)}`);
}
return ticket;
`;
const data = await this.request<Record<string, unknown>>(query);
const root = data[caps.conversationQuery!];
const rows = caps.conversationResultField
? (root as Record<string, unknown> | null)?.[caps.conversationResultField]
: root;
if (!Array.isArray(rows)) return null;
const entries = rows
.filter((r): r is Record<string, unknown> => Boolean(r) && typeof r === 'object')
.map((r, index) => ({
text: typeof r[caps.conversationContentField!] === 'string' ? htmlToText(r[caps.conversationContentField!] as string) : '',
at: caps.conversationTimeField ? parseTimestamp(r[caps.conversationTimeField]) : null,
index,
}))
.filter((e) => e.text.trim());
if (entries.length === 0) return null;
// Order by time when every entry has one; otherwise trust the API's order.
if (entries.every((e) => e.at !== null)) entries.sort((a, b) => a.at! - b.at! || a.index - b.index);
return entries[0].text;
}

/**
Expand Down
Loading
Loading