@guren/server 2.16.0 → 2.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -8,13 +8,13 @@ import { PATH_PARAM_PATTERN, extractPathParamNames } from "./internal/route-path
8
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-DxQK8h3P.js";
9
9
  import { n as ProviderManager, r as ServiceProvider } from "./loopback-guard-DT9gHF0F.js";
10
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";
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-CbdPH4Cd.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 NodeHasher, d as completePasswordReset, dt as BaseUserProvider, f as createPasswordResetToken, ft as installAgentPrincipal, g as MemoryOAuthStateStore, gt as getSessionFromContext, h as AuthenticatableModel, ht as createSessionMiddleware, i as createEmailVerificationToken, j as hostMatchesAllowlist, k as sanitizeOAuthRedirect, l as MemoryPasswordResetStore, lt as ScryptHasher, m as verifyPasswordResetToken, mt as MemorySessionStore, n as buildVerificationUrl, o as parseVerificationUrl, ot as ModelUserProvider, p as parsePasswordResetUrl, pt as readAgentPrincipal, q as revokeApiToken, r as completeEmailVerification, s as requireVerifiedEmail, st as DefaultHasher, t as MemoryEmailVerificationStore, u as buildPasswordResetUrl, ut as AuthenticationException, v as OAuthManager, w as createOAuthManager, x as createDiscordOAuthProviderConfig, y as buildOAuthAuthorizeUrl, z as createBearerTokenMiddleware } from "./auth-Gg54ppQi.js";
12
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-D2DFd8xX.js";
13
13
  import { n as getAuthContext, t as AUTH_CONTEXT_KEY } from "./context-CXk_umpT.js";
14
14
  import { r as isMcpEndpointEnabled } from "./endpoint-Dsw3Acvq.js";
15
15
  import { n as isHotReloadRuntime, r as matchingOpenParen, t as claimHotDisposable } from "./hot-disposables-B5BXqaIH.js";
16
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-Cg1aajRP.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-CTQp-SOo.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-B_Iy5183.js";
18
18
  import { r as isDocsViewerEnabled } from "./endpoint-BXipU2Jj.js";
19
19
  import { t as jsx_runtime_exports } from "./jsx-runtime.js";
20
20
  import { readObjectSchema, toJsonSchema } from "./internal/zod-json-schema.js";
@@ -889,6 +889,15 @@ function isMcpEndpointRequest(path) {
889
889
  return path === "/_guren/mcp" && isMcpEndpointEnabled();
890
890
  }
891
891
  /**
892
+ * An endpoint that cannot authenticate from a session cookie has no ambient
893
+ * authority for CSRF to defend, and verifying there only masks its own 401.
894
+ * Exact path, never {@link matchesPattern}: a declaring endpoint mounts one
895
+ * literal route, and a pattern here would be an escape hatch.
896
+ */
897
+ function isCookielessAuthEndpoint(path, declared) {
898
+ return declared !== void 0 && declared().has(path);
899
+ }
900
+ /**
892
901
  * A bearer request carrying no cookies at all (RFC 0016 §3). CSRF defends
893
902
  * cookie ambient authority, so the raw `Cookie` header's absence is proof
894
903
  * wherever this sits relative to the session mount; a session-based predicate
@@ -900,6 +909,16 @@ function isBearerRequestWithoutCookies(ctx) {
900
909
  return ctx.req.header("Cookie") === void 0;
901
910
  }
902
911
  /**
912
+ * A request the pipeline installed an agent principal on (RFC 0017 §2), exempt
913
+ * on the cookie-less bearer terms above: it carries no cookies **by
914
+ * construction** and authenticates by an identity keyed on the object itself,
915
+ * which no browser or network caller can attach to a request it did not build.
916
+ * Verification-only, like every exemption here; issuance is unchanged.
917
+ */
918
+ function isSeamPrincipalRequest(ctx) {
919
+ return readAgentPrincipal(ctx.req.raw) !== void 0;
920
+ }
921
+ /**
903
922
  * The request's CSRF token: bound to the session when a stable one exists,
904
923
  * otherwise a stateless signed double-submit token. Nothing is stored
905
924
  * server-side. The per-request cache is keyed by the *mode* it was issued for,
@@ -967,19 +986,20 @@ async function getTokenFromRequest(ctx) {
967
986
  } catch {}
968
987
  }
969
988
  /**
970
- * Issues a signed `XSRF-TOKEN` on safe requests and verifies it on
971
- * state-changing ones (`_token` field, `X-CSRF-TOKEN` / `X-XSRF-TOKEN` header).
972
- * `cookie: false` suits session-authenticated flows only; guest tokens need the
973
- * cookie. **Mount directly inside the session middleware:** anything between
974
- * the two that mutates the session after its own `await next()` moves the id after this has committed.
989
+ * Issues a signed `XSRF-TOKEN` on safe requests and verifies it on state-changing
990
+ * ones (`_token`, `X-CSRF-TOKEN` / `X-XSRF-TOKEN`), skipping cookie-less bearer
991
+ * requests (RFC 0016) and seam-marked ones (RFC 0017). `cookie: false` suits
992
+ * session flows only. **Mount directly inside the session middleware:** anything
993
+ * between that mutates the session after `await next()` moves the id too late.
975
994
  */
