@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,602 @@
1
+ // `count_tickets` (SPEC §8.2, C7): ticket counts grouped by one or two
2
+ // fields over a period of `created_at` days and the `list_tickets` filters,
3
+ // aggregated in code. Per docs/architecture/ticket-queries.md
4
+ // (`count_tickets`, "Past 300 results", "Date boundary").
5
+ //
6
+ // - Group-by fields (checked first, before any request): one or two, each
7
+ // a ticket field by label or API name (trimmed, NFC, any case), each of a
8
+ // known closed type (GROUPABLE: number, decimal, checkbox, date,
9
+ // dropdown, ticket type, nested field, status, priority, source, agent,
10
+ // group). A free-text field is `free_text_field`, any other type, known
11
+ // or not, `unsupported_field` (a date-time among them: SPEC §8.2 names
12
+ // date, and a date-time is one group per ticket); a third field, none, a name no field
13
+ // has, several fields share, or the same field twice is `validation` too.
14
+ // The count of fields is checked before the schema is read, so a third
15
+ // field sends no request at all; the rest needs the schema (its load is
16
+ // the only request then, none when cached).
17
+ // - A group's key is the field's label through `plainName` (a second field
18
+ // with the same label is `Label (api_name)`); its value is what
19
+ // `ticketOutput` shows through `fieldValue` (names for status, priority,
20
+ // source, agent and group, the " > " path of a nested field, a validated
21
+ // choice plain, anything else wrapped). `null`, `""`, and a field
22
+ // `ticketOutput` leaves out count under `null`. Hidden fields: built on
23
+ // `ticketOutput` as it is, so a field the team hides counts every ticket
24
+ // under `null`; nothing else is done about `hidden`, which is not an
25
+ // access control (SPEC §7.3) and not guaranteed in counts. An agent or
26
+ // group is grouped by its id, not its name: when several ids in the
27
+ // result share a name, each shows as `Name (id)`.
28
+ // - Each ticket id is counted once: a ticket a later page repeats (it
29
+ // moved while the call read the pages) is skipped. One that moved the
30
+ // other way can be missing.
31
+ // - At most GROUP_CAP groups are returned, largest first; past it
32
+ // `groups_not_shown` says how many more and the result is `truncated`.
33
+ // - The query: `buildTicketQuery` with the filters and the period as
34
+ // `created_between`, so always a search query, exact on the days
35
+ // (measured, T-055). Search page 1 is the probe; every request of the
36
+ // call is `expensive` (below the limiter's reserve the probe is refused,
37
+ // nothing sent).
38
+ // - `total` ≤ 300 (SEARCH_CAP): the remaining search pages, estimated as
39
+ // the pages after the probe, `checkBudget` before them. Above: the list
40
+ // scan, `updated_since=<from>T00:00:00Z`, `order_by=created_at`,
41
+ // `order_type=asc`, LIST_PAGE_SIZE a page, the search filters checked on
42
+ // each ticket here (status, priority, group, agent by id, type by its
43
+ // resolved name, tag exactly as given among `tags`), stopped after the
44
+ // first page whose last ticket was created on a UTC day after the
45
+ // period. Its estimate is a floor, the probe plus one page per 100 of
46
+ // `total` (the scan also reads tickets created before the period, or not
47
+ // matching): `checkBudget` refuses it when even that is over the budget,
48
+ // and without `confirm: true` the scan stops at the budget while it runs
49
+ // (before a page once the ticket requests, retries included, reach it).
50
+ // `confirm` lifts the budget only, never SCAN_START_MS.
51
+ // A refused estimate has spent the probe: the message says so.
52
+ // - `matchesLocal` on every ticket either source returns (the period's
53
+ // guard, `uncategorized`).
54
+ // - `truncated: true` beside the counts when the source was cut: the scan
55
+ // stopped at the budget, at MAX_LIST_PAGE (it links a next page or comes
56
+ // back full), or at SCAN_START_MS; or a later page the limiter refused
57
+ // (`rate_limited` with no HTTP status), or one the call's deadline
58
+ // ended (`network` the client marks `http.reachedDeadline`: aborted at the
59
+ // deadline, T-037 review, 2026-11-24; or failed with no time left to
60
+ // retry before it, T-059).
61
+ // Any other failed request, and a failed probe, fails the call: no
62
+ // partial count.
63
+ // - One deadline for the whole call, CALL_DEADLINE_MS from its start. No
64
+ // page is started after SCAN_START_MS, so an attempt (10 s) is not cut
65
+ // in flight by the deadline.
66
+ // - `api_calls_used`: every request this call sent, retries included, and
67
+ // the schema's load when this call started it.
68
+ // - The read (probe, estimate, budget, search pages or list scan, each id
69
+ // once, the cuts) is `readPeriod`, with `periodQuery` for the query,
70
+ // exported for `export_tickets` (T-037): it hands each ticket to the
71
+ // caller's `take`, which may stop the read (a cut) or fail it, and counts
72
+ // the requests on the caller's `Meter`. For `export_tickets`' pages
73
+ // (T-057) it also takes a `resume` position and a `limit` (the estimate
74
+ // counts no more tickets than it), and gives `next`, where a later read
75
+ // resumes, whenever it stopped before the period's end (export-tickets.ts
76
+ // header); `count_tickets` passes neither and ignores `next`.
77
+ import { z } from "zod";
78
+ import { MAX_SEARCH_PAGE, searchTickets } from "../../../client/resources/search.js";
79
+ import { listTickets, MAX_LIST_PAGE } from "../../../client/resources/tickets.js";
80
+ import { checkBudget, estimateCalls } from "../../budget.js";
81
+ import { fieldValue, plainName } from "../../format.js";
82
+ import { buildTicketQuery, matchesLocal, resolveFilter, } from "../../ticket-query.js";
83
+ /** One call's requests end within this, all of them together. */
84
+ export const CALL_DEADLINE_MS = 30_000;
85
+ /** No page is started after this: an attempt started before it ends by the deadline. */
86
+ export const SCAN_START_MS = CALL_DEADLINE_MS - 10_000;
87
+ /** Tickets of a search page (Freshdesk's fixed size). */
88
+ export const SEARCH_PAGE_SIZE = 30;
89
+ /** Tickets of a list page of the scan (the endpoint's largest). */
90
+ export const LIST_PAGE_SIZE = 100;
91
+ /** Search answers this many results at most: past it, the list scan. */
92
+ const SEARCH_CAP = MAX_SEARCH_PAGE * SEARCH_PAGE_SIZE;
93
+ /** Group-by fields a call takes at most. */
94
+ export const MAX_GROUP_FIELDS = 2;
95
+ /** Groups a result shows at most, largest first. */
96
+ export const GROUP_CAP = 200;
97
+ /** Field types whose values form a closed set: the only ones a count groups by. */
98
+ const GROUPABLE = new Set([
99
+ "custom_number",
100
+ "custom_decimal",
101
+ "custom_checkbox",
102
+ "custom_date",
103
+ "custom_dropdown",
104
+ "default_ticket_type",
105
+ "nested_field",
106
+ "default_status",
107
+ "default_priority",
108
+ "default_source",
109
+ "default_agent",
110
+ "default_group",
111
+ ]);
112
+ const FREE_TEXT = new Set([
113
+ "custom_text",
114
+ "custom_paragraph",
115
+ "default_subject",
116
+ "default_description",
117
+ ]);
118
+ const nameOrId = z.union([z.string(), z.number()]);
119
+ const input = z.object({
120
+ group_by: z.array(z.string()),
121
+ created_between: z.object({ from: z.string(), to: z.string() }),
122
+ status: nameOrId.optional(),
123
+ priority: nameOrId.optional(),
124
+ group: nameOrId.optional(),
125
+ agent: nameOrId.optional(),
126
+ type: z.string().optional(),
127
+ tag: z.string().optional(),
128
+ uncategorized: z.boolean().optional(),
129
+ confirm: z.boolean().optional(),
130
+ });
131
+ /** Whether the ids fall strictly, as search's order (measured 2026-11-25) gives them. */
132
+ function falls(tickets) {
133
+ return tickets.every((ticket, i) => i === 0 || ticket.id < tickets[i - 1].id);
134
+ }
135
+ function refused(problem) {
136
+ return {
137
+ ok: false,
138
+ error: {
139
+ code: "validation",
140
+ http_status: null,
141
+ message: "The fields to group by are not valid; nothing was sent.",
142
+ retryable: false,
143
+ errors: [problem],
144
+ },
145
+ };
146
+ }
147
+ function fold(text) {
148
+ return text.normalize("NFC").trim().toLowerCase();
149
+ }
150
+ /** The group-by fields, or the first problem with them. */
151
+ function groupFields(schema, names) {
152
+ const fields = [];
153
+ for (const name of names) {
154
+ const shown = JSON.stringify(plainName(name, 80));
155
+ const matches = schema.fields.filter((field) => fold(field.label) === fold(name) || fold(field.name) === fold(name));
156
+ const problem = (code, message) => ({
157
+ field: "group_by",
158
+ code,
159
+ message,
160
+ });
161
+ if (matches.length === 0)
162
+ return problem("unknown_field", `No ticket field is named ${shown}.`);
163
+ if (matches.length > 1) {
164
+ const which = matches.map((field) => plainName(field.name)).join(", ");
165
+ return problem("ambiguous_name", `${shown} names several fields (${which}): give its API name.`);
166
+ }
167
+ const field = matches[0];
168
+ if (FREE_TEXT.has(field.type)) {
169
+ return problem("free_text_field", `${shown} is free text: counts group only by a field with a closed set of values.`);
170
+ }
171
+ if (field.type === "custom_date_time") {
172
+ return problem("unsupported_field", `${shown} is a date-time: nearly every ticket has its own, so it cannot group. Group by a date field instead.`);
173
+ }
174
+ if (!GROUPABLE.has(field.type)) {
175
+ return problem("unsupported_field", `${shown} is not of a type a count can group by (a number, checkbox, date, dropdown, type, nested field, status, priority, source, agent or group).`);
176
+ }
177
+ if (fields.includes(field))
178
+ return problem("duplicate_field", `${shown} is given twice.`);
179
+ fields.push(field);
180
+ }
181
+ return fields;
182
+ }
183
+ /** Where an agent's or a group's id sits on the ticket: they are grouped by it. */
184
+ const ID_KEY = {
185
+ default_agent: "responder_id",
186
+ default_group: "group_id",
187
+ };
188
+ /**
189
+ * What a ticket is counted under for one field: `shown`, the value shown
190
+ * (`null` when it shows none), and `key`, what groups it (the id for an agent
191
+ * or a group, else the value shown).
192
+ */
193
+ function groupValue(context, schema, field, ticket) {
194
+ const out = Object.values(context.ticketOutput({ ...schema, fields: [field] }, ticket));
195
+ const value = out[0];
196
+ if (value === undefined || value === null || value === "")
197
+ return { key: null, shown: null };
198
+ const shown = fieldValue(field, value);
199
+ const idKey = ID_KEY[field.type];
200
+ return { key: idKey === undefined ? shown : (ticket[idKey] ?? null), shown };
201
+ }
202
+ /** The search filters, checked on a list ticket (the scan cannot ask them of Freshdesk). */
203
+ function fieldMatcher(schema, args) {
204
+ const checks = [];
205
+ const keys = { status: "status", priority: "priority", group: "group_id", agent: "responder_id" };
206
+ for (const kind of ["status", "priority", "group", "agent"]) {
207
+ if (args[kind] === undefined)
208
+ continue;
209
+ const resolved = resolveFilter(schema, kind, args[kind]);
210
+ // Already resolved once by buildTicketQuery: a failure here fails closed.
211
+ const id = resolved.ok ? resolved.value : Number.NaN;
212
+ checks.push((ticket) => ticket[keys[kind]] === id);
213
+ }
214
+ if (args.type !== undefined) {
215
+ const resolved = resolveFilter(schema, "type", args.type);
216
+ const name = resolved.ok ? resolved.value : Number.NaN;
217
+ checks.push((ticket) => ticket.type === name);
218
+ }
219
+ if (args.tag !== undefined) {
220
+ const tag = args.tag;
221
+ checks.push((ticket) => Array.isArray(ticket.tags) && ticket.tags.includes(tag));
222
+ }
223
+ return (ticket) => checks.every((check) => check(ticket));
224
+ }
225
+ /** The UTC day a ticket was created on, or `undefined` when unreadable. */
226
+ function createdDay(ticket) {
227
+ const value = ticket?.created_at;
228
+ const time = typeof value === "string" ? Date.parse(value) : Number.NaN;
229
+ return Number.isNaN(time) ? undefined : new Date(time).toISOString().slice(0, 10);
230
+ }
231
+ /** The second (epoch, UTC) a ticket was created in, or `undefined` when unreadable. */
232
+ function createdSecond(ticket) {
233
+ const value = ticket.created_at;
234
+ const time = typeof value === "string" ? Date.parse(value) : Number.NaN;
235
+ return Number.isNaN(time) ? undefined : Math.floor(time / 1000);
236
+ }
237
+ /** An epoch second as the list's `updated_since`: `2026-01-02T03:04:05Z`. */
238
+ function instantOf(second) {
239
+ return new Date(second * 1000).toISOString().replace(/\.\d{3}Z$/, "Z");
240
+ }
241
+ /**
242
+ * A later request that cuts the source rather than failing the call: one the
243
+ * limiter refused before sending (`rate_limited`, no HTTP status), or one the
244
+ * call's deadline ended (`network` the client marks so: aborted at it, or
245
+ * failed with no time left to retry before it; `http.reachedDeadline`, T-059).
246
+ */
247
+ export function isCut(error, context) {
248
+ return ((error.code === "rate_limited" && error.http_status === null) ||
249
+ (error.code === "network" && context.http.reachedDeadline(error)));
250
+ }
251
+ function calls(n) {
252
+ return `${n} API call${n === 1 ? "" : "s"}`;
253
+ }
254
+ /** The period and the filters as one search query (`created_between` always makes one). */
255
+ export function periodQuery(context, schema, args) {
256
+ const query = buildTicketQuery(context, schema, {
257
+ ...(args.status === undefined ? {} : { status: args.status }),
258
+ ...(args.priority === undefined ? {} : { priority: args.priority }),
259
+ ...(args.group === undefined ? {} : { group: args.group }),
260
+ ...(args.agent === undefined ? {} : { agent: args.agent }),
261
+ ...(args.type === undefined ? {} : { type: args.type }),
262
+ ...(args.tag === undefined ? {} : { tag: args.tag }),
263
+ ...(args.uncategorized === undefined ? {} : { uncategorized: args.uncategorized }),
264
+ created_between: args.created_between,
265
+ });
266
+ if (!query.ok)
267
+ return query;
268
+ if (query.endpoint !== "search") {
269
+ // created_between is always a search condition: fail closed otherwise.
270
+ throw new Error("periodQuery: the period did not make a search query");
271
+ }
272
+ return query;
273
+ }
274
+ /**
275
+ * Every ticket of the period and filters, each id once, handed to `take`:
276
+ * search when its total is SEARCH_CAP or less, else the ordered list scan
277
+ * (this file's header), from `resume` when given. Counts what it sends on
278
+ * `meter`; `truncated` when the read was cut, or `take` stopped it; `next`
279
+ * where a later read resumes, whenever it stopped before the period's end.
280
+ */
281
+ export async function readPeriod(context, schema, args, query, { started, deadline, meter, conversations, take, resume, limit }) {
282
+ const from = resume ?? { path: "start" };
283
+ const seen = new Set();
284
+ const spent = (error) => ({
285
+ ok: false,
286
+ error: {
287
+ ...error,
288
+ message: `${error.message} This call has already used ${calls(meter.used)} to learn the total.`,
289
+ },
290
+ });
291
+ /** The read stopped before the period's end: `at` is where it resumes. */
292
+ const cut = (at) => ({ ok: true, truncated: true, next: at });
293
+ const budget = args.confirm === true ? Infinity : context.team.limits.call_budget;
294
+ // A search position starts at the page that held its last ticket: that page is the probe.
295
+ const below = from.path === "search" ? from.below : undefined;
296
+ let firstPage = from.path === "search" ? from.page : 1;
297
+ let probe = await searchTickets(context.http, query.query, firstPage, deadline, "expensive");
298
+ if (!probe.ok)
299
+ return probe;
300
+ meter.used += probe.attempts;
301
+ meter.requests += probe.attempts;
302
+ /** A search position holds only while ids fall: past a disorder, a resumed read fails closed. */
303
+ const disordered = () => spent({
304
+ code: "validation",
305
+ http_status: null,
306
+ message: "Freshdesk's search gave this period's tickets out of id order, so it cannot be paged safely from a cursor: nothing was kept. Export it without max_tickets and without a cursor, in shorter periods.",
307
+ retryable: false,
308
+ });
309
+ if (below !== undefined && !falls(probe.results))
310
+ return disordered();
311
+ // Tickets that left the results since moved the rest forward: while the page starts
312
+ // below the boundary (or is empty), the boundary is on an earlier page.
313
+ while (below !== undefined && firstPage > 1 && (probe.results[0]?.id ?? 0) < below) {
314
+ // Counted against the budget and the time limit like any later page; the position stays.
315
+ if (meter.requests >= budget || Date.now() - started >= SCAN_START_MS)
316
+ return cut(from);
317
+ firstPage -= 1;
318
+ const earlier = await searchTickets(context.http, query.query, firstPage, deadline, "expensive");
319
+ if (!earlier.ok) {
320
+ if (!isCut(earlier.error, context))
321
+ return earlier;
322
+ meter.used += earlier.attempts ?? 0;
323
+ meter.requests += earlier.attempts ?? 0;
324
+ return cut(from);
325
+ }
326
+ meter.used += earlier.attempts;
327
+ meter.requests += earlier.attempts;
328
+ const after = probe.results[0];
329
+ const last = earlier.results.at(-1);
330
+ if (!falls(earlier.results) || (after && last && last.id <= after.id))
331
+ return disordered();
332
+ probe = earlier;
333
+ }
334
+ if (from.path === "search" && probe.total > SEARCH_CAP) {
335
+ return spent({
336
+ code: "validation",
337
+ http_status: null,
338
+ message: `The period now matches more than ${SEARCH_CAP} tickets, so the cursor's position in Freshdesk's search no longer holds: nothing was kept. Call again without a cursor to start over.`,
339
+ retryable: false,
340
+ });
341
+ }
342
+ if (from.path === "search" || (from.path === "start" && probe.total <= SEARCH_CAP)) {
343
+ // The results this call reads at most: the caller's limit from the first page read.
344
+ const skipped = (firstPage - 1) * SEARCH_PAGE_SIZE;
345
+ const end = Math.min(probe.total, limit === undefined ? probe.total : skipped + limit);
346
+ const estimate = estimateCalls({
347
+ tickets: Math.max(0, end - firstPage * SEARCH_PAGE_SIZE),
348
+ pageSize: SEARCH_PAGE_SIZE,
349
+ conversations: false,
350
+ probe: 1,
351
+ }) + (conversations ? Math.max(0, end - skipped) : 0);
352
+ const refusal = checkBudget(context, estimate, args.confirm);
353
+ if (refusal)
354
+ return spent(refusal);
355
+ /** The lowest id taken, and the page that held it. */
356
+ let lowest = from.path === "search" ? { below: from.below, page: from.page } : undefined;
357
+ /** The id before, across every page read: a fresh read past a disorder gives no position. */
358
+ let previous;
359
+ let unordered = false;
360
+ const stopped = () => unordered
361
+ ? { ok: true, truncated: true, unordered: true }
362
+ : cut(lowest === undefined ? { path: "start" } : { path: "search", ...lowest });
363
+ const pages = Math.ceil(probe.total / SEARCH_PAGE_SIZE);
364
+ let results = probe.results;
365
+ for (let page = firstPage;; page++) {
366
+ if (page > firstPage) {
367
+ if (page > pages)
368
+ break;
369
+ // Ticket requests, retries included, at the budget: no further page (the local checks can drop results).
370
+ if (meter.requests >= budget || Date.now() - started >= SCAN_START_MS)
371
+ return stopped();
372
+ const found = await searchTickets(context.http, query.query, page, deadline, "expensive");
373
+ if (!found.ok) {
374
+ if (!isCut(found.error, context))
375
+ return found;
376
+ meter.used += found.attempts ?? 0;
377
+ meter.requests += found.attempts ?? 0;
378
+ return stopped();
379
+ }
380
+ meter.used += found.attempts;
381
+ meter.requests += found.attempts;
382
+ results = found.results;
383
+ }
384
+ for (const ticket of results) {
385
+ if (previous !== undefined && ticket.id >= previous) {
386
+ // Resumed: the boundary may have dropped a ticket unseen. Fresh: nothing was skipped.
387
+ if (below !== undefined)
388
+ return disordered();
389
+ unordered = true;
390
+ }
391
+ previous = ticket.id;
392
+ // At or past the boundary: taken by an earlier call, or created since the first.
393
+ if (below !== undefined && ticket.id >= below)
394
+ continue;
395
+ if (!matchesLocal(query, ticket))
396
+ continue;
397
+ // A ticket a later page repeats (it moved during the call) is taken once.
398
+ if (seen.has(ticket.id))
399
+ continue;
400
+ seen.add(ticket.id);
401
+ const taken = await take(ticket);
402
+ if (taken === false)
403
+ return stopped();
404
+ if (taken !== true)
405
+ return { ok: false, error: taken };
406
+ if (lowest === undefined || ticket.id < lowest.below)
407
+ lowest = { below: ticket.id, page };
408
+ }
409
+ }
410
+ return { ok: true, truncated: false };
411
+ }
412
+ const estimate = estimateCalls({
413
+ tickets: limit === undefined ? probe.total : Math.min(probe.total, limit),
414
+ pageSize: LIST_PAGE_SIZE,
415
+ conversations,
416
+ probe: 1,
417
+ });
418
+ const refusal = checkBudget(context, estimate, args.confirm);
419
+ if (refusal)
420
+ return spent(refusal);
421
+ const matches = fieldMatcher(schema, args);
422
+ const { to } = args.created_between;
423
+ /** Taken before this read: tickets created before `skip.second`, and the first `skip.ties` created in it. */
424
+ const skip = from.path === "list" ? from : undefined;
425
+ let skipped = 0;
426
+ /** The latest second taken and how many tickets created in it were taken. */
427
+ let last = skip === undefined ? undefined : { second: skip.second, ties: skip.ties };
428
+ const here = () => (last === undefined ? { path: "start" } : { path: "list", ...last });
429
+ // Every ticket created in or after a second was updated in or after it: the list from just before it holds them all.
430
+ const since = skip === undefined ? `${args.created_between.from}T00:00:00Z` : instantOf(skip.second - 1);
431
+ for (let page = 1;; page++) {
432
+ // Ticket requests, retries included, at the budget: no further page.
433
+ if (meter.requests >= budget || Date.now() - started >= SCAN_START_MS)
434
+ return cut(here());
435
+ const listed = await listTickets(context.http, {
436
+ per_page: LIST_PAGE_SIZE,
437
+ page,
438
+ updated_since: since,
439
+ order_by: "created_at",
440
+ order_type: "asc",
441
+ }, deadline, "expensive");
442
+ if (!listed.ok) {
443
+ if (!isCut(listed.error, context))
444
+ return listed;
445
+ meter.used += listed.attempts ?? 0;
446
+ meter.requests += listed.attempts ?? 0;
447
+ return cut(here());
448
+ }
449
+ meter.used += listed.attempts;
450
+ meter.requests += listed.attempts;
451
+ for (const ticket of listed.tickets) {
452
+ if (!matches(ticket) || !matchesLocal(query, ticket))
453
+ continue;
454
+ if (seen.has(ticket.id))
455
+ continue;
456
+ seen.add(ticket.id);
457
+ // In the period (matchesLocal), so its created_at reads.
458
+ const second = createdSecond(ticket);
459
+ if (second === undefined)
460
+ continue;
461
+ if (skip !== undefined) {
462
+ if (second < skip.second)
463
+ continue;
464
+ if (second === skip.second && skipped < skip.ties) {
465
+ skipped += 1;
466
+ continue;
467
+ }
468
+ }
469
+ const taken = await take(ticket);
470
+ if (taken === false)
471
+ return cut(here());
472
+ if (taken !== true)
473
+ return { ok: false, error: taken };
474
+ // Out of order (an earlier second after a later one): the position stays at the later.
475
+ if (last === undefined || second > last.second)
476
+ last = { second, ties: 1 };
477
+ else if (second === last.second)
478
+ last.ties += 1;
479
+ }
480
+ const lastDay = createdDay(listed.tickets.at(-1));
481
+ if (lastDay !== undefined && lastDay > to)
482
+ break;
483
+ if (page === MAX_LIST_PAGE) {
484
+ if (listed.has_more || listed.tickets.length === LIST_PAGE_SIZE)
485
+ return cut(here());
486
+ break;
487
+ }
488
+ if (!listed.has_more)
489
+ break;
490
+ }
491
+ return { ok: true, truncated: false };
492
+ }
493
+ export const countTicketsTool = {
494
+ name: "count_tickets",
495
+ description: [
496
+ `Counts of the tickets created in a period, grouped by one or two ticket fields (group_by, by label or API name), counted here from every matching ticket. created_between {from, to}: days as YYYY-MM-DD, UTC, both included. Filters as list_tickets: status, priority, group and agent by name or id; type by name; tag (one tag, exact); uncategorized: true.`,
497
+ `Only a field with a closed set of values can group: a number, checkbox, date, dropdown, type, nested field (its full path), status, priority, source, agent or group. A free-text field or any other is refused, and nothing is sent.`,
498
+ `Example: {"group_by": ["Status", "Priority"], "created_between": {"from": "2026-01-01", "to": "2026-01-31"}} returns {"groups": [{"values": {"Status": "Open", "Priority": "High"}, "count": 2}, ...], "total": 2, "api_calls_used": 1}: groups by count, largest first; total is the tickets counted. A ticket with no value counts under null, and so does every ticket when the team config hides the field. Agents and groups that share a name show as "Name (id)". At most ${GROUP_CAP} groups are shown, the largest; groups_not_shown says how many more.`,
499
+ `Up to ${SEARCH_CAP} matching tickets it reads Freshdesk's search, ${SEARCH_PAGE_SIZE} a request; above that it reads the list of tickets updated since the period's start, oldest created first, ${LIST_PAGE_SIZE} a request, until it passes the period's end. It first asks for one search page to learn the size, estimates the calls, and is refused when the estimate is over the per-call API budget: narrow the period or the filters, or call again with confirm: true. Without confirm the list read also stops at the budget. confirm lifts the API budget only, not the time limit: the list read starts no request after ${SCAN_START_MS / 1000} s, about ${(SCAN_START_MS / 1000) * 2} requests (${((SCAN_START_MS / 1000) * 2 * LIST_PAGE_SIZE).toLocaleString("en-US")} tickets) at the default pacing.`,
500
+ `When the read was cut (the budget, Freshdesk's last list page, the time limit, or the API rate limit), the counts are of what was read and say truncated: true (so does a result past ${GROUP_CAP} groups): narrow the period or call again later. It counts as an expensive operation and is refused when the API budget is low. A ticket changed in the last few minutes, or while the call reads, can be missing; no ticket is counted twice.`,
501
+ "api_calls_used counts every request sent for this call, retries included, and the ticket-field schema's load when this call starts it.",
502
+ ].join(" "),
503
+ input,
504
+ annotations: {
505
+ readOnlyHint: true,
506
+ destructiveHint: false,
507
+ idempotentHint: true,
508
+ openWorldHint: true,
509
+ },
510
+ cost: `1 API call per ${SEARCH_PAGE_SIZE} matching tickets up to ${SEARCH_CAP} (${MAX_SEARCH_PAGE} at most); above that 1 plus 1 per ${LIST_PAGE_SIZE} tickets read, up to the per-call budget (limits.call_budget, 250 by default) unless confirm: true, and a list read starts no request after ${SCAN_START_MS / 1000} s (about ${(SCAN_START_MS / 1000) * 2} at the default pacing); all within 30 s, plus one per retry after an error, plus at least 3 when the ticket-field schema is not cached`,
511
+ customerText: true,
512
+ async handler(args, context) {
513
+ const started = Date.now();
514
+ const deadline = started + CALL_DEADLINE_MS;
515
+ if (args.group_by.length === 0 || args.group_by.length > MAX_GROUP_FIELDS) {
516
+ return refused({
517
+ field: "group_by",
518
+ code: args.group_by.length === 0 ? "no_field" : "too_many_fields",
519
+ message: `group_by takes one or ${MAX_GROUP_FIELDS} fields.`,
520
+ });
521
+ }
522
+ const loaded = await context.schema.get();
523
+ if (!loaded.ok)
524
+ return loaded;
525
+ const { schema } = loaded;
526
+ const fields = groupFields(schema, args.group_by);
527
+ if (!Array.isArray(fields))
528
+ return refused(fields);
529
+ const query = periodQuery(context, schema, args);
530
+ if (!query.ok)
531
+ return query;
532
+ const keys = [];
533
+ for (const field of fields) {
534
+ const label = plainName(field.label);
535
+ keys.push(keys.includes(label) ? `${label} (${plainName(field.name)})` : label);
536
+ }
537
+ const groups = new Map();
538
+ let total = 0;
539
+ const count = (ticket) => {
540
+ const parts = fields.map((field) => groupValue(context, schema, field, ticket));
541
+ const keys = parts.map((part) => part.key);
542
+ const id = JSON.stringify(keys);
543
+ const group = groups.get(id);
544
+ if (group)
545
+ group.count += 1;
546
+ else
547
+ groups.set(id, { keys, shown: parts.map((part) => part.shown), count: 1 });
548
+ total += 1;
549
+ };
550
+ const meter = { used: loaded.attempts, requests: 0 };
551
+ const read = await readPeriod(context, schema, args, query, {
552
+ started,
553
+ deadline,
554
+ meter,
555
+ conversations: false,
556
+ take: (ticket) => {
557
+ count(ticket);
558
+ return true;
559
+ },
560
+ });
561
+ if (!read.ok)
562
+ return read;
563
+ const sorted = [...groups.entries()].sort(([a, x], [b, y]) => y.count !== x.count ? y.count - x.count : a < b ? -1 : a > b ? 1 : 0);
564
+ // An agent or group name several ids share in this result shows its id.
565
+ const shared = fields.map((field, i) => {
566
+ const ids = new Map();
567
+ if (ID_KEY[field.type] !== undefined) {
568
+ for (const group of groups.values()) {
569
+ const set = ids.get(group.shown[i]) ?? new Set();
570
+ set.add(group.keys[i]);
571
+ ids.set(group.shown[i], set);
572
+ }
573
+ }
574
+ return (shown) => shown !== null && (ids.get(shown)?.size ?? 0) > 1;
575
+ });
576
+ const shownGroups = sorted.slice(0, GROUP_CAP);
577
+ const notShown = sorted.length - shownGroups.length;
578
+ return {
579
+ ok: true,
580
+ value: {
581
+ groups: shownGroups.map(([, group]) => {
582
+ const values = {};
583
+ group.shown.forEach((shown, i) => {
584
+ const value = shared[i](shown) ? `${String(shown)} (${String(group.keys[i])})` : shown;
585
+ // Defined, not assigned: a label `__proto__` stays an own key.
586
+ Object.defineProperty(values, keys[i], {
587
+ value,
588
+ enumerable: true,
589
+ writable: true,
590
+ configurable: true,
591
+ });
592
+ });
593
+ return { values, count: group.count };
594
+ }),
595
+ ...(notShown > 0 ? { groups_not_shown: notShown } : {}),
596
+ total,
597
+ ...(read.truncated || notShown > 0 ? { truncated: true } : {}),
598
+ api_calls_used: meter.used,
599
+ },
600
+ };
601
+ },
602
+ };