@guren/server 2.13.0 → 2.15.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.
Files changed (68) hide show
  1. package/dist/{Hash-CzrwKeDp.js → Hash-C8aejmi8.js} +5 -0
  2. package/dist/{McpServiceProvider-D6D9nhgn.js → McpServiceProvider-BawsYjgN.js} +72 -0
  3. package/dist/agent/AgentApprovalRequested.d.ts +59 -0
  4. package/dist/agent/approval.d.ts +295 -0
  5. package/dist/agent/audit-emitter.d.ts +64 -0
  6. package/dist/agent/audit.d.ts +103 -0
  7. package/dist/agent/derive.d.ts +155 -0
  8. package/dist/agent/dispatch.d.ts +165 -0
  9. package/dist/agent/events.d.ts +80 -0
  10. package/dist/agent/meta-tools.d.ts +62 -0
  11. package/dist/agent/public.d.ts +33 -0
  12. package/dist/agent/public.js +2 -0
  13. package/dist/agent/redact.d.ts +55 -0
  14. package/dist/agent/scopes.d.ts +115 -0
  15. package/dist/auth/AuthManager.d.ts +64 -0
  16. package/dist/auth/RequestAuthContext.d.ts +3 -5
  17. package/dist/auth/TokenGuard.d.ts +61 -0
  18. package/dist/auth/api-token.d.ts +25 -5
  19. package/dist/auth/context.d.ts +24 -0
  20. package/dist/auth/index.d.ts +5 -2
  21. package/dist/auth/index.js +2 -2
  22. package/dist/auth/password/DefaultHasher.d.ts +18 -5
  23. package/dist/auth/password/PasswordHasher.d.ts +15 -0
  24. package/dist/auth/password/hash-format.d.ts +19 -0
  25. package/dist/auth/providers/UserProvider.d.ts +7 -0
  26. package/dist/auth/types.d.ts +6 -0
  27. package/dist/{auth-C7sVmYgc.js → auth-DkYoAPVn.js} +431 -151
  28. package/dist/authorization/index.js +1 -1
  29. package/dist/authorization/middleware.d.ts +28 -1
  30. package/dist/{authorization-Dbcuc5ZK.js → authorization-CdfbCj8J.js} +119 -12
  31. package/dist/broadcasting/index.js +1 -1
  32. package/dist/{broadcasting-Dw-FhyjN.js → broadcasting-BwodCA4q.js} +2 -45
  33. package/dist/container/bindings.d.ts +19 -0
  34. package/dist/context-DoD0c7J_.js +26 -0
  35. package/dist/dispatch-erOS9epZ.js +285 -0
  36. package/dist/encryption/index.js +2 -2
  37. package/dist/{encryption-DJtkkhiw.js → encryption-D99Vmls3.js} +4 -1
  38. package/dist/http/dev-assets.d.ts +16 -0
  39. package/dist/http/middleware/auth.d.ts +2 -2
  40. package/dist/http/middleware/capabilities.d.ts +57 -0
  41. package/dist/http/middleware/csrf.d.ts +3 -0
  42. package/dist/http/public-assets.d.ts +10 -0
  43. package/dist/http/request.d.ts +139 -3
  44. package/dist/http/static-documents.d.ts +31 -0
  45. package/dist/index.d.ts +21 -4
  46. package/dist/index.js +1302 -118
  47. package/dist/internal/agent-preflight.d.ts +28 -0
  48. package/dist/internal/request.d.ts +25 -0
  49. package/dist/internal/request.js +2 -0
  50. package/dist/internal/route-path.d.ts +28 -0
  51. package/dist/internal/route-path.js +33 -0
  52. package/dist/internal/zod-compat.d.ts +201 -0
  53. package/dist/internal/zod-compat.js +193 -0
  54. package/dist/internal/zod-json-schema.d.ts +102 -0
  55. package/dist/internal/zod-json-schema.js +461 -0
  56. package/dist/logging/channels/DailyFileChannel.d.ts +0 -2
  57. package/dist/logging/daily-file-path.d.ts +24 -0
  58. package/dist/logging/index.d.ts +1 -0
  59. package/dist/logging/index.js +2 -2
  60. package/dist/{logging-CPaRMuPP.js → logging-B-kngi3q.js} +61 -18
  61. package/dist/mcp/create-mcp-server.d.ts +29 -0
  62. package/dist/mcp/index.js +1 -1
  63. package/dist/mvc/Controller.d.ts +20 -0
  64. package/dist/mvc/Router.d.ts +53 -0
  65. package/dist/request-CVQwpu2J.js +129 -0
  66. package/dist/runtime/index.js +94 -15
  67. package/dist/{vite-manifest-gdONBsM3.js → vite-manifest-w_RSOvQW.js} +1 -1
  68. package/package.json +22 -2
package/dist/index.js CHANGED
@@ -1,27 +1,32 @@
1
- import { a as setBroadcastManager, c as PresenceChannel, d as flattenRequestQueries, f as formatValidationErrors, i as getBroadcastManager, l as PrivateChannel, n as BroadcastManager, o as RedisDriver, p as parseRequestPayload, r as createBroadcastManager, s as MemoryDriver, t as createTypedBroadcaster, u as Channel } from "./broadcasting-Dw-FhyjN.js";
1
+ import { a as parseRequestPayload, i as parseRequestBody, n as flattenRequestQueries, o as parseRequestUploads, r as formatValidationErrors, t as asRecord } from "./request-CVQwpu2J.js";
2
2
  import { t as HttpException } from "./HttpException-BkS3euNG.js";
3
3
  import { n as ValidationException } from "./errors-BgeOl_DC.js";
4
+ import { _ as setGate, a as withAuthorization, b as mergeCapabilities, c as Gate, d as can, f as cannot, h as getGate, i as resourceAbilityForMethod, l as Response$1, m as defineGate, n as authorizeMiddleware, o as Policy, p as createGate, r as authorizeResourceMiddleware, s as definePolicy, t as authorizeAllMiddleware, u as authorize, v as AuthorizationException, x as stampCapabilities, y as capabilitiesOf } from "./authorization-CdfbCj8J.js";
5
+ import { a as mapToolResponse, i as describeBuildFailure, n as advertisesStructuredOutput, r as buildToolRequest, s as AGENT_PREFLIGHT_VERDICT_HEADER, t as PREFLIGHT_ARGUMENT } from "./dispatch-erOS9epZ.js";
4
6
  import { t as trimSlashes } from "./trim-slashes-ZJ_VsY5s.js";
7
+ import { PATH_PARAM_PATTERN, extractPathParamNames } from "./internal/route-path.js";
5
8
  import { a as getRegisteredJobs, c as setQueueDriver, d as getContainer, f as resolve, i as getQueueDriver, l as Container, n as clearJobRegistry, o as registerJob, p as setContainer, r as getJob, s as resolveJobName, t as Job, u as createContainer } from "./Job-BVT813DO.js";
6
9
  import { n as ProviderManager, r as ServiceProvider } from "./loopback-guard-D0Kc7-xc.js";
7
10
  import { a as generateAppKey, c as parseAppKey, i as encodeDerivedKey, l as parsePreviousAppKeys, n as deriveAppKey, o as getAppKeyringFromEnv, r as deriveAppKeyring, s as normalizeAppKey, t as MessageSigner } from "./MessageSigner-Bd25ZJAV.js";
8
- import { A as sanitizeOAuthRedirect, B as revokeAllApiTokens, C as createGitHubOAuthProviderConfig, D as exchangeOAuthCode, E as createOAuthState, F as createBearerTokenMiddleware, G as verifyApiToken, H as tokenCan, I as getApiToken, J as normalizeRedirectTarget, K as hostMatchesAllowlist, L as getApiTokenOrFail, M as API_TOKEN_KEY, N as MemoryApiTokenStore, O as fetchOAuthUserProfile, P as createApiToken, R as getUserApiTokens, S as createDiscordOAuthProviderConfig, T as createOAuthManager, U as tokenCanAll, V as revokeApiToken, W as tokenCanAny, X as SessionGuard, Y as AuthManager, _ as MemoryOAuthStateStore, a as isEmailVerified, at as BaseUserProvider, b as buildOAuthAuthorizeUrl, c as verifyEmailToken, ct as MemorySessionStore, d as completePasswordReset, f as createPasswordResetToken, g as NodeHasher, h as AuthenticatableModel, i as createEmailVerificationToken, it as ModelUserProvider, j as verifyOAuthState, k as parseOAuthRedirectUrl, l as MemoryPasswordResetStore, lt as createSessionMiddleware, m as verifyPasswordResetToken, n as buildVerificationUrl, o as parseVerificationUrl, ot as ScryptHasher, p as parsePasswordResetUrl, q as isAppRelativePath, r as completeEmailVerification, s as requireVerifiedEmail, st as AuthenticationException, t as MemoryEmailVerificationStore, u as buildPasswordResetUrl, ut as getSessionFromContext, v as OAUTH_SESSION_BINDING_KEY, w as createGoogleOAuthProviderConfig, x as buildOAuthRedirectUrl, y as OAuthManager, z as parseApiToken } from "./auth-C7sVmYgc.js";
9
- import { a as md5, c as sha256, d as verifyPassword, i as hmac, l as sha512, n as hash, o as needsRehash, r as hashPassword, s as secureCompare, t as check, u as verifyHmac } from "./Hash-CzrwKeDp.js";
11
+ import { A as verifyOAuthState, B as getApiToken, C as createGoogleOAuthProviderConfig, D as fetchOAuthUserProfile, E as exchangeOAuthCode, F as TokenGuard, G as readBearerToken, H as getUserApiTokens, I as API_TOKEN_KEY, J as tokenCan, K as revokeAllApiTokens, L as MemoryApiTokenStore, M as isAppRelativePath, N as normalizeRedirectTarget, O as parseOAuthRedirectUrl, P as AuthManager, Q as SessionGuard, R as createApiToken, S as createGitHubOAuthProviderConfig, T as createOAuthState, U as hasBearerHeader, V as getApiTokenOrFail, W as parseApiToken, X as tokenCanAny, Y as tokenCanAll, Z as verifyApiToken, _ as OAUTH_SESSION_BINDING_KEY, a as isEmailVerified, b as buildOAuthRedirectUrl, c as verifyEmailToken, ct as DefaultHasher, d as completePasswordReset, dt as AuthenticationException, f as createPasswordResetToken, ft as MemorySessionStore, g as MemoryOAuthStateStore, h as AuthenticatableModel, i as createEmailVerificationToken, j as hostMatchesAllowlist, k as sanitizeOAuthRedirect, l as MemoryPasswordResetStore, lt as NodeHasher, m as verifyPasswordResetToken, mt as getSessionFromContext, n as buildVerificationUrl, o as parseVerificationUrl, ot as ModelUserProvider, p as parsePasswordResetUrl, pt as createSessionMiddleware, q as revokeApiToken, r as completeEmailVerification, s as requireVerifiedEmail, st as BaseUserProvider, t as MemoryEmailVerificationStore, u as buildPasswordResetUrl, ut as ScryptHasher, v as OAuthManager, w as createOAuthManager, x as createDiscordOAuthProviderConfig, y as buildOAuthAuthorizeUrl, z as createBearerTokenMiddleware } from "./auth-DkYoAPVn.js";
12
+ import { a as md5, c as sha256, d as verifyPassword, i as hmac, l as sha512, n as hash, o as needsRehash, r as hashPassword, s as secureCompare, t as check, u as verifyHmac } from "./Hash-C8aejmi8.js";
13
+ import { n as getAuthContext, t as AUTH_CONTEXT_KEY } from "./context-DoD0c7J_.js";
10
14
  import { r as isMcpEndpointEnabled } from "./endpoint-D-20PiHY.js";
11
15
  import { n as isHotReloadRuntime, r as matchingOpenParen, t as claimHotDisposable } from "./hot-disposables-WsTX2ySN.js";
12
16
  import { a as setI18n, c as tryGetI18n, d as getPluralizationRule, f as pluralizationRules, i as getI18n, l as JsonLoader, n as I18nManager, o as t, p as selectPluralForm, r as createI18n, s as tc, t as MemoryLoader, u as Translator } from "./i18n-mcWi7LCd.js";
13
- import { _ as AuthorizationException, a as Policy, c as Response$1, d as cannot, f as createGate, g as setGate, i as withAuthorization, l as authorize, m as getGate, n as authorizeMiddleware, o as definePolicy, p as defineGate, r as authorizeResourceMiddleware, s as Gate, t as authorizeAllMiddleware, u as can } from "./authorization-Dbcuc5ZK.js";
14
- import { _ as parseImportMap, c as isViteProduction, d as startViteDevServer, g as DEFAULT_DEV_STYLES_ENTRY, h as logDevServerBanner, i as clientManifestCandidates, l as loadViteManifest, m as isWildcardHost, n as INJECTED_CLIENT_MANIFEST_SOURCE, o as getManifestFile, p as formatHostPort, r as PUBLIC_ASSETS_URL_PREFIX, s as injectedClientManifest, u as normalizeDevServerUrl } from "./vite-manifest-gdONBsM3.js";
17
+ import { _ as parseImportMap, c as isViteProduction, d as startViteDevServer, g as DEFAULT_DEV_STYLES_ENTRY, h as logDevServerBanner, i as clientManifestCandidates, l as loadViteManifest, m as isWildcardHost, n as INJECTED_CLIENT_MANIFEST_SOURCE, o as getManifestFile, p as formatHostPort, r as PUBLIC_ASSETS_URL_PREFIX, s as injectedClientManifest, u as normalizeDevServerUrl } from "./vite-manifest-w_RSOvQW.js";
15
18
  import { r as isDocsViewerEnabled } from "./endpoint-D6GIqOpe.js";
16
19
  import { t as jsx_runtime_exports } from "./jsx-runtime.js";
20
+ import { readObjectSchema, toJsonSchema } from "./internal/zod-json-schema.js";
17
21
  import { a as RequestFinished, c as UserLoggedOut, d as createEventManager, f as Event, i as JobProcessed, l as Listener, n as ApplicationStarted, o as RequestReceived, r as JobFailed, s as UserAuthenticated, t as ApplicationShutdown, u as EventManager } from "./events-aIH_bWRx.js";
22
+ import { a as NotificationManager, c as setNotificationManager, d as getNotification, f as registerNotification, i as MailChannel, l as resolveNotifiableType, n as SlackChannel, o as createNotificationManager, p as Notification, r as DatabaseChannel, s as getNotificationManager, t as MemoryChannel, u as clearNotificationRegistry } from "./notifications-BGqmUNZ8.js";
18
23
  import { a as RedisStore, i as FileStore, n as createCacheManager, o as MemoryStore, r as TaggedCache, t as CacheManager } from "./cache-BYnZf2FR.js";
19
24
  import { a as processJob, c as RedisDriver$1, i as Worker, l as SyncDriver, n as createQueueManager, o as SqsDriver, r as FailedJobReporter, s as createSqsAdapter, t as QueueManager, u as MemoryDriver$1 } from "./queue-CXrRK85G.js";
20
25
  import { a as MailManager, c as MemoryTransport, i as setMailManager, l as ResendTransport, n as getMailManager, o as createMailManager, r as mail, s as LogTransport, t as Mail, u as SmtpTransport } from "./mail-DfEfSQEr.js";