976
- function createCsrfMiddleware(options = {}) {
995
+ function createCsrfMiddleware(options = {}, cookielessAuthEndpoints) {
977
996
  const { exclude = [], onError, methods = DEFAULT_PROTECTED_METHODS, cookie: enableCookie = true, cookieOptions = {} } = options;
978
997
  const protectedMethods = new Set(methods.map((m) => m.toUpperCase()));
979
998
  const settleCookie = (ctx) => {
980
999
  if (enableCookie) setXsrfCookie(ctx, getCsrfToken(ctx), cookieOptions);
981
1000
  };
982
1001
  return async (ctx, next) => {
1002
+ if (isSeamPrincipalRequest(ctx) && ctx.req.header("Cookie") !== void 0) return jsonResponse({ message: "A request carrying an installed agent principal must not carry cookies. Refused." }, 403);
983
1003
  const method = ctx.req.method.toUpperCase();
984
1004
  const path = new URL(ctx.req.url).pathname;
985
1005
  if (!protectedMethods.has(method)) {
@@ -987,7 +1007,7 @@ function createCsrfMiddleware(options = {}) {
987
1007
  settleCookie(ctx);
988
1008
  return;
989
1009
  }
990
- if (isExcluded$1(path, exclude) || isMcpEndpointRequest(path) || isBearerRequestWithoutCookies(ctx)) {
1010
+ if (isExcluded$1(path, exclude) || isMcpEndpointRequest(path) || isCookielessAuthEndpoint(path, cookielessAuthEndpoints) || isBearerRequestWithoutCookies(ctx) || isSeamPrincipalRequest(ctx)) {
991
1011
  await next();
992
1012
  settleCookie(ctx);
993
1013
  return;
@@ -1774,7 +1794,7 @@ var AuthServiceProvider = class extends ServiceProvider {
1774
1794
  app.use("*", createCsrfMiddleware({
1775
1795
  cookieOptions: { secure: typeof process !== "undefined" ? process.env.NODE_ENV === "production" : true },
1776
1796
  ...csrfOptions
1777
- }));
1797
+ }, () => app.getCookielessAuthPaths()));
1778
1798
  }
1779
1799
  }
1780
1800
  app.use("*", attachAuthContext((ctx) => auth.createAuthContext(ctx)));
@@ -2868,6 +2888,7 @@ var Application = class {
2868
2888
  */
2869
2889
  disposeBunTeardown;
2870
2890
  autoSessionAttached = false;
2891
+ cookielessAuthPaths = /* @__PURE__ */ new Set();
2871
2892
  routesRegistered = false;
2872
2893
  bootPromise;
2873
2894
  constructor(options = {}) {
@@ -2928,6 +2949,25 @@ var Application = class {
2928
2949
  hasAutoSessionAttached() {
2929
2950
  return this.autoSessionAttached;
2930
2951
  }
2952
+ /**
2953
+ * Asserts that `path` resolves its principal without ever reading a session
2954
+ * cookie, so it refuses on its own terms and CSRF has no ambient authority to
2955
+ * defend there. Only for an endpoint whose own code establishes that; an app
2956
+ * exempting a path it chose wants `csrfOptions.exclude`. Call from `boot`,
2957
+ * after `mountRoutes()` — at `register` the collision check sees no routes.
2958
+ */
2959
+ declareCookielessAuthPath(path) {
2960
+ const collision = this.router.definitions().find((route) => route.path === path);
2961
+ if (collision) {
2962
+ console.warn(`[guren] Refusing to exempt "${path}" from CSRF verification: the application already routes ${collision.method} ${path}${collision.name ? ` (${collision.name})` : ""}, which is registered first and answers there. Mount the declaring endpoint on a path of its own — as it stands it is unreachable, and exempting the path would disarm CSRF for the route that does answer.`);
2963
+ return;
2964
+ }
2965
+ this.cookielessAuthPaths.add(path);
2966
+ }
2967
+ /** Matched by exact path — see {@link declareCookielessAuthPath}. */
2968
+ getCookielessAuthPaths() {
2969
+ return this.cookielessAuthPaths;
2970
+ }
2931
2971
  async mountRoutes() {
2932
2972
  if (!this.routesRegistered) {
2933
2973
  if (this.options.routes) await this.options.routes(this.router);
@@ -2955,11 +2995,20 @@ var Application = class {
2955
2995
  throw error;
2956
2996
  }
2957
2997
  }
2998
+ /**
2999
+ * Resolves when the boot that is running — or has already run — completes,
3000
+ * and immediately when none was ever started. For a surface holding this
3001
+ * application from *inside* `boot`, whose hook runs while later providers are
3002
+ * unbooted. Never await it from a provider's own `boot`: it waits on itself.
3003
+ */
3004
+ async booted() {
3005
+ await this.bootPromise;
3006
+ }
2958
3007
  async bootOnce() {
2959
3008
  await this.providerManager.registerAll();
2960
3009
  await this.options.boot?.(this.hono);
2961
3010
  await this.mountRoutes();
2962
- await this.mountDevEndpoint(isMcpEndpointEnabled(), async () => (await import("./McpServiceProvider-nNcbCIQX.js").then((n) => n.n)).McpServiceProvider, "GUREN_MCP=1 but the MCP endpoint could not load — is @modelcontextprotocol/sdk installed?");
3011
+ await this.mountDevEndpoint(isMcpEndpointEnabled(), async () => (await import("./McpServiceProvider-Zihx3Bjq.js").then((n) => n.n)).McpServiceProvider, "GUREN_MCP=1 but the MCP endpoint could not load — is @modelcontextprotocol/sdk installed?");
2963
3012
  await this.mountDevEndpoint(isDocsViewerEnabled(), async () => (await import("./DocsViewerServiceProvider-D2cuVgtN.js")).DocsViewerServiceProvider, "GUREN_DOCS=1 but the docs viewer could not load — is @guren/cli resolvable from this app?");
2964
3013
  await this.providerManager.bootAll();
2965
3014
  }
@@ -3827,6 +3876,34 @@ function parseToolScope(entry) {
3827
3876
  prefix
3828
3877
  };
3829
3878
  }
3879
+ /**
3880
+ * Judge one `scopes` entry of an agent registration.
3881
+ *
3882
+ * @param entry The scope as written in the config.
3883
+ */
3884
+ function classifyRegistrationScope(entry) {
3885
+ const scope = parseToolScope(entry);
3886
+ if (scope?.kind === "tool" || scope?.kind === "read") return {
3887
+ allowed: true,
3888
+ scope
3889
+ };
3890
+ if (scope?.kind === "all") return {
3891
+ allowed: false,
3892
+ reason: "wildcard",
3893
+ message: `"${entry}" grants every tool the application has, including every tool it grows later. An unattended agent must not acquire consent to tools that did not exist when this was written. List the tools as tool:<name> entries, or use tools:read if the agent only reads.`
3894
+ };
3895
+ if (scope?.kind === "prefix") return {
3896
+ allowed: false,
3897
+ reason: "prefix",
3898
+ message: `"${entry}" grants every tool in the ${scope.prefix}.* family, including ones added later. An unattended agent must not acquire consent to tools that did not exist when this was written. List the tools it needs as tool:<name> entries.`
3899
+ };
3900
+ const suggestion = AGENT_TOOL_NAME_PATTERN.test(entry) ? ` Did you mean "tool:${entry}"?` : "";
3901
+ return {
3902
+ allowed: false,
3903
+ reason: "not-a-tool-scope",
3904
+ message: `"${entry}" is not a tool scope, so it grants nothing. The registration grammar is tool:<name> for one tool by exact name, or tools:read for every read-only tool.` + suggestion
3905
+ };
3906
+ }
3830
3907
  /** Whether one parsed scope covers a given tool. */
3831
3908
  function scopeAllowsTool(scope, tool) {
3832
3909
  switch (scope.kind) {
@@ -4060,7 +4137,8 @@ const AGENT_SURFACES = {
4060
4137
  "mcp": true,
4061
4138
  "dev-mcp": true,
4062
4139
  "cli": true,
4063
- "webmcp": true
4140
+ "webmcp": true,
4141
+ "durable": true
4064
4142
  };
4065
4143
  /** Every denial reason, as a value, total over the union for the same reason. */
4066
4144
  const DENIAL_REASONS = {
@@ -4386,6 +4464,371 @@ function describePrincipal(request) {
4386
4464
  return `${principal.kind === "service" ? "Service" : "User"} ${String(principal.id)}`;
4387
4465
  }
4388
4466
  //#endregion
4467
+ //#region src/agent/gate.ts
4468
+ /**
4469
+ * The adapter-level checks a tool call passes before any HTTP request is
4470
+ * synthesized (RFC 0016 §5); what happens *inside* the dispatched request is
4471
+ * the application's verdict, reported as an invocation with its HTTP status and
4472
+ * never re-judged here. {@link gateToolCall} is synchronous and free of side
4473
+ * effects because `tools/list` calls it for every tool on every listing — an
4474
+ * approval check there would create a pending record and notify approvers once
4475
+ * per tool per client connect. The approval half is {@link gateApproval},
4476
+ * reached only from the call path.
4477
+ */
4478
+ /**
4479
+ * How an unconfigured approval queue is described when no surface says it
4480
+ * better. The pipeline cannot know whether it was reached over MCP, from a
4481
+ * durable agent or from a test harness, and naming one surface's configuration
4482
+ * call would send most readers to a package they do not install. A surface that
4483
+ * knows says so through {@link ScopeGateOptions.configureHint}.
4484
+ */
4485
+ const DEFAULT_APPROVAL_CONFIGURE_HINT = "an approval queue on the invocation pipeline (approvals: { store, notify })";
4486
+ /**
4487
+ * Whose scopes a refusal names when no surface says it better. Neutral because
4488
+ * a scope denial is not always about a token: a durable agent's principal is
4489
+ * minted from its registration and holds no credential, so naming "the token's
4490
+ * scopes" would send its operator looking for a token to widen.
4491
+ */
4492
+ const DEFAULT_SCOPE_SUBJECT = "The caller's scopes";
4493
+ /**
4494
+ * Wrap the application's `notify` so a failure can neither fail the tool call nor
4495
+ * lose the record: it is already persisted when this runs, so a dead channel costs
4496
+ * an approver an email, not a request. The failure is warned about with the request
4497
+ * id, which is what finds the record sitting there unannounced. Both shapes are
4498
+ * caught — a synchronous throw and a rejected promise.
4499
+ */
4500
+ function notifyApprovers(notify) {
4501
+ return (request) => {
4502
+ try {
4503
+ Promise.resolve(notify(request)).catch((error) => warnNotifyFailure(request, error));
4504
+ } catch (error) {
4505
+ warnNotifyFailure(request, error);
4506
+ }
4507
+ };
4508
+ }
4509
+ function warnNotifyFailure(request, error) {
4510
+ console.warn(`[guren] approval notification failed for request ${request.id} (${request.tool}); the request is recorded and pending, but nobody was told: ${String(error)}`);
4511
+ }
4512
+ /**
4513
+ * Scope and approval, in that order — a caller learns a tool needs approval only
4514
+ * once its token could invoke it, so an unauthorized probe cannot map which
4515
+ * tools are approval-gated. `approvalsConfigured` is synchronous because
4516
+ * `tools/list` asks it: with a queue an approval-gated tool *is* callable (the
4517
+ * call queues) and belongs in the catalogue; without one, listing it invites a refusal.
4518
+ */
4519
+ function gateToolCall(tool, abilities, options = {}) {
4520
+ const scope = gatePreflight(tool, abilities, options);
4521
+ if (!scope.allowed) return scope;
4522
+ if (tool.approval === "required" && !options.approvalsConfigured) return {
4523
+ allowed: false,
4524
+ reason: "approval",
4525
+ message: `The tool "${tool.toolName}" requires server-side approval, and this server has no approval queue configured. Nothing was executed. Configure one with ${options.configureHint ?? "an approval queue on the invocation pipeline (approvals: { store, notify })"}.`
4526
+ };
4527
+ return { allowed: true };
4528
+ }
4529
+ /**
4530
+ * The approval half (RFC 0016 §5.4 item 4). One lookup on tool + *raw* arguments'
4531
+ * fingerprint + principal: a pending or rejected match refuses without a second
4532
+ * record or notification (polling by re-calling would page approvers per poll);
4533
+ * a rejection blocks only while its record is live. Consumed *before* dispatch,
4534
+ * one attempt not one success: else concurrent calls pass and a crash is replayable.
4535
+ */
4536
+ async function gateApproval(tool, args, context) {
4537
+ if (context.principal === null) return {
4538
+ allowed: false,
4539
+ reason: "approval",
4540
+ message: `The tool "${tool.toolName}" requires approval, and this request carries no identified caller. An approval is granted to a principal and spent by one, so it cannot be bound to an anonymous call. Nothing was executed and no request was recorded.`
4541
+ };
4542
+ const fingerprint = await agentApprovalFingerprint(args);
4543
+ const principalKey = agentApprovalPrincipalKey(context.principal);
4544
+ const now = context.now();
4545
+ const existing = await context.store.findMatch({
4546
+ tool: tool.toolName,
4547
+ fingerprint,
4548
+ principalKey
4549
+ });
4550
+ if (existing) {
4551
+ if (agentApprovalUsableAt(existing, now)) {
4552
+ if (await context.store.consume(existing.id)) return { allowed: true };
4553
+ return spentVerdict(tool, existing);
4554
+ }
4555
+ const status = agentApprovalStatusAt(existing, now);
4556
+ if (status === "pending") return pendingVerdict(tool, existing, "pending");
4557
+ if (status === "rejected" && !agentApprovalExpiredAt(existing, now)) return rejectedVerdict(tool, existing);
4558
+ }
4559
+ const request = buildAgentApprovalRequest({
4560
+ tool: tool.toolName,
4561
+ input: context.redact(args),
4562
+ fingerprint,
4563
+ principal: context.principal,
4564
+ ttlMs: context.ttlMs
4565
+ }, now);
4566
+ await context.store.create(request);
4567
+ context.notify(request);
4568
+ return pendingVerdict(tool, request, "created");
4569
+ }
4570
+ /**
4571
+ * One builder for the three refusals, so the fields an agent parses cannot come
4572
+ * to differ between them. Every refusal states that nothing was executed in the
4573
+ * message *and* the body: an error plus a tool name is exactly the shape an
4574
+ * agent retries.
4575
+ */
4576
+ function approvalRefusal(status, message, request, extra = {}) {
4577
+ return {
4578
+ allowed: false,
4579
+ reason: "approval",
4580
+ message,
4581
+ body: {
4582
+ status,
4583
+ requestId: request.id,
4584
+ tool: request.tool,
4585
+ requestedAt: request.requestedAt,
4586
+ expiresAt: request.expiresAt,
4587
+ executed: false,
4588
+ ...extra
4589
+ }
4590
+ };
4591
+ }
4592
+ /**
4593
+ * The refusal for a call that is waiting on a human. `pollWith` rides only
4594
+ * here: this is the one answer a caller should come back to, where a rejection
4595
+ * is told not to poll and a spent approval to ask again.
4596
+ */
4597
+ function pendingVerdict(tool, request, origin) {
4598
+ return approvalRefusal("pending", `The tool "${tool.toolName}" requires approval. Nothing was executed. ` + (origin === "created" ? "A request was created and the approvers have been notified. " : "A request for this exact call is already waiting. ") + `Check it with ${APPROVAL_STATUS_TOOL_NAME} using requestId "${request.id}". Once it is approved, repeat this call with the same arguments to perform it.`, request, { pollWith: APPROVAL_STATUS_TOOL_NAME });
4599
+ }
4600
+ /** A call a human answered "no" to, reported distinctly from a pending wait. */
4601
+ function rejectedVerdict(tool, request) {
4602
+ return approvalRefusal("rejected", `The tool "${tool.toolName}" requires approval, and this exact call was rejected. Nothing was executed, and polling will not change that. Do not repeat the call with these arguments.`, request, request.resolvedAt ? { resolvedAt: request.resolvedAt } : {});
4603
+ }
4604
+ /**
4605
+ * An approval another call spent first — its own answer rather than a fresh
4606
+ * request: the loser of the race was not refused for want of approval, so
4607
+ * telling it to ask again is right, filing a request and paging a human is not.
4608
+ */
4609
+ function spentVerdict(tool, request) {
4610
+ return approvalRefusal("spent", `The tool "${tool.toolName}" requires approval, and the approval for this exact call was already used by another call. Nothing was executed. Ask again to request a new one.`, request);
4611
+ }
4612
+ /**
4613
+ * The scope half alone — what `guren.preflight` checks before rehearsing a call
4614
+ * (RFC 0016 §5.4). Checking requires the *same* scope as calling, or the
4615
+ * companion becomes a probe of tools the token cannot call. Approval is not
4616
+ * applied: a rehearsal executes nothing, and approval gates an ability rather
4617
+ * than knowledge; never reaching {@link gateApproval}, it files and pages nothing.
4618
+ */
4619
+ function gatePreflight(tool, abilities, options = {}) {
4620
+ if (!scopesAllowTool(abilities, scopedShape(tool))) return {
4621
+ allowed: false,
4622
+ reason: "scope",
4623
+ message: `${options.scopeSubject ?? "The caller's scopes"} do not grant the tool "${tool.toolName}".`
4624
+ };
4625
+ return { allowed: true };
4626
+ }
4627
+ /** The two fields the scope grammar judges a tool by. */
4628
+ function scopedShape(tool) {
4629
+ return {
4630
+ name: tool.toolName,
4631
+ readOnly: tool.annotations.readOnlyHint
4632
+ };
4633
+ }
4634
+ //#endregion
4635
+ //#region src/agent/pipeline.ts
4636
+ /**
4637
+ * Build {@link AgentInvocationOptions.approvals} for one caller.
4638
+ *
4639
+ * The TTL default, the redaction rules and the `notify` wrapping are invariants
4640
+ * of an approval record rather than of a protocol. Per caller, because an
4641
+ * approval binds to the principal that asked; `undefined` means no queue.
4642
+ */
4643
+ function createAgentApprovalContext(config, principal) {
4644
+ if (!config) return void 0;
4645
+ return {
4646
+ store: config.store,
4647
+ principal,
4648
+ now: () => /* @__PURE__ */ new Date(),
4649
+ ttlMs: config.ttlMs ?? 36e5,
4650
+ redact: (tool, args) => redactAgentArguments(args, tool.redact),
4651
+ notify: notifyApprovers(config.notify)
4652
+ };
4653
+ }
4654
+ /**
4655
+ * How a call is written down: principal, surface, and argument masking.
4656
+ *
4657
+ * Exported because a durable agent's approval-status check reaches the store
4658
+ * without dispatching a tool (RFC 0017 §5), and a second copy of this rule is
4659
+ * how one surface records an argument the other masks.
4660
+ */
4661
+ function createAgentAuditRecorder(options) {
4662
+ return {
4663
+ invoked(audited, args, status, durationMs) {
4664
+ options.audit?.(new AgentToolInvoked(options.principal, audited.toolName, redactAgentArguments(args, audited.redact), status, durationMs, options.surface));
4665
+ },
4666
+ denied(audited, args, reason) {
4667
+ options.audit?.(new AgentToolDenied(options.principal, audited.toolName, redactAgentArguments(args, audited.redact), reason, options.surface));
4668
+ }
4669
+ };
4670
+ }
4671
+ /**
4672
+ * Build the pipeline for one caller. A factory because everything in
4673
+ * {@link AgentInvocationOptions} is settled per caller and read per call — the
4674
+ * principal an approval binds to, the abilities the gate judges by, the surface
4675
+ * the trail records — and hoisting any of it would carry whichever caller
4676
+ * arrived first.
4677
+ */
4678
+ function createAgentInvocationPipeline(options) {
4679
+ if (options.handoff === "seam" && options.authorization !== void 0) throw new Error("createAgentInvocationPipeline: `authorization` and `handoff: 'seam'` are mutually exclusive. A surface either presents a credential the application verifies, or hands over a principal the application trusts — never both.");
4680
+ const scopeGateOptions = {
4681
+ approvalsConfigured: options.approvals !== void 0,
4682
+ ...options.approvalConfigureHint !== void 0 ? { configureHint: options.approvalConfigureHint } : {},
4683
+ ...options.scopeSubject !== void 0 ? { scopeSubject: options.scopeSubject } : {}
4684
+ };
4685
+ const record = createAgentAuditRecorder({
4686
+ ...options.audit ? { audit: options.audit } : {},
4687
+ principal: options.principal,
4688
+ surface: options.surface
4689
+ });
4690
+ return { async invoke(call) {
4691
+ const { tool, args } = call;
4692
+ const preflight = call.preflight === true;
4693
+ const audited = call.audited ?? tool;
4694
+ const auditArgs = call.auditedArguments ?? args;
4695
+ const deny = (denial) => {
4696
+ record.denied(audited, auditArgs, denial.reason);
4697
+ return {
4698
+ status: "denied",
4699
+ denial
4700
+ };
4701
+ };
4702
+ const scope = preflight ? gatePreflight(tool, options.abilities, scopeGateOptions) : gateToolCall(tool, options.abilities, scopeGateOptions);
4703
+ if (!scope.allowed) return deny(toDenial(scope));
4704
+ if (options.interpose) {
4705
+ const interposed = await options.interpose({
4706
+ tool,
4707
+ args,
4708
+ preflight
4709
+ });
4710
+ if (interposed) return deny(interposed);
4711
+ }
4712
+ if (!preflight && tool.approval === "required" && options.approvals) {
4713
+ const { approvals } = options;
4714
+ let verdict;
4715
+ try {
4716
+ verdict = await gateApproval(tool, args, {
4717
+ ...approvals,
4718
+ redact: (callArgs) => approvals.redact(tool, callArgs)
4719
+ });
4720
+ } catch (error) {
4721
+ return deny({
4722
+ reason: "approval",
4723
+ message: `The approval queue could not be reached, so "${tool.toolName}" was not run and no request was recorded: ${error instanceof Error ? error.message : String(error)}`
4724
+ });
4725
+ }
4726
+ if (!verdict.allowed) return deny(toDenial(verdict));
4727
+ }
4728
+ const startedAt = performance.now();
4729
+ try {
4730
+ const built = buildToolRequest(tool, args, {
4731
+ origin: options.origin,
4732
+ authorization: options.authorization,
4733
+ preflight,
4734
+ surface: options.surface
4735
+ });
4736
+ if (!("request" in built)) {
4737
+ const outcome = {
4738
+ content: [{
4739
+ type: "text",
4740
+ text: describeBuildFailure(built)
4741
+ }],
4742
+ isError: true,
4743
+ status: 400
4744
+ };
4745
+ record.invoked(audited, auditArgs, outcome.status, elapsed(startedAt));
4746
+ return {
4747
+ status: "executed",
4748
+ outcome
4749
+ };
4750
+ }
4751
+ const request = options.handoff === "seam" && options.principal ? installAgentPrincipal(built.request, {
4752
+ principal: options.principal,
4753
+ abilities: options.abilities
4754
+ }) : built.request;
4755
+ const outcome = await mapToolResponse(tool, await options.app.fetch(request, options.env, options.executionCtx));
4756
+ record.invoked(audited, auditArgs, outcome.status, elapsed(startedAt));
4757
+ return {
4758
+ status: "executed",
4759
+ outcome
4760
+ };
4761
+ } catch (error) {
4762
+ record.invoked(audited, auditArgs, 500, elapsed(startedAt));
4763
+ return {
4764
+ status: "failed",
4765
+ message: error instanceof Error ? error.message : String(error)
4766
+ };
4767
+ }
4768
+ } };
4769
+ }
4770
+ /**
4771
+ * A refused gate verdict, in the one shape every surface renders.
4772
+ *
4773
+ * `body` is spread conditionally rather than assigned: `body: verdict.body`
4774
+ * leaves the key present holding `undefined`, which is not the same object
4775
+ * under strict comparison or serialization as one that never carried a body.
4776
+ */
4777
+ function toDenial(verdict) {
4778
+ return {
4779
+ reason: verdict.reason,
4780
+ message: verdict.message,
4781
+ ...verdict.body ? { body: verdict.body } : {}
4782
+ };
4783
+ }
4784
+ function elapsed(startedAt) {
4785
+ return Math.round(performance.now() - startedAt);
4786
+ }
4787
+ //#endregion
4788
+ //#region src/agent/approval-status.ts
4789
+ /**
4790
+ * Reading one approval record as an answer for the caller that asked
4791
+ * (RFC 0016 §5.4 item 4). Pure derivation, like `approval.ts`: no store, no
4792
+ * clock, no protocol.
4793
+ *
4794
+ * Here rather than in an adapter because two surfaces answer this question —
4795
+ * `guren.approval_status` over MCP and a durable agent's own status check
4796
+ * (RFC 0017 §5) — and a record one of them calls "approved" must not be one
4797
+ * the other hides.
4798
+ */
4799
+ /**
4800
+ * The one message for "there is no such request *for you*". One function for
4801
+ * both branches because an unknown id and another principal's id must be the
4802
+ * same answer byte for byte: any difference turns the check into a way to
4803
+ * enumerate other principals' pending actions. The audit trail is where the
4804
+ * distinction is kept, for the operator.
4805
+ */
4806
+ function approvalStatusNotFoundMessage(requestId) {
4807
+ return `No approval request with id "${requestId}" was made by this caller.`;
4808
+ }
4809
+ /**
4810
+ * Read a stored record as an answer for `principal` at `now`. `record === null`
4811
+ * and "not visible to this principal" converge here rather than at two call
4812
+ * sites, so their sameness is structural.
4813
+ */
4814
+ function toApprovalStatusReport(requestId, record, principal, now) {
4815
+ if (!record || !agentApprovalVisibleTo(record, principal)) return {
4816
+ notFound: approvalStatusNotFoundMessage(requestId),
4817
+ foreign: record !== null
4818
+ };
4819
+ return { report: {
4820
+ requestId: record.id,
4821
+ status: agentApprovalStatusAt(record, now),
4822
+ tool: record.tool,
4823
+ requestedAt: record.requestedAt,
4824
+ expiresAt: record.expiresAt,
4825
+ executed: false,
4826
+ ...record.resolvedAt ? { resolvedAt: record.resolvedAt } : {},
4827
+ ...record.resolvedBy ? { resolvedBy: record.resolvedBy } : {},
4828
+ ...record.consumedAt ? { consumedAt: record.consumedAt } : {}
4829
+ } };
4830
+ }
4831
+ //#endregion
4389
4832
  //#region src/providers/OAuthServiceProvider.ts
4390
4833
  /** Binds OAuthManager as a singleton in the container. */
4391
4834
  var OAuthServiceProvider = class extends ServiceProvider {
@@ -7060,4 +7503,4 @@ function renderEnvironmentSection() {
7060
7503
  //#region src/index.ts
7061
7504
  ensureErrorStackTracePolyfill();
7062
7505
  //#endregion
7063
- 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 };
7506
+ 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, DEFAULT_APPROVAL_CONFIGURE_HINT, DEFAULT_SCOPE_SUBJECT, 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, approvalStatusNotFoundMessage, 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, classifyRegistrationScope, clearJobRegistry, clearNotificationRegistry, collect, completeEmailVerification, completePasswordReset, confirmed, createAgentApprovalContext, createAgentAuditRecorder, createAgentInvocationPipeline, 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, gateApproval, gatePreflight, gateToolCall, 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, notifyApprovers, 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, scopedShape, 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, toApprovalStatusReport, 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 };
@@ -0,0 +1,32 @@
1
+ /**
2
+ * The principal handoff seam (RFC 0017 §2), a leaf module the pipeline writes
3
+ * and the auth context reads — in either of them, one would import the other's
4
+ * whole layer. Keyed on the **object identity** of the `Request` handed to
5
+ * `app.fetch`, so it has no wire representation to forge, needs no
6
+ * `AsyncLocalStorage` (identical on workerd and Bun), and is collected with the
7
+ * request. `new Request(original)` and `clone()` carry nothing: that is the
8
+ * security property. Not exported from the package index — see the writer.
9
+ */
10
+ import type { AgentPrincipal } from '../agent/events.js';
11
+ /** What an installed principal answers for, for the life of one request. */
12
+ export interface InstalledAgentPrincipal {
13
+ /** Who the pipeline resolved before it built the request. */
14
+ principal: AgentPrincipal;
15
+ /**
16
+ * The scopes the pipeline gated the call with, carried for completeness.
17
+ * Nothing in the auth context consults them: scopes are the *pipeline's*
18
+ * verdict, taken before dispatch, and re-judging them inside the request
19
+ * would be a second, quieter scope rule beside the real one.
20
+ */
21
+ abilities: readonly string[];
22
+ }
23
+ /**
24
+ * Mark `request` as carrying `principal`, returning that same object — a copy
25
+ * would key the map on something the auth context never sees. Returning it is
26
+ * what makes the identity requirement hard to get wrong at a call site:
27
+ * `app.fetch(installAgentPrincipal(request, installed), env, ctx)`. Callers
28
+ * reach this through the pipeline's `handoff: 'seam'`, and the reader not at all.
29
+ */
30
+ export declare function installAgentPrincipal(request: Request, value: InstalledAgentPrincipal): Request;
31
+ /** The principal installed on this exact request object, or `undefined`. */
32
+ export declare function readAgentPrincipal(request: Request): InstalledAgentPrincipal | undefined;
@@ -76,6 +76,23 @@ export interface GurenCliApi {
76
76
  warnCount: number;
77
77
  failCount: number;
78
78
  }>;
79
+ /** Absent on a @guren/cli older than `guren gate`; the tool says so instead of throwing. */
80
+ runGate?(opts: {
81
+ cwd: string;
82
+ changed?: boolean;
83
+ deps?: boolean;
84
+ }): Promise<{
85
+ cwd: string;
86
+ ok: boolean;
87
+ changed: boolean;
88
+ stages: Array<{
89
+ name: string;
90
+ status: string;
91
+ durationMs: number;
92
+ findings: string[];
93
+ reason?: string;
94
+ }>;
95
+ }>;
79
96
  listModels(opts: {
80
97
  appRoot: string;
81
98
  }): Promise<Array<{