@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.
Files changed (45) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +205 -0
  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 +40 -3
@@ -0,0 +1,260 @@
1
+ // Input mapping (SPEC §7.3): what a tool is given, as `{field: value}`, turned
2
+ // into a Freshdesk API v2 ticket body, checked against the schema's choices.
3
+ //
4
+ // - A field is named by its API name, compared exactly, or by its label,
5
+ // compared trimmed, NFC-normalised and lower-cased (`fold`, as for hidden
6
+ // fields). A key that names more than one field, as a shared label or as
7
+ // one field's API name and another's label, is refused, naming their API
8
+ // names; so is a field given twice, a name no field has, and a key whose
9
+ // value would land where another key's already did. A nested level is not
10
+ // a field: its top field takes the path.
11
+ // - Where a value goes: a default field's at the body's top level under its
12
+ // ticket key (`agent` → `responder_id`), a custom field's under
13
+ // `custom_fields`, as output.ts reads them.
14
+ // - A value is matched like a label: an exact choice first, then a single
15
+ // choice that folds alike; Freshdesk's own spelling is sent. Several
16
+ // choices folding alike and none exact is refused.
17
+ // dropdown, ticket type a choice from the list
18
+ // status its agent name, or an id it has → the id
19
+ // priority, source a name, or an id among them → the id
20
+ // nested field "A > B > C": each level among the choices
21
+ // under the one before; a shorter path sends
22
+ // `null` for the levels after it, a longer one
23
+ // is refused
24
+ // any other type with a non-empty list of choices, one of
25
+ // them; with choices of another shape,
26
+ // refused; with none, passed through unchanged
27
+ // (agent, group and requester stay ids)
28
+ // A status, priority or source name two ids share is refused; a status
29
+ // key that is not a whole number is not offered.
30
+ // - `null` clears a field (every level of a nested one); a key not given
31
+ // is not sent. `null` and absent `choices` are alike.
32
+ // - Every problem is reported, as one `validation` error whose `errors[]`
33
+ // has one entry per input key, at most MAX_FIELD_ERRORS; an invalid
34
+ // choice lists the valid ones at the failing level. Echoed keys and
35
+ // values and the choice lists are clipped, each message to
36
+ // MAX_FIELD_TEXT. `http_status` is `null`: nothing was sent.
37
+ // - Lookups use own keys only, and the body is built with defined
38
+ // properties: a name such as `__proto__` or `constructor` is data.
39
+ import { MAX_FIELD_ERRORS, MAX_FIELD_TEXT, } from "../client/errors.js";
40
+ import { fold, ticketKey } from "./output.js";
41
+ /** Characters of an echoed key or value, and of a list of choices, in a message. */
42
+ const MAX_QUOTE = 80;
43
+ const MAX_LIST = 300;
44
+ /** One problem with one input key, before it becomes a FieldError. */
45
+ class Refusal {
46
+ code;
47
+ message;
48
+ constructor(code, message) {
49
+ this.code = code;
50
+ this.message = message;
51
+ }
52
+ }
53
+ function isRecord(value) {
54
+ return typeof value === "object" && value !== null && !Array.isArray(value);
55
+ }
56
+ function put(target, key, value) {
57
+ Object.defineProperty(target, key, {
58
+ value,
59
+ enumerable: true,
60
+ writable: true,
61
+ configurable: true,
62
+ });
63
+ }
64
+ function clip(text, max) {
65
+ return text.length > max ? `${text.slice(0, max - 1)}…` : text;
66
+ }
67
+ /** A key or value as JSON, clipped: what a message may echo of the input. */
68
+ function quote(value) {
69
+ let text;
70
+ try {
71
+ text = JSON.stringify(value);
72
+ }
73
+ catch {
74
+ text = undefined;
75
+ }
76
+ return clip(text ?? String(typeof value), MAX_QUOTE);
77
+ }
78
+ function listed(options) {
79
+ if (options.length === 0)
80
+ return "(none)";
81
+ const shown = [];
82
+ let length = 0;
83
+ for (const option of options) {
84
+ const text = quote(option);
85
+ if (shown.length > 0 && length + text.length > MAX_LIST)
86
+ break;
87
+ shown.push(text);
88
+ length += text.length + 2;
89
+ }
90
+ const rest = options.length - shown.length;
91
+ return shown.join(", ") + (rest > 0 ? ` … and ${rest} more` : "");
92
+ }
93
+ function findField(schema, key) {
94
+ const found = schema.fields.filter((field) => field.name === key || fold(field.label) === fold(key));
95
+ if (found.length === 1)
96
+ return found[0];
97
+ if (found.length > 1) {
98
+ return new Refusal("ambiguous_field", `${quote(key)} names several fields (${listed(found.map((field) => field.name))}): name one by its API name or its own label.`);
99
+ }
100
+ return new Refusal("unknown_field", `No ticket field is named or labelled ${quote(key)}.`);
101
+ }
102
+ /** The option `wanted` names: exact first, then the one option that folds alike. */
103
+ function pick(options, wanted, where) {
104
+ if (typeof wanted === "string") {
105
+ if (options.includes(wanted))
106
+ return wanted;
107
+ const alike = options.filter((option) => fold(option) === fold(wanted));
108
+ if (alike.length === 1)
109
+ return alike[0];
110
+ if (alike.length > 1) {
111
+ return new Refusal("ambiguous_choice", `${quote(wanted)} matches several choices for ${where} (${listed(alike)}): give one exactly.`);
112
+ }
113
+ }
114
+ return new Refusal("invalid_choice", `${quote(wanted)} is not a valid choice for ${where}. Valid choices: ${listed(options)}.`);
115
+ }
116
+ /** name → id pairs of a status (its agent name), priority or source. */
117
+ function namedIds(field) {
118
+ const choices = field.choices;
119
+ if (!isRecord(choices))
120
+ return [];
121
+ const pairs = [];
122
+ for (const [key, entry] of Object.entries(choices)) {
123
+ if (field.type === "default_status") {
124
+ if (/^\d+$/.test(key) && Array.isArray(entry) && typeof entry[0] === "string") {
125
+ pairs.push([entry[0], Number(key)]);
126
+ }
127
+ }
128
+ else if (typeof entry === "number") {
129
+ pairs.push([key, entry]);
130
+ }
131
+ }
132
+ return pairs;
133
+ }
134
+ function idValue(field, value) {
135
+ const pairs = namedIds(field);
136
+ if (typeof value === "number" && pairs.some(([, id]) => id === value))
137
+ return value;
138
+ const where = `field ${field.label}`;
139
+ const name = pick(pairs.map(([label]) => label), value, where);
140
+ if (name instanceof Refusal)
141
+ return name;
142
+ const ids = pairs.filter(([label]) => label === name).map(([, id]) => id);
143
+ if (ids.length > 1) {
144
+ return new Refusal("ambiguous_choice", `${quote(name)} names several ids for ${where} (${ids.join(", ")}): give the id.`);
145
+ }
146
+ return ids[0];
147
+ }
148
+ function levelFields(field) {
149
+ const levels = [...(field.nested_ticket_fields ?? [])].sort((a, b) => a.level - b.level);
150
+ return [{ name: field.name, label: field.label }, ...levels];
151
+ }
152
+ /** "A > B > C" → each level's API name and Freshdesk's spelling of its choice. */
153
+ function nestedValues(field, value) {
154
+ const levels = levelFields(field);
155
+ if (value === null)
156
+ return levels.map((level) => [level.name, null]);
157
+ if (typeof value !== "string") {
158
+ return new Refusal("invalid_choice", `Field ${field.label} takes a path such as "A > B" as a string.`);
159
+ }
160
+ const parts = value.split(" > ");
161
+ if (parts.length > levels.length) {
162
+ return new Refusal("invalid_choice", `Field ${field.label} has ${levels.length} levels; the path ${quote(value)} has ${parts.length}.`);
163
+ }
164
+ const out = levels.map((level) => [level.name, null]);
165
+ const chosen = [];
166
+ let node = field.choices;
167
+ for (const [i, part] of parts.entries()) {
168
+ const options = Array.isArray(node)
169
+ ? node
170
+ : isRecord(node)
171
+ ? Object.keys(node)
172
+ : [];
173
+ const under = chosen.length > 0 ? ` under ${chosen.join(" > ")}` : "";
174
+ const picked = pick(options, part, `level ${levels[i].label}${under}`);
175
+ if (picked instanceof Refusal)
176
+ return picked;
177
+ out[i][1] = picked;
178
+ chosen.push(picked);
179
+ node = isRecord(node) && Object.hasOwn(node, picked) ? node[picked] : undefined;
180
+ }
181
+ return out;
182
+ }
183
+ /** The field's value or values as `[API name, value]`, or why it is refused. */
184
+ function fieldValues(field, value) {
185
+ if (field.type === "nested_field")
186
+ return nestedValues(field, value);
187
+ if (value === null)
188
+ return [[field.name, null]];
189
+ switch (field.type) {
190
+ case "default_status":
191
+ case "default_priority":
192
+ case "default_source": {
193
+ const id = idValue(field, value);
194
+ return id instanceof Refusal ? id : [[field.name, id]];
195
+ }
196
+ case "custom_dropdown":
197
+ case "default_ticket_type": {
198
+ const options = Array.isArray(field.choices) ? field.choices : [];
199
+ const choice = pick(options, value, `field ${field.label}`);
200
+ return choice instanceof Refusal ? choice : [[field.name, choice]];
201
+ }
202
+ }
203
+ const choices = field.choices;
204
+ if (Array.isArray(choices) && choices.length > 0) {
205
+ const choice = pick(choices, value, `field ${field.label}`);
206
+ return choice instanceof Refusal ? choice : [[field.name, choice]];
207
+ }
208
+ if (choices && !Array.isArray(choices) && Object.keys(choices).length > 0) {
209
+ return new Refusal("unsupported_field", `Field ${field.label} has choices this server cannot check: it cannot be set here.`);
210
+ }
211
+ return [[field.name, value]];
212
+ }
213
+ export function ticketInput(schema, input) {
214
+ const body = {};
215
+ const custom = {};
216
+ const seen = new Set();
217
+ const problems = [];
218
+ for (const [key, value] of Object.entries(input)) {
219
+ const field = findField(schema, key);
220
+ let values = field instanceof Refusal
221
+ ? field
222
+ : seen.has(field.name)
223
+ ? new Refusal("duplicate_field", `Field ${field.label} is given more than once.`)
224
+ : fieldValues(field, value);
225
+ const isDefault = !(field instanceof Refusal) && field.default;
226
+ const target = isDefault ? body : custom;
227
+ if (!(values instanceof Refusal) &&
228
+ values.some(([name]) => Object.hasOwn(target, ticketKey(name, isDefault)))) {
229
+ values = new Refusal("duplicate_field", `${quote(key)} sets a ticket field another key already sets.`);
230
+ }
231
+ if (values instanceof Refusal) {
232
+ problems.push({
233
+ field: clip(key, MAX_FIELD_TEXT),
234
+ code: values.code,
235
+ message: clip(values.message, MAX_FIELD_TEXT),
236
+ });
237
+ continue;
238
+ }
239
+ seen.add(field.name);
240
+ for (const [name, shown] of values)
241
+ put(target, ticketKey(name, isDefault), shown);
242
+ }
243
+ if (problems.length > 0) {
244
+ const hidden = problems.length - MAX_FIELD_ERRORS;
245
+ return {
246
+ ok: false,
247
+ error: {
248
+ code: "validation",
249
+ http_status: null,
250
+ message: "Some ticket fields are not valid; nothing was sent." +
251
+ (hidden > 0 ? ` ${hidden} more problems are not listed.` : ""),
252
+ retryable: false,
253
+ errors: problems.slice(0, MAX_FIELD_ERRORS),
254
+ },
255
+ };
256
+ }
257
+ if (Object.keys(custom).length > 0)
258
+ put(body, "custom_fields", custom);
259
+ return { ok: true, body };
260
+ }
@@ -0,0 +1,138 @@
1
+ // Output mapping (SPEC §7.3, §8.4): a raw API v2 ticket as `{label: value}`,
2
+ // one key per ticket field, in the order of the field list.
3
+ //
4
+ // - Where a value is: a default field's at the ticket's top level under its
5
+ // API key (`agent` → `responder_id`, `group` → `group_id`, ...), a custom
6
+ // field's under `custom_fields`. A key the ticket does not carry leaves
7
+ // the field out; `null` stays `null`.
8
+ // - Status, priority and source become their names, agent and group their
9
+ // names from the schema's maps. Which rule applies is decided by the
10
+ // field's `type`, never by the shape of its choices: a status's choices
11
+ // and a 2-level tree look alike.
12
+ // - A nested field is one key, its top label, with the path of its levels
13
+ // joined by " > ", stopping at the first empty level.
14
+ // - An id that cannot be resolved is named, not guessed: `unknown status 9`;
15
+ // for an agent or group missing from a list that was truncated,
16
+ // `agent 9 (name not loaded: the agent list is incomplete)`.
17
+ // - `null` and absent `choices` or `nested_ticket_fields` are alike.
18
+ // - Requester, company and product show the ticket's raw id: their names
19
+ // need contacts, companies and products, not loaded here.
20
+ // - Hidden (team config `fields`): a key matches a field's label, its API
21
+ // name or, for a default field, its ticket key (`responder_id`), compared
22
+ // trimmed, NFC-normalised and lower-cased. The field is left out; a
23
+ // hidden nested level cuts the path before it.
24
+ // - A label already used keys the later field as `Label (api_name)`.
25
+ //
26
+ // Not here: the requester's name (needs contacts, M1), the ticket's own keys
27
+ // such as id and dates, and untrusted-content wrapping (SPEC §7.4, M1).
28
+ /** Default fields whose value sits under another key of the ticket. */
29
+ const TICKET_KEY = new Map([
30
+ ["agent", "responder_id"],
31
+ ["group", "group_id"],
32
+ ["requester", "requester_id"],
33
+ ["company", "company_id"],
34
+ ["product", "product_id"],
35
+ ["ticket_type", "type"],
36
+ ]);
37
+ /** Where a field's value sits in the ticket: a top-level key or one of `custom_fields`. */
38
+ export function ticketKey(name, isDefault) {
39
+ return isDefault ? (TICKET_KEY.get(name) ?? name) : name;
40
+ }
41
+ /** How a hidden key and a field's names are compared. */
42
+ export function fold(text) {
43
+ return text.normalize("NFC").trim().toLowerCase();
44
+ }
45
+ function isRecord(value) {
46
+ return typeof value === "object" && value !== null && !Array.isArray(value);
47
+ }
48
+ /** The field's value in the ticket, or `undefined` when the ticket has no such key. */
49
+ function rawValue(ticket, name, isDefault) {
50
+ const holder = isDefault ? ticket : ticket.custom_fields;
51
+ const key = ticketKey(name, isDefault);
52
+ if (!isRecord(holder) || !Object.hasOwn(holder, key))
53
+ return undefined;
54
+ return holder[key];
55
+ }
56
+ /** A status's choices: id → [agent label, customer label]. */
57
+ function statusName(choices, value) {
58
+ const id = String(value);
59
+ const entry = isRecord(choices) && Object.hasOwn(choices, id) ? choices[id] : undefined;
60
+ return Array.isArray(entry) && typeof entry[0] === "string"
61
+ ? entry[0]
62
+ : `unknown status ${String(value)}`;
63
+ }
64
+ /** A priority's or source's choices: name → id. */
65
+ function idName(kind, choices, value) {
66
+ const found = isRecord(choices)
67
+ ? Object.entries(choices).find(([, id]) => id === value)
68
+ : undefined;
69
+ return found ? found[0] : `unknown ${kind} ${String(value)}`;
70
+ }
71
+ function mapName(kind, map, value) {
72
+ const name = typeof value === "number" ? map.names.get(value) : undefined;
73
+ if (name !== undefined)
74
+ return name;
75
+ return map.truncated
76
+ ? `${kind} ${String(value)} (name not loaded: the ${kind} list is incomplete)`
77
+ : `unknown ${kind} ${String(value)}`;
78
+ }
79
+ function nestedPath(field, ticket, top, hidden) {
80
+ if (top === null || top === "")
81
+ return top;
82
+ const parts = [String(top)];
83
+ const levels = [...(field.nested_ticket_fields ?? [])].sort((a, b) => a.level - b.level);
84
+ for (const level of levels) {
85
+ if (hidden(level.name, level.label))
86
+ break;
87
+ const value = rawValue(ticket, level.name, field.default);
88
+ if (value === undefined || value === null || value === "")
89
+ break;
90
+ parts.push(String(value));
91
+ }
92
+ return parts.join(" > ");
93
+ }
94
+ export function ticketOutput(schema, ticket, fields) {
95
+ const hiddenKeys = new Set(Object.entries(fields)
96
+ .filter(([, entry]) => entry.hidden)
97
+ .map(([key]) => fold(key)));
98
+ const hidden = (...names) => names.some((name) => hiddenKeys.has(fold(name)));
99
+ const out = {};
100
+ for (const field of schema.fields) {
101
+ if (hidden(field.name, field.label, ticketKey(field.name, field.default)))
102
+ continue;
103
+ const value = rawValue(ticket, field.name, field.default);
104
+ if (value === undefined)
105
+ continue;
106
+ let shown = value;
107
+ if (value !== null) {
108
+ switch (field.type) {
109
+ case "default_status":
110
+ shown = statusName(field.choices, value);
111
+ break;
112
+ case "default_priority":
113
+ shown = idName("priority", field.choices, value);
114
+ break;
115
+ case "default_source":
116
+ shown = idName("source", field.choices, value);
117
+ break;
118
+ case "default_agent":
119
+ shown = mapName("agent", schema.agents, value);
120
+ break;
121
+ case "default_group":
122
+ shown = mapName("group", schema.groups, value);
123
+ break;
124
+ }
125
+ }
126
+ if (field.type === "nested_field")
127
+ shown = nestedPath(field, ticket, value, hidden);
128
+ const key = Object.hasOwn(out, field.label) ? `${field.label} (${field.name})` : field.label;
129
+ // Defined, not assigned: a label `__proto__` stays an own key.
130
+ Object.defineProperty(out, key, {
131
+ value: shown,
132
+ enumerable: true,
133
+ writable: true,
134
+ configurable: true,
135
+ });
136
+ }
137
+ return out;
138
+ }
package/dist/server.js ADDED
@@ -0,0 +1,31 @@
1
+ // The MCP server (SPEC §7, §8.1): built from the toolsets the team file
2
+ // enables, and from nothing else: there is no `FRESHDESK_TOOLSETS` variable
3
+ // (owner, 2026-11-23), and this module reads no environment.
4
+ //
5
+ // A toolset the team file enables but this version does not have (`write`,
6
+ // `send`) is a `ConfigError` naming it, thrown before any tool registers.
7
+ // A tool without its annotations or call cost throws a `TypeError` from the
8
+ // registry (src/tools/toolsets/index.ts). The transport is the caller's:
9
+ // `cli.ts` serves stdio, tests the in-memory one.
10
+ import { McpServer } from "@modelcontextprotocol/server";
11
+ import { ConfigError } from "./config.js";
12
+ import { registerTool, TOOLSETS } from "./tools/toolsets/index.js";
13
+ import { VERSION } from "./version.js";
14
+ export const SERVER_INFO = { name: "@zanichelli/freshdesk-mcp", version: VERSION };
15
+ /** A server with every tool of the context's enabled toolsets. Throws `ConfigError`, `TypeError`. */
16
+ export function createServer(context, toolsets = TOOLSETS) {
17
+ const available = Object.keys(toolsets);
18
+ const enabled = [...new Set(context.team.toolsets)].map((name) => {
19
+ const tools = Object.hasOwn(toolsets, name) ? toolsets[name] : undefined;
20
+ if (tools === undefined) {
21
+ throw new ConfigError(`The team config's "toolsets" enables "${name}", which this version does not have (it has: ${available.join(", ")}). Remove it from "toolsets".`);
22
+ }
23
+ return tools;
24
+ });
25
+ const server = new McpServer(SERVER_INFO);
26
+ for (const tools of enabled) {
27
+ for (const tool of tools)
28
+ registerTool(server, tool, context);
29
+ }
30
+ return server;
31
+ }
@@ -0,0 +1,63 @@
1
+ // Cost estimate and per-call budget (SPEC §7.2, last bullet): an operation
2
+ // that needs many calls (`count_tickets`, `export_tickets`) estimates them
3
+ // first and is refused beyond the team's budget unless `confirm: true`.
4
+ //
5
+ // - `estimateCalls`: the `probe` requests sent before the pages (such as
6
+ // search page 1, which tells the total), one page per `pageSize` tickets,
7
+ // plus one conversations call per ticket when the threads are asked for
8
+ // (2,000 tickets at 100 a page with conversations: 20 + 2,000 = 2,020). A
9
+ // thread over one page costs more than estimated
10
+ // (docs/architecture/ticket-queries.md, `export_tickets`).
11
+ // - What it covers: a path whose ticket count is known before its pages
12
+ // (search, `total` ≤ 300). A list scan's count is not known up front: its
13
+ // cost is not estimated but bounded while it runs, and its caller
14
+ // (T-036, T-037) must stop the scan at the budget.
15
+ // - `checkBudget`, before the operation's pages, in this order:
16
+ // 1. below the limiter's reserve: the limiter's own `rate_limited`
17
+ // refusal, whatever `confirm` says, since `confirm` never overrides
18
+ // the limiter (read through `http.reserveRefusal()`, no token taken);
19
+ // 2. an estimate that is not a whole number, 0 or more (NaN, negative,
20
+ // infinite, fractional, or not a number at all through a cast): a
21
+ // `validation` error, whatever `confirm` says (fails closed);
22
+ // 3. an estimate over `limits.call_budget` without `confirm: true`: a
23
+ // `validation` error naming the estimate and the budget. An estimate
24
+ // at exactly the budget passes.
25
+ // It sends nothing. A pass is not a reservation: each request still goes
26
+ // through the limiter, which can refuse it later in the run.
27
+ function isCount(value) {
28
+ return Number.isSafeInteger(value) && value >= 0;
29
+ }
30
+ /** Calls an operation over `tickets` tickets needs. Throws `RangeError` on a bad count. */
31
+ export function estimateCalls({ tickets, pageSize, conversations, probe = 0, }) {
32
+ if (!isCount(tickets))
33
+ throw new RangeError("tickets must be a whole number, 0 or more");
34
+ if (!isCount(pageSize) || pageSize === 0) {
35
+ throw new RangeError("pageSize must be a whole number, 1 or more");
36
+ }
37
+ if (!isCount(probe))
38
+ throw new RangeError("probe must be a whole number, 0 or more");
39
+ return probe + Math.ceil(tickets / pageSize) + (conversations ? tickets : 0);
40
+ }
41
+ /** The refusal for an operation estimated at `estimate` calls, or `undefined` when it may run. */
42
+ export function checkBudget(context, estimate, confirm) {
43
+ const reserve = context.http.reserveRefusal();
44
+ if (reserve !== undefined)
45
+ return reserve;
46
+ if (!isCount(estimate)) {
47
+ return {
48
+ code: "validation",
49
+ http_status: null,
50
+ message: "The call's cost estimate is not a whole number of API calls, so it is refused.",
51
+ retryable: false,
52
+ };
53
+ }
54
+ const budget = context.team.limits.call_budget;
55
+ if (estimate <= budget || confirm === true)
56
+ return undefined;
57
+ return {
58
+ code: "validation",
59
+ http_status: null,
60
+ message: `This call needs an estimated ${estimate} API calls, over the per-call budget of ${budget} (limits.call_budget). Narrow it, or call again with confirm: true.`,
61
+ retryable: false,
62
+ };
63
+ }
@@ -0,0 +1,62 @@
1
+ // App context (SPEC §7.3, §10): the one place a `Config` becomes the objects
2
+ // the tools work with. A tool takes the context, never the config.
3
+ //
4
+ // - One limiter, held by the client alone: built from the team `limits`.
5
+ // - One schema service on that client, its TTL `limits.schema_ttl_s`.
6
+ // - The team settings (`team`): field meanings, limits, toolsets. They are
7
+ // the context's own frozen copy, and the context object is frozen: a
8
+ // later change to the `Config` changes nothing here.
9
+ // - The limiter is not on the context: a tool meets it only through
10
+ // `http`, whose refusals come back as `rate_limited`. The client and the
11
+ // schema service are frozen and keep their state in private fields, so a
12
+ // tool's mistake or a cast cannot re-point the host, swap the limiter or
13
+ // drop the cache. Not claimed: hostile code in the process, which can
14
+ // patch a prototype or read `process.env`.
15
+ // - Lint (eslint.config.mjs; the list is eslint.tool-imports.json, not
16
+ // repeated here): in src/tools/** (this file exempt) an import or
17
+ // re-export source must be an entry of that list for the file's place,
18
+ // its `type` entries as types only; any dynamic import() is refused. In
19
+ // all of src/tools/**, this file included, the global `process` (so
20
+ // `process.env` and `process.getBuiltinModule`), eval, `new Function`
21
+ // and implied eval are refused. Not refused by lint: `.constructor` on
22
+ // the client or the service, which reaches the class, or on any
23
+ // function; a computed property on globalThis; a global `require`, if a
24
+ // build ever exposed one (createRequire from node:module is not listed,
25
+ // so it is refused as an import); a re-export through a module
26
+ // outside src/tools/; a symlink under src/tools/ or under a listed path.
27
+ // - `ticketOutput` with the team `fields` already given.
28
+ // - `exportDir`: the personal FRESHDESK_EXPORT_DIR as set, `undefined` when
29
+ // unset; `export_tickets` checks it when it runs.
30
+ // - The API key goes to the client, which keeps it in a private field: the
31
+ // context has no `config`, `domain` or `apiKey`, and the key cannot be
32
+ // read or printed from the context (serialised or inspected, it shows
33
+ // neither the key nor the Authorization header).
34
+ //
35
+ // The dispatcher is the caller's (RFC 2026-11-23, rule 2): `cli.ts` passes
36
+ // the Agent, tests the mock.
37
+ //
38
+ // Throws `ConfigError` for a domain the client refuses. A `Config` from
39
+ // `loadConfig` throws nothing else; one built by hand with `floor_pct` above
40
+ // `reserve_pct` gets the limiter's `RangeError`.
41
+ import { HttpClient } from "../client/http.js";
42
+ import { RateLimiter } from "../client/rate-limit.js";
43
+ import { deepFreeze, SchemaService } from "../schema/index.js";
44
+ import { ticketOutput } from "../schema/output.js";
45
+ export function createContext(config, dispatcher) {
46
+ const team = deepFreeze(structuredClone(config.team));
47
+ const limiter = new RateLimiter(team.limits);
48
+ const http = new HttpClient({
49
+ domain: config.domain,
50
+ apiKey: config.apiKey,
51
+ ...(config.hostOverride === undefined ? {} : { hostOverride: config.hostOverride }),
52
+ dispatcher,
53
+ limiter,
54
+ });
55
+ return Object.freeze({
56
+ http,
57
+ schema: new SchemaService(http, team.limits.schema_ttl_s),
58
+ team,
59
+ exportDir: config.exportDir,
60
+ ticketOutput: (schema, ticket) => ticketOutput(schema, ticket, team.fields),
61
+ });
62
+ }
@@ -0,0 +1,35 @@
1
+ // CSV for `export_tickets` (T-037): fields as RFC 4180 writes them, records
2
+ // ended by CRLF, and the spreadsheet formula guard, for customer text that
3
+ // is opened in a spreadsheet.
4
+ //
5
+ // - `csvCell`: `null` and `undefined` are empty; a string is itself; a
6
+ // number or a boolean is `String(value)`; anything else is its JSON.
7
+ // A string (not a number: `-5` is a value, not a formula) starting with
8
+ // `=`, `+`, `-`, `@`, a tab or a carriage return gets a leading `'`, so a
9
+ // spreadsheet shows it as text instead of running it. Then a cell holding
10
+ // a quote, a comma, a newline or a carriage return is put in quotes, each
11
+ // quote doubled.
12
+ // - `csvRecord`: the cells through `csvCell`, joined by commas, then CRLF.
13
+ // Header cells go through it too: a field's label is admin text.
14
+ /** What a spreadsheet may read as the start of a formula. */
15
+ const FORMULA_START = /^[=+\-@\t\r]/;
16
+ /** What makes a cell need quotes. */
17
+ const NEEDS_QUOTES = /[",\r\n]/;
18
+ export function csvCell(value) {
19
+ if (value === null || value === undefined)
20
+ return "";
21
+ let text;
22
+ if (typeof value === "string") {
23
+ text = FORMULA_START.test(value) ? `'${value}` : value;
24
+ }
25
+ else if (typeof value === "number" || typeof value === "boolean") {
26
+ text = String(value);
27
+ }
28
+ else {
29
+ text = JSON.stringify(value);
30
+ }
31
+ return NEEDS_QUOTES.test(text) ? `"${text.replaceAll('"', '""')}"` : text;
32
+ }
33
+ export function csvRecord(cells) {
34
+ return `${cells.map(csvCell).join(",")}\r\n`;
35
+ }