@zanichelli/freshdesk-mcp 0.0.0-stage → 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.
Files changed (45) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +204 -2
  3. package/dist/cli.js +56 -0
  4. package/dist/client/errors.js +136 -0
  5. package/dist/client/http.js +389 -0
  6. package/dist/client/rate-limit.js +198 -0
  7. package/dist/client/resources/agents.js +15 -0
  8. package/dist/client/resources/canned.js +134 -0
  9. package/dist/client/resources/companies.js +57 -0
  10. package/dist/client/resources/contacts.js +63 -0
  11. package/dist/client/resources/groups.js +15 -0
  12. package/dist/client/resources/list-all.js +54 -0
  13. package/dist/client/resources/search.js +94 -0
  14. package/dist/client/resources/solutions.js +192 -0
  15. package/dist/client/resources/ticket-fields.js +62 -0
  16. package/dist/client/resources/tickets.js +204 -0
  17. package/dist/config.js +174 -0
  18. package/dist/schema/index.js +145 -0
  19. package/dist/schema/input.js +260 -0
  20. package/dist/schema/output.js +138 -0
  21. package/dist/server.js +31 -0
  22. package/dist/tools/budget.js +63 -0
  23. package/dist/tools/context.js +62 -0
  24. package/dist/tools/csv.js +35 -0
  25. package/dist/tools/format.js +191 -0
  26. package/dist/tools/list.js +130 -0
  27. package/dist/tools/rows.js +132 -0
  28. package/dist/tools/ticket-query.js +408 -0
  29. package/dist/tools/toolsets/core/canned.js +163 -0
  30. package/dist/tools/toolsets/core/count-tickets.js +602 -0
  31. package/dist/tools/toolsets/core/export-tickets.js +461 -0
  32. package/dist/tools/toolsets/core/find-similar-tickets.js +309 -0
  33. package/dist/tools/toolsets/core/get-ticket-schema.js +134 -0
  34. package/dist/tools/toolsets/core/get-ticket.js +280 -0
  35. package/dist/tools/toolsets/core/index.js +30 -0
  36. package/dist/tools/toolsets/core/list-agents.js +70 -0
  37. package/dist/tools/toolsets/core/list-groups.js +60 -0
  38. package/dist/tools/toolsets/core/list-tickets.js +210 -0
  39. package/dist/tools/toolsets/core/search-tickets.js +82 -0
  40. package/dist/tools/toolsets/core/solutions.js +282 -0
  41. package/dist/tools/toolsets/core/triage-queue.js +253 -0
  42. package/dist/tools/toolsets/index.js +110 -0
  43. package/dist/version.js +4 -0
  44. package/examples/team-config.example.json +20 -0
  45. package/package.json +38 -4
