@estebanforge/pi-zendesk-me 1.0.0 → 1.0.2

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/CHANGELOG.md ADDED
@@ -0,0 +1,28 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [1.0.2] - 2026-11-15
9
+
10
+ ### Changed
11
+ - Raised the `@earendil-works/pi-coding-agent` peer dependency floor from `*` to `^1.0.0` (pi 1.0.0 stable contract). No code changes.
12
+
13
+ ### Fixed
14
+ - README link now points at the correct pi repository URL.
15
+
16
+ ## [1.0.0] - 2026-08-28
17
+
18
+ ### Added
19
+
20
+ - `zendesk_get_ticket`: fetch one ticket by numeric id or a full `/agent/tickets/N` URL, with requester, assignee, and organization resolved via side-loading.
21
+ - `zendesk_get_comments`: read the full comment thread (public replies and internal notes flagged), authors resolved via side-loading.
22
+ - `zendesk_search`: search tickets with the Zendesk search API; `type:ticket` prepended unless the query already targets other types.
23
+ - `zendesk_get_user` / `zendesk_get_organization`: look up a requester, assignee, or organization by id.
24
+ - `zendesk_download_attachment`: save a ticket attachment to an OS temp file for viewing; images render through the native pi `read` tool. Attachment content URLs are pre-signed and downloaded without an auth header.
25
+ - `zendesk_get_view`: list the tickets in a saved view (filter) by id or `/agent/filters/{id}` URL, with requester and assignee resolved. Requires the `ticket_views:read` scope.
26
+ - OAuth client-credentials auth (`ZENDESK_SUBDOMAIN`, `ZENDESK_CLIENT_ID`, `ZENDESK_CLIENT_SECRET`) with in-memory token caching; ready ahead of Zendesk's API-token deprecation (all API tokens stop working 2027-04-30). Requested scopes: `tickets:read users:read organizations:read ticket_views:read`.
27
+ - `/zendesk` command: bare status plus `ticket`, `comments`, `search`, `view`, `user`, and `org` prefills.
28
+ - Tool guidance injected into the system prompt: URL parsing, HTML-escaping rule for comment bodies, attachment download flow, scope hints, rate-limit notes.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @estebanforge/pi-zendesk-me
2
2
 
3
- Zendesk Support read tools for [pi](https://github.com/earendil-works/pi-coding-agent) that act on **your** Zendesk tenant.
3
+ Zendesk Support read tools for [pi](https://github.com/earendil-works/pi) that act on **your** Zendesk tenant.
4
4
 
5
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
6
 
@@ -58,7 +58,7 @@ export ZENDESK_CLIENT_SECRET="..."
58
58
  ### 3. Install
59
59
 
60
60
  ```bash
61
- pi install @estebanforge/pi-zendesk-me
61
+ pi install npm:@estebanforge/pi-zendesk-me
62
62
  ```
63
63
 
64
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.
@@ -86,10 +86,9 @@ No browser approval step, no user account to pick. The client-credentials token
86
86
  ## Development
87
87
 
88
88
  ```bash
89
+ # from the monorepo root
89
90
  npm install
90
- npm run typecheck # tsc --noEmit
91
- npm test # vitest run
92
- npm run test:watch
91
+ npm run check # tsc --noEmit, then vitest run
93
92
  ```
94
93
 
95
94
  ## License
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@estebanforge/pi-zendesk-me",
3
- "version": "1.0.0",
3
+ "version": "1.0.2",
4
4
  "description": "Zendesk Support read tools for Pi. Adds 7 LLM-callable tools (zendesk_*) that query the Zendesk Support API v2 over HTTPS: fetch a ticket (by id or agent URL), read the comment thread, search tickets, look up users and organizations, download attachments for viewing, and list tickets in a saved view (filter). OAuth client-credentials auth via ZENDESK_SUBDOMAIN / ZENDESK_CLIENT_ID / ZENDESK_CLIENT_SECRET - no API tokens (deprecated by Zendesk), no MCP server install.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -19,24 +19,19 @@
19
19
  },
20
20
  "repository": {
21
21
  "type": "git",
22
- "url": "git+https://github.com/EstebanForge/pi-zendesk-me.git"
22
+ "url": "git+https://github.com/EstebanForge/pi-extensions.git",
23
+ "directory": "packages/pi-zendesk-me"
23
24
  },
24
25
  "publishConfig": {
25
26
  "access": "public"
26
27
  },
27
28
  "type": "module",
28
- "scripts": {
29
- "test": "vitest run",
30
- "test:watch": "vitest",
31
- "typecheck": "tsc --noEmit",
32
- "prepublishOnly": "npm run typecheck && npm test"
33
- },
34
29
  "files": [
35
30
  "extensions",
36
31
  "lib",
37
- "tests",
38
- "vitest.config.ts",
39
- "README.md"
32
+ "README.md",
33
+ "CHANGELOG.md",
34
+ "LICENSE"
40
35
  ],
41
36
  "pi": {
42
37
  "extensions": [
@@ -44,7 +39,7 @@
44
39
  ]
45
40
  },
46
41
  "peerDependencies": {
47
- "@earendil-works/pi-coding-agent": "*",
42
+ "@earendil-works/pi-coding-agent": "^1.0.0",
48
43
  "typebox": "*"
49
44
  },
50
45
  "peerDependenciesMeta": {
@@ -54,12 +49,5 @@
54
49
  "typebox": {
55
50
  "optional": true
56
51
  }
57
- },
58
- "devDependencies": {
59
- "@earendil-works/pi-coding-agent": "^0.84.0",
60
- "@types/node": "^22.0.0",
61
- "typebox": "^1.3.4",
62
- "typescript": "^5.8.0",
63
- "vitest": "^4.1.7"
64
52
  }
65
53
  }
