@estebanforge/pi-zendesk-me 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +97 -0
- package/extensions/index.ts +166 -0
- package/lib/api.ts +267 -0
- package/lib/auth.ts +187 -0
- package/lib/format.ts +128 -0
- package/lib/prompts.ts +71 -0
- package/lib/result.ts +26 -0
- package/lib/tools/download-attachment.ts +124 -0
- package/lib/tools/get-comments.ts +90 -0
- package/lib/tools/get-organization.ts +52 -0
- package/lib/tools/get-ticket.ts +92 -0
- package/lib/tools/get-user.ts +53 -0
- package/lib/tools/get-view.ts +81 -0
- package/lib/tools/search.ts +94 -0
- package/lib/types.ts +135 -0
- package/lib/url.ts +27 -0
- package/package.json +65 -0
- package/tests/_helpers.ts +72 -0
- package/tests/api.test.ts +143 -0
- package/tests/auth.test.ts +124 -0
- package/tests/download-attachment.test.ts +135 -0
- package/tests/get-comments.test.ts +122 -0
- package/tests/get-ticket.test.ts +120 -0
- package/tests/get-view.test.ts +133 -0
- package/tests/search.test.ts +131 -0
- package/tests/url.test.ts +30 -0
- package/vitest.config.ts +12 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 EstebanForge
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
# @estebanforge/pi-zendesk-me
|
|
2
|
+
|
|
3
|
+
Zendesk Support read tools for [pi](https://github.com/earendil-works/pi-coding-agent) that act on **your** Zendesk tenant.
|
|
4
|
+
|
|
5
|
+
The extension adds 7 LLM-callable tools that query the Zendesk Support API v2 over HTTPS: fetch a ticket (by id or a pasted agent URL), read the full comment thread, search, look up users and organizations, download attachments (images included) to a temp file for viewing, and list the tickets in a saved view (filter). Read-only: no ticket can be created, edited, or commented on from here. No MCP server install required.
|
|
6
|
+
|
|
7
|
+
Authentication uses a **Zendesk OAuth confidential client** with the client-credentials grant. No API tokens: Zendesk is retiring them, and this extension starts on the path that survives.
|
|
8
|
+
|
|
9
|
+
## Tools
|
|
10
|
+
|
|
11
|
+
| Tool | Description |
|
|
12
|
+
|------|-------------|
|
|
13
|
+
| `zendesk_get_ticket` | Fetch one ticket with requester, assignee, and organization resolved via side-loading in a single call |
|
|
14
|
+
| `zendesk_get_comments` | Read the full comment thread; public replies and internal notes flagged, authors resolved |
|
|
15
|
+
| `zendesk_search` | Search with Zendesk search syntax (`status:open priority:urgent billing`); `type:ticket` prepended by default |
|
|
16
|
+
| `zendesk_get_user` | Look up a requester or assignee by id (name, email, role, notes) |
|
|
17
|
+
| `zendesk_get_organization` | Look up an organization by id (domains, details, notes) |
|
|
18
|
+
| `zendesk_download_attachment` | Save a ticket attachment to a temp file; view images with the native `read` tool |
|
|
19
|
+
| `zendesk_get_view` | List the tickets in a saved view (agent-UI filter, `/agent/filters/{id}` URLs work) |
|
|
20
|
+
|
|
21
|
+
Convenience details that save round-trips and mistakes:
|
|
22
|
+
|
|
23
|
+
- **Ticket URLs work as input.** `zendesk_get_ticket` and `zendesk_get_comments` accept `https://{subdomain}.zendesk.com/agent/tickets/7942` exactly as copied from the agent UI, or a bare `7942`.
|
|
24
|
+
- **Comment bodies arrive as stripped plain text.** Zendesk stores HTML; the tools strip tags before the text reaches the model, so nothing renders raw markup.
|
|
25
|
+
- **Ids ride along with names.** Output shows `Ada Lovelace <ada@example.com>` plus the underlying ids, so a follow-up `zendesk_get_user` never needs a re-fetch.
|
|
26
|
+
- **Images are viewable, not just listed.** `zendesk_get_comments` prints `attachment: #ID name (size)`; `zendesk_download_attachment` saves the bytes and the agent views the image with the native `read` tool. Zendesk content URLs are pre-signed: downloads follow the redirect with no auth header (an auth header breaks the storage signature).
|
|
27
|
+
|
|
28
|
+
## Setup
|
|
29
|
+
|
|
30
|
+
### 1. Create an OAuth client
|
|
31
|
+
|
|
32
|
+
In Zendesk Admin Center: **Apps and integrations** > **APIs** > **OAuth clients** > **Add OAuth client**.
|
|
33
|
+
|
|
34
|
+
Direct URL:
|
|
35
|
+
|
|
36
|
+
```text
|
|
37
|
+
https://{subdomain}.zendesk.com/admin/apps-integrations/apis/oauth-clients
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
| Setting | Value |
|
|
41
|
+
|---------|-------|
|
|
42
|
+
| Client kind | **Confidential** (required for client credentials) |
|
|
43
|
+
| Redirect URLs | Not needed for this flow; leave as is |
|
|
44
|
+
| Allowed scopes | `tickets:read users:read organizations:read ticket_views:read` |
|
|
45
|
+
|
|
46
|
+
Set **Allowed scopes** to exactly that read set. Allowed scopes are a ceiling: no token this client mints can exceed them, even if the client secret leaks. Blank means "anything", so do not leave it blank.
|
|
47
|
+
|
|
48
|
+
Save and copy the **Secret**. It is shown once.
|
|
49
|
+
|
|
50
|
+
### 2. Export the credentials
|
|
51
|
+
|
|
52
|
+
```bash
|
|
53
|
+
export ZENDESK_SUBDOMAIN="{subdomain}" # your tenant: https://{subdomain}.zendesk.com
|
|
54
|
+
export ZENDESK_CLIENT_ID="..."
|
|
55
|
+
export ZENDESK_CLIENT_SECRET="..."
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
### 3. Install
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
pi install @estebanforge/pi-zendesk-me
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
No browser approval step, no user account to pick. The client-credentials token acts as the OAuth client itself, scoped to the read set above.
|
|
65
|
+
|
|
66
|
+
## Commands
|
|
67
|
+
|
|
68
|
+
| Command | Description |
|
|
69
|
+
|---------|-------------|
|
|
70
|
+
| `/zendesk` | Show credential status and usage |
|
|
71
|
+
| `/zendesk ticket <id-or-url>` | Fetch a ticket (prefills `zendesk_get_ticket`) |
|
|
72
|
+
| `/zendesk comments <id-or-url>` | Read a thread (prefills `zendesk_get_comments`) |
|
|
73
|
+
| `/zendesk search <query>` | Search tickets (prefills `zendesk_search`) |
|
|
74
|
+
| `/zendesk view <id-or-url>` | List tickets in a saved view/filter (prefills `zendesk_get_view`) |
|
|
75
|
+
| `/zendesk user <id>` | Look up a user (prefills `zendesk_get_user`) |
|
|
76
|
+
| `/zendesk org <id>` | Look up an organization (prefills `zendesk_get_organization`) |
|
|
77
|
+
|
|
78
|
+
## Notes
|
|
79
|
+
|
|
80
|
+
- **Read-only by design.** The requested scopes contain no `write`, so the token cannot mutate tickets even by accident. Write tools would need a scope change plus new code; neither is planned.
|
|
81
|
+
- **Rate limits**: standard plans allow ~700 requests/min. The extension surfaces Zendesk's `429` `Retry-After` hint in the error text instead of retrying in a loop.
|
|
82
|
+
- **403 means scope**: with OAuth, `403 Forbidden` on a read almost always means the client's Allowed scopes were configured narrower than the read set (`tickets:read users:read organizations:read ticket_views:read`). Fix it in Admin Center, not in code.
|
|
83
|
+
- **Credential hygiene**: the client secret is a bearer credential for your whole Zendesk tenant. Keep it out of files pi commits; a dedicated read-scoped client keeps the blast radius to reading.
|
|
84
|
+
- **Visibility**: what the client can see is governed by the Zendesk account's permissions for OAuth clients; internal notes appear flagged as `INTERNAL NOTE` when returned.
|
|
85
|
+
|
|
86
|
+
## Development
|
|
87
|
+
|
|
88
|
+
```bash
|
|
89
|
+
npm install
|
|
90
|
+
npm run typecheck # tsc --noEmit
|
|
91
|
+
npm test # vitest run
|
|
92
|
+
npm run test:watch
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
## License
|
|
96
|
+
|
|
97
|
+
MIT
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* pi-zendesk-me - Zendesk Support read tools for pi.
|
|
3
|
+
*
|
|
4
|
+
* Adds 7 LLM-callable tools that query the Zendesk Support API v2 using an
|
|
5
|
+
* OAuth confidential client (client-credentials grant). Read-only: fetch a
|
|
6
|
+
* ticket (by id or pasted agent URL), read the comment thread, search, look
|
|
7
|
+
* up users and organizations, download attachments to a temp file for
|
|
8
|
+
* viewing, and list the tickets in a saved view (agent-UI filter). No API
|
|
9
|
+
* tokens - Zendesk retires those on 2027-04-30 - and no MCP server install.
|
|
10
|
+
*
|
|
11
|
+
* Based on: Zendesk Support API v2
|
|
12
|
+
* https://developer.zendesk.com/api-reference/ticketing/introduction/
|
|
13
|
+
* OAuth migration: https://developer.zendesk.com/documentation/authentication/oauth-migration/
|
|
14
|
+
*/
|
|
15
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
16
|
+
import { getTicketTool } from "../lib/tools/get-ticket";
|
|
17
|
+
import { getCommentsTool } from "../lib/tools/get-comments";
|
|
18
|
+
import { searchTool } from "../lib/tools/search";
|
|
19
|
+
import { getUserTool } from "../lib/tools/get-user";
|
|
20
|
+
import { getOrganizationTool } from "../lib/tools/get-organization";
|
|
21
|
+
import { downloadAttachmentTool } from "../lib/tools/download-attachment";
|
|
22
|
+
import { getViewTool } from "../lib/tools/get-view";
|
|
23
|
+
import { hasZendeskCredentials } from "../lib/auth";
|
|
24
|
+
|
|
25
|
+
// Compact tool guidance appended to the system prompt. Intentionally small:
|
|
26
|
+
// the tool descriptions carry the detail; this tells the agent what the
|
|
27
|
+
// extension is for, the URL shortcut, and the two gotchas (HTML bodies,
|
|
28
|
+
// read-only scope).
|
|
29
|
+
const TOOL_GUIDANCE = [
|
|
30
|
+
"These Zendesk tools are read-only and act on the tenant configured via ZENDESK_SUBDOMAIN.",
|
|
31
|
+
"zendesk_get_ticket and zendesk_get_comments accept a raw ticket id or a pasted agent URL like https://{subdomain}.zendesk.com/agent/tickets/7942 - pass the URL as-is.",
|
|
32
|
+
"Ticket descriptions and comment bodies come back as stripped plain text; the underlying Zendesk fields are HTML, so never paste raw HTML at the user.",
|
|
33
|
+
"To view attachments (images, PDFs): zendesk_get_comments lists them as 'attachment: #ID name'; call zendesk_download_attachment with that #ID, then use the native `read` tool on the returned path to view the image.",
|
|
34
|
+
"Saved ticket lists (filters in the agent UI, URLs like https://{subdomain}.zendesk.com/agent/filters/20824934716439) are readable with zendesk_get_view - pass the URL as-is.",
|
|
35
|
+
"Authentication uses Zendesk OAuth client credentials (ZENDESK_SUBDOMAIN, ZENDESK_CLIENT_ID, ZENDESK_CLIENT_SECRET); tokens are fetched and cached internally. API tokens are deprecated by Zendesk - never ask the user for one.",
|
|
36
|
+
"A 403 error means the OAuth client's Allowed scopes are narrower than the read scope set; a 429 includes a retry hint. Do not retry in a tight loop.",
|
|
37
|
+
].join(" ");
|
|
38
|
+
|
|
39
|
+
function zendeskMe(pi: ExtensionAPI): void {
|
|
40
|
+
pi.registerTool(getTicketTool);
|
|
41
|
+
pi.registerTool(getCommentsTool);
|
|
42
|
+
pi.registerTool(searchTool);
|
|
43
|
+
pi.registerTool(getUserTool);
|
|
44
|
+
pi.registerTool(getOrganizationTool);
|
|
45
|
+
pi.registerTool(downloadAttachmentTool);
|
|
46
|
+
pi.registerTool(getViewTool);
|
|
47
|
+
|
|
48
|
+
pi.on("before_agent_start", async (event) => {
|
|
49
|
+
return {
|
|
50
|
+
systemPrompt: [event.systemPrompt, TOOL_GUIDANCE]
|
|
51
|
+
.filter(Boolean)
|
|
52
|
+
.join("\n\n"),
|
|
53
|
+
};
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
// /zendesk <verb> - prefix the editor with an explicit instruction so the
|
|
57
|
+
// agent reaches for the right tool deterministically. Same prefill pattern
|
|
58
|
+
// as pi-slack and pi-asana.
|
|
59
|
+
//
|
|
60
|
+
// /zendesk ticket <id-or-url> -> zendesk_get_ticket
|
|
61
|
+
// /zendesk comments <id-or-url> -> zendesk_get_comments
|
|
62
|
+
// /zendesk search <query> -> zendesk_search
|
|
63
|
+
// /zendesk user <id> -> zendesk_get_user
|
|
64
|
+
// /zendesk org <id> -> zendesk_get_organization
|
|
65
|
+
//
|
|
66
|
+
// Bare /zendesk prints credential status + usage.
|
|
67
|
+
pi.registerCommand("zendesk", {
|
|
68
|
+
description:
|
|
69
|
+
"Zendesk read tools. Usage: /zendesk ticket <id-or-url> | /zendesk comments <id-or-url> | /zendesk search <query> | /zendesk view <id-or-url> | /zendesk user <id> | /zendesk org <id>.",
|
|
70
|
+
handler: async (args, ctx) => {
|
|
71
|
+
if (!hasZendeskCredentials()) {
|
|
72
|
+
ctx.ui.notify(
|
|
73
|
+
"Zendesk: ZENDESK_SUBDOMAIN, ZENDESK_CLIENT_ID, or ZENDESK_CLIENT_SECRET is not set. " +
|
|
74
|
+
"Create a Confidential OAuth client (Admin Center > Apps and integrations > APIs > OAuth clients) " +
|
|
75
|
+
"with Allowed scopes 'tickets:read users:read organizations:read', then export the three env vars " +
|
|
76
|
+
"in the shell that runs pi. API tokens are not supported (Zendesk retires them 2027-04-30).",
|
|
77
|
+
"warning",
|
|
78
|
+
);
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const trimmed = args.trim();
|
|
83
|
+
if (!trimmed) {
|
|
84
|
+
ctx.ui.notify(
|
|
85
|
+
"Zendesk: authenticated for https://${process.env.ZENDESK_SUBDOMAIN?.trim()}.zendesk.com (read-only). " +
|
|
86
|
+
"Usage: /zendesk ticket <id-or-url> | /zendesk comments <id-or-url> | /zendesk search <query> | /zendesk view <id-or-url> | /zendesk user <id> | /zendesk org <id>",
|
|
87
|
+
"info",
|
|
88
|
+
);
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const firstSpace = trimmed.indexOf(" ");
|
|
93
|
+
const verb = (
|
|
94
|
+
firstSpace === -1 ? trimmed : trimmed.slice(0, firstSpace)
|
|
95
|
+
).toLowerCase();
|
|
96
|
+
const rest = firstSpace === -1 ? "" : trimmed.slice(firstSpace + 1).trim();
|
|
97
|
+
|
|
98
|
+
let prompt: string | null = null;
|
|
99
|
+
|
|
100
|
+
switch (verb) {
|
|
101
|
+
case "ticket":
|
|
102
|
+
case "comments": {
|
|
103
|
+
if (!rest) {
|
|
104
|
+
ctx.ui.notify(
|
|
105
|
+
`Usage: /zendesk ${verb} <id-or-url>\nExample: /zendesk ${verb} https://{subdomain}.zendesk.com/agent/tickets/7942`,
|
|
106
|
+
"warning",
|
|
107
|
+
);
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
const tool = verb === "ticket" ? "zendesk_get_ticket" : "zendesk_get_comments";
|
|
111
|
+
prompt = `Call the ${tool} tool with ticket="${rest}" to read that Zendesk ticket${
|
|
112
|
+
verb === "ticket" ? " with people resolved" : "'s full comment thread"
|
|
113
|
+
}.`;
|
|
114
|
+
break;
|
|
115
|
+
}
|
|
116
|
+
case "search":
|
|
117
|
+
case "find":
|
|
118
|
+
if (!rest) {
|
|
119
|
+
ctx.ui.notify(
|
|
120
|
+
'Usage: /zendesk search <query>\nExample: /zendesk search status:open priority:urgent billing',
|
|
121
|
+
"warning",
|
|
122
|
+
);
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
prompt = `Call the zendesk_search tool with query=${JSON.stringify(rest)} to search Zendesk tickets.`;
|
|
126
|
+
break;
|
|
127
|
+
case "view":
|
|
128
|
+
case "filter": {
|
|
129
|
+
if (!rest) {
|
|
130
|
+
ctx.ui.notify(
|
|
131
|
+
`Usage: /zendesk ${verb} <id-or-url>\nExample: /zendesk ${verb} https://{subdomain}.zendesk.com/agent/filters/20824934716439`,
|
|
132
|
+
"warning",
|
|
133
|
+
);
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
prompt = `Call the zendesk_get_view tool with view="${rest}" to list the tickets in that Zendesk saved view.`;
|
|
137
|
+
break;
|
|
138
|
+
}
|
|
139
|
+
case "user": {
|
|
140
|
+
if (!/^\d+$/.test(rest)) {
|
|
141
|
+
ctx.ui.notify("Usage: /zendesk user <numeric-id>", "warning");
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
prompt = `Call the zendesk_get_user tool with user=${rest} to look up that Zendesk user.`;
|
|
145
|
+
break;
|
|
146
|
+
}
|
|
147
|
+
case "org":
|
|
148
|
+
case "organization": {
|
|
149
|
+
if (!/^\d+$/.test(rest)) {
|
|
150
|
+
ctx.ui.notify("Usage: /zendesk org <numeric-id>", "warning");
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
prompt = `Call the zendesk_get_organization tool with organization=${rest} to look up that Zendesk organization.`;
|
|
154
|
+
break;
|
|
155
|
+
}
|
|
156
|
+
default:
|
|
157
|
+
prompt = `The user typed "/zendesk ${trimmed}" with an unknown verb. Show the available verbs (ticket, comments, search, view, user, org) and ask what they want.`;
|
|
158
|
+
break;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
if (prompt) ctx.ui.setEditorText(prompt);
|
|
162
|
+
},
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export default zendeskMe;
|
package/lib/api.ts
ADDED
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
// Minimal Zendesk Support API v2 client. Plain fetch under the hood; no SDK.
|
|
2
|
+
// Mirrors the style of pi-slack-me's lib/api.ts: one call function, rich error
|
|
3
|
+
// class, JSON in / JSON out.
|
|
4
|
+
//
|
|
5
|
+
// Zendesk differences from Slack that matter here:
|
|
6
|
+
// - REST status codes are honest: 401/403/404/429 mean what they say.
|
|
7
|
+
// - OAuth 401 on an expired access token returns {error: "invalid_token"};
|
|
8
|
+
// we reset the token cache and retry once.
|
|
9
|
+
// - 429 is rate limiting; the JSON body or headers carry a retry hint.
|
|
10
|
+
// - 403 on a scoped OAuth token almost always means the token scope does
|
|
11
|
+
// not cover the endpoint (read vs write), or the client's Allowed scopes
|
|
12
|
+
// ceiling was configured narrower than what the code requests.
|
|
13
|
+
|
|
14
|
+
import {
|
|
15
|
+
getZendeskAccessToken,
|
|
16
|
+
getZendeskCredentials,
|
|
17
|
+
resetTokenCache,
|
|
18
|
+
ZendeskAuthError,
|
|
19
|
+
} from "./auth";
|
|
20
|
+
|
|
21
|
+
const REQUEST_TIMEOUT_MS = 30_000;
|
|
22
|
+
|
|
23
|
+
export interface ZdGetOptions {
|
|
24
|
+
query?: Record<string, string | number | boolean | undefined>;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// Error carrying HTTP status, the Zendesk error code when present, and an
|
|
28
|
+
// optional retry-after hint (seconds). isRateLimited / isAuthError let callers
|
|
29
|
+
// branch without parsing message text.
|
|
30
|
+
export class ZendeskApiError extends Error {
|
|
31
|
+
readonly status: number;
|
|
32
|
+
readonly code?: string;
|
|
33
|
+
readonly retryAfter?: number;
|
|
34
|
+
readonly isRateLimited: boolean;
|
|
35
|
+
readonly isAuthError: boolean;
|
|
36
|
+
constructor(message: string, status = 0, code?: string, retryAfter?: number) {
|
|
37
|
+
super(message);
|
|
38
|
+
this.name = "ZendeskApiError";
|
|
39
|
+
this.status = status;
|
|
40
|
+
this.code = code;
|
|
41
|
+
this.retryAfter = retryAfter;
|
|
42
|
+
this.isRateLimited = status === 429;
|
|
43
|
+
this.isAuthError = status === 401;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function buildUrl(path: string, query: ZdGetOptions["query"]): string {
|
|
48
|
+
const { subdomain } = getZendeskCredentials();
|
|
49
|
+
const url = new URL(`https://${subdomain}.zendesk.com/api/v2/${path}`);
|
|
50
|
+
if (query) {
|
|
51
|
+
for (const [k, v] of Object.entries(query)) {
|
|
52
|
+
if (v === undefined || v === null) continue;
|
|
53
|
+
url.searchParams.set(k, String(v));
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return url.toString();
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
interface ZdErrorBody {
|
|
60
|
+
error?: string;
|
|
61
|
+
description?: string;
|
|
62
|
+
details?: Record<string, Array<{ description?: string }>>;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// Extract Zendesk's human-readable description from an error body when one
|
|
66
|
+
// exists. Search errors nest descriptions under `details`; most others use
|
|
67
|
+
// top-level `description` or `error`.
|
|
68
|
+
function describeBody(parsed: ZdErrorBody | null): string | undefined {
|
|
69
|
+
if (!parsed) return undefined;
|
|
70
|
+
if (parsed.description) return parsed.description;
|
|
71
|
+
const first = Object.values(parsed.details ?? {})[0];
|
|
72
|
+
return first?.[0]?.description ?? parsed.error;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async function readJson<T>(response: Response, method: string): Promise<T> {
|
|
76
|
+
const text = await response.text();
|
|
77
|
+
try {
|
|
78
|
+
return JSON.parse(text) as T;
|
|
79
|
+
} catch {
|
|
80
|
+
throw new ZendeskApiError(
|
|
81
|
+
`Zendesk ${method}: non-JSON response (HTTP ${response.status}).`,
|
|
82
|
+
response.status,
|
|
83
|
+
);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// Shared GET with auth, timeout, rate-limit and auth-retry handling.
|
|
88
|
+
// Retries exactly once after a 401 invalid_token: the access token expired
|
|
89
|
+
// server-side or was revoked, so drop the cache, mint a new token, retry.
|
|
90
|
+
export async function zdGet<T>(
|
|
91
|
+
path: string,
|
|
92
|
+
options: ZdGetOptions = {},
|
|
93
|
+
): Promise<T> {
|
|
94
|
+
const method = `GET /api/v2/${path}`;
|
|
95
|
+
|
|
96
|
+
const runOnce = async (): Promise<Response> => {
|
|
97
|
+
const token = await getZendeskAccessToken();
|
|
98
|
+
const controller = new AbortController();
|
|
99
|
+
const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
|
|
100
|
+
try {
|
|
101
|
+
return await fetch(buildUrl(path, options.query), {
|
|
102
|
+
method: "GET",
|
|
103
|
+
headers: {
|
|
104
|
+
Authorization: `Bearer ${token}`,
|
|
105
|
+
Accept: "application/json",
|
|
106
|
+
},
|
|
107
|
+
signal: controller.signal,
|
|
108
|
+
});
|
|
109
|
+
} finally {
|
|
110
|
+
clearTimeout(timer);
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
let response: Response;
|
|
115
|
+
try {
|
|
116
|
+
response = await runOnce();
|
|
117
|
+
if (response.status === 401) {
|
|
118
|
+
const body = await readJson<ZdErrorBody>(response, method).catch(
|
|
119
|
+
() => null,
|
|
120
|
+
);
|
|
121
|
+
if (body?.error === "invalid_token") {
|
|
122
|
+
resetTokenCache();
|
|
123
|
+
response = await runOnce();
|
|
124
|
+
} else {
|
|
125
|
+
throw new ZendeskApiError(
|
|
126
|
+
`Zendesk ${method}: unauthorized (HTTP 401). Check the OAuth ` +
|
|
127
|
+
"client credentials (ZENDESK_CLIENT_ID / ZENDESK_CLIENT_SECRET).",
|
|
128
|
+
401,
|
|
129
|
+
body?.error,
|
|
130
|
+
);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
} catch (err) {
|
|
134
|
+
if (err instanceof ZendeskApiError || err instanceof ZendeskAuthError) {
|
|
135
|
+
throw err;
|
|
136
|
+
}
|
|
137
|
+
throw new ZendeskApiError(transportError(method, err));
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// Rate limited: surface the retry hint so the agent can back off precisely.
|
|
141
|
+
if (response.status === 429) {
|
|
142
|
+
const retryAfterRaw =
|
|
143
|
+
response.headers.get("retry-after") ?? undefined;
|
|
144
|
+
const retryAfter = retryAfterRaw ? Number(retryAfterRaw) : undefined;
|
|
145
|
+
throw new ZendeskApiError(
|
|
146
|
+
`Zendesk rate limited on ${method}.` +
|
|
147
|
+
(retryAfter && Number.isFinite(retryAfter)
|
|
148
|
+
? ` Retry in ~${retryAfter}s.`
|
|
149
|
+
: " Retry shortly."),
|
|
150
|
+
429,
|
|
151
|
+
"ratelimited",
|
|
152
|
+
Number.isFinite(retryAfter) ? retryAfter : undefined,
|
|
153
|
+
);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
if (!response.ok) {
|
|
157
|
+
const body = await readJson<ZdErrorBody>(response, method).catch(() => null);
|
|
158
|
+
const detail = describeBody(body);
|
|
159
|
+
if (response.status === 403) {
|
|
160
|
+
throw new ZendeskApiError(
|
|
161
|
+
`Zendesk ${method}: forbidden (HTTP 403). The access token scope ` +
|
|
162
|
+
"does not cover this endpoint. This extension requests read-only " +
|
|
163
|
+
"scopes (tickets:read users:read organizations:read); a 403 on a " +
|
|
164
|
+
"read usually means the client's Allowed scopes in Admin Center " +
|
|
165
|
+
"were configured narrower than that.",
|
|
166
|
+
403,
|
|
167
|
+
body?.error,
|
|
168
|
+
);
|
|
169
|
+
}
|
|
170
|
+
if (response.status === 404) {
|
|
171
|
+
throw new ZendeskApiError(
|
|
172
|
+
`Zendesk ${method}: not found (HTTP 404).${detail ? ` ${detail}` : ""}`,
|
|
173
|
+
404,
|
|
174
|
+
body?.error,
|
|
175
|
+
);
|
|
176
|
+
}
|
|
177
|
+
if (response.status === 401) {
|
|
178
|
+
// Second 401 after a fresh token: credentials are genuinely bad.
|
|
179
|
+
throw new ZendeskApiError(
|
|
180
|
+
`Zendesk ${method}: unauthorized even after refreshing the OAuth ` +
|
|
181
|
+
"token (HTTP 401). Verify ZENDESK_CLIENT_ID / " +
|
|
182
|
+
"ZENDESK_CLIENT_SECRET and that the client has not been revoked.",
|
|
183
|
+
401,
|
|
184
|
+
body?.error,
|
|
185
|
+
);
|
|
186
|
+
}
|
|
187
|
+
if (response.status >= 500) {
|
|
188
|
+
throw new ZendeskApiError(
|
|
189
|
+
`Zendesk ${method}: server error (HTTP ${response.status}). Retry; ` +
|
|
190
|
+
"check https://status.zendesk.com.",
|
|
191
|
+
response.status,
|
|
192
|
+
);
|
|
193
|
+
}
|
|
194
|
+
throw new ZendeskApiError(
|
|
195
|
+
`Zendesk ${method} failed (HTTP ${response.status}).` +
|
|
196
|
+
(detail ? ` ${detail}` : ""),
|
|
197
|
+
response.status,
|
|
198
|
+
body?.error,
|
|
199
|
+
);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
return readJson<T>(response, method);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// Classify a fetch() throw (network error or abort/timeout) into a readable
|
|
206
|
+
// message. Shared by zdGet and zdDownload.
|
|
207
|
+
function transportError(method: string, err: unknown): string {
|
|
208
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
209
|
+
if (msg.includes("abort")) {
|
|
210
|
+
return `Zendesk ${method} timed out after ${REQUEST_TIMEOUT_MS / 1000}s.`;
|
|
211
|
+
}
|
|
212
|
+
return `Network error reaching Zendesk (${method}): ${msg}`;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// Attachment content URLs are pre-signed and redirect (302) to storage. Send
|
|
216
|
+
// NO Authorization header: a bearer header breaks the storage-host redirect
|
|
217
|
+
// signature (verified against production 2026-08-28 - plain GET + redirects
|
|
218
|
+
// returns 200, authenticated GET returns a 403 HTML error page). Node fetch
|
|
219
|
+
// follows redirects by default.
|
|
220
|
+
const DOWNLOAD_TIMEOUT_MS = 60_000;
|
|
221
|
+
export const MAX_DOWNLOAD_BYTES = 100 * 1024 * 1024;
|
|
222
|
+
|
|
223
|
+
export async function zdDownload(
|
|
224
|
+
url: string,
|
|
225
|
+
): Promise<{ bytes: Uint8Array; contentType: string | null }> {
|
|
226
|
+
const controller = new AbortController();
|
|
227
|
+
const timer = setTimeout(() => controller.abort(), DOWNLOAD_TIMEOUT_MS);
|
|
228
|
+
try {
|
|
229
|
+
const response = await fetch(url, {
|
|
230
|
+
method: "GET",
|
|
231
|
+
headers: { Accept: "*/*" },
|
|
232
|
+
redirect: "follow",
|
|
233
|
+
signal: controller.signal,
|
|
234
|
+
});
|
|
235
|
+
if (!response.ok) {
|
|
236
|
+
throw new ZendeskApiError(
|
|
237
|
+
`Zendesk attachment download failed (HTTP ${response.status}). ` +
|
|
238
|
+
"The signed URL may have expired; re-run zendesk_get_comments to " +
|
|
239
|
+
"get a fresh one.",
|
|
240
|
+
response.status,
|
|
241
|
+
);
|
|
242
|
+
}
|
|
243
|
+
const declared = Number(response.headers.get("content-length") ?? "0");
|
|
244
|
+
if (declared > MAX_DOWNLOAD_BYTES) {
|
|
245
|
+
throw new ZendeskApiError(
|
|
246
|
+
`Zendesk attachment too large (${declared} bytes; limit ${MAX_DOWNLOAD_BYTES}).`,
|
|
247
|
+
413,
|
|
248
|
+
);
|
|
249
|
+
}
|
|
250
|
+
const buffer = await response.arrayBuffer();
|
|
251
|
+
if (buffer.byteLength > MAX_DOWNLOAD_BYTES) {
|
|
252
|
+
throw new ZendeskApiError(
|
|
253
|
+
`Zendesk attachment too large (${buffer.byteLength} bytes; limit ${MAX_DOWNLOAD_BYTES}).`,
|
|
254
|
+
413,
|
|
255
|
+
);
|
|
256
|
+
}
|
|
257
|
+
return {
|
|
258
|
+
bytes: new Uint8Array(buffer),
|
|
259
|
+
contentType: response.headers.get("content-type"),
|
|
260
|
+
};
|
|
261
|
+
} catch (err) {
|
|
262
|
+
if (err instanceof ZendeskApiError) throw err;
|
|
263
|
+
throw new ZendeskApiError(transportError("attachment download", err));
|
|
264
|
+
} finally {
|
|
265
|
+
clearTimeout(timer);
|
|
266
|
+
}
|
|
267
|
+
}
|