@@ -0,0 +1,82 @@
1
+ // `search_tickets` (SPEC §8.2, §5): Freshdesk's ticket query language, passed
2
+ // through, with its limits said in the description. Rows are rows.ts's
3
+ // `ticketRow`, in the list envelope.
4
+ //
5
+ // - The query goes to `searchTickets` as written: nothing is parsed,
6
+ // trimmed or rewritten, and no rule looks for a field the team hides
7
+ // (owner, 2026-11-23). The rows still leave a hidden field out
8
+ // (`ticketRow`). `searchTickets` adds the double quotes and refuses,
9
+ // with nothing sent to search, a blank query, one containing `"` or `\`,
10
+ // and one over its length limit: `validation` naming `query`, never its
11
+ // text. Freshdesk's own refusal (a 400 for a field that is not
12
+ // searchable, or a query it cannot parse) is returned as is, with its
13
+ // `errors[]`. A nested (dependent) field, at any level, is not
14
+ // searchable (Freshdesk answers 400).
15
+ // - The cursor is read first, before any request. A position is a search
16
+ // page, so the bound is search.ts's MAX_SEARCH_POSITION, search's
17
+ // last page: a cursor past it sends nothing.
18
+ // - One page of SEARCH_PER_PAGE a call. `has_more` and `next_cursor` come
19
+ // from search's `total` alone, never from the number of rows: more exists
20
+ // while the page is not the last of the 10 and `total` reaches past it.
21
+ // `total` over the 300 results the 10 pages hold is `truncated: true`, on
22
+ // every page.
23
+ // - One deadline for the whole call, CALL_DEADLINE_MS from its start.
24
+ // - `api_calls_used` is every request this call sent, retries included, and
25
+ // the schema's load when this call started it (the service's `attempts`).
26
+ // The schema is taken before the query is checked: a refused query on a
27
+ // schema not yet cached has loaded it.
28
+ import { z } from "zod";
29
+ import { MAX_QUERY_LENGTH, MAX_SEARCH_PAGE, MAX_SEARCH_POSITION, SEARCH_PER_PAGE, searchTickets, } from "../../../client/resources/search.js";
30
+ import { listEnvelope, readCursor } from "../../list.js";
31
+ import { ticketRow } from "../../rows.js";
32
+ /** One call's requests end within this, all of them together. */
33
+ const CALL_DEADLINE_MS = 30_000;
34
+ const input = z.object({
35
+ query: z.string(),
36
+ cursor: z.string().optional(),
37
+ });
38
+ export const searchTicketsTool = {
39
+ name: "search_tickets",
40
+ description: [
41
+ "Tickets matching a query in Freshdesk's ticket query language, as compact rows: id, subject, status, priority, category, last update, agent and group, by name. For the common filters (status, priority, group, agent, type, tag, dates) list_tickets is simpler and takes names; use this for a custom field or for OR.",
42
+ "query is conditions field:value joined by AND or OR, with parentheses: status:2 AND (priority:3 OR priority:4) AND cf_model:'Blue sprocket'. A number or true/false is written bare; text and a date (YYYY-MM-DD, UTC) go in single quotes. :> and :< compare dates and numbers (created_at:>'2026-01-01'; on created_at, :> and :< keep the day given (inclusive) and the day is the UTC day (measured 2026-11-24); for any other date field (updated_at, due_by, fr_due_by, custom dates) the rule is not measured, so widen the range by a day), and field:null finds a field with no value. Searchable fields: status, priority, agent_id and group_id by id, type, tag, due_by, fr_due_by, created_at, updated_at, and custom fields of type single-line text, number, checkbox, plain dropdown and date, each by its API name; get_ticket_schema gives the names, ids and choices.",
43
+ `Write the query without the double quotes around it: this tool adds them. It must contain no double quote (") and no backslash (\\) and be at most ${MAX_QUERY_LENGTH - 2} characters; otherwise it is refused and no search is sent. It is passed to Freshdesk unchanged, and Freshdesk refuses a field that is not searchable with a validation error naming it: a nested (dependent) field, at any level, is not searchable (Freshdesk answers 400).`,
44
+ "There is no full text: search matches field values only, never words in the subject, the description or the conversations.",
45
+ `Results come ${SEARCH_PER_PAGE} a call, and Freshdesk returns the first ${MAX_SEARCH_PAGE * SEARCH_PER_PAGE} matches only: past them the list is cut and says truncated: true (narrow the query with one more condition or a shorter date range). A ticket changed in the last few minutes can be missing. While has_more is true, call again with the same arguments and next_cursor.`,
46
+ "api_calls_used counts every request sent for this call, retries included, and the ticket-field schema's load when this call starts it.",
47
+ ].join(" "),
48
+ input,
49
+ annotations: {
50
+ readOnlyHint: true,
51
+ destructiveHint: false,
52
+ idempotentHint: true,
53
+ openWorldHint: true,
54
+ },
55
+ cost: "1 API call, within 30 s, plus one per retry after an error, plus at least 3 when the ticket-field schema is not cached",
56
+ customerText: true,
57
+ async handler(args, context) {
58
+ const call = { tool: "search_tickets", args };
59
+ const cursor = readCursor(call, MAX_SEARCH_POSITION);
60
+ if (!cursor.ok)
61
+ return cursor;
62
+ const deadline = Date.now() + CALL_DEADLINE_MS;
63
+ const loaded = await context.schema.get();
64
+ if (!loaded.ok)
65
+ return loaded;
66
+ const { schema } = loaded;
67
+ const page = cursor.position + 1;
68
+ const found = await searchTickets(context.http, args.query, page, deadline);
69
+ if (!found.ok)
70
+ return found;
71
+ const more = page < MAX_SEARCH_PAGE && page * SEARCH_PER_PAGE < found.total;
72
+ return {
73
+ ok: true,
74
+ value: listEnvelope(call, {
75
+ items: found.results.map((ticket) => ticketRow(context, schema, ticket)),
76
+ ...(more ? { next: page } : {}),
77
+ truncated: found.total > MAX_SEARCH_PAGE * SEARCH_PER_PAGE,
78
+ api_calls_used: loaded.attempts + found.attempts,
79
+ }),
80
+ };
81
+ },
82
+ };
@@ -0,0 +1,282 @@
1
+ // The knowledge-base reads (SPEC §8.2, C3, C9): `search_solutions`,
2
+ // `get_solution_article`, `list_solution_tree`, over solutions.ts (T-031).
3
+ //
4
+ // - Titles and names (article, folder, category) are admin-set: through
5
+ // `plainName` (tags stripped, capped at NAME_CAP), never wrapped (owner,
6
+ // 2026-11-23, OD-7). An article's text (Freshdesk's plain text) loses
7
+ // its tag-shaped runs (TAG: `<`, an optional `/`, a letter, then up to
8
+ // `>` with no `<` or `>` between) and nothing else: no entity is decoded
9
+ // and a lone `<` or `>` stays, so "Torque < 5 Nm, then > 3 turns" is
10
+ // kept. Then it is wrapped in `<ticket_content>` (which neutralises
11
+ // every `<`) and cut at ARTICLE_CAP with format.ts's marker, after the
12
+ // block; there is no way to fetch the rest, so the marker names none.
13
+ // (`htmlToText` is not used here: on plain text it deleted a `<`…`>`
14
+ // span of prose and decoded `&lt;b&gt;` into a tag.)
15
+ // - Drafts and non-public content are labelled, not dropped: an article
16
+ // or hit carries `status` by name (`draft` for 1, `published` for 2,
17
+ // else `null`), a folder or hit `visibility` by name (Freshdesk's
18
+ // documented values 1–4, else `null`, unknown). A hit's `visibility` is
19
+ // its folder's (solutions.ts's `folder_visibility`), and so is a tree
20
+ // article's. Every article, hit and tree article carries `customer_safe`:
21
+ // true only when `status` is `published` and `visibility` is `all users`;
22
+ // every description says only those may be quoted to a customer as
23
+ // published guidance, and that `customer_safe` does not check the
24
+ // category's portal visibility (solutions.ts drops `visible_in_portals`).
25
+ // - `get_solution_article` reads the article, then its folder (`getFolder`,
26
+ // 2 requests) for `visibility`. A folder answered `not_found`, or an
27
+ // article with no readable `folder_id` (no folder request), gives
28
+ // `visibility: null` and the article still; any other failed folder read
29
+ // fails the call.
30
+ // - `search_solutions`: the cursor is read first, before any request, with
31
+ // MAX_POSITION. Freshdesk returns every hit in one response, so each call
32
+ // runs the search again (1 request) and pages the hits locally, PAGE_SIZE
33
+ // a call; a position is a page. Hits past HIT_CAP are cut, `truncated:
34
+ // true` on every page, so the last position is HIT_CAP / PAGE_SIZE - 1.
35
+ // `has_more` from the capped hit list.
36
+ // - `list_solution_tree`: no cursor. Categories, then every category's
37
+ // folders, then every folder's article titles (breadth first, so the
38
+ // folder skeleton comes before articles), each list through `listAll`
39
+ // (1 request per 100 entries, at most 10). At most MAX_LISTS lists a
40
+ // call: a category whose folders, or a folder whose articles, were not
41
+ // read for the cap has `folders: null` / `articles: null`, and
42
+ // `truncated` is true; it is true too when `listAll`'s own cap cut a
43
+ // list. Subfolders are not walked (solutions.ts does not read them).
44
+ // A failed list fails the call. Every list is `expensive` for the limiter
45
+ // (the walk is the costliest read here): below the reserve the next list
46
+ // is refused, nothing sent, and the call is `rate_limited`.
47
+ // With the optional `category` (an id, T-058) the categories list is not
48
+ // read: that one category is (`getCategory`, `expensive` too, the first
49
+ // of MAX_LISTS), then its folders and their articles as above, so a
50
+ // knowledge base with more categories than MAX_LISTS still shows
51
+ // articles. A 404 for it is `not_found`, nothing more sent: one request,
52
+ // where checking the categories list would cost up to 10 and miss a
53
+ // category past `listAll`'s cap. Without `category` nothing changes.
54
+ // - `updated_at` through rows.ts's `isoUpdated`: a UTC instant, as the
55
+ // ticket tools give dates, or `null`.
56
+ // - One deadline for the whole call, CALL_DEADLINE_MS from its start.
57
+ // `api_calls_used` is every request sent, retries included (`attempts`).
58
+ import { z } from "zod";
59
+ import { getArticle, getCategory, getFolder, listArticles, listCategories, listFolders, MAX_TERM_LENGTH, searchArticles, } from "../../../client/resources/solutions.js";
60
+ import { NAME_CAP, plainName, untrusted } from "../../format.js";
61
+ import { listEnvelope, readCursor } from "../../list.js";
62
+ import { isoUpdated } from "../../rows.js";
63
+ /** One call's requests end within this, all of them together. */
64
+ const CALL_DEADLINE_MS = 30_000;
65
+ /** Code points of an article's text returned; the rest is cut with the marker. */
66
+ export const ARTICLE_CAP = 10_000;
67
+ /** A tag-shaped run in an article's plain text: removed, nothing else. */
68
+ const TAG = /<\/?[A-Za-z][^<>]*>/g;
69
+ /** Search hits returned a call. */
70
+ export const PAGE_SIZE = 10;
71
+ /** Search hits kept; past them the list is cut (`truncated: true`). */
72
+ export const HIT_CAP = 100;
73
+ /** The last cursor position `search_solutions` serves: the last page of HIT_CAP. */
74
+ export const MAX_POSITION = HIT_CAP / PAGE_SIZE - 1;
75
+ /** Lists `list_solution_tree` reads a call (categories, a category's folders, a folder's articles). */
76
+ export const MAX_LISTS = 20;
77
+ const STATUS = { 1: "draft", 2: "published" };
78
+ const VISIBILITY = {
79
+ 1: "all users",
80
+ 2: "logged-in users",
81
+ 3: "agents only",
82
+ 4: "selected companies",
83
+ };
84
+ function statusName(status) {
85
+ return Object.hasOwn(STATUS, status) ? STATUS[status] : null;
86
+ }
87
+ function visibilityName(visibility) {
88
+ return visibility !== null && Object.hasOwn(VISIBILITY, visibility)
89
+ ? VISIBILITY[visibility]
90
+ : null;
91
+ }
92
+ /** Only a published article visible to all users may be given to a customer. */
93
+ function customerSafe(status, visibility) {
94
+ return status === "published" && visibility === "all users";
95
+ }
96
+ const FOR_THE_AGENT = "A draft (status: draft), or content not visible to all users (visibility other than all users; null is unknown, so treat it as not public), is for the agent. Only an article with customer_safe: true may be quoted to a customer as published guidance. customer_safe does not check which portals show the article's category.";
97
+ const NAMES = `Titles and names are shown without HTML and cut at ${NAME_CAP} characters (ending with …).`;
98
+ const ANNOTATIONS = {
99
+ readOnlyHint: true,
100
+ destructiveHint: false,
101
+ idempotentHint: true,
102
+ openWorldHint: true,
103
+ };
104
+ const searchInput = z.object({ term: z.string(), cursor: z.string().optional() });
105
+ export const searchSolutionsTool = {
106
+ name: "search_solutions",
107
+ description: [
108
+ "Knowledge-base articles matching a term (for example squeak), drafts included: each one's id, title, status (draft, published, or null), visibility (its folder's: all users, logged-in users, agents only, selected companies, or null), customer_safe and last update. get_solution_article gives an article's text.",
109
+ `term is at most ${MAX_TERM_LENGTH} characters and not blank; otherwise it is refused and nothing is sent.`,
110
+ `Results come ${PAGE_SIZE} a call, from the first ${HIT_CAP} hits only: past them the list is cut and says truncated: true. While has_more is true, call again with the same arguments and next_cursor; every call runs the search again.`,
111
+ FOR_THE_AGENT,
112
+ NAMES,
113
+ "api_calls_used counts every request sent, retries included.",
114
+ ].join(" "),
115
+ input: searchInput,
116
+ annotations: ANNOTATIONS,
117
+ cost: "1 API call per call (the search runs again for every page), within 30 s, plus one per retry after an error",
118
+ customerText: false,
119
+ async handler(args, context) {
120
+ const call = { tool: "search_solutions", args };
121
+ const cursor = readCursor(call, MAX_POSITION);
122
+ if (!cursor.ok)
123
+ return cursor;
124
+ const found = await searchArticles(context.http, args.term, Date.now() + CALL_DEADLINE_MS);
125
+ if (!found.ok)
126
+ return found;
127
+ const kept = found.results.slice(0, HIT_CAP);
128
+ const start = cursor.position * PAGE_SIZE;
129
+ const more = start + PAGE_SIZE < kept.length;
130
+ return {
131
+ ok: true,
132
+ value: listEnvelope(call, {
133
+ items: kept.slice(start, start + PAGE_SIZE).map((hit) => {
134
+ const status = statusName(hit.status);
135
+ const visibility = visibilityName(hit.folder_visibility);
136
+ return {
137
+ id: hit.id,
138
+ title: plainName(hit.title),
139
+ status,
140
+ visibility,
141
+ updated_at: isoUpdated(hit.updated_at),
142
+ customer_safe: customerSafe(status, visibility),
143
+ };
144
+ }),
145
+ ...(more ? { next: cursor.position + 1 } : {}),
146
+ truncated: found.results.length > HIT_CAP,
147
+ api_calls_used: found.attempts,
148
+ }),
149
+ };
150
+ },
151
+ };
152
+ const articleInput = z.object({ article_id: z.number().int().positive() });
153
+ export const getSolutionArticleTool = {
154
+ name: "get_solution_article",
155
+ description: [
156
+ "One knowledge-base article by id: its title, status (draft, published, or null), visibility (its folder's: all users, logged-in users, agents only, selected companies, or null when unknown), customer_safe, last update and text, as plain text inside <ticket_content>.",
157
+ `A text over ${ARTICLE_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.`,
158
+ FOR_THE_AGENT,
159
+ NAMES,
160
+ "api_calls_used counts every request sent, retries included.",
161
+ ].join(" "),
162
+ input: articleInput,
163
+ annotations: ANNOTATIONS,
164
+ cost: "2 API calls (the article, then its folder), within 30 s, plus one per retry after an error",
165
+ customerText: true,
166
+ async handler(args, context) {
167
+ const deadline = Date.now() + CALL_DEADLINE_MS;
168
+ const got = await getArticle(context.http, args.article_id, deadline);
169
+ if (!got.ok)
170
+ return got;
171
+ const { article } = got;
172
+ let calls = got.attempts;
173
+ let visibility = null;
174
+ if (article.folder_id !== null) {
175
+ const folder = await getFolder(context.http, article.folder_id, deadline);
176
+ calls += folder.attempts ?? 0;
177
+ if (folder.ok)
178
+ visibility = visibilityName(folder.folder.visibility);
179
+ else if (folder.error.code !== "not_found")
180
+ return folder;
181
+ }
182
+ const status = statusName(article.status);
183
+ return {
184
+ ok: true,
185
+ value: {
186
+ id: article.id,
187
+ title: plainName(article.title),
188
+ status,
189
+ visibility,
190
+ customer_safe: customerSafe(status, visibility),
191
+ updated_at: isoUpdated(article.updated_at),
192
+ text: article.text === null
193
+ ? null
194
+ : untrusted(article.text.replace(TAG, ""), { cap: ARTICLE_CAP }),
195
+ api_calls_used: calls,
196
+ },
197
+ };
198
+ },
199
+ };
200
+ const treeInput = z.object({ category: z.number().int().positive().optional() });
201
+ export const listSolutionTreeTool = {
202
+ name: "list_solution_tree",
203
+ description: [
204
+ "The knowledge base's outline: categories, each with its folders (name and visibility: all users, logged-in users, agents only, selected companies, or null), each with its articles' ids, titles, status (draft, published, or null), customer_safe and last update. No article text: get_solution_article gives it.",
205
+ `It reads at most ${MAX_LISTS} lists a call (the categories, one per category for its folders, one per folder for its articles), categories and folders first: a category or folder past that has folders: null or articles: null, and truncated is true. truncated is true too when a list was longer than 1,000 entries and cut.`,
206
+ "category (optional, a category id from this outline) reads that category alone in place of the categories list: its folders and their articles. When the outline comes back truncated: true with no articles, call again with category set to one category's id. An unknown category is not_found.",
207
+ `Subfolders are not shown: an article in a subfolder is found only through search_solutions. Every list is sent as an expensive operation: paced (2 requests a second by default), so a full walk of single-page lists takes about 10 s, and refused with rate_limited when the account's API budget is low (the call then fails). A walk that cannot finish within 30 s fails as network.`,
208
+ FOR_THE_AGENT,
209
+ NAMES,
210
+ "api_calls_used counts every request sent, retries included.",
211
+ ].join(" "),
212
+ input: treeInput,
213
+ annotations: ANNOTATIONS,
214
+ cost: `1 API call per list of up to 100 entries, at most ${MAX_LISTS} lists of at most 10 calls each, within 30 s, plus one per retry after an error`,
215
+ customerText: false,
216
+ async handler(args, context) {
217
+ const deadline = Date.now() + CALL_DEADLINE_MS;
218
+ let lists = 1;
219
+ const listed = args.category === undefined
220
+ ? await listCategories(context.http, deadline, "expensive")
221
+ : await oneCategory(context, args.category, deadline);
222
+ if (!listed.ok)
223
+ return listed;
224
+ let calls = listed.attempts;
225
+ let truncated = listed.truncated;
226
+ const categories = listed.items.map((category) => ({
227
+ id: category.id,
228
+ name: plainName(category.name),
229
+ folders: null,
230
+ }));
231
+ for (const category of categories) {
232
+ if (lists >= MAX_LISTS) {
233
+ truncated = true;
234
+ break;
235
+ }
236
+ lists += 1;
237
+ const folders = await listFolders(context.http, category.id, deadline, "expensive");
238
+ if (!folders.ok)
239
+ return folders;
240
+ calls += folders.attempts;
241
+ truncated ||= folders.truncated;
242
+ category.folders = folders.items.map((folder) => ({
243
+ id: folder.id,
244
+ name: plainName(folder.name),
245
+ visibility: visibilityName(folder.visibility),
246
+ articles: null,
247
+ }));
248
+ }
249
+ outer: for (const category of categories) {
250
+ for (const folder of category.folders ?? []) {
251
+ if (lists >= MAX_LISTS) {
252
+ truncated = true;
253
+ break outer;
254
+ }
255
+ lists += 1;
256
+ const articles = await listArticles(context.http, folder.id, deadline, "expensive");
257
+ if (!articles.ok)
258
+ return articles;
259
+ calls += articles.attempts;
260
+ truncated ||= articles.truncated;
261
+ folder.articles = articles.items.map((article) => {
262
+ const status = statusName(article.status);
263
+ return {
264
+ id: article.id,
265
+ title: plainName(article.title),
266
+ status,
267
+ updated_at: isoUpdated(article.updated_at),
268
+ customer_safe: customerSafe(status, folder.visibility),
269
+ };
270
+ });
271
+ }
272
+ }
273
+ return { ok: true, value: { categories, truncated, api_calls_used: calls } };
274
+ },
275
+ };
276
+ /** The one category asked for, in `listCategories`' result shape. */
277
+ async function oneCategory(context, id, deadline) {
278
+ const got = await getCategory(context.http, id, deadline, "expensive");
279
+ if (!got.ok)
280
+ return got;
281
+ return { ok: true, items: [got.category], truncated: false, attempts: got.attempts };
282
+ }
@@ -0,0 +1,253 @@
1
+ // `triage_queue` (SPEC §8.2, C2): open and pending tickets with the urgency
2
+ // signals Claude ranks on. No ranking or scoring here. The endpoints and the
3
+ // bound are docs/architecture/ticket-queries.md's (`triage_queue`).
4
+ //
5
+ // - Source: search, QUERY (status 2 or 3). A result with any other status
6
+ // is dropped locally. One page of SEARCH_PER_PAGE a call; a cursor
7
+ // position is a search page, read first, before any request, with
8
+ // search.ts's MAX_SEARCH_POSITION. `has_more` and `next_cursor` come from
9
+ // search's `total` alone; `total` over the 300 results the 10 pages hold
10
+ // is `truncated: true`, on every page.
11
+ // - A row is rows.ts's `ticketRow` plus the signals a search result
12
+ // carries: `created` and `age`, the two due times with their overdue
13
+ // flags, the three escalation flags. A date is a UTC ISO 8601 instant
14
+ // through `isoUpdated`; a duration is in words (`human`). Overdue says
15
+ // only that the due time has passed at the call's start. A value that is
16
+ // missing or not in its expected form is `null`: unknown, never a guess.
17
+ // - `reply_signals: true` adds the signals that need `stats`: one
18
+ // `GET /tickets/{id}?include=stats` per returned row, one after another,
19
+ // each sent as `expensive` (refused below the reserve, paced). The bound
20
+ // is 1 + SEARCH_PER_PAGE requests a call (31, 61 credits), retries
21
+ // apart (they add to it). Without it no ticket is viewed and the rows have no reply key.
22
+ // `stats` is read here, key by key: a key that is absent or not `null`
23
+ // or an ISO 8601 date-time with a zone makes the signals that need it
24
+ // `null`.
25
+ // - `last_customer_reply` is `requester_responded_at`; when that is
26
+ // `null` the customer's last message is the opening one, so it is
27
+ // `created`. `unanswered_customer_reply`: no agent response
28
+ // (`agent_responded_at` `null`), or one before the customer's reply.
29
+ // - `first_response_overdue` is refined: true only when the due time
30
+ // has passed and `first_responded_at` is `null`. A due time that has
31
+ // passed with `first_responded_at` unreadable, or the ticket not
32
+ // viewed, is `null`.
33
+ // - A view answered `not_found` (search lags a few minutes) leaves the
34
+ // row unviewed: the three reply signals `null`.
35
+ // - Once a view was answered, a later one the limiter refuses unsent
36
+ // (`rate_limited` with no HTTP status) ends the views: every row of
37
+ // the page is returned, the rest unviewed, with
38
+ // `reply_signals_incomplete: true` beside the envelope. Any other
39
+ // failed view, and a refusal of the first, fails the call.
40
+ // - Order: the rows of a page by resolution due time, earliest first, a
41
+ // ticket with none last, ties by id. The pages follow search's own order,
42
+ // so the order holds within a page only.
43
+ // - One deadline for the whole call, CALL_DEADLINE_MS from its start; ages
44
+ // are measured at that start too.
45
+ // - `api_calls_used` is every request this call sent, retries included, and
46
+ // the schema's load when this call started it.
47
+ import { z } from "zod";
48
+ import { MAX_SEARCH_PAGE, MAX_SEARCH_POSITION, SEARCH_PER_PAGE, searchTickets, } from "../../../client/resources/search.js";
49
+ import { getTicket } from "../../../client/resources/tickets.js";
50
+ import { listEnvelope, readCursor } from "../../list.js";
51
+ import { isoUpdated, ticketRow } from "../../rows.js";
52
+ /** One call's requests end within this, all of them together. */
53
+ const CALL_DEADLINE_MS = 30_000;
54
+ /** Freshdesk's ids of the statuses Open and Pending. */
55
+ const OPEN = 2;
56
+ const PENDING = 3;
57
+ const QUERY = `status:${OPEN} OR status:${PENDING}`;
58
+ const MINUTE_MS = 60_000;
59
+ const DAY_MIN = 1440;
60
+ const input = z.object({
61
+ reply_signals: z.boolean().optional(),
62
+ cursor: z.string().optional(),
63
+ });
64
+ function count(n, unit) {
65
+ return `${n} ${unit}${n === 1 ? "" : "s"}`;
66
+ }
67
+ /** A duration in words, its two largest units of days, hours and minutes, rounded down; `null` when negative. */
68
+ function human(ms) {
69
+ if (!(ms >= 0))
70
+ return null;
71
+ const minutes = Math.floor(ms / MINUTE_MS);
72
+ if (minutes === 0)
73
+ return "under a minute";
74
+ const parts = [
75
+ count(Math.floor(minutes / DAY_MIN), "day"),
76
+ count(Math.floor((minutes % DAY_MIN) / 60), "hour"),
77
+ count(minutes % 60, "minute"),
78
+ ];
79
+ const first = parts.findIndex((part) => !part.startsWith("0 "));
80
+ return parts
81
+ .slice(first, first + 2)
82
+ .filter((part) => !part.startsWith("0 "))
83
+ .join(" ");
84
+ }
85
+ /** The time from an instant `isoUpdated` gave to `now`, in words. */
86
+ function since(iso, now) {
87
+ return iso === null ? null : human(now - Date.parse(iso));
88
+ }
89
+ function flag(value) {
90
+ return typeof value === "boolean" ? value : null;
91
+ }
92
+ /** A `stats` time: an instant in epoch ms, `null` for none yet, `undefined` when absent or in any other form. */
93
+ function statTime(stats, key) {
94
+ if (!Object.hasOwn(stats, key))
95
+ return undefined;
96
+ if (stats[key] === null)
97
+ return null;
98
+ const iso = isoUpdated(stats[key]);
99
+ return iso === null ? undefined : Date.parse(iso);
100
+ }
101
+ /** A due time in epoch ms for the order; one that is missing or unreadable sorts last. */
102
+ function dueTime(ticket) {
103
+ const iso = isoUpdated(ticket.due_by);
104
+ return iso === null ? Infinity : Date.parse(iso);
105
+ }
106
+ function byResolutionDue(a, b) {
107
+ const [dueA, dueB] = [dueTime(a), dueTime(b)];
108
+ return dueA === dueB ? a.id - b.id : dueA < dueB ? -1 : 1;
109
+ }
110
+ function signals(ticket, now) {
111
+ const created = isoUpdated(ticket.created_at);
112
+ const firstResponseDue = isoUpdated(ticket.fr_due_by);
113
+ const resolutionDue = isoUpdated(ticket.due_by);
114
+ const overdue = (due) => (due === null ? null : Date.parse(due) < now);
115
+ return {
116
+ created,
117
+ age: since(created, now),
118
+ first_response_due: firstResponseDue,
119
+ first_response_overdue: overdue(firstResponseDue),
120
+ resolution_due: resolutionDue,
121
+ resolution_overdue: overdue(resolutionDue),
122
+ first_response_escalated: flag(ticket.fr_escalated),
123
+ resolution_escalated: flag(ticket.is_escalated),
124
+ next_response_escalated: flag(ticket.nr_escalated),
125
+ };
126
+ }
127
+ /**
128
+ * The signals of a row whose `stats` could not be read at all. Whether a
129
+ * first response was sent is not known, so a due time that has passed is not
130
+ * known to be overdue.
131
+ */
132
+ function unviewed(row) {
133
+ return {
134
+ ...row,
135
+ first_response_overdue: row.first_response_overdue === true ? null : row.first_response_overdue,
136
+ last_customer_reply: null,
137
+ since_last_customer_reply: null,
138
+ unanswered_customer_reply: null,
139
+ };
140
+ }
141
+ function replySignals(row, stats, now) {
142
+ const unknown = unviewed(row);
143
+ if (typeof stats !== "object" || stats === null || Array.isArray(stats))
144
+ return unknown;
145
+ const record = stats;
146
+ const first = statTime(record, "first_responded_at");
147
+ const overdue = {
148
+ first_response_overdue: first === undefined
149
+ ? unknown.first_response_overdue
150
+ : row.first_response_overdue && first === null,
151
+ };
152
+ const requester = statTime(record, "requester_responded_at");
153
+ if (requester === undefined)
154
+ return { ...unknown, ...overdue };
155
+ const agent = statTime(record, "agent_responded_at");
156
+ // No reply since the ticket was opened: the customer's last message is the opening one.
157
+ const last = requester === null ? row.created : new Date(requester).toISOString();
158
+ return {
159
+ ...row,
160
+ ...overdue,
161
+ last_customer_reply: last,
162
+ since_last_customer_reply: since(last, now),
163
+ unanswered_customer_reply: agent === undefined ? null : agent === null || (requester !== null && requester > agent),
164
+ };
165
+ }
166
+ export const triageQueueTool = {
167
+ name: "triage_queue",
168
+ description: [
169
+ "The tickets in status Open or Pending with the signals to rank them by urgency; the ranking is yours. A ticket in any other status, a custom one included, is not listed (list_tickets filters by any status).",
170
+ "Each row is a compact ticket row (id, subject, status, priority, category, last update, agent and group, by name) plus: created and age; first_response_due and resolution_due with first_response_overdue and resolution_overdue (first_response_overdue means the first-response due time has passed, whether or not a first response was sent; reply_signals refines it); first_response_escalated, resolution_escalated and next_response_escalated, Freshdesk's own flags. Times are ISO 8601 in UTC; age is in words (3 days 4 hours), measured when the call starts. In any signal null means unknown (the value was missing or unreadable), not false and not zero.",
171
+ `With reply_signals: true each row also has last_customer_reply (the time of the customer's last message, the opening one when there was no later reply), since_last_customer_reply in words, and unanswered_customer_reply (true when no agent has responded since that message; null when unknown; a ticket an agent opened, an outbound email or a logged phone call, with no agent reply since also reads as unanswered, its opening counted as the customer's message), and first_response_overdue is true only while no first response has been sent. They cost one more request per row, at most ${1 + SEARCH_PER_PAGE} requests a call, sent as an expensive operation: paced, so a full page takes about 15 s, and refused with rate_limited when the account's API budget is low. If the budget runs out after some rows were read, every row still comes back, the rows not read with these signals null, and the result says reply_signals_incomplete: true: call again later to read them. Ask for the reply signals when the first pass leaves the ranking open.`,
172
+ `Rows come ${SEARCH_PER_PAGE} a call, ordered by resolution due time, earliest first (a ticket with none last, then by id): the order holds within a page only, so read every page before ranking. While has_more is true, call again with the same arguments and next_cursor. Freshdesk returns the first ${MAX_SEARCH_PAGE * SEARCH_PER_PAGE} matches only: past them the list is cut and says truncated: true. A ticket changed in the last few minutes can be missing or show its earlier state.`,
173
+ "api_calls_used counts every request sent for this call, retries included, and the ticket-field schema's load when this call starts it.",
174
+ ].join(" "),
175
+ input,
176
+ annotations: {
177
+ readOnlyHint: true,
178
+ destructiveHint: false,
179
+ idempotentHint: true,
180
+ openWorldHint: true,
181
+ },
182
+ cost: `1 API call, within 30 s; with reply_signals: true one more per row, at most ${1 + SEARCH_PER_PAGE} calls (about ${1 + 2 * SEARCH_PER_PAGE} credits of the rate limit); plus one per retry after an error, plus at least 3 when the ticket-field schema is not cached`,
183
+ customerText: true,
184
+ async handler(args, context) {
185
+ const call = { tool: "triage_queue", args };
186
+ const cursor = readCursor(call, MAX_SEARCH_POSITION);
187
+ if (!cursor.ok)
188
+ return cursor;
189
+ const now = Date.now();
190
+ const deadline = now + CALL_DEADLINE_MS;
191
+ const loaded = await context.schema.get();
192
+ if (!loaded.ok)
193
+ return loaded;
194
+ const { schema } = loaded;
195
+ const page = cursor.position + 1;
196
+ const found = await searchTickets(context.http, QUERY, page, deadline);
197
+ if (!found.ok)
198
+ return found;
199
+ const more = page < MAX_SEARCH_PAGE && page * SEARCH_PER_PAGE < found.total;
200
+ let calls = loaded.attempts + found.attempts;
201
+ const tickets = found.results
202
+ .filter((ticket) => ticket.status === OPEN || ticket.status === PENDING)
203
+ .sort(byResolutionDue);
204
+ const rows = tickets.map((ticket) => ({
205
+ id: ticket.id,
206
+ row: ticketRow(context, schema, ticket),
207
+ signals: signals(ticket, now),
208
+ }));
209
+ const items = [];
210
+ let answered = 0;
211
+ let incomplete = false;
212
+ for (const { id, row, signals: own } of rows) {
213
+ if (args.reply_signals !== true) {
214
+ items.push({ ...row, ...own });
215
+ continue;
216
+ }
217
+ if (incomplete) {
218
+ items.push({ ...row, ...unviewed(own) });
219
+ continue;
220
+ }
221
+ const viewed = await getTicket(context.http, id, ["stats"], deadline, "expensive");
222
+ calls += viewed.attempts ?? 0;
223
+ if (viewed.ok) {
224
+ answered += 1;
225
+ items.push({ ...row, ...replySignals(own, viewed.ticket.stats, now) });
226
+ continue;
227
+ }
228
+ const { error } = viewed;
229
+ if (error.code === "not_found") {
230
+ answered += 1;
231
+ }
232
+ else if (answered > 0 && error.code === "rate_limited" && error.http_status === null) {
233
+ incomplete = true;
234
+ }
235
+ else {
236
+ return { ok: false, error };
237
+ }
238
+ items.push({ ...row, ...unviewed(own) });
239
+ }
240
+ return {
241
+ ok: true,
242
+ value: {
243
+ ...listEnvelope(call, {
244
+ items,
245
+ ...(more ? { next: page } : {}),
246
+ truncated: found.total > MAX_SEARCH_PAGE * SEARCH_PER_PAGE,
247
+ api_calls_used: calls,
248
+ }),
249
+ ...(incomplete ? { reply_signals_incomplete: true } : {}),
250
+ },
251
+ };
252
+ },
253
+ };