package/tests/_helpers.ts DELETED
@@ -1,72 +0,0 @@
1
- import { vi } from "vitest";
2
- import type { AgentToolResult } from "@earendil-works/pi-coding-agent";
3
-
4
- // ToolDefinition.execute has a 5-arg signature (toolCallId, params, signal,
5
- // onUpdate, ctx) per @earendil-works/pi-coding-agent. Our tools only consume
6
- // the first two; the other three are required by the type but ignored at
7
- // runtime. This helper lets tests pass 2 args while satisfying the 5-arg
8
- // contract, same as pi-slack-me's tests/_helpers.ts. `any` matches what pi's
9
- // runtime does.
10
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
11
- type AnyExecute = (...args: any[]) => Promise<AgentToolResult<unknown>>;
12
-
13
- export function invoke<P>(
14
- tool: { execute: AnyExecute },
15
- params: P,
16
- ): Promise<AgentToolResult<unknown>> {
17
- const fn = tool.execute as unknown as (
18
- a: string,
19
- b: P,
20
- ) => Promise<AgentToolResult<unknown>>;
21
- return fn("call-id", params);
22
- }
23
-
24
- // First text block of a tool result, typed for assertions.
25
- export function firstText(result: AgentToolResult<unknown>): string {
26
- const block = result.content[0] as { type: string; text: string };
27
- return block.text;
28
- }
29
-
30
- // Set the three required env vars. Auth reads env at call time, so stubEnv is
31
- // enough; tests that need missing vars override with empty strings.
32
- export function stubZendeskEnv(): void {
33
- vi.stubEnv("ZENDESK_SUBDOMAIN", "{subdomain}");
34
- vi.stubEnv("ZENDESK_CLIENT_ID", "test-client-id");
35
- vi.stubEnv("ZENDESK_CLIENT_SECRET", "test-client-secret");
36
- }
37
-
38
- export function jsonResponse(
39
- body: unknown,
40
- status = 200,
41
- headers?: Record<string, string>,
42
- ): Response {
43
- return new Response(JSON.stringify(body), {
44
- status,
45
- headers: { "Content-Type": "application/json", ...headers },
46
- });
47
- }
48
-
49
- // Replace global fetch with a vi.fn dispatching through `handler`. The mock
50
- // receives (url: string, init?: RequestInit) and may be async.
51
- export function fetchMock(
52
- handler: (url: string, init?: RequestInit) => Response | Promise<Response>,
53
- ): ReturnType<typeof vi.fn> {
54
- const mock = vi.fn(async (url: unknown, init?: unknown) =>
55
- handler(String(url), init as RequestInit | undefined),
56
- );
57
- vi.stubGlobal("fetch", mock as unknown as typeof fetch);
58
- return mock;
59
- }
60
-
61
- // Standard OAuth token endpoint success response. Most api/tool tests need a
62
- // token before the request under test fires.
63
- export const TOKEN_OK = {
64
- access_token: "test-access-token",
65
- token_type: "bearer",
66
- scope: "tickets:read users:read organizations:read",
67
- expires_in: 1800,
68
- };
69
-
70
- export function isTokenRequest(url: string): boolean {
71
- return url === "https://{subdomain}.zendesk.com/oauth/tokens";
72
- }
package/tests/api.test.ts DELETED
@@ -1,143 +0,0 @@
1
- import { beforeEach, describe, expect, it, vi } from "vitest";
2
- import { ZendeskApiError, zdGet } from "../lib/api";
3
- import { _resetAuthCache } from "../lib/auth";
4
- import {
5
- TOKEN_OK,
6
- fetchMock,
7
- isTokenRequest,
8
- jsonResponse,
9
- stubZendeskEnv,
10
- } from "./_helpers";
11
-
12
- beforeEach(() => {
13
- vi.unstubAllEnvs();
14
- _resetAuthCache();
15
- stubZendeskEnv();
16
- });
17
-
18
- // Route token requests to a canned token; tests match API paths separately.
19
- function route(handler: (url: string) => Response | Promise<Response>) {
20
- return fetchMock(async (url) => {
21
- if (isTokenRequest(url)) return jsonResponse(TOKEN_OK);
22
- return handler(url);
23
- });
24
- }
25
-
26
- describe("zdGet", () => {
27
- it("sends a Bearer header to the right API v2 URL", async () => {
28
- const mock = route((url) =>
29
- url.includes("/api/v2/tickets/7942.json")
30
- ? jsonResponse({ ticket: { id: 7942 } })
31
- : jsonResponse({}, 404),
32
- );
33
-
34
- const resp = await zdGet<{ ticket: { id: number } }>(
35
- "tickets/7942.json",
36
- { query: { include: "users,organizations" } },
37
- );
38
-
39
- expect(resp.ticket.id).toBe(7942);
40
- const [url, init] = mock.mock.calls.find(
41
- (c) => !isTokenRequest(String(c[0])),
42
- ) as unknown as [string, RequestInit];
43
- expect(url).toContain("https://{subdomain}.zendesk.com/api/v2/tickets/7942.json");
44
- expect(url).toContain("include=");
45
- expect((init.headers as Record<string, string>).Authorization).toBe(
46
- "Bearer test-access-token",
47
- );
48
- });
49
-
50
- it("re-tokens once on 401 invalid_token and retries", async () => {
51
- let apiCalls = 0;
52
- const mock = fetchMock((url) => {
53
- if (isTokenRequest(url)) return jsonResponse(TOKEN_OK);
54
- apiCalls += 1;
55
- if (apiCalls === 1) {
56
- return jsonResponse(
57
- { error: "invalid_token", description: "expired" },
58
- 401,
59
- );
60
- }
61
- return jsonResponse({ ticket: { id: 7942 } });
62
- });
63
-
64
- const resp = await zdGet<{ ticket: { id: number } }>("tickets/7942.json");
65
-
66
- expect(resp.ticket.id).toBe(7942);
67
- // 2 token requests (initial + refresh) + 2 API calls (401 + retry).
68
- expect(mock).toHaveBeenCalledTimes(4);
69
- expect(apiCalls).toBe(2);
70
- });
71
-
72
- it("fails after invalid_token persists across the retry", async () => {
73
- fetchMock((url) =>
74
- isTokenRequest(url)
75
- ? jsonResponse(TOKEN_OK)
76
- : jsonResponse({ error: "invalid_token" }, 401),
77
- );
78
-
79
- await expect(zdGet("tickets/7942.json")).rejects.toThrow(
80
- /unauthorized even after refreshing/,
81
- );
82
- });
83
-
84
- it("fails fast on a non-invalid_token 401 without retrying", async () => {
85
- const mock = fetchMock((url) =>
86
- isTokenRequest(url)
87
- ? jsonResponse(TOKEN_OK)
88
- : jsonResponse({ error: "invalid_client" }, 401),
89
- );
90
-
91
- await expect(zdGet("tickets/7942.json")).rejects.toThrow(
92
- /unauthorized \(HTTP 401\)\. Check the OAuth/,
93
- );
94
- // No retry: one token request, one API call.
95
- expect(mock).toHaveBeenCalledTimes(2);
96
- });
97
-
98
- it("surfaces 429 with the Retry-After hint", async () => {
99
- route(() => jsonResponse({}, 429, { "Retry-After": "7" }));
100
-
101
- const err = await zdGet("tickets.json").catch((e) => e);
102
- expect(err).toBeInstanceOf(ZendeskApiError);
103
- expect((err as ZendeskApiError).isRateLimited).toBe(true);
104
- expect((err as ZendeskApiError).retryAfter).toBe(7);
105
- expect((err as ZendeskApiError).message).toContain("Retry in ~7s");
106
- });
107
-
108
- it("maps 403 to the scope-ceiling hint", async () => {
109
- route(() => jsonResponse({ error: "Forbidden" }, 403));
110
-
111
- const err = await zdGet("tickets.json").catch((e) => e);
112
- expect((err as ZendeskApiError).status).toBe(403);
113
- expect((err as ZendeskApiError).message).toMatch(/Allowed scopes/);
114
- });
115
-
116
- it("maps 404 to not-found with Zendesk's description", async () => {
117
- route(() =>
118
- jsonResponse(
119
- { error: "RecordNotFound", description: "Ticket 1 not found" },
120
- 404,
121
- ),
122
- );
123
-
124
- const err = await zdGet("tickets/1.json").catch((e) => e);
125
- expect((err as ZendeskApiError).status).toBe(404);
126
- expect((err as ZendeskApiError).message).toContain("Ticket 1 not found");
127
- });
128
-
129
- it("maps 5xx to a retryable server error", async () => {
130
- route(() => new Response("oops", { status: 502 }));
131
-
132
- const err = await zdGet("tickets.json").catch((e) => e);
133
- expect((err as ZendeskApiError).status).toBe(502);
134
- expect((err as ZendeskApiError).message).toMatch(/server error/);
135
- });
136
-
137
- it("rejects non-JSON success bodies", async () => {
138
- route(() => new Response("<html>hi</html>", { status: 200 }));
139
-
140
- const err = await zdGet("tickets.json").catch((e) => e);
141
- expect((err as ZendeskApiError).message).toMatch(/non-JSON/);
142
- });
143
- });
@@ -1,124 +0,0 @@
1
- import { beforeEach, describe, expect, it, vi } from "vitest";
2
- import {
3
- ZendeskAuthError,
4
- _resetAuthCache,
5
- getZendeskAccessToken,
6
- getZendeskCredentials,
7
- requestZendeskAccessToken,
8
- } from "../lib/auth";
9
- import {
10
- TOKEN_OK,
11
- fetchMock,
12
- isTokenRequest,
13
- jsonResponse,
14
- stubZendeskEnv,
15
- } from "./_helpers";
16
-
17
- beforeEach(() => {
18
- vi.unstubAllEnvs();
19
- _resetAuthCache();
20
- stubZendeskEnv();
21
- });
22
-
23
- describe("getZendeskCredentials", () => {
24
- it("returns the three credentials when set", () => {
25
- const creds = getZendeskCredentials();
26
- expect(creds).toEqual({
27
- subdomain: "{subdomain}",
28
- clientId: "test-client-id",
29
- clientSecret: "test-client-secret",
30
- });
31
- });
32
-
33
- it("throws a rich error listing every missing var", () => {
34
- vi.stubEnv("ZENDESK_SUBDOMAIN", "");
35
- vi.stubEnv("ZENDESK_CLIENT_SECRET", "");
36
- expect(() => getZendeskCredentials()).toThrow(ZendeskAuthError);
37
- expect(() => getZendeskCredentials()).toThrow(
38
- /ZENDESK_SUBDOMAIN, ZENDESK_CLIENT_SECRET/,
39
- );
40
- });
41
-
42
- it("the missing-env error mentions the deprecation deadline", () => {
43
- vi.stubEnv("ZENDESK_CLIENT_ID", "");
44
- expect(() => getZendeskCredentials()).toThrow(/2027-04-30/);
45
- });
46
- });
47
-
48
- describe("requestZendeskAccessToken", () => {
49
- it("POSTs client_credentials to the tenant token endpoint", async () => {
50
- const mock = fetchMock((url) =>
51
- isTokenRequest(url) ? jsonResponse(TOKEN_OK) : jsonResponse({}, 404),
52
- );
53
-
54
- const token = await requestZendeskAccessToken();
55
-
56
- expect(token).toBe("test-access-token");
57
- expect(mock).toHaveBeenCalledTimes(1);
58
- const [url, init] = mock.mock.calls[0] as [string, RequestInit];
59
- expect(url).toBe("https://{subdomain}.zendesk.com/oauth/tokens");
60
- expect(init.method).toBe("POST");
61
- expect(init.headers).toMatchObject({
62
- "Content-Type": "application/x-www-form-urlencoded",
63
- });
64
- const body = String(init.body);
65
- expect(body).toContain("grant_type=client_credentials");
66
- expect(body).toContain("client_id=test-client-id");
67
- expect(body).toContain("client_secret=test-client-secret");
68
- expect(body).toContain("scope=tickets%3Aread+users%3Aread+organizations%3Aread");
69
- });
70
-
71
- it("surfaces Zendesk's OAuth error code (invalid_scope)", async () => {
72
- fetchMock(() =>
73
- jsonResponse(
74
- {
75
- error: "invalid_scope",
76
- error_description: "The requested scope is invalid.",
77
- },
78
- 400,
79
- ),
80
- );
81
-
82
- await expect(requestZendeskAccessToken()).rejects.toThrow(
83
- /Allowed scopes.*invalid_scope/s,
84
- );
85
- });
86
-
87
- it("surfaces a non-JSON failure with the HTTP status", async () => {
88
- fetchMock(() => new Response("gateway timeout", { status: 504 }));
89
- await expect(requestZendeskAccessToken()).rejects.toThrow(/HTTP 504/);
90
- });
91
-
92
- it("rejects a 200 body without access_token", async () => {
93
- fetchMock(() => jsonResponse({ token_type: "bearer" }));
94
- await expect(requestZendeskAccessToken()).rejects.toThrow(
95
- /token request failed/,
96
- );
97
- });
98
- });
99
-
100
- describe("getZendeskAccessToken cache", () => {
101
- it("requests once and serves the second call from cache", async () => {
102
- const mock = fetchMock((url) =>
103
- isTokenRequest(url) ? jsonResponse(TOKEN_OK) : jsonResponse({}, 404),
104
- );
105
-
106
- await getZendeskAccessToken();
107
- await getZendeskAccessToken();
108
-
109
- expect(mock).toHaveBeenCalledTimes(1);
110
- });
111
-
112
- it("re-requests after resetTokenCache", async () => {
113
- const mock = fetchMock((url) =>
114
- isTokenRequest(url) ? jsonResponse(TOKEN_OK) : jsonResponse({}, 404),
115
- );
116
-
117
- await getZendeskAccessToken();
118
- const { resetTokenCache } = await import("../lib/auth");
119
- resetTokenCache();
120
- await getZendeskAccessToken();
121
-
122
- expect(mock).toHaveBeenCalledTimes(2);
123
- });
124
- });
@@ -1,135 +0,0 @@
1
- import { readFile, rm } from "node:fs/promises";
2
- import { tmpdir } from "node:os";
3
- import path from "node:path";
4
- import { beforeEach, describe, expect, it, vi } from "vitest";
5
- import { _resetAuthCache } from "../lib/auth";
6
- import { downloadAttachmentTool } from "../lib/tools/download-attachment";
7
- import {
8
- TOKEN_OK,
9
- fetchMock,
10
- firstText,
11
- invoke,
12
- isTokenRequest,
13
- jsonResponse,
14
- stubZendeskEnv,
15
- } from "./_helpers";
16
-
17
- beforeEach(() => {
18
- vi.unstubAllEnvs();
19
- vi.unstubAllGlobals();
20
- _resetAuthCache();
21
- stubZendeskEnv();
22
- });
23
-
24
- const COMMENTS = {
25
- comments: [
26
- {
27
- id: 1,
28
- body: "<p>see screenshot</p>",
29
- public: true,
30
- author_id: 1042,
31
- created_at: "2026-08-27T14:45:00Z",
32
- attachments: [
33
- {
34
- id: 43038971788439,
35
- file_name: "Screenshot 2026-08-27.png",
36
- content_url: "https://storage.example/signed/abc",
37
- content_type: "image/png",
38
- size: 8,
39
- },
40
- ],
41
- },
42
- ],
43
- };
44
-
45
- const PNG_BYTES = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
46
-
47
- function routeWithStorage(body: Uint8Array) {
48
- return fetchMock((url, init) => {
49
- if (isTokenRequest(url)) return jsonResponse(TOKEN_OK);
50
- if (url.includes("/api/v2/tickets/7942/comments.json")) {
51
- return jsonResponse(COMMENTS);
52
- }
53
- if (url.startsWith("https://storage.example/")) {
54
- // The signed-URL download must NOT carry the bearer token (it breaks
55
- // the storage signature).
56
- const hasAuth = Boolean(
57
- (init?.headers as Record<string, string> | undefined)?.Authorization,
58
- );
59
- if (hasAuth) return new Response("forbidden", { status: 403 });
60
- return new Response(body as unknown as BodyInit, {
61
- status: 200,
62
- headers: { "Content-Type": "image/png" },
63
- });
64
- }
65
- return jsonResponse({}, 404);
66
- });
67
- }
68
-
69
- describe("zendesk_download_attachment", () => {
70
- it("downloads by attachment id and writes to the temp dir", async () => {
71
- routeWithStorage(PNG_BYTES);
72
-
73
- const result = await invoke(downloadAttachmentTool, {
74
- ticket: "7942",
75
- attachment: 43038971788439,
76
- });
77
- const text = firstText(result);
78
-
79
- expect(text).toContain("Downloaded: ");
80
- expect(text).toContain("image/png");
81
- expect(text).toContain("from comment #1");
82
- expect(text).toContain("`read` tool");
83
-
84
- const filePath = text.split("Downloaded: ")[1]!.split("\n")[0]!;
85
- expect(filePath.startsWith(path.join(tmpdir(), "pi-zendesk-me"))).toBe(
86
- true,
87
- );
88
- expect(path.basename(filePath)).toContain("Screenshot_2026-08-27.png");
89
- const written = await readFile(filePath);
90
- expect([...written]).toEqual([...PNG_BYTES]);
91
-
92
- await rm(path.join(tmpdir(), "pi-zendesk-me"), {
93
- recursive: true,
94
- force: true,
95
- });
96
- });
97
-
98
- it("rejects an unparseable ticket reference", async () => {
99
- const result = await invoke(downloadAttachmentTool, {
100
- ticket: "junk",
101
- attachment: 1,
102
- });
103
- expect(firstText(result)).toContain("Invalid ticket reference");
104
- });
105
-
106
- it("lists available attachment ids when the id is not found", async () => {
107
- routeWithStorage(PNG_BYTES);
108
-
109
- const result = await invoke(downloadAttachmentTool, {
110
- ticket: "7942",
111
- attachment: 42,
112
- });
113
- const text = firstText(result);
114
-
115
- expect(text).toContain("Attachment 42 not found on ticket 7942");
116
- expect(text).toContain("#43038971788439 Screenshot 2026-08-27.png");
117
- });
118
-
119
- it("surfaces storage download failures through the error formatter", async () => {
120
- fetchMock((url) => {
121
- if (isTokenRequest(url)) return jsonResponse(TOKEN_OK);
122
- if (url.includes("/api/v2/tickets/7942/comments.json")) {
123
- return jsonResponse(COMMENTS);
124
- }
125
- return new Response("gone", { status: 410 });
126
- });
127
-
128
- const result = await invoke(downloadAttachmentTool, {
129
- ticket: "https://{subdomain}.zendesk.com/agent/tickets/7942",
130
- attachment: 43038971788439,
131
- });
132
- expect(firstText(result)).toContain("Zendesk error:");
133
- expect(firstText(result)).toContain("HTTP 410");
134
- });
135
- });
@@ -1,122 +0,0 @@
1
- import { beforeEach, describe, expect, it, vi } from "vitest";
2
- import { _resetAuthCache } from "../lib/auth";
3
- import { getCommentsTool } from "../lib/tools/get-comments";
4
- import {
5
- TOKEN_OK,
6
- fetchMock,
7
- firstText,
8
- invoke,
9
- isTokenRequest,
10
- jsonResponse,
11
- stubZendeskEnv,
12
- } from "./_helpers";
13
-
14
- beforeEach(() => {
15
- vi.unstubAllEnvs();
16
- _resetAuthCache();
17
- stubZendeskEnv();
18
- });
19
-
20
- function route(handler: (url: string) => Response | Promise<Response>) {
21
- return fetchMock(async (url) => {
22
- if (isTokenRequest(url)) return jsonResponse(TOKEN_OK);
23
- return handler(url);
24
- });
25
- }
26
-
27
- const COMMENTS_RESPONSE = {
28
- comments: [
29
- {
30
- id: 1,
31
- body: "<p>I cannot log in at all.</p>",
32
- public: true,
33
- author_id: 1042,
34
- created_at: "2026-08-14T09:30:00Z",
35
- },
36
- {
37
- id: 2,
38
- body: "<p>Internal: user is on an old plan, check entitlements.</p>",
39
- public: false,
40
- author_id: 2099,
41
- created_at: "2026-08-14T10:00:00Z",
42
- },
43
- {
44
- id: 3,
45
- body: "<p>We pushed a fix, please retry.</p>",
46
- public: true,
47
- author_id: 2099,
48
- created_at: "2026-08-15T11:00:00Z",
49
- attachments: [
50
- { id: 900, file_name: "fix-notes.pdf", size: 2048 },
51
- ],
52
- },
53
- ],
54
- users: [
55
- { id: 1042, name: "Ada Lovelace", active: true, role: "end-user" },
56
- { id: 2099, name: "Grace Agent", active: true, role: "agent" },
57
- ],
58
- };
59
-
60
- describe("zendesk_get_comments", () => {
61
- it("renders the thread oldest-first with visibility flags", async () => {
62
- route((url) =>
63
- url.includes("/api/v2/tickets/7942/comments.json")
64
- ? jsonResponse(COMMENTS_RESPONSE)
65
- : jsonResponse({}, 404),
66
- );
67
-
68
- const result = await invoke(getCommentsTool, { ticket: "7942" });
69
- const text = firstText(result);
70
-
71
- expect(text).toContain("Ticket #7942: 3 entries");
72
- expect(text).toContain("Ada Lovelace - public reply");
73
- expect(text).toContain("Grace Agent - INTERNAL NOTE");
74
- expect(text).toContain("I cannot log in at all.");
75
- expect(text).toContain("attachment: #900 fix-notes.pdf (2048 bytes)");
76
- expect(text).not.toContain("<p>");
77
- // Newest last: the fix reply appears after the internal note.
78
- expect(text.indexOf("Internal: user is on an old plan")).toBeLessThan(
79
- text.indexOf("We pushed a fix"),
80
- );
81
- });
82
-
83
- it("limits rendering to the N most recent and counts the hidden tail", async () => {
84
- route((url) =>
85
- url.includes("/api/v2/tickets/7942/comments.json")
86
- ? jsonResponse(COMMENTS_RESPONSE)
87
- : jsonResponse({}, 404),
88
- );
89
-
90
- const result = await invoke(getCommentsTool, {
91
- ticket: "7942",
92
- limit: 1,
93
- });
94
- const text = firstText(result);
95
-
96
- expect(text).toContain("showing 1 most recent, 2 oldest hidden");
97
- expect(text).toContain("We pushed a fix");
98
- expect(text).not.toContain("I cannot log in at all.");
99
- });
100
-
101
- it("public_only drops internal notes", async () => {
102
- route((url) =>
103
- url.includes("/api/v2/tickets/7942/comments.json")
104
- ? jsonResponse(COMMENTS_RESPONSE)
105
- : jsonResponse({}, 404),
106
- );
107
-
108
- const result = await invoke(getCommentsTool, {
109
- ticket: "7942",
110
- public_only: true,
111
- });
112
- const text = firstText(result);
113
-
114
- expect(text).toContain("2 entries (public replies only)");
115
- expect(text).not.toContain("INTERNAL NOTE");
116
- });
117
-
118
- it("rejects an unparseable ticket reference", async () => {
119
- const result = await invoke(getCommentsTool, { ticket: "nope" });
120
- expect(firstText(result)).toContain("Invalid ticket reference");
121
- });
122
- });
@@ -1,120 +0,0 @@
1
- import { beforeEach, describe, expect, it, vi } from "vitest";
2
- import { _resetAuthCache } from "../lib/auth";
3
- import { getTicketTool } from "../lib/tools/get-ticket";
4
- import {
5
- TOKEN_OK,
6
- fetchMock,
7
- firstText,
8
- invoke,
9
- isTokenRequest,
10
- jsonResponse,
11
- stubZendeskEnv,
12
- } from "./_helpers";
13
-
14
- beforeEach(() => {
15
- vi.unstubAllEnvs();
16
- _resetAuthCache();
17
- stubZendeskEnv();
18
- });
19
-
20
- function route(handler: (url: string) => Response | Promise<Response>) {
21
- return fetchMock(async (url) => {
22
- if (isTokenRequest(url)) return jsonResponse(TOKEN_OK);
23
- return handler(url);
24
- });
25
- }
26
-
27
- const TICKET_RESPONSE = {
28
- ticket: {
29
- id: 7942,
30
- subject: "Cannot login to portal",
31
- description: "<p>Password reset emails <b>never arrive</b>.</p>",
32
- status: "open",
33
- priority: "high",
34
- type: "incident",
35
- requester_id: 1042,
36
- submitter_id: 1042,
37
- assignee_id: 2099,
38
- organization_id: 77,
39
- group_id: 1,
40
- tags: ["login", "email"],
41
- created_at: "2026-08-14T09:30:00Z",
42
- updated_at: "2026-08-15T11:00:00Z",
43
- },
44
- users: [
45
- {
46
- id: 1042,
47
- name: "Ada Lovelace",
48
- email: "ada@example.com",
49
- active: true,
50
- role: "end-user",
51
- },
52
- {
53
- id: 2099,
54
- name: "Grace Agent",
55
- active: true,
56
- role: "agent",
57
- },
58
- ],
59
- organizations: [
60
- { id: 77, name: "Analytical Engines Ltd", active: true },
61
- ],
62
- };
63
-
64
- describe("zendesk_get_ticket", () => {
65
- it("rejects an unparseable ticket reference", async () => {
66
- const result = await invoke(getTicketTool, { ticket: "banana" });
67
- expect(firstText(result)).toContain("Invalid ticket reference");
68
- });
69
-
70
- it("fetches by bare id and renders people from side-loads", async () => {
71
- const mock = route((url) =>
72
- url.includes("/api/v2/tickets/7942.json")
73
- ? jsonResponse(TICKET_RESPONSE)
74
- : jsonResponse({}, 404),
75
- );
76
-
77
- const result = await invoke(getTicketTool, { ticket: "7942" });
78
- const text = firstText(result);
79
-
80
- expect(text).toContain("Ticket #7942 - [open] Cannot login to portal");
81
- expect(text).toContain("Requester: Ada Lovelace <ada@example.com>");
82
- expect(text).toContain("Assignee: Grace Agent");
83
- expect(text).toContain("Organization: Analytical Engines Ltd");
84
- expect(text).toContain("Priority: high");
85
- expect(text).toContain("Tags: login, email");
86
- expect(text).toContain("Password reset emails never arrive.");
87
- expect(text).not.toContain("<p>");
88
-
89
- const [url] = mock.mock.calls.find(
90
- (c) => !isTokenRequest(String(c[0])),
91
- ) as unknown as [string];
92
- expect(url).toContain("tickets/7942.json");
93
- expect(url).toContain("include=");
94
- });
95
-
96
- it("fetches from a pasted agent URL", async () => {
97
- route((url) =>
98
- url.includes("/api/v2/tickets/7942.json")
99
- ? jsonResponse(TICKET_RESPONSE)
100
- : jsonResponse({}, 404),
101
- );
102
-
103
- const result = await invoke(getTicketTool, {
104
- ticket: "https://{subdomain}.zendesk.com/agent/tickets/7942",
105
- });
106
- expect(firstText(result)).toContain("Ticket #7942");
107
- });
108
-
109
- it("maps API errors through the shared error formatter", async () => {
110
- route(() =>
111
- jsonResponse(
112
- { error: "RecordNotFound", description: "Ticket 7942 not found" },
113
- 404,
114
- ),
115
- );
116
-
117
- const result = await invoke(getTicketTool, { ticket: "7942" });
118
- expect(firstText(result)).toContain("Zendesk error:");
119
- });
120
- });
@@ -1,133 +0,0 @@
1
- import { beforeEach, describe, expect, it, vi } from "vitest";
2
- import { _resetAuthCache } from "../lib/auth";
3
- import { getViewTool } from "../lib/tools/get-view";
4
- import { parseViewRef } from "../lib/url";
5
- import {
6
- TOKEN_OK,
7
- fetchMock,
8
- firstText,
9
- invoke,
10
- isTokenRequest,
11
- jsonResponse,
12
- stubZendeskEnv,
13
- } from "./_helpers";
14
-
15
- beforeEach(() => {
16
- vi.unstubAllEnvs();
17
- _resetAuthCache();
18
- stubZendeskEnv();
19
- });
20
-
21
- describe("parseViewRef", () => {
22
- it("accepts bare ids and /filters/ and /views/ URLs", () => {
23
- expect(parseViewRef("20824934716439")).toBe(20824934716439);
24
- expect(
25
- parseViewRef("https://{subdomain}.zendesk.com/agent/filters/20824934716439"),
26
- ).toBe(20824934716439);
27
- expect(
28
- parseViewRef("https://{subdomain}.zendesk.com/agent/views/42"),
29
- ).toBe(42);
30
- expect(parseViewRef("nonsense")).toBeNull();
31
- });
32
- });
33
-
34
- function route(handler: (url: string) => Response | Promise<Response>) {
35
- return fetchMock(async (url) => {
36
- if (isTokenRequest(url)) return jsonResponse(TOKEN_OK);
37
- return handler(url);
38
- });
39
- }
40
-
41
- const VIEW = { view: { id: 20824934716439, title: "Mine - Web Team", active: true } };
42
- const EXEC = {
43
- count: 2,
44
- next_page: null,
45
- rows: [
46
- {
47
- ticket: {
48
- id: 7942,
49
- subject: "Manage Member button has disappeared in the dashboard",
50
- status: "open",
51
- priority: "urgent",
52
- requester_id: 1042,
53
- assignee_id: 2099,
54
- created_at: "2026-08-14T09:30:00Z",
55
- },
56
- },
57
- {
58
- ticket: {
59
- id: 7950,
60
- subject: "Email digest stopped",
61
- status: "pending",
62
- priority: "normal",
63
- requester_id: 2001,
64
- assignee_id: 2099,
65
- created_at: "2026-08-16T10:00:00Z",
66
- },
67
- },
68
- ],
69
- users: [
70
- { id: 1042, name: "Ada Lovelace", active: true, role: "end-user" },
71
- { id: 2099, name: "Grace Agent", active: true, role: "agent" },
72
- ],
73
- organizations: [{ id: 77, name: "Analytical Engines Ltd", active: true }],
74
- };
75
-
76
- describe("zendesk_get_view", () => {
77
- it("rejects an unparseable view reference", async () => {
78
- const result = await invoke(getViewTool, { view: "nope" });
79
- expect(firstText(result)).toContain("Invalid view reference");
80
- });
81
-
82
- it("renders title and tickets with resolved people from a filter URL", async () => {
83
- const mock = route((url) => {
84
- if (url.includes("/api/v2/views/20824934716439/execute.json")) {
85
- return jsonResponse(EXEC);
86
- }
87
- if (url.includes("/api/v2/views/20824934716439.json")) {
88
- return jsonResponse(VIEW);
89
- }
90
- return jsonResponse({}, 404);
91
- });
92
-
93
- const result = await invoke(getViewTool, {
94
- view: "https://{subdomain}.zendesk.com/agent/filters/20824934716439",
95
- });
96
- const text = firstText(result);
97
-
98
- expect(text).toContain("View #20824934716439 - Mine - Web Team");
99
- expect(text).toContain("2 matching tickets");
100
- expect(text).toContain(
101
- "#7942 [open] Manage Member button has disappeared in the dashboard (urgent)",
102
- );
103
- expect(text).toContain("#7950 [pending] Email digest stopped");
104
-
105
- const [execUrl] = mock.mock.calls
106
- .map((c) => String(c[0]))
107
- .filter((u) => u.includes("execute.json"));
108
- expect(execUrl).toContain("per_page=25");
109
- expect(execUrl).toContain("include=");
110
- });
111
-
112
- it("respects the limit param and reports empty views", async () => {
113
- route((url) => {
114
- if (url.includes("execute.json")) {
115
- return jsonResponse({ count: 0, next_page: null, rows: [] });
116
- }
117
- return jsonResponse(VIEW);
118
- });
119
-
120
- const result = await invoke(getViewTool, { view: "20824934716439", limit: 10 });
121
- const text = firstText(result);
122
-
123
- expect(text).toContain("0 matching tickets");
124
- expect(text).toContain("(no matching tickets)");
125
- });
126
-
127
- it("maps API errors through the shared error formatter", async () => {
128
- route(() => jsonResponse({ error: "Forbidden" }, 403));
129
-
130
- const result = await invoke(getViewTool, { view: "20824934716439" });
131
- expect(firstText(result)).toContain("Zendesk error:");
132
- });
133
- });
@@ -1,131 +0,0 @@
1
- import { beforeEach, describe, expect, it, vi } from "vitest";
2
- import { _resetAuthCache } from "../lib/auth";
3
- import { effectiveQuery, searchTool } from "../lib/tools/search";
4
- import {
5
- TOKEN_OK,
6
- fetchMock,
7
- firstText,
8
- invoke,
9
- isTokenRequest,
10
- jsonResponse,
11
- stubZendeskEnv,
12
- } from "./_helpers";
13
-
14
- beforeEach(() => {
15
- vi.unstubAllEnvs();
16
- _resetAuthCache();
17
- stubZendeskEnv();
18
- });
19
-
20
- describe("effectiveQuery", () => {
21
- it("prepends type:ticket for plain queries", () => {
22
- expect(effectiveQuery("billing urgent", false)).toBe(
23
- "type:ticket billing urgent",
24
- );
25
- });
26
-
27
- it("leaves queries that already pin a type", () => {
28
- expect(effectiveQuery("type:organization acme", false)).toBe(
29
- "type:organization acme",
30
- );
31
- });
32
-
33
- it("all_types disables the default", () => {
34
- expect(effectiveQuery("billing", true)).toBe("billing");
35
- });
36
- });
37
-
38
- describe("zendesk_search", () => {
39
- it("searches tickets and renders result lines", async () => {
40
- const mock = fetchMock((url) => {
41
- if (isTokenRequest(url)) return jsonResponse(TOKEN_OK);
42
- if (url.includes("/api/v2/search.json")) {
43
- return jsonResponse({
44
- count: 2,
45
- next_page: null,
46
- previous_page: null,
47
- results: [
48
- {
49
- result_type: "ticket",
50
- id: 7942,
51
- subject: "Cannot login to portal",
52
- status: "open",
53
- priority: "high",
54
- requester_id: 1042,
55
- created_at: "2026-08-14T09:30:00Z",
56
- },
57
- {
58
- result_type: "ticket",
59
- id: 7901,
60
- subject: "SSO loop after password change",
61
- status: "solved",
62
- priority: "normal",
63
- requester_id: 2001,
64
- created_at: "2026-08-01T08:00:00Z",
65
- },
66
- ],
67
- });
68
- }
69
- return jsonResponse({}, 404);
70
- });
71
-
72
- const result = await invoke(searchTool, { query: "login" });
73
- const text = firstText(result);
74
-
75
- expect(text).toContain("2 results for: type:ticket login");
76
- expect(text).toContain("#7942 [open] Cannot login to portal (high)");
77
- expect(text).toContain("#7901 [solved] SSO loop after password change");
78
- expect(text).toContain("#7942: created 2026-08-14 09:30 UTC");
79
-
80
- const [url] = mock.mock.calls.find(
81
- (c) => !isTokenRequest(String(c[0])),
82
- ) as unknown as [string];
83
- expect(url).toContain("query=type%3Aticket+login");
84
- expect(url).toContain("per_page=25");
85
- });
86
-
87
- it("reports empty result sets plainly", async () => {
88
- fetchMock((url) => {
89
- if (isTokenRequest(url)) return jsonResponse(TOKEN_OK);
90
- return jsonResponse({
91
- count: 0,
92
- next_page: null,
93
- previous_page: null,
94
- results: [],
95
- });
96
- });
97
-
98
- const result = await invoke(searchTool, { query: "zzz-nothing" });
99
- expect(firstText(result)).toContain(
100
- "No results for: type:ticket zzz-nothing",
101
- );
102
- });
103
-
104
- it("notes pagination when more results exist", async () => {
105
- fetchMock((url) => {
106
- if (isTokenRequest(url)) return jsonResponse(TOKEN_OK);
107
- return jsonResponse({
108
- count: 40,
109
- next_page:
110
- "https://{subdomain}.zendesk.com/api/v2/search.json?page=2",
111
- previous_page: null,
112
- results: [
113
- {
114
- result_type: "ticket",
115
- id: 1,
116
- subject: "a",
117
- status: "open",
118
- priority: "low",
119
- requester_id: 5,
120
- created_at: "2026-08-14T09:30:00Z",
121
- },
122
- ],
123
- });
124
- });
125
-
126
- const result = await invoke(searchTool, { query: "open" });
127
- expect(firstText(result)).toContain(
128
- "showing first 1 - narrow the query to refine",
129
- );
130
- });
131
- });
package/tests/url.test.ts DELETED
@@ -1,30 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
- import { parseTicketRef } from "../lib/url";
3
-
4
- describe("parseTicketRef", () => {
5
- it("accepts a bare numeric id", () => {
6
- expect(parseTicketRef("7942")).toBe(7942);
7
- });
8
-
9
- it("accepts a full agent URL", () => {
10
- expect(parseTicketRef("https://{subdomain}.zendesk.com/agent/tickets/7942")).toBe(
11
- 7942,
12
- );
13
- });
14
-
15
- it("accepts an API URL containing /tickets/N", () => {
16
- expect(
17
- parseTicketRef("https://{subdomain}.zendesk.com/api/v2/tickets/12.json"),
18
- ).toBe(12);
19
- });
20
-
21
- it("trims whitespace", () => {
22
- expect(parseTicketRef(" 7942 ")).toBe(7942);
23
- });
24
-
25
- it("returns null for non-ticket input", () => {
26
- expect(parseTicketRef("abc")).toBeNull();
27
- expect(parseTicketRef("")).toBeNull();
28
- expect(parseTicketRef("https://{subdomain}.zendesk.com/agent/")).toBeNull();
29
- });
30
- });
package/vitest.config.ts DELETED
@@ -1,12 +0,0 @@
1
- import { defineConfig } from "vitest/config";
2
-
3
- export default defineConfig({
4
- test: {
5
- include: ["tests/**/*.test.ts"],
6
- environment: "node",
7
- // Each test gets a fresh module cache so the auth token cache does not
8
- // leak across files; pairs with the explicit env-var management in
9
- // tests/auth.test.ts.
10
- isolate: true,
11
- },
12
- });