21
- import { a as DailyFileChannel, c as Logger, i as setLogManager, l as filterSensitiveData, n as createLogManager, o as FileChannel, r as getLogManager, s as ConsoleChannel, t as LogManager, u as LOG_LEVEL_PRIORITY } from "./logging-CPaRMuPP.js";
22
- import { a as NotificationManager, c as setNotificationManager, d as getNotification, f as registerNotification, i as MailChannel, l as resolveNotifiableType, n as SlackChannel, o as createNotificationManager, p as Notification, r as DatabaseChannel, s as getNotificationManager, t as MemoryChannel, u as clearNotificationRegistry } from "./notifications-BGqmUNZ8.js";
26
+ import { a as DailyFileChannel, c as matchDailyFileDate, d as Logger, f as filterSensitiveData, i as setLogManager, l as FileChannel, n as createLogManager, o as dailyFileDateStamp, p as LOG_LEVEL_PRIORITY, r as getLogManager, s as dailyFilePath, t as LogManager, u as ConsoleChannel } from "./logging-B-kngi3q.js";
27
+ import { a as setBroadcastManager, c as PresenceChannel, i as getBroadcastManager, l as PrivateChannel, n as BroadcastManager, o as RedisDriver, r as createBroadcastManager, s as MemoryDriver, t as createTypedBroadcaster, u as Channel } from "./broadcasting-BwodCA4q.js";
23
28
  import { a as random, c as randomHex, d as sample, f as shuffle, i as pick, l as randomInt, m as uuid, n as generatePassword, o as randomBase64, p as urlSafeToken, r as generateSlug, s as randomBase64Url, t as generateOtp, u as randomString } from "./Random-DbIJ22KQ.js";
24
- import { a as decrypt, c as getEncrypter, i as createEncrypter, l as setEncrypter, n as verifySignedUrl, o as encrypt, r as Encrypter, s as generateKey, t as signUrl } from "./encryption-DJtkkhiw.js";
29
+ import { a as decrypt, c as getEncrypter, i as createEncrypter, l as setEncrypter, n as verifySignedUrl, o as encrypt, r as Encrypter, s as generateKey, t as signUrl } from "./encryption-D99Vmls3.js";
25
30
  import { a as LocalDriver, i as S3Driver, n as createStorageManager, o as warnOnce, r as MemoryDriver$2, t as StorageManager } from "./storage-TLD9t0Q2.js";
26
31
  import { a as CacheCheck, c as HealthManager, i as StorageCheck, l as createHealthManager, n as customCheck, o as RedisCheck, r as MemoryCheck, s as DatabaseCheck, t as CustomCheck, u as HealthCheck } from "./health-VWdWXRwh.js";
27
32
  import { a as ScheduledTask, c as isDue, d as parseCron, f as toTimezone, i as Schedule, l as isDueInTimezone, n as createScheduler, o as getNextOccurrence, r as PendingSchedule, s as getNextOccurrences, t as Scheduler, u as matchesCron } from "./scheduling-CPiEdtQd.js";
@@ -104,33 +109,6 @@ function mountRoute(app, method, path, ...handlers) {
104
109
  app.on(method, path, ...handlers);
105
110
  }
106
111
  //#endregion
107
- //#region src/http/middleware/capabilities.ts
108
- /**
109
- * Internal security-capability marker (RFC 0007).
110
- *
111
- * Built-in middleware factories stamp the handlers they return so tooling
112
- * that holds the real function objects (the router registry, `guren audit`
113
- * via route loading) can recognize what a handler enforces without name
114
- * heuristics. `Symbol.for()` keeps the key identical across duplicated
115
- * `@guren/server` copies in one process.
116
- *
117
- * Deliberately not part of the public API: nothing here is exported from
118
- * the package root, and the shape may change in any release. A public
119
- * `defineMiddleware` integration is future work in RFC 0007.
120
- */
121
- const CAPABILITIES = Symbol.for("guren.capabilities");
122
- function stampCapabilities(handler, capabilities) {
123
- Object.defineProperty(handler, CAPABILITIES, {
124
- value: capabilities,
125
- enumerable: false
126
- });
127
- return handler;
128
- }
129
- function capabilitiesOf(handler) {
130
- if (typeof handler !== "function") return void 0;
131
- return handler[CAPABILITIES];
132
- }
133
- //#endregion
134
112
  //#region src/mvc/Router.ts
135
113
  function normalizeModelBinding(binding) {
136
114
  if (Array.isArray(binding)) {
@@ -146,6 +124,19 @@ async function resolveModelBinding({ model, key }, value) {
146
124
  return key === void 0 ? model.findOrFail(value) : model.findOrFail(value, key);
147
125
  }
148
126
  /**
127
+ * One immutable snapshot of agent metadata, taken when the metadata is
128
+ * attached and again when `definitions()` hands it out — so neither a caller
129
+ * mutating its options object after registration nor a consumer mutating a
130
+ * definition can change the agent metadata the router actually holds. The
131
+ * claim is scoped to this field: other definition fields (`schemas`, the
132
+ * spread OpenAPI metadata) alias the registry. Plain data end to end, so
133
+ * `structuredClone` keeps future nested fields covered without a
134
+ * hand-maintained field list.
135
+ */
136
+ function cloneAgentMetadata(metadata) {
137
+ return structuredClone(metadata);
138
+ }
139
+ /**
149
140
  * Group scopes are unwound synchronously, so an `async` callback registers its
150
141
  * routes after the scope has already been popped — silently dropping the
151
142
  * prefix or middleware the group was opened with. The callback type says
@@ -297,12 +288,23 @@ var Router = class {
297
288
  resource(path, controller, options = {}) {
298
289
  const baseName = options.name ?? path.replace(/^\//u, "").replace(/\//gu, ".");
299
290
  const paramName = options.param ?? "id";
300
- const { only, except } = options;
301
- for (const { method, suffix, httpMethod } of RESOURCE_ACTIONS) {
291
+ const { only, except, agent } = options;
292
+ const registrable = /* @__PURE__ */ new Set();
293
+ for (const { method } of RESOURCE_ACTIONS) {
302
294
  if (only && !only.includes(method)) continue;
303
295
  if (except?.includes(method)) continue;
296
+ if (typeof controller.prototype[method] === "function") registrable.add(method);
297
+ }
298
+ if (agent) {
299
+ const orphaned = Object.keys(agent).filter((action) => agent[action] !== void 0 && !registrable.has(action));
300
+ if (orphaned.length > 0) throw new Error(`Router.resource('${path}'): agent metadata declared for ${orphaned.map((a) => `"${a}"`).join(", ")}, but no such route was registered (excluded via only/except, or missing from the controller). Agent metadata for a tool that cannot exist is a wiring mistake.`);
301
+ }
302
+ for (const { method, suffix, httpMethod } of RESOURCE_ACTIONS) {
303
+ if (!registrable.has(method)) continue;
304
304
  const routePath = path + suffix.replace(":param", `:${paramName}`);
305
- if (typeof controller.prototype[method] === "function") this[httpMethod](routePath, [controller, method]).name(`${baseName}.${method}`);
305
+ const builder = this[httpMethod](routePath, [controller, method]).name(`${baseName}.${method}`);
306
+ const agentMetadata = agent?.[method];
307
+ if (agentMetadata) builder.agent(agentMetadata);
306
308
  }
307
309
  return this;
308
310
  }
@@ -312,17 +314,12 @@ var Router = class {
312
314
  const handler = resolveHandler(route.handler, this.modelBindings, options.container, route.bindings, route.path);
313
315
  const contractMiddleware = createContractValidationMiddleware(route);
314
316
  const inlineMiddlewares = [...route.scopedMiddlewares, ...route.middlewares];
315
- const allMiddlewares = contractMiddleware ? [
316
- ...resolvedMiddlewares,
317
- ...inlineMiddlewares,
318
- contractMiddleware,
319
- handler
320
- ] : [
321
- ...resolvedMiddlewares,
322
- ...inlineMiddlewares,
323
- handler
324
- ];
325
- mountRoute(app, route.method, route.path, ...allMiddlewares);
317
+ const preflightMiddleware = createAgentPreflightMiddleware(route, () => this.aggregateCapabilities(route.routeMiddlewareNames, inlineMiddlewares));
318
+ const chain = [...resolvedMiddlewares, ...inlineMiddlewares];
319
+ if (contractMiddleware) chain.push(contractMiddleware);
320
+ if (preflightMiddleware) chain.push(preflightMiddleware);
321
+ chain.push(handler);
322
+ mountRoute(app, route.method, route.path, ...chain);
326
323
  }
327
324
  }
