@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/lib/auth.ts
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
// Zendesk auth: OAuth client-credentials grant. Env-only, no file fallback,
|
|
2
|
+
// no API tokens (Zendesk deprecates API tokens: unused tokens auto-deactivate
|
|
3
|
+
// from 2026-07-28, all stop working 2027-04-30).
|
|
4
|
+
//
|
|
5
|
+
// Required env:
|
|
6
|
+
// ZENDESK_SUBDOMAIN e.g. "{subdomain}" for https://{subdomain}.zendesk.com
|
|
7
|
+
// ZENDESK_CLIENT_ID OAuth client identifier (confidential client)
|
|
8
|
+
// ZENDESK_CLIENT_SECRET OAuth client secret (shown once at creation)
|
|
9
|
+
//
|
|
10
|
+
// One-time setup in Admin Center: Apps and integrations > APIs > OAuth clients.
|
|
11
|
+
// Create a Confidential client and set Allowed scopes to the read set below so
|
|
12
|
+
// the client can never request broader access. The client-credentials flow has
|
|
13
|
+
// no refresh token: re-POST /oauth/tokens when the access token expires.
|
|
14
|
+
//
|
|
15
|
+
// The client secret is opaque - never logged, echoed, or redacted anywhere.
|
|
16
|
+
|
|
17
|
+
export const ZENDESK_OAUTH_SCOPE =
|
|
18
|
+
"tickets:read users:read organizations:read ticket_views:read";
|
|
19
|
+
|
|
20
|
+
export class ZendeskAuthError extends Error {
|
|
21
|
+
readonly kind: "missing_env" | "token_request_failed";
|
|
22
|
+
constructor(message: string, kind: ZendeskAuthError["kind"]) {
|
|
23
|
+
super(message);
|
|
24
|
+
this.name = "ZendeskAuthError";
|
|
25
|
+
this.kind = kind;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface ZendeskCredentials {
|
|
30
|
+
subdomain: string;
|
|
31
|
+
clientId: string;
|
|
32
|
+
clientSecret: string;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// Read the three env vars or throw with setup instructions. The rich message
|
|
36
|
+
// is the point: the agent (or the human) can act on it directly.
|
|
37
|
+
export function getZendeskCredentials(): ZendeskCredentials {
|
|
38
|
+
const subdomain = process.env.ZENDESK_SUBDOMAIN?.trim();
|
|
39
|
+
const clientId = process.env.ZENDESK_CLIENT_ID?.trim();
|
|
40
|
+
const clientSecret = process.env.ZENDESK_CLIENT_SECRET?.trim();
|
|
41
|
+
if (!subdomain || !clientId || !clientSecret) {
|
|
42
|
+
const missing = [
|
|
43
|
+
!subdomain && "ZENDESK_SUBDOMAIN",
|
|
44
|
+
!clientId && "ZENDESK_CLIENT_ID",
|
|
45
|
+
!clientSecret && "ZENDESK_CLIENT_SECRET",
|
|
46
|
+
]
|
|
47
|
+
.filter(Boolean)
|
|
48
|
+
.join(", ");
|
|
49
|
+
throw new ZendeskAuthError(
|
|
50
|
+
`Zendesk: missing env var(s): ${missing}. ` +
|
|
51
|
+
"In Admin Center go to Apps and integrations > APIs > OAuth clients, " +
|
|
52
|
+
"create a Confidential client, set Allowed scopes to " +
|
|
53
|
+
`"${ZENDESK_OAUTH_SCOPE}", then export ` +
|
|
54
|
+
"ZENDESK_SUBDOMAIN, ZENDESK_CLIENT_ID, and ZENDESK_CLIENT_SECRET " +
|
|
55
|
+
"in the shell that runs pi. API tokens are not supported: Zendesk " +
|
|
56
|
+
"retires them on 2027-04-30.",
|
|
57
|
+
"missing_env",
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
return { subdomain, clientId, clientSecret };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// True when all three env vars are present and non-empty. UI/status use only -
|
|
64
|
+
// never use this to gate a tool (call getZendeskAccessToken inside the tool so
|
|
65
|
+
// the rich ZendeskAuthError surfaces).
|
|
66
|
+
export function hasZendeskCredentials(): boolean {
|
|
67
|
+
return Boolean(
|
|
68
|
+
process.env.ZENDESK_SUBDOMAIN?.trim() &&
|
|
69
|
+
process.env.ZENDESK_CLIENT_ID?.trim() &&
|
|
70
|
+
process.env.ZENDESK_CLIENT_SECRET?.trim(),
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
interface CachedToken {
|
|
75
|
+
accessToken: string;
|
|
76
|
+
// Milliseconds since epoch after which the token should be re-requested.
|
|
77
|
+
expiresAt: number;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
let cachedToken: CachedToken | undefined;
|
|
81
|
+
|
|
82
|
+
// Re-request the token this long before the reported expiry, so a request in
|
|
83
|
+
// flight does not ride an expiring token.
|
|
84
|
+
const EXPIRY_MARGIN_MS = 60_000;
|
|
85
|
+
|
|
86
|
+
interface ZendeskTokenResponse {
|
|
87
|
+
access_token?: string;
|
|
88
|
+
token_type?: string;
|
|
89
|
+
scope?: string;
|
|
90
|
+
expires_in?: number;
|
|
91
|
+
error?: string;
|
|
92
|
+
error_description?: string;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function tokenEndpoint(subdomain: string): string {
|
|
96
|
+
return `https://${subdomain}.zendesk.com/oauth/tokens`;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// Exchange client credentials for an access token. No refresh token exists in
|
|
100
|
+
// this flow; callers just call this again after expiry (see
|
|
101
|
+
// getZendeskAccessToken). Throws ZendeskAuthError on missing env or a failed
|
|
102
|
+
// token request; error bodies are surfaced verbatim because Zendesk puts the
|
|
103
|
+
// useful part in `error` (invalid_client, invalid_scope, ...).
|
|
104
|
+
export async function requestZendeskAccessToken(): Promise<string> {
|
|
105
|
+
const { subdomain, clientId, clientSecret } = getZendeskCredentials();
|
|
106
|
+
|
|
107
|
+
// URLSearchParams = stdlib form-encoding. Zendesk accepts
|
|
108
|
+
// application/x-www-form-urlencoded per the OAuth 2.0 spec default.
|
|
109
|
+
const body = new URLSearchParams({
|
|
110
|
+
grant_type: "client_credentials",
|
|
111
|
+
client_id: clientId,
|
|
112
|
+
client_secret: clientSecret,
|
|
113
|
+
scope: ZENDESK_OAUTH_SCOPE,
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
let response: Response;
|
|
117
|
+
try {
|
|
118
|
+
response = await fetch(tokenEndpoint(subdomain), {
|
|
119
|
+
method: "POST",
|
|
120
|
+
headers: {
|
|
121
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
122
|
+
Accept: "application/json",
|
|
123
|
+
},
|
|
124
|
+
body: body.toString(),
|
|
125
|
+
});
|
|
126
|
+
} catch (err) {
|
|
127
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
128
|
+
throw new ZendeskAuthError(
|
|
129
|
+
`Zendesk: network error requesting OAuth token: ${msg}`,
|
|
130
|
+
"token_request_failed",
|
|
131
|
+
);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const text = await response.text();
|
|
135
|
+
let parsed: ZendeskTokenResponse | null = null;
|
|
136
|
+
try {
|
|
137
|
+
parsed = JSON.parse(text) as ZendeskTokenResponse;
|
|
138
|
+
} catch {
|
|
139
|
+
// Non-JSON body; fall through to the status-based message.
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
if (!response.ok || !parsed?.access_token) {
|
|
143
|
+
const detail =
|
|
144
|
+
parsed?.error_description ?? parsed?.error ?? `HTTP ${response.status}`;
|
|
145
|
+
throw new ZendeskAuthError(
|
|
146
|
+
`Zendesk OAuth token request failed: ${detail}. ` +
|
|
147
|
+
"Check ZENDESK_CLIENT_ID / ZENDESK_CLIENT_SECRET, that the client is " +
|
|
148
|
+
"Confidential, and that the token scope is within the client's " +
|
|
149
|
+
"Allowed scopes (400 invalid_scope = requested scope exceeds the " +
|
|
150
|
+
"ceiling configured in Admin Center).",
|
|
151
|
+
"token_request_failed",
|
|
152
|
+
);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
return parsed.access_token;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// Return a valid access token, using the cache when it is fresh. Reactively
|
|
159
|
+
// refreshes when the cache is missing or inside the expiry margin. The 401
|
|
160
|
+
// path (server-side revocation before expiry) is handled in api.ts, which
|
|
161
|
+
// calls resetTokenCache() and retries once.
|
|
162
|
+
export async function getZendeskAccessToken(): Promise<string> {
|
|
163
|
+
if (cachedToken && Date.now() < cachedToken.expiresAt) {
|
|
164
|
+
return cachedToken.accessToken;
|
|
165
|
+
}
|
|
166
|
+
const accessToken = await requestZendeskAccessToken();
|
|
167
|
+
|
|
168
|
+
// expires_in is in seconds and technically optional; default to the
|
|
169
|
+
// documented 30-minute value when absent.
|
|
170
|
+
const expiresInSec = 1800;
|
|
171
|
+
cachedToken = {
|
|
172
|
+
accessToken,
|
|
173
|
+
expiresAt: Date.now() + expiresInSec * 1000 - EXPIRY_MARGIN_MS,
|
|
174
|
+
};
|
|
175
|
+
return accessToken;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// Drop the cached token. Called by api.ts after a 401 invalid_token so the
|
|
179
|
+
// retry fetches a fresh one; also used in tests.
|
|
180
|
+
export function resetTokenCache(): void {
|
|
181
|
+
cachedToken = undefined;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// Test-only alias matching the sibling extensions' _resetAuthCache naming.
|
|
185
|
+
export function _resetAuthCache(): void {
|
|
186
|
+
resetTokenCache();
|
|
187
|
+
}
|
package/lib/format.ts
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
ZdComment,
|
|
3
|
+
ZdOrganization,
|
|
4
|
+
ZdTicket,
|
|
5
|
+
ZdUser,
|
|
6
|
+
} from "./types";
|
|
7
|
+
|
|
8
|
+
// Formatting helpers shared by the tools. Output targets an LLM: plain text,
|
|
9
|
+
// stable field order, ids alongside resolved names so the agent can follow up
|
|
10
|
+
// with zendesk_get_user / zendesk_get_organization without re-fetching.
|
|
11
|
+
|
|
12
|
+
export interface SideLoadMaps {
|
|
13
|
+
users: Map<number, ZdUser>;
|
|
14
|
+
organizations: Map<number, ZdOrganization>;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function buildSideLoadMaps(
|
|
18
|
+
users?: ZdUser[],
|
|
19
|
+
organizations?: ZdOrganization[],
|
|
20
|
+
): SideLoadMaps {
|
|
21
|
+
return {
|
|
22
|
+
users: new Map((users ?? []).map((u) => [u.id, u])),
|
|
23
|
+
organizations: new Map((organizations ?? []).map((o) => [o.id, o])),
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// "Ada Lovelace <ada@example.com>" when an email exists, "Ada Lovelace"
|
|
28
|
+
// otherwise, "#123 (unknown user)" when side-loading missed the record.
|
|
29
|
+
export function userName(maps: SideLoadMaps, id: number | null): string {
|
|
30
|
+
if (id === null || id === undefined) return "unassigned";
|
|
31
|
+
const user = maps.users.get(id);
|
|
32
|
+
if (!user) return `#${id}`;
|
|
33
|
+
return user.email ? `${user.name} <${user.email}>` : user.name;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function orgName(maps: SideLoadMaps, id: number | null): string {
|
|
37
|
+
if (id === null || id === undefined) return "none";
|
|
38
|
+
const org = maps.organizations.get(id);
|
|
39
|
+
return org ? org.name : `#${id}`;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// "2026-07-14 15:03 UTC" from a Zendesk ISO timestamp. UTC everywhere: the
|
|
43
|
+
// agent compares timestamps across tools, so no locale math.
|
|
44
|
+
export function formatDate(iso: string | null | undefined): string {
|
|
45
|
+
if (!iso) return "n/a";
|
|
46
|
+
return `${iso.slice(0, 10)} ${iso.slice(11, 16)} UTC`;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const ENTITY_MAP: Record<string, string> = {
|
|
50
|
+
"&": "&",
|
|
51
|
+
"<": "<",
|
|
52
|
+
">": ">",
|
|
53
|
+
""": '"',
|
|
54
|
+
"'": "'",
|
|
55
|
+
"'": "'",
|
|
56
|
+
" ": " ",
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
// Comment and description bodies arrive as HTML. The agent must not paste raw
|
|
60
|
+
// HTML at the user, so tools render stripped plain text (prefer plain_body
|
|
61
|
+
// when Zendesk supplies it). Full fidelity stays one call away: the raw field
|
|
62
|
+
// is echoed in the details the agent can quote when needed.
|
|
63
|
+
export function stripHtml(html: string | null | undefined): string {
|
|
64
|
+
if (!html) return "";
|
|
65
|
+
const withBreaks = html
|
|
66
|
+
.replace(/<br\s*\/?>/gi, "\n")
|
|
67
|
+
.replace(/<\/(p|div|li|tr|h[1-6]|blockquote)>/gi, "\n")
|
|
68
|
+
.replace(/<li[^>]*>/gi, "- ");
|
|
69
|
+
const withoutTags = withBreaks.replace(/<[^>]*>/g, "");
|
|
70
|
+
const decoded = withoutTags.replace(
|
|
71
|
+
/&(amp|lt|gt|quot|#39|apos|nbsp);/g,
|
|
72
|
+
(entity) => ENTITY_MAP[entity] ?? entity,
|
|
73
|
+
);
|
|
74
|
+
// Collapse >2 blank lines from block-tag expansion; trim leading pad.
|
|
75
|
+
return decoded
|
|
76
|
+
.split("\n")
|
|
77
|
+
.map((line) => line.replace(/\s+$/g, ""))
|
|
78
|
+
.join("\n")
|
|
79
|
+
.replace(/\n{3,}/g, "\n\n")
|
|
80
|
+
.trim();
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export function truncate(text: string, max = 1500): string {
|
|
84
|
+
if (text.length <= max) return text;
|
|
85
|
+
return `${text.slice(0, max)}... [truncated, ${text.length - max} chars]`;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function formatTicketLine(
|
|
89
|
+
ticket: ZdTicket,
|
|
90
|
+
maps: SideLoadMaps,
|
|
91
|
+
): string {
|
|
92
|
+
const bits = [
|
|
93
|
+
`#${ticket.id}`,
|
|
94
|
+
`[${ticket.status}]`,
|
|
95
|
+
ticket.subject ?? "(no subject)",
|
|
96
|
+
];
|
|
97
|
+
if (ticket.priority && ticket.priority !== "normal") {
|
|
98
|
+
bits.push(`(${ticket.priority})`);
|
|
99
|
+
}
|
|
100
|
+
bits.push(`- requester: ${userName(maps, ticket.requester_id)}`);
|
|
101
|
+
return bits.join(" ");
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export function formatComment(
|
|
105
|
+
comment: ZdComment,
|
|
106
|
+
maps: SideLoadMaps,
|
|
107
|
+
): string {
|
|
108
|
+
const visibility = comment.public ? "public reply" : "INTERNAL NOTE";
|
|
109
|
+
const channel = comment.via?.channel ? ` via ${comment.via.channel}` : "";
|
|
110
|
+
const header = `- ${formatDate(comment.created_at)} - ${userName(
|
|
111
|
+
maps,
|
|
112
|
+
comment.author_id,
|
|
113
|
+
)} - ${visibility}${channel} [comment #${comment.id}]`;
|
|
114
|
+
const body = truncate(stripHtml(comment.body ?? comment.html_body), 1500);
|
|
115
|
+
const attachments = (comment.attachments ?? []).filter((a) => !a.inline);
|
|
116
|
+
const attachmentLines = attachments.length
|
|
117
|
+
? [
|
|
118
|
+
"",
|
|
119
|
+
...attachments.map(
|
|
120
|
+
(a) =>
|
|
121
|
+
` attachment: #${a.id} ${a.file_name}${
|
|
122
|
+
a.size ? ` (${a.size} bytes)` : ""
|
|
123
|
+
}`,
|
|
124
|
+
),
|
|
125
|
+
]
|
|
126
|
+
: [];
|
|
127
|
+
return [header, body || "(empty)", ...attachmentLines].join("\n");
|
|
128
|
+
}
|
package/lib/prompts.ts
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
// Tool titles, descriptions, and parameter descriptions. Kept as constants so
|
|
2
|
+
// the tool modules stay lean and the wording is reviewable in one place.
|
|
3
|
+
// Descriptions are the model's main steering surface: they carry the accepted
|
|
4
|
+
// input shapes, the gotchas (HTML bodies, visibility), and the follow-up paths.
|
|
5
|
+
|
|
6
|
+
export const GET_TICKET_TITLE = "Get Zendesk ticket";
|
|
7
|
+
export const GET_TICKET_DESCRIPTION =
|
|
8
|
+
"Fetch one Zendesk ticket with requester, assignee, and organization resolved in a single call. " +
|
|
9
|
+
"Accepts a numeric ticket id or a pasted agent URL such as https://{subdomain}.zendesk.com/agent/tickets/7942. " +
|
|
10
|
+
"Returns subject, status, priority, people, tags, timestamps, and the stripped plain-text description. " +
|
|
11
|
+
"Read-only.";
|
|
12
|
+
export const GET_TICKET_PARAM =
|
|
13
|
+
'Ticket id ("7942") or full agent URL ("https://{subdomain}.zendesk.com/agent/tickets/7942").';
|
|
14
|
+
export const GET_TICKET_INCLUDE_DESCRIPTION =
|
|
15
|
+
'Extra side-loaded records beyond the default "users,organizations" (e.g. ["groups"]).';
|
|
16
|
+
|
|
17
|
+
export const GET_COMMENTS_TITLE = "Get Zendesk ticket comments";
|
|
18
|
+
export const GET_COMMENTS_DESCRIPTION =
|
|
19
|
+
"Read the full comment thread of a Zendesk ticket: public replies and internal notes (flagged as such), " +
|
|
20
|
+
"newest last, with author names resolved via side-loading. Accepts a numeric ticket id or a pasted agent URL. " +
|
|
21
|
+
"Bodies are returned as stripped plain text. Read-only.";
|
|
22
|
+
export const GET_COMMENTS_PARAM =
|
|
23
|
+
'Ticket id ("7942") or full agent URL ("https://{subdomain}.zendesk.com/agent/tickets/7942").';
|
|
24
|
+
export const GET_COMMENTS_LIMIT_DESCRIPTION =
|
|
25
|
+
"Render only the N most recent entries (default 20). Older entries are counted, not fetched twice - the thread arrives in one call either way.";
|
|
26
|
+
export const GET_COMMENTS_PUBLIC_ONLY_DESCRIPTION =
|
|
27
|
+
"When true, hide internal notes and render public replies only. Default false.";
|
|
28
|
+
|
|
29
|
+
export const SEARCH_TITLE = "Search Zendesk tickets";
|
|
30
|
+
export const SEARCH_DESCRIPTION =
|
|
31
|
+
"Search the Zendesk tenant. The query is sent to the search API; type:ticket is prepended unless the query already constrains a type or all_types is set. " +
|
|
32
|
+
"Use Zendesk search syntax: status:open, priority:urgent, requester:1042, organization:77, tags:billing, plus free text. " +
|
|
33
|
+
"Read-only.";
|
|
34
|
+
export const SEARCH_QUERY_DESCRIPTION =
|
|
35
|
+
'Zendesk search query, e.g. "status:open priority:urgent billing" or "requester:1042".';
|
|
36
|
+
export const SEARCH_LIMIT_DESCRIPTION =
|
|
37
|
+
"Max results per page (default 25, max 100).";
|
|
38
|
+
export const SEARCH_ALL_TYPES_DESCRIPTION =
|
|
39
|
+
"When true, do not prepend type:ticket - results may include users and organizations. Default false.";
|
|
40
|
+
|
|
41
|
+
export const GET_USER_TITLE = "Get Zendesk user";
|
|
42
|
+
export const GET_USER_DESCRIPTION =
|
|
43
|
+
"Look up one Zendesk user by id: name, email, role, active flag, organization, notes. " +
|
|
44
|
+
"Use the requester_id / assignee_id returned by zendesk_get_ticket or zendesk_search. Read-only.";
|
|
45
|
+
export const GET_USER_PARAM = "Numeric Zendesk user id.";
|
|
46
|
+
|
|
47
|
+
export const GET_ORG_TITLE = "Get Zendesk organization";
|
|
48
|
+
export const GET_ORG_DESCRIPTION =
|
|
49
|
+
"Look up one Zendesk organization by id: name, domains, details, notes, tags. " +
|
|
50
|
+
"Use the organization_id returned by zendesk_get_ticket or zendesk_search. Read-only.";
|
|
51
|
+
export const GET_ORG_PARAM = "Numeric Zendesk organization id.";
|
|
52
|
+
|
|
53
|
+
export const DOWNLOAD_TITLE = "Download Zendesk ticket attachment";
|
|
54
|
+
export const DOWNLOAD_DESCRIPTION =
|
|
55
|
+
"Download one ticket attachment to a local temp file so it can be viewed. " +
|
|
56
|
+
"Find the attachment id in zendesk_get_comments output (lines like 'attachment: #ID name'). " +
|
|
57
|
+
"After downloading, view images with the native `read` tool on the returned path. Read-only: writes only to the OS temp dir.";
|
|
58
|
+
export const DOWNLOAD_PARAM_TICKET =
|
|
59
|
+
'Ticket id ("7942") or full agent URL ("https://{subdomain}.zendesk.com/agent/tickets/7942").';
|
|
60
|
+
export const DOWNLOAD_PARAM_ID =
|
|
61
|
+
"Numeric Zendesk attachment id (from zendesk_get_comments output).";
|
|
62
|
+
|
|
63
|
+
export const GET_VIEW_TITLE = "Get Zendesk view tickets";
|
|
64
|
+
export const GET_VIEW_DESCRIPTION =
|
|
65
|
+
"List the tickets in a saved Zendesk view (called a filter in the agent UI, URLs look like https://{subdomain}.zendesk.com/agent/filters/20824934716439). " +
|
|
66
|
+
"Returns the view title and its matching tickets with requester and assignee resolved. Read-only.";
|
|
67
|
+
export const GET_VIEW_PARAM =
|
|
68
|
+
'View id ("20824934716439") or full agent URL ' +
|
|
69
|
+
'("https://{subdomain}.zendesk.com/agent/filters/20824934716439").';
|
|
70
|
+
export const GET_VIEW_LIMIT_DESCRIPTION =
|
|
71
|
+
"Max tickets to render (default 25, max 100).";
|
package/lib/result.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { AgentToolResult } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
|
|
3
|
+
// Read tools attach no details today; the union stays open so future tools
|
|
4
|
+
// can add shapes without touching every caller. Mirrors pi-slack-me.
|
|
5
|
+
export type ZendeskDetails = undefined;
|
|
6
|
+
|
|
7
|
+
export function toToolResult(
|
|
8
|
+
text: string,
|
|
9
|
+
details?: ZendeskDetails,
|
|
10
|
+
): AgentToolResult<ZendeskDetails> {
|
|
11
|
+
return {
|
|
12
|
+
content: [{ type: "text", text }],
|
|
13
|
+
details,
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
// Single error formatter shared across every tool. All Zendesk errors (auth,
|
|
18
|
+
// network, HTTP, scope) are caught at the tool boundary and converted to
|
|
19
|
+
// readable text rather than thrown - the agent sees one actionable message
|
|
20
|
+
// instead of a stack trace.
|
|
21
|
+
export function errorText(err: unknown): string {
|
|
22
|
+
if (err instanceof Error) {
|
|
23
|
+
return `Zendesk error: ${err.message}`;
|
|
24
|
+
}
|
|
25
|
+
return "Zendesk error: unknown failure.";
|
|
26
|
+
}
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { mkdir, writeFile } from "node:fs/promises";
|
|
2
|
+
import { tmpdir } from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { Type, type Static } from "typebox";
|
|
5
|
+
import type {
|
|
6
|
+
AgentToolResult,
|
|
7
|
+
ToolDefinition,
|
|
8
|
+
} from "@earendil-works/pi-coding-agent";
|
|
9
|
+
import { zdDownload, zdGet } from "../api";
|
|
10
|
+
import { toToolResult, errorText, type ZendeskDetails } from "../result";
|
|
11
|
+
import type { ZdAttachment, ZdCommentsResponse } from "../types";
|
|
12
|
+
import { parseTicketRef, TICKET_REF_EXAMPLE } from "../url";
|
|
13
|
+
import {
|
|
14
|
+
DOWNLOAD_DESCRIPTION,
|
|
15
|
+
DOWNLOAD_PARAM_ID,
|
|
16
|
+
DOWNLOAD_PARAM_TICKET,
|
|
17
|
+
DOWNLOAD_TITLE,
|
|
18
|
+
} from "../prompts";
|
|
19
|
+
|
|
20
|
+
const Params = Type.Object({
|
|
21
|
+
ticket: Type.String({ description: DOWNLOAD_PARAM_TICKET }),
|
|
22
|
+
attachment: Type.Number({ description: DOWNLOAD_PARAM_ID }),
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
// Filenames land in a shared temp dir; strip any path components and unsafe
|
|
26
|
+
// characters. Attachment id prefixes the name so repeated downloads of
|
|
27
|
+
// same-named files never collide.
|
|
28
|
+
function sanitizeFileName(name: string): string {
|
|
29
|
+
const base = path.basename(name || "attachment").replace(
|
|
30
|
+
/[^A-Za-z0-9._-]/g,
|
|
31
|
+
"_",
|
|
32
|
+
);
|
|
33
|
+
const capped = base.length > 120 ? base.slice(-120) : base;
|
|
34
|
+
return capped || "attachment";
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// Every attachment on the ticket, inline or not, for the not-found error.
|
|
38
|
+
function listAttachments(
|
|
39
|
+
resp: ZdCommentsResponse,
|
|
40
|
+
): Array<{ attachment: ZdAttachment; commentId: number }> {
|
|
41
|
+
const found: Array<{ attachment: ZdAttachment; commentId: number }> = [];
|
|
42
|
+
for (const comment of resp.comments ?? []) {
|
|
43
|
+
for (const attachment of comment.attachments ?? []) {
|
|
44
|
+
found.push({ attachment, commentId: comment.id });
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return found;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export const downloadAttachmentTool: ToolDefinition<
|
|
51
|
+
typeof Params,
|
|
52
|
+
ZendeskDetails
|
|
53
|
+
> = {
|
|
54
|
+
name: "zendesk_download_attachment",
|
|
55
|
+
label: DOWNLOAD_TITLE,
|
|
56
|
+
description: DOWNLOAD_DESCRIPTION,
|
|
57
|
+
parameters: Params,
|
|
58
|
+
async execute(
|
|
59
|
+
_toolCallId: string,
|
|
60
|
+
params: Static<typeof Params>,
|
|
61
|
+
): Promise<AgentToolResult<ZendeskDetails>> {
|
|
62
|
+
const id = parseTicketRef(params.ticket);
|
|
63
|
+
if (id === null) {
|
|
64
|
+
return toToolResult(
|
|
65
|
+
`Invalid ticket reference: ${JSON.stringify(params.ticket)}. ` +
|
|
66
|
+
`Pass ${TICKET_REF_EXAMPLE}.`,
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
try {
|
|
71
|
+
const resp = await zdGet<ZdCommentsResponse>(
|
|
72
|
+
`tickets/${id}/comments.json`,
|
|
73
|
+
);
|
|
74
|
+
const match = listAttachments(resp).find(
|
|
75
|
+
(entry) => entry.attachment.id === params.attachment,
|
|
76
|
+
);
|
|
77
|
+
|
|
78
|
+
if (!match) {
|
|
79
|
+
const available = listAttachments(resp);
|
|
80
|
+
const listing = available.length
|
|
81
|
+
? available
|
|
82
|
+
.map(
|
|
83
|
+
(entry) =>
|
|
84
|
+
`#${entry.attachment.id} ${entry.attachment.file_name} (comment #${entry.commentId})`,
|
|
85
|
+
)
|
|
86
|
+
.join(", ")
|
|
87
|
+
: "none on this ticket";
|
|
88
|
+
return toToolResult(
|
|
89
|
+
`Attachment ${params.attachment} not found on ticket ${id}. ` +
|
|
90
|
+
`Available attachments: ${listing}.`,
|
|
91
|
+
);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const { attachment } = match;
|
|
95
|
+
if (!attachment.content_url) {
|
|
96
|
+
return toToolResult(
|
|
97
|
+
`Attachment ${attachment.id} (${attachment.file_name}) has no ` +
|
|
98
|
+
"content URL; it cannot be downloaded.",
|
|
99
|
+
);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const { bytes, contentType } = await zdDownload(attachment.content_url);
|
|
103
|
+
|
|
104
|
+
const dir = path.join(tmpdir(), "pi-zendesk-me");
|
|
105
|
+
await mkdir(dir, { recursive: true });
|
|
106
|
+
const filePath = path.join(
|
|
107
|
+
dir,
|
|
108
|
+
`${attachment.id}-${sanitizeFileName(attachment.file_name)}`,
|
|
109
|
+
);
|
|
110
|
+
await writeFile(filePath, bytes);
|
|
111
|
+
|
|
112
|
+
return toToolResult(
|
|
113
|
+
[
|
|
114
|
+
`Downloaded: ${filePath}`,
|
|
115
|
+
`File: ${attachment.file_name} (${bytes.byteLength} bytes` +
|
|
116
|
+
`${contentType ? `, ${contentType}` : ""}) from comment #${match.commentId}.`,
|
|
117
|
+
"Images (png/jpg/gif/webp): view with the native `read` tool on this path.",
|
|
118
|
+
].join("\n"),
|
|
119
|
+
);
|
|
120
|
+
} catch (err) {
|
|
121
|
+
return toToolResult(errorText(err));
|
|
122
|
+
}
|
|
123
|
+
},
|
|
124
|
+
};
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { Type, type Static } from "typebox";
|
|
2
|
+
import type {
|
|
3
|
+
AgentToolResult,
|
|
4
|
+
ToolDefinition,
|
|
5
|
+
} from "@earendil-works/pi-coding-agent";
|
|
6
|
+
import { zdGet } from "../api";
|
|
7
|
+
import { toToolResult, errorText, type ZendeskDetails } from "../result";
|
|
8
|
+
import { buildSideLoadMaps, formatComment } from "../format";
|
|
9
|
+
import type { ZdCommentsResponse } from "../types";
|
|
10
|
+
import { parseTicketRef, TICKET_REF_EXAMPLE } from "../url";
|
|
11
|
+
import {
|
|
12
|
+
GET_COMMENTS_DESCRIPTION,
|
|
13
|
+
GET_COMMENTS_LIMIT_DESCRIPTION,
|
|
14
|
+
GET_COMMENTS_PARAM,
|
|
15
|
+
GET_COMMENTS_PUBLIC_ONLY_DESCRIPTION,
|
|
16
|
+
GET_COMMENTS_TITLE,
|
|
17
|
+
} from "../prompts";
|
|
18
|
+
|
|
19
|
+
const Params = Type.Object({
|
|
20
|
+
ticket: Type.String({ description: GET_COMMENTS_PARAM }),
|
|
21
|
+
limit: Type.Optional(
|
|
22
|
+
Type.Number({
|
|
23
|
+
description: GET_COMMENTS_LIMIT_DESCRIPTION,
|
|
24
|
+
minimum: 1,
|
|
25
|
+
maximum: 100,
|
|
26
|
+
}),
|
|
27
|
+
),
|
|
28
|
+
public_only: Type.Optional(
|
|
29
|
+
Type.Boolean({
|
|
30
|
+
description: GET_COMMENTS_PUBLIC_ONLY_DESCRIPTION,
|
|
31
|
+
}),
|
|
32
|
+
),
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
export const getCommentsTool: ToolDefinition<
|
|
36
|
+
typeof Params,
|
|
37
|
+
ZendeskDetails
|
|
38
|
+
> = {
|
|
39
|
+
name: "zendesk_get_comments",
|
|
40
|
+
label: GET_COMMENTS_TITLE,
|
|
41
|
+
description: GET_COMMENTS_DESCRIPTION,
|
|
42
|
+
parameters: Params,
|
|
43
|
+
async execute(
|
|
44
|
+
_toolCallId: string,
|
|
45
|
+
params: Static<typeof Params>,
|
|
46
|
+
): Promise<AgentToolResult<ZendeskDetails>> {
|
|
47
|
+
const id = parseTicketRef(params.ticket);
|
|
48
|
+
if (id === null) {
|
|
49
|
+
return toToolResult(
|
|
50
|
+
`Invalid ticket reference: ${JSON.stringify(params.ticket)}. ` +
|
|
51
|
+
`Pass ${TICKET_REF_EXAMPLE}.`,
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
try {
|
|
56
|
+
const resp = await zdGet<ZdCommentsResponse>(
|
|
57
|
+
`tickets/${id}/comments.json`,
|
|
58
|
+
{ query: { include: "users" } },
|
|
59
|
+
);
|
|
60
|
+
|
|
61
|
+
const all = resp.comments ?? [];
|
|
62
|
+
const filtered = params.public_only
|
|
63
|
+
? all.filter((c) => c.public)
|
|
64
|
+
: all;
|
|
65
|
+
const limit = params.limit ?? 20;
|
|
66
|
+
|
|
67
|
+
// Zendesk returns the thread oldest-first. Agents care most about the
|
|
68
|
+
// latest state, so render the tail and count what was cut.
|
|
69
|
+
const shown = filtered.slice(-limit);
|
|
70
|
+
const hidden = filtered.length - shown.length;
|
|
71
|
+
|
|
72
|
+
const maps = buildSideLoadMaps(resp.users, resp.organizations);
|
|
73
|
+
const header = `Ticket #${id}: ${filtered.length} entr${
|
|
74
|
+
filtered.length === 1 ? "y" : "ies"
|
|
75
|
+
}${params.public_only ? " (public replies only)" : ""}` +
|
|
76
|
+
(hidden > 0
|
|
77
|
+
? ` - showing ${shown.length} most recent, ${hidden} oldest hidden (raise limit to see them)`
|
|
78
|
+
: "");
|
|
79
|
+
|
|
80
|
+
const body = shown.map((c) => formatComment(c, maps)).join("\n\n");
|
|
81
|
+
return toToolResult(
|
|
82
|
+
[header, shown.length ? "" : "(no entries)", body]
|
|
83
|
+
.filter((s) => s !== undefined)
|
|
84
|
+
.join("\n"),
|
|
85
|
+
);
|
|
86
|
+
} catch (err) {
|
|
87
|
+
return toToolResult(errorText(err));
|
|
88
|
+
}
|
|
89
|
+
},
|
|
90
|
+
};
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { Type, type Static } from "typebox";
|
|
2
|
+
import type {
|
|
3
|
+
AgentToolResult,
|
|
4
|
+
ToolDefinition,
|
|
5
|
+
} from "@earendil-works/pi-coding-agent";
|
|
6
|
+
import { zdGet } from "../api";
|
|
7
|
+
import { toToolResult, errorText, type ZendeskDetails } from "../result";
|
|
8
|
+
import { formatDate } from "../format";
|
|
9
|
+
import type { ZdOrgResponse } from "../types";
|
|
10
|
+
import {
|
|
11
|
+
GET_ORG_DESCRIPTION,
|
|
12
|
+
GET_ORG_PARAM,
|
|
13
|
+
GET_ORG_TITLE,
|
|
14
|
+
} from "../prompts";
|
|
15
|
+
|
|
16
|
+
const Params = Type.Object({
|
|
17
|
+
organization: Type.Number({ description: GET_ORG_PARAM }),
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
export const getOrganizationTool: ToolDefinition<
|
|
21
|
+
typeof Params,
|
|
22
|
+
ZendeskDetails
|
|
23
|
+
> = {
|
|
24
|
+
name: "zendesk_get_organization",
|
|
25
|
+
label: GET_ORG_TITLE,
|
|
26
|
+
description: GET_ORG_DESCRIPTION,
|
|
27
|
+
parameters: Params,
|
|
28
|
+
async execute(
|
|
29
|
+
_toolCallId: string,
|
|
30
|
+
params: Static<typeof Params>,
|
|
31
|
+
): Promise<AgentToolResult<ZendeskDetails>> {
|
|
32
|
+
try {
|
|
33
|
+
const resp = await zdGet<ZdOrgResponse>(
|
|
34
|
+
`organizations/${params.organization}.json`,
|
|
35
|
+
);
|
|
36
|
+
const o = resp.organization;
|
|
37
|
+
const lines = [
|
|
38
|
+
`Organization #${o.id} - ${o.name}`,
|
|
39
|
+
"",
|
|
40
|
+
`Domains: ${o.domain_names?.length ? o.domain_names.join(", ") : "none"}`,
|
|
41
|
+
`Created: ${formatDate(o.created_at)}`,
|
|
42
|
+
`Updated: ${formatDate(o.updated_at)}`,
|
|
43
|
+
];
|
|
44
|
+
if (o.details) lines.push("", `Details: ${o.details}`);
|
|
45
|
+
if (o.notes) lines.push("", `Notes: ${o.notes}`);
|
|
46
|
+
if (o.tags?.length) lines.push("", `Tags: ${o.tags.join(", ")}`);
|
|
47
|
+
return toToolResult(lines.join("\n"));
|
|
48
|
+
} catch (err) {
|
|
49
|
+
return toToolResult(errorText(err));
|
|
50
|
+
}
|
|
51
|
+
},
|
|
52
|
+
};
|