@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,389 @@
1
+ // HTTP core (SPEC §7.1, §9; RFC 2026-11-23, rules 1, 2 and 5): the one send
2
+ // function every Freshdesk request goes through.
3
+ //
4
+ // - Host: the configured domain must be `<name>.freshdesk.com`, or equal
5
+ // the override, or construction fails. Every URL sent, built here or
6
+ // handed in whole (a pagination `Link`), must then be `https:`, on the
7
+ // default port, without credentials, and on exactly that host: not just
8
+ // any Freshdesk host, since anyone can open an account there. A URL that
9
+ // is not gets a `validation` error and nothing is sent.
10
+ // - Path: callers pass a template (`/tickets/{id}`) and its parameters.
11
+ // Parameters are percent-encoded here; the template is what is logged.
12
+ // - Redirects are not followed: a 3xx comes back as an error that is not
13
+ // retryable, so the API key never travels to a `Location`.
14
+ // - Limiter: `acquire` before sending, `observe` on every response.
15
+ // - Timeout: a request with no complete response after REQUEST_TIMEOUT_MS
16
+ // is aborted and comes back as a `network` error.
17
+ // - Result: a 2xx with its parsed JSON body, or a FreshdeskError. Nothing
18
+ // that comes from the network makes `request` throw.
19
+ // - stderr: one line per request sent, `METHOD template status ms`. Never
20
+ // a URL, a header or a body.
21
+ //
22
+ // `request` is one attempt. `requestWithRetry` and `paginate` are built on it
23
+ // and are what resource modules call:
24
+ // - Retries: MAX_RETRIES at most. A GET is retried on a 5xx or a network
25
+ // error (a timeout is one) after a backoff, and on a 429. Any other method
26
+ // is a write, whatever the caller thinks: it is retried on a 429 only,
27
+ // the one answer that says the request was not processed, so a write is
28
+ // never applied twice.
29
+ // - After a 429 the retry does not sleep here: the next attempt's `acquire`
30
+ // serves the limiter's hold, or refuses when the hold is beyond its
31
+ // bound, and that refusal is returned with nothing more sent.
32
+ // - Deadline: one `requestWithRetry` ends within TOTAL_DEADLINE_MS, its
33
+ // attempts, limiter waits and backoffs together. Each attempt carries the
34
+ // deadline: the limiter refuses a wait that would end at or after it
35
+ // (`rate_limited`, so that refusal wins over the expiry), and what is
36
+ // left caps the attempt's timeout, so an attempt in flight at the
37
+ // deadline is aborted and comes back as the expiry error: `network`,
38
+ // retryable for a GET only. A backoff that would end at or after the
39
+ // deadline is not started: the last answer is returned as it is.
40
+ // - Deadline reached: `http.reachedDeadline(error)` is true for an error the
41
+ // deadline ended, and only the client marks one (a private WeakSet, so
42
+ // the error's shape in a tool's output is unchanged): a GET's expiry
43
+ // error above, and a GET's `network` failure that no retry can follow before
44
+ // the deadline (an attempt started at 19.6 s times out at 29.6 s; T-059).
45
+ // Not a `network` failure that used its retries with time left, not a
46
+ // 5xx (an answer), not a write's failure (it may have been applied). A
47
+ // caller that cuts its work at the deadline asks this, not the clock.
48
+ // - A caller's deadline (epoch ms, optional) can only shorten that one: the
49
+ // call ends at the earlier of the two, by the same rules, and one already
50
+ // reached sends nothing and does not ask the limiter (`request` checks it
51
+ // after its own checks of the caller's code and of the URL). `paginate` hands
52
+ // its own to every page, so the pages share it; with none, each page
53
+ // gets the full TOTAL_DEADLINE_MS.
54
+ // - Pagination: `paginate` follows `Link: <url>; rel="next"`, each URL
55
+ // through `request` and so through the host check, up to the caller's cap.
56
+ // Its return value says whether a cap cut the list (`truncated`).
57
+ // - Attempts: `requestWithRetry`'s result says how many attempts it sent
58
+ // (`attempts`), and `paginate`'s return value sums them over its pages.
59
+ // An attempt is sent when `request` handed it to `fetch`, whatever came
60
+ // back (one cut in flight by a deadline included); one refused before
61
+ // that (URL, deadline, limiter) is not. `request` keeps the results it
62
+ // got through `fetch` in a private WeakSet, so a subclass's override that
63
+ // answers without calling it, or returns anything but the object it
64
+ // returned (a copy included), counts nothing for that attempt.
65
+ import { fetch } from "undici";
66
+ import { ConfigError } from "../config.js";
67
+ import { errorFromResponse, networkError } from "./errors.js";
68
+ import { VERSION } from "../version.js";
69
+ const FRESHDESK_HOST = /^[a-z0-9-]+\.freshdesk\.com$/;
70
+ export const USER_AGENT = `freshdesk-mcp/${VERSION}`;
71
+ /** What `path` may be, since it is logged: segments of names and `{params}`. */
72
+ const TEMPLATE = /^(\/[A-Za-z0-9_{}-]+)+$/;
73
+ /** Longest one attempt may take, headers and body together. */
74
+ export const REQUEST_TIMEOUT_MS = 10_000;
75
+ /** Attempts after the first. */
76
+ export const MAX_RETRIES = 3;
77
+ /** Wait before the first retry of a 5xx or network error; doubles each time. */
78
+ export const BACKOFF_MS = 500;
79
+ /** Longest one `requestWithRetry` may take, waits and attempts together. */
80
+ export const TOTAL_DEADLINE_MS = 30_000;
81
+ /** The errors a deadline ended: see the file's header, "Deadline reached". */
82
+ const ended = new WeakSet();
83
+ function notSent(why) {
84
+ return {
85
+ ok: false,
86
+ error: {
87
+ code: "validation",
88
+ http_status: null,
89
+ message: `Not sent: ${why}.`,
90
+ retryable: false,
91
+ },
92
+ };
93
+ }
94
+ /**
95
+ * An aborted write may have been applied, as with the timeout of one attempt.
96
+ * A write refused because its deadline had already passed was not sent, and
97
+ * is still marked not retryable: the conservative answer, until T-014 gives
98
+ * a write that is not sent an answer of its own.
99
+ */
100
+ function expired(method) {
101
+ const error = {
102
+ code: "network",
103
+ http_status: null,
104
+ message: "No answer from Freshdesk before the call's deadline: the call was given up.",
105
+ retryable: method === "GET",
106
+ };
107
+ // A write's expiry may have been applied: not the deadline's alone (T-059).
108
+ if (method === "GET")
109
+ ended.add(error);
110
+ return { ok: false, error };
111
+ }
112
+ export class HttpClient {
113
+ // Real private members, and the instance frozen at the end of the
114
+ // constructor: the key, the dispatcher, the host, the limiter and the two
115
+ // helpers are not properties, so they cannot be read, printed or replaced
116
+ // from the client, and no method can be shadowed on it. A tool's mistake
117
+ // or a cast (`as unknown as Record<...>`) gets a TypeError or changes
118
+ // nothing. Not claimed: hostile code in the process, which can patch the
119
+ // prototype or read `process.env`. A subclass gets no instance fields of
120
+ // its own: the instance is frozen here, so a public field throws, and a `#`
121
+ // field relies on engines still allowing a private field on a frozen
122
+ // object (the "nonextensible applies to private" proposal would refuse it).
123
+ #host;
124
+ #authorization;
125
+ #dispatcher;
126
+ #limiter;
127
+ /** The results `request` got through `fetch`: each one an attempt sent. */
128
+ #sent = new WeakSet();
129
+ constructor(options) {
130
+ if (!FRESHDESK_HOST.test(options.domain) && options.domain !== options.hostOverride) {
131
+ throw new ConfigError("FRESHDESK_DOMAIN must be a Freshdesk hostname (like acme.freshdesk.com), or equal FRESHDESK_HOST_OVERRIDE.");
132
+ }
133
+ this.#host = options.domain;
134
+ this.#authorization = `Basic ${Buffer.from(`${options.apiKey}:X`).toString("base64")}`;
135
+ this.#dispatcher = options.dispatcher;
136
+ this.#limiter = options.limiter;
137
+ Object.freeze(this);
138
+ }
139
+ /**
140
+ * The limiter's reserve refusal, read without a call (`RateLimiter`'s
141
+ * `reserveRefusal`): the one view of the limiter's state a tool gets, so
142
+ * an operation's budget check (src/tools/budget.ts) can refuse below the
143
+ * reserve before it starts. Read-only: it takes no token.
144
+ */
145
+ reserveRefusal() {
146
+ return this.#limiter.reserveRefusal();
147
+ }
148
+ /**
149
+ * True when the client marked `error` as one its call's deadline ended
150
+ * (the file's header, "Deadline reached"). Read-only, like
151
+ * `reserveRefusal`: a tool asks it and cannot set it.
152
+ */
153
+ reachedDeadline(error) {
154
+ return ended.has(error);
155
+ }
156
+ /**
157
+ * Throws a `TypeError` only for what the calling code got wrong: a `path`
158
+ * that is not a template, a parameter the template names and `params`
159
+ * lacks, a `body` that JSON cannot carry. Values (a parameter's, a URL's)
160
+ * are refused with a result.
161
+ *
162
+ * One attempt: resource modules call `requestWithRetry` or `paginate`.
163
+ *
164
+ * `deadline` (epoch ms) is `requestWithRetry`'s. It only shortens: the
165
+ * limiter's wait and the attempt's timeout keep their own bounds under it.
166
+ */
167
+ async request(request, deadline = Infinity) {
168
+ const method = request.method ?? "GET";
169
+ if (!TEMPLATE.test(request.path)) {
170
+ throw new TypeError("The path must be a template like /tickets/{id}.");
171
+ }
172
+ const payload = request.body === undefined ? undefined : JSON.stringify(request.body);
173
+ const url = request.url ?? this.#build(request);
174
+ if (url === undefined) {
175
+ return notSent("a path parameter is empty or a dot segment");
176
+ }
177
+ if (!this.#allowed(url)) {
178
+ return notSent("the URL is not on the configured Freshdesk host");
179
+ }
180
+ // A deadline already reached: the limiter is not asked. Written so that
181
+ // a deadline that is not a number sends nothing either.
182
+ if (!(deadline > Date.now()))
183
+ return expired(method);
184
+ const acquired = await this.#limiter.acquire(request.cost ?? "cheap", deadline - Date.now());
185
+ if (!acquired.ok)
186
+ return acquired;
187
+ // Read again: `acquire` may have slept. Its token is spent either way.
188
+ const left = deadline - Date.now();
189
+ if (!(left > 0))
190
+ return expired(method);
191
+ const started = performance.now();
192
+ const log = (outcome) => {
193
+ const ms = Math.round(performance.now() - started);
194
+ process.stderr.write(`${method} ${request.path} ${outcome} ${ms}ms\n`);
195
+ };
196
+ let status;
197
+ let headers;
198
+ let text;
199
+ const timeout = new AbortController();
200
+ const timer = setTimeout(() => {
201
+ timeout.abort(new DOMException("The request timed out.", "TimeoutError"));
202
+ }, Math.min(REQUEST_TIMEOUT_MS, left));
203
+ try {
204
+ const response = await fetch(url, {
205
+ method,
206
+ headers: {
207
+ authorization: this.#authorization,
208
+ "user-agent": USER_AGENT,
209
+ accept: "application/json",
210
+ ...(payload === undefined ? {} : { "content-type": "application/json" }),
211
+ },
212
+ ...(payload === undefined ? {} : { body: payload }),
213
+ dispatcher: this.#dispatcher,
214
+ redirect: "manual",
215
+ signal: timeout.signal,
216
+ });
217
+ ({ status, headers } = response);
218
+ this.#limiter.observe(status, headers);
219
+ text = await response.text();
220
+ }
221
+ catch (cause) {
222
+ log("network");
223
+ if (timeout.signal.aborted && left <= REQUEST_TIMEOUT_MS)
224
+ return this.#mark(expired(method));
225
+ return this.#mark({ ok: false, error: networkError(cause) });
226
+ }
227
+ finally {
228
+ clearTimeout(timer);
229
+ }
230
+ log(status);
231
+ let body;
232
+ let parsed = true;
233
+ if (text !== "") {
234
+ try {
235
+ body = JSON.parse(text);
236
+ }
237
+ catch {
238
+ parsed = false;
239
+ }
240
+ }
241
+ if (status < 200 || status >= 300) {
242
+ return this.#mark({ ok: false, error: errorFromResponse(status, headers, body) });
243
+ }
244
+ if (!parsed) {
245
+ return this.#mark({
246
+ ok: false,
247
+ error: {
248
+ code: "server",
249
+ http_status: status,
250
+ message: `Freshdesk sent a body that is not JSON (HTTP ${status}).`,
251
+ retryable: false,
252
+ },
253
+ });
254
+ }
255
+ return this.#mark({ ok: true, status, headers, body });
256
+ }
257
+ /**
258
+ * `request`, attempted again where that cannot apply a write twice. A write
259
+ * that failed on a 5xx, a network error or a timeout may have been applied:
260
+ * it comes back `retryable: false`, so no caller sends it again either.
261
+ *
262
+ * `callerDeadline` (epoch ms) is the caller's own, for an operation of
263
+ * several calls. It only shortens: the call still ends within
264
+ * TOTAL_DEADLINE_MS.
265
+ *
266
+ * `attempts` on the result is how many attempts were sent, the last one's
267
+ * included: 0 when none was (see the file's header).
268
+ */
269
+ async requestWithRetry(request, callerDeadline = Infinity) {
270
+ const read = (request.method ?? "GET") === "GET";
271
+ const deadline = Math.min(Date.now() + TOTAL_DEADLINE_MS, callerDeadline);
272
+ let attempts = 0;
273
+ for (let attempt = 0;; attempt += 1) {
274
+ const result = await this.request(request, deadline);
275
+ if (this.#sent.has(result))
276
+ attempts += 1;
277
+ if (result.ok)
278
+ return { ...result, attempts };
279
+ const { code, http_status, retryable } = result.error;
280
+ // With no status the limiter refused the call: waiting is its business.
281
+ const limited = code === "rate_limited" && http_status !== null;
282
+ const transient = retryable && (code === "server" || code === "network");
283
+ if (!read && transient) {
284
+ return { ok: false, error: { ...result.error, retryable: false }, attempts };
285
+ }
286
+ if (attempt === MAX_RETRIES || !(limited || transient))
287
+ return { ...result, attempts };
288
+ const backoff = limited ? 0 : BACKOFF_MS * 2 ** attempt;
289
+ // Written so that a deadline that is not a number starts no retry.
290
+ if (!(Date.now() + backoff < deadline)) {
291
+ // A GET with no time left to retry: the deadline ended it (T-059).
292
+ if (code === "network")
293
+ ended.add(result.error);
294
+ return { ...result, attempts };
295
+ }
296
+ if (!limited)
297
+ await sleep(backoff);
298
+ }
299
+ }
300
+ /**
301
+ * The pages of a list, one result each, following `Link` up to the cap. A
302
+ * failed page is yielded and ends the iteration. Throws a `TypeError` for a
303
+ * cap that is not a whole number, zero or more.
304
+ *
305
+ * Returns `truncated`: true when a cap ended the list with more of it left,
306
+ * a `Link` not followed or a page cut; false when the list ended, or a
307
+ * failed page did (the failure is the answer). And `attempts`: the
308
+ * attempts sent for all the pages, retries and a failed page's included.
309
+ *
310
+ * `deadline` (epoch ms) is one for all the pages: each page's
311
+ * `requestWithRetry` gets it, so a page it cuts, or one not asked for
312
+ * because it has passed, is a failed page, never a short list.
313
+ */
314
+ async *paginate(request, cap, deadline) {
315
+ if (!isCount(cap.pages) || (cap.items !== undefined && !isCount(cap.items))) {
316
+ throw new TypeError("A page cap and an item cap are whole numbers, zero or more.");
317
+ }
318
+ // Field by field: the type keeps a method, a body and a URL out, and a
319
+ // caller's wider object would carry them in.
320
+ const first = { method: "GET", path: request.path };
321
+ if (request.params !== undefined)
322
+ first.params = request.params;
323
+ if (request.query !== undefined)
324
+ first.query = request.query;
325
+ if (request.cost !== undefined)
326
+ first.cost = request.cost;
327
+ let next = first;
328
+ let room = cap.items ?? Infinity;
329
+ let attempts = 0;
330
+ for (let page = 0; page < cap.pages && room > 0 && next !== undefined; page += 1) {
331
+ // A page is yielded as `request`'s result: its count stays here.
332
+ const { attempts: sent, ...result } = await this.requestWithRetry(next, deadline);
333
+ attempts += sent;
334
+ if (!result.ok) {
335
+ yield result;
336
+ return { truncated: false, attempts };
337
+ }
338
+ const body = result.body;
339
+ if (Array.isArray(body) && body.length > room) {
340
+ yield { ...result, body: body.slice(0, room) };
341
+ return { truncated: true, attempts };
342
+ }
343
+ yield result;
344
+ if (Array.isArray(body))
345
+ room -= body.length;
346
+ const link = /<([^>]*)>\s*;\s*rel="?next"?/.exec(result.headers.get("link") ?? "")?.[1];
347
+ next = link === undefined ? undefined : { ...first, url: link };
348
+ }
349
+ return { truncated: next !== undefined, attempts };
350
+ }
351
+ #mark(result) {
352
+ this.#sent.add(result);
353
+ return result;
354
+ }
355
+ /** `undefined` when a parameter's value would change which resource is addressed. */
356
+ #build(request) {
357
+ let usable = true;
358
+ const path = request.path.replace(/\{(\w+)\}/g, (_match, name) => {
359
+ const value = request.params?.[name];
360
+ if (value === undefined) {
361
+ throw new TypeError(`The path names a parameter "${name}" that params lacks.`);
362
+ }
363
+ // "" drops a segment; "." and ".." survive encoding and climb out.
364
+ if (value === "" || value === "." || value === "..")
365
+ usable = false;
366
+ return encodeURIComponent(value);
367
+ });
368
+ if (!usable)
369
+ return undefined;
370
+ const query = new URLSearchParams(Object.entries(request.query ?? {}).map(([name, value]) => [name, String(value)])).toString();
371
+ return `https://${this.#host}/api/v2${path}${query === "" ? "" : `?${query}`}`;
372
+ }
373
+ #allowed(candidate) {
374
+ if (!URL.canParse(candidate))
375
+ return false;
376
+ const url = new URL(candidate);
377
+ return (url.protocol === "https:" &&
378
+ url.port === "" &&
379
+ url.hostname === this.#host &&
380
+ url.username === "" &&
381
+ url.password === "");
382
+ }
383
+ }
384
+ function sleep(ms) {
385
+ return new Promise((resolve) => setTimeout(resolve, ms));
386
+ }
387
+ function isCount(value) {
388
+ return Number.isSafeInteger(value) && value >= 0;
389
+ }
@@ -0,0 +1,198 @@
1
+ // Rate limiter (SPEC §7.2): a budget read from Freshdesk's response headers,
2
+ // shared by every call this process makes. No network, no config import.
3
+ //
4
+ // Use: `await acquire(cost)` before each request, `observe(status, headers)`
5
+ // on each response. The limiter owns every wait for the rate limit: a caller
6
+ // that is told to retry calls `acquire` again and never sleeps on a 429 itself
7
+ // (its backoff after a 5xx or a network error is its own, see `http.ts`).
8
+ //
9
+ // - Every allowed call takes one token from the local count; the next
10
+ // response's headers replace that count with the account's real one.
11
+ // - Reserve: below `reserve_pct` of Total, `expensive` is refused.
12
+ // `reserveRefusal()` reads that refusal without a call, so an operation
13
+ // can be refused before it starts (src/tools/budget.ts).
14
+ // - Floor: below `floor_pct` of Total, at zero, and after a 429, every call
15
+ // waits for the window's end, or is refused when that is too far.
16
+ // - Pacing: `expensive` calls start at most `pacing_rps` per second.
17
+ // - One `acquire` waits MAX_WAIT_S at most, all its waits together (floor,
18
+ // 429 and pacing): a wait that would end later is refused at once.
19
+ // - A caller with less time than that passes its own bound: a wait that
20
+ // would end at or after it is refused at once too. The bound only ever
21
+ // refuses sooner; MAX_WAIT_S holds whatever the caller passes.
22
+ // - A refusal is a `rate_limited` error with `retry_after_s`, never a throw.
23
+ //
24
+ // Freshdesk sends no window-end header. The limiter assumes a fixed window of
25
+ // WINDOW_S and takes the latest end the evidence allows: WINDOW_S after the
26
+ // last response seen, or the `Retry-After` of a 429. A state older than that
27
+ // is dropped and the budget assumed fresh; the next response corrects it.
28
+ //
29
+ // After a 429 nothing goes out until its `Retry-After` has passed, kept
30
+ // between MIN_HOLD_S and MAX_HOLD_S whatever the header says. Budget headers
31
+ // seen meanwhile are ignored: they answer requests sent before the 429.
32
+ //
33
+ // Known limit: outside a 429 hold, responses are taken in arrival order, so
34
+ // one that arrives late can raise the count again, and calls still in flight
35
+ // are not counted once a response has replaced the local count. The error
36
+ // is at most the number of calls in flight.
37
+ //
38
+ // MAX_WAIT_S is 15 s: long enough to ride out the tail of a window, short
39
+ // enough that a tool call answers well inside an MCP client's timeout.
40
+ /** Assumed length of Freshdesk's rate-limit window, seconds. */
41
+ export const WINDOW_S = 60;
42
+ /** Longest one `acquire` waits before the call is refused instead, seconds. */
43
+ export const MAX_WAIT_S = 15;
44
+ /** Calls per window assumed until a response says otherwise. */
45
+ export const DEFAULT_TOTAL = 50;
46
+ /** Shortest and longest hold after a 429, whatever its `Retry-After`, seconds. */
47
+ export const MIN_HOLD_S = 1;
48
+ export const MAX_HOLD_S = 3600;
49
+ export class RateLimiter {
50
+ // Real private members: the options and the state are not properties, so a
51
+ // tool's mistake or a cast cannot loosen a refusal; an assignment through
52
+ // one adds a property nothing reads. The instance is not frozen (tests spy
53
+ // on `acquire`). Not claimed: hostile code in the process.
54
+ #options;
55
+ #total = DEFAULT_TOTAL;
56
+ #remaining = DEFAULT_TOTAL;
57
+ /** Epoch ms; `undefined` until the first call or response of a window. */
58
+ #windowEnd;
59
+ /** A 429 was seen in this window: nothing goes out until it ends. */
60
+ #exhausted = false;
61
+ #nextExpensiveAt = 0;
62
+ constructor(options) {
63
+ if (options.floor_pct > options.reserve_pct) {
64
+ throw new RangeError("floor_pct must not be above reserve_pct");
65
+ }
66
+ this.#options = options;
67
+ }
68
+ /**
69
+ * Resolves when the call may go out, or with the reason it may not.
70
+ * `boundMs` is the time the caller has left: the call must go out strictly
71
+ * before it has passed. It cannot lengthen the wait beyond MAX_WAIT_S.
72
+ */
73
+ async acquire(cost, boundMs = Infinity) {
74
+ const start = Date.now();
75
+ const deadline = start + MAX_WAIT_S * 1000;
76
+ const tooFar = (end) => end > deadline || end >= start + boundMs;
77
+ for (;;) {
78
+ const now = Date.now();
79
+ this.#expire(now);
80
+ const windowEnd = (this.#windowEnd ??= now + WINDOW_S * 1000);
81
+ if (this.#exhausted || this.#remaining <= 0 || this.#below(this.#options.floor_pct)) {
82
+ if (tooFar(windowEnd)) {
83
+ const why = this.#exhausted ? "Freshdesk rate limit reached" : this.#left();
84
+ return refuse(`${why}: no call goes out until the window resets`, windowEnd - now);
85
+ }
86
+ await sleep(windowEnd - now);
87
+ continue;
88
+ }
89
+ if (cost === "expensive") {
90
+ if (this.#below(this.#options.reserve_pct))
91
+ return this.#belowReserve(windowEnd - now);
92
+ if (now < this.#nextExpensiveAt) {
93
+ if (tooFar(this.#nextExpensiveAt)) {
94
+ return refuse("Too many expensive operations are queued for pacing", this.#nextExpensiveAt - now);
95
+ }
96
+ await sleep(this.#nextExpensiveAt - now);
97
+ continue;
98
+ }
99
+ this.#nextExpensiveAt = now + 1000 / this.#options.pacing_rps;
100
+ }
101
+ this.#remaining -= 1;
102
+ return { ok: true };
103
+ }
104
+ }
105
+ /**
106
+ * The refusal an `expensive` call meets now for being below the reserve, or
107
+ * `undefined` when there is none. Read-only: it takes no token, starts no
108
+ * pacing and changes no state; a window already ended counts as fresh, as
109
+ * `acquire` would take it. Floor, 429 hold and pacing waits stay
110
+ * `acquire`'s. Below the floor it still gives the reserve refusal, where
111
+ * `acquire` would apply the floor rule first (wait for the window or
112
+ * refuse): it errs closed.
113
+ */
114
+ reserveRefusal() {
115
+ const now = Date.now();
116
+ if (this.#windowEnd === undefined || now >= this.#windowEnd)
117
+ return undefined;
118
+ if (!this.#below(this.#options.reserve_pct))
119
+ return undefined;
120
+ return this.#belowReserve(this.#windowEnd - now).error;
121
+ }
122
+ /**
123
+ * Feed every response in. Returns the hold a 429 starts, in milliseconds
124
+ * (its `Retry-After`, within MIN_HOLD_S..MAX_HOLD_S), and 0 for any other
125
+ * status. The value is for reporting only: the next `acquire` serves the
126
+ * hold or refuses, and the caller must not sleep on it.
127
+ */
128
+ observe(status, headers) {
129
+ const now = Date.now();
130
+ this.#expire(now);
131
+ if (status === 429) {
132
+ const asked = count(headers.get("retry-after")) ?? WINDOW_S;
133
+ const hold = Math.min(Math.max(asked, MIN_HOLD_S), MAX_HOLD_S) * 1000;
134
+ // A second 429 may extend a hold in force, never shorten it.
135
+ const end = Math.max(now + hold, this.#exhausted ? (this.#windowEnd ?? 0) : 0);
136
+ this.#exhausted = true;
137
+ this.#windowEnd = end;
138
+ return hold;
139
+ }
140
+ if (this.#exhausted)
141
+ return 0;
142
+ const total = count(headers.get("x-ratelimit-total"));
143
+ const remaining = count(headers.get("x-ratelimit-remaining"));
144
+ if (total !== undefined && remaining !== undefined && total > 0 && remaining <= total) {
145
+ this.#total = total;
146
+ this.#remaining = remaining;
147
+ this.#windowEnd = now + WINDOW_S * 1000;
148
+ }
149
+ return 0;
150
+ }
151
+ /** Past the window's end the state is stale: assume a fresh budget. */
152
+ #expire(now) {
153
+ if (this.#windowEnd !== undefined && now >= this.#windowEnd) {
154
+ this.#remaining = this.#total;
155
+ this.#exhausted = false;
156
+ this.#windowEnd = undefined;
157
+ }
158
+ }
159
+ #below(pct) {
160
+ return this.#remaining < (this.#total * pct) / 100;
161
+ }
162
+ #belowReserve(waitMs) {
163
+ return refuse(`${this.#left()}: below the reserve, expensive operations are refused`, waitMs);
164
+ }
165
+ #left() {
166
+ return `${this.#remaining} of ${this.#total} API calls left in this window`;
167
+ }
168
+ }
169
+ function refuse(why, waitMs) {
170
+ const seconds = Math.ceil(waitMs / 1000);
171
+ return {
172
+ ok: false,
173
+ error: {
174
+ code: "rate_limited",
175
+ http_status: null,
176
+ message: `${why}. Try again in ${seconds} s.`,
177
+ retryable: true,
178
+ retry_after_s: seconds,
179
+ },
180
+ };
181
+ }
182
+ /**
183
+ * A header holding a whole number of calls or seconds, digits with an
184
+ * optional fraction of zeros only ("5000" or "5000.0": the real account sends
185
+ * the rate-limit counts in that form, smoke run of 2026-11-25); anything else
186
+ * is no value. It reads Retry-After too, where "7.0" is 7.
187
+ */
188
+ function count(value) {
189
+ const trimmed = value?.trim();
190
+ const whole = trimmed === undefined ? null : /^(\d+)(?:\.0+)?$/.exec(trimmed);
191
+ if (whole === null)
192
+ return undefined;
193
+ const number = Number(whole[1]);
194
+ return Number.isSafeInteger(number) ? number : undefined;
195
+ }
196
+ function sleep(ms) {
197
+ return new Promise((resolve) => setTimeout(resolve, Math.ceil(ms)));
198
+ }
@@ -0,0 +1,15 @@
1
+ // Agents (SPEC §7.3): `GET /agents`, every page, for the schema service's
2
+ // id → name map. An agent's name is on its contact.
3
+ //
4
+ // An agent needs a whole-number `id` and a `contact` with a non-empty `name`;
5
+ // keys this module does not know are passed through. Paging and the malformed
6
+ // page error: see `list-all.ts`.
7
+ import { z } from "zod";
8
+ import { listAll } from "./list-all.js";
9
+ const agent = z.looseObject({
10
+ id: z.number().int(),
11
+ contact: z.looseObject({ name: z.string().min(1) }),
12
+ });
13
+ export function listAgents(http, deadline) {
14
+ return listAll(http, "/agents", agent, "agents", deadline);
15
+ }