@zanichelli/freshdesk-mcp 0.0.0 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +205 -0
- package/dist/cli.js +56 -0
- package/dist/client/errors.js +136 -0
- package/dist/client/http.js +389 -0
- package/dist/client/rate-limit.js +198 -0
- package/dist/client/resources/agents.js +15 -0
- package/dist/client/resources/canned.js +134 -0
- package/dist/client/resources/companies.js +57 -0
- package/dist/client/resources/contacts.js +63 -0
- package/dist/client/resources/groups.js +15 -0
- package/dist/client/resources/list-all.js +54 -0
- package/dist/client/resources/search.js +94 -0
- package/dist/client/resources/solutions.js +192 -0
- package/dist/client/resources/ticket-fields.js +62 -0
- package/dist/client/resources/tickets.js +204 -0
- package/dist/config.js +174 -0
- package/dist/schema/index.js +145 -0
- package/dist/schema/input.js +260 -0
- package/dist/schema/output.js +138 -0
- package/dist/server.js +31 -0
- package/dist/tools/budget.js +63 -0
- package/dist/tools/context.js +62 -0
- package/dist/tools/csv.js +35 -0
- package/dist/tools/format.js +191 -0
- package/dist/tools/list.js +130 -0
- package/dist/tools/rows.js +132 -0
- package/dist/tools/ticket-query.js +408 -0
- package/dist/tools/toolsets/core/canned.js +163 -0
- package/dist/tools/toolsets/core/count-tickets.js +602 -0
- package/dist/tools/toolsets/core/export-tickets.js +461 -0
- package/dist/tools/toolsets/core/find-similar-tickets.js +309 -0
- package/dist/tools/toolsets/core/get-ticket-schema.js +134 -0
- package/dist/tools/toolsets/core/get-ticket.js +280 -0
- package/dist/tools/toolsets/core/index.js +30 -0
- package/dist/tools/toolsets/core/list-agents.js +70 -0
- package/dist/tools/toolsets/core/list-groups.js +60 -0
- package/dist/tools/toolsets/core/list-tickets.js +210 -0
- package/dist/tools/toolsets/core/search-tickets.js +82 -0
- package/dist/tools/toolsets/core/solutions.js +282 -0
- package/dist/tools/toolsets/core/triage-queue.js +253 -0
- package/dist/tools/toolsets/index.js +110 -0
- package/dist/version.js +4 -0
- package/examples/team-config.example.json +20 -0
- package/package.json +40 -3
|
@@ -0,0 +1,408 @@
|
|
|
1
|
+
// Ticket filters (SPEC §8.2, §10; docs/architecture/ticket-queries.md): the
|
|
2
|
+
// nine `list_tickets` filters turned into the request that note names,
|
|
3
|
+
// names resolved to ids on the read side. Not `ticketInput`, which refuses
|
|
4
|
+
// agent and group.
|
|
5
|
+
//
|
|
6
|
+
// - `resolveFilter`: status, priority, type, group or agent, by name or by
|
|
7
|
+
// id. A name is compared trimmed, NFC-normalised and lower-cased; it
|
|
8
|
+
// resolves when it names exactly one id: status and priority through
|
|
9
|
+
// their field's choices (a status by its agent name), type to its
|
|
10
|
+
// choice as Freshdesk spells it, agent and group through the schema's
|
|
11
|
+
// name maps. A name several ids share is refused, listing the ids; an
|
|
12
|
+
// unknown one lists the valid names (each through `plainName`, the list
|
|
13
|
+
// clipped); for agent and group, a name not found while the list is
|
|
14
|
+
// truncated says the list is incomplete and asks for the id. An id
|
|
15
|
+
// resolves to itself when the field or map has it, or when the map is
|
|
16
|
+
// truncated (it may still exist); otherwise it is refused like a name.
|
|
17
|
+
// - `buildTicketQuery`: status, priority, group, agent, type, tag and
|
|
18
|
+
// `created_between` are search conditions, joined by ` AND ` in that
|
|
19
|
+
// order (`status:2`, `group_id:<id>`, `type:'<name>'`, `tag:'<tag>'`,
|
|
20
|
+
// `created_at:>'<from>' AND created_at:<'<to>'`); `updated_since`
|
|
21
|
+
// joins them as `updated_at:>'<its UTC day − 1>'`. On `created_at`,
|
|
22
|
+
// search's `>` and `<` keep the day given and compare UTC days
|
|
23
|
+
// (measured 2026-11-24, T-055), so `created_between` is exact, not
|
|
24
|
+
// widened. `updated_at` was not measured, so its day stays widened by
|
|
25
|
+
// one until it is. Both are also returned as local checks
|
|
26
|
+
// (`created_between`, `updated_since` on the result, which callers must
|
|
27
|
+
// apply with `matchesLocal`): the `updated_since` one drops the widened
|
|
28
|
+
// day and the time before the instant; the `created_between` one is a
|
|
29
|
+
// guard that drops nothing the measured search returns.
|
|
30
|
+
// With no search condition the list endpoint serves the call,
|
|
31
|
+
// `updated_since` as its parameter (a UTC instant to the second), no
|
|
32
|
+
// local date check. No filter: the list with no parameter.
|
|
33
|
+
// - A quoted value (type, tag) goes in single quotes. Freshdesk documents
|
|
34
|
+
// no escape inside them, so a value containing `'`, `"`, `\` or a
|
|
35
|
+
// control or format character (`\p{Cc}`, `\p{Cf}`) is refused, not
|
|
36
|
+
// escaped: a quote would end the value and add a clause, and
|
|
37
|
+
// `searchTickets` refuses `"` and `\` anyway. ` OR ` inside the quotes
|
|
38
|
+
// stays part of the one value.
|
|
39
|
+
// - Dates: `updated_since` an ISO 8601 date-time with a zone of `Z` or
|
|
40
|
+
// `±HH:MM`, `created_between` `{from, to}` as `YYYY-MM-DD`, from ≤ to;
|
|
41
|
+
// a calendar-impossible day (2026-02-30) is refused, not rolled over.
|
|
42
|
+
// - `uncategorized: true` is never a search condition (a nested field is
|
|
43
|
+
// not searchable): the result carries the checks, and the caller applies
|
|
44
|
+
// `isUncategorized` to each ticket the request returns. The fields are
|
|
45
|
+
// rows.ts's `categoryFields`, so rows and queries read the setting the
|
|
46
|
+
// same way: those `uncategorised_fields` names (label or API name; a
|
|
47
|
+
// nested level's name selects its nested field), else the first nested
|
|
48
|
+
// field. A nested field is checked at its last level, any other where
|
|
49
|
+
// the ticket holds it; `null`, absent or `""` is empty, and a ticket is
|
|
50
|
+
// uncategorised when any checked field is. `false` is no filter; any
|
|
51
|
+
// other non-boolean value is refused.
|
|
52
|
+
// - `matchesLocal(query, ticket)`: every local check of a built query
|
|
53
|
+
// (uncategorized, `updated_at` ≥ the instant, `created_at`'s UTC day
|
|
54
|
+
// within the range); a ticket whose date is absent or unreadable does
|
|
55
|
+
// not match a date check.
|
|
56
|
+
// - Every problem is reported, one `validation` error with one entry per
|
|
57
|
+
// filter, `http_status: null`: nothing was sent. A query longer than
|
|
58
|
+
// `searchTickets` takes is refused here, with the reason.
|
|
59
|
+
import { MAX_FIELD_TEXT } from "../client/errors.js";
|
|
60
|
+
import { MAX_QUERY_LENGTH } from "../client/resources/search.js";
|
|
61
|
+
import { plainName } from "./format.js";
|
|
62
|
+
import { categoryFields } from "./rows.js";
|
|
63
|
+
/** Characters of an echoed value, and of a list of valid names, in a message. */
|
|
64
|
+
const MAX_QUOTE = 80;
|
|
65
|
+
const MAX_LIST = 300;
|
|
66
|
+
/** Default fields whose value sits under another key of the ticket (as output.ts). */
|
|
67
|
+
const TICKET_KEY = new Map([
|
|
68
|
+
["agent", "responder_id"],
|
|
69
|
+
["group", "group_id"],
|
|
70
|
+
["requester", "requester_id"],
|
|
71
|
+
["company", "company_id"],
|
|
72
|
+
["product", "product_id"],
|
|
73
|
+
["ticket_type", "type"],
|
|
74
|
+
]);
|
|
75
|
+
const FIELD_TYPE = {
|
|
76
|
+
status: "default_status",
|
|
77
|
+
priority: "default_priority",
|
|
78
|
+
type: "default_ticket_type",
|
|
79
|
+
};
|
|
80
|
+
/** The search key of each id filter. */
|
|
81
|
+
const SEARCH_KEY = {
|
|
82
|
+
status: "status",
|
|
83
|
+
priority: "priority",
|
|
84
|
+
group: "group_id",
|
|
85
|
+
agent: "agent_id",
|
|
86
|
+
};
|
|
87
|
+
const DAY = /^(\d{4})-(\d{2})-(\d{2})$/;
|
|
88
|
+
const DATE_TIME = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.\d{1,9})?)?(?:Z|([+-])(\d{2}):(\d{2}))$/;
|
|
89
|
+
class Refusal {
|
|
90
|
+
code;
|
|
91
|
+
message;
|
|
92
|
+
constructor(code, message) {
|
|
93
|
+
this.code = code;
|
|
94
|
+
this.message = message;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
/** Where output.ts reads a field: its ticket key, under `custom_fields` unless default. */
|
|
98
|
+
export function fieldKey(name, isDefault) {
|
|
99
|
+
return isDefault ? (TICKET_KEY.get(name) ?? name) : name;
|
|
100
|
+
}
|
|
101
|
+
function fold(text) {
|
|
102
|
+
return text.normalize("NFC").trim().toLowerCase();
|
|
103
|
+
}
|
|
104
|
+
function clip(text, max) {
|
|
105
|
+
return text.length > max ? `${text.slice(0, max - 1)}…` : text;
|
|
106
|
+
}
|
|
107
|
+
function quote(value) {
|
|
108
|
+
let text;
|
|
109
|
+
try {
|
|
110
|
+
text = JSON.stringify(value);
|
|
111
|
+
}
|
|
112
|
+
catch {
|
|
113
|
+
text = undefined;
|
|
114
|
+
}
|
|
115
|
+
return clip(text ?? typeof value, MAX_QUOTE);
|
|
116
|
+
}
|
|
117
|
+
function listed(options, withIds) {
|
|
118
|
+
if (options.length === 0)
|
|
119
|
+
return "(none)";
|
|
120
|
+
const shown = [];
|
|
121
|
+
let length = 0;
|
|
122
|
+
for (const option of options) {
|
|
123
|
+
const name = JSON.stringify(plainName(option.name));
|
|
124
|
+
const text = withIds ? `${name} (${String(option.id)})` : name;
|
|
125
|
+
if (shown.length > 0 && length + text.length > MAX_LIST)
|
|
126
|
+
break;
|
|
127
|
+
shown.push(text);
|
|
128
|
+
length += text.length + 2;
|
|
129
|
+
}
|
|
130
|
+
const rest = options.length - shown.length;
|
|
131
|
+
return shown.join(", ") + (rest > 0 ? ` … and ${rest} more` : "");
|
|
132
|
+
}
|
|
133
|
+
function isRecord(value) {
|
|
134
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
135
|
+
}
|
|
136
|
+
/** The filter's options and whether the list behind them was cut, or why there are none. */
|
|
137
|
+
function optionsOf(schema, kind) {
|
|
138
|
+
if (kind === "agent" || kind === "group") {
|
|
139
|
+
const map = kind === "agent" ? schema.agents : schema.groups;
|
|
140
|
+
return {
|
|
141
|
+
options: [...map.names].map(([id, name]) => ({ name, id })),
|
|
142
|
+
truncated: map.truncated,
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
const field = schema.fields.find((candidate) => candidate.type === FIELD_TYPE[kind]);
|
|
146
|
+
if (!field)
|
|
147
|
+
return new Refusal("unknown_field", `This account has no ${kind} field.`);
|
|
148
|
+
const choices = field.choices;
|
|
149
|
+
const options = [];
|
|
150
|
+
if (kind === "type") {
|
|
151
|
+
if (Array.isArray(choices))
|
|
152
|
+
for (const name of choices)
|
|
153
|
+
options.push({ name, id: name });
|
|
154
|
+
}
|
|
155
|
+
else if (isRecord(choices)) {
|
|
156
|
+
for (const [key, entry] of Object.entries(choices)) {
|
|
157
|
+
if (kind === "status") {
|
|
158
|
+
if (/^\d+$/.test(key) && Array.isArray(entry) && typeof entry[0] === "string") {
|
|
159
|
+
options.push({ name: entry[0], id: Number(key) });
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
else if (typeof entry === "number") {
|
|
163
|
+
options.push({ name: key, id: entry });
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
return { options, truncated: false };
|
|
168
|
+
}
|
|
169
|
+
function resolveOne(schema, kind, value) {
|
|
170
|
+
const found = optionsOf(schema, kind);
|
|
171
|
+
if (found instanceof Refusal)
|
|
172
|
+
return found;
|
|
173
|
+
const { options, truncated } = found;
|
|
174
|
+
const withIds = kind === "agent" || kind === "group";
|
|
175
|
+
const valid = () => `Valid ${kind} names: ${listed(options, withIds)}.`;
|
|
176
|
+
const byId = kind === "type" ? false : typeof value === "number" && Number.isSafeInteger(value) && value > 0;
|
|
177
|
+
if (byId) {
|
|
178
|
+
if (options.some((option) => option.id === value) || truncated)
|
|
179
|
+
return value;
|
|
180
|
+
return new Refusal("unknown_id", `No ${kind} has the id ${quote(value)}. ${valid()}`);
|
|
181
|
+
}
|
|
182
|
+
if (typeof value !== "string") {
|
|
183
|
+
return new Refusal("invalid_value", kind === "type"
|
|
184
|
+
? `The ${kind} filter takes a name.`
|
|
185
|
+
: `The ${kind} filter takes a name or a whole-number id.`);
|
|
186
|
+
}
|
|
187
|
+
const ids = [
|
|
188
|
+
...new Set(options.filter((option) => fold(option.name) === fold(value)).map((option) => option.id)),
|
|
189
|
+
];
|
|
190
|
+
if (ids.length === 1)
|
|
191
|
+
return ids[0];
|
|
192
|
+
if (ids.length > 1) {
|
|
193
|
+
const which = kind === "type"
|
|
194
|
+
? `choices ${listed(options.filter((option) => fold(option.name) === fold(value)), false)}: give one exactly as listed by get_ticket_schema`
|
|
195
|
+
: `ids ${ids.join(", ")}: give the id`;
|
|
196
|
+
return new Refusal("ambiguous_name", `${quote(value)} names several ${kind}s (${which}).`);
|
|
197
|
+
}
|
|
198
|
+
if (truncated) {
|
|
199
|
+
return new Refusal("incomplete_list", `No ${kind} named ${quote(value)} among those loaded, but the ${kind} list is incomplete: give the ${kind}'s id.`);
|
|
200
|
+
}
|
|
201
|
+
return new Refusal("unknown_name", `No ${kind} is named ${quote(value)}. ${valid()}`);
|
|
202
|
+
}
|
|
203
|
+
function validation(problems) {
|
|
204
|
+
return {
|
|
205
|
+
ok: false,
|
|
206
|
+
error: {
|
|
207
|
+
code: "validation",
|
|
208
|
+
http_status: null,
|
|
209
|
+
message: "Some filters are not valid; nothing was sent.",
|
|
210
|
+
retryable: false,
|
|
211
|
+
errors: problems,
|
|
212
|
+
},
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
function problem(field, refusal) {
|
|
216
|
+
return { field, code: refusal.code, message: clip(refusal.message, MAX_FIELD_TEXT) };
|
|
217
|
+
}
|
|
218
|
+
export function resolveFilter(schema, kind, value) {
|
|
219
|
+
const resolved = resolveOne(schema, kind, value);
|
|
220
|
+
return resolved instanceof Refusal
|
|
221
|
+
? validation([problem(kind, resolved)])
|
|
222
|
+
: { ok: true, value: resolved };
|
|
223
|
+
}
|
|
224
|
+
/** A value in single quotes, or a refusal when it could end them. */
|
|
225
|
+
function quoted(what, value) {
|
|
226
|
+
if (/['"\\\p{Cc}\p{Cf}]/u.test(value)) {
|
|
227
|
+
return new Refusal("unquotable_value", `The ${what} ${quote(value)} contains a quote, a backslash or a control character, which a search query cannot quote safely.`);
|
|
228
|
+
}
|
|
229
|
+
return `'${value}'`;
|
|
230
|
+
}
|
|
231
|
+
/** Epoch ms of a valid calendar day, else `undefined`. */
|
|
232
|
+
function utcDay(year, month, day) {
|
|
233
|
+
const date = new Date(0);
|
|
234
|
+
date.setUTCFullYear(year, month - 1, day);
|
|
235
|
+
return date.getUTCFullYear() === year &&
|
|
236
|
+
date.getUTCMonth() === month - 1 &&
|
|
237
|
+
date.getUTCDate() === day
|
|
238
|
+
? date.getTime()
|
|
239
|
+
: undefined;
|
|
240
|
+
}
|
|
241
|
+
const DAY_MS = 86_400_000;
|
|
242
|
+
/** The UTC day before the instant `value`, as YYYY-MM-DD. */
|
|
243
|
+
function dayBefore(value) {
|
|
244
|
+
return new Date(Date.parse(value.slice(0, 10)) - DAY_MS).toISOString().slice(0, 10);
|
|
245
|
+
}
|
|
246
|
+
function isDay(value) {
|
|
247
|
+
if (typeof value !== "string")
|
|
248
|
+
return false;
|
|
249
|
+
const match = DAY.exec(value);
|
|
250
|
+
return (match !== null && utcDay(Number(match[1]), Number(match[2]), Number(match[3])) !== undefined);
|
|
251
|
+
}
|
|
252
|
+
/** `updated_since` as a UTC instant to the second (fractions dropped), or a refusal. */
|
|
253
|
+
function instant(value) {
|
|
254
|
+
const match = typeof value === "string" ? DATE_TIME.exec(value) : null;
|
|
255
|
+
const refusal = new Refusal("invalid_date", `updated_since ${quote(value)} is not an ISO 8601 date-time with a zone (2026-01-02T03:04:05Z or +01:00).`);
|
|
256
|
+
if (!match)
|
|
257
|
+
return refusal;
|
|
258
|
+
const [, y, mo, d, h, mi, s, sign, oh, om] = match;
|
|
259
|
+
const day = utcDay(Number(y), Number(mo), Number(d));
|
|
260
|
+
const parts = [Number(h), Number(mi), Number(s ?? 0), Number(oh ?? 0), Number(om ?? 0)];
|
|
261
|
+
const [hour, minute, second, offH, offM] = parts;
|
|
262
|
+
if (day === undefined || hour > 23 || minute > 59 || second > 59 || offH > 23 || offM > 59) {
|
|
263
|
+
return refusal;
|
|
264
|
+
}
|
|
265
|
+
const offset = (sign === "-" ? -1 : 1) * (offH * 60 + offM) * 60_000;
|
|
266
|
+
const ms = day + ((hour * 60 + minute) * 60 + second) * 1000 - offset;
|
|
267
|
+
return new Date(ms).toISOString().replace(/\.\d{3}Z$/, "Z");
|
|
268
|
+
}
|
|
269
|
+
function lastLevelKey(field) {
|
|
270
|
+
const levels = [...(field.nested_ticket_fields ?? [])].sort((a, b) => a.level - b.level);
|
|
271
|
+
return levels.at(-1)?.name ?? field.name;
|
|
272
|
+
}
|
|
273
|
+
function categoryChecks(ctx, schema) {
|
|
274
|
+
const fields = categoryFields(ctx, schema);
|
|
275
|
+
if (fields.length === 0) {
|
|
276
|
+
return new Refusal("no_category_field", ctx.team.uncategorised_fields === undefined
|
|
277
|
+
? "uncategorized cannot be checked: this account has no nested field and the team sets no uncategorised_fields."
|
|
278
|
+
: "uncategorized cannot be checked: the team's uncategorised_fields name no ticket field.");
|
|
279
|
+
}
|
|
280
|
+
return fields.map((field) => ({
|
|
281
|
+
field: field.name,
|
|
282
|
+
key: field.type === "nested_field" ? lastLevelKey(field) : fieldKey(field.name, field.default),
|
|
283
|
+
custom: !field.default,
|
|
284
|
+
}));
|
|
285
|
+
}
|
|
286
|
+
/** Epoch ms of a ticket's date key, or `undefined` when absent or unreadable. */
|
|
287
|
+
function ticketTime(ticket, key) {
|
|
288
|
+
const value = Object.hasOwn(ticket, key) ? ticket[key] : undefined;
|
|
289
|
+
const time = typeof value === "string" ? Date.parse(value) : Number.NaN;
|
|
290
|
+
return Number.isNaN(time) ? undefined : time;
|
|
291
|
+
}
|
|
292
|
+
/** Whether the ticket passes every local check of a built query. */
|
|
293
|
+
export function matchesLocal(checks, ticket) {
|
|
294
|
+
if (checks.uncategorized !== undefined && !isUncategorized(checks.uncategorized, ticket)) {
|
|
295
|
+
return false;
|
|
296
|
+
}
|
|
297
|
+
if (checks.updated_since !== undefined) {
|
|
298
|
+
const updated = ticketTime(ticket, "updated_at");
|
|
299
|
+
if (updated === undefined || updated < Date.parse(checks.updated_since))
|
|
300
|
+
return false;
|
|
301
|
+
}
|
|
302
|
+
if (checks.created_between !== undefined) {
|
|
303
|
+
const created = ticketTime(ticket, "created_at");
|
|
304
|
+
if (created === undefined)
|
|
305
|
+
return false;
|
|
306
|
+
const day = new Date(created).toISOString().slice(0, 10);
|
|
307
|
+
if (day < checks.created_between.from || day > checks.created_between.to)
|
|
308
|
+
return false;
|
|
309
|
+
}
|
|
310
|
+
return true;
|
|
311
|
+
}
|
|
312
|
+
/** Whether any checked field is empty (`null`, absent or `""`) on the ticket. */
|
|
313
|
+
export function isUncategorized(checks, ticket) {
|
|
314
|
+
return checks.some(({ key, custom }) => {
|
|
315
|
+
const holder = custom ? ticket.custom_fields : ticket;
|
|
316
|
+
const value = isRecord(holder) && Object.hasOwn(holder, key) ? holder[key] : undefined;
|
|
317
|
+
return value === undefined || value === null || value === "";
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
export function buildTicketQuery(ctx, schema, filters) {
|
|
321
|
+
const problems = [];
|
|
322
|
+
const conditions = [];
|
|
323
|
+
for (const kind of ["status", "priority", "group", "agent"]) {
|
|
324
|
+
if (filters[kind] === undefined)
|
|
325
|
+
continue;
|
|
326
|
+
const id = resolveOne(schema, kind, filters[kind]);
|
|
327
|
+
if (id instanceof Refusal)
|
|
328
|
+
problems.push(problem(kind, id));
|
|
329
|
+
else
|
|
330
|
+
conditions.push(`${SEARCH_KEY[kind]}:${String(id)}`);
|
|
331
|
+
}
|
|
332
|
+
if (filters.type !== undefined) {
|
|
333
|
+
const name = resolveOne(schema, "type", filters.type);
|
|
334
|
+
const value = name instanceof Refusal ? name : quoted("type", String(name));
|
|
335
|
+
if (value instanceof Refusal)
|
|
336
|
+
problems.push(problem("type", value));
|
|
337
|
+
else
|
|
338
|
+
conditions.push(`type:${value}`);
|
|
339
|
+
}
|
|
340
|
+
if (filters.tag !== undefined) {
|
|
341
|
+
const tag = filters.tag;
|
|
342
|
+
const value = typeof tag === "string" && tag.trim() !== ""
|
|
343
|
+
? quoted("tag", tag)
|
|
344
|
+
: new Refusal("invalid_value", "The tag filter takes a non-blank string.");
|
|
345
|
+
if (value instanceof Refusal)
|
|
346
|
+
problems.push(problem("tag", value));
|
|
347
|
+
else
|
|
348
|
+
conditions.push(`tag:${value}`);
|
|
349
|
+
}
|
|
350
|
+
let createdBetween;
|
|
351
|
+
if (filters.created_between !== undefined) {
|
|
352
|
+
const range = filters.created_between;
|
|
353
|
+
const from = isRecord(range) ? range.from : undefined;
|
|
354
|
+
const to = isRecord(range) ? range.to : undefined;
|
|
355
|
+
if (isDay(from) && isDay(to) && from <= to) {
|
|
356
|
+
conditions.push(`created_at:>'${from}' AND created_at:<'${to}'`);
|
|
357
|
+
createdBetween = { from, to };
|
|
358
|
+
}
|
|
359
|
+
else {
|
|
360
|
+
problems.push(problem("created_between", new Refusal("invalid_date", "created_between takes {from, to}, each a day as YYYY-MM-DD, from not after to.")));
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
let updatedSince;
|
|
364
|
+
if (filters.updated_since !== undefined) {
|
|
365
|
+
const value = instant(filters.updated_since);
|
|
366
|
+
if (value instanceof Refusal)
|
|
367
|
+
problems.push(problem("updated_since", value));
|
|
368
|
+
else
|
|
369
|
+
updatedSince = value;
|
|
370
|
+
}
|
|
371
|
+
let checks;
|
|
372
|
+
const uncategorized = filters.uncategorized;
|
|
373
|
+
if (uncategorized === true) {
|
|
374
|
+
const value = categoryChecks(ctx, schema);
|
|
375
|
+
if (value instanceof Refusal)
|
|
376
|
+
problems.push(problem("uncategorized", value));
|
|
377
|
+
else
|
|
378
|
+
checks = value;
|
|
379
|
+
}
|
|
380
|
+
else if (uncategorized !== undefined && uncategorized !== false) {
|
|
381
|
+
problems.push(problem("uncategorized", new Refusal("invalid_value", "uncategorized takes true or false.")));
|
|
382
|
+
}
|
|
383
|
+
const searched = conditions.length > 0;
|
|
384
|
+
if (searched && updatedSince !== undefined) {
|
|
385
|
+
// Widened a day: updated_at's boundary was not measured (T-055).
|
|
386
|
+
conditions.push(`updated_at:>'${dayBefore(updatedSince)}'`);
|
|
387
|
+
}
|
|
388
|
+
const query = conditions.join(" AND ");
|
|
389
|
+
if (problems.length === 0 && `"${query}"`.length > MAX_QUERY_LENGTH) {
|
|
390
|
+
problems.push(problem("query", new Refusal("query_too_long", `These filters make a search query longer than Freshdesk's ${MAX_QUERY_LENGTH} characters: use fewer or shorter values.`)));
|
|
391
|
+
}
|
|
392
|
+
if (problems.length > 0)
|
|
393
|
+
return validation(problems);
|
|
394
|
+
const local = checks === undefined ? {} : { uncategorized: checks };
|
|
395
|
+
if (searched) {
|
|
396
|
+
if (updatedSince !== undefined)
|
|
397
|
+
local.updated_since = updatedSince;
|
|
398
|
+
if (createdBetween !== undefined)
|
|
399
|
+
local.created_between = createdBetween;
|
|
400
|
+
return { ok: true, endpoint: "search", query, ...local };
|
|
401
|
+
}
|
|
402
|
+
return {
|
|
403
|
+
ok: true,
|
|
404
|
+
endpoint: "list",
|
|
405
|
+
list: updatedSince === undefined ? {} : { updated_since: updatedSince },
|
|
406
|
+
...local,
|
|
407
|
+
};
|
|
408
|
+
}
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
// The canned-response reads (SPEC §8.2, C3, C10): `list_canned_responses`,
|
|
2
|
+
// `get_canned_response`, over canned.ts (T-033).
|
|
3
|
+
//
|
|
4
|
+
// - Folder names and response titles are admin-set: through `plainName`
|
|
5
|
+
// (tags stripped, capped at NAME_CAP), never wrapped (owner, 2026-11-23,
|
|
6
|
+
// OD-7). A response's text (Freshdesk's plain-text `content`) loses its
|
|
7
|
+
// tag-shaped runs (TAG, as solutions.ts strips an article's) and nothing
|
|
8
|
+
// else: no entity is decoded and a lone `<` or `>` stays. Then it is
|
|
9
|
+
// wrapped in `<ticket_content>` and cut at format.ts's TEXT_CAP with its
|
|
10
|
+
// marker; the rest cannot be fetched, so the marker names no way to.
|
|
11
|
+
// - Personal and group-limited content is labelled, not dropped: a folder
|
|
12
|
+
// carries `personal` (true, false, or `null` when unknown), a viewed
|
|
13
|
+
// response `visibility` by name (`all agents` 0, `personal` 1, `selected
|
|
14
|
+
// groups` 2, else `null`, unknown) and `shared`, true only for `all
|
|
15
|
+
// agents`. Every description says a personal or group-limited canned
|
|
16
|
+
// response belongs to its owner(s) and should not be reused as team
|
|
17
|
+
// guidance unless it is shared. A listed response has no visibility
|
|
18
|
+
// (canned.ts's folder view gives ids and titles only), so it carries
|
|
19
|
+
// `shared: null`, unknown until viewed: a folder's `personal: false` does
|
|
20
|
+
// not make it shared.
|
|
21
|
+
// - `list_canned_responses`: the cursor is read first, before any request,
|
|
22
|
+
// with MAX_POSITION. Every call lists the folders again (`listAll`, 1
|
|
23
|
+
// request per 100) and keeps the first FOLDER_CAP; a position is a page of
|
|
24
|
+
// PAGE_SIZE folders, and each folder on the page has its responses read
|
|
25
|
+
// (1 request each), the first RESPONSE_CAP titles kept. `truncated` is
|
|
26
|
+
// true when FOLDER_CAP, RESPONSE_CAP (for a folder on this page) or
|
|
27
|
+
// `listAll`'s own cap cut a list. Every request is `expensive` (the call
|
|
28
|
+
// walks up to PAGE_SIZE lists): paced, and below the reserve the next is
|
|
29
|
+
// refused, nothing sent, and the call is `rate_limited`. A failed list
|
|
30
|
+
// fails the call.
|
|
31
|
+
// - `get_canned_response`: the response only (1 request); its `visibility`
|
|
32
|
+
// is on it, so no folder is read.
|
|
33
|
+
// - One deadline for the whole call, CALL_DEADLINE_MS from its start.
|
|
34
|
+
// `api_calls_used` is every request sent, retries included (`attempts`).
|
|
35
|
+
import { z } from "zod";
|
|
36
|
+
import { getCannedResponse, listCannedFolders, listCannedResponses, } from "../../../client/resources/canned.js";
|
|
37
|
+
import { NAME_CAP, plainName, TEXT_CAP, untrusted } from "../../format.js";
|
|
38
|
+
import { listEnvelope, readCursor } from "../../list.js";
|
|
39
|
+
/** One call's requests end within this, all of them together. */
|
|
40
|
+
const CALL_DEADLINE_MS = 30_000;
|
|
41
|
+
/** A tag-shaped run in a response's plain text: removed, nothing else. */
|
|
42
|
+
const TAG = /<\/?[A-Za-z][^<>]*>/g;
|
|
43
|
+
/** Folders returned a call, each with its responses read. */
|
|
44
|
+
export const PAGE_SIZE = 10;
|
|
45
|
+
/** Folders kept; past them the list is cut (`truncated: true`). */
|
|
46
|
+
export const FOLDER_CAP = 100;
|
|
47
|
+
/** Response titles kept a folder; past them the folder's list is cut (`truncated: true`). */
|
|
48
|
+
export const RESPONSE_CAP = 100;
|
|
49
|
+
/** The last cursor position `list_canned_responses` serves: the last page of FOLDER_CAP. */
|
|
50
|
+
export const MAX_POSITION = FOLDER_CAP / PAGE_SIZE - 1;
|
|
51
|
+
const VISIBILITY = {
|
|
52
|
+
0: "all agents",
|
|
53
|
+
1: "personal",
|
|
54
|
+
2: "selected groups",
|
|
55
|
+
};
|
|
56
|
+
function visibilityName(visibility) {
|
|
57
|
+
return visibility !== null && Object.hasOwn(VISIBILITY, visibility)
|
|
58
|
+
? VISIBILITY[visibility]
|
|
59
|
+
: null;
|
|
60
|
+
}
|
|
61
|
+
const OWNERS = "A canned response in a personal folder (personal: true), or one whose visibility is personal or selected groups, belongs to its owner(s) and should not be reused as team guidance unless it is shared (shared: true, visibility all agents). null is unknown: treat it as not shared.";
|
|
62
|
+
const NAMES = `Folder names and titles are shown without HTML and cut at ${NAME_CAP} characters (ending with …).`;
|
|
63
|
+
const ANNOTATIONS = {
|
|
64
|
+
readOnlyHint: true,
|
|
65
|
+
destructiveHint: false,
|
|
66
|
+
idempotentHint: true,
|
|
67
|
+
openWorldHint: true,
|
|
68
|
+
};
|
|
69
|
+
const listInput = z.object({ cursor: z.string().optional() });
|
|
70
|
+
export const listCannedResponsesTool = {
|
|
71
|
+
name: "list_canned_responses",
|
|
72
|
+
description: [
|
|
73
|
+
"Canned response folders (for example Sprocket Replies), each with its id, name, personal (true when only its owner sees it, or null) and its responses' ids, titles (for example Sprocket on its way) and shared: null. No text: get_canned_response gives a response's text and visibility.",
|
|
74
|
+
"A listed response's sharing is unknown until viewed (shared: null); a folder's personal: false does not make it shared.",
|
|
75
|
+
`The list gives ${PAGE_SIZE} folders a call, from the first ${FOLDER_CAP} folders only, each with the first ${RESPONSE_CAP} titles only: past either the list is cut and says truncated: true. While has_more is true, call again with next_cursor; every call lists the folders again.`,
|
|
76
|
+
"Every request is sent as an expensive operation: paced (2 requests a second by default), and refused with rate_limited when the account's API budget is low (the call then fails). A call that cannot finish within 30 s fails as network.",
|
|
77
|
+
OWNERS,
|
|
78
|
+
NAMES,
|
|
79
|
+
"api_calls_used counts every request sent, retries included.",
|
|
80
|
+
].join(" "),
|
|
81
|
+
input: listInput,
|
|
82
|
+
annotations: ANNOTATIONS,
|
|
83
|
+
cost: `1 API call per 100 folders listed (at most 10), plus 1 per folder returned (at most ${PAGE_SIZE}), within 30 s, plus one per retry after an error`,
|
|
84
|
+
customerText: false,
|
|
85
|
+
async handler(args, context) {
|
|
86
|
+
const call = { tool: "list_canned_responses", args };
|
|
87
|
+
const cursor = readCursor(call, MAX_POSITION);
|
|
88
|
+
if (!cursor.ok)
|
|
89
|
+
return cursor;
|
|
90
|
+
const deadline = Date.now() + CALL_DEADLINE_MS;
|
|
91
|
+
const listed = await listCannedFolders(context.http, deadline, "expensive");
|
|
92
|
+
if (!listed.ok)
|
|
93
|
+
return listed;
|
|
94
|
+
let calls = listed.attempts;
|
|
95
|
+
let truncated = listed.truncated || listed.items.length > FOLDER_CAP;
|
|
96
|
+
const kept = listed.items.slice(0, FOLDER_CAP);
|
|
97
|
+
const start = cursor.position * PAGE_SIZE;
|
|
98
|
+
const items = [];
|
|
99
|
+
for (const folder of kept.slice(start, start + PAGE_SIZE)) {
|
|
100
|
+
const got = await listCannedResponses(context.http, folder.id, deadline, "expensive");
|
|
101
|
+
if (!got.ok)
|
|
102
|
+
return got;
|
|
103
|
+
calls += got.attempts;
|
|
104
|
+
truncated ||= got.responses.length > RESPONSE_CAP;
|
|
105
|
+
items.push({
|
|
106
|
+
id: folder.id,
|
|
107
|
+
name: plainName(folder.name),
|
|
108
|
+
personal: folder.personal,
|
|
109
|
+
responses: got.responses.slice(0, RESPONSE_CAP).map((response) => ({
|
|
110
|
+
id: response.id,
|
|
111
|
+
title: plainName(response.title),
|
|
112
|
+
shared: null,
|
|
113
|
+
})),
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
const more = start + PAGE_SIZE < kept.length;
|
|
117
|
+
return {
|
|
118
|
+
ok: true,
|
|
119
|
+
value: listEnvelope(call, {
|
|
120
|
+
items,
|
|
121
|
+
...(more ? { next: cursor.position + 1 } : {}),
|
|
122
|
+
truncated,
|
|
123
|
+
api_calls_used: calls,
|
|
124
|
+
}),
|
|
125
|
+
};
|
|
126
|
+
},
|
|
127
|
+
};
|
|
128
|
+
const responseInput = z.object({ canned_response_id: z.number().int().positive() });
|
|
129
|
+
export const getCannedResponseTool = {
|
|
130
|
+
name: "get_canned_response",
|
|
131
|
+
description: [
|
|
132
|
+
"One canned response by id (for example 3601, Sprocket on its way): its title, folder_id, visibility (all agents, personal, selected groups, or null when unknown), shared (true only for all agents) and text, as plain text inside <ticket_content>.",
|
|
133
|
+
`A text over ${TEXT_CAP.toLocaleString("en-US")} characters is cut, with a marker after the block saying how many characters were not shown; the rest cannot be fetched.`,
|
|
134
|
+
OWNERS,
|
|
135
|
+
NAMES,
|
|
136
|
+
"api_calls_used counts every request sent, retries included.",
|
|
137
|
+
].join(" "),
|
|
138
|
+
input: responseInput,
|
|
139
|
+
annotations: ANNOTATIONS,
|
|
140
|
+
cost: "1 API call, within 30 s, plus one per retry after an error",
|
|
141
|
+
customerText: true,
|
|
142
|
+
async handler(args, context) {
|
|
143
|
+
const got = await getCannedResponse(context.http, args.canned_response_id, Date.now() + CALL_DEADLINE_MS);
|
|
144
|
+
if (!got.ok)
|
|
145
|
+
return got;
|
|
146
|
+
const { response } = got;
|
|
147
|
+
const visibility = visibilityName(response.visibility);
|
|
148
|
+
return {
|
|
149
|
+
ok: true,
|
|
150
|
+
value: {
|
|
151
|
+
id: response.id,
|
|
152
|
+
title: plainName(response.title),
|
|
153
|
+
folder_id: response.folder_id,
|
|
154
|
+
visibility,
|
|
155
|
+
shared: visibility === "all agents",
|
|
156
|
+
text: response.text === null
|
|
157
|
+
? null
|
|
158
|
+
: untrusted(response.text.replace(TAG, ""), { cap: TEXT_CAP }),
|
|
159
|
+
api_calls_used: got.attempts,
|
|
160
|
+
},
|
|
161
|
+
};
|
|
162
|
+
},
|
|
163
|
+
};
|