@knownagents/sdk 1.11.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts CHANGED
@@ -1,353 +1,8 @@
1
- import { IncomingMessage, ServerResponse } from "http"
2
-
3
- /**
4
- * A framework-agnostic HTTP request interface.
5
- * Used as a convenience type for single-request methods.
6
- */
7
- export interface Request {
8
- /** The URL path and query string (e.g. "/about?foo=bar") */
9
- path: string
10
- /** The HTTP method (e.g. "GET", "POST") */
11
- method: string
12
- /** The HTTP request headers */
13
- headers: Record<string, string | string[] | undefined>
14
- }
15
-
16
- /**
17
- * A minimal HTTP response interface.
18
- * Used as a convenience type for single-request methods.
19
- */
20
- export interface Response {
21
- /** The HTTP response status code (e.g. 200, 404) */
22
- statusCode: number
23
- /** The HTTP response headers */
24
- headers?: Record<string, string | string[] | undefined>
25
- }
26
-
27
- /**
28
- * A visit tracking request for the Known Agents API.
29
- * Used for batch visit tracking with `trackVisits()`.
30
- */
31
- export interface VisitRequest {
32
- /** The URL path of the request (e.g. "/about?foo=bar") */
33
- request_path: string
34
- /** The HTTP method (e.g. "GET", "POST") */
35
- request_method: string
36
- /** The HTTP request headers */
37
- request_headers: Record<string, string | string[] | undefined>
38
- /** The HTTP response status code (e.g. 200, 404) */
39
- response_status_code?: number
40
- /** The HTTP response headers */
41
- response_headers?: Record<string, string | string[] | undefined>
42
- /** The response duration in milliseconds */
43
- response_duration_in_milliseconds?: number
44
- /** The timestamp when the visit occurred (ISO 8601 format) */
45
- created?: string
46
- }
47
-
48
- /**
49
- * An agent identification request for the Known Agents API.
50
- * Used for batch agent identification with `identifyAgents()`.
51
- */
52
- export interface IdentificationRequest {
53
- /** An identifier that will be echoed back in the response to match requests with results */
54
- id?: string
55
- /** The HTTP request headers */
56
- request_headers: Record<string, string | string[] | undefined>
57
- }
58
-
59
- /**
60
- * The result of an agent identification request.
61
- */
62
- export interface IdentificationResult {
63
- /** The identifier from the request (if provided) */
64
- id?: string
65
- /**
66
- * The identification result:
67
- * - "verified": The agent was identified and verified
68
- * - "verification_failed": The agent was identified but failed verification (spoofed)
69
- * - "unknown_agent": The request is from an unrecognized agent or human
70
- * - "not_verifiable": The agent was identified but cannot be verified
71
- */
72
- result: "verified" | "verification_failed" | "unknown_agent" | "not_verifiable"
73
- /** The unique ID of the identified agent */
74
- agent_id?: string
75
- /** The name of the identified agent (e.g. "Googlebot") */
76
- agent_token?: string
77
- /** The documentation URL for the identified agent */
78
- agent_url?: string
79
- /** The type of the identified agent (e.g. "AI Agent", "Search Engine Crawler") */
80
- agent_type_name?: string
81
- /** The company behind the identified agent (e.g. "Google") */
82
- operator_name?: string
83
- }
84
-
85
- /**
86
- * Agent types that can be controlled with robots.txt rules.
87
- */
88
- export enum AgentType {
89
- AIAgent = "AI Agent",
90
- AIAssistant = "AI Assistant",
91
- AICodingAgent = "AI Coding Agent",
92
- AIDataProvider = "AI Data Provider",
93
- AIDataScraper = "AI Data Scraper",
94
- AISearchCrawler = "AI Search Crawler",
95
- Archiver = "Archiver",
96
- DeveloperHelper = "Developer Helper",
97
- Fetcher = "Fetcher",
98
- HeadlessAgent = "Headless Agent",
99
- IntelligenceGatherer = "Intelligence Gatherer",
100
- Scraper = "Scraper",
101
- SEOCrawler = "SEO Crawler",
102
- SearchEngineCrawler = "Search Engine Crawler",
103
- SecurityScanner = "Security Scanner",
104
- UndocumentedAIAgent = "Undocumented AI Agent"
105
- }
106
-
107
- export class KnownAgents {
108
- private readonly accessToken: string
109
-
110
- /**
111
- * Creates a new instance of the Known Agents client.
112
- *
113
- * @param accessToken - Your project's access token.
114
- */
115
- constructor(accessToken: string) {
116
- this.accessToken = accessToken
117
- }
118
-
119
- /**
120
- * Tracks a single agent visit for analytics.
121
- * This method is non-blocking and handles errors internally.
122
- *
123
- * @param request - The incoming HTTP request (Request or Node.js IncomingMessage).
124
- * @param response - The outgoing HTTP response (optional).
125
- * @param responseDurationInMilliseconds - The time taken to process the request in milliseconds (optional).
126
- */
127
- trackVisit(request: Request | IncomingMessage, response?: Response | ServerResponse, responseDurationInMilliseconds?: number): void {
128
- const path = "path" in request ? request.path : request.url
129
- const responseHeaders = response instanceof ServerResponse ? response.getHeaders() as Record<string, string | string[] | undefined> : response?.headers
130
-
131
- if (!path || this.isPathExcluded(path)) {
132
- return
133
- }
134
-
135
- fetch("https://api.knownagents.com/visits", {
136
- method: "POST",
137
- headers: {
138
- "Authorization": `Bearer ${this.accessToken}`,
139
- "Content-Type": "application/json"
140
- },
141
- body: JSON.stringify({
142
- request_path: path,
143
- request_method: request.method,
144
- request_headers: this.filterHeaders(request.headers),
145
- response_status_code: response?.statusCode,
146
- response_headers: responseHeaders ? this.filterHeaders(responseHeaders) : undefined,
147
- response_duration_in_milliseconds: responseDurationInMilliseconds,
148
- created: new Date().toISOString()
149
- })
150
- }).catch(error => {
151
- console.error(`Known Agents failed to track visit: ${error.message}`)
152
- })
153
- }
154
-
155
- /**
156
- * Tracks multiple agent visits in a batch for analytics.
157
- * This method is non-blocking and handles errors internally.
158
- * Recommended for high-traffic websites - batch visits and send periodically (e.g. every 30 seconds).
159
- *
160
- * @param visits - An array of visit tracking requests.
161
- */
162
- trackVisits(visits: VisitRequest[]): void {
163
- const filteredVisits = visits
164
- .filter((visit) => {
165
- return !this.isPathExcluded(visit.request_path)
166
- })
167
- .map((visit) => {
168
- return {
169
- ...visit,
170
- request_headers: this.filterHeaders(visit.request_headers),
171
- response_headers: visit.response_headers ? this.filterHeaders(visit.response_headers) : undefined,
172
- }
173
- })
174
-
175
- if (filteredVisits.length === 0) {
176
- return
177
- }
178
-
179
- fetch("https://api.knownagents.com/visits", {
180
- method: "POST",
181
- headers: {
182
- "Authorization": `Bearer ${this.accessToken}`,
183
- "Content-Type": "application/json"
184
- },
185
- body: JSON.stringify(filteredVisits)
186
- }).catch(error => {
187
- console.error(`Known Agents failed to track visits: ${error.message}`)
188
- })
189
- }
190
-
191
- /**
192
- * Generates a robots.txt file that disallows the specified agent types.
193
- * The generated file stays up-to-date with all current and future agents in the specified categories.
194
- * Cache and serve the result at your website's `/robots.txt` endpoint.
195
- *
196
- * @param agentTypes - An array of agent types to disallow.
197
- * @param disallow - The path to disallow (default: "/" for all paths).
198
- * @returns A promise that resolves to the generated robots.txt content as a string.
199
- * @throws {Error} If the API call fails or returns a non-200 status.
200
- */
201
- async generateRobotsTXT(agentTypes: AgentType[], disallow: string = "/"): Promise<string> {
202
- const response = await fetch("https://api.knownagents.com/robots-txts", {
203
- method: "POST",
204
- headers: {
205
- "Authorization": `Bearer ${this.accessToken}`,
206
- "Content-Type": "application/json"
207
- },
208
- body: JSON.stringify({
209
- agent_types: agentTypes,
210
- disallow: disallow
211
- })
212
- })
213
-
214
- if (response.ok) {
215
- return await response.text()
216
- } else {
217
- throw new Error(`Known Agents failed to generate robots.txt: ${response.status} ${response.statusText}`)
218
- }
219
- }
220
-
221
- /**
222
- * Identifies and verifies a single agent from an HTTP request.
223
- * Uses Web Bot Auth (HTTP message signatures), IP matching, or other available methods.
224
- *
225
- * @param request - The incoming HTTP request (Request or Node.js IncomingMessage).
226
- * @returns A promise that resolves to the identification result.
227
- * @throws {Error} If the API call fails or returns a non-200 status.
228
- */
229
- async identifyAgent(request: Request | IncomingMessage): Promise<IdentificationResult> {
230
- const response = await fetch("https://api.knownagents.com/agent-identifications", {
231
- method: "POST",
232
- headers: {
233
- "Authorization": `Bearer ${this.accessToken}`,
234
- "Content-Type": "application/json"
235
- },
236
- body: JSON.stringify({
237
- request_headers: this.filterHeaders(request.headers)
238
- })
239
- })
240
-
241
- if (response.ok) {
242
- return await response.json()
243
- } else {
244
- throw new Error(`Known Agents failed to identify agent: ${response.status} ${response.statusText}`)
245
- }
246
- }
247
-
248
- /**
249
- * Identifies and verifies multiple agents from HTTP requests in a batch.
250
- * Uses Web Bot Auth (HTTP message signatures), IP matching, or other available methods.
251
- *
252
- * @param requests - An array of identification requests.
253
- * @returns A promise that resolves to an array of identification results.
254
- * @throws {Error} If the API call fails or returns a non-200 status.
255
- */
256
- async identifyAgents(requests: IdentificationRequest[]): Promise<IdentificationResult[]> {
257
- const response = await fetch("https://api.knownagents.com/agent-identifications", {
258
- method: "POST",
259
- headers: {
260
- "Authorization": `Bearer ${this.accessToken}`,
261
- "Content-Type": "application/json"
262
- },
263
- body: JSON.stringify(requests.map(request => {
264
- return {
265
- ...request,
266
- request_headers: this.filterHeaders(request.request_headers),
267
- }
268
- }))
269
- })
270
-
271
- if (response.ok) {
272
- return await response.json()
273
- } else {
274
- throw new Error(`Known Agents failed to identify agents: ${response.status} ${response.statusText}`)
275
- }
276
- }
277
-
278
- // Helpers
279
-
280
- private isPathExcluded(path: string): boolean {
281
- const excludedPrefixes = [
282
- "/_next/",
283
- "/_nuxt/",
284
- "/_astro/",
285
- "/_app/",
286
- "/@vite/",
287
- "/@fs/",
288
- "/@id/",
289
- "/node_modules/",
290
- "/_vercel/",
291
- ]
292
-
293
- const excludedSuffixes = [
294
- ".ico",
295
- ".png",
296
- ".jpg",
297
- ".jpeg",
298
- ".gif",
299
- ".webp",
300
- ".svg",
301
- ".bmp",
302
- ".tiff",
303
- ".avif",
304
- ".css",
305
- ".js",
306
- ".mjs",
307
- ".ts",
308
- ".jsx",
309
- ".tsx",
310
- ".map",
311
- ".woff",
312
- ".woff2",
313
- ".ttf",
314
- ".otf",
315
- ".eot",
316
- ".mp3",
317
- ".mp4",
318
- ".webm",
319
- ".wav",
320
- ".ogg",
321
- ".mov",
322
- ".avi",
323
- ".flv",
324
- ".m4v",
325
- ".rss",
326
- ".json",
327
- ".xml",
328
- ".pdf",
329
- ".zip",
330
- ]
331
-
332
- return excludedPrefixes.some((excludedPrefix) => {
333
- return path.toLowerCase().startsWith(excludedPrefix.toLowerCase())
334
- }) || excludedSuffixes.some((excludedSuffix) => {
335
- return path.toLowerCase().endsWith(excludedSuffix.toLowerCase())
336
- })
337
- }
338
-
339
- private filterHeaders(headers: Record<string, string | string[] | undefined>): Record<string, string | string[] | undefined> {
340
- const excludedHeaders = new Set([
341
- "authorization",
342
- "proxy-authorization",
343
- "cookie",
344
- "set-cookie"
345
- ])
346
-
347
- return Object.fromEntries(
348
- Object.entries(headers).filter(([key]) => {
349
- return !excludedHeaders.has(key.toLowerCase())
350
- })
351
- )
352
- }
353
- }
1
+ export { KnownAgents } from "./KnownAgents"
2
+ export {
3
+ AgentType,
4
+ type IdentificationRequest,
5
+ type IdentificationResult,
6
+ type TrackPageviewOrRESTCallOptions,
7
+ type VisitRequest
8
+ } from "./types"
package/src/paths.ts ADDED
@@ -0,0 +1,72 @@
1
+ export function getIsPathExcluded(path: string): boolean {
2
+ const pathWithoutQueryString = path.split(/[?#]/)[0]
3
+ const lowercasedPath = pathWithoutQueryString.toLowerCase()
4
+
5
+ const excludedPrefixes = [
6
+ "/_next/",
7
+ "/_nuxt/",
8
+ "/_astro/",
9
+ "/_app/",
10
+ "/__nextjs",
11
+ "/__vite_ping",
12
+ "/__webpack_hmr",
13
+ "/@vite/",
14
+ "/@fs/",
15
+ "/@id/",
16
+ "/@react-refresh",
17
+ "/node_modules/",
18
+ "/_vercel/",
19
+ "/sockjs-node/",
20
+ "/webpack-dev-server/",
21
+ ]
22
+
23
+ const excludedSuffixes = [
24
+ ".ico",
25
+ ".png",
26
+ ".jpg",
27
+ ".jpeg",
28
+ ".gif",
29
+ ".webp",
30
+ ".svg",
31
+ ".bmp",
32
+ ".tiff",
33
+ ".avif",
34
+ ".heic",
35
+ ".heif",
36
+ ".css",
37
+ ".js",
38
+ ".mjs",
39
+ ".ts",
40
+ ".jsx",
41
+ ".tsx",
42
+ ".map",
43
+ ".wasm",
44
+ ".woff",
45
+ ".woff2",
46
+ ".ttf",
47
+ ".otf",
48
+ ".eot",
49
+ ".mp3",
50
+ ".mp4",
51
+ ".webm",
52
+ ".wav",
53
+ ".ogg",
54
+ ".aac",
55
+ ".m4a",
56
+ ".flac",
57
+ ".mov",
58
+ ".avi",
59
+ ".flv",
60
+ ".m4v",
61
+ ".webmanifest",
62
+ ".pdf",
63
+ ".zip",
64
+ ".gz",
65
+ ]
66
+
67
+ return excludedPrefixes.some((excludedPrefix) => {
68
+ return lowercasedPath.startsWith(excludedPrefix.toLowerCase())
69
+ }) || excludedSuffixes.some((excludedSuffix) => {
70
+ return lowercasedPath.endsWith(excludedSuffix.toLowerCase())
71
+ })
72
+ }
package/src/types.ts ADDED
@@ -0,0 +1,109 @@
1
+ import type { IncomingHttpHeaders, OutgoingHttpHeaders } from "http"
2
+
3
+ /**
4
+ * Additional metadata to include when tracking a pageview or REST API call.
5
+ */
6
+ export interface TrackPageviewOrRESTCallOptions {
7
+ /** The ACP response body. */
8
+ acpResponseBody?: Record<string, unknown>
9
+ /** The UCP response body. */
10
+ ucpResponseBody?: Record<string, unknown>
11
+ }
12
+
13
+ /**
14
+ * A normalized visit payload for the Known Agents API.
15
+ * Use this with `trackVisits()` when batching requests yourself.
16
+ */
17
+ export interface VisitRequest {
18
+ /** The URL path and query string of the request (e.g. "/about?foo=bar") */
19
+ request_path: string
20
+ /** The HTTP method (e.g. "GET", "POST") */
21
+ request_method: string
22
+ /** The HTTP request headers. Sensitive headers are removed before sending. */
23
+ request_headers: IncomingHttpHeaders
24
+ /** The HTTP response status code (e.g. 200, 404) */
25
+ response_status_code?: number
26
+ /** The HTTP response headers. Sensitive headers are removed before sending. */
27
+ response_headers?: OutgoingHttpHeaders
28
+ /** The response duration in milliseconds */
29
+ response_duration_in_milliseconds?: number
30
+ /** The MCP JSON-RPC request method */
31
+ mcp_request_method?: string
32
+ /** The MCP request tool name */
33
+ mcp_request_tool_name?: string
34
+ /** The MCP request client name */
35
+ mcp_request_client_info_name?: string
36
+ /** The MCP request client version */
37
+ mcp_request_client_info_version?: string
38
+ /** Whether the MCP response result is an error */
39
+ mcp_response_result_is_error?: boolean
40
+ /** The MCP response error code */
41
+ mcp_response_error_code?: number
42
+ /** The MCP response error message */
43
+ mcp_response_error_message?: string
44
+ /** The ACP response body */
45
+ acp_response_body?: Record<string, unknown>
46
+ /** The UCP response body */
47
+ ucp_response_body?: Record<string, unknown>
48
+ /** The timestamp when the visit occurred (ISO 8601 format) */
49
+ created?: string
50
+ }
51
+
52
+ /**
53
+ * An agent identification request for the Known Agents API.
54
+ * Used for batch agent identification with `identifyAgents()`.
55
+ */
56
+ export interface IdentificationRequest {
57
+ /** An identifier that will be echoed back in the response to match requests with results */
58
+ id?: string
59
+ /** The HTTP request headers. Sensitive headers are removed before sending. */
60
+ request_headers: IncomingHttpHeaders
61
+ }
62
+
63
+ /**
64
+ * The result of an agent identification request.
65
+ */
66
+ export interface IdentificationResult {
67
+ /** The identifier from the request (if provided) */
68
+ id?: string
69
+ /**
70
+ * The identification result:
71
+ * - "verified": The agent was identified and verified
72
+ * - "verification_failed": The agent was identified but failed verification (spoofed)
73
+ * - "unknown_agent": The request is from an unrecognized agent or human
74
+ * - "not_verifiable": The agent was identified but cannot be verified
75
+ */
76
+ result: "verified" | "verification_failed" | "unknown_agent" | "not_verifiable"
77
+ /** The unique ID of the identified agent */
78
+ agent_id?: string
79
+ /** The name of the identified agent (e.g. "Googlebot") */
80
+ agent_token?: string
81
+ /** The documentation URL for the identified agent */
82
+ agent_url?: string
83
+ /** The type of the identified agent (e.g. "AI Agent", "Search Engine Crawler") */
84
+ agent_type_name?: string
85
+ /** The company behind the identified agent (e.g. "Google") */
86
+ operator_name?: string
87
+ }
88
+
89
+ /**
90
+ * Agent types that can be controlled with robots.txt rules.
91
+ */
92
+ export enum AgentType {
93
+ AIAgent = "AI Agent",
94
+ AIAssistant = "AI Assistant",
95
+ AICodingAgent = "AI Coding Agent",
96
+ AIDataProvider = "AI Data Provider",
97
+ AIDataScraper = "AI Data Scraper",
98
+ AISearchCrawler = "AI Search Crawler",
99
+ Archiver = "Archiver",
100
+ AutomatedAgent = "Automated Agent",
101
+ DeveloperHelper = "Developer Helper",
102
+ Fetcher = "Fetcher",
103
+ IntelligenceGatherer = "Intelligence Gatherer",
104
+ Scraper = "Scraper",
105
+ SEOCrawler = "SEO Crawler",
106
+ SearchEngineCrawler = "Search Engine Crawler",
107
+ SecurityScanner = "Security Scanner",
108
+ UndocumentedAIAgent = "Undocumented AI Agent"
109
+ }
package/tsconfig.json DELETED
@@ -1,16 +0,0 @@
1
- {
2
- "include": ["src"],
3
- "compilerOptions": {
4
- "target": "ES2020",
5
- "module": "CommonJS",
6
- "outDir": "dist",
7
- "rootDir": "src",
8
- "declaration": true,
9
- "declarationMap": true,
10
- "esModuleInterop": true,
11
- "forceConsistentCasingInFileNames": true,
12
- "strict": true,
13
- "skipLibCheck": true,
14
- "types": ["node"]
15
- }
16
- }