mcp-feedback 0.6.0 → 0.7.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.
@@ -0,0 +1,447 @@
1
+ // The ingest hub (spec/ingest.md): accepts feedback from installations of a distributed MCP server
2
+ // and writes it into an ordinary store, which the reader tools and CLI then read as usual.
3
+ import { Readable } from "node:stream";
4
+ import { fingerprintToken } from "../identity.js";
5
+ import { FeedbackInputError } from "../reader.js";
6
+ import { buildRecord, DEFAULT_FEEDBACK_LIMITS, validateSubmission } from "../register.js";
7
+ import { GitHubError, pollDeviceFlow, signedInUser, startDeviceFlow } from "./github.js";
8
+ import { INGEST_PATHS, ingestSubmissionSchema, MAX_INGEST_BODY_BYTES, MAX_QUEUE_AGE_DAYS, } from "./protocol.js";
9
+ import { ANY_PROJECT, issueToken, isValidProjectName, TokenError, verifyToken } from "./tokens.js";
10
+ export const DEFAULT_INGEST_QUOTAS = {
11
+ perInstallPerDay: 20,
12
+ perIssuedSubjectPerDay: 200,
13
+ perProjectPerDay: 500,
14
+ enrollPerAddressPerHour: 20,
15
+ };
16
+ const DAY_MS = 24 * 60 * 60 * 1000;
17
+ const UUIDV7 = /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
18
+ class HttpError extends Error {
19
+ status;
20
+ code;
21
+ headers;
22
+ constructor(status, code, message, headers = {}) {
23
+ super(message);
24
+ this.status = status;
25
+ this.code = code;
26
+ this.headers = headers;
27
+ }
28
+ }
29
+ function json(status, body, headers = {}) {
30
+ return new Response(JSON.stringify(body), {
31
+ status,
32
+ headers: { "content-type": "application/json", "cache-control": "no-store", ...headers },
33
+ });
34
+ }
35
+ function errorResponse(error) {
36
+ const body = { error: { code: error.code, message: error.message } };
37
+ return json(error.status, body, error.headers);
38
+ }
39
+ function bearer(request) {
40
+ const header = request.headers.get("authorization") ?? "";
41
+ const match = /^Bearer ([A-Za-z0-9._-]+)$/.exec(header);
42
+ if (!match)
43
+ throw new HttpError(401, "unauthorized", "Send the token as Authorization: Bearer <token>.");
44
+ return match[1];
45
+ }
46
+ /** Reads at most `max` bytes of the body, refusing more without reading it all. */
47
+ async function readBody(request, max) {
48
+ const declared = Number(request.headers.get("content-length") ?? "NaN");
49
+ if (declared > max)
50
+ throw new HttpError(413, "payload_too_large", `The request is larger than ${max} bytes.`);
51
+ if (!request.body)
52
+ return "";
53
+ const reader = request.body.getReader();
54
+ const chunks = [];
55
+ let total = 0;
56
+ for (;;) {
57
+ const { done, value } = await reader.read();
58
+ if (done)
59
+ break;
60
+ total += value.byteLength;
61
+ if (total > max) {
62
+ await reader.cancel();
63
+ throw new HttpError(413, "payload_too_large", `The request is larger than ${max} bytes.`);
64
+ }
65
+ chunks.push(value);
66
+ }
67
+ return Buffer.concat(chunks).toString("utf8");
68
+ }
69
+ /** An installation's id is kept only if it is a UUIDv7 from no longer ago than a queue can hold a report. */
70
+ function acceptableId(id, now) {
71
+ if (id === undefined || !UUIDV7.test(id))
72
+ return undefined;
73
+ const time = parseInt(id.replace(/-/g, "").slice(0, 12), 16);
74
+ return time > now - MAX_QUEUE_AGE_DAYS * DAY_MS && time < now + 5 * 60 * 1000 ? id : undefined;
75
+ }
76
+ /** In-memory sliding window: process-local, so a host running several instances should add allowEnrollment. */
77
+ function windowLimiter(windowMs) {
78
+ const hits = new Map();
79
+ return (key, limit) => {
80
+ const now = Date.now();
81
+ const recent = (hits.get(key) ?? []).filter((time) => time > now - windowMs);
82
+ if (recent.length >= limit) {
83
+ hits.set(key, recent);
84
+ return false;
85
+ }
86
+ recent.push(now);
87
+ hits.set(key, recent);
88
+ if (hits.size > 10_000) {
89
+ for (const [entry, times] of hits)
90
+ if (!times.some((time) => time > now - windowMs))
91
+ hits.delete(entry);
92
+ }
93
+ return true;
94
+ };
95
+ }
96
+ export function createIngestHandler(options) {
97
+ for (const [name, project] of Object.entries(options.projects ?? {})) {
98
+ if (!isValidProjectName(name))
99
+ throw new Error(`Invalid project name: ${name}`);
100
+ if (!project.store && !options.store)
101
+ throw new Error(`Project ${name} has no store, and there is no shared store.`);
102
+ }
103
+ if (!options.store && !options.projects)
104
+ throw new Error("Give a store, or projects with stores of their own.");
105
+ if (!options.keyring.keys.length)
106
+ throw new Error("The keyring needs at least one verification key.");
107
+ const basePath = (options.basePath ?? "").replace(/\/+$/, "");
108
+ const limits = { ...DEFAULT_FEEDBACK_LIMITS, ...options.limits };
109
+ const installTtl = options.installTokenTtlSeconds ?? 30 * 24 * 60 * 60;
110
+ const userTtl = options.github?.userTokenTtlSeconds ?? 180 * 24 * 60 * 60;
111
+ const enrollLimiter = windowLimiter(60 * 60 * 1000);
112
+ const quotasFor = (project) => ({ ...DEFAULT_INGEST_QUOTAS, ...options.quotas, ...options.projects?.[project]?.quotas });
113
+ /** The store a project's feedback goes to, or undefined when this hub does not take that project. */
114
+ const storeFor = (project) => {
115
+ if (!options.projects)
116
+ return options.store;
117
+ const entry = options.projects[project];
118
+ return entry ? (entry.store ?? options.store) : undefined;
119
+ };
120
+ const authenticate = async (request, tiers) => {
121
+ const token = bearer(request);
122
+ let claims;
123
+ try {
124
+ claims = verifyToken(token, options.keyring, { issuer: options.issuer, tiers });
125
+ }
126
+ catch (error) {
127
+ if (error instanceof TokenError)
128
+ throw new HttpError(401, "unauthorized", error.message);
129
+ throw error;
130
+ }
131
+ if (await options.isRevoked?.(claims))
132
+ throw new HttpError(403, "revoked", "This token has been revoked.");
133
+ const store = storeFor(claims.prj);
134
+ if (!store)
135
+ throw new HttpError(404, "unknown_project", `This hub does not collect feedback for ${claims.prj}.`);
136
+ return { token, claims, store };
137
+ };
138
+ const requireSigner = () => {
139
+ const signer = options.keyring.signer;
140
+ if (!signer)
141
+ throw new HttpError(501, "not_enrolling", "This hub does not issue tokens; ask the maintainer for one.");
142
+ return signer;
143
+ };
144
+ const tokenResponse = (status, issued) => json(status, {
145
+ token: issued.token,
146
+ subject: issued.claims.sub,
147
+ tier: issued.claims.tier,
148
+ expires_at: new Date(issued.claims.exp * 1000).toISOString(),
149
+ });
150
+ const limitAddress = (key, project) => {
151
+ if (!enrollLimiter(key, quotasFor(project).enrollPerAddressPerHour)) {
152
+ throw new HttpError(429, "rate_limited", "Too many requests from this address. Try again later.", { "retry-after": "3600" });
153
+ }
154
+ };
155
+ /** A JSON object body, or `{}` when there is none. */
156
+ const readObject = async (request) => {
157
+ const text = await readBody(request, 8 * 1024);
158
+ if (!text.trim())
159
+ return {};
160
+ try {
161
+ const value = JSON.parse(text);
162
+ if (value && typeof value === "object" && !Array.isArray(value))
163
+ return value;
164
+ }
165
+ catch {
166
+ // Falls through.
167
+ }
168
+ throw new HttpError(400, "invalid_request", "The body must be a JSON object.");
169
+ };
170
+ /** A signed-in person's `user` token from a request body, verified and not revoked. */
171
+ const userClaims = async (token) => {
172
+ if (typeof token !== "string")
173
+ throw new HttpError(400, "invalid_request", "user_token must be a string.");
174
+ let claims;
175
+ try {
176
+ claims = verifyToken(token, options.keyring, { issuer: options.issuer, tiers: ["user"] });
177
+ }
178
+ catch (error) {
179
+ if (error instanceof TokenError)
180
+ throw new HttpError(401, "unauthorized", `The sign-in is no longer valid: ${error.message}`);
181
+ throw error;
182
+ }
183
+ if (await options.isRevoked?.(claims))
184
+ throw new HttpError(403, "revoked", "This sign-in has been revoked.");
185
+ return claims;
186
+ };
187
+ // With a user_token, the installation becomes that person for this project; without, it is anonymous.
188
+ const enroll = async (request, info) => {
189
+ const { claims } = await authenticate(request, ["project"]);
190
+ const signer = requireSigner();
191
+ const body = await readObject(request);
192
+ if (body.user_token !== undefined) {
193
+ const user = await userClaims(body.user_token);
194
+ return tokenResponse(201, issueToken({ issuer: options.issuer, project: claims.prj, tier: "issued", subject: user.sub, ttlSeconds: installTtl }, signer));
195
+ }
196
+ const clientAddress = info.clientAddress ?? null;
197
+ if (clientAddress)
198
+ limitAddress(clientAddress, claims.prj);
199
+ if (options.allowEnrollment && !(await options.allowEnrollment({ project: claims.prj, clientAddress }))) {
200
+ throw new HttpError(429, "rate_limited", "Enrolment is not available right now. Try again later.", { "retry-after": "3600" });
201
+ }
202
+ return tokenResponse(201, issueToken({ issuer: options.issuer, project: claims.prj, tier: "install", ttlSeconds: installTtl }, signer));
203
+ };
204
+ // A fresh copy of a token the hub issued: same subject, project and tier, new expiry. Installations
205
+ // call it as they start, so a machine in use never runs out.
206
+ const renew = async (request) => {
207
+ const token = bearer(request);
208
+ let claims;
209
+ try {
210
+ claims = verifyToken(token, options.keyring, { issuer: options.issuer, tiers: ["install", "user"] });
211
+ }
212
+ catch (error) {
213
+ if (error instanceof TokenError)
214
+ throw new HttpError(401, "unauthorized", error.message);
215
+ throw error;
216
+ }
217
+ if (await options.isRevoked?.(claims))
218
+ throw new HttpError(403, "revoked", "This token has been revoked.");
219
+ if (claims.prj !== ANY_PROJECT && !storeFor(claims.prj)) {
220
+ throw new HttpError(404, "unknown_project", `This hub does not collect feedback for ${claims.prj}.`);
221
+ }
222
+ if (claims.tier === "user" && !options.github)
223
+ throw new HttpError(501, "not_signing_in", "This hub no longer offers sign-in.");
224
+ const ttl = claims.tier === "user" ? userTtl : installTtl;
225
+ return tokenResponse(200, issueToken({ issuer: options.issuer, project: claims.prj, tier: claims.tier, subject: claims.sub, ttlSeconds: ttl }, requireSigner()));
226
+ };
227
+ const github = () => {
228
+ if (!options.github)
229
+ throw new HttpError(501, "not_signing_in", "This hub does not offer GitHub sign-in.");
230
+ return options.github;
231
+ };
232
+ const githubFailure = (error) => {
233
+ if (error instanceof GitHubError)
234
+ throw new HttpError(502, "github", error.message);
235
+ throw error;
236
+ };
237
+ // The installation gets a code for its user to enter at GitHub, and a handle to poll with.
238
+ const githubStart = async (request, info) => {
239
+ const { claims } = await authenticate(request, ["project"]);
240
+ const config = github();
241
+ requireSigner();
242
+ if (info.clientAddress)
243
+ limitAddress(`signin:${info.clientAddress}`, claims.prj);
244
+ const code = await startDeviceFlow(config).catch(githubFailure);
245
+ return json(200, {
246
+ verification_uri: code.verification_uri,
247
+ user_code: code.user_code,
248
+ expires_in: code.expires_in,
249
+ interval: code.interval,
250
+ handle: code.device_code,
251
+ });
252
+ };
253
+ const githubPoll = async (request) => {
254
+ await authenticate(request, ["project"]);
255
+ const config = github();
256
+ const signer = requireSigner();
257
+ const { handle } = await readObject(request);
258
+ if (typeof handle !== "string" || !handle || handle.length > 200)
259
+ throw new HttpError(400, "invalid_request", "handle must be the value start returned.");
260
+ const result = await pollDeviceFlow(config, handle).catch(githubFailure);
261
+ if (result.status === "pending")
262
+ return json(202, { status: "pending", ...(result.interval ? { interval: result.interval } : {}) });
263
+ if (result.status === "denied")
264
+ throw new HttpError(403, "signin_denied", "The sign-in was declined at GitHub.");
265
+ if (result.status === "expired")
266
+ throw new HttpError(410, "signin_expired", "The sign-in code expired before it was entered. Start again.");
267
+ let login;
268
+ try {
269
+ login = await signedInUser(config, result.accessToken);
270
+ }
271
+ catch (error) {
272
+ if (error instanceof GitHubError && /not (one|a member)/.test(error.message))
273
+ throw new HttpError(403, "not_allowed", error.message);
274
+ return githubFailure(error);
275
+ }
276
+ const issued = issueToken({ issuer: options.issuer, project: ANY_PROJECT, tier: "user", subject: `github:${login}`, ttlSeconds: userTtl }, signer);
277
+ if (await options.isRevoked?.(issued.claims))
278
+ throw new HttpError(403, "revoked", "This GitHub account has been revoked on this hub.");
279
+ return tokenResponse(200, issued);
280
+ };
281
+ const metadata = () => ({
282
+ issuer: options.issuer,
283
+ endpoints: { enroll: INGEST_PATHS.enroll, feedback: INGEST_PATHS.feedback, renew: INGEST_PATHS.renew },
284
+ signin: options.github && options.keyring.signer ? { github: { start: INGEST_PATHS.githubStart, poll: INGEST_PATHS.githubPoll } } : {},
285
+ install_token_ttl_seconds: installTtl,
286
+ user_token_ttl_seconds: options.github ? userTtl : null,
287
+ });
288
+ // Counted within the project, so projects sharing a store do not use up each other's quotas.
289
+ const checkQuota = async (store, claims, now) => {
290
+ const quotas = quotasFor(claims.prj);
291
+ const since = new Date(now - DAY_MS).toISOString();
292
+ const own = claims.tier === "install" ? quotas.perInstallPerDay : quotas.perIssuedSubjectPerDay;
293
+ const limited = (message) => new HttpError(429, "rate_limited", message, { "retry-after": "3600" });
294
+ if ((await store.stats({ server: claims.prj, subject: claims.sub, since })).total >= own) {
295
+ throw limited(`This installation has sent ${own} reports in the last day, the most this project accepts. Try again later.`);
296
+ }
297
+ if ((await store.stats({ server: claims.prj, since })).total >= quotas.perProjectPerDay) {
298
+ throw limited("This project has received as many reports today as it accepts. Try again later.");
299
+ }
300
+ };
301
+ const feedback = async (request) => {
302
+ const { token, claims, store } = await authenticate(request, ["install", "issued"]);
303
+ const text = await readBody(request, MAX_INGEST_BODY_BYTES);
304
+ let parsed;
305
+ try {
306
+ const result = ingestSubmissionSchema.safeParse(JSON.parse(text));
307
+ if (!result.success) {
308
+ const issue = result.error.issues[0];
309
+ throw new HttpError(400, "invalid_request", `${issue?.path.join(".") || "body"}: ${issue?.message ?? "invalid"}`);
310
+ }
311
+ parsed = result.data;
312
+ }
313
+ catch (error) {
314
+ if (error instanceof HttpError)
315
+ throw error;
316
+ throw new HttpError(400, "invalid_request", "The body is not valid JSON.");
317
+ }
318
+ try {
319
+ validateSubmission(parsed, limits);
320
+ if (parsed.server_context && Buffer.byteLength(JSON.stringify(parsed.server_context), "utf8") > limits.metadataBytes) {
321
+ throw new FeedbackInputError(`server_context is larger than ${limits.metadataBytes} bytes as JSON.`);
322
+ }
323
+ }
324
+ catch (error) {
325
+ if (error instanceof FeedbackInputError)
326
+ throw new HttpError(400, "invalid_request", error.message);
327
+ throw error;
328
+ }
329
+ const now = Date.now();
330
+ const id = acceptableId(parsed.id, now);
331
+ if (id) {
332
+ // A retry of a report this hub already has: answer as before, store nothing.
333
+ const existing = await store.get(id);
334
+ if (existing)
335
+ return duplicate(existing, claims);
336
+ }
337
+ await checkQuota(store, claims, now);
338
+ const identity = {
339
+ subject: claims.sub,
340
+ client_id: claims.prj,
341
+ session_id: null,
342
+ token_fingerprint: fingerprintToken(token, options.tokenFingerprintKey),
343
+ scopes: [`ingest:${claims.tier}`],
344
+ client_name: parsed.client_name ?? null,
345
+ client_version: parsed.client_version ?? null,
346
+ user_agent: request.headers.get("user-agent")?.slice(0, 200) ?? null,
347
+ };
348
+ let record = buildRecord(parsed, {
349
+ id,
350
+ now: new Date(now),
351
+ identity,
352
+ server: { name: claims.prj, version: parsed.server_version ?? null },
353
+ });
354
+ const { ingest: _reserved, ...reportedContext } = parsed.server_context ?? {};
355
+ const clientCreated = parsed.created_at && !Number.isNaN(Date.parse(parsed.created_at)) ? new Date(parsed.created_at).toISOString() : null;
356
+ record.context.server_context = {
357
+ ...reportedContext,
358
+ ingest: { tier: claims.tier, received_at: record.created_at, client_created_at: clientCreated },
359
+ };
360
+ if (options.redact)
361
+ record = await options.redact(record);
362
+ try {
363
+ await store.insert(record);
364
+ }
365
+ catch (error) {
366
+ // Two deliveries of the same queued report can race; the loser finds the winner's record.
367
+ const existing = await store.get(record.id).catch(() => null);
368
+ if (existing)
369
+ return duplicate(existing, claims);
370
+ throw error;
371
+ }
372
+ return json(201, { id: record.id, created_at: record.created_at, status: record.status });
373
+ };
374
+ const duplicate = (existing, claims) => {
375
+ if (existing.identity.subject !== claims.sub || existing.server.name !== claims.prj) {
376
+ throw new HttpError(409, "conflict", "That report id is already in use. Send the report again without an id.");
377
+ }
378
+ return json(200, { id: existing.id, created_at: existing.created_at, status: existing.status, duplicate: true });
379
+ };
380
+ return async (request, info = {}) => {
381
+ try {
382
+ const path = new URL(request.url).pathname.replace(/\/+$/, "");
383
+ if (path === basePath + INGEST_PATHS.wellKnown) {
384
+ if (request.method !== "GET")
385
+ throw new HttpError(405, "method_not_allowed", "Use GET.", { allow: "GET" });
386
+ return json(200, metadata(), { "cache-control": "public, max-age=300" });
387
+ }
388
+ const routes = {
389
+ [basePath + INGEST_PATHS.enroll]: enroll,
390
+ [basePath + INGEST_PATHS.feedback]: feedback,
391
+ [basePath + INGEST_PATHS.renew]: renew,
392
+ [basePath + INGEST_PATHS.githubStart]: githubStart,
393
+ [basePath + INGEST_PATHS.githubPoll]: githubPoll,
394
+ };
395
+ const route = Object.hasOwn(routes, path) ? routes[path] : undefined;
396
+ if (!route)
397
+ throw new HttpError(404, "not_found", "No such endpoint.");
398
+ if (request.method !== "POST")
399
+ throw new HttpError(405, "method_not_allowed", "Use POST.", { allow: "POST" });
400
+ return await route(request, info);
401
+ }
402
+ catch (error) {
403
+ if (error instanceof HttpError)
404
+ return errorResponse(error);
405
+ options.onError?.(error);
406
+ return errorResponse(new HttpError(503, "unavailable", "The feedback service could not store the report. Try again later."));
407
+ }
408
+ };
409
+ }
410
+ /**
411
+ * Adapts the handler to node:http and Express. Mount it before any body parser.
412
+ *
413
+ * The client address (for the enrolment limit) is, in order: `clientAddress(req)` if given; the
414
+ * first X-Forwarded-For entry with `trustProxy`, which is only safe behind a proxy that overwrites
415
+ * that header; Express's `req.ip`, which follows the app's own `trust proxy` setting; the socket.
416
+ */
417
+ export function toNodeListener(handler, options = {}) {
418
+ return async (req, res) => {
419
+ try {
420
+ const host = req.headers.host ?? "localhost";
421
+ const headers = new Headers();
422
+ for (const [key, value] of Object.entries(req.headers)) {
423
+ if (value !== undefined)
424
+ headers.set(key, Array.isArray(value) ? value.join(", ") : value);
425
+ }
426
+ const hasBody = req.method !== "GET" && req.method !== "HEAD";
427
+ // Express strips its mount path from req.url and keeps the full one in originalUrl.
428
+ const path = req.originalUrl ?? req.url ?? "/";
429
+ const request = new Request(`http://${host}${path}`, {
430
+ method: req.method,
431
+ headers,
432
+ ...(hasBody ? { body: Readable.toWeb(req), duplex: "half" } : {}),
433
+ });
434
+ const forwarded = options.trustProxy ? String(req.headers["x-forwarded-for"] ?? "").split(",")[0]?.trim() : "";
435
+ const expressIp = req.ip;
436
+ const clientAddress = options.clientAddress?.(req) || forwarded || (typeof expressIp === "string" ? expressIp : "") || req.socket.remoteAddress || null;
437
+ const response = await handler(request, { clientAddress });
438
+ res.writeHead(response.status, Object.fromEntries(response.headers));
439
+ res.end(Buffer.from(await response.arrayBuffer()));
440
+ }
441
+ catch {
442
+ if (!res.headersSent)
443
+ res.writeHead(500);
444
+ res.end();
445
+ }
446
+ };
447
+ }
@@ -0,0 +1,3 @@
1
+ export { createIngestHandler, toNodeListener, DEFAULT_INGEST_QUOTAS, type IngestHandler, type IngestOptions, type IngestProject, type IngestQuotas, type IngestRequestInfo, } from "./handler.js";
2
+ export { generateKeyPair, issueToken, publicKeyOf, signToken, verifyToken, isValidProjectName, TokenError, TOKEN_TIERS, type Keyring, type SigningKey, type TokenClaims, type TokenTier, type VerificationKey, } from "./tokens.js";
3
+ export { INGEST_PATHS, MAX_INGEST_BODY_BYTES, MAX_QUEUE_AGE_DAYS, ingestSubmissionSchema, toIngestSubmission, type IngestErrorBody, type IngestSubmission, } from "./protocol.js";
@@ -0,0 +1,5 @@
1
+ // The ingest hub: a hosted endpoint that accepts feedback from installations of a distributed MCP
2
+ // server and writes it into an ordinary store. See spec/ingest.md.
3
+ export { createIngestHandler, toNodeListener, DEFAULT_INGEST_QUOTAS, } from "./handler.js";
4
+ export { generateKeyPair, issueToken, publicKeyOf, signToken, verifyToken, isValidProjectName, TokenError, TOKEN_TIERS, } from "./tokens.js";
5
+ export { INGEST_PATHS, MAX_INGEST_BODY_BYTES, MAX_QUEUE_AGE_DAYS, ingestSubmissionSchema, toIngestSubmission, } from "./protocol.js";
@@ -0,0 +1,203 @@
1
+ import { z } from "zod";
2
+ import type { FeedbackRecord } from "../types.js";
3
+ export declare const INGEST_PATHS: {
4
+ readonly enroll: "/v1/enroll";
5
+ readonly feedback: "/v1/feedback";
6
+ readonly renew: "/v1/renew";
7
+ readonly githubStart: "/v1/signin/github/start";
8
+ readonly githubPoll: "/v1/signin/github/poll";
9
+ readonly wellKnown: "/.well-known/mcp-feedback";
10
+ };
11
+ /** What a hub publishes at `<base>/.well-known/mcp-feedback`, so a client can find out what it offers. */
12
+ export interface HubMetadata {
13
+ issuer: string;
14
+ /** Paths relative to the hub's base URL. */
15
+ endpoints: {
16
+ enroll: string;
17
+ feedback: string;
18
+ renew: string;
19
+ };
20
+ /** Ways to sign in, with their endpoints. Empty when the hub only takes anonymous installations and issued tokens. */
21
+ signin: {
22
+ github?: {
23
+ start: string;
24
+ poll: string;
25
+ };
26
+ };
27
+ install_token_ttl_seconds: number;
28
+ user_token_ttl_seconds: number | null;
29
+ }
30
+ /** The most a hub reads of a request body. */
31
+ export declare const MAX_INGEST_BODY_BYTES: number;
32
+ /** How long a report may wait in an installation's queue, and so how old an id a hub accepts. */
33
+ export declare const MAX_QUEUE_AGE_DAYS = 30;
34
+ /**
35
+ * What an installation sends: the submission, plus what the installation itself recorded. Every
36
+ * field is the installation's own account; the hub stamps identity, project, status and time.
37
+ */
38
+ export declare const ingestSubmissionSchema: z.ZodObject<{
39
+ /** The installation's id for the report, reused on every retry so the hub can tell a retry from a new report. */
40
+ id: z.ZodOptional<z.ZodString>;
41
+ /** When the installation built the report. Kept for reference only; the hub records when it received it. */
42
+ created_at: z.ZodOptional<z.ZodString>;
43
+ /** What the server's own attachContext hook recorded. */
44
+ server_context: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
45
+ server_version: z.ZodOptional<z.ZodNullable<z.ZodString>>;
46
+ client_name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
47
+ client_version: z.ZodOptional<z.ZodNullable<z.ZodString>>;
48
+ context: z.ZodOptional<z.ZodObject<{
49
+ references: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>> | z.ZodOptional<z.ZodObject<{
50
+ [k: string]: z.ZodOptional<z.ZodString>;
51
+ }, "strip", z.ZodString, z.objectOutputType<{
52
+ [k: string]: z.ZodOptional<z.ZodString>;
53
+ }, z.ZodString, "strip">, z.objectInputType<{
54
+ [k: string]: z.ZodOptional<z.ZodString>;
55
+ }, z.ZodString, "strip">>>;
56
+ goal: z.ZodOptional<z.ZodString>;
57
+ expected: z.ZodOptional<z.ZodString>;
58
+ actual: z.ZodOptional<z.ZodString>;
59
+ workaround: z.ZodOptional<z.ZodString>;
60
+ suggestion: z.ZodOptional<z.ZodString>;
61
+ tool_calls: z.ZodOptional<z.ZodArray<z.ZodObject<{
62
+ name: z.ZodString;
63
+ arguments_summary: z.ZodOptional<z.ZodString>;
64
+ error: z.ZodOptional<z.ZodString>;
65
+ is_error: z.ZodOptional<z.ZodBoolean>;
66
+ }, "strip", z.ZodTypeAny, {
67
+ name: string;
68
+ arguments_summary?: string | undefined;
69
+ error?: string | undefined;
70
+ is_error?: boolean | undefined;
71
+ }, {
72
+ name: string;
73
+ arguments_summary?: string | undefined;
74
+ error?: string | undefined;
75
+ is_error?: boolean | undefined;
76
+ }>, "many">>;
77
+ repro_steps: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
78
+ excerpt: z.ZodOptional<z.ZodString>;
79
+ metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
80
+ }, "strip", z.ZodTypeAny, {
81
+ expected?: string | undefined;
82
+ references?: Record<string, string> | z.objectOutputType<{
83
+ [k: string]: z.ZodOptional<z.ZodString>;
84
+ }, z.ZodString, "strip"> | undefined;
85
+ goal?: string | undefined;
86
+ actual?: string | undefined;
87
+ workaround?: string | undefined;
88
+ suggestion?: string | undefined;
89
+ tool_calls?: {
90
+ name: string;
91
+ arguments_summary?: string | undefined;
92
+ error?: string | undefined;
93
+ is_error?: boolean | undefined;
94
+ }[] | undefined;
95
+ repro_steps?: string[] | undefined;
96
+ excerpt?: string | undefined;
97
+ metadata?: Record<string, unknown> | undefined;
98
+ }, {
99
+ expected?: string | undefined;
100
+ references?: Record<string, string> | z.objectInputType<{
101
+ [k: string]: z.ZodOptional<z.ZodString>;
102
+ }, z.ZodString, "strip"> | undefined;
103
+ goal?: string | undefined;
104
+ actual?: string | undefined;
105
+ workaround?: string | undefined;
106
+ suggestion?: string | undefined;
107
+ tool_calls?: {
108
+ name: string;
109
+ arguments_summary?: string | undefined;
110
+ error?: string | undefined;
111
+ is_error?: boolean | undefined;
112
+ }[] | undefined;
113
+ repro_steps?: string[] | undefined;
114
+ excerpt?: string | undefined;
115
+ metadata?: Record<string, unknown> | undefined;
116
+ }>>;
117
+ kind: z.ZodEnum<["bug", "tool_failure", "feature_request", "friction", "praise", "other"]>;
118
+ title: z.ZodString;
119
+ body: z.ZodString;
120
+ severity: z.ZodOptional<z.ZodEnum<["blocker", "major", "minor", "none"]>>;
121
+ tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
122
+ }, "strip", z.ZodTypeAny, {
123
+ kind: "bug" | "tool_failure" | "feature_request" | "friction" | "praise" | "other";
124
+ title: string;
125
+ body: string;
126
+ created_at?: string | undefined;
127
+ id?: string | undefined;
128
+ severity?: "blocker" | "major" | "minor" | "none" | undefined;
129
+ tags?: string[] | undefined;
130
+ context?: {
131
+ expected?: string | undefined;
132
+ references?: Record<string, string> | z.objectOutputType<{
133
+ [k: string]: z.ZodOptional<z.ZodString>;
134
+ }, z.ZodString, "strip"> | undefined;
135
+ goal?: string | undefined;
136
+ actual?: string | undefined;
137
+ workaround?: string | undefined;
138
+ suggestion?: string | undefined;
139
+ tool_calls?: {
140
+ name: string;
141
+ arguments_summary?: string | undefined;
142
+ error?: string | undefined;
143
+ is_error?: boolean | undefined;
144
+ }[] | undefined;
145
+ repro_steps?: string[] | undefined;
146
+ excerpt?: string | undefined;
147
+ metadata?: Record<string, unknown> | undefined;
148
+ } | undefined;
149
+ client_name?: string | null | undefined;
150
+ client_version?: string | null | undefined;
151
+ server_version?: string | null | undefined;
152
+ server_context?: Record<string, unknown> | undefined;
153
+ }, {
154
+ kind: "bug" | "tool_failure" | "feature_request" | "friction" | "praise" | "other";
155
+ title: string;
156
+ body: string;
157
+ created_at?: string | undefined;
158
+ id?: string | undefined;
159
+ severity?: "blocker" | "major" | "minor" | "none" | undefined;
160
+ tags?: string[] | undefined;
161
+ context?: {
162
+ expected?: string | undefined;
163
+ references?: Record<string, string> | z.objectInputType<{
164
+ [k: string]: z.ZodOptional<z.ZodString>;
165
+ }, z.ZodString, "strip"> | undefined;
166
+ goal?: string | undefined;
167
+ actual?: string | undefined;
168
+ workaround?: string | undefined;
169
+ suggestion?: string | undefined;
170
+ tool_calls?: {
171
+ name: string;
172
+ arguments_summary?: string | undefined;
173
+ error?: string | undefined;
174
+ is_error?: boolean | undefined;
175
+ }[] | undefined;
176
+ repro_steps?: string[] | undefined;
177
+ excerpt?: string | undefined;
178
+ metadata?: Record<string, unknown> | undefined;
179
+ } | undefined;
180
+ client_name?: string | null | undefined;
181
+ client_version?: string | null | undefined;
182
+ server_version?: string | null | undefined;
183
+ server_context?: Record<string, unknown> | undefined;
184
+ }>;
185
+ export type IngestSubmission = z.infer<typeof ingestSubmissionSchema>;
186
+ /** The wire form of a record built by registerFeedback in an installation. */
187
+ export declare function toIngestSubmission(record: FeedbackRecord): IngestSubmission;
188
+ /** A hub's error body: `{ error: { code, message } }`. The message is written to be shown to an agent. */
189
+ export interface IngestErrorBody {
190
+ error: {
191
+ code: string;
192
+ message: string;
193
+ };
194
+ }
195
+ /** Reads a token's claims without verifying them. Only for an installation's own bookkeeping (when to renew). */
196
+ export declare function unverifiedClaimsOf(token: string): {
197
+ tier: string;
198
+ iat: number;
199
+ exp?: number;
200
+ sub: string;
201
+ } | null;
202
+ /** Reads the project a token names without verifying it. Only for choosing where to keep local state. */
203
+ export declare function unverifiedProjectOf(token: string): string | null;