328
325
  clear() {
@@ -337,12 +334,13 @@ var Router = class {
337
334
  this.modelBindings.clear();
338
335
  }
339
336
  definitions() {
340
- return this.registry.map(({ method, path, name, schemas, resource, openapi, routeMiddlewareNames, middlewares, scopedMiddlewares, handler, bindings }) => ({
337
+ return this.registry.map(({ method, path, name, schemas, resource, openapi, routeMiddlewareNames, middlewares, scopedMiddlewares, handler, bindings, agent }) => ({
341
338
  method,
342
339
  path,
343
340
  name,
344
341
  schemas,
345
342
  resource: serializeResourceHint(resource),
343
+ agent: agent ? cloneAgentMetadata(agent) : void 0,
346
344
  middlewareNames: [...routeMiddlewareNames],
347
345
  hasInlineMiddleware: middlewares.length > 0,
348
346
  capabilities: this.aggregateCapabilities(routeMiddlewareNames, [...scopedMiddlewares, ...middlewares]),
@@ -405,26 +403,30 @@ var Router = class {
405
403
  * thrown: `definitions()` must stay side-effect-free for introspection of
406
404
  * routers that never mount (audit, codegen), and an unresolvable alias
407
405
  * simply contributes no capabilities.
406
+ *
407
+ * This walks the chain; the rules for combining what it finds live with the
408
+ * capability type, in `mergeCapabilities`.
408
409
  */
409
- aggregateCapabilities(names, inline, seen) {
410
+ aggregateCapabilities(names, inline, seen, seenStamps) {
410
411
  const aggregated = {};
411
412
  const visited = seen ?? /* @__PURE__ */ new Set();
412
- const absorb = (capabilities) => {
413
- const auth = capabilities?.authentication;
414
- if (!auth) return;
415
- if (!aggregated.authentication || auth.mode === "required") aggregated.authentication = auth;
413
+ const merged = seenStamps ?? /* @__PURE__ */ new Set();
414
+ const absorbStamp = (stamp) => {
415
+ if (!stamp || merged.has(stamp)) return;
416
+ merged.add(stamp);
417
+ mergeCapabilities(aggregated, stamp);
416
418
  };
417
419
  for (const name of names) {
418
420
  if (visited.has(name)) continue;
419
421
  visited.add(name);
420
422
  const groupNames = this.middlewareGroups.get(name);
421
423
  if (groupNames) {
422
- absorb(this.aggregateCapabilities(groupNames, [], visited));
424
+ mergeCapabilities(aggregated, this.aggregateCapabilities(groupNames, [], visited, merged));
423
425
  continue;
424
426
  }
425
- absorb(capabilitiesOf(this.middlewareAliases.get(name)));
427
+ absorbStamp(capabilitiesOf(this.middlewareAliases.get(name)));
426
428
  }
427
- for (const handler of inline) absorb(capabilitiesOf(handler));
429
+ for (const handler of inline) absorbStamp(capabilitiesOf(handler));
428
430
  return aggregated;
429
431
  }
430
432
  resolveMiddlewareNames(names, seen) {
@@ -465,6 +467,7 @@ function applyRouteContract(route, options) {
465
467
  deprecated: options.deprecated
466
468
  };
467
469
  if (options.bind) route.bindings = new Map(Object.entries(options.bind).map(([param, binding]) => [param, normalizeModelBinding(binding)]));
470
+ if (options.agent) route.agent = cloneAgentMetadata(options.agent);
468
471
  }
469
472
  var RouterMiddlewareGroupBuilder = class {
470
473
  router;
@@ -513,14 +516,14 @@ function createRouteBuilder(route, namedRoutes) {
513
516
  route.routeMiddlewareNames.push(...names);
514
517
  route.middlewares.push(...handlers);
515
518
  return this;
519
+ },
520
+ agent(metadata) {
521
+ if (route.agent) throw new Error(`Route ${route.method} ${route.path} already carries agent metadata (declared via route options or an earlier .agent() call). Declare it once.`);
522
+ route.agent = cloneAgentMetadata(metadata);
523
+ return this;
516
524
  }
517
525
  };
518
526
  }
519
- const PATH_PARAM_PATTERN = /(^|\/):([A-Za-z0-9_-]+\*?)(?:\{[^{}]*\{[^{}]*\}[^{}]*\}|\{[^{}]*\})?\??/gu;
520
- /** Param labels in path order, with constraints and modifiers dropped. */
521
- function extractPathParamNames(path) {
522
- return Array.from(path.matchAll(PATH_PARAM_PATTERN), (match) => match[2]);
523
- }
524
527
  function substituteParams(path, params) {
525
528
  return path.replace(PATH_PARAM_PATTERN, (match, prefix, key) => {
526
529
  if (!Object.prototype.hasOwnProperty.call(params, key)) return match;
@@ -533,7 +536,7 @@ function createContractHandler(path, options, handler) {
533
536
  if (params instanceof Response) return params;
534
537
  const query = parseRouteSegment(options.query, flattenRequestQueries(ctx), 422);
535
538
  if (query instanceof Response) return query;
536
- const payload = options.body ? await parseRequestPayload(ctx) : {};
539
+ const payload = options.body ? await parseRequestBody(ctx) : {};
537
540
  const body = parseRouteSegment(options.body, payload, 422);
538
541
  if (body instanceof Response) return body;
539
542
  const result = await handler({
@@ -603,6 +606,67 @@ function throwOnInvalid(schema, data) {
603
606
  const result = schema.safeParse(data);
604
607
  if (!result.success) throw ValidationException.withMessages(formatValidationErrors(result.error));
605
608
  }
609
+ /**
610
+ * The preflight seam: everything a request must pass before the handler runs,
611
+ * reported instead of executed.
612
+ *
613
+ * Mounted last, so the whole chain in front of it has already run — an
614
+ * unauthenticated call is a 401 and an unauthorized one a 403 from the real
615
+ * middleware, not from a second copy of the rule here. Reaching this point is
616
+ * itself the positive half of the verdict; what it adds is validating the
617
+ * contract the *tool advertised* and then stopping, so an agent can ask "would
618
+ * this be allowed" without the write happening.
619
+ *
620
+ * **Only routes declaring `.agent()` honour the header.** A non-agent route
621
+ * ignores it completely, so no ordinary endpoint changes behaviour on a header
622
+ * an arbitrary client can set; the surface is exactly what RFC 0016 defines.
623
+ *
624
+ * Body validation happens *here* rather than being left to the controller's
625
+ * `validateBody()`: the chain stops before the controller by construction, so
626
+ * the alternative is a verdict that silently never checked the body — the
627
+ * shape of the request an agent is most likely to get wrong. Reading the body
628
+ * is safe precisely because this branch does not call `next()`, so nothing
629
+ * downstream reads the stream after it.
630
+ *
631
+ * What it cannot check, it says. A route may authorize inside its action
632
+ * (`await this.authorize(...)`), which `guren check` accepts as satisfying the
633
+ * agent-route authorization rule — and which this seam structurally cannot
634
+ * reach, because the action never runs. So `allowed: true` means "passed
635
+ * everything that runs before the handler", and `unverified` names what a real
636
+ * call would still evaluate. Reporting a bare `allowed: true` for a route
637
+ * whose only authorization lives in its body would be the verdict claiming a
638
+ * check it never made.
639
+ */
640
+ function createAgentPreflightMiddleware(route, capabilities) {
641
+ if (!route.agent) return null;
642
+ const schemas = route.schemas;
643
+ const unverified = capabilities().authorization === void 0 ? ["authorization"] : [];
644
+ return async (c, next) => {
645
+ if (c.req.header("X-Guren-Agent-Preflight") === void 0) return next();
646
+ const validated = [];
647
+ if (schemas?.params) {
648
+ throwOnInvalid(schemas.params, c.req.param());
649
+ validated.push("params");
650
+ }
651
+ if (schemas?.query) {
652
+ throwOnInvalid(schemas.query, flattenRequestQueries(c));
653
+ validated.push("query");
654
+ }
655
+ if (schemas?.body) {
656
+ throwOnInvalid(schemas.body, await parseRequestBody(c));
657
+ validated.push("body");
658
+ }
659
+ c.header(AGENT_PREFLIGHT_VERDICT_HEADER, "1");
660
+ return c.json({
661
+ preflight: true,
662
+ allowed: true,
663
+ route: route.name,
664
+ validated,
665
+ unverified,
666
+ message: "Preflight only: the request passed this route's middleware" + (validated.length > 0 ? ` and its ${validated.join(", ")} schema${validated.length > 1 ? "s" : ""}` : "") + ". The handler did not run. The route's own middleware did run, so any effect a middleware on this route has of its own has already happened." + (unverified.length > 0 ? " No authorization middleware was found on this route, so any check inside the handler itself was not evaluated." : "")
667
+ });
668
+ };
669
+ }
606
670
  function createContractValidationMiddleware(route) {
607
671
  if (!isControllerAction(route.handler)) return null;
608
672
  const schemas = route.schemas;
@@ -611,7 +675,8 @@ function createContractValidationMiddleware(route) {
611
675
  if (schemas.params) throwOnInvalid(schemas.params, c.req.param());
612
676
  if (schemas.query) throwOnInvalid(schemas.query, flattenRequestQueries(c));
613
677
  await next();
614
- if (schemas.output && c.res) {
678
+ const isSuccess = c.res !== void 0 && c.res.status >= 200 && c.res.status < 300;
679
+ if (schemas.output && isSuccess && c.res.headers.get("X-Guren-Agent-Preflight-Verdict") === null) {
615
680
  let sourceBody;
616
681
  let parsedBody;
617
682
  try {
@@ -731,10 +796,13 @@ function serializeBindings(path, routeBindings, routerBindings) {
731
796
  function serializeResourceHint(hint) {
732
797
  if (hint === void 0) return;
733
798
  if (typeof hint === "function") return hint.name || void 0;
799
+ if (typeof hint !== "object" || hint === null) return;
734
800
  if (Array.isArray(hint)) {
735
801
  const inner = serializeResourceHint(hint[0]);
736
802
  return inner === void 0 ? void 0 : [inner];
737
803
  }
804
+ const proto = Object.getPrototypeOf(hint);
805
+ if (proto !== Object.prototype && proto !== null) return;
738
806
  const entries = [];
739
807
  for (const [key, value] of Object.entries(hint)) {
740
808
  const serialized = serializeResourceHint(value);
@@ -748,7 +816,7 @@ function isControllerAction(action) {
748
816
  }
749
817
  function isRouteContractOptions(value) {
750
818
  if (!value || typeof value !== "object" || Array.isArray(value)) return false;
751
- return "params" in value || "query" in value || "body" in value || "output" in value || "resource" in value || "bind" in value || "name" in value || "middlewares" in value || "summary" in value || "description" in value || "tags" in value || "operationId" in value || "deprecated" in value;
819
+ return "params" in value || "query" in value || "body" in value || "output" in value || "resource" in value || "bind" in value || "name" in value || "middlewares" in value || "agent" in value || "summary" in value || "description" in value || "tags" in value || "operationId" in value || "deprecated" in value;
752
820
  }
753
821
  function joinPaths(prefixStack, path) {
754
822
  const segments = [...prefixStack, path].filter(Boolean).map(trimSlashes).filter(Boolean);
@@ -942,6 +1010,36 @@ function isMcpEndpointRequest(path) {
942
1010
  return path === "/_guren/mcp" && isMcpEndpointEnabled();
943
1011
  }
944
1012
  /**
1013
+ * A bearer-authenticated request that carries no cookies at all (RFC 0016
1014
+ * §3). CSRF defends cookie ambient authority — a browser attaching the
1015
+ * victim's cookies to a request the victim never made. A request that
1016
+ * authenticates by `Authorization: Bearer` and sends no `Cookie` header has
1017
+ * none to attach: the token is the client's own credential, deliberately
1018
+ * presented, and a browser cannot strip its cookies from a cross-site
1019
+ * request. Agent tool dispatch is the intended caller — it synthesizes
1020
+ * cookie-less bearer requests by construction.
1021
+ *
1022
+ * The predicate is the raw `Cookie` header, deliberately not the loaded
1023
+ * session. Ambient authority *requires a cookie*, so the header's absence is
1024
+ * proof by itself — independent of where this middleware sits relative to
1025
+ * the session mount. A session-based predicate reads as more precise and is
1026
+ * weaker on both edges: mounted before the session middleware it sees no
1027
+ * session and fails open for a cookie-carrying victim browser, and an
1028
+ * intermediate middleware that writes one value into a fresh session turns a
1029
+ * genuinely cookie-less client into a 403. Any cookie — even one this app
1030
+ * never reads — therefore keeps verification on; a bearer client that wants
1031
+ * the skip sends none, which is what every non-browser client does.
1032
+ *
1033
+ * Bearer detection is `hasBearerHeader`, the same predicate
1034
+ * `AuthManager.resolveGuardName` routes a request to the token guard by, so
1035
+ * this rule and token authentication cannot disagree about what a bearer
1036
+ * request is.
1037
+ */
1038
+ function isBearerRequestWithoutCookies(ctx) {
1039
+ if (!hasBearerHeader(ctx)) return false;
1040
+ return ctx.req.header("Cookie") === void 0;
1041
+ }
1042
+ /**
945
1043
  * Get the request's CSRF token.
946
1044
  *
947
1045
  * Signed token bound to the session when a stable one exists, otherwise a
@@ -1049,6 +1147,9 @@ async function getTokenFromRequest(ctx) {
1049
1147
  * those sessions expire
1050
1148
  * - Exempts the dev-only MCP endpoint while it is mounted, since agent
1051
1149
  * clients cannot fetch a token first (it guards local-only access instead)
1150
+ * - Skips verification for `Authorization: Bearer` requests that carry no
1151
+ * cookies (RFC 0016) — token clients authenticate per request and hold no
1152
+ * cookie ambient authority for CSRF to defend
1052
1153
  *
1053
1154
  * `cookie: false` disables the `XSRF-TOKEN` cookie for apps that deliver the
1054
1155
  * token themselves (meta tag / form field). Session-bound tokens still
@@ -1087,7 +1188,7 @@ function createCsrfMiddleware(options = {}) {
1087
1188
  settleCookie(ctx);
1088
1189
  return;
1089
1190
  }
1090
- if (isExcluded$1(path, exclude) || isMcpEndpointRequest(path)) {
1191
+ if (isExcluded$1(path, exclude) || isMcpEndpointRequest(path) || isBearerRequestWithoutCookies(ctx)) {
1091
1192
  await next();
1092
1193
  settleCookie(ctx);
1093
1194
  return;
@@ -1137,7 +1238,7 @@ function getValidatedData(ctx) {
1137
1238
  function validateRequest(schema, options = {}) {
1138
1239
  const { onError, status = 422, fallbackMessage = "The provided data is invalid." } = options;
1139
1240
  return async (ctx, next) => {
1140
- const payload = await parseRequestPayload(ctx);
1241
+ const payload = await parseRequestBody(ctx);
1141
1242
  const result = schema.safeParse(payload);
1142
1243
  if (!result.success) {
1143
1244
  const errors = formatValidationErrors(result.error, fallbackMessage);
@@ -1164,7 +1265,7 @@ function validateRequestWith(schemaFactory, options = {}) {
1164
1265
  const { onError, status = 422, fallbackMessage = "The provided data is invalid." } = options;
1165
1266
  return async (ctx, next) => {
1166
1267
  const schema = schemaFactory(ctx);
1167
- const payload = await parseRequestPayload(ctx);
1268
+ const payload = await parseRequestBody(ctx);
1168
1269
  const result = schema.safeParse(payload);
1169
1270
  if (!result.success) {
1170
1271
  const errors = formatValidationErrors(result.error, fallbackMessage);
@@ -2040,7 +2141,6 @@ function jsonResponse(data, status = 200) {
2040
2141
  }
2041
2142
  //#endregion
2042
2143
  //#region src/http/middleware/auth.ts
2043
- const AUTH_CONTEXT_KEY = "guren:auth";
2044
2144
  const TESTING_USER_HEADER = "x-testing-user";
2045
2145
  function resolveTestingUser(ctx) {
2046
2146
  if (!process.env.GUREN_TESTING) return null;
@@ -2081,13 +2181,10 @@ function attachAuthContext(contextFactory) {
2081
2181
  await next();
2082
2182
  };
2083
2183
  }
2084
- function resolveAuth(ctx) {
2085
- return ctx.get(AUTH_CONTEXT_KEY);
2086
- }
2087
2184
  function requireAuthenticated(options = {}) {
2088
2185
  const { redirectTo, status = 401, responseFactory } = options;
2089
2186
  return stampCapabilities(async (ctx, next) => {
2090
- const auth = resolveAuth(ctx);
2187
+ const auth = getAuthContext(ctx);
2091
2188
  if (!auth) throw new Error("Auth context has not been attached. Did you register the auth middleware?");
2092
2189
  if (!await auth.check()) {
2093
2190
  if (redirectTo) return ctx.redirect(redirectTo);
@@ -2100,7 +2197,7 @@ function requireAuthenticated(options = {}) {
2100
2197
  function requireGuest(options = {}) {
2101
2198
  const { redirectTo, status = 403, responseFactory } = options;
2102
2199
  return stampCapabilities(async (ctx, next) => {
2103
- const auth = resolveAuth(ctx);
2200
+ const auth = getAuthContext(ctx);
2104
2201
  if (!auth) throw new Error("Auth context has not been attached. Did you register the auth middleware?");
2105
2202
  if (!await auth.guest()) {
2106
2203
  if (redirectTo) return ctx.redirect(redirectTo);
@@ -2324,7 +2421,7 @@ var ExceptionHandler = class {
2324
2421
  */
2325
2422
  async reportException(error) {
2326
2423
  if (this.shouldNotReport(error)) return;
2327
- if (this.reporters.length === 0) console.error("Unhandled exception:", error);
2424
+ if (this.reporters.length === 0 && resolveExceptionStatus(error) >= 500) console.error("Unhandled exception:", error);
2328
2425
  for (const reporter of this.reporters) try {
2329
2426
  await reporter(error);
2330
2427
  } catch (reporterError) {
@@ -2355,12 +2452,12 @@ var ExceptionHandler = class {
2355
2452
  */
2356
2453
  renderDefaultException(error, ctx) {
2357
2454
  const debug = this.shouldShowDetails();
2455
+ const statusCode = resolveExceptionStatus(error);
2358
2456
  if (HttpException.isHttpException(error)) {
2359
- const { status, body } = error.toResponse(debug);
2360
- if (this.wantsHtmlResponse(ctx) && !debug) return ctx.html(renderErrorPage(status, body.message), status);
2361
- return ctx.json(body, status);
2457
+ const { body } = error.toResponse(debug);
2458
+ if (this.wantsHtmlResponse(ctx) && !debug) return ctx.html(renderErrorPage(statusCode, body.message), statusCode);
2459
+ return ctx.json(body, statusCode);
2362
2460
  }
2363
- const statusCode = "statusCode" in error && typeof error.statusCode === "number" ? error.statusCode : 500;
2364
2461
  const body = { message: statusCode < 500 || debug ? error.message : "Internal Server Error" };
2365
2462
  if (debug) {
2366
2463
  body.exception = error.name;
@@ -2395,6 +2492,26 @@ var ExceptionHandler = class {
2395
2492
  }
2396
2493
  };
2397
2494
  /**
2495
+ * The HTTP status an exception carries, or 500 when it names none.
2496
+ *
2497
+ * Duck-typed on `statusCode` rather than on `instanceof HttpException`, which
2498
+ * is what lets a foreign exception (`ModelNotFoundException` from
2499
+ * `@guren/orm`, crossing a package boundary) render as its own 404 rather than
2500
+ * a 500. `HttpException.isHttpException()` treats the same property as the
2501
+ * authority, so this reads what that check already required.
2502
+ *
2503
+ * One rule, read by both halves of the handler: what an exception is delivered
2504
+ * as and whether the fallback logger treats it as a server failure must be the
2505
+ * same number, or an exception could be sent as a 422 and reported as a crash.
2506
+ * That is why `renderDefaultException` takes the status from here rather than
2507
+ * from `toResponse()`, whose `status` a duck-typed implementation could spell
2508
+ * differently from its own `statusCode`.
2509
+ */
2510
+ function resolveExceptionStatus(error) {
2511
+ const statusCode = error?.statusCode;
2512
+ return typeof statusCode === "number" ? statusCode : 500;
2513
+ }
2514
+ /**
2398
2515
  * Create an exception handler.
2399
2516
  */
2400
2517
  function createExceptionHandler(options) {
@@ -3578,7 +3695,7 @@ var Application = class {
3578
3695
  await this.providerManager.registerAll();
3579
3696
  await this.options.boot?.(this.hono);
3580
3697
  await this.mountRoutes();
3581
- await this.mountDevEndpoint(isMcpEndpointEnabled(), async () => (await import("./McpServiceProvider-D6D9nhgn.js").then((n) => n.n)).McpServiceProvider, "GUREN_MCP=1 but the MCP endpoint could not load — is @modelcontextprotocol/sdk installed?");
3698
+ await this.mountDevEndpoint(isMcpEndpointEnabled(), async () => (await import("./McpServiceProvider-BawsYjgN.js").then((n) => n.n)).McpServiceProvider, "GUREN_MCP=1 but the MCP endpoint could not load — is @modelcontextprotocol/sdk installed?");
3582
3699
  await this.mountDevEndpoint(isDocsViewerEnabled(), async () => (await import("./DocsViewerServiceProvider-qFCaeiUv.js")).DocsViewerServiceProvider, "GUREN_DOCS=1 but the docs viewer could not load — is @guren/cli resolvable from this app?");
3583
3700
  await this.providerManager.bootAll();
3584
3701
  }
@@ -3985,7 +4102,7 @@ var Controller = class {
3985
4102
  * ```
3986
4103
  */
3987
4104
  async file(name) {
3988
- const value = (await this.ctx.req.parseBody({ all: true }))[name];
4105
+ const value = (await parseRequestUploads(this.ctx))[name];
3989
4106
  const candidate = Array.isArray(value) ? value[0] : value;
3990
4107
  return candidate instanceof File && candidate.size > 0 ? candidate : null;
3991
4108
  }
@@ -3994,11 +4111,11 @@ var Controller = class {
3994
4111
  * Returns an empty array when none were uploaded.
3995
4112
  */
3996
4113
  async files(name) {
3997
- const value = (await this.ctx.req.parseBody({ all: true }))[name];
4114
+ const value = (await parseRequestUploads(this.ctx))[name];
3998
4115
  return (Array.isArray(value) ? value : value !== void 0 ? [value] : []).filter((item) => item instanceof File && item.size > 0);
3999
4116
  }
4000
4117
  get auth() {
4001
- const auth = this.ctx.get(AUTH_CONTEXT_KEY);
4118
+ const auth = getAuthContext(this.ctx);
4002
4119
  if (!auth) throw new Error("Controller auth helper requires the auth middleware. Make sure AuthServiceProvider is registered.");
4003
4120
  return auth;
4004
4121
  }
@@ -4057,7 +4174,7 @@ var Controller = class {
4057
4174
  return getGate().forUser(await this.gateUser()).allows(ability, ...args);
4058
4175
  }
4059
4176
  async gateUser() {
4060
- const auth = this.ctx.get(AUTH_CONTEXT_KEY);
4177
+ const auth = getAuthContext(this.ctx);
4061
4178
  if (!auth) return null;
4062
4179
  return await auth.user();
4063
4180
  }
@@ -4271,8 +4388,7 @@ var Controller = class {
4271
4388
  * ```
4272
4389
  */
4273
4390
  async validateBody(schema) {
4274
- const body = await this.getBody();
4275
- return this.runValidation(schema, body);
4391
+ return this.runValidation(schema, await this.getRawBody());
4276
4392
  }
4277
4393
  /**
4278
4394
  * Validate query parameters against a Zod-like schema.
@@ -4313,8 +4429,7 @@ var Controller = class {
4313
4429
  * ```
4314
4430
  */
4315
4431
  async validateBodySafe(schema) {
4316
- const body = await this.getBody();
4317
- return this.runValidationSafe(schema, body);
4432
+ return this.runValidationSafe(schema, await this.getRawBody());
4318
4433
  }
4319
4434
  /**
4320
4435
  * Validate query parameters against a Zod-like schema without throwing.
@@ -4352,14 +4467,32 @@ var Controller = class {
4352
4467
  errors
4353
4468
  };
4354
4469
  }
4470
+ /**
4471
+ * The parsed body as sent: an array stays an array, a string stays a string.
4472
+ * Only validation reads it — a schema is what decides whether the shape is
4473
+ * acceptable, so narrowing first would make a non-object contract
4474
+ * unreachable.
4475
+ *
4476
+ * Memoized in a box rather than by truthiness: a body of `null`, `''`, `0`
4477
+ * or `false` is a parsed body, and re-reading the request would find the
4478
+ * stream consumed.
4479
+ *
4480
+ * No fallback of its own: an unparseable body already arrives here as `{}`
4481
+ * from {@link parseRequestBody}, which is what gives every dispatch path the
4482
+ * same answer. A second fallback here could only diverge from that one.
4483
+ */
4484
+ async getRawBody() {
4485
+ if (this.parsedBody) return this.parsedBody.value;
4486
+ this.parsedBody = { value: await parseRequestBody(this.ctx) };
4487
+ return this.parsedBody.value;
4488
+ }
4489
+ /**
4490
+ * The record view of {@link getRawBody}, for the field-by-field helpers
4491
+ * (`input`, `only`, `except`, `has`). A non-object body has no field to
4492
+ * read, so it reads as `{}`.
4493
+ */
4355
4494
  async getBody() {
4356
- if (this.parsedBody) return this.parsedBody;
4357
- try {
4358
- this.parsedBody = await parseRequestPayload(this.ctx);
4359
- } catch {
4360
- this.parsedBody = {};
4361
- }
4362
- return this.parsedBody;
4495
+ return asRecord(await this.getRawBody());
4363
4496
  }
4364
4497
  };
4365
4498
  //#endregion
@@ -4436,6 +4569,1077 @@ function viteAsset(entry, options = {}) {
4436
4569
  return manifestAssetUrl(manifest, normalizedEntry);
4437
4570
  }
4438
4571
  //#endregion
4572
+ //#region src/agent/derive.ts
4573
+ /** HTTP methods whose semantics are read-only, per the MCP annotation defaults. */
4574
+ const READ_ONLY_METHODS = /* @__PURE__ */ new Set(["GET", "QUERY"]);
4575
+ /** HTTP methods that are idempotent whether or not they are read-only. */
4576
+ const IDEMPOTENT_METHODS = /* @__PURE__ */ new Set([
4577
+ "GET",
4578
+ "QUERY",
4579
+ "PUT",
4580
+ "DELETE"
4581
+ ]);
4582
+ /**
4583
+ * Derive the agent tools a set of route definitions exposes.
4584
+ *
4585
+ * @param definitions Registered routes, as `Router.definitions()` hands them out.
4586
+ */
4587
+ function deriveAgentTools(definitions) {
4588
+ const tools = [];
4589
+ const warnings = [];
4590
+ const claimed = /* @__PURE__ */ new Map();
4591
+ for (const definition of definitions) {
4592
+ const agent = definition.agent;
4593
+ if (!agent) continue;
4594
+ const method = definition.method.toUpperCase();
4595
+ const where = `${method} ${definition.path}`;
4596
+ if (!definition.name) {
4597
+ warnings.push(`${where}: declares agent metadata but has no route name, so it is not exposed as a tool. Chain .name() on the route — the tool name is its identity.`);
4598
+ continue;
4599
+ }
4600
+ const routeName = definition.name;
4601
+ const toolName = agent.toolName ?? routeName;
4602
+ const existing = claimed.get(toolName);
4603
+ if (existing) {
4604
+ warnings.push(`${toolName}: ${where} (route "${routeName}") claims a tool name already derived from ${existing.method} ${existing.path} (route "${existing.routeName}") — the later route is not exposed. Give one of them a distinct agent toolName.`);
4605
+ continue;
4606
+ }
4607
+ const toolWarnings = [];
4608
+ const readOnlyHint = agent.readOnlyHint ?? READ_ONLY_METHODS.has(method);
4609
+ const input = buildInputSchema(definition, method, toolWarnings);
4610
+ const tool = {
4611
+ toolName,
4612
+ routeName,
4613
+ method,
4614
+ path: definition.path,
4615
+ description: agent.description ?? definition.description ?? definition.summary,
4616
+ inputSchema: input.schema,
4617
+ inputSources: input.sources,
4618
+ inputBodyNested: input.nestedBody,
4619
+ outputSchema: buildOutputSchema(definition, method, toolWarnings),
4620
+ resource: definition.schemas?.output ? void 0 : definition.resource,
4621
+ annotations: {
4622
+ readOnlyHint,
4623
+ destructiveHint: agent.destructiveHint ?? !readOnlyHint,
4624
+ idempotentHint: agent.idempotentHint ?? IDEMPOTENT_METHODS.has(method)
4625
+ },
4626
+ authorization: deriveAuthorization(definition, method),
4627
+ approval: agent.approval,
4628
+ redact: agent.redact ? [...agent.redact] : void 0,
4629
+ expose: {
4630
+ mcp: agent.expose?.mcp ?? true,
4631
+ webMcp: agent.expose?.webMcp ?? true
4632
+ },
4633
+ warnings: toolWarnings
4634
+ };
4635
+ claimed.set(toolName, tool);
4636
+ tools.push(tool);
4637
+ for (const warning of toolWarnings) warnings.push(`${toolName}: ${warning}`);
4638
+ }
4639
+ return {
4640
+ tools,
4641
+ warnings
4642
+ };
4643
+ }
4644
+ function buildInputSchema(definition, method, warnings) {
4645
+ const label = `${method} ${definition.path}`;
4646
+ const merged = {
4647
+ properties: Object.create(null),
4648
+ required: /* @__PURE__ */ new Set(),
4649
+ owner: /* @__PURE__ */ new Map()
4650
+ };
4651
+ const pathParamNames = extractPathParamNames(definition.path);
4652
+ const paramsDetails = definition.schemas?.params ? readObjectSchema(definition.schemas.params, warnings, `${label} params`, "input") : void 0;
4653
+ if (paramsDetails) mergeProperties(merged, paramsDetails.properties, paramsDetails.required, "params", warnings);
4654
+ const supplements = Object.create(null);
4655
+ const supplementRequired = /* @__PURE__ */ new Set();
4656
+ for (const name of pathParamNames) {
4657
+ if (merged.owner.has(name)) continue;
4658
+ supplements[name] = { type: "string" };
4659
+ supplementRequired.add(name);
4660
+ }
4661
+ mergeProperties(merged, supplements, supplementRequired, "path", warnings);
4662
+ const queryDetails = definition.schemas?.query ? readObjectSchema(definition.schemas.query, warnings, `${label} query`, "input") : void 0;
4663
+ if (queryDetails) mergeProperties(merged, queryDetails.properties, queryDetails.required, "query", warnings);
4664
+ let nestedBody = false;
4665
+ const body = definition.schemas?.body ? toJsonSchema(definition.schemas.body, warnings, `${label} body`, "input") : void 0;
4666
+ if (body) {
4667
+ if (body.type === "object" && body.properties) mergeProperties(merged, body.properties, new Set(body.required ?? []), "body", warnings);
4668
+ else {
4669
+ mergeProperties(merged, { body }, /* @__PURE__ */ new Set(["body"]), "body", warnings);
4670
+ nestedBody = true;
4671
+ }
4672
+ }
4673
+ for (const name of pathParamNames) if (name in merged.properties) merged.required.add(name);
4674
+ const required = Array.from(merged.required);
4675
+ const sources = Object.create(null);
4676
+ for (const [name, source] of merged.owner) sources[name] = source;
4677
+ return {
4678
+ schema: {
4679
+ type: "object",
4680
+ properties: { ...merged.properties },
4681
+ ...required.length > 0 ? { required } : {}
4682
+ },
4683
+ sources: { ...sources },
4684
+ nestedBody
4685
+ };
4686
+ }
4687
+ /**
4688
+ * Fold one source's properties into the merge. A collision replaces both the
4689
+ * property *and* its required-ness — carrying a losing source's `required`
4690
+ * forward would demand a key the advertised schema no longer describes.
4691
+ */
4692
+ function mergeProperties(merged, properties, required, source, warnings) {
4693
+ for (const [name, schema] of Object.entries(properties)) {
4694
+ const previous = merged.owner.get(name);
4695
+ if (previous) warnings.push(`input key "${name}" is declared by both the ${previous} and the ${source} schema; the ${source} definition wins. Rename one — merged tool input has one namespace.`);
4696
+ merged.properties[name] = schema;
4697
+ merged.owner.set(name, source);
4698
+ merged.required.delete(name);
4699
+ if (required.has(name)) merged.required.add(name);
4700
+ }
4701
+ }
4702
+ /**
4703
+ * The route's `output` schema, which is the only response shape validated at
4704
+ * runtime — so advertising it costs no new machinery. A `resource` hint is the
4705
+ * next rung of RFC 0016's ladder and is CLI-only: `definitions()` carries
4706
+ * class names, and the type text behind them exists solely in the CLI's AST
4707
+ * extraction.
4708
+ */
4709
+ function buildOutputSchema(definition, method, warnings) {
4710
+ const output = definition.schemas?.output;
4711
+ if (!output) return void 0;
4712
+ return toJsonSchema(output, warnings, `${method} ${definition.path} response`, "output");
4713
+ }
4714
+ /**
4715
+ * The ability a route's middleware chain checks, when the stamped capability
4716
+ * says so unambiguously (RFC 0007's `MiddlewareCapabilities.authorization`).
4717
+ *
4718
+ * Everything else is omitted rather than guessed — `'any'`/`'mixed'`, several
4719
+ * abilities, an `abilityFor` callback that overrides the verb map, a custom
4720
+ * verb the map refuses, or a definition from a server old enough to carry no
4721
+ * capabilities at all. Absence means "undetermined", which is what lets
4722
+ * `guren check`'s "authn is not authz" rule fail closed on it instead of
4723
+ * reading a name that was never checked.
4724
+ */
4725
+ function deriveAuthorization(definition, method) {
4726
+ const authorization = definition.capabilities?.authorization;
4727
+ if (!authorization) return void 0;
4728
+ if (authorization.resource) {
4729
+ if (!authorization.resource.fromMethodMap) return void 0;
4730
+ if (authorization.abilities.length > 0 || authorization.mode !== "all") return void 0;
4731
+ const ability = resourceAbilityForMethod(method);
4732
+ return ability ? { ability } : void 0;
4733
+ }
4734
+ if (authorization.abilities.length === 1 && authorization.mode === "all") return { ability: authorization.abilities[0] };
4735
+ }
4736
+ //#endregion
4737
+ //#region src/agent/meta-tools.ts
4738
+ /**
4739
+ * The names a protocol adapter may add to an application's tool catalogue on
4740
+ * its own, and which an application route therefore may not claim (RFC 0016
4741
+ * §5.4).
4742
+ *
4743
+ * This is the one rule, with two readers. `@guren/plugin-mcp` adds
4744
+ * `guren.preflight` to the catalogue it serves; `guren check` fails a route
4745
+ * whose `.agent()` tool name would collide with it. Restating the string in
4746
+ * either place is how the two drift: the check would keep passing a route
4747
+ * whose tool the endpoint has already shadowed, and `tools/list` would carry
4748
+ * two tools with one name — which an MCP client rejects wholesale, so the
4749
+ * collision costs the *entire* catalogue, not the one tool.
4750
+ *
4751
+ * It lives beside the derivation rather than in the plugin because the check
4752
+ * cannot import the plugin (the CLI does not depend on it, and an app that
4753
+ * never installs App MCP is still checked), and the plugin must not restate a
4754
+ * name the check is enforcing.
4755
+ *
4756
+ * The list stays deliberately short. Every entry is a name taken away from
4757
+ * applications, and the `guren.` prefix is not reserved wholesale for the
4758
+ * same reason: reserving a namespace nothing occupies fails routes over a
4759
+ * collision that does not exist.
4760
+ */
4761
+ /**
4762
+ * The preflight companion tool (RFC 0016 §5.4).
4763
+ *
4764
+ * Preflight cannot be an *argument* of the tool being checked on MCP: a tool
4765
+ * advertising an `outputSchema` must answer with `structuredContent`
4766
+ * conforming to it unless the result is an error, and a verdict conforms to
4767
+ * no route's output. So the verdict needs a tool of its own, with its own
4768
+ * output schema — one meta-tool for the whole catalogue, not one companion
4769
+ * per tool, which would double the catalogue against §5.5's own
4770
+ * catalogue-quality rule.
4771
+ */
4772
+ const PREFLIGHT_TOOL_NAME = "guren.preflight";
4773
+ /**
4774
+ * The approval-status companion tool (RFC 0016 §5.4 item 4).
4775
+ *
4776
+ * A tool declaring `approval: 'required'` answers its first call with a
4777
+ * pending record rather than an execution, and the caller is handed a request
4778
+ * id. Something has to be able to say what became of that id, and it cannot be
4779
+ * the gated tool itself for the reason preflight cannot be an argument of one:
4780
+ * a status is not that route's output, and a tool advertising an `outputSchema`
4781
+ * may not answer with a different shape of success.
4782
+ *
4783
+ * A second meta-tool rather than a mode of the first: `guren.preflight`
4784
+ * rehearses a call and answers a verdict, this reads a record and answers its
4785
+ * state. Folding both under one name would mean one tool whose output schema
4786
+ * is the union of two unrelated shapes, which is the thing a schema is for
4787
+ * preventing.
4788
+ */
4789
+ const APPROVAL_STATUS_TOOL_NAME = "guren.approval_status";
4790
+ /** Every meta-tool name an adapter may occupy. */
4791
+ const RESERVED_AGENT_TOOL_NAMES = [PREFLIGHT_TOOL_NAME, APPROVAL_STATUS_TOOL_NAME];
4792
+ /**
4793
+ * Whether a tool name belongs to the framework rather than the application.
4794
+ *
4795
+ * Case-sensitive, like every other comparison the tool-name grammar makes:
4796
+ * MCP tool names are matched literally, so `Guren.Preflight` is a different
4797
+ * tool and reserving it would take a name away for nothing.
4798
+ */
4799
+ function isReservedAgentToolName(name) {
4800
+ return RESERVED_AGENT_TOOL_NAMES.includes(name);
4801
+ }
4802
+ //#endregion
4803
+ //#region src/agent/scopes.ts
4804
+ /**
4805
+ * The scope grammar an API token's `abilities` use to reach agent tools
4806
+ * (RFC 0016 §5.1).
4807
+ *
4808
+ * Four forms, and deliberately no more — a grammar an agent-facing consent
4809
+ * screen has to render is only useful if a human can read a scope and say
4810
+ * which tools it grants:
4811
+ *
4812
+ * - `tool:<name>` one tool, by exact name
4813
+ * - `tools:read` every tool whose resolved `readOnlyHint` is true
4814
+ * - `tools:*` every tool
4815
+ * - `tools:<prefix>.*` every tool named `<prefix>.…`
4816
+ *
4817
+ * **Only `tool:` / `tools:` entries are considered.** Every other ability an
4818
+ * `ApiToken` carries — including the store's default `['*']` — is ignored, so
4819
+ * it matches nothing. This is the fail-closed half of a deliberate split:
4820
+ *
4821
+ * - A token issued before agent tools existed, for an app's own API, holds
4822
+ * `['*']`. Reading that as "all agent tools" would silently hand every
4823
+ * already-issued token the whole agent surface the moment an app declares
4824
+ * its first `.agent()` route. Access to the agent surface is granted by an
4825
+ * explicit tool scope or not at all (default deny, RFC §5.1); `tools:*` is
4826
+ * the explicit way to say "everything".
4827
+ * - A malformed entry is likewise ignored here rather than throwing: this
4828
+ * module judges an already-issued token, and a token that cannot be parsed
4829
+ * must grant less, never more. Rejecting a bad scope belongs to the
4830
+ * *issuer* (`token:issue`, a later PR), which runs {@link parseToolScope}
4831
+ * over what it was asked for and refuses a `null`.
4832
+ *
4833
+ * Matching is case-sensitive and entries are not trimmed. A stored ability
4834
+ * with stray whitespace is an issuance bug; normalizing it here would make
4835
+ * the judge more permissive than the issuer, which is the wrong direction.
4836
+ */
4837
+ /**
4838
+ * The MCP tool-name grammar (SEP-986), which a `tool:` scope names and a
4839
+ * `tools:<prefix>.*` scope has to stay inside — a scope that could not
4840
+ * possibly name a legal tool is not a scope.
4841
+ *
4842
+ * `packages/cli/src/agent-route-check.ts` holds the same pattern for the
4843
+ * check that fails a build over an illegal tool name. Collapsing the two onto
4844
+ * this export is a later change, not this one: the CLI reaches `@guren/server`
4845
+ * through `dist/`, so the collapse needs a built server and belongs with the
4846
+ * PR that does the build-order work.
4847
+ *
4848
+ * Note what the charset gives for free: `*` is not in it, so `tool:posts.*`
4849
+ * fails the test and needs no special case to be rejected.
4850
+ */
4851
+ const AGENT_TOOL_NAME_PATTERN = /^[A-Za-z0-9._-]{1,128}$/;
4852
+ /** `tool:` scope prefix, including the separator. */
4853
+ const SINGLE_PREFIX = "tool:";
4854
+ /** `tools:` scope prefix, including the separator. */
4855
+ const SET_PREFIX = "tools:";
4856
+ /** The reserved `tools:` word granting every read-only tool. */
4857
+ const READ_KEYWORD = "read";
4858
+ /** The reserved `tools:` word granting every tool. */
4859
+ const ALL_KEYWORD = "*";
4860
+ /** Wildcard suffix of a prefix scope, dot included. */
4861
+ const PREFIX_SUFFIX = ".*";
4862
+ /**
4863
+ * Parse one `abilities` entry.
4864
+ *
4865
+ * @returns The scope it denotes, or `null` for an entry that is not a tool
4866
+ * scope at all (`'*'`, an app's own ability name) and for one that is
4867
+ * malformed (`tools:`, `tools:.*`, `tools:*.store`, a prefix outside the
4868
+ * tool-name grammar). Callers cannot tell those apart on purpose: both mean
4869
+ * "grants no tool", and a judge that distinguished them would be inventing
4870
+ * a third answer for a two-valued question.
4871
+ *
4872
+ * Note the two reserved `tools:` words are matched before the wildcard form,
4873
+ * so a tool family literally named `read.…` is still reachable as
4874
+ * `tools:read.*`, while a tool named exactly `read` is reachable only as
4875
+ * `tool:read` — the reserved word wins its own spelling.
4876
+ */
4877
+ function parseToolScope(entry) {
4878
+ if (entry.startsWith(SINGLE_PREFIX)) {
4879
+ const name = entry.slice(5);
4880
+ return AGENT_TOOL_NAME_PATTERN.test(name) ? {
4881
+ kind: "tool",
4882
+ name
4883
+ } : null;
4884
+ }
4885
+ if (!entry.startsWith(SET_PREFIX)) return null;
4886
+ const rest = entry.slice(6);
4887
+ if (rest === READ_KEYWORD) return { kind: "read" };
4888
+ if (rest === ALL_KEYWORD) return { kind: "all" };
4889
+ if (!rest.endsWith(PREFIX_SUFFIX)) return null;
4890
+ const prefix = rest.slice(0, -2);
4891
+ if (!AGENT_TOOL_NAME_PATTERN.test(prefix)) return null;
4892
+ return {
4893
+ kind: "prefix",
4894
+ prefix
4895
+ };
4896
+ }
4897
+ /** Whether one parsed scope covers a given tool. */
4898
+ function scopeAllowsTool(scope, tool) {
4899
+ switch (scope.kind) {
4900
+ case "tool": return scope.name === tool.name;
4901
+ case "read": return tool.readOnly;
4902
+ case "all": return true;
4903
+ case "prefix": return tool.name.startsWith(`${scope.prefix}.`);
4904
+ default: return scope;
4905
+ }
4906
+ }
4907
+ /**
4908
+ * Whether a token's abilities grant a tool. Any one entry suffices — scopes
4909
+ * are additive, and there is no deny form.
4910
+ */
4911
+ function scopesAllowTool(abilities, tool) {
4912
+ for (const entry of abilities) {
4913
+ const scope = parseToolScope(entry);
4914
+ if (scope && scopeAllowsTool(scope, tool)) return true;
4915
+ }
4916
+ return false;
4917
+ }
4918
+ /**
4919
+ * The concrete tool names a token's abilities grant, for the surfaces that
4920
+ * have to show a human what a scope means: the OAuth consent screen, the
4921
+ * `token:issue` confirmation, and the issuance-time lint.
4922
+ *
4923
+ * Literally a filter over {@link scopesAllowTool}, and it must stay one. A
4924
+ * second matcher that walked entries and accumulated names is how a consent
4925
+ * screen comes to list a tool the dispatcher then denies — the two answers
4926
+ * have to be the same answer, not two implementations of one rule.
4927
+ *
4928
+ * @returns Names in the order the tools were given, so a caller controls the
4929
+ * display order by ordering its input.
4930
+ */
4931
+ function expandToolScopes(abilities, tools) {
4932
+ return tools.filter((tool) => scopesAllowTool(abilities, tool)).map((tool) => tool.name);
4933
+ }
4934
+ //#endregion
4935
+ //#region src/agent/events.ts
4936
+ /**
4937
+ * The audit trail of the agent surface (RFC 0016 §5.2): every tool invocation
4938
+ * and every denial, as framework events, so an application forwards them
4939
+ * wherever it already forwards events instead of learning a second logging
4940
+ * API.
4941
+ *
4942
+ * Declarations only. Nothing here emits — the dispatch path does, once, at
4943
+ * the one place that knows the verdict — and nothing here redacts:
4944
+ * {@link AgentToolInvoked.arguments} is a *contract* that the emitter has
4945
+ * already run the arguments through `redactAgentArguments`. An event class
4946
+ * that redacted on construction would give a second, quieter redaction rule
4947
+ * beside the real one, and a listener has no way to tell a masked payload
4948
+ * from an unmasked one.
4949
+ */
4950
+ /**
4951
+ * Emitted when an agent tool invocation completed — successfully or not.
4952
+ * `status` carries the HTTP status the dispatch resolved to, so an error
4953
+ * response is one of these rather than a separate event; a call that never
4954
+ * reached the handler is an {@link AgentToolDenied} instead.
4955
+ */
4956
+ var AgentToolInvoked = class extends Event {
4957
+ principal;
4958
+ tool;
4959
+ status;
4960
+ durationMs;
4961
+ surface;
4962
+ /**
4963
+ * The invocation arguments **already redacted** by the emitter (see the
4964
+ * module header). Assigned in the body rather than declared as a
4965
+ * constructor parameter property: `arguments` is not a legal binding
4966
+ * identifier in strict mode, which every ES module is, though it is a
4967
+ * perfectly legal property name.
4968
+ */
4969
+ arguments;
4970
+ constructor(principal, tool, redactedArguments, status, durationMs, surface) {
4971
+ super();
4972
+ this.principal = principal;
4973
+ this.tool = tool;
4974
+ this.status = status;
4975
+ this.durationMs = durationMs;
4976
+ this.surface = surface;
4977
+ this.arguments = redactedArguments;
4978
+ }
4979
+ };
4980
+ /**
4981
+ * Emitted when an agent tool invocation was refused. Carries no status or
4982
+ * duration: nothing ran, and {@link AgentToolDenialReason} is the finding.
4983
+ * `'approval'` covers a tool declaring `approval: 'required'` whose call
4984
+ * became a pending record instead of an execution.
4985
+ */
4986
+ var AgentToolDenied = class extends Event {
4987
+ principal;
4988
+ tool;
4989
+ reason;
4990
+ surface;
4991
+ /** Redacted by the emitter, exactly as on {@link AgentToolInvoked}. */
4992
+ arguments;
4993
+ constructor(principal, tool, redactedArguments, reason, surface) {
4994
+ super();
4995
+ this.principal = principal;
4996
+ this.tool = tool;
4997
+ this.reason = reason;
4998
+ this.surface = surface;
4999
+ this.arguments = redactedArguments;
5000
+ }
5001
+ };
5002
+ //#endregion
5003
+ //#region src/agent/redact.ts
5004
+ /**
5005
+ * Argument masking for the agent audit trail (RFC 0016 §5.2).
5006
+ *
5007
+ * Agent tool arguments are logged by default, which is only safe if the
5008
+ * logging path masks the fields that must not be written down. Two sources,
5009
+ * unioned: a fixed list of sensitive key *fragments* every application gets
5010
+ * without asking, and the route's own `.agent({ redact })` metadata.
5011
+ *
5012
+ * The rule is deliberately blunt — a key matches when its lowercased name
5013
+ * *contains* a fragment, and that applies to the declared `redact` entries
5014
+ * too, not just the built-ins. So `redact: ['id']` also masks `userId`, and
5015
+ * the built-in `session` masks `sessionCount`. Over-redaction is the safe
5016
+ * direction for a log: a masked field that did not need masking costs a
5017
+ * debugging round trip, an unmasked credential costs a rotation.
5018
+ *
5019
+ * The walk is total for the same reason the derivation is: it runs while
5020
+ * *recording* what happened, including a denial taken before the route's own
5021
+ * validation, so it must not be the thing that throws. A cycle and a payload
5022
+ * nested past {@link MAX_DEPTH} both terminate with a marker.
5023
+ */
5024
+ /**
5025
+ * The replacement written in place of a masked value. A string, so a redacted
5026
+ * record still serializes as JSON and reads the same in every sink.
5027
+ */
5028
+ const AGENT_REDACTED = "[REDACTED]";
5029
+ /**
5030
+ * Written in place of a value that closes a cycle, so a self-referencing
5031
+ * argument object produces a finite record instead of throwing or hanging.
5032
+ * Distinct from {@link AGENT_REDACTED} on purpose: one says "we would not show
5033
+ * you", the other "there is nothing further here to show".
5034
+ */
5035
+ const AGENT_CIRCULAR = "[Circular]";
5036
+ /**
5037
+ * Written in place of a value nested deeper than {@link MAX_DEPTH}.
5038
+ */
5039
+ const AGENT_TRUNCATED = "[Truncated]";
5040
+ /**
5041
+ * How deep the walk goes before it stops descending.
5042
+ *
5043
+ * A cycle is not the only way an argument record ends recursion badly: a
5044
+ * deeply nested one ends it with a `RangeError`. That matters here more than
5045
+ * in an ordinary utility, because this is the *audit* path and a denial is
5046
+ * recorded before the route's own schema validation has run — an argument
5047
+ * payload that overflows the stack would throw inside the code writing the
5048
+ * record about it, suppressing the very `AgentToolDenied` that says a
5049
+ * hostile call arrived. Truncating keeps the record.
5050
+ *
5051
+ * Far past anything a tool input schema describes; a record this deep is
5052
+ * already unreadable in a log.
5053
+ */
5054
+ const MAX_DEPTH = 64;
5055
+ /**
5056
+ * Key-name fragments masked in every application. Spelled in the normalized
5057
+ * form {@link normalizeKeyText} produces — lowercase, no separators — so
5058
+ * `Authorization`, `apiKey`, `API_KEY` and `x-api-key` are all covered by
5059
+ * their one entry.
5060
+ */
5061
+ const DEFAULT_SENSITIVE_KEY_FRAGMENTS = [
5062
+ "password",
5063
+ "passphrase",
5064
+ "secret",
5065
+ "token",
5066
+ "apikey",
5067
+ "authorization",
5068
+ "credential",
5069
+ "cookie",
5070
+ "session",
5071
+ "privatekey",
5072
+ "pwd",
5073
+ "jwt"
5074
+ ];
5075
+ /**
5076
+ * The form keys and fragments are compared in: lowercased, with separator
5077
+ * characters removed. `apiKey`, `api_key`, `api-key` and `X-Api-Key` are the
5078
+ * same name to a human reading a log, so they must be the same name to the
5079
+ * mask — a literal substring test lets the hyphenated spelling of a fragment
5080
+ * through, and header-shaped argument names (`x-api-key`) are exactly where
5081
+ * credentials live. Applied to declared `redact` entries too, so a route
5082
+ * author writes any spelling.
5083
+ */
5084
+ function normalizeKeyText(text) {
5085
+ return text.toLowerCase().replace(/[-_\s]/gu, "");
5086
+ }
5087
+ /**
5088
+ * Mask the sensitive fields of an agent tool's arguments.
5089
+ *
5090
+ * Returns a deep copy: the input is never mutated, and a caller may keep
5091
+ * holding the unredacted original. The copy is deep only through the
5092
+ * structures this walks — plain objects and arrays. Anything else (a `Date`,
5093
+ * a `Map`, a `Set`, a class instance) is carried across as the *same
5094
+ * reference*, because copying it would need a rule per type and would still
5095
+ * get the exotic cases wrong; nothing below such a value is inspected, so a
5096
+ * credential hidden inside a class instance is masked only if the key holding
5097
+ * that instance matches. Tool arguments arrive as parsed JSON on every
5098
+ * surface, where this case does not occur; a caller synthesizing arguments in
5099
+ * process is the one that can hit it.
5100
+ *
5101
+ * @param args The invocation arguments. Walked as a record whatever its
5102
+ * prototype, so the return is always a fresh plain object.
5103
+ * @param redact Extra key fragments from the route's `.agent({ redact })`.
5104
+ */
5105
+ function redactAgentArguments(args, redact) {
5106
+ if (args === null || typeof args !== "object") return {};
5107
+ const fragments = [...DEFAULT_SENSITIVE_KEY_FRAGMENTS];
5108
+ for (const entry of redact ?? []) {
5109
+ const fragment = normalizeKeyText(entry);
5110
+ if (fragment.length > 0) fragments.push(fragment);
5111
+ }
5112
+ return redactRecord(args, fragments, new WeakSet([args]), 0);
5113
+ }
5114
+ /** Whether a key name should have its value masked. */
5115
+ function isSensitiveKey(key, fragments) {
5116
+ const normalized = normalizeKeyText(key);
5117
+ return fragments.some((fragment) => normalized.includes(fragment));
5118
+ }
5119
+ /**
5120
+ * Copy one object's entries, masking sensitive keys.
5121
+ *
5122
+ * Accumulates on a null-prototype object: an argument named `__proto__`
5123
+ * survives `JSON.parse` as an own property, and assigning that key on a
5124
+ * plain `{}` invokes the prototype setter instead of defining a property —
5125
+ * the value would vanish from the record, and a crafted payload would be
5126
+ * reaching the prototype chain from inside the logging path. The result is
5127
+ * then spread onto a normal object so a consumer calling `hasOwnProperty` on
5128
+ * it works; spread *defines* own properties (`Object.assign` would assign
5129
+ * them, putting the `__proto__` hazard straight back).
5130
+ */
5131
+ function redactRecord(source, fragments, ancestors, depth) {
5132
+ const accumulator = Object.create(null);
5133
+ for (const [key, value] of Object.entries(source)) accumulator[key] = isSensitiveKey(key, fragments) ? AGENT_REDACTED : redactValue(value, fragments, ancestors, depth + 1);
5134
+ return { ...accumulator };
5135
+ }
5136
+ /** Copy one value, masking the sensitive keys anywhere beneath it. */
5137
+ function redactValue(value, fragments, ancestors, depth) {
5138
+ if (value === null || typeof value !== "object") return value;
5139
+ if (!isWalkable(value)) return value;
5140
+ if (depth > MAX_DEPTH) return AGENT_TRUNCATED;
5141
+ if (ancestors.has(value)) return AGENT_CIRCULAR;
5142
+ ancestors.add(value);
5143
+ try {
5144
+ if (Array.isArray(value)) return value.map((element) => redactValue(element, fragments, ancestors, depth + 1));
5145
+ return redactRecord(value, fragments, ancestors, depth);
5146
+ } finally {
5147
+ ancestors.delete(value);
5148
+ }
5149
+ }
5150
+ /**
5151
+ * Whether a value is a structure this walks: an array, or an object with no
5152
+ * prototype or the plain one. Everything else is carried across by reference
5153
+ * (see {@link redactAgentArguments}).
5154
+ */
5155
+ function isWalkable(value) {
5156
+ if (Array.isArray(value)) return true;
5157
+ const prototype = Object.getPrototypeOf(value);
5158
+ return prototype === null || prototype === Object.prototype;
5159
+ }
5160
+ //#endregion
5161
+ //#region src/agent/audit.ts
5162
+ /**
5163
+ * Where an application's audit trail is written by default, relative to the
5164
+ * app root. `storage/logs/` is the convention `LogManager`'s own examples
5165
+ * already use, so an audit trail lands beside the application log rather than
5166
+ * inventing a second place to look.
5167
+ */
5168
+ const DEFAULT_AGENT_AUDIT_PATH = "storage/logs/agent-audit.log";
5169
+ /**
5170
+ * Every surface, as a value. Written as a total map of the union so that
5171
+ * adding a surface to {@link AgentSurface} fails to compile here rather than
5172
+ * making {@link parseAuditRecord} silently reject records from it.
5173
+ */
5174
+ const AGENT_SURFACES = {
5175
+ "mcp": true,
5176
+ "dev-mcp": true,
5177
+ "cli": true,
5178
+ "webmcp": true
5179
+ };
5180
+ /** Every denial reason, as a value, total over the union for the same reason. */
5181
+ const DENIAL_REASONS = {
5182
+ "auth": true,
5183
+ "scope": true,
5184
+ "approval": true,
5185
+ "rate-limit": true
5186
+ };
5187
+ /**
5188
+ * Derive the record for one audit event.
5189
+ *
5190
+ * `now` is a parameter rather than a `Date.now()` inside: the sink writing
5191
+ * this record also picks the dated file it lands in, and two clock reads can
5192
+ * disagree across a midnight boundary — a record stamped just before it,
5193
+ * filed just after. One read, used for both.
5194
+ *
5195
+ * The two events are told apart structurally, not with `instanceof`. The event
5196
+ * classes cross a package boundary that this repo resolves twice — `@guren/cli`
5197
+ * and the plugins reach `@guren/server` through its `dist`, a test inside
5198
+ * `packages/server` through `src` — so an `instanceof` here would answer
5199
+ * `false` for a genuine event constructed on the other side of that seam, and
5200
+ * would do it by mislabelling the record rather than by failing.
5201
+ */
5202
+ function toAuditRecord(event, now) {
5203
+ const base = {
5204
+ ts: now.toISOString(),
5205
+ surface: event.surface,
5206
+ tool: event.tool,
5207
+ principal: event.principal,
5208
+ arguments: event.arguments
5209
+ };
5210
+ return "reason" in event ? {
5211
+ ...base,
5212
+ outcome: "denied",
5213
+ reason: event.reason
5214
+ } : {
5215
+ ...base,
5216
+ outcome: "invoked",
5217
+ status: event.status,
5218
+ durationMs: event.durationMs
5219
+ };
5220
+ }
5221
+ /**
5222
+ * Read one line of an audit file back, or `null` if it is not a record.
5223
+ *
5224
+ * The one parser on the read side. A caller that hand-rolled a second would be
5225
+ * the reader half of the drift this whole feature is built to avoid, and would
5226
+ * be the half that fails silently: a record it stops recognising reads as an
5227
+ * empty trail.
5228
+ *
5229
+ * Returning `null` rather than throwing is what makes the reader usable
5230
+ * against a file that is being appended to right now. The last line of such a
5231
+ * file is routinely a *partial* record — an append is not atomic — and a blank
5232
+ * line is what a file ends with. Neither is corruption, and neither should
5233
+ * take down a command whose whole job is to show what the earlier lines say.
5234
+ *
5235
+ * Extra keys are ignored, deliberately: the file sink writes through
5236
+ * `DailyFileChannel`, whose JSON format wraps the record in a log envelope
5237
+ * (`timestamp`, `level`, `message`). Tolerating that envelope is what lets the
5238
+ * sink reuse the channel's rotation and retention instead of reimplementing
5239
+ * both, and the record's own fields are unambiguous beside it.
5240
+ */
5241
+ function parseAuditRecord(line) {
5242
+ if (line.trim() === "") return null;
5243
+ let parsed;
5244
+ try {
5245
+ parsed = JSON.parse(line);
5246
+ } catch {
5247
+ return null;
5248
+ }
5249
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return null;
5250
+ const candidate = parsed;
5251
+ const ts = candidate.ts;
5252
+ const tool = candidate.tool;
5253
+ const surface = candidate.surface;
5254
+ if (typeof ts !== "string" || typeof tool !== "string") return null;
5255
+ if (typeof surface !== "string" || !Object.hasOwn(AGENT_SURFACES, surface)) return null;
5256
+ const base = {
5257
+ ts,
5258
+ tool,
5259
+ surface,
5260
+ principal: readPrincipal(candidate.principal),
5261
+ arguments: isRecord(candidate.arguments) ? candidate.arguments : {}
5262
+ };
5263
+ if (candidate.outcome === "invoked") {
5264
+ const { status, durationMs } = candidate;
5265
+ if (typeof status !== "number" || typeof durationMs !== "number") return null;
5266
+ return {
5267
+ ...base,
5268
+ outcome: "invoked",
5269
+ status,
5270
+ durationMs
5271
+ };
5272
+ }
5273
+ if (candidate.outcome === "denied") {
5274
+ const reason = candidate.reason;
5275
+ if (typeof reason !== "string" || !Object.hasOwn(DENIAL_REASONS, reason)) return null;
5276
+ return {
5277
+ ...base,
5278
+ outcome: "denied",
5279
+ reason
5280
+ };
5281
+ }
5282
+ return null;
5283
+ }
5284
+ /**
5285
+ * The principal of a record, or `null`.
5286
+ *
5287
+ * An unreadable principal is `null` rather than a rejected record: who made a
5288
+ * call is the field most likely to change shape over the life of a log, and
5289
+ * losing the whole line — the tool, the arguments, the outcome — to recover
5290
+ * nothing is the wrong trade for an audit trail.
5291
+ */
5292
+ function readPrincipal(value) {
5293
+ if (!isRecord(value)) return null;
5294
+ const { kind, id, abilities } = value;
5295
+ if (kind !== "user" && kind !== "service") return null;
5296
+ if (typeof id !== "string" && typeof id !== "number") return null;
5297
+ const principal = {
5298
+ kind,
5299
+ id
5300
+ };
5301
+ if (Array.isArray(abilities)) principal.abilities = abilities.filter((ability) => typeof ability === "string");
5302
+ return principal;
5303
+ }
5304
+ function isRecord(value) {
5305
+ return value !== null && typeof value === "object" && !Array.isArray(value);
5306
+ }
5307
+ //#endregion
5308
+ //#region src/agent/audit-emitter.ts
5309
+ /**
5310
+ * The container service an application's audit emitter is published under
5311
+ * (`ServiceBindings['agent.audit']`).
5312
+ *
5313
+ * A constant rather than a literal at each site, because this is the first
5314
+ * binding written by one package and read by another that cannot import it:
5315
+ * `@guren/plugin-mcp` binds it, `@guren/cli` resolves it, and neither depends
5316
+ * on the other. Two literals that drifted would break the wiring *silently* —
5317
+ * the CLI would resolve nothing and record nothing, which reads exactly like
5318
+ * an application that configured no trail. That is the one failure this
5319
+ * feature exists to prevent, so it may not be spelled twice.
5320
+ */
5321
+ const AGENT_AUDIT_BINDING = "agent.audit";
5322
+ /**
5323
+ * Build the function a surface calls for every invocation and denial.
5324
+ *
5325
+ * **The sink is called directly, not subscribed as a listener**, and that is
5326
+ * the whole reason this function exists rather than an `events.on(...)` pair.
5327
+ * `EventManager.emit` awaits its listeners in priority order inside a bare
5328
+ * `for` loop, so the first one to throw ends the loop and every listener after
5329
+ * it never runs. An unrelated application listener registered at a higher
5330
+ * priority would then silence the audit trail, and the only evidence an
5331
+ * operator would have of that is an empty file. A record of what agents did
5332
+ * cannot be contingent on what else the application happens to listen for.
5333
+ *
5334
+ * The events are still emitted, unchanged, for every consumer that
5335
+ * legitimately is a listener — RFC 0016 §5.2's "forward them wherever you
5336
+ * already forward events" is untouched.
5337
+ *
5338
+ * Neither half may fail the tool call it is recording, so both are caught. The
5339
+ * sink's failure is *warned* rather than swallowed: an audit sink dropping
5340
+ * records in silence is precisely the failure this feature exists to prevent.
5341
+ */
5342
+ function createAuditEmitter(sink, events, now = () => /* @__PURE__ */ new Date()) {
5343
+ return (event) => {
5344
+ if (sink) try {
5345
+ Promise.resolve(sink(toAuditRecord(event, now()))).catch(warnSinkFailure);
5346
+ } catch (error) {
5347
+ warnSinkFailure(error);
5348
+ }
5349
+ events?.emit(event).catch((error) => {
5350
+ console.warn(`[guren] audit event listener failed: ${String(error)}`);
5351
+ });
5352
+ };
5353
+ }
5354
+ function warnSinkFailure(error) {
5355
+ console.warn(`[guren] agent audit sink failed, record dropped: ${String(error)}`);
5356
+ }
5357
+ //#endregion
5358
+ //#region src/agent/approval.ts
5359
+ /**
5360
+ * How long a pending request stays answerable by default: one hour.
5361
+ *
5362
+ * An approval is permission for one call *now*, not a standing grant. The
5363
+ * default is short for the reason the single-use rule exists — an approval
5364
+ * granted last month must not let a call through today — and an application
5365
+ * that wants longer says so.
5366
+ */
5367
+ const DEFAULT_AGENT_APPROVAL_TTL_MS = 36e5;
5368
+ /**
5369
+ * The configuration key an adapter reads the queue out of, as a value.
5370
+ *
5371
+ * `guren check` fails a route declaring `approval: 'required'` in an app whose
5372
+ * `mcpPlugin({ … })` call carries no queue, and it finds that call by looking
5373
+ * for this key. The CLI cannot import `@guren/plugin-mcp` — it does not depend
5374
+ * on it, and an app that never installs App MCP is still checked — so without
5375
+ * this constant the check would restate the string and the two would drift:
5376
+ * renaming the option would leave the check passing every app, silently. Same
5377
+ * rule, two readers, as {@link file://./meta-tools.ts}.
5378
+ */
5379
+ const AGENT_APPROVAL_CONFIG_KEY = "approvals";
5380
+ /**
5381
+ * A stable key for "the same caller".
5382
+ *
5383
+ * Kind and id only: a token's *abilities* are not part of the identity,
5384
+ * because a token rotated or re-scoped between the approval and the call is
5385
+ * still the same principal, and an approval a human granted should not
5386
+ * evaporate because an unrelated ability was added. The scope gate has already
5387
+ * run by the time this key is used, so the call's own authority is checked
5388
+ * regardless.
5389
+ *
5390
+ * The id's type is part of the key. `id: 5` and `id: '5'` are different
5391
+ * principals to every store that distinguishes them, and collapsing the two
5392
+ * here would let a service token named `"5"` spend a user 5 approval.
5393
+ */
5394
+ function agentApprovalPrincipalKey(principal) {
5395
+ if (!principal) return "anonymous";
5396
+ return `${principal.kind}:${typeof principal.id === "number" ? "n" : "s"}:${principal.id}`;
5397
+ }
5398
+ /**
5399
+ * The canonical text of one call's arguments — the *only* rule for deciding
5400
+ * that two calls are the same call.
5401
+ *
5402
+ * One function, two readers: {@link agentApprovalFingerprint} hashes it when a
5403
+ * record is created and again when a call looks one up. A second
5404
+ * serialization is how approving `posts.destroy {id: 5}` comes to authorize
5405
+ * `{id: 9}` — the failure this whole binding exists to prevent — and it would
5406
+ * do it silently, because both sides would still produce *a* string.
5407
+ *
5408
+ * What it normalizes: object key order, at every depth. `{a: 1, b: 2}` and
5409
+ * `{b: 2, a: 1}` are the same call, nested or not.
5410
+ *
5411
+ * What it deliberately does **not** normalize, because each would make two
5412
+ * genuinely different calls match:
5413
+ *
5414
+ * - **Types.** `{id: 5}` and `{id: '5'}` are different calls. A route that
5415
+ * coerces them to the same value is coercing *after* the gate; the approver
5416
+ * saw one of the two written down.
5417
+ * - **Array order.** Order is meaning in a JSON array (`ids: [1, 2]` vs
5418
+ * `[2, 1]` may be the same call to one route and not to another) and the
5419
+ * framework cannot know which.
5420
+ * - **Absent vs. explicitly null.** A dropped key and `null` are different
5421
+ * inputs to a schema with a default.
5422
+ * - Unicode form, number spelling beyond what JSON already fixes, or
5423
+ * whitespace inside strings.
5424
+ *
5425
+ * Total over JSON, and deliberately *not* total over everything else: a value
5426
+ * JSON cannot carry throws rather than serializing to a placeholder. A
5427
+ * placeholder would make two distinct inputs canonicalize identically, which
5428
+ * is the one failure mode worse than refusing — and refusing is safe here,
5429
+ * because the gate turns a throw into a fail-closed refusal. Arguments reach
5430
+ * this function parsed from JSON-RPC, so no such value can occur in practice;
5431
+ * the rule is written down for the surface that one day passes one.
5432
+ */
5433
+ function canonicalizeAgentApprovalInput(input) {
5434
+ return canonicalize(input);
5435
+ }
5436
+ function canonicalize(value) {
5437
+ if (value === null) return "null";
5438
+ switch (typeof value) {
5439
+ case "boolean": return value ? "true" : "false";
5440
+ case "number":
5441
+ if (!Number.isFinite(value)) throw new TypeError(`Agent approval arguments must be JSON: ${String(value)} is not a finite number.`);
5442
+ return JSON.stringify(value);
5443
+ case "string": return JSON.stringify(value);
5444
+ case "object": {
5445
+ if (Array.isArray(value)) return `[${value.map((entry) => canonicalize(entry)).join(",")}]`;
5446
+ const record = value;
5447
+ return `{${Object.keys(record).filter((key) => record[key] !== void 0).sort().map((key) => `${JSON.stringify(key)}:${canonicalize(record[key])}`).join(",")}}`;
5448
+ }
5449
+ default: throw new TypeError(`Agent approval arguments must be JSON: a value of type ${typeof value} cannot be fingerprinted, so no approval could be bound to it.`);
5450
+ }
5451
+ }
5452
+ /**
5453
+ * The fingerprint an approval is bound to: SHA-256 of
5454
+ * {@link canonicalizeAgentApprovalInput}, hex.
5455
+ *
5456
+ * Hashed rather than stored verbatim because the record persists and is shown
5457
+ * to a human, while these are the **raw** arguments — the ones the record's
5458
+ * own `input` field is redacted precisely to keep out of storage. The hash
5459
+ * binds the approval without keeping the secret.
5460
+ *
5461
+ * Async because `crypto.subtle` is: it is the one digest available unchanged
5462
+ * on every runtime the framework targets (Bun, Node, Workers), and the gate is
5463
+ * async already.
5464
+ */
5465
+ async function agentApprovalFingerprint(input) {
5466
+ const bytes = new TextEncoder().encode(canonicalizeAgentApprovalInput(input));
5467
+ const digest = await crypto.subtle.digest("SHA-256", bytes);
5468
+ return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
5469
+ }
5470
+ /**
5471
+ * Derive a new pending record.
5472
+ *
5473
+ * `now` is a parameter for the reason `toAuditRecord`'s is: the caller that
5474
+ * creates a record also decides whether an existing one has expired, and two
5475
+ * clock reads can disagree — a record stamped a millisecond after the instant
5476
+ * its own expiry was measured against.
5477
+ *
5478
+ * The id comes from `crypto.randomUUID()` rather than a parameter, which is
5479
+ * not the same compromise: an id needs no seam to be testable, since the
5480
+ * caller reads it straight off the returned record, and threading one in from
5481
+ * every call site would invite two of them to generate ids differently.
5482
+ */
5483
+ function buildAgentApprovalRequest(request, now) {
5484
+ const ttlMs = request.ttlMs ?? 36e5;
5485
+ return {
5486
+ id: crypto.randomUUID(),
5487
+ tool: request.tool,
5488
+ input: request.input,
5489
+ fingerprint: request.fingerprint,
5490
+ principal: request.principal,
5491
+ principalKey: agentApprovalPrincipalKey(request.principal),
5492
+ requestedAt: now.toISOString(),
5493
+ expiresAt: new Date(now.getTime() + ttlMs).toISOString(),
5494
+ status: "pending"
5495
+ };
5496
+ }
5497
+ /**
5498
+ * Whether a record has passed its expiry at `now`.
5499
+ *
5500
+ * An unparseable `expiresAt` counts as expired. The alternative — treating a
5501
+ * date the framework cannot read as "not expired yet" — is a store bug that
5502
+ * fails open into a permanent approval, and this is the one direction of error
5503
+ * that cannot be noticed from the outside.
5504
+ */
5505
+ function agentApprovalExpiredAt(request, now) {
5506
+ const expiresAt = Date.parse(request.expiresAt);
5507
+ return Number.isNaN(expiresAt) || expiresAt <= now.getTime();
5508
+ }
5509
+ /**
5510
+ * The record's status as of `now`, with expiry applied.
5511
+ *
5512
+ * Expiry is derived here rather than filtered by the store on purpose: a store
5513
+ * that judged it would be a second copy of the rule, and the copy that fails
5514
+ * open — a store that forgets to compare, or compares in local time, hands out
5515
+ * an approval granted last month and nothing anywhere reports it. A resolved
5516
+ * record keeps its resolution: a rejection does not become an expiry, and an
5517
+ * approval that was already spent is reported by `consumedAt`, not by this.
5518
+ */
5519
+ function agentApprovalStatusAt(request, now) {
5520
+ if (request.status === "rejected") return "rejected";
5521
+ if (agentApprovalExpiredAt(request, now)) return "expired";
5522
+ return request.status;
5523
+ }
5524
+ /**
5525
+ * Whether this record authorizes a call at `now`: approved, unexpired, and
5526
+ * not already spent.
5527
+ *
5528
+ * All three are checked here, in framework code, rather than trusted to the
5529
+ * store's query — see {@link AgentApprovalStore.findMatch}. `consumedAt` is
5530
+ * checked even though `findMatch` promises unconsumed records, because the
5531
+ * single-use guarantee must not rest on an application's SQL: the *atomic*
5532
+ * half of it is `consume`'s compare-and-set, and this is the cheap half.
5533
+ */
5534
+ function agentApprovalUsableAt(request, now) {
5535
+ if (request.status !== "approved") return false;
5536
+ if (request.consumedAt !== void 0) return false;
5537
+ return !agentApprovalExpiredAt(request, now);
5538
+ }
5539
+ /**
5540
+ * Whether `principal` may be told anything at all about `request`.
5541
+ *
5542
+ * The scope rule of `guren.approval_status` (RFC 0016 §5.4): a caller reads
5543
+ * the status only of a request it created. Without it the tool is a way to
5544
+ * enumerate other principals' pending actions — an agent could walk ids and
5545
+ * learn what a colleague is waiting to have approved, which is both the
5546
+ * content of the request and the fact that it exists.
5547
+ *
5548
+ * A record this returns `false` for must be answered *exactly* as an unknown
5549
+ * id is. Any difference between the two answers — a distinct message, a
5550
+ * different error shape, a slower path — is the enumeration the rule forbids,
5551
+ * reintroduced.
5552
+ */
5553
+ function agentApprovalVisibleTo(request, principal) {
5554
+ return request.principalKey === agentApprovalPrincipalKey(principal);
5555
+ }
5556
+ //#endregion
5557
+ //#region src/agent/AgentApprovalRequested.ts
5558
+ /**
5559
+ * The notification an application sends its approvers when an agent tool call
5560
+ * becomes a pending approval request (RFC 0016 §5.4 item 4).
5561
+ *
5562
+ * A ready-made {@link Notification} rather than a message the adapter composes,
5563
+ * so "notify approvers through the existing notifications system" is one line
5564
+ * in an application's configuration:
5565
+ *
5566
+ * ```typescript
5567
+ * mcpPlugin({
5568
+ * approvals: {
5569
+ * store,
5570
+ * notify: (request) => notifications.sendToMany(admins, new AgentApprovalRequested(request)),
5571
+ * },
5572
+ * })
5573
+ * ```
5574
+ *
5575
+ * **Who the approvers are is never the framework's decision**, which is why
5576
+ * this class takes a request and not a recipient. The plugin hands the request
5577
+ * over; the application picks who hears about it, over which channels, with
5578
+ * whatever escalation it already has. An adapter that chose recipients would be
5579
+ * choosing them from a list it cannot see.
5580
+ *
5581
+ * Deliberately in its own module, and deliberately not imported by
5582
+ * `approval.ts`: the store interface and its derivations stay declaration-only
5583
+ * and free of the notifications subsystem, so a runtime that never notifies
5584
+ * never pulls it into the graph.
5585
+ *
5586
+ * Not queued (`shouldQueue` stays false). An approval request is answered by a
5587
+ * human in the next few minutes or it expires, and a queue worker that is
5588
+ * behind — or absent, which is the common case in the small deployments this
5589
+ * endpoint targets — turns "notify approvers" into "notify approvers
5590
+ * eventually", after the window closed.
5591
+ */
5592
+ var AgentApprovalRequested = class extends Notification {
5593
+ request;
5594
+ constructor(request) {
5595
+ super();
5596
+ this.request = request;
5597
+ }
5598
+ /**
5599
+ * Mail and database by default — the two channels an application configures
5600
+ * first, and the pair that covers "tell someone now" and "there is a list of
5601
+ * things waiting". An application overrides by subclassing, exactly as it
5602
+ * would for any other notification.
5603
+ */
5604
+ via(_notifiable) {
5605
+ return ["mail", "database"];
5606
+ }
5607
+ toMail(_notifiable) {
5608
+ const who = describePrincipal(this.request);
5609
+ return {
5610
+ subject: `Approval needed: ${this.request.tool}`,
5611
+ text: `${who} asked to run the agent tool "${this.request.tool}". Nothing has been executed.\n\nRequest id: ${this.request.id}\nRequested at: ${this.request.requestedAt}\nExpires at: ${this.request.expiresAt}\n\nArguments (sensitive fields masked):\n${JSON.stringify(this.request.input, null, 2)}\n`
5612
+ };
5613
+ }
5614
+ /**
5615
+ * The record's own fields, minus the fingerprint.
5616
+ *
5617
+ * The fingerprint is a hash of the *raw* arguments (see `approval.ts`), and
5618
+ * a database notification is read by more people, and kept longer, than the
5619
+ * approval store itself. It decides nothing an approver looks at: the
5620
+ * arguments they judge are `input`, already masked.
5621
+ */
5622
+ toDatabase(_notifiable) {
5623
+ return {
5624
+ requestId: this.request.id,
5625
+ tool: this.request.tool,
5626
+ input: this.request.input,
5627
+ principal: this.request.principal,
5628
+ requestedAt: this.request.requestedAt,
5629
+ expiresAt: this.request.expiresAt
5630
+ };
5631
+ }
5632
+ toSlack(_notifiable) {
5633
+ return { text: `Approval needed: *${this.request.tool}* requested by ${describePrincipal(this.request)}. Nothing was executed. Request \`${this.request.id}\` expires at ${this.request.expiresAt}.` };
5634
+ }
5635
+ };
5636
+ /** The requester, in the vocabulary an approver reads rather than a key. */
5637
+ function describePrincipal(request) {
5638
+ const { principal } = request;
5639
+ if (!principal) return "An unidentified caller";
5640
+ return `${principal.kind === "service" ? "Service" : "User"} ${String(principal.id)}`;
5641
+ }
5642
+ //#endregion
4439
5643
  //#region src/providers/OAuthServiceProvider.ts
4440
5644
  /**
4441
5645
  * Binds OAuthManager as a singleton in the container.
@@ -4877,7 +6081,7 @@ var FormRequest = class {
4877
6081
  * true, because an unawaited call is a pending promise.
4878
6082
  */
4879
6083
  async user() {
4880
- return await this.ctx.get("guren:auth")?.user() ?? null;
6084
+ return await getAuthContext(this.ctx)?.user() ?? null;
4881
6085
  }
4882
6086
  /**
4883
6087
  * Handle the form request: authorize, parse body, validate, return typed data.
@@ -8150,27 +9354,7 @@ function renderEnvironmentSection() {
8150
9354
  </section>`;
8151
9355
  }
8152
9356
  //#endregion
8153
- //#region src/auth/password/DefaultHasher.ts
8154
- /**
8155
- * Runtime-detecting password hasher: uses Bun's native scrypt implementation
8156
- * when running on Bun, and the Node.js crypto implementation otherwise
8157
- * (e.g. AWS Lambda on the Node runtime). This is the hasher behind the
8158
- * `Hash` export, so code written against `Hash` runs on both runtimes.
8159
- */
8160
- var DefaultHasher = class {
8161
- delegate;
8162
- constructor() {
8163
- this.delegate = typeof Bun !== "undefined" ? new ScryptHasher() : new NodeHasher();
8164
- }
8165
- hash(plain) {
8166
- return this.delegate.hash(plain);
8167
- }
8168
- verify(hashed, plain) {
8169
- return this.delegate.verify(hashed, plain);
8170
- }
8171
- };
8172
- //#endregion
8173
9357
  //#region src/index.ts
8174
9358
  ensureErrorStackTracePolyfill();
8175
9359
  //#endregion
8176
- export { API_TOKEN_KEY, AUTH_CONTEXT_KEY, Application, ApplicationShutdown, ApplicationStarted, AuthManager, Response$1 as AuthResponse, AuthServiceProvider, AuthenticatableModel, AuthenticationException, AuthorizationException, AuthorizationServiceProvider, AutoDiscovery, BaseFactory, BaseFactory as Factory, BaseSeeder, BaseSeeder as Seeder, BaseUserProvider, BroadcastManager, BroadcastServiceProvider, BufferedOutput, CSP_NONCE_KEY, CSRF_FORM_FIELD, CSRF_HEADER_NAME, CSRF_TOKEN_KEY, CacheCheck, CacheManager, CacheServiceProvider, Channel, Command, ConsoleChannel, ConsoleKernel, Container, Controller, CursorPaginator, CustomCheck, DailyFileChannel, DatabaseChannel, DatabaseCheck, DefaultHasher, DefaultHasher as Hash, Encrypter, EncryptionServiceProvider, ErrorServiceProvider, Event, EventManager, EventServiceProvider, ExceptionHandler, FailedJobReporter, FieldValidator, FileStore as FileCacheStore, FileChannel, FormRequest, Gate, HealthCheck, HealthManager, HealthServiceProvider, HttpException, I18nManager, I18nServiceProvider, InertiaServiceProvider, Input, Job, JobFailed, JobProcessed, JsonLoader, JsonResource, LOCALE_CONTEXT_KEY, LOG_LEVEL_PRIORITY, Listener, LocalDriver as LocalStorageDriver, LogManager, LogServiceProvider, LogTransport, Logger, Mail, MailChannel, MailManager, MailServiceProvider, MemoryApiTokenStore, MemoryDriver as MemoryBroadcastDriver, MemoryStore as MemoryCacheStore, MemoryChannel, MemoryCheck, MemoryDriver$1 as MemoryDriver, MemoryDriver$1 as MemoryQueueDriver, MemoryEmailVerificationStore, MemoryLoader, MemoryOAuthStateStore, MemoryPasswordResetStore, MemoryRateLimitStore, MemorySessionStore, MemoryDriver$2 as MemoryStorageDriver, MemoryTransport, MessageSigner, MethodNotAllowedException, ModelUserProvider, NodeHasher, NotFoundHttpException, Notification, NotificationManager, NotificationServiceProvider, OAUTH_SESSION_BINDING_KEY, OAuthManager, OAuthServiceProvider, Output, Paginator, PendingSchedule, Policy, PresenceChannel, PrivateChannel, ProviderManager, QueueManager, QueueServiceProvider, RedisDriver as RedisBroadcastDriver, RedisStore as RedisCacheStore, RedisCheck, RedisDriver$1 as RedisDriver, RedisDriver$1 as RedisQueueDriver, RequestFinished, RequestReceived, ResendTransport, Resource, ResourceCollection, Router, S3Driver, Schedule, ScheduledTask, Scheduler, SchedulingServiceProvider, ScryptHasher, SeederRunner, ServiceProvider, SessionGuard, SlackChannel, SlidingWindowRateLimitStore, SmtpTransport, SqsDriver, StorageCheck, StorageManager, StorageServiceProvider, SyncDriver, SyncDriver as SyncQueueDriver, TaggedCache, Translator, UserAuthenticated, UserLoggedOut, VALIDATED_DATA_KEY, ValidationException, Validator, ViewEngine, Worker, abort, abortIf, abortUnless, after, afterOrEqual, alpha, alphaDash, alphaNum, array as arrayRule, attachAuthContext, authorize as authorizeAbility, authorizeAllMiddleware, authorizeMiddleware, authorizeResourceMiddleware, before, beforeOrEqual, between, boolean as booleanRule, buildOAuthAuthorizeUrl, buildOAuthRedirectUrl, buildPasswordResetUrl, buildVerificationUrl, can, cannot, check as checkHash, clearJobRegistry, clearNotificationRegistry, collect, completeEmailVerification, completePasswordReset, confirmed, createApiToken, createApp, createBearerTokenMiddleware, createBroadcastManager, createCacheManager, createConsoleKernel, createContainer, createCorsMiddleware, createCspMiddleware, createCsrfMiddleware, createDiscordOAuthProviderConfig, createEmailVerificationToken, createEncrypter, createEventManager, createExceptionHandler, createFacade, createFacades, createForceHttpsMiddleware, createGate, createGitHubOAuthProviderConfig, createGoogleOAuthProviderConfig, createHealthManager, createHostAuthorizationMiddleware, createI18n, createLogManager, createMailManager, createNotificationManager, createOAuthManager, createOAuthState, createPasswordResetToken, createQueueManager, createRateLimitMiddleware, createRedirectSafetyMiddleware, createRedisClient, createScheduler, createSecurityHeaders, createSeederRunner, createSessionMiddleware, createSqsAdapter, createStorageManager, createTypedBroadcaster, createValidator, csrfField, cursorPaginate, custom, customCheck, dateFormat, date as dateRule, debugErrorMiddleware, decodeCursor, decrypt, defineFactory, defineGate, defineMiddleware, defineModule, definePlugin, definePolicy, deriveAppKey, deriveAppKeyring, detectLocaleMiddleware, different, email as emailRule, encodeCursor, encrypt, endsWith, exchangeOAuthCode, exists, fetchOAuthUserProfile, file as fileRule, filterSensitiveData, formatValidationErrors, generateAppKey, generateKey, generateOtp, generatePassword, generateSlug, getApiToken, getApiTokenOrFail, getAppKeyringFromEnv, getBroadcastManager, getContainer, getCspNonce, getCsrfToken, getEncrypter, getExceptionHandler, getGate, getI18n, getInertiaSharedPropsResolver, getJob, getLogManager, getMailManager, getNextOccurrence, getNextOccurrences, getNotification, getNotificationManager, getPluralizationRule, getQueueDriver, getRateLimitInfo, getRegisteredJobs, getRequestLocale, getRequestTranslator, getSessionFromContext, getUserApiTokens, getValidatedData, hash, hashPassword, hmac, image as imageRule, inValues, inertia, integer, ip, ipv4, ipv6, isDue, isDueInTimezone, isEmailVerified, isSafeRedirectUrl, jsonResponse, json as jsonRule, mail, matchesCron, max, maxFileSize, md5, mimes, min, minFileSize, mountModuleRoutes, needsRehash, normalizeAppKey, notIn, nullable, numeric, object as objectRule, paginate, parseApiToken, parseAppKey, parseCron, parseOAuthRedirectUrl, parsePasswordResetUrl, parsePreviousAppKeys, parseRequestPayload, parseSignature, parseVerificationUrl, pick, pluralizationRules, processJob, quickValidate, quickValidateOrThrow, random, randomBase64, randomBase64Url, randomHex, randomInt, randomString, regex, registerJob, registerNotification, renderDebugPage, renderDocument, renderErrorPage, requestIdMiddleware, requestLoggingMiddleware, requireAuthenticated, requireGuest, requireVerifiedEmail, required, requiredIf, requiredUnless, requiredWith, requiredWithout, resetCalledSeeders, resetRateLimit, resolve, resolveJobName, resolveNotifiableType, revokeAllApiTokens, revokeApiToken, same, sample, sanitizeOAuthRedirect, secureCompare, selectPluralForm, setBroadcastManager, setContainer, setEncrypter, setExceptionHandler, setGate, setI18n, setInertiaDocument, setInertiaSharedProps, setInertiaSsrRenderer, setLogManager, setMailManager, setNotificationManager, setQueueDriver, sha256, sha512, shareInertiaProps, shuffle, signUrl, size, startsWith, string as stringRule, t, tc, toTimezone, tokenCan, tokenCanAll, tokenCanAny, tryGetI18n, unique, url as urlRule, urlSafeToken, uuid, uuid$1 as uuidRule, validate, validateRequest, validateRequestWith, validateSafe, verifyApiToken, verifyCsrfToken, verifyEmailToken, verifyHmac, verifyOAuthState, verifyPassword, verifyPasswordResetToken, verifySignedUrl, viteAsset, withAuthorization };
9360
+ export { AGENT_APPROVAL_CONFIG_KEY, AGENT_AUDIT_BINDING, AGENT_REDACTED, AGENT_TOOL_NAME_PATTERN, API_TOKEN_KEY, APPROVAL_STATUS_TOOL_NAME, AUTH_CONTEXT_KEY, AgentApprovalRequested, AgentToolDenied, AgentToolInvoked, Application, ApplicationShutdown, ApplicationStarted, AuthManager, Response$1 as AuthResponse, AuthServiceProvider, AuthenticatableModel, AuthenticationException, AuthorizationException, AuthorizationServiceProvider, AutoDiscovery, BaseFactory, BaseFactory as Factory, BaseSeeder, BaseSeeder as Seeder, BaseUserProvider, BroadcastManager, BroadcastServiceProvider, BufferedOutput, CSP_NONCE_KEY, CSRF_FORM_FIELD, CSRF_HEADER_NAME, CSRF_TOKEN_KEY, CacheCheck, CacheManager, CacheServiceProvider, Channel, Command, ConsoleChannel, ConsoleKernel, Container, Controller, CursorPaginator, CustomCheck, DEFAULT_AGENT_APPROVAL_TTL_MS, DEFAULT_AGENT_AUDIT_PATH, DailyFileChannel, DatabaseChannel, DatabaseCheck, DefaultHasher, DefaultHasher as Hash, Encrypter, EncryptionServiceProvider, ErrorServiceProvider, Event, EventManager, EventServiceProvider, ExceptionHandler, FailedJobReporter, FieldValidator, FileStore as FileCacheStore, FileChannel, FormRequest, Gate, HealthCheck, HealthManager, HealthServiceProvider, HttpException, I18nManager, I18nServiceProvider, InertiaServiceProvider, Input, Job, JobFailed, JobProcessed, JsonLoader, JsonResource, LOCALE_CONTEXT_KEY, LOG_LEVEL_PRIORITY, Listener, LocalDriver as LocalStorageDriver, LogManager, LogServiceProvider, LogTransport, Logger, Mail, MailChannel, MailManager, MailServiceProvider, MemoryApiTokenStore, MemoryDriver as MemoryBroadcastDriver, MemoryStore as MemoryCacheStore, MemoryChannel, MemoryCheck, MemoryDriver$1 as MemoryDriver, MemoryDriver$1 as MemoryQueueDriver, MemoryEmailVerificationStore, MemoryLoader, MemoryOAuthStateStore, MemoryPasswordResetStore, MemoryRateLimitStore, MemorySessionStore, MemoryDriver$2 as MemoryStorageDriver, MemoryTransport, MessageSigner, MethodNotAllowedException, ModelUserProvider, NodeHasher, NotFoundHttpException, Notification, NotificationManager, NotificationServiceProvider, OAUTH_SESSION_BINDING_KEY, OAuthManager, OAuthServiceProvider, Output, PREFLIGHT_ARGUMENT, PREFLIGHT_TOOL_NAME, Paginator, PendingSchedule, Policy, PresenceChannel, PrivateChannel, ProviderManager, QueueManager, QueueServiceProvider, RESERVED_AGENT_TOOL_NAMES, RedisDriver as RedisBroadcastDriver, RedisStore as RedisCacheStore, RedisCheck, RedisDriver$1 as RedisDriver, RedisDriver$1 as RedisQueueDriver, RequestFinished, RequestReceived, ResendTransport, Resource, ResourceCollection, Router, S3Driver, Schedule, ScheduledTask, Scheduler, SchedulingServiceProvider, ScryptHasher, SeederRunner, ServiceProvider, SessionGuard, SlackChannel, SlidingWindowRateLimitStore, SmtpTransport, SqsDriver, StorageCheck, StorageManager, StorageServiceProvider, SyncDriver, SyncDriver as SyncQueueDriver, TaggedCache, TokenGuard, Translator, UserAuthenticated, UserLoggedOut, VALIDATED_DATA_KEY, ValidationException, Validator, ViewEngine, Worker, abort, abortIf, abortUnless, advertisesStructuredOutput, after, afterOrEqual, agentApprovalExpiredAt, agentApprovalFingerprint, agentApprovalPrincipalKey, agentApprovalStatusAt, agentApprovalUsableAt, agentApprovalVisibleTo, alpha, alphaDash, alphaNum, array as arrayRule, attachAuthContext, authorize as authorizeAbility, authorizeAllMiddleware, authorizeMiddleware, authorizeResourceMiddleware, before, beforeOrEqual, between, boolean as booleanRule, buildAgentApprovalRequest, buildOAuthAuthorizeUrl, buildOAuthRedirectUrl, buildPasswordResetUrl, buildToolRequest, buildVerificationUrl, can, cannot, canonicalizeAgentApprovalInput, check as checkHash, clearJobRegistry, clearNotificationRegistry, collect, completeEmailVerification, completePasswordReset, confirmed, createApiToken, createApp, createAuditEmitter, createBearerTokenMiddleware, createBroadcastManager, createCacheManager, createConsoleKernel, createContainer, createCorsMiddleware, createCspMiddleware, createCsrfMiddleware, createDiscordOAuthProviderConfig, createEmailVerificationToken, createEncrypter, createEventManager, createExceptionHandler, createFacade, createFacades, createForceHttpsMiddleware, createGate, createGitHubOAuthProviderConfig, createGoogleOAuthProviderConfig, createHealthManager, createHostAuthorizationMiddleware, createI18n, createLogManager, createMailManager, createNotificationManager, createOAuthManager, createOAuthState, createPasswordResetToken, createQueueManager, createRateLimitMiddleware, createRedirectSafetyMiddleware, createRedisClient, createScheduler, createSecurityHeaders, createSeederRunner, createSessionMiddleware, createSqsAdapter, createStorageManager, createTypedBroadcaster, createValidator, csrfField, cursorPaginate, custom, customCheck, dailyFileDateStamp, dailyFilePath, dateFormat, date as dateRule, debugErrorMiddleware, decodeCursor, decrypt, defineFactory, defineGate, defineMiddleware, defineModule, definePlugin, definePolicy, deriveAgentTools, deriveAppKey, deriveAppKeyring, describeBuildFailure, detectLocaleMiddleware, different, email as emailRule, encodeCursor, encrypt, endsWith, exchangeOAuthCode, exists, expandToolScopes, fetchOAuthUserProfile, file as fileRule, filterSensitiveData, formatValidationErrors, generateAppKey, generateKey, generateOtp, generatePassword, generateSlug, getApiToken, getApiTokenOrFail, getAppKeyringFromEnv, getBroadcastManager, getContainer, getCspNonce, getCsrfToken, getEncrypter, getExceptionHandler, getGate, getI18n, getInertiaSharedPropsResolver, getJob, getLogManager, getMailManager, getNextOccurrence, getNextOccurrences, getNotification, getNotificationManager, getPluralizationRule, getQueueDriver, getRateLimitInfo, getRegisteredJobs, getRequestLocale, getRequestTranslator, getSessionFromContext, getUserApiTokens, getValidatedData, hash, hashPassword, hmac, image as imageRule, inValues, inertia, integer, ip, ipv4, ipv6, isDue, isDueInTimezone, isEmailVerified, isReservedAgentToolName, isSafeRedirectUrl, jsonResponse, json as jsonRule, mail, mapToolResponse, matchDailyFileDate, matchesCron, max, maxFileSize, md5, mimes, min, minFileSize, mountModuleRoutes, needsRehash, normalizeAppKey, notIn, nullable, numeric, object as objectRule, paginate, parseApiToken, parseAppKey, parseAuditRecord, parseCron, parseOAuthRedirectUrl, parsePasswordResetUrl, parsePreviousAppKeys, parseRequestPayload, parseSignature, parseToolScope, parseVerificationUrl, pick, pluralizationRules, processJob, quickValidate, quickValidateOrThrow, random, randomBase64, randomBase64Url, randomHex, randomInt, randomString, readBearerToken, redactAgentArguments, regex, registerJob, registerNotification, renderDebugPage, renderDocument, renderErrorPage, requestIdMiddleware, requestLoggingMiddleware, requireAuthenticated, requireGuest, requireVerifiedEmail, required, requiredIf, requiredUnless, requiredWith, requiredWithout, resetCalledSeeders, resetRateLimit, resolve, resolveJobName, resolveNotifiableType, revokeAllApiTokens, revokeApiToken, same, sample, sanitizeOAuthRedirect, scopesAllowTool, secureCompare, selectPluralForm, setBroadcastManager, setContainer, setEncrypter, setExceptionHandler, setGate, setI18n, setInertiaDocument, setInertiaSharedProps, setInertiaSsrRenderer, setLogManager, setMailManager, setNotificationManager, setQueueDriver, sha256, sha512, shareInertiaProps, shuffle, signUrl, size, startsWith, string as stringRule, t, tc, toAuditRecord, toTimezone, tokenCan, tokenCanAll, tokenCanAny, tryGetI18n, unique, url as urlRule, urlSafeToken, uuid, uuid$1 as uuidRule, validate, validateRequest, validateRequestWith, validateSafe, verifyApiToken, verifyCsrfToken, verifyEmailToken, verifyHmac, verifyOAuthState, verifyPassword, verifyPasswordResetToken, verifySignedUrl, viteAsset, withAuthorization };